@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,127 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Quick open: reach a file by NAME, without expanding the tree.
8
+ *
9
+ * `⌘P` is the fastest route to a file the reader has not opened — the tree needs
10
+ * every folder on the path expanded, and a search panel needs a query about the
11
+ * file's CONTENT. The index is `/api/fs/list`, which already exists for the
12
+ * composer's `@` picker: a flat walk, capped at 3 000 files, skipping the
13
+ * dependency trees (`node_modules`, `dist`, …). That budget is exactly what a picker
14
+ * wants, so this reuses the route rather than growing a second one.
15
+ *
16
+ * ## Matching is per-SEGMENT, not a substring of the whole path
17
+ *
18
+ * `useTabs` finds `use-file-tabs.ts`; so does `uft`; and so does `tabs`. What a
19
+ * user types is usually the tail of a path, and a plain `path.includes(query)` ranks
20
+ * `src/client/hooks/editor/use-file-tabs.ts` no better than a file whose directory
21
+ * happens to contain the same letters. Scoring prefers, in order: an exact basename
22
+ * match, a basename prefix, a basename substring, then the same three against the
23
+ * whole path — and shorter paths win ties, because the file you want is usually the
24
+ * one closest to the root of what you typed.
25
+ */
26
+
27
+ /** One file the picker can offer. */
28
+ export interface QuickOpenEntry {
29
+ /** Workspace-relative path — what `handleOpenFile` takes. */
30
+ path: string;
31
+ /** The last segment, for the row's title. */
32
+ name: string;
33
+ /** Everything before the last segment, for the row's subtitle. */
34
+ directory: string;
35
+ }
36
+
37
+ /** The shape `/api/fs/list` answers. */
38
+ interface FileListResponse {
39
+ files?: unknown;
40
+ truncated?: unknown;
41
+ }
42
+
43
+ /** A row from `/api/fs/list`, narrowed rather than asserted. */
44
+ function isFileRow(value: unknown): value is { path: string } {
45
+ return typeof value === 'object' && value !== null && 'path' in value && typeof value.path === 'string';
46
+ }
47
+
48
+ /** Split a workspace-relative path into the two parts a row prints. */
49
+ export function quickOpenEntry(path: string): QuickOpenEntry {
50
+ const cut = path.lastIndexOf('/');
51
+ return cut === -1
52
+ ? { path, name: path, directory: '' }
53
+ : { path, name: path.slice(cut + 1), directory: path.slice(0, cut) };
54
+ }
55
+
56
+ /**
57
+ * A score for one entry against a query, or `null` when it does not match.
58
+ *
59
+ * Higher is better. The tiers are ordered so that a basename hit ALWAYS beats a
60
+ * directory-only hit, which is what makes typing a file's name find the file rather
61
+ * than every sibling in a folder named after it.
62
+ */
63
+ export function scoreQuickOpen(entry: QuickOpenEntry, query: string): number | null {
64
+ const needle = query.trim().toLowerCase();
65
+ if (!needle) return 0;
66
+ const name = entry.name.toLowerCase();
67
+ const path = entry.path.toLowerCase();
68
+
69
+ const tier = (haystack: string, weight: number): number | null => {
70
+ if (haystack === needle) return weight + 300;
71
+ if (haystack.startsWith(needle)) return weight + 200;
72
+ if (haystack.includes(needle)) return weight + 100;
73
+ return null;
74
+ };
75
+
76
+ const nameScore = tier(name, 1000);
77
+ if (nameScore !== null) return nameScore - entry.path.length / 100;
78
+ const pathScore = tier(path, 0);
79
+ if (pathScore !== null) return pathScore - entry.path.length / 100;
80
+ // A subsequence match (`uft` → use-file-tabs) is the last resort, and only on the
81
+ // basename: a subsequence over a whole path matches almost everything.
82
+ if (isSubsequence(needle, name)) return 50 - entry.path.length / 100;
83
+ return null;
84
+ }
85
+
86
+ /** Whether every character of `needle` appears in `haystack`, in order. */
87
+ export function isSubsequence(needle: string, haystack: string): boolean {
88
+ let index = 0;
89
+ for (const character of haystack) {
90
+ if (character === needle[index]) index += 1;
91
+ if (index === needle.length) return true;
92
+ }
93
+ return needle.length === 0;
94
+ }
95
+
96
+ /** The ranked matches for `query`, best first, capped at `limit`. */
97
+ export function rankQuickOpen(
98
+ entries: readonly QuickOpenEntry[],
99
+ query: string,
100
+ limit = 50,
101
+ ): QuickOpenEntry[] {
102
+ const scored: Array<{ entry: QuickOpenEntry; score: number }> = [];
103
+ for (const entry of entries) {
104
+ const score = scoreQuickOpen(entry, query);
105
+ if (score !== null) scored.push({ entry, score });
106
+ }
107
+ scored.sort((a, b) => b.score - a.score || a.entry.path.localeCompare(b.entry.path));
108
+ return scored.slice(0, limit).map((row) => row.entry);
109
+ }
110
+
111
+ /** Read the index for one scope. A refusal answers an empty list, never a throw. */
112
+ export async function fetchQuickOpenIndex(root?: string | null, repo?: string | null): Promise<QuickOpenEntry[]> {
113
+ const params = new URLSearchParams();
114
+ if (root) params.set('root', root);
115
+ if (repo && repo !== '.') params.set('repo', repo);
116
+ try {
117
+ const res = await fetch(`/api/fs/list?${params.toString()}`);
118
+ const data = (await res.json().catch(() => null)) as FileListResponse | null;
119
+ if (!res.ok || !data || !Array.isArray(data.files)) return [];
120
+ return data.files.flatMap((row) => {
121
+ if (!isFileRow(row)) return [];
122
+ return row.path ? [quickOpenEntry(row.path)] : [];
123
+ });
124
+ } catch {
125
+ return [];
126
+ }
127
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Save As: the name it suggests, the name it accepts, and what each answer means.
8
+ *
9
+ * The suggestion keeps the EXTENSION: a destination that lost it would be saved as a file
10
+ * the surface no longer recognises, so the language would change under the user. A `409`
11
+ * is a REFUSAL rather than a failure — the user picked a name that is taken — and the
12
+ * dialog has to be able to say so without closing.
13
+ */
14
+
15
+ import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
16
+ import { Window } from 'happy-dom';
17
+
18
+ import { isSingleSegmentName, saveAsSuggestedName, saveFileAs } from '@/client/hooks/editor/save-as';
19
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
20
+
21
+ /**
22
+ * The DOM globals come from the shared helper, and the `File`/`Blob` it installs are
23
+ * RESTORED at the end.
24
+ *
25
+ * A local save-and-restore loop is what broke a suite two directories away: this file
26
+ * swapped `File` and `Blob` for happy-dom's and never put them back, so a later file's
27
+ * `carriesBytes` read a happy-dom `File` whose `slice().arrayBuffer()` answered empty and
28
+ * reported that a real file held no bytes — a failure in a suite this file does not name.
29
+ * `installDomGlobals`/`restoreDomGlobals` capture the runner's own values at their first
30
+ * install and put them back, which is the only ordering-safe way to do it in a directory
31
+ * run (Bun imports every file before any test executes).
32
+ */
33
+ const nativeFetch = Bun.fetch;
34
+
35
+ beforeAll(() => {
36
+ installDomGlobals(new Window({ url: 'http://localhost' }));
37
+ });
38
+
39
+ afterAll(() => {
40
+ restoreDomGlobals();
41
+ });
42
+
43
+ afterEach(() => {
44
+ globalThis.fetch = nativeFetch;
45
+ });
46
+
47
+ function stub(answer: { ok: boolean; status?: number; body?: unknown }): FormData[] {
48
+ const forms: FormData[] = [];
49
+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
50
+ forms.push(init?.body as FormData);
51
+ return {
52
+ ok: answer.ok,
53
+ status: answer.status ?? (answer.ok ? 200 : 500),
54
+ json: async () => answer.body ?? null,
55
+ };
56
+ }) as unknown as typeof fetch;
57
+ return forms;
58
+ }
59
+
60
+ describe('saveAsSuggestedName', () => {
61
+ test('keeps the extension', () => {
62
+ expect(saveAsSuggestedName('notes.ts')).toBe('notes copy.ts');
63
+ expect(saveAsSuggestedName('README.md')).toBe('README copy.md');
64
+ });
65
+
66
+ test('a name with several dots keeps only the last as the extension', () => {
67
+ expect(saveAsSuggestedName('a.test.ts')).toBe('a.test copy.ts');
68
+ });
69
+
70
+ test('a name with no extension gains none', () => {
71
+ expect(saveAsSuggestedName('Makefile')).toBe('Makefile copy');
72
+ });
73
+
74
+ test('a dotfile is not treated as an extension', () => {
75
+ // `.gitignore` has no stem to keep, so appending is the only sensible answer.
76
+ expect(saveAsSuggestedName('.gitignore')).toBe('.gitignore copy');
77
+ });
78
+ });
79
+
80
+ describe('isSingleSegmentName', () => {
81
+ test('accepts a plain name', () => {
82
+ expect(isSingleSegmentName('notes.ts')).toBe(true);
83
+ expect(isSingleSegmentName(' notes.ts ')).toBe(true);
84
+ });
85
+
86
+ test('refuses a separator, an empty name, and the two dot segments', () => {
87
+ expect(isSingleSegmentName('a/b.ts')).toBe(false);
88
+ expect(isSingleSegmentName('a\\b.ts')).toBe(false);
89
+ expect(isSingleSegmentName('')).toBe(false);
90
+ expect(isSingleSegmentName(' ')).toBe(false);
91
+ expect(isSingleSegmentName('.')).toBe(false);
92
+ expect(isSingleSegmentName('..')).toBe(false);
93
+ });
94
+ });
95
+
96
+ describe('saveFileAs', () => {
97
+ test('posts the directory, the name and the buffer, and answers the new path', async () => {
98
+ const forms = stub({ ok: true, body: { success: true, path: 'src/notes copy.ts' } });
99
+ const outcome = await saveFileAs({
100
+ parent: 'src',
101
+ name: 'notes copy.ts',
102
+ content: 'const a = 1;\n',
103
+ eol: 'lf',
104
+ root: '/ws',
105
+ });
106
+ expect(outcome).toEqual({ status: 'written', path: 'src/notes copy.ts' });
107
+ expect(forms[0].get('actionType')).toBe('saveAs');
108
+ expect(forms[0].get('path')).toBe('src');
109
+ expect(forms[0].get('name')).toBe('notes copy.ts');
110
+ expect(forms[0].get('content')).toBe('const a = 1;\n');
111
+ expect(forms[0].get('eol')).toBe('lf');
112
+ expect(forms[0].get('root')).toBe('/ws');
113
+ });
114
+
115
+ test('no baseMtime is sent — a new file has nothing to compare against', async () => {
116
+ const forms = stub({ ok: true, body: { success: true, path: 'a.ts' } });
117
+ await saveFileAs({ parent: '', name: 'a.ts', content: 'x', eol: 'lf' });
118
+ expect(forms[0].get('baseMtime')).toBeNull();
119
+ });
120
+
121
+ test('an empty name is refused before the request', async () => {
122
+ const forms = stub({ ok: true, body: { success: true, path: 'x' } });
123
+ expect(await saveFileAs({ parent: '', name: ' ', content: 'x', eol: 'lf' })).toEqual({
124
+ status: 'failed',
125
+ reason: 'Enter a file name.',
126
+ });
127
+ expect(forms).toHaveLength(0);
128
+ });
129
+
130
+ test('a 409 is an EXISTS refusal carrying the server sentence, not a failure', async () => {
131
+ stub({ ok: false, status: 409, body: { error: 'notes.ts already exists' } });
132
+ expect(await saveFileAs({ parent: 'src', name: 'notes.ts', content: 'x', eol: 'lf' })).toEqual({
133
+ status: 'exists',
134
+ reason: 'notes.ts already exists',
135
+ });
136
+ });
137
+
138
+ test('a 409 with no body still names the name it collided with', async () => {
139
+ stub({ ok: false, status: 409, body: null });
140
+ const outcome = await saveFileAs({ parent: '', name: 'a.ts', content: 'x', eol: 'lf' });
141
+ expect(outcome.status).toBe('exists');
142
+ expect(outcome.status === 'exists' && outcome.reason).toContain('a.ts');
143
+ });
144
+
145
+ test('any other refusal is a failure with the server reason', async () => {
146
+ stub({ ok: false, status: 403, body: { error: 'Invalid path' } });
147
+ expect(await saveFileAs({ parent: '../x', name: 'a.ts', content: 'x', eol: 'lf' })).toEqual({
148
+ status: 'failed',
149
+ reason: 'Invalid path',
150
+ });
151
+
152
+ globalThis.fetch = (async () => { throw new Error('offline'); }) as unknown as typeof fetch;
153
+ const dropped = await saveFileAs({ parent: '', name: 'a.ts', content: 'x', eol: 'lf' });
154
+ expect(dropped.status).toBe('failed');
155
+ });
156
+ });
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Save As: write the buffer to a NEW path.
8
+ *
9
+ * ## What the server does, and what it deliberately does not
10
+ *
11
+ * One `POST /api/fs/action` with `actionType: 'saveAs'`: create the destination and
12
+ * write the bytes. It does NOT delete the original, does not copy its permissions or
13
+ * mtime, and does not ask the Files panel to refresh — those are three different
14
+ * decisions and only the first is "save as".
15
+ *
16
+ * **A destination that already exists is refused, not overwritten.** The same rule the
17
+ * Files panel's `create` applies: an overwrite is what `save` is for, and a dialog whose
18
+ * "Save" silently replaced a file the user did not name is the worst possible outcome of
19
+ * a mis-click. The refusal is a `409` carrying the reason, so the dialog can stay open
20
+ * with the name still in it.
21
+ *
22
+ * **The write is a new file, so there is no `baseMtime`.** A conflict guard compares a
23
+ * buffer against the bytes it was read from; a file that did not exist a moment ago has
24
+ * nothing to compare, and sending the ORIGINAL's mtime would refuse every Save As.
25
+ *
26
+ * ## The destination is a path plus a name, and the path is validated on the server
27
+ *
28
+ * The dialog builds `parent/name`, but the server re-resolves both against its own root
29
+ * allow-list: a client-supplied absolute path is exactly the shape that would let a
30
+ * crafted request write outside the workspace.
31
+ */
32
+
33
+ /** What a Save As attempt answers. */
34
+ export type SaveAsOutcome =
35
+ /** Written; `path` is workspace-relative, which is what a tab needs. */
36
+ | { status: 'written'; path: string }
37
+ /** The destination exists. `reason` is the server's own sentence. */
38
+ | { status: 'exists'; reason: string }
39
+ /** Anything else: a bad name, a scope refusal, a dropped request. */
40
+ | { status: 'failed'; reason: string };
41
+
42
+ interface SaveAsOptions {
43
+ /** Workspace-relative directory the new file lands in. `''` means the scope root. */
44
+ parent: string;
45
+ /** One path segment — the server refuses a name carrying a separator. */
46
+ name: string;
47
+ /** The buffer, LF-only. The server rebuilds the bytes with `eol`. */
48
+ content: string;
49
+ eol: 'lf' | 'crlf';
50
+ root?: string;
51
+ repo?: string;
52
+ }
53
+
54
+ /** What `/api/fs/action` answers for a saveAs. */
55
+ interface SaveAsResponse {
56
+ success?: unknown;
57
+ path?: unknown;
58
+ error?: unknown;
59
+ }
60
+
61
+ /**
62
+ * Write `content` to `parent/name`.
63
+ *
64
+ * The name is trimmed and refused when empty HERE as well as on the server: a dialog
65
+ * that posted an empty name would get a `400` and could only report a failure, while the
66
+ * user's actual mistake ("you did not type a name") is one the caller can show inline.
67
+ */
68
+ export async function saveFileAs(options: SaveAsOptions): Promise<SaveAsOutcome> {
69
+ const name = options.name.trim();
70
+ if (!name) return { status: 'failed', reason: 'Enter a file name.' };
71
+
72
+ const formData = new FormData();
73
+ formData.append('actionType', 'saveAs');
74
+ formData.append('path', options.parent);
75
+ formData.append('name', name);
76
+ formData.append('content', options.content);
77
+ formData.append('eol', options.eol);
78
+ if (options.root) formData.append('root', options.root);
79
+ if (options.repo && options.repo !== '.') formData.append('repo', options.repo);
80
+
81
+ try {
82
+ const res = await fetch('/api/fs/action', { method: 'POST', body: formData });
83
+ const data = (await res.json().catch(() => null)) as SaveAsResponse | null;
84
+ const reason = typeof data?.error === 'string' ? data.error : null;
85
+ if (res.status === 409) {
86
+ return { status: 'exists', reason: reason ?? `${name} already exists.` };
87
+ }
88
+ if (res.ok && data?.success && typeof data.path === 'string') {
89
+ return { status: 'written', path: data.path };
90
+ }
91
+ return { status: 'failed', reason: reason ?? 'The file could not be written.' };
92
+ } catch {
93
+ return { status: 'failed', reason: 'The file could not be written.' };
94
+ }
95
+ }
96
+
97
+ /**
98
+ * The name a Save As dialog starts with.
99
+ *
100
+ * `notes.ts` → `notes copy.ts`, not `notes copy` — a destination that loses the
101
+ * extension would be saved as a file the editor no longer recognises, and the language
102
+ * the surface resolved would change under the user.
103
+ */
104
+ export function saveAsSuggestedName(fileName: string): string {
105
+ const dot = fileName.lastIndexOf('.');
106
+ if (dot <= 0) return `${fileName} copy`;
107
+ return `${fileName.slice(0, dot)} copy${fileName.slice(dot)}`;
108
+ }
109
+
110
+ /**
111
+ * Whether a typed name is one path segment, as the DIALOG checks it before posting.
112
+ *
113
+ * The server's own `isSinglePathSegment` is the authority (it also normalizes and refuses
114
+ * a NUL byte); this is the same shape minus the syscall-level cases, so the dialog can
115
+ * name the problem inline instead of posting a request it knows will be refused.
116
+ */
117
+ export function isSingleSegmentName(name: string): boolean {
118
+ const trimmed = name.trim();
119
+ if (!trimmed) return false;
120
+ if (trimmed === '.' || trimmed === '..') return false;
121
+ return !trimmed.includes('/') && !trimmed.includes('\\');
122
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The write half of the file-editing contract.
8
+ *
9
+ * Two things are pinned here. The multipart shape the server rebuilds the file
10
+ * from — including the line ending that travels as its own field, because a
11
+ * multipart body normalizes bare LF — and the CONFLICT verdict, which is the only
12
+ * answer that must not be reported as a failure: a `409` carries the disk's own
13
+ * mtime so the panel can offer Reload/Keep instead of "save failed".
14
+ */
15
+
16
+ import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
17
+ import { Window } from 'happy-dom';
18
+
19
+ import { retainKeys, saveEditorFile } from '@/client/hooks/editor/save-file';
20
+
21
+ /** Globals happy-dom provides and the save path reads. */
22
+ const DOM_GLOBALS = ['window', 'document', 'navigator', 'FormData', 'File', 'Blob'] as const;
23
+
24
+ /** The runner's own `fetch`, reached through `Bun` so a leaked stub cannot be mistaken for it. */
25
+ const nativeFetch = Bun.fetch;
26
+ /** The runner's own globals, put back once this file's DOM work is done. */
27
+ const native: Partial<Record<(typeof DOM_GLOBALS)[number], unknown>> = {};
28
+
29
+ beforeAll(() => {
30
+ const win = new Window({ url: 'http://localhost' });
31
+ const target = globalThis as unknown as Record<string, unknown>;
32
+ const source = win as unknown as Record<string, unknown>;
33
+ for (const key of DOM_GLOBALS) {
34
+ native[key] = target[key];
35
+ target[key] = source[key];
36
+ }
37
+ });
38
+
39
+ afterAll(() => {
40
+ const target = globalThis as unknown as Record<string, unknown>;
41
+ for (const key of DOM_GLOBALS) target[key] = native[key];
42
+ globalThis.fetch = nativeFetch;
43
+ });
44
+
45
+ afterEach(() => {
46
+ globalThis.fetch = nativeFetch;
47
+ });
48
+
49
+ interface Write {
50
+ url: string;
51
+ method: string;
52
+ form: FormData;
53
+ }
54
+
55
+ /** Captures the write request and answers it with `answer`. */
56
+ function stubWrite(answer: { ok: boolean; status?: number; body?: unknown; throwOnJson?: boolean }): Write[] {
57
+ const writes: Write[] = [];
58
+ globalThis.fetch = (async (input: unknown, init?: RequestInit) => {
59
+ writes.push({ url: String(input), method: init?.method ?? 'GET', form: init?.body as FormData });
60
+ return {
61
+ ok: answer.ok,
62
+ status: answer.status ?? (answer.ok ? 200 : 500),
63
+ json: async () => {
64
+ if (answer.throwOnJson) throw new Error('not json');
65
+ return answer.body ?? null;
66
+ },
67
+ };
68
+ }) as unknown as typeof fetch;
69
+ return writes;
70
+ }
71
+
72
+ describe('saveEditorFile — the request it builds', () => {
73
+ test('posts the buffer with the path and the ending as its own field', async () => {
74
+ const writes = stubWrite({ ok: true, body: { success: true } });
75
+ const outcome = await saveEditorFile({ path: 'src/a.ts', root: '/repo' }, 'const a = 1;\n', 'lf', { interactive: false });
76
+
77
+ expect(outcome).toEqual({ status: 'written' });
78
+ expect(writes.length).toBe(1);
79
+ expect(writes[0].url).toBe('/api/fs/action');
80
+ expect(writes[0].method).toBe('POST');
81
+ // A multipart body normalizes bare LF, so the ending cannot travel in it.
82
+ expect(writes[0].form.get('actionType')).toBe('save');
83
+ expect(writes[0].form.get('path')).toBe('src/a.ts');
84
+ expect(writes[0].form.get('content')).toBe('const a = 1;\n');
85
+ expect(writes[0].form.get('eol')).toBe('lf');
86
+ expect(writes[0].form.get('root')).toBe('/repo');
87
+ });
88
+
89
+ test('omits the root when the file has none and the repo when it is the cwd marker', async () => {
90
+ const writes = stubWrite({ ok: true, body: { success: true } });
91
+ await saveEditorFile({ path: 'a.ts', repo: '.' }, 'x', 'crlf', { interactive: false });
92
+ expect(writes[0].form.get('root')).toBeNull();
93
+ expect(writes[0].form.get('repo')).toBeNull();
94
+ });
95
+
96
+ test('a named repo travels with the write', async () => {
97
+ const writes = stubWrite({ ok: true, body: { success: true } });
98
+ await saveEditorFile({ path: 'a.ts', repo: 'other' }, 'x', 'crlf', { interactive: false });
99
+ expect(writes[0].form.get('repo')).toBe('other');
100
+ });
101
+
102
+ test('a file with no path is refused without touching the network', async () => {
103
+ const writes = stubWrite({ ok: true, body: { success: true } });
104
+ expect(await saveEditorFile({}, 'x', 'lf', { interactive: false })).toEqual({ status: 'failed' });
105
+ expect(writes).toEqual([]);
106
+ });
107
+ });
108
+
109
+ describe('saveEditorFile — the conflict contract', () => {
110
+ test('the base mtime travels with the write when the caller has one', async () => {
111
+ const writes = stubWrite({ ok: true, body: { success: true } });
112
+ await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false, baseMtimeMs: 1_700_000_000_123 });
113
+ expect(writes[0].form.get('baseMtime')).toBe('1700000000123');
114
+ });
115
+
116
+ test('no base mtime sends no field — a handle write and an older client must still save', async () => {
117
+ const writes = stubWrite({ ok: true, body: { success: true } });
118
+ await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false });
119
+ expect(writes[0].form.get('baseMtime')).toBeNull();
120
+
121
+ const again = stubWrite({ ok: true, body: { success: true } });
122
+ await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false, baseMtimeMs: null });
123
+ // `null` must not become the string "null", which the server would parse and
124
+ // then compare against a real mtime — failing every save.
125
+ expect(again[0].form.get('baseMtime')).toBeNull();
126
+ });
127
+
128
+ test('a 409 is a CONFLICT with the disk mtime, never a failure', async () => {
129
+ stubWrite({
130
+ ok: false,
131
+ status: 409,
132
+ body: { error: 'This file changed on disk since it was opened.', conflict: true, mtimeMs: 1_700_000_000_999 },
133
+ });
134
+ expect(await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false, baseMtimeMs: 1 })).toEqual({
135
+ status: 'conflict',
136
+ diskMtimeMs: 1_700_000_000_999,
137
+ });
138
+ });
139
+
140
+ test('a 409 whose body names no mtime still reports a conflict, with null', async () => {
141
+ stubWrite({ ok: false, status: 409, body: null });
142
+ expect(await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false, baseMtimeMs: 1 })).toEqual({
143
+ status: 'conflict',
144
+ diskMtimeMs: null,
145
+ });
146
+ });
147
+ });
148
+
149
+ describe('saveEditorFile — every other refusal is a failure', () => {
150
+ test('non-2xx, an error body, a non-JSON body, a dropped connection', async () => {
151
+ stubWrite({ ok: false, body: { success: true } });
152
+ expect(await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false })).toEqual({ status: 'failed' });
153
+
154
+ stubWrite({ ok: true, body: { success: false } });
155
+ expect(await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false })).toEqual({ status: 'failed' });
156
+
157
+ stubWrite({ ok: true, body: null });
158
+ expect(await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false })).toEqual({ status: 'failed' });
159
+
160
+ stubWrite({ ok: true, throwOnJson: true });
161
+ expect(await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false })).toEqual({ status: 'failed' });
162
+
163
+ globalThis.fetch = (async () => { throw new Error('offline'); }) as unknown as typeof fetch;
164
+ expect(await saveEditorFile({ path: 'a.ts' }, 'x', 'lf', { interactive: false })).toEqual({ status: 'failed' });
165
+ });
166
+ });
167
+
168
+ describe('retainKeys', () => {
169
+ test('keeps the same object when nothing was dropped, so children keep their identity', () => {
170
+ const record = { a: 1, b: 2 };
171
+ expect(retainKeys(record, new Set(['a', 'b']))).toBe(record);
172
+ });
173
+
174
+ test('drops the keys that left the tab set and keeps the rest', () => {
175
+ const record = { a: 1, b: 2, c: 3 };
176
+ expect(retainKeys(record, new Set(['a', 'c']))).toEqual({ a: 1, c: 3 });
177
+ expect(retainKeys(record, new Set())).toEqual({});
178
+ });
179
+ });