@yahyahammad/venastine 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tui/widgets.py CHANGED
@@ -5,14 +5,23 @@ ROADMAP_v2 §16 widgets. Presentation only -- nothing here imports core/
5
5
  or reaches into harness state; tui/app.py feeds them.
6
6
  """
7
7
 
8
+ import webbrowser
9
+
10
+ from rich import box
11
+ from rich.console import Console
12
+ from rich.style import Style
8
13
  from rich.syntax import Syntax
14
+ from rich.table import Table
9
15
  from rich.text import Text
16
+ from textual.binding import Binding
17
+ from textual.message import Message
10
18
  from textual.reactive import reactive
11
- from textual.widgets import RichLog, Static
19
+ from textual.widgets import RichLog, Static, TextArea
12
20
 
13
21
  from prompts.system_prompts import pass_label
14
22
 
15
- from tui import diffs, ravens, themes
23
+ from tui import diffs, markdown, ravens, themes
24
+ from tui.commands import registry as commands
16
25
 
17
26
  # Animation cadence. Slow enough to read, and paused outright while tokens
18
27
  # are streaming -- a redraw loop competing with token deltas is the one
@@ -34,6 +43,39 @@ THINKING_INDENT = " "
34
43
  # (a bare-built test widget, a widget before mount) reads as 0.
35
44
  MIN_WRAP_WIDTH = 20
36
45
 
46
+ # Batch 55, the slash-command suggestion panel. The two caps are a pair:
47
+ # five entries is the list a reader takes in at a glance, eight rows is
48
+ # what leaves the transcript readable at the 24-row floor, and at 80
49
+ # columns most entries wrap to two rows so the ROW cap is usually the one
50
+ # that bites. See SlashSuggest for why the gutters are inside the wrap.
51
+ SUGGEST_SEP = " ● "
52
+ SUGGEST_ELLIPSIS = "…"
53
+ SUGGEST_LEAD = " "
54
+ SUGGEST_CONT = " "
55
+ SUGGEST_MAX_ENTRIES = 5
56
+ SUGGEST_MAX_ROWS = 8
57
+ SUGGEST_MAX_LINES = 2
58
+ SUGGEST_HIGHLIGHT = "reverse"
59
+
60
+ # Batch 62, the keys the panel spends while it is open. Four of them
61
+ # change meaning here and none was written anywhere in the TUI: the
62
+ # arrows move the highlight, tab and enter BOTH complete, escape
63
+ # dismisses. `enter` is the one that costs something -- it completes
64
+ # rather than sends, so a fully typed /help takes two presses, and the
65
+ # first changes nothing a reader can see except a trailing space.
66
+ #
67
+ # `tab/enter` is one item because they are one action: action_submit
68
+ # and action_complete both call _complete(). The separator is the
69
+ # title's, so the two labels on this box read as one voice.
70
+ #
71
+ # NO SQUARE BRACKETS. `_BorderTitle.__set__` runs the value through
72
+ # `render_str`, so a `[` is markup -- and the getter hands back
73
+ # `.markup`, which re-escapes it, so the change-guard below would
74
+ # never compare equal and every paint would schedule another.
75
+ SUGGEST_HINT_SEP = " · "
76
+ SUGGEST_HINT_MOVE = "↑↓ move"
77
+ SUGGEST_HINT_REST = ("tab/enter complete", "esc dismiss")
78
+
37
79
  # §41. The inline diff's furniture, owned by the renderer for the same
38
80
  # reason the thinking bar is: `_entries` keeps the canonical block, so
39
81
  # /copy hands back a diff rather than a decorated string and a replay
@@ -69,6 +111,14 @@ _DIFF_MARKS = {
69
111
  diffs.ELIDED: " ",
70
112
  }
71
113
 
114
+ # Batch 53. The table's box, and the owner's choice among rich.box's
115
+ # presets. A full grid rather than one of the rule-only forms: the
116
+ # transcript already draws box characters for a thinking span (╭ │ ╰), so
117
+ # the vocabulary is established, and a table is the one construct here
118
+ # whose whole point is that a reader can follow a row across several
119
+ # columns without losing the line.
120
+ TABLE_BOX = box.SQUARE
121
+
72
122
  # Batch 41 (X3). The checklist vocabulary, in ONE place because two
73
123
  # panels render it and they were already spelling it differently: the
74
124
  # todo list used `x` for done where the research panel used `x` for a
@@ -112,15 +162,37 @@ MARK_STAGE = "·"
112
162
  # MESSAGE_ROLES, so a new role has to be classified rather than land in
113
163
  # one target or the other by accident.
114
164
  CONVERSATION_ROLES = frozenset({
115
- "user", "assistant", "thinking", "tool", "tool_error", "diff"})
165
+ "user", "assistant", "thinking", "tool", "tool_error", "diff",
166
+ "pipeline_tool"})
116
167
 
117
168
  # `pass` and `pass_done` are here rather than above deliberately: a
118
169
  # ten-pass run's boundaries are progress reporting about the harness,
119
170
  # not the exchange, so a research run copies as the query, the tool
120
- # lines and the report.
171
+ # lines and the report. `pipeline_tool` is that same call made in the
172
+ # other direction: it is the research tool line's own role -- distinct
173
+ # from `tool` so it cannot open the turn's label the way a chat tool
174
+ # call now can -- and it classifies as CONVERSATION so batch 48's copy
175
+ # shape survives the rename unchanged.
121
176
  META_ROLES = frozenset({
122
177
  "system", "warning", "error", "pass", "pass_done", "success"})
123
178
 
179
+ # Batch 65 (TECHNICAL_DEBT 16). The lines whose URLs are armed for
180
+ # ctrl+click, beside the two sets above for their reason: which roles a
181
+ # rule is true of is a list, and a list that lives at its one use site
182
+ # is a list nothing can check.
183
+ #
184
+ # These three are what a model's tool CALL or its failure produced --
185
+ # `▸ fetch_url https://…` is where a URL most obviously appears, and it
186
+ # was the one place inert while the same URL in prose was not. The
187
+ # harness's own voice (`system`, `error`, `warning`) is deliberately
188
+ # absent: those lines are written here, not by a model, and nothing has
189
+ # reported wanting to click one.
190
+ #
191
+ # They take the LINKS-ONLY scanner, never the prose grammar. A tool
192
+ # line is a digest, and `markdown.link_spans` says at length what the
193
+ # full grammar does to one.
194
+ LINKED_ROLES = frozenset({"tool", "pipeline_tool", "tool_error"})
195
+
124
196
 
125
197
  class RavenPanel(Static):
126
198
  """Corner raven: what the harness is doing right now."""
@@ -409,7 +481,9 @@ class TodoPanel(Static):
409
481
 
410
482
  # A window, for ResearchProgress's reason: a Static does not scroll
411
483
  # itself to the bottom, so an unbounded list would push the newest item
412
- # out of view -- the opposite of the problem being solved.
484
+ # out of view -- the opposite of the problem being solved. The window is
485
+ # the ONLY bound since batch 59; the `max-height` beside it in the
486
+ # stylesheet was clipping, not scrolling.
413
487
  ROWS = 12
414
488
 
415
489
  todos = reactive(None, always_update=True)
@@ -459,6 +533,121 @@ class TodoPanel(Static):
459
533
  self.update(body)
460
534
 
461
535
 
536
+ class AgentPanel(Static):
537
+ """Who is running, and how deep (batch 59).
538
+
539
+ A STACK, NEVER A LIST OF PEERS, and that is a fact about the harness
540
+ rather than a rendering choice. core/loop.py dispatches tool calls in
541
+ a plain `for` loop and spawn_subagent BLOCKS on the child run, so
542
+ there is never a second agent alongside the first -- what there is is
543
+ a chain, each frame suspended inside the one below it, bounded by
544
+ config.SUBAGENT_MAX_DEPTH. Indentation is the honest drawing of that;
545
+ a flat list would claim a concurrency this harness does not have.
546
+
547
+ Fed from core/agent_activity.py through app.py, never polled -- the
548
+ same split TodoPanel keeps: the sink says when, and this widget holds
549
+ no authoritative copy of anything.
550
+
551
+ Hidden when it has nothing to say, GoalBanner-style: the sidebar is
552
+ twenty columns wide and its rows are contested, so `default` with an
553
+ empty stack costs nothing rather than a permanent row saying so.
554
+ """
555
+
556
+ # 22-column box, less a border column and a padding column each side.
557
+ # MEASURED, not derived from the `width: 22` in the stylesheet: the
558
+ # border is easy to forget and the answer is 19, dropping to 18 while
559
+ # the sidebar's scrollbar is up. The narrow case is the one to lay out
560
+ # against, since a row that fits 18 fits 19.
561
+ WIDTH = 18
562
+
563
+ # Two spaces per level, so depth 2 costs four columns of the eighteen.
564
+ INDENT = 2
565
+
566
+ def __init__(self, **kwargs):
567
+ super().__init__(**kwargs)
568
+ self._agent = None
569
+ self._stack: list = []
570
+ # Explicit, for TodoPanel's reason: a widget that renders nothing
571
+ # yet must not be a visible empty box before its first update.
572
+ self.display = False
573
+
574
+ def _styles(self) -> dict:
575
+ try:
576
+ app = self.app
577
+ except Exception: # noqa: BLE001 -- see Transcript._styles
578
+ return {}
579
+ return themes.styles_for(app)
580
+
581
+ def show(self, agent_name, stack) -> None:
582
+ """Draw the active agent and the spans currently open under it.
583
+
584
+ `agent_name` is None when no /agent switch is active. `stack` is a
585
+ list of (name, depth), outermost first.
586
+ """
587
+ self._agent = agent_name
588
+ self._stack = list(stack)
589
+ self._redraw()
590
+
591
+ def restyle(self) -> None:
592
+ """Re-render under the current theme (#183), like ResearchProgress."""
593
+ self._redraw()
594
+
595
+ @classmethod
596
+ def _fit(cls, text: str, width: int) -> str:
597
+ """Truncate to `width` cells, with an ellipsis when it bites.
598
+
599
+ Appended by hand rather than through `Text.truncate()`, which
600
+ batch 55 measured doing nothing on a wrapped line -- and the rows
601
+ here are `no_wrap`, so an overlong one would be cropped invisibly
602
+ instead. `pipeline-reviewer` is seventeen characters and reaches
603
+ this at every depth below the root.
604
+ """
605
+ if width <= 0:
606
+ return ""
607
+ if len(text) <= width:
608
+ return text
609
+ if width == 1:
610
+ return "\u2026"
611
+ return text[:width - 1] + "\u2026"
612
+
613
+ def _redraw(self) -> None:
614
+ if self._agent is None and not self._stack:
615
+ self.display = False
616
+ self.update("")
617
+ return
618
+
619
+ styles = self._styles()
620
+ body = Text()
621
+ body.append("agent\n\n")
622
+ # The root row is drawn whenever anything is: the indented rows
623
+ # below hang off it, and a spawn under no /agent switch would
624
+ # otherwise start at column two with nothing above it.
625
+ # `assistant_label`, not a raw "accent" key -- role_styles has no
626
+ # such role, so that lookup would silently return "" and /theme
627
+ # would never reach this row. Bold accent is the IDENTITY role,
628
+ # which is exactly what "which agent is answering" is; the spans
629
+ # below take plain `tool` accent, so the root reads as the heavier
630
+ # of the two without introducing a second hue.
631
+ body.append(
632
+ self._fit(self._agent or "default", self.WIDTH) + "\n",
633
+ styles.get("assistant_label", ""))
634
+ for name, depth in self._stack:
635
+ # `max(depth, 1)` so a span that somehow reports depth 0 still
636
+ # reads as nested rather than colliding with the root row --
637
+ # two rows at column zero would say two agents are running,
638
+ # which is the one thing this panel must never claim.
639
+ pad = " " * (self.INDENT * max(depth, 1))
640
+ room = self.WIDTH - len(pad) - 2 # the marker and its space
641
+ body.append(f"{pad}{MARK_RUNNING} {self._fit(name, room)}\n",
642
+ styles.get("tool", ""))
643
+ # `no_wrap` / crop for batch 55's reason: a row this widget already
644
+ # sized must not be re-wrapped by the Static underneath it, and a
645
+ # miscalculation should clip visibly rather than reflow invisibly.
646
+ body.no_wrap = True
647
+ body.overflow = "crop"
648
+ self.display = True
649
+ self.update(body)
650
+
462
651
  class ResearchProgress(Static):
463
652
  """Live state of a /research run (ROADMAP_v2 §22).
464
653
 
@@ -488,10 +677,15 @@ class ResearchProgress(Static):
488
677
 
489
678
  # §26. Code stages roughly double the row count, so the §22 window of 8
490
679
  # would push Pass 0 off before the run reached its own claims. Still a
491
- # WINDOW rather than the whole list: #research-progress scrolls, but a
492
- # Static does not scroll itself to the bottom, so an unbounded list
493
- # would leave the newest row out of view -- the opposite of the
494
- # problem being fixed.
680
+ # WINDOW rather than the whole list: a Static does not scroll itself to
681
+ # the bottom, so an unbounded list would leave the newest row out of
682
+ # view -- the opposite of the problem being fixed.
683
+ #
684
+ # This used to say "#research-progress scrolls", and it never did
685
+ # (batch 59). The panel carried `max-height` + `overflow-y: auto`,
686
+ # which on a Static clips rather than scrolls -- EP3's trap, measured
687
+ # here at one lost row. The SIDEBAR scrolls now; this window is what
688
+ # keeps the newest row near the top of what it reveals.
495
689
  ROWS = 16
496
690
 
497
691
  def __init__(self, **kwargs):
@@ -629,6 +823,587 @@ class ResearchProgress(Static):
629
823
  self.update(body)
630
824
 
631
825
 
826
+ class SlashSuggest(Static):
827
+ """The commands you could be typing, above the prompt (batch 55).
828
+
829
+ Twenty-six slash commands were reachable only by remembering that
830
+ `/help` exists -- the mount banner says so once and then scrolls away.
831
+ This lists the ones whose name starts with what has been typed, and
832
+ `tui/commands.py`'s `matching()` is what it lists, so the panel and
833
+ `/help` read one registry and cannot drift.
834
+
835
+ A widget in `#main`, NOT a screen. `#prompt` is `dock: bottom`, so a
836
+ sibling yielded after the transcript lands directly above it -- the
837
+ ThinkingIndicator/TodoPanel shape, hidden until it has something to
838
+ say, `height: auto` so it costs nothing while hidden.
839
+
840
+ Three things here are load-bearing.
841
+
842
+ **It owns the selection, not the prompt.** How many entries fit is a
843
+ function of the RENDERED WIDTH, and only the thing that draws knows
844
+ that. Split the two and the prompt can highlight a sixth entry the
845
+ panel had no room for -- an invisible selection that `enter` would
846
+ then complete. `chosen` and `move()` are the whole interface.
847
+
848
+ **The budget is on ROWS.** At most SUGGEST_MAX_ENTRIES entries and at
849
+ most SUGGEST_MAX_ROWS rows, whichever binds first, stopping at the
850
+ first entry that would overflow rather than skipping it -- a list that
851
+ skipped would no longer be alphabetical and the order would read as
852
+ arbitrary. At 80 columns most entries wrap to two rows, so the row cap
853
+ is usually the one that bites: `/` shows four.
854
+
855
+ **The window SLIDES** (batch 56). `_first` is where it starts and it is
856
+ derived, never stored beside the selection: `move()` picks a command
857
+ out of all the matches and `_budget()` scrolls the window the least
858
+ it can to keep that command on screen. Batch 55 wrapped at the last
859
+ DRAWN entry instead, which left twenty-two of twenty-six commands
860
+ unreachable by keyboard under a panel whose own title said twenty-six.
861
+
862
+ Because entries are one or two rows, a step down drops one entry from
863
+ the top and gains one at the bottom -- or drops one and gains two. That
864
+ is not a rule; it is the row budget refilling, and it is why the window
865
+ changes SIZE as well as contents while it scrolls (measured: four
866
+ entries over seven rows at the top of the list, four over eight one
867
+ step later, five over seven in the middle). Two things follow, and
868
+ neither is optional: `move()` refreshes with `layout=True`, and it is
869
+ reached through app.py rather than called directly -- a panel that
870
+ resizes takes rows from the transcript, and the scroll position that
871
+ has to survive that is only knowable before the relayout.
872
+
873
+ **A Static RE-WRAPS what you already wrapped.** The first draft wrapped
874
+ each entry to `width - 2` and then drew continuation lines under a
875
+ four-space gutter, so a two-line entry rendered as THREE rows, the
876
+ height arithmetic was wrong by one per entry, and the ellipsis ended up
877
+ on a row that had already been dropped. Both gutters have to fit inside
878
+ the wrap width, and the outer Text carries `no_wrap` / `overflow="crop"`
879
+ so that a miscalculation clips where it can be seen instead of
880
+ reflowing where it cannot. The pin is a test that no rendered row is
881
+ wider than the panel.
882
+
883
+ A related trap in the same family: `Text.truncate()` on a WRAPPED line
884
+ does nothing. The overflow is in the lines that were dropped, not in
885
+ the line that was kept, so the line reads as complete when it is not --
886
+ the ellipsis has to be appended deliberately.
887
+
888
+ **The bottom border says which keys this spends** (batch 62). Four
889
+ keys change meaning while the panel is open and none of them was
890
+ written anywhere. Not the TITLE, which the count already holds --
891
+ at 80 columns the label budget is 52 cells, the count is 25 and the
892
+ hint is 42, so they cannot share the row. And not the FOOTER:
893
+ `Screen.active_bindings` drops a binding only on `check_action`
894
+ returning `is False`, and `tab`/`escape` must return `None` here so
895
+ they still reach the focus system with the panel shut -- a shown
896
+ binding would therefore sit in the footer greyed and permanent.
897
+
898
+ The hint shortens by STATE first and by width second, and the state
899
+ half is the title's own rule applied to a control: with one match
900
+ `move()` wraps to the command it is already on, so `↑↓ move` would
901
+ advertise a key that does nothing. Parts then drop from the LEFT
902
+ while the rest overflows, rather than being truncated -- an
903
+ ellipsised `esc dism…` is furniture, not help. What survives the
904
+ narrowest terminal is therefore how to get rid of the panel, which
905
+ is the useful key at a width where the entries are unreadable.
906
+
907
+ The highlight is `reverse` rather than a palette role. TodoPanel's
908
+ caution applies (only the theme-invariant roles are safe across all
909
+ fourteen themes) and reverse is invariant by construction: it swaps
910
+ whatever the theme already chose, so it adds no colour for
911
+ tests/test_themes.py's contrast floors to fail to measure.
912
+ """
913
+
914
+ def __init__(self, **kwargs):
915
+ super().__init__(**kwargs)
916
+ # EXPLICIT, TodoPanel's reason: nothing sets a list until the user
917
+ # types a slash, which on many sessions is never, and a visible
918
+ # empty box is worse than the thing it advertises.
919
+ self.display = False
920
+ self._matches: list = []
921
+ # An index into _matches, NOT into the window: the window slides to
922
+ # follow it (batch 56), and _first is where the window starts.
923
+ self._selected = 0
924
+ self._first = 0
925
+ self._width = 0
926
+ # Per entry, the rendered lines. Computed in get_content_height,
927
+ # where the width arrives before the first paint.
928
+ self._groups: list = []
929
+
930
+ # -- what the prompt drives ---------------------------------------------
931
+
932
+ def offer(self, matches: list) -> None:
933
+ """Replace the list, hiding the panel when it is empty.
934
+
935
+ `refresh(layout=True)`, not `update()`: the render is a function of
936
+ the width, so the panel has to be re-MEASURED, not just repainted.
937
+ """
938
+ self._matches = list(matches)
939
+ self._selected = 0
940
+ self._first = 0
941
+ self._groups = []
942
+ self.display = bool(self._matches)
943
+ self.refresh(layout=True)
944
+
945
+ def move(self, delta: int) -> None:
946
+ """Move the highlight over ALL the matches, wrapping at the ends.
947
+
948
+ Over the matches, not over what is on screen (batch 56). Wrapping
949
+ at the last DRAWN entry left twenty-two of twenty-six commands
950
+ unreachable by keyboard under a bare slash, on a panel whose own
951
+ title said there were twenty-six.
952
+
953
+ This sets the selection and nothing else. Where the window has to
954
+ move so the selection is visible is `_budget`'s answer, because it
955
+ is a function of the WIDTH -- which is the same split the class
956
+ docstring already turns on.
957
+
958
+ `layout=True` is load-bearing rather than tidy. A sliding window
959
+ changes SIZE as well as contents (measured: four entries over seven
960
+ rows at the top of the list, four over eight one step later, five
961
+ over seven in the middle), and a plain `refresh()` leaves the
962
+ widget measured at its old height with the extra row silently
963
+ clipped.
964
+ """
965
+ self._ensure()
966
+ if not self._matches:
967
+ return
968
+ self._selected = (self._selected + delta) % len(self._matches)
969
+ self._groups = []
970
+ self.refresh(layout=True)
971
+
972
+ @property
973
+ def chosen(self):
974
+ """The highlighted command, or None when nothing is offered."""
975
+ self._ensure()
976
+ if not self.display or not self._matches:
977
+ return None
978
+ return self._matches[min(self._selected, len(self._matches) - 1)]
979
+
980
+ @property
981
+ def visible(self) -> list:
982
+ """The commands actually on screen, in order.
983
+
984
+ The honest accessor, and it exists because the obvious spelling --
985
+ `_matches[:shown]` -- quietly assumes a window that starts at zero,
986
+ which stopped being true the moment the list could scroll.
987
+ """
988
+ self._ensure()
989
+ return self._matches[self._first:self._first + len(self._groups)]
990
+
991
+ @property
992
+ def shown(self) -> int:
993
+ """How many entries the last measurement had room for."""
994
+ self._ensure()
995
+ return len(self._groups)
996
+
997
+ def _ensure(self) -> None:
998
+ """Measure now if a layout pass has not happened yet.
999
+
1000
+ `offer()` and `move()` clear the groups and the next layout
1001
+ recomputes them, but a key pressed in between -- or a test that
1002
+ offers and asks in one breath -- would otherwise see an empty list
1003
+ and no selection.
1004
+ """
1005
+ if not self._groups and self._matches and self._width:
1006
+ self._budget(self._width)
1007
+
1008
+ # -- measuring -----------------------------------------------------------
1009
+
1010
+ def _entry(self, command, inner: int) -> list:
1011
+ """One command's rendered lines, at most SUGGEST_MAX_LINES of them.
1012
+
1013
+ `/name SEP summary usage`, in that order: the reverse order pushes
1014
+ the DESCRIPTION off the entry for the two commands whose flags are
1015
+ long, and the description is the half this panel exists for. The
1016
+ flags are what truncates.
1017
+ """
1018
+ body = "/" + command.name + SUGGEST_SEP + command.summary
1019
+ if command.usage:
1020
+ body += " " + command.usage
1021
+ lines = list(Text(body).wrap(Console(width=inner), inner, no_wrap=False))
1022
+ if len(lines) > SUGGEST_MAX_LINES:
1023
+ lines = lines[:SUGGEST_MAX_LINES]
1024
+ # crop THEN append: truncate(overflow="ellipsis") is a no-op
1025
+ # here, because this line is not the one that overflowed.
1026
+ lines[-1].truncate(max(0, inner - 1), overflow="crop")
1027
+ lines[-1].append(SUGGEST_ELLIPSIS)
1028
+ return lines
1029
+
1030
+ def _fill(self, first: int, inner: int) -> list:
1031
+ """The entries that fit starting at `first`, under both caps."""
1032
+ groups, used = [], 0
1033
+ for command in self._matches[first:first + SUGGEST_MAX_ENTRIES]:
1034
+ lines = self._entry(command, inner)
1035
+ if used + len(lines) > SUGGEST_MAX_ROWS:
1036
+ break
1037
+ groups.append(lines)
1038
+ used += len(lines)
1039
+ return groups
1040
+
1041
+ def _budget(self, width: int) -> None:
1042
+ """Where the window sits, what fits in it, and the title.
1043
+
1044
+ The window is DERIVED from the selection rather than stored beside
1045
+ it, so the two cannot disagree: `move()` says which command is
1046
+ chosen and this says which commands can be seen.
1047
+
1048
+ Scrolling is minimal in both directions -- the window advances only
1049
+ far enough to keep the selection visible, and jumps straight to it
1050
+ going the other way. Because the entries are one or two rows, that
1051
+ is what makes a step down drop one entry and gain one, or drop one
1052
+ and gain TWO: it is the row budget refilling, not a rule of its own.
1053
+
1054
+ The loop terminates because `first` only rises and a single entry
1055
+ is at most SUGGEST_MAX_LINES rows, so `first == self._selected`
1056
+ always yields a window containing the selection. The empty guard is
1057
+ what keeps that true -- with no matches `_fill` returns nothing and
1058
+ the condition could never be met.
1059
+
1060
+ No minimum width: a terminal too narrow to read is still bounded
1061
+ here, because the two-line cap holds whatever the wrap does, so the
1062
+ panel degrades to something short rather than to something
1063
+ unbounded. MIN_WRAP_WIDTH's posture, one line up the same street.
1064
+ """
1065
+ self._width = width
1066
+ if not self._matches:
1067
+ self._groups = []
1068
+ self._first = 0
1069
+ return
1070
+ inner = max(1, width - len(SUGGEST_CONT))
1071
+ if self._selected >= len(self._matches):
1072
+ self._selected = 0
1073
+ first = min(self._first, self._selected)
1074
+ while True:
1075
+ groups = self._fill(first, inner)
1076
+ if self._selected < first + len(groups):
1077
+ break
1078
+ first += 1
1079
+ self._first = first
1080
+ self._groups = groups
1081
+ # #30/M14: a capped list that does not say it is capped reads as
1082
+ # "this is everything". Shown-of-MATCHED rather than shown-of-all,
1083
+ # because "4 of 26" under a typed `/c` would claim twenty-two
1084
+ # candidates that do not exist. Both numbers are counted, never
1085
+ # written down -- register a twenty-seventh command and the bare
1086
+ # `/` title says 27 with no edit here.
1087
+ #
1088
+ # The RANGE appears only once the list can scroll (batch 56). On a
1089
+ # list that fits entirely there is nowhere to be, so "1-1 of 1"
1090
+ # would be noise where "1 of 1" is a fact.
1091
+ if len(groups) == len(self._matches):
1092
+ span = str(len(groups))
1093
+ else:
1094
+ span = f"{first + 1}-{first + len(groups)}"
1095
+ title = f"{span} of {len(self._matches)} · /help for all"
1096
+ if self.border_title != title:
1097
+ self.border_title = title
1098
+ # Batch 62. The same honesty rule one row down, applied to a
1099
+ # control instead of to a count: `↑↓ move` is a claim about a
1100
+ # key, and with one match that key does nothing.
1101
+ #
1102
+ # `width - 2` is the border label's budget, MEASURED rather than
1103
+ # reasoned: textual truncates a label at the outer width minus
1104
+ # six, and `border: solid` plus `padding: 0 1` makes the outer
1105
+ # width four more than the one handed here. Change either in
1106
+ # app.tcss and this constant is wrong -- which is why the pilot
1107
+ # test asserts the drawn row carries no ellipsis.
1108
+ #
1109
+ # cell_len, not len: the arrows are East-Asian AMBIGUOUS width,
1110
+ # exactly like the SUGGEST_SEP this panel already ships.
1111
+ parts = list(SUGGEST_HINT_REST)
1112
+ if len(self._matches) > 1:
1113
+ parts.insert(0, SUGGEST_HINT_MOVE)
1114
+ while parts and Text(
1115
+ SUGGEST_HINT_SEP.join(parts)).cell_len > width - 2:
1116
+ parts.pop(0)
1117
+ hint = SUGGEST_HINT_SEP.join(parts) or None
1118
+ # Guarded for the title's reason, and it is not tidiness:
1119
+ # `_BorderTitle.__set__` calls `refresh()` and this runs from
1120
+ # `render()`, so an unguarded assignment schedules a paint from
1121
+ # inside a paint. It converges because the second pass compares
1122
+ # equal -- `border_subtitle` hands back markup, and neither
1123
+ # string carries any.
1124
+ if self.border_subtitle != hint:
1125
+ self.border_subtitle = hint
1126
+
1127
+ def get_content_height(self, container, viewport, width: int) -> int:
1128
+ # Textual hands the width here BEFORE the first paint, which is the
1129
+ # only place it is knowable while the panel is still hidden.
1130
+ self._budget(width)
1131
+ return sum(len(group) for group in self._groups)
1132
+
1133
+ # -- drawing -------------------------------------------------------------
1134
+
1135
+ def render(self):
1136
+ width = self.size.width or self._width
1137
+ if width and (width != self._width or not self._groups):
1138
+ self._budget(width)
1139
+ rows = []
1140
+ for index, group in enumerate(self._groups):
1141
+ for offset, line in enumerate(group):
1142
+ gutter = SUGGEST_LEAD if offset == 0 else SUGGEST_CONT
1143
+ row = Text(gutter, no_wrap=True, overflow="crop")
1144
+ row.append_text(line)
1145
+ # Padded to the full width so the highlight is a BAR rather
1146
+ # than a stripe the length of the text.
1147
+ row.pad_right(max(0, width - row.cell_len))
1148
+ if index == self._selected - self._first:
1149
+ row.stylize(SUGGEST_HIGHLIGHT)
1150
+ rows.append(row)
1151
+ body = Text(no_wrap=True, overflow="crop")
1152
+ for position, row in enumerate(rows):
1153
+ if position:
1154
+ body.append("\n")
1155
+ body.append_text(row)
1156
+ return body
1157
+
1158
+
1159
+ class PromptInput(TextArea):
1160
+ """The box the user types into. Wraps, grows to four rows, and since
1161
+ batch 55 offers the slash commands while one is being typed.
1162
+
1163
+ It was a plain `Input` until batch 54, and an `Input` is single-line by
1164
+ construction -- `height: 3` in its own DEFAULT_CSS, one text row, no
1165
+ wrap, horizontal scroll. A prompt longer than the box showed its last
1166
+ ~70 columns and nothing before them, so a paragraph could not be read
1167
+ back before it was sent. `TextArea` is the only multi-line widget in
1168
+ the pinned textual, so this is a swap rather than a setting.
1169
+
1170
+ The GROWING is `soft_wrap` plus `height: auto` in app.tcss, and those
1171
+ two are the feature: a long line wraps and the box gets taller on its
1172
+ own, with no key pressed. `ctrl+j` is for a break the user WANTS.
1173
+
1174
+ Four things here are load-bearing.
1175
+
1176
+ `value`. `TextArea` calls it `text`, and roughly sixty test sites plus
1177
+ the app's own submit handler say `.value`. An alias is a one-line
1178
+ adapter; renaming them would have been sixty edits across five files
1179
+ to make a rendering change, and every one of those files is about
1180
+ something else. It is a property over `text`, not a second store --
1181
+ two writers of one string is the shape §22 spent a section removing.
1182
+
1183
+ `priority=True` on enter. `TextArea._on_key` maps enter to a newline
1184
+ insert and calls `event.stop()` / `event.prevent_default()`, which
1185
+ beats an ordinary binding: measured on the pinned textual 1.0.0 (D22,
1186
+ both ways -- without the flag enter inserts and never submits). It
1187
+ reads like caution and is the opposite.
1188
+
1189
+ `ctrl+j` is what carries the newline; `shift+enter` is a courtesy.
1190
+ Textual turns the kitty keyboard protocol on in its LINUX drivers
1191
+ alone (`drivers/linux_driver.py`, `linux_inline_driver.py`), and
1192
+ without it a terminal sends a bare CR for shift+enter and the parser
1193
+ yields plain `enter` -- so on Windows that binding is unreachable and
1194
+ the box would submit instead. `ctrl+j` is byte 0x0a, parses to its own
1195
+ key, is bound by neither Input, TextArea, App nor Footer, and is
1196
+ exactly what iTerm2 / VS Code / Windows Terminal emit once configured
1197
+ to send a newline on shift+enter. `alt+enter` is the obvious third
1198
+ guess and is a dead end: fed `ESC CR` the parser yields no key at all,
1199
+ and a second one behind it degrades to `escape`, `enter`.
1200
+
1201
+ **`load_text` is where typing is told apart from assignment** (batch
1202
+ 55), and it is the seam the whole suggestion panel hangs off. Setting
1203
+ `.value` posts `TextArea.Changed` exactly as a keystroke does --
1204
+ measured -- so a panel driven straight off that message would open in
1205
+ the ~73 `query_one("#prompt").value = "/..."` sites across four test
1206
+ files and turn each one's single `press("enter")` into a COMPLETION
1207
+ instead of a dispatch. The line to draw is not a test accommodation:
1208
+ assignment is the API, typing is the user, and textual draws the same
1209
+ line itself -- `_replace_via_keyboard`'s docstring says "as opposed to
1210
+ the API". That method covers inserts only (backspace does not go
1211
+ through it, measured), and this panel must react to deletions, so the
1212
+ seam is `load_text` instead: the single public funnel behind both
1213
+ `.text =` and `.value =`.
1214
+
1215
+ `tab_behavior` stays at its "focus" default, deliberately. Under
1216
+ "indent" `TextArea._on_key` also swallows `escape` (it focuses the
1217
+ next widget), and tab/escape behaving as they did under `Input` is
1218
+ worth more here than tab-indenting a chat message. Batch 55 spends
1219
+ both keys, but only while the panel is open: `check_action` hands them
1220
+ back to the focus system and to nobody the rest of the time.
1221
+
1222
+ The placeholder is the border TITLE because `TextArea` has no
1223
+ placeholder at all -- no parameter, no attribute. Taking it as a
1224
+ `placeholder=` keyword anyway keeps the call site in app.py reading
1225
+ as it always did.
1226
+ """
1227
+
1228
+ BINDINGS = [
1229
+ Binding("enter", "submit", "Submit", show=False, priority=True),
1230
+ Binding("ctrl+j", "newline", "Newline", show=False),
1231
+ Binding("shift+enter", "newline", "Newline", show=False),
1232
+ # Both gated by check_action, so with no panel open they are the
1233
+ # keys they have always been: tab moves focus, escape reaches
1234
+ # whoever wants it.
1235
+ Binding("tab", "complete", "Complete", show=False),
1236
+ Binding("escape", "dismiss_suggestions", "Dismiss", show=False),
1237
+ ]
1238
+
1239
+ # CLASS attributes, not set in __init__: `load_text` runs during
1240
+ # TextArea.__init__, before any assignment of ours could have happened.
1241
+ suggest = None # the SlashSuggest panel; app.py hands it over
1242
+ _api_edit = False # the next Changed came from .value, not a key
1243
+ _dismissed = False # escape latched the panel shut
1244
+
1245
+ class Submitted(Message):
1246
+ """Posted when enter is pressed. `Input.Submitted`'s shape.
1247
+
1248
+ A distinct message type rather than reusing `Input.Submitted`, and
1249
+ that is a fix as much as a necessity: `Input.Submitted` BUBBLES
1250
+ past a modal's own handler to the app's (measured -- the screen
1251
+ handler runs and then the app's), so enter in ReviewScreen's note
1252
+ box reached the prompt's submit handler, which cleared the note
1253
+ and dispatched it as a slash command if it began with one.
1254
+ """
1255
+
1256
+ def __init__(self, prompt: "PromptInput", value: str) -> None:
1257
+ self.prompt = prompt
1258
+ self.value = value
1259
+ super().__init__()
1260
+
1261
+ @property
1262
+ def control(self) -> "PromptInput":
1263
+ return self.prompt
1264
+
1265
+ class SuggestionsChanged(Message):
1266
+ """The command list to offer, after a keystroke (batch 55).
1267
+
1268
+ A message rather than the prompt writing to the panel directly, so
1269
+ app.py stays the one place that touches both this and the
1270
+ transcript -- which it has to, because a panel opening SHRINKS the
1271
+ transcript and textual does not re-pin a scroll on shrink.
1272
+ """
1273
+
1274
+ def __init__(self, prompt: "PromptInput", matches: list) -> None:
1275
+ self.prompt = prompt
1276
+ self.matches = matches
1277
+ super().__init__()
1278
+
1279
+ @property
1280
+ def control(self) -> "PromptInput":
1281
+ return self.prompt
1282
+
1283
+ class SuggestionsMoved(Message):
1284
+ """The arrow keys, asking the panel to move its highlight.
1285
+
1286
+ A message rather than a direct `suggest.move()` call, and batch 56
1287
+ is what made that necessary: the window SLIDES now, so a move can
1288
+ change the panel's HEIGHT, and a panel that changes height takes
1289
+ rows from the transcript. Whether the reader was at the bottom is
1290
+ knowable only before that relayout, so the move has to happen
1291
+ inside app.py's pin -- the same one `SuggestionsChanged` uses.
1292
+ """
1293
+
1294
+ def __init__(self, prompt: "PromptInput", delta: int) -> None:
1295
+ self.prompt = prompt
1296
+ self.delta = delta
1297
+ super().__init__()
1298
+
1299
+ @property
1300
+ def control(self) -> "PromptInput":
1301
+ return self.prompt
1302
+
1303
+ def __init__(self, placeholder: str = "", **kwargs) -> None:
1304
+ super().__init__(soft_wrap=True, show_line_numbers=False, **kwargs)
1305
+ self.placeholder = placeholder
1306
+ self.border_title = placeholder
1307
+
1308
+ @property
1309
+ def value(self) -> str:
1310
+ return self.text
1311
+
1312
+ @value.setter
1313
+ def value(self, new_value: str) -> None:
1314
+ self.text = new_value
1315
+
1316
+ # -- the suggestion panel -----------------------------------------------
1317
+
1318
+ def load_text(self, text: str) -> None:
1319
+ # See the docstring: this is the API half of the API/keyboard
1320
+ # split, and `.value =` reaches it through `.text =`.
1321
+ self._api_edit = True
1322
+ super().load_text(text)
1323
+
1324
+ def on_text_area_changed(self, event: TextArea.Changed) -> None:
1325
+ if self._api_edit:
1326
+ # Assignment is not typing. It also CLOSES the panel, which is
1327
+ # what makes `event.prompt.value = ""` on submit tidy up.
1328
+ self._api_edit = False
1329
+ self._dismissed = False
1330
+ self.post_message(self.SuggestionsChanged(self, []))
1331
+ return
1332
+ matches = commands.matching(self.text)
1333
+ if not matches:
1334
+ # Nothing to dismiss any more, so the latch is spent. This is
1335
+ # what lets a dismissed panel come back: type a space (or clear
1336
+ # the line) and the next bare slash token offers again.
1337
+ self._dismissed = False
1338
+ self.post_message(
1339
+ self.SuggestionsChanged(self, [] if self._dismissed else matches))
1340
+
1341
+ def _panel_open(self) -> bool:
1342
+ return self.suggest is not None and self.suggest.display
1343
+
1344
+ def _complete(self) -> bool:
1345
+ """Put the highlighted command in the box. True if one was taken."""
1346
+ if not self._panel_open():
1347
+ return False
1348
+ command = self.suggest.chosen
1349
+ if command is None:
1350
+ return False
1351
+ # The TRAILING SPACE is doing two jobs: `matching()` is empty once
1352
+ # the line has whitespace in it, so the panel closes on its own,
1353
+ # and deleting that one character is what brings it back.
1354
+ self.value = "/" + command.name + " "
1355
+ # load_text leaves the cursor at the START of the document, which
1356
+ # would have the next typed argument land in front of the command.
1357
+ self.move_cursor(self.document.end)
1358
+ return True
1359
+
1360
+ def check_action(self, action: str, parameters) -> bool | None:
1361
+ # None, not False: False would DISABLE the key, where None declines
1362
+ # it and lets the press carry on to the focus system (tab) or to
1363
+ # nobody (escape) -- which is what both did before batch 55.
1364
+ if action in ("complete", "dismiss_suggestions"):
1365
+ return True if self._panel_open() else None
1366
+ return True
1367
+
1368
+ # -- actions -------------------------------------------------------------
1369
+
1370
+ def action_submit(self) -> None:
1371
+ # Enter ALWAYS completes while the panel is open, so a fully typed
1372
+ # /help takes two presses. The alternative -- submit when the typed
1373
+ # token already equals the highlighted name -- is a coin flip from
1374
+ # the user's side and stops being well defined the day two commands
1375
+ # share a prefix.
1376
+ if self._complete():
1377
+ return
1378
+ self.post_message(self.Submitted(self, self.text))
1379
+
1380
+ def action_newline(self) -> None:
1381
+ self.insert("\n")
1382
+
1383
+ def action_complete(self) -> None:
1384
+ self._complete()
1385
+
1386
+ def action_dismiss_suggestions(self) -> None:
1387
+ self._dismissed = True
1388
+ self.post_message(self.SuggestionsChanged(self, []))
1389
+
1390
+ def action_cursor_up(self, select: bool = False) -> None:
1391
+ # `select` is shift+up, which is a text selection and stays one.
1392
+ # Everything else: batch 54 made this box multi-line, so the arrow
1393
+ # keys have to go back to moving the CURSOR the moment the panel
1394
+ # is closed.
1395
+ if not select and self._panel_open():
1396
+ self.post_message(self.SuggestionsMoved(self, -1))
1397
+ return
1398
+ super().action_cursor_up(select)
1399
+
1400
+ def action_cursor_down(self, select: bool = False) -> None:
1401
+ if not select and self._panel_open():
1402
+ self.post_message(self.SuggestionsMoved(self, 1))
1403
+ return
1404
+ super().action_cursor_down(select)
1405
+
1406
+
632
1407
  class Transcript(RichLog):
633
1408
  """The conversation. Code fences render highlighted via Rich's Syntax.
634
1409
 
@@ -691,18 +1466,26 @@ class Transcript(RichLog):
691
1466
 
692
1467
  §43 moves that label. It belongs to the TURN, not to an answer span:
693
1468
  one "venastine ›" above the model's first output of the turn,
694
- whether that output is reasoning or text, retired by the next
695
- "you ›". See _open_label for why, and note the property that makes
696
- it safe -- placement is a pure function of the role sequence in
697
- `_entries`, so rerender() reproduces it rather than approximating
698
- it. A re-render that moves a label is the same defect as one that
699
- reflows a paragraph.
1469
+ whether that output is reasoning, text or a tool call, retired by
1470
+ the next "you ›". See _open_label for why, and note the property
1471
+ that makes it safe -- placement is a pure function of the role
1472
+ sequence in `_entries`, so rerender() reproduces it rather than
1473
+ approximating it. A re-render that moves a label is the same defect
1474
+ as one that reflows a paragraph.
700
1475
  """
701
1476
 
702
1477
  def __init__(self, **kwargs):
703
1478
  super().__init__(wrap=True, markup=False, **kwargs)
704
1479
  self._pending = ""
705
1480
  self._entries: list[tuple[str, str]] = []
1481
+ # Batch 65. Click TARGETS for entry N, when the drawn line is
1482
+ # too short to be one -- see `markdown.link_spans`. A side
1483
+ # table rather than a third element in the tuple above, because
1484
+ # `_entries` is read by /copy, by last_answer() and by the
1485
+ # replay contract, and a link is a rendering fact about a line
1486
+ # rather than part of what was said. Keyed by INDEX, which
1487
+ # rerender() already walks.
1488
+ self._links: dict[int, tuple] = {}
706
1489
  # §38. An assistant span with rows already on screen: its label is
707
1490
  # drawn and its single entry is open at _entries[-1].
708
1491
  self._stream_open = False
@@ -748,13 +1531,22 @@ class Transcript(RichLog):
748
1531
 
749
1532
  # -- writing -----------------------------------------------------------
750
1533
 
751
- def _emit(self, role: str, text: str, record: bool = True) -> None:
752
- """Render one entry and remember it. THE single write path."""
1534
+ def _emit(self, role: str, text: str, record: bool = True,
1535
+ links=()) -> None:
1536
+ """Render one entry and remember it. THE single write path.
1537
+
1538
+ `links` are batch 65's click targets, remembered beside the
1539
+ entry so a `/theme` rerender arms what the live draw armed. An
1540
+ entry with none -- every role outside LINKED_ROLES, and most
1541
+ tool lines -- stores nothing.
1542
+ """
753
1543
  if record:
754
1544
  self._entries.append((role, text))
755
- self._render_entry(role, text)
1545
+ if links:
1546
+ self._links[len(self._entries) - 1] = tuple(links)
1547
+ self._render_entry(role, text, links)
756
1548
 
757
- def _render_entry(self, role: str, text: str) -> None:
1549
+ def _render_entry(self, role: str, text: str, links=()) -> None:
758
1550
  if role == "user":
759
1551
  # §43 (RM1). The turn's label is retired HERE and nowhere
760
1552
  # else, so where the labels land is a pure function of the
@@ -777,6 +1569,23 @@ class Transcript(RichLog):
777
1569
  self._render_blocks(text[:-1] if text.endswith("\n") else text)
778
1570
  elif role == "diff":
779
1571
  self._render_diff(text)
1572
+ elif role == "tool":
1573
+ # §43 RM1, as amended: a tool call is model output too, and on
1574
+ # a turn that OPENS with one -- the normal MCP shape, a call
1575
+ # made before any prose -- it is the turn's first output.
1576
+ # Without this the call rendered under `you ›` and the label
1577
+ # opened below it, above the prose that eventually followed.
1578
+ # The guard inside _open_label keeps the other half of the
1579
+ # §43 sentence true: a tool line INSIDE the turn, after
1580
+ # reasoning or text has already opened the label, is a no-op.
1581
+ self._open_label()
1582
+ self.write(self._linked_line(text, "tool", links))
1583
+ elif role == "pipeline_tool":
1584
+ # The research pipeline's tool lines. Same kind of line and
1585
+ # the same style, deliberately NOT an opener: the run's label
1586
+ # belongs to the report, and a pipeline call is the harness
1587
+ # working, not the model answering (§43 RM1, owner decision).
1588
+ self.write(self._linked_line(text, "tool", links))
780
1589
  elif role == "thinking":
781
1590
  # §38. The furniture is OWNED by the renderer, not stored in
782
1591
  # the entry: `_entries` keeps the model's raw reasoning, so
@@ -787,9 +1596,28 @@ class Transcript(RichLog):
787
1596
  self._write_thinking_open()
788
1597
  self._write_thinking_lines(text)
789
1598
  self._write_thinking_close()
1599
+ elif role in LINKED_ROLES:
1600
+ # `tool_error` arrives here, and needs no `links`: its text
1601
+ # is redact_secrets(str(error)) with no truncation, so the
1602
+ # URL it carries is whole and the span resolves to itself.
1603
+ self.write(self._linked_line(text, role, links))
790
1604
  else:
791
1605
  self.write(Text(f" {text}", self._style(role)))
792
1606
 
1607
+ def _linked_line(self, text: str, role: str, targets=()) -> Text:
1608
+ """One harness-drawn line, with its URLs armed (batch 65).
1609
+
1610
+ The five-space indent every one of these lines carries is inside
1611
+ the scanned text rather than prepended after, so a span's
1612
+ columns are the columns Textual dispatches a click on -- the
1613
+ offsets have to be the drawn ones or the arming lands beside the
1614
+ URL instead of on it.
1615
+ """
1616
+ out = Text(style=self._style(role))
1617
+ self._append_spans(out, f" {text}", self._styles(),
1618
+ block=False, links_only=True, targets=targets)
1619
+ return out
1620
+
793
1621
  def _open_label(self) -> None:
794
1622
  """Draw this turn's `venastine ›`, once (§43, RM1).
795
1623
 
@@ -800,14 +1628,24 @@ class Transcript(RichLog):
800
1628
  so the transcript read as if the user had done the thinking and
801
1629
  the model had answered without any.
802
1630
 
803
- It is now the TURN's, opened by whichever of reasoning or text
804
- comes first and retired only by the next `you ›`. A tool line, a
805
- diff or a system notice inside the turn does NOT re-open one:
806
- they are part of the turn the label already announced. The cost,
807
- accepted rather than fixed: an answer resuming after a tool line
808
- starts directly under it, where the suppressed label used to
809
- supply a blank row. A separator drawn instead would be a second
810
- thing the live path and rerender() must agree about.
1631
+ It is now the TURN's, opened by whichever of reasoning, text or a
1632
+ tool call comes first and retired only by the next `you ›`. A
1633
+ tool line, a diff or a system notice INSIDE the turn does not
1634
+ re-open one -- they are part of the turn the label already
1635
+ announced, and the guard below is what keeps that sentence true
1636
+ now that a tool line can open the label too. It has to be able
1637
+ to: a call made before any prose (the normal MCP shape) is the
1638
+ turn's first output, and §43's original wording left such a turn
1639
+ unlabelled until the prose followed, so the call read as if the
1640
+ user had made it. `tool_error` stays exempt on purpose -- a
1641
+ failure line is the tool's outcome rather than the model
1642
+ speaking, and the call line above it already carries the label.
1643
+ The research pipeline's tool lines never open one (they are
1644
+ `pipeline_tool`; the run's label belongs to the report). The
1645
+ cost, accepted rather than fixed: an answer resuming after a
1646
+ tool line starts directly under it, where the suppressed label
1647
+ used to supply a blank row. A separator drawn instead would be a
1648
+ second thing the live path and rerender() must agree about.
811
1649
  """
812
1650
  if self._label_in_force:
813
1651
  return
@@ -861,11 +1699,20 @@ class Transcript(RichLog):
861
1699
  return
862
1700
  self.write(Text(text.ljust(total), style), width=total)
863
1701
 
864
- def _render_blocks(self, text: str) -> None:
1702
+ def _render_blocks(self, text: str, *, line_start: bool = True) -> None:
865
1703
  """The assistant body: fenced code highlighted, everything else
866
1704
  plain. Shared by a replayed entry and a committed stream chunk, so
867
1705
  the two cannot render the same text differently.
868
1706
 
1707
+ `line_start=False` says this chunk begins in the MIDDLE of a line,
1708
+ so nothing that depends on where a line starts may fire on its
1709
+ first line. Two callers want it and both were bugs without it: a
1710
+ streamed fragment whose wrap boundary fell just before a `# `
1711
+ token rendered as a heading and swallowed the hash, which a
1712
+ `/theme` replay then put back; and a chunk the cap released
1713
+ because HOLD_LIMIT expired, which is a line the cap gave up on
1714
+ rather than a construct.
1715
+
869
1716
  The newline trimming around a fence is what makes that sharing
870
1717
  exact rather than approximate. A `Syntax` renderable occupies its own
871
1718
  rows, so the newline that ends the ``` line is structural, not a
@@ -876,15 +1723,22 @@ class Transcript(RichLog):
876
1723
  answer grew a blank row per code block, and a /theme mid-session
877
1724
  reflowed a transcript it was only meant to recolour.
878
1725
  """
879
- blocks = _split_fences(text)
1726
+ blocks = markdown.split_blocks(text)
880
1727
  for index, block in enumerate(blocks):
881
- if isinstance(block, tuple):
882
- language, code = block
883
- self.write(Syntax(code, language or "text",
1728
+ # Batch 53. `isinstance(block, tuple)` still asks exactly the
1729
+ # question §26 asked -- "does this block occupy its own rows"
1730
+ # -- because both block kinds are tuple subclasses. That is
1731
+ # what keeps the trimming below ONE rule for the two of them
1732
+ # rather than a second branch to be kept in step.
1733
+ if isinstance(block, markdown.CodeBlock):
1734
+ self.write(Syntax(block.code, block.language or "text",
884
1735
  theme=self._syntax_theme(),
885
1736
  word_wrap=True,
886
1737
  indent_guides=False))
887
1738
  continue
1739
+ if isinstance(block, markdown.TableBlock):
1740
+ self._render_table(block)
1741
+ continue
888
1742
  body = block
889
1743
  if index and isinstance(blocks[index - 1], tuple) \
890
1744
  and body.startswith("\n"):
@@ -892,7 +1746,207 @@ class Transcript(RichLog):
892
1746
  if index + 1 < len(blocks) and isinstance(blocks[index + 1], tuple) \
893
1747
  and body.endswith("\n"):
894
1748
  body = body[:-1]
895
- self.write(Text(body, self._style("assistant")))
1749
+ # Only the FIRST block can begin mid-line; everything after a
1750
+ # renderable block starts where that block ended.
1751
+ self.write(self._inline_text(
1752
+ body, line_start=line_start and index == 0))
1753
+
1754
+ def _inline_text(self, body: str, *, line_start: bool = True) -> Text:
1755
+ """A plain stretch of an answer, with its inline marks painted.
1756
+
1757
+ The marks are the RENDERER's, exactly as the thinking bar and the
1758
+ diff's gutter are: `_entries` keeps the markdown the model wrote,
1759
+ so `/copy` hands back `**bold**`, `- ` and the brackets of a link,
1760
+ and a replay under a new theme re-derives the weight rather than
1761
+ replaying something decorated once.
1762
+
1763
+ Line by line, because a heading, a list item and the indent rule
1764
+ are all properties of a LINE and `tui/markdown.py` is where that
1765
+ is decided. The newlines are put back here so the block still
1766
+ reaches Rich as one `Text` and wraps as one flow -- which is what
1767
+ `markdown.width_split` is measuring against.
1768
+
1769
+ A LIST ITEM is the one line this widget wraps itself (batch 58).
1770
+ Rich has no hanging indent -- `Text` has none and `Padding`
1771
+ indents the first row too -- so the item's body is pre-wrapped
1772
+ through `markdown.wrap_display` at the width left after its
1773
+ marker, and every row after the first is padded to the column the
1774
+ marker's own text starts at. It is the same reason `_render_diff`
1775
+ and the thinking bar pre-wrap, and it is why the cap holds an item
1776
+ until its newline: a fragment committed without its marker could
1777
+ never be indented afterwards.
1778
+
1779
+ With no measurable width -- unmounted, or built bare in the suite
1780
+ -- nothing is pre-wrapped and the item draws flat, which is
1781
+ `_write_padded`'s guard rule applied to the same geometry.
1782
+ """
1783
+ styles = self._styles()
1784
+ base = styles.get("assistant", "")
1785
+ out = Text(style=base)
1786
+ width = self._wrap_width()
1787
+ for index, line in enumerate(body.split("\n")):
1788
+ if index:
1789
+ out.append("\n")
1790
+ block = line_start or index > 0
1791
+ item = markdown.list_item(line) if block else None
1792
+ if item is None:
1793
+ self._append_spans(out, line, styles, block=block)
1794
+ continue
1795
+ prefix, content, indent = item
1796
+ out.append(prefix, styles.get(markdown.BULLET) or None)
1797
+ rows = markdown.wrap_display(content, width - indent) \
1798
+ if width > indent else [content]
1799
+ for row_index, row in enumerate(rows):
1800
+ if row_index:
1801
+ out.append("\n" + " " * indent)
1802
+ self._append_spans(out, row, styles, block=False)
1803
+ return out
1804
+
1805
+ def _append_spans(self, out: Text, line: str, styles: dict, *,
1806
+ block: bool, links_only: bool = False,
1807
+ targets=()) -> None:
1808
+ """One line's spans, appended to `out` in their palette roles.
1809
+
1810
+ A LINK span is the one that carries more than a style. Its text is
1811
+ the URL -- the grammar guarantees that, which is the whole security
1812
+ rule: there is no label to hide a target behind, so the only thing
1813
+ a click can open is the thing the reader is looking at. The URL
1814
+ rides along as style METADATA, which `on_click` reads back.
1815
+
1816
+ Metadata rather than textual's `@click` action string, and the
1817
+ difference is not stylistic: an action string is PARSED, so
1818
+ building one out of model output would be an injection grammar fed
1819
+ by the model. A plain key is data all the way through.
1820
+
1821
+ `links_only` picks the other scanner (batch 65): a harness-drawn
1822
+ line gets URLs and no other mark, because it is a digest rather
1823
+ than prose. Both scanners are normalised to `(text, role,
1824
+ target)` here so that the metadata attach below stays a SINGLE
1825
+ line -- it is the security-critical one, and two copies of it
1826
+ drifting apart is the shape this project keeps recording.
1827
+
1828
+ For prose the target IS the span, which is batch 58 unchanged.
1829
+ `targets` is how a TRUNCATED tool line resolves to the URL it
1830
+ was cut from, under the rules `markdown.link_spans` states.
1831
+ """
1832
+ spans = markdown.link_spans(line, targets=targets) if links_only \
1833
+ else ((text, role, text)
1834
+ for text, role in markdown.inline_spans(line, block=block))
1835
+ for span, role, target in spans:
1836
+ if role == markdown.LINK:
1837
+ out.append(span, Style.parse(styles.get(role) or "")
1838
+ + Style(meta={"url": target}))
1839
+ continue
1840
+ out.append(span, styles.get(role) if role else None)
1841
+
1842
+ def _render_table(self, block) -> None:
1843
+ """One markdown table (batch 53).
1844
+
1845
+ A `rich.table.Table` rather than characters we lay out ourselves,
1846
+ for the reason `Syntax` is a `Syntax`: `RichLog.write` takes any
1847
+ renderable, so the alignment, the column widths and the wrapping
1848
+ inside a cell are Rich's problem and stay right at any terminal
1849
+ size. Textual's own `Markdown` cannot be used here -- it is a
1850
+ Widget, not a renderable, so reaching for it means replacing the
1851
+ transcript rather than rendering into it.
1852
+
1853
+ EVERY CELL IS A `Text`, header cells included. A bare `str` handed
1854
+ to a Table is parsed for console markup by the console that renders
1855
+ it, and the RichLog's own `markup=False` does not reach inside a
1856
+ renderable. Measured against the pinned Rich, both halves bite:
1857
+
1858
+ - `[bold]x` renders as `x`. The tag is SWALLOWED, silently, and
1859
+ a cell describing a style, a Textual selector or a log line
1860
+ loses part of itself with nothing raised.
1861
+ - `a[/]b` raises `MarkupError`, which is batch 42's RA1 -- the
1862
+ failure where a modal was pushed, never drew, and left a
1863
+ worker waiting on a dismissal that could not come. Here it
1864
+ would take down the turn that was answering.
1865
+
1866
+ `[1, 2]` survives, which is why the rule has to be about the TYPE
1867
+ rather than about scanning for brackets: the shapes that fail are
1868
+ not the ones a reader expects to be dangerous.
1869
+
1870
+ Cells are rendered with `line_start=False` (batch 58). A cell is a
1871
+ fragment rather than a line, so a cell reading `- 3` is a minus
1872
+ three and not a bullet, and one indented four spaces is a padded
1873
+ column rather than a code sample.
1874
+
1875
+ Written with an explicit `width=` when the widget can be measured,
1876
+ following the diff's discipline: it is the same number the text
1877
+ pre-wrap uses, so a table and the paragraph above it break at one
1878
+ width rather than two.
1879
+ """
1880
+ styles = self._styles()
1881
+ table = Table(box=TABLE_BOX,
1882
+ border_style=styles.get("table_border") or None,
1883
+ header_style=styles.get("table_header") or None)
1884
+ for header, align in zip(block.headers, block.aligns):
1885
+ table.add_column(
1886
+ self._inline_text(header, line_start=False), justify=align)
1887
+ for row in block.rows:
1888
+ table.add_row(*(self._inline_text(cell, line_start=False)
1889
+ for cell in row))
1890
+ width = self._wrap_width()
1891
+ if width:
1892
+ self.write(table, width=width)
1893
+ else:
1894
+ self.write(table)
1895
+
1896
+ # -- links (batch 58) ---------------------------------------------------
1897
+
1898
+ def on_click(self, event) -> None:
1899
+ """CTRL+click a URL to open it.
1900
+
1901
+ Ctrl rather than a bare click, which is the terminal's own
1902
+ convention for a link and also the reason a click while reading
1903
+ cannot launch a browser by accident.
1904
+
1905
+ The target is read back out of the style METADATA the span was
1906
+ drawn with, so what opens is what was underlined, which is what
1907
+ the reader saw. `markdown.clickable` is re-asked here rather than
1908
+ trusted from render time: the styles in a `RichLog` outlive the
1909
+ text that produced them, and a check at the point of ACTION is
1910
+ the one that governs.
1911
+
1912
+ Textual dispatches this by position, so a click one column off the
1913
+ URL carries no metadata and does nothing.
1914
+ """
1915
+ if not getattr(event, "ctrl", False):
1916
+ return
1917
+ style = getattr(event, "style", None)
1918
+ url = (getattr(style, "meta", None) or {}).get("url")
1919
+ if url:
1920
+ self.open_url(url)
1921
+
1922
+ def open_url(self, url) -> None:
1923
+ """Hand `url` to the platform's browser, off the UI thread.
1924
+
1925
+ A thread worker for the reason every other outward call in this
1926
+ app uses one: `webbrowser.open` can block while a cold browser
1927
+ starts, and the UI thread is drawing a live stream.
1928
+
1929
+ SILENT on success -- the browser appearing is the confirmation,
1930
+ and a transcript line would call `flush_stream()` and close a
1931
+ live answer span in the middle of a turn. A failure is a toast,
1932
+ which is the vocabulary `tui/app.py` already uses for a turn that
1933
+ did not survive.
1934
+ """
1935
+ if not markdown.clickable(url):
1936
+ return
1937
+
1938
+ def work() -> None:
1939
+ try:
1940
+ opened = webbrowser.open(url)
1941
+ except Exception: # noqa: BLE001 -- reported, never fatal
1942
+ opened = False
1943
+ if not opened:
1944
+ self.app.call_from_thread(
1945
+ self.app.notify,
1946
+ f"Could not open {url}", severity="warning")
1947
+
1948
+ self.run_worker(work, thread=True, exit_on_error=False,
1949
+ name="open-url")
896
1950
 
897
1951
  def write_user(self, text: str) -> None:
898
1952
  self.flush_stream()
@@ -906,16 +1960,20 @@ class Transcript(RichLog):
906
1960
  self.flush_stream()
907
1961
  self._emit("error", text)
908
1962
 
909
- def write_role(self, role: str, text: str) -> None:
1963
+ def write_role(self, role: str, text: str, links=()) -> None:
910
1964
  """Write a line in an arbitrary palette role (§26).
911
1965
 
912
1966
  Exists so the research view can style a pass boundary, a tool call
913
1967
  and a failed tool differently without Transcript growing a method
914
1968
  per event kind -- the roles already live in one table, and this is
915
1969
  the accessor for it.
1970
+
1971
+ `links` is batch 65's, and it is ignored for every role outside
1972
+ LINKED_ROLES rather than refused: a caller that has candidates
1973
+ should not have to know which roles use them.
916
1974
  """
917
1975
  self.flush_stream()
918
- self._emit(role, text)
1976
+ self._emit(role, text, links=links)
919
1977
 
920
1978
  def write_answer(self, text: str) -> None:
921
1979
  """A model answer that did not arrive as a stream (a one-shot turn,
@@ -953,12 +2011,9 @@ class Transcript(RichLog):
953
2011
  return width if width >= MIN_WRAP_WIDTH else 0
954
2012
 
955
2013
  @staticmethod
956
- def _fence_is_open(text: str) -> bool:
957
- """An odd number of ``` means a code fence is still open."""
958
- return text.count("```") % 2 == 1
959
-
960
- @staticmethod
961
- def _split_committable(pending: str, width: int) -> tuple[str, str]:
2014
+ def _split_committable(pending: str, width: int,
2015
+ *, marks: bool = False,
2016
+ block: bool = True) -> tuple[str, str]:
962
2017
  """Split `pending` into (commit now, keep buffered).
963
2018
 
964
2019
  The two rules from the class docstring. The over-long-token branch
@@ -966,16 +2021,31 @@ class Transcript(RichLog):
966
2021
  space in it (a URL) would otherwise be held until a newline
967
2022
  arrived, so it is cut at the row boundary -- which is what Rich's
968
2023
  own wrapping does with a word too long for the line.
2024
+
2025
+ `marks` measures the width rule in RENDERED cells rather than in
2026
+ source characters (batch 53), which is what an answer carrying
2027
+ `**bold**` needs: the mark is four cells narrower drawn than
2028
+ written, so a source-column cut lands where Rich would not have
2029
+ wrapped and the streamed rows stop matching the ones rerender()
2030
+ draws from the same text. OFF by default, and the default is the
2031
+ answer for `thinking_delta`: reasoning is rendered as prose, marks
2032
+ and all, so measuring it as anything else would be describing a
2033
+ rendering that does not happen.
2034
+
2035
+ `block` is `markdown.inline_spans`' and travels with `marks`: when
2036
+ the pending text is the tail of a line already partly drawn, its
2037
+ leading spaces are not an indent, so the indent rule must not
2038
+ decide the measurement here when it will not decide the drawing
2039
+ there.
969
2040
  """
970
2041
  cut = pending.rfind("\n")
971
2042
  if cut != -1:
972
2043
  return pending[:cut + 1], pending[cut + 1:]
973
- if width and len(pending) > width:
974
- space = pending.rfind(" ", 0, width + 1)
975
- if space > 0:
976
- return pending[:space + 1], pending[space + 1:]
977
- return pending[:width], pending[width:]
978
- return "", pending
2044
+ if not width:
2045
+ return "", pending
2046
+ if marks:
2047
+ return markdown.width_split(pending, width, block=block)
2048
+ return markdown.plain_split(pending, width)
979
2049
 
980
2050
  def stream_delta(self, delta: str) -> None:
981
2051
  self._pending += delta
@@ -987,16 +2057,44 @@ class Transcript(RichLog):
987
2057
  Loops because one delta can make several rows committable at once
988
2058
  -- a paragraph arriving in one chunk, or a buffer that has been
989
2059
  held back behind a closing fence.
2060
+
2061
+ §38 held the whole chunk while a ``` fence was open. Batch 53 turns
2062
+ that single rejection into `markdown.safe_commit_limit`, a CAP over
2063
+ four constructs -- an open fence, a table, a heading, an unclosed
2064
+ inline mark -- because the reason was never about fences: RichLog
2065
+ appends and cannot rewrite a drawn row, so anything committed in
2066
+ halves renders as its own source and can never be put right.
2067
+
2068
+ A cap is strictly better than the rejection it replaces: a
2069
+ paragraph sharing a buffer with a fence used to wait for the fence
2070
+ to close, and now streams. Where the construct starts the buffer,
2071
+ the cap is 0 and nothing commits -- which is what keeps §38's two
2072
+ fence pins saying what they always said.
2073
+
2074
+ Batch 58 adds the fifth construct (a list item) and the ceiling.
2075
+ `commit_span`'s second value says the cap gave up on a line-scoped
2076
+ hold because HOLD_LIMIT expired, and it reaches the renderer as
2077
+ `line_start=False`: the line is no longer a heading or a list item
2078
+ on EITHER path, so the rows it is drawn in are the rows the replay
2079
+ will draw. Without that a model could hold the screen indefinitely
2080
+ by never sending a newline.
990
2081
  """
991
2082
  width = self._wrap_width()
992
2083
  while True:
993
- chunk, rest = self._split_committable(self._pending, width)
994
- if not chunk or self._fence_is_open(self._stream_text + chunk):
2084
+ limit, forced = markdown.commit_span(
2085
+ self._stream_text, self._pending)
2086
+ mid_line = bool(self._stream_text) \
2087
+ and not self._stream_text.endswith("\n")
2088
+ chunk, rest = self._split_committable(
2089
+ self._pending[:limit], width, marks=True,
2090
+ block=not mid_line)
2091
+ if not chunk:
995
2092
  return
996
- self._pending = rest
997
- self._write_stream_chunk(chunk)
2093
+ self._pending = rest + self._pending[limit:]
2094
+ self._write_stream_chunk(chunk, line_start=not (mid_line or forced))
998
2095
 
999
- def _write_stream_chunk(self, chunk: str) -> None:
2096
+ def _write_stream_chunk(self, chunk: str, *,
2097
+ line_start: bool = True) -> None:
1000
2098
  if not self._stream_open:
1001
2099
  self.end_thinking()
1002
2100
  self._open_label()
@@ -1011,7 +2109,7 @@ class Transcript(RichLog):
1011
2109
  # still has to draw one.
1012
2110
  body = chunk[:-1] if chunk.endswith("\n") else chunk
1013
2111
  if body:
1014
- self._render_blocks(body)
2112
+ self._render_blocks(body, line_start=line_start)
1015
2113
  else:
1016
2114
  self.write(Text("", self._style("assistant")))
1017
2115
 
@@ -1047,9 +2145,14 @@ class Transcript(RichLog):
1047
2145
  self._emit("assistant", residual)
1048
2146
  return residual
1049
2147
  if residual:
2148
+ # Read BEFORE the append, for _commit_ready's reason: the
2149
+ # flush draws the tail of a line the stream may already have
2150
+ # drawn part of, and that tail is not the start of one.
2151
+ line_start = not self._stream_text \
2152
+ or self._stream_text.endswith("\n")
1050
2153
  self._stream_text += residual
1051
2154
  self._entries[-1] = ("assistant", self._stream_text)
1052
- self._render_blocks(residual)
2155
+ self._render_blocks(residual, line_start=line_start)
1053
2156
  text = self._stream_text
1054
2157
  self._stream_open = False
1055
2158
  self._stream_text = ""
@@ -1149,6 +2252,11 @@ class Transcript(RichLog):
1149
2252
  # in the session with no `venastine ›`.
1150
2253
  self._label_in_force = False
1151
2254
  self._entries.clear()
2255
+ # Batch 65, and the same sentence as the line above it: a click
2256
+ # target left behind would belong to a thread that is no longer
2257
+ # on screen, and index N would then arm the NEXT thread's Nth
2258
+ # line with the previous one's URL.
2259
+ self._links.clear()
1152
2260
  self.clear()
1153
2261
 
1154
2262
  def rerender(self) -> None:
@@ -1165,8 +2273,12 @@ class Transcript(RichLog):
1165
2273
  # loop below re-derives every one of them from the role sequence
1166
2274
  # exactly as the live path did.
1167
2275
  self._label_in_force = False
1168
- for role, text in self._entries:
1169
- self._render_entry(role, text)
2276
+ for index, (role, text) in enumerate(self._entries):
2277
+ # Batch 65: the targets too, or a /theme would silently
2278
+ # disarm every long URL in the session -- the line would
2279
+ # look identical and stop being clickable, which is the
2280
+ # kind of loss only the pointer can find.
2281
+ self._render_entry(role, text, self._links.get(index, ()))
1170
2282
 
1171
2283
  def last_answer(self) -> str:
1172
2284
  """The most recent answer in this session, or "" (for /copy last).
@@ -1218,22 +2330,3 @@ class Transcript(RichLog):
1218
2330
  label = labels.get(role)
1219
2331
  out.append(f"{label}: {text}" if label else text)
1220
2332
  return "\n\n".join(out)
1221
-
1222
-
1223
- def _split_fences(text: str):
1224
- """Split markdown into plain strings and (language, code) tuples.
1225
-
1226
- Deliberately small: this is a renderer, not a markdown parser. An
1227
- unterminated fence is treated as running to the end of the text, which
1228
- is the common case mid-stream.
1229
- """
1230
- out = []
1231
- parts = text.split("```")
1232
- for i, part in enumerate(parts):
1233
- if i % 2 == 0:
1234
- if part:
1235
- out.append(part)
1236
- else:
1237
- language, _, code = part.partition("\n")
1238
- out.append((language.strip() or None, code))
1239
- return out