Repository navigation
Expand file tree
/
Copy pathscript_tools.py
More file actions
2266 lines (1959 loc) · 94.5 KB
/
Copy pathscript_tools.py
File metadata and controls
2266 lines (1959 loc) · 94.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import jpype
from jpype import JClass, JImplements, JOverride
from matplotlib import text
from langchain.tools import tool
from imagentj.imagej_context import get_ij
import os
import re
import json
from .analyst_tools import run_python_code
import datetime
import shutil
from typing import Optional, Any, List
from pydantic import BaseModel, ConfigDict
from filelock import FileLock
import logging
import threading
import time
from scyjava import jimport
from imagentj import run_control, stop_signal
from .utils import add_line_numbers, strip_line_numbers
log = logging.getLogger(__name__)
# ── Window classification ─────────────────────────────────────────────────
_ERROR_KEYWORDS = (
"not a valid choice", "not found", "unrecognized",
"macro error", "exception", "no such", "requires",
"unknown", "invalid", "cannot find", "failed",
"undefined", "expected", "syntax error", "illegal",
)
# Titles that are ALWAYS errors regardless of window class.
# ImageJ opens "Macro Error", "Exception", etc. as plain TextWindows.
_ERROR_TITLE_HINTS = (
"error", "exception", "macro error", "warning",
)
# TextWindow titles that are tabular data output, not errors.
_RESULTS_TITLE_HINTS = (
"morphometry", "results", "-bnd", "summary",
"area", "label", "measurements",
)
def _classify_window(window, title: str, text: str) -> str:
"""
Return one of: "ERROR", "RESULTS", "INFO".
Priority order (critical — do not reorder):
1. Title contains an error keyword -> ERROR
(catches TextWindow-based macro errors, which bypass MessageDialog)
2. Window class is MessageDialog -> ERROR
(IJ.error, "command not found" modal dialogs)
3. Body text contains error keyword -> ERROR
4. TextWindow with tabular content -> RESULTS
5. Everything else -> INFO
"""
try:
cls = str(window.getClass().getSimpleName())
except Exception:
cls = ""
low_text = (text or "").lower()
low_title = (title or "").lower()
# 1. Title-based error detection — HIGHEST PRIORITY.
# Must come before the TextWindow/RESULTS branch because ImageJ's
# "Macro Error" window is a TextWindow, not a MessageDialog.
if any(h in low_title for h in _ERROR_TITLE_HINTS):
return "ERROR"
# 2. Modal error dialogs (IJ.error, plugin "command not found", etc.)
if cls == "MessageDialog":
return "ERROR"
# 3. Body-text error detection
if any(k in low_text for k in _ERROR_KEYWORDS):
return "ERROR"
# 4. Tabular TextWindow → results table, suppress from context
if cls == "TextWindow":
if any(h in low_title for h in _RESULTS_TITLE_HINTS):
return "RESULTS"
lines = (text or "").splitlines()
if len(lines) > 5 and sum(1 for l in lines if "\t" in l) > len(lines) * 0.5:
return "RESULTS"
return "INFO"
def _get_open_frames() -> dict:
"""
Snapshot all visible AWT Frames by title.
Returns {title: frame} — uses title as key since TextWindows
are identified by title in the Window menu.
"""
Frame = jimport("java.awt.Frame")
result = {}
try:
for frame in Frame.getFrames():
if frame.isVisible():
title = str(frame.getTitle())
result[title] = frame
except Exception:
pass
return result
def _read_multilinelabel_via_reflection(obj) -> str:
"""
Scan all declared fields on `obj` (and its superclasses) for a
MultiLineLabel instance and extract its 'lines' array.
ImageJ's Macro Error / MessageDialog windows store their text in a
MultiLineLabel that is NOT added to getComponents(), so normal AWT
recursion can't find it. The field name varies by ImageJ version
("label", "theLabel", etc.), so we scan by type instead of by name.
"""
try:
MultiLineLabel = JClass("ij.gui.MultiLineLabel")
except Exception:
MultiLineLabel = None
try:
cls = obj.getClass()
while cls is not None:
try:
for field in cls.getDeclaredFields():
try:
field.setAccessible(True)
value = field.get(obj)
if value is None:
continue
# Match by type if we have MultiLineLabel available,
# otherwise match by class name as a fallback
is_mll = False
if MultiLineLabel is not None:
try:
is_mll = jpype.isinstance(value, MultiLineLabel)
except Exception:
is_mll = False
if not is_mll:
try:
if "MultiLineLabel" in str(value.getClass().getName()):
is_mll = True
except Exception:
pass
if not is_mll:
continue
# Found it — extract the 'lines' array
try:
lines_field = value.getClass().getDeclaredField("lines")
lines_field.setAccessible(True)
lines = lines_field.get(value)
if lines is not None:
text = "\n".join(str(l) for l in lines).strip()
if text:
return text
except Exception:
pass
# Fallback: try getText() on the MultiLineLabel itself
try:
text = str(value.getText()).strip()
if text:
return text
except Exception:
pass
except Exception:
continue
except Exception:
pass
try:
parent = cls.getSuperclass()
if parent is None or str(parent.getName()) == "java.lang.Object":
break
cls = parent
except Exception:
break
except Exception:
pass
return ""
def _extract_component_text(component) -> list[str]:
"""
Recursively extract text from all AWT and Swing components.
Covers: Label, TextArea, TextField, JLabel, JTextArea, JTextField.
"""
Label = JClass("java.awt.Label")
TextArea = JClass("java.awt.TextArea")
TextField = JClass("java.awt.TextField")
Container = JClass("java.awt.Container")
try:
JLabel = JClass("javax.swing.JLabel")
JTextArea = JClass("javax.swing.JTextArea")
JTextField = JClass("javax.swing.JTextField")
has_swing = True
except Exception:
has_swing = False
texts = []
try:
if jpype.isinstance(component, Label):
t = str(component.getText()).strip()
if t:
texts.append(t)
elif jpype.isinstance(component, (TextArea, TextField)):
t = str(component.getText()).strip()
if t:
texts.append(t)
elif has_swing and jpype.isinstance(component, (JLabel, JTextArea, JTextField)):
t = str(component.getText()).strip()
if t:
texts.append(t)
if jpype.isinstance(component, Container):
for child in component.getComponents():
texts.extend(_extract_component_text(child))
except Exception:
pass
return texts
def _read_frame_text(frame) -> str:
"""
Attempt to read text content from a frame/dialog.
Strategies in order:
1. getTextPanel().getText() — Log, most TextWindows
2. getTextPanel().getLine(i) loop — some TextWindow variants
3. MultiLineLabel reflection scan — Macro Error, MessageDialog
4. Component recursion fallback — anything else
"""
# Strategy 1 + 2: TextPanel (Log, Results, etc.)
try:
text_panel = frame.getTextPanel()
try:
text = str(text_panel.getText()).strip()
if text:
return text
except Exception:
pass
try:
line_count = int(text_panel.getLineCount())
if line_count > 0:
lines = []
for i in range(line_count):
try:
line = str(text_panel.getLine(i))
if line:
lines.append(line)
except Exception:
pass
if lines:
return "\n".join(lines).strip()
except Exception:
pass
except Exception:
pass
# Strategy 3: MultiLineLabel reflection (Macro Error window)
text = _read_multilinelabel_via_reflection(frame)
if text:
return text
# Strategy 4: AWT component recursion
return "\n".join(_extract_component_text(frame))
def _flush_edt() -> None:
"""Block until all currently queued AWT events have been processed."""
SwingUtilities = JClass("javax.swing.SwingUtilities")
if SwingUtilities.isEventDispatchThread():
return
@JImplements("java.lang.Runnable")
class Flusher:
@JOverride
def run(self):
pass
try:
SwingUtilities.invokeAndWait(Flusher())
except Exception:
pass
def _collect_new_frames(frames_before: dict, timeout: float = 0.5) -> dict:
"""
Poll for new AWT Frames, classify each, and return:
{"errors": [...], "results_count": int, "info": [...]}
"""
result = {"errors": [], "results_count": 0, "info": []}
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
_flush_edt()
current = _get_open_frames()
new_frames = {
title: frame
for title, frame in current.items()
if title not in frames_before and title not in _IGNORE_TITLES
}
if new_frames:
for title, frame in new_frames.items():
text = _read_frame_text(frame)
kind = _classify_window(frame, title, text)
entry = f"[{title}]"
if text and kind in ("ERROR", "INFO"):
entry += f"\n{text[:500]}"
if kind == "ERROR":
result["errors"].append(entry)
elif kind == "RESULTS":
result["results_count"] += 1
else:
result["info"].append(entry)
break
time.sleep(0.05)
return result
# ── Popup dialog text extraction ──────────────────────────────────────────
def _read_window_text(window) -> str:
"""
Read text from any AWT Window. Tries in order:
1. getTextPanel().getText()
2. getTextPanel().getLine(i) loop
3. MultiLineLabel reflection scan (Macro Error, MessageDialog, etc.)
4. Component recursion
"""
try:
text_panel = window.getTextPanel()
try:
text = str(text_panel.getText()).strip()
if text:
return text
except Exception:
pass
try:
line_count = int(text_panel.getLineCount())
if line_count > 0:
lines = []
for i in range(line_count):
try:
line = str(text_panel.getLine(i))
if line:
lines.append(line)
except Exception:
pass
if lines:
return "\n".join(lines).strip()
except Exception:
pass
except Exception:
pass
text = _read_multilinelabel_via_reflection(window)
if text:
return text
return "\n".join(_extract_component_text(window))
# ── Background monitor for modal dialogs DURING execution ─────────────────
_IGNORE_TITLES = {"ImageJ", "Fiji", "Log", "ROI Manager", "Results", ""}
def _is_unattended_mode() -> bool:
"""Whether scripts are running without a human available to answer dialogs.
Benchmark auto-pilot predates ``IMAGENTJ_UNATTENDED`` and does not set it, so
derive the same fact from the benchmark flags as well. An explicit true
unattended flag always wins; an explicit false flag only disables the generic
unattended mode, not benchmark auto-pilot.
"""
explicit = os.environ.get("IMAGENTJ_UNATTENDED", "").strip().lower()
if explicit in {"1", "true", "yes", "on"}:
return True
return (
os.environ.get("BENCHMARK_MODE", "").strip().lower() == "true"
and os.environ.get("BENCHMARK_INTERACTIVE", "").strip().lower() != "true"
)
def _is_dialog_window(window) -> bool:
"""Return True for any java.awt.Dialog/JDialog, modal or modeless.
``WaitForUserDialog`` is deliberately modeless at the AWT level but still
blocks the calling workflow until a button is pressed, so ``isModal()`` is not
a sufficient unattended-safety test.
"""
try:
cls = window.getClass()
while cls is not None:
if str(cls.getName()) in {"java.awt.Dialog", "javax.swing.JDialog"}:
return True
cls = cls.getSuperclass()
except Exception:
pass
return False
def _snapshot_all_windows() -> dict:
"""
Snapshot {classname::title: window} for ALL visible AWT windows
(Frame + Dialog). Used by _WindowMonitor only — _get_open_frames
remains the source of truth for TextWindow exception detection.
"""
Window = jimport("java.awt.Window")
result = {}
try:
for window in Window.getWindows():
if not window.isVisible():
continue
try:
title = str(window.getTitle())
except Exception:
title = str(window.getClass().getSimpleName())
key = f"{window.getClass().getSimpleName()}::{title}"
result[key] = window
except Exception:
pass
return result
class _WindowMonitor:
"""
Polls Window.getWindows() in a background thread while the script runs.
Classifies each new window into errors / results / info buckets.
"""
def __init__(
self,
snapshot_before: dict,
poll_interval: float = 0.05,
modal_grace: float = 0.5,
unattended: Optional[bool] = None,
):
self._seen = dict(snapshot_before)
self._errors: list[str] = []
self._results_count = 0
self._info: list[str] = []
self._unattended = _is_unattended_mode() if unattended is None else unattended
self._poll_interval = poll_interval
self._modal_grace = modal_grace
self._pending_modals: dict[str, float] = {}
self._fatal_dialog: Optional[str] = None
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread = threading.Thread(target=self._run, daemon=True)
def start(self) -> "_WindowMonitor":
self._thread.start()
return self
def _run(self):
while not self._stop.is_set():
self._poll()
time.sleep(self._poll_interval)
def _poll(self):
try:
Window = jimport("java.awt.Window")
visible_keys: set[str] = set()
for window in Window.getWindows():
if not window.isVisible():
continue
try:
title = str(window.getTitle())
except Exception:
title = str(window.getClass().getSimpleName())
key = f"{window.getClass().getSimpleName()}::{title}"
visible_keys.add(key)
if key in self._seen:
continue
if title in _IGNORE_TITLES:
self._seen[key] = window
continue
# A macro can instantiate a dialog and immediately satisfy it from
# recorded options. Give those transient windows a short grace
# period, but a modal that remains visible in unattended mode is
# necessarily waiting for input that will never arrive. Do not
# auto-click or dispose it: accepting defaults can silently change a
# scientific result. _await_groovy observes this fatal marker and
# terminates the disposable worker instead.
if self._unattended and _is_dialog_window(window):
first_seen = self._pending_modals.setdefault(key, time.monotonic())
if time.monotonic() - first_seen < self._modal_grace:
continue
text = _read_window_text(window)
entry = f"[{title}]" if title else "[Modal dialog]"
if text:
entry += f"\n{text[:500]}"
with self._lock:
if self._fatal_dialog is None:
self._fatal_dialog = entry
self._errors.append(entry)
self._seen[key] = window
continue
text = _read_window_text(window)
kind = _classify_window(window, title, text)
entry = f"[{title}]" if title else "[Window]"
if text and kind in ("ERROR", "INFO"):
entry += f"\n{text[:500]}"
with self._lock:
if kind == "ERROR":
self._errors.append(entry)
elif kind == "RESULTS":
self._results_count += 1
else:
self._info.append(entry)
self._seen[key] = window
for key in list(self._pending_modals):
if key not in visible_keys:
self._pending_modals.pop(key, None)
except Exception:
pass
@property
def fatal_dialog(self) -> Optional[str]:
with self._lock:
return self._fatal_dialog
def stop(self) -> dict:
self._stop.set()
self._thread.join(timeout=2.0)
with self._lock:
return {
"errors": list(self._errors),
"results_count": self._results_count,
"info": list(self._info),
}
# ── IJ Log capture ────────────────────────────────────────────────────────
def get_ij_log_content() -> str:
"""Read current text from ImageJ's Log window (IJ.log() output)."""
WindowManager = JClass("ij.WindowManager")
log_frame = WindowManager.getFrame("Log")
if log_frame is None:
return ""
try:
text_panel = log_frame.getTextPanel()
return str(text_panel.getText())
except Exception:
return ""
def get_new_ij_log_entries(log_before: str) -> str:
"""Return only log lines that appeared after `log_before` was captured."""
log_after = get_ij_log_content()
if not log_before:
return log_after
if log_after.startswith(log_before):
return log_after[len(log_before):]
# Log was cleared or rotated between calls — return full current log
return log_after
def _truncate(s: str, max_bytes: int = 2048) -> str:
"""Truncate long text blocks so they don't drown the LLM context."""
if len(s) <= max_bytes:
return s
head = s[:max_bytes]
remaining_lines = s[max_bytes:].count("\n")
return f"{head}\n...[truncated {remaining_lines} more lines]"
# ── Groovy interruption ───────────────────────────────────────────────────
#
# Groovy runs in the shared Fiji JVM, which is what lets a script leave its images
# on screen for the user. Stopping one is subtle, and the obvious approach is
# wrong in a way that silently lies:
#
# ij.py.run_script() is `script().run(...).get()` — the script executes on a
# SciJava pool thread and the caller merely blocks on Future.get(). Interrupting
# the *calling* thread therefore only stops us waiting; the script runs happily on.
# We submit the Future ourselves so we can act on the thread that is really doing
# the work.
#
# Abort is then three escalating signals:
# 1. Future.cancel(true) — interrupts the SciJava thread executing the script
# 2. Macro.abort() — stops the IJ macro interpreter between statements
# 3. IJ.setKeyDown(ESC) — long-running IJ ops poll IJ.escapePressed() and bail
#
# Interrupting only reaches code that checks the interrupt flag, so on its own it
# cannot stop a pure-CPU `while(true){}` — and there is no hard kill to fall back
# on, JDK 20 having degraded Thread.stop() to always throw
# UnsupportedOperationException. That gap is closed by compiling every script with
# @ThreadInterrupt (see _INTERRUPTIBLE_PREFIX), which injects the missing checks.
#
# Verified on this container (JDK 21.0.10, ImageJ 1.54p): sleep/IO/IJ operations
# and runaway CPU loops all stop. What remains uninterruptible is a blocking call
# *inside a Java library* that ignores interrupts — the transform instruments the
# Groovy code, not the plugin it calls into.
#
# Crucially we do not have to guess which happened. Future.isDone() returns true
# the moment cancel() is called even when the thread keeps running, so instead we
# inspect JVM thread stacks for Groovy frames and report what is actually true.
_ESC_KEYCODE = 27 # java.awt.event.KeyEvent.VK_ESCAPE
_ABORT_GRACE_SECONDS = 5.0 # how long we wait for an abort to actually land
# Groovy's @ThreadInterrupt AST transform injects a
# Thread.currentThread().isInterrupted() check into every loop iteration and
# method entry. That is what makes a pure-CPU `while(true){x++}` killable at all:
# Future.cancel(true) sets the interrupt flag, but code that never blocks would
# otherwise never look at it.
#
# Applied by annotating an import — the documented way to attach a script-level
# AST transform — and deliberately kept to ONE line, because it shifts every
# reported error line number by exactly that much (see _fix_line_numbers).
#
# Verified on this container: the spin loop dies, and SciJava `#@` parameter
# injection still resolves behind this line.
_INTERRUPTIBLE_PREFIX = "@groovy.transform.ThreadInterrupt import groovy.transform.Field\n"
_PREFIX_LINES = 1
_SCRIPT_LINE_RE = re.compile(r"(script\.groovy:)(\d+)")
def _fix_line_numbers(text: str) -> str:
"""
Undo the line shift the @ThreadInterrupt prefix introduces.
The debugger agent navigates by these numbers, so an uncorrected off-by-one
would point it at the wrong line of every failing Groovy script.
"""
return _SCRIPT_LINE_RE.sub(
lambda m: f"{m.group(1)}{max(int(m.group(2)) - _PREFIX_LINES, 1)}", text
)
_HARD_TIMEOUT_SECONDS = run_control.HARD_TIMEOUT_SECONDS
def _signal_imagej_abort() -> None:
"""Fire ImageJ's cooperative abort paths. Never raises."""
try:
jimport("ij.Macro").abort()
except Exception:
pass
try:
jimport("ij.IJ").setKeyDown(_ESC_KEYCODE)
except Exception:
pass
def _reset_imagej_escape() -> None:
"""
Clear a latched ESC. Must run before every script: IJ.escapePressed() is
global JVM state, so an ESC left set by a previous abort would make the next
script bail out instantly for no visible reason.
"""
try:
jimport("ij.IJ").resetEscape()
except Exception:
pass
def _groovy_thread_ids() -> set[int]:
"""
IDs of JVM threads currently executing a Groovy script.
This is our ground truth for "is it actually still running" — the Future
cannot tell us, since cancel() marks it done regardless.
"""
ids: set[int] = set()
try:
JThread = jimport("java.lang.Thread")
for entry in JThread.getAllStackTraces().entrySet():
frames = " ".join(str(f.getClassName()) for f in entry.getValue())
if "groovy" in frames.lower():
ids.add(int(entry.getKey().getId()))
except Exception:
pass
return ids
class _GroovyRunner:
"""
Submits a Groovy script and keeps hold of the Future and the thread running it.
Unlike ij.py.run_script this never blocks the caller, so the run stays
observable and the UI can be handed back the instant a stop is requested.
"""
def __init__(self, ij, script: str):
self._ij = ij
self._script = script
self._future = None
self._baseline: set[int] = set()
self._script_tid: int | None = None
def start(self) -> "_GroovyRunner":
# Threads already running Groovy (e.g. an earlier detached runaway) must
# not be mistaken for this run's thread.
self._baseline = _groovy_thread_ids()
self._future = self._ij.script().run(
"script.groovy", _INTERRUPTIBLE_PREFIX + self._script, True
)
return self
def track_thread(self) -> None:
"""Latch onto this run's SciJava thread. Cheap no-op once found."""
if self._script_tid is not None:
return
new = _groovy_thread_ids() - self._baseline
if new:
self._script_tid = next(iter(new))
def script_thread_running(self) -> bool:
"""
Is this run's thread still executing Groovy?
If we never managed to latch onto the thread we fall back to "is any
Groovy thread running that was not already running when we started" —
failing to identify the thread must never be reported as a clean stop.
"""
self.track_thread()
if self._script_tid is None:
return bool(_groovy_thread_ids() - self._baseline)
return self._script_tid in _groovy_thread_ids()
@property
def done(self) -> bool:
try:
return bool(self._future.isDone())
except Exception:
return True
def cancel(self) -> None:
try:
self._future.cancel(True) # mayInterruptIfRunning
except Exception:
pass
_signal_imagej_abort()
def result(self):
"""Return the script's result, re-raising the script's own error if it threw."""
try:
return self._future.get()
except Exception as exc:
# Future.get wraps script failures in ExecutionException; unwrap so the
# debugger sees the real Groovy error rather than the wrapper.
cause = getattr(exc, "getCause", None)
if cause is not None:
try:
inner = cause()
if inner is not None:
raise RuntimeError(str(inner.toString())) from exc
except RuntimeError:
raise
except Exception:
pass
raise
def _abort_groovy(runner: "_GroovyRunner") -> bool:
"""
Stop a Groovy run. Returns True only when the script thread has verifiably
stopped executing — never on the mere fact that we asked it to.
"""
runner.cancel()
deadline = time.monotonic() + _ABORT_GRACE_SECONDS
while time.monotonic() < deadline:
if not runner.script_thread_running():
return True
time.sleep(0.2)
log.warning(
"Groovy script ignored abort (Future.cancel + Macro.abort + ESC) after %.0fs; "
"detaching — its SciJava thread keeps running until it returns on its own.",
_ABORT_GRACE_SECONDS,
)
return False
def _await_groovy(
runner: "_GroovyRunner",
handle: "run_control.RunHandle",
monitor: _WindowMonitor,
live_sink=None,
live_output=None,
) -> bool:
"""
Wait for the script, honouring stop requests. Returns True if we detached from
a script that refused to stop.
`live_sink` matters only for the batch-subprocess path: the script's output is
captured into JVM buffers, so without echoing it to real stdout the parent
process would see total silence and its watchdog would judge a perfectly
healthy long batch job as stuck.
"""
deadline = time.monotonic() + _HARD_TIMEOUT_SECONDS
emitted = 0
def _echo() -> None:
nonlocal emitted
if live_sink is None or live_output is None:
return
try:
current = live_output()
# IJ.log('\\Clear') makes this shrink, so resync instead of slicing
# with a stale offset (which would emit garbage or nothing at all).
if len(current) < emitted:
emitted = 0
if len(current) > emitted:
live_sink.write(current[emitted:])
live_sink.flush()
emitted = len(current)
except Exception:
pass
while True:
runner.track_thread()
_echo()
fatal_dialog = monitor.fatal_dialog
if fatal_dialog and not handle.terminated:
# Never dismiss a dialog in a disposable worker. Closing it can make
# the plugin accept defaults and let the script execute another write
# before cooperative cancellation lands. Return the error report now;
# groovy_worker flushes it and os._exit() kills the entire JVM.
if os.environ.get("IMAGENTJ_BATCH_WORKER") == "1":
return False
handle.terminate(
"Unexpected modal dialog in unattended execution: "
+ fatal_dialog.replace("\n", " ")[:300],
by="watchdog",
)
return handle.terminate_succeeded is False
if runner.done and not handle.terminated:
_echo()
return False
# The Stop button trips the global signal; the watchdog flips the handle
# from its own thread. Both mean stop waiting on this script.
if stop_signal.is_set() and not handle.terminated:
handle.terminate("Stopped by user", by="user")
# Backstop for when the watchdog is disabled — matches the Python path,
# which bounds its wait via proc.wait(timeout=...).
elif time.monotonic() > deadline and not handle.terminated:
handle.terminate(
f"Exceeded the hard {_HARD_TIMEOUT_SECONDS}s execution limit",
by="watchdog",
)
if handle.terminated:
# terminate() flips the status before the abort has actually been
# attempted, so wait for the verdict rather than racing it to None.
handle.wait_termination_settled(_ABORT_GRACE_SECONDS + 3.0)
return handle.terminate_succeeded is False
time.sleep(0.1)
def _stopped_report(handle, out_stream, ij_log_before, monitor, detached: bool) -> str:
"""
Report for a run that was stopped, whether it aborted cleanly or had to be
abandoned. Deliberately not shaped like a crash: the supervisor must not hand
this to the debugger as a bug to repair.
"""
monitor.stop()
try:
partial = str(out_stream.toString())[-1500:]
except Exception:
partial = ""
try:
ij_log = get_new_ij_log_entries(ij_log_before)[-800:]
except Exception:
ij_log = ""
by_user = handle.killed_by == "user"
headline = run_control.stop_headline(handle)
guidance = run_control.stop_guidance(handle)
tail = (
"Groovy script ignored the abort and was detached"
if detached else
"Groovy script aborted on request"
)
parts = [
f"SUMMARY: {headline} — {tail}",
f"STATUS: {'STOPPED' if by_user else 'TERMINATED'}",
"LANGUAGE: Groovy",
guidance,
]
if detached:
parts.append(
"IMPORTANT: the abort (Future.cancel + Macro.abort + ESC) did not land. Groovy "
"runs inside the shared Fiji JVM and cannot be force-killed (JDK 21 removed "
"Thread.stop), so this script MAY STILL BE RUNNING in the background and could "
"keep writing output or opening windows. Scripts are compiled with "
"@ThreadInterrupt, so a runaway Groovy loop would have stopped — reaching this "
"state means it is most likely blocked inside a Java plugin call that ignores "
"interrupts. Warn the user; to stop it for certain, Fiji has to be restarted."
)
parts.append(f"PARTIAL_STDOUT:\n{partial}" if partial.strip() else "PARTIAL_STDOUT: (none)")
parts.append(f"PARTIAL_IJ_LOG:\n{ij_log}" if ij_log.strip() else "PARTIAL_IJ_LOG: (none)")
return "\n".join(parts)
def _unexpected_dialog_report(
handle, out_stream, ij_log_before, monitor, detached: bool
) -> str:
"""Actionable failure for a modal dialog detected during unattended work."""
fatal = monitor.fatal_dialog or "[unknown modal dialog]"
monitor.stop()
try:
partial = str(out_stream.toString())[-1500:]
except Exception:
partial = ""
try:
ij_log = get_new_ij_log_entries(ij_log_before)[-800:]
except Exception:
ij_log = ""
parts = [
"SUMMARY: ERROR — unexpected modal dialog in unattended execution",
"STATUS: ERROR",
"LANGUAGE: Groovy",
"UNATTENDED DIALOG BLOCKED:",
fatal,
"The script was terminated because nobody can answer a modal dialog in "
"auto-pilot mode. Do not auto-click it or retry unchanged. Replace the "
"prompting plugin entry point with a programmatic/windowless API and pass "
"every required option explicitly.",
]
if os.environ.get("IMAGENTJ_BATCH_WORKER") == "1":
parts.append(
"The isolated worker is exiting with the dialog still unanswered; no "
"post-dialog script statement is allowed to run."
)
if detached:
parts.append(
"The in-JVM script ignored cooperative abort. If this was an isolated "
"batch worker it will now exit; otherwise restart Fiji before running "
"another script."
)
if partial.strip():
parts.append(f"PARTIAL_STDOUT:\n{partial}")
if ij_log.strip():
parts.append(f"PARTIAL_IJ_LOG:\n{ij_log}")
return "\n".join(parts)
def run_groovy_script(script: str, ij, purpose: str = "", live_sink=None) -> str:
"""
Execute a Groovy script in ImageJ/Fiji, capturing all output channels
and classifying windows into errors vs. results vs. info.
Thin wrapper over _run_groovy_script so the @ThreadInterrupt prefix's line
shift is corrected at exactly one place, on every return path.
"""
return _fix_line_numbers(_run_groovy_script(script, ij, purpose, live_sink))
def _run_groovy_script(script: str, ij, purpose: str = "", live_sink=None) -> str:
System = jpype.JClass("java.lang.System")
ByteArrayOutputStream = jpype.JClass("java.io.ByteArrayOutputStream")
PrintStream = jpype.JClass("java.io.PrintStream")
out_stream = ByteArrayOutputStream()
err_stream = ByteArrayOutputStream()
original_out = System.out
original_err = System.err
System.setOut(PrintStream(out_stream))
System.setErr(PrintStream(err_stream))
ij_log_before = get_ij_log_content()
frames_before = _get_open_frames()
windows_before = _snapshot_all_windows()
monitor = _WindowMonitor(windows_before).start()
_reset_imagej_escape()
runner = _GroovyRunner(script=script, ij=ij).start()
# The redirected System.out buffer is readable while the script runs, so the
# watchdog gets live progress here exactly as it does from the Python pipes.
# IJ.log output is folded in too — plenty of Groovy scripts report progress