@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
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The desktop shell's drop path, which is the only route a WebKit webview has.
8
+ *
9
+ * Measured on macOS 27 against a real `NSFilenamesPboardType` + `public.file-url`
10
+ * pasteboard delivered into a `WKWebView`:
11
+ *
12
+ * drop: types ["Files"], files [File], getData('text/uri-list') ''
13
+ * getData('text/plain') '', File.path undefined
14
+ * DataTransferItem.getAsFileSystemHandle undefined
15
+ *
16
+ * So both routes the hook already had are dead there: there is no handle to
17
+ * open (WebKit implements no File System Access API) and no URI list to resolve
18
+ * (WebKit stopped adding local filenames as URLs to a file drag). Every Finder
19
+ * drop on the macOS shell was refused with "that drop carried no readable file"
20
+ * — the composer still worked, because it only needs the bytes.
21
+ *
22
+ * The shell reads its own pasteboard before the DOM event and answers
23
+ * `dropped_paths`. These cases pin the three properties of that answer: it is
24
+ * used when present, it does not displace a handle, and it is refused when it
25
+ * is stale.
26
+ */
27
+
28
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
29
+ import { Window } from 'happy-dom';
30
+ import { h, render } from 'preact';
31
+ import { act } from 'preact/test-utils';
32
+ import { useEditorDrop, type UseEditorDropResult } from '@/client/hooks/editor/use-editor-drop';
33
+ import { readShellDroppedPaths, SHELL_DROP_TTL_MS } from '@/client/lib/desktop/dropped-paths';
34
+
35
+ const DOM_GLOBALS = ['window', 'document', 'navigator', 'Node', 'Element', 'HTMLElement', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'fetch'] as const;
36
+ const nativeGlobals: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
37
+
38
+ let scopeResponse: { ok: boolean; status: number; body: unknown } = { ok: true, status: 200, body: {} };
39
+ let fetchCalls: string[] = [];
40
+ let opened: unknown[] = [];
41
+ let bridgeCalls: string[] = [];
42
+ /** What the shell answers for `dropped_paths`, per case. */
43
+ let bridgeAnswer: unknown = null;
44
+
45
+ beforeAll(() => {
46
+ const win = new Window({ url: 'http://localhost' });
47
+ const target = globalThis as unknown as Record<string, unknown>;
48
+ for (const key of DOM_GLOBALS) {
49
+ nativeGlobals[key] = target[key];
50
+ target[key] = (win as unknown as Record<string, unknown>)[key];
51
+ }
52
+ globalThis.fetch = (async (url: string) => {
53
+ fetchCalls.push(String(url));
54
+ const { ok, status, body } = scopeResponse;
55
+ return { ok, status, json: async () => body };
56
+ }) as unknown as typeof globalThis.fetch;
57
+ win.addEventListener('omp:open-file', (event) => {
58
+ opened.push((event as unknown as CustomEvent).detail);
59
+ });
60
+ });
61
+
62
+ afterAll(() => {
63
+ const target = globalThis as unknown as Record<string, unknown>;
64
+ for (const key of DOM_GLOBALS) {
65
+ if (nativeGlobals[key] === undefined) delete target[key];
66
+ else target[key] = nativeGlobals[key];
67
+ }
68
+ });
69
+
70
+ /** A `DataTransfer` shaped exactly as a Finder drag arrives on WebKit. */
71
+ function webkitFinderTransfer(): DataTransfer {
72
+ return {
73
+ types: ['Files'],
74
+ files: [{ name: 'from-finder.ts', size: 12 }],
75
+ getData: () => '',
76
+ items: [{ kind: 'file', type: '', getAsFile: () => null }],
77
+ } as unknown as DataTransfer;
78
+ }
79
+
80
+ /** A `DataTransfer` that offers a handle — the Chromium shape. */
81
+ function handleTransfer(handle: FileSystemFileHandle): DataTransfer {
82
+ return {
83
+ types: ['Files'],
84
+ files: [],
85
+ getData: () => '',
86
+ items: [{ kind: 'file', type: '', getAsFileSystemHandle: async () => handle }],
87
+ } as unknown as DataTransfer;
88
+ }
89
+
90
+ async function mount(enabled = true): Promise<UseEditorDropResult> {
91
+ const container = document.createElement('div');
92
+ document.body.appendChild(container);
93
+ let api: UseEditorDropResult | null = null;
94
+ const Probe = () => {
95
+ api = useEditorDrop({ enabled, onResult: () => {} });
96
+ return null;
97
+ };
98
+ await act(async () => {
99
+ render(h(Probe, {}), container);
100
+ });
101
+ if (!api) throw new Error('the hook did not mount');
102
+ return api;
103
+ }
104
+
105
+ /** Deliver a drop and drain the handler's awaits (fetch, bridge, handle). */
106
+ async function drop(api: UseEditorDropResult, transfer: DataTransfer): Promise<void> {
107
+ const event = {
108
+ dataTransfer: transfer,
109
+ defaultPrevented: false,
110
+ target: document.body,
111
+ preventDefault: () => {},
112
+ stopPropagation: () => {},
113
+ };
114
+ await act(async () => {
115
+ api.dropProps.onDrop(event as never);
116
+ });
117
+ for (let pass = 0; pass < 6; pass += 1) {
118
+ await act(async () => {
119
+ await Promise.resolve();
120
+ });
121
+ }
122
+ }
123
+
124
+ describe('a WebKit drop with no payload path', () => {
125
+ beforeEach(() => {
126
+ scopeResponse = {
127
+ ok: true,
128
+ status: 200,
129
+ body: { root: '/repo', path: 'src/from-finder.ts', name: 'from-finder.ts', kind: 'text' },
130
+ };
131
+ fetchCalls = [];
132
+ opened = [];
133
+ bridgeCalls = [];
134
+ bridgeAnswer = { paths: ['/repo/src/from-finder.ts'], at: Date.now() };
135
+ window.__kabmoCall = async (method: string) => {
136
+ bridgeCalls.push(method);
137
+ return bridgeAnswer;
138
+ };
139
+ });
140
+
141
+ test('the shell’s path is what opens the file', async () => {
142
+ const api = await mount();
143
+ await drop(api, webkitFinderTransfer());
144
+
145
+ // The bridge was asked, and the answer went through the same resolver every
146
+ // other drop uses — the shell's path is a path, not a second code path.
147
+ expect(bridgeCalls).toEqual(['dropped_paths']);
148
+ expect(fetchCalls[0]).toContain('/api/fs/scope?path=');
149
+ expect(decodeURIComponent(fetchCalls[0])).toContain('/repo/src/from-finder.ts');
150
+ expect(opened).toHaveLength(1);
151
+ expect(opened[0]).toEqual({ path: 'src/from-finder.ts', name: 'from-finder.ts', root: '/repo' });
152
+ });
153
+
154
+ test('a handle still wins over the shell’s path', async () => {
155
+ const writes: string[] = [];
156
+ const handle = {
157
+ name: 'by-handle.ts',
158
+ kind: 'file',
159
+ async getFile() {
160
+ return new File([new TextEncoder().encode('const a = 1;\n')], 'by-handle.ts');
161
+ },
162
+ async createWritable() {
163
+ return {
164
+ async write(data: string) {
165
+ writes.push(data);
166
+ },
167
+ async close() {},
168
+ };
169
+ },
170
+ } as unknown as FileSystemFileHandle;
171
+
172
+ const api = await mount();
173
+ await drop(api, handleTransfer(handle));
174
+
175
+ // The handle is the shape that carries write access, so it must not be
176
+ // displaced by a path the shell also happened to capture.
177
+ expect(bridgeCalls).toEqual([]);
178
+ expect(fetchCalls).toHaveLength(0);
179
+ expect(opened).toHaveLength(1);
180
+ expect((opened[0] as { handleId?: string }).handleId).toBeTruthy();
181
+ });
182
+
183
+ test('an in-page drag with no path is still reported, not swallowed', async () => {
184
+ bridgeAnswer = null;
185
+ const api = await mount();
186
+ await drop(api, webkitFinderTransfer());
187
+
188
+ expect(fetchCalls).toHaveLength(0);
189
+ expect(opened).toHaveLength(0);
190
+ });
191
+ });
192
+
193
+ describe('readShellDroppedPaths', () => {
194
+ beforeEach(() => {
195
+ bridgeCalls = [];
196
+ bridgeAnswer = { paths: ['/repo/a.ts'], at: 1_000 };
197
+ window.__kabmoCall = async (method: string) => {
198
+ bridgeCalls.push(method);
199
+ return bridgeAnswer;
200
+ };
201
+ });
202
+
203
+ test('a stale answer is refused', async () => {
204
+ // The page asks in the drop's own turn; anything older is a leftover from a
205
+ // drag released where no target claimed it.
206
+ expect(await readShellDroppedPaths(1_000 + SHELL_DROP_TTL_MS + 1)).toEqual([]);
207
+ expect(await readShellDroppedPaths(1_000 + SHELL_DROP_TTL_MS - 1)).toEqual(['/repo/a.ts']);
208
+ });
209
+
210
+ test('an empty or malformed answer reads as no help', async () => {
211
+ bridgeAnswer = { paths: [], at: 1_000 };
212
+ expect(await readShellDroppedPaths(1_000)).toEqual([]);
213
+ bridgeAnswer = { paths: ['', ' '], at: 1_000 };
214
+ expect(await readShellDroppedPaths(1_000)).toEqual([]);
215
+ bridgeAnswer = { paths: 'nope', at: 1_000 };
216
+ expect(await readShellDroppedPaths(1_000)).toEqual([]);
217
+ });
218
+
219
+ test('a browser never asks the bridge', async () => {
220
+ delete window.__kabmoCall;
221
+ expect(await readShellDroppedPaths(1_000)).toEqual([]);
222
+ expect(bridgeCalls).toHaveLength(0);
223
+ });
224
+ });
@@ -18,20 +18,31 @@
18
18
  * `text/uri-list` / `text/plain`. That resolves through `/api/fs/scope`,
19
19
  * because a path can be written back through the server.
20
20
  *
21
+ * 3. **A Finder drag onto a DESKTOP SHELL's webview.** Neither of the above
22
+ * exists there: WebKit implements no `getAsFileSystemHandle` (WebKit bug
23
+ * 257792) and puts no path on the pasteboard the page can read, so a drop
24
+ * carried bytes and nothing else and the editor refused it. The shell reads
25
+ * the pasteboard itself and hands the paths over — see
26
+ * `client/lib/desktop/dropped-paths`.
27
+ *
21
28
  * Handles are tried FIRST: they are the shape that carries write access, and a
22
29
  * host that offers both (a Finder drag onto a page that also set a URI list)
23
- * should keep it.
30
+ * should keep it. The shell's paths come next — they resolve to a real path,
31
+ * which is what the editor saves through.
24
32
  *
25
- * The overlay's state is a depth COUNTER, and it is reset by a window-level
26
- * `dragend`/`drop` too — a drag that ends outside the element (Escape, released
27
- * over another window) fires no matching `dragleave`, and a counter left above
28
- * zero made the NEXT drag's overlay look stuck.
33
+ * The overlay's state is `useDragPresence`, NOT a depth counter: `dragenter`
34
+ * fires for every nested child the pointer crosses, so a counter rose with each
35
+ * crossing and only a full exit lowered it — measured in Chromium, five child
36
+ * crossings inside the chat left the counter at 5 after the pointer had left, and
37
+ * the overlay stayed on. `relatedTarget` answers the same question symmetrically.
29
38
  */
30
39
 
31
- import { useCallback, useEffect, useRef, useState } from 'preact/hooks';
40
+ import { useCallback, useRef } from 'preact/hooks';
32
41
  import type { TargetedDragEvent } from 'preact';
33
42
  import { collectDroppedFileUris, hasDraggedFiles } from '@/client/hooks/chat/composer/drop-payload';
43
+ import { useDragPresence } from '@/client/hooks/ui/drag-presence';
34
44
  import { openHandleAsTab } from '@/client/lib/launch/file-handlers';
45
+ import { readShellDroppedPaths } from '@/client/lib/desktop/dropped-paths';
35
46
  import { openFileInEditor } from '@/client/hooks/ui/open-file';
36
47
 
37
48
  /** What `/api/fs/scope` answers with. */
@@ -178,47 +189,24 @@ async function openDroppedHandle(
178
189
  }
179
190
 
180
191
  export function useEditorDrop({ enabled = true, onResult }: UseEditorDropOptions = {}): UseEditorDropResult {
181
- const [isDragging, setIsDragging] = useState(false);
182
- // dragenter/dragleave fire per nested child the pointer crosses, so a boolean
183
- // drops to false the moment the cursor moves from the pane onto a child.
184
- const depthRef = useRef(0);
192
+ // `relatedTarget`-based, not a counter: see `useDragPresence`. The counter that
193
+ // used to live here is what left the overlay stuck after a gesture the element
194
+ // never saw the end of.
195
+ const presence = useDragPresence();
185
196
  const enabledRef = useRef(enabled);
186
197
  enabledRef.current = enabled;
187
198
  const onResultRef = useRef(onResult);
188
199
  onResultRef.current = onResult;
189
200
 
190
- const reset = useCallback(() => {
191
- depthRef.current = 0;
192
- setIsDragging(false);
193
- }, []);
194
-
195
- // A drag can end without reaching this element again — released over another
196
- // window, cancelled with Escape, or its source node unmounted mid-drag. The
197
- // element's own handlers have already run by the time these fire, so this only
198
- // clears state the drop handler did not. Without it a counter left above zero
199
- // made the next drag's overlay look stuck on, and a counter left BELOW zero
200
- // (see `onDragLeave`) made the next one never appear.
201
- useEffect(() => {
202
- window.addEventListener('dragend', reset);
203
- window.addEventListener('drop', reset);
204
- return () => {
205
- window.removeEventListener('dragend', reset);
206
- window.removeEventListener('drop', reset);
207
- };
208
- }, [reset]);
209
-
210
201
  const onDragEnter = useCallback((e: TargetedDragEvent<HTMLElement>) => {
211
202
  // A descendant already claimed this drag — the composer, whose own handler
212
- // runs first because it is deeper in the tree. Skipping the increment here
213
- // is safe ONLY because `onDragLeave` counts symmetrically; the two must
214
- // agree or the counter drifts negative and the overlay stops appearing.
203
+ // runs first because it is deeper in the tree.
215
204
  if (e.defaultPrevented) return;
216
205
  if (!isOpenableDrag(e.dataTransfer)) return;
217
206
  e.preventDefault();
218
207
  if (!enabledRef.current) return;
219
- depthRef.current += 1;
220
- setIsDragging(true);
221
- }, []);
208
+ presence.enter();
209
+ }, [presence]);
222
210
 
223
211
  const onDragOver = useCallback((e: TargetedDragEvent<HTMLElement>) => {
224
212
  // A descendant claimed the drag — the composer, whose own handler runs first
@@ -228,7 +216,7 @@ export function useEditorDrop({ enabled = true, onResult }: UseEditorDropOptions
228
216
  // of them. The counter is left alone, so moving back off the composer
229
217
  // restores this overlay.
230
218
  if (e.defaultPrevented) {
231
- setIsDragging(false);
219
+ presence.clear();
232
220
  return;
233
221
  }
234
222
  if (!isOpenableDrag(e.dataTransfer)) return;
@@ -237,44 +225,46 @@ export function useEditorDrop({ enabled = true, onResult }: UseEditorDropOptions
237
225
  // window-level guard, which runs later in the bubble.
238
226
  e.preventDefault();
239
227
  e.stopPropagation();
240
- if (depthRef.current > 0) setIsDragging(true);
228
+ // Every `dragover` on this element is proof the pointer is inside it — a
229
+ // child crossing fires the pair in between, and this is what re-asserts the
230
+ // overlay without counting anything. Gated on `enabled` for the same reason
231
+ // `onDragEnter` is: a target with no workspace behind it must stay dark
232
+ // rather than light up to refuse.
233
+ if (enabledRef.current) presence.enter();
241
234
  if (!e.dataTransfer) return;
242
235
  e.dataTransfer.dropEffect = enabledRef.current ? 'copy' : 'none';
243
- }, []);
236
+ }, [presence]);
244
237
 
245
238
  /**
246
239
  * A `dragleave` that stays INSIDE the element is a move between children, not
247
- * an exit — and counting it is what made the overlay disappear while the
248
- * pointer was still over the workspace.
249
- *
250
- * The failure, measured: entering the workspace increments the counter, moving
251
- * onto the composer is claimed by the composer (`defaultPrevented`, so the
252
- * workspace does NOT increment), and moving back off the composer fires a
253
- * `dragleave` that bubbles up and DECREMENTS — the counter returns to zero and
254
- * the overlay turns off even though the pointer never left the workspace.
255
- *
256
- * `relatedTarget` is the element being entered, so `contains` is the exact
257
- * test. It can be null (a drag leaving the window), which the counter still
258
- * handles; the clamp at zero keeps a stray leave from going negative, because
259
- * a negative counter makes every later drag's `=== 0` test miss and the
260
- * overlay never appears again.
240
+ * an exit — `useDragPresence.leave` is the only rule here, because the counter
241
+ * this replaced is what made the overlay stay lit (or vanish) for the wrong
242
+ * reason.
261
243
  */
262
244
  const onDragLeave = useCallback((e: TargetedDragEvent<HTMLElement>) => {
263
- if (e.relatedTarget instanceof Node && e.currentTarget.contains(e.relatedTarget)) return;
264
- if (depthRef.current === 0) return;
265
- depthRef.current -= 1;
266
- if (depthRef.current === 0) setIsDragging(false);
267
- }, []);
245
+ presence.leave(e);
246
+ }, [presence]);
268
247
 
269
248
  /** Open what a drop carries — shared by the bubble and the capture paths. */
270
249
  const openDropped = useCallback((dt: DataTransfer | null) => {
271
250
  if (!dt) return;
251
+ // The payload is read in THIS tick, before any await. A drop's data store is
252
+ // released when the handler returns, so a `getData` issued after an IPC
253
+ // round trip reads an empty string — measured on the shell's `dropped_paths`
254
+ // call, which is exactly such a round trip.
255
+ const references = collectDroppedFileUris(dt);
272
256
  // Handles first: they are the only shape that carries write access, and a
273
- // Finder drag has nothing else.
274
- void openDroppedHandle(dt, onResultRef.current).then((opened) => {
257
+ // Finder drag on a Chromium webview has nothing else.
258
+ void openDroppedHandle(dt, onResultRef.current).then(async (opened) => {
275
259
  if (opened) return;
276
- const references = collectDroppedFileUris(dt);
277
- if (references.length === 0) {
260
+ // Then the shell's own read of the pasteboard, which is the ONLY route a
261
+ // WebKit webview offers: it has no file-system handle and no URI list, so
262
+ // a Finder drop there carries bytes the editor cannot save. Asked only
263
+ // when no handle won, and consumed by the shell, so one drop opens one
264
+ // file.
265
+ const shellPaths = await readShellDroppedPaths();
266
+ const first = shellPaths[0] ?? references[0];
267
+ if (!first) {
278
268
  onResultRef.current?.({
279
269
  ok: false,
280
270
  message: 'That drop carried no readable file — drop it on the composer to attach it instead.',
@@ -283,7 +273,7 @@ export function useEditorDrop({ enabled = true, onResult }: UseEditorDropOptions
283
273
  }
284
274
  // One open per gesture: the editor has a single active tab, so opening
285
275
  // several would leave the user on whichever resolved last.
286
- void openDroppedReference(references[0], onResultRef.current);
276
+ await openDroppedReference(first, onResultRef.current);
287
277
  });
288
278
  }, []);
289
279
 
@@ -295,10 +285,10 @@ export function useEditorDrop({ enabled = true, onResult }: UseEditorDropOptions
295
285
  if (!isOpenableDrag(e.dataTransfer)) return;
296
286
  e.preventDefault();
297
287
  e.stopPropagation();
298
- reset();
288
+ presence.clear();
299
289
  if (!enabledRef.current || !e.dataTransfer) return;
300
290
  openDropped(e.dataTransfer);
301
- }, [openDropped, reset]);
291
+ }, [openDropped, presence]);
302
292
 
303
293
  /**
304
294
  * Claim a file drop that is about to land on a code surface.
@@ -315,13 +305,13 @@ export function useEditorDrop({ enabled = true, onResult }: UseEditorDropOptions
315
305
  if (!(target instanceof Element) || !target.closest(`[${CODE_SURFACE_ATTRIBUTE}]`)) return;
316
306
  e.preventDefault();
317
307
  e.stopPropagation();
318
- reset();
308
+ presence.clear();
319
309
  if (!enabledRef.current || !e.dataTransfer) return;
320
310
  openDropped(e.dataTransfer);
321
- }, [openDropped, reset]);
311
+ }, [openDropped, presence]);
322
312
 
323
313
  return {
324
- isDragging,
314
+ isDragging: presence.active,
325
315
  dropProps: { onDragEnter, onDragOver, onDragLeave, onDrop },
326
316
  captureDropProps: { onDropCapture },
327
317
  };
@@ -135,7 +135,7 @@ describe('useEditorFind revealMatch', () => {
135
135
  test('aims the caret at the first match on the given line and focuses it', async () => {
136
136
  // `alpha beta alpha` — line 1 holds the first match; the request names it.
137
137
  await harness.act(async () => {
138
- harness.find?.revealMatch({ query: 'beta', options: { matchCase: false, wholeWord: false, isRegex: false }, line: 1 });
138
+ harness.find?.revealMatch({ query: 'beta', options: { matchCase: false, wholeWord: false, isRegex: false, inSelection: false }, line: 1 });
139
139
  });
140
140
 
141
141
  expect(harness.find?.query).toBe('beta');
@@ -148,7 +148,7 @@ describe('useEditorFind revealMatch', () => {
148
148
 
149
149
  test('does not open the bar — the jump must not cover the line it shows', async () => {
150
150
  await harness.act(async () => {
151
- harness.find?.revealMatch({ query: 'alpha', options: { matchCase: false, wholeWord: false, isRegex: false }, line: 1 });
151
+ harness.find?.revealMatch({ query: 'alpha', options: { matchCase: false, wholeWord: false, isRegex: false, inSelection: false }, line: 1 });
152
152
  });
153
153
 
154
154
  expect(harness.find?.open).toBe(false);
@@ -22,6 +22,8 @@
22
22
  import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
23
23
 
24
24
  import { useSessionState } from '@/client/hooks/workspace/session-state';
25
+ import { useFindHistory } from '@/client/hooks/editor/find-history';
26
+ import { useSelectionRange } from '@/client/hooks/editor/find-selection-range';
25
27
  import {
26
28
  DEFAULT_FIND_OPTIONS,
27
29
  findMatches,
@@ -59,6 +61,10 @@ export function useEditorFind({
59
61
  // A blob written before an option existed carries only the keys it had, so
60
62
  // the read is merged over the defaults rather than trusted wholesale.
61
63
  const options = useMemo<FindOptions>(() => ({ ...DEFAULT_FIND_OPTIONS, ...storedOptions }), [storedOptions]);
64
+ // The range an "in selection" search is restricted to, captured when it is armed.
65
+ const selection = useSelectionRange();
66
+ // Recent queries, remembered when a search was actually USED — see `find-history.ts`.
67
+ const findHistory = useFindHistory();
62
68
  const [open, setOpen] = useState(false);
63
69
  const [replaceOpen, setReplaceOpen] = useState(false);
64
70
  const [currentIndex, setCurrentIndex] = useState(-1);
@@ -76,7 +82,12 @@ export function useEditorFind({
76
82
  const openRef = useRef(false);
77
83
  openRef.current = open;
78
84
 
79
- const result = useMemo(() => findMatches(text, query, options), [text, query, options]);
85
+ const result = useMemo(
86
+ // The range travels beside the options: the flag says WHETHER to restrict, the range
87
+ // says to what, and the two are captured at different moments.
88
+ () => findMatches(text, query, options, options.inSelection ? selection.range : null),
89
+ [text, query, options, selection.range],
90
+ );
80
91
 
81
92
  /**
82
93
  * Where the current match is resolved FROM: the caret/anchor a reseed uses.
@@ -166,6 +177,9 @@ export function useEditorFind({
166
177
  const toggleReplace = useCallback(() => setReplaceOpen((prev) => !prev), []);
167
178
 
168
179
  const close = useCallback(() => {
180
+ // A query that was actually searched is worth remembering; one typed and abandoned
181
+ // is not, which is why this is here rather than in `setQuery`.
182
+ findHistory.remember(query);
169
183
  setOpen(false);
170
184
  setReplaceOpen(false);
171
185
  // Focus returns to the match, which is where the user was looking.
@@ -190,10 +204,28 @@ export function useEditorFind({
190
204
 
191
205
  const toggleOption = useCallback(
192
206
  (key: keyof FindOptions) => {
193
- setOptions({ ...options, [key]: !options[key] });
207
+ const next = { ...options, [key]: !options[key] };
208
+ if (key === 'inSelection' && !selection.arm(readSelection)) {
209
+ // Nothing selected: the toggle cannot mean anything, so it does not arm.
210
+ setOptions({ ...options, inSelection: false });
211
+ return;
212
+ }
213
+ if (key === 'inSelection' && !next.inSelection) selection.disarm();
214
+ setOptions(next);
194
215
  reseed(anchorRef.current);
195
216
  },
196
- [options, setOptions, reseed],
217
+ [options, setOptions, reseed, readSelection, selection],
218
+ );
219
+
220
+ /** Re-run a query from the history, and remember it as the most recent again. */
221
+ const useHistoryEntry = useCallback(
222
+ (value: string) => {
223
+ setQueryState(value);
224
+ findHistory.remember(value);
225
+ reseed(anchorRef.current);
226
+ setResolveRequest((previous) => previous + 1);
227
+ },
228
+ [findHistory, reseed],
197
229
  );
198
230
 
199
231
  /**
@@ -300,6 +332,9 @@ export function useEditorFind({
300
332
  runCommand,
301
333
  revealMatch,
302
334
  toggleOption,
335
+ selectionRange: options.inSelection ? selection.range : null,
336
+ history: findHistory.entries,
337
+ useHistoryEntry,
303
338
  step,
304
339
  replaceCurrent,
305
340
  replaceAll,