@yahyahammad/venastine 0.2.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 (129) hide show
  1. package/.env.example +19 -14
  2. package/CONFIG_ARCHITECTURE.md +2002 -0
  3. package/NOTICE +1 -1
  4. package/README.md +233 -94
  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 +277 -43
  12. package/agents/tui_commands.py +7 -12
  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 +158 -20
  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 +1238 -82
  29. package/core/commands.py +454 -0
  30. package/core/compaction.py +830 -66
  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 +1516 -440
  38. package/core/memory.py +120 -8
  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 +158 -26
  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 +1671 -199
  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 +7 -12
  70. package/package.json +234 -4
  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 +51 -2
  80. package/requirements.txt +252 -29
  81. package/safety/policy_enforcement.py +353 -17
  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 +368 -35
  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 +347 -30
  118. package/tui/app.py +4645 -438
  119. package/tui/app.tcss +185 -2
  120. package/tui/commands.py +10 -154
  121. package/tui/diffs.py +286 -265
  122. package/tui/hosted_driver.py +102 -0
  123. package/tui/markdown.py +60 -10
  124. package/tui/meters.py +103 -7
  125. package/tui/screens.py +346 -92
  126. package/tui/themes.py +59 -19
  127. package/tui/widgets.py +1575 -111
  128. package/SECURITY.md +0 -88
  129. package/THIRD_PARTY_NOTICES.md +0 -100
package/tui/widgets.py CHANGED
@@ -1,28 +1,75 @@
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
 
8
21
  import webbrowser
22
+ from dataclasses import dataclass
9
23
 
10
24
  from rich import box
25
+ from rich.cells import cell_len
11
26
  from rich.console import Console
27
+ from rich.measure import measure_renderables
12
28
  from rich.style import Style
13
29
  from rich.syntax import Syntax
14
30
  from rich.table import Table
15
31
  from rich.text import Text
16
32
  from textual.binding import Binding
33
+ from textual.content import Content
17
34
  from textual.message import Message
18
35
  from textual.reactive import reactive
19
- from textual.widgets import RichLog, Static, TextArea
36
+ from textual.widgets import ContentSwitcher, RichLog, Static, TextArea
20
37
 
38
+ from core.ansi import AnsiStripper
21
39
  from prompts.system_prompts import pass_label
22
-
23
40
  from tui import diffs, markdown, ravens, themes
24
41
  from tui.commands import registry as commands
25
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)
71
+
72
+
26
73
  # Animation cadence. Slow enough to read, and paused outright while tokens
27
74
  # are streaming -- a redraw loop competing with token deltas is the one
28
75
  # place the mascot can cost responsiveness rather than just effort.
@@ -43,6 +90,14 @@ THINKING_INDENT = " "
43
90
  # (a bare-built test widget, a widget before mount) reads as 0.
44
91
  MIN_WRAP_WIDTH = 20
45
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
+
46
101
  # Batch 55, the slash-command suggestion panel. The two caps are a pair:
47
102
  # five entries is the list a reader takes in at a glance, eight rows is
48
103
  # what leaves the transcript readable at the 24-row floor, and at 80
@@ -163,7 +218,14 @@ MARK_STAGE = "·"
163
218
  # one target or the other by accident.
164
219
  CONVERSATION_ROLES = frozenset({
165
220
  "user", "assistant", "thinking", "tool", "tool_error", "diff",
166
- "pipeline_tool"})
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"})
167
229
 
168
230
  # `pass` and `pass_done` are here rather than above deliberately: a
169
231
  # ten-pass run's boundaries are progress reporting about the harness,
@@ -174,7 +236,15 @@ CONVERSATION_ROLES = frozenset({
174
236
  # call now can -- and it classifies as CONVERSATION so batch 48's copy
175
237
  # shape survives the rename unchanged.
176
238
  META_ROLES = frozenset({
177
- "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"})
178
248
 
179
249
  # Batch 65 (TECHNICAL_DEBT 16). The lines whose URLs are armed for
180
250
  # ctrl+click, beside the two sets above for their reason: which roles a
@@ -191,11 +261,27 @@ META_ROLES = frozenset({
191
261
  # They take the LINKS-ONLY scanner, never the prose grammar. A tool
192
262
  # line is a digest, and `markdown.link_spans` says at length what the
193
263
  # full grammar does to one.
194
- LINKED_ROLES = frozenset({"tool", "pipeline_tool", "tool_error"})
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"})
195
269
 
196
270
 
197
271
  class RavenPanel(Static):
198
- """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
+ """
199
285
 
200
286
  # NOT always_update=True. Every token_delta reassigns state to
201
287
  # THINKING, so always_update fired watch_state once per token for the
@@ -204,24 +290,51 @@ class RavenPanel(Static):
204
290
  # pause_animation exists to eliminate. Genuine transitions still fire.
205
291
  state = reactive(ravens.IDLE)
206
292
 
207
- def __init__(self, animations: bool = True, **kwargs):
293
+ def __init__(self, animations: bool = True, still_when_idle: bool = False,
294
+ **kwargs):
208
295
  super().__init__(**kwargs)
209
296
  self._animations = animations
297
+ self._still_when_idle = still_when_idle
298
+ self._held = False # the app paused it, for a token stream
210
299
  self._frame = 0
211
300
  self._timer = None
212
301
 
213
302
  def on_mount(self) -> None:
214
303
  if self._animations:
215
304
  self._timer = self.set_interval(ANIMATION_INTERVAL, self._advance)
305
+ self._hold_still_if_idle()
216
306
  self._render_state()
217
307
 
218
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
219
320
  self._frame += 1
220
321
  self._render_state()
221
322
 
222
323
  def watch_state(self) -> None:
223
324
  self._frame = 0
224
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()
225
338
 
226
339
  def _render_state(self) -> None:
227
340
  frames = self.state.frames
@@ -230,11 +343,13 @@ class RavenPanel(Static):
230
343
 
231
344
  def pause_animation(self) -> None:
232
345
  """Called while a token stream is active. Idempotent."""
346
+ self._held = True
233
347
  if self._timer is not None:
234
348
  self._timer.pause()
235
349
 
236
350
  def resume_animation(self) -> None:
237
- if self._timer is not None:
351
+ self._held = False
352
+ if self._timer is not None and not self._idle_and_still():
238
353
  self._timer.resume()
239
354
 
240
355
 
@@ -280,7 +395,7 @@ class ThinkingIndicator(Static):
280
395
  except Exception: # noqa: BLE001 -- no running app; render unstyled
281
396
  style = ""
282
397
  frame = self.FRAMES[self._frame] if self._animations else self.FRAMES[-1]
283
- self.update(Text(f"{THINKING_INDENT}{frame}", style))
398
+ self.update(as_content(Text(f"{THINKING_INDENT}{frame}", style)))
284
399
 
285
400
  def start(self) -> None:
286
401
  """Idempotent -- called on every thinking delta."""
@@ -348,7 +463,7 @@ class PostureBadge(Static):
348
463
  body = Text("!! REDUCED SECURITY\n")
349
464
  for label, _detail in self._reasons:
350
465
  body.append("- " + label + "\n")
351
- self.update(body)
466
+ self.update(as_content(body))
352
467
  self.display = True
353
468
 
354
469
 
@@ -391,17 +506,30 @@ class UsageLine(Static):
391
506
  self.update("")
392
507
 
393
508
  def update_usage(self, billed: int, ctx: int,
394
- ceiling: int = 0, overridden: bool = False) -> None:
509
+ ceiling: int = 0, overridden: bool = False,
510
+ window: int = 0) -> None:
395
511
  """`ceiling` is the compaction trigger this thread is measured
396
- against, shown as a denominator so `ctx` has a scale. `overridden`
397
- marks it with a `*` when a session /trigger set it -- ephemeral
398
- state that changes when compaction fires should not be invisible,
399
- which is the same rule M14 states for injected memories.
400
-
401
- 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
402
530
  gets the batch-27 two-instrument line unchanged.
403
531
  """
404
- key = (billed, ctx, ceiling, overridden)
532
+ key = (billed, ctx, ceiling, overridden, window)
405
533
  if key == self._last or not (billed or ctx):
406
534
  # Change-guard: on_loop_event fires per token delta during a
407
535
  # stream; both figures only move at step boundaries, so this
@@ -413,13 +541,26 @@ class UsageLine(Static):
413
541
  return f"{n / 1000:.0f}k" if n >= 1000 else str(n)
414
542
 
415
543
  self.display = True
416
- 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 = ""
417
557
  # `system` is the harness-talking-about-itself role -- the right
418
558
  # meaning for a usage line, and the palette route the batch-26
419
559
  # guard test demands (it caught this line as a literal within one
420
560
  # commit of the widget existing).
421
- self.update(Text(f"usage · ctx {_k(ctx)}{scale} · billed {_k(billed)}",
422
- 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", ""))))
423
564
 
424
565
 
425
566
  class GoalBanner(Static):
@@ -450,7 +591,7 @@ class GoalBanner(Static):
450
591
  # is the second place a weight would be decided. Guarded still,
451
592
  # because a bare-built widget has no styles dict at all.
452
593
  style = self._styles().get("warning", "") or "bold"
453
- self.update(Text(f"goal {self.goal}", style=style))
594
+ self.update(as_content(Text(f"goal {self.goal}", style=style)))
454
595
  else:
455
596
  self.display = False
456
597
  self.update("")
@@ -530,19 +671,316 @@ class TodoPanel(Static):
530
671
  body.append(f"(+{len(items) - self.ROWS} earlier)\n",
531
672
  styles.get("system", ""))
532
673
  self.display = True
533
- 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
534
965
 
535
966
 
536
967
  class AgentPanel(Static):
537
968
  """Who is running, and how deep (batch 59).
538
969
 
539
- A STACK, NEVER A LIST OF PEERS, and that is a fact about the harness
540
- rather than a rendering choice. core/loop.py dispatches tool calls in
541
- a plain `for` loop and spawn_subagent BLOCKS on the child run, so
542
- there is never a second agent alongside the first -- what there is is
543
- a chain, each frame suspended inside the one below it, bounded by
544
- config.SUBAGENT_MAX_DEPTH. Indentation is the honest drawing of that;
545
- a flat list would claim a concurrency this harness does not have.
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`.
546
984
 
547
985
  Fed from core/agent_activity.py through app.py, never polled -- the
548
986
  same split TodoPanel keeps: the sink says when, and this widget holds
@@ -551,6 +989,13 @@ class AgentPanel(Static):
551
989
  Hidden when it has nothing to say, GoalBanner-style: the sidebar is
552
990
  twenty columns wide and its rows are contested, so `default` with an
553
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.
554
999
  """
555
1000
 
556
1001
  # 22-column box, less a border column and a padding column each side.
@@ -567,6 +1012,7 @@ class AgentPanel(Static):
567
1012
  super().__init__(**kwargs)
568
1013
  self._agent = None
569
1014
  self._stack: list = []
1015
+ self._root = None
570
1016
  # Explicit, for TodoPanel's reason: a widget that renders nothing
571
1017
  # yet must not be a visible empty box before its first update.
572
1018
  self.display = False
@@ -578,22 +1024,29 @@ class AgentPanel(Static):
578
1024
  return {}
579
1025
  return themes.styles_for(app)
580
1026
 
581
- def show(self, agent_name, stack) -> None:
1027
+ def show(self, agent_name, stack, root_thread=None) -> None:
582
1028
  """Draw the active agent and the spans currently open under it.
583
1029
 
584
1030
  `agent_name` is None when no /agent switch is active. `stack` is a
585
- list of (name, depth), outermost first.
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.
586
1035
  """
587
1036
  self._agent = agent_name
588
1037
  self._stack = list(stack)
1038
+ self._root = root_thread
589
1039
  self._redraw()
590
1040
 
591
1041
  def restyle(self) -> None:
592
1042
  """Re-render under the current theme (#183), like ResearchProgress."""
593
1043
  self._redraw()
594
1044
 
595
- @classmethod
596
- def _fit(cls, text: str, width: int) -> str:
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:
597
1050
  """Truncate to `width` cells, with an ellipsis when it bites.
598
1051
 
599
1052
  Appended by hand rather than through `Text.truncate()`, which
@@ -601,14 +1054,44 @@ class AgentPanel(Static):
601
1054
  here are `no_wrap`, so an overlong one would be cropped invisibly
602
1055
  instead. `pipeline-reviewer` is seventeen characters and reaches
603
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.
604
1062
  """
605
1063
  if width <= 0:
606
1064
  return ""
607
- if len(text) <= width:
1065
+ if cell_len(text) <= width:
608
1066
  return text
609
1067
  if width == 1:
610
1068
  return "\u2026"
611
- return text[:width - 1] + "\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))
612
1095
 
613
1096
  def _redraw(self) -> None:
614
1097
  if self._agent is None and not self._stack:
@@ -630,23 +1113,209 @@ class AgentPanel(Static):
630
1113
  # of the two without introducing a second hue.
631
1114
  body.append(
632
1115
  self._fit(self._agent or "default", self.WIDTH) + "\n",
633
- styles.get("assistant_label", ""))
634
- for name, depth in self._stack:
635
- # `max(depth, 1)` so a span that somehow reports depth 0 still
636
- # reads as nested rather than colliding with the root row --
637
- # two rows at column zero would say two agents are running,
638
- # which is the one thing this panel must never claim.
639
- pad = " " * (self.INDENT * max(depth, 1))
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)
640
1137
  room = self.WIDTH - len(pad) - 2 # the marker and its space
641
- body.append(f"{pad}{MARK_RUNNING} {self._fit(name, room)}\n",
642
- styles.get("tool", ""))
643
- # `no_wrap` / crop for batch 55's reason: a row this widget already
644
- # sized must not be re-wrapped by the Static underneath it, and a
645
- # miscalculation should clip visibly rather than reflow invisibly.
646
- body.no_wrap = True
647
- body.overflow = "crop"
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.
648
1240
  self.display = True
649
- self.update(body)
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))
1318
+
650
1319
 
651
1320
  class ResearchProgress(Static):
652
1321
  """Live state of a /research run (ROADMAP_v2 §22).
@@ -705,6 +1374,36 @@ class ResearchProgress(Static):
705
1374
  self.display = True
706
1375
  self._redraw()
707
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
+
708
1407
  def pass_started(self, pass_id: str) -> None:
709
1408
  self._passes.append([pass_id, False, False, False, 0, 0])
710
1409
  self._redraw()
@@ -820,7 +1519,7 @@ class ResearchProgress(Static):
820
1519
  body.append(f" {label} {count}\n", styles.get(tier, ""))
821
1520
  if self._retries:
822
1521
  body.append(f"{self._retries} revision(s)\n")
823
- self.update(body)
1522
+ self.update(as_content(body))
824
1523
 
825
1524
 
826
1525
  class SlashSuggest(Static):
@@ -929,13 +1628,14 @@ class SlashSuggest(Static):
929
1628
 
930
1629
  # -- what the prompt drives ---------------------------------------------
931
1630
 
932
- def offer(self, matches: list) -> None:
1631
+ def offer(self, matches: list, label: str | None = None) -> None:
933
1632
  """Replace the list, hiding the panel when it is empty.
934
1633
 
935
1634
  `refresh(layout=True)`, not `update()`: the render is a function of
936
1635
  the width, so the panel has to be re-MEASURED, not just repainted.
937
1636
  """
938
1637
  self._matches = list(matches)
1638
+ self._label = label
939
1639
  self._selected = 0
940
1640
  self._first = 0
941
1641
  self._groups = []
@@ -1015,7 +1715,7 @@ class SlashSuggest(Static):
1015
1715
  long, and the description is the half this panel exists for. The
1016
1716
  flags are what truncates.
1017
1717
  """
1018
- body = "/" + command.name + SUGGEST_SEP + command.summary
1718
+ body = getattr(command, "prefix", "/") + command.name + SUGGEST_SEP + command.summary
1019
1719
  if command.usage:
1020
1720
  body += " " + command.usage
1021
1721
  lines = list(Text(body).wrap(Console(width=inner), inner, no_wrap=False))
@@ -1092,7 +1792,7 @@ class SlashSuggest(Static):
1092
1792
  span = str(len(groups))
1093
1793
  else:
1094
1794
  span = f"{first + 1}-{first + len(groups)}"
1095
- title = f"{span} of {len(self._matches)} · /help for all"
1795
+ title = f"{span} of {len(self._matches)} · {getattr(self, '_label', None) or '/help for all'}"
1096
1796
  if self.border_title != title:
1097
1797
  self.border_title = title
1098
1798
  # Batch 62. The same honesty rule one row down, applied to a
@@ -1182,16 +1882,32 @@ class PromptInput(TextArea):
1182
1882
 
1183
1883
  `priority=True` on enter. `TextArea._on_key` maps enter to a newline
1184
1884
  insert and calls `event.stop()` / `event.prevent_default()`, which
1185
- beats an ordinary binding: measured on the pinned textual 1.0.0 (D22,
1885
+ beats an ordinary binding: measured on the installed textual (D22,
1186
1886
  both ways -- without the flag enter inserts and never submits). It
1187
- reads like caution and is the opposite.
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.
1188
1891
 
1189
1892
  `ctrl+j` is what carries the newline; `shift+enter` is a courtesy.
1190
- Textual turns the kitty keyboard protocol on in its LINUX drivers
1191
- alone (`drivers/linux_driver.py`, `linux_inline_driver.py`), and
1192
- without it a terminal sends a bare CR for shift+enter and the parser
1193
- yields plain `enter` -- so on Windows that binding is unreachable and
1194
- the box would submit instead. `ctrl+j` is byte 0x0a, parses to its own
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
1195
1911
  key, is bound by neither Input, TextArea, App nor Footer, and is
1196
1912
  exactly what iTerm2 / VS Code / Windows Terminal emit once configured
1197
1913
  to send a newline on shift+enter. `alt+enter` is the obvious third
@@ -1219,10 +1935,12 @@ class PromptInput(TextArea):
1219
1935
  both keys, but only while the panel is open: `check_action` hands them
1220
1936
  back to the focus system and to nobody the rest of the time.
1221
1937
 
1222
- The placeholder is the border TITLE because `TextArea` has no
1223
- placeholder at all -- no parameter, no attribute. Taking it as a
1224
- `placeholder=` keyword anyway keeps the call site in app.py reading
1225
- as it always did.
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`.
1226
1944
  """
1227
1945
 
1228
1946
  BINDINGS = [
@@ -1241,6 +1959,9 @@ class PromptInput(TextArea):
1241
1959
  suggest = None # the SlashSuggest panel; app.py hands it over
1242
1960
  _api_edit = False # the next Changed came from .value, not a key
1243
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
1244
1965
 
1245
1966
  class Submitted(Message):
1246
1967
  """Posted when enter is pressed. `Input.Submitted`'s shape.
@@ -1271,9 +1992,11 @@ class PromptInput(TextArea):
1271
1992
  transcript and textual does not re-pin a scroll on shrink.
1272
1993
  """
1273
1994
 
1274
- def __init__(self, prompt: "PromptInput", matches: list) -> None:
1995
+ def __init__(self, prompt: "PromptInput", matches: list,
1996
+ label: str | None = None) -> None:
1275
1997
  self.prompt = prompt
1276
1998
  self.matches = matches
1999
+ self.label = label
1277
2000
  super().__init__()
1278
2001
 
1279
2002
  @property
@@ -1302,7 +2025,9 @@ class PromptInput(TextArea):
1302
2025
 
1303
2026
  def __init__(self, placeholder: str = "", **kwargs) -> None:
1304
2027
  super().__init__(soft_wrap=True, show_line_numbers=False, **kwargs)
1305
- self.placeholder = placeholder
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.
1306
2031
  self.border_title = placeholder
1307
2032
 
1308
2033
  @property
@@ -1319,24 +2044,52 @@ class PromptInput(TextArea):
1319
2044
  # See the docstring: this is the API half of the API/keyboard
1320
2045
  # split, and `.value =` reaches it through `.text =`.
1321
2046
  self._api_edit = True
2047
+ self._suggest_enabled = False
1322
2048
  super().load_text(text)
1323
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
+
1324
2076
  def on_text_area_changed(self, event: TextArea.Changed) -> None:
1325
2077
  if self._api_edit:
1326
2078
  # Assignment is not typing. It also CLOSES the panel, which is
1327
2079
  # what makes `event.prompt.value = ""` on submit tidy up.
1328
2080
  self._api_edit = False
1329
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
1330
2089
  self.post_message(self.SuggestionsChanged(self, []))
1331
2090
  return
1332
- matches = commands.matching(self.text)
1333
- if not matches:
1334
- # Nothing to dismiss any more, so the latch is spent. This is
1335
- # what lets a dismissed panel come back: type a space (or clear
1336
- # the line) and the next bare slash token offers again.
1337
- self._dismissed = False
1338
- self.post_message(
1339
- self.SuggestionsChanged(self, [] if self._dismissed else matches))
2091
+ self._suggest_enabled = True
2092
+ self.refresh_suggestions()
1340
2093
 
1341
2094
  def _panel_open(self) -> bool:
1342
2095
  return self.suggest is not None and self.suggest.display
@@ -1348,13 +2101,39 @@ class PromptInput(TextArea):
1348
2101
  command = self.suggest.chosen
1349
2102
  if command is None:
1350
2103
  return False
1351
- # The TRAILING SPACE is doing two jobs: `matching()` is empty once
1352
- # the line has whitespace in it, so the panel closes on its own,
1353
- # and deleting that one character is what brings it back.
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.
1354
2121
  self.value = "/" + command.name + " "
1355
2122
  # load_text leaves the cursor at the START of the document, which
1356
2123
  # would have the next typed argument land in front of the command.
1357
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
1358
2137
  return True
1359
2138
 
1360
2139
  def check_action(self, action: str, parameters) -> bool | None:
@@ -1437,11 +2216,18 @@ class Transcript(RichLog):
1437
2216
  streaming latency should look here first." They should still look
1438
2217
  here first; the answer is now the two rules above.
1439
2218
 
1440
- Known edge, stated rather than fixed: a terminal resize mid-answer
1441
- leaves already-drawn rows wrapped to the old width. `_entries` keeps
1442
- the unwrapped source, so rerender() puts it right, and a resize
1443
- handler for the seconds an answer is in flight is machinery with no
1444
- 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`.
1445
2231
 
1446
2232
  §26 adds two things and one obligation.
1447
2233
 
@@ -1486,6 +2272,10 @@ class Transcript(RichLog):
1486
2272
  # rather than part of what was said. Keyed by INDEX, which
1487
2273
  # rerender() already walks.
1488
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 = {}
1489
2279
  # §38. An assistant span with rows already on screen: its label is
1490
2280
  # drawn and its single entry is open at _entries[-1].
1491
2281
  self._stream_open = False
@@ -1500,6 +2290,165 @@ class Transcript(RichLog):
1500
2290
  # ONE label per turn, above the model's first output of it
1501
2291
  # whether that output is reasoning or text -- see _open_label.
1502
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)
1503
2452
 
1504
2453
  # -- styling -----------------------------------------------------------
1505
2454
 
@@ -1532,21 +2481,51 @@ class Transcript(RichLog):
1532
2481
  # -- writing -----------------------------------------------------------
1533
2482
 
1534
2483
  def _emit(self, role: str, text: str, record: bool = True,
1535
- links=()) -> None:
2484
+ links=(), opens: tuple = ()) -> None:
1536
2485
  """Render one entry and remember it. THE single write path.
1537
2486
 
1538
2487
  `links` are batch 65's click targets, remembered beside the
1539
2488
  entry so a `/theme` rerender arms what the live draw armed. An
1540
2489
  entry with none -- every role outside LINKED_ROLES, and most
1541
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.
1542
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()
1543
2513
  if record:
1544
2514
  self._entries.append((role, text))
1545
2515
  if links:
1546
2516
  self._links[len(self._entries) - 1] = tuple(links)
1547
- self._render_entry(role, text, links)
1548
-
1549
- def _render_entry(self, role: str, text: str, links=()) -> None:
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."""
1550
2529
  if role == "user":
1551
2530
  # §43 (RM1). The turn's label is retired HERE and nowhere
1552
2531
  # else, so where the labels land is a pure function of the
@@ -1556,6 +2535,14 @@ class Transcript(RichLog):
1556
2535
  self.write(Text.assemble(
1557
2536
  ("\nyou › ", self._style("user_label")),
1558
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")))
1559
2546
  elif role == "assistant":
1560
2547
  self._open_label()
1561
2548
  # One trailing newline is dropped, exactly as a committed
@@ -1579,7 +2566,7 @@ class Transcript(RichLog):
1579
2566
  # §43 sentence true: a tool line INSIDE the turn, after
1580
2567
  # reasoning or text has already opened the label, is a no-op.
1581
2568
  self._open_label()
1582
- self.write(self._linked_line(text, "tool", links))
2569
+ self.write(self._linked_line(text, "tool", links, opens))
1583
2570
  elif role == "pipeline_tool":
1584
2571
  # The research pipeline's tool lines. Same kind of line and
1585
2572
  # the same style, deliberately NOT an opener: the run's label
@@ -1595,7 +2582,8 @@ class Transcript(RichLog):
1595
2582
  self._open_label()
1596
2583
  self._write_thinking_open()
1597
2584
  self._write_thinking_lines(text)
1598
- self._write_thinking_close()
2585
+ if closed:
2586
+ self._write_thinking_close()
1599
2587
  elif role in LINKED_ROLES:
1600
2588
  # `tool_error` arrives here, and needs no `links`: its text
1601
2589
  # is redact_secrets(str(error)) with no truncation, so the
@@ -1604,7 +2592,8 @@ class Transcript(RichLog):
1604
2592
  else:
1605
2593
  self.write(Text(f" {text}", self._style(role)))
1606
2594
 
1607
- def _linked_line(self, text: str, role: str, targets=()) -> Text:
2595
+ def _linked_line(self, text: str, role: str, targets=(),
2596
+ opens: tuple = ()) -> Text:
1608
2597
  """One harness-drawn line, with its URLs armed (batch 65).
1609
2598
 
1610
2599
  The five-space indent every one of these lines carries is inside
@@ -1616,8 +2605,56 @@ class Transcript(RichLog):
1616
2605
  out = Text(style=self._style(role))
1617
2606
  self._append_spans(out, f" {text}", self._styles(),
1618
2607
  block=False, links_only=True, targets=targets)
2608
+ if opens:
2609
+ self._arm_call(out, opens)
1619
2610
  return out
1620
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
+
1621
2658
  def _open_label(self) -> None:
1622
2659
  """Draw this turn's `venastine ›`, once (§43, RM1).
1623
2660
 
@@ -1697,7 +2734,10 @@ class Transcript(RichLog):
1697
2734
  if not total:
1698
2735
  self.write(Text(text, style))
1699
2736
  return
1700
- 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)
1701
2741
 
1702
2742
  def _render_blocks(self, text: str, *, line_start: bool = True) -> None:
1703
2743
  """The assistant body: fenced code highlighted, everything else
@@ -1896,7 +2936,7 @@ class Transcript(RichLog):
1896
2936
  # -- links (batch 58) ---------------------------------------------------
1897
2937
 
1898
2938
  def on_click(self, event) -> None:
1899
- """CTRL+click a URL to open it.
2939
+ """CTRL+click a URL to open it, or a spawn to read its run.
1900
2940
 
1901
2941
  Ctrl rather than a bare click, which is the terminal's own
1902
2942
  convention for a link and also the reason a click while reading
@@ -1915,9 +2955,28 @@ class Transcript(RichLog):
1915
2955
  if not getattr(event, "ctrl", False):
1916
2956
  return
1917
2957
  style = getattr(event, "style", None)
1918
- url = (getattr(style, "meta", None) or {}).get("url")
2958
+ meta = getattr(style, "meta", None) or {}
2959
+ url = meta.get("url")
1919
2960
  if url:
1920
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])))
1921
2980
 
1922
2981
  def open_url(self, url) -> None:
1923
2982
  """Hand `url` to the platform's browser, off the UI thread.
@@ -1935,6 +2994,15 @@ class Transcript(RichLog):
1935
2994
  if not markdown.clickable(url):
1936
2995
  return
1937
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
+
1938
3006
  def work() -> None:
1939
3007
  try:
1940
3008
  opened = webbrowser.open(url)
@@ -1960,7 +3028,8 @@ class Transcript(RichLog):
1960
3028
  self.flush_stream()
1961
3029
  self._emit("error", text)
1962
3030
 
1963
- def write_role(self, role: str, text: str, links=()) -> None:
3031
+ def write_role(self, role: str, text: str, links=(),
3032
+ opens: tuple = ()) -> None:
1964
3033
  """Write a line in an arbitrary palette role (§26).
1965
3034
 
1966
3035
  Exists so the research view can style a pass boundary, a tool call
@@ -1970,10 +3039,12 @@ class Transcript(RichLog):
1970
3039
 
1971
3040
  `links` is batch 65's, and it is ignored for every role outside
1972
3041
  LINKED_ROLES rather than refused: a caller that has candidates
1973
- should not have to know which roles use them.
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.
1974
3045
  """
1975
3046
  self.flush_stream()
1976
- self._emit(role, text, links=links)
3047
+ self._emit(role, text, links=links, opens=opens)
1977
3048
 
1978
3049
  def write_answer(self, text: str) -> None:
1979
3050
  """A model answer that did not arrive as a stream (a one-shot turn,
@@ -1984,6 +3055,46 @@ class Transcript(RichLog):
1984
3055
 
1985
3056
  # -- streaming ---------------------------------------------------------
1986
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
+
1987
3098
  def _wrap_width(self, prefix: str = "") -> int:
1988
3099
  """Usable text columns for one rendered row, or 0 when there is
1989
3100
  nothing to measure.
@@ -1997,14 +3108,15 @@ class Transcript(RichLog):
1997
3108
  for safety) wrapped a streamed answer ~15 columns narrower than the
1998
3109
  same text replayed by rerender() -- so a /theme mid-session visibly
1999
3110
  reflowed the conversation, which is the one thing a pre-wrap must
2000
- 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.
2001
3113
 
2002
3114
  A widget has no size before mount and is built bare throughout the
2003
3115
  suite, so the guard is around the measurement itself, for the same
2004
3116
  reason _styles' is.
2005
3117
  """
2006
3118
  try:
2007
- width = max(self.scrollable_content_region.width, self.min_width)
3119
+ width = max(self._region_width(), self.min_width)
2008
3120
  except Exception: # noqa: BLE001 -- unmounted; the newline rule alone
2009
3121
  return 0
2010
3122
  width -= len(prefix)
@@ -2048,9 +3160,26 @@ class Transcript(RichLog):
2048
3160
  return markdown.plain_split(pending, width)
2049
3161
 
2050
3162
  def stream_delta(self, delta: str) -> None:
2051
- 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)
2052
3170
  self._commit_ready()
2053
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
+
2054
3183
  def _commit_ready(self) -> None:
2055
3184
  """Write whatever of the pending stream can safely be drawn now.
2056
3185
 
@@ -2078,6 +3207,27 @@ class Transcript(RichLog):
2078
3207
  on EITHER path, so the rows it is drawn in are the rows the replay
2079
3208
  will draw. Without that a model could hold the screen indefinitely
2080
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.
2081
3231
  """
2082
3232
  width = self._wrap_width()
2083
3233
  while True:
@@ -2090,6 +3240,9 @@ class Transcript(RichLog):
2090
3240
  block=not mid_line)
2091
3241
  if not chunk:
2092
3242
  return
3243
+ if not chunk.endswith("\n") and not rest \
3244
+ and limit >= len(self._pending):
3245
+ return
2093
3246
  self._pending = rest + self._pending[limit:]
2094
3247
  self._write_stream_chunk(chunk, line_start=not (mid_line or forced))
2095
3248
 
@@ -2123,7 +3276,12 @@ class Transcript(RichLog):
2123
3276
  ordering for free.
2124
3277
  """
2125
3278
  self.end_thinking()
2126
- 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
2127
3285
 
2128
3286
  def _close_answer(self) -> str:
2129
3287
  """flush_stream without the thinking half.
@@ -2135,6 +3293,14 @@ class Transcript(RichLog):
2135
3293
  emits that remainder as a second, standalone thinking entry and
2136
3294
  then drops it.
2137
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()
2138
3304
  if not self._pending and not self._stream_open:
2139
3305
  return ""
2140
3306
  residual, self._pending = self._pending, ""
@@ -2169,24 +3335,57 @@ class Transcript(RichLog):
2169
3335
  self._style("thinking")))
2170
3336
 
2171
3337
  def _write_thinking_lines(self, text: str) -> None:
2172
- """One bar-prefixed row per source line. The rows are pre-wrapped
2173
- by the time they arrive here (that is what _wrap_width's prefix
2174
- argument is for), because RichLog's own soft wrap would put the
2175
- 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)
2176
3355
  lines = text.split("\n")
2177
3356
  if lines and lines[-1] == "":
2178
3357
  lines.pop()
3358
+ style = self._style("thinking")
2179
3359
  for line in lines:
2180
- self.write(Text(f"{THINKING_INDENT}{THINKING_BAR}{line}",
2181
- self._style("thinking")))
3360
+ for row in markdown.plain_wrap(line, width):
3361
+ self.write(Text(f"{THINKING_INDENT}{THINKING_BAR}{row}",
3362
+ style))
2182
3363
 
2183
3364
  def thinking_delta(self, delta: str) -> None:
2184
- 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."""
2185
3376
  width = self._wrap_width(THINKING_INDENT + THINKING_BAR)
2186
3377
  while True:
2187
3378
  chunk, rest = self._split_committable(self._thinking_pending, width)
2188
3379
  if not chunk:
2189
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
2190
3389
  self._thinking_pending = rest
2191
3390
  self._write_thinking_chunk(chunk)
2192
3391
 
@@ -2207,6 +3406,11 @@ class Transcript(RichLog):
2207
3406
  def end_thinking(self) -> str:
2208
3407
  """Close the thinking span, if one is open. Idempotent: every
2209
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()
2210
3414
  if not self._thinking_open and not self._thinking_pending:
2211
3415
  return ""
2212
3416
  residual, self._thinking_pending = self._thinking_pending, ""
@@ -2252,13 +3456,36 @@ class Transcript(RichLog):
2252
3456
  # in the session with no `venastine ›`.
2253
3457
  self._label_in_force = False
2254
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()
2255
3468
  # Batch 65, and the same sentence as the line above it: a click
2256
3469
  # target left behind would belong to a thread that is no longer
2257
3470
  # on screen, and index N would then arm the NEXT thread's Nth
2258
3471
  # line with the previous one's URL.
2259
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()
2260
3477
  self.clear()
2261
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
+
2262
3489
  def rerender(self) -> None:
2263
3490
  """Redraw every entry under the current theme.
2264
3491
 
@@ -2266,19 +3493,256 @@ class Transcript(RichLog):
2266
3493
  cannot restyle what is already on screen -- without this, /theme
2267
3494
  would leave the session split between two palettes at the exact
2268
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).
2269
3502
  """
2270
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."""
2271
3510
  self.clear()
2272
3511
  # §43 (RM1). The screen is empty, so no label is in force; the
2273
3512
  # loop below re-derives every one of them from the role sequence
2274
3513
  # exactly as the live path did.
2275
3514
  self._label_in_force = False
3515
+ last = len(self._entries) - 1
2276
3516
  for index, (role, text) in enumerate(self._entries):
2277
3517
  # Batch 65: the targets too, or a /theme would silently
2278
3518
  # disarm every long URL in the session -- the line would
2279
3519
  # look identical and stop being clickable, which is the
2280
3520
  # kind of loss only the pointer can find.
2281
- self._render_entry(role, text, self._links.get(index, ()))
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)
2282
3746
 
2283
3747
  def last_answer(self) -> str:
2284
3748
  """The most recent answer in this session, or "" (for /copy last).