@cueloop/client 0.1.0-alpha.10 → 0.1.0-alpha.100

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