@cueloop/client 0.1.0-alpha.8 → 0.1.0-alpha.80

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 (307) hide show
  1. package/native/build-pty.sh +51 -0
  2. package/native/build.sh +82 -0
  3. package/native/darwin-arm64/libcuelooppty.dylib +0 -0
  4. package/native/darwin-arm64/libcueloopvt.dylib +0 -0
  5. package/native/src/pty.zig +193 -0
  6. package/native/src/shim.zig +114 -0
  7. package/package.json +40 -32
  8. package/src/App.appearance.test.tsx +53 -0
  9. package/src/App.autoclose.test.tsx +77 -51
  10. package/src/App.diff.test.tsx +176 -45
  11. package/src/App.export.test.tsx +58 -41
  12. package/src/App.focus.test.ts +89 -0
  13. package/src/App.identity.test.tsx +78 -0
  14. package/src/App.plan-render.test.tsx +209 -0
  15. package/src/App.plan-review.test.tsx +428 -0
  16. package/src/App.prototype-markdown.test.tsx +92 -0
  17. package/src/App.prototype.test.tsx +176 -0
  18. package/src/App.readonly.test.tsx +129 -67
  19. package/src/App.regression.test.tsx +94 -0
  20. package/src/App.rendering.test.tsx +61 -35
  21. package/src/App.share-dialog.test.tsx +172 -0
  22. package/src/App.submit-confirm.test.tsx +222 -0
  23. package/src/App.test.tsx +333 -131
  24. package/src/App.toast.test.tsx +98 -0
  25. package/src/App.tsx +1338 -608
  26. package/src/App.visual.test.tsx +57 -0
  27. package/src/App.walk.test.tsx +299 -0
  28. package/src/App.workbench.test.tsx +701 -0
  29. package/src/__snapshots__/view-plan.regression.test.ts.snap +100 -0
  30. package/src/annotation-palette.ts +62 -0
  31. package/src/ansi-screen.test.ts +28 -0
  32. package/src/ansi-screen.ts +72 -0
  33. package/src/app-key-state.ts +61 -0
  34. package/src/app-screens.tsx +574 -0
  35. package/src/app-view-model.ts +162 -0
  36. package/src/attribution.test.ts +31 -0
  37. package/src/attribution.ts +42 -0
  38. package/src/clipboard.test.ts +23 -0
  39. package/src/clipboard.ts +33 -0
  40. package/src/components/AnnotatableFileView.stories.tsx +42 -0
  41. package/src/components/AnnotatableFileView.test.tsx +102 -0
  42. package/src/components/AnnotatableFileView.tsx +134 -0
  43. package/src/components/AnnotationCards.stories.tsx +86 -0
  44. package/src/components/AnnotationCards.tsx +341 -0
  45. package/src/components/AnsiScreen.stories.tsx +12 -0
  46. package/src/components/AnsiScreen.tsx +28 -0
  47. package/src/components/AppHeader.stories.tsx +50 -0
  48. package/src/components/AppHeader.tsx +83 -0
  49. package/src/components/AppShell.brand.test.tsx +58 -0
  50. package/src/components/AppShell.stories.tsx +89 -0
  51. package/src/components/AppShell.tsx +329 -0
  52. package/src/components/AppShell.zoom.test.tsx +135 -0
  53. package/src/components/BareWorkbenchFileView.stories.tsx +27 -0
  54. package/src/components/BareWorkbenchFileView.tsx +64 -0
  55. package/src/components/Breadcrumb.stories.tsx +19 -0
  56. package/src/components/Breadcrumb.tsx +45 -0
  57. package/src/components/ChangesColumn.stories.tsx +44 -0
  58. package/src/components/ChangesColumn.tsx +199 -0
  59. package/src/components/ChangesFileTree.test.tsx +61 -0
  60. package/src/components/CodeBlock.stories.tsx +42 -0
  61. package/src/components/CodeBlock.tsx +84 -0
  62. package/src/components/CompletionOverlay.stories.tsx +37 -0
  63. package/src/components/CompletionOverlay.tsx +77 -0
  64. package/src/components/ConfirmCard.stories.tsx +37 -0
  65. package/src/components/ConfirmCard.tsx +153 -0
  66. package/src/components/ConfirmDialog.stories.tsx +21 -0
  67. package/src/components/ConfirmDialog.tsx +72 -0
  68. package/src/components/DiffContentView.scroll.test.tsx +121 -0
  69. package/src/components/DiffContentView.split.test.tsx +140 -0
  70. package/src/components/DiffContentView.stories.tsx +80 -0
  71. package/src/components/DiffContentView.syntax.test.tsx +82 -0
  72. package/src/components/DiffContentView.tsx +876 -0
  73. package/src/components/DiscussionMarkerRail.stories.tsx +54 -0
  74. package/src/components/DiscussionMarkerRail.tsx +186 -0
  75. package/src/components/EditorGrid.stories.tsx +59 -0
  76. package/src/components/EditorGrid.tabs.test.tsx +118 -0
  77. package/src/components/EditorGrid.tsx +426 -0
  78. package/src/components/EditorGrid.zoom.test.tsx +68 -0
  79. package/src/components/FileContentsView.stories.tsx +16 -0
  80. package/src/components/FileContentsView.test.tsx +29 -0
  81. package/src/components/FileContentsView.tsx +98 -0
  82. package/src/components/GridTabContent.stories.tsx +59 -0
  83. package/src/components/GridTabContent.tsx +182 -0
  84. package/src/components/HandleChipsInput.stories.tsx +24 -0
  85. package/src/components/HandleChipsInput.test.tsx +35 -0
  86. package/src/components/HandleChipsInput.tsx +145 -0
  87. package/src/components/KeybindsDialog.stories.tsx +31 -0
  88. package/src/components/KeybindsDialog.tsx +103 -0
  89. package/src/components/MarkdownGridBlock.stories.tsx +33 -0
  90. package/src/components/MarkdownGridBlock.tsx +72 -0
  91. package/src/components/MarkdownThreadEditor.stories.tsx +15 -0
  92. package/src/components/MarkdownThreadEditor.test.tsx +98 -0
  93. package/src/components/MarkdownThreadEditor.tsx +162 -0
  94. package/src/components/MenuBar.stories.tsx +28 -0
  95. package/src/components/MenuBar.tsx +44 -0
  96. package/src/components/NavModeHint.stories.tsx +40 -0
  97. package/src/components/NavModeHint.tsx +31 -0
  98. package/src/components/OverlayScrollbar.stories.tsx +33 -0
  99. package/src/components/OverlayScrollbar.test.tsx +139 -0
  100. package/src/components/OverlayScrollbar.tsx +129 -0
  101. package/src/components/PaneGrid.stories.tsx +84 -0
  102. package/src/components/PaneGrid.tsx +128 -0
  103. package/src/components/PanelColumn.stories.tsx +25 -0
  104. package/src/components/PanelColumn.tsx +98 -0
  105. package/src/components/ProjectTreeView.stories.tsx +25 -0
  106. package/src/components/ProjectTreeView.test.tsx +59 -0
  107. package/src/components/ProjectTreeView.tsx +111 -0
  108. package/src/components/PromptDialog.stories.tsx +36 -0
  109. package/src/components/PromptDialog.test.tsx +61 -0
  110. package/src/components/PromptDialog.tsx +99 -0
  111. package/src/components/PrototypeContentView.stories.tsx +19 -0
  112. package/src/components/PrototypeContentView.tsx +446 -0
  113. package/src/components/RootOverlay.stories.tsx +45 -0
  114. package/src/components/RootOverlay.tsx +48 -0
  115. package/src/components/ScrollArea.stories.tsx +20 -0
  116. package/src/components/ScrollArea.tsx +44 -0
  117. package/src/components/SettingsDialog.stories.tsx +117 -0
  118. package/src/components/SettingsDialog.tsx +186 -0
  119. package/src/components/SettingsRows.stories.tsx +18 -0
  120. package/src/components/SettingsRows.tsx +112 -0
  121. package/src/components/ShareDialog.stories.tsx +121 -0
  122. package/src/components/ShareDialog.tsx +552 -0
  123. package/src/components/ShellHeader.stories.tsx +50 -0
  124. package/src/components/ShellHeader.tsx +137 -0
  125. package/src/components/SlashComposer.stories.tsx +37 -0
  126. package/src/components/SlashComposer.tsx +87 -0
  127. package/src/components/ThreadFooter.stories.tsx +30 -0
  128. package/src/components/ThreadFooter.test.tsx +47 -0
  129. package/src/components/ThreadFooter.tsx +76 -0
  130. package/src/components/ThreadTree.stories.tsx +46 -0
  131. package/src/components/ThreadTree.tsx +255 -0
  132. package/src/components/ThreadView.selection.test.tsx +899 -0
  133. package/src/components/ThreadView.slash.test.tsx +146 -0
  134. package/src/components/ThreadView.stories.tsx +26 -0
  135. package/src/components/ThreadView.tsx +472 -0
  136. package/src/components/Toast.stories.tsx +19 -0
  137. package/src/components/Toast.tsx +52 -0
  138. package/src/components/Tooltip.stories.tsx +26 -0
  139. package/src/components/Tooltip.tsx +72 -0
  140. package/src/components/TreePane.stories.tsx +106 -0
  141. package/src/components/TreePane.tsx +157 -0
  142. package/src/components/WalkWizard.stories.tsx +100 -0
  143. package/src/components/WalkWizard.tsx +150 -0
  144. package/src/components/WelcomePlayground.stories.tsx +12 -0
  145. package/src/components/WelcomePlayground.test.tsx +47 -0
  146. package/src/components/WelcomePlayground.tsx +142 -0
  147. package/src/components/__snapshots__/stories.test.tsx.snap +2238 -0
  148. package/src/components/diff-content-view-layout.test.ts +198 -0
  149. package/src/components/diff-content-view-layout.ts +84 -0
  150. package/src/components/editor-grid.test.ts +86 -0
  151. package/src/components/editor-grid.ts +138 -0
  152. package/src/components/file-tree.test.ts +60 -0
  153. package/src/components/file-tree.ts +112 -0
  154. package/src/components/menu-control.stories.tsx +35 -0
  155. package/src/components/menu-control.tsx +43 -0
  156. package/src/components/pages/Workspace.stories.tsx +181 -0
  157. package/src/components/primitives/Button.stories.tsx +32 -0
  158. package/src/components/primitives/Button.tsx +56 -0
  159. package/src/components/primitives/Card.stories.tsx +25 -0
  160. package/src/components/primitives/Card.tsx +63 -0
  161. package/src/components/primitives/Dialog.stories.tsx +24 -0
  162. package/src/components/primitives/Dialog.test.tsx +37 -0
  163. package/src/components/primitives/Dialog.tsx +71 -0
  164. package/src/components/primitives/DialogActions.stories.tsx +20 -0
  165. package/src/components/primitives/DialogActions.tsx +39 -0
  166. package/src/components/primitives/IconButton.stories.tsx +36 -0
  167. package/src/components/primitives/IconButton.tsx +62 -0
  168. package/src/components/primitives/StatusBar.stories.tsx +11 -0
  169. package/src/components/primitives/StatusBar.tsx +23 -0
  170. package/src/components/primitives/Switch.stories.tsx +17 -0
  171. package/src/components/primitives/Switch.tsx +32 -0
  172. package/src/components/primitives/Tabs.stories.tsx +29 -0
  173. package/src/components/primitives/Tabs.tsx +102 -0
  174. package/src/components/primitives/Toolbar.stories.tsx +17 -0
  175. package/src/components/primitives/Toolbar.tsx +14 -0
  176. package/src/components/primitives/Tree.stories.tsx +124 -0
  177. package/src/components/primitives/Tree.tsx +100 -0
  178. package/src/components/primitives/frame.test.ts +12 -0
  179. package/src/components/primitives/frame.ts +17 -0
  180. package/src/components/primitives/icons.ts +61 -0
  181. package/src/components/primitives/tree-model.test.ts +99 -0
  182. package/src/components/primitives/tree-model.ts +137 -0
  183. package/src/components/quick-actions-editor.stories.tsx +58 -0
  184. package/src/components/quick-actions-editor.test.tsx +117 -0
  185. package/src/components/quick-actions-editor.tsx +226 -0
  186. package/src/components/share-dialog-store.ts +58 -0
  187. package/src/components/stories-app.tsx +193 -0
  188. package/src/components/stories.test.tsx +74 -0
  189. package/src/components/story-fixtures.ts +102 -0
  190. package/src/components/story-tree.test.ts +108 -0
  191. package/src/components/story.ts +159 -0
  192. package/src/components/syntax-highlight.ts +133 -0
  193. package/src/components/terminal-pane.test.tsx +40 -0
  194. package/src/components/terminal-pane.ts +199 -0
  195. package/src/components/theme-context.stories.tsx +46 -0
  196. package/src/components/theme-context.tsx +37 -0
  197. package/src/components/thread-tree.test.ts +134 -0
  198. package/src/components/thread-tree.ts +109 -0
  199. package/src/components/truncate-text.ts +7 -0
  200. package/src/components/truncate-title.test.ts +31 -0
  201. package/src/components/truncate-title.ts +15 -0
  202. package/src/config-identity.test.ts +78 -0
  203. package/src/config.test.ts +517 -33
  204. package/src/config.ts +467 -57
  205. package/src/diff-fold.test.ts +78 -0
  206. package/src/diff-fold.ts +126 -0
  207. package/src/diff-hunk-curate.test.ts +315 -0
  208. package/src/diff-hunk-curate.ts +153 -0
  209. package/src/diff-intraline.test.ts +238 -0
  210. package/src/diff-intraline.ts +236 -0
  211. package/src/diff-syntax.test.ts +112 -0
  212. package/src/diff-syntax.ts +179 -0
  213. package/src/discussions.ts +79 -0
  214. package/src/editor.test.ts +149 -0
  215. package/src/editor.ts +139 -9
  216. package/src/ghostty-terminal.test.ts +85 -0
  217. package/src/ghostty-terminal.ts +199 -0
  218. package/src/github-identity.test.ts +58 -0
  219. package/src/github-identity.ts +41 -0
  220. package/src/herdr.test.ts +9 -34
  221. package/src/herdr.ts +25 -21
  222. package/src/index.ts +13 -0
  223. package/src/integrations.test.ts +41 -0
  224. package/src/integrations.ts +32 -0
  225. package/src/intent-dispatch.test.ts +723 -0
  226. package/src/intent-dispatch.ts +692 -0
  227. package/src/key-bindings.test.ts +156 -0
  228. package/src/key-bindings.ts +459 -0
  229. package/src/keymap.test.ts +461 -113
  230. package/src/keymap.ts +321 -79
  231. package/src/kitty-image.test.ts +66 -0
  232. package/src/kitty-image.ts +138 -0
  233. package/src/launch-layout.test.ts +52 -0
  234. package/src/launch-layout.ts +42 -0
  235. package/src/mark-runs.ts +121 -0
  236. package/src/markdown-editor-syntax-style.ts +50 -0
  237. package/src/markdown-grid.test.ts +101 -0
  238. package/src/markdown-grid.ts +203 -0
  239. package/src/markdown-highlight.test.ts +61 -0
  240. package/src/markdown-highlight.ts +122 -0
  241. package/src/pasted-image.test.ts +67 -0
  242. package/src/pasted-image.ts +60 -0
  243. package/src/perf/otlp-trace.test.ts +116 -0
  244. package/src/perf/otlp-trace.ts +130 -0
  245. package/src/perf/perf-report.ts +17 -0
  246. package/src/perf/perf-timings.test.ts +18 -0
  247. package/src/perf/perf-timings.ts +38 -0
  248. package/src/prototype-browser.test.ts +64 -0
  249. package/src/prototype-browser.ts +329 -0
  250. package/src/prototype-pixels.tsx +35 -0
  251. package/src/pty.test.ts +81 -0
  252. package/src/pty.ts +245 -0
  253. package/src/ready-signal.test.ts +85 -0
  254. package/src/ready-signal.ts +52 -0
  255. package/src/run.ts +78 -13
  256. package/src/serve.test.ts +24 -12
  257. package/src/serve.ts +52 -10
  258. package/src/share.ts +237 -0
  259. package/src/skills.test.ts +74 -0
  260. package/src/skills.ts +75 -0
  261. package/src/slash-palette.test.ts +103 -0
  262. package/src/slash-palette.ts +129 -0
  263. package/src/split-diff.test.ts +110 -0
  264. package/src/split-diff.ts +149 -0
  265. package/src/test-support.test.ts +264 -0
  266. package/src/test-support.ts +369 -0
  267. package/src/theme-presets.test.ts +51 -0
  268. package/src/theme-presets.ts +214 -0
  269. package/src/theme.ts +84 -19
  270. package/src/thread-chords.test.ts +79 -0
  271. package/src/thread-chords.ts +163 -0
  272. package/src/thread-controller.curate.test.ts +450 -0
  273. package/src/thread-controller.derivation.test.ts +62 -0
  274. package/src/thread-controller.live-diff.test.ts +322 -0
  275. package/src/thread-controller.optimistic.test.ts +69 -0
  276. package/src/thread-controller.share.test.ts +561 -0
  277. package/src/thread-controller.switch-cache.test.ts +176 -0
  278. package/src/thread-controller.tree.test.ts +261 -0
  279. package/src/thread-controller.ts +1893 -0
  280. package/src/thread-selection.test.ts +210 -0
  281. package/src/thread-selection.ts +243 -0
  282. package/src/tree-view.test.ts +128 -0
  283. package/src/tree-view.ts +148 -0
  284. package/src/use-annotation-surface.tsx +915 -0
  285. package/src/use-changes-workbench.ts +190 -0
  286. package/src/use-frame-measure.ts +41 -0
  287. package/src/use-remember-layout.ts +31 -0
  288. package/src/use-settings-dialog.tsx +320 -0
  289. package/src/use-terminal-virtualizer.ts +233 -0
  290. package/src/use-thread-body-editing.tsx +58 -0
  291. package/src/version.ts +5 -0
  292. package/src/view-diff.test.ts +137 -9
  293. package/src/view-diff.ts +269 -23
  294. package/src/view-plan.regression.test.ts +60 -0
  295. package/src/view-plan.test.ts +456 -0
  296. package/src/view-plan.ts +719 -0
  297. package/src/visual/contrast.test.ts +35 -0
  298. package/src/visual/contrast.ts +33 -0
  299. package/src/walk.test.ts +121 -0
  300. package/src/walk.ts +74 -0
  301. package/src/workbench-snapshot.test.ts +81 -0
  302. package/src/workbench-snapshot.ts +29 -0
  303. package/src/session-controller.ts +0 -345
  304. package/src/syntax.test.ts +0 -41
  305. package/src/syntax.ts +0 -88
  306. package/src/view.test.ts +0 -157
  307. package/src/view.ts +0 -312
@@ -0,0 +1,1893 @@
1
+ /**
2
+ * The thread controller: every daemon round-trip and mutation
3
+ * primitive behind one React-free object. It owns connect/autostart/subscribe,
4
+ * the session/inbox/status/error snapshot, optimistic apply, the mutation
5
+ * primitives (cut/edit/annotate/submit/...), and the post-submit completion
6
+ * lifecycle including the notes-vault export and the herdr return-focus.
7
+ * App subscribes to snapshots and keeps only view state.
8
+ */
9
+
10
+ import { SystemClock, type Clock, type TimerHandle } from "@opentui/core";
11
+ import { createStore, type StoreApi } from "zustand/vanilla";
12
+ import { DaemonClient, type ThreadClient } from "@cueloop/daemon/client";
13
+ import {
14
+ applyPathView,
15
+ createBranch,
16
+ cutBlock,
17
+ detectHerdr,
18
+ labelTip,
19
+ MAIN_BRANCH,
20
+ makeAnchor,
21
+ navigateTo,
22
+ newAnnotationId,
23
+ parseBlocks,
24
+ resolveAnchor,
25
+ restoreBlock,
26
+ restoreLine,
27
+ returnPaneFor,
28
+ switchBranch,
29
+ threadShareLinks,
30
+ viewOfPath,
31
+ type Anchor,
32
+ type Annotation,
33
+ type AnnotationTarget,
34
+ type Artifact,
35
+ type DiffFileContents,
36
+ type ShareLink,
37
+ type Thread,
38
+ type SessionHistory,
39
+ type MessageOutcome,
40
+ } from "@cueloop/schema";
41
+ import { loadBundledExporters, type BundledExporter } from "./integrations";
42
+ import {
43
+ collaboratorAnnotations,
44
+ mergeFromShare,
45
+ publishShare,
46
+ pullShare,
47
+ pushShare,
48
+ revokeShare,
49
+ watchShare,
50
+ shareIdFromLine,
51
+ formatShareLine,
52
+ } from "./share";
53
+ import { buildDisplay, nextWorkBlock, renderedSpanToWork, type DisplayBlock } from "./view-plan";
54
+ import { entryTarget, treeRows, type TreeRow } from "./tree-view";
55
+ import {
56
+ diffRowBlocks,
57
+ diffRows,
58
+ fileChangeCounts,
59
+ fileRowRange,
60
+ readsFrozenDiff,
61
+ type DiffRow,
62
+ } from "./view-diff";
63
+ import { applyFold } from "./diff-fold";
64
+ import { snapshotWorkbench } from "./workbench-snapshot";
65
+ import { copyToClipboard } from "./clipboard";
66
+ import {
67
+ changeRejectionForRow,
68
+ hunkRejectionForRow,
69
+ isRowRejected,
70
+ parseFileDiff,
71
+ rejectsWholeHunk,
72
+ sameRejection,
73
+ type HunkRejection,
74
+ } from "./diff-hunk-curate";
75
+ import type { FileDiffMetadata } from "@pierre/diffs";
76
+ import { firstUnviewedIndex, walkFiles, type WalkFile } from "./walk";
77
+ import { editInEditor } from "./editor";
78
+ import { focusHerdrPane } from "./herdr";
79
+ import { persistAutoClose, type AutoClose, type CueloopConfig, type QuickAction } from "./config";
80
+ import { slashItemsFrom } from "./slash-palette";
81
+
82
+ /**
83
+ * Post-submit lifecycle (a review pane should hand you back to the agent,
84
+ * not linger): idle → counting (a visible countdown, the default) → exit.
85
+ * esc dismisses to the resolved view; a remembers the countdown as default.
86
+ */
87
+ export type Completion =
88
+ | { phase: "idle" }
89
+ | { phase: "prompt" }
90
+ | { phase: "counting"; remaining: number }
91
+ | { phase: "dismissed" };
92
+
93
+ /** Seconds the completion overlay counts down before it hands back. */
94
+ export const DEFAULT_AUTO_CLOSE = 5;
95
+
96
+ /** How often an open shared plan re-pulls collaborator notes (ADR 0005 stage 2). */
97
+ /** Reconnect backoff for a dropped watch stream: doubles from the floor to the cap. */
98
+ export const SHARE_RECONNECT_MIN_MS = 1000;
99
+ export const SHARE_RECONNECT_MAX_MS = 30_000;
100
+
101
+ /** Shared empty set so "nothing rejected" is a stable identity for renders. */
102
+ const EMPTY_REJECTIONS: HunkRejection[] = [];
103
+ const EMPTY_REJECTED_ROWS: Set<number> = new Set();
104
+
105
+ /** Shared empty list so "nothing curated out" is a stable identity for renders. */
106
+ const EMPTY_CURATION_ITEMS: CurationItem[] = [];
107
+
108
+ /** Status shown when a curated-out removal (diff rejection or plan cut) is restored. */
109
+ const REMOVAL_RESTORED_STATUS = "removal restored";
110
+
111
+ export interface ToastState {
112
+ title?: string;
113
+ body: string;
114
+ }
115
+
116
+ /**
117
+ * One removed piece projected for the review rail, unified across both review
118
+ * kinds: a diff hunk/change the owner curated out, or a plan block they cut.
119
+ * `source` tells restore and reveal which path to take; `preview` is the removed
120
+ * content (a few lines) the card renders struck through; `revealIndex` is the
121
+ * diff row (diff) or display block (plan) to scroll to and restore against.
122
+ */
123
+ export interface CurationItem {
124
+ id: string;
125
+ source: "diff" | "plan";
126
+ preview: string[];
127
+ revealIndex: number;
128
+ }
129
+
130
+ /** Stable id for a rejection's rail item: diff:path#hunk#change (or #hunk for a whole hunk). */
131
+ export function curationItemId(rejection: HunkRejection): string {
132
+ return `diff:${rejection.path}#${rejection.hunkIndex}#${rejection.changeIndex ?? "hunk"}`;
133
+ }
134
+
135
+ /** Stable id for a plan cut's rail item, keyed on its fixed base-content line range. */
136
+ function planCutId(base: { lineStart: number; lineEnd: number }): string {
137
+ return `plan:${base.lineStart}-${base.lineEnd}`;
138
+ }
139
+
140
+ /**
141
+ * Whether two records of the same thread yield the same document projection (display, rows, files,
142
+ * models). Those derive only from the artifact content and the working copy, so an update that
143
+ * touched only annotations, status, or the message leaves them identical - the projection can be
144
+ * reused rather than re-parsed. Content and working copy are strings, compared here by value.
145
+ */
146
+ export function sameDerivationInputs(previous: Thread, next: Thread): boolean {
147
+ return (
148
+ previous.id === next.id &&
149
+ previous.artifact.content === next.artifact.content &&
150
+ previous.workingCopy === next.workingCopy
151
+ );
152
+ }
153
+
154
+ /**
155
+ * The session with `annotation` upserted, for an optimistic paint the instant the composer closes
156
+ * rather than after the daemon round-trip - otherwise a saved comment blinks out until the write
157
+ * lands. An edit keeps the note in place and its timestamp; a new note appends. The daemon's record
158
+ * replaces this guess when the write returns.
159
+ */
160
+ export function withAnnotationUpserted(
161
+ session: Thread,
162
+ annotation: Omit<Annotation, "createdAt">,
163
+ ): Thread {
164
+ const index = session.annotations.findIndex((entry) => entry.id === annotation.id);
165
+ const createdAt = index >= 0 ? session.annotations[index]!.createdAt : new Date().toISOString();
166
+ const optimistic: Annotation = { ...annotation, createdAt };
167
+ const annotations =
168
+ index >= 0
169
+ ? session.annotations.map((entry) => (entry.id === annotation.id ? optimistic : entry))
170
+ : [...session.annotations, optimistic];
171
+
172
+ return { ...session, annotations };
173
+ }
174
+
175
+ export interface ControllerSnapshot {
176
+ session: Thread | null;
177
+ inbox: Thread[] | null;
178
+ status: string;
179
+ toast: ToastState | null;
180
+ error: string | null;
181
+ completion: Completion;
182
+ /**
183
+ * Annotations whose anchor stopped resolving after the last editor
184
+ * hand-off - the reconciliation banner count. 0 = no banner.
185
+ */
186
+ editOrphanCount: number;
187
+ /**
188
+ * The guided walk's cursor (diff sessions): which wizard step is on
189
+ * screen. index === file count is the end card. null = not walking; the
190
+ * viewed set itself rides the session record, so leaving loses nothing.
191
+ */
192
+ walk: { index: number } | null;
193
+ }
194
+
195
+ export interface ShareTransport {
196
+ publish: typeof publishShare;
197
+ pull: typeof pullShare;
198
+ push: typeof pushShare;
199
+ revoke: typeof revokeShare;
200
+ watch: typeof watchShare;
201
+ parseShareId: typeof shareIdFromLine;
202
+ formatShareLine: typeof formatShareLine;
203
+ collaboratorAnnotations: typeof collaboratorAnnotations;
204
+ mergeFromShare: typeof mergeFromShare;
205
+ }
206
+
207
+ const DEFAULT_SHARE_TRANSPORT: ShareTransport = {
208
+ publish: publishShare,
209
+ pull: pullShare,
210
+ watch: watchShare,
211
+ push: pushShare,
212
+ revoke: revokeShare,
213
+ parseShareId: shareIdFromLine,
214
+ formatShareLine,
215
+ collaboratorAnnotations,
216
+ mergeFromShare,
217
+ };
218
+
219
+ /** The editable fields of a share link, as the share wizard collects them. */
220
+ export interface NewShareLink {
221
+ name?: string;
222
+ requireAuth: boolean;
223
+ allowlist: string[];
224
+ }
225
+
226
+ export interface ReviewControllerOptions {
227
+ home?: string;
228
+ sessionId?: string;
229
+ /** The directory the client launched in; its git repo backs the no-session welcome tree. Defaults to process.cwd(). */
230
+ cwd?: string;
231
+ /** Observer mode: stored for the key reducer's read-only gate. */
232
+ readOnly?: boolean;
233
+ onExit?: (code: number) => void;
234
+ /** Timer source for the auto-close countdown; tests inject a ManualClock. */
235
+ clock?: Clock;
236
+ /**
237
+ * How the controller gets its session client. Defaults to dialing the local
238
+ * daemon; the sharing gateway injects a blob-backed client so the same <App>
239
+ * renders a decrypted share instead.
240
+ */
241
+ openClient?: () => Promise<ThreadClient>;
242
+ shareTransport?: ShareTransport;
243
+ /** Serve mode: pin this frozen diff onto the served thread so an observer sees a stable snapshot. */
244
+ servedArtifact?: Artifact;
245
+ }
246
+
247
+ export interface ReviewController {
248
+ readonly readOnly: boolean;
249
+ /** Snapshot listeners (stable identity - safe for useSyncExternalStore). */
250
+ subscribe(listener: () => void): () => void;
251
+ getSnapshot(): ControllerSnapshot;
252
+ /** Dial the daemon (autostart), subscribe to events, fetch session or inbox. */
253
+ connect(): void;
254
+ close(): void;
255
+ /** Loaded config parts the controller acts on: auto-close and exporters. */
256
+ applyConfig(config: CueloopConfig): void;
257
+ setStatus(message: string): void;
258
+ showToast(body: string, title?: string): void;
259
+ dismissToast(): void;
260
+ /** Derived projections, cached per session identity. */
261
+ display(): DisplayBlock[];
262
+ rows(): DiffRow[];
263
+ /** Fold a file's diff body to just its band, or unfold it; rows() reflects the change. */
264
+ setFileCollapsed(file: string, collapsed: boolean): void;
265
+ isFileCollapsed(file: string): boolean;
266
+ /** Weave a file's full contents inline (unchanged lines as context), or fold back to hunks. */
267
+ setFileExpanded(file: string, expanded: boolean): void;
268
+ isFileExpanded(file: string): boolean;
269
+ /** Whether the file carries the full contents weaving needs (curatable diffs do). */
270
+ canExpandFile(file: string): boolean;
271
+ /** Copy a file's path to the clipboard; reports the outcome via status. */
272
+ copyFilePath(file: string): void;
273
+ /** Per-file added/removed line counts from the base rows (survives collapse). */
274
+ fileStats(): Map<string, { additions: number; deletions: number }>;
275
+ /** The walk's step list, derived from the diff rows. */
276
+ files(): WalkFile[];
277
+ working(): string;
278
+ /** The workspace's tracked files (git ls-files) for the Project tree; empty when unavailable. */
279
+ projectFiles(): Promise<string[]>;
280
+ /** Read a workspace file's contents for a Changes file tab; null when it cannot be read. */
281
+ readFile(path: string): Promise<string | null>;
282
+ /** The launch repo's tracked files for the no-session welcome Project tree; empty when not a repo. */
283
+ repoFiles(): Promise<string[]>;
284
+ /** Read a launch-repo file's contents for a welcome file tab; null when it cannot be read. */
285
+ repoReadFile(path: string): Promise<string | null>;
286
+ /** The launch repo's working-tree changed files for the no-session welcome Changes tree. */
287
+ repoChanges(): Promise<readonly DiffFileContents[]>;
288
+ /** Open a session from the inbox. */
289
+ open(id: string): void;
290
+ /** Delete a session for good (inbox delete); the inbox refreshes on the event. */
291
+ deleteSession(id: string): void;
292
+ /** Rename a session's title; the inbox refreshes on the event. */
293
+ renameSession(id: string, title: string): void;
294
+ /** Record the viewer's own name into the share's participant registry (collaborator self-naming). */
295
+ setSelfName(name: string): void;
296
+ /** Cut the block under the cursor, or restore a cut one. */
297
+ cut(displayIndex: number): void;
298
+ /** Toggle rejection of the whole hunk under the diff cursor (owner curation). */
299
+ toggleRejectHunk(rowIndex: number): void;
300
+ /** Toggle rejection of the single change under the diff cursor (owner curation). */
301
+ toggleRejectChange(rowIndex: number): void;
302
+ /** Rendered row indices dropped by the current reject decisions (for dimming). */
303
+ rejectedRows(): Set<number>;
304
+ /** The curated-out rejections as rail items, in the order they were rejected. */
305
+ curationItems(): CurationItem[];
306
+ /** Undo one curation item by id: drop the rejection and recompute the working copy. */
307
+ restoreCuration(id: string): void;
308
+ /** The $EDITOR hand-off on the working copy. */
309
+ edit(): void;
310
+ /** Track an edited thread body as the working copy and re-resolve annotations against it. */
311
+ saveEditedBody(content: string): void;
312
+ /**
313
+ * Anchor and store an annotation; both plan and diff anchor constructions.
314
+ * `end` is an offset within `endDisplayIndex` (the same block by default).
315
+ * Returns the minted annotation id so the view can select the new card.
316
+ */
317
+ annotate(
318
+ kind: "comment",
319
+ displayIndex: number,
320
+ start: number,
321
+ end: number,
322
+ body: string,
323
+ endDisplayIndex?: number,
324
+ /** The surface being annotated; a `file` target anchors into the Changes diff rows. */
325
+ target?: AnnotationTarget,
326
+ ): string | undefined;
327
+ /** Persist a comment whose anchor a surface already built (e.g. a file-contents view). */
328
+ addComment(anchor: Anchor, target: AnnotationTarget, body: string): string | undefined;
329
+ /**
330
+ * Comment from the bare launch shell, where no thread is open: find-or-create the per-repo
331
+ * workbench thread, open it (the shell becomes a thread view), then add the comment. This is the
332
+ * first write a browse-only launch makes - nothing is on disk until it runs.
333
+ */
334
+ commentOnWorkbench(anchor: Anchor, target: AnnotationTarget, body: string): Promise<void>;
335
+ /** As commentOnWorkbench, for a note drawn on the bare-launch Changes diff (row coords, file target). */
336
+ commentOnWorkbenchDiff(
337
+ displayIndex: number,
338
+ start: number,
339
+ end: number,
340
+ endDisplayIndex: number,
341
+ body: string,
342
+ ): Promise<void>;
343
+ /**
344
+ * Reply to `rootAnnotationId`: the reply shares the root's anchor and names
345
+ * it in replyTo, so the discussion stays one conversation. Returns the minted id.
346
+ */
347
+ reply(rootAnnotationId: string, body: string): string | undefined;
348
+ /** Anchor a prototype comment to a DOM element by its selector. */
349
+ annotatePrototype(selector: string, quote: string, body: string): string | undefined;
350
+ /** Rewrite a stored annotation's body in place (the rail-card edit). */
351
+ updateAnnotation(id: string, body: string): void;
352
+ removeAnnotation(id: string): void;
353
+ setWorkingCopy(content: string | undefined): void;
354
+ /** Enter the guided walk at the first unviewed file (diff sessions). */
355
+ walkStart(): void;
356
+ /** Mark the current file viewed (persists with the session) and advance. */
357
+ walkForward(): void;
358
+ walkBack(): void;
359
+ /** Leave the walk; the viewed set stays on the session record. */
360
+ walkLeave(): void;
361
+ /** Resolve the review, run the export, start the completion hand-back. */
362
+ submit(message: MessageOutcome, summary: string): void;
363
+ /** Publish the current session as a public share link; the ssh line lands on the clipboard. */
364
+ share(): void;
365
+ /** Stop sharing the current session, revoking every link at the gateway. Owner only. */
366
+ unshare(): void;
367
+ /** Replace the private-share allowlist of GitHub logins for the current session. Owner only. */
368
+ setShareAccess(githubLogins: string[]): void;
369
+ /** The current thread's share links (a legacy single share migrates to a one-element list). */
370
+ shareLinks(): ShareLink[];
371
+ /** Publish a new share link with the given name and auth; the ssh line lands on the clipboard. Owner only. */
372
+ createShareLink(input: NewShareLink): void;
373
+ /** Update a link's name and auth in place, re-pushing its access to the gateway. Owner only. */
374
+ updateShareLink(id: string, input: NewShareLink): void;
375
+ /** Revoke a link and remove it from the thread. Owner only. */
376
+ deleteShareLink(id: string): void;
377
+ /** Copy a link's ssh line to the clipboard. */
378
+ copyShareLink(id: string): void;
379
+ /** The session tree as rows for the rail's Tree tab, cached per session identity. */
380
+ treeRows(): TreeRow[];
381
+ /**
382
+ * Go to an entry: switch to the branch whose tip it is, or move the current
383
+ * branch's tip back to it, with an optional branch summary. Owner only.
384
+ */
385
+ goToEntry(entryId: string, summary?: string): void;
386
+ /** Start a branch at the current tip and switch to it. */
387
+ branch(name: string): void;
388
+ /** Name the current tip as a checkpoint. */
389
+ labelTip(label: string): void;
390
+ /** Copy the current path into a new session and open it. */
391
+ fork(): void;
392
+ /** Fork, then share the fork; the current session stays open and unshared. */
393
+ forkAndShare(): void;
394
+ /** Pull a shared plan's collaborator notes back and union them in (planner only). */
395
+ pullShared(): Promise<void>;
396
+ /** Poll the share for collaborator notes while it is open; returns a stop handle. */
397
+ startShareSync(): () => void;
398
+ /** Close the review and, inside herdr, bounce focus back to the agent. */
399
+ finishReview(): void;
400
+ dismissCompletion(): void;
401
+ /** From the completion prompt: persist auto-close and start the countdown. */
402
+ optInAutoClose(): void;
403
+ }
404
+
405
+ export function createReviewController(options: ReviewControllerOptions): ReviewController {
406
+ return new Controller(options);
407
+ }
408
+
409
+ interface DerivedSessionProjection {
410
+ display: DisplayBlock[];
411
+ rows: DiffRow[];
412
+ files: WalkFile[];
413
+ /** Raw per-file contents; parsed into a model lazily on first curation touch, not all upfront. */
414
+ fileContents: Map<string, DiffFileContents>;
415
+ /** Parsed file models, filled on demand from fileContents and memoized here. */
416
+ models: Map<string, FileDiffMetadata>;
417
+ tree: TreeRow[];
418
+ }
419
+
420
+ /** A live working-tree diff: the same patch + per-file contents a diff capture pins. */
421
+ interface LiveWorkingDiff {
422
+ patch: string;
423
+ files: readonly DiffFileContents[];
424
+ }
425
+
426
+ interface DerivedCacheEntry {
427
+ derivedFor: Thread;
428
+ derivedForLiveDiff: LiveWorkingDiff | null;
429
+ derived: DerivedSessionProjection;
430
+ }
431
+
432
+ /** Recently-viewed threads whose parsed projection is kept for an instant return; oldest evicted first. */
433
+ const DERIVED_CACHE_LIMIT = 8;
434
+
435
+ class Controller implements ReviewController {
436
+ readonly readOnly: boolean;
437
+ private client: ThreadClient | null = null;
438
+ private closed = false;
439
+ /** The controller's state lives in a zustand store; internal reads go through the snapshot getter. */
440
+ private readonly store: StoreApi<ControllerSnapshot> = createStore<ControllerSnapshot>(() => ({
441
+ session: null,
442
+ inbox: null,
443
+ status: "",
444
+ toast: null,
445
+ error: null,
446
+ completion: { phase: "idle" },
447
+ editOrphanCount: 0,
448
+ walk: null,
449
+ }));
450
+ private get snapshot(): ControllerSnapshot {
451
+ return this.store.getState();
452
+ }
453
+ private autoClose: AutoClose = "off";
454
+ private quickActions: QuickAction[] = [];
455
+ private editor: string | undefined;
456
+ private exporters: BundledExporter[] = [];
457
+ private readonly clock: Clock;
458
+ private readonly shareTransport: ShareTransport;
459
+ private countdown: TimerHandle | undefined;
460
+ private shareReconnect: TimerHandle | undefined;
461
+ private shareStop: (() => void) | null = null;
462
+ private shareRun: object | null = null;
463
+ /** Projections keyed by session identity (and the live diff for non-diff threads) so renders reuse one computation. */
464
+ private derivedFor: Thread | null = null;
465
+ /** The launch/workspace repo's live working-tree diff, feeding the Changes view for non-diff threads. */
466
+ private liveDiff: LiveWorkingDiff | null = null;
467
+ private derivedForLiveDiff: LiveWorkingDiff | null = null;
468
+ private derived: DerivedSessionProjection = {
469
+ display: [],
470
+ rows: [],
471
+ files: [],
472
+ fileContents: new Map(),
473
+ models: new Map(),
474
+ tree: [],
475
+ };
476
+ /** Recently-viewed threads' parsed projections, so returning to a thread reuses its work instead of re-parsing. */
477
+ private derivedCache = new Map<string, DerivedCacheEntry>();
478
+ /** The thread the view is on now; a revalidation for a since-abandoned thread is discarded. */
479
+ private viewingId: string | undefined;
480
+ /** File paths whose diff body is folded to just the file band. */
481
+ private collapsedFiles = new Set<string>();
482
+ /** File paths woven to their full contents (unchanged lines shown as context). */
483
+ private expandedFiles = new Set<string>();
484
+ /** The diff's reject decisions live on the session record; the daemon curates from them. */
485
+ private get rejections(): HunkRejection[] {
486
+ return this.snapshot.session?.curation ?? EMPTY_REJECTIONS;
487
+ }
488
+
489
+ constructor(private readonly options: ReviewControllerOptions) {
490
+ this.readOnly = options.readOnly ?? false;
491
+ this.clock = options.clock ?? new SystemClock();
492
+ this.shareTransport = options.shareTransport ?? DEFAULT_SHARE_TRANSPORT;
493
+ }
494
+
495
+ subscribe = (listener: () => void): (() => void) => this.store.subscribe(listener);
496
+
497
+ getSnapshot = (): ControllerSnapshot => this.store.getState();
498
+
499
+ private update(patch: Partial<ControllerSnapshot>): void {
500
+ this.store.setState(this.freezeServed(patch));
501
+ }
502
+
503
+ /** Serve mode pins the served thread's diff to a snapshot; its annotations and the rest stay live. */
504
+ private freezeServed(patch: Partial<ControllerSnapshot>): Partial<ControllerSnapshot> {
505
+ const served = this.options.servedArtifact;
506
+
507
+ if (!served || !patch.session || patch.session.id !== this.options.sessionId) return patch;
508
+
509
+ return { ...patch, session: { ...patch.session, artifact: served } };
510
+ }
511
+
512
+ connect(): void {
513
+ void (async () => {
514
+ try {
515
+ const openClient =
516
+ this.options.openClient ??
517
+ (() => DaemonClient.connect({ home: this.options.home, autostart: true }));
518
+ const client = await openClient();
519
+
520
+ if (this.closed) return void client.close();
521
+ this.client = client;
522
+ client.onEvent((event) => {
523
+ // another controller/observer changed state: re-fetch the active session's content
524
+ const session = this.snapshot.session;
525
+
526
+ if (session && event.sessionId === session.id) void this.refreshSession(session.id);
527
+ // only the list-changing events touch the Threads sidebar; refreshing on every
528
+ // content edit (session.updated) would amplify an active review into a request storm
529
+ if (event.event !== "session.updated") void this.refreshInbox();
530
+ });
531
+ await client.subscribe();
532
+ // load the inbox in both cases so the sidebar can jump between threads
533
+ const inbox = await client.sessionList({ status: "pending" });
534
+
535
+ if (this.options.sessionId) {
536
+ this.viewingId = this.options.sessionId;
537
+ this.update({ session: await client.sessionGet(this.options.sessionId), inbox });
538
+ } else {
539
+ this.update({ inbox });
540
+ }
541
+ } catch (err) {
542
+ this.update({ error: err instanceof Error ? err.message : String(err) });
543
+ }
544
+ })();
545
+ }
546
+
547
+ close(): void {
548
+ this.closed = true;
549
+ this.clearCountdown();
550
+ this.stopShareSync();
551
+ this.client?.close();
552
+ }
553
+
554
+ private clearCountdown(): void {
555
+ if (this.countdown !== undefined) this.clock.clearTimeout(this.countdown);
556
+ this.countdown = undefined;
557
+ }
558
+
559
+ applyConfig(config: CueloopConfig): void {
560
+ this.autoClose = config.ui.autoClose;
561
+ this.quickActions = config.actions;
562
+ this.editor = config.ui.editor;
563
+ void loadBundledExporters(config.integrations).then((exporters) => {
564
+ this.exporters = exporters;
565
+ });
566
+ }
567
+
568
+ setStatus(message: string): void {
569
+ // the persistent status bar is gone; transient feedback surfaces as a toast
570
+ this.update({ status: message, toast: message ? { body: message } : null });
571
+ }
572
+
573
+ showToast(body: string, title?: string): void {
574
+ this.update({ toast: { body, title } });
575
+ }
576
+
577
+ dismissToast(): void {
578
+ if (this.snapshot.toast) this.update({ toast: null });
579
+ }
580
+
581
+ // ── derived projections ─────────────────────
582
+ /**
583
+ * The projection reuses when the same thread's derivation inputs are unchanged. display, rows,
584
+ * files, and models derive only from the artifact and working copy - never from annotations,
585
+ * status, or the message - so an update that touched only those produces an all-new session
586
+ * record but an identical projection.
587
+ */
588
+ private reusesDerived(session: Thread, liveDiff: LiveWorkingDiff | null): boolean {
589
+ return (
590
+ this.derivedFor !== null &&
591
+ this.derivedForLiveDiff === liveDiff &&
592
+ sameDerivationInputs(this.derivedFor, session)
593
+ );
594
+ }
595
+
596
+ private buildDerived(
597
+ session: Thread | null,
598
+ frozenDiff: boolean,
599
+ liveDiff: LiveWorkingDiff | null,
600
+ ): DerivedSessionProjection {
601
+ const content = frozenDiff ? session!.artifact.content : (liveDiff?.patch ?? "");
602
+ const files = frozenDiff ? (session?.artifact.files ?? []) : (liveDiff?.files ?? []);
603
+ const rows = content ? diffRows(content) : [];
604
+ const fileContents = new Map<string, DiffFileContents>();
605
+
606
+ for (const file of files) fileContents.set(file.path, file);
607
+
608
+ return {
609
+ display: session ? buildDisplay(session.artifact.content, session.workingCopy) : [],
610
+ rows,
611
+ files: walkFiles(rows),
612
+ fileContents,
613
+ models: new Map<string, FileDiffMetadata>(),
614
+ tree: session?.history ? treeRows(session.history) : [],
615
+ };
616
+ }
617
+
618
+ /** The parsed model for a changed file, computed on first touch and memoized in the projection. */
619
+ private fileModel(path: string): FileDiffMetadata | undefined {
620
+ const cached = this.derived.models.get(path);
621
+
622
+ if (cached) return cached;
623
+ const contents = this.derived.fileContents.get(path);
624
+
625
+ if (!contents) return undefined;
626
+ const model = parseFileDiff(contents);
627
+
628
+ this.derived.models.set(path, model);
629
+
630
+ return model;
631
+ }
632
+
633
+ private ensureDerived(): void {
634
+ const session = this.snapshot.session;
635
+ const frozenDiff = readsFrozenDiff(session);
636
+ // a plain diff thread reads its pinned capture; a workbench thread and every other thread reflect the live working tree
637
+ const liveDiff = frozenDiff ? null : this.liveDiff;
638
+
639
+ if (this.derivedFor === session && this.derivedForLiveDiff === liveDiff) return;
640
+ // reuse the parsed projection across an update that left the inputs unchanged; only the cheap tree can differ
641
+ if (session !== null && this.reusesDerived(session, liveDiff)) {
642
+ this.derivedFor = session;
643
+ this.derived = { ...this.derived, tree: session.history ? treeRows(session.history) : [] };
644
+
645
+ return;
646
+ }
647
+ // a different thread resets fold state; a same-thread re-derivation (content edit) keeps it
648
+ if (this.derivedFor?.id !== session?.id) {
649
+ this.collapsedFiles.clear();
650
+ this.expandedFiles.clear();
651
+ }
652
+ // returning to a recently-viewed thread whose inputs are unchanged reuses its parsed projection
653
+ const cached = session !== null ? this.derivedCache.get(session.id) : undefined;
654
+
655
+ if (
656
+ cached &&
657
+ cached.derivedForLiveDiff === liveDiff &&
658
+ sameDerivationInputs(cached.derivedFor, session!)
659
+ ) {
660
+ this.derivedFor = session;
661
+ this.derivedForLiveDiff = liveDiff;
662
+ this.derived = {
663
+ ...cached.derived,
664
+ tree: session!.history ? treeRows(session!.history) : [],
665
+ };
666
+ this.rememberDerived(session!, liveDiff, this.derived);
667
+
668
+ return;
669
+ }
670
+ this.derivedFor = session;
671
+ this.derivedForLiveDiff = liveDiff;
672
+ this.derived = this.buildDerived(session, frozenDiff, liveDiff);
673
+ if (session !== null) this.rememberDerived(session, liveDiff, this.derived);
674
+ }
675
+
676
+ /** Keep the freshest projections per thread, evicting the least-recently-used past the cap. */
677
+ private rememberDerived(
678
+ session: Thread,
679
+ liveDiff: LiveWorkingDiff | null,
680
+ derived: DerivedSessionProjection,
681
+ ): void {
682
+ this.derivedCache.delete(session.id);
683
+ this.derivedCache.set(session.id, {
684
+ derivedFor: session,
685
+ derivedForLiveDiff: liveDiff,
686
+ derived,
687
+ });
688
+ while (this.derivedCache.size > DERIVED_CACHE_LIMIT) {
689
+ const oldest = this.derivedCache.keys().next().value;
690
+
691
+ if (oldest === undefined) break;
692
+ this.derivedCache.delete(oldest);
693
+ }
694
+ }
695
+
696
+ /** The per-file contents that back the current rows: a diff thread's capture, else the live working tree. */
697
+ private foldFiles(): readonly DiffFileContents[] | undefined {
698
+ const session = this.snapshot.session;
699
+
700
+ return readsFrozenDiff(session) ? session!.artifact.files : this.liveDiff?.files;
701
+ }
702
+
703
+ treeRows(): TreeRow[] {
704
+ this.ensureDerived();
705
+
706
+ return this.derived.tree;
707
+ }
708
+
709
+ display(): DisplayBlock[] {
710
+ this.ensureDerived();
711
+
712
+ return this.derived.display;
713
+ }
714
+
715
+ rows(): DiffRow[] {
716
+ this.ensureDerived();
717
+ if (this.collapsedFiles.size === 0 && this.expandedFiles.size === 0) return this.derived.rows;
718
+
719
+ return applyFold(this.derived.rows, this.collapsedFiles, this.expandedFiles, this.foldFiles());
720
+ }
721
+
722
+ setFileCollapsed(file: string, collapsed: boolean): void {
723
+ if (collapsed) {
724
+ this.collapsedFiles.add(file);
725
+ this.expandedFiles.delete(file);
726
+ } else {
727
+ this.collapsedFiles.delete(file);
728
+ }
729
+ this.update({});
730
+ }
731
+
732
+ isFileCollapsed(file: string): boolean {
733
+ return this.collapsedFiles.has(file);
734
+ }
735
+
736
+ setFileExpanded(file: string, expanded: boolean): void {
737
+ if (expanded) {
738
+ this.expandedFiles.add(file);
739
+ this.collapsedFiles.delete(file);
740
+ } else {
741
+ this.expandedFiles.delete(file);
742
+ }
743
+ this.update({});
744
+ }
745
+
746
+ isFileExpanded(file: string): boolean {
747
+ return this.expandedFiles.has(file);
748
+ }
749
+
750
+ canExpandFile(file: string): boolean {
751
+ // a live working-tree diff carries the same per-file contents as a captured one,
752
+ // so a non-diff thread can expand its files too
753
+ return (this.foldFiles() ?? []).some((entry) => entry.path === file);
754
+ }
755
+
756
+ copyFilePath(file: string): void {
757
+ void copyToClipboard(file).then((copied) =>
758
+ this.setStatus(copied ? `copied ${file}` : "no clipboard tool available"),
759
+ );
760
+ }
761
+
762
+ fileStats(): Map<string, { additions: number; deletions: number }> {
763
+ this.ensureDerived();
764
+
765
+ return fileChangeCounts(this.derived.rows);
766
+ }
767
+
768
+ files(): WalkFile[] {
769
+ this.ensureDerived();
770
+
771
+ return this.derived.files;
772
+ }
773
+
774
+ working(): string {
775
+ const session = this.snapshot.session;
776
+
777
+ return session ? (session.workingCopy ?? session.artifact.content) : "";
778
+ }
779
+
780
+ async projectFiles(): Promise<string[]> {
781
+ const session = this.snapshot.session;
782
+ if (this.client?.projectFiles === undefined || !session) return [];
783
+
784
+ return this.client.projectFiles(session.id);
785
+ }
786
+
787
+ async readFile(path: string): Promise<string | null> {
788
+ const session = this.snapshot.session;
789
+ if (this.client?.fileContents === undefined || !session) return null;
790
+
791
+ return this.client.fileContents(session.id, path);
792
+ }
793
+
794
+ /** The repo the sidebar tree/changes point at: the thread's own repo, else the launch directory. */
795
+ private sidebarRepoRoot(): string {
796
+ return this.snapshot.session?.workspace.repoRoot || this.options.cwd || process.cwd();
797
+ }
798
+
799
+ async repoFiles(): Promise<string[]> {
800
+ if (this.client?.repoFiles === undefined) return [];
801
+
802
+ return this.client.repoFiles(this.sidebarRepoRoot());
803
+ }
804
+
805
+ async repoReadFile(path: string): Promise<string | null> {
806
+ if (this.client?.repoFileContents === undefined) return null;
807
+
808
+ return this.client.repoFileContents(this.sidebarRepoRoot(), path);
809
+ }
810
+
811
+ async repoChanges(): Promise<readonly DiffFileContents[]> {
812
+ // a plain diff review pins its captured snapshot; a workbench thread and every other thread reflect the live working tree
813
+ const session = this.snapshot.session;
814
+ if (readsFrozenDiff(session)) return session!.artifact.files ?? [];
815
+ // eager: capture the live working-tree diff so the Changes navigator and its file tabs render a real diff
816
+ if (this.client?.repoDiff !== undefined) {
817
+ const diff = await this.client.repoDiff(this.sidebarRepoRoot());
818
+ // a thread switch during the request would let this response overwrite the new thread's diff,
819
+ // showing changes from the wrong repo; compare the thread id, not the object, so an unrelated
820
+ // re-render that replaced the snapshot for the SAME thread does not drop its diff to "No changes"
821
+ if (this.snapshot.session?.id !== session?.id) return diff.files;
822
+ this.liveDiff = diff;
823
+ // rows() derive from the fresh patch; re-render so an open diff tab repaints
824
+ this.update({});
825
+
826
+ return diff.files;
827
+ }
828
+ // a peer without the live-diff capability still lists changes, just without a diff body
829
+ if (this.client?.repoChanges === undefined) return [];
830
+ const changes = await this.client.repoChanges(this.sidebarRepoRoot());
831
+
832
+ return changes.map((change) => ({
833
+ path: change.path,
834
+ status: change.status,
835
+ oldContents: "",
836
+ newContents: "",
837
+ }));
838
+ }
839
+
840
+ // Refreshes race the connection teardown: an event can arrive while close()
841
+ // is rejecting in-flight requests, and a fire-and-forget refresh must never
842
+ // surface that as an unhandled rejection.
843
+ private async refreshSession(id: string): Promise<void> {
844
+ try {
845
+ if (!this.client) return;
846
+ const session = await this.client.sessionGet(id);
847
+
848
+ // a rapid switch may have moved on during the fetch; never clobber the now-viewed thread
849
+ if (this.viewingId === session.id) this.update({ session });
850
+ } catch (cause) {
851
+ if (!this.closed) this.setStatus(cause instanceof Error ? cause.message : String(cause));
852
+ }
853
+ }
854
+
855
+ private async refreshInbox(): Promise<void> {
856
+ try {
857
+ if (this.client) this.update({ inbox: await this.client.sessionList({ status: "pending" }) });
858
+ } catch (cause) {
859
+ if (!this.closed) this.setStatus(cause instanceof Error ? cause.message : String(cause));
860
+ }
861
+ }
862
+
863
+ /** Optimistic apply: the daemon response is the next session snapshot. */
864
+ private apply(mutation: Promise<Thread>): void {
865
+ mutation
866
+ .then((session) => this.update({ session }))
867
+ .catch((cause: unknown) =>
868
+ this.setStatus(String(cause instanceof Error ? cause.message : cause)),
869
+ );
870
+ }
871
+
872
+ /**
873
+ * Show the expected result before the daemon answers, so a second keypress
874
+ * builds on the first instead of on the stale snapshot. Answers arrive in
875
+ * request order over the socket and replace the guess with the daemon's copy.
876
+ */
877
+ private applyOptimistic(expected: Thread, mutation: Promise<Thread>): void {
878
+ this.update({ session: expected });
879
+ mutation
880
+ .then((session) => this.update({ session }))
881
+ .catch((cause: unknown) => {
882
+ // a refused guess must not stay on screen: the daemon's record replaces it
883
+ this.setStatus(String(cause instanceof Error ? cause.message : cause));
884
+ void this.refreshSession(expected.id);
885
+ });
886
+ }
887
+
888
+ // ── primitives ───────────────────────────────────
889
+ open(id: string): void {
890
+ this.locallyViewed.clear();
891
+ this.viewingId = id;
892
+ const cached = this.snapshot.inbox?.find((candidate) => candidate.id === id);
893
+
894
+ // paint the sidebar copy at once for a snappy switch, then revalidate: the inbox
895
+ // copy trails the daemon for a live diff, whose session.updated refreshes the open
896
+ // thread but not the list, so a returned-to diff would otherwise show stale content
897
+ if (cached) this.update({ session: cached });
898
+ void this.refreshSession(id);
899
+ }
900
+
901
+ deleteSession(id: string): void {
902
+ if (this.readOnly) return this.setStatus("observer - read-only");
903
+ // a deleted thread's links must not outlive it; revoke every one first, best-effort, so an
904
+ // unreachable gateway never blocks the local delete (the blob's 30-day TTL is the backstop)
905
+ for (const link of this.linksFor(this.sessionRecord(id)))
906
+ void this.shareTransport.revoke(link.id).catch(() => {});
907
+ this.client
908
+ ?.sessionDelete(id)
909
+ .then(() => this.setStatus("thread deleted"))
910
+ .catch((cause: unknown) =>
911
+ this.setStatus(`delete failed: ${cause instanceof Error ? cause.message : String(cause)}`),
912
+ );
913
+ }
914
+
915
+ /** The record for a thread id, whether it is the open thread or a sidebar row. */
916
+ private sessionRecord(id: string): Thread | undefined {
917
+ if (this.snapshot.session?.id === id) return this.snapshot.session;
918
+
919
+ return this.snapshot.inbox?.find((candidate) => candidate.id === id);
920
+ }
921
+
922
+ /** A thread's share links, migrating a legacy single share; empty when never shared. */
923
+ private linksFor(session: Thread | null | undefined): ShareLink[] {
924
+ return session ? (threadShareLinks(session) ?? []) : [];
925
+ }
926
+
927
+ renameSession(id: string, title: string): void {
928
+ if (this.readOnly) return this.setStatus("observer - read-only");
929
+ this.client
930
+ ?.sessionSetTitle(id, title)
931
+ .then(() => this.setStatus("thread renamed"))
932
+ .catch((cause: unknown) =>
933
+ this.setStatus(`rename failed: ${cause instanceof Error ? cause.message : String(cause)}`),
934
+ );
935
+ }
936
+
937
+ setSelfName(name: string): void {
938
+ const session = this.snapshot.session;
939
+
940
+ if (!session) return;
941
+ this.apply(this.client!.sessionSetSelfName(session.id, name));
942
+ }
943
+
944
+ cut(displayIndex: number): void {
945
+ const session = this.snapshot.session;
946
+
947
+ if (!session || session.status === "resolved") return;
948
+ const block = this.display()[displayIndex];
949
+
950
+ if (!block) return;
951
+ const working = this.working();
952
+
953
+ if (block.type === "del") {
954
+ this.restoreDelBlock(block, displayIndex);
955
+ } else if (block.work) {
956
+ const workIndex = parseBlocks(working).findIndex(
957
+ (candidate) => candidate.lineStart === block.work!.lineStart,
958
+ );
959
+
960
+ if (workIndex === -1) return;
961
+ this.applyOptimistic(
962
+ { ...session, workingCopy: cutBlock(working, block.work) },
963
+ this.client!.sessionCutBlock(session.id, workIndex),
964
+ );
965
+ this.setStatus("block cut - it serializes into the diff");
966
+ }
967
+ }
968
+
969
+ /** Re-insert a cut plan block at the next surviving block's line (Cut toggle + rail undo). */
970
+ private restoreDelBlock(block: DisplayBlock, displayIndex: number): void {
971
+ const session = this.snapshot.session;
972
+
973
+ if (!session || !block.base) return;
974
+ const working = this.working();
975
+ const line = restoreLine(
976
+ nextWorkBlock(this.display(), displayIndex),
977
+ working.split("\n").length,
978
+ );
979
+ const base = session.artifact.content;
980
+ const baseIndex = parseBlocks(base).findIndex(
981
+ (candidate) => candidate.lineStart === block.base!.lineStart,
982
+ );
983
+
984
+ if (baseIndex === -1) return;
985
+ const expected: Thread = {
986
+ ...session,
987
+ workingCopy: restoreBlock(base, working, block.base, line),
988
+ };
989
+
990
+ if (expected.workingCopy === undefined) delete expected.workingCopy;
991
+ this.applyOptimistic(expected, this.client!.sessionRestoreBlock(session.id, baseIndex, line));
992
+ this.setStatus(REMOVAL_RESTORED_STATUS);
993
+ }
994
+
995
+ // ── diff hunk curation ──────────────────────
996
+ /** The parsed model and row for a curation action, or null with a status set. */
997
+ private curationRow(rowIndex: number): { row: DiffRow; model: FileDiffMetadata } | null {
998
+ const session = this.snapshot.session;
999
+
1000
+ if (!session || session.status === "resolved") return null;
1001
+ if (!session.artifact.files?.length) {
1002
+ this.setStatus("hunk curation needs full file contents (PR diffs cannot be curated)");
1003
+
1004
+ return null;
1005
+ }
1006
+ const row = this.rows()[rowIndex];
1007
+
1008
+ if (!row || row.kind === "file" || row.kind === "hunk") {
1009
+ this.setStatus("move to a code line to curate");
1010
+
1011
+ return null;
1012
+ }
1013
+ const model = this.fileModel(row.file);
1014
+
1015
+ if (!model) return null;
1016
+
1017
+ return { row, model };
1018
+ }
1019
+
1020
+ toggleRejectHunk(rowIndex: number): void {
1021
+ const located = this.curationRow(rowIndex);
1022
+
1023
+ if (!located) return;
1024
+ const target = hunkRejectionForRow(located.row.file, located.model, located.row);
1025
+
1026
+ if (!target) return this.setStatus("no hunk under the cursor");
1027
+ const wholeHunk = (rejection: HunkRejection): boolean => rejectsWholeHunk(rejection, target);
1028
+
1029
+ if (this.rejections.some(wholeHunk)) {
1030
+ this.curate(this.rejections.filter((rejection) => !wholeHunk(rejection)));
1031
+ this.setStatus("hunk restored");
1032
+ } else {
1033
+ // a whole-hunk reject supersedes any change-level rejects inside it
1034
+ const others = this.rejections.filter(
1035
+ (rejection) =>
1036
+ !(rejection.path === target.path && rejection.hunkIndex === target.hunkIndex),
1037
+ );
1038
+
1039
+ this.curate([...others, target]);
1040
+ this.setStatus("hunk rejected - dropped from the working copy");
1041
+ }
1042
+ }
1043
+
1044
+ toggleRejectChange(rowIndex: number): void {
1045
+ const located = this.curationRow(rowIndex);
1046
+
1047
+ if (!located) return;
1048
+ if (located.row.kind !== "add" && located.row.kind !== "del")
1049
+ return this.setStatus("move to a changed line to reject a change");
1050
+ const target = changeRejectionForRow(located.row.file, located.model, located.row);
1051
+
1052
+ if (!target) return this.setStatus("no change under the cursor");
1053
+ const wholeCovers = this.rejections.some((rejection) => rejectsWholeHunk(rejection, target));
1054
+
1055
+ if (wholeCovers) return this.setStatus("the whole hunk is rejected - restore it first");
1056
+ if (this.rejections.some((rejection) => sameRejection(rejection, target))) {
1057
+ this.curate(this.rejections.filter((rejection) => !sameRejection(rejection, target)));
1058
+ this.setStatus("change restored");
1059
+ } else {
1060
+ this.curate([...this.rejections, target]);
1061
+ this.setStatus("change rejected - dropped from the working copy");
1062
+ }
1063
+ }
1064
+
1065
+ /** Hand the daemon the full set of reject decisions; the working copy follows. */
1066
+ private curate(rejections: HunkRejection[]): void {
1067
+ const session = this.snapshot.session;
1068
+
1069
+ if (!session) return;
1070
+ const expected: Thread = { ...session, curation: rejections };
1071
+
1072
+ if (!rejections.length) delete expected.curation;
1073
+ this.applyOptimistic(expected, this.client!.sessionCurate(session.id, rejections));
1074
+ }
1075
+
1076
+ setShareAccess(githubLogins: string[]): void {
1077
+ if (this.readOnly) return this.setStatus("observer - read-only");
1078
+ // legacy single-allowlist entry point: apply it to the thread's primary link
1079
+ const primary = this.linksFor(this.snapshot.session)[0];
1080
+
1081
+ if (!primary) return;
1082
+ this.updateShareLink(primary.id, {
1083
+ name: primary.name,
1084
+ requireAuth: true,
1085
+ allowlist: githubLogins,
1086
+ });
1087
+ }
1088
+
1089
+ rejectedRows(): Set<number> {
1090
+ this.ensureDerived();
1091
+ if (!this.rejections.length) return EMPTY_REJECTED_ROWS;
1092
+ const rejected = new Set<number>();
1093
+
1094
+ this.derived.rows.forEach((row, index) => {
1095
+ const model = this.fileModel(row.file);
1096
+
1097
+ if (model && isRowRejected(row.file, model, row, this.rejections)) rejected.add(index);
1098
+ });
1099
+
1100
+ return rejected;
1101
+ }
1102
+
1103
+ curationItems(): CurationItem[] {
1104
+ this.ensureDerived();
1105
+ const session = this.snapshot.session;
1106
+
1107
+ if (!session) return EMPTY_CURATION_ITEMS;
1108
+
1109
+ return session.artifact.type === "diff" ? this.diffCurationItems() : this.planCurationItems();
1110
+ }
1111
+
1112
+ restoreCuration(id: string): void {
1113
+ // diff rejections drop from the reject list; a plan cut re-inserts its block
1114
+ if (id.startsWith("diff:")) {
1115
+ const kept = this.rejections.filter((rejection) => curationItemId(rejection) !== id);
1116
+
1117
+ if (kept.length === this.rejections.length) return;
1118
+ this.curate(kept);
1119
+ this.setStatus(REMOVAL_RESTORED_STATUS);
1120
+
1121
+ return;
1122
+ }
1123
+ const display = this.display();
1124
+ const displayIndex = display.findIndex(
1125
+ (block) => block.type === "del" && block.base && planCutId(block.base) === id,
1126
+ );
1127
+
1128
+ if (displayIndex !== -1) this.restoreDelBlock(display[displayIndex]!, displayIndex);
1129
+ }
1130
+
1131
+ /** The curated-out diff rejections as removal cards (newest decisions last). */
1132
+ private diffCurationItems(): CurationItem[] {
1133
+ if (!this.rejections.length) return EMPTY_CURATION_ITEMS;
1134
+ const items: CurationItem[] = [];
1135
+
1136
+ for (const rejection of this.rejections) {
1137
+ const rows = this.rowsForRejection(rejection);
1138
+ const firstRow = rows[0];
1139
+
1140
+ items.push({
1141
+ id: curationItemId(rejection),
1142
+ source: "diff",
1143
+ preview: rows.map(
1144
+ (row) => `${row.kind === "add" ? "+" : "-"} ${row.text.replace(/\n$/, "")}`,
1145
+ ),
1146
+ revealIndex: firstRow ? this.derived.rows.indexOf(firstRow) : 0,
1147
+ });
1148
+ }
1149
+
1150
+ return items;
1151
+ }
1152
+
1153
+ /** The cut plan blocks as removal cards, in document order. */
1154
+ private planCurationItems(): CurationItem[] {
1155
+ const items: CurationItem[] = [];
1156
+
1157
+ this.derived.display.forEach((block, displayIndex) => {
1158
+ if (block.type !== "del" || !block.base) return;
1159
+ items.push({
1160
+ id: planCutId(block.base),
1161
+ source: "plan",
1162
+ preview: block.base.text.split("\n"),
1163
+ revealIndex: displayIndex,
1164
+ });
1165
+ });
1166
+
1167
+ return items.length ? items : EMPTY_CURATION_ITEMS;
1168
+ }
1169
+
1170
+ /** The change/deletion rows a rejection covers, for its preview and reveal row. */
1171
+ private rowsForRejection(rejection: HunkRejection): DiffRow[] {
1172
+ const model = this.fileModel(rejection.path);
1173
+
1174
+ if (!model) return [];
1175
+ const rows: DiffRow[] = [];
1176
+
1177
+ for (const row of this.derived.rows) {
1178
+ if (row.file !== rejection.path || (row.kind !== "add" && row.kind !== "del")) continue;
1179
+ if (rejection.changeIndex === undefined) {
1180
+ const target = hunkRejectionForRow(rejection.path, model, row);
1181
+
1182
+ if (target && target.hunkIndex === rejection.hunkIndex) rows.push(row);
1183
+ } else {
1184
+ const target = changeRejectionForRow(rejection.path, model, row);
1185
+
1186
+ if (target && sameRejection(target, rejection)) rows.push(row);
1187
+ }
1188
+ }
1189
+
1190
+ return rows;
1191
+ }
1192
+
1193
+ edit(): void {
1194
+ const session = this.snapshot.session;
1195
+
1196
+ if (!session || session.status === "resolved") return;
1197
+ try {
1198
+ const result = editInEditor(this.working(), "plan.md", { editor: this.editor });
1199
+
1200
+ if (result.changed) {
1201
+ this.saveEditedBody(result.content);
1202
+ this.setStatus("edits tracked - one diff");
1203
+ } else this.setStatus("no changes");
1204
+ } catch (err) {
1205
+ this.setStatus(err instanceof Error ? err.message : String(err));
1206
+ }
1207
+ }
1208
+
1209
+ // no toast: leaving the inline editor is a quiet return to the read-only view
1210
+ saveEditedBody(content: string): void {
1211
+ const session = this.snapshot.session;
1212
+
1213
+ if (!session || session.status === "resolved") return;
1214
+ if (content === this.working()) return;
1215
+ this.setWorkingCopy(content);
1216
+ this.reconcileAnnotations(session, content);
1217
+ }
1218
+
1219
+ /**
1220
+ * Edit-exit reconciliation: re-resolve every annotation against the edited
1221
+ * working copy with the quote-primary cascade. Annotations that stop
1222
+ * resolving stay stored (the feedback serializer flags orphaned anchors);
1223
+ * the count feeds the one-line banner above the sheet.
1224
+ */
1225
+ private reconcileAnnotations(session: Thread, editedContent: string): void {
1226
+ const editedBlocks = parseBlocks(editedContent);
1227
+ const orphanCount = session.annotations.filter(
1228
+ (annotation) => resolveAnchor(annotation.anchor, editedBlocks) === null,
1229
+ ).length;
1230
+
1231
+ this.update({ editOrphanCount: orphanCount });
1232
+ }
1233
+
1234
+ annotate(
1235
+ kind: "comment",
1236
+ displayIndex: number,
1237
+ start: number,
1238
+ end: number,
1239
+ body: string,
1240
+ endDisplayIndex: number = displayIndex,
1241
+ target: AnnotationTarget = { kind: "artifact" },
1242
+ ): string | undefined {
1243
+ const session = this.snapshot.session;
1244
+
1245
+ if (!session) return undefined;
1246
+ let anchor;
1247
+ let resolvedTarget = target;
1248
+ // a file target (a Changes-panel diff note) and a diff artifact both anchor into the diff rows
1249
+ const onDiff = target.kind === "file" || session.artifact.type === "diff";
1250
+
1251
+ if (target.kind === "file") {
1252
+ // a Changes-panel note anchors within its own file's rows, so a quote never attaches across
1253
+ // files; a selection that spills into the next file is clamped back to the file it started in
1254
+ const rows = this.rows();
1255
+ const startRow = rows[displayIndex];
1256
+ const path = startRow?.file ?? "";
1257
+ const range = fileRowRange(rows, path);
1258
+ const base = range?.start ?? 0;
1259
+ const fileRows = range ? rows.slice(range.start, range.end) : rows;
1260
+ const lastInFile = fileRows.length - 1;
1261
+ const clamp = (index: number): number => Math.max(0, Math.min(index - base, lastInFile));
1262
+
1263
+ anchor = makeAnchor(
1264
+ diffRowBlocks(fileRows),
1265
+ clamp(displayIndex),
1266
+ start,
1267
+ end,
1268
+ clamp(endDisplayIndex),
1269
+ );
1270
+ resolvedTarget = { kind: "file", path, rev: startRow?.kind === "del" ? "head" : "worktree" };
1271
+ } else if (onDiff) {
1272
+ // rows are the diff's blocks: a span over one or more code rows anchors with the
1273
+ // same quote, context, and position selectors a plan span does
1274
+ anchor = makeAnchor(diffRowBlocks(this.rows()), displayIndex, start, end, endDisplayIndex);
1275
+ } else {
1276
+ const display = this.display();
1277
+ const workBlocks = display.filter((entry) => entry.work).map((entry) => entry.work!);
1278
+ const workIndexOf = (index: number): number =>
1279
+ display.slice(0, index + 1).filter((entry) => entry.work).length - 1;
1280
+ // the plan surface hands back rendered offsets (inline markers concealed); the quote is cut
1281
+ // from work text, so map the selection onto the work characters it covers first
1282
+ const work = renderedSpanToWork(display, displayIndex, endDisplayIndex, start, end);
1283
+
1284
+ anchor = makeAnchor(
1285
+ workBlocks,
1286
+ workIndexOf(displayIndex),
1287
+ work.start,
1288
+ work.end,
1289
+ workIndexOf(endDisplayIndex),
1290
+ );
1291
+ }
1292
+ // absent target means the reviewed artifact, so keep artifact notes free of the field
1293
+ const wire =
1294
+ resolvedTarget.kind === "artifact"
1295
+ ? { id: newAnnotationId(), kind, anchor, body }
1296
+ : { id: newAnnotationId(), kind, anchor, body, target: resolvedTarget };
1297
+ const persisted = this.client!.sessionComment(session.id, wire);
1298
+
1299
+ this.applyOptimistic(withAnnotationUpserted(session, wire), persisted);
1300
+ this.mirrorAnnotation(persisted, wire);
1301
+
1302
+ return wire.id;
1303
+ }
1304
+
1305
+ addComment(anchor: Anchor, target: AnnotationTarget, body: string): string | undefined {
1306
+ const session = this.snapshot.session;
1307
+
1308
+ if (!session) return undefined;
1309
+ const wire =
1310
+ target.kind === "artifact"
1311
+ ? { id: newAnnotationId(), kind: "comment", anchor, body }
1312
+ : { id: newAnnotationId(), kind: "comment", anchor, body, target };
1313
+ const persisted = this.client!.sessionComment(session.id, wire);
1314
+
1315
+ this.applyOptimistic(withAnnotationUpserted(session, wire), persisted);
1316
+ this.mirrorAnnotation(persisted, wire);
1317
+
1318
+ return wire.id;
1319
+ }
1320
+
1321
+ /** Find-or-create the per-repo workbench thread and adopt it as active; true once a session exists. */
1322
+ private async ensureWorkbenchSession(): Promise<boolean> {
1323
+ if (this.snapshot.session) return true;
1324
+ if (this.client?.sessionWorkbench === undefined) return false;
1325
+ let workbench;
1326
+
1327
+ try {
1328
+ workbench = await this.client.sessionWorkbench(this.options.cwd ?? process.cwd());
1329
+ } catch (cause) {
1330
+ // the composer already closed, so a lost first comment must at least surface, not vanish
1331
+ this.setStatus(String(cause instanceof Error ? cause.message : cause));
1332
+
1333
+ return false;
1334
+ }
1335
+ // adopt the thread as active (the shell flips to the thread view) and let the inbox catch up
1336
+ this.update({ session: workbench });
1337
+ void this.refreshInbox();
1338
+
1339
+ return true;
1340
+ }
1341
+
1342
+ async commentOnWorkbench(anchor: Anchor, target: AnnotationTarget, body: string): Promise<void> {
1343
+ if (!(await this.ensureWorkbenchSession())) return;
1344
+ this.addComment(anchor, target, body);
1345
+ }
1346
+
1347
+ /** A first comment on the bare-launch Changes diff: promote to the workbench thread, then anchor it in the diff rows. */
1348
+ async commentOnWorkbenchDiff(
1349
+ displayIndex: number,
1350
+ start: number,
1351
+ end: number,
1352
+ endDisplayIndex: number,
1353
+ body: string,
1354
+ ): Promise<void> {
1355
+ if (!(await this.ensureWorkbenchSession())) return;
1356
+ // annotate re-derives the file path and rev from the diff row it lands on
1357
+ this.annotate("comment", displayIndex, start, end, body, endDisplayIndex, {
1358
+ kind: "file",
1359
+ path: "",
1360
+ rev: "worktree",
1361
+ });
1362
+ }
1363
+
1364
+ reply(rootAnnotationId: string, body: string): string | undefined {
1365
+ const session = this.snapshot.session;
1366
+ const root = session?.annotations.find((annotation) => annotation.id === rootAnnotationId);
1367
+
1368
+ if (!session || !root) return undefined;
1369
+ // a reply to a reply still hangs off the discussion's root comment, and shares its target
1370
+ // so it renders and resolves on the same surface
1371
+ const base = {
1372
+ id: newAnnotationId(),
1373
+ kind: "comment",
1374
+ anchor: root.anchor,
1375
+ body,
1376
+ replyTo: root.replyTo ?? root.id,
1377
+ };
1378
+ const wire = root.target ? { ...base, target: root.target } : base;
1379
+ const persisted = this.client!.sessionComment(session.id, wire);
1380
+
1381
+ this.applyOptimistic(withAnnotationUpserted(session, wire), persisted);
1382
+ this.mirrorAnnotation(persisted, wire);
1383
+
1384
+ return wire.id;
1385
+ }
1386
+
1387
+ annotatePrototype(selector: string, quote: string, body: string): string | undefined {
1388
+ const session = this.snapshot.session;
1389
+
1390
+ if (!session) return undefined;
1391
+ const anchor = { quote, prefix: "", suffix: "", selector };
1392
+ const wire = { id: newAnnotationId(), kind: "comment", anchor, body };
1393
+ const persisted = this.client!.sessionComment(session.id, wire);
1394
+
1395
+ this.applyOptimistic(withAnnotationUpserted(session, wire), persisted);
1396
+ this.mirrorAnnotation(persisted, wire);
1397
+
1398
+ return wire.id;
1399
+ }
1400
+
1401
+ updateAnnotation(id: string, body: string): void {
1402
+ const session = this.snapshot.session;
1403
+
1404
+ if (!session) return;
1405
+ const existing = session.annotations.find((annotation) => annotation.id === id);
1406
+
1407
+ if (!existing) return;
1408
+ // the daemon's annotate primitive upserts by id: same id, anchor, and
1409
+ // reply link, new body
1410
+ const wire: Omit<Annotation, "createdAt"> = {
1411
+ id: existing.id,
1412
+ kind: existing.kind,
1413
+ anchor: existing.anchor,
1414
+ body,
1415
+ };
1416
+
1417
+ if (existing.replyTo !== undefined) wire.replyTo = existing.replyTo;
1418
+ const persisted = this.client!.sessionComment(session.id, wire);
1419
+
1420
+ this.applyOptimistic(withAnnotationUpserted(session, wire), persisted);
1421
+ this.mirrorAnnotation(persisted, wire);
1422
+ }
1423
+
1424
+ // push only after the local write lands, so a rejected write never leaks to the share
1425
+ private mirrorAnnotation(
1426
+ persisted: Promise<Thread>,
1427
+ annotation: Omit<Annotation, "createdAt">,
1428
+ ): void {
1429
+ const session = this.snapshot.session;
1430
+ const branch = session?.history?.branch;
1431
+ // each link follows one branch: a note lands on the links whose branch is the one being edited
1432
+ const links = this.linksFor(session).filter(
1433
+ (link) => branch === undefined || branch === (link.shareBranch ?? MAIN_BRANCH),
1434
+ );
1435
+
1436
+ if (links.length === 0) return;
1437
+ void persisted
1438
+ .then(() => Promise.all(links.map((link) => this.shareTransport.push(link.id, [annotation]))))
1439
+ .catch(() => {});
1440
+ }
1441
+
1442
+ removeAnnotation(id: string): void {
1443
+ const session = this.snapshot.session;
1444
+
1445
+ if (!session) return;
1446
+ this.apply(this.client!.sessionRemoveAnnotation(session.id, id));
1447
+ this.setStatus("annotation deleted");
1448
+ }
1449
+
1450
+ setWorkingCopy(content: string | undefined): void {
1451
+ const session = this.snapshot.session;
1452
+
1453
+ if (!session) return;
1454
+ this.apply(this.client!.sessionSetWorkingCopy(session.id, content));
1455
+ }
1456
+
1457
+ // ── the guided walk ─────────────────────────
1458
+ // Marks sent but possibly not yet reflected in the session snapshot; the
1459
+ // union keeps the walk title truthful and rapid advances from losing marks.
1460
+ private locallyViewed = new Set<string>();
1461
+
1462
+ private viewedSet(): Set<string> {
1463
+ return new Set([...(this.snapshot.session?.viewedPaths ?? []), ...this.locallyViewed]);
1464
+ }
1465
+
1466
+ walkStart(): void {
1467
+ const session = this.snapshot.session;
1468
+
1469
+ if (!session || session.artifact.type !== "diff") return;
1470
+ const files = this.files();
1471
+
1472
+ if (files.length === 0) return this.setStatus("nothing to walk - the diff is empty");
1473
+ // resume at the first unviewed file; a finished walk reopens on the end card
1474
+ this.update({ walk: { index: firstUnviewedIndex(files, this.viewedSet()) } });
1475
+ }
1476
+
1477
+ walkForward(): void {
1478
+ const walk = this.snapshot.walk;
1479
+ const session = this.snapshot.session;
1480
+
1481
+ if (!walk || !session) return;
1482
+ const files = this.files();
1483
+ const current = files[walk.index];
1484
+
1485
+ if (!current) return; // already on the end card
1486
+ // advancing IS the viewed mark: the step is complete once you move past
1487
+ // it; the daemon primitive merges, so only the new path travels
1488
+ if (!this.viewedSet().has(current.path)) {
1489
+ this.locallyViewed.add(current.path);
1490
+ this.apply(this.client!.sessionSetViewed(session.id, [current.path]));
1491
+ }
1492
+ this.update({ walk: { index: walk.index + 1 } });
1493
+ }
1494
+
1495
+ walkBack(): void {
1496
+ const walk = this.snapshot.walk;
1497
+
1498
+ if (!walk) return;
1499
+ this.update({ walk: { index: Math.max(0, walk.index - 1) } });
1500
+ }
1501
+
1502
+ walkLeave(): void {
1503
+ if (this.snapshot.walk) this.update({ walk: null });
1504
+ }
1505
+
1506
+ submit(message: MessageOutcome, summary: string): void {
1507
+ const session = this.snapshot.session;
1508
+
1509
+ if (!session) return;
1510
+ this.walkLeave();
1511
+ const actionBodies = Object.fromEntries(
1512
+ slashItemsFrom(this.quickActions).map((item) => [item.name, item.body]),
1513
+ );
1514
+ this.client!.sessionSendMessage(session.id, message, summary, actionBodies)
1515
+ .then((resolved) => {
1516
+ // The completion overlay heading already states the message, so the
1517
+ // status line stays empty here - only export/error messages fill it.
1518
+ this.update({ session: resolved, status: "" });
1519
+ // notes-vault export: guarded by each exporter's policy (default manual = no-op)
1520
+ for (const exporter of this.exporters) {
1521
+ if (!exporter.runsOn(message)) continue;
1522
+ void exporter.run(resolved).then((exportResult) => {
1523
+ this.setStatus(
1524
+ exportResult.success && exportResult.path
1525
+ ? `exported to ${exportResult.path}`
1526
+ : `export failed: ${exportResult.error ?? "unknown"}`,
1527
+ );
1528
+ });
1529
+ }
1530
+ // Hand the reviewer back to the agent. The default is a visible
1531
+ // countdown from DEFAULT_AUTO_CLOSE that closes on its own; esc stays,
1532
+ // a remembers the choice. A configured delay overrides; 0 closes now.
1533
+ const delay = this.autoClose;
1534
+
1535
+ if (delay === "off") this.startCounting(DEFAULT_AUTO_CLOSE);
1536
+ else if (delay === 0) this.finishReview();
1537
+ else this.startCounting(delay);
1538
+ })
1539
+ .catch((cause: unknown) =>
1540
+ this.setStatus(String(cause instanceof Error ? cause.message : cause)),
1541
+ );
1542
+ }
1543
+
1544
+ /** A workbench thread renders live locally; freeze its diff so a remote reviewer gets a stable snapshot. */
1545
+ private freezeForShare(session: Thread): Promise<Thread> {
1546
+ const repoDiff = this.client?.repoDiff;
1547
+
1548
+ return repoDiff
1549
+ ? snapshotWorkbench(session, (root) => repoDiff.call(this.client, root))
1550
+ : Promise.resolve(session);
1551
+ }
1552
+
1553
+ share(): void {
1554
+ this.createShareLink({ requireAuth: false, allowlist: [] });
1555
+ }
1556
+
1557
+ shareLinks(): ShareLink[] {
1558
+ return this.linksFor(this.snapshot.session);
1559
+ }
1560
+
1561
+ createShareLink(input: NewShareLink): void {
1562
+ if (this.readOnly) return this.setStatus("observer - read-only");
1563
+ const session = this.snapshot.session;
1564
+
1565
+ if (!session || !this.client) return;
1566
+ const client = this.client;
1567
+ const shareBranch = session.history?.branch ?? MAIN_BRANCH;
1568
+
1569
+ this.setStatus("sharing…");
1570
+ this.freezeForShare(session)
1571
+ .then((shared) => {
1572
+ // bake this link's access into its own blob: an allowlist gates it, absent = public
1573
+ const access = input.requireAuth ? { githubLogins: input.allowlist } : undefined;
1574
+
1575
+ return this.shareTransport.publish({ ...shared, access, shareBranch });
1576
+ })
1577
+ .then(async ({ line, copied }) => {
1578
+ const id = this.shareTransport.parseShareId(line);
1579
+
1580
+ if (!id) throw new Error("gateway returned no share id");
1581
+ const link: ShareLink = {
1582
+ id,
1583
+ name: input.name?.trim() || undefined,
1584
+ requireAuth: input.requireAuth,
1585
+ allowlist: input.requireAuth ? input.allowlist : [],
1586
+ shareBranch,
1587
+ };
1588
+
1589
+ await client.sessionSetShares(session.id, [...this.linksFor(this.snapshot.session), link]);
1590
+ this.setStatus("");
1591
+ this.showToast(line, copied ? "link copied" : "link created");
1592
+ })
1593
+ .catch((cause: unknown) =>
1594
+ this.setStatus(`share failed: ${cause instanceof Error ? cause.message : String(cause)}`),
1595
+ );
1596
+ }
1597
+
1598
+ updateShareLink(id: string, input: NewShareLink): void {
1599
+ if (this.readOnly) return this.setStatus("observer - read-only");
1600
+ const session = this.snapshot.session;
1601
+
1602
+ if (!session || !this.client) return;
1603
+ const links = this.linksFor(session);
1604
+
1605
+ if (!links.some((link) => link.id === id)) return;
1606
+ const allowlist = input.requireAuth ? input.allowlist : [];
1607
+ // re-push the link's access to its blob: an allowlist for private, "public" clears it
1608
+ void this.shareTransport
1609
+ .push(id, [], input.requireAuth ? { githubLogins: allowlist } : "public")
1610
+ .catch(() => {});
1611
+ const next = links.map((link) =>
1612
+ link.id === id
1613
+ ? {
1614
+ ...link,
1615
+ name: input.name?.trim() || undefined,
1616
+ requireAuth: input.requireAuth,
1617
+ allowlist,
1618
+ }
1619
+ : link,
1620
+ );
1621
+
1622
+ this.applyOptimistic(
1623
+ { ...session, shares: next },
1624
+ this.client.sessionSetShares(session.id, next),
1625
+ );
1626
+ this.setStatus("link updated");
1627
+ }
1628
+
1629
+ deleteShareLink(id: string): void {
1630
+ if (this.readOnly) return this.setStatus("observer - read-only");
1631
+ const session = this.snapshot.session;
1632
+
1633
+ if (!session || !this.client) return;
1634
+ const remaining = this.linksFor(session).filter((link) => link.id !== id);
1635
+
1636
+ void this.shareTransport.revoke(id).catch(() => {});
1637
+ this.applyOptimistic(
1638
+ { ...session, shares: remaining },
1639
+ this.client.sessionSetShares(session.id, remaining),
1640
+ );
1641
+ this.setStatus("link revoked");
1642
+ }
1643
+
1644
+ copyShareLink(id: string): void {
1645
+ const line = this.shareTransport.formatShareLine(id);
1646
+
1647
+ void copyToClipboard(line).then((copied) =>
1648
+ this.showToast(line, copied ? "link copied" : "link"),
1649
+ );
1650
+ }
1651
+
1652
+ /** Stop sharing the open thread: revoke every link so none of them resolve. */
1653
+ unshare(): void {
1654
+ if (this.readOnly) return this.setStatus("observer - read-only");
1655
+ const session = this.snapshot.session;
1656
+ const links = this.linksFor(session);
1657
+
1658
+ if (!session || links.length === 0) return this.setStatus("this thread is not shared");
1659
+ this.stopShareSync();
1660
+ void Promise.all(links.map((link) => this.shareTransport.revoke(link.id).catch(() => {})))
1661
+ .then(() => this.setStatus("sharing stopped"))
1662
+ .catch(() => {});
1663
+ void this.client?.sessionSetShares(session.id, []).catch(() => {});
1664
+ }
1665
+
1666
+ goToEntry(entryId: string, summary?: string): void {
1667
+ const session = this.snapshot.session;
1668
+
1669
+ if (!session?.history || !this.client) return;
1670
+ const target = entryTarget(session.history, entryId);
1671
+
1672
+ if (target === null) return this.setStatus("that entry is not on any branch");
1673
+ if (target.kind === "here") return this.setStatus("already at the tip");
1674
+ if (target.kind === "switch") {
1675
+ this.moveTree(session, switchBranch(session.history, target.branch), () =>
1676
+ this.client!.sessionSwitch(session.id, target.branch),
1677
+ );
1678
+ this.setStatus(`on branch ${target.branch}`);
1679
+
1680
+ return;
1681
+ }
1682
+ // an entry another branch reaches: the daemon stands on that branch first, in the same request
1683
+ const onBranch = switchBranch(session.history, target.branch);
1684
+ const options = summary === undefined || summary === "" ? {} : { summary };
1685
+ const moved = navigateTo(onBranch, entryId, options);
1686
+ const branch = target.branch === session.history.branch ? undefined : target.branch;
1687
+
1688
+ this.moveTree(session, moved, () =>
1689
+ this.client!.sessionNavigate(session.id, entryId, options.summary, branch),
1690
+ );
1691
+ this.setStatus(
1692
+ options.summary === undefined
1693
+ ? "moved back - later entries stay in the tree"
1694
+ : "moved back with a summary",
1695
+ );
1696
+ }
1697
+
1698
+ branch(name: string): void {
1699
+ const session = this.snapshot.session;
1700
+ const branchName = name.trim();
1701
+
1702
+ if (!session?.history || !this.client) return;
1703
+ if (!branchName) return this.setStatus("a branch needs a name");
1704
+ if (session.history.tips[branchName] !== undefined)
1705
+ return this.setStatus(`branch ${branchName} exists`);
1706
+ this.moveTree(session, createBranch(session.history, branchName), () =>
1707
+ this.client!.sessionBranch(session.id, branchName),
1708
+ );
1709
+ this.setStatus(`on branch ${branchName}`);
1710
+ }
1711
+
1712
+ labelTip(label: string): void {
1713
+ const session = this.snapshot.session;
1714
+ const name = label.trim();
1715
+
1716
+ if (!session?.history || !this.client) return;
1717
+ if (!name) return this.setStatus("a checkpoint needs a name");
1718
+ this.moveTree(session, labelTip(session.history, name), () =>
1719
+ this.client!.sessionLabel(session.id, name),
1720
+ );
1721
+ this.setStatus(`checkpoint ${name}`);
1722
+ }
1723
+
1724
+ fork(): void {
1725
+ const session = this.snapshot.session;
1726
+
1727
+ if (!session || !this.client) return;
1728
+ this.client
1729
+ .sessionFork(session.id)
1730
+ .then((fork) => {
1731
+ this.update({ session: fork });
1732
+ this.showToast(`forked ${session.id} - you are on the fork now`, "fork");
1733
+ })
1734
+ .catch((cause: unknown) =>
1735
+ this.setStatus(`fork failed: ${cause instanceof Error ? cause.message : String(cause)}`),
1736
+ );
1737
+ }
1738
+
1739
+ forkAndShare(): void {
1740
+ const session = this.snapshot.session;
1741
+
1742
+ if (!session || !this.client) return;
1743
+ const client = this.client;
1744
+
1745
+ this.setStatus("forking and sharing…");
1746
+ client
1747
+ .sessionFork(session.id)
1748
+ .then(async (fork) => {
1749
+ const shareBranch = fork.history?.branch ?? MAIN_BRANCH;
1750
+ const shared = await this.freezeForShare(fork);
1751
+ const { line, copied } = await this.shareTransport.publish({ ...shared, shareBranch });
1752
+ const id = this.shareTransport.parseShareId(line);
1753
+
1754
+ if (id)
1755
+ await client.sessionSetShares(fork.id, [
1756
+ { id, requireAuth: false, allowlist: [], shareBranch },
1757
+ ]);
1758
+ this.setStatus("");
1759
+ this.showToast(line, copied ? "fork shared - link copied" : "fork shared");
1760
+ })
1761
+ .catch((cause: unknown) =>
1762
+ this.setStatus(
1763
+ `fork and share failed: ${cause instanceof Error ? cause.message : String(cause)}`,
1764
+ ),
1765
+ );
1766
+ }
1767
+
1768
+ /**
1769
+ * Show a moved tree at once - the record re-derived from its new path - and
1770
+ * let the daemon's answer replace it. A refused move surfaces as status.
1771
+ */
1772
+ private moveTree(session: Thread, history: SessionHistory, request: () => Promise<Thread>): void {
1773
+ const expected: Thread = { ...session, history };
1774
+
1775
+ applyPathView(
1776
+ expected,
1777
+ viewOfPath(history, [...session.annotations, ...(session.shelvedAnnotations ?? [])]),
1778
+ );
1779
+ this.applyOptimistic(expected, request());
1780
+ }
1781
+
1782
+ /**
1783
+ * Pull collaborator notes for a shared plan and union them in. The daemon's
1784
+ * merge emits session.updated, so the re-render happens through the normal
1785
+ * event path. Best-effort: a failed refresh is silent.
1786
+ */
1787
+ pullShared(): Promise<void> {
1788
+ const links = this.linksFor(this.snapshot.session);
1789
+
1790
+ if (links.length === 0) return Promise.resolve();
1791
+
1792
+ // pull every link's blob and union its collaborator notes back in
1793
+ return Promise.all(
1794
+ links.map((link) =>
1795
+ this.shareTransport
1796
+ .pull(link.id)
1797
+ .then((remote) => this.mergeShared(remote))
1798
+ .catch(() => {}),
1799
+ ),
1800
+ ).then(() => {});
1801
+ }
1802
+
1803
+ private mergeShared(remote: Thread): Promise<void> {
1804
+ const session = this.snapshot.session;
1805
+
1806
+ if (!session || !this.client) return Promise.resolve();
1807
+
1808
+ return this.client
1809
+ .sessionMergeShared(session.id, this.shareTransport.mergeFromShare(remote))
1810
+ .then(() => {})
1811
+ .catch(() => {});
1812
+ }
1813
+
1814
+ /**
1815
+ * Follow the thread's shares live while it is open. To bound idle cost at one
1816
+ * connection per open thread (not one per link), a single watch stream follows
1817
+ * the primary link for instant updates, while a pull on each (re)connect
1818
+ * catches up every link's collaborator notes. A dropped link reconnects with
1819
+ * backoff. Returns a stop handle the caller runs on leave.
1820
+ */
1821
+ startShareSync(): () => void {
1822
+ this.stopShareSync();
1823
+ // per-run token so a stale run's close never re-arms a newer run
1824
+ const run = {};
1825
+ let delay = SHARE_RECONNECT_MIN_MS;
1826
+
1827
+ this.shareRun = run;
1828
+ const connect = (): void => {
1829
+ const shareId = this.linksFor(this.snapshot.session)[0]?.id;
1830
+
1831
+ if (this.shareRun !== run || this.closed || !shareId) return;
1832
+ void this.pullShared();
1833
+ this.shareStop = this.shareTransport.watch(shareId, {
1834
+ onSession: (remote) => {
1835
+ delay = SHARE_RECONNECT_MIN_MS;
1836
+ void this.mergeShared(remote);
1837
+ },
1838
+ onClose: () => {
1839
+ if (this.shareRun !== run || this.closed) return;
1840
+ this.shareStop = null;
1841
+ this.shareReconnect = this.clock.setTimeout(connect, delay);
1842
+ delay = Math.min(delay * 2, SHARE_RECONNECT_MAX_MS);
1843
+ },
1844
+ });
1845
+ };
1846
+
1847
+ connect();
1848
+
1849
+ return () => {
1850
+ if (this.shareRun === run) this.stopShareSync();
1851
+ };
1852
+ }
1853
+
1854
+ private stopShareSync(): void {
1855
+ this.shareRun = null;
1856
+ if (this.shareReconnect !== undefined) this.clock.clearTimeout(this.shareReconnect);
1857
+ this.shareReconnect = undefined;
1858
+ this.shareStop?.();
1859
+ this.shareStop = null;
1860
+ }
1861
+
1862
+ // ── completion hand-back ────────────────────
1863
+ private startCounting(remaining: number): void {
1864
+ if (remaining <= 0) return this.finishReview();
1865
+ this.update({ completion: { phase: "counting", remaining } });
1866
+ this.countdown = this.clock.setTimeout(() => this.startCounting(remaining - 1), 1000);
1867
+ }
1868
+
1869
+ finishReview(): void {
1870
+ this.clearCountdown();
1871
+ const herdr = detectHerdr();
1872
+ const pane = returnPaneFor(this.snapshot.session?.artifact.meta.herdrPane);
1873
+
1874
+ if (herdr && pane) focusHerdrPane(herdr.binPath, pane);
1875
+ this.options.onExit?.(0);
1876
+ }
1877
+
1878
+ dismissCompletion(): void {
1879
+ this.clearCountdown();
1880
+ this.update({ completion: { phase: "dismissed" } });
1881
+ }
1882
+
1883
+ optInAutoClose(): void {
1884
+ // Remember the default countdown for future submits, persisted to the user
1885
+ // config. The countdown is already running; this only makes it the default.
1886
+ try {
1887
+ persistAutoClose(DEFAULT_AUTO_CLOSE);
1888
+ } catch {
1889
+ // a read-only config dir must not block closing the review
1890
+ }
1891
+ this.autoClose = DEFAULT_AUTO_CLOSE;
1892
+ }
1893
+ }