@sigrun/tui 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/dist/actions.d.ts +119 -0
  3. package/dist/actions.js +12 -0
  4. package/dist/api.d.ts +209 -0
  5. package/dist/api.js +282 -0
  6. package/dist/blocks/braille.d.ts +41 -0
  7. package/dist/blocks/braille.js +131 -0
  8. package/dist/blocks/chart.d.ts +20 -0
  9. package/dist/blocks/chart.js +397 -0
  10. package/dist/blocks/chat-transport.d.ts +44 -0
  11. package/dist/blocks/chat-transport.js +116 -0
  12. package/dist/blocks/collection/calendar.d.ts +28 -0
  13. package/dist/blocks/collection/calendar.js +232 -0
  14. package/dist/blocks/collection/card.d.ts +36 -0
  15. package/dist/blocks/collection/card.js +128 -0
  16. package/dist/blocks/collection/collection.d.ts +9 -0
  17. package/dist/blocks/collection/collection.js +26 -0
  18. package/dist/blocks/collection/grid.d.ts +18 -0
  19. package/dist/blocks/collection/grid.js +72 -0
  20. package/dist/blocks/collection/lanes.d.ts +32 -0
  21. package/dist/blocks/collection/lanes.js +320 -0
  22. package/dist/blocks/collection/list.d.ts +30 -0
  23. package/dist/blocks/collection/list.js +273 -0
  24. package/dist/blocks/collection/move.d.ts +67 -0
  25. package/dist/blocks/collection/move.js +96 -0
  26. package/dist/blocks/collection/shared.d.ts +87 -0
  27. package/dist/blocks/collection/shared.js +177 -0
  28. package/dist/blocks/collection/table.d.ts +26 -0
  29. package/dist/blocks/collection/table.js +221 -0
  30. package/dist/blocks/content.d.ts +48 -0
  31. package/dist/blocks/content.js +253 -0
  32. package/dist/blocks/context.d.ts +117 -0
  33. package/dist/blocks/context.js +65 -0
  34. package/dist/blocks/diff.d.ts +21 -0
  35. package/dist/blocks/diff.js +25 -0
  36. package/dist/blocks/ext-transport.d.ts +70 -0
  37. package/dist/blocks/ext-transport.js +165 -0
  38. package/dist/blocks/form/choice.d.ts +54 -0
  39. package/dist/blocks/form/choice.js +175 -0
  40. package/dist/blocks/form/fields.d.ts +56 -0
  41. package/dist/blocks/form/fields.js +136 -0
  42. package/dist/blocks/form/file.d.ts +61 -0
  43. package/dist/blocks/form/file.js +121 -0
  44. package/dist/blocks/form/form.d.ts +66 -0
  45. package/dist/blocks/form/form.js +764 -0
  46. package/dist/blocks/form/list.d.ts +37 -0
  47. package/dist/blocks/form/list.js +70 -0
  48. package/dist/blocks/form/values.d.ts +20 -0
  49. package/dist/blocks/form/values.js +106 -0
  50. package/dist/blocks/icons.d.ts +14 -0
  51. package/dist/blocks/icons.js +74 -0
  52. package/dist/blocks/image.d.ts +39 -0
  53. package/dist/blocks/image.js +82 -0
  54. package/dist/blocks/interaction-transport.d.ts +42 -0
  55. package/dist/blocks/interaction-transport.js +79 -0
  56. package/dist/blocks/layout.d.ts +31 -0
  57. package/dist/blocks/layout.js +155 -0
  58. package/dist/blocks/log.d.ts +24 -0
  59. package/dist/blocks/log.js +111 -0
  60. package/dist/blocks/meter.d.ts +16 -0
  61. package/dist/blocks/meter.js +50 -0
  62. package/dist/blocks/page.d.ts +54 -0
  63. package/dist/blocks/page.js +360 -0
  64. package/dist/blocks/render.d.ts +31 -0
  65. package/dist/blocks/render.js +163 -0
  66. package/dist/blocks/surface-view.d.ts +41 -0
  67. package/dist/blocks/surface-view.js +137 -0
  68. package/dist/blocks/surface.d.ts +80 -0
  69. package/dist/blocks/surface.js +506 -0
  70. package/dist/blocks/tones.d.ts +23 -0
  71. package/dist/blocks/tones.js +63 -0
  72. package/dist/blocks/treeview.d.ts +22 -0
  73. package/dist/blocks/treeview.js +121 -0
  74. package/dist/blocks/width.d.ts +32 -0
  75. package/dist/blocks/width.js +70 -0
  76. package/dist/clipboard.d.ts +20 -0
  77. package/dist/clipboard.js +19 -0
  78. package/dist/editor-launch.d.ts +34 -0
  79. package/dist/editor-launch.js +70 -0
  80. package/dist/keymaps/emacs.d.ts +18 -0
  81. package/dist/keymaps/emacs.js +172 -0
  82. package/dist/keymaps/standard.d.ts +17 -0
  83. package/dist/keymaps/standard.js +175 -0
  84. package/dist/keymaps/types.d.ts +43 -0
  85. package/dist/keymaps/types.js +28 -0
  86. package/dist/keymaps/vim.d.ts +48 -0
  87. package/dist/keymaps/vim.js +291 -0
  88. package/dist/launch.d.ts +159 -0
  89. package/dist/launch.js +478 -0
  90. package/dist/sse.d.ts +112 -0
  91. package/dist/sse.js +418 -0
  92. package/dist/theme.d.ts +51 -0
  93. package/dist/theme.js +119 -0
  94. package/dist/ui/ambient.d.ts +78 -0
  95. package/dist/ui/ambient.js +264 -0
  96. package/dist/ui/app.d.ts +319 -0
  97. package/dist/ui/app.js +1539 -0
  98. package/dist/ui/composer.d.ts +66 -0
  99. package/dist/ui/composer.js +133 -0
  100. package/dist/ui/conversation-pane.d.ts +143 -0
  101. package/dist/ui/conversation-pane.js +615 -0
  102. package/dist/ui/help.d.ts +15 -0
  103. package/dist/ui/help.js +80 -0
  104. package/dist/ui/interactions.d.ts +91 -0
  105. package/dist/ui/interactions.js +477 -0
  106. package/dist/ui/picker.d.ts +26 -0
  107. package/dist/ui/picker.js +130 -0
  108. package/dist/ui/settings.d.ts +68 -0
  109. package/dist/ui/settings.js +254 -0
  110. package/dist/ui/sidebar.d.ts +99 -0
  111. package/dist/ui/sidebar.js +269 -0
  112. package/dist/ui/status-bar.d.ts +77 -0
  113. package/dist/ui/status-bar.js +146 -0
  114. package/package.json +4 -3
package/dist/ui/app.js ADDED
@@ -0,0 +1,1539 @@
1
+ /**
2
+ * The TUI shell (Task 6): sidebar left, conversation pane right, composer
3
+ * footer — pi's idiom over the Task 4 client layers.
4
+ *
5
+ * File naming (the controller's pick-one ruling): plain `.ts` — pi-tui is
6
+ * not React (components are `render(width): string[]` classes), so the
7
+ * plan's `app.tsx` alternative does not apply.
8
+ *
9
+ * Layout: {@link TuiApp} is a `VStack`: the body row (`HStack`: sidebar
10
+ * at a fixed basis, pane growing), then the interaction seam's prompt
11
+ * strip (Task 8 — the pending stack, answerable via ctrl+o + digits), then
12
+ * the ambient chrome (panel/footer/statusline zones by the record's
13
+ * `place`). Both strips collapse to zero height when empty. The composer
14
+ * is a pi-tui `Editor` the launcher mounts after the app on the TUI root —
15
+ * pi's idiom is `TuiMainScreen` (the terminal owns scrollback; chat content
16
+ * scrolls, the editor anchors the bottom as the last child). Viewport
17
+ * `VStack`/`ScrollView` layouts are alt-screen-only (pi-tui 1.3.0), so the
18
+ * footer composition lives in the launcher, not the app component.
19
+ *
20
+ * Wiring: the sidebar refreshes from `listConversations()`; selecting a
21
+ * conversation swaps the pane's `watchConversation` subscription (the old
22
+ * watch is closed before the new one opens); stream frames REPLACE the
23
+ * pane (the SSE contract — a snapshot subsumes missed frames); the
24
+ * composer submits fire-and-forget via `submit(id, text)` — the stream is
25
+ * the source of truth for the reply (spec §10's composer rule). The fork
26
+ * action (`forkActive`, driven by the `/fork` slash command; task C3's
27
+ * action layer reintroduces a keybinding) calls
28
+ * `forkConversation(id)` at the latest entry (the v1 default, spec §8),
29
+ * refreshes the sidebar, and switches to the fork.
30
+ *
31
+ * Composer behaviors (Task 7): the composer tracks the wire's `steer.busy`
32
+ * per frame; submitting while busy sends `whenBusy: "steer"`. Esc during a
33
+ * live run aborts (the binding rides the launcher's pre-editor global
34
+ * listener through {@link handleKeybinding} — pi-tui 1.3.0's `Editor` has
35
+ * no escape hook of its own). A `/`-prefixed line routes through the
36
+ * slash-command catalog (`getCommands()`, fetched once and cached by
37
+ * {@link SlashCatalog}); unknown commands render a clear error. The POST's
38
+ * immediate failure (4xx) and the abort outcomes render as pane
39
+ * error/notice lines — the pane keeps rendering the reply off the stream.
40
+ *
41
+ * Sidebar focus (fix wave F2): the sidebar is the switcher (spec §2), so it
42
+ * must be keyboard-reachable — ctrl+b toggles key routing between the
43
+ * composer and the conversation list; a selection (or a second ctrl+b)
44
+ * returns keys to the composer. Guarded actions (fix wave F1): every
45
+ * fire-and-forget mutation path (`+ new`, conversation select, ctrl+f
46
+ * fork) catches its rejection into a pane error line — a flaky remote must
47
+ * never crash the process on an unhandled rejection.
48
+ */
49
+ import { Editor, HStack, Key, matchesKey, VStack, } from "@earendil-works/pi-tui";
50
+ import { SigrunApiError } from "../api.js";
51
+ import { ExtSurfaceHub, surfaceKeyHash, transportKey, } from "../blocks/ext-transport.js";
52
+ import { ChatSurfaceHub } from "../blocks/chat-transport.js";
53
+ import { watchConversation } from "../sse.js";
54
+ import { spawnSync } from "node:child_process";
55
+ import { plainTuiTheme } from "../theme.js";
56
+ import { editInVim, resolveVimEditor } from "../editor-launch.js";
57
+ import { copyToTerminal } from "../clipboard.js";
58
+ import { commandInsertText, describeCommandError, isSkillCommandName, parseSlashInput, SlashCatalog, } from "./composer.js";
59
+ import { AmbientChrome } from "./ambient.js";
60
+ import { ConversationPane } from "./conversation-pane.js";
61
+ import { InteractionPrompter } from "./interactions.js";
62
+ import { SettingsView } from "./settings.js";
63
+ import { openPicker } from "./picker.js";
64
+ import { Sidebar } from "./sidebar.js";
65
+ /**
66
+ * How long the restart-recovery poll waits for /readyz before giving up
67
+ * with a permanent error (U4 Task 2, spec §13.3). DUPLICATE of the
68
+ * webui's `RESTART_READYZ_DEADLINE_MS` (webui/src/App.tsx) by design:
69
+ * the tui package consumes only `@sigrun/shared` wire types (NodeNext,
70
+ * no codegen), and a shared-module move for one number is not worth the
71
+ * coupling — keep the two in sync by hand.
72
+ */
73
+ export const RESTART_READYZ_DEADLINE_MS = 60_000;
74
+ /** PATH lookup for the vim fallback chain (nvim/vim/vi). */
75
+ function whichPath(name) {
76
+ const result = spawnSync("which", [name], { encoding: "utf8" });
77
+ if (result.status !== 0)
78
+ return undefined;
79
+ return result.stdout.trim().split("\n")[0] || undefined;
80
+ }
81
+ /** The main column's swap slot (U4 Task 4 round-2): renders the
82
+ * conversation pane, or the open settings view while one is up.
83
+ * The launcher mounts this slot (in its ScrollView) so the swap is
84
+ * visible — a settings view rendered only in `TuiApp.render`'s
85
+ * fallback path never paints in the launcher's composition. */
86
+ export class MainSlot {
87
+ #child;
88
+ constructor(child) {
89
+ this.#child = child;
90
+ }
91
+ /** Swap the rendered child (the conversation pane ↔ settings view). */
92
+ set(child) {
93
+ this.#child = child;
94
+ }
95
+ /** The current child (tests assert the swap). */
96
+ get current() {
97
+ return this.#child;
98
+ }
99
+ render(width) {
100
+ return this.#child.render(width);
101
+ }
102
+ handleInput(data) {
103
+ this.#child.handleInput?.(data);
104
+ }
105
+ invalidate() {
106
+ this.#child.invalidate();
107
+ }
108
+ }
109
+ /** No-color theme: the shell pins structure; styling is a later task. */
110
+ function plainEditorTheme() {
111
+ const identity = (text) => text;
112
+ const selectList = {
113
+ selectedPrefix: identity,
114
+ selectedText: identity,
115
+ description: identity,
116
+ scrollInfo: identity,
117
+ noMatch: identity,
118
+ };
119
+ return { borderColor: identity, selectList };
120
+ }
121
+ export class TuiApp {
122
+ #client;
123
+ /** The extension-surface transport hub (U3 Task 5): one per app —
124
+ * `openExtView`'s transport subscribes through it; the launcher
125
+ * dispatches `surface.changed` events into it. */
126
+ #extHub = new ExtSurfaceHub();
127
+ /** The chat-block transport hub (U5 Task 4): the conversation-scoped
128
+ * `surface.changed` frames dispatch here; the conversation pane's
129
+ * inline block surfaces subscribe through it. */
130
+ #chatHub = new ChatSurfaceHub();
131
+ /** The open extension view (the main pane's surface state). The
132
+ * HANDLE (not the bare transport): a reconnect's new stream id
133
+ * lands via setStreamId without re-creating the transport. */
134
+ #extView;
135
+ /** The app's theme (the settings view's SurfaceView reuses it). */
136
+ #theme;
137
+ /** Unicode glyphs (the settings view's SurfaceView). Pinned true,
138
+ * matching the blocks tests' default; a terminal-capability
139
+ * downgrade is the theme system's call when it lands one. */
140
+ #unicode = true;
141
+ /** The open settings view (U4 Task 4; `/settings` opens, Esc closes). */
142
+ #settingsView;
143
+ #watch;
144
+ #watchOptions;
145
+ /** The sidebar (the app mounts it; tests drive it). */
146
+ sidebar;
147
+ /** The conversation pane (the stream replaces its contents). */
148
+ pane;
149
+ /** The composer (the launcher mounts it after the app + focuses it). */
150
+ editor;
151
+ /** The interaction seam's prompt strip (Task 8; zero height when empty). */
152
+ interactions;
153
+ /** The ambient seam's chrome zones (Task 8; zero height when empty). */
154
+ ambient;
155
+ #body = new HStack();
156
+ #layout = new VStack();
157
+ /** The main column's slot: renders the conversation pane normally,
158
+ * the open settings view while one is up (U4 Task 4 round-2 — the
159
+ * settings view renders IN the body slot; the launcher's root
160
+ * scrolls this slot, so a `#settingsView`-only render would paint
161
+ * nothing and swallow keys). Exported for the launcher's mount. */
162
+ mainContent;
163
+ #activeId;
164
+ #unwatch;
165
+ /** Monotonic watch generation: a stale watch's frames must never land. */
166
+ #watchGen = 0;
167
+ /** The last frame's `steer.busy` — the steer gate for the next submit. */
168
+ #busy = false;
169
+ /** The slash-command catalog (session-cached snapshot, live-rechecked
170
+ * on a miss — see SlashCatalog). */
171
+ #catalog;
172
+ /** The repainting surface (pickers, copy flashes, redraw). */
173
+ #tui;
174
+ /** The status bar sink the launcher mounts (notices, flashes, hints). */
175
+ #statusBar;
176
+ /** The focus region the action layer drives (C3). */
177
+ #focus = "composer";
178
+ /** A modal overlay (picker/search) owns the keys. */
179
+ #overlayOpen = false;
180
+ /** The quit sink: the launcher's exit resolution. */
181
+ onQuit;
182
+ /** The status-bar state the launcher last painted (flashes preserve it). */
183
+ #statusSnapshot;
184
+ /** The transcript search overlay state (query + direction). */
185
+ #search;
186
+ /** The last frame's configured model id (status bar + pickers). */
187
+ #modelId;
188
+ /** The last frame's thinking level (the cycle order starts here). */
189
+ #thinkingLevel = "off";
190
+ /** The vim resolution for edit-in-vim (C4; configured → env → PATH). */
191
+ #resolveVim;
192
+ /** The restart-recovery poll cadence (U4 Task 2). */
193
+ #restartPollMs;
194
+ /** The restart-recovery deadline (U4 Task 2 round-2). */
195
+ #restartDeadlineMs;
196
+ /** The in-flight restart poll's cancel flag (dispose fences it). */
197
+ #restartGeneration = 0;
198
+ constructor(client, options) {
199
+ this.#client = client;
200
+ this.#watch = options.watch ?? watchConversation;
201
+ this.#watchOptions = options.watchOptions ?? { baseUrl: "" };
202
+ this.#tui = options.tui;
203
+ this.#catalog = new SlashCatalog(client);
204
+ this.#resolveVim = options.resolveVim ?? (() => resolveVimEditor({ configured: options.editor, env: process.env, which: whichPath }));
205
+ this.#restartPollMs = options.restartPollMs ?? 500;
206
+ this.#restartDeadlineMs =
207
+ options.restartDeadlineMs ?? RESTART_READYZ_DEADLINE_MS;
208
+ const theme = options.theme ?? plainTuiTheme();
209
+ this.#theme = theme;
210
+ this.sidebar = new Sidebar(client, theme === undefined ? undefined : { theme });
211
+ this.pane = new ConversationPane({
212
+ ...(theme === undefined ? {} : { theme }),
213
+ attachChatTransport: (conversationId, entryId) => this.#chatHub.attach({
214
+ conversationId,
215
+ entryId,
216
+ baseUrl: this.#watchOptions.baseUrl,
217
+ ...(this.#watchOptions.user === undefined
218
+ ? {}
219
+ : { user: this.#watchOptions.user }),
220
+ ...(this.#watchOptions.token === undefined
221
+ ? {}
222
+ : { token: this.#watchOptions.token }),
223
+ }),
224
+ });
225
+ this.editor = new Editor(options.tui, plainEditorTheme());
226
+ this.interactions = new InteractionPrompter(client, theme === undefined ? undefined : { theme });
227
+ this.ambient = new AmbientChrome(client, theme === undefined ? undefined : { theme });
228
+ this.#body.addChild(this.sidebar, {
229
+ basis: options.sidebarWidth ?? 24,
230
+ shrink: 1,
231
+ });
232
+ this.mainContent = new MainSlot(this.pane);
233
+ this.#body.addChild(this.mainContent, { basis: 0, grow: 1, minSize: 1 });
234
+ // All entries are intrinsic-height (basis "auto"): the TUI mounts
235
+ // the app on the MAIN screen, where render(width) is the production
236
+ // path and the terminal owns scrollback — a numeric basis would be
237
+ // clamped to its minSize and slice the body to one line (VStack
238
+ // render path, no available height).
239
+ this.#layout.addChild(this.#body, { basis: "auto" });
240
+ this.#layout.addChild(this.interactions, { basis: "auto" });
241
+ this.#layout.addChild(this.ambient, { basis: "auto" });
242
+ // Seam state changes repaint; answer failures are user-initiated,
243
+ // so they land as pane error lines (background polls fail quiet).
244
+ const repaint = () => options.tui.requestRender();
245
+ this.interactions.onChanged = repaint;
246
+ this.ambient.onChanged = repaint;
247
+ this.interactions.onError = (message) => this.pane.showError(message);
248
+ this.sidebar.onSelect = (selection) => {
249
+ if (selection === "new") {
250
+ void this.createAndSelect();
251
+ }
252
+ else if (typeof selection === "object") {
253
+ // An extension VIEW (U3 Task 5): open it in the main pane.
254
+ void this.openExtView(selection.view.slug, selection.view.id).catch((error) => {
255
+ this.pane.showError(describeCommandError("open view", error));
256
+ });
257
+ }
258
+ else {
259
+ // Caught at the call site (fix wave F1): selectConversation
260
+ // keeps propagating for boot's fail-loud refresh, so the
261
+ // interactive path guards here.
262
+ void this.selectConversation(selection).catch((error) => {
263
+ this.pane.showError(describeCommandError("select", error));
264
+ });
265
+ }
266
+ };
267
+ this.editor.onSubmit = (text) => {
268
+ this.#submit(text);
269
+ };
270
+ }
271
+ /** The active conversation id (undefined before the first refresh). */
272
+ get activeConversationId() {
273
+ return this.#activeId;
274
+ }
275
+ /** The current /v1/events stream id (the hello frame's payload);
276
+ * the ext-view transports send it as X-Sigrun-Stream. */
277
+ #eventsStreamId;
278
+ /** The launcher's hello hook (U3 Task 5): the stream id feeds
279
+ * future openExtView transports; an OPEN view's handle gets the
280
+ * new id at once (its next fetch re-registers the watcher entry —
281
+ * spec §7.3's reconnect rule; the webui twin remounts instead). */
282
+ setEventsStreamId(streamId) {
283
+ this.#eventsStreamId = streamId;
284
+ this.#extView?.handle.setStreamId(streamId);
285
+ }
286
+ /** The open extension view's identity (undefined = the conversation
287
+ * pane is the main content). */
288
+ get extView() {
289
+ return this.#extView === undefined
290
+ ? undefined
291
+ : { slug: this.#extView.slug, id: this.#extView.id };
292
+ }
293
+ /**
294
+ * Open an extension VIEW in the main pane (U3 Task 5, spec §7.1):
295
+ * the sidebar's view selection swaps the pane's content to the
296
+ * surface's transport. The block renderer is U2's; the app holds
297
+ * the transport + identity here so U2's mount is one prop pass.
298
+ */
299
+ async openExtView(slug, id, params) {
300
+ const key = transportKey({ slug, id, baseUrl: this.#watchOptions.baseUrl, ...(params === undefined ? {} : { params }) });
301
+ const handle = this.#extHub.attach({
302
+ slug,
303
+ id,
304
+ ...(params === undefined ? {} : { params }),
305
+ baseUrl: this.#watchOptions.baseUrl,
306
+ ...(this.#watchOptions.user === undefined
307
+ ? {}
308
+ : { user: this.#watchOptions.user }),
309
+ ...(this.#watchOptions.token === undefined
310
+ ? {}
311
+ : { token: this.#watchOptions.token }),
312
+ ...(this.#eventsStreamId === undefined
313
+ ? {}
314
+ : { streamId: this.#eventsStreamId }),
315
+ }, surfaceKeyHash(slug, id, key));
316
+ this.#extView = { slug, id, handle };
317
+ this.#tui.requestRender();
318
+ }
319
+ /**
320
+ * Open the settings view (U4 Task 4, spec §13.4): `/settings` mounts
321
+ * the SettingsView (the sections list + the search picker over the
322
+ * index); Esc closes it back to the conversation.
323
+ */
324
+ async openSettings() {
325
+ if (this.#settingsView !== undefined)
326
+ return;
327
+ const view = new SettingsView(this.#client, {
328
+ tui: this.#tui,
329
+ theme: this.#theme,
330
+ unicode: this.#unicode,
331
+ onRestart: async () => {
332
+ await this.restart();
333
+ },
334
+ onClose: () => {
335
+ this.#settingsView = undefined;
336
+ this.mainContent.set(this.pane);
337
+ this.#tui.requestRender();
338
+ },
339
+ });
340
+ this.#settingsView = view;
341
+ // The view renders in the main column's slot (visible + scrollable
342
+ // under the launcher's composition).
343
+ this.mainContent.set(view);
344
+ await view.load();
345
+ this.#tui.requestRender();
346
+ }
347
+ /** The open settings view (tests drive it). */
348
+ get settingsView() {
349
+ return this.#settingsView;
350
+ }
351
+ /**
352
+ * Close the open settings view (Esc). Returns true when one was open.
353
+ */
354
+ closeSettings() {
355
+ if (this.#settingsView === undefined)
356
+ return false;
357
+ this.#settingsView.dispose();
358
+ this.#settingsView = undefined;
359
+ this.mainContent.set(this.pane);
360
+ this.#tui.requestRender();
361
+ return true;
362
+ }
363
+ /**
364
+ * Close the open extension view (the Esc/back idiom): the pane
365
+ * returns to the conversation AND the surface's fetches stop — no
366
+ * cadence, no keepalive for a surface nobody is looking at (spec
367
+ * §7.3's stop-when-hidden rule; U2's cadence timer consults this).
368
+ * Returns true when a view was open (the key was consumed).
369
+ */
370
+ closeExtView() {
371
+ if (this.#extView === undefined)
372
+ return false;
373
+ this.#extView = undefined;
374
+ this.#tui.requestRender();
375
+ return true;
376
+ }
377
+ /** The app-level surface.changed dispatch (the launcher's
378
+ * `watchEvents` onEvent routes events here). */
379
+ dispatchSurfaceChanged(event) {
380
+ this.#extHub.dispatch(event);
381
+ }
382
+ /** The chat member of `surface.changed` (U5 Task 4): fan the
383
+ * conversation-scoped frame into the chat hub. */
384
+ dispatchChatSurfaceChanged(event) {
385
+ this.#chatHub.dispatch(event);
386
+ }
387
+ /** The focused region (the action layer's routing state). */
388
+ get focus() {
389
+ return this.#focus;
390
+ }
391
+ /** A modal overlay (picker/search) owns the keys. */
392
+ get overlayOpen() {
393
+ return this.#overlayOpen;
394
+ }
395
+ /** The last frame's `steer.busy` (the keymap's abort gate). */
396
+ get busy() {
397
+ return this.#busy;
398
+ }
399
+ /**
400
+ * The launcher's sink: the status bar it mounted (flashes, help, and
401
+ * the search overlay render through it). `set` also snapshots the
402
+ * launcher's steady state so a flash can restore it.
403
+ */
404
+ setStatusBar(statusBar) {
405
+ this.#statusBar = statusBar;
406
+ const originalSet = statusBar.set.bind(statusBar);
407
+ statusBar.set = (state) => {
408
+ if (state.message === undefined)
409
+ this.#statusSnapshot = state;
410
+ originalSet(state);
411
+ };
412
+ // The launcher paints the steady state BEFORE attaching (the
413
+ // wrapper never saw it): seed the snapshot from the bar's current
414
+ // state, or flashes/config paints stay dead until the next set.
415
+ const current = statusBar.getState();
416
+ if (current.message === undefined)
417
+ this.#statusSnapshot = current;
418
+ // The plan's status-bar mouse rule (C3): the MODEL segment opens
419
+ // the model picker, the THINKING segment cycles the level — the
420
+ // same actions as ctrl+p's picker and ctrl+t, through the one
421
+ // dispatch seam.
422
+ statusBar.onModelClick = () => void this.dispatch({ type: "picker", kind: "model" });
423
+ statusBar.onThinkingClick = () => void this.dispatch({ type: "cycle-thinking" });
424
+ }
425
+ /** Flash a transient status-bar message, restoring the steady state. */
426
+ #flashStatus(message) {
427
+ const base = this.#statusSnapshot;
428
+ if (this.#statusBar === undefined || base === undefined)
429
+ return;
430
+ this.#statusBar.set({ ...base, message });
431
+ }
432
+ /**
433
+ * The configured model/thinking a frame carries (drives the cycle and
434
+ * the status bar's model/thinking segments). The source is the
435
+ * `pi.agent` doc (pi-durable's AgentState) — ConversationRecord is
436
+ * `{id, parent?}` and carries no model/thinking fields.
437
+ */
438
+ #trackConfig(wire) {
439
+ const doc = wire.docs["pi.agent"];
440
+ if (doc?.model !== undefined) {
441
+ this.#modelId = `${doc.model.provider}/${doc.model.modelId}`;
442
+ }
443
+ if (doc?.thinkingLevel !== undefined) {
444
+ this.#thinkingLevel = doc.thinkingLevel;
445
+ }
446
+ this.#paintConfig();
447
+ }
448
+ /**
449
+ * Feed the tracked model/thinking to the status bar's segments,
450
+ * merged into the launcher's steady state (no `message`) so a flash
451
+ * restores the segments too.
452
+ */
453
+ #paintConfig() {
454
+ const base = this.#statusSnapshot;
455
+ if (this.#statusBar === undefined || base === undefined)
456
+ return;
457
+ this.#statusBar.set({
458
+ ...base,
459
+ ...(this.#modelId === undefined ? {} : { model: this.#modelId }),
460
+ thinking: this.#thinkingLevel,
461
+ });
462
+ }
463
+ /**
464
+ * Refresh the sidebar listing. Boot selects the first conversation;
465
+ * later refreshes keep the current selection.
466
+ */
467
+ async refresh() {
468
+ await this.sidebar.refresh();
469
+ if (this.#activeId === undefined) {
470
+ const first = this.sidebar.rows[0];
471
+ if (first !== undefined) {
472
+ await this.selectConversation(first.id);
473
+ }
474
+ }
475
+ else {
476
+ this.sidebar.setActive(this.#activeId);
477
+ }
478
+ }
479
+ /**
480
+ * Swap the pane to `id`: close the old watch, open the new one. The
481
+ * composer is disabled for the swap's duration (review finding): a
482
+ * submission must never split from the pane it was typed against, so
483
+ * Enter cannot fire `onSubmit` mid-swap (pi-tui's `disableSubmit`
484
+ * gates the submit path).
485
+ */
486
+ async selectConversation(id) {
487
+ if (id === this.#activeId)
488
+ return;
489
+ this.editor.disableSubmit = true;
490
+ try {
491
+ this.#unwatch?.();
492
+ this.#unwatch = undefined;
493
+ this.#activeId = id;
494
+ // Busy state is per-frame: unknown for the new conversation until
495
+ // its first frame arrives.
496
+ this.#busy = false;
497
+ this.sidebar.setActive(id);
498
+ // Notices are per-conversation context (fix wave F4): an error
499
+ // from the OLD conversation must never render in the new one.
500
+ // The clear happens when the NEW watch installs (below): clearing
501
+ // here — at selection time — would race the fork/create action
502
+ // that LED to the swap (fix wave A1's /fork notice must survive
503
+ // into the fork's pane).
504
+ // Generation guard (review finding): a frame already in flight
505
+ // from the JUST-closed watch can still deliver after the swap;
506
+ // without a per-watch token it would land in the new
507
+ // conversation's pane. The guard also fences error callbacks,
508
+ // which carry no conversation id.
509
+ const gen = ++this.#watchGen;
510
+ // Fix wave A6: the swap repaints immediately — notice rows drop
511
+ // and the pane swaps to the empty view (the stream's fresh
512
+ // snapshot is the real first revision; a wholesale replacement
513
+ // is the pane's own idiom, and the container is in entry order,
514
+ // so dropping notice rows mid-list would leave a hole).
515
+ this.pane.clearNotices();
516
+ this.pane.showView(this.#emptyView(id));
517
+ this.#unwatch = this.#watch(id, {
518
+ onSnapshot: (wire) => {
519
+ if (gen !== this.#watchGen)
520
+ return;
521
+ this.#busy = wire.steer.busy;
522
+ this.#trackConfig(wire);
523
+ // A revision may change the seam state: re-poll the
524
+ // pending interactions; the ambient chrome tracks the
525
+ // run state for its expires:"idle" surfaces.
526
+ this.interactions.kick();
527
+ this.ambient.setBusy(wire.steer.busy);
528
+ this.pane.showView(wire);
529
+ },
530
+ onView: (wire) => {
531
+ if (gen !== this.#watchGen)
532
+ return;
533
+ this.#busy = wire.steer.busy;
534
+ this.#trackConfig(wire);
535
+ this.interactions.kick();
536
+ this.ambient.setBusy(wire.steer.busy);
537
+ this.pane.showView(wire);
538
+ },
539
+ onError: (message) => {
540
+ if (gen === this.#watchGen)
541
+ this.onWatchError?.(message);
542
+ },
543
+ onOpen: () => {
544
+ if (gen === this.#watchGen)
545
+ this.onWatchOpen?.();
546
+ },
547
+ }, this.#watchOptions);
548
+ this.interactions.setConversation(id);
549
+ this.ambient.setConversation(id);
550
+ }
551
+ finally {
552
+ this.editor.disableSubmit = false;
553
+ }
554
+ }
555
+ /** The pre-snapshot pane state on a swap (fix wave A6): no entries,
556
+ * not busy — the stream's fresh snapshot is the real first revision. */
557
+ #emptyView(id) {
558
+ // SAFETY: a structural stub — ConversationViewWire's full shape is
559
+ // server-built; the pane reads only conversation.id + entries.
560
+ return {
561
+ conversation: { id },
562
+ entries: [],
563
+ docs: {},
564
+ steer: { busy: false, queued: 0 },
565
+ };
566
+ }
567
+ /**
568
+ * Stream-error sink: the launcher wires this to the stream-health
569
+ * notices (fix wave F5 — "stream: disconnected" on the first failure,
570
+ * "stream: reconnected" on the next open). The generation guard above
571
+ * fences STALE watches' errors so they can't reach whatever is mounted
572
+ * here.
573
+ */
574
+ onWatchError;
575
+ /**
576
+ * Stream-open sink (fix wave F5): fires on every (re)connect of the
577
+ * CURRENT watch — the recovery half of the launcher's stream-health
578
+ * notices. Generation-guarded like {@link onWatchError}.
579
+ */
580
+ onWatchOpen;
581
+ /** Create a conversation (`+ new`), refresh the sidebar, select it. */
582
+ async createAndSelect() {
583
+ // The submit guard spans the WHOLE async swap: the awaits below are
584
+ // the window where an Enter would otherwise target the old id.
585
+ this.editor.disableSubmit = true;
586
+ try {
587
+ const created = await this.#client.createConversation();
588
+ await this.sidebar.refresh();
589
+ await this.selectConversation(created.id);
590
+ }
591
+ catch (error) {
592
+ // Fix wave F1: every fire-and-forget caller (`+ new`, `/new`) is
593
+ // void-ed — a rejection must surface as a pane error, never an
594
+ // unhandled rejection that kills the process.
595
+ this.pane.showError(describeCommandError("new", error));
596
+ }
597
+ finally {
598
+ this.editor.disableSubmit = false;
599
+ }
600
+ }
601
+ /**
602
+ * Fork the active conversation at the latest entry (the v1 default,
603
+ * spec §8), refresh the sidebar, and switch to the fork. No-op with no
604
+ * active conversation.
605
+ */
606
+ async forkActive() {
607
+ if (this.#activeId === undefined)
608
+ return;
609
+ this.editor.disableSubmit = true;
610
+ try {
611
+ const forked = await this.#client.forkConversation(this.#activeId);
612
+ await this.sidebar.refresh();
613
+ await this.selectConversation(forked.id);
614
+ }
615
+ catch (error) {
616
+ // Fix wave F1 (see createAndSelect).
617
+ this.pane.showError(describeCommandError("fork", error));
618
+ }
619
+ finally {
620
+ this.editor.disableSubmit = false;
621
+ }
622
+ }
623
+ /**
624
+ * The launcher's global keybinding seam: ctrl+o enters the interaction
625
+ * seam's answer mode; Esc during a live run aborts it (the composer
626
+ * idiom — the launcher routes input through here before the editor sees
627
+ * it, so Esc while busy never reaches the editor). Returns true when the
628
+ * key was consumed. Task C1b removed ctrl+b (sidebar focus) and ctrl+f
629
+ * (fork): task C3's action layer reintroduces navigation — until then
630
+ * the mouse drives the sidebar and `/fork` carries the fork.
631
+ */
632
+ handleKeybinding(data) {
633
+ // The search overlay owns every key while open (C3).
634
+ if (this.#search !== undefined) {
635
+ return this.#handleSearchKey(data);
636
+ }
637
+ // A modal overlay (picker) owns the keys: the pre-keymap seams
638
+ // below (answer mode, ctrl+o, busy Esc) must never fire behind it.
639
+ // Returning false hands the key to the keymap, which passes
640
+ // everything but ctrl+c through to the focused overlay.
641
+ if (this.#overlayOpen)
642
+ return false;
643
+ // Answer mode captures the prompt's keys first (Task 8): esc here
644
+ // exits answer mode — it must NOT reach the busy-abort below.
645
+ if (this.interactions.answerMode) {
646
+ if (this.interactions.handleKey(data))
647
+ return true;
648
+ }
649
+ // ctrl+o enters answer mode (ctrl+a is the editor's cursorLineStart).
650
+ // Not consumed when nothing answerable is pending — the key falls
651
+ // through to the editor.
652
+ if (matchesKey(data, Key.ctrl("o"))) {
653
+ return this.interactions.beginAnswer();
654
+ }
655
+ // The settings view owns its keys while open (U4 Task 4): Esc
656
+ // closes an open section first, then the view; `/` opens the
657
+ // search picker over the sections index.
658
+ if (this.#settingsView !== undefined) {
659
+ if (matchesKey(data, Key.escape)) {
660
+ if (this.#settingsView.closeSection())
661
+ return true;
662
+ return this.closeSettings();
663
+ }
664
+ if (data === "/" && this.#settingsView.openSectionId === undefined) {
665
+ this.#settingsView.openSearch();
666
+ return true;
667
+ }
668
+ this.#settingsView.handleInput(data);
669
+ return true;
670
+ }
671
+ if (matchesKey(data, Key.escape) && this.#busy && this.#activeId !== undefined) {
672
+ this.#abortActive();
673
+ return true;
674
+ }
675
+ // Esc closes an open extension view — back to the
676
+ // conversation pane; the surface's fetches stop (the keepalive
677
+ // stops with the view, spec §7.3's stop-when-hidden).
678
+ if (matchesKey(data, Key.escape) && this.#extView !== undefined) {
679
+ return this.closeExtView();
680
+ }
681
+ return false;
682
+ }
683
+ /**
684
+ * Fire-and-forget submit (the stream carries the reply, spec §10). While
685
+ * the last frame reported a live run, the input goes as a steer
686
+ * (`whenBusy`, spec §7 item 3). The POST's own failure (an immediate 4xx
687
+ * — Review Focus 2) is the only thing awaited, and it lands as a pane
688
+ * error line; the composer never wedges on it.
689
+ */
690
+ #submit(text) {
691
+ // Belt to the editor's own gate: pi-tui checks `disableSubmit` in
692
+ // handleInput, not in the onSubmit callback — a programmatic
693
+ // onSubmit during a swap must no-op too, and never destroy a draft.
694
+ if (this.editor.disableSubmit)
695
+ return;
696
+ // Guard BEFORE clearing: a no-op submit must never destroy a draft.
697
+ if (text.trim() === "")
698
+ return;
699
+ if (text.startsWith("/")) {
700
+ // A command line is consumed by its dispatch (even when the
701
+ // outcome is an error line).
702
+ this.editor.setText("");
703
+ void this.#runSlashCommand(text);
704
+ return;
705
+ }
706
+ this.#submitLine(text);
707
+ }
708
+ /** Submit one line as a MESSAGE (the composer's plain path — also the
709
+ * expand path, Task 2c: `/skill:name` and prompt-template lines go to
710
+ * the server verbatim and are expanded AT ADMISSION, so the client
711
+ * never calls an endpoint for them). */
712
+ #submitLine(text) {
713
+ const id = this.#activeId;
714
+ if (id === undefined)
715
+ return;
716
+ this.editor.setText("");
717
+ const whenBusy = this.#busy ? "steer" : undefined;
718
+ this.#client.submit(id, text, whenBusy).catch((error) => {
719
+ this.pane.showError(describeCommandError("submit", error));
720
+ });
721
+ }
722
+ /**
723
+ * Abort the active conversation's live run (the Esc binding). The
724
+ * settled race (Review Focus 3) surfaces as a plain notice — the
725
+ * server's 200 `{result: "settled"}` and its 404 `no_active_submission`
726
+ * both mean "nothing left to abort"; a landed abort stays silent (the
727
+ * stream carries the outcome). Anything else is an error line.
728
+ */
729
+ #abortActive() {
730
+ const id = this.#activeId;
731
+ if (id === undefined)
732
+ return;
733
+ void this.#client.abort(id).then((response) => {
734
+ if (response.result === "settled") {
735
+ this.pane.showNotice("abort: the run had already settled");
736
+ }
737
+ }, (error) => {
738
+ if (error instanceof SigrunApiError && error.status === 404) {
739
+ this.pane.showNotice("abort: no active run (already settled)");
740
+ return;
741
+ }
742
+ this.pane.showError(describeCommandError("abort", error));
743
+ });
744
+ }
745
+ /**
746
+ * Route a `/`-prefixed line through the slash-command catalog. The
747
+ * catalog tells the composer what exists and where it goes (the server's
748
+ * thin-registry rule: no server-side execute indirection); the dispatch
749
+ * itself is the client's typed calls. Unknown commands and catalog
750
+ * commands the composer cannot drive both render clear errors.
751
+ */
752
+ async #runSlashCommand(input) {
753
+ const parsed = parseSlashInput(input);
754
+ if (parsed === undefined || parsed.name === "") {
755
+ this.pane.showError("empty slash command");
756
+ return;
757
+ }
758
+ let command;
759
+ try {
760
+ command = await this.#catalog.get(parsed.name);
761
+ }
762
+ catch (error) {
763
+ this.pane.showError(describeCommandError("getCommands", error));
764
+ return;
765
+ }
766
+ // Live-catalog re-check (fix round): the cached snapshot is a session
767
+ // snapshot — the server re-scans per request, and the command PICKER
768
+ // fetches fresh, so a template the picker just offered must also
769
+ // SUBMIT. One fresh fetch when the cache lacks the name, then the
770
+ // honest unknown-command error if it is still absent.
771
+ if (command === undefined) {
772
+ try {
773
+ command = await this.#catalog.getFresh(parsed.name);
774
+ }
775
+ catch (error) {
776
+ this.pane.showError(describeCommandError("getCommands", error));
777
+ return;
778
+ }
779
+ }
780
+ // EXPAND inputs (Task 2c) are submissions, not dispatches: a
781
+ // `kind: "expand"` catalog entry (prompt template, skill) — and ANY
782
+ // `skill:`-prefixed name, known or not (unknown skills pass through
783
+ // server-side) — goes to the server verbatim; expansion happens at
784
+ // admission. Falling through BEFORE the unknown-command error keeps
785
+ // `/skill:nope x` a submission, never a local error.
786
+ if (command?.kind === "expand" || isSkillCommandName(parsed.name)) {
787
+ this.#submitLine(input);
788
+ return;
789
+ }
790
+ if (command === undefined) {
791
+ this.pane.showError(`unknown command: /${parsed.name}`);
792
+ return;
793
+ }
794
+ try {
795
+ switch (parsed.name) {
796
+ case "new":
797
+ await this.createAndSelect();
798
+ return;
799
+ case "archive":
800
+ case "unarchive": {
801
+ const id = this.#activeId;
802
+ if (id === undefined) {
803
+ this.pane.showError(`/${parsed.name} needs an active conversation`);
804
+ return;
805
+ }
806
+ await this.#client.patchMeta(id, { archived: parsed.name === "archive" });
807
+ await this.sidebar.refresh();
808
+ return;
809
+ }
810
+ case "model":
811
+ case "thinking": {
812
+ const id = this.#activeId;
813
+ if (id === undefined) {
814
+ this.pane.showError(`/${parsed.name} needs an active conversation`);
815
+ return;
816
+ }
817
+ if (parsed.args === "") {
818
+ this.pane.showError(`/${parsed.name} needs an argument (${command.argsHint ?? ""})`);
819
+ return;
820
+ }
821
+ const response = parsed.name === "model"
822
+ ? await this.#client.configure(id, { model: parsed.args })
823
+ : await this.#client.configure(id, { thinking: parsed.args });
824
+ this.#thinkingLevel = response.thinkingLevel;
825
+ if (response.model !== undefined) {
826
+ this.#modelId = `${response.model.provider}/${response.model.modelId}`;
827
+ }
828
+ const model = this.#modelId ?? "no model";
829
+ this.#flashStatus(`model ${model} · thinking ${response.thinkingLevel}`);
830
+ return;
831
+ }
832
+ case "fork": {
833
+ if (this.#activeId === undefined) {
834
+ this.pane.showError("/fork needs an active conversation");
835
+ return;
836
+ }
837
+ const droppedArgs = parsed.args;
838
+ await this.forkActive();
839
+ // The catalog advertises argsHint "[at]", but the composer
840
+ // has no at-entry selection (notice, not support — the fix
841
+ // wave's ruling): the argument is dropped WITH a notice, and
842
+ // the fork still landed at the latest entry. The notice is
843
+ // posted AFTER the fork: forkActive swaps conversations, and
844
+ // the swap clears the pane (fix wave A6), so a notice posted
845
+ // before would be discarded with the old conversation.
846
+ if (droppedArgs !== "") {
847
+ this.pane.showNotice("fork at-entry selection is not supported by the TUI composer; forking at latest");
848
+ }
849
+ return;
850
+ }
851
+ case "compact": {
852
+ const id = this.#activeId;
853
+ if (id === undefined) {
854
+ this.pane.showError("/compact needs an active conversation");
855
+ return;
856
+ }
857
+ await this.#client.compact(id, parsed.args === "" ? undefined : parsed.args);
858
+ this.pane.showNotice("compaction admitted — the summary arrives on the stream");
859
+ return;
860
+ }
861
+ case "jobs": {
862
+ // W4 Task 5: the job table into the pane's notice area — one
863
+ // row per job (name, next run, last outcome), framed by a
864
+ // header/footer so the list reads as a table, not stray lines.
865
+ const { jobs } = await this.#client.listJobs();
866
+ if (jobs.length === 0) {
867
+ this.pane.showNotice("jobs: none");
868
+ return;
869
+ }
870
+ this.pane.showNotice(`jobs: ${jobs.length} (name · next run · last outcome)`);
871
+ for (const job of jobs) {
872
+ const next = job.nextRun ?? "no next run";
873
+ const last = job.lastRun?.outcome ?? "never run";
874
+ this.pane.showNotice(` ${job.name} · ${next} · ${last}`);
875
+ }
876
+ return;
877
+ }
878
+ case "settings": {
879
+ // U4 Task 4: the settings view (sections + the search
880
+ // picker over the index) mounts in the app's main column.
881
+ await this.openSettings();
882
+ return;
883
+ }
884
+ default:
885
+ // An extension-contributed command (W5 Task 3): the catalog entry
886
+ // carries its slug — POST the invoke endpoint and flash the
887
+ // returned notice in the status bar (the client surface for
888
+ // extension notices). A failure rejects through the surrounding
889
+ // catch: the pane error line carries the server's words
890
+ // (`command_failed` + the extension slug).
891
+ if (command.extension !== undefined) {
892
+ const id = this.#activeId;
893
+ if (id === undefined) {
894
+ this.pane.showError(`/${parsed.name} needs an active conversation`);
895
+ return;
896
+ }
897
+ const result = await this.#client.runCommand(id, parsed.name, parsed.args);
898
+ if (result.notice !== undefined)
899
+ this.#flashStatus(result.notice);
900
+ return;
901
+ }
902
+ this.pane.showError(`/${parsed.name} is not supported by the TUI composer`);
903
+ }
904
+ }
905
+ catch (error) {
906
+ this.pane.showError(describeCommandError(`/${parsed.name}`, error));
907
+ }
908
+ }
909
+ /** Close the stream subscription + seam pollers (the launcher calls this on exit). */
910
+ dispose() {
911
+ this.#unwatch?.();
912
+ this.#unwatch = undefined;
913
+ // Bump the watch generation too (fix wave A9): a handler still
914
+ // held by an unwound delivery must fence after dispose exactly as
915
+ // after a switch — nothing renders post-dispose.
916
+ this.#watchGen += 1;
917
+ this.#restartGeneration += 1;
918
+ this.interactions.dispose();
919
+ this.ambient.dispose();
920
+ // The pane's chat-block surface states hold live hub subscriptions
921
+ // + action timers — the shell owns their teardown (the pane never
922
+ // leaves a subscription behind).
923
+ this.pane.dispose();
924
+ }
925
+ /**
926
+ * The admin restart surface (U4 Task 2, spec §13.3): POST
927
+ * `/v1/admin/restart`, show the "Restarting…" notice, and poll
928
+ * `/readyz` — when it answers, the supervisor brought the server
929
+ * back, so refresh the sidebar (the durable listing) and clear the
930
+ * notice. A rejected POST (403/409 — no restart began) renders the
931
+ * error and returns without touching state. Resolves once the
932
+ * recovery poll ends (recovered or disposed).
933
+ */
934
+ async restart() {
935
+ try {
936
+ await this.#client.requestRestart();
937
+ }
938
+ catch (error) {
939
+ this.pane.showError(describeCommandError("restart", error));
940
+ return;
941
+ }
942
+ this.pane.showNotice("Restarting… — waiting for the server");
943
+ this.#tui.requestRender();
944
+ const generation = this.#restartGeneration;
945
+ const deadline = Date.now() + this.#restartDeadlineMs;
946
+ for (;;) {
947
+ await new Promise((resolve) => setTimeout(resolve, this.#restartPollMs));
948
+ if (generation !== this.#restartGeneration)
949
+ return;
950
+ let ready = false;
951
+ try {
952
+ ready = await this.#client.checkReady();
953
+ }
954
+ catch {
955
+ // Connection refused mid-restart: keep polling.
956
+ }
957
+ if (ready)
958
+ break;
959
+ // The deadline (the webui's RESTART_READYZ_DEADLINE_MS shape):
960
+ // a stalled supervisor must SURFACE, never hang the poll
961
+ // forever — clear the Restarting notice and leave a permanent
962
+ // error naming the failure.
963
+ if (Date.now() > deadline) {
964
+ this.pane.clearNotices();
965
+ this.pane.showError(`restart did not come back: /readyz never answered within ${Math.round(this.#restartDeadlineMs / 1000)}s — check the deployment's supervisor`);
966
+ this.#tui.requestRender();
967
+ return;
968
+ }
969
+ }
970
+ // Re-check the generation AFTER the probe: a dispose during the
971
+ // sleep+check must not let the recovery render post-dispose.
972
+ if (generation !== this.#restartGeneration)
973
+ return;
974
+ // Back: the listing is durable and the stream re-attach subsumes
975
+ // whatever the restart dropped (the SSE reconnect contract).
976
+ await this.sidebar.refresh().catch(() => { });
977
+ this.pane.clearNotices();
978
+ this.pane.showNotice("Restarted.");
979
+ this.#tui.requestRender();
980
+ }
981
+ // ─── The action layer (Task C3) ────────────────────────────────────
982
+ /**
983
+ * The keymap's context: focus, busy, autocomplete, overlay. The
984
+ * composer's autocomplete state is internal to pi-tui's Editor (no
985
+ * public getter), so the flag is a projection — the composer is the
986
+ * default focus and the editor cancels autocomplete before any
987
+ * focus-leaving key the keymap would act on.
988
+ */
989
+ keyContext() {
990
+ return {
991
+ focus: this.#focus,
992
+ busy: this.#busy,
993
+ autocompleteOpen: false,
994
+ overlayOpen: this.#overlayOpen,
995
+ };
996
+ }
997
+ /** Run one action (the keymap's / pickers' / mouse's single seam). */
998
+ async dispatch(action) {
999
+ switch (action.type) {
1000
+ case "focus":
1001
+ this.#focus = action.target;
1002
+ this.#applyFocusTarget();
1003
+ return;
1004
+ case "focus-cycle": {
1005
+ const order = ["composer", "list", "transcript"];
1006
+ const index = order.indexOf(this.#focus);
1007
+ this.#focus = order[(index + action.direction + order.length) % order.length];
1008
+ this.#applyFocusTarget();
1009
+ return;
1010
+ }
1011
+ case "move":
1012
+ if (this.#focus === "list") {
1013
+ this.sidebar.moveCursor(action.delta);
1014
+ }
1015
+ else if (this.#focus === "transcript") {
1016
+ this.#moveTranscriptFocus(action.delta);
1017
+ }
1018
+ return;
1019
+ case "page":
1020
+ if (this.#focus === "list") {
1021
+ this.sidebar.moveCursor(action.direction * 10);
1022
+ }
1023
+ else if (this.#focus === "transcript") {
1024
+ this.#moveTranscriptFocus(action.direction * 10);
1025
+ }
1026
+ return;
1027
+ case "edge":
1028
+ if (this.#focus === "list") {
1029
+ this.sidebar.moveCursor(action.to === "top" ? -1_000_000 : 1_000_000);
1030
+ }
1031
+ else if (this.#focus === "transcript") {
1032
+ this.#moveTranscriptFocus(action.to === "top" ? -1_000_000 : 1_000_000);
1033
+ }
1034
+ return;
1035
+ case "prompt-jump":
1036
+ this.#promptJump(action.delta);
1037
+ return;
1038
+ case "toggle-fold":
1039
+ this.#foldFocused();
1040
+ return;
1041
+ case "open":
1042
+ if (this.#focus === "list")
1043
+ this.sidebar.confirm();
1044
+ else if (this.#focus === "transcript")
1045
+ this.#foldFocused();
1046
+ return;
1047
+ case "copy": {
1048
+ const index = this.pane.focusIndex;
1049
+ if (index === undefined)
1050
+ return;
1051
+ copyToTerminal(this.#tui.terminal, this.pane.textOf(index));
1052
+ this.#flashStatus("Copied");
1053
+ return;
1054
+ }
1055
+ case "fork-here": {
1056
+ const id = this.#activeId;
1057
+ const index = this.pane.focusIndex;
1058
+ if (id === undefined || index === undefined)
1059
+ return;
1060
+ this.editor.disableSubmit = true;
1061
+ try {
1062
+ const forked = await this.#client.forkConversation(id, this.pane.entryIdOf(index));
1063
+ await this.sidebar.refresh();
1064
+ await this.selectConversation(forked.id);
1065
+ }
1066
+ catch (error) {
1067
+ this.pane.showError(describeCommandError("fork", error));
1068
+ }
1069
+ finally {
1070
+ this.editor.disableSubmit = false;
1071
+ }
1072
+ return;
1073
+ }
1074
+ case "edit-here":
1075
+ await this.#editHere();
1076
+ return;
1077
+ case "edit-in-vim":
1078
+ this.#editInVim();
1079
+ return;
1080
+ case "picker":
1081
+ this.#openPickerFor(action.kind);
1082
+ return;
1083
+ case "new-conversation":
1084
+ await this.createAndSelect();
1085
+ return;
1086
+ case "cycle-thinking":
1087
+ await this.#cycleThinking();
1088
+ return;
1089
+ case "search":
1090
+ this.#beginSearch(action.direction);
1091
+ return;
1092
+ case "search-next":
1093
+ this.#searchNext(action.reverse);
1094
+ return;
1095
+ case "answer-interaction":
1096
+ if (!this.interactions.answerMode)
1097
+ this.interactions.beginAnswer();
1098
+ return;
1099
+ case "cancel-run":
1100
+ this.#abortActive();
1101
+ return;
1102
+ case "redraw":
1103
+ this.invalidate();
1104
+ this.#tui.requestRender(true);
1105
+ return;
1106
+ case "quit":
1107
+ this.onQuit?.();
1108
+ return;
1109
+ case "help":
1110
+ this.#openHelp();
1111
+ return;
1112
+ case "command-line":
1113
+ this.editor.setText("/");
1114
+ return;
1115
+ case "run-command":
1116
+ await this.runCommand(action.line);
1117
+ return;
1118
+ }
1119
+ }
1120
+ /**
1121
+ * The key reference overlay (C5): the launcher wires {@link helpOverlay}
1122
+ * to `showHelp(tui, keymap)`. Without the seam the one-line hint flash
1123
+ * is the fallback (the unit harness mounts no overlay).
1124
+ */
1125
+ #openHelp() {
1126
+ if (this.#overlayOpen)
1127
+ return;
1128
+ if (this.helpOverlay === undefined) {
1129
+ this.#flashStatus("tab focus · enter open · y copy · f fork · e edit · / search · ctrl+p conversations");
1130
+ return;
1131
+ }
1132
+ this.#overlayOpen = true;
1133
+ this.helpOverlay(() => {
1134
+ this.#overlayOpen = false;
1135
+ });
1136
+ }
1137
+ /** pi-tui focus follows the action layer's region. */
1138
+ #applyFocusTarget() {
1139
+ if (this.#focus === "composer")
1140
+ this.#tui.setFocus(this.editor);
1141
+ else if (this.#focus === "list")
1142
+ this.#tui.setFocus(this.sidebar);
1143
+ else
1144
+ this.#tui.setFocus(this.pane);
1145
+ this.refreshHints();
1146
+ }
1147
+ /**
1148
+ * The launcher's keymap seam (C5 fix): the active keymap's
1149
+ * `hints(ctx)` for the current {@link keyContext}. Wired once at
1150
+ * launch; {@link refreshHints} re-polls it on every focus change
1151
+ * (and the launcher re-polls after each key for vim mode changes).
1152
+ */
1153
+ hintsProvider;
1154
+ /**
1155
+ * Re-poll the keymap's hints into the status bar's steady state.
1156
+ * A transient flash or the search overlay owns the bar's right
1157
+ * cluster until it restores the snapshot, so only the snapshot is
1158
+ * updated while one is up (the restore paints the fresh hints).
1159
+ */
1160
+ refreshHints() {
1161
+ if (this.#statusBar === undefined || this.hintsProvider === undefined)
1162
+ return;
1163
+ const hints = this.hintsProvider();
1164
+ const base = this.#statusSnapshot ?? { conversation: "", hints: [] };
1165
+ const next = { ...base, hints };
1166
+ this.#statusSnapshot = next;
1167
+ if (this.#search === undefined && this.#statusBar.getState().message === undefined) {
1168
+ this.#statusBar.set(next);
1169
+ }
1170
+ }
1171
+ /** Move the transcript's focused turn, clamped to the turn count. */
1172
+ #moveTranscriptFocus(delta) {
1173
+ const count = this.pane.turns().length;
1174
+ if (count === 0)
1175
+ return;
1176
+ const current = this.pane.focusIndex;
1177
+ if (current === undefined) {
1178
+ this.pane.setFocus(delta < 0 ? count - 1 : 0);
1179
+ return;
1180
+ }
1181
+ this.pane.setFocus(Math.max(0, Math.min(current + delta, count - 1)));
1182
+ }
1183
+ /** Fold/unfold the focused assistant turn (no-op without one). */
1184
+ #foldFocused() {
1185
+ const index = this.pane.focusIndex;
1186
+ if (index !== undefined)
1187
+ this.pane.toggleFold(index);
1188
+ }
1189
+ /** Focus the previous/next user turn (delta -1 backward, 1 forward). */
1190
+ #promptJump(delta) {
1191
+ const turns = this.pane.turns();
1192
+ const current = this.pane.focusIndex ?? (delta < 0 ? turns.length : -1);
1193
+ for (let i = current + delta; i >= 0 && i < turns.length; i += delta) {
1194
+ if (turns[i].kind === "user") {
1195
+ this.pane.setFocus(i);
1196
+ return;
1197
+ }
1198
+ }
1199
+ }
1200
+ /** The transcript search overlay: a `/` query line in the status bar. */
1201
+ #beginSearch(direction) {
1202
+ this.#search = { query: "", direction };
1203
+ this.#overlayOpen = true;
1204
+ this.#paintSearch();
1205
+ }
1206
+ /** The search line's status-bar rendering. */
1207
+ #paintSearch() {
1208
+ const search = this.#search;
1209
+ if (this.#statusBar === undefined || search === undefined)
1210
+ return;
1211
+ const base = this.#statusSnapshot ?? { conversation: "", hints: [] };
1212
+ this.#statusBar.set({
1213
+ ...base,
1214
+ message: `/${search.query}`,
1215
+ });
1216
+ }
1217
+ /** End the search overlay (Enter keeps the match, Esc restores). */
1218
+ #endSearch() {
1219
+ this.#search = undefined;
1220
+ this.#overlayOpen = false;
1221
+ const base = this.#statusSnapshot;
1222
+ if (this.#statusBar !== undefined && base !== undefined)
1223
+ this.#statusBar.set(base);
1224
+ }
1225
+ /** Advance to the next match (reverse flips the remembered direction). */
1226
+ #searchNext(reverse) {
1227
+ const search = this.#search;
1228
+ if (search === undefined || search.query === "")
1229
+ return;
1230
+ const forward = search.direction === "forward";
1231
+ this.#findMatch(search.query, reverse ? !forward : forward);
1232
+ }
1233
+ /** Focus the next turn whose text contains the query (case-insensitive). */
1234
+ #findMatch(query, forward) {
1235
+ const turns = this.pane.turns();
1236
+ if (turns.length === 0)
1237
+ return false;
1238
+ const needle = query.toLowerCase();
1239
+ const delta = forward ? 1 : -1;
1240
+ const current = this.pane.focusIndex ?? (forward ? -1 : turns.length);
1241
+ for (let i = current + delta; i >= 0 && i < turns.length; i += delta) {
1242
+ if (this.pane.textOf(i).toLowerCase().includes(needle)) {
1243
+ this.pane.setFocus(i);
1244
+ return true;
1245
+ }
1246
+ }
1247
+ return false;
1248
+ }
1249
+ /** The search overlay's input seam (the launcher routes keys here). */
1250
+ #handleSearchKey(data) {
1251
+ const search = this.#search;
1252
+ if (search === undefined)
1253
+ return false;
1254
+ if (matchesKey(data, Key.escape) || data === "\x07") {
1255
+ // Esc — and C-g, the emacs cancel — close the search.
1256
+ this.#endSearch();
1257
+ return true;
1258
+ }
1259
+ // C-s / C-r walk the matches while the overlay stays open (emacs).
1260
+ if (data === "\x13" || data === "\x12") {
1261
+ if (search.query !== "")
1262
+ this.#findMatch(search.query, data === "\x13");
1263
+ return true;
1264
+ }
1265
+ if (matchesKey(data, Key.enter) || data === "\r") {
1266
+ if (search.query !== "") {
1267
+ this.#findMatch(search.query, search.direction === "forward");
1268
+ }
1269
+ this.#endSearch();
1270
+ return true;
1271
+ }
1272
+ if (matchesKey(data, Key.backspace) || data === "\x7f" || data === "\b") {
1273
+ search.query = search.query.slice(0, -1);
1274
+ this.#paintSearch();
1275
+ return true;
1276
+ }
1277
+ if (data.length === 1 && data >= " ") {
1278
+ search.query += data;
1279
+ this.#paintSearch();
1280
+ return true;
1281
+ }
1282
+ return true; // the overlay owns every key while open
1283
+ }
1284
+ /** Open the conversation/model/command picker for `kind`. */
1285
+ #openPickerFor(kind) {
1286
+ if (this.#overlayOpen)
1287
+ return;
1288
+ this.#overlayOpen = true;
1289
+ const close = () => {
1290
+ this.#overlayOpen = false;
1291
+ };
1292
+ if (kind === "conversation") {
1293
+ const items = this.sidebar.rows.map((row) => ({
1294
+ label: `${" ".repeat(row.depth)}${row.depth > 0 ? "↳ " : ""}${row.name}`,
1295
+ detail: row.age,
1296
+ value: row.id,
1297
+ }));
1298
+ openPicker(this.#tui, items, {
1299
+ title: "Conversations",
1300
+ onPick: (id) => {
1301
+ void this.selectConversation(id).catch((error) => {
1302
+ this.pane.showError(describeCommandError("select", error));
1303
+ });
1304
+ },
1305
+ onClose: close,
1306
+ });
1307
+ return;
1308
+ }
1309
+ if (kind === "model") {
1310
+ this.#client
1311
+ .listModels()
1312
+ .then((response) => {
1313
+ openPicker(this.#tui, response.models.map((model) => ({
1314
+ label: model.id,
1315
+ detail: model.name,
1316
+ value: model.id,
1317
+ })), {
1318
+ title: "Models",
1319
+ onPick: (modelId) => {
1320
+ void this.dispatch({ type: "run-command", line: `/model ${modelId}` });
1321
+ },
1322
+ onClose: close,
1323
+ });
1324
+ })
1325
+ .catch((error) => {
1326
+ close();
1327
+ this.pane.showError(describeCommandError("listModels", error));
1328
+ });
1329
+ return;
1330
+ }
1331
+ this.#client
1332
+ .getCommands()
1333
+ .then((response) => {
1334
+ openPicker(this.#tui, response.commands.map((command) => ({
1335
+ label: `/${command.name}`,
1336
+ // An EXPAND entry's detail carries its argument-hint too (Task
1337
+ // 2c — the hint IS the affordance: `/review <focus>`); endpoint
1338
+ // rows stay exactly as before.
1339
+ detail: command.kind === "expand" && command.argsHint !== undefined
1340
+ ? `${command.description} ${command.argsHint}`
1341
+ : command.description,
1342
+ value: command,
1343
+ })), {
1344
+ title: "Commands",
1345
+ onPick: (command) => {
1346
+ this.#focus = "composer";
1347
+ this.#applyFocusTarget();
1348
+ this.editor.setText(commandInsertText(command));
1349
+ },
1350
+ onClose: close,
1351
+ });
1352
+ })
1353
+ .catch((error) => {
1354
+ close();
1355
+ this.pane.showError(describeCommandError("getCommands", error));
1356
+ });
1357
+ }
1358
+ /** The thinking cycle (off → minimal → low → medium → high → xhigh → off). */
1359
+ async #cycleThinking() {
1360
+ const id = this.#activeId;
1361
+ if (id === undefined)
1362
+ return;
1363
+ const order = ["off", "minimal", "low", "medium", "high", "xhigh"];
1364
+ const index = order.indexOf(this.#thinkingLevel);
1365
+ const next = order[(index + 1) % order.length];
1366
+ try {
1367
+ const response = await this.#client.configure(id, { thinking: next });
1368
+ this.#thinkingLevel = response.thinkingLevel;
1369
+ this.#flashStatus(`thinking: ${response.thinkingLevel}`);
1370
+ }
1371
+ catch (error) {
1372
+ this.pane.showError(describeCommandError("configure", error));
1373
+ }
1374
+ }
1375
+ /**
1376
+ * Edit-from-here (the web B4 Edit rule): fork at the PREVIOUS turn so
1377
+ * the message is re-entered; on the first turn there is no fork point,
1378
+ * so a fresh conversation is created. Either way the text prefills the
1379
+ * durable draft (`patchMeta`) and the local composer. The fork point
1380
+ * comes from the TURNS list (webui TurnList's rule): pi-durable mints
1381
+ * ids from ONE global counter (entries, conversations, submissions,
1382
+ * tasks), so entry-id arithmetic (`entryId - 1`) cannot locate the
1383
+ * previous entry.
1384
+ */
1385
+ async #editHere() {
1386
+ const id = this.#activeId;
1387
+ const index = this.pane.focusIndex;
1388
+ if (id === undefined || index === undefined)
1389
+ return;
1390
+ const turn = this.pane.turns()[index];
1391
+ if (turn === undefined || turn.kind !== "user") {
1392
+ this.pane.showError("edit: focus a user turn");
1393
+ return;
1394
+ }
1395
+ const text = this.pane.textOf(index);
1396
+ this.editor.disableSubmit = true;
1397
+ try {
1398
+ const newId = index === 0
1399
+ ? (await this.#client.createConversation()).id
1400
+ : (await this.#client.forkConversation(id, this.pane.entryIdOf(index - 1))).id;
1401
+ await this.#client.patchMeta(newId, { draft: { text } });
1402
+ await this.sidebar.refresh();
1403
+ await this.selectConversation(newId);
1404
+ this.editor.setText(text);
1405
+ this.#focus = "composer";
1406
+ this.#applyFocusTarget();
1407
+ }
1408
+ catch (error) {
1409
+ this.pane.showError(describeCommandError("edit", error));
1410
+ }
1411
+ finally {
1412
+ this.editor.disableSubmit = false;
1413
+ }
1414
+ }
1415
+ /**
1416
+ * The vim command line's command table (Task C4). A `/`-prefixed line
1417
+ * (or any name outside the table) routes through the existing slash
1418
+ * catalog — the table holds only the vim-native commands.
1419
+ */
1420
+ async runCommand(line) {
1421
+ if (line.startsWith("/")) {
1422
+ await this.#runSlashCommand(line);
1423
+ return;
1424
+ }
1425
+ const space = line.indexOf(" ");
1426
+ const name = space === -1 ? line : line.slice(0, space);
1427
+ const arg = space === -1 ? "" : line.slice(space + 1).trim();
1428
+ switch (name) {
1429
+ case "q":
1430
+ case "quit":
1431
+ this.onQuit?.();
1432
+ return;
1433
+ case "new":
1434
+ await this.createAndSelect();
1435
+ return;
1436
+ case "fork":
1437
+ await this.dispatch({ type: "fork-here" });
1438
+ return;
1439
+ case "ls":
1440
+ this.#openPickerFor("conversation");
1441
+ return;
1442
+ case "model":
1443
+ if (arg === "") {
1444
+ this.pane.showError("usage: model <provider/id>");
1445
+ return;
1446
+ }
1447
+ await this.#runSlashCommand(`/model ${arg}`);
1448
+ return;
1449
+ case "set": {
1450
+ const thinking = /^thinking=(\S+)$/.exec(arg);
1451
+ if (thinking === null) {
1452
+ this.pane.showError("usage: set thinking=<level>");
1453
+ return;
1454
+ }
1455
+ await this.#runSlashCommand(`/thinking ${thinking[1]}`);
1456
+ return;
1457
+ }
1458
+ case "b": {
1459
+ if (arg === "") {
1460
+ this.pane.showError("usage: b <id|name>");
1461
+ return;
1462
+ }
1463
+ const hit = /^\d+$/.test(arg)
1464
+ ? this.sidebar.rows.find((row) => row.id === Number(arg))
1465
+ : this.sidebar.rows.find((row) => row.name.toLowerCase().includes(arg.toLowerCase()));
1466
+ if (hit === undefined) {
1467
+ this.#flashStatus("no match");
1468
+ return;
1469
+ }
1470
+ await this.selectConversation(hit.id);
1471
+ return;
1472
+ }
1473
+ default:
1474
+ await this.#runSlashCommand(`/${line}`);
1475
+ }
1476
+ }
1477
+ /**
1478
+ * Edit the composer draft in a vim-family editor (Task C4): the TUI
1479
+ * suspends while vim owns the terminal. No vim found → a status
1480
+ * message and the draft stays untouched; nothing is spawned.
1481
+ */
1482
+ #editInVim() {
1483
+ const editor = this.#resolveVim();
1484
+ if (editor === undefined) {
1485
+ this.#flashStatus("no vim found");
1486
+ return;
1487
+ }
1488
+ const tui = this.#tui;
1489
+ const result = editInVim({ text: this.editor.getText(), editor, tui });
1490
+ if (!result.ok) {
1491
+ this.pane.showError(result.reason);
1492
+ return;
1493
+ }
1494
+ this.editor.setText(result.text);
1495
+ this.#focus = "composer";
1496
+ this.#applyFocusTarget();
1497
+ // Focus and mode must agree: the composer is focused, so the vim
1498
+ // keymap returns to INSERT (the launcher wires this seam).
1499
+ this.enterInsertMode?.();
1500
+ }
1501
+ /** The launcher's vim-keymap seam: re-enter INSERT after edit-in-vim. */
1502
+ enterInsertMode;
1503
+ /**
1504
+ * The launcher's help-overlay seam (C5): opens the key reference for
1505
+ * the active keymap; the callback fires when the overlay closes.
1506
+ */
1507
+ helpOverlay;
1508
+ /**
1509
+ * The slash catalog's command names (C3's picker source, cached) —
1510
+ * the launcher feeds them to the vim `:` Tab completion.
1511
+ */
1512
+ async slashCommandNames() {
1513
+ return this.#catalog.names();
1514
+ }
1515
+ /**
1516
+ * The vim keymap's status-bar seam (Task C4): the app polls the keymap
1517
+ * after each key. `commandLine` set → the bar shows the `:` line;
1518
+ * otherwise the steady state is restored with the keymap's mode chip
1519
+ * in the `mode` segment.
1520
+ */
1521
+ renderCommandLine(commandLine, modeLabel) {
1522
+ const base = this.#statusSnapshot;
1523
+ if (this.#statusBar === undefined || base === undefined)
1524
+ return;
1525
+ if (commandLine !== undefined) {
1526
+ // A dedicated non-expiring segment — the `:` line must outlive the
1527
+ // flash TTL for the whole command mode.
1528
+ this.#statusBar.set({ ...base, commandLine });
1529
+ return;
1530
+ }
1531
+ this.#statusBar.set({ ...base, commandLine: undefined, mode: modeLabel ?? base.mode });
1532
+ }
1533
+ render(width) {
1534
+ return this.#layout.render(width);
1535
+ }
1536
+ invalidate() {
1537
+ this.#layout.invalidate();
1538
+ }
1539
+ }