forked from LJMedPhys/Imagent_J
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgui_runner.py
More file actions
1358 lines (1139 loc) · 53.7 KB
/
Copy pathgui_runner.py
File metadata and controls
1358 lines (1139 loc) · 53.7 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
"""ImagentJ GUI — chat bubbles + per-conversation usage tracking."""
import sys
sys.path.insert(0, 'src')
import os
import re
import json
import time
import html as html_module
import logging
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import jpype
from PySide6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QTextEdit, QPushButton, QLabel, QListWidget,
QSplitter, QScrollArea, QMessageBox, QListWidgetItem,
QSizePolicy, QFrame, QGroupBox,
QDialog, QDialogButtonBox, QPlainTextEdit, QCheckBox,
)
from PySide6.QtCore import QObject, Signal, Slot, QThread, Qt, QSize, QEvent, QTimer
from queue import Queue
from imagentj.agents import init_agent, set_qa_enabled
from imagentj.imagej_context import get_ij
from imagentj.chat_history import ChatHistoryManager
from imagentj.tools.analyst_tools import kill_running_processes
import imagentj.stop_signal as stop_signal
from imagentj.benchmark_gui_hooks import is_benchmark_mode, setup_benchmark_gui
logging.basicConfig(
filename="/app/data/agentic-j_debug.log",
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(message)s",
force=True,
)
log = logging.getLogger("imagentj")
SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "scripts/saved_scripts")
intro_message = """Hello I am ImageJ agent, some call me Agentic-J :)
I can design a step-by-step protocol and, if useful, generate a runnable Groovy macro (and execute/test it if you want).
To get started, please share:
- **Goal:** what you want measured/segmented/processed/counted etc.
- **Image details:** 1-2 sample images (file type), single image or batch?
- **File location:** file/folder path or is the image open in the window.
- **Outputs:** tables/measurements, labeled masks/overlays, ROIs, saved images, what format.
- **Solving approach (UI/script):** do you want to go click-by-click via user interface or do you want scripts to run in the background for you?
- **Plugin preference:** are there specific plugin/models you want to use.
If you're unsure, tell me what task do you want to solve and provide one representative image."""
os.environ["LANGCHAIN_CALLBACKS_BACKGROUND"] = "true"
# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------
def _extract_text(content) -> str:
"""Extract plain text from a message content field (str or list of blocks)."""
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
parts.append(block["text"])
elif isinstance(block, str):
parts.append(block)
return " ".join(parts)
return ""
def _md_to_html(text: str) -> str:
"""Convert plain/markdown text to HTML suitable for a QLabel."""
escaped = html_module.escape(text)
lines = escaped.split('\n')
result: list[str] = []
in_code = False
code_lines: list[str] = []
for line in lines:
if line.startswith('```'):
if not in_code:
in_code = True
code_lines = []
else:
in_code = False
code_html = '<br>'.join(code_lines)
result.append(
'<div style="background:#2b2b2b; color:#f8f8f2; '
'padding:10px; border-radius:6px; font-family:monospace; '
f'margin:6px 0;">{code_html}</div>'
)
continue
if in_code:
code_lines.append(line)
continue
# Headings → bold (same size as body text)
if line.startswith('### '):
result.append(f'<b>{line[4:]}</b>')
continue
if line.startswith('## '):
result.append(f'<b>{line[3:]}</b>')
continue
if line.startswith('# '):
result.append(f'<b>{line[2:]}</b>')
continue
# Horizontal rules → dropped
if re.fullmatch(r'[-*_]{3,}', line.strip()):
continue
# Inline code
line = re.sub(
r'`([^`]+)`',
r'<code style="background:rgba(0,0,0,0.12); padding:1px 4px; '
r'border-radius:3px; font-family:monospace;">\1</code>',
line,
)
line = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', line)
line = re.sub(r'\*(.+?)\*', r'<i>\1</i>', line)
result.append(line)
return '<br>'.join(result)
# ---------------------------------------------------------------------------
# Chat bubble widgets
# ---------------------------------------------------------------------------
class _BubbleLabel(QLabel):
"""QLabel that lets its parent layout freely constrain its width."""
def minimumSizeHint(self):
sh = super().minimumSizeHint()
return QSize(1, sh.height())
class MessageBubble(QFrame):
"""A single chat message rendered as a styled bubble."""
_STYLES = {
'user': dict(bg='#2980b9', fg='white', align='right', label='You'),
'ai': dict(bg='#ecf0f1', fg='#2c3e50', align='left', label='AI'),
'system': dict(bg='transparent', fg='#7f8c8d', align='left', label=None),
'error': dict(bg='#fdecea', fg='#c0392b', align='left', label='Error'),
}
def __init__(self, text: str, role: str = 'ai', parent=None):
super().__init__(parent)
self.role = role
s = self._STYLES.get(role, self._STYLES['system'])
outer = QHBoxLayout(self)
outer.setContentsMargins(4, 2, 4, 2)
outer.setSpacing(0)
self._label = _BubbleLabel()
self._label.setWordWrap(True)
self._label.setTextFormat(Qt.RichText)
self._label.setTextInteractionFlags(
Qt.TextSelectableByMouse
| Qt.TextSelectableByKeyboard
| Qt.LinksAccessibleByMouse
)
self._label.setOpenExternalLinks(True)
self._label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
if s['bg'] != 'transparent':
self._label.setStyleSheet(
f"background-color:{s['bg']}; color:{s['fg']}; "
"border-radius:10px; padding:8px 12px; font-size:13px;"
)
else:
self._label.setStyleSheet(
f"color:{s['fg']}; font-size:11px; font-style:italic; padding:2px 8px;"
)
outer.addWidget(self._label)
self._label_prefix = s['label']
self.update_text(text)
def update_text(self, text: str):
try:
# Guard: C++ widget may have been deleted during shutdown
self._label.isVisible()
except RuntimeError:
return
body = _md_to_html(text)
content = f'<b>{self._label_prefix}:</b> {body}' if self._label_prefix else body
if self.role == 'user':
self._label.setText(f'<div align="right">{content}</div>')
else:
self._label.setText(content)
class ChatScrollArea(QWidget):
"""Scrollable container for MessageBubble widgets."""
def __init__(self, parent=None):
super().__init__(parent)
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
self._scroll = QScrollArea()
self._scroll.setWidgetResizable(True)
self._scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self._scroll.setStyleSheet("QScrollArea { border: none; background: white; }")
self._container = QWidget()
self._container.setStyleSheet("background: white;")
self._msg_layout = QVBoxLayout(self._container)
self._msg_layout.setContentsMargins(2,2,2,2)
self._msg_layout.setSpacing(6)
self._msg_layout.setAlignment(Qt.AlignTop)
self._last_bubble = None
self._scroll.setWidget(self._container)
outer.addWidget(self._scroll)
def resizeEvent(self, event):
super().resizeEvent(event)
vp_w = self._scroll.viewport().width()
if vp_w > 0:
self._container.setMaximumWidth(vp_w)
def scroll_to_bottom(self, widget: "MessageBubble | None" = None):
"""Scroll to make `widget` visible, or to the last bubble if None.
Uses ensureWidgetVisible so we land on actual content rather than the
empty space Qt leaves below AlignTop layouts in a resizable scroll area.
The zero-delay timer defers the call until after Qt's layout pass.
"""
def _do_scroll():
target = widget or self._last_bubble
if target is not None:
try:
self._scroll.ensureWidgetVisible(target)
except RuntimeError:
pass # widget deleted during shutdown
QTimer.singleShot(0, _do_scroll)
def add_message(self, role: str, text: str, *, auto_scroll: bool = True) -> MessageBubble:
bubble = MessageBubble(text, role)
self._msg_layout.addWidget(bubble)
self._last_bubble = bubble
if auto_scroll:
self.scroll_to_bottom(bubble)
return bubble
def clear_messages(self):
self._last_bubble = None
while self._msg_layout.count() > 0:
item = self._msg_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
class SubagentHeartbeatTimer:
"""Cycles through plausible sub-step messages while a subagent tool is running.
Because subagents are called synchronously (no streaming), we can't receive
their internal tool calls. This timer fires every INTERVAL ms and updates
the status bubble with the next message in the sequence, giving the user
visual evidence that work is happening.
"""
INTERVAL = 5000 # ms between message rotations
# Messages shown while each long-running subagent is in flight.
# Each list is cycled in order and then repeated.
STEPS: dict[str, list[str]] = {
"imagej_coder": [
"Bio-Imaging Specialist is checking past lessons learned…",
"Bio-Imaging Specialist is searching ImageJ documentation…",
"Bio-Imaging Specialist is verifying the Java API…",
"Bio-Imaging Specialist is writing the Groovy script…",
"Bio-Imaging Specialist is adding error handling…",
"Bio-Imaging Specialist is saving the script…",
],
"imagej_debugger": [
"Debugger is reading the faulty script…",
"Debugger is checking previous failure history…",
"Debugger is inspecting the Java API for the correct signature…",
"Debugger is applying the minimal fix…",
"Debugger is saving the repaired script…",
],
"python_data_analyst": [
"Data Scientist is inspecting the CSV structure…",
"Data Scientist is checking previous script versions…",
"Data Scientist is selecting appropriate statistical tests…",
"Data Scientist is writing the analysis script…",
"Data Scientist is adding publication-quality plot settings…",
"Data Scientist is saving the script…",
],
# "vlm_judge": [ # VLM disabled
# "Vision AI is capturing the ImageJ window…",
# "Vision AI is building the comparison panel…",
# "Vision AI is sending the image for analysis…",
# "Vision AI is evaluating against expected output…",
# "Vision AI is compiling the verdict…",
# ],
"qa_reporter": [
"QA Agent is scanning the project folder…",
"QA Agent is reading script documentation…",
"QA Agent is reading CSV output headers…",
"QA Agent is evaluating workflow checklist items…",
"QA Agent is evaluating image publishing checklist items…",
"QA Agent is writing the QA report…",
],
}
def __init__(self, tool_name: str, set_status_fn):
"""
Args:
tool_name: one of the keys in STEPS
set_status_fn: callable(str) — updates the status bubble
"""
self._steps = self.STEPS.get(tool_name, [f"Running {tool_name}…"])
self._set = set_status_fn
self._idx = 0
self._timer = QTimer()
self._timer.setInterval(self.INTERVAL)
self._timer.timeout.connect(self._tick)
def start(self):
"""Show the first message immediately, then start rotating."""
self._idx = 0
self._set(self._steps[0])
if len(self._steps) > 1:
self._timer.start()
def stop(self):
self._timer.stop()
def _tick(self):
self._idx = (self._idx + 1) % len(self._steps)
self._set(self._steps[self._idx])
# ---------------------------------------------------------------------------
# Metrics panel
# ---------------------------------------------------------------------------
class MetricsPanelWidget(QWidget):
"""Shows token/cost/tool metrics for the active conversation."""
qa_toggled = Signal(bool)
def __init__(self, parent=None):
super().__init__(parent)
self._build_ui()
def _build_ui(self):
root = QVBoxLayout(self)
root.setContentsMargins(6, 6, 6, 6)
root.setSpacing(4)
header = QLabel("<b>Conversation Metrics</b>")
header.setAlignment(Qt.AlignCenter)
root.addWidget(header)
sep = QFrame()
sep.setFrameShape(QFrame.HLine)
sep.setFrameShadow(QFrame.Sunken)
root.addWidget(sep)
tok_box = QGroupBox("Tokens")
tok_layout = QVBoxLayout(tok_box)
tok_layout.setSpacing(2)
self._lbl_in = QLabel()
self._lbl_out = QLabel()
self._lbl_total = QLabel()
for lbl in (self._lbl_in, self._lbl_out, self._lbl_total):
lbl.setTextFormat(Qt.RichText)
tok_layout.addWidget(lbl)
root.addWidget(tok_box)
perf_box = QGroupBox("Performance")
perf_layout = QVBoxLayout(perf_box)
perf_layout.setSpacing(2)
self._lbl_time = QLabel()
self._lbl_cost = QLabel()
for lbl in (self._lbl_time, self._lbl_cost):
lbl.setTextFormat(Qt.RichText)
perf_layout.addWidget(lbl)
root.addWidget(perf_box)
tool_box = QGroupBox("Tool Calls")
tool_layout = QVBoxLayout(tool_box)
tool_layout.setSpacing(2)
self._lbl_calls = QLabel()
self._lbl_failed = QLabel()
self._lbl_soft = QLabel()
for lbl in (self._lbl_calls, self._lbl_failed, self._lbl_soft):
lbl.setTextFormat(Qt.RichText)
tool_layout.addWidget(lbl)
root.addWidget(tool_box)
self._btn_save = QPushButton("Save Usage Report")
self._btn_save.setStyleSheet(
"padding: 4px; background-color: #2980b9; "
"color: white; border-radius: 3px; font-size: 11px;"
)
root.addWidget(self._btn_save)
self._btn_report = QPushButton("Report Issue")
self._btn_report.setStyleSheet(
"padding: 4px; background-color: #e74c3c; "
"color: white; border-radius: 3px; font-size: 11px;"
)
root.addWidget(self._btn_report)
sep2 = QFrame()
sep2.setFrameShape(QFrame.HLine)
sep2.setFrameShadow(QFrame.Sunken)
root.addWidget(sep2)
agent_box = QGroupBox("Agent Options")
agent_layout = QVBoxLayout(agent_box)
agent_layout.setSpacing(4)
self._qa_checkbox = QCheckBox("QA Agent")
self._qa_checkbox.setChecked(False)
self._qa_checkbox.stateChanged.connect(
lambda _: self.qa_toggled.emit(self._qa_checkbox.isChecked())
)
agent_layout.addWidget(self._qa_checkbox)
qa_desc = QLabel(
"Audits the finished project against publication-readiness "
"checks and writes <i>QA_Checklist_Report.md</i>.<br>"
"<span style='color:#c0392b;'>Expensive — adds significant "
"token cost per workflow.</span>"
)
qa_desc.setTextFormat(Qt.RichText)
qa_desc.setWordWrap(True)
qa_desc.setStyleSheet("color:#555; font-size:10px; padding-left:18px;")
agent_layout.addWidget(qa_desc)
root.addWidget(agent_box)
root.addStretch()
self.update_metrics({
"input_tokens": 0, "output_tokens": 0, "total_tokens": 0,
"thinking_seconds": 0.0, "cost_usd": 0.0,
"tool_calls": 0, "failed_tool_calls": 0, "soft_error_tool_calls": 0,
})
@staticmethod
def _fmt(name: str, value: str, color: str, bold: bool = False) -> str:
w = "bold" if bold else "normal"
return (
f"<span style='color:#555;'>{name}:</span> "
f"<span style='color:{color};font-weight:{w};'>{value}</span>"
)
@Slot(dict)
def update_metrics(self, data: dict):
f = self._fmt
self._lbl_in.setText( f("Input", f"{data['input_tokens']:,}", "#2980b9"))
self._lbl_out.setText( f("Output", f"{data['output_tokens']:,}", "#27ae60"))
self._lbl_total.setText( f("Total", f"{data['total_tokens']:,}", "#8e44ad", bold=True))
secs = data["thinking_seconds"]
t_str = f"{int(secs//60)}m {int(secs%60)}s" if secs >= 60 else f"{secs:.1f}s"
self._lbl_time.setText( f("Think time", t_str, "#16a085"))
cost = data["cost_usd"]
cost_str = f"${cost:.4f}" if cost >= 0.0001 else "-"
self._lbl_cost.setText( f("Est. cost", cost_str, "#c0392b", bold=True))
self._lbl_calls.setText( f("Total", str(data["tool_calls"]), "#2c3e50"))
self._lbl_failed.setText(f("Hard errors", str(data["failed_tool_calls"]), "#e74c3c"))
self._lbl_soft.setText( f("Soft errors", str(data["soft_error_tool_calls"]), "#e67e22"))
# ---------------------------------------------------------------------------
# Email helper
# ---------------------------------------------------------------------------
_REPORT_EMAIL = "[email protected]"
def _send_report_email(subject: str, body: str, attachments: list[tuple[str, bytes]]) -> None:
"""Send a report email from [email protected] to itself via Gmail SMTP.
Raises RuntimeError if GMAIL_APP_PASSWORD is not set or sending fails.
attachments: list of (filename, bytes) pairs.
"""
app_password = os.environ.get("GMAIL_APP_PASSWORD", "").replace(" ", "")
if not app_password:
raise RuntimeError(
"GMAIL_APP_PASSWORD is not set in your .env file.\n"
"Generate an App Password at:\n"
" Google Account → Security → 2-Step Verification → App Passwords"
)
msg = MIMEMultipart()
msg["From"] = _REPORT_EMAIL
msg["To"] = _REPORT_EMAIL
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))
for filename, data in attachments:
part = MIMEApplication(data, Name=filename)
part["Content-Disposition"] = f'attachment; filename="{filename}"'
msg.attach(part)
ctx = ssl.create_default_context()
import socket
# Resolve to IPv4 — Docker containers often lack IPv6 (errno 97).
smtp_ip = socket.getaddrinfo("smtp.gmail.com", 587, socket.AF_INET)[0][4][0]
smtp_ip_465 = socket.getaddrinfo("smtp.gmail.com", 465, socket.AF_INET)[0][4][0]
raw = msg.as_bytes()
try:
# Port 587 with STARTTLS (preferred)
with smtplib.SMTP(smtp_ip, 587, timeout=15) as smtp:
smtp._host = "smtp.gmail.com" # starttls verifies against hostname, not IP
smtp.ehlo()
smtp.starttls(context=ctx)
smtp.ehlo()
smtp.login(_REPORT_EMAIL, app_password)
smtp.sendmail(_REPORT_EMAIL, _REPORT_EMAIL, raw)
except (OSError, smtplib.SMTPException):
# Port 465 implicit TLS fallback (some networks block 587)
with smtplib.SMTP_SSL(smtp_ip_465, 465, context=ctx, timeout=15) as smtp:
smtp._host = "smtp.gmail.com"
smtp.login(_REPORT_EMAIL, app_password)
smtp.sendmail(_REPORT_EMAIL, _REPORT_EMAIL, raw)
# ---------------------------------------------------------------------------
# Feedback / Error-Report dialog
# ---------------------------------------------------------------------------
class FeedbackDialog(QDialog):
"""Modal dialog for collecting user feedback and exporting an error report."""
def __init__(self, tracker_cb, history_manager, current_thread_id, parent=None):
super().__init__(parent)
self._tracker_cb = tracker_cb
self._history_manager = history_manager
self._current_thread_id = current_thread_id
self.setWindowTitle("Report Issue")
self.setMinimumWidth(480)
self.setModal(True)
layout = QVBoxLayout(self)
layout.setSpacing(10)
layout.setContentsMargins(14, 14, 14, 14)
desc_label = QLabel(
"<b>Describe the problem</b><br>"
"<span style='color:#555; font-size:11px;'>"
"What did you ask the agent to do, and what went wrong?</span>"
)
desc_label.setTextFormat(Qt.RichText)
desc_label.setWordWrap(True)
layout.addWidget(desc_label)
self._text_edit = QPlainTextEdit()
self._text_edit.setPlaceholderText(
"e.g. 'The script ran but measured 0 cells on my fluorescence image.'"
)
self._text_edit.setFixedHeight(120)
layout.addWidget(self._text_edit)
options_box = QGroupBox("Export options")
options_layout = QVBoxLayout(options_box)
options_layout.setSpacing(4)
self._chk_usage = QCheckBox("Include usage stats (token counts, cost)")
self._chk_usage.setChecked(True)
options_layout.addWidget(self._chk_usage)
layout.addWidget(options_box)
conv_box = QGroupBox("Include conversations")
conv_layout = QVBoxLayout(conv_box)
conv_layout.setSpacing(2)
self._conv_list = QListWidget()
self._conv_list.setSelectionMode(QListWidget.NoSelection)
threads = self._history_manager.list_threads()
for thread_id, meta in threads:
title = meta.get("title", thread_id)
display = f"{title[:45]}\u2026" if len(title) > 45 else title
item = QListWidgetItem(display)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(
Qt.Checked if thread_id == self._current_thread_id else Qt.Unchecked
)
item.setData(Qt.UserRole, thread_id)
self._conv_list.addItem(item)
self._conv_list.setFixedHeight(min(len(threads), 6) * 22 + 6)
conv_layout.addWidget(self._conv_list)
sel_row = QHBoxLayout()
btn_all = QPushButton("Select all")
btn_none = QPushButton("Select none")
btn_all.setFixedHeight(20)
btn_none.setFixedHeight(20)
btn_all.clicked.connect(lambda: self._set_all_checks(Qt.Checked))
btn_none.clicked.connect(lambda: self._set_all_checks(Qt.Unchecked))
sel_row.addWidget(btn_all)
sel_row.addWidget(btn_none)
conv_layout.addLayout(sel_row)
layout.addWidget(conv_box)
info = QLabel(
"<span style='color:#888; font-size:10px;'>"
"The report includes: error details and script code from selected conversation, "
"your description, and basic system info (OS, Python version). "
"No image data or raw file contents are included. Multiple conversations are exported as a ZIP.</span>"
)
info.setTextFormat(Qt.RichText)
info.setWordWrap(True)
layout.addWidget(info)
btn_box = QDialogButtonBox()
btn_box.addButton("Send Report\u2026", QDialogButtonBox.AcceptRole)
btn_box.addButton("Cancel", QDialogButtonBox.RejectRole)
btn_box.accepted.connect(self._on_export)
btn_box.rejected.connect(self.reject)
layout.addWidget(btn_box)
def _set_all_checks(self, state):
for i in range(self._conv_list.count()):
self._conv_list.item(i).setCheckState(state)
def _on_export(self):
selected = []
for i in range(self._conv_list.count()):
item = self._conv_list.item(i)
if item.checkState() == Qt.Checked:
selected.append(item.data(Qt.UserRole))
if not selected:
QMessageBox.warning(self, "Nothing selected",
"Please select at least one conversation.")
return
self._tracker_cb.set_user_feedback(self._text_edit.toPlainText().strip())
include_usage = self._chk_usage.isChecked()
import io, zipfile as _zipfile
timestamp = time.strftime('%Y%m%d_%H%M%S')
feedback_text = self._text_edit.toPlainText().strip()
try:
if len(selected) == 1:
report = self._tracker_cb.get_error_report_for_thread(
selected[0], include_usage_stats=include_usage
)
fname = f"report_{selected[0][:8]}_{timestamp}.json"
attachments = [(fname, json.dumps(report, indent=2, ensure_ascii=False).encode())]
else:
buf = io.BytesIO()
with _zipfile.ZipFile(buf, "w", _zipfile.ZIP_DEFLATED) as zf:
for thread_id in selected:
report = self._tracker_cb.get_error_report_for_thread(
thread_id, include_usage_stats=include_usage
)
zf.writestr(f"report_{thread_id[:8]}.json",
json.dumps(report, indent=2, ensure_ascii=False))
fname = f"agentic-j_issue_{timestamp}.zip"
attachments = [(fname, buf.getvalue())]
subject = f"[Agentic-J] Issue Report — {timestamp}"
body = f"User feedback:\n{feedback_text or '(none provided)'}\n\nAttached: {len(selected)} conversation(s)."
_send_report_email(subject, body, attachments)
QMessageBox.information(self, "Report Sent",
f"Issue report sent to {_REPORT_EMAIL}.\n\nThank you for the feedback!")
self.accept()
except Exception as e:
log.exception(f"Failed to send issue report: {e}")
reply = QMessageBox.warning(
self, "Send Failed",
f"Could not send the report by email:\n{e}\n\n"
"Would you like to save it to a file instead?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes,
)
if reply == QMessageBox.Yes:
default_name = os.path.expanduser(
f"~/agentic-j_issue_{time.strftime('%Y%m%d_%H%M%S')}"
f"{'zip' if len(attachments) == 1 and attachments[0][0].endswith('.zip') else 'json'}"
)
path, _ = QFileDialog.getSaveFileName(
self, "Save Issue Report", default_name,
"All files (*)",
)
if path:
with open(path, "wb") as f:
f.write(attachments[0][1])
QMessageBox.information(self, "Report Saved",
f"Report saved to:\n{path}\n\nPlease send it manually to {_REPORT_EMAIL}.")
self.accept()
# ---------------------------------------------------------------------------
# Background worker
# ---------------------------------------------------------------------------
class AgentWorker(QObject):
event_received = Signal(dict)
finished = Signal()
error = Signal(str)
def __init__(self, supervisor, thread_id: str, tracker_callback):
super().__init__()
self.supervisor = supervisor
self.thread_id = thread_id
self.tracker_callback = tracker_callback
self.tasks = Queue()
self._stop_requested = False
@Slot()
def start(self):
if jpype.isJVMStarted() and not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
while True:
prompt = self.tasks.get()
if prompt is None:
break
self._stop_requested = False
stop_signal.clear()
self._run_prompt(prompt)
def _run_prompt(self, user_input: str):
try:
config = {
"configurable": {"thread_id": self.thread_id},
"callbacks": [self.tracker_callback],
}
gen = self.supervisor.stream(
{"messages": [{"role": "user", "content": user_input}]},
config=config,
stream_mode="updates",
)
for event in gen:
if self._stop_requested:
gen.close()
break
self.event_received.emit(event)
except Exception as e:
log.exception(f"_run_prompt exception: {e}")
self.error.emit(str(e))
finally:
log.debug("_run_prompt finished")
self.finished.emit()
def submit(self, prompt: str):
self.tasks.put(prompt)
def request_stop(self):
self._stop_requested = True
stop_signal.request_stop()
# Kill any running subprocesses immediately (Python scripts, etc.)
killed = kill_running_processes()
if killed:
log.info(f"Stop: killed {killed} running subprocess(es)")
# ---------------------------------------------------------------------------
# Chat history sidebar
# ---------------------------------------------------------------------------
class ChatHistoryPanel(QWidget):
thread_selected = Signal(str)
new_chat_requested = Signal()
def __init__(self):
super().__init__()
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
self.setMinimumWidth(180)
self.setMaximumWidth(280)
layout = QVBoxLayout()
layout.setContentsMargins(4, 4, 4, 4)
layout.setSpacing(4)
header = QLabel("<b>Chat history</b>")
header.setStyleSheet("font-size: 13px; padding: 4px 0;")
layout.addWidget(header)
self.btn_new = QPushButton("New Chat")
self.btn_new.setStyleSheet(
"background-color: #2ecc71; color: white; font-weight: bold; "
"padding: 6px; border-radius: 4px;"
)
self.btn_new.clicked.connect(self.new_chat_requested)
layout.addWidget(self.btn_new)
self.session_list = QListWidget()
self.session_list.setWordWrap(True)
self.session_list.setStyleSheet(
"QListWidget { border: 1px solid #ddd; border-radius: 4px; outline: none; }"
"QListWidget::item { padding: 6px 4px; border-bottom: 1px solid #eee; }"
"QListWidget::item:selected, "
"QListWidget::item:selected:active, "
"QListWidget::item:selected:!active { background-color: #3498db; color: white; }"
"QListWidget::item:hover:!selected { background-color: #e8f4fd; }"
)
self.session_list.itemClicked.connect(self._on_item_clicked)
layout.addWidget(self.session_list)
self.setLayout(layout)
self._thread_ids: list[str] = []
def populate(self, threads: list[tuple[str, dict]]):
self.session_list.clear()
self._thread_ids = []
for thread_id, meta in threads:
title = meta.get("title", "Untitled")
date_str = meta.get("last_updated", "")[:10]
item = QListWidgetItem(f"{title}\n{date_str}")
item.setSizeHint(QSize(0, 52))
self.session_list.addItem(item)
self._thread_ids.append(thread_id)
def set_active(self, thread_id: str):
if thread_id in self._thread_ids:
self.session_list.setCurrentRow(self._thread_ids.index(thread_id))
else:
self.session_list.clearSelection()
def _on_item_clicked(self, item: QListWidgetItem):
idx = self.session_list.row(item)
if 0 <= idx < len(self._thread_ids):
self.thread_selected.emit(self._thread_ids[idx])
# ---------------------------------------------------------------------------
# Main window
# ---------------------------------------------------------------------------
class ImageJAgentGUI(QWidget):
start_agent_work = Signal(str)
def __init__(self):
super().__init__()
self.setWindowTitle("Agentic-J - AI Supervisor & Script Library")
self.resize(1100, 680)
self.setAcceptDrops(True)
self.attached_files: list[str] = []
self.history_manager = ChatHistoryManager()
# Streaming state
self._current_ai_bubble: MessageBubble | None = None
self._ai_response_buffer: str = ""
self._status_bubble: MessageBubble | None = None
self._agent_had_error: bool = False
# Agent + tracker (init_agent returns 5 values)
(self.supervisor,
self.checkpointer,
self._metrics,
self._metrics_bridge,
self._tracker_cb) = init_agent()
# --- Main layout ---
main_layout = QHBoxLayout()
splitter = QSplitter(Qt.Horizontal)
# LEFT: chat history sidebar
self.history_panel = ChatHistoryPanel()
self.history_panel.thread_selected.connect(self.switch_thread)
self.history_panel.new_chat_requested.connect(self.new_chat)
# MIDDLE: chat interface
chat_widget = QWidget()
chat_layout = QVBoxLayout()
self.chat_scroll = ChatScrollArea()
self.input_line = QTextEdit()
self.input_line.setFixedHeight(120)
self.send_button = QPushButton("Send")
self.send_button.setStyleSheet(
"background-color: #3498db; color: white; font-weight: bold; padding: 8px; border:none;"
)
self.stop_button = QPushButton("Stop")
self.stop_button.setEnabled(False)
self.stop_button.setStyleSheet(
"background-color: #bdc3c7; color: #7f8c8d; font-weight: bold; padding: 8px; border:none;"
)
self.stop_button.clicked.connect(self.on_stop)
self.status_label = QLabel("Agent is ready to help")
self.status_label.setStyleSheet("color: green; font-weight: bold;")
btn_row = QHBoxLayout()
btn_row.addWidget(self.send_button, stretch=4)
btn_row.addWidget(self.stop_button, stretch=1)
chat_layout.addWidget(self.chat_scroll, stretch=3)
chat_layout.addWidget(self.input_line, stretch=1)
chat_layout.addLayout(btn_row)
chat_layout.addWidget(self.status_label, stretch=0)
chat_widget.setLayout(chat_layout)
# RIGHT: metrics panel
self.metrics_panel = MetricsPanelWidget()
self.metrics_panel.setMinimumWidth(190)
self.metrics_panel.setMaximumWidth(250)
self.metrics_panel._btn_save.clicked.connect(self._save_report)
self.metrics_panel._btn_report.clicked.connect(self._open_feedback_dialog)
self.metrics_panel.qa_toggled.connect(self._on_qa_toggled)
splitter.addWidget(self.history_panel)
splitter.addWidget(chat_widget)
splitter.addWidget(self.metrics_panel)
splitter.setStretchFactor(0, 0)
splitter.setStretchFactor(1, 1)
splitter.setStretchFactor(2, 0)
main_layout.addWidget(splitter)
self.setLayout(main_layout)
# Wire signals
self.send_button.clicked.connect(self.on_send)
self.input_line.installEventFilter(self)
self._metrics_bridge.updated.connect(self.metrics_panel.update_metrics)
# Initialize ImageJ
self.ij = get_ij()
self.ij.ui().showUI()
# Worker thread
self.current_thread_id: str = ""
self._is_new_thread: bool = True
self.thread = QThread()
self.worker = AgentWorker(self.supervisor, "", self._tracker_cb)
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.start)
self.worker.event_received.connect(self.handle_event)
self.worker.finished.connect(self.on_agent_finished)
self.worker.error.connect(self.on_agent_error)
self.thread.start()
self._current_status_bubble = None
self._active_tasks = {} # Tracks tool_id -> status_text
self._init_session()
if is_benchmark_mode():
setup_benchmark_gui(self)
# ------------------------------------------------------------------
# Session management
# ------------------------------------------------------------------
def _init_session(self):
threads = self.history_manager.list_threads()
self.history_panel.populate(threads)
if threads:
self._load_thread(threads[0][0])
else:
self._start_new_thread()
def _start_new_thread(self):
thread_id = self.history_manager.create_thread()
self.current_thread_id = thread_id
self.worker.thread_id = thread_id
self._is_new_thread = True
self._current_ai_bubble = None
self._ai_response_buffer = ""
self._status_bubble = None
self._tracker_cb.switch_thread(thread_id)
self.chat_scroll.clear_messages()
self.chat_scroll.add_message('ai', intro_message)
self.history_panel.populate(self.history_manager.list_threads())
self.history_panel.set_active(thread_id)
if is_benchmark_mode():
setup_benchmark_gui(self)
def _load_thread(self, thread_id: str):
self.current_thread_id = thread_id
self.worker.thread_id = thread_id
self._is_new_thread = False
self._current_ai_bubble = None
self._ai_response_buffer = ""
self._status_bubble = None
self._tracker_cb.switch_thread(thread_id)