This repository was archived by the owner on Jun 10, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtui.py
More file actions
2035 lines (1804 loc) · 78.7 KB
/
Copy pathtui.py
File metadata and controls
2035 lines (1804 loc) · 78.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
"""TUI for mimicode — pi-style line-by-line chat, multi-line input, live footer."""
import asyncio
import os
import shutil
import sys
import random
from rich.text import Text
from rich.markdown import Markdown
from rich.padding import Padding
from textual import events
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Vertical, ScrollableContainer
from textual.message import Message
from textual.screen import ModalScreen
from textual.widgets import Input, Label, RichLog, Static, TextArea
from agent import AgentInterrupted, _run_reflect, agent_turn, load_messages, save_messages
from logger import log, start_session
from providers import get_last_usage
from tools_router import analyze_routing, format_routing_stats
from tools_session import all_sessions_token_usage, session_token_usage
from session_history import add_to_history, get_most_recent, get_all, get_by_session_id
import compactor
from diff_display import create_file_diff, DiffLine
# ---------------------------------------------------------------------------
# Color Palettes
# ---------------------------------------------------------------------------
_PALETTES = {
# Uses the terminal's own colours — no overrides
"none": {
"BG": "default",
"BG2": "default",
"FG": "default",
"DIM": "bright_black",
"USER": "bright_blue",
"BOT": "bright_cyan",
"TOOL": "bright_yellow",
"OK": "bright_green",
"ERR": "bright_red",
"ACCENT": "blue",
},
# Balanced neutral charcoal — good for any environment
"default": {
"BG": "#1c1c1e",
"BG2": "#2c2c2e",
"FG": "#d1d1d6",
"DIM": "#6e6e73",
"USER": "#5ac8fa",
"BOT": "#32d74b",
"TOOL": "#ff9f0a",
"OK": "#32d74b",
"ERR": "#ff453a",
"ACCENT": "#0a84ff",
},
# Near-black background, soft high-contrast text
"dark": {
"BG": "#090909",
"BG2": "#141414",
"FG": "#ebebeb",
"DIM": "#4a4a4a",
"USER": "#c8c8c8",
"BOT": "#8db89a",
"TOOL": "#c8a96e",
"OK": "#5fad6f",
"ERR": "#c85a5a",
"ACCENT": "#585858",
},
# White background, warm ink tones
"light": {
"BG": "#ffffff",
"BG2": "#f2f2f7",
"FG": "#1c1c1e",
"DIM": "#8e8e93",
"USER": "#0071e3",
"BOT": "#1a8a3a",
"TOOL": "#b25000",
"OK": "#1a8a3a",
"ERR": "#d70015",
"ACCENT": "#0071e3",
},
# Deep ocean: dark navy with cool blue accents
"dark_blue": {
"BG": "#0a1628",
"BG2": "#0d1f3c",
"FG": "#cdd6f4",
"DIM": "#4a5270",
"USER": "#89b4fa",
"BOT": "#74c7ec",
"TOOL": "#f9e2af",
"OK": "#a6e3a1",
"ERR": "#f38ba8",
"ACCENT": "#89b4fa",
},
# Sky and cloud: pale blue-white with deep blue ink
"light_blue": {
"BG": "#eef2ff",
"BG2": "#dde6fb",
"FG": "#1e1b4b",
"DIM": "#7c87b0",
"USER": "#3730a3",
"BOT": "#0369a1",
"TOOL": "#6d28d9",
"OK": "#15803d",
"ERR": "#be123c",
"ACCENT": "#4f46e5",
},
}
# Current active palette
_CURRENT_PALETTE = "default"
def _get_color(key: str) -> str:
"""Get color from current palette."""
return _PALETTES[_CURRENT_PALETTE][key]
# Color accessors
_BG = lambda: _get_color("BG")
_BG2 = lambda: _get_color("BG2")
_FG = lambda: _get_color("FG")
_DIM = lambda: _get_color("DIM")
_USER = lambda: _get_color("USER")
_BOT = lambda: _get_color("BOT")
_TOOL = lambda: _get_color("TOOL")
_OK = lambda: _get_color("OK")
_ERR = lambda: _get_color("ERR")
_ACCENT = lambda: _get_color("ACCENT")
# ---------------------------------------------------------------------------
# Tool action synonyms and animation
# ---------------------------------------------------------------------------
_ANIMATION_CHARS = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
# Mouse-tracking escape sequences — disable to let the terminal do native selection
_MOUSE_TRACKING_OFF = "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l"
_MOUSE_TRACKING_ON = "\x1b[?1000h\x1b[?1003h\x1b[?1006h"
_TOOL_SYNONYMS = {
"read": ["reading", "scanning", "parsing", "loading", "opening"],
"write": ["writing", "creating", "saving", "generating", "composing"],
"edit": ["editing", "modifying", "updating", "patching", "revising"],
"bash": ["executing", "running", "invoking", "processing", "launching"],
"memory_write": ["storing", "recording", "persisting", "archiving", "saving"],
}
def _get_tool_verb(tool_name: str) -> str:
"""Get a random synonym verb for the tool action."""
synonyms = _TOOL_SYNONYMS.get(tool_name, [f"{tool_name}ing"])
return random.choice(synonyms)
# ---------------------------------------------------------------------------
# Slash command registry
# ---------------------------------------------------------------------------
SLASH_COMMANDS: list[tuple[str, str]] = [
("/help", "show available commands"),
("/clear", "clear chat history"),
("/exit", "exit the application"),
("/new", "start a fresh session"),
("/session", "interactive session picker (or /session <name> to switch directly)"),
("/restore", "restore last closed session (or /restore <session-id>)"),
("/usage", "token usage — this session"),
("/usage all", "token usage — all sessions"),
("/cwd", "change working directory"),
("/palette", "change theme (none/default/dark/light/dark_blue/light_blue)"),
("/pmon", "toggle prompt monitoring (warns on vague prompts)"),
("/compact", "compact conversation now"),
("/compact on", "enable auto-compaction"),
("/compact off", "disable auto-compaction"),
("/compact status", "show compaction status"),
("/copy", "copy last response to clipboard (or ctrl+y)"),
("/select", "toggle select mode for mouse text selection (or f2)"),
]
def _has_subcommands(cmd: str) -> bool:
"""Check if a command has sub-commands in the SLASH_COMMANDS list."""
# Commands with dynamic arguments (not fixed sub-commands) should not be treated as hierarchical
DYNAMIC_ARG_COMMANDS = {"/session", "/palette", "/restore", "/cwd"}
if cmd in DYNAMIC_ARG_COMMANDS:
return False
# A command has sub-commands if there's another command that starts with "cmd "
cmd_prefix = cmd.rstrip() + " "
return any(other_cmd.startswith(cmd_prefix) for other_cmd, _ in SLASH_COMMANDS if other_cmd != cmd)
def _completions(prefix: str) -> list[tuple[str, str]]:
p = prefix.lower()
return [(cmd, desc) for cmd, desc in SLASH_COMMANDS if cmd.startswith(p)]
def _key_arg(tool_name: str, args: dict) -> str:
"""Extract the most informative single argument for the activity line."""
from pathlib import Path as _P
if tool_name in ("read", "write", "edit"):
p = args.get("path", "")
return _P(p).name if p else ""
if tool_name == "bash":
cmd = args.get("cmd", "")
return (cmd[:60] + "…") if len(cmd) > 60 else cmd
return ""
# ---------------------------------------------------------------------------
# Session picker helpers
# ---------------------------------------------------------------------------
def _time_ago(mtime: float) -> str:
"""Convert a Unix mtime to a concise human-readable string."""
import time as _t
delta = _t.time() - mtime
if delta < 60: return "just now"
if delta < 3600: return f"{int(delta/60)}m ago"
if delta < 86400: return f"{int(delta/3600)}h ago"
if delta < 604800: return f"{int(delta/86400)}d ago"
return f"{int(delta/604800)}w ago"
def _session_preview(session_path) -> tuple[int, str]:
"""Return (turn_count, last_user_message_preview) from a session's messages file."""
import json as _j
mp = session_path.with_suffix(".messages.json")
if not mp.exists():
return 0, ""
try:
data = _j.loads(mp.read_text())
if not isinstance(data, list):
return 0, ""
turns, last_msg = 0, ""
for msg in data:
if msg.get("role") == "user":
c = msg.get("content", "")
if isinstance(c, str) and c.strip():
turns += 1
last_msg = c.strip().replace("\n", " ")
return turns, last_msg[:80]
except Exception:
return 0, ""
def _gather_session_metas(sessions_dir, current_id: str) -> list[dict]:
"""Collect metadata for all sessions in sessions_dir, sorted newest first."""
paths = sorted(
[p for p in sessions_dir.glob("*.jsonl") if not p.name.startswith(".")],
key=lambda p: p.stat().st_mtime,
reverse=True,
)
metas = []
for path in paths:
mtime = path.stat().st_mtime
turns, last_msg = _session_preview(path)
try:
cost = session_token_usage(path)["cost_usd"]
except Exception:
cost = 0.0
metas.append({
"id": path.stem,
"mtime": mtime,
"turns": turns,
"last_msg": last_msg,
"cost": cost,
"is_current": path.stem == current_id,
})
return metas
# ---------------------------------------------------------------------------
# Session picker CSS + screen
# ---------------------------------------------------------------------------
def _get_session_picker_css() -> str:
return f"""
SessionPickerScreen {{
align: center middle;
}}
#picker-box {{
width: 96%;
max-width: 120;
height: 85%;
background: {_BG2()};
border: solid {_ACCENT()};
}}
#picker-title {{
height: 1;
background: {_ACCENT()};
color: {_BG()};
padding: 0 1;
text-style: bold;
}}
#picker-filter {{
height: 3;
background: {_BG()};
border: none;
border-bottom: solid {_DIM()};
color: {_FG()};
padding: 0 1;
}}
#picker-filter:focus {{
border-bottom: solid {_ACCENT()};
}}
#picker-scroll {{
height: 1fr;
background: {_BG2()};
}}
#picker-list {{
height: auto;
background: {_BG2()};
padding: 0 0 0 0;
}}
#picker-help {{
height: 1;
background: {_BG2()};
color: {_DIM()};
padding: 0 1;
border-top: solid {_DIM()};
}}
"""
class SessionPickerInput(Input):
"""Custom Input that passes navigation keys to parent screen."""
async def _on_key(self, event: events.Key) -> None:
"""Pass escape, up, down, enter to parent screen for navigation."""
# Navigation keys should not be handled by Input - let them bubble to parent
if event.key in ("escape", "up", "down", "enter"):
return # Don't handle, let parent screen handle
# For all other keys, call parent Input's handler
await super()._on_key(event)
class SessionPickerScreen(ModalScreen):
"""Claude Code-style interactive session picker."""
BINDINGS = [
Binding("escape", "cancel", show=False, priority=True),
Binding("up", "cursor_up", show=False, priority=True),
Binding("down", "cursor_down", show=False, priority=True),
Binding("enter", "confirm", show=False, priority=True),
]
def __init__(self, metas: list[dict]) -> None:
SessionPickerScreen.DEFAULT_CSS = _get_session_picker_css()
super().__init__()
self._all_metas = metas
self._displayed: list[dict | None] = [] # None = "new session" sentinel
self._cursor = 0
self._filter = ""
self._rebuild()
def _rebuild(self) -> None:
f = self._filter.lower()
filtered = [
m for m in self._all_metas
if not f or f in m["id"].lower() or f in (m["last_msg"] or "").lower()
]
self._displayed = [None] + filtered
self._cursor = max(0, min(self._cursor, len(self._displayed) - 1))
def compose(self) -> ComposeResult:
with Vertical(id="picker-box"):
yield Label(
" SESSIONS · ↑↓ navigate · Enter open · type to filter · Esc stay",
id="picker-title",
)
yield SessionPickerInput(placeholder=" filter...", id="picker-filter")
with ScrollableContainer(id="picker-scroll"):
yield Static("", id="picker-list")
yield Label(
" id age turns cost last message",
id="picker-help",
)
def on_mount(self) -> None:
self._render_list()
self.query_one(Input).focus()
def _render_list(self) -> None:
widget = self.query_one("#picker-list", Static)
if not self._displayed:
widget.update(Text(" (nothing matches)", style=_DIM()))
return
lines = Text()
for i, item in enumerate(self._displayed):
sel = (i == self._cursor)
arrow = "▶ " if sel else " "
if item is None:
icon = "✦"
row = Text.assemble(
(f" {arrow}", f"bold {_ACCENT() if sel else _DIM()}"),
(f"{icon} new session", f"bold {_USER() if sel else _FG()}"),
)
else:
sid = item["id"]
age = _time_ago(item["mtime"])
turns_s = f"{item['turns']}t"
cost_s = f"${item['cost']:.3f}"
preview = (item["last_msg"] or "")[:50]
mark = " ←" if item["is_current"] else ""
id_color = _ACCENT() if item["is_current"] else _FG()
if sel:
row = Text.assemble(
(f" {arrow}", f"bold {_ACCENT()}"),
(f"{sid:<20}", f"bold {id_color}"),
(f" {age:<10}", _DIM()),
(f" {turns_s:<6}", _DIM()),
(f" {cost_s:<8}", _OK()),
(f" {preview}", _FG()),
(mark, f"bold {_ACCENT()}"),
)
else:
row = Text.assemble(
(f" {arrow}", _DIM()),
(f"{sid:<20}", id_color),
(f" {age:<10}", _DIM()),
(f" {turns_s:<6}", _DIM()),
(f" {cost_s:<8}", _DIM()),
(f" {preview}", _DIM()),
(mark, _ACCENT()),
)
lines.append_text(row)
if i < len(self._displayed) - 1:
lines.append("\n")
widget.update(lines)
def on_input_changed(self, event: Input.Changed) -> None:
self._filter = event.value
self._cursor = 0
self._rebuild()
self._render_list()
def on_key(self, event: events.Key) -> None:
"""Handle key events at screen level."""
if event.key == "escape":
event.prevent_default()
event.stop()
# Find and return to current session
current = next((m["id"] for m in self._all_metas if m.get("is_current")), None)
self.dismiss(current)
elif event.key == "up":
event.prevent_default()
event.stop()
if self._cursor > 0:
self._cursor -= 1
self._render_list()
elif event.key == "down":
event.prevent_default()
event.stop()
if self._cursor < len(self._displayed) - 1:
self._cursor += 1
self._render_list()
elif event.key == "enter":
event.prevent_default()
event.stop()
if not self._displayed:
self.dismiss(None)
return
item = self._displayed[self._cursor]
self.dismiss("__new__" if item is None else item["id"])
else:
# Pass unhandled keys to parent
super().on_key(event)
def action_cancel(self) -> None:
"""Cancel action - return to current session."""
current = next((m["id"] for m in self._all_metas if m.get("is_current")), None)
self.dismiss(current)
def action_cursor_up(self) -> None:
if self._cursor > 0:
self._cursor -= 1
self._render_list()
def action_cursor_down(self) -> None:
if self._cursor < len(self._displayed) - 1:
self._cursor += 1
self._render_list()
def action_confirm(self) -> None:
if not self._displayed:
self.dismiss(None)
return
item = self._displayed[self._cursor]
self.dismiss("__new__" if item is None else item["id"])
# ---------------------------------------------------------------------------
# PromptEditor
# ---------------------------------------------------------------------------
def _get_prompt_editor_css() -> str:
"""Generate PromptEditor CSS with current palette colors."""
return f"""
PromptEditor {{
height: auto;
min-height: 3;
max-height: 10;
background: {_BG()};
color: {_FG()};
border: none;
border-top: solid {_ACCENT()};
padding: 0 1;
}}
PromptEditor:focus {{
border-top: solid {_USER()};
}}
PromptEditor .text-area--cursor-line {{
background: {_BG2()};
}}
"""
class PromptEditor(TextArea):
"""Multi-line input. Enter=submit, Shift+Enter=newline, Tab=autocomplete."""
DEFAULT_CSS = _get_prompt_editor_css()
class Submitted(Message):
def __init__(self, editor: "PromptEditor", value: str) -> None:
self.editor = editor
self.value = value
super().__init__()
class TabPressed(Message):
def __init__(self, editor: "PromptEditor") -> None:
self.editor = editor
super().__init__()
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._paste_content: dict[str, str] = {}
self._history: list[str] = []
self._history_index: int = 0
self._draft: str = ""
def _on_paste(self, event: events.Paste) -> None:
"""Intercept paste before TextArea processes it."""
pasted_text = event.text
lines = pasted_text.splitlines()
if len(lines) > 1:
event.prevent_default()
event.stop()
placeholder = f"[Pasted {len(lines)} lines]"
self._paste_content[placeholder] = pasted_text
self.insert(placeholder)
else:
super()._on_paste(event)
def _on_key(self, event: events.Key) -> None:
"""Intercept keys before TextArea's default handling."""
if event.key == "enter":
# If autocomplete has matches, select the highlighted one
current_completions = getattr(self.app, "_current_completions", [])
if current_completions:
event.prevent_default()
event.stop()
self.app.run_worker(self.app._select_completion(), exclusive=False)
return
# Otherwise submit the prompt
event.prevent_default()
event.stop()
text = self.text.strip()
if text:
expanded_text = self._expand_paste_placeholders(text)
self._history.append(text)
self._history_index = len(self._history)
self._draft = ""
self.post_message(self.Submitted(self, expanded_text))
self.load_text("")
self._paste_content.clear()
elif event.key == "up":
if getattr(self.app, "_current_completions", []):
event.prevent_default()
event.stop()
self.app._navigate_completion(-1)
return
row, _ = self.cursor_location
if row == 0 and self._history_index > 0:
event.prevent_default()
event.stop()
if self._history_index == len(self._history):
self._draft = self.text
self._history_index -= 1
self.load_text(self._history[self._history_index])
self.move_cursor(self.document.end)
elif event.key == "down":
if getattr(self.app, "_current_completions", []):
event.prevent_default()
event.stop()
self.app._navigate_completion(1)
return
row, _ = self.cursor_location
if row == self.document.line_count - 1 and self._history_index < len(self._history):
event.prevent_default()
event.stop()
self._history_index += 1
if self._history_index == len(self._history):
self.load_text(self._draft)
else:
self.load_text(self._history[self._history_index])
self.move_cursor(self.document.end)
elif event.key == "escape":
# Hide autocomplete on Escape
if getattr(self.app, "_current_completions", []):
event.prevent_default()
event.stop()
self.app._hide_autocomplete()
return
elif event.key == "shift+enter":
event.prevent_default()
event.stop()
self.insert("\n")
elif event.key == "tab":
event.prevent_default()
event.stop()
self.post_message(self.TabPressed(self))
elif event.key == "backspace":
row, col = self.cursor_location
line_text = self.document.get_line(row)
text_before = line_text[:col]
for placeholder in list(self._paste_content.keys()):
if text_before.endswith(placeholder):
event.prevent_default()
event.stop()
# Select the whole placeholder and delete it as one unit
self.move_cursor((row, col - len(placeholder)), select=True)
self.insert("")
del self._paste_content[placeholder]
return
def _expand_paste_placeholders(self, text: str) -> str:
"""Replace all paste placeholders with their actual content."""
expanded = text
for placeholder, actual_content in self._paste_content.items():
expanded = expanded.replace(placeholder, actual_content)
return expanded
# ---------------------------------------------------------------------------
# AutocompleteBox
# ---------------------------------------------------------------------------
def _get_autocomplete_css() -> str:
"""Generate AutocompleteBox CSS with current palette colors."""
return f"""
AutocompleteBox {{
background: {_BG2()};
border: solid {_ACCENT()};
padding: 0 1;
height: auto;
display: none;
}}
AutocompleteBox.visible {{
display: block;
}}
"""
class AutocompleteBox(Static):
"""Floating slash-command suggestions shown above the editor."""
DEFAULT_CSS = _get_autocomplete_css()
def show_completions(self, matches: list[tuple[str, str]], selected: int = 0) -> None:
if not matches:
self.remove_class("visible")
return
lines = Text()
for i, (cmd, desc) in enumerate(matches):
indicator = " → " if i == selected else " "
row = Text.assemble(
(indicator, f"bold {_USER()}"),
(f"{cmd:<20}", _FG() if i != selected else f"bold {_USER()}"),
(f" {desc}", _DIM()),
)
lines.append_text(row)
if i < len(matches) - 1:
lines.append("\n")
self.update(lines)
self.add_class("visible")
def hide(self) -> None:
self.remove_class("visible")
# ---------------------------------------------------------------------------
# MimicodeApp
# ---------------------------------------------------------------------------
def _get_app_css() -> str:
"""Generate app CSS with current palette colors."""
return f"""
Screen {{
background: {_BG()};
}}
#header {{
background: {_BG2()};
color: {_DIM()};
height: 1;
padding: 0 1;
}}
#chat {{
height: 1fr;
background: {_BG()};
padding: 0 1;
scrollbar-size: 0 0;
}}
#activity {{
height: 2;
background: {_BG()};
padding: 0 1;
display: none;
}}
#activity.active {{
display: block;
}}
#pmon-warning {{
background: #3d2e00;
color: #f0c060;
height: 1;
padding: 0 1;
display: none;
}}
#pmon-warning.visible {{
display: block;
}}
#footer-bar {{
background: {_BG2()};
color: {_DIM()};
height: 1;
padding: 0 1;
}}
"""
class MimicodeApp(App):
"""Mimicode TUI — pi-style layout."""
CSS = _get_app_css()
BINDINGS = [
Binding("ctrl+d", "quit", "Quit", show=False, priority=True),
Binding("ctrl+c", "interrupt", "Interrupt", show=False, priority=True),
Binding("escape", "interrupt_restore", "Interrupt+restore", show=False, priority=True),
Binding("ctrl+y", "copy_last", "Copy", show=False, priority=True),
Binding("f2", "toggle_select_mode", "Select", show=False),
]
def __init__(self, session_id: str | None = None) -> None:
super().__init__()
self.session = start_session(session_id)
self.messages = load_messages(self.session.path)
self.cwd = os.getcwd()
self.is_processing = False
self._last_prompt: str = ""
self._cancel_event: asyncio.Event = asyncio.Event()
self._agent_task: asyncio.Task | None = None
self._current_completions: list[tuple[str, str]] = []
self._autocomplete_selected: int = 0
self._current_text_blocks: dict[int, str] = {}
self._current_tool_blocks: dict[int, dict] = {}
self._interrupted: bool = False
self._last_tool_name: str = ""
self._last_tool_args: dict = {}
self._last_tool_result: str | None = None
self._last_tool_diff_info: dict | None = None
self._animation_index: int = 0
self._animation_timer: asyncio.Task | None = None
self._pmon_enabled: bool = False
self._pmon_warned: bool = False
self._task_start_time: float | None = None
self._tools_used_this_turn: bool = False
self._truncated_diffs: dict[str, dict] = {} # path -> {file_diff, max_lines_shown}
self._last_bot_text: str = ""
self._select_mode: bool = False
def compose(self) -> ComposeResult:
yield Label(
f"mimicode · {self.session.id} · {self.cwd} · shift+enter for newline · ctrl+c interrupt · esc interrupt+restore · ctrl+y copy · f2 select · ctrl+d quit",
id="header",
)
yield RichLog(id="chat", markup=False, highlight=False, wrap=True, auto_scroll=True)
yield Static("", id="activity")
yield AutocompleteBox(id="autocomplete")
yield Static("", id="pmon-warning")
yield PromptEditor("", id="editor", language=None, show_line_numbers=False)
yield Label("", id="footer-bar")
def on_key(self, event: events.Key) -> None:
"""Keep focus locked to the editor at all times (main screen only)."""
if isinstance(self.screen, ModalScreen):
return
try:
editor = self.query_one(PromptEditor)
except Exception:
return
# block tab/shift+tab from cycling focus to other widgets
if event.key in ("tab", "shift+tab"):
event.prevent_default()
event.stop()
# if focus drifted away (e.g. clicked RichLog), snap it back
if self.focused is not editor:
editor.focus()
def on_mount(self) -> None:
log("tui_start", {"session_id": self.session.id, "cwd": self.cwd, "resumed": len(self.messages)})
if self.messages:
self._render_history()
n = sum(1 for m in self.messages if m["role"] == "user" and isinstance(m.get("content"), str))
self._sys(f"resumed · {n} prior turns")
self._update_footer()
self.query_one(PromptEditor).focus()
# -----------------------------------------------------------------------
# Actions
# -----------------------------------------------------------------------
def _do_interrupt(self, restore: bool = False) -> None:
"""Immediately cancel the agent task and restore UI. No waiting."""
# Escape always exits select mode first
if self._select_mode:
self._select_mode = False
self._write_terminal_seq(_MOUSE_TRACKING_ON)
self._update_header()
self._sys("select mode off.")
self._log().scroll_end(animate=True)
return
if not self.is_processing:
if not restore:
pass
else:
self.query_one(AutocompleteBox).hide()
return
self._cancel_event.set()
if self._agent_task and not self._agent_task.done():
self._agent_task.cancel()
self._interrupted = True
self._stop_animation_timer()
self._pmon_warned = False
self._hide_pmon_warning()
editor = self.query_one(PromptEditor)
self._clear_activity()
self._current_text_blocks.clear()
self._current_tool_blocks.clear()
self._blank()
self._sys("interrupted.")
self._update_footer()
self._log().scroll_end(animate=True)
editor.disabled = False
editor.focus()
self.is_processing = False
if restore and self._last_prompt:
editor.load_text(self._last_prompt)
editor.move_cursor(editor.document.end)
def action_interrupt(self) -> None:
self._do_interrupt(restore=False)
def action_interrupt_restore(self) -> None:
self._do_interrupt(restore=True)
def _copy_to_clipboard(self, text: str) -> bool:
"""Write text to the system clipboard. Returns True on success."""
import subprocess
try:
if sys.platform == "win32":
subprocess.run(["clip"], input=text, text=True, encoding="utf-8", check=True)
elif sys.platform == "darwin":
subprocess.run(["pbcopy"], input=text, text=True, check=True)
else:
try:
subprocess.run(["xclip", "-selection", "clipboard"], input=text, text=True, check=True)
except FileNotFoundError:
subprocess.run(["xsel", "--clipboard", "--input"], input=text, text=True, check=True)
return True
except Exception:
return False
def action_copy_last(self) -> None:
"""Copy the last bot response to the system clipboard (Ctrl+Y)."""
if not self._last_bot_text:
self._sys("nothing to copy yet")
self._log().scroll_end(animate=True)
return
if self._copy_to_clipboard(self._last_bot_text):
self._sys("copied to clipboard.")
else:
self._sys("copy failed — clipboard tool not available")
self._log().scroll_end(animate=True)
def _write_terminal_seq(self, seq: str) -> None:
"""Write a raw VT escape sequence directly to the terminal device."""
try:
# sys.__stdout__ is the original stdout before any redirection
out = sys.__stdout__
if out is not None:
out.write(seq)
out.flush()
except Exception:
pass
def action_toggle_select_mode(self) -> None:
"""Toggle select mode (F2): disable Textual mouse tracking so the terminal
can do native text selection with click-and-drag."""
self._select_mode = not self._select_mode
if self._select_mode:
self._write_terminal_seq(_MOUSE_TRACKING_OFF)
self._update_header()
self._sys(
"SELECT MODE — drag to select · Ctrl+C or right-click to copy"
" · F2 or Esc to return"
)
else:
self._write_terminal_seq(_MOUSE_TRACKING_ON)
self._update_header()
self._sys("select mode off.")
self._log().scroll_end(animate=True)
# -----------------------------------------------------------------------
# Streaming event handler
# -----------------------------------------------------------------------
async def _handle_stream_event(self, event_type: str, data: dict) -> None:
"""Handle real-time streaming events from the agent."""
# Don't render anything if user has cancelled
if self._cancel_event.is_set():
return
if event_type == "text_start":
# New text block starting
idx = data["index"]
self._current_text_blocks[idx] = ""
elif event_type == "text_delta":
# Text chunk received - render immediately
idx = data["index"]
text_chunk = data["text"]
self._current_text_blocks[idx] = self._current_text_blocks.get(idx, "") + text_chunk
# For now, we'll just accumulate - full render happens at tool_start/tool_complete
elif event_type == "tool_start":
# Tool use block starting - track it
idx = data["index"]
tool_name = data["name"]
self._current_tool_blocks[idx] = {
"id": data["id"],
"name": tool_name,
"input": {},
}
# Render any accumulated text before showing the tool
self._render_accumulated_text()
elif event_type == "tool_complete":
# Tool definition complete - store the full args
idx = data["index"]
self._current_tool_blocks[idx] = {
"id": data["id"],
"name": data["name"],
"input": data["input"],
}
elif event_type == "tool_exec_start":
tool_name = data["name"]
args = data["args"]
self._tools_used_this_turn = True
self._last_tool_name = tool_name
self._last_tool_args = args
self._last_tool_result = None
self._set_activity(tool_name, args)
elif event_type == "tool_exec_result":
output = data["output"]
is_error = data["is_error"]
diff_info = data.get("diff_info")
args = dict(self._last_tool_args)
args["_is_error"] = is_error
self._last_tool_result = output
self._last_tool_diff_info = diff_info
# Render tool result immediately with diff
self._tool_call(self._last_tool_name, self._last_tool_args)
self._tool_result(output, is_error, diff_info)
self._log().scroll_end(animate=True)
# Update activity widget
self._set_activity(self._last_tool_name, args, result=output)
def _render_accumulated_text(self) -> None:
"""Render any accumulated text blocks."""
if self._current_text_blocks:
full_text = "".join(self._current_text_blocks.values())
if full_text.strip():
self._bot(full_text)
self._current_text_blocks.clear()
# -----------------------------------------------------------------------