teamsmith 0.0.0-stage → 0.1.1

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 (243) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -2
  3. package/bin/team.mjs +59 -0
  4. package/install.sh +94 -0
  5. package/package.json +37 -4
  6. package/skills/teamsmith/CHANGELOG.md +747 -0
  7. package/skills/teamsmith/SKILL.md +312 -0
  8. package/skills/teamsmith/extension/team-bg.ts +399 -0
  9. package/skills/teamsmith/extension/team-inbox-watch.ts +1412 -0
  10. package/skills/teamsmith/extension/team-notify.ts +524 -0
  11. package/skills/teamsmith/references/agent-adapters.md +643 -0
  12. package/skills/teamsmith/references/config.md +477 -0
  13. package/skills/teamsmith/references/meeting.md +124 -0
  14. package/skills/teamsmith/references/memory.md +133 -0
  15. package/skills/teamsmith/references/migration.md +227 -0
  16. package/skills/teamsmith/references/openspec.md +208 -0
  17. package/skills/teamsmith/references/philosophy.md +95 -0
  18. package/skills/teamsmith/references/protocol.md +712 -0
  19. package/skills/teamsmith/references/troubleshooting.md +1384 -0
  20. package/skills/teamsmith/references/workflows.md +448 -0
  21. package/skills/teamsmith/scripts/lib/cmd-agents.sh +1709 -0
  22. package/skills/teamsmith/scripts/lib/cmd-bg.sh +284 -0
  23. package/skills/teamsmith/scripts/lib/cmd-bootstrap.sh +311 -0
  24. package/skills/teamsmith/scripts/lib/cmd-config.sh +1156 -0
  25. package/skills/teamsmith/scripts/lib/cmd-death.sh +562 -0
  26. package/skills/teamsmith/scripts/lib/cmd-docs.sh +149 -0
  27. package/skills/teamsmith/scripts/lib/cmd-draft.sh +124 -0
  28. package/skills/teamsmith/scripts/lib/cmd-init.sh +212 -0
  29. package/skills/teamsmith/scripts/lib/cmd-meeting.sh +904 -0
  30. package/skills/teamsmith/scripts/lib/cmd-outbox.sh +196 -0
  31. package/skills/teamsmith/scripts/lib/cmd-project.sh +642 -0
  32. package/skills/teamsmith/scripts/lib/cmd-review.sh +1393 -0
  33. package/skills/teamsmith/scripts/lib/cmd-status.sh +1399 -0
  34. package/skills/teamsmith/scripts/lib/cmd-update.sh +191 -0
  35. package/skills/teamsmith/scripts/lib/cmd-watch.sh +1681 -0
  36. package/skills/teamsmith/scripts/lib/common.sh +4964 -0
  37. package/skills/teamsmith/scripts/lib/draft-entry.sh +51 -0
  38. package/skills/teamsmith/scripts/lib/outbox.sh +2042 -0
  39. package/skills/teamsmith/scripts/lib/tmux-argv.sh +165 -0
  40. package/skills/teamsmith/scripts/monitor.mjs +616 -0
  41. package/skills/teamsmith/scripts/panel/README.md +192 -0
  42. package/skills/teamsmith/scripts/panel/build.sh +47 -0
  43. package/skills/teamsmith/scripts/panel/bun.lock +109 -0
  44. package/skills/teamsmith/scripts/panel/draft-send.sh +68 -0
  45. package/skills/teamsmith/scripts/panel/package.json +24 -0
  46. package/skills/teamsmith/scripts/panel/panel.js +388 -0
  47. package/skills/teamsmith/scripts/panel/src/App.tsx +2150 -0
  48. package/skills/teamsmith/scripts/panel/src/clipboard.ts +154 -0
  49. package/skills/teamsmith/scripts/panel/src/compose.ts +691 -0
  50. package/skills/teamsmith/scripts/panel/src/data.ts +555 -0
  51. package/skills/teamsmith/scripts/panel/src/format.ts +50 -0
  52. package/skills/teamsmith/scripts/panel/src/layout.ts +2562 -0
  53. package/skills/teamsmith/scripts/panel/src/main.tsx +894 -0
  54. package/skills/teamsmith/scripts/panel/src/markdown.ts +340 -0
  55. package/skills/teamsmith/scripts/panel/src/sanitize.ts +42 -0
  56. package/skills/teamsmith/scripts/panel/src/settings.ts +154 -0
  57. package/skills/teamsmith/scripts/panel/src/strings/en.ts +416 -0
  58. package/skills/teamsmith/scripts/panel/src/strings/index.ts +65 -0
  59. package/skills/teamsmith/scripts/panel/src/strings/types.ts +9 -0
  60. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +414 -0
  61. package/skills/teamsmith/scripts/panel/src/theme.ts +116 -0
  62. package/skills/teamsmith/scripts/panel/src/types.ts +652 -0
  63. package/skills/teamsmith/scripts/panel/src/width.ts +105 -0
  64. package/skills/teamsmith/scripts/panel/tsconfig.json +16 -0
  65. package/skills/teamsmith/scripts/shim/signal-gate +156 -0
  66. package/skills/teamsmith/scripts/shim/tmux +403 -0
  67. package/skills/teamsmith/scripts/team +143 -0
  68. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +147 -0
  69. package/skills/teamsmith/templates/BOARD.md.tmpl +18 -0
  70. package/skills/teamsmith/templates/DECISIONS.md.tmpl +22 -0
  71. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +25 -0
  72. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +84 -0
  73. package/skills/teamsmith/templates/ROADMAP.md.tmpl +29 -0
  74. package/skills/teamsmith/templates/config.sh.tmpl +106 -0
  75. package/skills/teamsmith/templates/memory-seed.md.tmpl +46 -0
  76. package/skills/teamsmith/templates/pm-prompt.md.tmpl +110 -0
  77. package/skills/teamsmith/templates/report.md.tmpl +36 -0
  78. package/skills/teamsmith/templates/task.md.tmpl +65 -0
  79. package/skills/teamsmith/templates/threads-README.md +17 -0
  80. package/skills/teamsmith/tests/checkout-shape-probe.sh +571 -0
  81. package/skills/teamsmith/tests/config-cli.sh +1562 -0
  82. package/skills/teamsmith/tests/container-tmux.sh +493 -0
  83. package/skills/teamsmith/tests/coverage-inventory.sh +173 -0
  84. package/skills/teamsmith/tests/death-cause.sh +564 -0
  85. package/skills/teamsmith/tests/delivery-truth.sh +1231 -0
  86. package/skills/teamsmith/tests/fake-tui.py +450 -0
  87. package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +60 -0
  88. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +139 -0
  89. package/skills/teamsmith/tests/fixtures/delivery-truth-real/mock-server.py +29 -0
  90. package/skills/teamsmith/tests/fixtures/delivery-truth-real/observe.ts +20 -0
  91. package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +79 -0
  92. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +175 -0
  93. package/skills/teamsmith/tests/fixtures/p55/flip-p49.sh +229 -0
  94. package/skills/teamsmith/tests/fixtures/p71-incident/README.md +22 -0
  95. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.seen +8 -0
  96. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.wake +9 -0
  97. package/skills/teamsmith/tests/fixtures/p71-incident/pm-nudges.wake +3 -0
  98. package/skills/teamsmith/tests/fixtures/signal-lint-cases.txt +40 -0
  99. package/skills/teamsmith/tests/flip-glue.sh +162 -0
  100. package/skills/teamsmith/tests/flip-m12-26c.sh +129 -0
  101. package/skills/teamsmith/tests/flip-m12.sh +185 -0
  102. package/skills/teamsmith/tests/flip-m16.sh +166 -0
  103. package/skills/teamsmith/tests/flip-m17.sh +204 -0
  104. package/skills/teamsmith/tests/flip-m33.sh +284 -0
  105. package/skills/teamsmith/tests/flip-m34.sh +96 -0
  106. package/skills/teamsmith/tests/flip-m37.sh +185 -0
  107. package/skills/teamsmith/tests/flip-m4.3.sh +375 -0
  108. package/skills/teamsmith/tests/flip-m43.sh +128 -0
  109. package/skills/teamsmith/tests/flip-m44.sh +262 -0
  110. package/skills/teamsmith/tests/flip-m45.sh +244 -0
  111. package/skills/teamsmith/tests/flip-m46.sh +238 -0
  112. package/skills/teamsmith/tests/flip-m48.sh +304 -0
  113. package/skills/teamsmith/tests/flip-m6.2.sh +205 -0
  114. package/skills/teamsmith/tests/flip-m6.3.sh +283 -0
  115. package/skills/teamsmith/tests/flip-m6.4.sh +267 -0
  116. package/skills/teamsmith/tests/flip-m6.5.sh +113 -0
  117. package/skills/teamsmith/tests/flip-m7.1.sh +135 -0
  118. package/skills/teamsmith/tests/flip-m7.2.sh +321 -0
  119. package/skills/teamsmith/tests/flip-p144.sh +112 -0
  120. package/skills/teamsmith/tests/flip-p156.sh +133 -0
  121. package/skills/teamsmith/tests/flip-p158.sh +301 -0
  122. package/skills/teamsmith/tests/flip-p160.sh +182 -0
  123. package/skills/teamsmith/tests/flip-p171.sh +249 -0
  124. package/skills/teamsmith/tests/flip-p18.1.sh +95 -0
  125. package/skills/teamsmith/tests/flip-p20.sh +286 -0
  126. package/skills/teamsmith/tests/flip-p201.sh +249 -0
  127. package/skills/teamsmith/tests/flip-p210.sh +239 -0
  128. package/skills/teamsmith/tests/flip-p211.sh +152 -0
  129. package/skills/teamsmith/tests/flip-p217.sh +288 -0
  130. package/skills/teamsmith/tests/flip-p22.sh +123 -0
  131. package/skills/teamsmith/tests/flip-p23.sh +239 -0
  132. package/skills/teamsmith/tests/flip-p25.sh +165 -0
  133. package/skills/teamsmith/tests/flip-p71.sh +184 -0
  134. package/skills/teamsmith/tests/flip-p72.sh +202 -0
  135. package/skills/teamsmith/tests/frames/README.md +176 -0
  136. package/skills/teamsmith/tests/frames/p78-conversation-rule-below-box.txt +6 -0
  137. package/skills/teamsmith/tests/frames/p78-cursor-mid-draft.txt +6 -0
  138. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor-line.txt +6 -0
  139. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor.txt +6 -0
  140. package/skills/teamsmith/tests/frames/p78-draft-rule-blank-region.txt +6 -0
  141. package/skills/teamsmith/tests/frames/p78-draft-rule-only.txt +5 -0
  142. package/skills/teamsmith/tests/frames/p78-spinner-row-below-cursor.txt +6 -0
  143. package/skills/teamsmith/tests/frames/p78-wider-rule-below-cursor.txt +6 -0
  144. package/skills/teamsmith/tests/frames/p86-f1-mixed-width-disjoint-box.txt +8 -0
  145. package/skills/teamsmith/tests/frames/p86-f1-narrower-width-disjoint-box.txt +8 -0
  146. package/skills/teamsmith/tests/frames/p86-f1-spinner-top-disjoint-box.txt +8 -0
  147. package/skills/teamsmith/tests/frames/pi-0.85.1-update-banner.txt +30 -0
  148. package/skills/teamsmith/tests/frames/pi-0.87.0-draft-half-sentence.txt +30 -0
  149. package/skills/teamsmith/tests/frames/pi-0.87.0-empty-box.txt +30 -0
  150. package/skills/teamsmith/tests/frames/pi-0.87.0-one-line-draft.txt +30 -0
  151. package/skills/teamsmith/tests/frames/pi-0.87.0-project-trust-prompt.txt +30 -0
  152. package/skills/teamsmith/tests/frames/pi-0.99.2-empty-editor.txt +32 -0
  153. package/skills/teamsmith/tests/frames/pi-0.99.2-human-draft.txt +32 -0
  154. package/skills/teamsmith/tests/frames/pi-1.0.0-git-error-in-box.txt +32 -0
  155. package/skills/teamsmith/tests/gate-guard.sh +112 -0
  156. package/skills/teamsmith/tests/guard-matrix.sh +233 -0
  157. package/skills/teamsmith/tests/install-shape.sh +731 -0
  158. package/skills/teamsmith/tests/ledger-ban.sh +612 -0
  159. package/skills/teamsmith/tests/lib/box-judge.sh +68 -0
  160. package/skills/teamsmith/tests/lib/checkout-shape.sh +77 -0
  161. package/skills/teamsmith/tests/lib/loop-scan.awk +114 -0
  162. package/skills/teamsmith/tests/lib/pty-wait.sh +676 -0
  163. package/skills/teamsmith/tests/lib/section-guard.sh +855 -0
  164. package/skills/teamsmith/tests/lib/shell-lex.pl +261 -0
  165. package/skills/teamsmith/tests/lib/tmp-root.sh +528 -0
  166. package/skills/teamsmith/tests/lib/tmux-cap.sh +35 -0
  167. package/skills/teamsmith/tests/lib/tmux-iso-call-probe.sh +81 -0
  168. package/skills/teamsmith/tests/lib/tmux-iso-probe.sh +46 -0
  169. package/skills/teamsmith/tests/lib/tmux-iso.sh +381 -0
  170. package/skills/teamsmith/tests/load-experiment.sh +290 -0
  171. package/skills/teamsmith/tests/loop-inventory.tsv +84 -0
  172. package/skills/teamsmith/tests/panel-b2-slow-stub.sh +19 -0
  173. package/skills/teamsmith/tests/panel-b2.sh +1183 -0
  174. package/skills/teamsmith/tests/panel-b3-pty-mouse.py +240 -0
  175. package/skills/teamsmith/tests/panel-b3-pty-tmux-mouse.py +138 -0
  176. package/skills/teamsmith/tests/panel-b3-stub.sh +279 -0
  177. package/skills/teamsmith/tests/panel-b3.sh +1301 -0
  178. package/skills/teamsmith/tests/panel-choices.sh +572 -0
  179. package/skills/teamsmith/tests/panel-clipboard-model.ts +187 -0
  180. package/skills/teamsmith/tests/panel-compose-model.ts +290 -0
  181. package/skills/teamsmith/tests/panel-contrast.mjs +81 -0
  182. package/skills/teamsmith/tests/panel-cpu-premise.sh +173 -0
  183. package/skills/teamsmith/tests/panel-cpu.sh +391 -0
  184. package/skills/teamsmith/tests/panel-flip-m54.sh +207 -0
  185. package/skills/teamsmith/tests/panel-flip-p123.sh +278 -0
  186. package/skills/teamsmith/tests/panel-flip-p125.sh +318 -0
  187. package/skills/teamsmith/tests/panel-flip-p128.sh +259 -0
  188. package/skills/teamsmith/tests/panel-keyprobe-pty.py +99 -0
  189. package/skills/teamsmith/tests/panel-keyprobe-stub.sh +41 -0
  190. package/skills/teamsmith/tests/panel-keyprobe.sh +82 -0
  191. package/skills/teamsmith/tests/panel-keyprobe.tsx +116 -0
  192. package/skills/teamsmith/tests/panel-knobs.sh +83 -0
  193. package/skills/teamsmith/tests/panel-p21.sh +2181 -0
  194. package/skills/teamsmith/tests/panel-snapshots.sh +802 -0
  195. package/skills/teamsmith/tests/panel-strings.mjs +195 -0
  196. package/skills/teamsmith/tests/perf.sh +740 -0
  197. package/skills/teamsmith/tests/pm-box-real.sh +350 -0
  198. package/skills/teamsmith/tests/pulse-nudge-key.sh +563 -0
  199. package/skills/teamsmith/tests/routes.sh +1652 -0
  200. package/skills/teamsmith/tests/section-budgets.tsv +150 -0
  201. package/skills/teamsmith/tests/section-guard.sh +231 -0
  202. package/skills/teamsmith/tests/section-needs-audit.sh +94 -0
  203. package/skills/teamsmith/tests/section-paths.tsv +142 -0
  204. package/skills/teamsmith/tests/section-select.sh +648 -0
  205. package/skills/teamsmith/tests/signal-gate.sh +366 -0
  206. package/skills/teamsmith/tests/signal-lint-legacy.txt +14 -0
  207. package/skills/teamsmith/tests/signal-lint.pl +416 -0
  208. package/skills/teamsmith/tests/skill-load.mjs +65 -0
  209. package/skills/teamsmith/tests/smoke.sh +19599 -0
  210. package/skills/teamsmith/tests/snapshots/zh-dark-120-detail.txt +32 -0
  211. package/skills/teamsmith/tests/snapshots/zh-dark-120-p4.txt +32 -0
  212. package/skills/teamsmith/tests/snapshots/zh-dark-120.txt +32 -0
  213. package/skills/teamsmith/tests/snapshots/zh-dark-160-p4.txt +32 -0
  214. package/skills/teamsmith/tests/snapshots/zh-dark-160.txt +32 -0
  215. package/skills/teamsmith/tests/snapshots/zh-dark-59-detail.txt +32 -0
  216. package/skills/teamsmith/tests/snapshots/zh-dark-59-p4.txt +32 -0
  217. package/skills/teamsmith/tests/snapshots/zh-dark-59.txt +32 -0
  218. package/skills/teamsmith/tests/snapshots/zh-dark-99-p4.txt +32 -0
  219. package/skills/teamsmith/tests/snapshots/zh-dark-99.txt +32 -0
  220. package/skills/teamsmith/tests/snapshots/zh-light-120-detail.txt +32 -0
  221. package/skills/teamsmith/tests/snapshots/zh-light-120-p4.txt +32 -0
  222. package/skills/teamsmith/tests/snapshots/zh-light-120.txt +32 -0
  223. package/skills/teamsmith/tests/snapshots/zh-light-160-p4.txt +32 -0
  224. package/skills/teamsmith/tests/snapshots/zh-light-160.txt +32 -0
  225. package/skills/teamsmith/tests/snapshots/zh-light-59-detail.txt +32 -0
  226. package/skills/teamsmith/tests/snapshots/zh-light-59-p4.txt +32 -0
  227. package/skills/teamsmith/tests/snapshots/zh-light-59.txt +32 -0
  228. package/skills/teamsmith/tests/snapshots/zh-light-99-p4.txt +32 -0
  229. package/skills/teamsmith/tests/snapshots/zh-light-99.txt +32 -0
  230. package/skills/teamsmith/tests/spec-ledger-refs.tsv +78 -0
  231. package/skills/teamsmith/tests/spec-refs.sh +826 -0
  232. package/skills/teamsmith/tests/task-header-model.sh +267 -0
  233. package/skills/teamsmith/tests/team-bg-flip.sh +239 -0
  234. package/skills/teamsmith/tests/team-bg-harness.mjs +392 -0
  235. package/skills/teamsmith/tests/team-bg-stop.sh +434 -0
  236. package/skills/teamsmith/tests/team-inbox-watch-flip.sh +191 -0
  237. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +1559 -0
  238. package/skills/teamsmith/tests/tmp-hygiene.sh +1190 -0
  239. package/skills/teamsmith/tests/tmux-lint-legacy.txt +31 -0
  240. package/skills/teamsmith/tests/tmux-lint.pl +604 -0
  241. package/skills/teamsmith-init/SKILL.md +100 -0
  242. package/skills/teamsmith-init/references/bootstrap.md +74 -0
  243. package/skills/teamsmith-init/templates/bootstrap-prompt.md.tmpl +46 -0
@@ -0,0 +1,2150 @@
1
+ // The Ink frame: Ink owns the terminal (raw keys, redraw, cursor, mouse bytes), the layout module
2
+ // owns the rows. Rendering pre-computed segments — rather than nested flex boxes — is what makes
3
+ // the TUI and `--print` show the same frame, and it keeps the pane capture free of content the
4
+ // sanitizer has not seen: every segment is built from sanitized fields by construction.
5
+ //
6
+ // B3 adds the console surface: four pages (Tab / `1`–`4`, `state/panel-page`), the settings
7
+ // overlay (`,`) writing `state/panel.conf`, SGR mouse (every documented key is a click target and
8
+ // the wheel scrolls), the zh/en string tables and the density preference. `console-board-page` adds
9
+ // the board page's kanban and the read-only markdown detail view. The compose entry (B2) works on
10
+ // every page; the receipt and the three actions are unchanged.
11
+
12
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
13
+ import { writeSync } from 'node:fs'
14
+ import { Box, Text, useApp, useCursor, useInput } from 'ink'
15
+ import { layout, resolveFocus, focusRefOf, focusRow, rowKey, settingsViewRows } from './layout.js'
16
+ import type { LayoutInput } from './layout.js'
17
+ import { clockOf } from './format.js'
18
+ import { fill, stringsFor, type Strings } from './strings/index.js'
19
+ import { composeKey, cpLength, cursorView, insertAt, intake, killSpan, moveCursor, popUndo, pushKill, pushUndo, receiptLine, resetKillDirection, ringEntry, type ComposeMode, type ComposeView, type KillRing, type Receipt, type UndoSnapshot } from './compose.js'
20
+ import type { Settings } from './settings.js'
21
+ import type { Action, DetailWindow, FocusRef, FrameInput, PageId, PrefName, Segment, SettingsChoiceEntry, SettingsChoicePicker, SettingsKey, SettingsWindow, ViewState } from './types.js'
22
+ import type { Palette } from './theme.js'
23
+ import { dispWidth } from './width.js'
24
+
25
+ const TRAY_TL = '╭'
26
+ const TRAY_TR = '╮'
27
+ const TRAY_H = '─'
28
+ const TRAY_V = '│'
29
+
30
+ /**
31
+ * The kinds whose editor is the choice picker (M55). `enum` joins only when the command reports
32
+ * values (an enum with no constraints has no choice set: R3's visible fallback names the reason),
33
+ * and a key the command reports without a `choices` object falls back to the compose editor — the
34
+ * bundle works against an older command instead of inventing options.
35
+ */
36
+ const CHOICE_KINDS = new Set(['bool', 'enum', 'int', 'seconds', 'mb', 'bytes', 'pct', 'path', 'model', 'pairlist', 'winlist', 'pattern'])
37
+ const NUMERIC_KINDS = new Set(['int', 'seconds', 'mb', 'bytes', 'pct'])
38
+
39
+ function hasChoiceEditor(key: SettingsKey): boolean {
40
+ const ch = key.choices
41
+ if (!ch || typeof ch !== 'object' || !Array.isArray(ch.values)) return false
42
+ const kind = String(key.kind ?? '')
43
+ if (!CHOICE_KINDS.has(kind)) return false
44
+ if (kind === 'enum') return ch.values.length > 0
45
+ return true
46
+ }
47
+
48
+ /** Open-bottom compose tray (top edge + left wall). The last text row stays last so the IME cursor stays on the draft. */
49
+ function composeTrayTop(title: string, width: number): string {
50
+ const w = Math.max(2, Math.floor(width) || 2)
51
+ const inner = w - 2
52
+ if (!title) return TRAY_TL + TRAY_H.repeat(inner) + TRAY_TR
53
+ const titleW = dispWidth(title)
54
+ if (1 + 1 + titleW + 1 > inner) return TRAY_TL + TRAY_H + title + TRAY_TR
55
+ const fill = inner - (1 + 1 + titleW + 1)
56
+ return `${TRAY_TL}${TRAY_H} ${title} ${TRAY_H.repeat(Math.max(0, fill))}${TRAY_TR}`
57
+ }
58
+
59
+ /** The console's own actions, owned by main.tsx (file I/O, subprocesses, the editor relay). */
60
+ export interface PanelApi {
61
+ readDraft(): string
62
+ writeDraft(text: string): void
63
+ clearDraft(): void
64
+ send(text: string): Promise<Receipt>
65
+ flushQueue(): Promise<{ ok: boolean; line: string }>
66
+ setStandby(on: boolean, reason: string): Promise<{ ok: boolean; line: string }>
67
+ /** Hand the terminal to `$EDITOR`; resolves with the (possibly edited) draft. */
68
+ editDraft(text: string): Promise<string>
69
+ /**
70
+ * The `C-v` clipboard probe (P20/B4): `path` = a temporary image file to insert, `text` = the
71
+ * clipboard's text, `none` = nothing to paste. Never called from the render/refresh path.
72
+ */
73
+ pasteClipboard(): Promise<{ kind: 'path' | 'text' | 'none'; value: string }>
74
+ /** Rebuild the cache now (after an action that changed the state the frame reads). */
75
+ refreshNow(): void
76
+ /** True while an external program owns the terminal (the render callback must not run). */
77
+ suspended(): boolean
78
+ /** The shared clock ref (0 = no tick yet): row 0 renders this stamp so repaints never revert it. */
79
+ clockNowMs(): number
80
+ /** Register the title band's base row + palette for the out-of-React clock writer (null = off). */
81
+ registerClockRow(row: Segment[] | null, palette: Palette): void
82
+ /**
83
+ * Register the compose insertion point (Ink-output coordinates) for the cursor-aware stdout,
84
+ * which re-asserts it absolutely after every Ink write; null = not composing (cursor hidden).
85
+ */
86
+ setComposeCursor(position: { x: number; y: number } | null): void
87
+ /** Persist one preference (`state/panel.conf`). */
88
+ saveSettings(settings: Settings): void
89
+ /** Remember the current page (`state/panel-page`). */
90
+ savePage(page: PageId): void
91
+ /** Tell the cache whether the activity block is wanted (the overlay's TUI-only override). */
92
+ setActivity(on: boolean): void
93
+ /**
94
+ * Tell the cache which entry's detail view is open (null = closed). While an id is set the
95
+ * `detail` block joins the wanted set; `file` selects the repo-relative path to serve (the first
96
+ * discovered file when omitted). Both are cached options, so an unchanged call rebuilds nothing.
97
+ */
98
+ setDetail(id: string | null, file?: string | null): void
99
+ /** Rebuild the patrol window as the headless tick loop (`team pulse collapse`). */
100
+ collapse(): Promise<{ ok: boolean; line: string }>
101
+ /** Represents one `team config set` result: the exit code (the machine contract) + one line. */
102
+ setSetting(
103
+ key: string,
104
+ value: string,
105
+ opts: { dryRun?: boolean; fingerprint?: string | null; allowDanger?: boolean },
106
+ ): Promise<{ code: number; line: string }>
107
+ /**
108
+ * Re-read the settings block in the background after a write settled (M65/D11). The receipt is
109
+ * drawn from the command's own settle and never waits for this read; it only refreshes what the
110
+ * next interaction sees. Never awaited on the interaction path.
111
+ */
112
+ refreshSettingsSoon(): void
113
+ /** One `team config set-agent-model <seat> <model|->` invocation (P22/B4). */
114
+ setSeatModel(
115
+ seat: string,
116
+ model: string,
117
+ opts: { dryRun?: boolean; fingerprint?: string | null },
118
+ ): Promise<{ code: number; line: string }>
119
+ /**
120
+ * The path kind's existence mark (M55): the value against the rule the command's own `note`
121
+ * carries (`file`/`dir`/`exec`/`any`). A pure read — the command has no existence check, so the
122
+ * mark is an advisory the confirmation repeats, never a refusal.
123
+ */
124
+ pathMark(value: string, rule: string): 'exists' | 'missing' | 'not-exec'
125
+ /**
126
+ * Tell the cache whether the project-settings view is open (P22/B2). While it is, the `settings`
127
+ * block joins the wanted set; closing it drops the block so a parked console spawns no reader.
128
+ */
129
+ setSettingsOpen(open: boolean): void
130
+ }
131
+
132
+ export interface AppProps {
133
+ frame: FrameInput
134
+ /** Redraw period in seconds (`TEAM_MONITOR_REFRESH`). */
135
+ refresh: number
136
+ /** Called once per redraw; returns the fresh frame (and runs a tick when one is due). */
137
+ reload: () => FrameInput
138
+ /** Render one frame and exit. */
139
+ once: boolean
140
+ api: PanelApi
141
+ /** The initial preferences (from `state/panel.conf` in the TUI, defaults elsewhere). */
142
+ settings: Settings
143
+ /** The page restored from `state/panel-page` (or the preference's default). */
144
+ page: PageId
145
+ /** The palette resolved from the `theme` preference + the environment. */
146
+ palette: Palette
147
+ /** True when a CLI flag pins the activity column (the overlay cannot override it). */
148
+ activityPinned: boolean
149
+ }
150
+
151
+ interface Size {
152
+ columns: number
153
+ rows: number
154
+ }
155
+
156
+ /**
157
+ * A cheap content signature: identical data renders an identical frame, so a refresh that changed
158
+ * nothing must not repaint (the red line is <1% of one core; an idle console should cost ~0).
159
+ * Exported because main.tsx's `adopt()` guards its Ink `rerender` with the same rule.
160
+ *
161
+ * The panel's `timestamp` is deliberately excluded: the title band's clock is driven by the App's
162
+ * own 1s ticker (it repaints just that row), so a new assembly time alone is not a visible change
163
+ * (and repainting the whole frame for it is what pushed the console over the red line).
164
+ */
165
+ export function frameSignature(frame: FrameInput): string {
166
+ const { timestamp: _stamp, ...panel } = frame.panel ?? {}
167
+ return JSON.stringify([panel, frame.degraded ?? [], frame.activityBlocks ?? [], frame.blocks ?? {}, frame.activity])
168
+ }
169
+
170
+ function liveSize(fallback: FrameInput): Size {
171
+ return {
172
+ columns: process.stdout.columns || fallback.width,
173
+ rows: process.stdout.rows || fallback.height,
174
+ }
175
+ }
176
+
177
+ const MOUSE_ON = '\u001b[?1000h\u001b[?1006h'
178
+ const MOUSE_OFF = '\u001b[?1000l\u001b[?1006l'
179
+ const SGR_MOUSE = /^(?:\u001b)?\[<(\d+);(\d+);(\d+)([Mm])$/
180
+
181
+ const PREFS: PrefName[] = ['lang', 'defaultPage', 'activity', 'mouse', 'density']
182
+
183
+ /**
184
+ * One frame row. Memoized: a repaint that only changed the clock (or one block) must not re-render
185
+ * the other rows — React skips a memoized subtree whose props are referentially equal, and the
186
+ * caller below reuses the previous row object whenever its content key is unchanged.
187
+ */
188
+ const Row = React.memo(function Row({ row, palette }: { row: Segment[]; palette: Palette }) {
189
+ return (
190
+ <Text wrap="truncate">
191
+ {row.length
192
+ ? row.map((segment, j) => (
193
+ <Text key={j} color={palette.tones[segment.tone]}>
194
+ {segment.text}
195
+ </Text>
196
+ ))
197
+ : ' '}
198
+ </Text>
199
+ )
200
+ })
201
+
202
+ /** Reuse the previous row objects whose content did not change, so `Row` can skip them. */
203
+ function stableRows(prev: { key: string; row: Segment[] }[], rows: Segment[][]): { key: string; row: Segment[] }[] {
204
+ return rows.map((row, i) => {
205
+ const key = rowKey(row)
206
+ const before = prev[i]
207
+ if (before && before.key === key) return before
208
+ return { key, row }
209
+ })
210
+ }
211
+
212
+ /**
213
+ * Patch the title band's clock segment (the segment `titleBlock` marked `clock`) with the shared
214
+ * ticker's UTC time. Called at render time with the ref's ms — App renders are data-gated, so a
215
+ * repaint picks up the latest stamp and never reverts the screen. A degraded frame block has no
216
+ * clock segment and keeps its `—` instead of a clock that would mask the failure.
217
+ */
218
+ function clockRow(row: Segment[], now: number): Segment[] {
219
+ if (now <= 0) return row
220
+ const seg = row.find((s) => s.clock)
221
+ if (!seg) return row
222
+ const stamp = clockOf(new Date(now).toISOString())
223
+ if (seg.text === stamp) return row
224
+ return row.map((s) => (s.clock ? { ...s, text: stamp } : s))
225
+ }
226
+
227
+ export function App({
228
+ frame,
229
+ refresh,
230
+ reload,
231
+ once,
232
+ api,
233
+ settings: settingsProp,
234
+ page: pageProp,
235
+ palette,
236
+ activityPinned,
237
+ }: AppProps) {
238
+ const [data, setData] = useState<FrameInput>(frame)
239
+ const [size, setSize] = useState<Size>(() => liveSize(frame))
240
+ const [scroll, setScroll] = useState(0)
241
+ const [composing, setComposing] = useState(false)
242
+ const [mode, setMode] = useState<ComposeMode>('message')
243
+ const [draft, setDraft] = useState('')
244
+ // The insertion point, as a codepoint index into the draft (P20/B1). It lives in a ref beside the
245
+ // state because the input handler edits the draft synchronously (two keys in one React batch must
246
+ // see each other's result, the same reason `draftRef` exists).
247
+ const [cursor, setCursor] = useState(0)
248
+ const [receipt, setReceipt] = useState<Receipt | null>(null)
249
+ const [status, setStatus] = useState<string | null>(null)
250
+ const [busy, setBusy] = useState(false)
251
+ const [editorOpen, setEditorOpen] = useState(false)
252
+ const [settings, setSettings] = useState<Settings>(settingsProp)
253
+ const [page, setPage] = useState<PageId>(pageProp)
254
+ const [overlay, setOverlay] = useState(false)
255
+ const [overlayIndex, setOverlayIndex] = useState(0)
256
+ const [viewEntry, setViewEntry] = useState<number | null>(null)
257
+ const [focus, setFocus] = useState<FocusRef | null>(null)
258
+ const [laneOffset, setLaneOffset] = useState<Record<string, number>>({})
259
+ // The open detail view's entry id (the board page's Enter / a click on the focused card), its
260
+ // tab and its document scroll. The view is read-only: no key of its own beyond navigation.
261
+ const [detailId, setDetailId] = useState<string | null>(null)
262
+ const [detailIndex, setDetailIndex] = useState(0)
263
+ const [detailScroll, setDetailScroll] = useState(0)
264
+ // P22/B2: the project-settings view (opened from the overlay's navigation row), its window and
265
+ // its filter. The view is a view, not a page: the four-page composition and `state/panel-page`
266
+ // keep their meaning, and `esc` lands back on the overlay row it was opened from.
267
+ const [settingsView, setSettingsView] = useState(false)
268
+ const [settingsOrigin, setSettingsOrigin] = useState(0)
269
+ const [settingsFocus, setSettingsFocus] = useState(0)
270
+ const [settingsFilter, setSettingsFilter] = useState('')
271
+ /**
272
+ * The settings view's own row-window offset (P30/D5), `null` = unset and the window keeps the
273
+ * focus-follow rule. The wheel sets it; the focus keys push it exactly enough to keep the
274
+ * focused row inside (the board page's `laneOffset` rule).
275
+ */
276
+ const [settingsOffset, setSettingsOffset] = useState<number | null>(null)
277
+ /** The pending two-step write confirmation ({danger} = the command answered 7). */
278
+ const [settingConfirm, setSettingConfirm] = useState<{ key: string; next: string; danger: boolean } | null>(null)
279
+ /** The seat picker (P22/B4): the seat, its row and the option list with the selection. */
280
+ const [seatPicker, setSeatPicker] = useState<{ agent: string; row: number; models: string[]; index: number } | null>(null)
281
+ /** The choice picker (M55): the key's schema-derived entries and the selection. */
282
+ const [choicePicker, setChoicePicker] = useState<SettingsChoicePicker | null>(null)
283
+ const { exit } = useApp()
284
+ const scrollRef = useRef(0)
285
+ const dataRef = useRef(frame)
286
+ const draftRef = useRef('')
287
+ const cursorRef = useRef(0)
288
+ // pi's recoverable deletions (P20/B2): the ring, the bounded undo history and the one-step
289
+ // yank-pop state. They are refs, not state, because two keys inside one React batch must see
290
+ // each other's result (the same reason `draftRef` exists).
291
+ const killRingRef = useRef<KillRing>({ entries: [], lastDirection: null })
292
+ const undoRef = useRef<UndoSnapshot[]>([])
293
+ /** How many `alt+y` pops followed the last yank, and how long the text it inserted is. */
294
+ const yankRef = useRef<{ pops: number; length: number } | null>(null)
295
+ /** pi's `lastAction`: `alt+y` only pops right after a yank. */
296
+ const lastActionRef = useRef<'yank' | 'edit' | null>(null)
297
+ /** One clipboard probe at a time: a second `C-v` while one is in flight is a no-op. */
298
+ const probingRef = useRef(false)
299
+ const pasteOpenRef = useRef(false)
300
+ const settingsRef = useRef(settings)
301
+ const pageRef = useRef(page)
302
+ const targetsRef = useRef<{ row: number; hit: { start: number; end: number; action: Action } }[]>([])
303
+ const overlayIndexRef = useRef(0)
304
+ const focusRef = useRef<FocusRef | null>(null)
305
+ const laneOffsetRef = useRef<Record<string, number>>({})
306
+ const lanesRef = useRef<{ lane: string; offset: number; visible: number; count: number }[]>([])
307
+ /** The work page's board rows in the order the last frame drew them (P20/B5). */
308
+ const boardOrderRef = useRef<FocusRef[]>([])
309
+ const detailRef = useRef<DetailWindow | null>(null)
310
+ const detailIdRef = useRef<string | null>(null)
311
+ const detailIndexRef = useRef(0)
312
+ const detailScrollRef = useRef(0)
313
+ const settingsViewRef = useRef(false)
314
+ const settingsFocusRef = useRef(0)
315
+ const settingsFilterRef = useRef('')
316
+ const settingsOffsetRef = useRef<number | null>(null)
317
+ /** The row window the last frame drew (the wheel and the focus keys clamp against it). */
318
+ const settingsWindowRef = useRef<SettingsWindow | null>(null)
319
+ /** The row the open `setting` editor writes (the fingerprint was pinned when it opened). */
320
+ const settingRowRef = useRef<{ row: number; key: string; value: string; cls: string; fingerprint: string; seat?: string; kind?: string; choices?: SettingsKey['choices'] } | null>(null)
321
+ const seatPickerRef = useRef<{ agent: string; row: number; models: string[]; index: number } | null>(null)
322
+ seatPickerRef.current = seatPicker
323
+ const choicePickerRef = useRef<SettingsChoicePicker | null>(null)
324
+ choicePickerRef.current = choicePicker
325
+ const settingConfirmRef = useRef<{ key: string; next: string; danger: boolean } | null>(null)
326
+ /**
327
+ * The value the picker's first accept found dangerous (the command's exit 7): one more accept of
328
+ * that same value writes it with the command's danger allowance, and any other selection clears
329
+ * it so a new value is validated first (M65/D10).
330
+ */
331
+ const choiceDangerRef = useRef<{ key: string; value: string } | null>(null)
332
+ focusRef.current = focus
333
+ laneOffsetRef.current = laneOffset
334
+ detailIdRef.current = detailId
335
+ detailIndexRef.current = detailIndex
336
+ detailScrollRef.current = detailScroll
337
+ settingsViewRef.current = settingsView
338
+ settingsFocusRef.current = settingsFocus
339
+ settingsFilterRef.current = settingsFilter
340
+ settingsOffsetRef.current = settingsOffset
341
+
342
+ const strings: Strings = stringsFor(settings.lang)
343
+ const stringsRef = useRef(strings)
344
+ stringsRef.current = strings
345
+ overlayIndexRef.current = overlayIndex
346
+
347
+ useEffect(() => {
348
+ dataRef.current = frame
349
+ setData(frame)
350
+ }, [frame])
351
+
352
+ const saveSettings = useCallback(
353
+ (next: Settings) => {
354
+ settingsRef.current = next
355
+ setSettings(next)
356
+ api.saveSettings(next)
357
+ },
358
+ [api],
359
+ )
360
+
361
+ const goPage = useCallback(
362
+ (next: PageId) => {
363
+ pageRef.current = next
364
+ setPage(next)
365
+ setViewEntry(null)
366
+ setDetailId(null)
367
+ setDetailIndex(0)
368
+ setDetailScroll(0)
369
+ api.savePage(next)
370
+ },
371
+ [api],
372
+ )
373
+
374
+ /** The scroll offset lives in a ref as well as in state: the periodic refresh re-renders from
375
+ * `scrollRef.current`, so a wheel that only updated state would be reset by the next cadence. */
376
+ const updateScroll = useCallback((fn: (v: number) => number) => {
377
+ const next = Math.max(0, fn(scrollRef.current))
378
+ scrollRef.current = next
379
+ setScroll(next)
380
+ }, [])
381
+
382
+ const updateDraft = useCallback(
383
+ (next: string, persist = true) => {
384
+ draftRef.current = next
385
+ setDraft(next)
386
+ if (persist) api.writeDraft(next)
387
+ },
388
+ [api],
389
+ )
390
+
391
+ /** Move the insertion point (clamped by the model's callers, never past the draft's ends). */
392
+ const setPoint = useCallback((next: number) => {
393
+ cursorRef.current = next
394
+ setCursor(next)
395
+ }, [])
396
+
397
+ /** One draft edit at the insertion point: text, point and `state/draft.md` move together. */
398
+ const updateCompose = useCallback(
399
+ (next: { text: string; cursor: number }, persist = true) => {
400
+ draftRef.current = next.text
401
+ cursorRef.current = next.cursor
402
+ setDraft(next.text)
403
+ setCursor(next.cursor)
404
+ if (persist) api.writeDraft(next.text)
405
+ },
406
+ [api],
407
+ )
408
+
409
+ /**
410
+ * The width one drawn draft row has: the boxed (comfortable) tray eats two columns, the compact
411
+ * style draws the raw rows. This must be the same expression `lines` uses to build the rows, so
412
+ * the cursor's visual-row moves and the drawn wrapping can never disagree.
413
+ */
414
+ const composeWidth = useCallback(
415
+ () => (composing && settings.density === 'comfortable' ? Math.max(1, size.columns - 2) : size.columns),
416
+ [composing, settings.density, size.columns],
417
+ )
418
+
419
+ /** The window's draft capacity: at most half the pane, and never so many rows that the input
420
+ * area would push the rendered frame past the pane (an overflow scrolls, which would move the
421
+ * frame's top row away from the coordinate the cursor is placed in). */
422
+ const composeMaxRows = useCallback(() => {
423
+ if (size.rows <= 0) return Number.MAX_SAFE_INTEGER
424
+ const boxed = composing && settings.density === 'comfortable'
425
+ const avail = size.rows - 3 - 1 - (boxed ? 1 : 0) - (busy ? 1 : 0)
426
+ return Math.max(1, Math.min(Math.floor(size.rows / 2), avail))
427
+ }, [busy, composing, settings.density, size.rows])
428
+
429
+ const openCompose = useCallback(
430
+ (withMode: ComposeMode = 'message', initial?: string) => {
431
+ setReceipt(null)
432
+ setStatus(null)
433
+ setMode(withMode)
434
+ const seed =
435
+ initial !== undefined
436
+ ? initial
437
+ : withMode === 'message'
438
+ ? api.readDraft()
439
+ : withMode === 'filter'
440
+ ? settingsFilterRef.current
441
+ : ''
442
+ draftRef.current = seed
443
+ pasteOpenRef.current = false
444
+ setDraft(seed)
445
+ // The insertion point opens at the end of the restored draft (the cursor is not persisted).
446
+ cursorRef.current = cpLength(seed)
447
+ setCursor(cpLength(seed))
448
+ // The undo history and the ring start empty at the draft the compose opened on.
449
+ killRingRef.current = { entries: [], lastDirection: null }
450
+ undoRef.current = []
451
+ yankRef.current = null
452
+ lastActionRef.current = null
453
+ setComposing(true)
454
+ },
455
+ [api],
456
+ )
457
+
458
+ const closeCompose = useCallback(() => {
459
+ // Esc keeps the draft: the ref stays as typed and the file already holds it.
460
+ setComposing(false)
461
+ pasteOpenRef.current = false
462
+ // A cancelled setting edit writes nothing and leaves no audit line (the two-step rule).
463
+ settingRowRef.current = null
464
+ settingConfirmRef.current = null
465
+ setSettingConfirm(null)
466
+ }, [])
467
+
468
+ /**
469
+ * The path kind's existence mark for the value about to be written (M55): an advisory the
470
+ * confirmation repeats. The command has no existence check, so the console never turns this into
471
+ * a refusal — it does not invent a rule the writer would not make.
472
+ */
473
+ const pathMarkNote = useCallback(
474
+ (target: { kind?: string; choices?: SettingsKey['choices'] }, value: string): string => {
475
+ if (String(target.kind ?? '') !== 'path') return ''
476
+ const mark = api.pathMark(value, String(target.choices?.note ?? ''))
477
+ const word =
478
+ mark === 'exists'
479
+ ? stringsRef.current.settingsPathExists
480
+ : mark === 'not-exec'
481
+ ? stringsRef.current.settingsPathNotExec
482
+ : stringsRef.current.settingsPathMissing
483
+ return ` · ${word}`
484
+ },
485
+ [api],
486
+ )
487
+
488
+ // V15/F3: one draft = at most one message. The re-entry guard is a ref set *synchronously* at
489
+ // the top of the send, not the `busy` state: a double Enter lands inside the same React batch,
490
+ // before any state update could gate the second call. A failed send releases the guard so the
491
+ // human can retry (the draft is kept on error).
492
+ const sendingRef = useRef(false)
493
+ const submit = useCallback(async () => {
494
+ const text = draftRef.current
495
+ if (mode === 'filter') {
496
+ // The filter is one of the compose editor's modes (P22/B2): Enter applies it and closes the
497
+ // line, Esc clears it (handled with the compose cancel below).
498
+ settingsFilterRef.current = text
499
+ setSettingsFilter(text)
500
+ setSettingsFocus(0)
501
+ settingsFocusRef.current = 0
502
+ // D5: a new filter resets the window with the focus (the row set may be a fraction of the old).
503
+ setSettingsOffset(null)
504
+ settingsOffsetRef.current = null
505
+ closeCompose()
506
+ return
507
+ }
508
+ if (mode === 'setting') {
509
+ // The write is always the owning command's: the first Enter asks for a `--dry-run`
510
+ // validation, the second performs the write with the fingerprint pinned when the editor
511
+ // opened. The console never opens the contract itself.
512
+ const target = settingRowRef.current
513
+ if (!target) {
514
+ closeCompose()
515
+ return
516
+ }
517
+ if (sendingRef.current) return
518
+ sendingRef.current = true
519
+ setBusy(true)
520
+ try {
521
+ const conf = settingConfirmRef.current
522
+ const timing =
523
+ target.cls === 'restart' ? stringsRef.current.settingTimingRestart : stringsRef.current.settingTimingApply
524
+ const isSeat = Boolean(target.seat)
525
+ const seatModel = text.trim() === '' ? '-' : text.trim()
526
+ const call = (dryRun: boolean, allowDanger: boolean): Promise<{ code: number; line: string }> =>
527
+ isSeat
528
+ ? api.setSeatModel(target.seat as string, seatModel, { dryRun, fingerprint: target.fingerprint })
529
+ : api.setSetting(target.key, text, { dryRun, fingerprint: target.fingerprint, allowDanger })
530
+ if (!conf) {
531
+ const r = await call(true, false)
532
+ if (r.code === 0) {
533
+ settingConfirmRef.current = { key: target.key, next: text, danger: false }
534
+ setSettingConfirm(settingConfirmRef.current)
535
+ setReceipt(null)
536
+ setStatus(
537
+ isSeat
538
+ ? fill(stringsRef.current.settingSeatConfirm, {
539
+ seat: target.seat as string,
540
+ old: target.value || stringsRef.current.dash,
541
+ next: seatModel === '-' ? stringsRef.current.dash : seatModel,
542
+ })
543
+ : fill(stringsRef.current.settingConfirm, {
544
+ key: target.key,
545
+ old: target.value || stringsRef.current.dash,
546
+ next: text,
547
+ timing,
548
+ }) + pathMarkNote(target, text),
549
+ )
550
+ } else if (r.code === 7) {
551
+ settingConfirmRef.current = { key: target.key, next: text, danger: true }
552
+ setSettingConfirm(settingConfirmRef.current)
553
+ setReceipt(null)
554
+ setStatus(fill(stringsRef.current.settingDanger, { reason: r.line }))
555
+ } else if (r.code === 3) {
556
+ // The file changed under the editor: name it now, and let the second Enter perform the
557
+ // real write so the command audits the conflict (a --dry-run writes no audit line).
558
+ settingConfirmRef.current = { key: target.key, next: text, danger: false }
559
+ setSettingConfirm(settingConfirmRef.current)
560
+ setReceipt(null)
561
+ setStatus(stringsRef.current.settingConflict)
562
+ } else {
563
+ setReceipt(null)
564
+ setStatus(
565
+ fill(r.code === 5 ? stringsRef.current.settingRefused : stringsRef.current.settingInvalid, { line: r.line }),
566
+ )
567
+ }
568
+ return
569
+ }
570
+ const r = await call(false, conf.danger)
571
+ if (r.code === 0) {
572
+ setReceipt(null)
573
+ const fallback = dataRef.current.blocks?.settings?.models?.default ?? ''
574
+ setStatus(
575
+ isSeat
576
+ ? seatModel === '-'
577
+ ? fill(stringsRef.current.settingSeatRemoved, { seat: target.seat as string, value: fallback || stringsRef.current.dash })
578
+ : fill(stringsRef.current.settingSeatWritten, { seat: target.seat as string, value: seatModel })
579
+ : fill(stringsRef.current.settingWritten, { key: target.key, value: text, timing }),
580
+ )
581
+ settingRowRef.current = null
582
+ settingConfirmRef.current = null
583
+ setSettingConfirm(null)
584
+ closeCompose()
585
+ api.refreshSettingsSoon()
586
+ } else if (r.code === 3) {
587
+ // The other writer's bytes survived; reload so the view shows their value (the settle).
588
+ setReceipt(null)
589
+ setStatus(stringsRef.current.settingConflict)
590
+ settingConfirmRef.current = null
591
+ setSettingConfirm(null)
592
+ api.refreshSettingsSoon()
593
+ } else {
594
+ setReceipt(null)
595
+ setStatus(
596
+ fill(
597
+ r.code === 5
598
+ ? stringsRef.current.settingRefused
599
+ : r.code === 4
600
+ ? stringsRef.current.settingInvalid
601
+ : stringsRef.current.settingWriteError,
602
+ { line: r.line },
603
+ ),
604
+ )
605
+ }
606
+ } finally {
607
+ sendingRef.current = false
608
+ setBusy(false)
609
+ }
610
+ void text
611
+ return
612
+ }
613
+ if (mode === 'reason') {
614
+ if (!text.trim()) return
615
+ if (sendingRef.current) return
616
+ sendingRef.current = true
617
+ setBusy(true)
618
+ try {
619
+ const r = await api.setStandby(true, text)
620
+ setStatus(r.line)
621
+ setComposing(false)
622
+ updateDraft('', false)
623
+ } finally {
624
+ sendingRef.current = false
625
+ setBusy(false)
626
+ }
627
+ return
628
+ }
629
+ if (!text.trim()) return
630
+ if (sendingRef.current) return
631
+ sendingRef.current = true
632
+ setBusy(true)
633
+ try {
634
+ const r = await api.send(text)
635
+ setReceipt(r.state === 'error' ? r : { ...r, detail: '' })
636
+ setStatus(null)
637
+ if (r.state !== 'error') {
638
+ updateDraft('', false)
639
+ setPoint(0)
640
+ api.clearDraft()
641
+ }
642
+ setComposing(false)
643
+ } finally {
644
+ sendingRef.current = false
645
+ setBusy(false)
646
+ }
647
+ }, [api, mode, updateDraft, closeCompose, setSettingsFilter, pathMarkNote])
648
+
649
+ const runAction = useCallback(
650
+ async (kind: 'flush' | 'standby') => {
651
+ if (kind === 'standby') {
652
+ const on = Boolean(dataRef.current.panel?.standby?.on)
653
+ if (!on) {
654
+ openCompose('reason')
655
+ return
656
+ }
657
+ setBusy(true)
658
+ try {
659
+ const r = await api.setStandby(false, '')
660
+ setStatus(r.line)
661
+ setReceipt(null)
662
+ } finally {
663
+ setBusy(false)
664
+ }
665
+ return
666
+ }
667
+ setBusy(true)
668
+ try {
669
+ const r = await api.flushQueue()
670
+ setStatus(r.line)
671
+ setReceipt(null)
672
+ } finally {
673
+ setBusy(false)
674
+ }
675
+ },
676
+ [api, openCompose],
677
+ )
678
+
679
+ const collapse = useCallback(async () => {
680
+ setStatus(null)
681
+ const r = await api.collapse()
682
+ if (!r.ok) setStatus(r.line)
683
+ }, [api])
684
+
685
+ /**
686
+ * `C-v`: paste the clipboard (P20/B4). The probe runs only here — never on the render or refresh
687
+ * path — and one probe at a time; while it runs the frame keeps rendering and typing keeps landing
688
+ * in the draft. An image becomes its temporary file path, a non-image the clipboard's text, and a
689
+ * failed probe changes nothing (no error line, no file).
690
+ */
691
+ const pasteClipboard = useCallback(async () => {
692
+ if (busy || probingRef.current) return
693
+ probingRef.current = true
694
+ try {
695
+ const read = await api.pasteClipboard()
696
+ if (read.kind === 'none' || read.value === '') return
697
+ const text = draftRef.current
698
+ const point = cursorRef.current
699
+ pushUndo(undoRef.current, text, point)
700
+ killRingRef.current = resetKillDirection(killRingRef.current)
701
+ yankRef.current = null
702
+ lastActionRef.current = 'edit'
703
+ const flatten = (value: string): string => (mode === 'reason' ? value.replace(/\n/g, ' ') : value)
704
+ // The insertion point is read *after* the probe settles: a keystroke during the probe lands
705
+ // before the paste, exactly where the point then is.
706
+ updateCompose(insertAt(draftRef.current, cursorRef.current, flatten(read.value)), mode === 'message')
707
+ } finally {
708
+ probingRef.current = false
709
+ }
710
+ }, [api, busy, mode, updateCompose])
711
+
712
+ const relayEditor = useCallback(async () => {
713
+ // `C-o` hands the draft to `$EDITOR`. The editor relay writes `state/draft.md`; in reason mode
714
+ // that would clobber the message draft, and a long reason is not the flow the design asks for —
715
+ // `C-o` belongs to the letter.
716
+ if (busy || composing === false || mode !== 'message') return
717
+ // Ink's own input must be deactivated for the handoff: both Ink and `$EDITOR` read the same
718
+ // pty, and whoever reads a keystroke first consumes it (measured: `:wq` never reached vi
719
+ // while Ink's `useInput` stayed active). Do NOT flip `busy` here: a state change that alters
720
+ // the frame forces a repaint, and that repaint races the editor's first output bytes and
721
+ // erases them (the 2.3 "the editor got the terminal" assertion flipped with machine speed).
722
+ // `editorOpen` alone gates the input; the frame stays byte-identical, so Ink writes nothing.
723
+ setEditorOpen(true)
724
+ try {
725
+ const next = await api.editDraft(draftRef.current)
726
+ updateDraft(next, mode === 'message')
727
+ setPoint(cpLength(next))
728
+ // The editor may have replaced the whole draft: an undo that resurrected pre-editor text
729
+ // would be a lie, so the history (and the ring) restarts here (design §5).
730
+ undoRef.current = []
731
+ killRingRef.current = { entries: [], lastDirection: null }
732
+ yankRef.current = null
733
+ lastActionRef.current = null
734
+ } finally {
735
+ setEditorOpen(false)
736
+ }
737
+ }, [api, busy, composing, mode, updateDraft])
738
+
739
+ const cyclePref = useCallback(
740
+ (pref: PrefName) => {
741
+ const cur = settingsRef.current
742
+ const next: Settings = { ...cur }
743
+ switch (pref) {
744
+ case 'lang':
745
+ next.lang = cur.lang === 'zh' ? 'en' : 'zh'
746
+ break
747
+ case 'defaultPage':
748
+ // Four pages since P18/B2: the cycle covers 1–4 and wraps (the old three-page test let 4
749
+ // fall through to 5, which the next launch rejects as out of range — a silent reset).
750
+ next.defaultPage = cur.defaultPage === 4 ? 1 : ((cur.defaultPage + 1) as PageId)
751
+ goPage(next.defaultPage)
752
+ break
753
+ case 'activity':
754
+ next.activity = !cur.activity
755
+ if (!activityPinned) api.setActivity(next.activity)
756
+ break
757
+ case 'mouse':
758
+ next.mouse = !cur.mouse
759
+ break
760
+ case 'density':
761
+ next.density = cur.density === 'compact' ? 'comfortable' : 'compact'
762
+ break
763
+ }
764
+ saveSettings(next)
765
+ },
766
+ [activityPinned, api, goPage, saveSettings],
767
+ )
768
+
769
+ /** The board's rows as the last assembly saw them (the kanban moves over these). */
770
+ const boardRows = useCallback(() => dataRef.current.blocks?.board?.rows ?? [], [])
771
+
772
+ /**
773
+ * P123: the effective fold of one lane, exactly as the layout resolves it (explicit fold wins,
774
+ * then explicit show, then the empty default). The App needs it for the no-op card walk and for
775
+ * what a toggle writes; the layout is still the single place the frame is drawn from.
776
+ */
777
+ const laneFoldedNow = useCallback((lane: string, empty: boolean): boolean => {
778
+ const cur = settingsRef.current
779
+ if (cur.boardFold.includes(lane)) return true
780
+ if (cur.boardShow.includes(lane)) return false
781
+ return empty && cur.boardEmptyFold
782
+ }, [])
783
+
784
+ /**
785
+ * P123's `c` / header click: flip the lane's fold and write the explicit state in the same step
786
+ * (the requirement is "each toggle is written as it happens", so a quit cannot lose it). An
787
+ * explicit show survives emptiness and restarts; the default state is recomputed per frame.
788
+ */
789
+ const toggleLaneFold = useCallback(
790
+ (lane: string) => {
791
+ const cur = settingsRef.current
792
+ const rows = boardRows()
793
+ const empty = !rows.some((r) => r.state === lane)
794
+ const next: Settings = { ...cur }
795
+ if (laneFoldedNow(lane, empty)) {
796
+ next.boardFold = cur.boardFold.filter((l) => l !== lane)
797
+ next.boardShow = [...cur.boardShow.filter((l) => l !== lane), lane]
798
+ } else {
799
+ next.boardFold = [...cur.boardFold.filter((l) => l !== lane), lane]
800
+ next.boardShow = cur.boardShow.filter((l) => l !== lane)
801
+ }
802
+ saveSettings(next)
803
+ },
804
+ [boardRows, laneFoldedNow, saveSettings],
805
+ )
806
+
807
+ const moveFocus = useCallback(
808
+ (laneDelta: number, cardDelta: number) => {
809
+ const rows = boardRows()
810
+ const current = resolveFocus(rows, focusRef.current)
811
+ if (!current) return
812
+ if (laneDelta !== 0) {
813
+ // ←/→: the neighbouring lane's first card (empty lanes are stepped over). The target lane's
814
+ // window is pushed to show it, so an offset the wheel left behind cannot hide the focus.
815
+ const lanes = ['todo', 'wip', 'review', 'done', 'blocked', 'dropped']
816
+ let i = lanes.indexOf(current.lane)
817
+ for (let step = 0; step < lanes.length; step++) {
818
+ i = (i + laneDelta + lanes.length) % lanes.length
819
+ const card = rows.find((r) => r.state === lanes[i])
820
+ if (card) {
821
+ setFocus(focusRefOf(rows, card))
822
+ setLaneOffset((prev) => ({ ...prev, [lanes[i]]: 0 }))
823
+ return
824
+ }
825
+ }
826
+ return
827
+ }
828
+ // ↑/↓: the next/previous **row** of the current lane. M48: a lookup by id stopped dead on the
829
+ // first of two rows sharing an id, so the second was unreachable — the walk is positional now
830
+ // (the resolved row object), and every drawn card is exactly one step.
831
+ const row = focusRow(rows, current)
832
+ if (!row) return
833
+ // P123: while the focused lane is folded its one line draws at the top of its column, so a
834
+ // card move would be an invisible state change (the cursor would leave the only drawn row).
835
+ // The keys no-op; `c` first, or `←`/`→` to another lane, brings the cards back.
836
+ if (laneFoldedNow(current.lane, !rows.some((r) => r.state === current.lane))) return
837
+ const inLane = rows.filter((r) => r.state === current.lane)
838
+ const idx = inLane.indexOf(row)
839
+ const next = idx < 0 ? undefined : inLane[idx + cardDelta]
840
+ if (!next || next === row) return
841
+ setFocus(focusRefOf(rows, next))
842
+ // Scrolling the lane's window is the layout's own follow-the-focus rule; the wheel keeps its
843
+ // own offset, so push that offset along when the focus walks past the window's edge.
844
+ const win = lanesRef.current.find((w) => w.lane === current.lane)
845
+ if (win && win.visible > 0) {
846
+ const target = inLane.indexOf(next)
847
+ const start = Math.max(
848
+ 0,
849
+ Math.min(
850
+ Math.max(0, win.count - win.visible),
851
+ win.offset +
852
+ (target < win.offset ? target - win.offset : target >= win.offset + win.visible ? target - win.offset - win.visible + 1 : 0),
853
+ ),
854
+ )
855
+ setLaneOffset((prev) => ({ ...prev, [current.lane]: start }))
856
+ }
857
+ },
858
+ [boardRows, laneFoldedNow],
859
+ )
860
+
861
+ /**
862
+ * The work page's `↑`/`↓` (P20/B5): walk the rows in the order the block drew them, so the keys
863
+ * touch exactly what is on screen. The first press with no usable focus lands on the first drawn
864
+ * row, and a focus whose entry left the board re-anchors there too. M48: the drawn order carries
865
+ * the duplicate ordinal, so two rows sharing an id are two steps — not one, and never a freeze.
866
+ */
867
+ const moveBoardFocus = useCallback((delta: number) => {
868
+ const order = boardOrderRef.current
869
+ if (!order.length) return
870
+ const cur = focusRef.current
871
+ let idx = -1
872
+ if (cur) {
873
+ idx = order.findIndex((r) => r.id === cur.id && (r.nth ?? 0) === (cur.nth ?? 0))
874
+ if (idx < 0) idx = order.findIndex((r) => r.id === cur.id)
875
+ }
876
+ if (idx < 0) {
877
+ setFocus(order[0])
878
+ return
879
+ }
880
+ const next = Math.max(0, Math.min(order.length - 1, idx + delta))
881
+ if (next !== idx) setFocus(order[next])
882
+ }, [])
883
+
884
+ const scrollLane = useCallback((lane: string, delta: number) => {
885
+ const win = lanesRef.current.find((w) => w.lane === lane)
886
+ const max = win ? Math.max(0, win.count - win.visible) : Number.MAX_SAFE_INTEGER
887
+ setLaneOffset((prev) => ({ ...prev, [lane]: Math.max(0, Math.min(max, (prev[lane] ?? (win?.offset ?? 0)) + delta)) }))
888
+ }, [])
889
+
890
+ /** Open an entry's detail view: the first tab, from the top (the board page's Enter / a click). */
891
+ const openDetail = useCallback((id: string) => {
892
+ setDetailIndex(0)
893
+ setDetailScroll(0)
894
+ setDetailId(id)
895
+ }, [])
896
+
897
+ /** Enter on the work page: open the focused row (or the first drawn one, when it left the board). */
898
+ const openWorkFocused = useCallback(() => {
899
+ const order = boardOrderRef.current
900
+ if (!order.length) return
901
+ const cur = focusRef.current
902
+ const hit = cur
903
+ ? order.find((r) => r.id === cur.id && (r.nth ?? 0) === (cur.nth ?? 0)) ?? order.find((r) => r.id === cur.id)
904
+ : undefined
905
+ openDetail((hit ?? order[0]).id)
906
+ }, [openDetail])
907
+
908
+ // ---- project settings (P22/B2): the view's focus walk, its origin and its row opening.
909
+
910
+ /** The view's focusable rows as the last assembly saw them (the walk must match the screen). */
911
+ const settingsRowsNow = useCallback((): ({ kind: 'key'; key: import('./types.js').SettingsKey } | { kind: 'seat'; seat: import('./types.js').SettingsSeat })[] => {
912
+ const rows = settingsViewRows(dataRef.current.blocks?.settings, settingsFilterRef.current, stringsRef.current)
913
+ return rows.filter((r): r is { kind: 'key'; key: import('./types.js').SettingsKey } | { kind: 'seat'; seat: import('./types.js').SettingsSeat } => r.kind === 'key' || r.kind === 'seat')
914
+ }, [])
915
+
916
+ const moveSettingsFocus = useCallback(
917
+ (delta: number) => {
918
+ const rows = settingsRowsNow()
919
+ if (!rows.length) return
920
+ const next = Math.max(0, Math.min(rows.length - 1, settingsFocusRef.current + delta))
921
+ settingsFocusRef.current = next
922
+ setSettingsFocus(next)
923
+ // P30/D5: with a wheel offset in force the window is pushed just enough to keep the focused
924
+ // row inside it (the board page's `moveFocus` rule) — so the row `enter` would open can never
925
+ // be one a wheel scrolled out of the window. With no offset set the window still follows the
926
+ // focus (the layout's own default).
927
+ const win = settingsWindowRef.current
928
+ const current = settingsOffsetRef.current
929
+ if (win && current !== null && win.visible > 0) {
930
+ const start = Math.max(
931
+ 0,
932
+ Math.min(
933
+ Math.max(0, win.count - win.visible),
934
+ current +
935
+ (next < current ? next - current : next >= current + win.visible ? next - current - win.visible + 1 : 0),
936
+ ),
937
+ )
938
+ setSettingsOffset(start)
939
+ }
940
+ },
941
+ [settingsRowsNow],
942
+ )
943
+
944
+ /**
945
+ * The wheel over the project-settings view (P30/D5): one row per notch through the view's own
946
+ * offset, the focus untouched. The event is **consumed** — the page the view was opened from
947
+ * never moves (today every other wheel fell through to `updateScroll` and scrolled a hidden
948
+ * page while the view, being focus-derived, did not move at all).
949
+ */
950
+ const scrollSettings = useCallback(
951
+ (delta: number) => {
952
+ const rows = settingsRowsNow()
953
+ if (!rows.length) return
954
+ const win = settingsWindowRef.current
955
+ const visible = Math.max(1, win?.visible ?? rows.length)
956
+ const max = Math.max(0, rows.length - visible)
957
+ const current = settingsOffsetRef.current ?? win?.offset ?? 0
958
+ const next = Math.max(0, Math.min(max, current + delta))
959
+ settingsOffsetRef.current = next
960
+ setSettingsOffset(next)
961
+ },
962
+ [settingsRowsNow],
963
+ )
964
+
965
+ // ---- the choice picker (M55): one entry list per key, built from the command's own read.
966
+
967
+ /**
968
+ * The entries R3 fixes the order of: a keep-unset lead for a key the file does not carry, the
969
+ * current value (only when the file carries the key), the schema default (only when non-empty),
970
+ * the command's `choices.values` in their order (deduped), then the kind's own actions. Closed
971
+ * kinds (`bool`, `enum`) get no free-text entry; the open kinds end with one; `path` offers a
972
+ * clear entry exactly when the command accepts the empty value. No option table lives here —
973
+ * pulling a value out of the schema would be the second source the requirement forbids.
974
+ */
975
+ const buildChoiceEntries = useCallback(
976
+ (key: SettingsKey): SettingsChoiceEntry[] => {
977
+ const ch = key.choices
978
+ if (!ch) return []
979
+ const kind = String(key.kind ?? '')
980
+ const rule = String(ch.note ?? '')
981
+ const values = (Array.isArray(ch.values) ? ch.values : []).map((v) => String(v))
982
+ const out: SettingsChoiceEntry[] = []
983
+ const seen = new Set<string>()
984
+ const pushValue = (value: string, entryKind: SettingsChoiceEntry['kind']): void => {
985
+ if (value === '' || seen.has(value)) return
986
+ seen.add(value)
987
+ out.push(kind === 'path' ? { value, kind: entryKind, mark: api.pathMark(value, rule) } : { value, kind: entryKind })
988
+ }
989
+ const base = key.set ? key.value : ''
990
+ if (!key.set) out.push({ value: '', kind: 'keep-unset' })
991
+ pushValue(key.value, 'current')
992
+ pushValue(key.default, 'default')
993
+ for (const v of values) pushValue(v, 'value')
994
+ if (kind === 'bool' || kind === 'enum' || kind === 'pairlist') return out
995
+ if (kind === 'path') {
996
+ if (ch.empty) out.push({ value: '', kind: 'clear' })
997
+ out.push({ value: '', kind: 'free', seed: base })
998
+ return out
999
+ }
1000
+ if (kind === 'winlist' || kind === 'pattern') {
1001
+ // The token vocabulary: choosing a model seeds the compose editor with `<model>=` at the
1002
+ // insertion point (the current value's end); the number to the right stays free text.
1003
+ const seeded = out.map((e) => (e.kind === 'value' ? { ...e, seed: `${base}${base !== '' && !/\s$/.test(base) ? ' ' : ''}${e.value}=` } : e))
1004
+ return [...seeded, { value: '', kind: 'free', seed: base }]
1005
+ }
1006
+ out.push({ value: '', kind: 'free', seed: base })
1007
+ return out
1008
+ },
1009
+ [api],
1010
+ )
1011
+
1012
+ /**
1013
+ * The write target a picker accept acts on (M65/D11): built from the `settings` block the view
1014
+ * already read, never from a fresh `config list`/`__panel-data`. The fingerprint is that block's,
1015
+ * so a contract changed under the picker is the owning command's conflict verdict — CAS is the
1016
+ * freshness check, not a re-read between every keystroke and its frame.
1017
+ */
1018
+ const choiceTarget = useCallback(
1019
+ (picker: SettingsChoicePicker): NonNullable<typeof settingRowRef.current> => {
1020
+ const rows = settingsRowsNow()
1021
+ // By key name, not by index: the picker's row index is a focus index and the row list can be
1022
+ // replaced by a settle re-read while the picker is open.
1023
+ const rowNow = rows.find((r) => r.kind === 'key' && r.key.name === picker.key) ?? rows[picker.row]
1024
+ const keyNow = rowNow && rowNow.kind === 'key' ? rowNow.key : null
1025
+ return {
1026
+ row: picker.row,
1027
+ key: picker.key,
1028
+ value: keyNow?.value ?? '',
1029
+ cls: keyNow?.class ?? 'apply',
1030
+ fingerprint: dataRef.current.blocks?.settings?.fingerprint ?? '',
1031
+ kind: picker.kind,
1032
+ choices: keyNow?.choices,
1033
+ }
1034
+ },
1035
+ [settingsRowsNow],
1036
+ )
1037
+
1038
+ /**
1039
+ * The direct write (M65/D10): accepting a value entry asks the owning command for the validation
1040
+ * it already uses (`--dry-run`) and, when it accepts, performs the write on the very same accept
1041
+ * (`--yes --fingerprint` of the read the editor was built from) — no confirmation frame and no
1042
+ * compose editor on this path. A value the command reports dangerous (exit 7) is not written by
1043
+ * that first accept: the warning rides the status line and one more accept of the same value
1044
+ * writes it with the command's allowance. The receipt is the existing exit-code mapping; a
1045
+ * conflict names the other writer, writes nothing and refreshes the block in the background.
1046
+ */
1047
+ const writeChoiceValue = useCallback(
1048
+ async (target: NonNullable<typeof settingRowRef.current>, value: string): Promise<void> => {
1049
+ if (sendingRef.current) return
1050
+ sendingRef.current = true
1051
+ setBusy(true)
1052
+ const timing =
1053
+ target.cls === 'restart' ? stringsRef.current.settingTimingRestart : stringsRef.current.settingTimingApply
1054
+ try {
1055
+ const danger = choiceDangerRef.current
1056
+ const dangerAccept = Boolean(danger && danger.key === target.key && danger.value === value)
1057
+ if (!dangerAccept) {
1058
+ const dry = await api.setSetting(target.key, value, { dryRun: true, fingerprint: target.fingerprint })
1059
+ if (dry.code === 7) {
1060
+ choiceDangerRef.current = { key: target.key, value }
1061
+ setReceipt(null)
1062
+ setStatus(fill(stringsRef.current.settingDanger, { reason: dry.line }))
1063
+ return
1064
+ }
1065
+ // 3 = the file changed under the picker: the real write below is what the command audits.
1066
+ if (dry.code !== 0 && dry.code !== 3) {
1067
+ choiceDangerRef.current = null
1068
+ setReceipt(null)
1069
+ setStatus(
1070
+ fill(
1071
+ dry.code === 5
1072
+ ? stringsRef.current.settingRefused
1073
+ : dry.code === 4
1074
+ ? stringsRef.current.settingInvalid
1075
+ : stringsRef.current.settingWriteError,
1076
+ { line: dry.line },
1077
+ ),
1078
+ )
1079
+ return
1080
+ }
1081
+ }
1082
+ const r = await api.setSetting(target.key, value, {
1083
+ dryRun: false,
1084
+ fingerprint: target.fingerprint,
1085
+ allowDanger: dangerAccept,
1086
+ })
1087
+ choiceDangerRef.current = null
1088
+ if (r.code === 0) {
1089
+ setReceipt(null)
1090
+ setStatus(fill(stringsRef.current.settingWritten, { key: target.key, value, timing }))
1091
+ settingRowRef.current = null
1092
+ setChoicePicker(null)
1093
+ choicePickerRef.current = null
1094
+ api.refreshSettingsSoon()
1095
+ } else if (r.code === 3) {
1096
+ // The other writer's bytes survived; reload so the view shows their value (the settle).
1097
+ setReceipt(null)
1098
+ setStatus(stringsRef.current.settingConflict)
1099
+ setChoicePicker(null)
1100
+ choicePickerRef.current = null
1101
+ api.refreshSettingsSoon()
1102
+ } else {
1103
+ setReceipt(null)
1104
+ setStatus(
1105
+ fill(
1106
+ r.code === 5
1107
+ ? stringsRef.current.settingRefused
1108
+ : r.code === 4
1109
+ ? stringsRef.current.settingInvalid
1110
+ : stringsRef.current.settingWriteError,
1111
+ { line: r.line },
1112
+ ),
1113
+ )
1114
+ }
1115
+ } finally {
1116
+ sendingRef.current = false
1117
+ setBusy(false)
1118
+ }
1119
+ },
1120
+ [api],
1121
+ )
1122
+
1123
+ /**
1124
+ * The pairlist row's editor is the seats block (the requirement that owns per-seat editing):
1125
+ * `enter` moves the focus there, no compose editor and no option list opens. A filter that hides
1126
+ * the seats is dropped, because otherwise "focus the seats block" would name a row that is not
1127
+ * on screen.
1128
+ */
1129
+ const routePairlist = useCallback(() => {
1130
+ const rows = settingsRowsNow()
1131
+ let seat = rows.findIndex((r) => r.kind === 'seat')
1132
+ if (seat < 0) {
1133
+ settingsFilterRef.current = ''
1134
+ setSettingsFilter('')
1135
+ // The focus index counts focusable rows, not the group headings `settingsViewRows` also
1136
+ // returns — counting those would land the cursor on the wrong row (or past the end).
1137
+ const all = settingsViewRows(dataRef.current.blocks?.settings, '', stringsRef.current).filter(
1138
+ (r) => r.kind === 'key' || r.kind === 'seat',
1139
+ )
1140
+ seat = all.findIndex((r) => r.kind === 'seat')
1141
+ }
1142
+ setChoicePicker(null)
1143
+ choicePickerRef.current = null
1144
+ if (seat >= 0) setSettingsFocus(seat)
1145
+ setReceipt(null)
1146
+ setStatus(stringsRef.current.settingsChoicePairlist)
1147
+ }, [settingsRowsNow])
1148
+
1149
+ /**
1150
+ * One picker choice (M65/D10): a value entry validates and writes on this accept; a seeded entry
1151
+ * (`winlist`/`pattern`'s `<model>=`) and the free-text entry open the compose editor, which keeps
1152
+ * its validation and confirmation; keep-unset cancels. A click on an entry that does not carry
1153
+ * the cursor only moves it — a click on the cursor's entry accepts it like `enter` does.
1154
+ */
1155
+ const chooseChoiceOption = useCallback(
1156
+ (index: number) => {
1157
+ const picker = choicePickerRef.current
1158
+ if (!picker) return
1159
+ if (index >= 0 && index !== picker.index) {
1160
+ const next = { ...picker, index: Math.max(0, Math.min(picker.entries.length - 1, index)) }
1161
+ choiceDangerRef.current = null
1162
+ choicePickerRef.current = next
1163
+ setChoicePicker(next)
1164
+ return
1165
+ }
1166
+ const entry = picker.entries[index < 0 ? picker.index : index]
1167
+ if (!entry) return
1168
+ // keep-unset cancels: no compose editor, no write, no audit line, no temporary file. The
1169
+ // writer has no removal operation, so the view never claims it deleted the line.
1170
+ if (entry.kind === 'keep-unset') {
1171
+ choiceDangerRef.current = null
1172
+ setChoicePicker(null)
1173
+ choicePickerRef.current = null
1174
+ return
1175
+ }
1176
+ const target = choiceTarget(picker)
1177
+ settingRowRef.current = target
1178
+ if (entry.kind === 'free' || entry.seed !== undefined) {
1179
+ // The only typed path: the editor's validation and confirmation are unchanged (D10).
1180
+ settingConfirmRef.current = null
1181
+ setSettingConfirm(null)
1182
+ choiceDangerRef.current = null
1183
+ setChoicePicker(null)
1184
+ choicePickerRef.current = null
1185
+ openCompose('setting', entry.seed !== undefined ? entry.seed : entry.value)
1186
+ return
1187
+ }
1188
+ void writeChoiceValue(target, entry.value)
1189
+ },
1190
+ [choiceTarget, openCompose, writeChoiceValue],
1191
+ )
1192
+
1193
+ const moveChoicePicker = useCallback((delta: number) => {
1194
+ const picker = choicePickerRef.current
1195
+ if (!picker) return
1196
+ choiceDangerRef.current = null
1197
+ const next = { ...picker, index: Math.max(0, Math.min(picker.entries.length - 1, picker.index + delta)) }
1198
+ choicePickerRef.current = next
1199
+ setChoicePicker(next)
1200
+ }, [])
1201
+
1202
+ const closeChoicePicker = useCallback(() => {
1203
+ choiceDangerRef.current = null
1204
+ setChoicePicker(null)
1205
+ choicePickerRef.current = null
1206
+ }, [])
1207
+
1208
+ const openSettingsView = useCallback(
1209
+ (origin: number) => {
1210
+ setSettingsOrigin(origin)
1211
+ setOverlayIndex(origin)
1212
+ overlayIndexRef.current = origin
1213
+ setSettingsView(true)
1214
+ settingsViewRef.current = true
1215
+ setSettingsFocus(0)
1216
+ settingsFocusRef.current = 0
1217
+ setSettingsFilter('')
1218
+ settingsFilterRef.current = ''
1219
+ // D5: the view opens at the top (no wheel offset in force).
1220
+ setSettingsOffset(null)
1221
+ settingsOffsetRef.current = null
1222
+ api.setSettingsOpen(true)
1223
+ api.refreshNow()
1224
+ },
1225
+ [api],
1226
+ )
1227
+
1228
+ const closeSettingsView = useCallback(() => {
1229
+ setSettingsView(false)
1230
+ settingsViewRef.current = false
1231
+ // D5: the wheel's offset does not survive the view (reopening starts at the top).
1232
+ setSettingsOffset(null)
1233
+ settingsOffsetRef.current = null
1234
+ settingsWindowRef.current = null
1235
+ setSeatPicker(null)
1236
+ seatPickerRef.current = null
1237
+ setChoicePicker(null)
1238
+ choicePickerRef.current = null
1239
+ api.setSettingsOpen(false)
1240
+ // Back to the overlay row it was opened from (the design's origin rule).
1241
+ setOverlay(true)
1242
+ setOverlayIndex(settingsOrigin)
1243
+ overlayIndexRef.current = settingsOrigin
1244
+ }, [api, settingsOrigin])
1245
+
1246
+ /**
1247
+ * Enter on a view row: a `refuse` row opens no editor and surfaces the owning command's route;
1248
+ * an editable row opens the value editor (the compose line's `setting` mode, B3).
1249
+ */
1250
+ const openSettingsRow = useCallback(
1251
+ (index: number) => {
1252
+ const rows = settingsRowsNow()
1253
+ // `-1` = the focused row: resolve it once here, so the picker/editor carries a real index
1254
+ // (the focus walk passes -1 from the Enter handler).
1255
+ const at = index < 0 ? settingsFocusRef.current : index
1256
+ const row = rows[at]
1257
+ if (!row) return
1258
+ if (row.kind === 'seat') {
1259
+ // The picker: the command's known models, then the removal and the free-text line. The
1260
+ // editor opens on the chosen option so the two-step confirmation has a surface.
1261
+ const models = [...(dataRef.current.blocks?.settings?.models?.known ?? [])]
1262
+ setSeatPicker({ agent: row.seat.agent, row: at, models, index: 0 })
1263
+ seatPickerRef.current = { agent: row.seat.agent, row: at, models, index: 0 }
1264
+ setReceipt(null)
1265
+ setStatus(null)
1266
+ return
1267
+ }
1268
+ const key = row.key
1269
+ if (key.class === 'refuse') {
1270
+ setReceipt(null)
1271
+ setStatus(`${key.name} · ${key.route || key.warning || stringsRef.current.settingsRefusedRoute}`)
1272
+ return
1273
+ }
1274
+ // M65/D11: the editor opens on the `settings` block already on screen — no `config list` or
1275
+ // `__panel-data` stands between the keystroke and the frame that answers it. The fingerprint
1276
+ // is that block's, so a contract changed underneath is the owning command's conflict verdict
1277
+ // (CAS), not a reason to re-read before every action.
1278
+ if (hasChoiceEditor(key)) {
1279
+ if (String(key.kind ?? '') === 'pairlist') {
1280
+ routePairlist()
1281
+ return
1282
+ }
1283
+ const entries = buildChoiceEntries(key)
1284
+ if (entries.length) {
1285
+ const kind = String(key.kind ?? '')
1286
+ const picker: SettingsChoicePicker = {
1287
+ row: at,
1288
+ key: key.name,
1289
+ kind,
1290
+ entries,
1291
+ index: 0,
1292
+ interval: NUMERIC_KINDS.has(kind) ? { min: String(key.choices?.min ?? ''), max: String(key.choices?.max ?? '') } : null,
1293
+ }
1294
+ choiceDangerRef.current = null
1295
+ setChoicePicker(picker)
1296
+ choicePickerRef.current = picker
1297
+ setReceipt(null)
1298
+ setStatus(null)
1299
+ return
1300
+ }
1301
+ }
1302
+ settingRowRef.current = {
1303
+ row: index,
1304
+ key: key.name,
1305
+ value: key.value,
1306
+ cls: key.class,
1307
+ fingerprint: dataRef.current.blocks?.settings?.fingerprint ?? '',
1308
+ kind: String(key.kind ?? ''),
1309
+ choices: key.choices,
1310
+ }
1311
+ settingConfirmRef.current = null
1312
+ setSettingConfirm(null)
1313
+ openCompose('setting', key.set || key.value !== '' ? key.value : key.default)
1314
+ if (key.choices && !hasChoiceEditor(key)) {
1315
+ // The visible fallback (R3): the kind defines no choice set and the command still validates
1316
+ // the write. The line rides the editor's own hint row, so it stays on screen while typing.
1317
+ setStatus(fill(stringsRef.current.settingsChoiceNoChoice, { kind: String(key.kind ?? '') }))
1318
+ }
1319
+ },
1320
+ [buildChoiceEntries, openCompose, routePairlist, settingsRowsNow],
1321
+ )
1322
+
1323
+ /**
1324
+ * One picker choice: a model opens the editor holding it, `-` opens it holding the removal,
1325
+ * the free-text row opens it empty. The editor's two Enter presses are the confirmation.
1326
+ */
1327
+ /** Resolve a picker index (or -1 = the selected one) into the picker + its option. */
1328
+ const pickerIndex = useCallback(
1329
+ (index: number): { picker: { agent: string; row: number; models: string[]; index: number }; option: string } | null => {
1330
+ const p = seatPickerRef.current
1331
+ if (!p) return null
1332
+ const options = [...p.models, '-', '']
1333
+ const i = index < 0 ? p.index : index
1334
+ if (i < 0 || i >= options.length) return null
1335
+ return { picker: p, option: options[i] }
1336
+ },
1337
+ [],
1338
+ )
1339
+
1340
+ const chooseSeatOption = useCallback(
1341
+ (index: number) => {
1342
+ const picker = pickerIndex(index)
1343
+ if (!picker) return
1344
+ const { picker: p, option } = picker
1345
+ const seat = p.agent
1346
+ // M65/D11: the editor opens from the block already on screen (no read on the interaction
1347
+ // path); its fingerprint is that block's, so CAS catches a contract changed underneath.
1348
+ const block = dataRef.current.blocks?.settings
1349
+ const seatRow = (block?.models?.seats ?? []).find((x) => x.agent === seat)
1350
+ const initial = option === '' ? '' : option
1351
+ settingRowRef.current = {
1352
+ row: p.row,
1353
+ key: seat,
1354
+ value: seatRow?.model ?? '',
1355
+ cls: 'restart',
1356
+ fingerprint: block?.fingerprint ?? '',
1357
+ seat,
1358
+ }
1359
+ settingConfirmRef.current = null
1360
+ setSettingConfirm(null)
1361
+ setSeatPicker(null)
1362
+ seatPickerRef.current = null
1363
+ openCompose('setting', initial)
1364
+ },
1365
+ [openCompose, pickerIndex],
1366
+ )
1367
+
1368
+ const moveSeatPicker = useCallback((delta: number) => {
1369
+ const p = seatPickerRef.current
1370
+ if (!p) return
1371
+ const count = p.models.length + 2
1372
+ const next = { ...p, index: Math.max(0, Math.min(count - 1, p.index + delta)) }
1373
+ seatPickerRef.current = next
1374
+ setSeatPicker(next)
1375
+ }, [])
1376
+
1377
+ /** The detail view's file tabs: `←`/`→` clamp at the ends (no wrap — the row shows the order). */
1378
+ const moveDetailTab = useCallback((delta: number) => {
1379
+ const files = dataRef.current.blocks?.detail?.files ?? []
1380
+ if (!files.length) return
1381
+ setDetailIndex((i) => Math.max(0, Math.min(files.length - 1, i + delta)))
1382
+ setDetailScroll(0)
1383
+ }, [])
1384
+
1385
+ /** The detail document's scroll: clamped against the window the last frame reported. */
1386
+ const scrollDetail = useCallback((delta: number) => {
1387
+ const win = detailRef.current
1388
+ const max = win ? Math.max(0, win.total - win.visible) : 0
1389
+ setDetailScroll((v) => Math.max(0, Math.min(max, v + delta)))
1390
+ }, [])
1391
+
1392
+ /**
1393
+ * The detail block's one data contract (design §8): it is requested only while the view is open,
1394
+ * and only for the tab in view. Opening forces the first build; a tab switch forces the newly
1395
+ * requested file (`--file`); closing clears the request, which drops `detail` from the wanted set
1396
+ * so a parked page 4 spawns no reader at all. The call is idempotent — `setDetail` records an
1397
+ * option whose content the cached block already serves without rebuilding it.
1398
+ */
1399
+ const detailBlockData = data.blocks?.detail
1400
+ useEffect(() => {
1401
+ if (!detailId) {
1402
+ api.setDetail(null)
1403
+ return
1404
+ }
1405
+ const files = detailBlockData?.files ?? []
1406
+ api.setDetail(detailId, files[detailIndexRef.current]?.path ?? null)
1407
+ }, [api, detailId, detailIndex, detailBlockData])
1408
+
1409
+ const dispatch = useCallback(
1410
+ (action: Action) => {
1411
+ switch (action.kind) {
1412
+ case 'compose':
1413
+ openCompose('message')
1414
+ return
1415
+ case 'flush':
1416
+ void runAction('flush')
1417
+ return
1418
+ case 'standby':
1419
+ void runAction('standby')
1420
+ return
1421
+ case 'settings':
1422
+ setOverlay(true)
1423
+ setOverlayIndex(0)
1424
+ return
1425
+ case 'page':
1426
+ goPage(action.page)
1427
+ return
1428
+ case 'page-cycle':
1429
+ goPage(pageRef.current === 3 ? 1 : ((pageRef.current + 1) as PageId))
1430
+ return
1431
+ case 'scroll':
1432
+ updateScroll((v) => v + action.delta)
1433
+ return
1434
+ case 'quit':
1435
+ void collapse()
1436
+ return
1437
+ case 'close-overlay':
1438
+ setOverlay(false)
1439
+ return
1440
+ case 'toggle':
1441
+ cyclePref(action.pref as PrefName)
1442
+ return
1443
+ case 'view-entry':
1444
+ setViewEntry(action.index)
1445
+ return
1446
+ case 'queue-list':
1447
+ setViewEntry(null)
1448
+ return
1449
+ case 'focus':
1450
+ setFocus({ lane: action.lane, id: action.id, nth: action.nth ?? 0 })
1451
+ return
1452
+ case 'open-focused': {
1453
+ // One action kind, two pages: the kanban resolves its lane/card focus, the work page the
1454
+ // drawn row order (P20/B5).
1455
+ if (pageRef.current === 2) {
1456
+ openWorkFocused()
1457
+ return
1458
+ }
1459
+ const current = resolveFocus(boardRows(), focusRef.current)
1460
+ if (current) openDetail(current.id)
1461
+ return
1462
+ }
1463
+ case 'lane-move':
1464
+ moveFocus(action.delta, 0)
1465
+ return
1466
+ case 'card-move':
1467
+ if (pageRef.current === 2) moveBoardFocus(action.delta)
1468
+ else moveFocus(0, action.delta)
1469
+ return
1470
+ case 'lane-scroll':
1471
+ scrollLane(action.lane, action.delta)
1472
+ return
1473
+ case 'lane-fold': {
1474
+ // P123: a click on a lane header/folded line toggles that lane; the chip names the
1475
+ // focused lane (empty when the board has no cards — nothing to fold, nothing to write).
1476
+ if (action.lane) toggleLaneFold(action.lane)
1477
+ return
1478
+ }
1479
+ case 'detail-tab':
1480
+ setDetailIndex(action.index)
1481
+ setDetailScroll(0)
1482
+ return
1483
+ case 'detail-tab-move':
1484
+ moveDetailTab(action.delta)
1485
+ return
1486
+ case 'detail-scroll':
1487
+ scrollDetail(action.delta)
1488
+ return
1489
+ case 'detail-close':
1490
+ setDetailId(null)
1491
+ return
1492
+ case 'settings-open-view':
1493
+ openSettingsView(overlayIndexRef.current)
1494
+ return
1495
+ case 'settings-close':
1496
+ closeSettingsView()
1497
+ return
1498
+ case 'settings-focus':
1499
+ setSettingsFocus(action.index)
1500
+ return
1501
+ case 'settings-open':
1502
+ openSettingsRow(action.index)
1503
+ return
1504
+ case 'settings-filter':
1505
+ openCompose('filter')
1506
+ return
1507
+ case 'settings-scroll':
1508
+ moveSettingsFocus(action.delta)
1509
+ return
1510
+ case 'choice-pick':
1511
+ chooseChoiceOption(action.index)
1512
+ return
1513
+ case 'choice-move':
1514
+ moveChoicePicker(action.delta)
1515
+ return
1516
+ case 'choice-close':
1517
+ closeChoicePicker()
1518
+ return
1519
+ case 'seat-pick':
1520
+ if (action.index < 0) chooseSeatOption(-1)
1521
+ else chooseSeatOption(action.index)
1522
+ return
1523
+ case 'seat-move':
1524
+ moveSeatPicker(action.delta)
1525
+ return
1526
+ }
1527
+ },
1528
+ [boardRows, chooseChoiceOption, closeChoicePicker, closeSettingsView, collapse, cyclePref, goPage, moveBoardFocus, moveChoicePicker, moveDetailTab, moveFocus, moveSeatPicker, moveSettingsFocus, openCompose, openDetail, openSettingsRow, openSettingsView, openWorkFocused, runAction, scrollDetail, scrollLane, scrollSettings, toggleLaneFold, updateScroll],
1529
+ )
1530
+
1531
+ const effectiveActivity = activityPinned ? data.activity : settings.activity
1532
+
1533
+ const rowCacheRef = useRef<{ key: string; row: Segment[] }[]>([])
1534
+
1535
+ const lines = useMemo(() => {
1536
+ const bottom: string[] = []
1537
+ if (!composing) {
1538
+ const notice = receipt ? receiptLine(receipt, strings) : status
1539
+ if (notice) bottom.push(notice)
1540
+ }
1541
+ const boxed = composing && settings.density === 'comfortable'
1542
+ const inputWidth = boxed ? Math.max(1, size.columns - 2) : size.columns
1543
+ // One windowed view for the whole compose surface: the drawn rows, the point's drawn position
1544
+ // and the hidden-rows count all come from the same row map (P20/B1).
1545
+ const inputView: ComposeView | null = composing
1546
+ ? cursorView(mode, draft, cursor, inputWidth, composeMaxRows(), strings.composeHiddenAbove)
1547
+ : null
1548
+ const rawInput = inputView?.lines ?? []
1549
+ const trayTitle =
1550
+ mode === 'message'
1551
+ ? strings.composeTitle
1552
+ : mode === 'reason'
1553
+ ? strings.composeStandbyTitle
1554
+ : mode === 'filter'
1555
+ ? strings.settingFilterTitle
1556
+ : settingRowRef.current?.key ?? strings.settingsViewTitle
1557
+ const input = boxed
1558
+ ? [composeTrayTop(trayTitle, size.columns), ...rawInput.map((line) => `${TRAY_V} ${line}`)]
1559
+ : rawInput
1560
+ const hint = composing
1561
+ ? [
1562
+ // The setting/filter editor's own receipt (the confirmation line, the danger warning, the
1563
+ // command's refusal) rides the hint row *above* the input so the input line stays last
1564
+ // (the IME cursor anchor rule) while the editor stays open with its draft.
1565
+ ...(status && (mode === 'setting' || mode === 'filter') ? [status] : []),
1566
+ mode === 'message'
1567
+ ? strings.composeHint
1568
+ : mode === 'reason'
1569
+ ? strings.composeReasonHint
1570
+ : strings.settingsKeyHint,
1571
+ ]
1572
+ : []
1573
+ // The in-flight-send row is part of the pane too: counting it keeps the rendered output at the
1574
+ // pane's height, so the frame never scrolls (the absolute cursor position depends on the frame
1575
+ // starting at the pane's first row).
1576
+ const busyRow = busy ? 1 : 0
1577
+ const frameRows = size.rows > 0 ? Math.max(3, size.rows - input.length - hint.length - bottom.length - busyRow) : data.height
1578
+ const view: ViewState = {
1579
+ page,
1580
+ density: settings.density,
1581
+ lang: settings.lang,
1582
+ mouseOn: settings.mouse,
1583
+ tui: true,
1584
+ overlay,
1585
+ overlayIndex,
1586
+ viewEntry,
1587
+ scroll,
1588
+ focus,
1589
+ laneOffset,
1590
+ boardFold: settings.boardFold,
1591
+ boardShow: settings.boardShow,
1592
+ boardEmptyFold: settings.boardEmptyFold,
1593
+ detail: detailId,
1594
+ detailIndex,
1595
+ detailScroll,
1596
+ settings: settingsView,
1597
+ settingsFocus,
1598
+ settingsFilter,
1599
+ settingsOffset,
1600
+ seatPicker,
1601
+ choicePicker,
1602
+ }
1603
+ // The geometry comes from the live terminal, not from the frame's snapshot of it: a resize must
1604
+ // re-lay out the next frame (the spec's "A resize re-lays out live"), and `data.width` is frozen
1605
+ // at process start. The live clock is NOT fed through here: it patches row 0 after the memo
1606
+ // (below), so the per-second tick never re-runs the full layout (measured: routing `now`
1607
+ // through layout() pushed an idle console to ~1.1% of one core — over the red line).
1608
+ const themed = layout({
1609
+ ...data,
1610
+ width: Math.max(1, size.columns || data.width),
1611
+ activity: effectiveActivity,
1612
+ strings,
1613
+ height: frameRows,
1614
+ view,
1615
+ } as LayoutInput)
1616
+ const pad = size.rows > 0 ? Math.max(0, size.rows - input.length - hint.length - bottom.length - busyRow - themed.rows.length) : 0
1617
+ targetsRef.current = themed.targets
1618
+ lanesRef.current = themed.lanes ?? []
1619
+ boardOrderRef.current = themed.boardOrder ?? []
1620
+ detailRef.current = themed.detail ?? null
1621
+ settingsWindowRef.current = themed.settings ?? null
1622
+ return { frame: themed, input, hint, bottom, pad, boxed, inputView }
1623
+ }, [
1624
+ data,
1625
+ strings,
1626
+ page,
1627
+ settings.density,
1628
+ settings.lang,
1629
+ settings.mouse,
1630
+ overlay,
1631
+ overlayIndex,
1632
+ viewEntry,
1633
+ scroll,
1634
+ focus,
1635
+ laneOffset,
1636
+ settings.boardFold,
1637
+ settings.boardShow,
1638
+ settings.boardEmptyFold,
1639
+ detailId,
1640
+ detailIndex,
1641
+ detailScroll,
1642
+ settingsView,
1643
+ settingsFocus,
1644
+ settingsFilter,
1645
+ settingsOffset,
1646
+ seatPicker,
1647
+ choicePicker,
1648
+ size,
1649
+ composing,
1650
+ mode,
1651
+ draft,
1652
+ cursor,
1653
+ composeMaxRows,
1654
+ receipt,
1655
+ status,
1656
+ busy,
1657
+ effectiveActivity,
1658
+ ])
1659
+
1660
+ // The real terminal cursor on the insertion point (P20/B1): the position is relative to the Ink
1661
+ // output origin, which is the frame's first row. `y` counts the rows before the draft's row
1662
+ // (frame, pad, hint, the boxed tray's top edge); `x` adds the tray wall to the drawn column.
1663
+ // `undefined` while not composing or while a send is in flight hides it. Ink's own cursor math
1664
+ // is corrected by main.tsx's cursor-aware stdout, which re-asserts this same position after
1665
+ // every write; `useCursor` keeps Ink's show/hide bookkeeping in charge.
1666
+ const { setCursorPosition } = useCursor()
1667
+ const cursorPos =
1668
+ composing && !busy && lines.inputView
1669
+ ? {
1670
+ x: (lines.boxed ? 2 : 0) + lines.inputView.cursorColumn,
1671
+ y: lines.frame.rows.length + lines.pad + lines.hint.length + (lines.boxed ? 1 : 0) + lines.inputView.cursorLine,
1672
+ }
1673
+ : undefined
1674
+ setCursorPosition(cursorPos)
1675
+ api.setComposeCursor(cursorPos ?? null)
1676
+
1677
+ const refreshData = useCallback(
1678
+ (nextScroll = scrollRef.current) => {
1679
+ const fresh = reload()
1680
+ // A refresh that produced the same frame must not repaint: with the block TTLs, most cadences
1681
+ // change nothing at all, and an idle console should cost ~0% (the red line is <1% of one core).
1682
+ const same = frameSignature(dataRef.current) === frameSignature(fresh)
1683
+ dataRef.current = fresh
1684
+ scrollRef.current = nextScroll
1685
+ if (!same) setData(fresh)
1686
+ setScroll(nextScroll)
1687
+ },
1688
+ [reload],
1689
+ )
1690
+
1691
+ useEffect(() => {
1692
+ if (once) {
1693
+ // One frame and out: Ink needs a tick to flush the frame before unmounting.
1694
+ const t = setTimeout(() => exit(), 30)
1695
+ return () => clearTimeout(t)
1696
+ }
1697
+ const id = setInterval(() => {
1698
+ // The render callback is explicitly gated while an external program owns the terminal.
1699
+ if (api.suspended()) return
1700
+ refreshData(scrollRef.current)
1701
+ }, Math.max(1, refresh) * 1000)
1702
+ return () => clearInterval(id)
1703
+ }, [once, refresh, refreshData, exit, api])
1704
+
1705
+ // A shrinking pane must never keep the padding of the old height (Ink would write the taller box
1706
+ // and tmux would scroll the frame out of the visible rows — measured). Re-read the geometry and
1707
+ // let the layout rebuild from the latest data.
1708
+ useEffect(() => {
1709
+ const onResize = () => {
1710
+ if (api.suspended()) return
1711
+ setSize(liveSize(dataRef.current))
1712
+ }
1713
+ if (typeof process.stdout.on !== 'function') return undefined
1714
+ process.stdout.on('resize', onResize)
1715
+ return () => {
1716
+ process.stdout.off('resize', onResize)
1717
+ }
1718
+ }, [api])
1719
+
1720
+ // SGR mouse reporting follows the preference: on enables for the console's lifetime, off emits
1721
+ // no sequence at all (the spec's "Off means silent"), and unmounting always disables it.
1722
+ useEffect(() => {
1723
+ if (!process.stdout.isTTY) return undefined
1724
+ if (settings.mouse) writeSync(1, MOUSE_ON)
1725
+ return () => {
1726
+ if (settings.mouse) writeSync(1, MOUSE_OFF)
1727
+ }
1728
+ }, [settings.mouse])
1729
+
1730
+ useInput(
1731
+ (input, key) => {
1732
+ // The mouse's SGR sequences arrive as one input event (Ink strips the leading ESC — E6 §1.1c).
1733
+ const mouse = SGR_MOUSE.exec(input)
1734
+ if (mouse) {
1735
+ if (!settingsRef.current.mouse) return
1736
+ const button = Number(mouse[1])
1737
+ const x = Number(mouse[2])
1738
+ const y = Number(mouse[3])
1739
+ if (button === 64 || button === 65) {
1740
+ const delta = button === 65 ? 1 : -1
1741
+ // With the detail view open the wheel scrolls the document (the one scrollable region),
1742
+ // on the page the view was opened from (the work page's rows open it too, P20/B5).
1743
+ if (choicePickerRef.current) {
1744
+ // The choice picker's entries may outrun the budget: the wheel walks the list like
1745
+ // ↑/↓ (the window follows the selection, as the seat picker's does).
1746
+ moveChoicePicker(delta)
1747
+ return
1748
+ }
1749
+ if (seatPickerRef.current) {
1750
+ // P30/D5: the seat picker's wheel used to fall through to the page. It walks its
1751
+ // entries now, exactly like the choice picker, and the page still does not move.
1752
+ moveSeatPicker(delta)
1753
+ return
1754
+ }
1755
+ if (settingsViewRef.current) {
1756
+ // P30/D5: while the project-settings view is open the wheel is its region — the row
1757
+ // window moves one row per notch, the focus stays, and the page behind it is untouched.
1758
+ scrollSettings(delta)
1759
+ return
1760
+ }
1761
+ if ((pageRef.current === 4 || pageRef.current === 2) && detailIdRef.current) {
1762
+ scrollDetail(delta)
1763
+ return
1764
+ }
1765
+ // On the board page the wheel scrolls the lane under the cursor (a card hit carries its
1766
+ // lane, the lane's own hover target covers the rest); elsewhere it scrolls the page's list.
1767
+ if (pageRef.current === 4) {
1768
+ const over = targetsRef.current.find((t) => t.row === y - 1 && x - 1 >= t.hit.start && x - 1 < t.hit.end)
1769
+ const a = over?.hit.action
1770
+ if (a && (a.kind === 'lane-scroll' || a.kind === 'focus' || a.kind === 'open-focused')) {
1771
+ scrollLane(a.lane, delta)
1772
+ return
1773
+ }
1774
+ if (a && a.kind === 'lane-fold') {
1775
+ // P123: a lane's header/folded line keeps that lane's wheel region — the folded line
1776
+ // has no window to move (nothing to scroll), and the grouped tier's header names the
1777
+ // one page window it shares with the other lanes. The page behind is never touched.
1778
+ const key = a.scroll ?? a.lane
1779
+ if (lanesRef.current.some((w) => w.lane === key)) {
1780
+ scrollLane(key, delta)
1781
+ return
1782
+ }
1783
+ }
1784
+ }
1785
+ // The wheel scrolls the page's list: down reveals later rows, up goes back.
1786
+ updateScroll((v) => v + delta)
1787
+ return
1788
+ }
1789
+ if (mouse[4] !== 'M' || (button & 3) !== 0) return
1790
+ const row = y - 1
1791
+ const col = x - 1
1792
+ const hit = targetsRef.current.find((t) => t.row === row && col >= t.hit.start && col < t.hit.end)
1793
+ if (hit) dispatch(hit.hit.action)
1794
+ return
1795
+ }
1796
+
1797
+ if (overlay && !settingsViewRef.current) {
1798
+ if (key.escape || input === ',') {
1799
+ setOverlay(false)
1800
+ return
1801
+ }
1802
+ if (key.upArrow) {
1803
+ setOverlayIndex((i) => (i + PREFS.length) % (PREFS.length + 1))
1804
+ return
1805
+ }
1806
+ if (key.downArrow) {
1807
+ setOverlayIndex((i) => (i + 1) % (PREFS.length + 1))
1808
+ return
1809
+ }
1810
+ if (key.return || input === ' ') {
1811
+ // The sixth row is the one navigation row: it opens the project-settings view instead of
1812
+ // toggling a preference (and writes no file).
1813
+ if (overlayIndexRef.current >= PREFS.length) openSettingsView(overlayIndexRef.current)
1814
+ else cyclePref(PREFS[overlayIndexRef.current] ?? 'lang')
1815
+ return
1816
+ }
1817
+ return
1818
+ }
1819
+
1820
+ if (composing) {
1821
+ const composeText = draftRef.current
1822
+ const point = cursorRef.current
1823
+ const persist = mode === 'message'
1824
+ // The reason is one line: every line break lands as a space, typed, pasted or yanked.
1825
+ const flatten = (value: string): string => (mode === 'reason' ? value.replace(/\n/g, ' ') : value)
1826
+ if (key.ctrl && input === 'o') {
1827
+ void relayEditor()
1828
+ return
1829
+ }
1830
+ if (key.ctrl && input === 'v') {
1831
+ void pasteClipboard()
1832
+ return
1833
+ }
1834
+ // One pure decoder for both encodings (design §4): the App only applies its intent.
1835
+ const intent = composeKey(input, key)
1836
+ switch (intent.kind) {
1837
+ case 'submit':
1838
+ void submit()
1839
+ return
1840
+ case 'cancel':
1841
+ // The filter line's esc clears the filter without closing the view (P22/B2).
1842
+ if (mode === 'filter') {
1843
+ settingsFilterRef.current = ''
1844
+ setSettingsFilter('')
1845
+ setSettingsFocus(0)
1846
+ settingsFocusRef.current = 0
1847
+ // D5: clearing a filter resets the window with the focus.
1848
+ setSettingsOffset(null)
1849
+ settingsOffsetRef.current = null
1850
+ }
1851
+ closeCompose()
1852
+ return
1853
+ case 'none':
1854
+ return
1855
+ case 'newline': {
1856
+ if (busy) return
1857
+ pushUndo(undoRef.current, composeText, point)
1858
+ killRingRef.current = resetKillDirection(killRingRef.current)
1859
+ yankRef.current = null
1860
+ lastActionRef.current = 'edit'
1861
+ updateCompose(insertAt(composeText, point, flatten('\n')), persist)
1862
+ return
1863
+ }
1864
+ case 'move':
1865
+ setPoint(moveCursor(composeText, point, intent.motion, { width: composeWidth(), pageRows: composeMaxRows() }))
1866
+ return
1867
+ case 'insert': {
1868
+ if (busy) return
1869
+ // The typed/pasted text path: `intake` normalizes CR/LF and strips control bytes; the
1870
+ // paste markers may arrive with a leading ESC already consumed by Ink, so both
1871
+ // spellings are accepted and an unclosed bracket stays open across reads.
1872
+ const next = intake(input, pasteOpenRef.current)
1873
+ pasteOpenRef.current = next.pasteOpen
1874
+ if (!next.append) return
1875
+ pushUndo(undoRef.current, composeText, point)
1876
+ killRingRef.current = resetKillDirection(killRingRef.current)
1877
+ yankRef.current = null
1878
+ lastActionRef.current = 'edit'
1879
+ updateCompose(insertAt(composeText, point, flatten(next.append)), persist)
1880
+ return
1881
+ }
1882
+ case 'kill': {
1883
+ if (busy) return
1884
+ const span = killSpan(composeText, point, intent.unit)
1885
+ if (!span) return
1886
+ pushUndo(undoRef.current, composeText, point)
1887
+ killRingRef.current = pushKill(killRingRef.current, span.text, span.direction)
1888
+ yankRef.current = null
1889
+ lastActionRef.current = 'edit'
1890
+ const cps = [...composeText]
1891
+ updateCompose({ text: [...cps.slice(0, span.from), ...cps.slice(span.to)].join(''), cursor: span.from }, persist)
1892
+ return
1893
+ }
1894
+ case 'yank': {
1895
+ if (busy) return
1896
+ const text = ringEntry(killRingRef.current, 0)
1897
+ if (!text) return
1898
+ pushUndo(undoRef.current, composeText, point)
1899
+ killRingRef.current = resetKillDirection(killRingRef.current)
1900
+ yankRef.current = { pops: 0, length: cpLength(text) }
1901
+ lastActionRef.current = 'yank'
1902
+ updateCompose(insertAt(composeText, point, flatten(text)), persist)
1903
+ return
1904
+ }
1905
+ case 'yankPop': {
1906
+ if (busy) return
1907
+ const yank = yankRef.current
1908
+ if (!yank || lastActionRef.current !== 'yank') return
1909
+ const text = ringEntry(killRingRef.current, yank.pops + 1)
1910
+ if (!text) return
1911
+ pushUndo(undoRef.current, composeText, point)
1912
+ // Replace what the previous yank inserted: it sits directly before the point.
1913
+ const cps = [...composeText]
1914
+ const from = Math.max(0, point - yank.length)
1915
+ const replaced = [...cps.slice(0, from), ...cps.slice(point)].join('')
1916
+ yankRef.current = { pops: yank.pops + 1, length: cpLength(text) }
1917
+ lastActionRef.current = 'yank'
1918
+ updateCompose(insertAt(replaced, from, flatten(text)), persist)
1919
+ return
1920
+ }
1921
+ case 'undo': {
1922
+ if (busy) return
1923
+ const snap = popUndo(undoRef.current)
1924
+ if (!snap) return
1925
+ killRingRef.current = resetKillDirection(killRingRef.current)
1926
+ yankRef.current = null
1927
+ lastActionRef.current = 'edit'
1928
+ updateCompose({ text: snap.text, cursor: snap.cursor }, persist)
1929
+ return
1930
+ }
1931
+ }
1932
+ return
1933
+ }
1934
+
1935
+ // The project-settings view owns its keys first (it sits above the overlay it was opened
1936
+ // from); anything it does not claim (notably `q`) falls through to the global handling.
1937
+ if (settingsViewRef.current && !composing) {
1938
+ if (choicePickerRef.current) {
1939
+ // The choice picker owns the same keys the seat picker does: esc closes it back to the
1940
+ // row list with the row focus untouched, and it writes nothing on the way out.
1941
+ if (key.escape) {
1942
+ closeChoicePicker()
1943
+ return
1944
+ }
1945
+ if (key.upArrow || key.downArrow) {
1946
+ moveChoicePicker(key.upArrow ? -1 : 1)
1947
+ return
1948
+ }
1949
+ if (key.return) {
1950
+ chooseChoiceOption(-1)
1951
+ return
1952
+ }
1953
+ return
1954
+ }
1955
+ if (seatPickerRef.current) {
1956
+ if (key.escape) {
1957
+ setSeatPicker(null)
1958
+ seatPickerRef.current = null
1959
+ return
1960
+ }
1961
+ if (key.upArrow || key.downArrow) {
1962
+ moveSeatPicker(key.upArrow ? -1 : 1)
1963
+ return
1964
+ }
1965
+ if (key.return) {
1966
+ chooseSeatOption(-1)
1967
+ return
1968
+ }
1969
+ return
1970
+ }
1971
+ if (key.escape) {
1972
+ closeSettingsView()
1973
+ return
1974
+ }
1975
+ if (key.upArrow || key.downArrow) {
1976
+ moveSettingsFocus(key.upArrow ? -1 : 1)
1977
+ return
1978
+ }
1979
+ if (input === '/') {
1980
+ openCompose('filter')
1981
+ return
1982
+ }
1983
+ if (key.return) {
1984
+ openSettingsRow(-1)
1985
+ return
1986
+ }
1987
+ if (input !== 'q' && !(key.ctrl && input === 'c')) return
1988
+ }
1989
+
1990
+ if (viewEntry != null && key.escape) {
1991
+ setViewEntry(null)
1992
+ return
1993
+ }
1994
+ // The detail view is read-only and full-page: Esc or `q` backs out to the board page and never
1995
+ // collapses the console (the documented `q` exception); `←`/`→` switch files, `↑`/`↓` scroll.
1996
+ if (detailId) {
1997
+ if (key.escape || input === 'q') {
1998
+ setDetailId(null)
1999
+ return
2000
+ }
2001
+ if (key.leftArrow || key.rightArrow) {
2002
+ moveDetailTab(key.leftArrow ? -1 : 1)
2003
+ return
2004
+ }
2005
+ if (key.upArrow || key.downArrow) {
2006
+ scrollDetail(key.upArrow ? -1 : 1)
2007
+ return
2008
+ }
2009
+ // Enter adds no action here (no write operation), and the page keys stay live below.
2010
+ }
2011
+ if (input === 'q' || (key.ctrl && input === 'c')) {
2012
+ void collapse()
2013
+ return
2014
+ }
2015
+ if (busy) return
2016
+ if (key.tab) {
2017
+ goPage(pageRef.current === 4 ? 1 : ((pageRef.current + 1) as PageId))
2018
+ return
2019
+ }
2020
+ if (input === '1' || input === '2' || input === '3' || input === '4') {
2021
+ goPage(Number(input) as PageId)
2022
+ return
2023
+ }
2024
+ if (input === ',') {
2025
+ setOverlay(true)
2026
+ setOverlayIndex(0)
2027
+ return
2028
+ }
2029
+ if (input === 'm') {
2030
+ openCompose('message')
2031
+ return
2032
+ }
2033
+ if (input === 'f') {
2034
+ void runAction('flush')
2035
+ return
2036
+ }
2037
+ if (input === 's') {
2038
+ void runAction('standby')
2039
+ return
2040
+ }
2041
+ if (input === 'r') {
2042
+ // `r` is the human asking for it: rebuild every block now, not "when its TTL is up".
2043
+ setReceipt(null)
2044
+ setStatus(null)
2045
+ api.refreshNow()
2046
+ return
2047
+ }
2048
+ if (page === 4 && input === 'c' && !detailId) {
2049
+ // P123: `c` folds/unfolds the lane the focus names. The detail view and the settings
2050
+ // surfaces own the page region and never reach here (their branches returned above).
2051
+ const current = resolveFocus(boardRows(), focusRef.current)
2052
+ if (current) toggleLaneFold(current.lane)
2053
+ return
2054
+ }
2055
+ if (page === 4 && (key.leftArrow || key.rightArrow)) {
2056
+ moveFocus(key.leftArrow ? -1 : 1, 0)
2057
+ return
2058
+ }
2059
+ if (key.upArrow || key.downArrow) {
2060
+ // The board page walks its cards and the work page its board rows (the window follows the
2061
+ // focus); the other pages scroll.
2062
+ if (page === 4) moveFocus(0, key.upArrow ? -1 : 1)
2063
+ else if (page === 2) moveBoardFocus(key.upArrow ? -1 : 1)
2064
+ else updateScroll((v) => (key.upArrow ? v - 1 : v + 1))
2065
+ return
2066
+ }
2067
+ if (page === 4 && key.return) {
2068
+ const current = resolveFocus(boardRows(), focusRef.current)
2069
+ if (current) openDetail(current.id)
2070
+ return
2071
+ }
2072
+ if (page === 2 && key.return) {
2073
+ // The work page's board rows open the same detail view (P20/B5), on the page it was
2074
+ // opened from.
2075
+ openWorkFocused()
2076
+ return
2077
+ }
2078
+ if (key.pageUp || key.pageDown) {
2079
+ // `↑`/`↓` move the work page's row focus, so the keyboard keeps a page-scroll route (the
2080
+ // documented keyboard-only exception beside `r`).
2081
+ const step = Math.max(1, (size.rows || 10) - 4)
2082
+ updateScroll((v) => v + (key.pageUp ? -step : step))
2083
+ return
2084
+ }
2085
+ if (key.return && viewEntry == null && page === 3) {
2086
+ // Enter on the messages page opens the first queued entry's full text.
2087
+ const entries = dataRef.current.blocks?.outbox_list?.entries ?? []
2088
+ if (entries.length) setViewEntry(0)
2089
+ }
2090
+ },
2091
+ { isActive: !editorOpen && Boolean(process.stdin.isTTY) },
2092
+ )
2093
+
2094
+ // The title band's clock is the one visible thing that must advance while the data is
2095
+ // byte-identical (V15/F2 — without it an idle console's clock froze at startup, and B2's 2.5
2096
+ // lost its "a refresh completed" evidence on screen). It ticks OUTSIDE React: main.tsx paints
2097
+ // the clock field directly once a second (a full commit per second costs a whole frame's
2098
+ // reconcile + Yoga + rewrite — measured over the <1% red line), and the App registers row 0's
2099
+ // segments + palette for that writer. Row 0 itself renders the shared stamp via `clockRow`, so
2100
+ // Ink's rare repaints agree with the screen. The data cadence keeps its signature-gated
2101
+ // repaint as the only full-frame path.
2102
+ const renderRows = stableRows(rowCacheRef.current, lines.frame.rows)
2103
+ rowCacheRef.current = renderRows
2104
+
2105
+ const row0 = renderRows.length > 0 ? renderRows[0].row : null
2106
+ useEffect(() => {
2107
+ api.registerClockRow(row0, palette)
2108
+ return () => api.registerClockRow(null, palette)
2109
+ }, [api, row0, palette])
2110
+
2111
+ return (
2112
+ <Box flexDirection="column" width={size.columns}>
2113
+ {renderRows.map(({ row }, i) => (
2114
+ <Row key={`f${i}`} row={i === 0 ? clockRow(row, api.clockNowMs()) : row} palette={palette} />
2115
+ ))}
2116
+ {Array.from({ length: lines.pad }, (_, i) => (
2117
+ <Text key={`p${i}`}> </Text>
2118
+ ))}
2119
+ {/* The hint sits above the input: the input line must be the LAST rendered line while
2120
+ composing, because Ink leaves the terminal cursor at the end of the output and the IME
2121
+ candidate window anchors there (V15/F1 — with the hint below the input the cursor sat on
2122
+ the hint row and B2's CJK cursor acceptance, cursor_x=8, went red). */}
2123
+ {lines.hint.map((line, i) => (
2124
+ <Text key={`h${i}`} color={palette.tones.dim} wrap="truncate">
2125
+ {line}
2126
+ </Text>
2127
+ ))}
2128
+ {lines.input.map((line, i) => (
2129
+ <Text
2130
+ key={`i${i}`}
2131
+ color={
2132
+ lines.boxed && i === 0
2133
+ ? palette.tones.dim
2134
+ : i === lines.input.length - 1
2135
+ ? palette.tones.accent
2136
+ : palette.tones.text
2137
+ }
2138
+ >
2139
+ {line || ' '}
2140
+ </Text>
2141
+ ))}
2142
+ {lines.bottom.map((line, i) => (
2143
+ <Text key={`b${i}`} color={palette.tones.accent}>
2144
+ {line}
2145
+ </Text>
2146
+ ))}
2147
+ {busy ? <Text color={palette.tones.warn}>{mode === 'message' ? strings.busySend : strings.busyAction}</Text> : null}
2148
+ </Box>
2149
+ )
2150
+ }