@yahyahammad/venastine 0.1.0 → 0.3.8

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.
Files changed (130) hide show
  1. package/.env.example +19 -14
  2. package/CONFIG_ARCHITECTURE.md +2002 -0
  3. package/NOTICE +1 -1
  4. package/README.md +249 -93
  5. package/agents/builtin/build.md +73 -0
  6. package/agents/builtin/general.md +80 -0
  7. package/agents/builtin/plan.md +23 -5
  8. package/agents/builtin/test.md +65 -0
  9. package/agents/builtin/writer.md +67 -0
  10. package/agents/manager.py +261 -195
  11. package/agents/subagent_tool.py +280 -23
  12. package/agents/tui_commands.py +31 -21
  13. package/bin/venastine.mjs +528 -382
  14. package/bin/venastine.py +71 -0
  15. package/cli_commands.py +835 -0
  16. package/config.py +95 -1198
  17. package/config.yaml +1090 -0
  18. package/config_edit.py +1301 -0
  19. package/config_schema.py +966 -0
  20. package/config_update.py +749 -0
  21. package/core/agent_activity.py +256 -0
  22. package/core/ansi.py +452 -0
  23. package/core/approval.py +27 -5
  24. package/core/call_view.py +364 -0
  25. package/core/cancel.py +121 -0
  26. package/core/chatgpt_auth.py +747 -0
  27. package/core/claims_view.py +107 -0
  28. package/core/client.py +1249 -82
  29. package/core/commands.py +454 -0
  30. package/core/compaction.py +1735 -959
  31. package/core/config_loader.py +516 -97
  32. package/core/connect.py +686 -0
  33. package/core/events.py +68 -6
  34. package/core/file_mentions.py +280 -0
  35. package/core/interaction.py +87 -4
  36. package/core/line_pattern.py +128 -0
  37. package/core/loop.py +2566 -1353
  38. package/core/memory.py +482 -370
  39. package/core/pipeline_models.py +23 -9
  40. package/core/provider_errors.py +234 -0
  41. package/core/reasoning/confidence_scoring.py +70 -54
  42. package/core/reasoning/json_retry.py +19 -1
  43. package/core/reasoning/orchestrator.py +232 -53
  44. package/core/reasoning/output_writer.py +90 -31
  45. package/core/reasoning/payload_validation.py +133 -7
  46. package/core/reasoning/pipeline_storage.py +427 -361
  47. package/core/reasoning/review.py +659 -615
  48. package/core/reasoning/scholar.py +38 -14
  49. package/core/reasoning/source_corpus.py +110 -4
  50. package/core/replay.py +315 -167
  51. package/core/session.py +36 -12
  52. package/core/session_view.py +259 -0
  53. package/core/session_wake.py +259 -0
  54. package/core/shell_sessions.py +1553 -0
  55. package/core/workspace_trust.py +1 -1
  56. package/credentials.py +308 -180
  57. package/database.py +82 -1
  58. package/{PRIVACY.md → docs/PRIVACY.md} +19 -7
  59. package/docs/SECURITY.md +108 -0
  60. package/docs/THIRD_PARTY_NOTICES.md +148 -0
  61. package/env_secrets.py +118 -77
  62. package/json_store.py +236 -16
  63. package/logging_setup.py +121 -11
  64. package/main.py +1672 -198
  65. package/mcp_client/client.py +257 -23
  66. package/mcp_client/config.py +484 -379
  67. package/mcp_client/registration.py +163 -2
  68. package/memories/manager.py +15 -0
  69. package/memories/tui_commands.py +21 -14
  70. package/package.json +303 -73
  71. package/project_init/config_files.py +4 -0
  72. package/project_init/generator.py +201 -37
  73. package/project_init/manifest.py +418 -406
  74. package/project_init/tui_commands.py +7 -4
  75. package/prompts/revalidate.md +1 -1
  76. package/prompts/revise.md +17 -15
  77. package/prompts/system_prompts.py +64 -10
  78. package/providers.json.example +94 -92
  79. package/pyproject.toml +149 -100
  80. package/requirements.txt +252 -29
  81. package/safety/policy_enforcement.py +1082 -682
  82. package/security/askpass.py +419 -0
  83. package/security/capability.py +37 -7
  84. package/security/confine.py +484 -0
  85. package/security/hosted.py +182 -0
  86. package/security/permissions.py +54 -7
  87. package/security/posture.py +124 -12
  88. package/security/protected_paths.py +198 -6
  89. package/security/sandbox.py +3262 -139
  90. package/security/secrets.py +855 -0
  91. package/skills/tui_commands.py +3 -4
  92. package/storage.py +1338 -1005
  93. package/tools/base.py +465 -305
  94. package/tools/builtin/_math_common.py +306 -16
  95. package/tools/builtin/_net_common.py +267 -61
  96. package/tools/builtin/arxiv.py +681 -223
  97. package/tools/builtin/ask_user.py +231 -213
  98. package/tools/builtin/discrete_math.py +35 -4
  99. package/tools/builtin/fetch_url.py +239 -21
  100. package/tools/builtin/file_ops.py +341 -33
  101. package/tools/builtin/geometry.py +184 -148
  102. package/tools/builtin/get_time.py +2 -2
  103. package/tools/builtin/linear_algebra.py +66 -23
  104. package/tools/builtin/load_skill.py +10 -0
  105. package/tools/builtin/logic.py +171 -12
  106. package/tools/builtin/pin.py +46 -12
  107. package/tools/builtin/probability_stats.py +224 -228
  108. package/tools/builtin/project_docs.py +80 -21
  109. package/tools/builtin/remember.py +21 -4
  110. package/tools/builtin/shell.py +586 -67
  111. package/tools/builtin/shell_sessions.py +613 -0
  112. package/tools/builtin/symbolic_math.py +80 -10
  113. package/tools/builtin/todo.py +5 -3
  114. package/tools/builtin/web_search.py +329 -151
  115. package/tools/context.py +23 -0
  116. package/tools/isolation.py +387 -314
  117. package/tools/registry.py +374 -29
  118. package/tui/app.py +5281 -397
  119. package/tui/app.tcss +290 -9
  120. package/tui/commands.py +26 -61
  121. package/tui/diffs.py +286 -265
  122. package/tui/history.py +128 -0
  123. package/tui/hosted_driver.py +102 -0
  124. package/tui/markdown.py +1329 -0
  125. package/tui/meters.py +364 -0
  126. package/tui/screens.py +346 -92
  127. package/tui/themes.py +599 -366
  128. package/tui/widgets.py +2673 -116
  129. package/SECURITY.md +0 -88
  130. package/THIRD_PARTY_NOTICES.md +0 -100
package/tui/widgets.py CHANGED
@@ -1,18 +1,74 @@
1
1
  """
2
2
  tui/widgets.py
3
3
 
4
- ROADMAP_v2 §16 widgets. Presentation only -- nothing here imports core/
5
- or reaches into harness state; tui/app.py feeds them.
4
+ ROADMAP_v2 §16 widgets. Presentation only -- nothing here reaches into
5
+ harness state or does I/O; tui/app.py feeds them.
6
+
7
+ THE RULE SAID "nothing here imports core/" UNTIL BATCH 145, and the one
8
+ import it now has is the reason the wording moved rather than the rule.
9
+ `core/ansi.py` is a pure text transform -- it imports `__future__` and
10
+ nothing else, holds no harness state, touches no widget and does no I/O,
11
+ which its own docstring says in those words. It lives in `core/` because
12
+ the pty reader needs it too, not because it is harness machinery; it is
13
+ the same KIND of module as `tui/markdown.py`, one directory over. A second
14
+ copy here is what the rule would actually have bought, and that is the
15
+ two-copies-of-one-decision shape (EP6, #157) that `core/ansi.py`'s own
16
+ docstring refuses -- and batch 144 had just spent a whole surface undoing
17
+ it for the secret redactors. The part of the rule that matters is intact:
18
+ nothing here reads config, storage, a session or a tool.
6
19
  """
7
20
 
21
+ import webbrowser
22
+ from dataclasses import dataclass
23
+
24
+ from rich import box
25
+ from rich.cells import cell_len
26
+ from rich.console import Console
27
+ from rich.measure import measure_renderables
28
+ from rich.style import Style
8
29
  from rich.syntax import Syntax
30
+ from rich.table import Table
9
31
  from rich.text import Text
32
+ from textual.binding import Binding
33
+ from textual.content import Content
34
+ from textual.message import Message
10
35
  from textual.reactive import reactive
11
- from textual.widgets import RichLog, Static
36
+ from textual.widgets import ContentSwitcher, RichLog, Static, TextArea
12
37
 
38
+ from core.ansi import AnsiStripper
13
39
  from prompts.system_prompts import pass_label
40
+ from tui import diffs, markdown, ravens, themes
41
+ from tui.commands import registry as commands
42
+
43
+
44
+ def as_content(text: Text) -> Content:
45
+ """A Rich ``Text`` as the ``Content`` textual would build from it anyway.
46
+
47
+ ``Static.update`` routes its argument through ``visual.visualize()``,
48
+ which special-cases a Rich ``Text`` into
49
+ ``Content.from_rich_text(obj, console=widget.app.console)`` -- and
50
+ ``self.app`` RAISES outside a running app. Every panel in this module is
51
+ built bare in the suite (``ThinkingIndicator._redraw``'s guard is the
52
+ same fact one door along), so handing textual a ``Text`` turned every
53
+ such construction into an error about the event loop.
54
+
55
+ ``Content.from_rich_text`` itself takes ``console=None`` and falls back
56
+ to ``RichStyle.parse``, so doing the conversion HERE is what removes the
57
+ app lookup. Parity rather than approximation, measured: over 1085
58
+ (theme, role) style strings across all 35 selectable themes the console
59
+ changes not one span. ``role_styles`` emits literal Rich style strings
60
+ (``bold #0178D4``, ``dim italic``, ``green``) and never a textual CSS
61
+ variable, and those are exactly what ``RichStyle.parse`` reads.
62
+
63
+ The other half is what does NOT survive: ``Content`` carries no
64
+ ``no_wrap`` and no ``overflow``, and ``from_rich_text`` drops both.
65
+ Textual's own call drops them too, so a widget that set them on its
66
+ ``Text`` lost them the moment the pin moved -- silently, and with no
67
+ test able to see it. They are ``text-wrap`` / ``text-overflow`` in
68
+ ``app.tcss`` now; see ``#agent-panel`` and ``#thread-crumb``.
69
+ """
70
+ return Content.from_rich_text(text)
14
71
 
15
- from tui import diffs, ravens, themes
16
72
 
17
73
  # Animation cadence. Slow enough to read, and paused outright while tokens
18
74
  # are streaming -- a redraw loop competing with token deltas is the one
@@ -34,6 +90,47 @@ THINKING_INDENT = " "
34
90
  # (a bare-built test widget, a widget before mount) reads as 0.
35
91
  MIN_WRAP_WIDTH = 20
36
92
 
93
+ # Batch 112 (TECHNICAL_DEBT 23). How long after the LAST resize event the
94
+ # transcript re-lays itself. Dragging a window edge delivers one Resize per
95
+ # frame and a replay is O(the whole session), so the redraw is coalesced
96
+ # rather than run per event. 0.15s is below the threshold at which a redraw
97
+ # reads as a delay and comfortably above a drag's frame interval. Tests
98
+ # monkeypatch it to 0 rather than sleeping through it.
99
+ REFLOW_DEBOUNCE_S = 0.15
100
+
101
+ # Batch 55, the slash-command suggestion panel. The two caps are a pair:
102
+ # five entries is the list a reader takes in at a glance, eight rows is
103
+ # what leaves the transcript readable at the 24-row floor, and at 80
104
+ # columns most entries wrap to two rows so the ROW cap is usually the one
105
+ # that bites. See SlashSuggest for why the gutters are inside the wrap.
106
+ SUGGEST_SEP = " ● "
107
+ SUGGEST_ELLIPSIS = "…"
108
+ SUGGEST_LEAD = " "
109
+ SUGGEST_CONT = " "
110
+ SUGGEST_MAX_ENTRIES = 5
111
+ SUGGEST_MAX_ROWS = 8
112
+ SUGGEST_MAX_LINES = 2
113
+ SUGGEST_HIGHLIGHT = "reverse"
114
+
115
+ # Batch 62, the keys the panel spends while it is open. Four of them
116
+ # change meaning here and none was written anywhere in the TUI: the
117
+ # arrows move the highlight, tab and enter BOTH complete, escape
118
+ # dismisses. `enter` is the one that costs something -- it completes
119
+ # rather than sends, so a fully typed /help takes two presses, and the
120
+ # first changes nothing a reader can see except a trailing space.
121
+ #
122
+ # `tab/enter` is one item because they are one action: action_submit
123
+ # and action_complete both call _complete(). The separator is the
124
+ # title's, so the two labels on this box read as one voice.
125
+ #
126
+ # NO SQUARE BRACKETS. `_BorderTitle.__set__` runs the value through
127
+ # `render_str`, so a `[` is markup -- and the getter hands back
128
+ # `.markup`, which re-escapes it, so the change-guard below would
129
+ # never compare equal and every paint would schedule another.
130
+ SUGGEST_HINT_SEP = " · "
131
+ SUGGEST_HINT_MOVE = "↑↓ move"
132
+ SUGGEST_HINT_REST = ("tab/enter complete", "esc dismiss")
133
+
37
134
  # §41. The inline diff's furniture, owned by the renderer for the same
38
135
  # reason the thinking bar is: `_entries` keeps the canonical block, so
39
136
  # /copy hands back a diff rather than a decorated string and a replay
@@ -69,6 +166,14 @@ _DIFF_MARKS = {
69
166
  diffs.ELIDED: " ",
70
167
  }
71
168
 
169
+ # Batch 53. The table's box, and the owner's choice among rich.box's
170
+ # presets. A full grid rather than one of the rule-only forms: the
171
+ # transcript already draws box characters for a thinking span (╭ │ ╰), so
172
+ # the vocabulary is established, and a table is the one construct here
173
+ # whose whole point is that a reader can follow a row across several
174
+ # columns without losing the line.
175
+ TABLE_BOX = box.SQUARE
176
+
72
177
  # Batch 41 (X3). The checklist vocabulary, in ONE place because two
73
178
  # panels render it and they were already spelling it differently: the
74
179
  # todo list used `x` for done where the research panel used `x` for a
@@ -112,18 +217,71 @@ MARK_STAGE = "·"
112
217
  # MESSAGE_ROLES, so a new role has to be classified rather than land in
113
218
  # one target or the other by accident.
114
219
  CONVERSATION_ROLES = frozenset({
115
- "user", "assistant", "thinking", "tool", "tool_error", "diff"})
220
+ "user", "assistant", "thinking", "tool", "tool_error", "diff",
221
+ "pipeline_tool",
222
+ # ROADMAP_v3 §49 (SS14): a line of a background session's own output,
223
+ # in a session view. CONVERSATION rather than META for `tool_error`'s
224
+ # reason -- it is the far end of a tool call, which is part of the
225
+ # exchange, and the harness is quoting it rather than saying it. Its
226
+ # only home today is the session-view pane, which `/copy` does not
227
+ # read; the classification is what a copy of one WOULD do.
228
+ "output"})
116
229
 
117
230
  # `pass` and `pass_done` are here rather than above deliberately: a
118
231
  # ten-pass run's boundaries are progress reporting about the harness,
119
232
  # not the exchange, so a research run copies as the query, the tool
120
- # lines and the report.
233
+ # lines and the report. `pipeline_tool` is that same call made in the
234
+ # other direction: it is the research tool line's own role -- distinct
235
+ # from `tool` so it cannot open the turn's label the way a chat tool
236
+ # call now can -- and it classifies as CONVERSATION so batch 48's copy
237
+ # shape survives the rename unchanged.
121
238
  META_ROLES = frozenset({
122
- "system", "warning", "error", "pass", "pass_done", "success"})
239
+ "system", "warning", "error", "pass", "pass_done", "success",
240
+ # ROADMAP_v3 §49 (SS5). A background session's result, written by the
241
+ # harness to start a turn. The model reads it, but nobody in the
242
+ # conversation SAID it, so /copy conversation leaves it out as it leaves
243
+ # out a routed warning -- and the answer it prompted still copies.
244
+ "wake",
245
+ # Batch 199: the hosted banner's star line. The harness's voice, like
246
+ # the `system` lines around it, so /copy conversation leaves it out.
247
+ "invite"})
248
+
249
+ # Batch 65 (TECHNICAL_DEBT 16). The lines whose URLs are armed for
250
+ # ctrl+click, beside the two sets above for their reason: which roles a
251
+ # rule is true of is a list, and a list that lives at its one use site
252
+ # is a list nothing can check.
253
+ #
254
+ # These three are what a model's tool CALL or its failure produced --
255
+ # `▸ fetch_url https://…` is where a URL most obviously appears, and it
256
+ # was the one place inert while the same URL in prose was not. The
257
+ # harness's own voice (`system`, `error`, `warning`) is deliberately
258
+ # absent: those lines are written here, not by a model, and nothing has
259
+ # reported wanting to click one.
260
+ #
261
+ # They take the LINKS-ONLY scanner, never the prose grammar. A tool
262
+ # line is a digest, and `markdown.link_spans` says at length what the
263
+ # full grammar does to one.
264
+ #
265
+ # Batch 199 adds `invite`, the hosted banner's star line, by the owner's
266
+ # choice: the one line the harness writes so that it is clicked. Same
267
+ # links-only scanner; `system`, `error` and `warning` stay unarmed.
268
+ LINKED_ROLES = frozenset({"tool", "pipeline_tool", "tool_error", "invite"})
123
269
 
124
270
 
125
271
  class RavenPanel(Static):
126
- """Corner raven: what the harness is doing right now."""
272
+ """Corner raven: what the harness is doing right now.
273
+
274
+ `still_when_idle` (ROADMAP_v3 §79, batch 168) is for a hosted session,
275
+ whose screen is relayed to a browser. There the idle blink was the whole
276
+ of what a silent tab received -- 6.9 KB/s, five packets a second,
277
+ measured through the bridge -- and the bridge counts a session's output
278
+ as activity, so the 20-minute idle limit could never fire and an
279
+ abandoned tab held its slot for the full two-hour lifetime. Idle, the
280
+ raven draws its first frame and its timer stays paused; every other
281
+ state animates as before, and a pause the app asked for (a token
282
+ stream) is never undone by a state change. A local install keeps the
283
+ blink.
284
+ """
127
285
 
128
286
  # NOT always_update=True. Every token_delta reassigns state to
129
287
  # THINKING, so always_update fired watch_state once per token for the
@@ -132,24 +290,51 @@ class RavenPanel(Static):
132
290
  # pause_animation exists to eliminate. Genuine transitions still fire.
133
291
  state = reactive(ravens.IDLE)
134
292
 
135
- def __init__(self, animations: bool = True, **kwargs):
293
+ def __init__(self, animations: bool = True, still_when_idle: bool = False,
294
+ **kwargs):
136
295
  super().__init__(**kwargs)
137
296
  self._animations = animations
297
+ self._still_when_idle = still_when_idle
298
+ self._held = False # the app paused it, for a token stream
138
299
  self._frame = 0
139
300
  self._timer = None
140
301
 
141
302
  def on_mount(self) -> None:
142
303
  if self._animations:
143
304
  self._timer = self.set_interval(ANIMATION_INTERVAL, self._advance)
305
+ self._hold_still_if_idle()
144
306
  self._render_state()
145
307
 
146
308
  def _advance(self) -> None:
309
+ # Batch 200. A tick can arrive while this panel holds its timer
310
+ # paused. Textual's timer task waits on an asyncio.Event, resume()
311
+ # releases it, and a pause() before the task runs clears the event
312
+ # but cannot recall the release. The app does exactly that at a
313
+ # turn's end -- resume_animation(), then IDLE -- so a stream that
314
+ # held the raven past one interval let a tick through after
315
+ # watch_state had reset the frame, and a hosted raven sat still
316
+ # with its eye shut. Both conditions are the ones under which this
317
+ # panel pauses the timer, so a tick that meets either is stale.
318
+ if self._held or self._idle_and_still():
319
+ return
147
320
  self._frame += 1
148
321
  self._render_state()
149
322
 
150
323
  def watch_state(self) -> None:
151
324
  self._frame = 0
152
325
  self._render_state()
326
+ self._hold_still_if_idle()
327
+
328
+ def _idle_and_still(self) -> bool:
329
+ return self._still_when_idle and self.state is ravens.IDLE
330
+
331
+ def _hold_still_if_idle(self) -> None:
332
+ if self._timer is None or not self._still_when_idle:
333
+ return
334
+ if self._idle_and_still():
335
+ self._timer.pause()
336
+ elif not self._held:
337
+ self._timer.resume()
153
338
 
154
339
  def _render_state(self) -> None:
155
340
  frames = self.state.frames
@@ -158,11 +343,13 @@ class RavenPanel(Static):
158
343
 
159
344
  def pause_animation(self) -> None:
160
345
  """Called while a token stream is active. Idempotent."""
346
+ self._held = True
161
347
  if self._timer is not None:
162
348
  self._timer.pause()
163
349
 
164
350
  def resume_animation(self) -> None:
165
- if self._timer is not None:
351
+ self._held = False
352
+ if self._timer is not None and not self._idle_and_still():
166
353
  self._timer.resume()
167
354
 
168
355
 
@@ -208,7 +395,7 @@ class ThinkingIndicator(Static):
208
395
  except Exception: # noqa: BLE001 -- no running app; render unstyled
209
396
  style = ""
210
397
  frame = self.FRAMES[self._frame] if self._animations else self.FRAMES[-1]
211
- self.update(Text(f"{THINKING_INDENT}{frame}", style))
398
+ self.update(as_content(Text(f"{THINKING_INDENT}{frame}", style)))
212
399
 
213
400
  def start(self) -> None:
214
401
  """Idempotent -- called on every thinking delta."""
@@ -276,7 +463,7 @@ class PostureBadge(Static):
276
463
  body = Text("!! REDUCED SECURITY\n")
277
464
  for label, _detail in self._reasons:
278
465
  body.append("- " + label + "\n")
279
- self.update(body)
466
+ self.update(as_content(body))
280
467
  self.display = True
281
468
 
282
469
 
@@ -319,17 +506,30 @@ class UsageLine(Static):
319
506
  self.update("")
320
507
 
321
508
  def update_usage(self, billed: int, ctx: int,
322
- ceiling: int = 0, overridden: bool = False) -> None:
509
+ ceiling: int = 0, overridden: bool = False,
510
+ window: int = 0) -> None:
323
511
  """`ceiling` is the compaction trigger this thread is measured
324
- against, shown as a denominator so `ctx` has a scale. `overridden`
325
- marks it with a `*` when a session /trigger set it -- ephemeral
326
- state that changes when compaction fires should not be invisible,
327
- which is the same rule M14 states for injected memories.
328
-
329
- Both are optional so a caller that has no threshold to hand still
512
+ against and `window` is the model's actual context limit.
513
+ `overridden` marks the trigger with a `*` when a session /trigger
514
+ set it -- ephemeral state that changes when compaction fires should
515
+ not be invisible, which is the same rule M14 states for injected
516
+ memories.
517
+
518
+ THE DENOMINATOR IS THE WINDOW SINCE BATCH 119, and the trigger is
519
+ annotated beside it. It used to be the trigger alone, which was
520
+ defensible -- that is the number `ctx` is compared against, and the
521
+ line existed to give `ctx` a scale -- and was still the wrong
522
+ choice, because a denominator is read as a LIMIT. `ctx 230k/223k`
523
+ says "over budget" about a thread with 32k of window left, and the
524
+ window appeared nowhere in the TUI but `/window`. An owner read that
525
+ line and concluded the harness treats the window and the trigger as
526
+ one value; the blocked-compaction notice saying "Context is full"
527
+ was the other half, and batch 119 corrects both.
528
+
529
+ All three are optional so a caller with no threshold to hand still
330
530
  gets the batch-27 two-instrument line unchanged.
331
531
  """
332
- key = (billed, ctx, ceiling, overridden)
532
+ key = (billed, ctx, ceiling, overridden, window)
333
533
  if key == self._last or not (billed or ctx):
334
534
  # Change-guard: on_loop_event fires per token delta during a
335
535
  # stream; both figures only move at step boundaries, so this
@@ -341,13 +541,26 @@ class UsageLine(Static):
341
541
  return f"{n / 1000:.0f}k" if n >= 1000 else str(n)
342
542
 
343
543
  self.display = True
344
- scale = f"/{_k(ceiling)}{'*' if overridden else ''}" if ceiling else ""
544
+ mark = "*" if overridden else ""
545
+ if window:
546
+ # The limit as the scale, the fold point named as what it is.
547
+ scale = f"/{_k(window)}"
548
+ scale += f" (fold {_k(ceiling)}{mark})" if ceiling else ""
549
+ elif ceiling:
550
+ # No window resolved -- context_limit() always answers, so this
551
+ # is the bare-built widget and the pre-batch-119 callers that
552
+ # pass four arguments. The old shape exactly, rather than a
553
+ # blank scale, because a trigger is still better than nothing.
554
+ scale = f"/{_k(ceiling)}{mark}"
555
+ else:
556
+ scale = ""
345
557
  # `system` is the harness-talking-about-itself role -- the right
346
558
  # meaning for a usage line, and the palette route the batch-26
347
559
  # guard test demands (it caught this line as a literal within one
348
560
  # commit of the widget existing).
349
- self.update(Text(f"usage · ctx {_k(ctx)}{scale} · billed {_k(billed)}",
350
- style=self._styles().get("system", "")))
561
+ self.update(as_content(
562
+ Text(f"usage · ctx {_k(ctx)}{scale} · billed {_k(billed)}",
563
+ style=self._styles().get("system", ""))))
351
564
 
352
565
 
353
566
  class GoalBanner(Static):
@@ -378,7 +591,7 @@ class GoalBanner(Static):
378
591
  # is the second place a weight would be decided. Guarded still,
379
592
  # because a bare-built widget has no styles dict at all.
380
593
  style = self._styles().get("warning", "") or "bold"
381
- self.update(Text(f"goal {self.goal}", style=style))
594
+ self.update(as_content(Text(f"goal {self.goal}", style=style)))
382
595
  else:
383
596
  self.display = False
384
597
  self.update("")
@@ -409,7 +622,9 @@ class TodoPanel(Static):
409
622
 
410
623
  # A window, for ResearchProgress's reason: a Static does not scroll
411
624
  # itself to the bottom, so an unbounded list would push the newest item
412
- # out of view -- the opposite of the problem being solved.
625
+ # out of view -- the opposite of the problem being solved. The window is
626
+ # the ONLY bound since batch 59; the `max-height` beside it in the
627
+ # stylesheet was clipping, not scrolling.
413
628
  ROWS = 12
414
629
 
415
630
  todos = reactive(None, always_update=True)
@@ -456,7 +671,650 @@ class TodoPanel(Static):
456
671
  body.append(f"(+{len(items) - self.ROWS} earlier)\n",
457
672
  styles.get("system", ""))
458
673
  self.display = True
459
- self.update(body)
674
+ self.update(as_content(body))
675
+
676
+
677
+ #: How often the viewer re-reads a thread whose run is still going.
678
+ #: A second is slow enough to cost nothing on a database this size and
679
+ #: fast enough that watching a subagent work does not feel like
680
+ #: refreshing a page. The timer only exists while the viewed run is
681
+ #: live, so an idle session pays nothing.
682
+ THREAD_VIEW_POLL_S = 1.0
683
+
684
+ #: Between crumb segments. A single glyph, so the trail reads as one
685
+ #: line rather than a path someone could mistake for a filename.
686
+ CRUMB_SEPARATOR = " \u203a "
687
+
688
+
689
+ def meta_style(style, key: str, value):
690
+ """`style`, carrying `value` under `key` as click metadata.
691
+
692
+ The mechanism half of `armed_style`, split out by ROADMAP_v3 §49
693
+ (SS14) when the session panel needed the same thing with a different
694
+ key. Two keys rather than one, because the click handlers on the
695
+ other side ask different questions of the answer -- see
696
+ `Transcript.on_click`, which has kept `url` and a pane target apart
697
+ since batch 58 for exactly this reason.
698
+ """
699
+ if value is None:
700
+ return style
701
+ return Style.parse(style or "") + Style(meta={key: str(value)})
702
+
703
+
704
+ def armed_style(style, thread_id):
705
+ """`style`, carrying `thread_id` as click metadata (§47).
706
+
707
+ Returns the bare style unchanged when there is no thread, so a run
708
+ whose thread does not exist yet -- the window between `enter` and
709
+ `bind` -- draws identically and simply answers nothing when
710
+ clicked. Arming it anyway and failing on the click would be a lie
711
+ told to save nobody any time.
712
+
713
+ ONE FUNCTION for the panel and the crumb, because they are the same
714
+ affordance in two places and a second copy is how the two would
715
+ come to disagree about what a click reads.
716
+
717
+ `str()` because a thread id is a UUID and metadata crosses into a
718
+ handler that looks it up as text.
719
+ """
720
+ return meta_style(style, "agent_thread", thread_id)
721
+
722
+
723
+ class CallSelected(Message):
724
+ """Someone ctrl+clicked a tool line that opens something (§47,
725
+ widened by ROADMAP_v3 §49 SS14).
726
+
727
+ Carries the CALL id, not a thread or a session id, because the
728
+ transcript does not have one: the line is drawn when the call
729
+ starts, and neither the child's thread nor the session's final
730
+ state exists yet. Resolution happens at PRESS time in the app,
731
+ which is what lets a line drawn before its run existed still open
732
+ it.
733
+
734
+ `kind` is `OPENS_THREAD` or `OPENS_SESSION`, as the registry
735
+ answered at draw time. IT TRAVELS WITH THE ID rather than being
736
+ re-derived from the tool name here, because the transcript does not
737
+ keep the tool name either -- a line is text and metadata by the
738
+ time anyone can click it -- and asking again on the other side
739
+ would be the second copy §47 spent a declaration to avoid.
740
+
741
+ This was `SpawnSelected` until batch 98, when a second kind of
742
+ target made the name a lie.
743
+ """
744
+
745
+ def __init__(self, kind: str, call_id: str) -> None:
746
+ self.kind = kind
747
+ self.call_id = call_id
748
+ super().__init__()
749
+
750
+
751
+ class SessionSelected(Message):
752
+ """Someone clicked a row of the session panel (ROADMAP_v3 §49,
753
+ SS14).
754
+
755
+ Carries the SESSION id directly, and that is the difference from
756
+ `CallSelected`: the panel draws only sessions that exist, so there
757
+ is nothing to resolve later. The same split `ThreadSelected` and
758
+ `SpawnSelected` have had since §47, one subject over.
759
+ """
760
+
761
+ def __init__(self, session_id: str) -> None:
762
+ self.session_id = session_id
763
+ super().__init__()
764
+
765
+
766
+ class ThreadSelected(Message):
767
+ """Someone clicked a row that names a thread (§47).
768
+
769
+ A MESSAGE, not a call into the app. The panel and the crumb know
770
+ which thread a row is about and nothing else -- what opening one
771
+ means is the app's question, and a widget reaching into `self.app`
772
+ to answer it would put half of that decision here.
773
+
774
+ Carries the id as TEXT, because that is what came back out of style
775
+ metadata; the app parses it once, where it also decides what an
776
+ unparseable one means.
777
+ """
778
+
779
+ def __init__(self, thread_id: str) -> None:
780
+ self.thread_id = thread_id
781
+ super().__init__()
782
+
783
+
784
+ def _clicked_meta(widget, event, key: str):
785
+ """The value stored under `key` at a click's position, or None.
786
+
787
+ METADATA, NEVER ARITHMETIC. Computing a row index from `event.y`
788
+ would need a second copy of the widget's layout, and that copy
789
+ would already be wrong: `#agent-panel` has `padding-top: 1`, so the
790
+ Nth content line sits at y = N+1. `get_style_at` asks the widget
791
+ that drew the row, which cannot disagree with itself.
792
+ """
793
+ style = widget.get_style_at(event.x, event.y)
794
+ return (getattr(style, "meta", None) or {}).get(key)
795
+
796
+
797
+ def _clicked_thread(widget, event):
798
+ """The thread id under a click, or None (§47)."""
799
+ return _clicked_meta(widget, event, "agent_thread")
800
+
801
+
802
+ @dataclass(frozen=True)
803
+ class AgentRow:
804
+ """One row of the agent panel: a run, and where to find it (§47).
805
+
806
+ Batch 59 drew rows from `(name, depth)` tuples, which cannot name a
807
+ RUN -- two spawns of `explore` at one depth produce the same tuple,
808
+ which is why the sink had to remove rows by last match and hope.
809
+
810
+ `thread_id` is None between `enter` and `bind`: the span opens
811
+ before its run creates a thread, so for the first instants a row
812
+ describes a run that has no address yet. An unbound row simply
813
+ carries no metadata, which is the honest drawing of "there is
814
+ nothing to open yet" -- and the window is short enough that the
815
+ alternative, arming it and failing on the click, would be a lie
816
+ told to save nobody any time.
817
+
818
+ Lives here rather than in tui/app.py because the panel is what
819
+ draws it and app.py already imports this module; the reverse would
820
+ close an import cycle.
821
+ """
822
+ name: str
823
+ depth: int
824
+ span_id: str = ""
825
+ thread_id: object = None
826
+ # §47. WHICH tool call started this run, so the app can pair the
827
+ # transcript's `▸ spawn_subagent` line with the thread bound to
828
+ # this row -- and the line becomes openable while the run is
829
+ # still going, rather than only once its result comes back.
830
+ call_id: object = None
831
+ # §47 slice 8. WHOSE child this run is, carried from AgentSpan so the
832
+ # panel can order rows by lineage instead of by arrival.
833
+ #
834
+ # It was not needed while one agent ran at a time: a stack arrives in
835
+ # the only order it can be in, so indenting by depth drew the chain
836
+ # correctly for free. With peers it does not. Two children of one turn
837
+ # each spawning a grandchild can arrive A, B, A's child, B's child --
838
+ # and depth alone then draws A's child hanging off B, which is a
839
+ # LINEAGE THE PANEL INVENTED. Wrong rather than missing, which is the
840
+ # harder kind to notice.
841
+ parent_id: object = None
842
+
843
+
844
+ def lineage_rows(rows) -> list:
845
+ """`[(row, level)]` depth-first, every child immediately under its
846
+ own parent, at the column its own lineage puts it in.
847
+
848
+ §47 SLICE 8. The panel indents, so what sits ABOVE a row is what a
849
+ reader takes to be its parent. While one agent ran at a time arrival
850
+ order guaranteed that reading: a stack can only arrive
851
+ outermost-first. Peers break it -- two children of one turn each
852
+ spawning a grandchild can arrive A, B, A's child, B's child, and
853
+ drawing that in order puts A's child under B. The panel would be
854
+ inventing a lineage, which is worse than omitting one.
855
+
856
+ THE LEVEL IS THE DEEPER OF THE WALK AND `AgentRow.depth`, which are
857
+ two different questions however often they agree. `depth` is
858
+ ToolContext.subagent_depth -- the number C3 BOUNDS, about how many
859
+ spawns deep a run is. The walk is where the row sits in the parent
860
+ chain THIS stack contains. Each is a lower bound on how nested the run
861
+ is, so the honest column is the larger, and the two ways they part are
862
+ both real:
863
+
864
+ * The walk knows more where a span added a display level without
865
+ adding a spawn level. A research pass opens its span at
866
+ `context_depth + 1` and hands the same context down, so a subagent
867
+ it spawns reports depth 1 as well and drew level with its own
868
+ parent; `/init`'s initializer is the same shape. Taking the walk
869
+ fixes every instance at once and leaves the spawn bound alone --
870
+ bumping the pass's context would have spent one level of what a
871
+ pass may spawn on a rendering fix.
872
+ * The row knows more where its parent is not in the stack at all.
873
+ `parent_id` is None for a genuine top-level span AND for a row
874
+ that never recorded one, and a depth above 1 is what tells them
875
+ apart, since a run two spawns deep has a parent by construction.
876
+
877
+ A top-level span is level 1, so the ordinary case draws exactly where
878
+ it drew before: a chat turn's spawn at depth 1 is also at level 1.
879
+
880
+ Ordered here rather than sorted in the sink for the reason the sink
881
+ keeps its own stack: enter/exit pairing is the sink's business and
882
+ what the rows MEAN on screen is this widget's. It is also why this
883
+ takes rows and returns them rather than mutating anything. PUBLIC,
884
+ unlike the module's other helpers, because two surfaces draw this
885
+ same list -- the panel and §47's ctrl+g picker, which is a screen
886
+ rather than a widget. The picker indented by `depth` in ARRIVAL order
887
+ and invented the lineage this function exists to prevent, in the one
888
+ case slice 8 made ordinary.
889
+
890
+ ORPHANS ARE DRAWN, at the end. A row whose parent is not in the stack
891
+ cannot happen through `span()` -- a child's span opens inside its
892
+ parent's frame, so parents always outlive children -- so this is the
893
+ defensive half, covering a hand-built row and a stack observed
894
+ mid-tear-down. Dropping them would make the panel lie by omission
895
+ instead.
896
+
897
+ The `seen` set is what makes a cycle terminate rather than hang, which
898
+ is the same guard ThreadCrumb's walk carries and for the same reason:
899
+ a row's parent is data, and data can be wrong in ways that recursion
900
+ turns into a wedged UI rather than a visible mistake.
901
+
902
+ IT KEYS ON ROW IDENTITY, NOT ON `span_id`, and that is not fussiness.
903
+ `AgentRow.span_id` defaults to `""`, so every hand-built row shares
904
+ one -- and a set of span ids would treat the second such row as
905
+ already drawn and silently DROP it. Live rows always carry a real id,
906
+ so this would have been invisible in the app and wrong in every test
907
+ that builds rows directly, which `tests/BREAKING_CHANGES.md` already
908
+ warns is a thing tests here do. Identity is unique by construction,
909
+ which is the property the guard actually needs.
910
+ """
911
+ by_parent: dict = {}
912
+ for row in rows:
913
+ by_parent.setdefault(row.parent_id, []).append(row)
914
+
915
+ seen: set = set()
916
+ ordered: list = []
917
+
918
+ def walk(parent, level: int) -> None:
919
+ for row in by_parent.get(parent, []):
920
+ if id(row) in seen:
921
+ continue
922
+ seen.add(id(row))
923
+ # THE DEEPER OF THE TWO ANSWERS, because both are LOWER BOUNDS
924
+ # on how nested this run is and neither may be under-drawn.
925
+ # The walk knows the lineage this stack contains; the row knows
926
+ # how many spawns deep it is. Where they differ, one of them is
927
+ # missing something:
928
+ #
929
+ # level > depth -- a span that added a display level without
930
+ # adding a spawn level. A research pass and the subagent it
931
+ # spawned both report depth 1, so only the walk tells them
932
+ # apart.
933
+ # depth > level -- a run whose parent is not in this stack.
934
+ # `parent_id` is None both for a genuine top-level span and
935
+ # for a row that never recorded one, and a depth above 1
936
+ # settles which: a run two spawns deep HAS a parent, so an
937
+ # absent one is missing rather than nonexistent. That is
938
+ # the orphan case below reached through a null instead of a
939
+ # dangling id, and drawing it at level 1 would claim it is
940
+ # a child of the conversation.
941
+ drawn = max(level, row.depth)
942
+ ordered.append((row, drawn))
943
+ # Only a row with a real id can have children. Recursing on
944
+ # `""` would look up the bucket every defaulted row shares.
945
+ #
946
+ # ONE IN FROM WHERE THE PARENT WAS DRAWN, not from the walk's
947
+ # own count, so a chain always steps in. Pass the walk level
948
+ # instead and a parent bumped out by its own depth ends up
949
+ # level with its child, which is the invented lineage this
950
+ # function exists to prevent, one row along.
951
+ if row.span_id:
952
+ walk(row.span_id, drawn + 1)
953
+
954
+ # Depth is bounded by SUBAGENT_MAX_DEPTH, so the recursion is too.
955
+ walk(None, 1)
956
+ for row in rows:
957
+ if id(row) not in seen:
958
+ seen.add(id(row))
959
+ # An ORPHAN has no walk position, so its own depth is the only
960
+ # answer available -- floored at 1 for the reason the panel
961
+ # floors it, and the honest drawing of "somewhere below the
962
+ # root, we cannot say where".
963
+ ordered.append((row, max(row.depth, 1)))
964
+ return ordered
965
+
966
+
967
+ class AgentPanel(Static):
968
+ """Who is running, and how deep (batch 59).
969
+
970
+ A TREE SINCE §47 SLICE 8, AND IT USED TO BE A STACK. This docstring
971
+ said "A STACK, NEVER A LIST OF PEERS, and that is a fact about the
972
+ harness rather than a rendering choice", because it was: core/loop.py
973
+ dispatched tool calls in a plain `for` loop and spawn_subagent BLOCKED
974
+ on the child run, so there was never a second agent alongside the
975
+ first. It finished "a flat list would claim a concurrency this harness
976
+ does not have". NA9 gave it that concurrency, so both sentences went.
977
+
978
+ What replaces them is smaller than it sounds, because slice 2 built the
979
+ data model as a tree ON PURPOSE against this day. Rows still indent by
980
+ `depth`, bounded by config.SUBAGENT_MAX_DEPTH, and peers at one depth
981
+ now legitimately share a column. The one thing that had to change is
982
+ the ORDER: arrival order and lineage order were the same thing for a
983
+ stack and are not for a tree. See `lineage_rows`.
984
+
985
+ Fed from core/agent_activity.py through app.py, never polled -- the
986
+ same split TodoPanel keeps: the sink says when, and this widget holds
987
+ no authoritative copy of anything.
988
+
989
+ Hidden when it has nothing to say, GoalBanner-style: the sidebar is
990
+ twenty columns wide and its rows are contested, so `default` with an
991
+ empty stack costs nothing rather than a permanent row saying so.
992
+
993
+ §47 ARMS EACH ROW WITH THE THREAD IT STANDS FOR, as style metadata
994
+ -- the mechanism batch 58 built for URLs, reused rather than
995
+ re-derived. Metadata rather than arithmetic on the click's y: the
996
+ row heights, the blank line and the header are this widget's own
997
+ layout, and a second copy of them at the click site would be free
998
+ to disagree with the first.
999
+ """
1000
+
1001
+ # 22-column box, less a border column and a padding column each side.
1002
+ # MEASURED, not derived from the `width: 22` in the stylesheet: the
1003
+ # border is easy to forget and the answer is 19, dropping to 18 while
1004
+ # the sidebar's scrollbar is up. The narrow case is the one to lay out
1005
+ # against, since a row that fits 18 fits 19.
1006
+ WIDTH = 18
1007
+
1008
+ # Two spaces per level, so depth 2 costs four columns of the eighteen.
1009
+ INDENT = 2
1010
+
1011
+ def __init__(self, **kwargs):
1012
+ super().__init__(**kwargs)
1013
+ self._agent = None
1014
+ self._stack: list = []
1015
+ self._root = None
1016
+ # Explicit, for TodoPanel's reason: a widget that renders nothing
1017
+ # yet must not be a visible empty box before its first update.
1018
+ self.display = False
1019
+
1020
+ def _styles(self) -> dict:
1021
+ try:
1022
+ app = self.app
1023
+ except Exception: # noqa: BLE001 -- see Transcript._styles
1024
+ return {}
1025
+ return themes.styles_for(app)
1026
+
1027
+ def show(self, agent_name, stack, root_thread=None) -> None:
1028
+ """Draw the active agent and the spans currently open under it.
1029
+
1030
+ `agent_name` is None when no /agent switch is active. `stack` is a
1031
+ list of AgentRow, outermost first. `root_thread` is the id of the
1032
+ conversation the root row stands for, or None before there is
1033
+ one -- a session that has not had a turn yet has no thread, and
1034
+ the panel must not be what creates one.
1035
+ """
1036
+ self._agent = agent_name
1037
+ self._stack = list(stack)
1038
+ self._root = root_thread
1039
+ self._redraw()
1040
+
1041
+ def restyle(self) -> None:
1042
+ """Re-render under the current theme (#183), like ResearchProgress."""
1043
+ self._redraw()
1044
+
1045
+ #: Shared with SessionPanel, which fits the same box to the same
1046
+ #: width -- a staticmethod on the class that measured the box,
1047
+ #: rather than a second copy of the ellipsis rule.
1048
+ @staticmethod
1049
+ def _fit(text: str, width: int) -> str:
1050
+ """Truncate to `width` cells, with an ellipsis when it bites.
1051
+
1052
+ Appended by hand rather than through `Text.truncate()`, which
1053
+ batch 55 measured doing nothing on a wrapped line -- and the rows
1054
+ here are `no_wrap`, so an overlong one would be cropped invisibly
1055
+ instead. `pipeline-reviewer` is seventeen characters and reaches
1056
+ this at every depth below the root.
1057
+
1058
+ Cells, which the docstring always said and `len` did not measure
1059
+ (#224, batch 214): ten double-width characters passed an 18-cell
1060
+ box whole and drew 20 cells. A glyph that would straddle the
1061
+ ellipsis is dropped rather than split.
1062
+ """
1063
+ if width <= 0:
1064
+ return ""
1065
+ if cell_len(text) <= width:
1066
+ return text
1067
+ if width == 1:
1068
+ return "\u2026"
1069
+ kept, cells = [], 0
1070
+ for char in text:
1071
+ cells += cell_len(char)
1072
+ if cells > width - 1:
1073
+ break
1074
+ kept.append(char)
1075
+ return "".join(kept) + "\u2026"
1076
+
1077
+ #: Shared with ThreadCrumb -- see armed_style.
1078
+ _armed = staticmethod(armed_style)
1079
+
1080
+ def on_click(self, event) -> None:
1081
+ """Open the run this row is about.
1082
+
1083
+ A PLAIN CLICK, unlike the transcript's ctrl+click, and the
1084
+ asymmetry is caused by text selection existing in one place and
1085
+ not the other. A sidebar row is a control; dragging across it
1086
+ selects nothing, so there is no gesture to dodge.
1087
+
1088
+ A click on a row with no thread does nothing at all -- not even
1089
+ a message -- so an unbound run and the header are the same
1090
+ silence.
1091
+ """
1092
+ thread_id = _clicked_thread(self, event)
1093
+ if thread_id:
1094
+ self.post_message(ThreadSelected(thread_id))
1095
+
1096
+ def _redraw(self) -> None:
1097
+ if self._agent is None and not self._stack:
1098
+ self.display = False
1099
+ self.update("")
1100
+ return
1101
+
1102
+ styles = self._styles()
1103
+ body = Text()
1104
+ body.append("agent\n\n")
1105
+ # The root row is drawn whenever anything is: the indented rows
1106
+ # below hang off it, and a spawn under no /agent switch would
1107
+ # otherwise start at column two with nothing above it.
1108
+ # `assistant_label`, not a raw "accent" key -- role_styles has no
1109
+ # such role, so that lookup would silently return "" and /theme
1110
+ # would never reach this row. Bold accent is the IDENTITY role,
1111
+ # which is exactly what "which agent is answering" is; the spans
1112
+ # below take plain `tool` accent, so the root reads as the heavier
1113
+ # of the two without introducing a second hue.
1114
+ body.append(
1115
+ self._fit(self._agent or "default", self.WIDTH) + "\n",
1116
+ # The root row stands for the conversation itself, so it is
1117
+ # armed like any other -- "back to the main agent" is then a
1118
+ # click rather than a special case somebody has to remember.
1119
+ self._armed(styles.get("assistant_label", ""), self._root))
1120
+ for row, level in lineage_rows(self._stack):
1121
+ # THE WALK'S LEVEL, not `row.depth`. The two agree for a chat
1122
+ # turn's spawns and part company wherever a span adds a display
1123
+ # level without adding a spawn level -- a research pass and its
1124
+ # own subagent both report depth 1, and drawing that put a
1125
+ # child level with its parent. See `lineage_rows`.
1126
+ #
1127
+ # It is never 0, so a span cannot collide with the root row.
1128
+ # That floor USED to be spelled `max(depth, 1)` and its reason
1129
+ # USED to be "two rows at column zero would say two agents are
1130
+ # running, which is the one thing this panel must never
1131
+ # claim". Slice 8 makes that claim true, and peers sharing a
1132
+ # column is now the point. What survives is the narrower half:
1133
+ # the root row stands for the CONVERSATION, and a span drawn
1134
+ # level with it would read as a second conversation rather
1135
+ # than as a run inside this one.
1136
+ pad = " " * (self.INDENT * level)
1137
+ room = self.WIDTH - len(pad) - 2 # the marker and its space
1138
+ body.append(f"{pad}{MARK_RUNNING} {self._fit(row.name, room)}\n",
1139
+ self._armed(styles.get("tool", ""), row.thread_id))
1140
+ # Batch 55's reason -- a row this widget already sized must not be
1141
+ # re-wrapped by the Static underneath it, and a miscalculation
1142
+ # should clip visibly rather than reflow invisibly -- but the rule
1143
+ # is `text-wrap: nowrap` / `text-overflow: clip` on `#agent-panel`
1144
+ # now. `Content` carries neither flag and `from_rich_text` drops
1145
+ # both, so setting them on the Text stopped meaning anything the
1146
+ # moment the pin moved: silently, and on the widget least able to
1147
+ # afford a reflow. See `as_content`.
1148
+ self.display = True
1149
+ self.update(as_content(body))
1150
+
1151
+ class SessionPanel(Static):
1152
+ """What is running in the background, and nothing else (§49, SS14).
1153
+
1154
+ LIVE SESSIONS ONLY, which is the decision rather than a consequence
1155
+ of how it is fed. A finished session is still readable -- SS14 puts
1156
+ that on the tool-call line that started it, resolved at press time
1157
+ the way §47 resolves a spawn -- so listing finished ones here would
1158
+ spend contested sidebar rows on a second route to the same pane,
1159
+ and would grow without bound in a session that starts many.
1160
+
1161
+ PROCESS-WIDE, like AgentPanel above it and like ctrl+b's picker.
1162
+ SS11 scopes the five TOOLS to the caller's own thread, which is a
1163
+ rule about what the model may touch; what the person may SEE is a
1164
+ different question, and a panel that hid a subagent's sessions
1165
+ would disagree with the kill picker about what is running.
1166
+
1167
+ Fed from core/shell_sessions.py's SessionActivity through app.py,
1168
+ never polled -- TodoPanel's split, and AgentPanel's: the sink says
1169
+ when, and this widget holds no authoritative copy of anything. It
1170
+ is handed ROWS ALREADY REDACTED AND ALREADY FITTED TO A LABEL, for
1171
+ SessionKillScreen's reason (batch 97): a command reaches a display
1172
+ surface only through check_output_policy, and keeping that call in
1173
+ app.py means this file never holds an unredacted one.
1174
+
1175
+ Hidden when nothing is running, GoalBanner-style, which is almost
1176
+ always -- the sidebar is twenty columns wide and its rows are
1177
+ contested.
1178
+ """
1179
+
1180
+ #: AgentPanel's, measured the same way and for the same box.
1181
+ WIDTH = 18
1182
+
1183
+ def __init__(self, **kwargs):
1184
+ super().__init__(**kwargs)
1185
+ self._rows: list = []
1186
+ # TodoPanel's reason: a widget that renders nothing yet must not
1187
+ # be a visible empty box before its first update.
1188
+ self.display = False
1189
+
1190
+ def _styles(self) -> dict:
1191
+ try:
1192
+ app = self.app
1193
+ except Exception: # noqa: BLE001 -- see Transcript._styles
1194
+ return {}
1195
+ return themes.styles_for(app)
1196
+
1197
+ def show(self, rows) -> None:
1198
+ """Draw the live sessions. `rows` is [{"id", "label"}], already
1199
+ redacted, in the order they started.
1200
+
1201
+ An empty list hides the widget, which is how the panel closes
1202
+ without a second method meaning the same thing (ThreadCrumb's
1203
+ rule).
1204
+ """
1205
+ self._rows = list(rows)
1206
+ self._redraw()
1207
+
1208
+ def restyle(self) -> None:
1209
+ """Re-render under the current theme (#183), like AgentPanel."""
1210
+ self._redraw()
1211
+
1212
+ def on_click(self, event) -> None:
1213
+ """Open the session this row is about.
1214
+
1215
+ A PLAIN CLICK, for AgentPanel's reason: a sidebar row is a
1216
+ control, and dragging across it selects nothing, so there is no
1217
+ text-selection gesture to dodge here the way the transcript's
1218
+ ctrl+click dodges one.
1219
+ """
1220
+ session_id = _clicked_meta(self, event, "session")
1221
+ if session_id:
1222
+ self.post_message(SessionSelected(session_id))
1223
+
1224
+ def _redraw(self) -> None:
1225
+ if not self._rows:
1226
+ self.display = False
1227
+ self.update("")
1228
+ return
1229
+
1230
+ styles = self._styles()
1231
+ body = Text()
1232
+ body.append("sessions\n\n")
1233
+ for row in self._rows:
1234
+ label = AgentPanel._fit(row.get("label", ""), self.WIDTH - 2)
1235
+ body.append(
1236
+ f"{MARK_RUNNING} {label}\n",
1237
+ meta_style(styles.get("tool", ""), "session", row.get("id")))
1238
+ # AgentPanel's note: the nowrap/clip rule lives on the widget in
1239
+ # app.tcss, because `Content` carries neither flag.
1240
+ self.display = True
1241
+ self.update(as_content(body))
1242
+
1243
+
1244
+ class ThreadCrumb(Static):
1245
+ """Where you are, and every step back out (§47).
1246
+
1247
+ `chat \u203a explore \u203a review`, each segment but the last armed
1248
+ with its own thread. The viewer needs a header row anyway to say
1249
+ what is being looked at, so making it the LINEAGE costs nothing and
1250
+ turns "up one level" into a visible click rather than hidden
1251
+ history. It is honest because the parent link is stored now: this
1252
+ is read from the database, not reconstructed from the order things
1253
+ were opened in.
1254
+
1255
+ THE LAST SEGMENT IS NOT ARMED. It is where you already are, and a
1256
+ control that does nothing is worse than one that is plainly inert.
1257
+
1258
+ Hidden when empty, GoalBanner-style, so the live conversation costs
1259
+ no row for a trail it does not need.
1260
+ """
1261
+
1262
+ def __init__(self, **kwargs):
1263
+ super().__init__(**kwargs)
1264
+ self._steps: list = []
1265
+ self.display = False
1266
+
1267
+ def _styles(self) -> dict:
1268
+ try:
1269
+ app = self.app
1270
+ except Exception: # noqa: BLE001 -- see Transcript._styles
1271
+ return {}
1272
+ return themes.styles_for(app)
1273
+
1274
+ def show(self, steps) -> None:
1275
+ """Draw the trail. `steps` is [(label, thread_id)], root first.
1276
+
1277
+ An empty list hides the widget, which is how the viewer closes
1278
+ its header without a second method meaning the same thing.
1279
+ """
1280
+ self._steps = list(steps)
1281
+ self._redraw()
1282
+
1283
+ def restyle(self) -> None:
1284
+ """Re-render under the current theme (#183), like AgentPanel."""
1285
+ self._redraw()
1286
+
1287
+ def on_click(self, event) -> None:
1288
+ thread_id = _clicked_thread(self, event)
1289
+ if thread_id:
1290
+ self.post_message(ThreadSelected(thread_id))
1291
+
1292
+ def _redraw(self) -> None:
1293
+ if not self._steps:
1294
+ self.display = False
1295
+ self.update("")
1296
+ return
1297
+
1298
+ styles = self._styles()
1299
+ body = Text()
1300
+ for index, (label, thread_id) in enumerate(self._steps):
1301
+ if index:
1302
+ body.append(CRUMB_SEPARATOR, styles.get("system", ""))
1303
+ here = index == len(self._steps) - 1
1304
+ if here:
1305
+ body.append(label, styles.get("assistant_label", ""))
1306
+ else:
1307
+ body.append(label, armed_style(styles.get("tool", ""),
1308
+ thread_id))
1309
+ body.append(" read-only \u2014 esc to go back",
1310
+ styles.get("system", ""))
1311
+ # One line, elided rather than wrapped: a trail that reflowed
1312
+ # would take a second row from the transcript below it, and the
1313
+ # segment that matters most is the one you are standing on. The
1314
+ # rule is on `#thread-crumb` in app.tcss, for `as_content`'s
1315
+ # reason.
1316
+ self.display = True
1317
+ self.update(as_content(body))
460
1318
 
461
1319
 
462
1320
  class ResearchProgress(Static):
@@ -488,10 +1346,15 @@ class ResearchProgress(Static):
488
1346
 
489
1347
  # §26. Code stages roughly double the row count, so the §22 window of 8
490
1348
  # 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.
1349
+ # WINDOW rather than the whole list: a Static does not scroll itself to
1350
+ # the bottom, so an unbounded list would leave the newest row out of
1351
+ # view -- the opposite of the problem being fixed.
1352
+ #
1353
+ # This used to say "#research-progress scrolls", and it never did
1354
+ # (batch 59). The panel carried `max-height` + `overflow-y: auto`,
1355
+ # which on a Static clips rather than scrolls -- EP3's trap, measured
1356
+ # here at one lost row. The SIDEBAR scrolls now; this window is what
1357
+ # keeps the newest row near the top of what it reveals.
495
1358
  ROWS = 16
496
1359
 
497
1360
  def __init__(self, **kwargs):
@@ -511,6 +1374,36 @@ class ResearchProgress(Static):
511
1374
  self.display = True
512
1375
  self._redraw()
513
1376
 
1377
+ def clear_for_thread(self) -> None:
1378
+ """Drop the run and hide, because the session changed threads.
1379
+
1380
+ THE ONE-WAY REVEAL ABOVE IS DELIBERATE and stays (TodoPanel is the
1381
+ panel that hides again, for the reason its own tests record): a
1382
+ finished run's shape is worth reading while its report is on
1383
+ screen. That argument is about the thread the run belongs to, and
1384
+ it stops at the thread boundary.
1385
+
1386
+ This panel was the last piece of per-thread state that survived a
1387
+ switch. `switch_to_thread` and `/new` already clear `_last_run`,
1388
+ `_live_claims` and the transcript on the stated rule that a stale
1389
+ panel pointing at the wrong thread is WRONG where a blank one is
1390
+ merely unhelpful -- and the research panel, which is the most
1391
+ panel-shaped thing in the sidebar, was missed at both sites. A
1392
+ failed run stayed on screen under a thread that never ran it, and
1393
+ so did a successful one; nothing distinguished them, because
1394
+ nothing cleared either.
1395
+
1396
+ CLEARED rather than reloaded, and that is forced rather than
1397
+ chosen: a `PipelineRun` records its own pass threads and has no
1398
+ column naming the chat thread that launched it, so "this thread's
1399
+ run" is not a question the database can answer. Clearing is also
1400
+ what makes the sidebar agree with `/claims`, which already answers
1401
+ "No research run in this session yet" after a switch.
1402
+ """
1403
+ self.reset()
1404
+ self.display = False
1405
+ self._redraw()
1406
+
514
1407
  def pass_started(self, pass_id: str) -> None:
515
1408
  self._passes.append([pass_id, False, False, False, 0, 0])
516
1409
  self._redraw()
@@ -626,7 +1519,668 @@ class ResearchProgress(Static):
626
1519
  body.append(f" {label} {count}\n", styles.get(tier, ""))
627
1520
  if self._retries:
628
1521
  body.append(f"{self._retries} revision(s)\n")
629
- self.update(body)
1522
+ self.update(as_content(body))
1523
+
1524
+
1525
+ class SlashSuggest(Static):
1526
+ """The commands you could be typing, above the prompt (batch 55).
1527
+
1528
+ Twenty-six slash commands were reachable only by remembering that
1529
+ `/help` exists -- the mount banner says so once and then scrolls away.
1530
+ This lists the ones whose name starts with what has been typed, and
1531
+ `tui/commands.py`'s `matching()` is what it lists, so the panel and
1532
+ `/help` read one registry and cannot drift.
1533
+
1534
+ A widget in `#main`, NOT a screen. `#prompt` is `dock: bottom`, so a
1535
+ sibling yielded after the transcript lands directly above it -- the
1536
+ ThinkingIndicator/TodoPanel shape, hidden until it has something to
1537
+ say, `height: auto` so it costs nothing while hidden.
1538
+
1539
+ Three things here are load-bearing.
1540
+
1541
+ **It owns the selection, not the prompt.** How many entries fit is a
1542
+ function of the RENDERED WIDTH, and only the thing that draws knows
1543
+ that. Split the two and the prompt can highlight a sixth entry the
1544
+ panel had no room for -- an invisible selection that `enter` would
1545
+ then complete. `chosen` and `move()` are the whole interface.
1546
+
1547
+ **The budget is on ROWS.** At most SUGGEST_MAX_ENTRIES entries and at
1548
+ most SUGGEST_MAX_ROWS rows, whichever binds first, stopping at the
1549
+ first entry that would overflow rather than skipping it -- a list that
1550
+ skipped would no longer be alphabetical and the order would read as
1551
+ arbitrary. At 80 columns most entries wrap to two rows, so the row cap
1552
+ is usually the one that bites: `/` shows four.
1553
+
1554
+ **The window SLIDES** (batch 56). `_first` is where it starts and it is
1555
+ derived, never stored beside the selection: `move()` picks a command
1556
+ out of all the matches and `_budget()` scrolls the window the least
1557
+ it can to keep that command on screen. Batch 55 wrapped at the last
1558
+ DRAWN entry instead, which left twenty-two of twenty-six commands
1559
+ unreachable by keyboard under a panel whose own title said twenty-six.
1560
+
1561
+ Because entries are one or two rows, a step down drops one entry from
1562
+ the top and gains one at the bottom -- or drops one and gains two. That
1563
+ is not a rule; it is the row budget refilling, and it is why the window
1564
+ changes SIZE as well as contents while it scrolls (measured: four
1565
+ entries over seven rows at the top of the list, four over eight one
1566
+ step later, five over seven in the middle). Two things follow, and
1567
+ neither is optional: `move()` refreshes with `layout=True`, and it is
1568
+ reached through app.py rather than called directly -- a panel that
1569
+ resizes takes rows from the transcript, and the scroll position that
1570
+ has to survive that is only knowable before the relayout.
1571
+
1572
+ **A Static RE-WRAPS what you already wrapped.** The first draft wrapped
1573
+ each entry to `width - 2` and then drew continuation lines under a
1574
+ four-space gutter, so a two-line entry rendered as THREE rows, the
1575
+ height arithmetic was wrong by one per entry, and the ellipsis ended up
1576
+ on a row that had already been dropped. Both gutters have to fit inside
1577
+ the wrap width, and the outer Text carries `no_wrap` / `overflow="crop"`
1578
+ so that a miscalculation clips where it can be seen instead of
1579
+ reflowing where it cannot. The pin is a test that no rendered row is
1580
+ wider than the panel.
1581
+
1582
+ A related trap in the same family: `Text.truncate()` on a WRAPPED line
1583
+ does nothing. The overflow is in the lines that were dropped, not in
1584
+ the line that was kept, so the line reads as complete when it is not --
1585
+ the ellipsis has to be appended deliberately.
1586
+
1587
+ **The bottom border says which keys this spends** (batch 62). Four
1588
+ keys change meaning while the panel is open and none of them was
1589
+ written anywhere. Not the TITLE, which the count already holds --
1590
+ at 80 columns the label budget is 52 cells, the count is 25 and the
1591
+ hint is 42, so they cannot share the row. And not the FOOTER:
1592
+ `Screen.active_bindings` drops a binding only on `check_action`
1593
+ returning `is False`, and `tab`/`escape` must return `None` here so
1594
+ they still reach the focus system with the panel shut -- a shown
1595
+ binding would therefore sit in the footer greyed and permanent.
1596
+
1597
+ The hint shortens by STATE first and by width second, and the state
1598
+ half is the title's own rule applied to a control: with one match
1599
+ `move()` wraps to the command it is already on, so `↑↓ move` would
1600
+ advertise a key that does nothing. Parts then drop from the LEFT
1601
+ while the rest overflows, rather than being truncated -- an
1602
+ ellipsised `esc dism…` is furniture, not help. What survives the
1603
+ narrowest terminal is therefore how to get rid of the panel, which
1604
+ is the useful key at a width where the entries are unreadable.
1605
+
1606
+ The highlight is `reverse` rather than a palette role. TodoPanel's
1607
+ caution applies (only the theme-invariant roles are safe across all
1608
+ fourteen themes) and reverse is invariant by construction: it swaps
1609
+ whatever the theme already chose, so it adds no colour for
1610
+ tests/test_themes.py's contrast floors to fail to measure.
1611
+ """
1612
+
1613
+ def __init__(self, **kwargs):
1614
+ super().__init__(**kwargs)
1615
+ # EXPLICIT, TodoPanel's reason: nothing sets a list until the user
1616
+ # types a slash, which on many sessions is never, and a visible
1617
+ # empty box is worse than the thing it advertises.
1618
+ self.display = False
1619
+ self._matches: list = []
1620
+ # An index into _matches, NOT into the window: the window slides to
1621
+ # follow it (batch 56), and _first is where the window starts.
1622
+ self._selected = 0
1623
+ self._first = 0
1624
+ self._width = 0
1625
+ # Per entry, the rendered lines. Computed in get_content_height,
1626
+ # where the width arrives before the first paint.
1627
+ self._groups: list = []
1628
+
1629
+ # -- what the prompt drives ---------------------------------------------
1630
+
1631
+ def offer(self, matches: list, label: str | None = None) -> None:
1632
+ """Replace the list, hiding the panel when it is empty.
1633
+
1634
+ `refresh(layout=True)`, not `update()`: the render is a function of
1635
+ the width, so the panel has to be re-MEASURED, not just repainted.
1636
+ """
1637
+ self._matches = list(matches)
1638
+ self._label = label
1639
+ self._selected = 0
1640
+ self._first = 0
1641
+ self._groups = []
1642
+ self.display = bool(self._matches)
1643
+ self.refresh(layout=True)
1644
+
1645
+ def move(self, delta: int) -> None:
1646
+ """Move the highlight over ALL the matches, wrapping at the ends.
1647
+
1648
+ Over the matches, not over what is on screen (batch 56). Wrapping
1649
+ at the last DRAWN entry left twenty-two of twenty-six commands
1650
+ unreachable by keyboard under a bare slash, on a panel whose own
1651
+ title said there were twenty-six.
1652
+
1653
+ This sets the selection and nothing else. Where the window has to
1654
+ move so the selection is visible is `_budget`'s answer, because it
1655
+ is a function of the WIDTH -- which is the same split the class
1656
+ docstring already turns on.
1657
+
1658
+ `layout=True` is load-bearing rather than tidy. A sliding window
1659
+ changes SIZE as well as contents (measured: four entries over seven
1660
+ rows at the top of the list, four over eight one step later, five
1661
+ over seven in the middle), and a plain `refresh()` leaves the
1662
+ widget measured at its old height with the extra row silently
1663
+ clipped.
1664
+ """
1665
+ self._ensure()
1666
+ if not self._matches:
1667
+ return
1668
+ self._selected = (self._selected + delta) % len(self._matches)
1669
+ self._groups = []
1670
+ self.refresh(layout=True)
1671
+
1672
+ @property
1673
+ def chosen(self):
1674
+ """The highlighted command, or None when nothing is offered."""
1675
+ self._ensure()
1676
+ if not self.display or not self._matches:
1677
+ return None
1678
+ return self._matches[min(self._selected, len(self._matches) - 1)]
1679
+
1680
+ @property
1681
+ def visible(self) -> list:
1682
+ """The commands actually on screen, in order.
1683
+
1684
+ The honest accessor, and it exists because the obvious spelling --
1685
+ `_matches[:shown]` -- quietly assumes a window that starts at zero,
1686
+ which stopped being true the moment the list could scroll.
1687
+ """
1688
+ self._ensure()
1689
+ return self._matches[self._first:self._first + len(self._groups)]
1690
+
1691
+ @property
1692
+ def shown(self) -> int:
1693
+ """How many entries the last measurement had room for."""
1694
+ self._ensure()
1695
+ return len(self._groups)
1696
+
1697
+ def _ensure(self) -> None:
1698
+ """Measure now if a layout pass has not happened yet.
1699
+
1700
+ `offer()` and `move()` clear the groups and the next layout
1701
+ recomputes them, but a key pressed in between -- or a test that
1702
+ offers and asks in one breath -- would otherwise see an empty list
1703
+ and no selection.
1704
+ """
1705
+ if not self._groups and self._matches and self._width:
1706
+ self._budget(self._width)
1707
+
1708
+ # -- measuring -----------------------------------------------------------
1709
+
1710
+ def _entry(self, command, inner: int) -> list:
1711
+ """One command's rendered lines, at most SUGGEST_MAX_LINES of them.
1712
+
1713
+ `/name SEP summary usage`, in that order: the reverse order pushes
1714
+ the DESCRIPTION off the entry for the two commands whose flags are
1715
+ long, and the description is the half this panel exists for. The
1716
+ flags are what truncates.
1717
+ """
1718
+ body = getattr(command, "prefix", "/") + command.name + SUGGEST_SEP + command.summary
1719
+ if command.usage:
1720
+ body += " " + command.usage
1721
+ lines = list(Text(body).wrap(Console(width=inner), inner, no_wrap=False))
1722
+ if len(lines) > SUGGEST_MAX_LINES:
1723
+ lines = lines[:SUGGEST_MAX_LINES]
1724
+ # crop THEN append: truncate(overflow="ellipsis") is a no-op
1725
+ # here, because this line is not the one that overflowed.
1726
+ lines[-1].truncate(max(0, inner - 1), overflow="crop")
1727
+ lines[-1].append(SUGGEST_ELLIPSIS)
1728
+ return lines
1729
+
1730
+ def _fill(self, first: int, inner: int) -> list:
1731
+ """The entries that fit starting at `first`, under both caps."""
1732
+ groups, used = [], 0
1733
+ for command in self._matches[first:first + SUGGEST_MAX_ENTRIES]:
1734
+ lines = self._entry(command, inner)
1735
+ if used + len(lines) > SUGGEST_MAX_ROWS:
1736
+ break
1737
+ groups.append(lines)
1738
+ used += len(lines)
1739
+ return groups
1740
+
1741
+ def _budget(self, width: int) -> None:
1742
+ """Where the window sits, what fits in it, and the title.
1743
+
1744
+ The window is DERIVED from the selection rather than stored beside
1745
+ it, so the two cannot disagree: `move()` says which command is
1746
+ chosen and this says which commands can be seen.
1747
+
1748
+ Scrolling is minimal in both directions -- the window advances only
1749
+ far enough to keep the selection visible, and jumps straight to it
1750
+ going the other way. Because the entries are one or two rows, that
1751
+ is what makes a step down drop one entry and gain one, or drop one
1752
+ and gain TWO: it is the row budget refilling, not a rule of its own.
1753
+
1754
+ The loop terminates because `first` only rises and a single entry
1755
+ is at most SUGGEST_MAX_LINES rows, so `first == self._selected`
1756
+ always yields a window containing the selection. The empty guard is
1757
+ what keeps that true -- with no matches `_fill` returns nothing and
1758
+ the condition could never be met.
1759
+
1760
+ No minimum width: a terminal too narrow to read is still bounded
1761
+ here, because the two-line cap holds whatever the wrap does, so the
1762
+ panel degrades to something short rather than to something
1763
+ unbounded. MIN_WRAP_WIDTH's posture, one line up the same street.
1764
+ """
1765
+ self._width = width
1766
+ if not self._matches:
1767
+ self._groups = []
1768
+ self._first = 0
1769
+ return
1770
+ inner = max(1, width - len(SUGGEST_CONT))
1771
+ if self._selected >= len(self._matches):
1772
+ self._selected = 0
1773
+ first = min(self._first, self._selected)
1774
+ while True:
1775
+ groups = self._fill(first, inner)
1776
+ if self._selected < first + len(groups):
1777
+ break
1778
+ first += 1
1779
+ self._first = first
1780
+ self._groups = groups
1781
+ # #30/M14: a capped list that does not say it is capped reads as
1782
+ # "this is everything". Shown-of-MATCHED rather than shown-of-all,
1783
+ # because "4 of 26" under a typed `/c` would claim twenty-two
1784
+ # candidates that do not exist. Both numbers are counted, never
1785
+ # written down -- register a twenty-seventh command and the bare
1786
+ # `/` title says 27 with no edit here.
1787
+ #
1788
+ # The RANGE appears only once the list can scroll (batch 56). On a
1789
+ # list that fits entirely there is nowhere to be, so "1-1 of 1"
1790
+ # would be noise where "1 of 1" is a fact.
1791
+ if len(groups) == len(self._matches):
1792
+ span = str(len(groups))
1793
+ else:
1794
+ span = f"{first + 1}-{first + len(groups)}"
1795
+ title = f"{span} of {len(self._matches)} · {getattr(self, '_label', None) or '/help for all'}"
1796
+ if self.border_title != title:
1797
+ self.border_title = title
1798
+ # Batch 62. The same honesty rule one row down, applied to a
1799
+ # control instead of to a count: `↑↓ move` is a claim about a
1800
+ # key, and with one match that key does nothing.
1801
+ #
1802
+ # `width - 2` is the border label's budget, MEASURED rather than
1803
+ # reasoned: textual truncates a label at the outer width minus
1804
+ # six, and `border: solid` plus `padding: 0 1` makes the outer
1805
+ # width four more than the one handed here. Change either in
1806
+ # app.tcss and this constant is wrong -- which is why the pilot
1807
+ # test asserts the drawn row carries no ellipsis.
1808
+ #
1809
+ # cell_len, not len: the arrows are East-Asian AMBIGUOUS width,
1810
+ # exactly like the SUGGEST_SEP this panel already ships.
1811
+ parts = list(SUGGEST_HINT_REST)
1812
+ if len(self._matches) > 1:
1813
+ parts.insert(0, SUGGEST_HINT_MOVE)
1814
+ while parts and Text(
1815
+ SUGGEST_HINT_SEP.join(parts)).cell_len > width - 2:
1816
+ parts.pop(0)
1817
+ hint = SUGGEST_HINT_SEP.join(parts) or None
1818
+ # Guarded for the title's reason, and it is not tidiness:
1819
+ # `_BorderTitle.__set__` calls `refresh()` and this runs from
1820
+ # `render()`, so an unguarded assignment schedules a paint from
1821
+ # inside a paint. It converges because the second pass compares
1822
+ # equal -- `border_subtitle` hands back markup, and neither
1823
+ # string carries any.
1824
+ if self.border_subtitle != hint:
1825
+ self.border_subtitle = hint
1826
+
1827
+ def get_content_height(self, container, viewport, width: int) -> int:
1828
+ # Textual hands the width here BEFORE the first paint, which is the
1829
+ # only place it is knowable while the panel is still hidden.
1830
+ self._budget(width)
1831
+ return sum(len(group) for group in self._groups)
1832
+
1833
+ # -- drawing -------------------------------------------------------------
1834
+
1835
+ def render(self):
1836
+ width = self.size.width or self._width
1837
+ if width and (width != self._width or not self._groups):
1838
+ self._budget(width)
1839
+ rows = []
1840
+ for index, group in enumerate(self._groups):
1841
+ for offset, line in enumerate(group):
1842
+ gutter = SUGGEST_LEAD if offset == 0 else SUGGEST_CONT
1843
+ row = Text(gutter, no_wrap=True, overflow="crop")
1844
+ row.append_text(line)
1845
+ # Padded to the full width so the highlight is a BAR rather
1846
+ # than a stripe the length of the text.
1847
+ row.pad_right(max(0, width - row.cell_len))
1848
+ if index == self._selected - self._first:
1849
+ row.stylize(SUGGEST_HIGHLIGHT)
1850
+ rows.append(row)
1851
+ body = Text(no_wrap=True, overflow="crop")
1852
+ for position, row in enumerate(rows):
1853
+ if position:
1854
+ body.append("\n")
1855
+ body.append_text(row)
1856
+ return body
1857
+
1858
+
1859
+ class PromptInput(TextArea):
1860
+ """The box the user types into. Wraps, grows to four rows, and since
1861
+ batch 55 offers the slash commands while one is being typed.
1862
+
1863
+ It was a plain `Input` until batch 54, and an `Input` is single-line by
1864
+ construction -- `height: 3` in its own DEFAULT_CSS, one text row, no
1865
+ wrap, horizontal scroll. A prompt longer than the box showed its last
1866
+ ~70 columns and nothing before them, so a paragraph could not be read
1867
+ back before it was sent. `TextArea` is the only multi-line widget in
1868
+ the pinned textual, so this is a swap rather than a setting.
1869
+
1870
+ The GROWING is `soft_wrap` plus `height: auto` in app.tcss, and those
1871
+ two are the feature: a long line wraps and the box gets taller on its
1872
+ own, with no key pressed. `ctrl+j` is for a break the user WANTS.
1873
+
1874
+ Four things here are load-bearing.
1875
+
1876
+ `value`. `TextArea` calls it `text`, and roughly sixty test sites plus
1877
+ the app's own submit handler say `.value`. An alias is a one-line
1878
+ adapter; renaming them would have been sixty edits across five files
1879
+ to make a rendering change, and every one of those files is about
1880
+ something else. It is a property over `text`, not a second store --
1881
+ two writers of one string is the shape §22 spent a section removing.
1882
+
1883
+ `priority=True` on enter. `TextArea._on_key` maps enter to a newline
1884
+ insert and calls `event.stop()` / `event.prevent_default()`, which
1885
+ beats an ordinary binding: measured on the installed textual (D22,
1886
+ both ways -- without the flag enter inserts and never submits). It
1887
+ reads like caution and is the opposite. Re-read on 8.2.8 when the
1888
+ pin moved: `_on_key` still maps enter through `insert_values` and
1889
+ still stops the event, so the flag is still what makes this a
1890
+ prompt box rather than a text editor.
1891
+
1892
+ `ctrl+j` is what carries the newline; `shift+enter` is a courtesy.
1893
+ Every half of that courtesy the CODE owns works now, and it is still
1894
+ not the key. Textual turned the kitty keyboard protocol on in its
1895
+ LINUX drivers alone through 6.5, which is why batch 54 called this
1896
+ binding unreachable here; 6.6.0 added it to
1897
+ `drivers/windows_driver.py`, which writes `ESC [>1u` when application
1898
+ mode starts, and the parser turns `ESC [13;2u` into `shift+enter`.
1899
+ Both measured on 8.2.8 and both pinned by
1900
+ `TestShiftEnterIsStillNotTheKey`, because that is the sentence that
1901
+ went stale unnoticed for twenty months last time.
1902
+
1903
+ What is left is the TERMINAL. This driver reads console records and
1904
+ keeps the translated character alone, discarding the modifier state,
1905
+ so that escape sequence is the only route a modified Enter has -- and
1906
+ a terminal that does not implement the protocol still sends a bare CR,
1907
+ which reads as `enter` and submits the half-written message. Windows
1908
+ Terminal shipped support in Preview 1.25 and this is developed on
1909
+ 1.24, so the press has never been observed here and the courtesy stays
1910
+ unclaimed. `ctrl+j` is byte 0x0a, parses to its own
1911
+ key, is bound by neither Input, TextArea, App nor Footer, and is
1912
+ exactly what iTerm2 / VS Code / Windows Terminal emit once configured
1913
+ to send a newline on shift+enter. `alt+enter` is the obvious third
1914
+ guess and is a dead end: fed `ESC CR` the parser yields no key at all,
1915
+ and a second one behind it degrades to `escape`, `enter`.
1916
+
1917
+ **`load_text` is where typing is told apart from assignment** (batch
1918
+ 55), and it is the seam the whole suggestion panel hangs off. Setting
1919
+ `.value` posts `TextArea.Changed` exactly as a keystroke does --
1920
+ measured -- so a panel driven straight off that message would open in
1921
+ the ~73 `query_one("#prompt").value = "/..."` sites across four test
1922
+ files and turn each one's single `press("enter")` into a COMPLETION
1923
+ instead of a dispatch. The line to draw is not a test accommodation:
1924
+ assignment is the API, typing is the user, and textual draws the same
1925
+ line itself -- `_replace_via_keyboard`'s docstring says "as opposed to
1926
+ the API". That method covers inserts only (backspace does not go
1927
+ through it, measured), and this panel must react to deletions, so the
1928
+ seam is `load_text` instead: the single public funnel behind both
1929
+ `.text =` and `.value =`.
1930
+
1931
+ `tab_behavior` stays at its "focus" default, deliberately. Under
1932
+ "indent" `TextArea._on_key` also swallows `escape` (it focuses the
1933
+ next widget), and tab/escape behaving as they did under `Input` is
1934
+ worth more here than tab-indenting a chat message. Batch 55 spends
1935
+ both keys, but only while the panel is open: `check_action` hands them
1936
+ back to the focus system and to nobody the rest of the time.
1937
+
1938
+ The placeholder is the border TITLE. `TextArea` has a native
1939
+ `placeholder` reactive that renders inside the box when it is empty,
1940
+ so assigning the same string to both drew it twice -- once on the
1941
+ frame, once in the text. Taking it as a `placeholder=` keyword anyway
1942
+ keeps the call site in app.py reading as it always did; it is simply
1943
+ never assigned to `self.placeholder`.
1944
+ """
1945
+
1946
+ BINDINGS = [
1947
+ Binding("enter", "submit", "Submit", show=False, priority=True),
1948
+ Binding("ctrl+j", "newline", "Newline", show=False),
1949
+ Binding("shift+enter", "newline", "Newline", show=False),
1950
+ # Both gated by check_action, so with no panel open they are the
1951
+ # keys they have always been: tab moves focus, escape reaches
1952
+ # whoever wants it.
1953
+ Binding("tab", "complete", "Complete", show=False),
1954
+ Binding("escape", "dismiss_suggestions", "Dismiss", show=False),
1955
+ ]
1956
+
1957
+ # CLASS attributes, not set in __init__: `load_text` runs during
1958
+ # TextArea.__init__, before any assignment of ours could have happened.
1959
+ suggest = None # the SlashSuggest panel; app.py hands it over
1960
+ _api_edit = False # the next Changed came from .value, not a key
1961
+ _dismissed = False # escape latched the panel shut
1962
+ _completing = False # ...and that .value came from tab or enter
1963
+ file_completion = None # app supplies a cached, I/O-free callback
1964
+ _suggest_enabled = False
1965
+
1966
+ class Submitted(Message):
1967
+ """Posted when enter is pressed. `Input.Submitted`'s shape.
1968
+
1969
+ A distinct message type rather than reusing `Input.Submitted`, and
1970
+ that is a fix as much as a necessity: `Input.Submitted` BUBBLES
1971
+ past a modal's own handler to the app's (measured -- the screen
1972
+ handler runs and then the app's), so enter in ReviewScreen's note
1973
+ box reached the prompt's submit handler, which cleared the note
1974
+ and dispatched it as a slash command if it began with one.
1975
+ """
1976
+
1977
+ def __init__(self, prompt: "PromptInput", value: str) -> None:
1978
+ self.prompt = prompt
1979
+ self.value = value
1980
+ super().__init__()
1981
+
1982
+ @property
1983
+ def control(self) -> "PromptInput":
1984
+ return self.prompt
1985
+
1986
+ class SuggestionsChanged(Message):
1987
+ """The command list to offer, after a keystroke (batch 55).
1988
+
1989
+ A message rather than the prompt writing to the panel directly, so
1990
+ app.py stays the one place that touches both this and the
1991
+ transcript -- which it has to, because a panel opening SHRINKS the
1992
+ transcript and textual does not re-pin a scroll on shrink.
1993
+ """
1994
+
1995
+ def __init__(self, prompt: "PromptInput", matches: list,
1996
+ label: str | None = None) -> None:
1997
+ self.prompt = prompt
1998
+ self.matches = matches
1999
+ self.label = label
2000
+ super().__init__()
2001
+
2002
+ @property
2003
+ def control(self) -> "PromptInput":
2004
+ return self.prompt
2005
+
2006
+ class SuggestionsMoved(Message):
2007
+ """The arrow keys, asking the panel to move its highlight.
2008
+
2009
+ A message rather than a direct `suggest.move()` call, and batch 56
2010
+ is what made that necessary: the window SLIDES now, so a move can
2011
+ change the panel's HEIGHT, and a panel that changes height takes
2012
+ rows from the transcript. Whether the reader was at the bottom is
2013
+ knowable only before that relayout, so the move has to happen
2014
+ inside app.py's pin -- the same one `SuggestionsChanged` uses.
2015
+ """
2016
+
2017
+ def __init__(self, prompt: "PromptInput", delta: int) -> None:
2018
+ self.prompt = prompt
2019
+ self.delta = delta
2020
+ super().__init__()
2021
+
2022
+ @property
2023
+ def control(self) -> "PromptInput":
2024
+ return self.prompt
2025
+
2026
+ def __init__(self, placeholder: str = "", **kwargs) -> None:
2027
+ super().__init__(soft_wrap=True, show_line_numbers=False, **kwargs)
2028
+ # Never assigned to self.placeholder: TextArea renders that reactive
2029
+ # inside the box when empty, which drew the hint twice (frame and
2030
+ # text). The border title is the only placeholder this box has.
2031
+ self.border_title = placeholder
2032
+
2033
+ @property
2034
+ def value(self) -> str:
2035
+ return self.text
2036
+
2037
+ @value.setter
2038
+ def value(self, new_value: str) -> None:
2039
+ self.text = new_value
2040
+
2041
+ # -- the suggestion panel -----------------------------------------------
2042
+
2043
+ def load_text(self, text: str) -> None:
2044
+ # See the docstring: this is the API half of the API/keyboard
2045
+ # split, and `.value =` reaches it through `.text =`.
2046
+ self._api_edit = True
2047
+ self._suggest_enabled = False
2048
+ super().load_text(text)
2049
+
2050
+ def _mention_cursor_offset(self) -> int:
2051
+ row, column = self.cursor_location
2052
+ return sum(len(line) + 1 for line in self.text.split("\n")[:row]) + column
2053
+
2054
+ def _location(self, offset: int) -> tuple[int, int]:
2055
+ before = self.text[:offset]
2056
+ return before.count("\n"), len(before.rsplit("\n", 1)[-1])
2057
+
2058
+ def refresh_suggestions(self) -> None:
2059
+ """Re-filter cached rows after typing, cursor movement or indexing."""
2060
+ label = None
2061
+ context = (self.file_completion(self.text, self._mention_cursor_offset())
2062
+ if self.file_completion else None)
2063
+ if context is not None:
2064
+ _, matches, label = context
2065
+ else:
2066
+ matches = commands.matching(self.text)
2067
+ if not matches:
2068
+ self._dismissed = False
2069
+ self.post_message(self.SuggestionsChanged(
2070
+ self, [] if self._dismissed else matches, label))
2071
+
2072
+ def on_text_area_selection_changed(self, event: TextArea.SelectionChanged) -> None:
2073
+ if self._suggest_enabled and not self._api_edit:
2074
+ self.refresh_suggestions()
2075
+
2076
+ def on_text_area_changed(self, event: TextArea.Changed) -> None:
2077
+ if self._api_edit:
2078
+ # Assignment is not typing. It also CLOSES the panel, which is
2079
+ # what makes `event.prompt.value = ""` on submit tidy up.
2080
+ self._api_edit = False
2081
+ self._dismissed = False
2082
+ if self._completing:
2083
+ # ...except the one assignment a keystroke made. See
2084
+ # `_complete`.
2085
+ self._completing = False
2086
+ self._suggest_enabled = True
2087
+ self.refresh_suggestions()
2088
+ return
2089
+ self.post_message(self.SuggestionsChanged(self, []))
2090
+ return
2091
+ self._suggest_enabled = True
2092
+ self.refresh_suggestions()
2093
+
2094
+ def _panel_open(self) -> bool:
2095
+ return self.suggest is not None and self.suggest.display
2096
+
2097
+ def _complete(self) -> bool:
2098
+ """Put the highlighted command in the box. True if one was taken."""
2099
+ if not self._panel_open():
2100
+ return False
2101
+ command = self.suggest.chosen
2102
+ if command is None:
2103
+ return False
2104
+ if getattr(command, "prefix", "/") == "@":
2105
+ context = self.file_completion(self.text, self._mention_cursor_offset())
2106
+ if context is None:
2107
+ return False
2108
+ mention, _, _ = context
2109
+ replacement = "@" + command.name
2110
+ # Reuse an existing separating space without losing the suffix.
2111
+ reuse = self.text[mention.end:mention.end + 1] == " "
2112
+ self.replace(replacement + ("" if reuse else " "),
2113
+ self._location(mention.start), self._location(mention.end),
2114
+ maintain_selection_offset=False)
2115
+ self.move_cursor(self._location(mention.start + len(replacement) + 1))
2116
+ return True
2117
+ # The TRAILING SPACE is doing two jobs: for a command with no
2118
+ # argument completer `matching()` is empty once the line has a
2119
+ # space in it, so the panel closes on its own, and deleting that
2120
+ # one character is what brings it back.
2121
+ self.value = "/" + command.name + " "
2122
+ # load_text leaves the cursor at the START of the document, which
2123
+ # would have the next typed argument land in front of the command.
2124
+ self.move_cursor(self.document.end)
2125
+ # RE-OFFER (batch 84), through a FLAG rather than a message posted
2126
+ # from here. The assignment above went through `load_text`, which
2127
+ # queues a `TextArea.Changed` -- so anything posted here is handled
2128
+ # BEFORE that Changed arrives and is then overwritten by the empty
2129
+ # list its api-edit branch posts. Measured: the panel came back
2130
+ # with 133 rows and was cleared a tick later.
2131
+ #
2132
+ # The branch exists because assignment is the API and typing is the
2133
+ # user; a tab is the user, which is why this one re-offers. For
2134
+ # every command without an argument completer it posts the same
2135
+ # empty list that branch already did.
2136
+ self._completing = True
2137
+ return True
2138
+
2139
+ def check_action(self, action: str, parameters) -> bool | None:
2140
+ # None, not False: False would DISABLE the key, where None declines
2141
+ # it and lets the press carry on to the focus system (tab) or to
2142
+ # nobody (escape) -- which is what both did before batch 55.
2143
+ if action in ("complete", "dismiss_suggestions"):
2144
+ return True if self._panel_open() else None
2145
+ return True
2146
+
2147
+ # -- actions -------------------------------------------------------------
2148
+
2149
+ def action_submit(self) -> None:
2150
+ # Enter ALWAYS completes while the panel is open, so a fully typed
2151
+ # /help takes two presses. The alternative -- submit when the typed
2152
+ # token already equals the highlighted name -- is a coin flip from
2153
+ # the user's side and stops being well defined the day two commands
2154
+ # share a prefix.
2155
+ if self._complete():
2156
+ return
2157
+ self.post_message(self.Submitted(self, self.text))
2158
+
2159
+ def action_newline(self) -> None:
2160
+ self.insert("\n")
2161
+
2162
+ def action_complete(self) -> None:
2163
+ self._complete()
2164
+
2165
+ def action_dismiss_suggestions(self) -> None:
2166
+ self._dismissed = True
2167
+ self.post_message(self.SuggestionsChanged(self, []))
2168
+
2169
+ def action_cursor_up(self, select: bool = False) -> None:
2170
+ # `select` is shift+up, which is a text selection and stays one.
2171
+ # Everything else: batch 54 made this box multi-line, so the arrow
2172
+ # keys have to go back to moving the CURSOR the moment the panel
2173
+ # is closed.
2174
+ if not select and self._panel_open():
2175
+ self.post_message(self.SuggestionsMoved(self, -1))
2176
+ return
2177
+ super().action_cursor_up(select)
2178
+
2179
+ def action_cursor_down(self, select: bool = False) -> None:
2180
+ if not select and self._panel_open():
2181
+ self.post_message(self.SuggestionsMoved(self, 1))
2182
+ return
2183
+ super().action_cursor_down(select)
630
2184
 
631
2185
 
632
2186
  class Transcript(RichLog):
@@ -662,11 +2216,18 @@ class Transcript(RichLog):
662
2216
  streaming latency should look here first." They should still look
663
2217
  here first; the answer is now the two rules above.
664
2218
 
665
- Known edge, stated rather than fixed: a terminal resize mid-answer
666
- leaves already-drawn rows wrapped to the old width. `_entries` keeps
667
- the unwrapped source, so rerender() puts it right, and a resize
668
- handler for the seconds an answer is in flight is machinery with no
669
- user.
2219
+ A TERMINAL RESIZE RE-LAYS THE TRANSCRIPT since batch 112, which is
2220
+ what this paragraph used to say was a known edge. RichLog renders at
2221
+ write time and stores Strips, so nothing re-wraps itself and every row
2222
+ drawn before a drag kept the width it was drawn at -- not only an
2223
+ answer in flight. `_entries` keeps the unwrapped source, so a replay
2224
+ puts it right; what took nine batches is that `rerender()` opens with
2225
+ `flush_stream()`, which ENDS an open answer span, so routing a resize
2226
+ to it would split a live answer into two entries under two
2227
+ `venastine ›` labels. `reflow()` is the replay that leaves the span
2228
+ open -- see `_uncommit_partial_line` for the one thing it has to move
2229
+ first -- and `on_resize` coalesces it. A pane the switcher HIDES is a
2230
+ different cause with the same look, fixed earlier: see `_region_width`.
670
2231
 
671
2232
  §26 adds two things and one obligation.
672
2233
 
@@ -691,18 +2252,30 @@ class Transcript(RichLog):
691
2252
 
692
2253
  §43 moves that label. It belongs to the TURN, not to an answer span:
693
2254
  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.
2255
+ whether that output is reasoning, text or a tool call, retired by
2256
+ the next "you ›". See _open_label for why, and note the property
2257
+ that makes it safe -- placement is a pure function of the role
2258
+ sequence in `_entries`, so rerender() reproduces it rather than
2259
+ approximating it. A re-render that moves a label is the same defect
2260
+ as one that reflows a paragraph.
700
2261
  """
701
2262
 
702
2263
  def __init__(self, **kwargs):
703
2264
  super().__init__(wrap=True, markup=False, **kwargs)
704
2265
  self._pending = ""
705
2266
  self._entries: list[tuple[str, str]] = []
2267
+ # Batch 65. Click TARGETS for entry N, when the drawn line is
2268
+ # too short to be one -- see `markdown.link_spans`. A side
2269
+ # table rather than a third element in the tuple above, because
2270
+ # `_entries` is read by /copy, by last_answer() and by the
2271
+ # replay contract, and a link is a rendering fact about a line
2272
+ # rather than part of what was said. Keyed by INDEX, which
2273
+ # rerender() already walks.
2274
+ self._links: dict[int, tuple] = {}
2275
+ # §47, widened by §49 (SS14). entry index -> (kind, call id) for
2276
+ # the call that drew that line, where kind says whether clicking
2277
+ # it opens a thread or a session.
2278
+ self._opens: dict = {}
706
2279
  # §38. An assistant span with rows already on screen: its label is
707
2280
  # drawn and its single entry is open at _entries[-1].
708
2281
  self._stream_open = False
@@ -717,6 +2290,165 @@ class Transcript(RichLog):
717
2290
  # ONE label per turn, above the model's first output of it
718
2291
  # whether that output is reasoning or text -- see _open_label.
719
2292
  self._label_in_force = False
2293
+ # Batch 112 (TECHNICAL_DEBT 23). The width the rows on screen were
2294
+ # laid out at -- maintained in `write()`, which every draw path
2295
+ # funnels through -- and the pending coalesced redraw. None before
2296
+ # the first write, which no real width equals, so the first resize
2297
+ # always reflows rather than having to guess what was drawn.
2298
+ self._drawn_width: int | None = None
2299
+ self._reflow_timer = None
2300
+ # Batch 113 (TECHNICAL_DEBT 25). How many entries were on screen
2301
+ # when the span now streaming began, which is where
2302
+ # `retract_to_mark` truncates back to. None means nothing is
2303
+ # retractable. See that method for why a mark and not a span.
2304
+ self._retract_mark: int | None = None
2305
+ # Batch 145. Three, and each one is measured -- see
2306
+ # `_strip` for the vocabulary and `_new_strippers` for why the
2307
+ # count is three rather than one.
2308
+ self._new_strippers()
2309
+
2310
+ def _new_strippers(self) -> None:
2311
+ """One stripper per independent ingress stream (batch 145).
2312
+
2313
+ THREE, not one, and not one per call:
2314
+
2315
+ `_entry` takes complete strings -- every `write_*` path -- so it is
2316
+ fed and flushed within the call and carries nothing between two
2317
+ unrelated entries.
2318
+
2319
+ `_answer` and `_thinking` are held ACROSS deltas, because a
2320
+ sequence split over two of them is ordinary rather than a corner:
2321
+ the model's chunk boundaries fall wherever the provider put them,
2322
+ which is the same argument `core/ansi.py` makes about a pipe. A
2323
+ fresh stripper per delta was measured both ways and both are wrong
2324
+ -- dropping the carry turns `hi ESC [` + `2Jthere` into
2325
+ `hi 2Jthere`, and flushing it per call emits the ESC itself.
2326
+
2327
+ They are SEPARATE from each other for the reason `_thinking_pending`
2328
+ is separate from `_pending` one screen up: the two spans interleave,
2329
+ and a shared stripper carries one span's unterminated sequence into
2330
+ the other. Measured -- an open CSI from the answer ate the `t` of
2331
+ the next reasoning chunk, because 0x74 is inside the CSI final-byte
2332
+ range, so the sequence terminated on the reasoning text's first
2333
+ character.
2334
+
2335
+ `release_unterminated=False` on all three. The pty's default is to
2336
+ release a carry that never completed as text; here the text is
2337
+ handed to a terminal, where `ESC [` with no final byte consumes
2338
+ whatever is drawn next, so an unterminated sequence is dropped.
2339
+ `core/ansi.py` argues both contracts where the flag is defined.
2340
+ """
2341
+ self._entry_ansi = AnsiStripper(release_unterminated=False)
2342
+ self._answer_ansi = AnsiStripper(release_unterminated=False)
2343
+ self._thinking_ansi = AnsiStripper(release_unterminated=False)
2344
+
2345
+ def _strip(self, stripper, text: str) -> str:
2346
+ """The ONE redaction of terminal control sequences this widget does.
2347
+
2348
+ A function rather than three call sites spelling it out, for the
2349
+ reason batch 144 spent a surface on: five sinks each composing
2350
+ their own version of one transform is how two of them end up with
2351
+ different vocabularies, and nothing can tell you which.
2352
+
2353
+ Returns the text with every escape sequence removed, in BOTH
2354
+ encodings (`ESC [` and U+009B alike, batch 145's addition to
2355
+ `core/ansi.py`). What it does NOT do is announce anything: this
2356
+ widget does no logging, deliberately -- `on_log_record_message`
2357
+ feeds routed records straight back into `write_role`, and a
2358
+ Transcript that logged while writing would close that loop. The
2359
+ count is kept instead and `tui/app.py` reads it, which is the
2360
+ layer that knows whose text this was.
2361
+ """
2362
+ return stripper.feed(text)
2363
+
2364
+ def take_stripped_count(self) -> int:
2365
+ """How many control sequences have been removed since the last ask.
2366
+
2367
+ READ-AND-CLEAR, so the caller gets a count per turn rather than a
2368
+ total that only grows -- `tui/app.py` asks once when a turn ends.
2369
+ """
2370
+ total = 0
2371
+ for stripper in (self._entry_ansi, self._answer_ansi,
2372
+ self._thinking_ansi):
2373
+ total += stripper.sequences_removed
2374
+ stripper.sequences_removed = 0
2375
+ return total
2376
+
2377
+ def write(self, content, *args, width=None, **kwargs):
2378
+ """Write at the width this pane will be SHOWN at (§47).
2379
+
2380
+ `RichLog.write` wraps at WRITE time -- 8.x stores Strips --
2381
+ measuring the widget's own region, which is 0 while the switcher
2382
+ hides this pane and is then floored to min_width (78). Both panes
2383
+ are written hidden (see `_region_width`), so a `width=None` write
2384
+ there is handed the width RichLog would have chosen with the pane
2385
+ on screen; our own pre-wrap (thinking, lists, diffs, streamed
2386
+ commits) reads the same region through `_wrap_width`, so the two
2387
+ halves of one transcript cannot break at two widths.
2388
+
2389
+ The borrowed REGION is not that width, and passing it is the
2390
+ obvious shortcut this used to take. An explicit width switches off
2391
+ RichLog's shrink, so a renderable that pads to its render width --
2392
+ a code block under a syntax theme with a background -- drew edge
2393
+ to edge where the same block on screen stopped at
2394
+ max(longest line, 78). Both shipped syntax themes are transparent,
2395
+ which is why nobody saw it; the width pins run under monokai.
2396
+
2397
+ An explicit width is the caller's and passes through untouched.
2398
+
2399
+ `*args` because Textual itself replays deferred writes
2400
+ positionally (`self.write(*deferred_render)` on resize, with
2401
+ content/width/expand/shrink/scroll_end all filled) -- a
2402
+ keyword-only width would turn its own replay into a TypeError. A
2403
+ never-shown pane defers every write, so its deferred entries carry
2404
+ the width computed here, which is the width it is shown at.
2405
+ """
2406
+ # Batch 112. Every drawn row passes here, so this is the one place
2407
+ # that can say what width the screen is currently laid out at --
2408
+ # which is what `on_resize` compares against, so a resize that does
2409
+ # not change the wrap width (a height-only drag) redraws nothing.
2410
+ self._drawn_width = self._wrap_width()
2411
+ if args:
2412
+ # Textual's own replay (or any positional caller): pass
2413
+ # through byte-identical, never merging a keyword beside it.
2414
+ return super().write(content, *args, **kwargs)
2415
+ if width is None:
2416
+ width = self._borrowed_render_width(content, **kwargs)
2417
+ return super().write(content, width=width, **kwargs)
2418
+
2419
+ def _borrowed_render_width(self, content, expand: bool = False,
2420
+ shrink: bool = True,
2421
+ **_ignored) -> int | None:
2422
+ """RichLog.write's render width as if this pane were on screen, or
2423
+ None when it is on screen (or there is nothing to borrow), which
2424
+ leaves RichLog to measure for itself.
2425
+
2426
+ Mirrors `RichLog.write` in the pinned textual step for step:
2427
+ measure the renderable, expand or shrink it against the region,
2428
+ raise the result to min_width. A pin bump that changes that
2429
+ computation fails the row equality in
2430
+ `TestTheLiveTranscriptWritesAtTheOnScreenWidth`.
2431
+ """
2432
+ try:
2433
+ if self.scrollable_content_region.width:
2434
+ return None
2435
+ region = self._borrowed_width()
2436
+ except Exception: # noqa: BLE001 -- unmounted; RichLog decides
2437
+ return None
2438
+ if not region:
2439
+ return None
2440
+ renderable = self._make_renderable(content)
2441
+ console = self.app.console
2442
+ options = console.options
2443
+ if isinstance(renderable, Text) and not self.wrap:
2444
+ options = options.update(overflow="ignore", no_wrap=True)
2445
+ measured = measure_renderables(console, options, [renderable]).maximum
2446
+ render_width = measured
2447
+ if expand and measured < region:
2448
+ render_width = max(measured, region)
2449
+ if shrink and measured > region:
2450
+ render_width = min(measured, region)
2451
+ return max(render_width, self.min_width)
720
2452
 
721
2453
  # -- styling -----------------------------------------------------------
722
2454
 
@@ -748,13 +2480,52 @@ class Transcript(RichLog):
748
2480
 
749
2481
  # -- writing -----------------------------------------------------------
750
2482
 
751
- def _emit(self, role: str, text: str, record: bool = True) -> None:
752
- """Render one entry and remember it. THE single write path."""
2483
+ def _emit(self, role: str, text: str, record: bool = True,
2484
+ links=(), opens: tuple = ()) -> None:
2485
+ """Render one entry and remember it. THE single write path.
2486
+
2487
+ `links` are batch 65's click targets, remembered beside the
2488
+ entry so a `/theme` rerender arms what the live draw armed. An
2489
+ entry with none -- every role outside LINKED_ROLES, and most
2490
+ tool lines -- stores nothing.
2491
+
2492
+ `opens` is §47's `(kind, call id)`, and it is kept in a SECOND
2493
+ side table rather than folded into `_links`. They are different
2494
+ kinds of target: a link opens a browser and a call opens a
2495
+ pane, and the click handler has to tell them apart anyway. Same
2496
+ keying, same two lifetimes -- `reset()` drops it, `rerender()`
2497
+ replays it -- because it is the same kind of fact ABOUT a line.
2498
+
2499
+ ONE TABLE FOR BOTH KINDS since batch 98, because a thread and a
2500
+ session are the same fact about a line -- what clicking it
2501
+ opens -- and a second dict keyed by the same index would have
2502
+ been a third lifetime to keep in step with the other two.
2503
+ """
2504
+ # Batch 145. BEFORE the entry is recorded, so `_entries`,
2505
+ # the screen, `/copy` and the replay all hold the same bytes --
2506
+ # which is the obligation this method's own docstring states, now
2507
+ # also about what the text IS and not only about where it goes.
2508
+ # Fed and flushed within the call: this is a complete string, so a
2509
+ # sequence left open at the end of it was never split, and the
2510
+ # flush discards it rather than releasing it as text.
2511
+ text = self._strip(self._entry_ansi, text)
2512
+ self._entry_ansi.flush()
753
2513
  if record:
754
2514
  self._entries.append((role, text))
755
- self._render_entry(role, text)
756
-
757
- def _render_entry(self, role: str, text: str) -> None:
2515
+ if links:
2516
+ self._links[len(self._entries) - 1] = tuple(links)
2517
+ if opens:
2518
+ self._opens[len(self._entries) - 1] = tuple(opens)
2519
+ self._render_entry(role, text, links, opens)
2520
+
2521
+ def _render_entry(self, role: str, text: str, links=(),
2522
+ opens: tuple = (), *, closed: bool = True) -> None:
2523
+ """Draw one entry. `closed` says whether the span it belongs to has
2524
+ ENDED, and only `reflow()` ever passes False (batch 112): a resize
2525
+ mid-reasoning replays a thinking entry that is still being streamed,
2526
+ and drawing its `╰ …done thinking` there would announce an end that
2527
+ has not happened. An open ANSWER span needs nothing -- it has no
2528
+ closing furniture -- so the flag is thinking's alone."""
758
2529
  if role == "user":
759
2530
  # §43 (RM1). The turn's label is retired HERE and nowhere
760
2531
  # else, so where the labels land is a pure function of the
@@ -764,6 +2535,14 @@ class Transcript(RichLog):
764
2535
  self.write(Text.assemble(
765
2536
  ("\nyou › ", self._style("user_label")),
766
2537
  (text, self._style("user"))))
2538
+ elif role == "wake":
2539
+ # ROADMAP_v3 §49 (SS5). The harness opening a turn with a
2540
+ # background session's result. It retires the label exactly as a
2541
+ # `user` row does, for §43's reason: the answer it prompts is a
2542
+ # new turn with its own `venastine ›`, and where labels land stays
2543
+ # a pure function of the role sequence, so rerender() agrees.
2544
+ self._label_in_force = False
2545
+ self.write(Text(f"\n{text}", self._style("wake")))
767
2546
  elif role == "assistant":
768
2547
  self._open_label()
769
2548
  # One trailing newline is dropped, exactly as a committed
@@ -777,6 +2556,23 @@ class Transcript(RichLog):
777
2556
  self._render_blocks(text[:-1] if text.endswith("\n") else text)
778
2557
  elif role == "diff":
779
2558
  self._render_diff(text)
2559
+ elif role == "tool":
2560
+ # §43 RM1, as amended: a tool call is model output too, and on
2561
+ # a turn that OPENS with one -- the normal MCP shape, a call
2562
+ # made before any prose -- it is the turn's first output.
2563
+ # Without this the call rendered under `you ›` and the label
2564
+ # opened below it, above the prose that eventually followed.
2565
+ # The guard inside _open_label keeps the other half of the
2566
+ # §43 sentence true: a tool line INSIDE the turn, after
2567
+ # reasoning or text has already opened the label, is a no-op.
2568
+ self._open_label()
2569
+ self.write(self._linked_line(text, "tool", links, opens))
2570
+ elif role == "pipeline_tool":
2571
+ # The research pipeline's tool lines. Same kind of line and
2572
+ # the same style, deliberately NOT an opener: the run's label
2573
+ # belongs to the report, and a pipeline call is the harness
2574
+ # working, not the model answering (§43 RM1, owner decision).
2575
+ self.write(self._linked_line(text, "tool", links))
780
2576
  elif role == "thinking":
781
2577
  # §38. The furniture is OWNED by the renderer, not stored in
782
2578
  # the entry: `_entries` keeps the model's raw reasoning, so
@@ -786,10 +2582,79 @@ class Transcript(RichLog):
786
2582
  self._open_label()
787
2583
  self._write_thinking_open()
788
2584
  self._write_thinking_lines(text)
789
- self._write_thinking_close()
2585
+ if closed:
2586
+ self._write_thinking_close()
2587
+ elif role in LINKED_ROLES:
2588
+ # `tool_error` arrives here, and needs no `links`: its text
2589
+ # is redact_secrets(str(error)) with no truncation, so the
2590
+ # URL it carries is whole and the span resolves to itself.
2591
+ self.write(self._linked_line(text, role, links))
790
2592
  else:
791
2593
  self.write(Text(f" {text}", self._style(role)))
792
2594
 
2595
+ def _linked_line(self, text: str, role: str, targets=(),
2596
+ opens: tuple = ()) -> Text:
2597
+ """One harness-drawn line, with its URLs armed (batch 65).
2598
+
2599
+ The five-space indent every one of these lines carries is inside
2600
+ the scanned text rather than prepended after, so a span's
2601
+ columns are the columns Textual dispatches a click on -- the
2602
+ offsets have to be the drawn ones or the arming lands beside the
2603
+ URL instead of on it.
2604
+ """
2605
+ out = Text(style=self._style(role))
2606
+ self._append_spans(out, f" {text}", self._styles(),
2607
+ block=False, links_only=True, targets=targets)
2608
+ if opens:
2609
+ self._arm_call(out, opens)
2610
+ return out
2611
+
2612
+ def _arm_call(self, out: Text, opens: tuple) -> None:
2613
+ """Make the TOOL NAME on a line open what the call opened (§47,
2614
+ widened by §49 SS14).
2615
+
2616
+ THE NAME, not the whole line. A tool line is `▸ name digest`,
2617
+ and the digest is the task text -- which for a spawn is a
2618
+ sentence a reader wants to select and read, and for a session
2619
+ is the command, not a control. Arming the name keeps the
2620
+ clickable region exactly as wide as the thing it is about.
2621
+
2622
+ ONE LOCATOR for both kinds. This was `_arm_spawn` and the shape
2623
+ it finds is the same either way, so a second copy for sessions
2624
+ would have been two implementations of "where does the tool
2625
+ name start" -- and the one that drifted would disarm a line
2626
+ rather than fail visibly.
2627
+
2628
+ Applied AFTER the URL scan and over its own columns only, so a
2629
+ URL in the task text keeps its own target: the two never
2630
+ overlap, because the name ends before the digest begins.
2631
+
2632
+ Located STRUCTURALLY rather than by the marker glyph. The `▸`
2633
+ is written by app.py and by core/replay.py as a literal and has
2634
+ no shared constant, so matching on it here would be a third
2635
+ copy -- and the shape (indent, marker, space, name, two spaces,
2636
+ digest) is what both writers actually agree on.
2637
+
2638
+ A line that does not have that shape is left unarmed, which is
2639
+ what an unopenable line should be.
2640
+ """
2641
+ plain = out.plain
2642
+ marker = len(plain) - len(plain.lstrip())
2643
+ start = plain.find(" ", marker) + 1
2644
+ if not start or start >= len(plain):
2645
+ return
2646
+ end = plain.find(" ", start)
2647
+ if end < 0:
2648
+ end = len(plain.rstrip())
2649
+ if end <= start:
2650
+ return
2651
+ # A TUPLE in the metadata, which rich marshals and hands back
2652
+ # as one. The kind has to survive the round trip: the click
2653
+ # handler is the only thing that reads it, and by then the tool
2654
+ # name that decided it is long gone.
2655
+ out.stylize(Style(meta={"opens": (str(opens[0]), str(opens[1]))}),
2656
+ start, end)
2657
+
793
2658
  def _open_label(self) -> None:
794
2659
  """Draw this turn's `venastine ›`, once (§43, RM1).
795
2660
 
@@ -800,14 +2665,24 @@ class Transcript(RichLog):
800
2665
  so the transcript read as if the user had done the thinking and
801
2666
  the model had answered without any.
802
2667
 
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.
2668
+ It is now the TURN's, opened by whichever of reasoning, text or a
2669
+ tool call comes first and retired only by the next `you ›`. A
2670
+ tool line, a diff or a system notice INSIDE the turn does not
2671
+ re-open one -- they are part of the turn the label already
2672
+ announced, and the guard below is what keeps that sentence true
2673
+ now that a tool line can open the label too. It has to be able
2674
+ to: a call made before any prose (the normal MCP shape) is the
2675
+ turn's first output, and §43's original wording left such a turn
2676
+ unlabelled until the prose followed, so the call read as if the
2677
+ user had made it. `tool_error` stays exempt on purpose -- a
2678
+ failure line is the tool's outcome rather than the model
2679
+ speaking, and the call line above it already carries the label.
2680
+ The research pipeline's tool lines never open one (they are
2681
+ `pipeline_tool`; the run's label belongs to the report). The
2682
+ cost, accepted rather than fixed: an answer resuming after a
2683
+ tool line starts directly under it, where the suppressed label
2684
+ used to supply a blank row. A separator drawn instead would be a
2685
+ second thing the live path and rerender() must agree about.
811
2686
  """
812
2687
  if self._label_in_force:
813
2688
  return
@@ -859,13 +2734,25 @@ class Transcript(RichLog):
859
2734
  if not total:
860
2735
  self.write(Text(text, style))
861
2736
  return
862
- self.write(Text(text.ljust(total), style), width=total)
2737
+ # Padded in cells (#224, batch 214): `ljust` counts characters,
2738
+ # so a row of double-width text overshot `total` and wrapped.
2739
+ self.write(Text(text + " " * max(0, total - cell_len(text)), style),
2740
+ width=total)
863
2741
 
864
- def _render_blocks(self, text: str) -> None:
2742
+ def _render_blocks(self, text: str, *, line_start: bool = True) -> None:
865
2743
  """The assistant body: fenced code highlighted, everything else
866
2744
  plain. Shared by a replayed entry and a committed stream chunk, so
867
2745
  the two cannot render the same text differently.
868
2746
 
2747
+ `line_start=False` says this chunk begins in the MIDDLE of a line,
2748
+ so nothing that depends on where a line starts may fire on its
2749
+ first line. Two callers want it and both were bugs without it: a
2750
+ streamed fragment whose wrap boundary fell just before a `# `
2751
+ token rendered as a heading and swallowed the hash, which a
2752
+ `/theme` replay then put back; and a chunk the cap released
2753
+ because HOLD_LIMIT expired, which is a line the cap gave up on
2754
+ rather than a construct.
2755
+
869
2756
  The newline trimming around a fence is what makes that sharing
870
2757
  exact rather than approximate. A `Syntax` renderable occupies its own
871
2758
  rows, so the newline that ends the ``` line is structural, not a
@@ -876,15 +2763,22 @@ class Transcript(RichLog):
876
2763
  answer grew a blank row per code block, and a /theme mid-session
877
2764
  reflowed a transcript it was only meant to recolour.
878
2765
  """
879
- blocks = _split_fences(text)
2766
+ blocks = markdown.split_blocks(text)
880
2767
  for index, block in enumerate(blocks):
881
- if isinstance(block, tuple):
882
- language, code = block
883
- self.write(Syntax(code, language or "text",
2768
+ # Batch 53. `isinstance(block, tuple)` still asks exactly the
2769
+ # question §26 asked -- "does this block occupy its own rows"
2770
+ # -- because both block kinds are tuple subclasses. That is
2771
+ # what keeps the trimming below ONE rule for the two of them
2772
+ # rather than a second branch to be kept in step.
2773
+ if isinstance(block, markdown.CodeBlock):
2774
+ self.write(Syntax(block.code, block.language or "text",
884
2775
  theme=self._syntax_theme(),
885
2776
  word_wrap=True,
886
2777
  indent_guides=False))
887
2778
  continue
2779
+ if isinstance(block, markdown.TableBlock):
2780
+ self._render_table(block)
2781
+ continue
888
2782
  body = block
889
2783
  if index and isinstance(blocks[index - 1], tuple) \
890
2784
  and body.startswith("\n"):
@@ -892,7 +2786,235 @@ class Transcript(RichLog):
892
2786
  if index + 1 < len(blocks) and isinstance(blocks[index + 1], tuple) \
893
2787
  and body.endswith("\n"):
894
2788
  body = body[:-1]
895
- self.write(Text(body, self._style("assistant")))
2789
+ # Only the FIRST block can begin mid-line; everything after a
2790
+ # renderable block starts where that block ended.
2791
+ self.write(self._inline_text(
2792
+ body, line_start=line_start and index == 0))
2793
+
2794
+ def _inline_text(self, body: str, *, line_start: bool = True) -> Text:
2795
+ """A plain stretch of an answer, with its inline marks painted.
2796
+
2797
+ The marks are the RENDERER's, exactly as the thinking bar and the
2798
+ diff's gutter are: `_entries` keeps the markdown the model wrote,
2799
+ so `/copy` hands back `**bold**`, `- ` and the brackets of a link,
2800
+ and a replay under a new theme re-derives the weight rather than
2801
+ replaying something decorated once.
2802
+
2803
+ Line by line, because a heading, a list item and the indent rule
2804
+ are all properties of a LINE and `tui/markdown.py` is where that
2805
+ is decided. The newlines are put back here so the block still
2806
+ reaches Rich as one `Text` and wraps as one flow -- which is what
2807
+ `markdown.width_split` is measuring against.
2808
+
2809
+ A LIST ITEM is the one line this widget wraps itself (batch 58).
2810
+ Rich has no hanging indent -- `Text` has none and `Padding`
2811
+ indents the first row too -- so the item's body is pre-wrapped
2812
+ through `markdown.wrap_display` at the width left after its
2813
+ marker, and every row after the first is padded to the column the
2814
+ marker's own text starts at. It is the same reason `_render_diff`
2815
+ and the thinking bar pre-wrap, and it is why the cap holds an item
2816
+ until its newline: a fragment committed without its marker could
2817
+ never be indented afterwards.
2818
+
2819
+ With no measurable width -- unmounted, or built bare in the suite
2820
+ -- nothing is pre-wrapped and the item draws flat, which is
2821
+ `_write_padded`'s guard rule applied to the same geometry.
2822
+ """
2823
+ styles = self._styles()
2824
+ base = styles.get("assistant", "")
2825
+ out = Text(style=base)
2826
+ width = self._wrap_width()
2827
+ for index, line in enumerate(body.split("\n")):
2828
+ if index:
2829
+ out.append("\n")
2830
+ block = line_start or index > 0
2831
+ item = markdown.list_item(line) if block else None
2832
+ if item is None:
2833
+ self._append_spans(out, line, styles, block=block)
2834
+ continue
2835
+ prefix, content, indent = item
2836
+ out.append(prefix, styles.get(markdown.BULLET) or None)
2837
+ rows = markdown.wrap_display(content, width - indent) \
2838
+ if width > indent else [content]
2839
+ for row_index, row in enumerate(rows):
2840
+ if row_index:
2841
+ out.append("\n" + " " * indent)
2842
+ self._append_spans(out, row, styles, block=False)
2843
+ return out
2844
+
2845
+ def _append_spans(self, out: Text, line: str, styles: dict, *,
2846
+ block: bool, links_only: bool = False,
2847
+ targets=()) -> None:
2848
+ """One line's spans, appended to `out` in their palette roles.
2849
+
2850
+ A LINK span is the one that carries more than a style. Its text is
2851
+ the URL -- the grammar guarantees that, which is the whole security
2852
+ rule: there is no label to hide a target behind, so the only thing
2853
+ a click can open is the thing the reader is looking at. The URL
2854
+ rides along as style METADATA, which `on_click` reads back.
2855
+
2856
+ Metadata rather than textual's `@click` action string, and the
2857
+ difference is not stylistic: an action string is PARSED, so
2858
+ building one out of model output would be an injection grammar fed
2859
+ by the model. A plain key is data all the way through.
2860
+
2861
+ `links_only` picks the other scanner (batch 65): a harness-drawn
2862
+ line gets URLs and no other mark, because it is a digest rather
2863
+ than prose. Both scanners are normalised to `(text, role,
2864
+ target)` here so that the metadata attach below stays a SINGLE
2865
+ line -- it is the security-critical one, and two copies of it
2866
+ drifting apart is the shape this project keeps recording.
2867
+
2868
+ For prose the target IS the span, which is batch 58 unchanged.
2869
+ `targets` is how a TRUNCATED tool line resolves to the URL it
2870
+ was cut from, under the rules `markdown.link_spans` states.
2871
+ """
2872
+ spans = markdown.link_spans(line, targets=targets) if links_only \
2873
+ else ((text, role, text)
2874
+ for text, role in markdown.inline_spans(line, block=block))
2875
+ for span, role, target in spans:
2876
+ if role == markdown.LINK:
2877
+ out.append(span, Style.parse(styles.get(role) or "")
2878
+ + Style(meta={"url": target}))
2879
+ continue
2880
+ out.append(span, styles.get(role) if role else None)
2881
+
2882
+ def _render_table(self, block) -> None:
2883
+ """One markdown table (batch 53).
2884
+
2885
+ A `rich.table.Table` rather than characters we lay out ourselves,
2886
+ for the reason `Syntax` is a `Syntax`: `RichLog.write` takes any
2887
+ renderable, so the alignment, the column widths and the wrapping
2888
+ inside a cell are Rich's problem and stay right at any terminal
2889
+ size. Textual's own `Markdown` cannot be used here -- it is a
2890
+ Widget, not a renderable, so reaching for it means replacing the
2891
+ transcript rather than rendering into it.
2892
+
2893
+ EVERY CELL IS A `Text`, header cells included. A bare `str` handed
2894
+ to a Table is parsed for console markup by the console that renders
2895
+ it, and the RichLog's own `markup=False` does not reach inside a
2896
+ renderable. Measured against the pinned Rich, both halves bite:
2897
+
2898
+ - `[bold]x` renders as `x`. The tag is SWALLOWED, silently, and
2899
+ a cell describing a style, a Textual selector or a log line
2900
+ loses part of itself with nothing raised.
2901
+ - `a[/]b` raises `MarkupError`, which is batch 42's RA1 -- the
2902
+ failure where a modal was pushed, never drew, and left a
2903
+ worker waiting on a dismissal that could not come. Here it
2904
+ would take down the turn that was answering.
2905
+
2906
+ `[1, 2]` survives, which is why the rule has to be about the TYPE
2907
+ rather than about scanning for brackets: the shapes that fail are
2908
+ not the ones a reader expects to be dangerous.
2909
+
2910
+ Cells are rendered with `line_start=False` (batch 58). A cell is a
2911
+ fragment rather than a line, so a cell reading `- 3` is a minus
2912
+ three and not a bullet, and one indented four spaces is a padded
2913
+ column rather than a code sample.
2914
+
2915
+ Written with an explicit `width=` when the widget can be measured,
2916
+ following the diff's discipline: it is the same number the text
2917
+ pre-wrap uses, so a table and the paragraph above it break at one
2918
+ width rather than two.
2919
+ """
2920
+ styles = self._styles()
2921
+ table = Table(box=TABLE_BOX,
2922
+ border_style=styles.get("table_border") or None,
2923
+ header_style=styles.get("table_header") or None)
2924
+ for header, align in zip(block.headers, block.aligns):
2925
+ table.add_column(
2926
+ self._inline_text(header, line_start=False), justify=align)
2927
+ for row in block.rows:
2928
+ table.add_row(*(self._inline_text(cell, line_start=False)
2929
+ for cell in row))
2930
+ width = self._wrap_width()
2931
+ if width:
2932
+ self.write(table, width=width)
2933
+ else:
2934
+ self.write(table)
2935
+
2936
+ # -- links (batch 58) ---------------------------------------------------
2937
+
2938
+ def on_click(self, event) -> None:
2939
+ """CTRL+click a URL to open it, or a spawn to read its run.
2940
+
2941
+ Ctrl rather than a bare click, which is the terminal's own
2942
+ convention for a link and also the reason a click while reading
2943
+ cannot launch a browser by accident.
2944
+
2945
+ The target is read back out of the style METADATA the span was
2946
+ drawn with, so what opens is what was underlined, which is what
2947
+ the reader saw. `markdown.clickable` is re-asked here rather than
2948
+ trusted from render time: the styles in a `RichLog` outlive the
2949
+ text that produced them, and a check at the point of ACTION is
2950
+ the one that governs.
2951
+
2952
+ Textual dispatches this by position, so a click one column off the
2953
+ URL carries no metadata and does nothing.
2954
+ """
2955
+ if not getattr(event, "ctrl", False):
2956
+ return
2957
+ style = getattr(event, "style", None)
2958
+ meta = getattr(style, "meta", None) or {}
2959
+ url = meta.get("url")
2960
+ if url:
2961
+ self.open_url(url)
2962
+ return
2963
+ # §47. The same gesture, a different kind of target: a URL
2964
+ # leaves for a browser, a call opens a pane. One key each
2965
+ # rather than one key with two meanings, so the branch here
2966
+ # reads as what it is.
2967
+ #
2968
+ # THE TWO PANE TARGETS SHARE A KEY, and that is not the same
2969
+ # compromise: a thread and a session are both "open this in the
2970
+ # viewer", the gesture is identical, and the kind rides in the
2971
+ # value where the app can branch on it once. What the paragraph
2972
+ # above refuses is a key that sometimes means a browser.
2973
+ #
2974
+ # POSTED rather than resolved: the transcript knows which CALL
2975
+ # drew the line and nothing about what it made -- the line is
2976
+ # drawn before the child thread or the session's result exists.
2977
+ opens = meta.get("opens")
2978
+ if opens:
2979
+ self.post_message(CallSelected(str(opens[0]), str(opens[1])))
2980
+
2981
+ def open_url(self, url) -> None:
2982
+ """Hand `url` to the platform's browser, off the UI thread.
2983
+
2984
+ A thread worker for the reason every other outward call in this
2985
+ app uses one: `webbrowser.open` can block while a cold browser
2986
+ starts, and the UI thread is drawing a live stream.
2987
+
2988
+ SILENT on success -- the browser appearing is the confirmation,
2989
+ and a transcript line would call `flush_stream()` and close a
2990
+ live answer span in the middle of a turn. A failure is a toast,
2991
+ which is the vocabulary `tui/app.py` already uses for a turn that
2992
+ did not survive.
2993
+ """
2994
+ if not markdown.clickable(url):
2995
+ return
2996
+
2997
+ # ROADMAP_v3 §79. In a browser tab (Textual's web driver) the
2998
+ # platform's browser is the SERVER's: `webbrowser.open` there opens
2999
+ # nothing the reader can see and reports failure. The driver sends
3000
+ # the URL to the reader's own browser instead, and the tab opening is
3001
+ # the confirmation, as it is here.
3002
+ if self.app.is_web:
3003
+ self.app.open_url(url)
3004
+ return
3005
+
3006
+ def work() -> None:
3007
+ try:
3008
+ opened = webbrowser.open(url)
3009
+ except Exception: # noqa: BLE001 -- reported, never fatal
3010
+ opened = False
3011
+ if not opened:
3012
+ self.app.call_from_thread(
3013
+ self.app.notify,
3014
+ f"Could not open {url}", severity="warning")
3015
+
3016
+ self.run_worker(work, thread=True, exit_on_error=False,
3017
+ name="open-url")
896
3018
 
897
3019
  def write_user(self, text: str) -> None:
898
3020
  self.flush_stream()
@@ -906,16 +3028,23 @@ class Transcript(RichLog):
906
3028
  self.flush_stream()
907
3029
  self._emit("error", text)
908
3030
 
909
- def write_role(self, role: str, text: str) -> None:
3031
+ def write_role(self, role: str, text: str, links=(),
3032
+ opens: tuple = ()) -> None:
910
3033
  """Write a line in an arbitrary palette role (§26).
911
3034
 
912
3035
  Exists so the research view can style a pass boundary, a tool call
913
3036
  and a failed tool differently without Transcript growing a method
914
3037
  per event kind -- the roles already live in one table, and this is
915
3038
  the accessor for it.
3039
+
3040
+ `links` is batch 65's, and it is ignored for every role outside
3041
+ LINKED_ROLES rather than refused: a caller that has candidates
3042
+ should not have to know which roles use them. `opens` is §47's
3043
+ and follows the same rule -- only a `tool` line arms it,
3044
+ because only a tool call opens a run or a session.
916
3045
  """
917
3046
  self.flush_stream()
918
- self._emit(role, text)
3047
+ self._emit(role, text, links=links, opens=opens)
919
3048
 
920
3049
  def write_answer(self, text: str) -> None:
921
3050
  """A model answer that did not arrive as a stream (a one-shot turn,
@@ -926,6 +3055,46 @@ class Transcript(RichLog):
926
3055
 
927
3056
  # -- streaming ---------------------------------------------------------
928
3057
 
3058
+ def _region_width(self) -> int:
3059
+ """This pane's scrollable width -- or, while `#pane` hides it, the
3060
+ width of the pane the switcher is showing instead (§47).
3061
+
3062
+ A hidden widget has no region, so it measures 0 and RichLog floors
3063
+ the write to min_width (78). Both panes are written while hidden:
3064
+ the viewer is painted before the switcher shows it, and a running
3065
+ turn goes on writing to the live transcript while a stored run is
3066
+ being read. RichLog stores Strips, so a row drawn at 78 stays at 78
3067
+ after the pane comes back -- the answer down the left half of a
3068
+ wide panel, healed only by a restart's replay.
3069
+
3070
+ Equal by construction rather than by hope: every pane in the
3071
+ switcher is the same box in app.tcss (`border: solid`,
3072
+ `padding: 0 1`) and RichLog is `overflow-y: scroll`, so the
3073
+ scrollbar gutter is the same on all of them.
3074
+ `test_the_panes_measure_the_same_width_when_shown` holds that, and
3075
+ it asks the switcher for its children rather than naming them --
3076
+ there were two when this was written, three after §49's SS14 and
3077
+ four after §55's TR10, and the sentence above was the one that had
3078
+ to keep up. Measured at every write, so there is nothing to set
3079
+ when the viewer opens, nothing to clear when it closes, and a
3080
+ resize with the viewer up is simply the next measurement.
3081
+
3082
+ Raises where the widget cannot be measured at all (built bare in the
3083
+ suite); callers guard, as `_wrap_width` always has.
3084
+ """
3085
+ return self.scrollable_content_region.width or self._borrowed_width()
3086
+
3087
+ def _borrowed_width(self) -> int:
3088
+ """The on-screen sibling's width while the switcher hides this pane,
3089
+ or 0 when there is no such sibling to measure."""
3090
+ parent = self.parent
3091
+ if not isinstance(parent, ContentSwitcher):
3092
+ return 0
3093
+ shown = parent.visible_content
3094
+ if shown is self or not isinstance(shown, Transcript):
3095
+ return 0
3096
+ return shown.scrollable_content_region.width
3097
+
929
3098
  def _wrap_width(self, prefix: str = "") -> int:
930
3099
  """Usable text columns for one rendered row, or 0 when there is
931
3100
  nothing to measure.
@@ -939,26 +3108,24 @@ class Transcript(RichLog):
939
3108
  for safety) wrapped a streamed answer ~15 columns narrower than the
940
3109
  same text replayed by rerender() -- so a /theme mid-session visibly
941
3110
  reflowed the conversation, which is the one thing a pre-wrap must
942
- not do.
3111
+ not do. The region is read through `_region_width`, so a pane the
3112
+ switcher is hiding pre-wraps at the width it will be shown at.
943
3113
 
944
3114
  A widget has no size before mount and is built bare throughout the
945
3115
  suite, so the guard is around the measurement itself, for the same
946
3116
  reason _styles' is.
947
3117
  """
948
3118
  try:
949
- width = max(self.scrollable_content_region.width, self.min_width)
3119
+ width = max(self._region_width(), self.min_width)
950
3120
  except Exception: # noqa: BLE001 -- unmounted; the newline rule alone
951
3121
  return 0
952
3122
  width -= len(prefix)
953
3123
  return width if width >= MIN_WRAP_WIDTH else 0
954
3124
 
955
3125
  @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]:
3126
+ def _split_committable(pending: str, width: int,
3127
+ *, marks: bool = False,
3128
+ block: bool = True) -> tuple[str, str]:
962
3129
  """Split `pending` into (commit now, keep buffered).
963
3130
 
964
3131
  The two rules from the class docstring. The over-long-token branch
@@ -966,37 +3133,121 @@ class Transcript(RichLog):
966
3133
  space in it (a URL) would otherwise be held until a newline
967
3134
  arrived, so it is cut at the row boundary -- which is what Rich's
968
3135
  own wrapping does with a word too long for the line.
3136
+
3137
+ `marks` measures the width rule in RENDERED cells rather than in
3138
+ source characters (batch 53), which is what an answer carrying
3139
+ `**bold**` needs: the mark is four cells narrower drawn than
3140
+ written, so a source-column cut lands where Rich would not have
3141
+ wrapped and the streamed rows stop matching the ones rerender()
3142
+ draws from the same text. OFF by default, and the default is the
3143
+ answer for `thinking_delta`: reasoning is rendered as prose, marks
3144
+ and all, so measuring it as anything else would be describing a
3145
+ rendering that does not happen.
3146
+
3147
+ `block` is `markdown.inline_spans`' and travels with `marks`: when
3148
+ the pending text is the tail of a line already partly drawn, its
3149
+ leading spaces are not an indent, so the indent rule must not
3150
+ decide the measurement here when it will not decide the drawing
3151
+ there.
969
3152
  """
970
3153
  cut = pending.rfind("\n")
971
3154
  if cut != -1:
972
3155
  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
3156
+ if not width:
3157
+ return "", pending
3158
+ if marks:
3159
+ return markdown.width_split(pending, width, block=block)
3160
+ return markdown.plain_split(pending, width)
979
3161
 
980
3162
  def stream_delta(self, delta: str) -> None:
981
- self._pending += delta
3163
+ self._arm_retraction()
3164
+ # Batch 145. AT INGRESS, before `_pending` holds it: the
3165
+ # commit rules below measure this buffer in rendered cells, and an
3166
+ # escape sequence counted as cells is a row that wraps early.
3167
+ # Measured: `display_len` read 10 for text whose visible width is
3168
+ # 6, so stripping here also corrects arithmetic that was wrong.
3169
+ self._pending += self._strip(self._answer_ansi, delta)
982
3170
  self._commit_ready()
983
3171
 
3172
+ def _arm_retraction(self) -> None:
3173
+ """Remember where the span now starting begins (batch 113).
3174
+
3175
+ Called by both delta entry points and idempotent within a span,
3176
+ so interleaved reasoning -- which closes an open ANSWER without
3177
+ flushing -- keeps one mark across all the entries of one model
3178
+ call. `flush_stream` is what clears it.
3179
+ """
3180
+ if self._retract_mark is None:
3181
+ self._retract_mark = len(self._entries)
3182
+
984
3183
  def _commit_ready(self) -> None:
985
3184
  """Write whatever of the pending stream can safely be drawn now.
986
3185
 
987
3186
  Loops because one delta can make several rows committable at once
988
3187
  -- a paragraph arriving in one chunk, or a buffer that has been
989
3188
  held back behind a closing fence.
3189
+
3190
+ §38 held the whole chunk while a ``` fence was open. Batch 53 turns
3191
+ that single rejection into `markdown.safe_commit_limit`, a CAP over
3192
+ four constructs -- an open fence, a table, a heading, an unclosed
3193
+ inline mark -- because the reason was never about fences: RichLog
3194
+ appends and cannot rewrite a drawn row, so anything committed in
3195
+ halves renders as its own source and can never be put right.
3196
+
3197
+ A cap is strictly better than the rejection it replaces: a
3198
+ paragraph sharing a buffer with a fence used to wait for the fence
3199
+ to close, and now streams. Where the construct starts the buffer,
3200
+ the cap is 0 and nothing commits -- which is what keeps §38's two
3201
+ fence pins saying what they always said.
3202
+
3203
+ Batch 58 adds the fifth construct (a list item) and the ceiling.
3204
+ `commit_span`'s second value says the cap gave up on a line-scoped
3205
+ hold because HOLD_LIMIT expired, and it reaches the renderer as
3206
+ `line_start=False`: the line is no longer a heading or a list item
3207
+ on EITHER path, so the rows it is drawn in are the rows the replay
3208
+ will draw. Without that a model could hold the screen indefinitely
3209
+ by never sending a newline.
3210
+
3211
+ BATCH 112 ADDS A THIRD RULE: A CUT THAT KEEPS NOTHING BACK COMMITS
3212
+ NOTHING (TECHNICAL_DEBT 24). The width rule can drain the buffer,
3213
+ in exactly one shape -- `width_split`/`plain_split` cut after the
3214
+ last space that fits, and when that space is the buffer's final
3215
+ character (a row that filled the width exactly, then a space that
3216
+ overflows by its own cell) the cut is the whole of it. Committing
3217
+ then buys nothing, because nothing is held back; and if the
3218
+ model's NEXT delta opens with the newline, the newline rule
3219
+ commits a chunk that is only `"\\n"` and both draw paths render it
3220
+ as a blank row the replay does not have (measured: an answer drew
3221
+ 5 rows live and 4 replayed). Holding the row until the next delta
3222
+ or the flush puts the newline in the SAME chunk, where it simply
3223
+ ends the line -- which is what `plain_wrap`'s own docstring
3224
+ already says about the replay side of this shape.
3225
+
3226
+ `limit >= len(self._pending)` is the half that is easy to drop:
3227
+ the split is handed the CAPPED prefix, so a drained prefix is not
3228
+ a drained buffer. Without it a paragraph sitting in front of a
3229
+ held table would wait for the table to close, which is precisely
3230
+ the regression the cap was built to remove.
990
3231
  """
991
3232
  width = self._wrap_width()
992
3233
  while True:
993
- chunk, rest = self._split_committable(self._pending, width)
994
- if not chunk or self._fence_is_open(self._stream_text + chunk):
3234
+ limit, forced = markdown.commit_span(
3235
+ self._stream_text, self._pending)
3236
+ mid_line = bool(self._stream_text) \
3237
+ and not self._stream_text.endswith("\n")
3238
+ chunk, rest = self._split_committable(
3239
+ self._pending[:limit], width, marks=True,
3240
+ block=not mid_line)
3241
+ if not chunk:
995
3242
  return
996
- self._pending = rest
997
- self._write_stream_chunk(chunk)
3243
+ if not chunk.endswith("\n") and not rest \
3244
+ and limit >= len(self._pending):
3245
+ return
3246
+ self._pending = rest + self._pending[limit:]
3247
+ self._write_stream_chunk(chunk, line_start=not (mid_line or forced))
998
3248
 
999
- def _write_stream_chunk(self, chunk: str) -> None:
3249
+ def _write_stream_chunk(self, chunk: str, *,
3250
+ line_start: bool = True) -> None:
1000
3251
  if not self._stream_open:
1001
3252
  self.end_thinking()
1002
3253
  self._open_label()
@@ -1011,7 +3262,7 @@ class Transcript(RichLog):
1011
3262
  # still has to draw one.
1012
3263
  body = chunk[:-1] if chunk.endswith("\n") else chunk
1013
3264
  if body:
1014
- self._render_blocks(body)
3265
+ self._render_blocks(body, line_start=line_start)
1015
3266
  else:
1016
3267
  self.write(Text("", self._style("assistant")))
1017
3268
 
@@ -1025,7 +3276,12 @@ class Transcript(RichLog):
1025
3276
  ordering for free.
1026
3277
  """
1027
3278
  self.end_thinking()
1028
- return self._close_answer()
3279
+ text = self._close_answer()
3280
+ # Batch 113. A flush ENDS the retractable region: what it just
3281
+ # committed belongs to a model call that finished, and the next
3282
+ # delta will arm a new mark where its own span begins.
3283
+ self._retract_mark = None
3284
+ return text
1029
3285
 
1030
3286
  def _close_answer(self) -> str:
1031
3287
  """flush_stream without the thinking half.
@@ -1037,6 +3293,14 @@ class Transcript(RichLog):
1037
3293
  emits that remainder as a second, standalone thinking entry and
1038
3294
  then drops it.
1039
3295
  """
3296
+ # Batch 145. The span is over, so a sequence still open was never
3297
+ # going to be completed by a later delta. Discarded rather than
3298
+ # released (`release_unterminated=False`), and discarded HERE
3299
+ # rather than left in place, because a carry that outlived its span
3300
+ # would prepend itself to the next one's first delta and eat a
3301
+ # character of it -- which is the measurement in `_new_strippers`,
3302
+ # arriving between two spans instead of between two streams.
3303
+ self._answer_ansi.flush()
1040
3304
  if not self._pending and not self._stream_open:
1041
3305
  return ""
1042
3306
  residual, self._pending = self._pending, ""
@@ -1047,9 +3311,14 @@ class Transcript(RichLog):
1047
3311
  self._emit("assistant", residual)
1048
3312
  return residual
1049
3313
  if residual:
3314
+ # Read BEFORE the append, for _commit_ready's reason: the
3315
+ # flush draws the tail of a line the stream may already have
3316
+ # drawn part of, and that tail is not the start of one.
3317
+ line_start = not self._stream_text \
3318
+ or self._stream_text.endswith("\n")
1050
3319
  self._stream_text += residual
1051
3320
  self._entries[-1] = ("assistant", self._stream_text)
1052
- self._render_blocks(residual)
3321
+ self._render_blocks(residual, line_start=line_start)
1053
3322
  text = self._stream_text
1054
3323
  self._stream_open = False
1055
3324
  self._stream_text = ""
@@ -1066,24 +3335,57 @@ class Transcript(RichLog):
1066
3335
  self._style("thinking")))
1067
3336
 
1068
3337
  def _write_thinking_lines(self, text: str) -> None:
1069
- """One bar-prefixed row per source line. The rows are pre-wrapped
1070
- by the time they arrive here (that is what _wrap_width's prefix
1071
- argument is for), because RichLog's own soft wrap would put the
1072
- bar on the first row of a wrapped line and nothing on the rest."""
3338
+ """One bar-prefixed row per RENDERED row.
3339
+
3340
+ RichLog's own soft wrap would put the bar on the first row of a
3341
+ wrapped line and nothing on the rest, so every source line is cut
3342
+ into rows here, at `_wrap_width`'s width after the bar, by
3343
+ `markdown.plain_wrap` -- `plain_split`'s rule, the one
3344
+ `thinking_delta` commits by.
3345
+
3346
+ It has to happen HERE and not only in `thinking_delta`, because two
3347
+ callers hand this lines longer than a row: a replay (`rerender()`, a
3348
+ resumed thread, the thread viewer) passes the whole entry, and the
3349
+ newline rule commits everything through the last newline uncut.
3350
+ Both drew their continuation rows with no bar -- visible in any
3351
+ restarted session with long reasoning. A chunk `thinking_delta` has
3352
+ already cut fits one row and passes through as it was.
3353
+ """
3354
+ width = self._wrap_width(THINKING_INDENT + THINKING_BAR)
1073
3355
  lines = text.split("\n")
1074
3356
  if lines and lines[-1] == "":
1075
3357
  lines.pop()
3358
+ style = self._style("thinking")
1076
3359
  for line in lines:
1077
- self.write(Text(f"{THINKING_INDENT}{THINKING_BAR}{line}",
1078
- self._style("thinking")))
3360
+ for row in markdown.plain_wrap(line, width):
3361
+ self.write(Text(f"{THINKING_INDENT}{THINKING_BAR}{row}",
3362
+ style))
1079
3363
 
1080
3364
  def thinking_delta(self, delta: str) -> None:
1081
- self._thinking_pending += delta
3365
+ self._arm_retraction()
3366
+ # Batch 145, and `stream_delta`'s comment. Its own
3367
+ # stripper, because the two spans interleave -- see
3368
+ # `_new_strippers` for what a shared one was measured to do.
3369
+ self._thinking_pending += self._strip(self._thinking_ansi, delta)
3370
+ self._commit_thinking_ready()
3371
+
3372
+ def _commit_thinking_ready(self) -> None:
3373
+ """`_commit_ready` for the reasoning span, and split out of
3374
+ `thinking_delta` for its reason: `reflow()` has to re-commit a
3375
+ buffer nothing has added to."""
1082
3376
  width = self._wrap_width(THINKING_INDENT + THINKING_BAR)
1083
3377
  while True:
1084
3378
  chunk, rest = self._split_committable(self._thinking_pending, width)
1085
3379
  if not chunk:
1086
3380
  return
3381
+ # A cut that keeps nothing back commits nothing, for
3382
+ # _commit_ready's reason (TECHNICAL_DEBT 24) -- and here with
3383
+ # no `limit` clause beside it, because this path has no
3384
+ # commit cap and the buffer IS the whole of what was offered.
3385
+ # Measured before the fix: a streamed span drew 7 rows where
3386
+ # the replay drew 6, the extra one a bar with nothing beside it.
3387
+ if not chunk.endswith("\n") and not rest:
3388
+ return
1087
3389
  self._thinking_pending = rest
1088
3390
  self._write_thinking_chunk(chunk)
1089
3391
 
@@ -1104,6 +3406,11 @@ class Transcript(RichLog):
1104
3406
  def end_thinking(self) -> str:
1105
3407
  """Close the thinking span, if one is open. Idempotent: every
1106
3408
  non-thinking event calls it, and most of them find nothing."""
3409
+ # Batch 145, for `_close_answer`'s reason. Before the early
3410
+ # return, so an idempotent call that finds no span still clears a
3411
+ # carry -- `flush` on an empty stripper costs nothing, which is
3412
+ # what lets this sit in front of the cheap exit.
3413
+ self._thinking_ansi.flush()
1107
3414
  if not self._thinking_open and not self._thinking_pending:
1108
3415
  return ""
1109
3416
  residual, self._thinking_pending = self._thinking_pending, ""
@@ -1149,8 +3456,36 @@ class Transcript(RichLog):
1149
3456
  # in the session with no `venastine ›`.
1150
3457
  self._label_in_force = False
1151
3458
  self._entries.clear()
3459
+ # Batch 113, on the open-span flags' list and for their reason: a
3460
+ # mark left pointing into an emptied log would have the next
3461
+ # retraction truncate to an index that no longer means anything.
3462
+ self._retract_mark = None
3463
+ # Batch 145, on the same list and for the same reason twice over: a
3464
+ # carry left behind would put the previous thread's unterminated
3465
+ # sequence in front of this one's first delta, and a count left
3466
+ # behind would be reported against a thread that did not produce it.
3467
+ self._new_strippers()
3468
+ # Batch 65, and the same sentence as the line above it: a click
3469
+ # target left behind would belong to a thread that is no longer
3470
+ # on screen, and index N would then arm the NEXT thread's Nth
3471
+ # line with the previous one's URL.
3472
+ self._links.clear()
3473
+ # §47, on `_links`' list for its reason: keyed by entry index,
3474
+ # so a table that outlived its entries would arm the NEXT
3475
+ # thread's Nth line with the previous thread's run.
3476
+ self._opens.clear()
1152
3477
  self.clear()
1153
3478
 
3479
+ def opens_at(self, index: int) -> tuple:
3480
+ """The `(kind, call id)` recorded for entry `index`, or `()`
3481
+ (§47, widened by §49 SS14).
3482
+
3483
+ An accessor because the app resolves at press time and has no
3484
+ business reading a private table -- and because `_opens` is
3485
+ keyed by entry index, which is this widget's own bookkeeping.
3486
+ """
3487
+ return self._opens.get(index, ())
3488
+
1154
3489
  def rerender(self) -> None:
1155
3490
  """Redraw every entry under the current theme.
1156
3491
 
@@ -1158,15 +3493,256 @@ class Transcript(RichLog):
1158
3493
  cannot restyle what is already on screen -- without this, /theme
1159
3494
  would leave the session split between two palettes at the exact
1160
3495
  line the command was typed.
3496
+
3497
+ The flush is what makes this safe to call from a COMMAND and unsafe
3498
+ to call from an event: it closes an open answer span, so a resize
3499
+ routed here mid-turn would split the live answer into two entries
3500
+ under two `venastine ›` labels. `reflow()` below is the route that
3501
+ does not (TECHNICAL_DEBT 23).
1161
3502
  """
1162
3503
  self.flush_stream()
3504
+ self._replay()
3505
+
3506
+ def _replay(self) -> None:
3507
+ """Draw `_entries` from an empty screen. The shared half of
3508
+ `rerender()` and `reflow()`, which differ only in what they do to
3509
+ an open span before calling it."""
1163
3510
  self.clear()
1164
3511
  # §43 (RM1). The screen is empty, so no label is in force; the
1165
3512
  # loop below re-derives every one of them from the role sequence
1166
3513
  # exactly as the live path did.
1167
3514
  self._label_in_force = False
1168
- for role, text in self._entries:
1169
- self._render_entry(role, text)
3515
+ last = len(self._entries) - 1
3516
+ for index, (role, text) in enumerate(self._entries):
3517
+ # Batch 65: the targets too, or a /theme would silently
3518
+ # disarm every long URL in the session -- the line would
3519
+ # look identical and stop being clickable, which is the
3520
+ # kind of loss only the pointer can find.
3521
+ # §47's side table too, for batch 65's reason one table
3522
+ # over: a /theme that dropped it would leave every spawn
3523
+ # line looking identical and silently unopenable.
3524
+ self._render_entry(role, text,
3525
+ self._links.get(index, ()),
3526
+ self._opens.get(index, ()),
3527
+ closed=not (self._thinking_open
3528
+ and index == last))
3529
+
3530
+ # -- reflow on resize (TECHNICAL_DEBT 23, batch 112) --------------------
3531
+
3532
+ def on_resize(self, _event) -> None:
3533
+ """Coalesce a redraw at the new width.
3534
+
3535
+ RichLog renders at WRITE time and stores Strips, so nothing already
3536
+ drawn re-wraps by itself: widen a terminal mid-session and every row
3537
+ drawn before the drag keeps the width it was drawn at while new rows
3538
+ use the full panel. Measured before the fix: rows 114 wide against a
3539
+ 198-column panel.
3540
+
3541
+ Two guards, both load-bearing. A `Resize` also arrives for a HEIGHT
3542
+ change, which moves no wrap, so the redraw is keyed on
3543
+ `_wrap_width()` changing rather than on the event. And a width of 0
3544
+ is "cannot be measured" (a widget before mount, a bare-built one in
3545
+ the suite), never a real narrow pane -- a hidden pane measures its
3546
+ on-screen sibling through `_region_width` and DOES reflow, which is
3547
+ batch 90's fix and the reason this cannot simply skip hidden panes.
3548
+ """
3549
+ width = self._wrap_width()
3550
+ if not width or width == self._drawn_width:
3551
+ return
3552
+ if self._reflow_timer is not None:
3553
+ self._reflow_timer.stop()
3554
+ self._reflow_timer = self.set_timer(REFLOW_DEBOUNCE_S, self.reflow)
3555
+
3556
+ def reflow(self) -> None:
3557
+ """Re-lay the whole transcript at the current width, WITHOUT closing
3558
+ an open span.
3559
+
3560
+ That is the whole difference from `rerender()`, and it is the reason
3561
+ item 23 stayed open: a replay that flushes first would end the
3562
+ answer being streamed and start the next chunk as a second entry
3563
+ under a second label, which is what §38's one-entry-per-span rule
3564
+ exists to prevent.
3565
+ """
3566
+ if not self._wrap_width():
3567
+ return
3568
+ fraction, at_bottom = self._scroll_fraction()
3569
+ # AUTO-SCROLL OFF FOR THE REDRAW. RichLog scrolls to the end after
3570
+ # every write, and it DEFERS that scroll to after the next screen
3571
+ # refresh -- so a position set here would be overwritten a frame
3572
+ # later by the last write's pending scroll_end, and the reader
3573
+ # would land at the bottom however carefully it was computed.
3574
+ # `rerender()` is left alone: /theme belongs at the bottom.
3575
+ auto, self.auto_scroll = self.auto_scroll, False
3576
+ try:
3577
+ self._uncommit_partial_line()
3578
+ self._replay()
3579
+ # AND COMMIT AGAIN AT THE NEW WIDTH, which is not tidying: the
3580
+ # line handed back above is usually the whole of an open span
3581
+ # (a model sends a paragraph before it sends a newline), so a
3582
+ # replay on its own would leave the reader watching their
3583
+ # half-written answer disappear until the next delta arrived.
3584
+ # These re-cut it at the width now in force and put it back.
3585
+ self._commit_ready()
3586
+ self._commit_thinking_ready()
3587
+ finally:
3588
+ self.auto_scroll = auto
3589
+ self._restore_scroll(fraction, at_bottom)
3590
+
3591
+ def _uncommit_partial_line(self) -> None:
3592
+ """Give an open span's half-drawn line back to its pending buffer.
3593
+
3594
+ Without this the replay draws `_stream_text` whole -- ending in the
3595
+ middle of a line -- and the next committed chunk is a separate
3596
+ `write()` and therefore a separate ROW, so the join lands mid-row at
3597
+ the new width and the seam is visible for the rest of the answer.
3598
+ Handing the tail back means the next commit re-cuts it at the width
3599
+ now in force.
3600
+
3601
+ `_entries` moves with it. Pending text has never been in the entry
3602
+ log, so keeping the two in step is what lets a `/copy` or a `/theme`
3603
+ in the same window agree with the screen; the flush appends the
3604
+ residual back at the end of the span, exactly as it always has.
3605
+
3606
+ If the tail was the whole entry, the entry goes: an empty assistant
3607
+ entry would replay as a row nothing wrote, and `_open_label`'s guard
3608
+ means the next chunk re-opening the span draws the same single
3609
+ label. The two branches cannot both fire -- opening either span
3610
+ closes the other -- and both are written because the state is
3611
+ per-span and reading one to decide the other is how they drift.
3612
+ """
3613
+ if self._stream_open:
3614
+ tail = self._stream_text.rsplit("\n", 1)[-1]
3615
+ if tail:
3616
+ self._stream_text = self._stream_text[:-len(tail)]
3617
+ self._pending = tail + self._pending
3618
+ if self._stream_text:
3619
+ self._entries[-1] = ("assistant", self._stream_text)
3620
+ else:
3621
+ self._drop_last_entry()
3622
+ self._stream_open = False
3623
+ if self._thinking_open:
3624
+ tail = self._thinking_text.rsplit("\n", 1)[-1]
3625
+ if tail:
3626
+ self._thinking_text = self._thinking_text[:-len(tail)]
3627
+ self._thinking_pending = tail + self._thinking_pending
3628
+ if self._thinking_text:
3629
+ self._entries[-1] = ("thinking", self._thinking_text)
3630
+ else:
3631
+ self._drop_last_entry()
3632
+ self._thinking_open = False
3633
+
3634
+ def _drop_last_entry(self) -> None:
3635
+ """Remove the final entry and the side-table rows keyed to it.
3636
+
3637
+ Both tables are keyed by INDEX, and the index this frees is the one
3638
+ the next appended entry takes -- so a row left behind would arm an
3639
+ unrelated line with someone else's URL or someone else's call."""
3640
+ index = len(self._entries) - 1
3641
+ self._entries.pop()
3642
+ self._links.pop(index, None)
3643
+ self._opens.pop(index, None)
3644
+
3645
+ def retract_to_mark(self, note: str | None = None) -> None:
3646
+ """Take back everything drawn since the last flush, and redraw.
3647
+
3648
+ TECHNICAL_DEBT 25, batch 113. A model call that fails mid-answer
3649
+ can now be tried again, and the reader must not be shown the
3650
+ answer twice -- so what the failed attempt drew is deleted from
3651
+ `_entries` and the transcript is redrawn from what is left. The
3652
+ redraw is batch 112's `_replay()`, which is the whole reason this
3653
+ costs a dozen lines rather than a batch of its own.
3654
+
3655
+ A MARK AND NOT A SPAN, which is the part worth reading. The
3656
+ obvious rule is "drop the open span", and it is wrong: interleaved
3657
+ reasoning makes `_write_thinking_chunk` close an open ANSWER
3658
+ before it draws, so one attempt can leave several entries behind
3659
+ with only the last of them open. Measured -- text, then reasoning,
3660
+ then text, inside one attempt, is three entries and one open span.
3661
+ Dropping the open one would leave the first two on screen and the
3662
+ retry would then draw them again underneath.
3663
+
3664
+ THE MARK IS ARMED BY THE FIRST DELTA and CLEARED BY A FLUSH, and
3665
+ the asymmetry is the correction of a rule this batch tried first.
3666
+ Taking the mark at the flush reads well and is wrong, because
3667
+ `write_system`, `write_user`, `write_error` and `write_role` all
3668
+ OPEN with `flush_stream()`: a line written while a span was live
3669
+ moved the mark past the attempt's own text, so the retraction
3670
+ deleted the unrelated line and kept the half-answer. Wrong in
3671
+ both directions at once, and found by the test written to pin
3672
+ what the rule was supposed to cost.
3673
+
3674
+ Armed at the span's start instead, the ordinary case is identical
3675
+ -- the app flushes before a tool line and at the end of a turn,
3676
+ so the mark lands at the beginning of the call now streaming --
3677
+ and the awkward one degrades to doing nothing, which is the right
3678
+ way for it to fail.
3679
+
3680
+ Idempotent, and a no-op when nothing is armed: an attempt that
3681
+ failed before its first delta has nothing to take back, which is
3682
+ also why the loop guards the event on `shown`. The `note` is
3683
+ still written in that case, because the retry is happening
3684
+ whether or not this widget had anything to undo.
3685
+
3686
+ `note`, when given, is written under the redraw and survives the
3687
+ next retraction; the tail of this method says why that costs
3688
+ nothing.
3689
+ """
3690
+ while (self._retract_mark is not None
3691
+ and len(self._entries) > self._retract_mark):
3692
+ self._drop_last_entry()
3693
+ # The buffers as well as the entries: text held back by the commit
3694
+ # cap was produced by the attempt being retracted, and leaving it
3695
+ # would splice the dead attempt's tail onto the new one's head.
3696
+ self._pending = ""
3697
+ self._stream_text = ""
3698
+ self._stream_open = False
3699
+ self._thinking_pending = ""
3700
+ self._thinking_text = ""
3701
+ self._thinking_open = False
3702
+ # Both spans are closed now, so the replay draws every entry
3703
+ # closed -- which is correct here and is exactly what `reflow()`
3704
+ # must NOT do, the one place the two callers differ.
3705
+ self._retract_mark = None
3706
+ self._replay()
3707
+ # No scroll restore, unlike `reflow()`. A retraction happens at the
3708
+ # live end of the transcript with the reader watching it, so
3709
+ # `auto_scroll` keeping them at the bottom is the right answer --
3710
+ # `/theme`'s reasoning, not a resize's.
3711
+ if note:
3712
+ # AND IT SURVIVES THE NEXT RETRACTION for free, which is worth
3713
+ # a sentence because the first version of this method bought
3714
+ # it with a line of code. `write_system` opens with
3715
+ # `flush_stream()`, so the note lands with NOTHING armed, and
3716
+ # the next delta arms the mark after it. Two failures
3717
+ # therefore leave two lines rather than one reading "attempt 3
3718
+ # of 3" with nothing saying there had been an attempt 2 --
3719
+ # which is the disclosure §21 spent a section on. Under the
3720
+ # rule this batch tried first, where a flush SET the mark, the
3721
+ # note would have landed inside the next retraction's region
3722
+ # and an explicit advance was needed; the mutation pass found
3723
+ # that line still here and no longer doing anything.
3724
+ self.write_system(note)
3725
+
3726
+ def _scroll_fraction(self) -> tuple:
3727
+ """How far down the transcript the reader is, and whether that is
3728
+ the bottom. A fraction rather than a row, because the row COUNT
3729
+ changes with the width -- an exact restore is not available at any
3730
+ price, and a resize is involuntary, so landing back where /theme
3731
+ lands (the bottom) would lose a reader's place on a window drag."""
3732
+ limit = self.max_scroll_y
3733
+ if not limit:
3734
+ return 0.0, True
3735
+ return self.scroll_y / limit, self.scroll_y >= limit - 1
3736
+
3737
+ def _restore_scroll(self, fraction: float, at_bottom: bool) -> None:
3738
+ """`immediate=True` on both, because the default defers the scroll
3739
+ to after the next refresh and the reflow is already over by then --
3740
+ the same deferral that makes turning `auto_scroll` off necessary."""
3741
+ if at_bottom:
3742
+ self.scroll_end(animate=False, immediate=True, x_axis=False)
3743
+ return
3744
+ self.scroll_to(y=round(fraction * self.max_scroll_y),
3745
+ animate=False, immediate=True)
1170
3746
 
1171
3747
  def last_answer(self) -> str:
1172
3748
  """The most recent answer in this session, or "" (for /copy last).
@@ -1218,22 +3794,3 @@ class Transcript(RichLog):
1218
3794
  label = labels.get(role)
1219
3795
  out.append(f"{label}: {text}" if label else text)
1220
3796
  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