@cueloop/client 0.1.0-alpha.9 → 0.1.0-alpha.90

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