@kabmo-labs/kabmo 0.9.0 → 0.10.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 (180) hide show
  1. package/README.md +45 -0
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +333 -333
  4. package/dist/client/static/js/index-18xe7655.css +1 -0
  5. package/dist/client/static/js/{index-bpptfkz2.js → index-nxpe7835.js} +768 -763
  6. package/package.json +3 -1
  7. package/src/client/components/common/code-surface/bracket-guide.test.ts +249 -0
  8. package/src/client/components/common/code-surface/bracket-guide.ts +131 -0
  9. package/src/client/components/common/code-surface/documents.test.ts +5 -3
  10. package/src/client/components/common/code-surface/documents.ts +85 -0
  11. package/src/client/components/common/code-surface/extensions.test.ts +5 -0
  12. package/src/client/components/common/code-surface/extensions.ts +140 -7
  13. package/src/client/components/common/code-surface/fold-stack.test.ts +218 -0
  14. package/src/client/components/common/code-surface/fold.test.ts +148 -0
  15. package/src/client/components/common/code-surface/fold.ts +118 -0
  16. package/src/client/components/common/code-surface/indent-guide.ts +104 -0
  17. package/src/client/components/common/code-surface/indent.test.ts +239 -0
  18. package/src/client/components/common/code-surface/indent.ts +124 -0
  19. package/src/client/components/common/code-surface/index.tsx +76 -46
  20. package/src/client/components/common/code-surface/keymap.ts +12 -23
  21. package/src/client/components/common/code-surface/line-commands.test.ts +90 -0
  22. package/src/client/components/common/code-surface/line-commands.ts +103 -0
  23. package/src/client/components/common/code-surface/props.ts +87 -0
  24. package/src/client/components/common/code-surface/stream-language.test.ts +118 -0
  25. package/src/client/components/common/code-surface/stream-language.ts +123 -0
  26. package/src/client/components/common/code-surface/theme.test.ts +40 -5
  27. package/src/client/components/common/code-surface/theme.ts +113 -0
  28. package/src/client/components/common/code-surface/typing.test.ts +97 -0
  29. package/src/client/components/common/code-surface/typing.ts +111 -0
  30. package/src/client/components/common/toolbar-row/index.test.tsx +53 -4
  31. package/src/client/components/common/toolbar-row/index.tsx +101 -30
  32. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +17 -0
  33. package/src/client/components/layout/desktop-layout/index.tsx +18 -0
  34. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +35 -33
  35. package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +20 -1
  36. package/src/client/components/mobile/mobile-right-sidebar/editor-props.ts +25 -0
  37. package/src/client/components/settings/categories/AppearanceSettings.tsx +6 -0
  38. package/src/client/components/settings/categories/appearance-settings/EditorIndentSection.tsx +87 -0
  39. package/src/client/components/settings/categories/appearance-settings/EditorTypingSection.tsx +99 -0
  40. package/src/client/components/workspace/chat-timeline/chat-input/expansion.ts +9 -4
  41. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +15 -11
  42. package/src/client/components/workspace/chat-timeline/chat-input/stretch-send.test.tsx +165 -0
  43. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/DiffView.test.ts +17 -3
  44. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/DiffView.tsx +10 -6
  45. package/src/client/components/workspace/editor/Body.tsx +24 -0
  46. package/src/client/components/workspace/editor/CommandPalette.tsx +4 -4
  47. package/src/client/components/workspace/editor/ConflictStrip.tsx +77 -0
  48. package/src/client/components/workspace/editor/Dialogs.tsx +53 -0
  49. package/src/client/components/workspace/editor/EmptyEditor.tsx +23 -0
  50. package/src/client/components/workspace/editor/ExternalChangeStrip.tsx +61 -0
  51. package/src/client/components/workspace/editor/FileDocument.tsx +89 -1
  52. package/src/client/components/workspace/editor/FilePane.tsx +43 -0
  53. package/src/client/components/workspace/editor/FindWidget.test.ts +9 -5
  54. package/src/client/components/workspace/editor/FindWidget.tsx +29 -0
  55. package/src/client/components/workspace/editor/GoToLineModal.tsx +123 -0
  56. package/src/client/components/workspace/editor/Notices.tsx +71 -0
  57. package/src/client/components/workspace/editor/Pane.tsx +118 -0
  58. package/src/client/components/workspace/editor/PluginColumn.tsx +32 -0
  59. package/src/client/components/workspace/editor/QuickOpenModal.tsx +146 -0
  60. package/src/client/components/workspace/editor/SaveAsModal.tsx +175 -0
  61. package/src/client/components/workspace/editor/SplitColumn.tsx +98 -0
  62. package/src/client/components/workspace/editor/SplitPane.tsx +57 -0
  63. package/src/client/components/workspace/editor/StatusBar.tsx +106 -0
  64. package/src/client/components/workspace/editor/TabContextMenu.tsx +75 -0
  65. package/src/client/components/workspace/editor/Tabs.tsx +195 -18
  66. package/src/client/components/workspace/editor/Toolbar.tsx +54 -181
  67. package/src/client/components/workspace/editor/index.tsx +199 -189
  68. package/src/client/components/workspace/editor/props.ts +64 -0
  69. package/src/client/components/workspace/editor/toolbar-clusters.tsx +300 -0
  70. package/src/client/components/workspace/file-explorer/Modals.tsx +14 -1
  71. package/src/client/components/workspace/file-explorer/TreeItem.tsx +2 -1
  72. package/src/client/components/workspace/file-explorer/clipboard.test.ts +3 -1
  73. package/src/client/components/workspace/file-explorer/index.test.ts +61 -0
  74. package/src/client/components/workspace/file-explorer/index.tsx +10 -48
  75. package/src/client/components/workspace/file-explorer/local-edit.test.ts +8 -3
  76. package/src/client/components/workspace/search-panel/Body.tsx +6 -1
  77. package/src/client/hooks/chat/composer/file-drop.ts +22 -37
  78. package/src/client/hooks/chat/composer/pipeline.test.ts +76 -0
  79. package/src/client/hooks/chat/composer/pipeline.ts +12 -1
  80. package/src/client/hooks/editor/caret-position.test.ts +58 -0
  81. package/src/client/hooks/editor/caret-position.ts +48 -0
  82. package/src/client/hooks/editor/file-editor-types.ts +200 -0
  83. package/src/client/hooks/editor/find-history.test.ts +132 -0
  84. package/src/client/hooks/editor/find-history.ts +46 -0
  85. package/src/client/hooks/editor/find-selection-range.test.ts +100 -0
  86. package/src/client/hooks/editor/find-selection-range.ts +49 -0
  87. package/src/client/hooks/editor/find-state.ts +13 -0
  88. package/src/client/hooks/editor/font.test.ts +0 -93
  89. package/src/client/hooks/editor/indent-settings.test.ts +104 -0
  90. package/src/client/hooks/editor/indent-settings.ts +88 -0
  91. package/src/client/hooks/editor/quick-open.test.ts +141 -0
  92. package/src/client/hooks/editor/quick-open.ts +127 -0
  93. package/src/client/hooks/editor/save-as.test.ts +156 -0
  94. package/src/client/hooks/editor/save-as.ts +122 -0
  95. package/src/client/hooks/editor/save-file.test.ts +179 -0
  96. package/src/client/hooks/editor/save-file.ts +73 -28
  97. package/src/client/hooks/editor/typing-settings.test.ts +73 -0
  98. package/src/client/hooks/editor/typing-settings.ts +65 -0
  99. package/src/client/hooks/editor/use-close-guard.ts +98 -0
  100. package/src/client/hooks/editor/use-editor-drop-overlay.test.ts +159 -0
  101. package/src/client/hooks/editor/use-editor-drop.shell.test.ts +224 -0
  102. package/src/client/hooks/editor/use-editor-drop.ts +58 -68
  103. package/src/client/hooks/editor/use-editor-find.test.ts +2 -2
  104. package/src/client/hooks/editor/use-editor-find.ts +38 -3
  105. package/src/client/hooks/editor/use-editor-panel-keys.ts +152 -0
  106. package/src/client/hooks/editor/use-editor-tab-state.ts +71 -0
  107. package/src/client/hooks/editor/use-external-change-notice.ts +71 -0
  108. package/src/client/hooks/editor/use-external-change.test.ts +88 -0
  109. package/src/client/hooks/editor/use-external-change.ts +146 -0
  110. package/src/client/hooks/editor/use-file-editor.ts +83 -116
  111. package/src/client/hooks/editor/use-file-read.ts +16 -8
  112. package/src/client/hooks/editor/use-file-writes.ts +28 -3
  113. package/src/client/hooks/editor/use-mobile-editor-find.ts +69 -0
  114. package/src/client/hooks/editor/use-mobile-reveal.ts +53 -0
  115. package/src/client/hooks/editor/use-search-reveal-jump.ts +57 -0
  116. package/src/client/hooks/editor/use-split-editor.test.tsx +169 -0
  117. package/src/client/hooks/editor/use-split-editor.ts +91 -0
  118. package/src/client/hooks/editor/use-unload-guard.tsx +117 -0
  119. package/src/client/hooks/editor/use-write-conflict.test.ts +164 -0
  120. package/src/client/hooks/editor/use-write-conflict.ts +152 -0
  121. package/src/client/hooks/editor/wheel-zoom.test.ts +141 -0
  122. package/src/client/hooks/editor/wheel-zoom.ts +96 -0
  123. package/src/client/hooks/ui/drag-presence.test.ts +193 -0
  124. package/src/client/hooks/ui/drag-presence.ts +108 -0
  125. package/src/client/hooks/ui/settings-modal.test.ts +115 -0
  126. package/src/client/hooks/workspace/file-listing.ts +36 -24
  127. package/src/client/hooks/workspace/file-tabs.test.ts +90 -0
  128. package/src/client/hooks/workspace/file-tabs.ts +46 -0
  129. package/src/client/hooks/workspace/file-tree-edits.ts +103 -0
  130. package/src/client/lib/desktop/dropped-paths.ts +83 -0
  131. package/src/client/lib/editor/tab-menu.test.ts +127 -0
  132. package/src/client/lib/editor/tab-menu.ts +127 -0
  133. package/src/client/lib/editor-dirty-tabs.test.ts +102 -0
  134. package/src/client/lib/editor-dirty-tabs.ts +103 -0
  135. package/src/client/lib/native/resume.test.ts +66 -0
  136. package/src/client/lib/native/resume.ts +42 -0
  137. package/src/client/main.tsx +8 -0
  138. package/src/client/tailwind.css +38 -0
  139. package/src/server/lib/bundler/css.test.ts +31 -0
  140. package/src/server/lib/fs/listing.test.ts +81 -16
  141. package/src/server/lib/fs/listing.ts +72 -5
  142. package/src/server/lib/fs/write-conflict.test.ts +68 -0
  143. package/src/server/lib/fs/write-conflict.ts +84 -0
  144. package/src/server/routes/fs/action-save-as.test.ts +82 -0
  145. package/src/server/routes/fs/action.test.ts +82 -0
  146. package/src/server/routes/fs/action.ts +54 -1
  147. package/src/server/routes/fs/exists.ts +11 -1
  148. package/src/server/routes/fs/read.ts +6 -1
  149. package/src/shared/lib/code/editor/find-replace.test.ts +1 -1
  150. package/src/shared/lib/code/editor/find-scan.test.ts +1 -1
  151. package/src/shared/lib/code/editor/find-scan.ts +22 -1
  152. package/src/shared/lib/code/editor/find-selection.test.ts +56 -0
  153. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +65 -0
  154. package/src/shared/lib/code/editor/indent-guide-rule.ts +47 -0
  155. package/src/shared/lib/code/editor/indent-rules.test.ts +219 -0
  156. package/src/shared/lib/code/editor/indent-rules.ts +198 -0
  157. package/src/shared/lib/code/editor/keymap.test.ts +23 -0
  158. package/src/shared/lib/code/editor/keymap.ts +40 -3
  159. package/src/shared/lib/code/editor/palette.test.ts +25 -2
  160. package/src/shared/lib/code/editor/palette.ts +10 -0
  161. package/src/shared/lib/code/editor/stream-modes.ts +225 -0
  162. package/src/shared/lib/code/syntax-highlight.test.ts +1 -1
  163. package/src/shared/lib/fs/file-tree.test.ts +41 -0
  164. package/src/shared/lib/fs/file-tree.ts +126 -34
  165. package/src/shared/lib/fs/folder-chain.test.ts +87 -0
  166. package/src/shared/lib/fs/folder-chain.ts +91 -0
  167. package/src/shared/lib/fs/fs-helpers.test.ts +4 -50
  168. package/src/shared/lib/realtime/connection.test.ts +5 -1
  169. package/src/shared/lib/realtime/connection.ts +25 -119
  170. package/src/shared/lib/realtime/frozen-recovery.test.ts +93 -0
  171. package/src/shared/lib/realtime/resume.ts +223 -0
  172. package/src/shared/lib/realtime/state.ts +22 -0
  173. package/src/shared/lib/realtime/watchdog-wiring.test.ts +224 -0
  174. package/src/shared/lib/realtime/watchdog.test.ts +99 -0
  175. package/src/shared/lib/realtime/watchdog.ts +72 -0
  176. package/src/shared/lib/workspace/split-editor.test.ts +104 -0
  177. package/src/shared/lib/workspace/split-editor.ts +129 -0
  178. package/src/test-support/file-explorer-disk.test-util.ts +30 -3
  179. package/src/test-support/pristine-globals.ts +7 -0
  180. package/dist/client/static/js/index-k315p1e8.css +0 -1
@@ -25,7 +25,7 @@
25
25
 
26
26
  import { useRef, useState } from 'preact/hooks';
27
27
  import type { FsNode } from '@/shared/types';
28
- import { placeEntry, rehydrateTree, setChildrenAt, takeEntry, rekeyCache } from '@/shared/lib/fs/file-tree';
28
+ import { placeEntry, rehydrateTree, takeEntry, rekeyCache } from '@/shared/lib/fs/file-tree';
29
29
  import { isRecord } from '@/shared/lib/util/guards';
30
30
 
31
31
  /**
@@ -92,14 +92,21 @@ export interface FileListing {
92
92
  * A create answers with the entry's path, so the tree already knows the whole
93
93
  * result; re-reading the root plus every open folder to learn it back would
94
94
  * be one request per open folder for an answer the caller holds.
95
+ *
96
+ * Returns the tree as committed, because the caller's next step is to reveal
97
+ * the row — and a reveal has to expand the rows that are DRAWN, not the path's
98
+ * own segments: a single-child folder is one collapsed row
99
+ * (`foldSingleChildFolders`), so `lib` and `lib/deep` may be a single node.
100
+ * `null` means the entry could not be placed — a folder whose contents are
101
+ * not loaded — and the caller has to re-read.
95
102
  */
96
- insertEntry: (entry: { path: string; kind: 'file' | 'folder' }) => void;
103
+ insertEntry: (entry: { path: string; kind: 'file' | 'folder' }) => FsNode[] | null;
97
104
  /**
98
- * Move a row the panel just renamed, without a reload. Returns the folders
99
- * whose path moved, so the caller can rekey its expansion set — a renamed
100
- * folder's open branches are still open, under their new names.
105
+ * Move a row the panel just renamed, without a reload.
106
+ *
107
+ * Returns the tree as committed, or `null` when the moved entry is not in it.
101
108
  */
102
- moveEntry: (fromPath: string, toPath: string) => void;
109
+ moveEntry: (fromPath: string, toPath: string) => FsNode[] | null;
103
110
  /** Forget the root listing and every cached child (a repo switch). */
104
111
  reset: () => void;
105
112
  }
@@ -145,15 +152,19 @@ export function useFileListing({
145
152
  return `/api/fs/dir?${params.toString()}`;
146
153
  };
147
154
 
148
- /** Render the tree from the current root listing plus the children cache. */
149
- const commit = (requested: string, root: string) => {
155
+ /**
156
+ * Render the tree from the current root listing plus the children cache.
157
+ *
158
+ * Returns what it rendered, so a caller that must act on the RESULT (a reveal
159
+ * after a create, an expansion rekey after a rename) reads the rows that are
160
+ * drawn instead of re-deriving them.
161
+ */
162
+ const commit = (requested: string, root: string): FsNode[] => {
150
163
  listedScopeRef.current = requested;
151
164
  listedRootRef.current = root;
152
- setState({
153
- scope: requested,
154
- files: rehydrateTree(rootFilesRef.current, childrenCacheRef.current),
155
- root,
156
- });
165
+ const files = rehydrateTree(rootFilesRef.current, childrenCacheRef.current);
166
+ setState({ scope: requested, files, root });
167
+ return files;
157
168
  };
158
169
 
159
170
  /**
@@ -219,9 +230,10 @@ export function useFileListing({
219
230
  const read = await readDir(listUrl(path));
220
231
  if (scopeRef.current !== requested || read.status !== 'ok') return;
221
232
  childrenCacheRef.current[path] = read.files;
222
- setState((prev) => (prev.scope === requested
223
- ? { ...prev, files: setChildrenAt(prev.files, path, read.files) }
224
- : prev));
233
+ // Committed through `rehydrateTree` rather than patched in place: a fresh
234
+ // listing can itself hold a single-child chain, and a branch set directly
235
+ // would draw the unfolded rows the next refresh folds away.
236
+ if (listedScopeRef.current === requested) commit(requested, listedRootRef.current);
225
237
  };
226
238
 
227
239
  const adoptRoot = (data: unknown): void => {
@@ -250,9 +262,9 @@ export function useFileListing({
250
262
  * the only thing that builds what is rendered. Editing the rendered tree
251
263
  * directly would be undone by the next commit, which rebuilds from these.
252
264
  */
253
- const insertEntry = (entry: { path: string; kind: 'file' | 'folder' }): void => {
265
+ const insertEntry = (entry: { path: string; kind: 'file' | 'folder' }): FsNode[] | null => {
254
266
  const requested = scopeRef.current;
255
- if (listedScopeRef.current !== requested) return;
267
+ if (listedScopeRef.current !== requested) return null;
256
268
  const node: FsNode = {
257
269
  name: entry.path.slice(entry.path.lastIndexOf('/') + 1),
258
270
  path: entry.path,
@@ -260,23 +272,23 @@ export function useFileListing({
260
272
  ignored: false,
261
273
  };
262
274
  const placed = placeEntry(rootFilesRef.current, childrenCacheRef.current, node);
263
- if (placed.nodes === rootFilesRef.current) return;
275
+ if (placed.nodes === rootFilesRef.current) return null;
264
276
  rootFilesRef.current = placed.nodes;
265
277
  childrenCacheRef.current = placed.cache;
266
- commit(requested, listedRootRef.current);
278
+ return commit(requested, listedRootRef.current);
267
279
  };
268
280
 
269
- const moveEntry = (fromPath: string, toPath: string): void => {
281
+ const moveEntry = (fromPath: string, toPath: string): FsNode[] | null => {
270
282
  const requested = scopeRef.current;
271
- if (listedScopeRef.current !== requested) return;
283
+ if (listedScopeRef.current !== requested) return null;
272
284
  const taken = takeEntry(rootFilesRef.current, childrenCacheRef.current, fromPath);
273
- if (!taken.entry) return;
285
+ if (!taken.entry) return null;
274
286
  childrenCacheRef.current = rekeyCache(taken.cache, fromPath, toPath);
275
287
  const moved: FsNode = { ...taken.entry, path: toPath, name: toPath.slice(toPath.lastIndexOf('/') + 1) };
276
288
  const placed = placeEntry(taken.nodes, childrenCacheRef.current, moved);
277
289
  rootFilesRef.current = placed.nodes;
278
290
  childrenCacheRef.current = placed.cache;
279
- commit(requested, listedRootRef.current);
291
+ return commit(requested, listedRootRef.current);
280
292
  };
281
293
 
282
294
  // A listing read for another scope is not this one's to render: the panel
@@ -49,6 +49,9 @@ let container: HTMLElement;
49
49
  /** The provider component, kept so a case can re-render with a different root. */
50
50
  let SessionStateProvider: ComponentType<{ sessionId: string; children: ComponentChildren }>;
51
51
  let handleOpenFile: ((file: OpenFileInput) => void) | null = null;
52
+ let handleCloseFile: ((id: number | string) => void) | null = null;
53
+ let handleReopenClosed: (() => boolean) | null = null;
54
+ let reopenableCount: (() => number) | null = null;
52
55
  /** The mounted probe, so a re-render can hand it another root. */
53
56
  let Probe: ComponentType<{ rootPath: string | null }>;
54
57
  let openedFiles: OpenedFile[] = [];
@@ -85,6 +88,9 @@ async function mount(stored: Record<string, unknown> = {}, root: string | null =
85
88
  Probe = ({ rootPath }: { rootPath: string | null }) => {
86
89
  const tabs = useFileTabs(rootPath, SESSION);
87
90
  handleOpenFile = tabs.handleOpenFile;
91
+ handleCloseFile = tabs.handleCloseFile;
92
+ handleReopenClosed = tabs.handleReopenClosed;
93
+ reopenableCount = tabs.reopenableCount;
88
94
  openedFiles = tabs.openedFiles;
89
95
  activeFileId = tabs.activeFileId;
90
96
  return null;
@@ -109,6 +115,9 @@ afterAll(() => {
109
115
 
110
116
  beforeEach(() => {
111
117
  handleOpenFile = null;
118
+ handleCloseFile = null;
119
+ handleReopenClosed = null;
120
+ reopenableCount = null;
112
121
  openedFiles = [];
113
122
  activeFileId = null;
114
123
  globalThis.fetch = (async () => ({
@@ -220,3 +229,84 @@ describe('useFileTabs open resolution', () => {
220
229
  expect(activeFileId).toBe(fileTabId('src/a.ts'));
221
230
  });
222
231
  });
232
+
233
+ describe('useFileTabs reopen', () => {
234
+ test('a closed tab comes back whole, and activated', async () => {
235
+ await mount();
236
+ await act(async () => handleOpenFile?.(explorerPayload('src/a.ts')));
237
+ await settle();
238
+ expect(openedFiles).toHaveLength(1);
239
+
240
+ await act(async () => handleCloseFile?.('src/a.ts'));
241
+ await settle();
242
+ expect(openedFiles).toHaveLength(0);
243
+
244
+ let restored = false;
245
+ await act(async () => { restored = handleReopenClosed?.() ?? false; });
246
+ await settle();
247
+ // Whole, not re-derived: the same id the explorer gave it, so the tab strip and the
248
+ // scroll-position map still address it.
249
+ expect(restored).toBe(true);
250
+ expect(openedFiles.map((file) => file.id)).toEqual(['src/a.ts']);
251
+ expect(activeFileId).toBe('src/a.ts');
252
+ });
253
+
254
+ test('an empty stack answers false, so the chord can stay inert', async () => {
255
+ await mount();
256
+ let restored = true;
257
+ await act(async () => { restored = handleReopenClosed?.() ?? true; });
258
+ expect(restored).toBe(false);
259
+ });
260
+
261
+ test('the stack is last-in-first-out', async () => {
262
+ await mount();
263
+ await act(async () => handleOpenFile?.(explorerPayload('src/a.ts')));
264
+ await act(async () => handleOpenFile?.(explorerPayload('src/b.ts')));
265
+ await settle();
266
+ await act(async () => handleCloseFile?.('src/a.ts'));
267
+ await act(async () => handleCloseFile?.('src/b.ts'));
268
+ await settle();
269
+
270
+ await act(async () => { handleReopenClosed?.(); });
271
+ await settle();
272
+ expect(openedFiles.map((file) => file.id)).toEqual(['src/b.ts']);
273
+
274
+ await act(async () => { handleReopenClosed?.(); });
275
+ await settle();
276
+ expect(openedFiles.map((file) => file.id)).toEqual(['src/b.ts', 'src/a.ts']);
277
+ });
278
+
279
+ test('the count follows the stack, so the menu row appears and disappears with it', async () => {
280
+ await mount();
281
+ await act(async () => handleOpenFile?.(explorerPayload('src/a.ts')));
282
+ await settle();
283
+ expect(reopenableCount?.()).toBe(0);
284
+ await act(async () => handleCloseFile?.('src/a.ts'));
285
+ await settle();
286
+ expect(reopenableCount?.()).toBe(1);
287
+ await act(async () => { handleReopenClosed?.(); });
288
+ await settle();
289
+ expect(reopenableCount?.()).toBe(0);
290
+ });
291
+
292
+ test('a diff tab is restored as a DIFF — a path cannot derive that', async () => {
293
+ await mount();
294
+ // Opened through `handleOpenFile` with the shape only a diff has: a display name the
295
+ // file system does not have, plus `isDiff`. The reopen path must preserve it, because
296
+ // re-deriving a tab from its path would come back as a plain file tab.
297
+ await act(async () => handleOpenFile?.({
298
+ id: 'a.ts-diff',
299
+ name: 'a.ts (diff)',
300
+ path: 'a.ts',
301
+ root: ROOT,
302
+ repo: '.',
303
+ isDiff: true,
304
+ } as OpenFileInput));
305
+ await settle();
306
+ await act(async () => handleCloseFile?.('a.ts-diff'));
307
+ await settle();
308
+ await act(async () => { handleReopenClosed?.(); });
309
+ await settle();
310
+ expect(openedFiles[0]?.isDiff).toBe(true);
311
+ });
312
+ });
@@ -22,6 +22,14 @@ export interface OpenFileInput {
22
22
  handleId?: string;
23
23
  }
24
24
 
25
+ /**
26
+ * How many closed tabs `Reopen` can restore.
27
+ *
28
+ * Ten is what a reader can still remember closing; past that the stack is a log rather
29
+ * than an undo.
30
+ */
31
+ const REOPEN_STACK_LIMIT = 10;
32
+
25
33
  export function useFileTabs(
26
34
  activeProjectPath: string | null,
27
35
  sessionId: string,
@@ -155,9 +163,24 @@ export function useFileTabs(
155
163
  onOpenTab?.();
156
164
  }, [activeProjectPath, onOpenTab, setOpenedFiles, setActiveFileId]);
157
165
 
166
+ /**
167
+ * The tabs closed recently, newest last, so `Reopen` is a stack.
168
+ *
169
+ * A REF, not state: nothing renders the stack, and a re-render per close would be a
170
+ * second thing every tab interaction pays for. Bounded, because a session that closes
171
+ * a hundred tabs should not hold a hundred `OpenedFile`s alive.
172
+ */
173
+ const closedRef = useRef<OpenedFile[]>([]);
174
+
158
175
  const handleCloseFile = useCallback((id: number | string) => {
159
176
  dropScrollFor([id]);
160
177
  setOpenedFiles(prev => {
178
+ const closed = prev.find(f => f.id === id);
179
+ // Only a tab that actually existed is remembered: a close on a stale id must not
180
+ // put a phantom entry on the reopen stack.
181
+ if (closed) {
182
+ closedRef.current = [...closedRef.current, closed].slice(-REOPEN_STACK_LIMIT);
183
+ }
161
184
  const next = prev.filter(f => f.id !== id);
162
185
  if (activeFileId === id) {
163
186
  setActiveFileId(next.length > 0 ? next[next.length - 1].id : null);
@@ -166,6 +189,27 @@ export function useFileTabs(
166
189
  });
167
190
  }, [activeFileId, dropScrollFor, setOpenedFiles, setActiveFileId]);
168
191
 
192
+ /**
193
+ * Put the most recently closed tab back, activating it.
194
+ *
195
+ * The entry is restored WHOLE — name, path, scope, diff flags — because reopening
196
+ * reconstructs the tab rather than re-deriving it from a path (a diff tab has no file
197
+ * to derive from). Returns false with an empty stack so the caller can leave the chord
198
+ * inert rather than swallowing it.
199
+ */
200
+ const handleReopenClosed = useCallback(() => {
201
+ const entry = closedRef.current[closedRef.current.length - 1];
202
+ if (!entry) return false;
203
+ closedRef.current = closedRef.current.slice(0, -1);
204
+ setOpenedFiles(prev => (prev.some(f => f.id === entry.id) ? prev : [...prev, entry]));
205
+ setActiveFileId(entry.id);
206
+ onOpenTab?.();
207
+ return true;
208
+ }, [onOpenTab, setOpenedFiles, setActiveFileId]);
209
+
210
+ /** How many tabs `Reopen` can still restore, for the menu's enabled state. */
211
+ const reopenableCount = useCallback(() => closedRef.current.length, []);
212
+
169
213
  /**
170
214
  * Turn a diff tab into the plain editor tab for the same file.
171
215
  *
@@ -254,6 +298,8 @@ export function useFileTabs(
254
298
  handleOpenFile,
255
299
  handleOpenDiff,
256
300
  handleCloseFile,
301
+ handleReopenClosed,
302
+ reopenableCount,
257
303
  convertDiffToEditor,
258
304
  };
259
305
  }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The Files panel's local tree edits: a create and a rename land WITHOUT a
8
+ * reload, and the row they produce is REVEALED.
9
+ *
10
+ * Extracted from the panel because the reveal and the placement are one
11
+ * decision with two halves. A folder holding exactly one folder is collapsed
12
+ * into a single row naming the chain (`lib/deep`), so the ancestors a reveal may
13
+ * expand are the rows that are DRAWN — not the path's own segments. A reveal
14
+ * derived from the path would fill the expansion set with paths nothing draws,
15
+ * and the next refresh would read each of them from disk for nothing.
16
+ *
17
+ * The placement's answer is what the reveal reads, which is why the two live
18
+ * together: `insertEntry`/`moveEntry` return the tree they committed, and this
19
+ * module is the only caller that consumes it.
20
+ */
21
+
22
+ import { useCallback } from 'preact/hooks';
23
+ import type { FsNode } from '@/shared/types';
24
+ import { drawnAncestors } from '@/shared/lib/fs/folder-chain';
25
+ import { rekeyExpansion } from '@/shared/lib/fs/file-tree';
26
+ import type { FileListing } from '@/client/hooks/workspace/file-listing';
27
+
28
+ export interface FileTreeEditDeps {
29
+ listing: FileListing;
30
+ setExpandedPaths: (updater: (prev: Set<string>) => Set<string>) => void;
31
+ setStoredExpandedPaths: (value: string[]) => void;
32
+ /**
33
+ * Re-read the panel. A local edit answers `null` when the entry is not in the
34
+ * rendered tree — a collapsed folder's contents are not — and re-reading is
35
+ * the only honest way to learn where the row went.
36
+ */
37
+ reload: () => void;
38
+ }
39
+
40
+ export interface FileTreeEdits {
41
+ /** Place a row a create just produced, without re-reading the tree. */
42
+ insertCreated: (entry: { path: string; kind: 'file' | 'folder' }) => void;
43
+ /** Move a row a rename just relocated, without re-reading. */
44
+ moveRenamed: (fromPath: string, toPath: string) => void;
45
+ }
46
+
47
+ export function useFileTreeEdits({
48
+ listing,
49
+ setExpandedPaths,
50
+ setStoredExpandedPaths,
51
+ reload,
52
+ }: FileTreeEditDeps): FileTreeEdits {
53
+ /**
54
+ * Open every folder row that leads to `path`.
55
+ *
56
+ * A nested create (`lib/parse.ts`) and a rename into a new folder both make
57
+ * directories the user has never opened, and a row placed inside a collapsed
58
+ * folder is a row nobody can see — the write would look like it failed.
59
+ */
60
+ const reveal = useCallback((path: string, tree: FsNode[]) => {
61
+ const chain = drawnAncestors(tree, path);
62
+ if (chain.length === 0) return;
63
+ setExpandedPaths((prev) => {
64
+ if (chain.every((folder) => prev.has(folder))) return prev;
65
+ const next = new Set(prev);
66
+ for (const folder of chain) next.add(folder);
67
+ setStoredExpandedPaths(Array.from(next));
68
+ return next;
69
+ });
70
+ }, [setExpandedPaths, setStoredExpandedPaths]);
71
+
72
+ const insertCreated = useCallback((entry: { path: string; kind: 'file' | 'folder' }) => {
73
+ const tree = listing.insertEntry(entry);
74
+ if (!tree) {
75
+ reload();
76
+ return;
77
+ }
78
+ reveal(entry.path, tree);
79
+ }, [listing, reload, reveal]);
80
+
81
+ /**
82
+ * A folder's descendants and every open branch beneath it carry its path as a
83
+ * prefix, so the expansion set is rekeyed in the same step — an open `src`
84
+ * renamed to `lib` must stay open as `lib`, not collapse.
85
+ */
86
+ const moveRenamed = useCallback((fromPath: string, toPath: string) => {
87
+ const tree = listing.moveEntry(fromPath, toPath);
88
+ if (!tree) {
89
+ reload();
90
+ return;
91
+ }
92
+ setExpandedPaths((prev) => {
93
+ const next = rekeyExpansion(prev, fromPath, toPath);
94
+ setStoredExpandedPaths(Array.from(next));
95
+ return next;
96
+ });
97
+ // A rename INTO a new folder (`a.ts` → `nested/a.ts`) has the same problem a
98
+ // nested create does: the destination folder is one nobody has opened.
99
+ reveal(toPath, tree);
100
+ }, [listing, reload, reveal, setExpandedPaths, setStoredExpandedPaths]);
101
+
102
+ return { insertCreated, moveRenamed };
103
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The paths the SHELL saw in a drag, for a webview that gives the page none.
8
+ *
9
+ * A Finder drag onto a `WKWebView` hands the page BYTES and nothing else.
10
+ * Measured on macOS 27 with a real `NSFilenamesPboardType` + `public.file-url`
11
+ * pasteboard: at `drop` the payload is `types: ["Files"]`, `files: [File]`,
12
+ * `getData('text/uri-list')` and `getData('text/plain')` both empty, and `File`
13
+ * carries no `path` property. So neither of the editor's open routes can fire:
14
+ *
15
+ * - `DataTransferItem.getAsFileSystemHandle` is `undefined` in WKWebView — the
16
+ * File System Access API is not implemented by WebKit (bug 257792 is open) —
17
+ * so there is no handle to read or write through.
18
+ * - There is no URI list. WebKit stopped adding local filenames as URLs to a
19
+ * file drag on macOS (WebKit changeset 222257), which is exactly the payload
20
+ * `/api/fs/scope` would need.
21
+ *
22
+ * A Finder drag on the macOS shell therefore ended at "That drop carried no
23
+ * readable file — drop it on the composer to attach it instead": the chat
24
+ * composer worked (it only needs bytes) and the editor did not (it needs a
25
+ * path). The Linux shell never had the bug — WebKitGTK preloads
26
+ * `text/uri-list` for a file-manager drag — and neither does the Windows one,
27
+ * where WebView2 is Chromium and `getAsFileSystemHandle` is available.
28
+ *
29
+ * The shell is the only layer that HAS the path, so it reads its pasteboard
30
+ * before the page's `drop` fires and answers `dropped_paths` with what it saw.
31
+ *
32
+ * Two rules, both about a value that outlives its gesture:
33
+ *
34
+ * - **Reading CONSUMES it** (in the shell). One drop opens one file, and a drop
35
+ * whose handler never asked must not open the previous file.
36
+ * - **A stale value is ignored.** A drop released where no target claimed it
37
+ * leaves the paths unread; the age check keeps that leftover from opening the
38
+ * wrong file later. The clock is the shell's own, and it runs on this machine.
39
+ */
40
+
41
+ import { isDesktopShell } from '@/client/lib/desktop/bridge';
42
+
43
+ /** What the shell answers with. */
44
+ export interface ShellDroppedPaths {
45
+ /** Absolute paths, in the pasteboard's own order. */
46
+ paths: string[];
47
+ /** The shell's clock, in milliseconds. */
48
+ at: number;
49
+ }
50
+
51
+ /**
52
+ * How long a captured drop stays usable.
53
+ *
54
+ * The page asks in the same turn the drop is delivered, so anything older is a
55
+ * leftover rather than this gesture. Generous enough for a busy main thread
56
+ * without letting one drop leak into the next.
57
+ */
58
+ export const SHELL_DROP_TTL_MS = 2_000;
59
+
60
+ /**
61
+ * The paths the shell captured for the drop being handled, or `[]`.
62
+ *
63
+ * Resolves `[]` in a browser, in a shell too old to answer, and when the answer
64
+ * is stale — all three mean the same thing to the caller: there is nothing to
65
+ * add, so the drop's own payload decides.
66
+ */
67
+ export async function readShellDroppedPaths(
68
+ now: number = Date.now(),
69
+ ): Promise<string[]> {
70
+ if (!isDesktopShell()) return [];
71
+ const invoke = typeof window === 'undefined' ? undefined : window.__kabmoCall;
72
+ if (!invoke) return [];
73
+ let answer: unknown;
74
+ try {
75
+ answer = await invoke('dropped_paths');
76
+ } catch {
77
+ return [];
78
+ }
79
+ const captured = answer as ShellDroppedPaths | null;
80
+ if (!captured || !Array.isArray(captured.paths) || captured.paths.length === 0) return [];
81
+ if (!Number.isFinite(captured.at) || Math.abs(now - captured.at) > SHELL_DROP_TTL_MS) return [];
82
+ return captured.paths.filter((entry) => typeof entry === 'string' && entry.trim().length > 0);
83
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The tab menu's rows and what each close action leaves behind.
8
+ *
9
+ * Two rules, and both are about not losing an edit: `Close saved` must leave the DIRTY
10
+ * tabs standing, and a row that would do nothing is absent rather than disabled — a menu
11
+ * of always-present rows that refuse is a menu that reads as broken.
12
+ */
13
+
14
+ import { describe, expect, test } from 'bun:test';
15
+
16
+ import { buildTabMenuRows, tabIdsAfterClose } from '@/client/lib/editor/tab-menu';
17
+ import type { OpenedFile } from '@/shared/types/fs';
18
+
19
+ function tab(id: string, path = `src/${id}.ts`): OpenedFile {
20
+ return { id, name: `${id}.ts`, path };
21
+ }
22
+
23
+ const A = tab('a');
24
+ const B = tab('b');
25
+ const C = tab('c');
26
+ const ALL = [A, B, C];
27
+
28
+ /**
29
+ * Rows with the split columns defaulted.
30
+ *
31
+ * `activeFileId` is the tab the menu was opened on and `splitRightFileId` is null — the
32
+ * ordinary unsplit column, where `Split right` applies and `Unsplit` does not.
33
+ */
34
+ function menuRows(options: {
35
+ tab: OpenedFile;
36
+ openedFiles: OpenedFile[];
37
+ dirtyIds?: Set<string | number>;
38
+ reopenable?: number;
39
+ activeFileId?: string | number | null;
40
+ splitRightFileId?: string | number | null;
41
+ }) {
42
+ return buildTabMenuRows({
43
+ dirtyIds: new Set(),
44
+ reopenable: 0,
45
+ activeFileId: options.tab.id,
46
+ splitRightFileId: null,
47
+ ...options,
48
+ });
49
+ }
50
+
51
+ describe('buildTabMenuRows', () => {
52
+ test('every row that applies is offered', () => {
53
+ const rows = menuRows({ tab: B, openedFiles: ALL, dirtyIds: new Set(), reopenable: 2 });
54
+ expect(rows.map((row) => row.action)).toEqual([
55
+ 'close',
56
+ 'close-others',
57
+ 'close-all',
58
+ 'close-saved',
59
+ 'copy-path',
60
+ 'reveal-in-files',
61
+ 'reopen-closed',
62
+ ]);
63
+ });
64
+
65
+ test('the only open tab offers no "close others"', () => {
66
+ const rows = menuRows({ tab: A, openedFiles: [A], dirtyIds: new Set(), reopenable: 0 });
67
+ expect(rows.map((row) => row.action)).toEqual(['close', 'close-all', 'copy-path', 'reveal-in-files']);
68
+ });
69
+
70
+ test('an empty reopen stack offers no "reopen closed"', () => {
71
+ const rows = menuRows({ tab: A, openedFiles: ALL, dirtyIds: new Set(), reopenable: 0 });
72
+ expect(rows.map((row) => row.action)).not.toContain('reopen-closed');
73
+ });
74
+
75
+ test('with every OTHER tab dirty, "close saved" would do nothing and is absent', () => {
76
+ const rows = menuRows({ tab: A, openedFiles: ALL, dirtyIds: new Set(['b', 'c']), reopenable: 0 });
77
+ expect(rows.map((row) => row.action)).not.toContain('close-saved');
78
+ });
79
+
80
+ test('"close saved" IS offered when this tab is the only saved one, since it closes it', () => {
81
+ // The row is about the SAVED tabs, and the one it was opened on counts.
82
+ const rows = menuRows({ tab: A, openedFiles: ALL, dirtyIds: new Set(['b', 'c']), reopenable: 0 });
83
+ expect(rows.map((row) => row.action)).not.toContain('close-saved');
84
+ });
85
+
86
+ test('a diff tab offers Copy path but not Reveal — a diff names a change, not a file row', () => {
87
+ // The path is real (it is the changed file), so copying it is meaningful; revealing
88
+ // it in the Files panel is not, because the panel lists files and the diff tab is a
89
+ // change against one.
90
+ const diff: OpenedFile = { id: 'd', name: 'a.ts (diff)', path: 'a.ts', isDiff: true };
91
+ const rows = menuRows({ tab: diff, openedFiles: [diff], dirtyIds: new Set(), reopenable: 0 });
92
+ expect(rows.map((row) => row.action)).toEqual(['close', 'close-all', 'copy-path']);
93
+ });
94
+
95
+ test('a path-less tab (an attachment chip) offers no path actions', () => {
96
+ const chip: OpenedFile = { id: 'chip', name: 'notes.txt', path: '' };
97
+ const rows = menuRows({ tab: chip, openedFiles: [chip], dirtyIds: new Set(), reopenable: 0 });
98
+ expect(rows.map((row) => row.action)).not.toContain('copy-path');
99
+ });
100
+ });
101
+
102
+ describe('tabIdsAfterClose', () => {
103
+ test('close removes exactly one tab', () => {
104
+ expect(tabIdsAfterClose('close', B, ALL, new Set())).toEqual(['a', 'c']);
105
+ });
106
+
107
+ test('close others keeps exactly the tab it was opened on', () => {
108
+ expect(tabIdsAfterClose('close-others', B, ALL, new Set())).toEqual(['b']);
109
+ });
110
+
111
+ test('close all keeps nothing', () => {
112
+ expect(tabIdsAfterClose('close-all', B, ALL, new Set())).toEqual([]);
113
+ });
114
+
115
+ test('close saved keeps the DIRTY tabs — the only reading that cannot lose an edit', () => {
116
+ expect(tabIdsAfterClose('close-saved', A, ALL, new Set(['b', 'c']))).toEqual(['b', 'c']);
117
+ });
118
+
119
+ test('close saved on a clean set keeps nothing', () => {
120
+ expect(tabIdsAfterClose('close-saved', A, ALL, new Set())).toEqual([]);
121
+ });
122
+
123
+ test('a non-close action answers null, so a caller can tell it apart from "close nothing"', () => {
124
+ expect(tabIdsAfterClose('copy-path', A, ALL, new Set())).toBeNull();
125
+ expect(tabIdsAfterClose('reopen-closed', A, ALL, new Set())).toBeNull();
126
+ });
127
+ });