@cueloop/client 0.1.0-alpha.11 → 0.1.0-alpha.111

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 (360) 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 +63 -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 +383 -0
  12. package/src/annotations/components/DiscussionMarkerRail.stories.tsx +54 -0
  13. package/src/annotations/components/DiscussionMarkerRail.tsx +189 -0
  14. package/src/annotations/discussions.ts +78 -0
  15. package/src/annotations/thread-selection.test.ts +210 -0
  16. package/src/annotations/thread-selection.ts +248 -0
  17. package/src/annotations/use-annotation-surface.tsx +1378 -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 +190 -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.harness-settings.test.tsx +77 -0
  25. package/src/app/App.identity.test.tsx +84 -0
  26. package/src/app/App.plan-render.test.tsx +211 -0
  27. package/src/app/App.plan-review.test.tsx +429 -0
  28. package/src/app/App.prototype-markdown.test.tsx +129 -0
  29. package/src/app/App.prototype.test.tsx +176 -0
  30. package/src/app/App.readonly.test.tsx +274 -0
  31. package/src/app/App.regression.test.tsx +99 -0
  32. package/src/app/App.rendering.test.tsx +134 -0
  33. package/src/app/App.share-dialog.test.tsx +177 -0
  34. package/src/app/App.submit-confirm.test.tsx +267 -0
  35. package/src/app/App.test.tsx +497 -0
  36. package/src/app/App.thread-agent.test.ts +20 -0
  37. package/src/app/App.toast.test.tsx +124 -0
  38. package/src/app/App.tsx +1758 -0
  39. package/src/app/App.visual.test.tsx +60 -0
  40. package/src/app/App.walk.test.tsx +300 -0
  41. package/src/app/App.workbench.test.tsx +1153 -0
  42. package/src/app/app-key-state.ts +61 -0
  43. package/src/app/app-screens.tsx +607 -0
  44. package/src/app/app-view-model.ts +178 -0
  45. package/src/app/components/AppHeader.stories.tsx +50 -0
  46. package/src/app/components/AppHeader.tsx +81 -0
  47. package/src/app/components/AppShell.brand.test.tsx +58 -0
  48. package/src/app/components/AppShell.extensions.test.tsx +191 -0
  49. package/src/app/components/AppShell.stories.tsx +89 -0
  50. package/src/app/components/AppShell.tsx +358 -0
  51. package/src/app/components/AppShell.zoom.test.tsx +149 -0
  52. package/src/app/components/Breadcrumb.stories.tsx +19 -0
  53. package/src/app/components/Breadcrumb.tsx +45 -0
  54. package/src/app/components/MenuBar.stories.tsx +28 -0
  55. package/src/app/components/MenuBar.tsx +44 -0
  56. package/src/app/components/PaneGrid.stories.tsx +84 -0
  57. package/src/app/components/PaneGrid.tsx +128 -0
  58. package/src/app/components/PanelColumn.stories.tsx +25 -0
  59. package/src/app/components/PanelColumn.tsx +93 -0
  60. package/src/app/components/ShellHeader.stories.tsx +50 -0
  61. package/src/app/components/ShellHeader.tsx +137 -0
  62. package/src/app/components/WorkspacePanels.stories.tsx +36 -0
  63. package/src/app/components/WorkspacePanels.tsx +121 -0
  64. package/src/app/components/pages/Workspace.stories.tsx +181 -0
  65. package/src/app/intent-dispatch.test.ts +729 -0
  66. package/src/app/intent-dispatch.ts +713 -0
  67. package/src/app/launch-layout.test.ts +78 -0
  68. package/src/app/launch-layout.ts +57 -0
  69. package/src/app/ready-signal.test.ts +85 -0
  70. package/src/app/ready-signal.ts +54 -0
  71. package/src/app/run.ts +111 -0
  72. package/src/{serve.test.ts → app/serve.test.ts} +28 -12
  73. package/src/app/serve.ts +111 -0
  74. package/src/app/version.ts +5 -0
  75. package/src/appearance/components/theme-context.stories.tsx +46 -0
  76. package/src/appearance/components/theme-context.tsx +37 -0
  77. package/src/appearance/theme-presets.test.ts +51 -0
  78. package/src/appearance/theme-presets.ts +219 -0
  79. package/src/appearance/theme.ts +112 -0
  80. package/src/appearance/visual/contrast.test.ts +35 -0
  81. package/src/appearance/visual/contrast.ts +33 -0
  82. package/src/diff/components/AnnotatableFileView.stories.tsx +42 -0
  83. package/src/diff/components/AnnotatableFileView.test.tsx +160 -0
  84. package/src/diff/components/AnnotatableFileView.tsx +142 -0
  85. package/src/diff/components/BareWorkbenchFileView.stories.tsx +27 -0
  86. package/src/diff/components/BareWorkbenchFileView.tsx +63 -0
  87. package/src/diff/components/DiffContentView.scroll.test.tsx +443 -0
  88. package/src/diff/components/DiffContentView.split.test.tsx +140 -0
  89. package/src/diff/components/DiffContentView.stories.tsx +80 -0
  90. package/src/diff/components/DiffContentView.syntax.test.tsx +85 -0
  91. package/src/diff/components/DiffContentView.tsx +1080 -0
  92. package/src/diff/components/WalkWizard.stories.tsx +100 -0
  93. package/src/diff/components/WalkWizard.tsx +146 -0
  94. package/src/diff/components/diff-content-view-layout.test.ts +198 -0
  95. package/src/diff/components/diff-content-view-layout.ts +87 -0
  96. package/src/diff/diff-fold.test.ts +78 -0
  97. package/src/diff/diff-fold.ts +130 -0
  98. package/src/diff/diff-hunk-curate.test.ts +315 -0
  99. package/src/diff/diff-hunk-curate.ts +155 -0
  100. package/src/diff/diff-intraline.test.ts +239 -0
  101. package/src/diff/diff-intraline.ts +244 -0
  102. package/src/diff/diff-syntax.test.ts +125 -0
  103. package/src/diff/diff-syntax.ts +194 -0
  104. package/src/diff/split-diff.test.ts +110 -0
  105. package/src/diff/split-diff.ts +150 -0
  106. package/src/diff/view-diff.test.ts +325 -0
  107. package/src/diff/view-diff.ts +540 -0
  108. package/src/diff/walk.test.ts +121 -0
  109. package/src/diff/walk.ts +76 -0
  110. package/src/index.ts +32 -2
  111. package/src/integrations/attribution.test.ts +31 -0
  112. package/src/integrations/attribution.ts +44 -0
  113. package/src/integrations/client-extension-registry.test.tsx +61 -0
  114. package/src/integrations/client-extension-registry.ts +163 -0
  115. package/src/integrations/clipboard.test.ts +23 -0
  116. package/src/integrations/clipboard.ts +34 -0
  117. package/src/integrations/components/ExtensionZone.stories.tsx +28 -0
  118. package/src/integrations/components/ExtensionZone.tsx +145 -0
  119. package/src/integrations/components/ShareDialog.agent.test.tsx +52 -0
  120. package/src/integrations/components/ShareDialog.stories.tsx +121 -0
  121. package/src/integrations/components/ShareDialog.tsx +602 -0
  122. package/src/integrations/components/share-dialog-store.ts +59 -0
  123. package/src/integrations/editor.test.ts +149 -0
  124. package/src/integrations/editor.ts +163 -0
  125. package/src/integrations/github-identity.test.ts +59 -0
  126. package/src/integrations/github-identity.ts +42 -0
  127. package/src/integrations/herdr.test.ts +43 -0
  128. package/src/integrations/herdr.ts +40 -0
  129. package/src/integrations/integrations.test.ts +41 -0
  130. package/src/integrations/integrations.ts +32 -0
  131. package/src/integrations/pasted-image.test.ts +67 -0
  132. package/src/integrations/pasted-image.ts +62 -0
  133. package/src/integrations/share.ts +283 -0
  134. package/src/keyboard/components/CompletionOverlay.stories.tsx +37 -0
  135. package/src/keyboard/components/CompletionOverlay.tsx +75 -0
  136. package/src/keyboard/components/HandleChipsInput.stories.tsx +24 -0
  137. package/src/keyboard/components/HandleChipsInput.test.tsx +35 -0
  138. package/src/keyboard/components/HandleChipsInput.tsx +147 -0
  139. package/src/keyboard/components/KeybindsDialog.stories.tsx +31 -0
  140. package/src/keyboard/components/KeybindsDialog.tsx +103 -0
  141. package/src/keyboard/components/NavModeHint.stories.tsx +40 -0
  142. package/src/keyboard/components/NavModeHint.tsx +31 -0
  143. package/src/keyboard/components/SlashComposer.stories.tsx +37 -0
  144. package/src/keyboard/components/SlashComposer.tsx +90 -0
  145. package/src/keyboard/key-bindings.test.ts +156 -0
  146. package/src/keyboard/key-bindings.ts +462 -0
  147. package/src/keyboard/keymap.test.ts +611 -0
  148. package/src/keyboard/keymap.ts +446 -0
  149. package/src/keyboard/skills.test.ts +74 -0
  150. package/src/keyboard/skills.ts +77 -0
  151. package/src/keyboard/slash-palette.test.ts +103 -0
  152. package/src/keyboard/slash-palette.ts +137 -0
  153. package/src/keyboard/thread-chords.test.ts +79 -0
  154. package/src/keyboard/thread-chords.ts +168 -0
  155. package/src/keyboard/use-shared-keyboard.ts +56 -0
  156. package/src/markdown/__snapshots__/view-plan.regression.test.ts.snap +100 -0
  157. package/src/markdown/components/MarkdownGridBlock.stories.tsx +33 -0
  158. package/src/markdown/components/MarkdownGridBlock.tsx +72 -0
  159. package/src/markdown/components/MarkdownThreadEditor.stories.tsx +15 -0
  160. package/src/markdown/components/MarkdownThreadEditor.test.tsx +98 -0
  161. package/src/markdown/components/MarkdownThreadEditor.tsx +165 -0
  162. package/src/markdown/components/ThreadView.selection.test.tsx +954 -0
  163. package/src/markdown/components/ThreadView.slash.test.tsx +146 -0
  164. package/src/markdown/components/ThreadView.stories.tsx +26 -0
  165. package/src/markdown/components/ThreadView.tsx +577 -0
  166. package/src/markdown/mark-runs.ts +125 -0
  167. package/src/markdown/markdown-editor-syntax-style.ts +66 -0
  168. package/src/markdown/markdown-grid.test.ts +101 -0
  169. package/src/markdown/markdown-grid.ts +209 -0
  170. package/src/markdown/markdown-highlight.test.ts +61 -0
  171. package/src/markdown/markdown-highlight.ts +125 -0
  172. package/src/markdown/thread-code-syntax.ts +48 -0
  173. package/src/markdown/use-thread-body-editing.tsx +54 -0
  174. package/src/markdown/view-plan.regression.test.ts +60 -0
  175. package/src/markdown/view-plan.test.ts +545 -0
  176. package/src/markdown/view-plan.ts +1061 -0
  177. package/src/performance/otlp-trace.test.ts +119 -0
  178. package/src/performance/otlp-trace.ts +134 -0
  179. package/src/performance/perf-report.ts +19 -0
  180. package/src/performance/perf-timings.test.ts +18 -0
  181. package/src/performance/perf-timings.ts +40 -0
  182. package/src/prototype/components/PrototypeContentView.stories.tsx +19 -0
  183. package/src/prototype/components/PrototypeContentView.tsx +459 -0
  184. package/src/prototype/prototype-browser.test.ts +81 -0
  185. package/src/prototype/prototype-browser.ts +332 -0
  186. package/src/prototype/prototype-pixels.tsx +35 -0
  187. package/src/settings/components/SettingsDialog.stories.tsx +117 -0
  188. package/src/settings/components/SettingsDialog.tsx +186 -0
  189. package/src/settings/components/SettingsRows.stories.tsx +18 -0
  190. package/src/settings/components/SettingsRows.tsx +112 -0
  191. package/src/settings/components/quick-actions-editor.stories.tsx +58 -0
  192. package/src/settings/components/quick-actions-editor.test.tsx +120 -0
  193. package/src/settings/components/quick-actions-editor.tsx +222 -0
  194. package/src/settings/config-identity.test.ts +78 -0
  195. package/src/settings/config.test.ts +771 -0
  196. package/src/settings/config.ts +722 -0
  197. package/src/settings/use-settings-dialog.test.tsx +172 -0
  198. package/src/settings/use-settings-dialog.tsx +465 -0
  199. package/src/settings/use-thread-harness-setting.test.tsx +87 -0
  200. package/src/settings/use-thread-harness-setting.ts +86 -0
  201. package/src/stories/__snapshots__/stories.test.tsx.snap +2358 -0
  202. package/src/stories/stories-app.tsx +196 -0
  203. package/src/stories/stories.test.tsx +78 -0
  204. package/src/stories/story-fixtures.ts +102 -0
  205. package/src/stories/story-tree.test.ts +108 -0
  206. package/src/stories/story.ts +160 -0
  207. package/src/terminal/ansi-screen.test.ts +28 -0
  208. package/src/terminal/ansi-screen.ts +77 -0
  209. package/src/terminal/components/AnsiScreen.stories.tsx +12 -0
  210. package/src/terminal/components/AnsiScreen.tsx +28 -0
  211. package/src/terminal/components/terminal-pane.test.tsx +40 -0
  212. package/src/terminal/components/terminal-pane.ts +208 -0
  213. package/src/terminal/ghostty-terminal.test.ts +85 -0
  214. package/src/terminal/ghostty-terminal.ts +207 -0
  215. package/src/terminal/kitty-image.test.ts +66 -0
  216. package/src/terminal/kitty-image.ts +140 -0
  217. package/src/terminal/pty.test.ts +81 -0
  218. package/src/terminal/pty.ts +255 -0
  219. package/src/testing/test-support.test.ts +266 -0
  220. package/src/testing/test-support.ts +449 -0
  221. package/src/thread/agent-continuation.test.ts +34 -0
  222. package/src/thread/agent-continuation.ts +13 -0
  223. package/src/thread/agent-transcript.test.ts +161 -0
  224. package/src/thread/agent-transcript.ts +344 -0
  225. package/src/thread/components/AgentConfigControls.stories.tsx +39 -0
  226. package/src/thread/components/AgentConfigControls.test.tsx +153 -0
  227. package/src/thread/components/AgentConfigControls.tsx +121 -0
  228. package/src/thread/components/AgentThreadPane.stories.tsx +105 -0
  229. package/src/thread/components/AgentThreadPane.test.tsx +1248 -0
  230. package/src/thread/components/AgentThreadPane.tsx +458 -0
  231. package/src/thread/components/ThreadFooter.stories.tsx +30 -0
  232. package/src/thread/components/ThreadFooter.test.tsx +49 -0
  233. package/src/thread/components/ThreadFooter.tsx +77 -0
  234. package/src/thread/components/ThreadTree.stories.tsx +46 -0
  235. package/src/thread/components/ThreadTree.test.tsx +41 -0
  236. package/src/thread/components/ThreadTree.tsx +268 -0
  237. package/src/thread/components/thread-tree.test.ts +138 -0
  238. package/src/thread/components/thread-tree.ts +112 -0
  239. package/src/thread/thread-controller.curate.test.ts +504 -0
  240. package/src/thread/thread-controller.derivation.test.ts +62 -0
  241. package/src/thread/thread-controller.live-diff.test.ts +357 -0
  242. package/src/thread/thread-controller.optimistic.test.ts +69 -0
  243. package/src/thread/thread-controller.share.test.ts +618 -0
  244. package/src/thread/thread-controller.switch-cache.test.ts +174 -0
  245. package/src/thread/thread-controller.tree.test.ts +263 -0
  246. package/src/thread/thread-controller.ts +2151 -0
  247. package/src/thread/tree-view.test.ts +128 -0
  248. package/src/thread/tree-view.ts +150 -0
  249. package/src/thread/use-thread-agent.test.tsx +209 -0
  250. package/src/thread/use-thread-agent.ts +122 -0
  251. package/src/ui/components/CodeBlock.stories.tsx +42 -0
  252. package/src/ui/components/CodeBlock.tsx +82 -0
  253. package/src/ui/components/ConfirmCard.stories.tsx +37 -0
  254. package/src/ui/components/ConfirmCard.tsx +151 -0
  255. package/src/ui/components/ConfirmDialog.stories.tsx +21 -0
  256. package/src/ui/components/ConfirmDialog.tsx +72 -0
  257. package/src/ui/components/OverlayScrollbar.stories.tsx +33 -0
  258. package/src/ui/components/OverlayScrollbar.test.tsx +142 -0
  259. package/src/ui/components/OverlayScrollbar.tsx +134 -0
  260. package/src/ui/components/PromptDialog.stories.tsx +36 -0
  261. package/src/ui/components/PromptDialog.test.tsx +65 -0
  262. package/src/ui/components/PromptDialog.tsx +101 -0
  263. package/src/ui/components/RootOverlay.stories.tsx +45 -0
  264. package/src/ui/components/RootOverlay.tsx +50 -0
  265. package/src/ui/components/ScrollArea.stories.tsx +20 -0
  266. package/src/ui/components/ScrollArea.tsx +63 -0
  267. package/src/ui/components/Toast.stories.tsx +19 -0
  268. package/src/ui/components/Toast.tsx +54 -0
  269. package/src/ui/components/Tooltip.stories.tsx +26 -0
  270. package/src/ui/components/Tooltip.tsx +93 -0
  271. package/src/ui/components/menu-control.stories.tsx +35 -0
  272. package/src/ui/components/menu-control.tsx +43 -0
  273. package/src/ui/components/primitives/Button.stories.tsx +32 -0
  274. package/src/ui/components/primitives/Button.tsx +58 -0
  275. package/src/ui/components/primitives/Card.stories.tsx +25 -0
  276. package/src/ui/components/primitives/Card.tsx +62 -0
  277. package/src/ui/components/primitives/Dialog.stories.tsx +24 -0
  278. package/src/ui/components/primitives/Dialog.test.tsx +38 -0
  279. package/src/ui/components/primitives/Dialog.tsx +69 -0
  280. package/src/ui/components/primitives/DialogActions.stories.tsx +20 -0
  281. package/src/ui/components/primitives/DialogActions.tsx +39 -0
  282. package/src/ui/components/primitives/IconButton.stories.tsx +36 -0
  283. package/src/ui/components/primitives/IconButton.tsx +58 -0
  284. package/src/ui/components/primitives/StatusBar.stories.tsx +11 -0
  285. package/src/ui/components/primitives/StatusBar.tsx +23 -0
  286. package/src/ui/components/primitives/Switch.stories.tsx +17 -0
  287. package/src/ui/components/primitives/Switch.tsx +32 -0
  288. package/src/ui/components/primitives/Tabs.stories.tsx +29 -0
  289. package/src/ui/components/primitives/Tabs.tsx +102 -0
  290. package/src/ui/components/primitives/Toolbar.stories.tsx +17 -0
  291. package/src/ui/components/primitives/Toolbar.tsx +14 -0
  292. package/src/ui/components/primitives/Tree.stories.tsx +124 -0
  293. package/src/ui/components/primitives/Tree.tsx +137 -0
  294. package/src/ui/components/primitives/frame.test.ts +12 -0
  295. package/src/ui/components/primitives/frame.ts +17 -0
  296. package/src/ui/components/primitives/icons.ts +61 -0
  297. package/src/ui/components/primitives/tree-model.test.ts +99 -0
  298. package/src/ui/components/primitives/tree-model.ts +144 -0
  299. package/src/ui/components/syntax-highlight.ts +154 -0
  300. package/src/ui/components/truncate-text.ts +7 -0
  301. package/src/ui/components/truncate-title.test.ts +31 -0
  302. package/src/ui/components/truncate-title.ts +16 -0
  303. package/src/ui/use-frame-measure.ts +88 -0
  304. package/src/ui/use-terminal-virtualizer.ts +286 -0
  305. package/src/workbench/components/ChangesColumn.stories.tsx +44 -0
  306. package/src/workbench/components/ChangesColumn.tsx +210 -0
  307. package/src/workbench/components/ChangesFileTree.test.tsx +184 -0
  308. package/src/workbench/components/EditorGrid.split.test.tsx +119 -0
  309. package/src/workbench/components/EditorGrid.stories.tsx +86 -0
  310. package/src/workbench/components/EditorGrid.tabs.test.tsx +118 -0
  311. package/src/workbench/components/EditorGrid.tsx +552 -0
  312. package/src/workbench/components/EditorGrid.zoom.test.tsx +132 -0
  313. package/src/workbench/components/FileContentsView.stories.tsx +16 -0
  314. package/src/workbench/components/FileContentsView.test.tsx +29 -0
  315. package/src/workbench/components/FileContentsView.tsx +104 -0
  316. package/src/workbench/components/GridTabContent.actions.test.tsx +151 -0
  317. package/src/workbench/components/GridTabContent.stories.tsx +59 -0
  318. package/src/workbench/components/GridTabContent.tsx +195 -0
  319. package/src/workbench/components/ProjectTreeView.stories.tsx +25 -0
  320. package/src/workbench/components/ProjectTreeView.test.tsx +239 -0
  321. package/src/workbench/components/ProjectTreeView.tsx +159 -0
  322. package/src/workbench/components/TreePane.stories.tsx +106 -0
  323. package/src/workbench/components/TreePane.tsx +157 -0
  324. package/src/workbench/components/WelcomePlayground.stories.tsx +12 -0
  325. package/src/workbench/components/WelcomePlayground.test.tsx +83 -0
  326. package/src/workbench/components/WelcomePlayground.tsx +138 -0
  327. package/src/workbench/components/editor-grid.test.ts +184 -0
  328. package/src/workbench/components/editor-grid.ts +284 -0
  329. package/src/workbench/components/file-tree.test.ts +60 -0
  330. package/src/workbench/components/file-tree.ts +114 -0
  331. package/src/workbench/use-changes-workbench.ts +210 -0
  332. package/src/workbench/use-remember-layout.ts +33 -0
  333. package/src/workbench/use-repo-changes.ts +93 -0
  334. package/src/workbench/workbench-snapshot.test.ts +99 -0
  335. package/src/workbench/workbench-snapshot.ts +59 -0
  336. package/src/App.diff.test.tsx +0 -99
  337. package/src/App.export.test.tsx +0 -88
  338. package/src/App.plan-review.test.tsx +0 -259
  339. package/src/App.readonly.test.tsx +0 -148
  340. package/src/App.rendering.test.tsx +0 -108
  341. package/src/App.submit-confirm.test.tsx +0 -183
  342. package/src/App.test.tsx +0 -218
  343. package/src/App.tsx +0 -1249
  344. package/src/config.test.ts +0 -116
  345. package/src/config.ts +0 -150
  346. package/src/editor.ts +0 -34
  347. package/src/herdr.test.ts +0 -68
  348. package/src/herdr.ts +0 -34
  349. package/src/keymap.test.ts +0 -270
  350. package/src/keymap.ts +0 -173
  351. package/src/run.ts +0 -30
  352. package/src/serve.ts +0 -75
  353. package/src/session-controller.ts +0 -398
  354. package/src/syntax.test.ts +0 -41
  355. package/src/syntax.ts +0 -88
  356. package/src/theme.ts +0 -46
  357. package/src/view-diff.test.ts +0 -55
  358. package/src/view-diff.ts +0 -86
  359. package/src/view.test.ts +0 -157
  360. package/src/view.ts +0 -364
@@ -0,0 +1,1758 @@
1
+ import { THREAD_MODEL_DEFAULTS } from "@cueloop/schema";
2
+ import { useThreadHarnessSetting } from "../settings/use-thread-harness-setting";
3
+ import React, {
4
+ useCallback,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ useSyncExternalStore,
10
+ } from "react";
11
+ import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react";
12
+ import type { Clock, KeyEvent } from "@opentui/core";
13
+ import { buildDisplay, marksByDisplay, type Mark } from "../markdown/view-plan";
14
+ import {
15
+ DEFAULT_KEYS,
16
+ DEFAULT_QUICK_ACTIONS,
17
+ loadConfig,
18
+ persistAuthorName,
19
+ persistDiffView,
20
+ persistIdentity,
21
+ persistPins,
22
+ type AutoClose,
23
+ type DiffViewMode,
24
+ type IdentityConfig,
25
+ type QuickAction,
26
+ type ReviewWorkspaceMode,
27
+ } from "../settings/config";
28
+ import { resolveDisplayName } from "../integrations/attribution";
29
+ import { resolveGithubIdentity } from "../integrations/github-identity";
30
+ import { loadSkills, PaletteNamesContext, SlashSkillsContext } from "../keyboard/skills";
31
+ import { mergeSlashItems, slashItemsFrom, type SlashItem } from "../keyboard/slash-palette";
32
+ import {
33
+ composeTheme,
34
+ DEFAULT_THEME_NAME,
35
+ themeForName,
36
+ type Appearance,
37
+ type ThemeName,
38
+ } from "../appearance/theme-presets";
39
+ import type { Theme } from "../appearance/theme";
40
+ import {
41
+ createReviewController,
42
+ type ShareTransport,
43
+ type ReviewController,
44
+ } from "../thread/thread-controller";
45
+ import type { ThreadClient } from "@cueloop/daemon/client";
46
+ import { createIntentDispatch, type Mode, type RailTab } from "./intent-dispatch";
47
+ import { reduceKey, type KeyState } from "../keyboard/keymap";
48
+ import { KeyBindings, type CheatsheetSection } from "../keyboard/key-bindings";
49
+ import { useReadySignal } from "./ready-signal";
50
+ import { ThemeProvider } from "../appearance/components/theme-context";
51
+ import { Button } from "../ui/components/primitives/Button";
52
+ import { ShareDialog } from "../integrations/components/ShareDialog";
53
+ import { shareDialogStore } from "../integrations/components/share-dialog-store";
54
+ import { Toolbar } from "../ui/components/primitives/Toolbar";
55
+ import { groupInbox, projectName, threadTitle } from "../thread/components/thread-tree";
56
+ import { ThreadTree } from "../thread/components/ThreadTree";
57
+ import { ChangesFileTree } from "../workbench/components/ChangesColumn";
58
+ import { MenuControlProvider, useMenuControlState } from "../ui/components/menu-control";
59
+ import { ProjectTreeView } from "../workbench/components/ProjectTreeView";
60
+ import { AppShell, type FocusPane, type ProjectPanelMode } from "./components/AppShell";
61
+ import type { ClientExtensionRegistry } from "../integrations/client-extension-registry";
62
+ import type { ExtensionUIContext } from "@cueloop/extension-api/client";
63
+ import { EditorGrid } from "../workbench/components/EditorGrid";
64
+ import { GridTabContent } from "../workbench/components/GridTabContent";
65
+ import { useChangesWorkbench } from "../workbench/use-changes-workbench";
66
+ import { useRepoChanges } from "../workbench/use-repo-changes";
67
+ import { useThreadBodyEditing } from "../markdown/use-thread-body-editing";
68
+ import { useRememberLayout } from "../workbench/use-remember-layout";
69
+ import type { LaunchLayout } from "./launch-layout";
70
+ import { ThreadFooter, THREAD_FOOTER_HEIGHT } from "../thread/components/ThreadFooter";
71
+ import { AgentThreadPrototype, agentOwnsKeyboard } from "../thread/components/AgentThreadPane";
72
+ import { ConfirmCard } from "../ui/components/ConfirmCard";
73
+ import { THREAD_VIEW_CHEATSHEET, ThreadView } from "../markdown/components/ThreadView";
74
+ import {
75
+ curationCommandEntries,
76
+ diffCommandEntries,
77
+ resolveNavKey,
78
+ resolveSessionChord,
79
+ sessionCommandEntries,
80
+ treeCommandEntries,
81
+ } from "../keyboard/thread-chords";
82
+ import { type DiffFoldControls } from "../diff/components/DiffContentView";
83
+ import { commentCountsByFile, readsFrozenDiff } from "../diff/view-diff";
84
+ import { annotationTarget, isAddressed, isAgentNote } from "@cueloop/schema";
85
+ import type {
86
+ Annotation,
87
+ Artifact,
88
+ DiffFileContents,
89
+ Identity,
90
+ ShareLink,
91
+ Thread,
92
+ MessageOutcome,
93
+ } from "@cueloop/schema";
94
+ import { PrototypePixels } from "../prototype/prototype-pixels";
95
+ import type { PrototypeElement } from "../prototype/prototype-browser";
96
+ import {
97
+ buildRenderFlags,
98
+ buildSubmitConfirmState,
99
+ computeRoleCapabilities,
100
+ deriveReviewFlags,
101
+ isPixelPrototypeMode,
102
+ isCompletionOverlayPhase,
103
+ isWalking,
104
+ resolveOverlay,
105
+ } from "./app-view-model";
106
+ import { buildKeyState } from "./app-key-state";
107
+ import { useSettingsDialog } from "../settings/use-settings-dialog";
108
+ import {
109
+ CompletionScreen,
110
+ ConnectingScreen,
111
+ ErrorScreen,
112
+ MenuChrome,
113
+ NoThreadShell,
114
+ TrailingOverlays,
115
+ } from "./app-screens";
116
+ /** A toast clears itself after this idle; esc dismisses it sooner. */
117
+ const TOAST_DISMISS_MS = 2000;
118
+
119
+ export interface AppProps {
120
+ home?: string;
121
+ sessionId?: string;
122
+ initialReview?: { session: Thread; diff: { patch: string; files: DiffFileContents[] } };
123
+ initialClient?: ThreadClient;
124
+ agentClient?: import("../thread/use-thread-agent").ThreadAgentClient;
125
+ cwd?: string;
126
+ readOnly?: boolean;
127
+ onExit?: (code: number) => void;
128
+ onReady?: () => void;
129
+ clock?: Clock;
130
+ openClient?: () => Promise<ThreadClient>;
131
+ shareTransport?: ShareTransport;
132
+ role?: "owner" | "observer" | "collaborator";
133
+ selfAuthor?: string;
134
+ appearance?: Appearance;
135
+ layout?: LaunchLayout;
136
+ servedArtifact?: Artifact;
137
+ extensionRegistry?: ClientExtensionRegistry;
138
+ }
139
+
140
+ function initialReviewControllerOptions(initialReview: AppProps["initialReview"]) {
141
+ const options = { initialSession: initialReview?.session, initialDiff: initialReview?.diff };
142
+
143
+ return options;
144
+ }
145
+
146
+ function initialReviewFiles(initialReview: AppProps["initialReview"], sessionId: string) {
147
+ const files = initialReview?.session.id === sessionId ? initialReview.diff.files : undefined;
148
+
149
+ return files;
150
+ }
151
+
152
+ function extensionContext(cwd: string | undefined, threadId: string | null): ExtensionUIContext {
153
+ return { workspace: cwd ?? process.cwd(), threadId };
154
+ }
155
+
156
+ /** True while the drop-up or one of its dialogs is open and owns the keyboard. */
157
+ function menuChromeOpen(menuDialog: "keybinds" | "settings" | null): boolean {
158
+ return menuDialog !== null;
159
+ }
160
+
161
+ /** Whether a thread already has at least one live share link. */
162
+ function isSharedThread(session: Thread | null): boolean {
163
+ return session !== null && (session.shares?.length ?? 0) > 0;
164
+ }
165
+
166
+ /** A thread's live share links for the share dialog, or an empty list with no session. */
167
+ function shareLinksFor(session: Thread | null): ShareLink[] {
168
+ return session ? (session.shares ?? []) : [];
169
+ }
170
+
171
+ /** The title the share dialog shows and prefills a new link with, or empty with no session. */
172
+ function shareThreadName(session: Thread | null): string {
173
+ return session ? threadTitle(session) : "";
174
+ }
175
+
176
+ /** Show the diff source before long titles can truncate it in the header. */
177
+ function reviewThreadTitle(session: Thread): string {
178
+ if (session.artifact.type === "diff" && session.artifact.meta.vcs)
179
+ return `vcs: ${session.artifact.meta.vcs} · ${threadTitle(session)}`;
180
+
181
+ return threadTitle(session);
182
+ }
183
+
184
+ /** The drop-up chrome or a floating popover menu (thread actions, editor split) holds the keyboard. */
185
+ function keyboardHeldByMenu(
186
+ menuDialog: "keybinds" | "settings" | null,
187
+ openMenuId: string | null,
188
+ ): boolean {
189
+ return menuChromeOpen(menuDialog) || openMenuId !== null;
190
+ }
191
+
192
+ /** A non-modal toast: escape dismisses it only when nothing else owns escape (no overlay, not span mode). */
193
+ export function toastDismissRequested(
194
+ toastOpen: boolean,
195
+ key: { name: string },
196
+ overlay: KeyState["overlay"],
197
+ spanMode: boolean,
198
+ ): boolean {
199
+ return toastOpen && key.name === "escape" && overlay === "none" && !spanMode;
200
+ }
201
+
202
+ /** ctrl+q quits from anywhere, ahead of every focus/menu/overlay gate, with no confirmation. */
203
+ export function quitKeyHandled(
204
+ key: { name: string; ctrl?: boolean },
205
+ onExit?: (code: number) => void,
206
+ ): boolean {
207
+ if (!key.ctrl || key.name !== "q") return false;
208
+
209
+ onExit?.(0);
210
+
211
+ return true;
212
+ }
213
+
214
+ /** A popover menu is open, so the shell keyboard is modal: escape closes it, every other key is swallowed. */
215
+ function menuModalHandled(
216
+ menuControl: { openMenuId: string | null; closeMenu: () => void },
217
+ key: { name: string },
218
+ ): boolean {
219
+ if (menuControl.openMenuId === null) return false;
220
+
221
+ if (key.name === "escape") menuControl.closeMenu();
222
+
223
+ return true;
224
+ }
225
+
226
+ /** True while a menu, an overlay, or the share dialog owns the keyboard instead of the thread view. */
227
+ function keyboardOwnedElsewhere(
228
+ menuOwnsKeyboard: boolean,
229
+ overlay: KeyState["overlay"],
230
+ shareDialogOpen: boolean,
231
+ ): boolean {
232
+ return menuOwnsKeyboard || overlay !== "none" || shareDialogOpen;
233
+ }
234
+
235
+ /** The footer submit fires only for the owner of an unresolved review, never an observer. */
236
+ function canSubmitReview(isOwner: boolean, resolved: boolean, observer: boolean): boolean {
237
+ return isOwner && !resolved && !observer;
238
+ }
239
+
240
+ /** The thread body edits inline only for its owner, on an unresolved markdown thread (never a diff). */
241
+ function canEditThreadBody(
242
+ threadViewActive: boolean,
243
+ isDiff: boolean,
244
+ isOwner: boolean,
245
+ resolved: boolean,
246
+ ): boolean {
247
+ return threadViewActive && !isDiff && isOwner && !resolved;
248
+ }
249
+
250
+ /** The owner's header actions: an edit/normal toggle that opens or leaves the inline editor, plus share when not editing. */
251
+ function ownerThreadActions(actions: {
252
+ editing: boolean;
253
+ onEdit: () => void;
254
+ onExitEdit: () => void;
255
+ onShare: () => void;
256
+ theme: Theme;
257
+ }): React.ReactNode {
258
+ return (
259
+ <Toolbar>
260
+ <Button onPress={actions.editing ? actions.onExitEdit : actions.onEdit} theme={actions.theme}>
261
+ {actions.editing ? " normal " : " edit "}
262
+ </Button>
263
+ {actions.editing ? null : (
264
+ <Button onPress={actions.onShare} theme={actions.theme}>
265
+ {" share "}
266
+ </Button>
267
+ )}
268
+ </Toolbar>
269
+ );
270
+ }
271
+
272
+ function refreshDiffAction(onRefresh: () => void, theme: Theme): React.ReactNode {
273
+ return (
274
+ <Toolbar>
275
+ <Button onPress={onRefresh} foreground={theme.warning} theme={theme}>
276
+ {" refresh "}
277
+ </Button>
278
+ </Toolbar>
279
+ );
280
+ }
281
+
282
+ /** Present pull request context with the ordinary read-only Thread renderer. */
283
+ function pullRequestBriefThread(session: Thread): Thread {
284
+ return {
285
+ ...session,
286
+ artifact: {
287
+ ...session.artifact,
288
+ type: "reply",
289
+ content: session.artifact.meta.prBrief ?? "",
290
+ },
291
+ workingCopy: undefined,
292
+ annotations: [],
293
+ };
294
+ }
295
+
296
+ /** Pick the thread pane's body: the pixel prototype, the diff placeholder, the inline editor, or the read-only view. */
297
+ function chooseThreadBody(choice: {
298
+ isPixelPrototype: boolean;
299
+ isDiff: boolean;
300
+ editingBody: boolean;
301
+ prototype: React.ReactNode;
302
+ diffPlaceholder: React.ReactNode;
303
+ editor: React.ReactNode;
304
+ threadView: React.ReactNode;
305
+ }): React.ReactNode {
306
+ if (choice.isPixelPrototype) return choice.prototype;
307
+
308
+ if (choice.isDiff) return choice.diffPlaceholder;
309
+
310
+ if (choice.editingBody) return choice.editor;
311
+
312
+ return choice.threadView;
313
+ }
314
+
315
+ /** The author display name for a comment's hover tooltip: the reviewer's own name for their notes, else the resolved collaborator name. */
316
+ function authorLabelResolver(
317
+ ownName: string | undefined,
318
+ participants: Identity[] | undefined,
319
+ overrides: Record<string, string>,
320
+ ): (annotation: Annotation) => string | undefined {
321
+ return (annotation) =>
322
+ annotation.author === undefined
323
+ ? (ownName ?? "you")
324
+ : resolveDisplayName(annotation.author, participants, overrides);
325
+ }
326
+
327
+ /** The Project pane body: the resolved repo's changed files in changes mode, its full tree otherwise. */
328
+ function ProjectPanelBody(props: {
329
+ mode: ProjectPanelMode;
330
+ loadChanges: () => Promise<readonly DiffFileContents[]>;
331
+ initialFiles?: readonly DiffFileContents[];
332
+ loadProjectFiles: () => Promise<string[]>;
333
+ diffSourceKey: string;
334
+ liveWorkingTree: boolean;
335
+ frozenFiles?: readonly DiffFileContents[];
336
+ onOpenChangedFile: (path: string, persistent?: boolean) => void;
337
+ onOpenProjectFile: (path: string, persistent?: boolean) => void;
338
+ commentCounts?: ReadonlyMap<string, number>;
339
+ focused?: boolean;
340
+ theme: Theme;
341
+ }): React.ReactNode {
342
+ const changes = useRepoChanges({
343
+ loadChanges: props.loadChanges,
344
+ visible: props.mode === "changes" && props.liveWorkingTree,
345
+ diffSourceKey: props.diffSourceKey,
346
+ initialFiles: props.initialFiles,
347
+ });
348
+
349
+ if (props.mode === "changes") {
350
+ return (
351
+ <ChangesFileTree
352
+ files={props.liveWorkingTree ? changes : (props.frozenFiles ?? [])}
353
+ onSelectFile={props.onOpenChangedFile}
354
+ commentCounts={props.commentCounts}
355
+ focused={props.focused}
356
+ theme={props.theme}
357
+ />
358
+ );
359
+ }
360
+
361
+ return (
362
+ <ProjectTreeView
363
+ key={props.diffSourceKey}
364
+ loadFiles={props.loadProjectFiles}
365
+ onSelectFile={props.onOpenProjectFile}
366
+ focused={props.focused}
367
+ theme={props.theme}
368
+ />
369
+ );
370
+ }
371
+
372
+ /** Frozen reviews read their captured files directly; live workspaces poll the repo. */
373
+ interface ProjectDiffFiles {
374
+ liveWorkingTree: boolean;
375
+ frozenFiles?: readonly DiffFileContents[];
376
+ }
377
+
378
+ function projectDiffFiles(session: Thread): ProjectDiffFiles {
379
+ const frozen = readsFrozenDiff(session);
380
+
381
+ return {
382
+ liveWorkingTree: !frozen,
383
+ frozenFiles: frozen ? session.artifact.files : undefined,
384
+ };
385
+ }
386
+
387
+ /** The render tree has left the connecting screen: an error, a session, or the no-thread shell. */
388
+ function usableScreenReached(
389
+ error: string | null,
390
+ session: Thread | null,
391
+ inbox: Thread[] | null,
392
+ ): boolean {
393
+ return Boolean(error) || session !== null || inbox !== null;
394
+ }
395
+
396
+ /** The keybinds dialog content: the thread grammar while the thread view owns the keys. */
397
+ function cheatsheetFor(keyBindings: KeyBindings, threadViewActive: boolean): CheatsheetSection[] {
398
+ const base = keyBindings.cheatsheet();
399
+ const fileTree: CheatsheetSection = {
400
+ title: "Changes / Project files",
401
+ entries: [
402
+ { keys: "enter", label: "open selected file or toggle folder" },
403
+ { keys: "tab", label: "cycle panes" },
404
+ ],
405
+ };
406
+
407
+ if (!threadViewActive) {
408
+ return [fileTree, ...base];
409
+ }
410
+
411
+ return [
412
+ fileTree,
413
+ ...THREAD_VIEW_CHEATSHEET,
414
+ { title: "Nav mode · session", entries: sessionCommandEntries() },
415
+ { title: "Nav mode · diff", entries: diffCommandEntries() },
416
+ { title: "Nav mode · discussion", entries: curationCommandEntries() },
417
+ { title: "Nav mode · history", entries: treeCommandEntries() },
418
+ ];
419
+ }
420
+
421
+ /** The Threads sidebar opens from the launch layout; a bare launch opens it only on the inbox. */
422
+ function initialThreadsOpen(
423
+ layout: LaunchLayout | undefined,
424
+ sessionId: string | undefined,
425
+ ): boolean {
426
+ return layout ? layout.threads : sessionId === undefined;
427
+ }
428
+
429
+ function initialFocusedPane(
430
+ sessionId: string | undefined,
431
+ zoomed: boolean,
432
+ layout?: LaunchLayout,
433
+ ): FocusPane {
434
+ if (sessionId === undefined) return "threads";
435
+
436
+ return layout?.focusPane ?? (zoomed ? "changes" : "thread");
437
+ }
438
+
439
+ function bareShellDefersKeys(
440
+ sessionIsNull: boolean,
441
+ overlayIsNone: boolean,
442
+ focusedPane: FocusPane,
443
+ ): boolean {
444
+ return sessionIsNull && overlayIsNone && focusedPane !== "threads";
445
+ }
446
+
447
+ function surfaceSuspended(base: boolean, focusedPane: FocusPane, pane: FocusPane): boolean {
448
+ return base || focusedPane !== pane;
449
+ }
450
+
451
+ export function threadsNavHandled(params: {
452
+ focusedPane: FocusPane;
453
+ quiet: boolean;
454
+ key: { name: string };
455
+ count: number;
456
+ setInboxCursor: (update: (cursor: number) => number) => void;
457
+ openSession: () => void;
458
+ }): boolean {
459
+ const { focusedPane, quiet, key, count } = params;
460
+
461
+ if (focusedPane !== "threads" || !quiet || count === 0) return false;
462
+
463
+ if (key.name === "j" || key.name === "down") {
464
+ params.setInboxCursor((cursor) => Math.min(cursor + 1, count - 1));
465
+
466
+ return true;
467
+ }
468
+
469
+ if (key.name === "k" || key.name === "up") {
470
+ params.setInboxCursor((cursor) => Math.max(cursor - 1, 0));
471
+
472
+ return true;
473
+ }
474
+
475
+ if (key.name === "return" || key.name === "enter") {
476
+ params.openSession();
477
+
478
+ return true;
479
+ }
480
+
481
+ return false;
482
+ }
483
+
484
+ export function paneCycleRequested(
485
+ key: { name: string },
486
+ overlay: string,
487
+ menuOwnsKeyboard: boolean,
488
+ threadComposing: boolean,
489
+ ): boolean {
490
+ return key.name === "tab" && overlay === "none" && !menuOwnsKeyboard && !threadComposing;
491
+ }
492
+
493
+ export function visiblePanes(
494
+ sidebarOpen: boolean,
495
+ threadShown: boolean,
496
+ changesOpen: boolean,
497
+ projectOpen: boolean,
498
+ ): FocusPane[] {
499
+ const panes: FocusPane[] = [];
500
+
501
+ if (sidebarOpen) panes.push("threads");
502
+
503
+ if (threadShown) panes.push("thread");
504
+
505
+ if (changesOpen) panes.push("changes");
506
+
507
+ if (projectOpen) panes.push("project");
508
+
509
+ return panes;
510
+ }
511
+
512
+ export function nextFocusPane(
513
+ current: FocusPane,
514
+ panes: FocusPane[],
515
+ backward: boolean,
516
+ ): FocusPane {
517
+ if (panes.length === 0) return current;
518
+
519
+ const index = panes.indexOf(current);
520
+ const step = backward ? -1 : 1;
521
+
522
+ return panes[(index + step + panes.length) % panes.length] ?? current;
523
+ }
524
+
525
+ /** The panes that can own the keyboard: a diff's Thread pane is an inert placeholder, so it is out. */
526
+ function navigableFocusPanes(
527
+ sidebarOpen: boolean,
528
+ zoomed: boolean,
529
+ isDiff: boolean,
530
+ changesOpen: boolean,
531
+ projectOpen: boolean,
532
+ ): FocusPane[] {
533
+ return visiblePanes(sidebarOpen, !zoomed && !isDiff, changesOpen, projectOpen);
534
+ }
535
+
536
+ /** The layout hid or inert-ed the focused pane: fall back to the first navigable one, else stay put. */
537
+ export function reconciledFocus(navigable: FocusPane[], focusedPane: FocusPane): FocusPane | null {
538
+ if (navigable.length === 0 || navigable.includes(focusedPane)) return null;
539
+
540
+ return navigable[0] ?? null;
541
+ }
542
+
543
+ export function App({
544
+ home,
545
+ sessionId,
546
+ initialReview,
547
+ initialClient,
548
+ agentClient,
549
+ cwd,
550
+ readOnly = false,
551
+ onExit,
552
+ onReady,
553
+ clock,
554
+ openClient,
555
+ shareTransport,
556
+ role = "owner",
557
+ selfAuthor,
558
+ appearance = "dark",
559
+ layout,
560
+ servedArtifact,
561
+ extensionRegistry,
562
+ }: AppProps): React.ReactNode {
563
+ const { observer, isOwner, canManageThreads } = computeRoleCapabilities(
564
+ readOnly,
565
+ role,
566
+ isSharedThreadConnection(openClient, shareTransport),
567
+ );
568
+ const controller = useMemo(
569
+ () =>
570
+ createReviewController({
571
+ home,
572
+ sessionId,
573
+ ...initialReviewControllerOptions(initialReview),
574
+ initialClient,
575
+ cwd,
576
+ readOnly: observer,
577
+ onExit,
578
+ clock,
579
+ openClient,
580
+ shareTransport,
581
+ servedArtifact,
582
+ }),
583
+ // eslint-disable-next-line react-hooks/exhaustive-deps
584
+ [home, sessionId],
585
+ );
586
+ const showExtensionError = useCallback(
587
+ (message: string) => controller.showToast(message),
588
+ [controller],
589
+ );
590
+
591
+ useEffect(() => {
592
+ controller.connect();
593
+
594
+ return () => controller.close();
595
+ }, [controller]);
596
+ // stable across renders so the memoized PrototypeContentView is not
597
+ // re-rendered by unrelated App state (status ticks, a rail-width drag)
598
+ const onCommentPrototype = useCallback(
599
+ (element: PrototypeElement, body: string) =>
600
+ controller.annotatePrototype(element.selector, element.quote, body),
601
+ [controller],
602
+ );
603
+ const { session, inbox, status, toast, error, completion, editOrphanCount, walk } =
604
+ useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
605
+ const initialReviewForFirstMount = useRef(initialReview);
606
+
607
+ useEffect(() => {
608
+ initialReviewForFirstMount.current = undefined;
609
+ }, []);
610
+
611
+ // A shared plan you own polls for collaborator notes while it is open; the
612
+ // merge refreshes through the normal event path. Stops on leave.
613
+ const threadShared = isSharedThread(session);
614
+
615
+ useEffect(() => {
616
+ if (!isOwner || !threadShared) return;
617
+
618
+ return controller.startShareSync();
619
+ }, [isOwner, session?.id, threadShared, controller]);
620
+ const renderer = useRenderer();
621
+ const { width: terminalWidth } = useTerminalDimensions();
622
+
623
+ // ── view state ──────────────────────────────
624
+ const [cursor, setCursor] = useState(0);
625
+ const [inboxCursor, setInboxCursor] = useState(0);
626
+ // Projects and Threads grouping; ordered is the flat sequence the inbox cursor walks
627
+ // pinned threads are client-local view state, seeded from the user config and
628
+ // persisted on toggle; a pin lifts the thread into the sidebar's Pinned section
629
+ const [pinnedIds, setPinnedIds] = useState<Set<string>>(new Set());
630
+ const grouped = useMemo(() => groupInbox(inbox ?? [], pinnedIds), [inbox, pinnedIds]);
631
+ const togglePin = (id: string): void =>
632
+ setPinnedIds((current) => {
633
+ const next = new Set(current);
634
+
635
+ if (next.has(id)) next.delete(id);
636
+ else next.add(id);
637
+
638
+ persistPins([...next]);
639
+
640
+ return next;
641
+ });
642
+ // the left Projects and Threads column; collapsed by default per the context
643
+ // matrix (the thread owns the width), toggled open to jump between threads
644
+ // one sidebar-open state across the no-thread shell and the thread view, so
645
+ // picking a thread keeps the sidebar as it was. It opens when the app lands with
646
+ // nothing selected (pick a thread) and stays collapsed on a direct thread open,
647
+ // where the thread owns the width.
648
+ const [sidebarOpen, setSidebarOpen] = useState(() => initialThreadsOpen(layout, sessionId));
649
+ // the Changes + Project right region and its editor grid (tabs, splits, zoom)
650
+ const workbench = useChangesWorkbench({ layout });
651
+ const [focusedPane, setFocusedPane] = useState<FocusPane>(() =>
652
+ initialFocusedPane(sessionId, workbench.zoomed, layout),
653
+ );
654
+
655
+ // only the session view persists from here; the bare shell owns its own (NoThreadShell), so this
656
+ // workbench stays inactive with no session and never clobbers what the shell saved
657
+ useRememberLayout(
658
+ layout,
659
+ session !== null,
660
+ sidebarOpen,
661
+ workbench.changesOpen,
662
+ workbench.projectOpen,
663
+ workbench.zoomed,
664
+ );
665
+ const [mode, setMode] = useState<Mode>({ type: "normal" });
666
+ // the top-left settings gear drop-down and the centered dialog it opens
667
+ const [menuDialog, setMenuDialog] = useState<"keybinds" | "settings" | null>(null);
668
+ const [shareDialogOpen, setShareDialogOpen] = useState(false);
669
+ const [autoClose, setAutoClose] = useState<AutoClose>("off");
670
+ // unified or side-by-side diff; split lays out when the Changes pane is zoomed
671
+ const [diffView, setDiffView] = useState<DiffViewMode>("split");
672
+ const [defaultMessage, setDefaultMessage] = useState<MessageOutcome>("approved");
673
+ const [focusedAnnotationId, setFocusedAnnotationId] = useState<string | undefined>(undefined);
674
+ const [selectedCurationId, setSelectedCurationId] = useState<string | undefined>(undefined);
675
+ const [railTab, setRailTab] = useState<RailTab>("review");
676
+ // the tree row the reviewer stands on in the session tree
677
+ const [selectedEntryId, setSelectedEntryId] = useState<string | undefined>(undefined);
678
+ // ~2s focus pulse on the document highlight when a card is activated
679
+ const [pulsedAnnotationId, setPulsedAnnotationId] = useState<string | null>(null);
680
+ const pulseTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
681
+ // live mirror of overlay input text: refs commit synchronously, so the
682
+ // RETURN handler never reads a stale value mid-typing
683
+ const liveInput = useRef("");
684
+ // keymap from layered config; the loaded theme swaps the provider value
685
+ const keysRef = useRef(DEFAULT_KEYS);
686
+ const keyBindings = useMemo(() => new KeyBindings(DEFAULT_KEYS), []);
687
+ const [theme, setTheme] = useState(() => themeForName(DEFAULT_THEME_NAME, appearance));
688
+ const [themeName, setThemeName] = useState<ThemeName>(DEFAULT_THEME_NAME);
689
+ const [themeOverrides, setThemeOverrides] = useState<Partial<Theme>>({});
690
+ const [authorNames, setAuthorNames] = useState<Record<string, string>>({});
691
+ const [identity, setIdentity] = useState<IdentityConfig>({ provider: "typed" });
692
+ const [quickActions, setQuickActions] = useState<QuickAction[]>(DEFAULT_QUICK_ACTIONS);
693
+ const [skills, setSkills] = useState<SlashItem[]>([]);
694
+ const [threadModelDefaults, setThreadModelDefaults] = useState(THREAD_MODEL_DEFAULTS);
695
+ const [reviewSkill, setReviewSkill] = useState("code-review");
696
+ const [reviewWorkspace, setReviewWorkspace] = useState<ReviewWorkspaceMode>("worktree");
697
+ const paletteNames = useMemo(
698
+ () => new Set(mergeSlashItems(slashItemsFrom(quickActions), skills).map((item) => item.name)),
699
+ [quickActions, skills],
700
+ );
701
+ // opt-in: render a prototype as a kitty pixel mockup instead of the markdown doc
702
+ const [prototypePixels, setPrototypePixels] = useState(false);
703
+ const [threadAgentEnabled, setThreadAgentEnabled] = useState(false);
704
+
705
+ useEffect(() => {
706
+ const config = loadConfig({ repoRoot: session?.workspace.repoRoot });
707
+
708
+ setPrototypePixels(config.experimental.prototypePixels);
709
+ setThreadAgentEnabled(config.experimental.threadAgent);
710
+ setThreadHarness(config.thread.harness);
711
+ setThreadModelDefaults({ pi: config.thread.pi, fx: config.thread.fx });
712
+ keysRef.current = config.keys;
713
+ keyBindings.setKeys(config.keys);
714
+ setTheme(composeTheme(config.ui.theme, config.themeOverrides, appearance));
715
+ setThemeName(config.ui.theme);
716
+ setThemeOverrides(config.themeOverrides);
717
+ setAuthorNames(config.authors);
718
+ setIdentity(config.identity);
719
+ setQuickActions(config.actions);
720
+ setSkills(loadSkills(config.skillsPath));
721
+ setReviewSkill(config.review.skill);
722
+ setReviewWorkspace(config.review.workspace);
723
+ setAutoClose(config.ui.autoClose);
724
+ setDiffView(config.ui.diffView);
725
+ setDefaultMessage(config.ui.defaultMessage);
726
+ setPinnedIds(new Set(config.ui.pins));
727
+ controller.applyConfig(config);
728
+ }, [session?.workspace.repoRoot, controller, keyBindings, appearance]);
729
+ useEffect(
730
+ () => () => {
731
+ if (pulseTimer.current) clearTimeout(pulseTimer.current);
732
+ },
733
+ [],
734
+ );
735
+
736
+ useEffect(() => {
737
+ if (!toast) return;
738
+
739
+ const timer = setTimeout(() => controller.dismissToast(), TOAST_DISMISS_MS);
740
+
741
+ return () => clearTimeout(timer);
742
+ }, [toast, controller]);
743
+
744
+ // First open of a share: ask the collaborator for a display name once, unless
745
+ // a past visit already recorded one. esc skips and their notes read anonymous.
746
+ const promptedSelfRef = useRef(false);
747
+
748
+ useEffect(() => {
749
+ if (promptedSelfRef.current || role !== "collaborator" || !selfAuthor || !session) return;
750
+
751
+ promptedSelfRef.current = true;
752
+ const known = session.participants?.find((participant) => participant.id === selfAuthor)?.name;
753
+
754
+ if (!known) setMode({ type: "nameSelf", text: "" });
755
+ }, [role, selfAuthor, session]);
756
+
757
+ // Bumped on every identity change so a slow GitHub sync that lands after a newer rename is discarded.
758
+ const identityGenerationRef = useRef(0);
759
+ const applyIdentity = (next: IdentityConfig): void => {
760
+ identityGenerationRef.current += 1;
761
+ setIdentity(next);
762
+ try {
763
+ persistIdentity(next);
764
+ } catch {
765
+ controller.setStatus("could not save identity to config");
766
+ }
767
+ };
768
+ const syncGithubIdentity = (): void => {
769
+ const generation = (identityGenerationRef.current += 1);
770
+
771
+ void resolveGithubIdentity().then((github) => {
772
+ if (identityGenerationRef.current !== generation) return;
773
+
774
+ if (!github) return controller.setStatus("GitHub not connected - run gh auth login");
775
+
776
+ const name = github.name?.trim() || github.login;
777
+
778
+ applyIdentity({ name, provider: "github" });
779
+ });
780
+ };
781
+
782
+ const [agentState, setAgentState] = useState<import("@cueloop/schema").ThreadAgentState>();
783
+ const [threadHarness, setThreadHarness] = useState<"pi" | "fx">("pi");
784
+
785
+ const harnessSetting = useThreadHarnessSetting({
786
+ home,
787
+ thread: session,
788
+ enabled: threadAgentEnabled,
789
+ owner: isOwner,
790
+ state: agentState,
791
+ preferred: threadHarness,
792
+ client: agentClient,
793
+ onState: setAgentState,
794
+ onPreferred: setThreadHarness,
795
+ onError: (message) => controller.setStatus(message),
796
+ });
797
+
798
+ // ── settings dialog: config-backed model, navigation, persistence ──
799
+ const {
800
+ settingsNav,
801
+ settingsCategories,
802
+ settingsValues,
803
+ cycleSetting,
804
+ handleSettingsKey,
805
+ onCategorySelect,
806
+ openSettings,
807
+ } = useSettingsDialog({
808
+ threadDefaults: threadModelDefaults,
809
+ setThreadDefaults: setThreadModelDefaults,
810
+ theme,
811
+ appearance,
812
+ autoClose,
813
+ setAutoClose,
814
+ diffView,
815
+ setDiffView,
816
+ themeName,
817
+ setThemeName,
818
+ themeOverrides,
819
+ setTheme,
820
+ quickActions,
821
+ setQuickActions,
822
+ setMenuDialog,
823
+ identityName: identity.name,
824
+ identityProvider: identity.provider,
825
+ onSyncGithubIdentity: syncGithubIdentity,
826
+ onRenameDisplayName: () => {
827
+ setMenuDialog(null);
828
+ setMode({ type: "renameSelf", text: identity.name ?? "" });
829
+ },
830
+ reviewSkill,
831
+ reviewWorkspace,
832
+ setReviewWorkspace,
833
+ canSwitchHarness: harnessSetting.enabled,
834
+ threadHarness: harnessSetting.harness,
835
+ onSwitchHarness: harnessSetting.switchHarness,
836
+ });
837
+
838
+ // ── derived view model ──────────────────────
839
+ const display = controller.display();
840
+ const rows = controller.rows();
841
+ const rejectedRows = controller.rejectedRows();
842
+ const marks = useMemo(
843
+ () =>
844
+ session
845
+ ? marksByDisplay(
846
+ // the plan thread shows only artifact notes; Changes-diff notes render on that surface
847
+ session.annotations.filter(
848
+ (annotation) => annotationTarget(annotation).kind === "artifact",
849
+ ),
850
+ display,
851
+ pulsedAnnotationId ?? undefined,
852
+ )
853
+ : new Map<number, Mark[]>(),
854
+ [session, display, pulsedAnnotationId],
855
+ );
856
+ /** Annotation ids whose anchor resolved against the working copy. */
857
+ const resolvedIds = useMemo(() => {
858
+ const ids = new Set<string>();
859
+
860
+ for (const blockMarks of marks.values()) {
861
+ for (const mark of blockMarks) if (mark.annotationId) ids.add(mark.annotationId);
862
+ }
863
+
864
+ return ids;
865
+ }, [marks]);
866
+ const { isDiff, isPrototype, resolved } = deriveReviewFlags(session);
867
+ // a prototype is a markdown design doc by default; only the opt-in experimental
868
+ // pixel mode (flag on + an HTML entry) renders it as a kitty mockup instead
869
+ const isPixelPrototype = isPixelPrototypeMode(
870
+ isPrototype,
871
+ prototypePixels,
872
+ session?.artifact.meta.prototypePath,
873
+ );
874
+ // comments per changed-file path, for the changed-files tree and tab badges
875
+ const diffCommentCounts = useMemo(
876
+ () => (session && isDiff ? commentCountsByFile(session, rows) : undefined),
877
+ [session, isDiff, rows],
878
+ );
879
+
880
+ // entering a diff opens the right region in changed-files mode; a plan or reply opens it closed
881
+ workbench.syncSession(session?.id, isDiff);
882
+ // plans, replies, and the default (markdown) prototype open in the thread view, diffs in the
883
+ // diff sheet: both drive the shared annotation surface; only the pixel prototype keeps the keymap
884
+ const threadViewActive = session !== null && !isPixelPrototype;
885
+ const [threadComposing, setThreadComposing] = useState(false);
886
+ const [agentActive, setAgentActive] = useState(false);
887
+ const [agentControls, setAgentControls] = useState<React.ReactNode>(null);
888
+ const agentActions = useRef<(id: string) => { label: string; run: () => void } | undefined>(
889
+ () => undefined,
890
+ );
891
+ const agentInvoke = useRef<((commentId?: string) => void) | undefined>(undefined);
892
+ const [prototypeComposing, setPrototypeComposing] = useState(false);
893
+ const [welcomeComposing, setWelcomeComposing] = useState(false);
894
+ // inline body edit: the markdown editor owns the thread pane and all keys while open
895
+ const canEditBody = canEditThreadBody(threadViewActive, isDiff, isOwner, resolved);
896
+ const bodyEditing = useThreadBodyEditing({
897
+ controller,
898
+ sessionId: session?.id,
899
+ canEdit: canEditBody,
900
+ });
901
+ // sort position per annotation so the rail interleaves annotation and removal
902
+ // cards in one line-ordered stack: a diff row carries its blockIndex; a plan
903
+ // annotation resolves to the display index it marked
904
+ // ── the guided walk's view model ────────────
905
+ const walkFileList = controller.files();
906
+ const walking = isWalking(isDiff, walk);
907
+ const viewedPaths = useMemo(() => new Set(session?.viewedPaths ?? []), [session]);
908
+
909
+ // ── selection symmetry: one selected id, both sides ──
910
+ const selectCardFromDocument = (annotationId: string): void => {
911
+ setFocusedAnnotationId(annotationId);
912
+ };
913
+
914
+ const openCardEdit = (annotationId: string): void => {
915
+ if (observer) return controller.setStatus("observer - read-only");
916
+
917
+ const annotation = session?.annotations.find((candidate) => candidate.id === annotationId);
918
+
919
+ if (!annotation) return;
920
+
921
+ // a collaborator's note is theirs to word: activating it (click or e) renames
922
+ // the author rather than editing the body the planner does not own
923
+ if (annotation.author) {
924
+ setFocusedAnnotationId(annotationId);
925
+
926
+ return void setMode({
927
+ type: "rename",
928
+ authorId: annotation.author,
929
+ text: authorNames[annotation.author] ?? "",
930
+ });
931
+ }
932
+
933
+ if (resolved) return controller.setStatus("review submitted - read-only");
934
+
935
+ liveInput.current = annotation.body;
936
+ setMode({ type: "railEdit", id: annotation.id, text: annotation.body });
937
+ };
938
+
939
+ // a markdown thread edits inline; a diff is not markdown, so it keeps the external-editor hand-off
940
+ const openBodyEditor = (): void => {
941
+ if (canEditBody) {
942
+ bodyEditing.openEditor();
943
+
944
+ return;
945
+ }
946
+
947
+ void (async () => {
948
+ let suspended = false;
949
+
950
+ try {
951
+ await renderer?.suspend();
952
+ suspended = true;
953
+ } catch {
954
+ suspended = false;
955
+ }
956
+ try {
957
+ controller.edit();
958
+ } finally {
959
+ if (suspended) await renderer?.resume();
960
+ }
961
+ })();
962
+ };
963
+
964
+ // ── keyboard grammar: build state, reduce, dispatch ──
965
+ const dispatch = createIntentDispatch({
966
+ controller,
967
+ onExit,
968
+ isDiff,
969
+ display,
970
+ rows,
971
+ cursor,
972
+ inbox: inbox === null ? null : grouped.ordered,
973
+ inboxCursor,
974
+ mode,
975
+ session,
976
+ defaultMessage,
977
+ focusedAnnotationId,
978
+ selectedCurationId,
979
+ railTab,
980
+ selectedEntryId,
981
+ authorNames,
982
+ quickActions,
983
+ renameAuthor: (id: string, name: string) => {
984
+ persistAuthorName(id, name);
985
+ setAuthorNames((prev) => ({ ...prev, [id]: name }));
986
+ },
987
+ renameThread: (id: string, title: string) => controller.renameSession(id, title),
988
+ setLocalIdentityName: (name: string) => {
989
+ applyIdentity(name ? { name, provider: "typed" } : { provider: "typed" });
990
+ },
991
+ liveInput,
992
+ setCursor,
993
+ setInboxCursor,
994
+ setMode,
995
+ setRailTab,
996
+ setSelectedEntryId,
997
+ setFocusedAnnotationId,
998
+ setSelectedCurationId,
999
+ setPulsedAnnotationId,
1000
+ selectCardFromDocument,
1001
+ openBodyEditor,
1002
+ openCardEdit,
1003
+ toggleDiffView: () => {
1004
+ const next: DiffViewMode = diffView === "stacked" ? "split" : "stacked";
1005
+
1006
+ setDiffView(next);
1007
+ persistDiffView(next);
1008
+ },
1009
+ openShareDialog: () => {
1010
+ if (!isOwner) return controller.setStatus("only the plan owner can share");
1011
+
1012
+ shareDialogStore.getState().reset();
1013
+ setShareDialogOpen(true);
1014
+ },
1015
+ });
1016
+
1017
+ const overlay = resolveOverlay(mode, completion.phase, walking);
1018
+
1019
+ const menuControl = useMenuControlState();
1020
+ const menuOwnsKeyboard = keyboardHeldByMenu(menuDialog, menuControl.openMenuId);
1021
+ // an overlay (submit, walk, prompt, confirm, share choice), the manage-access
1022
+ // dialog, or the menu takes the keyboard from the thread view; the view suspends
1023
+ // its own grammar meanwhile so typing lands in the dialog, not the thread
1024
+ const threadViewSuspended = keyboardOwnedElsewhere(menuOwnsKeyboard, overlay, shareDialogOpen);
1025
+
1026
+ const navigablePanes = navigableFocusPanes(
1027
+ sidebarOpen,
1028
+ workbench.zoomed,
1029
+ isDiff,
1030
+ workbench.changesOpen,
1031
+ workbench.projectOpen,
1032
+ );
1033
+
1034
+ useEffect(() => {
1035
+ // the bare shell drives its panes from its own workbench, so only reconcile against this one
1036
+ if (!session) return;
1037
+
1038
+ const next = reconciledFocus(navigablePanes, focusedPane);
1039
+
1040
+ if (next) setFocusedPane(next);
1041
+ }, [session, navigablePanes, focusedPane]);
1042
+ const cyclePanes = (backward: boolean): void =>
1043
+ setFocusedPane((current) => nextFocusPane(current, navigablePanes, backward));
1044
+ const runNavCommand = (
1045
+ key: { name: string; shift?: boolean },
1046
+ selection: {
1047
+ start: { blockIndex: number; char: number };
1048
+ end: { blockIndex: number; char: number };
1049
+ } | null = null,
1050
+ ): boolean => {
1051
+ const intent = resolveNavKey(key, {
1052
+ isOwner,
1053
+ resolved,
1054
+ treeActive: railTab === "tree",
1055
+ isDiff,
1056
+ });
1057
+
1058
+ if (!intent) return false;
1059
+
1060
+ if (intent.type === "cut" && selection) {
1061
+ controller.cut(
1062
+ selection.start.blockIndex,
1063
+ selection.start.char,
1064
+ selection.end.char,
1065
+ selection.end.blockIndex,
1066
+ );
1067
+ } else dispatch(intent);
1068
+
1069
+ return true;
1070
+ };
1071
+ // clicking a sidebar thread moves the cursor onto it too, so the row shows its selected backdrop at once
1072
+ const openThread = (id: string): void => {
1073
+ // save the open editor into the leaving thread's working copy before the switch, so a click away never drops edits
1074
+ if (bodyEditing.editing) bodyEditing.requestExit();
1075
+
1076
+ const index = grouped.ordered.findIndex((thread) => thread.id === id);
1077
+
1078
+ if (index >= 0) setInboxCursor(() => index);
1079
+
1080
+ controller.open(id);
1081
+ };
1082
+
1083
+ const createEmptyThread = enabledThreadAction(
1084
+ canRunThreadAgent({
1085
+ enabled: threadAgentEnabled,
1086
+ owner: isOwner,
1087
+ editing: false,
1088
+ shared: isSharedThreadConnection(openClient, shareTransport),
1089
+ }),
1090
+ () => {
1091
+ void controller.createEmptyThread();
1092
+ setFocusedPane("thread");
1093
+ },
1094
+ );
1095
+
1096
+ const threadSurfaceHandledKey = (key: KeyEvent): boolean => {
1097
+ if (
1098
+ agentOwnsKeyboard(agentActive, focusedPane) &&
1099
+ (key.name === "return" || key.name === "enter") &&
1100
+ key.ctrl &&
1101
+ !key.meta &&
1102
+ !key.super
1103
+ )
1104
+ return true;
1105
+
1106
+ if (!threadViewActive || threadViewSuspended) return false;
1107
+
1108
+ if (!threadComposing) {
1109
+ const chord = resolveSessionChord(key, { isOwner, resolved });
1110
+
1111
+ if (chord) dispatch(chord);
1112
+ }
1113
+
1114
+ return true;
1115
+ };
1116
+
1117
+ useKeyboard((key) => {
1118
+ if (quitKeyHandled(key, onExit)) return;
1119
+
1120
+ // the inline body editor owns the pane and every key while open
1121
+ if (bodyEditing.editing) return;
1122
+
1123
+ // the share dialog owns its own keys while open; the shell grammar stands down
1124
+ if (shareDialogOpen) return;
1125
+
1126
+ if (menuModalHandled(menuControl, key)) return;
1127
+
1128
+ if (paneCycleRequested(key, overlay, menuOwnsKeyboard, threadComposing)) {
1129
+ return cyclePanes(Boolean(key.shift));
1130
+ }
1131
+
1132
+ if (
1133
+ threadsNavHandled({
1134
+ focusedPane,
1135
+ quiet: overlay === "none" && !menuOwnsKeyboard && !threadComposing,
1136
+ key,
1137
+ count: grouped.ordered.length,
1138
+ setInboxCursor,
1139
+ openSession: () => dispatch({ type: "openSession" }),
1140
+ })
1141
+ )
1142
+ return;
1143
+
1144
+ if (threadSurfaceHandledKey(key)) return;
1145
+
1146
+ // A compose textarea owns the keyboard while open: let it receive the typed note instead of the
1147
+ // global keymap acting on each letter (the prototype, and the bare-shell welcome playground).
1148
+ if (prototypeComposing || welcomeComposing) return;
1149
+
1150
+ if (menuDialog === "settings") return void handleSettingsKey(key.name);
1151
+
1152
+ if (menuDialog) return void (key.name === "escape" && setMenuDialog(null));
1153
+
1154
+ // the toast is non-modal: escape only dismisses it when nothing else owns
1155
+ // escape, so an open overlay (compose, submit, prompt, walk) still cancels
1156
+ if (toastDismissRequested(toast !== null, key, overlay, mode.type === "span"))
1157
+ return controller.dismissToast();
1158
+
1159
+ if (bareShellDefersKeys(session === null, overlay === "none", focusedPane)) return;
1160
+
1161
+ const state = buildKeyState({
1162
+ keys: keysRef.current,
1163
+ observer,
1164
+ isOwner,
1165
+ overlay,
1166
+ session,
1167
+ isDiff,
1168
+ mode,
1169
+ resolved,
1170
+ inbox,
1171
+ focusedAnnotationId,
1172
+ walk,
1173
+ walkFileList,
1174
+ rows,
1175
+ cursor,
1176
+ display,
1177
+ });
1178
+
1179
+ keyBindings.setContext({
1180
+ overlay: state.overlay,
1181
+ spanMode: state.spanMode,
1182
+ });
1183
+ const action = keyBindings.resolveAction({
1184
+ name: key.name,
1185
+ shift: !!key.shift,
1186
+ });
1187
+
1188
+ for (const intent of reduceKey(
1189
+ state,
1190
+ { name: key.name, shift: !!key.shift, meta: !!key.meta },
1191
+ action,
1192
+ ))
1193
+ dispatch(intent);
1194
+ });
1195
+
1196
+ // after every keyboard hook above, so their subscriptions precede the signal
1197
+ useReadySignal(usableScreenReached(error, session, inbox), onReady);
1198
+
1199
+ // ── shared bottom chrome: the menu bar and its drop-up dialogs, one render
1200
+ // reused by the inbox and by plan/diff review so the two never drift ──
1201
+ const menuChrome = (
1202
+ <MenuChrome
1203
+ menuDialog={menuDialog}
1204
+ theme={theme}
1205
+ keybindsSections={cheatsheetFor(keyBindings, threadViewActive)}
1206
+ settingsCategories={settingsCategories}
1207
+ settingsValues={settingsValues}
1208
+ settingsNav={settingsNav}
1209
+ onCategorySelect={onCategorySelect}
1210
+ cycleSetting={cycleSetting}
1211
+ onClose={() => setMenuDialog(null)}
1212
+ />
1213
+ );
1214
+
1215
+ // ── render ──────────────────────────────────
1216
+ if (error) return <ErrorScreen error={error} theme={theme} />;
1217
+
1218
+ if (!session)
1219
+ return inbox ? (
1220
+ <SlashSkillsContext.Provider value={skills}>
1221
+ <PaletteNamesContext.Provider value={paletteNames}>
1222
+ <NoThreadShell
1223
+ toast={toast}
1224
+ extensionRegistry={extensionRegistry}
1225
+ extensionContext={extensionContext(cwd, null)}
1226
+ rows={grouped.rows}
1227
+ inboxCursor={inboxCursor}
1228
+ onOpenThread={openThread}
1229
+ onCreateThread={createEmptyThread}
1230
+ mode={mode}
1231
+ theme={theme}
1232
+ controller={controller}
1233
+ setMode={setMode}
1234
+ menuChrome={menuChrome}
1235
+ onOpenMenu={openSettings}
1236
+ sidebarOpen={sidebarOpen}
1237
+ onToggleSidebar={() => setSidebarOpen((open) => !open)}
1238
+ focusedPane={focusedPane}
1239
+ onFocusPane={setFocusedPane}
1240
+ menuControl={menuControl}
1241
+ pinnedIds={pinnedIds}
1242
+ onPin={enabledThreadAction(canManageThreads, togglePin)}
1243
+ onRename={enabledThreadAction(canManageThreads, (id: string, title: string) =>
1244
+ setMode({ type: "renameThread", sessionId: id, text: title }),
1245
+ )}
1246
+ quickActions={quickActions}
1247
+ diffView={diffView}
1248
+ onWelcomeComposingChange={setWelcomeComposing}
1249
+ layout={layout}
1250
+ />
1251
+ </PaletteNamesContext.Provider>
1252
+ </SlashSkillsContext.Provider>
1253
+ ) : (
1254
+ <ConnectingScreen theme={theme} />
1255
+ );
1256
+
1257
+ const activeSession = session;
1258
+ const resolveAuthorLabel = authorLabelResolver(
1259
+ identity.name,
1260
+ activeSession.participants,
1261
+ authorNames,
1262
+ );
1263
+
1264
+ if (isCompletionOverlayPhase(completion) && activeSession.message)
1265
+ return (
1266
+ <CompletionScreen
1267
+ theme={theme}
1268
+ session={activeSession}
1269
+ message={activeSession.message.outcome}
1270
+ completion={completion}
1271
+ status={status}
1272
+ onClose={() => dispatch({ type: "finishReview" })}
1273
+ onBackToPlan={() => dispatch({ type: "dismissCompletion" })}
1274
+ onAlways={() => dispatch({ type: "optInAutoClose" })}
1275
+ />
1276
+ );
1277
+
1278
+ const diffFold: DiffFoldControls = {
1279
+ isCollapsed: (file) => controller.isFileCollapsed(file),
1280
+ isExpanded: (file) => controller.isFileExpanded(file),
1281
+ canExpand: (file) => controller.canExpandFile(file),
1282
+ onToggleCollapse: (file) =>
1283
+ controller.setFileCollapsed(file, !controller.isFileCollapsed(file)),
1284
+ onToggleExpand: (file) => controller.setFileExpanded(file, !controller.isFileExpanded(file)),
1285
+ onCopyPath: (file) => controller.copyFilePath(file),
1286
+ };
1287
+ const submitConfirmState = buildSubmitConfirmState({
1288
+ mode,
1289
+ isDiff,
1290
+ session: activeSession,
1291
+ walkFileList,
1292
+ viewedPaths,
1293
+ quickActions,
1294
+ liveInput,
1295
+ setMode,
1296
+ dispatch,
1297
+ });
1298
+ const { showOwnerActions, showDiffRefresh, prototypeCanComment, chromeHidden, prototypePath } =
1299
+ buildRenderFlags({
1300
+ session: activeSession,
1301
+ isOwner,
1302
+ isDiff,
1303
+ isPixelPrototype,
1304
+ resolved,
1305
+ menuDialog,
1306
+ resolvedIds,
1307
+ });
1308
+
1309
+ const onEditRequest = (): void => {
1310
+ // A share viewer/observer has no Edit affordance (the button is hidden), so
1311
+ // this is owner-only; stay silent rather than nag if it is ever reached.
1312
+ if (!isOwner) return;
1313
+
1314
+ if (resolved) return controller.setStatus("review submitted - read-only");
1315
+
1316
+ openBodyEditor();
1317
+ };
1318
+
1319
+ // clicking the rail Submit button: same read-only answer as the submit key
1320
+ const onSubmitRequest = (): void => {
1321
+ if (observer) return controller.setStatus("observer - read-only");
1322
+
1323
+ if (!isOwner) return controller.setStatus("shared view - your notes save as you go");
1324
+
1325
+ if (resolved) return;
1326
+
1327
+ dispatch({ type: "openSubmit" });
1328
+ };
1329
+
1330
+ const threadFooter = (
1331
+ <ThreadFooter
1332
+ controls={threadAgentControls(agentActive, agentControls)}
1333
+ repo={projectName(activeSession.workspace)}
1334
+ branch={activeSession.workspace.branch}
1335
+ onSubmit={onSubmitRequest}
1336
+ canSubmit={canSubmitReview(isOwner, resolved, observer)}
1337
+ pendingAnnotations={
1338
+ activeSession.annotations.filter(
1339
+ (annotation) => !isAddressed(annotation) && !isAgentNote(annotation),
1340
+ ).length
1341
+ }
1342
+ theme={theme}
1343
+ />
1344
+ );
1345
+
1346
+ return (
1347
+ <SlashSkillsContext.Provider value={skills}>
1348
+ <PaletteNamesContext.Provider value={paletteNames}>
1349
+ <ThemeProvider theme={theme}>
1350
+ <MenuControlProvider value={menuControl}>
1351
+ <AppShell
1352
+ extensionRegistry={extensionRegistry}
1353
+ extensionContext={{
1354
+ workspace: activeSession.workspace.repoRoot,
1355
+ threadId: activeSession.id,
1356
+ }}
1357
+ onExtensionError={showExtensionError}
1358
+ sidebarOpen={sidebarOpen}
1359
+ onToggleSidebar={() => setSidebarOpen((open) => !open)}
1360
+ onOpenMenu={openSettings}
1361
+ onFocusPane={setFocusedPane}
1362
+ focusedPane={focusedPane}
1363
+ threadsPanel={
1364
+ <scrollbox style={{ flexGrow: 1 }} focused={false}>
1365
+ <ThreadTree
1366
+ rows={grouped.rows}
1367
+ cursor={inboxCursor}
1368
+ activeId={activeSession.id}
1369
+ focused={focusedPane === "threads"}
1370
+ pinnedIds={pinnedIds}
1371
+ width={30}
1372
+ onSelect={openThread}
1373
+ onCreateThread={createEmptyThread}
1374
+ onPin={enabledThreadAction(canManageThreads, togglePin)}
1375
+ onRename={enabledThreadAction(canManageThreads, (id: string, title: string) =>
1376
+ setMode({ type: "renameThread", sessionId: id, text: title }),
1377
+ )}
1378
+ onRequestDelete={enabledThreadAction(
1379
+ canManageThreads,
1380
+ (id: string, title: string) =>
1381
+ setMode({ type: "confirmDelete", sessionId: id, title }),
1382
+ )}
1383
+ theme={theme}
1384
+ />
1385
+ </scrollbox>
1386
+ }
1387
+ threadTitle={reviewThreadTitle(activeSession)}
1388
+ threadActions={
1389
+ <>
1390
+ {showOwnerActions
1391
+ ? ownerThreadActions({
1392
+ editing: bodyEditing.editing,
1393
+ onEdit: onEditRequest,
1394
+ onExitEdit: bodyEditing.requestExit,
1395
+ onShare: () => dispatch({ type: "share" }),
1396
+ theme,
1397
+ })
1398
+ : showDiffRefresh
1399
+ ? refreshDiffAction(() => void controller.refreshDiff(), theme)
1400
+ : undefined}
1401
+ </>
1402
+ }
1403
+ threadPanel={
1404
+ <box style={{ flexGrow: 1, flexDirection: "column" }}>
1405
+ <box style={{ flexGrow: 1, flexDirection: "row" }}>
1406
+ <AgentThreadPrototype
1407
+ key={activeSession.id}
1408
+ client={agentClient}
1409
+ enabled={canRunThreadAgent({
1410
+ enabled: threadAgentEnabled,
1411
+ owner: isOwner,
1412
+ editing: bodyEditing.editing,
1413
+ shared: isSharedThreadConnection(openClient, shareTransport),
1414
+ sharedAgent: sharedAgentAvailable(agentClient, activeSession),
1415
+ })}
1416
+ observer={observer}
1417
+ pixelPrototype={isPixelPrototype}
1418
+ thread={activeSession}
1419
+ home={home}
1420
+ theme={theme}
1421
+ focused={focusedPane === "thread"}
1422
+ suspended={threadViewSuspended}
1423
+ onActiveChange={setAgentActive}
1424
+ onControlsChange={setAgentControls}
1425
+ onStateChange={setAgentState}
1426
+ onActionsChange={(actions) => {
1427
+ agentActions.current = actions;
1428
+ }}
1429
+ onInvokeChange={(invoke) => {
1430
+ agentInvoke.current = invoke;
1431
+ }}
1432
+ onRevealReply={() => setFocusedPane("thread")}
1433
+ flushMutations={() => flushReviewMutations(controller)}
1434
+ onOpenFile={(path) => workbench.openFile(path, "contents", true)}
1435
+ onNextPane={cyclePanes}
1436
+ >
1437
+ {chooseThreadBody({
1438
+ isPixelPrototype,
1439
+ isDiff,
1440
+ editingBody: bodyEditing.editing,
1441
+ prototype: (
1442
+ <PrototypePixels
1443
+ prototypePath={prototypePath}
1444
+ canComment={prototypeCanComment}
1445
+ onCommentElement={onCommentPrototype}
1446
+ onComposingChange={setPrototypeComposing}
1447
+ hidden={chromeHidden}
1448
+ />
1449
+ ),
1450
+ diffPlaceholder: activeSession.artifact.meta.prBrief ? (
1451
+ <ThreadView
1452
+ session={pullRequestBriefThread(activeSession)}
1453
+ display={buildDisplay(activeSession.artifact.meta.prBrief)}
1454
+ marks={new Map()}
1455
+ quickActions={quickActions}
1456
+ suspended={threadViewSuspended}
1457
+ resolved
1458
+ observer
1459
+ onComposingChange={() => {}}
1460
+ onObserverBlocked={() => {}}
1461
+ onCursorChange={() => {}}
1462
+ onAnnotate={() => {}}
1463
+ onReply={() => {}}
1464
+ onUpdateAnnotation={() => {}}
1465
+ resolveAuthorLabel={() => undefined}
1466
+ onExit={() => onExit?.(0)}
1467
+ />
1468
+ ) : (
1469
+ <box
1470
+ style={{
1471
+ flexGrow: 1,
1472
+ flexDirection: "column",
1473
+ alignItems: "center",
1474
+ justifyContent: "center",
1475
+ }}
1476
+ >
1477
+ <text fg={theme.textDim}>Select a thread</text>
1478
+ </box>
1479
+ ),
1480
+ editor: bodyEditing.renderEditor(theme),
1481
+ threadView: (
1482
+ <ThreadView
1483
+ session={activeSession}
1484
+ suspended={surfaceSuspended(threadViewSuspended, focusedPane, "thread")}
1485
+ editOrphanCount={editOrphanCount}
1486
+ onComposingChange={setThreadComposing}
1487
+ onNavCommand={runNavCommand}
1488
+ resolved={resolved}
1489
+ onObserverBlocked={(reason) =>
1490
+ controller.setStatus(
1491
+ reason === "observer"
1492
+ ? "observer - read-only"
1493
+ : "review submitted - read-only",
1494
+ )
1495
+ }
1496
+ onCursorChange={setCursor}
1497
+ focusedAnnotationId={focusedAnnotationId}
1498
+ onFocusAnnotation={setFocusedAnnotationId}
1499
+ display={display}
1500
+ marks={marks}
1501
+ quickActions={quickActions}
1502
+ observer={observer}
1503
+ onAnnotate={(span, body) =>
1504
+ controller.annotate(
1505
+ "comment",
1506
+ span.start.blockIndex,
1507
+ span.start.char,
1508
+ span.end.char,
1509
+ body,
1510
+ span.end.blockIndex,
1511
+ )
1512
+ }
1513
+ onReply={(rootAnnotationId, body) =>
1514
+ controller.reply(rootAnnotationId, body)
1515
+ }
1516
+ onUpdateAnnotation={(id, body) => controller.updateAnnotation(id, body)}
1517
+ resolveAuthorLabel={resolveAuthorLabel}
1518
+ onExit={() => onExit?.(0)}
1519
+ />
1520
+ ),
1521
+ })}
1522
+ </AgentThreadPrototype>
1523
+ </box>
1524
+ {threadFooter}
1525
+ </box>
1526
+ }
1527
+ changesOpen={workbench.changesOpen}
1528
+ projectOpen={workbench.projectOpen}
1529
+ onToggleChanges={workbench.toggleChanges}
1530
+ onToggleProject={workbench.toggleProject}
1531
+ onToggleRight={workbench.toggleRight}
1532
+ projectMode={workbench.projectMode}
1533
+ zoomHideThread={workbench.zoomed}
1534
+ changesFooter={threadFooter}
1535
+ changesPanel={
1536
+ <EditorGrid
1537
+ tree={workbench.grid}
1538
+ focusedGroupId={workbench.activeGroup}
1539
+ commentCounts={diffCommentCounts}
1540
+ onFocusGroup={workbench.focusGroup}
1541
+ onActivateTab={workbench.activate}
1542
+ onKeepTab={workbench.keepTab}
1543
+ onCloseTab={workbench.close}
1544
+ onSplit={workbench.split}
1545
+ onZoom={workbench.toggleZoom}
1546
+ zoomed={workbench.zoomed}
1547
+ renderTab={(tab, groupFocused) => (
1548
+ <GridTabContent
1549
+ tab={tab}
1550
+ rows={rows}
1551
+ surface={{
1552
+ session: activeSession,
1553
+ quickActions,
1554
+ observer,
1555
+ commentsEnabled: true,
1556
+ resolved,
1557
+ suspended: surfaceSuspended(
1558
+ threadViewSuspended || !groupFocused,
1559
+ focusedPane,
1560
+ "changes",
1561
+ ),
1562
+ onComposingChange: setThreadComposing,
1563
+ onObserverBlocked: (reason) =>
1564
+ controller.setStatus(
1565
+ reason === "observer"
1566
+ ? "observer - read-only"
1567
+ : "review submitted - read-only",
1568
+ ),
1569
+ onCursorChange: setCursor,
1570
+ focusedAnnotationId,
1571
+ onFocusAnnotation: setFocusedAnnotationId,
1572
+ // a diff thread's Changes view is the artifact itself; any other thread's is the
1573
+ // live working-tree diff, so its notes carry a file target and anchor there
1574
+ onAnnotate: (span, body) =>
1575
+ controller.annotate(
1576
+ "comment",
1577
+ span.start.blockIndex,
1578
+ span.start.char,
1579
+ span.end.char,
1580
+ body,
1581
+ span.end.blockIndex,
1582
+ isDiff
1583
+ ? { kind: "artifact" }
1584
+ : { kind: "file", path: "", rev: "worktree" },
1585
+ ),
1586
+ onReply: (rootAnnotationId, body) =>
1587
+ controller.reply(rootAnnotationId, body),
1588
+ onUpdateAnnotation: (id, body) => controller.updateAnnotation(id, body),
1589
+ onInvoke: agentActive
1590
+ ? (commentId) => {
1591
+ agentInvoke.current?.(commentId);
1592
+ setFocusedPane("thread");
1593
+ }
1594
+ : undefined,
1595
+ annotationAction: (id) => agentActions.current(id),
1596
+ isAnnotationReadOnly: (id) =>
1597
+ isSubmittedComment(agentState, activeSession.id, id),
1598
+ resolveAuthorLabel,
1599
+ onNavCommand: runNavCommand,
1600
+ onExit: () => onExit?.(0),
1601
+ }}
1602
+ rejectedRows={rejectedRows}
1603
+ fold={diffFold}
1604
+ fileStats={controller.fileStats()}
1605
+ split={diffView === "split" && workbench.zoomed}
1606
+ dimmed={walking}
1607
+ readFile={(path) => controller.repoReadFile(path)}
1608
+ onAddFileComment={(path, anchor, body) =>
1609
+ void controller.addComment(
1610
+ anchor,
1611
+ { kind: "file", path, rev: "worktree" },
1612
+ body,
1613
+ )
1614
+ }
1615
+ // zoomed, the footer already rides the Changes pane, so no extra offset is needed
1616
+ emptyBottomPadding={workbench.zoomed ? 0 : THREAD_FOOTER_HEIGHT}
1617
+ theme={theme}
1618
+ />
1619
+ )}
1620
+ theme={theme}
1621
+ />
1622
+ }
1623
+ projectPanel={
1624
+ <ProjectPanelBody
1625
+ mode={workbench.projectMode}
1626
+ loadChanges={() => controller.repoChanges()}
1627
+ initialFiles={initialReviewFiles(
1628
+ initialReviewForFirstMount.current,
1629
+ activeSession.id,
1630
+ )}
1631
+ loadProjectFiles={() => controller.repoFiles()}
1632
+ diffSourceKey={activeSession.id}
1633
+ {...projectDiffFiles(activeSession)}
1634
+ // the Changes navigator always opens a changed file as a diff - a diff review shows its
1635
+ // captured snapshot, every other thread the live working-tree diff
1636
+ onOpenChangedFile={(path, persistent) =>
1637
+ workbench.openFile(path, "diff", persistent)
1638
+ }
1639
+ onOpenProjectFile={(path, persistent) =>
1640
+ workbench.openFile(path, "contents", persistent)
1641
+ }
1642
+ commentCounts={diffCommentCounts}
1643
+ focused={focusedPane === "project"}
1644
+ theme={theme}
1645
+ />
1646
+ }
1647
+ theme={theme}
1648
+ >
1649
+ <TrailingOverlays
1650
+ walking={walking}
1651
+ walk={walk}
1652
+ walkFileList={walkFileList}
1653
+ viewedPaths={viewedPaths}
1654
+ session={activeSession}
1655
+ terminalWidth={terminalWidth}
1656
+ theme={theme}
1657
+ mode={mode}
1658
+ toast={toast}
1659
+ onDismissToast={() => controller.dismissToast()}
1660
+ setMode={setMode}
1661
+ dispatch={dispatch}
1662
+ />
1663
+ {submitConfirmState !== null ? (
1664
+ <box
1665
+ onMouseUp={submitConfirmState.onCancel}
1666
+ style={{
1667
+ position: "absolute",
1668
+ left: 0,
1669
+ top: 0,
1670
+ width: "100%",
1671
+ height: "100%",
1672
+ justifyContent: "center",
1673
+ alignItems: "center",
1674
+ }}
1675
+ >
1676
+ <box onMouseUp={(event) => event.stopPropagation()}>
1677
+ <ConfirmCard {...submitConfirmState} theme={theme} />
1678
+ </box>
1679
+ </box>
1680
+ ) : null}
1681
+ <ShareDialog
1682
+ key={String(shareDialogOpen)}
1683
+ isOpen={shareDialogOpen}
1684
+ threadName={shareThreadName(session)}
1685
+ links={shareLinksFor(session)}
1686
+ isOwner={isOwner}
1687
+ agentAvailable={canRunThreadAgent({
1688
+ enabled: threadAgentEnabled,
1689
+ owner: isOwner,
1690
+ editing: false,
1691
+ shared: isSharedThreadConnection(openClient, shareTransport),
1692
+ })}
1693
+ onCreateLink={(input) => controller.createShareLink(input)}
1694
+ onUpdateLink={(id, input) => controller.updateShareLink(id, input)}
1695
+ onDeleteLink={(id) => controller.deleteShareLink(id)}
1696
+ onCopyLink={(id) => controller.copyShareLink(id)}
1697
+ onClose={() => setShareDialogOpen(false)}
1698
+ theme={theme}
1699
+ />
1700
+ {menuChrome}
1701
+ </AppShell>
1702
+ </MenuControlProvider>
1703
+ </ThemeProvider>
1704
+ </PaletteNamesContext.Provider>
1705
+ </SlashSkillsContext.Provider>
1706
+ );
1707
+ }
1708
+
1709
+ function enabledThreadAction<Arguments extends unknown[]>(
1710
+ enabled: boolean,
1711
+ action: (...args: Arguments) => void,
1712
+ ): ((...args: Arguments) => void) | undefined {
1713
+ return enabled ? action : undefined;
1714
+ }
1715
+
1716
+ /** Experimental agent UI is available only in a local owner's review. */
1717
+ export function canRunThreadAgent(options: {
1718
+ enabled: boolean;
1719
+ owner: boolean;
1720
+ editing: boolean;
1721
+ shared: boolean;
1722
+ sharedAgent?: boolean;
1723
+ }): boolean {
1724
+ if (options.editing) return false;
1725
+
1726
+ return Boolean(options.sharedAgent || (options.enabled && options.owner && !options.shared));
1727
+ }
1728
+
1729
+ function sharedAgentAvailable(client: AppProps["agentClient"], thread: Thread): boolean {
1730
+ return Boolean(client && thread.shares?.[0]?.agentEnabled);
1731
+ }
1732
+
1733
+ function isSubmittedComment(
1734
+ state: import("@cueloop/schema").ThreadAgentState | undefined,
1735
+ threadId: string,
1736
+ commentId: string,
1737
+ ): boolean {
1738
+ return (
1739
+ state?.threadId === threadId &&
1740
+ Boolean(state.submissions?.some((entry) => entry.commentId === commentId))
1741
+ );
1742
+ }
1743
+
1744
+ function flushReviewMutations(controller: ReviewController): Promise<void> {
1745
+ return controller.flushMutations?.() ?? Promise.resolve();
1746
+ }
1747
+
1748
+ function threadAgentControls(active: boolean, controls: React.ReactNode): React.ReactNode {
1749
+ return active ? controls : undefined;
1750
+ }
1751
+
1752
+ /** Injected shared transports never own a local harness connection. */
1753
+ function isSharedThreadConnection(
1754
+ openClient: AppProps["openClient"],
1755
+ shareTransport: ShareTransport | undefined,
1756
+ ): boolean {
1757
+ return Boolean(openClient || shareTransport);
1758
+ }