@chatcode/cco-better-sidebar 0.18.0-alpha.0

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 (329) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +554 -0
  3. package/README_EN.md +563 -0
  4. package/assets/logo.svg +1 -0
  5. package/cordis.patch.yml +79 -0
  6. package/lib/client-editor.js +55744 -0
  7. package/lib/client-mermaid.js +208256 -0
  8. package/lib/client-registry.js +30378 -0
  9. package/lib/client-terminal.js +16894 -0
  10. package/lib/client.js +30378 -0
  11. package/lib/index.js +6897 -0
  12. package/lib/invariant.js +22 -0
  13. package/lib/types/agent-opens.d.ts +65 -0
  14. package/lib/types/agent-pty.d.ts +226 -0
  15. package/lib/types/browser-probe.d.ts +15 -0
  16. package/lib/types/bundle-route.d.ts +12 -0
  17. package/lib/types/chatcode-update.d.ts +47 -0
  18. package/lib/types/client/AccountMenu.d.ts +1 -0
  19. package/lib/types/client/AiRatioSection.d.ts +3 -0
  20. package/lib/types/client/BrowserView.d.ts +39 -0
  21. package/lib/types/client/ChatcodeGate.d.ts +6 -0
  22. package/lib/types/client/CodingPlanModelsSettings.d.ts +9 -0
  23. package/lib/types/client/DiffTab.d.ts +6 -0
  24. package/lib/types/client/DiffView.d.ts +51 -0
  25. package/lib/types/client/EditorHost.d.ts +13 -0
  26. package/lib/types/client/FenceErrorNotice.d.ts +5 -0
  27. package/lib/types/client/FileTree.d.ts +41 -0
  28. package/lib/types/client/FreeWindow.d.ts +29 -0
  29. package/lib/types/client/GitView.d.ts +12 -0
  30. package/lib/types/client/MarkdownHtml.d.ts +32 -0
  31. package/lib/types/client/OrphanedTab.d.ts +11 -0
  32. package/lib/types/client/PdfView.d.ts +6 -0
  33. package/lib/types/client/ReleaseNotesDialog.d.ts +11 -0
  34. package/lib/types/client/RenderBoundary.d.ts +32 -0
  35. package/lib/types/client/SandboxStatusBar.d.ts +10 -0
  36. package/lib/types/client/SideCardSection.d.ts +74 -0
  37. package/lib/types/client/Sidebar.d.ts +8 -0
  38. package/lib/types/client/TabBar.d.ts +54 -0
  39. package/lib/types/client/TerminalView.d.ts +24 -0
  40. package/lib/types/client/TextEditor.d.ts +10 -0
  41. package/lib/types/client/TreePanel.d.ts +27 -0
  42. package/lib/types/client/UpdateDialog.d.ts +10 -0
  43. package/lib/types/client/UpdateSettingsPanel.d.ts +1 -0
  44. package/lib/types/client/UpdateSettingsSection.d.ts +10 -0
  45. package/lib/types/client/UploadOverlay.d.ts +20 -0
  46. package/lib/types/client/UsageHeatmapSection.d.ts +4 -0
  47. package/lib/types/client/add-plugin-modal.d.ts +15 -0
  48. package/lib/types/client/api.d.ts +345 -0
  49. package/lib/types/client/binary-download.d.ts +12 -0
  50. package/lib/types/client/breakpoints.d.ts +17 -0
  51. package/lib/types/client/browser.d.ts +60 -0
  52. package/lib/types/client/builtins/index.d.ts +18 -0
  53. package/lib/types/client/builtins/tabs.d.ts +11 -0
  54. package/lib/types/client/builtins/viewers.d.ts +3 -0
  55. package/lib/types/client/chat-presentation.d.ts +13 -0
  56. package/lib/types/client/chunk-loader.d.ts +124 -0
  57. package/lib/types/client/chunks/editor.d.ts +9 -0
  58. package/lib/types/client/chunks/mermaid.d.ts +10 -0
  59. package/lib/types/client/chunks/terminal.d.ts +9 -0
  60. package/lib/types/client/cm-themes.d.ts +24 -0
  61. package/lib/types/client/conversation-draft.d.ts +14 -0
  62. package/lib/types/client/desktop-env.d.ts +35 -0
  63. package/lib/types/client/editor-load.d.ts +66 -0
  64. package/lib/types/client/frame-batcher.d.ts +24 -0
  65. package/lib/types/client/icons.d.ts +66 -0
  66. package/lib/types/client/image-types.d.ts +3 -0
  67. package/lib/types/client/ime-guard.d.ts +36 -0
  68. package/lib/types/client/index.d.ts +19 -0
  69. package/lib/types/client/intercept.d.ts +44 -0
  70. package/lib/types/client/lang.d.ts +14 -0
  71. package/lib/types/client/layout-push.d.ts +15 -0
  72. package/lib/types/client/lazy-chunk.d.ts +25 -0
  73. package/lib/types/client/link-intercept.d.ts +42 -0
  74. package/lib/types/client/locales-ar.d.ts +18 -0
  75. package/lib/types/client/locales-de.d.ts +4 -0
  76. package/lib/types/client/locales-fr.d.ts +10 -0
  77. package/lib/types/client/locales-hi.d.ts +17 -0
  78. package/lib/types/client/locales-id.d.ts +15 -0
  79. package/lib/types/client/locales-it.d.ts +8 -0
  80. package/lib/types/client/locales-ja.d.ts +17 -0
  81. package/lib/types/client/locales-ko.d.ts +9 -0
  82. package/lib/types/client/locales-nl.d.ts +16 -0
  83. package/lib/types/client/locales-pl.d.ts +19 -0
  84. package/lib/types/client/locales-pt.d.ts +1 -0
  85. package/lib/types/client/locales-ru.d.ts +13 -0
  86. package/lib/types/client/locales-sv.d.ts +1 -0
  87. package/lib/types/client/locales-th.d.ts +17 -0
  88. package/lib/types/client/locales-tr.d.ts +17 -0
  89. package/lib/types/client/locales-vi.d.ts +17 -0
  90. package/lib/types/client/locales-zh-HK.d.ts +32 -0
  91. package/lib/types/client/locales-zh-MO.d.ts +32 -0
  92. package/lib/types/client/locales-zh-TW.d.ts +32 -0
  93. package/lib/types/client/locales.d.ts +571 -0
  94. package/lib/types/client/markdown-html.d.ts +96 -0
  95. package/lib/types/client/markdown-images.d.ts +45 -0
  96. package/lib/types/client/markdown-labels.d.ts +21 -0
  97. package/lib/types/client/md-toc.d.ts +4 -0
  98. package/lib/types/client/mermaid-blocks.d.ts +47 -0
  99. package/lib/types/client/mermaid-sanitize.d.ts +2 -0
  100. package/lib/types/client/mermaid.d.ts +12 -0
  101. package/lib/types/client/open-when-sized.d.ts +20 -0
  102. package/lib/types/client/open-with-settings.d.ts +4 -0
  103. package/lib/types/client/open-with.d.ts +87 -0
  104. package/lib/types/client/openpath-intercept.d.ts +52 -0
  105. package/lib/types/client/paths.d.ts +43 -0
  106. package/lib/types/client/pdf-types.d.ts +2 -0
  107. package/lib/types/client/pinned.d.ts +86 -0
  108. package/lib/types/client/plugin-settings.d.ts +8 -0
  109. package/lib/types/client/plugins-shared.d.ts +27 -0
  110. package/lib/types/client/plugins-tabs.d.ts +3 -0
  111. package/lib/types/client/plugins-viewers.d.ts +3 -0
  112. package/lib/types/client/prefs.d.ts +41 -0
  113. package/lib/types/client/produced-files.d.ts +29 -0
  114. package/lib/types/client/selection-payload.d.ts +27 -0
  115. package/lib/types/client/service.d.ts +445 -0
  116. package/lib/types/client/session-pins.d.ts +14 -0
  117. package/lib/types/client/settings-nav-icon.d.ts +27 -0
  118. package/lib/types/client/shell-presets.d.ts +48 -0
  119. package/lib/types/client/split-pane.d.ts +38 -0
  120. package/lib/types/client/state.d.ts +480 -0
  121. package/lib/types/client/tab-content-memo.d.ts +40 -0
  122. package/lib/types/client/terminal-font.d.ts +78 -0
  123. package/lib/types/client/terminal-links.d.ts +119 -0
  124. package/lib/types/client/theme.d.ts +45 -0
  125. package/lib/types/client/titlebar-strip.d.ts +23 -0
  126. package/lib/types/client/ui-tweaks/appicons.d.ts +16 -0
  127. package/lib/types/client/ui-tweaks/archive.d.ts +42 -0
  128. package/lib/types/client/ui-tweaks/branding.d.ts +45 -0
  129. package/lib/types/client/ui-tweaks/cachehit.d.ts +41 -0
  130. package/lib/types/client/ui-tweaks/gitbar.d.ts +103 -0
  131. package/lib/types/client/ui-tweaks/index.d.ts +279 -0
  132. package/lib/types/client/ui-tweaks/mcp.d.ts +28 -0
  133. package/lib/types/client/ui-tweaks/notifier.d.ts +125 -0
  134. package/lib/types/client/ui-tweaks/whale.d.ts +55 -0
  135. package/lib/types/client/upload.d.ts +69 -0
  136. package/lib/types/client/useChatcodeAccount.d.ts +10 -0
  137. package/lib/types/client/wco.d.ts +47 -0
  138. package/lib/types/codingplan.d.ts +37 -0
  139. package/lib/types/config.d.ts +95 -0
  140. package/lib/types/context-types.d.ts +540 -0
  141. package/lib/types/fs-operations.d.ts +30 -0
  142. package/lib/types/fs-search.d.ts +24 -0
  143. package/lib/types/fs-tree.d.ts +51 -0
  144. package/lib/types/git.d.ts +124 -0
  145. package/lib/types/html-route.d.ts +59 -0
  146. package/lib/types/index.d.ts +47 -0
  147. package/lib/types/invariant.d.ts +15 -0
  148. package/lib/types/login-route.d.ts +2 -0
  149. package/lib/types/open-external.d.ts +24 -0
  150. package/lib/types/path-security.d.ts +26 -0
  151. package/lib/types/prefs-shared.d.ts +257 -0
  152. package/lib/types/pty-deps.d.ts +79 -0
  153. package/lib/types/pty-manager.d.ts +168 -0
  154. package/lib/types/tools.d.ts +34 -0
  155. package/lib/types/trust-fence.d.ts +24 -0
  156. package/lib/types/ui-tweaks/archive.d.ts +71 -0
  157. package/lib/types/ui-tweaks/config.d.ts +186 -0
  158. package/lib/types/ui-tweaks/git-web.d.ts +43 -0
  159. package/lib/types/ui-tweaks/git.d.ts +311 -0
  160. package/lib/types/ui-tweaks/index.d.ts +17 -0
  161. package/lib/types/ui-tweaks/mcp.d.ts +103 -0
  162. package/lib/types/ui-tweaks/turn-outcome.d.ts +57 -0
  163. package/lib/types/ui-tweaks/web.d.ts +55 -0
  164. package/lib/types/wire.d.ts +38 -0
  165. package/package.json +213 -0
  166. package/scripts/install.ps1 +310 -0
  167. package/scripts/install.sh +287 -0
  168. package/src/agent-opens.ts +265 -0
  169. package/src/agent-pty.ts +527 -0
  170. package/src/browser-probe.ts +26 -0
  171. package/src/bundle-route.ts +129 -0
  172. package/src/chatcode-update.ts +193 -0
  173. package/src/client/AccountMenu.tsx +177 -0
  174. package/src/client/AiRatioSection.module.css +329 -0
  175. package/src/client/AiRatioSection.tsx +292 -0
  176. package/src/client/BrowserView.tsx +289 -0
  177. package/src/client/ChatcodeGate.tsx +35 -0
  178. package/src/client/CodingPlanModelsSettings.module.css +118 -0
  179. package/src/client/CodingPlanModelsSettings.tsx +101 -0
  180. package/src/client/DiffTab.tsx +114 -0
  181. package/src/client/DiffView.tsx +305 -0
  182. package/src/client/EditorHost.tsx +563 -0
  183. package/src/client/FenceErrorNotice.tsx +40 -0
  184. package/src/client/FileTree.tsx +701 -0
  185. package/src/client/FreeWindow.tsx +337 -0
  186. package/src/client/GitView.tsx +722 -0
  187. package/src/client/MarkdownHtml.tsx +296 -0
  188. package/src/client/OrphanedTab.tsx +27 -0
  189. package/src/client/PdfView.tsx +110 -0
  190. package/src/client/ReleaseNotesDialog.tsx +91 -0
  191. package/src/client/RenderBoundary.tsx +49 -0
  192. package/src/client/SandboxStatusBar.tsx +60 -0
  193. package/src/client/SideCardSection.module.css +932 -0
  194. package/src/client/SideCardSection.tsx +1169 -0
  195. package/src/client/Sidebar.tsx +1857 -0
  196. package/src/client/TabBar.tsx +365 -0
  197. package/src/client/TerminalView.tsx +424 -0
  198. package/src/client/TextEditor.tsx +468 -0
  199. package/src/client/TreePanel.tsx +279 -0
  200. package/src/client/UpdateDialog.tsx +186 -0
  201. package/src/client/UpdateSettingsPanel.tsx +29 -0
  202. package/src/client/UpdateSettingsSection.tsx +22 -0
  203. package/src/client/UploadOverlay.tsx +62 -0
  204. package/src/client/UsageHeatmapSection.module.css +440 -0
  205. package/src/client/UsageHeatmapSection.tsx +301 -0
  206. package/src/client/add-plugin-modal.tsx +199 -0
  207. package/src/client/api.ts +433 -0
  208. package/src/client/binary-download.tsx +23 -0
  209. package/src/client/breakpoints.ts +61 -0
  210. package/src/client/browser.ts +167 -0
  211. package/src/client/builtins/index.ts +37 -0
  212. package/src/client/builtins/tabs.tsx +275 -0
  213. package/src/client/builtins/viewers.tsx +125 -0
  214. package/src/client/chat-presentation.ts +95 -0
  215. package/src/client/chunk-loader.ts +350 -0
  216. package/src/client/chunks/editor.tsx +9 -0
  217. package/src/client/chunks/mermaid.tsx +10 -0
  218. package/src/client/chunks/terminal.tsx +9 -0
  219. package/src/client/cm-themes.ts +129 -0
  220. package/src/client/conversation-draft.ts +29 -0
  221. package/src/client/css-modules.d.ts +5 -0
  222. package/src/client/desktop-env.ts +72 -0
  223. package/src/client/editor-load.ts +92 -0
  224. package/src/client/frame-batcher.ts +56 -0
  225. package/src/client/icons.tsx +170 -0
  226. package/src/client/image-types.ts +8 -0
  227. package/src/client/ime-guard.ts +47 -0
  228. package/src/client/index.tsx +501 -0
  229. package/src/client/intercept.tsx +172 -0
  230. package/src/client/lang.ts +225 -0
  231. package/src/client/layout-push.ts +37 -0
  232. package/src/client/layout.css +156 -0
  233. package/src/client/lazy-chunk.tsx +89 -0
  234. package/src/client/link-intercept.ts +73 -0
  235. package/src/client/locales-ar.ts +387 -0
  236. package/src/client/locales-de.ts +372 -0
  237. package/src/client/locales-fr.ts +379 -0
  238. package/src/client/locales-hi.ts +386 -0
  239. package/src/client/locales-id.ts +384 -0
  240. package/src/client/locales-it.ts +377 -0
  241. package/src/client/locales-ja.ts +486 -0
  242. package/src/client/locales-ko.ts +378 -0
  243. package/src/client/locales-nl.ts +384 -0
  244. package/src/client/locales-pl.ts +388 -0
  245. package/src/client/locales-pt.ts +369 -0
  246. package/src/client/locales-ru.ts +384 -0
  247. package/src/client/locales-sv.ts +369 -0
  248. package/src/client/locales-th.ts +386 -0
  249. package/src/client/locales-tr.ts +386 -0
  250. package/src/client/locales-vi.ts +386 -0
  251. package/src/client/locales-zh-HK.ts +401 -0
  252. package/src/client/locales-zh-MO.ts +401 -0
  253. package/src/client/locales-zh-TW.ts +401 -0
  254. package/src/client/locales.ts +1229 -0
  255. package/src/client/markdown-html.ts +331 -0
  256. package/src/client/markdown-images.ts +137 -0
  257. package/src/client/markdown-labels.tsx +31 -0
  258. package/src/client/md-toc.tsx +127 -0
  259. package/src/client/mermaid-blocks.ts +110 -0
  260. package/src/client/mermaid-sanitize.ts +93 -0
  261. package/src/client/mermaid.tsx +406 -0
  262. package/src/client/open-when-sized.ts +43 -0
  263. package/src/client/open-with-settings.tsx +135 -0
  264. package/src/client/open-with.ts +221 -0
  265. package/src/client/openpath-intercept.ts +79 -0
  266. package/src/client/paths.ts +63 -0
  267. package/src/client/pdf-types.ts +4 -0
  268. package/src/client/pinned.ts +184 -0
  269. package/src/client/plugin-settings.ts +43 -0
  270. package/src/client/plugins-shared.ts +29 -0
  271. package/src/client/plugins-tabs.ts +153 -0
  272. package/src/client/plugins-viewers.ts +44 -0
  273. package/src/client/prefs.ts +216 -0
  274. package/src/client/produced-files.ts +120 -0
  275. package/src/client/selection-payload.ts +86 -0
  276. package/src/client/service.ts +873 -0
  277. package/src/client/session-pins.tsx +334 -0
  278. package/src/client/settings-nav-icon.ts +55 -0
  279. package/src/client/shell-presets.ts +83 -0
  280. package/src/client/sidebar.module.css +3607 -0
  281. package/src/client/split-pane.tsx +333 -0
  282. package/src/client/state.ts +1646 -0
  283. package/src/client/tab-content-memo.ts +55 -0
  284. package/src/client/terminal-font.ts +224 -0
  285. package/src/client/terminal-links.ts +194 -0
  286. package/src/client/theme.ts +110 -0
  287. package/src/client/titlebar-strip.ts +37 -0
  288. package/src/client/ui-tweaks/appicons.ts +24 -0
  289. package/src/client/ui-tweaks/archive.tsx +281 -0
  290. package/src/client/ui-tweaks/branding.tsx +232 -0
  291. package/src/client/ui-tweaks/cachehit.tsx +122 -0
  292. package/src/client/ui-tweaks/gitbar.tsx +2559 -0
  293. package/src/client/ui-tweaks/index.tsx +1696 -0
  294. package/src/client/ui-tweaks/mcp.tsx +582 -0
  295. package/src/client/ui-tweaks/notifier.ts +514 -0
  296. package/src/client/ui-tweaks/whale.tsx +171 -0
  297. package/src/client/upload.ts +187 -0
  298. package/src/client/useChatcodeAccount.ts +103 -0
  299. package/src/client/wco.ts +120 -0
  300. package/src/codingplan.ts +146 -0
  301. package/src/config.ts +207 -0
  302. package/src/context-types.ts +559 -0
  303. package/src/fs-operations.ts +97 -0
  304. package/src/fs-search.ts +113 -0
  305. package/src/fs-tree.ts +158 -0
  306. package/src/git.ts +446 -0
  307. package/src/html-route.ts +106 -0
  308. package/src/index.ts +1524 -0
  309. package/src/invariant.ts +32 -0
  310. package/src/login-route.ts +26 -0
  311. package/src/open-external.ts +90 -0
  312. package/src/path-security.ts +81 -0
  313. package/src/prefs-shared.ts +303 -0
  314. package/src/pty-deps.ts +241 -0
  315. package/src/pty-manager.ts +376 -0
  316. package/src/tools.ts +482 -0
  317. package/src/trust-fence.ts +84 -0
  318. package/src/ui-tweaks/archive.ts +293 -0
  319. package/src/ui-tweaks/config.ts +257 -0
  320. package/src/ui-tweaks/git-web.ts +421 -0
  321. package/src/ui-tweaks/git.ts +1524 -0
  322. package/src/ui-tweaks/index.ts +61 -0
  323. package/src/ui-tweaks/mcp.ts +535 -0
  324. package/src/ui-tweaks/turn-outcome.ts +105 -0
  325. package/src/ui-tweaks/web.ts +225 -0
  326. package/src/wire.ts +110 -0
  327. package/vendor/addon-fit.js +2 -0
  328. package/vendor/xterm.css +218 -0
  329. package/vendor/xterm.js +5 -0
@@ -0,0 +1,1646 @@
1
+ /**
2
+ * Per-session sidebar state: the panel geometry, the split-pane workbench
3
+ * tree, open tabs, and the explorer expansion set. One state instance per
4
+ * conversation id, persisted to localStorage under `dsh-sidebar:v1:<id>` so
5
+ * a reload restores the exact layout of the session it belongs to — switching
6
+ * conversations swaps the whole state (memory + isolation).
7
+ *
8
+ * The split tree is a recursive structure: a leaf holds a tab group, a split
9
+ * divides the space row- or column-wise with fractional sizes. All tree
10
+ * operations are pure functions over the node, unit-tested in tests/state.spec.ts.
11
+ */
12
+ import { SIDEBAR_PREFS_DEFAULTS, type SidebarPrefs } from '../prefs-shared.ts'
13
+ import { isNarrowWidth } from './breakpoints.ts'
14
+
15
+ /**
16
+ * Tab type identifier. Builtins register their ids (editor / git / terminal
17
+ * / browser / diff) through the sidebar service; external
18
+ * plugins register their own (e.g. `'my-plugin:db'`). Kept as `string` so
19
+ * the registry stays open.
20
+ */
21
+ export type TabType = string
22
+
23
+ /** What a diff tab shows: a worktree/index change of one path, or one commit's full patch. */
24
+ export type SidebarDiffRef =
25
+ | { kind: 'worktree'; path: string; staged: boolean; untracked?: boolean; worktree?: string; repoRoot?: string }
26
+ | { kind: 'commit'; hash: string; hashFull: string; subject: string; worktree?: string; repoRoot?: string }
27
+
28
+ /** One open tab. `path` carries the file (editor) or is absent (git/terminal);
29
+ * `diff` carries the change a diff tab shows; `meta` (v0.12.0+) carries
30
+ * plugin-owned JSON-serializable state, preserved across reloads. */
31
+ export interface SidebarTab {
32
+ id: string
33
+ type: TabType
34
+ title: string
35
+ path?: string
36
+ diff?: SidebarDiffRef
37
+ /** Plugin-owned state (v0.12.0+): MUST be JSON-serializable — it is
38
+ * persisted with the layout and restored verbatim on reload. */
39
+ meta?: unknown
40
+ /** Pinned-terminal marker (v0.17.0+): a pinned terminal tab survives a
41
+ * session switch in its home session's state and surfaces in the
42
+ * PinnedRail of every session the scope allows. `homeCwd` is the cwd
43
+ * snapshot at pin time — a `workspace`-scoped pin is only visible to
44
+ * sessions whose cwd matches it. Absent = unpinned (legacy states). */
45
+ pin?: { scope: 'workspace' | 'global'; homeCwd?: string }
46
+ }
47
+
48
+ /** A tab group. */
49
+ export interface SidebarLeaf {
50
+ kind: 'leaf'
51
+ id: string
52
+ tabs: SidebarTab[]
53
+ active: string | null
54
+ }
55
+
56
+ /** A recursive split between child panes (fractional sizes summing to 1). */
57
+ export interface SidebarSplit {
58
+ kind: 'split'
59
+ id: string
60
+ dir: 'row' | 'col'
61
+ sizes: number[]
62
+ children: SplitNode[]
63
+ }
64
+
65
+ export type SplitNode = SidebarLeaf | SidebarSplit
66
+
67
+ /**
68
+ * One free window: a tab dragged out of the workbench onto the conversation
69
+ * area floats in the panel host at viewport coordinates. The tab is OWNED by
70
+ * the window exactly like a pane owns its tabs (moved, not copied); geometry
71
+ * persists with the session so a reload restores the window in place.
72
+ * Stacking order is the array order (last = topmost).
73
+ */
74
+ export interface FloatWindow {
75
+ id: string
76
+ tab: SidebarTab
77
+ /** Viewport coordinates of the window's top-left corner. */
78
+ x: number
79
+ y: number
80
+ w: number
81
+ h: number
82
+ }
83
+
84
+ /** The full per-session state. */
85
+ export interface SidebarState {
86
+ panelOpen: boolean
87
+ width: number
88
+ /** The pane receiving newly opened tabs (last pane the user touched).
89
+ * Pane ids are globally unique across BOTH trees (shared uid counter), so
90
+ * one field resolves into either tree — see {@link treeOf}. */
91
+ activePane: string | null
92
+ /** Monotonic terminal tab counter (ids survive reloads). */
93
+ nextTerminal: number
94
+ /** Monotonic browser tab counter (ids survive reloads; mirrors nextTerminal). */
95
+ nextBrowser: number
96
+ /** Explorer expansion set (absolute directory paths). */
97
+ expanded: string[]
98
+ /**
99
+ * Explorer rows highlighted by a "Show in folder" reveal (absolute paths).
100
+ * Transient by design: sanitizeState never restores it, so a reload starts
101
+ * unhighlighted.
102
+ */
103
+ revealed: string[]
104
+ /** The right sidebar's split tree (the original workbench). */
105
+ splits: SplitNode
106
+ /** Whether the bottom panel (a second, independent workbench) is open. */
107
+ bottomOpen: boolean
108
+ /** The bottom panel's height (clamped to the contract range). */
109
+ bottomHeight: number
110
+ /**
111
+ * Whether the bottom panel has been expanded at least once in this
112
+ * session — the FIRST expansion tries to auto-open a terminal tab (gated
113
+ * on the bottomPanelAutoTerminal pref); later expansions never do.
114
+ */
115
+ bottomOpenedOnce: boolean
116
+ /** The bottom panel's own split tree (panes/tabs live only in ONE tree;
117
+ * tabs never cross panels — the two panels only share panel-size drags). */
118
+ bottomSplits: SplitNode
119
+ /** Free windows (tabs dragged out onto the conversation area). */
120
+ floats: FloatWindow[]
121
+ }
122
+
123
+ export const PANEL_MIN = 280
124
+ export const PANEL_MAX = 640
125
+ export const PANEL_DEFAULT = 400
126
+ export const TAB_MAX_WIDTH = 160
127
+ /** Bottom panel geometry contract (mirrors the width contract; the upper
128
+ * bound is the viewport, enforced by {@link setBottomHeight}). */
129
+ export const BOTTOM_MIN = 120
130
+ export const BOTTOM_DEFAULT = 220
131
+ /** Free-window geometry contract: the floor keeps the window usable (a
132
+ * header plus some content), the ceiling is the viewport. */
133
+ export const FLOAT_MIN_W = 320
134
+ export const FLOAT_MIN_H = 200
135
+ /** Geometry a fresh free window starts with: a phone-like portrait ratio
136
+ * (390×780 ≈ 1:2). The creation path additionally caps the size to the
137
+ * viewport (minus a 24px margin), so a short viewport gets a shorter —
138
+ * not overflowing — window instead of an exact ratio. */
139
+ export const FLOAT_DEFAULT_W = 390
140
+ export const FLOAT_DEFAULT_H = 780
141
+
142
+ let nextIdCounter = 0
143
+ /** Unique pane/tab id within one state instance. */
144
+ function uid(prefix: string): string {
145
+ nextIdCounter += 1
146
+ return `${prefix}:${nextIdCounter}`
147
+ }
148
+
149
+ /** Mint a fresh uid-based tab id. The `'editor:' + path` convention only
150
+ * covers openSidebarFile opens (per-path dedupe); opens that must not
151
+ * dedupe (the tree's "open to the side") mint through here. */
152
+ export function mintTabId(): string {
153
+ return uid('tab')
154
+ }
155
+
156
+ /**
157
+ * The largest numeric suffix across a raw persisted state's counter ids
158
+ * (`pane:N` / `tab:N` / `split:N`). The uid counter is module-global and
159
+ * resets on every reload, so a split minted AFTER a reload would collide
160
+ * with the persisted ids (a fresh "pane:1" beside the persisted "pane:1");
161
+ * mapLeaf would then visit BOTH leaves and every open would land in both
162
+ * panes of the split. Seeding the counter past the persisted ids keeps
163
+ * fresh ids disjoint.
164
+ */
165
+ function maxCounterId(parsed: unknown): number {
166
+ let max = 0
167
+ const consider = (id: unknown): void => {
168
+ if (typeof id !== 'string') return
169
+ const match = /^(?:pane|tab|split):(\d+)$/.exec(id)
170
+ if (match !== null) max = Math.max(max, Number(match[1]))
171
+ }
172
+ const walk = (node: unknown): void => {
173
+ if (node === null || typeof node !== 'object') return
174
+ const record = node as Record<string, unknown>
175
+ consider(record.id)
176
+ if (Array.isArray(record.tabs)) {
177
+ for (const tab of record.tabs) {
178
+ if (tab !== null && typeof tab === 'object') consider((tab as Record<string, unknown>).id)
179
+ }
180
+ }
181
+ if (Array.isArray(record.children)) {
182
+ for (const child of record.children) walk(child)
183
+ }
184
+ }
185
+ walk((parsed as Record<string, unknown> | null)?.splits)
186
+ walk((parsed as Record<string, unknown> | null)?.bottomSplits)
187
+ // Free windows mint through the same shared counter; their ids must seed it
188
+ // too (a persisted float:N with a lower pane max would collide otherwise).
189
+ const floats = (parsed as Record<string, unknown> | null)?.floats
190
+ if (Array.isArray(floats)) {
191
+ for (const float of floats) {
192
+ if (float !== null && typeof float === 'object') consider((float as Record<string, unknown>).id)
193
+ }
194
+ }
195
+ return max
196
+ }
197
+
198
+ /** The default tab a fresh session seeds. */
199
+ export type DefaultSeed = 'editor-home' | 'none'
200
+
201
+ /** A fresh default state: one seeded tab in one pane, open per the caller's
202
+ * preference. `width` is the caller's preferred panel width (default
203
+ * PANEL_DEFAULT) and `panelOpen` whether the panel starts expanded (default
204
+ * true); the store seeds new sessions from the user's side card prefs.
205
+ * `seed` picks the seeded tab: 'editor-home' places the EMPTY files window
206
+ * (an editor tab with no path whose tree panel starts open,
207
+ * `meta.treeOpen: true`) — in BOTH editorExplorer modes that window is the
208
+ * file explorer page — and 'none' starts with an empty pane (the store
209
+ * passes it when the user disabled the editor tab type in settings). */
210
+ export function makeDefaultState(width = PANEL_DEFAULT, panelOpen = true, seed: DefaultSeed = 'editor-home'): SidebarState {
211
+ const leaf: SidebarLeaf = { kind: 'leaf', id: uid('pane'), tabs: [], active: null }
212
+ if (seed === 'editor-home') {
213
+ // No path: the editor host renders its empty-state hint and the docked
214
+ // tree panel (treeOpen defaults open for path-less tabs; meta pins it).
215
+ leaf.tabs = [{ id: uid('tab'), type: 'editor', title: 'Files', meta: { treeOpen: true } }]
216
+ leaf.active = leaf.tabs[0]!.id
217
+ }
218
+ // The bottom panel starts closed with an empty pane (its welcome cards
219
+ // offer the openable types on first use).
220
+ const bottomLeaf: SidebarLeaf = { kind: 'leaf', id: uid('pane'), tabs: [], active: null }
221
+ return {
222
+ panelOpen,
223
+ width,
224
+ activePane: leaf.id,
225
+ nextTerminal: 1,
226
+ nextBrowser: 1,
227
+ expanded: [],
228
+ revealed: [],
229
+ splits: leaf,
230
+ bottomOpen: false,
231
+ bottomHeight: BOTTOM_DEFAULT,
232
+ bottomOpenedOnce: false,
233
+ bottomSplits: bottomLeaf,
234
+ floats: [],
235
+ }
236
+ }
237
+
238
+ /** Whether a tree node (or any descendant) carries the given pane/split id. */
239
+ function treeHasId(node: SplitNode, id: string): boolean {
240
+ if (node.id === id) return true
241
+ if (node.kind === 'split') return node.children.some(child => treeHasId(child, id))
242
+ return false
243
+ }
244
+
245
+ /** Which tree owns a pane/split id: 'bottomSplits' when the id lives in the
246
+ * bottom panel's tree, else 'splits' (the right panel's tree). Ids are
247
+ * globally unique (the shared uid counter), so an id in neither tree falls
248
+ * back to the right tree, where tree operations no-op on a missing node —
249
+ * the pre-bottom-panel behavior. */
250
+ export function treeOf(state: SidebarState, id: string): 'splits' | 'bottomSplits' {
251
+ return treeHasId(state.bottomSplits, id) ? 'bottomSplits' : 'splits'
252
+ }
253
+
254
+ /** Walk the tree and apply `visit` to the leaf with the given id. */
255
+ export function mapLeaf(node: SplitNode, paneId: string, visit: (leaf: SidebarLeaf) => void): SplitNode {
256
+ if (node.kind === 'leaf') {
257
+ if (node.id === paneId) {
258
+ const copy: SidebarLeaf = { ...node, tabs: [...node.tabs] }
259
+ visit(copy)
260
+ return copy
261
+ }
262
+ return node
263
+ }
264
+ const split = node
265
+ return {
266
+ ...split,
267
+ sizes: [...split.sizes],
268
+ children: split.children.map(child => mapLeaf(child, paneId, visit)),
269
+ }
270
+ }
271
+
272
+ /** The first leaf of the tree (fallback pane when activePane is gone). */
273
+ export function firstLeaf(node: SplitNode): SidebarLeaf {
274
+ if (node.kind === 'leaf') return node
275
+ return firstLeaf(node.children[0]!)
276
+ }
277
+
278
+ /** Empty every leaf of a tree (the bottom tree after its tabs migrate out). */
279
+ function clearAllTabs(node: SplitNode): SplitNode {
280
+ if (node.kind === 'leaf') return { ...node, tabs: [], active: null }
281
+ return { ...node, children: node.children.map(clearAllTabs) }
282
+ }
283
+
284
+ /**
285
+ * Narrow-viewport migration: the bottom panel's tabs are thrown INTO the
286
+ * right sidebar — the "merged display" on mobile is the right panel alone,
287
+ * whose tab strips now carry the bottom tree's tabs (depth-first order,
288
+ * appended to the right tree's FIRST leaf). The bottom tree is emptied (its
289
+ * structure stays — the desktop bottom panel re-renders its welcome cards)
290
+ * and the panel closes. The active pane moves to the right tree's first
291
+ * leaf so every new tab lands in the visible panel.
292
+ *
293
+ * Idempotent: a bottom tree with no tabs and a closed panel returns the
294
+ * same reference. Runs when the viewport enters narrow (see the Sidebar
295
+ * shell); migrating is permanent for the session — the tabs now live in the
296
+ * right tree, exactly like the user "threw them in".
297
+ */
298
+ export function migrateBottomTabs(state: SidebarState): SidebarState {
299
+ const bottomTabs = allLeaves(state.bottomSplits).flatMap(leaf => leaf.tabs)
300
+ const activeInBottom = state.activePane !== null && treeHasId(state.bottomSplits, state.activePane)
301
+ if (bottomTabs.length === 0 && !state.bottomOpen && !activeInBottom) return state
302
+ const target = firstLeaf(state.splits)
303
+ return {
304
+ ...state,
305
+ activePane: target.id,
306
+ bottomOpen: false,
307
+ splits: bottomTabs.length > 0
308
+ ? mapLeaf(state.splits, target.id, leaf => {
309
+ leaf.tabs = [...leaf.tabs, ...bottomTabs]
310
+ })
311
+ : state.splits,
312
+ bottomSplits: bottomTabs.length > 0 ? clearAllTabs(state.bottomSplits) : state.bottomSplits,
313
+ }
314
+ }
315
+
316
+ /** Find the leaf containing a tab id, if any. */
317
+ export function leafWithTab(node: SplitNode, tabId: string): SidebarLeaf | undefined {
318
+ if (node.kind === 'leaf') {
319
+ return node.tabs.some(tab => tab.id === tabId) ? node : undefined
320
+ }
321
+ for (const child of node.children) {
322
+ const found = leafWithTab(child, tabId)
323
+ if (found !== undefined) return found
324
+ }
325
+ return undefined
326
+ }
327
+
328
+ /** All leaves of the tree, depth-first. */
329
+ export function allLeaves(node: SplitNode): SidebarLeaf[] {
330
+ if (node.kind === 'leaf') return [node]
331
+ return node.children.flatMap(allLeaves)
332
+ }
333
+
334
+ /** Whether a tab exists anywhere in a state (either tree, any pane, or any
335
+ * free window — a floating tab is as open as a docked one). */
336
+ export function tabOpenIn(state: SidebarState, tabId: string): boolean {
337
+ return allLeaves(state.splits).some(leaf => leaf.tabs.some(tab => tab.id === tabId))
338
+ || allLeaves(state.bottomSplits).some(leaf => leaf.tabs.some(tab => tab.id === tabId))
339
+ || state.floats.some(float => float.tab.id === tabId)
340
+ }
341
+
342
+ /** The free window holding a tab id, if any. */
343
+ export function floatWithTab(state: SidebarState, tabId: string): FloatWindow | undefined {
344
+ return state.floats.find(float => float.tab.id === tabId)
345
+ }
346
+
347
+ /** The free window with the given window id, if any. */
348
+ export function floatById(state: SidebarState, floatId: string): FloatWindow | undefined {
349
+ return state.floats.find(float => float.id === floatId)
350
+ }
351
+
352
+ /** Replace a leaf with a split of it plus a fresh empty leaf. */
353
+ export function splitLeafAt(node: SplitNode, paneId: string, dir: 'row' | 'col'): SplitNode {
354
+ const fresh: SidebarLeaf = { kind: 'leaf', id: uid('pane'), tabs: [], active: null }
355
+ return mapLeaf(node, paneId, (leaf) => {
356
+ const target: SidebarLeaf = { ...leaf }
357
+ const split: SidebarSplit = {
358
+ kind: 'split',
359
+ id: uid('split'),
360
+ dir,
361
+ sizes: [0.5, 0.5],
362
+ children: [target, fresh],
363
+ }
364
+ Object.assign(leaf, split)
365
+ })
366
+ }
367
+
368
+ /**
369
+ * Split a leaf by inserting a fresh leaf holding `tab` beside it — the
370
+ * VSCode drag-to-edge gesture. `dir` is the split direction ('row' for
371
+ * left/right, 'col' for up/down); `front` places the new leaf first (left/
372
+ * up) or second (right/down).
373
+ * @returns the new tree plus the fresh leaf's id (the drop's active pane).
374
+ */
375
+ export function insertLeafAt(
376
+ node: SplitNode,
377
+ paneId: string,
378
+ dir: 'row' | 'col',
379
+ tab: SidebarTab,
380
+ front: boolean,
381
+ ): { node: SplitNode; leafId: string } {
382
+ const fresh: SidebarLeaf = { kind: 'leaf', id: uid('pane'), tabs: [tab], active: tab.id }
383
+ const leafId = fresh.id
384
+ const next = mapLeaf(node, paneId, (leaf) => {
385
+ const target: SidebarLeaf = { ...leaf }
386
+ const split: SidebarSplit = {
387
+ kind: 'split',
388
+ id: uid('split'),
389
+ dir,
390
+ sizes: [0.5, 0.5],
391
+ children: front ? [fresh, target] : [target, fresh],
392
+ }
393
+ Object.assign(leaf, split)
394
+ })
395
+ return { node: next, leafId }
396
+ }
397
+
398
+ /** Where a tab drop lands on a pane: an edge creates a split, center merges. */
399
+ export type DropZone = 'left' | 'right' | 'up' | 'down' | 'center'
400
+
401
+ /**
402
+ * The VSCode drag gesture: move a tab out of its pane and either merge it
403
+ * into the target pane (center) or split the target pane with the tab in a
404
+ * fresh leaf (edge). The source pane collapses when it empties.
405
+ *
406
+ * The panes may live in DIFFERENT trees (dragging a tab between the two
407
+ * panels): the tab then leaves its own tree and lands in the other one.
408
+ */
409
+ export function moveTabToEdge(
410
+ state: SidebarState,
411
+ fromPane: string,
412
+ tabId: string,
413
+ toPane: string,
414
+ zone: DropZone,
415
+ ): SidebarState {
416
+ if (fromPane === toPane && zone === 'center') {
417
+ // Dropped back onto its own pane's center: reorder to the end.
418
+ return moveTab(state, fromPane, tabId, toPane, -1)
419
+ }
420
+ const key = treeOf(state, fromPane)
421
+ const toKey = treeOf(state, toPane)
422
+ if (key !== toKey) {
423
+ // Cross-panel drop: remove the tab from its own tree, then merge (center)
424
+ // or split (edge) a pane of the OTHER tree with the tab.
425
+ const source = leafWithTab(state[key], tabId)
426
+ if (source === undefined) return state
427
+ const tab = source.tabs.find(candidate => candidate.id === tabId)!
428
+ let emptied = false
429
+ let sourceNode = mapLeaf(state[key], source.id, (leaf) => {
430
+ leaf.tabs = leaf.tabs.filter(candidate => candidate.id !== tabId)
431
+ if (leaf.active === tabId) leaf.active = leaf.tabs[leaf.tabs.length - 1]?.id ?? null
432
+ if (leaf.tabs.length === 0) emptied = true
433
+ })
434
+ if (emptied) sourceNode = removeLeafAt(sourceNode, source.id)
435
+ let targetNode = state[toKey]
436
+ let activePane: string
437
+ if (zone === 'center') {
438
+ targetNode = mapLeaf(targetNode, toPane, (leaf) => {
439
+ leaf.tabs = [...leaf.tabs, tab]
440
+ leaf.active = tab.id
441
+ })
442
+ activePane = toPane
443
+ } else {
444
+ const dir = zone === 'left' || zone === 'right' ? 'row' : 'col'
445
+ const result = insertLeafAt(targetNode, toPane, dir, tab, zone === 'left' || zone === 'up')
446
+ targetNode = result.node
447
+ activePane = result.leafId
448
+ }
449
+ return { ...state, [key]: sourceNode, [toKey]: targetNode, activePane }
450
+ }
451
+ const node = state[key]
452
+ const source = leafWithTab(node, tabId)
453
+ if (source === undefined) return state
454
+ const tab = source.tabs.find(candidate => candidate.id === tabId)!
455
+ let emptied = false
456
+ let splits = mapLeaf(node, source.id, (leaf) => {
457
+ leaf.tabs = leaf.tabs.filter(candidate => candidate.id !== tabId)
458
+ if (leaf.active === tabId) leaf.active = leaf.tabs[leaf.tabs.length - 1]?.id ?? null
459
+ if (leaf.tabs.length === 0) emptied = true
460
+ })
461
+ if (emptied) splits = removeLeafAt(splits, source.id)
462
+ if (zone === 'center') {
463
+ splits = mapLeaf(splits, toPane, (leaf) => {
464
+ leaf.tabs = [...leaf.tabs, tab]
465
+ leaf.active = tab.id
466
+ })
467
+ return { ...state, [key]: splits, activePane: toPane }
468
+ }
469
+ const dir = zone === 'left' || zone === 'right' ? 'row' : 'col'
470
+ const result = insertLeafAt(splits, toPane, dir, tab, zone === 'left' || zone === 'up')
471
+ return { ...state, [key]: result.node, activePane: result.leafId }
472
+ }
473
+
474
+ /**
475
+ * Remove a leaf from the tree. A split left with one child promotes that
476
+ * child; removing the last leaf yields an empty leaf.
477
+ */
478
+ export function removeLeafAt(node: SplitNode, paneId: string): SplitNode {
479
+ if (node.kind === 'leaf') return node.id === paneId ? { ...node, tabs: [], active: null } : node
480
+ const children = node.children.filter(child => !(child.kind === 'leaf' && child.id === paneId))
481
+ if (children.length === node.children.length) {
482
+ return {
483
+ ...node,
484
+ sizes: [...node.sizes],
485
+ children: node.children.map(child => removeLeafAt(child, paneId)),
486
+ }
487
+ }
488
+ if (children.length === 1) return children[0]!
489
+ return { ...node, sizes: [...node.sizes], children }
490
+ }
491
+
492
+ /** Close a tab; an emptied leaf is removed (unless it is the only pane). */
493
+ export function closeTab(state: SidebarState, paneId: string, tabId: string): SidebarState {
494
+ const key = treeOf(state, paneId)
495
+ let emptied = false
496
+ const splits = mapLeaf(state[key], paneId, (leaf) => {
497
+ leaf.tabs = leaf.tabs.filter(tab => tab.id !== tabId)
498
+ if (leaf.active === tabId) leaf.active = leaf.tabs[leaf.tabs.length - 1]?.id ?? null
499
+ if (leaf.tabs.length === 0) emptied = true
500
+ })
501
+ return { ...state, [key]: emptied ? removeLeafAt(splits, paneId) : splits }
502
+ }
503
+
504
+ /** Activate a tab in its pane (the pane's own tree). */
505
+ export function activateTab(state: SidebarState, paneId: string, tabId: string): SidebarState {
506
+ const key = treeOf(state, paneId)
507
+ return {
508
+ ...state,
509
+ activePane: paneId,
510
+ [key]: mapLeaf(state[key], paneId, (leaf) => {
511
+ if (leaf.tabs.some(tab => tab.id === tabId)) leaf.active = tabId
512
+ }),
513
+ }
514
+ }
515
+
516
+ /** Update the display fields of one open tab (title / path / meta) without
517
+ * re-opening it. The browser tab persists its current URL and hostname
518
+ * title through this reducer so a reload restores the visited page. A
519
+ * missing tab id is a no-op. The tab may live in either tree or a free
520
+ * window. */
521
+ export function patchTab(
522
+ state: SidebarState,
523
+ tabId: string,
524
+ patch: { title?: string; path?: string; meta?: unknown },
525
+ ): SidebarState {
526
+ let changed = false
527
+ const apply = (tab: SidebarTab): SidebarTab => {
528
+ changed = true
529
+ return {
530
+ ...tab,
531
+ ...(patch.title !== undefined ? { title: patch.title } : {}),
532
+ ...(patch.path !== undefined ? { path: patch.path } : {}),
533
+ ...(patch.meta !== undefined ? { meta: patch.meta } : {}),
534
+ }
535
+ }
536
+ const walk = (node: SplitNode): SplitNode => {
537
+ if (node.kind === 'leaf') {
538
+ const tabs = node.tabs.map(tab => (tab.id === tabId ? apply(tab) : tab))
539
+ return tabs === node.tabs ? node : { ...node, tabs }
540
+ }
541
+ const children = node.children.map(walk)
542
+ return children === node.children ? node : { ...node, children }
543
+ }
544
+ const splits = walk(state.splits)
545
+ const bottomSplits = walk(state.bottomSplits)
546
+ const floats = state.floats.map(float => (float.tab.id === tabId ? { ...float, tab: apply(float.tab) } : float))
547
+ return changed ? { ...state, splits, bottomSplits, floats } : state
548
+ }
549
+
550
+ /**
551
+ * Set or clear the pin marker on one open tab (v0.17.0+). A pin marker is
552
+ * structural metadata (NOT display fields like title/path), so it walks
553
+ * both split trees AND the free windows exactly like {@link patchTab} —
554
+ * the tab may live in either tree or float. Passing `null` clears the pin
555
+ * (the tab stays open in its home session); passing a `{ scope, homeCwd }`
556
+ * object sets it. An unknown tab id is a strict no-op (same reference
557
+ * returned) so a stale pin request never churns the state or rewrites
558
+ * localStorage.
559
+ * @param state - the current per-session sidebar state.
560
+ * @param tabId - the tab to pin/unpin.
561
+ * @param pin - the pin marker to set, or null to clear.
562
+ * @returns the next state (or the same reference when the tab is missing
563
+ * or the pin marker is already the requested value).
564
+ */
565
+ export function setTabPin(
566
+ state: SidebarState,
567
+ tabId: string,
568
+ pin: { scope: 'workspace' | 'global'; homeCwd?: string } | null,
569
+ ): SidebarState {
570
+ let changed = false
571
+ const apply = (tab: SidebarTab): SidebarTab => {
572
+ // Pin is terminal-only (design YAGNI): a defensive guard keeps the
573
+ // invariant even if a caller accidentally targets a non-terminal tab.
574
+ if (tab.type !== 'terminal') return tab
575
+ // Idempotent: setting the same pin (deep-equal on scope + homeCwd) is a
576
+ // no-op so re-clicking the menu item never churns the state.
577
+ if (pin === null) {
578
+ if (tab.pin === undefined) return tab
579
+ } else if (
580
+ tab.pin !== undefined
581
+ && tab.pin.scope === pin.scope
582
+ && tab.pin.homeCwd === pin.homeCwd
583
+ ) {
584
+ return tab
585
+ }
586
+ changed = true
587
+ const { pin: _omit, ...rest } = tab
588
+ return pin === null ? rest : { ...rest, pin }
589
+ }
590
+ const walk = (node: SplitNode): SplitNode => {
591
+ if (node.kind === 'leaf') {
592
+ // Find the target tab without rebuilding the whole array: only clone
593
+ // when the tab is actually here and apply changed it (idempotent
594
+ // no-ops return the same tab reference, so === holds).
595
+ const idx = node.tabs.findIndex(tab => tab.id === tabId)
596
+ if (idx < 0) return node
597
+ const oldTab = node.tabs[idx]!
598
+ const newTab = apply(oldTab)
599
+ if (newTab === oldTab) return node
600
+ const tabs = node.tabs.slice()
601
+ tabs[idx] = newTab
602
+ return { ...node, tabs }
603
+ }
604
+ const children = node.children.map(walk)
605
+ // Only rebuild if at least one child actually changed reference.
606
+ if (children.every((child, i) => child === node.children[i])) return node
607
+ return { ...node, children }
608
+ }
609
+ const splits = walk(state.splits)
610
+ const bottomSplits = walk(state.bottomSplits)
611
+ const floatIdx = state.floats.findIndex(f => f.tab.id === tabId)
612
+ const floats = floatIdx < 0 ? state.floats : (() => {
613
+ const oldFloat = state.floats[floatIdx]!
614
+ const newTab = apply(oldFloat.tab)
615
+ if (newTab === oldFloat.tab) return state.floats
616
+ const next = state.floats.slice()
617
+ next[floatIdx] = { ...oldFloat, tab: newTab }
618
+ return next
619
+ })()
620
+ return changed ? { ...state, splits, bottomSplits, floats } : state
621
+ }
622
+
623
+ /**
624
+ * Land a tab in the active pane (or focus its existing instance by id).
625
+ * Dedup strategies (single-instance, per-path, per-change) are owned by the
626
+ * tab descriptor through {@link BetterSidebarService.openTab} / `dedupeKey`;
627
+ * this reducer only handles the id-based safety net (reconcile and
628
+ * openDiffTab already check existence before calling) and the landing
629
+ * itself — the service's dedupe path delegates here after its dedupeKey
630
+ * check misses.
631
+ *
632
+ * The active pane may live in EITHER tree (pane ids are globally unique):
633
+ * a stale id that survives in neither tree falls back to the right tree's
634
+ * first pane instead of swallowing the open.
635
+ */
636
+ export function openTabInActivePane(state: SidebarState, tab: SidebarTab): SidebarState {
637
+ let targetId = state.activePane ?? firstLeaf(state.splits).id
638
+ // A stale activePane (its pane was closed since) must not swallow the
639
+ // open: fall back to the first pane of the right tree instead of dropping
640
+ // the tab.
641
+ if (!allLeaves(state[treeOf(state, targetId)]).some(leaf => leaf.id === targetId)) {
642
+ targetId = firstLeaf(state.splits).id
643
+ }
644
+ const targetKey = treeOf(state, targetId)
645
+ // Id-based safety net: if a tab with the same id exists, focus it — in a
646
+ // pane (activate) or in a free window (raise, no panel switch).
647
+ for (const leaf of allLeaves(state.splits).concat(allLeaves(state.bottomSplits))) {
648
+ const existing = leaf.tabs.find(candidate => candidate.id === tab.id)
649
+ if (existing !== undefined) return activateTab(state, leaf.id, existing.id)
650
+ }
651
+ const floated = floatWithTab(state, tab.id)
652
+ if (floated !== undefined) return raiseFloat(state, floated.id)
653
+ return {
654
+ ...state,
655
+ activePane: targetId,
656
+ [targetKey]: mapLeaf(state[targetKey], targetId, (leaf) => {
657
+ leaf.tabs = [...leaf.tabs, tab]
658
+ leaf.active = tab.id
659
+ }),
660
+ }
661
+ }
662
+
663
+ /** Move a tab from one pane to another (insert at index; -1 appends).
664
+ * The panes may live in DIFFERENT trees — dragging a tab between the two
665
+ * panels removes it from its own tree and lands it in the other one. */
666
+ export function moveTab(state: SidebarState, fromPane: string, tabId: string, toPane: string, index = -1): SidebarState {
667
+ const fromKey = treeOf(state, fromPane)
668
+ const toKey = treeOf(state, toPane)
669
+ if (fromKey !== toKey) {
670
+ let moved: SidebarTab | undefined
671
+ let emptied = false
672
+ const source = mapLeaf(state[fromKey], fromPane, (leaf) => {
673
+ const found = leaf.tabs.find(tab => tab.id === tabId)
674
+ if (found === undefined) return
675
+ moved = found
676
+ leaf.tabs = leaf.tabs.filter(tab => tab.id !== tabId)
677
+ if (leaf.active === tabId) leaf.active = leaf.tabs[leaf.tabs.length - 1]?.id ?? null
678
+ if (leaf.tabs.length === 0) emptied = true
679
+ })
680
+ if (moved === undefined) return state
681
+ const target = mapLeaf(state[toKey], toPane, (leaf) => {
682
+ const insertAt = index >= 0 && index <= leaf.tabs.length ? index : leaf.tabs.length
683
+ leaf.tabs = [...leaf.tabs.slice(0, insertAt), moved!, ...leaf.tabs.slice(insertAt)]
684
+ leaf.active = moved!.id
685
+ })
686
+ return {
687
+ ...state,
688
+ [fromKey]: emptied ? removeLeafAt(source, fromPane) : source,
689
+ [toKey]: target,
690
+ activePane: toPane,
691
+ }
692
+ }
693
+ let moved: SidebarTab | undefined
694
+ let emptied = false
695
+ let splits = mapLeaf(state[fromKey], fromPane, (leaf) => {
696
+ const found = leaf.tabs.find(tab => tab.id === tabId)
697
+ if (found === undefined) return
698
+ moved = found
699
+ leaf.tabs = leaf.tabs.filter(tab => tab.id !== tabId)
700
+ if (leaf.active === tabId) leaf.active = leaf.tabs[leaf.tabs.length - 1]?.id ?? null
701
+ if (leaf.tabs.length === 0) emptied = true
702
+ })
703
+ if (moved === undefined) return state
704
+ if (emptied) splits = removeLeafAt(splits, fromPane)
705
+ splits = mapLeaf(splits, toPane, (leaf) => {
706
+ const insertAt = index >= 0 && index <= leaf.tabs.length ? index : leaf.tabs.length
707
+ leaf.tabs = [...leaf.tabs.slice(0, insertAt), moved!, ...leaf.tabs.slice(insertAt)]
708
+ leaf.active = moved!.id
709
+ })
710
+ return { ...state, [fromKey]: splits, activePane: toPane }
711
+ }
712
+
713
+ /** Split the active pane (or the pane containing the active tab). */
714
+ export function splitPane(state: SidebarState, dir: 'row' | 'col'): SidebarState {
715
+ const paneId = state.activePane ?? firstLeaf(state.splits).id
716
+ const key = treeOf(state, paneId)
717
+ return { ...state, [key]: splitLeafAt(state[key], paneId, dir) }
718
+ }
719
+
720
+ /**
721
+ * Open a diff tab the VSCode way: an existing instance of the same change is
722
+ * focused wherever it lives; otherwise the tab joins the first pane that
723
+ * already holds diff tabs (diff panes are sticky — repeated clicks stack
724
+ * there); on the FIRST diff of a layout the source pane splits vertically so
725
+ * the diff lands in a fresh pane below it ("默认在下半栏新增一个").
726
+ *
727
+ * This is split-tree placement surgery, not registry dispatch: the diff tab
728
+ * descriptor's `dedupeKey` is `(tab) => tab.id`, and the existing-instance
729
+ * check below is exactly that rule — the two agree by construction (asserted
730
+ * in tests). Diff tabs minted by the Git view carry change-derived ids, so
731
+ * the id check is the per-change dedupe.
732
+ * @returns the new state, with the diff pane active.
733
+ */
734
+ export function openDiffTab(state: SidebarState, sourcePaneId: string, tab: SidebarTab): SidebarState {
735
+ const existingLeaf = leafWithTab(state.splits, tab.id)
736
+ if (existingLeaf !== undefined) return activateTab(state, existingLeaf.id, tab.id)
737
+ const diffLeaf = allLeaves(state.splits).find(leaf => leaf.tabs.some(candidate => candidate.type === 'diff'))
738
+ if (diffLeaf !== undefined) {
739
+ return {
740
+ ...state,
741
+ activePane: diffLeaf.id,
742
+ splits: mapLeaf(state.splits, diffLeaf.id, (leaf) => {
743
+ leaf.tabs = [...leaf.tabs, tab]
744
+ leaf.active = tab.id
745
+ }),
746
+ }
747
+ }
748
+ // First diff: split the source pane, the diff tab in the new LOWER leaf.
749
+ // (A stale sourcePaneId — its pane closed meanwhile — degrades to the
750
+ // regular open path instead of dropping the tab into an orphaned leaf.)
751
+ if (!allLeaves(state.splits).some(leaf => leaf.id === sourcePaneId)) {
752
+ return openTabInActivePane(state, tab)
753
+ }
754
+ const result = insertLeafAt(state.splits, sourcePaneId, 'col', tab, false)
755
+ return { ...state, splits: result.node, activePane: result.leafId }
756
+ }
757
+
758
+ /** Toggle the panel open/closed (opening restores the previous layout). */
759
+ export function togglePanel(state: SidebarState): SidebarState {
760
+ return { ...state, panelOpen: !state.panelOpen }
761
+ }
762
+
763
+ /** Toggle the bottom panel open/closed (independent of the right panel). */
764
+ export function toggleBottomPanel(state: SidebarState): SidebarState {
765
+ return { ...state, bottomOpen: !state.bottomOpen }
766
+ }
767
+
768
+ /** Set the panel width (clamped to the contract range; the upper bound is
769
+ * the viewport so the fullscreen expansion can fill the window). */
770
+ export function setWidth(state: SidebarState, width: number): SidebarState {
771
+ const max = typeof window !== 'undefined' ? Math.max(PANEL_MIN, window.innerWidth) : PANEL_MAX
772
+ return { ...state, width: Math.min(max, Math.max(PANEL_MIN, Math.round(width))) }
773
+ }
774
+
775
+ /** Set the bottom panel height (clamped to the contract range). The upper
776
+ * bound leaves the center column (the agent output area) at least PANEL_MIN
777
+ * tall — without the cap the bottom panel could swallow the whole viewport
778
+ * and squeeze the conversation to zero height. */
779
+ export function setBottomHeight(state: SidebarState, height: number): SidebarState {
780
+ const viewport = typeof window !== 'undefined' ? window.innerHeight : Infinity
781
+ const max = Math.max(BOTTOM_MIN, viewport - PANEL_MIN)
782
+ return { ...state, bottomHeight: Math.min(max, Math.max(BOTTOM_MIN, Math.round(height))) }
783
+ }
784
+
785
+ /** Toggle a directory in the explorer expansion set. */
786
+ export function toggleExpanded(state: SidebarState, path: string): SidebarState {
787
+ const expanded = state.expanded.includes(path)
788
+ ? state.expanded.filter(item => item !== path)
789
+ : [...state.expanded, path]
790
+ return { ...state, expanded }
791
+ }
792
+
793
+ /**
794
+ * Reveal files in the explorer: expand every ancestor directory between the
795
+ * explorer root and each file (so the lazy tree actually shows the row) and
796
+ * record the paths for highlighting. The reveal set is transient —
797
+ * sanitizeState never restores it, so a reload starts unhighlighted.
798
+ * @param state - current sidebar state.
799
+ * @param cwd - the explorer's root (session working directory).
800
+ * @param files - absolute paths to highlight (parent dirs are expanded).
801
+ * @returns the next state, or the same reference when nothing is revealed.
802
+ */
803
+ export function revealPaths(state: SidebarState, cwd: string | undefined, files: readonly string[]): SidebarState {
804
+ const expanded = new Set(state.expanded)
805
+ const revealed: string[] = []
806
+ const rootParts = (cwd ?? '').split(/[\\/]+/).filter(part => part !== '')
807
+ for (const file of files) {
808
+ if (typeof file !== 'string' || file === '') continue
809
+ revealed.push(file)
810
+ const parts = file.split(/[\\/]+/).filter(part => part !== '' && part !== '.')
811
+ const separator = file.includes('\\') ? '\\' : '/'
812
+ // Keep the original leading separator(s) when rebuilding ancestor dirs:
813
+ // FileTree matches expansion against ABSOLUTE paths, so dropping the
814
+ // root (POSIX `/w/src` �W `w/src`) or a UNC prefix (`\\server\share`)
815
+ // would leave every ancestor collapsed and the row unreachable.
816
+ const prefix = file.startsWith('/') ? '/' : file.startsWith('\\\\') ? '\\\\' : file.startsWith('\\') ? '\\' : ''
817
+ for (let i = rootParts.length; i < parts.length - 1; i++) {
818
+ expanded.add(prefix + parts.slice(0, i + 1).join(separator))
819
+ }
820
+ }
821
+ if (revealed.length === 0) return state
822
+ return { ...state, expanded: [...expanded], revealed }
823
+ }
824
+
825
+ /** Adjust one split divider: `i` is the left/top child index, delta in fractions. */
826
+ export function resizeSplit(node: SplitNode, splitId: string, index: number, delta: number): SplitNode {
827
+ if (node.kind === 'leaf') return node
828
+ if (node.id === splitId) {
829
+ const sizes = [...node.sizes]
830
+ const left = Math.min(0.92, Math.max(0.08, sizes[index]! + delta))
831
+ const right = Math.min(0.92, Math.max(0.08, sizes[index + 1]! - delta))
832
+ sizes[index] = left
833
+ sizes[index + 1] = right
834
+ return { ...node, sizes }
835
+ }
836
+ return {
837
+ ...node,
838
+ sizes: [...node.sizes],
839
+ children: node.children.map(child => resizeSplit(child, splitId, index, delta)),
840
+ }
841
+ }
842
+
843
+ /** State-level {@link resizeSplit} route: the divider may live in either
844
+ * tree (split ids are globally unique). */
845
+ export function resizeSplitIn(state: SidebarState, splitId: string, index: number, delta: number): SidebarState {
846
+ const key = treeOf(state, splitId)
847
+ return { ...state, [key]: resizeSplit(state[key], splitId, index, delta) }
848
+ }
849
+
850
+ // ── Free windows ────────────────────────────────────────────────────────────
851
+
852
+ /** The viewport size, or Infinity where there is no (usable) window — unit
853
+ * tests stub partial window objects, and a NaN bound would poison geometry. */
854
+ function viewportW(): number {
855
+ return typeof window !== 'undefined' && Number.isFinite(window.innerWidth) ? window.innerWidth : Infinity
856
+ }
857
+
858
+ function viewportH(): number {
859
+ return typeof window !== 'undefined' && Number.isFinite(window.innerHeight) ? window.innerHeight : Infinity
860
+ }
861
+
862
+ /** Clamp free-window geometry: sizes respect the floor and the viewport, and
863
+ * the position keeps the whole window inside the viewport. Without a window
864
+ * (unit tests) only the floor applies — the caller's values pass through. */
865
+ export function clampFloatGeometry(x: number, y: number, w: number, h: number): Pick<FloatWindow, 'x' | 'y' | 'w' | 'h'> {
866
+ const vw = viewportW()
867
+ const vh = viewportH()
868
+ const width = Math.round(Math.min(Math.max(w, FLOAT_MIN_W), Math.max(FLOAT_MIN_W, vw)))
869
+ const height = Math.round(Math.min(Math.max(h, FLOAT_MIN_H), Math.max(FLOAT_MIN_H, vh)))
870
+ return {
871
+ x: Math.round(Math.min(Math.max(x, 0), Math.max(0, vw - width))),
872
+ y: Math.round(Math.min(Math.max(y, 0), Math.max(0, vh - height))),
873
+ w: width,
874
+ h: height,
875
+ }
876
+ }
877
+
878
+ /**
879
+ * Float a docked tab: remove it from its pane (either tree; an emptied pane
880
+ * collapses like any move) and append a free window centered on the drop
881
+ * point, with the default size clamped to the viewport. The stacking order
882
+ * is the array order, so a fresh window is born topmost. An unknown tab id
883
+ * (or one already floating) is a strict no-op.
884
+ */
885
+ export function floatTab(state: SidebarState, tabId: string, x: number, y: number): SidebarState {
886
+ let source: SidebarLeaf | undefined
887
+ let key: 'splits' | 'bottomSplits' | undefined
888
+ for (const treeKey of ['splits', 'bottomSplits'] as const) {
889
+ source = leafWithTab(state[treeKey], tabId)
890
+ if (source !== undefined) { key = treeKey; break }
891
+ }
892
+ if (key === undefined || source === undefined) return state
893
+ const tab = source.tabs.find(candidate => candidate.id === tabId)!
894
+ let emptied = false
895
+ let node = mapLeaf(state[key], source.id, (leaf) => {
896
+ leaf.tabs = leaf.tabs.filter(candidate => candidate.id !== tabId)
897
+ if (leaf.active === tabId) leaf.active = leaf.tabs[leaf.tabs.length - 1]?.id ?? null
898
+ if (leaf.tabs.length === 0) emptied = true
899
+ })
900
+ if (emptied) node = removeLeafAt(node, source.id)
901
+ // Phone-ratio default, capped to the viewport before centering so the
902
+ // clamped position never leaves the window's bottom past the fold.
903
+ const vw = viewportW()
904
+ const vh = viewportH()
905
+ const width = Math.min(FLOAT_DEFAULT_W, Math.max(FLOAT_MIN_W, vw - 24))
906
+ const height = Math.min(FLOAT_DEFAULT_H, Math.max(FLOAT_MIN_H, vh - 24))
907
+ const window = clampFloatGeometry(
908
+ x - width / 2,
909
+ y - height / 2,
910
+ width,
911
+ height,
912
+ )
913
+ const next: SidebarState = {
914
+ ...state,
915
+ [key]: node,
916
+ floats: [...state.floats, { id: uid('float'), tab, ...window }],
917
+ }
918
+ // The pane the user was working in may have just collapsed with the tab.
919
+ if (emptied && state.activePane === source.id) next.activePane = firstLeaf(next.splits).id
920
+ return next
921
+ }
922
+
923
+ /** Move a free window (clamped to the viewport); unknown ids are a no-op. */
924
+ export function moveFloat(state: SidebarState, floatId: string, x: number, y: number): SidebarState {
925
+ const float = floatById(state, floatId)
926
+ if (float === undefined) return state
927
+ const geo = clampFloatGeometry(x, y, float.w, float.h)
928
+ if (geo.x === float.x && geo.y === float.y) return state
929
+ return { ...state, floats: state.floats.map(f => (f.id === floatId ? { ...f, ...geo } : f)) }
930
+ }
931
+
932
+ /** Resize a free window from its SE corner: the top-left corner stays
933
+ * anchored, sizes clamp to the floor and to the viewport's remaining room. */
934
+ export function resizeFloat(state: SidebarState, floatId: string, w: number, h: number): SidebarState {
935
+ const float = floatById(state, floatId)
936
+ if (float === undefined) return state
937
+ const vw = viewportW()
938
+ const vh = viewportH()
939
+ const width = Math.round(Math.min(Math.max(w, FLOAT_MIN_W), Math.max(FLOAT_MIN_W, vw - float.x)))
940
+ const height = Math.round(Math.min(Math.max(h, FLOAT_MIN_H), Math.max(FLOAT_MIN_H, vh - float.y)))
941
+ if (width === float.w && height === float.h) return state
942
+ return { ...state, floats: state.floats.map(f => (f.id === floatId ? { ...f, w: width, h: height } : f)) }
943
+ }
944
+
945
+ /** Bring a free window to the top (the array's end). Already topmost (or the
946
+ * only window) returns the same reference — no persist churn on every click. */
947
+ export function raiseFloat(state: SidebarState, floatId: string): SidebarState {
948
+ if (state.floats.length < 2) return state
949
+ const index = state.floats.findIndex(f => f.id === floatId)
950
+ if (index < 0 || index === state.floats.length - 1) return state
951
+ const floats = [...state.floats]
952
+ const [raised] = floats.splice(index, 1)
953
+ floats.push(raised!)
954
+ return { ...state, floats }
955
+ }
956
+
957
+ /** Dock a free window back into a pane (center merge): the tab joins the
958
+ * target pane and activates. `toPane` defaults to the active pane with the
959
+ * right tree's first leaf as the stale-id fallback (mirrors
960
+ * {@link openTabInActivePane}). Unknown window ids are a no-op. */
961
+ export function dockFloat(state: SidebarState, floatId: string, toPane?: string): SidebarState {
962
+ const float = floatById(state, floatId)
963
+ if (float === undefined) return state
964
+ let targetId = toPane ?? state.activePane ?? firstLeaf(state.splits).id
965
+ if (!allLeaves(state[treeOf(state, targetId)]).some(leaf => leaf.id === targetId)) {
966
+ targetId = firstLeaf(state.splits).id
967
+ }
968
+ const targetKey = treeOf(state, targetId)
969
+ return {
970
+ ...state,
971
+ floats: state.floats.filter(f => f.id !== floatId),
972
+ activePane: targetId,
973
+ [targetKey]: mapLeaf(state[targetKey], targetId, (leaf) => {
974
+ leaf.tabs = [...leaf.tabs, float.tab]
975
+ leaf.active = float.tab.id
976
+ }),
977
+ }
978
+ }
979
+
980
+ /** Close the free window holding a tab (the tab closes WITH the window —
981
+ * the caller fires the descriptor's onClose lifecycle). */
982
+ export function closeFloatByTab(state: SidebarState, tabId: string): SidebarState {
983
+ if (!state.floats.some(f => f.tab.id === tabId)) return state
984
+ return { ...state, floats: state.floats.filter(f => f.tab.id !== tabId) }
985
+ }
986
+
987
+ /** Prefix marking a tab id as an agent-owned terminal (suffix is the uuid). */
988
+ export const AGENT_TAB_PREFIX = 'agent:'
989
+
990
+ /** Whether a tab id refers to an agent-owned terminal. */
991
+ export function isAgentTabId(tabId: string): boolean {
992
+ return tabId.startsWith(AGENT_TAB_PREFIX)
993
+ }
994
+
995
+ /** Extract the agent terminal uuid from an `agent:<uuid>` tab id. */
996
+ export function agentUuidOf(tabId: string): string {
997
+ return tabId.slice(AGENT_TAB_PREFIX.length)
998
+ }
999
+
1000
+ /** Build the sidebar tab id for one agent terminal uuid. */
1001
+ export function agentTabId(uuid: string): string {
1002
+ return `${AGENT_TAB_PREFIX}${uuid}`
1003
+ }
1004
+
1005
+ /**
1006
+ * Reconcile the sidebar's agent-terminal tabs with the host's live list.
1007
+ * The host pushes the current list of agent terminals (created by the model
1008
+ * through the `terminal_create` tool) over a dedicated WebSocket; this
1009
+ * reducer mirrors that list into tabs: new uuids get a tab, vanished uuids
1010
+ * lose theirs. The agent owns the lifetime — the user closing a tab sends a
1011
+ * WS close frame that kills the pty, which fires a change, which converges
1012
+ * the view. Idempotent: a no-op when the lists already match.
1013
+ * @param state - the current per-session sidebar state.
1014
+ * @param agentTerminals - the live agent terminal snapshots from the host.
1015
+ * @returns the next state (or the same reference if no change was needed).
1016
+ */
1017
+ export function reconcileAgentTerminals(
1018
+ state: SidebarState,
1019
+ agentTerminals: ReadonlyArray<{ uuid: string; title: string }>,
1020
+ ): SidebarState {
1021
+ const existingTabs = allLeaves(state.splits).concat(allLeaves(state.bottomSplits)).flatMap(leaf => leaf.tabs)
1022
+ .concat(state.floats.map(float => float.tab))
1023
+ const existingAgentTabs = existingTabs.filter(tab => isAgentTabId(tab.id))
1024
+ const existingUuids = new Set(existingAgentTabs.map(tab => agentUuidOf(tab.id)))
1025
+ const serverUuids = new Set(agentTerminals.map(t => t.uuid))
1026
+ const toAdd = agentTerminals.filter(t => !existingUuids.has(t.uuid))
1027
+ // Pinned agent terminals (v0.17.0+) are EXEMPT from removal: the agent
1028
+ // closed them or the pty exited, but the user pinned them so the tab
1029
+ // stays as a disconnected surface. The xterm view's reconnect-failure
1030
+ // banner is the user-visible "disconnected" signal (the design's M3
1031
+ // convergence: no title suffix, no meta write — the tab keeps its uuid
1032
+ // so a later reconcile push revives it if the agent reopens the same one).
1033
+ const toRemove = existingAgentTabs.filter(tab => !serverUuids.has(agentUuidOf(tab.id)) && tab.pin === undefined)
1034
+ if (toAdd.length === 0 && toRemove.length === 0) return state
1035
+ // Remove tabs whose uuids vanished from the server list (the agent closed
1036
+ // them, or the pty exited and was reaped). Reuse closeTab's leaf cleanup;
1037
+ // a FLOATED agent terminal leaves with its window.
1038
+ let splits = state.splits
1039
+ let floats = state.floats
1040
+ for (const tab of toRemove) {
1041
+ const leaf = leafWithTab(splits, tab.id)
1042
+ if (leaf !== undefined) {
1043
+ splits = closeTab({ ...state, splits }, leaf.id, tab.id).splits
1044
+ }
1045
+ if (floats.some(float => float.tab.id === tab.id)) {
1046
+ floats = floats.filter(float => float.tab.id !== tab.id)
1047
+ }
1048
+ }
1049
+ // Add tabs for new uuids (the agent created a terminal). They land in the
1050
+ // active pane via openTabInActivePane; the next reconcile is a no-op for them.
1051
+ let next: SidebarState = { ...state, splits, floats }
1052
+ for (const terminal of toAdd) {
1053
+ const tab: SidebarTab = {
1054
+ id: agentTabId(terminal.uuid),
1055
+ type: 'terminal',
1056
+ title: terminal.title,
1057
+ }
1058
+ next = openTabInActivePane(next, tab)
1059
+ }
1060
+ return next
1061
+ }
1062
+
1063
+ // ── The per-session store ──────────────────────────────────────────────────
1064
+
1065
+ const STORAGE_PREFIX = 'dsh-sidebar:v1'
1066
+
1067
+ /**
1068
+ * Cross-session panel width: the last dragged width, shared by EVERY
1069
+ * conversation (the panel width is a layout preference, not per-session
1070
+ * content). Written on every persist, read at session load and on
1071
+ * cache-hit session switches, so a drag in one conversation carries to all
1072
+ * the others (last drag wins).
1073
+ */
1074
+ const GLOBAL_WIDTH_KEY = 'dsh-sidebar:v1:width'
1075
+
1076
+ /** Clamp one width to the contract and the current viewport (mirror of {@link setWidth}). */
1077
+ function clampWidth(width: number): number {
1078
+ const max = typeof window !== 'undefined' ? Math.max(PANEL_MIN, window.innerWidth) : PANEL_MAX
1079
+ return Math.min(max, Math.max(PANEL_MIN, Math.round(width)))
1080
+ }
1081
+
1082
+ /** Read the cross-session panel width (undefined when never dragged). */
1083
+ function readGlobalWidth(): number | undefined {
1084
+ try {
1085
+ const raw = localStorage.getItem(GLOBAL_WIDTH_KEY)
1086
+ if (raw !== null) {
1087
+ const parsed = Number(raw)
1088
+ if (Number.isFinite(parsed) && parsed > 0) return clampWidth(parsed)
1089
+ }
1090
+ } catch {
1091
+ // Storage unavailable: fall back to the per-session behavior.
1092
+ }
1093
+ return undefined
1094
+ }
1095
+
1096
+ /** Persist the cross-session panel width (best-effort, like the session states). */
1097
+ function writeGlobalWidth(width: number): void {
1098
+ try {
1099
+ localStorage.setItem(GLOBAL_WIDTH_KEY, String(width))
1100
+ } catch {
1101
+ // Storage full or unavailable: layout memory is best-effort.
1102
+ }
1103
+ }
1104
+
1105
+ /** Immutable snapshot handed to React (replaced only on real changes). */
1106
+ export interface SidebarSnapshot {
1107
+ sessionId: string | undefined
1108
+ state: SidebarState | undefined
1109
+ /**
1110
+ * The current side card prefs. Carried IN the snapshot (not a separate
1111
+ * subscription) so prefs changes re-render the consumers that gate on
1112
+ * them — the + menu hides a tab type the moment its switch flips.
1113
+ */
1114
+ prefs: SidebarPrefs
1115
+ }
1116
+
1117
+ /** Default panel width for one viewport: the prefs percent of the window,
1118
+ * clamped to the panel floor (a tiny percent must stay usable) and to the
1119
+ * viewport (a large one must never cover the whole window). */
1120
+ export function defaultWidthFor(viewport: number, percent: number): number {
1121
+ return Math.min(viewport, Math.max(PANEL_MIN, Math.round(viewport * percent / 100)))
1122
+ }
1123
+
1124
+ /**
1125
+ * URL escape hatch (#369): loading the app with `?dsh-sidebar-reset` drops
1126
+ * the persisted layout for the session instead of restoring it. When a
1127
+ * restored tab hangs the page on mount (the #369 freeze loop), reloading
1128
+ * into the same state replays the hang forever; this param starts from the
1129
+ * default layout and clears the stored copy, breaking the loop. Persisting
1130
+ * resumes as soon as the param is gone from the URL.
1131
+ */
1132
+ const RESET_PARAM = 'dsh-sidebar-reset'
1133
+
1134
+ /** Whether the current page load asked for a persisted-state reset. */
1135
+ function resetRequested(): boolean {
1136
+ try {
1137
+ return new URLSearchParams(window.location.search).has(RESET_PARAM)
1138
+ } catch {
1139
+ return false
1140
+ }
1141
+ }
1142
+
1143
+ function loadState(sessionId: string, prefs: SidebarPrefs): SidebarState {
1144
+ const reset = resetRequested()
1145
+ if (reset) {
1146
+ try {
1147
+ localStorage.removeItem(`${STORAGE_PREFIX}:${sessionId}`)
1148
+ localStorage.removeItem(GLOBAL_WIDTH_KEY)
1149
+ } catch {
1150
+ // Storage unavailable: the default layout below is still the escape.
1151
+ }
1152
+ }
1153
+ // The panel width is a cross-session preference: the last dragged width
1154
+ // wins over a session's own persisted value, so switching conversations
1155
+ // keeps the width the user chose anywhere.
1156
+ const globalWidth = reset ? undefined : readGlobalWidth()
1157
+ if (!reset) {
1158
+ try {
1159
+ const raw = localStorage.getItem(`${STORAGE_PREFIX}:${sessionId}`)
1160
+ if (raw !== null) {
1161
+ const parsed = JSON.parse(raw) as unknown
1162
+ // Seed the uid counter past the persisted ids (it resets on reload);
1163
+ // sanitize re-ids any duplicates the pre-seeding counter left behind.
1164
+ nextIdCounter = maxCounterId(parsed)
1165
+ const sanitized = sanitizeState(parsed)
1166
+ if (sanitized !== undefined) {
1167
+ return globalWidth === undefined ? sanitized : { ...sanitized, width: globalWidth }
1168
+ }
1169
+ }
1170
+ } catch {
1171
+ // Corrupt or unavailable storage: fall through to the default.
1172
+ }
1173
+ }
1174
+ // New sessions seed from the user's side card prefs: the width is the
1175
+ // chosen percent of the window (clamped to the panel floor and the
1176
+ // viewport so a huge percent can never crush the app shell), the panel
1177
+ // starts open only when the preference says so, and the seed tab is the
1178
+ // empty files window (tree panel open) in BOTH editorExplorer modes — a
1179
+ // disabled editor type seeds nothing. On a NARROW viewport a brand-new
1180
+ // session starts collapsed instead — the panel is a full-screen drawer
1181
+ // there, and auto-opening it on first paint would cover the conversation
1182
+ // before the user asked. Only the first seeding is affected: once the
1183
+ // user expands the drawer, `panelOpen: true` persists like any other
1184
+ // state.
1185
+ const viewport = typeof window !== 'undefined' ? window.innerWidth : undefined
1186
+ const width = globalWidth ?? (viewport === undefined
1187
+ ? PANEL_DEFAULT
1188
+ : defaultWidthFor(viewport, prefs.defaultWidthPercent))
1189
+ const openByDefault = prefs.openByDefault && (viewport === undefined || !isNarrowWidth(viewport))
1190
+ const seed: DefaultSeed = prefs.tabsEnabled['editor'] === false ? 'none' : 'editor-home'
1191
+ return makeDefaultState(width, openByDefault, seed)
1192
+ }
1193
+
1194
+ /**
1195
+ * Structural validation of one persisted state. A malformed or stale shape
1196
+ * (older layouts, hand-edited storage) must fall back to the default instead
1197
+ * of crashing the panel on every reload; the restored width is also clamped
1198
+ * to the current viewport so a stale fullscreen width can never crush the
1199
+ * app shell (margin-right larger than the window) or cover the whole screen.
1200
+ * @returns a clean state, or undefined to fall back to the default.
1201
+ */
1202
+ export function sanitizeState(parsed: unknown): SidebarState | undefined {
1203
+ if (parsed === null || typeof parsed !== 'object') return undefined
1204
+ const record = parsed as Record<string, unknown>
1205
+ if (typeof record.panelOpen !== 'boolean') return undefined
1206
+ if (typeof record.width !== 'number' || !Number.isFinite(record.width)) return undefined
1207
+ if (typeof record.nextTerminal !== 'number' || !Number.isInteger(record.nextTerminal) || record.nextTerminal < 1) {
1208
+ return undefined
1209
+ }
1210
+ // nextBrowser arrived in a later build; a missing or malformed value on an
1211
+ // OLDER persisted state defaults to 1 so existing layouts keep loading
1212
+ // (unlike nextTerminal, which is strict — it predates the v1 shape).
1213
+ const nextBrowser = typeof record.nextBrowser === 'number' && Number.isInteger(record.nextBrowser) && record.nextBrowser >= 1
1214
+ ? record.nextBrowser
1215
+ : 1
1216
+ if (typeof record.activePane !== 'string' && record.activePane !== null) return undefined
1217
+ if (!Array.isArray(record.expanded) || record.expanded.some(item => typeof item !== 'string')) return undefined
1218
+ // The seen/reid maps are SHARED across both trees: pane/split ids must be
1219
+ // globally unique (the runtime uid counter is shared too), so a duplicate
1220
+ // seen first in the right tree gets a fresh id when it reappears in the
1221
+ // bottom tree.
1222
+ const seen = new Set<string>()
1223
+ const reid = new Map<string, string>()
1224
+ const restoredSplits = sanitizeNode(record.splits, seen, reid)
1225
+ if (restoredSplits === undefined) return undefined
1226
+ const splits = pruneEmptyPanes(restoredSplits)
1227
+ // Bottom-panel fields arrived in a later build: a missing or malformed
1228
+ // value on an OLDER persisted state defaults (closed / default height /
1229
+ // empty pane) so existing layouts keep loading, like nextBrowser.
1230
+ const bottomOpen = record.bottomOpen === true
1231
+ // Cap the persisted height so the center column (the agent output area)
1232
+ // keeps at least PANEL_MIN tall (a stale full-height bottom panel from an
1233
+ // older build must never squeeze the conversation to zero).
1234
+ const maxHeight = typeof window !== 'undefined' ? window.innerHeight : Infinity
1235
+ const bottomCap = Math.max(BOTTOM_MIN, maxHeight - PANEL_MIN)
1236
+ const rawHeight = typeof record.bottomHeight === 'number' && Number.isFinite(record.bottomHeight)
1237
+ ? record.bottomHeight
1238
+ : BOTTOM_DEFAULT
1239
+ const bottomHeight = Math.min(bottomCap, Math.max(BOTTOM_MIN, Math.round(rawHeight)))
1240
+ const bottomSplits = pruneEmptyPanes(sanitizeNode(record.bottomSplits, seen, reid)
1241
+ ?? { kind: 'leaf' as const, id: uid('pane'), tabs: [], active: null })
1242
+ // Free windows arrived with the float feature: a missing field on an older
1243
+ // persisted state defaults to none (like the bottom-panel fields above).
1244
+ // Malformed ENTRIES drop individually — unlike the split trees, where
1245
+ // corruption resets the whole state, a bad window must not cost the user
1246
+ // their whole layout. Geometry clamps into the CURRENT viewport so a stale
1247
+ // off-screen window stays reachable; the window ids join the same
1248
+ // uniqueness set as the pane/split ids (the uid counter mints for both).
1249
+ const floats: FloatWindow[] = []
1250
+ if (Array.isArray(record.floats)) {
1251
+ for (const entry of record.floats) {
1252
+ if (entry === null || typeof entry !== 'object') continue
1253
+ const candidate = entry as Record<string, unknown>
1254
+ if (typeof candidate.id !== 'string' || seen.has(candidate.id)) continue
1255
+ const tab = sanitizePersistedTab(candidate.tab)
1256
+ if (tab === undefined || tab === 'diff') continue
1257
+ if (
1258
+ typeof candidate.x !== 'number' || !Number.isFinite(candidate.x)
1259
+ || typeof candidate.y !== 'number' || !Number.isFinite(candidate.y)
1260
+ || typeof candidate.w !== 'number' || !Number.isFinite(candidate.w)
1261
+ || typeof candidate.h !== 'number' || !Number.isFinite(candidate.h)
1262
+ ) continue
1263
+ seen.add(candidate.id)
1264
+ floats.push({ id: candidate.id, tab, ...clampFloatGeometry(candidate.x, candidate.y, candidate.w, candidate.h) })
1265
+ }
1266
+ }
1267
+ const requestedActivePane = typeof record.activePane === 'string'
1268
+ ? (reid.get(record.activePane) ?? record.activePane)
1269
+ : null
1270
+ const activePane = requestedActivePane === null
1271
+ ? null
1272
+ : treeHasId(splits, requestedActivePane) || treeHasId(bottomSplits, requestedActivePane)
1273
+ ? requestedActivePane
1274
+ : firstLeaf(splits).id
1275
+ const maxWidth = typeof window !== 'undefined' ? window.innerWidth : Infinity
1276
+ return {
1277
+ panelOpen: record.panelOpen,
1278
+ width: Math.max(PANEL_MIN, Math.min(record.width, maxWidth)),
1279
+ // A stale duplicate pane id may have been re-ided; follow the rename so
1280
+ // new tabs still land in the pane the user was using.
1281
+ activePane,
1282
+ nextTerminal: record.nextTerminal,
1283
+ nextBrowser,
1284
+ expanded: record.expanded as string[],
1285
+ revealed: [],
1286
+ splits,
1287
+ bottomOpen,
1288
+ bottomHeight,
1289
+ // An older persisted state never expanded the bottom panel (the field
1290
+ // arrived later): defaulting to false gives it the first-expansion
1291
+ // auto-terminal exactly once after the upgrade.
1292
+ bottomOpenedOnce: record.bottomOpenedOnce === true,
1293
+ bottomSplits,
1294
+ floats,
1295
+ }
1296
+ }
1297
+
1298
+ /** Collapse persisted split panes left empty after ephemeral diff tabs are dropped. */
1299
+ function pruneEmptyPanes(node: SplitNode): SplitNode {
1300
+ const leaves = allLeaves(node)
1301
+ if (!leaves.some(leaf => leaf.tabs.length > 0)) return node
1302
+ return leaves.reduce(
1303
+ (tree, leaf) => leaf.tabs.length === 0 ? removeLeafAt(tree, leaf.id) : tree,
1304
+ node,
1305
+ )
1306
+ }
1307
+
1308
+ /**
1309
+ * One tree node id, deduplicated against the ids already seen in this
1310
+ * state. Duplicates are exactly the pre-seeding counter-reset corruption
1311
+ * (a "pane:1"/"split:1" minted after a reload beside the persisted ones):
1312
+ * keeping both would make mapLeaf visit two leaves at once and every open
1313
+ * would land in both panes, so the repeat gets a fresh id.
1314
+ * @returns the id to use (the original, or a fresh uid for repeats).
1315
+ */
1316
+ function uniqueNodeId(id: string, seen: Set<string>, reid: Map<string, string>): string {
1317
+ if (!seen.has(id)) {
1318
+ seen.add(id)
1319
+ return id
1320
+ }
1321
+ const prefix = /^split:\d+$/.test(id) ? 'split' : 'pane'
1322
+ const fresh = uid(prefix)
1323
+ seen.add(fresh)
1324
+ reid.set(id, fresh)
1325
+ return fresh
1326
+ }
1327
+
1328
+ /**
1329
+ * Validate one persisted tab record. @returns the clean tab, `'diff'` for an
1330
+ * ephemeral diff tab (dropped everywhere — diff tabs never survive a reload),
1331
+ * or undefined when the record is malformed (structural corruption when it
1332
+ * comes from a split-tree leaf; a malformed FLOAT tab only drops the window).
1333
+ */
1334
+ function sanitizePersistedTab(tab: unknown): SidebarTab | 'diff' | undefined {
1335
+ if (tab === null || typeof tab !== 'object') return undefined
1336
+ const candidate = tab as Record<string, unknown>
1337
+ if (typeof candidate.id !== 'string' || typeof candidate.title !== 'string') return undefined
1338
+ if (candidate.type === 'diff') return 'diff'
1339
+ // Tab types are an open set (external plugins register their own); accept
1340
+ // any string type here — an unregistered type renders an <OrphanedTab/> at
1341
+ // view time and recovers if its plugin loads later.
1342
+ if (typeof candidate.type !== 'string') return undefined
1343
+ // The standalone explorer tab type merged INTO the editor (the single
1344
+ // files window): a persisted explorer tab reopens as an editor home tab —
1345
+ // no path, tree panel open (an existing meta object survives).
1346
+ if (candidate.type === 'explorer') {
1347
+ const meta = candidate.meta !== null && typeof candidate.meta === 'object' && !Array.isArray(candidate.meta)
1348
+ ? candidate.meta as Record<string, unknown>
1349
+ : undefined
1350
+ return { id: candidate.id, type: 'editor', title: 'Files', meta: { treeOpen: true, ...meta } }
1351
+ }
1352
+ // `meta` is plugin-owned JSON-serializable state (v0.12.0+): the persisted
1353
+ // value already went through JSON.parse, so it is inherently serializable —
1354
+ // carry it through verbatim (absent on older states).
1355
+ const result: SidebarTab = {
1356
+ id: candidate.id,
1357
+ type: candidate.type,
1358
+ title: candidate.title,
1359
+ ...(typeof candidate.path === 'string' ? { path: candidate.path } : {}),
1360
+ ...(candidate.meta !== undefined ? { meta: candidate.meta } : {}),
1361
+ }
1362
+ // `pin` (v0.17.0+): a pinned-terminal marker. Whitelist-validate the
1363
+ // shape so a hand-edited / corrupted pin never crashes the rail's
1364
+ // resolver: an unknown scope or a non-string homeCwd drops the pin
1365
+ // silently (the tab survives, just unpinned — the legacy behavior).
1366
+ // Pin is terminal-only: a non-terminal tab carrying a persisted pin
1367
+ // (e.g. from a hand-edited state) has it stripped here.
1368
+ const pin = (candidate as Record<string, unknown>).pin
1369
+ if (pin !== null && typeof pin === 'object' && !Array.isArray(pin) && result.type === 'terminal') {
1370
+ const pinRecord = pin as Record<string, unknown>
1371
+ if (pinRecord.scope === 'workspace' || pinRecord.scope === 'global') {
1372
+ const homeCwd = pinRecord.homeCwd
1373
+ result.pin = homeCwd === undefined || typeof homeCwd === 'string'
1374
+ ? { scope: pinRecord.scope, ...(typeof homeCwd === 'string' ? { homeCwd } : {}) }
1375
+ : { scope: pinRecord.scope }
1376
+ }
1377
+ }
1378
+ return result
1379
+ }
1380
+
1381
+ /** Validate one split-tree node (leaf or split) and rebuild it cleanly. */
1382
+ function sanitizeNode(node: unknown, seen: Set<string>, reid: Map<string, string>): SplitNode | undefined {
1383
+ if (node === null || typeof node !== 'object') return undefined
1384
+ const record = node as Record<string, unknown>
1385
+ if (record.kind === 'leaf') {
1386
+ if (typeof record.id !== 'string' || !Array.isArray(record.tabs)) return undefined
1387
+ const tabs: SidebarTab[] = []
1388
+ let droppedDiff = false
1389
+ for (const tab of record.tabs) {
1390
+ const clean = sanitizePersistedTab(tab)
1391
+ if (clean === undefined) return undefined
1392
+ if (clean === 'diff') {
1393
+ droppedDiff = true
1394
+ continue
1395
+ }
1396
+ tabs.push(clean)
1397
+ }
1398
+ const active = typeof record.active === 'string' ? record.active : null
1399
+ // An active pointer into a dropped diff tab is expected after the drop;
1400
+ // any other missing active is structural corruption → reset the state.
1401
+ if (active !== null && !tabs.some(tab => tab.id === active) && !droppedDiff) return undefined
1402
+ return { kind: 'leaf', id: uniqueNodeId(record.id, seen, reid), tabs, active: active !== null && tabs.some(tab => tab.id === active) ? active : null }
1403
+ }
1404
+ if (record.kind === 'split') {
1405
+ if (typeof record.id !== 'string' || (record.dir !== 'row' && record.dir !== 'col')) return undefined
1406
+ if (!Array.isArray(record.children) || !Array.isArray(record.sizes)) return undefined
1407
+ const children: SplitNode[] = []
1408
+ for (const child of record.children) {
1409
+ const clean = sanitizeNode(child, seen, reid)
1410
+ if (clean === undefined) return undefined
1411
+ children.push(clean)
1412
+ }
1413
+ if (children.length < 2) return undefined
1414
+ if (
1415
+ record.sizes.length !== children.length
1416
+ || record.sizes.some(size => typeof size !== 'number' || !Number.isFinite(size) || size <= 0)
1417
+ ) {
1418
+ return undefined
1419
+ }
1420
+ return { kind: 'split', id: uniqueNodeId(record.id, seen, reid), dir: record.dir, sizes: record.sizes as number[], children }
1421
+ }
1422
+ return undefined
1423
+ }
1424
+
1425
+ /** The session-scoped store: one state per conversation, localStorage-backed. */
1426
+ export class SidebarStore {
1427
+ private readonly bySession = new Map<string, SidebarState>()
1428
+ private snapshot: SidebarSnapshot = {
1429
+ sessionId: undefined,
1430
+ state: undefined,
1431
+ prefs: { ...SIDEBAR_PREFS_DEFAULTS },
1432
+ }
1433
+ private readonly listeners = new Set<() => void>()
1434
+ /** Per-session persist debounce timers (v0.12.0+: one per session, so a
1435
+ * targeted open never cancels another session's pending write). */
1436
+ private readonly persistTimers = new Map<string, number>()
1437
+ /** User-facing side card prefs seeding brand-new session states (defaults until the settings RPC resolves). */
1438
+ private prefs: SidebarPrefs = { ...SIDEBAR_PREFS_DEFAULTS }
1439
+ /**
1440
+ * External disable (the dsh-web-ui family's aionui-panel provider choice):
1441
+ * while true the sidebar must not mount at all. Not part of the snapshot —
1442
+ * nothing renders on it; the mount gate and the intercept predicates read
1443
+ * it directly.
1444
+ */
1445
+ private suspended = false
1446
+
1447
+ /**
1448
+ * Set the external-disable flag (from the settings route) and remember it
1449
+ * for the mount gate and the intercept predicates.
1450
+ */
1451
+ setSuspended(suspended: boolean): void {
1452
+ this.suspended = suspended
1453
+ }
1454
+
1455
+ /** Whether the sidebar is externally disabled (aionui-panel chosen). */
1456
+ getSuspended(): boolean {
1457
+ return this.suspended
1458
+ }
1459
+
1460
+ /**
1461
+ * Replace the side card prefs (the settings RPC result / settings page
1462
+ * write). Notifies like any store change: the snapshot carries the prefs,
1463
+ * so consumers that gate on enable switches (the + menu, derived flows)
1464
+ * re-render with the new values immediately.
1465
+ */
1466
+ setPrefs(prefs: SidebarPrefs): void {
1467
+ this.prefs = { ...prefs }
1468
+ this.snapshot = { ...this.snapshot, prefs: this.prefs }
1469
+ this.notify()
1470
+ }
1471
+
1472
+ /** The current side card prefs (seeds new sessions; persisted states win). */
1473
+ getPrefs(): SidebarPrefs {
1474
+ return { ...this.prefs }
1475
+ }
1476
+
1477
+ /** Select a session (or none); loads its persisted state. */
1478
+ setSession(sessionId: string | undefined): void {
1479
+ if (this.snapshot.sessionId === sessionId) return
1480
+ if (sessionId === undefined) {
1481
+ this.snapshot = { sessionId: undefined, state: undefined, prefs: this.prefs }
1482
+ } else {
1483
+ let state = this.bySession.get(sessionId)
1484
+ if (state === undefined) {
1485
+ state = loadState(sessionId, this.prefs)
1486
+ this.bySession.set(sessionId, state)
1487
+ } else {
1488
+ // Cache hit: another session's load/ops may have left the uid
1489
+ // counter below THIS session's persisted ids — re-seed so fresh
1490
+ // pane/split ids can never collide with its tree.
1491
+ nextIdCounter = maxCounterId(state)
1492
+ // The panel width is cross-session: adopt the latest dragged width
1493
+ // (a cached session keeps its own layout otherwise).
1494
+ const globalWidth = readGlobalWidth()
1495
+ if (globalWidth !== undefined && state.width !== globalWidth) {
1496
+ state = { ...state, width: globalWidth }
1497
+ this.bySession.set(sessionId, state)
1498
+ }
1499
+ }
1500
+ this.snapshot = { sessionId, state, prefs: this.prefs }
1501
+ }
1502
+ this.notify()
1503
+ }
1504
+
1505
+ subscribe(listener: () => void): () => void {
1506
+ this.listeners.add(listener)
1507
+ return () => { this.listeners.delete(listener) }
1508
+ }
1509
+
1510
+ getSnapshot(): SidebarSnapshot {
1511
+ return this.snapshot
1512
+ }
1513
+
1514
+ /** Mutate the current session's state (no-op without a session). */
1515
+ update(mutator: (draft: SidebarState) => void): void {
1516
+ const sessionId = this.snapshot.sessionId
1517
+ const state = this.snapshot.state
1518
+ if (sessionId === undefined || state === undefined) return
1519
+ const draft = structuredClone(state)
1520
+ mutator(draft)
1521
+ this.bySession.set(sessionId, draft)
1522
+ this.snapshot = { sessionId, state: draft, prefs: this.prefs }
1523
+ this.schedulePersist(sessionId, draft)
1524
+ this.notify()
1525
+ }
1526
+
1527
+ /**
1528
+ * Whether a tab still exists in its session's state. Views use this on
1529
+ * unmount to tell "the tab was closed" (release the terminal now) from
1530
+ * "the tree re-rendered / the conversation switched" (the tab is still
1531
+ * open — keep the terminal alive through the host's reconnect grace).
1532
+ * Checks the session's own map entry (the current snapshot may already
1533
+ * point at another session when a conversation switch unmounts the old
1534
+ * one's tabs).
1535
+ */
1536
+ tabOpen(sessionId: string, tabId: string): boolean {
1537
+ const state = this.bySession.get(sessionId)
1538
+ ?? (this.snapshot.sessionId === sessionId ? this.snapshot.state : undefined)
1539
+ return state !== undefined && tabOpenIn(state, tabId)
1540
+ }
1541
+
1542
+ /**
1543
+ * Read-only view of EVERY cached session's state (v0.17.0+). The
1544
+ * PinnedRail uses this to collect pinned terminals across sessions
1545
+ * without each render reading private fields. The map is the live
1546
+ * `bySession` reference — callers MUST treat it as read-only (mutations
1547
+ * go through {@link reduce} / {@link reduceFor}). A session that has
1548
+ * never been visited in this run is absent (its pinned tabs are not
1549
+ * visible until first load — accepted as YAGNI by the design).
1550
+ */
1551
+ getSessionStates(): ReadonlyMap<string, SidebarState> {
1552
+ return new Map(this.bySession)
1553
+ }
1554
+
1555
+ /** Apply a pure reducer (returns the next state). */
1556
+ reduce(reducer: (state: SidebarState) => SidebarState): void {
1557
+ const sessionId = this.snapshot.sessionId
1558
+ const state = this.snapshot.state
1559
+ if (sessionId === undefined || state === undefined) return
1560
+ const next = reducer(state)
1561
+ // A reducer returning the SAME reference means "no change": skip the
1562
+ // persist + notify entirely — strict no-op paths (unknown tab ids,
1563
+ // patchTab on a missing tab) must not churn the state or rewrite
1564
+ // localStorage.
1565
+ if (next === state) return
1566
+ this.bySession.set(sessionId, next)
1567
+ this.snapshot = { sessionId, state: next, prefs: this.prefs }
1568
+ this.schedulePersist(sessionId, next)
1569
+ this.notify()
1570
+ }
1571
+
1572
+ /**
1573
+ * Apply a pure reducer to a TARGET session's state (not the active one),
1574
+ * loading it on demand and persisting the result — WITHOUT switching the
1575
+ * active snapshot or notifying (the UI must not follow along). Used by the
1576
+ * service's targeted `openTab(seed, scope)`: the open lands in the target
1577
+ * session's layout and is visible whenever the user switches to it.
1578
+ */
1579
+ reduceFor(sessionId: string, reducer: (state: SidebarState) => SidebarState): void {
1580
+ // The uid counter is SHARED across sessions, and the ACTIVE session's
1581
+ // safety requires it to never drop below the ids IT minted. Seeding it
1582
+ // from the target's max may LOWER it (a cached target older than the
1583
+ // active session): restoring the pre-call level afterwards keeps the
1584
+ // active session's next mint collision-free — ids minted for the target
1585
+ // only need to exceed the target's own max, which the seed guaranteed.
1586
+ const counterBefore = nextIdCounter
1587
+ let state = this.bySession.get(sessionId)
1588
+ if (state === undefined) {
1589
+ state = loadState(sessionId, this.prefs)
1590
+ this.bySession.set(sessionId, state)
1591
+ } else {
1592
+ // Re-seed the uid counter past THIS session's persisted ids, exactly
1593
+ // like setSession's cache-hit path.
1594
+ nextIdCounter = maxCounterId(state)
1595
+ }
1596
+ const next = reducer(state)
1597
+ // Same-reference result = no change: keep the counter restore (it may
1598
+ // have been seeded down) but skip the write.
1599
+ nextIdCounter = Math.max(nextIdCounter, counterBefore)
1600
+ if (next === state) return
1601
+ this.bySession.set(sessionId, next)
1602
+ this.schedulePersist(sessionId, next)
1603
+ }
1604
+
1605
+ private schedulePersist(sessionId: string, state: SidebarState): void {
1606
+ // Keep the cross-session width in sync: any width change (drag, fullscreen
1607
+ // toggle) on the ACTIVE session becomes the shared width for every
1608
+ // conversation. A targeted open persists an INACTIVE session (reduceFor)
1609
+ // and must not clobber that global — its width is stale by definition,
1610
+ // so writing it would break "last drag wins".
1611
+ if (sessionId === this.snapshot.sessionId) {
1612
+ writeGlobalWidth(state.width)
1613
+ }
1614
+ // Per-session debounce timers: one session's pending write must never
1615
+ // cancel another's (targeted opens schedule writes for INACTIVE
1616
+ // sessions while the active session may already have one pending —
1617
+ // a shared timer would drop the earlier write and the reload would
1618
+ // lose that session's layout).
1619
+ const existing = this.persistTimers.get(sessionId)
1620
+ if (existing !== undefined) window.clearTimeout(existing)
1621
+ const timer = window.setTimeout(() => {
1622
+ this.persistTimers.delete(sessionId)
1623
+ try {
1624
+ localStorage.setItem(`${STORAGE_PREFIX}:${sessionId}`, JSON.stringify(state))
1625
+ } catch {
1626
+ // Storage full or unavailable: layout memory is best-effort.
1627
+ }
1628
+ }, 200)
1629
+ this.persistTimers.set(sessionId, timer)
1630
+ }
1631
+
1632
+ private notify(): void {
1633
+ for (const listener of [...this.listeners]) listener()
1634
+ }
1635
+ }
1636
+
1637
+ /**
1638
+ * Create one sidebar store instance. Production code calls this only from
1639
+ * the client plugin's `apply` (the instance is handed to components as a
1640
+ * prop); tests call it directly. No module-level singleton: the store's
1641
+ * lifetime belongs to the plugin activation, exactly like the official
1642
+ * `createXXXStore()` factory rule.
1643
+ */
1644
+ export function createSidebarStore(): SidebarStore {
1645
+ return new SidebarStore()
1646
+ }