@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
@@ -27,6 +27,46 @@ export interface DirectoryEntry {
27
27
  ignored: boolean;
28
28
  }
29
29
 
30
+ /** How deep a collapsed chain may go before the listing stops walking. */
31
+ const MAX_CHAIN_DEPTH = 32;
32
+
33
+ /**
34
+ * The segments a single-child folder chain runs through, starting at `dir`.
35
+ *
36
+ * A row per directory level spends a row on each level of a package tree, and
37
+ * the reader scrolls through `com`, `java`, `app`, `package` to reach the four
38
+ * files inside. Every editor collapses that, so the listing does too: the row
39
+ * names the whole chain and expands into the DEEPEST directory's contents.
40
+ *
41
+ * Stops at the first directory that holds anything other than exactly one
42
+ * FOLDER — a file, two entries, or nothing at all ends the chain, so a folder
43
+ * of files never folds. The last directory's own contents are a later read, and
44
+ * probing one level past what the row displays would stat a directory nothing
45
+ * shows.
46
+ */
47
+ async function folderChain(dir: string): Promise<string[]> {
48
+ const segments = [path.basename(dir)];
49
+ let current = dir;
50
+ for (let depth = 1; depth < MAX_CHAIN_DEPTH; depth += 1) {
51
+ let entries: string[];
52
+ try {
53
+ entries = await fs.promises.readdir(current);
54
+ } catch {
55
+ return segments;
56
+ }
57
+ if (entries.length !== 1) return segments;
58
+ const child = path.join(current, entries[0]!);
59
+ try {
60
+ if (!(await Bun.file(child).stat()).isDirectory()) return segments;
61
+ } catch {
62
+ return segments; // unreadable / broken symlink — the row ends here
63
+ }
64
+ segments.push(entries[0]!);
65
+ current = child;
66
+ }
67
+ return segments;
68
+ }
69
+
30
70
  /**
31
71
  * Read one directory, folders first then files, each marked ignored or not.
32
72
  *
@@ -38,6 +78,14 @@ export interface DirectoryEntry {
38
78
  * which dims the row via `git check-ignore` instead of deleting it — and a tree
39
79
  * that is expensive to expand costs nothing until someone expands it, because
40
80
  * children are lazy.
81
+ *
82
+ * A folder holding exactly one folder and nothing else is COLLAPSED into one
83
+ * row naming the chain (`folderChain`). Its `path` is the DEEPEST directory —
84
+ * the one whose contents the row will show, and the one the panel opens,
85
+ * renames and drops on — while `name` is the whole chain relative to the
86
+ * directory being listed, so the row still reads as a path. The client's local
87
+ * edits fold by the same rule (`foldSingleChildFolders`, `lib/fs/file-tree.ts`);
88
+ * two spellings of it is how a create would draw a tree the next read undoes.
41
89
  */
42
90
  export async function listDirectoryEntries(dirPath: string, rootPath: string): Promise<DirectoryEntry[]> {
43
91
  const listed = (await fs.promises.readdir(dirPath))
@@ -53,22 +101,41 @@ export async function listDirectoryEntries(dirPath: string, rootPath: string): P
53
101
  return { child, full, rel };
54
102
  });
55
103
 
56
- const ignored = await collectIgnoredPaths(rootPath, listed.map((entry) => entry.rel));
57
-
58
104
  const mapped = await Promise.all(listed.map(async ({ child, full, rel }): Promise<DirectoryEntry | null> => {
59
105
  try {
60
106
  const st = await Bun.file(full).stat();
61
- const isIgnored = ignored.has(rel);
62
107
  if (st.isDirectory()) {
63
- return { id: rel, name: child, type: 'folder', path: rel, children: null, is_expanded: 0, ignored: isIgnored };
108
+ const chain = await folderChain(full);
109
+ if (chain.length > 1) {
110
+ const collapsedPath = `${rel}/${chain.slice(1).join('/')}`;
111
+ return {
112
+ id: collapsedPath,
113
+ name: chain.join('/'),
114
+ type: 'folder',
115
+ path: collapsedPath,
116
+ children: null,
117
+ is_expanded: 0,
118
+ ignored: false,
119
+ };
120
+ }
121
+ return { id: rel, name: child, type: 'folder', path: rel, children: null, is_expanded: 0, ignored: false };
64
122
  }
65
- return { id: rel, name: child, type: 'file', path: rel, ignored: isIgnored };
123
+ return { id: rel, name: child, type: 'file', path: rel, ignored: false };
66
124
  } catch {
67
125
  return null; // unreadable entry / broken symlink — skip
68
126
  }
69
127
  }));
70
128
 
71
129
  const result = mapped.filter((entry): entry is DirectoryEntry => entry !== null);
130
+ // One `git check-ignore` for the whole listing. A collapsed row is asked about
131
+ // its DEEPEST directory: that is the path the row names, and a rule matching
132
+ // any level of the chain matches it too (verified — `.gitignore` holding `a/`
133
+ // answers for `a`, `a/b` and `a/b/c` alike), so no level is left un-asked.
134
+ const ignored = await collectIgnoredPaths(rootPath, result.map((entry) => entry.path));
135
+ for (const entry of result) {
136
+ if (ignored.has(entry.path)) entry.ignored = true;
137
+ }
138
+
72
139
  result.sort((a, b) => {
73
140
  if (a.type === 'folder' && b.type === 'file') return -1;
74
141
  if (a.type === 'file' && b.type === 'folder') return 1;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The write-conflict rules, as a pure function plus its request parser.
8
+ *
9
+ * Three branches that all look alike in a handler, and each is a different
10
+ * decision:
11
+ *
12
+ * - no base → no expectation (a handle-backed file, an older client);
13
+ * - the file is gone → not a conflict (recreating it is `confirmSaveMissing`'s
14
+ * decision, already made by the caller);
15
+ * - the mtime moved → a conflict, carrying the CURRENT value so the client can
16
+ * offer Reload/Keep instead of reporting a failure.
17
+ */
18
+
19
+ import { describe, expect, test } from 'bun:test';
20
+
21
+ import { checkWriteConflict, parseBaseMtime } from '@/server/lib/fs/write-conflict';
22
+
23
+ /** A stat that answers `mtimeMs` for one path, or null when it is gone. */
24
+ function statOf(mtimeMs: number | null) {
25
+ return async () => (mtimeMs === null ? null : { mtimeMs });
26
+ }
27
+
28
+ describe('checkWriteConflict', () => {
29
+ test('no base means no expectation — the write proceeds', async () => {
30
+ expect(await checkWriteConflict('/a.ts', undefined, statOf(5))).toEqual({ write: true, diskMtimeMs: null });
31
+ expect(await checkWriteConflict('/a.ts', null, statOf(5))).toEqual({ write: true, diskMtimeMs: null });
32
+ });
33
+
34
+ test('a matching mtime writes', async () => {
35
+ expect(await checkWriteConflict('/a.ts', 5, statOf(5))).toEqual({ write: true, diskMtimeMs: 5 });
36
+ });
37
+
38
+ test('a moved mtime is a conflict, and the verdict carries what is there now', async () => {
39
+ expect(await checkWriteConflict('/a.ts', 5, statOf(9))).toEqual({ write: false, diskMtimeMs: 9 });
40
+ });
41
+
42
+ test('a file that is gone is not a conflict — recreating it is the caller’s decision', async () => {
43
+ expect(await checkWriteConflict('/a.ts', 5, statOf(null))).toEqual({ write: true, diskMtimeMs: null });
44
+ });
45
+
46
+ test('the comparison is exact: a one-millisecond move is a conflict', async () => {
47
+ expect(await checkWriteConflict('/a.ts', 5, statOf(6))).toEqual({ write: false, diskMtimeMs: 6 });
48
+ });
49
+ });
50
+
51
+ describe('parseBaseMtime', () => {
52
+ test('a numeric field parses', () => {
53
+ expect(parseBaseMtime('1700000000123')).toBe(1_700_000_000_123);
54
+ });
55
+
56
+ test('an absent, empty or malformed field is "no expectation", never a refusal', () => {
57
+ // Refusing a legitimate save over a parsing detail is the failure this
58
+ // tolerance exists to prevent.
59
+ expect(parseBaseMtime(null)).toBeUndefined();
60
+ expect(parseBaseMtime('')).toBeUndefined();
61
+ expect(parseBaseMtime('abc')).toBeUndefined();
62
+ expect(parseBaseMtime('NaN')).toBeUndefined();
63
+ });
64
+
65
+ test('a File entry is not a mtime', () => {
66
+ expect(parseBaseMtime(new File(['x'], 'a.txt'))).toBeUndefined();
67
+ });
68
+ });
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The save path's conflict check, as one testable function.
8
+ *
9
+ * Kept out of `action.ts` because it is the only part of that handler with a rule
10
+ * worth pinning, and because the rule has three branches that all look alike in a
11
+ * handler:
12
+ *
13
+ * - **No `baseMtime` → no expectation.** A handle-backed file has no server path
14
+ * and an older client sends nothing; both must write unconditionally, which is
15
+ * the contract this feature is layered onto rather than replaces.
16
+ * - **A missing file is not a conflict.** `confirmSaveMissing` is what allows
17
+ * recreating a deleted file, and there is no mtime to disagree with.
18
+ * - **A moved mtime IS a conflict**, and the verdict carries the CURRENT value so
19
+ * the client can offer Reload/Keep instead of reporting a failure.
20
+ *
21
+ * ## The comparison is exact, and its one blind spot is a millisecond
22
+ *
23
+ * An editor writes whole files, so a moved mtime is a real change. The blind spot is
24
+ * two writes inside the SAME millisecond: the filesystem's `mtimeMs` does not move,
25
+ * so the guard cannot tell them apart. Measured on this filesystem — two
26
+ * `writeFileSync` calls in a row leave the value identical. That is accepted rather
27
+ * than papered over with a tolerance, which would widen the hole instead of closing
28
+ * it; a content hash would close it and cost a full read per save, which is the wrong
29
+ * trade for a guard whose job is the common case (a tool call, another tab, a
30
+ * `git checkout` — all of which take far longer than a millisecond).
31
+ */
32
+
33
+ /** What the file on disk says about the buffer's base. */
34
+ export interface ConflictVerdict {
35
+ /** The save may proceed. */
36
+ write: boolean;
37
+ /** The mtime on disk right now; `null` when the file is gone. */
38
+ diskMtimeMs: number | null;
39
+ }
40
+
41
+ /**
42
+ * An mtime rounded to a whole millisecond.
43
+ *
44
+ * Load-bearing, and measured: `node:fs`' `statSync` and `Bun.file().stat()` disagree
45
+ * on the FRACTIONAL part of `mtimeMs` for the same file, so a comparison of the raw
46
+ * values answers "conflict" for a file nobody touched — a save loop the user can never
47
+ * get out of. Whole milliseconds are what both agree on, and what survives a JSON
48
+ * round trip exactly.
49
+ */
50
+ export function stableMtime(mtimeMs: number): number {
51
+ return Math.round(mtimeMs);
52
+ }
53
+
54
+ /**
55
+ * Whether a save may proceed, given the buffer's base mtime.
56
+ *
57
+ * `baseMtimeMs` is `undefined`/`null` when the caller has no expectation — that is
58
+ * the "write unconditionally" case, not an error.
59
+ */
60
+ export async function checkWriteConflict(
61
+ fullPath: string,
62
+ baseMtimeMs: number | null | undefined,
63
+ stat: (path: string) => Promise<{ mtimeMs: number } | null>,
64
+ ): Promise<ConflictVerdict> {
65
+ if (typeof baseMtimeMs !== 'number') return { write: true, diskMtimeMs: null };
66
+ const current = await stat(fullPath);
67
+ // The file is gone: recreating it is `confirmSaveMissing`'s decision, which the
68
+ // caller has already made by the time it gets here.
69
+ if (!current) return { write: true, diskMtimeMs: null };
70
+ const disk = stableMtime(current.mtimeMs);
71
+ return { write: disk === stableMtime(baseMtimeMs), diskMtimeMs: disk };
72
+ }
73
+
74
+ /**
75
+ * The `baseMtime` a save request carries, or `undefined`.
76
+ *
77
+ * A missing field and a malformed one are the same answer — "no expectation" —
78
+ * because the alternative is refusing a legitimate save over a parsing detail.
79
+ */
80
+ export function parseBaseMtime(raw: FormDataEntryValue | null): number | undefined {
81
+ if (typeof raw !== 'string' || raw === '') return undefined;
82
+ const value = Number(raw);
83
+ return Number.isFinite(value) ? value : undefined;
84
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * Save As, against the real handler.
8
+ *
9
+ * Three rules, each of which a careless implementation gets wrong: an existing destination
10
+ * is REFUSED (overwriting is what `save` is for), the name must be ONE segment (a
11
+ * separator would reach outside the directory the dialog named), and the new file is
12
+ * written with the requested line ending — the same rebuild `save` does, because a
13
+ * multipart body normalizes bare LF.
14
+ */
15
+
16
+ import { afterEach, describe, expect, test } from 'bun:test';
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+
20
+ import { action } from '@/server/routes/fs/action';
21
+
22
+ /** Probe files live in the repo root — the one directory the root allow-list always accepts. */
23
+ const ROOT = process.cwd();
24
+ const PROBE = path.join(ROOT, 'tmp-save-as-probe.ts');
25
+ const COPY = path.join(ROOT, 'tmp-save-as-probe copy.ts');
26
+
27
+ afterEach(() => {
28
+ fs.rmSync(PROBE, { force: true });
29
+ fs.rmSync(COPY, { force: true });
30
+ });
31
+
32
+ function saveAs(fields: { path?: string; name: string; content?: string; eol?: string }) {
33
+ const form = new FormData();
34
+ form.append('actionType', 'saveAs');
35
+ form.append('root', ROOT);
36
+ form.append('path', fields.path ?? '.');
37
+ form.append('name', fields.name);
38
+ form.append('content', fields.content ?? 'a\nb\n');
39
+ if (fields.eol) form.append('eol', fields.eol);
40
+ return action({ request: new Request('http://localhost/api/fs/action', { method: 'POST', body: form }) } as never);
41
+ }
42
+
43
+ describe('fs saveAs', () => {
44
+ test('writes a new file and answers its workspace-relative path', async () => {
45
+ const res = await saveAs({ name: 'tmp-save-as-probe.ts', content: 'const a = 1;\n', eol: 'lf' });
46
+ expect(res.status).toBe(200);
47
+ const body = (await res.json()) as { success?: boolean; path?: string };
48
+ expect(body.success).toBe(true);
49
+ expect(body.path).toBe('tmp-save-as-probe.ts');
50
+ expect(fs.readFileSync(PROBE, 'utf8')).toBe('const a = 1;\n');
51
+ });
52
+
53
+ test('an existing destination is a 409 and its bytes are untouched', async () => {
54
+ fs.writeFileSync(PROBE, 'original\n');
55
+ const res = await saveAs({ name: 'tmp-save-as-probe.ts', content: 'replacement\n', eol: 'lf' });
56
+ expect(res.status).toBe(409);
57
+ expect(((await res.json()) as { error?: string }).error).toContain('already exists');
58
+ // The refusal is the point: an overwrite is what `save` is for.
59
+ expect(fs.readFileSync(PROBE, 'utf8')).toBe('original\n');
60
+ });
61
+
62
+ test('a name carrying a separator is refused before anything is written', async () => {
63
+ for (const name of ['nested/probe.ts', '..', '.', '']) {
64
+ const res = await saveAs({ name, content: 'x' });
65
+ expect(res.status).toBe(400);
66
+ }
67
+ expect(fs.existsSync(PROBE)).toBe(false);
68
+ });
69
+
70
+ test('the requested line ending is what lands on disk', async () => {
71
+ await saveAs({ name: 'tmp-save-as-probe.ts', content: 'a\nb\n', eol: 'crlf' });
72
+ expect([...fs.readFileSync(PROBE)]).toEqual([0x61, 0x0d, 0x0a, 0x62, 0x0d, 0x0a]);
73
+ });
74
+
75
+ test('a subdirectory destination is created when it does not exist', async () => {
76
+ const res = await saveAs({ name: 'tmp-save-as-probe.ts', path: 'tmp-save-as-dir', content: 'x', eol: 'lf' });
77
+ expect(res.status).toBe(200);
78
+ const written = path.join(ROOT, 'tmp-save-as-dir', 'tmp-save-as-probe.ts');
79
+ expect(fs.readFileSync(written, 'utf8')).toBe('x');
80
+ fs.rmSync(path.join(ROOT, 'tmp-save-as-dir'), { recursive: true, force: true });
81
+ });
82
+ });
@@ -62,3 +62,85 @@ describe('fs save line endings', () => {
62
62
  expect([...bytes]).toEqual([0x61, 0x0d, 0x0a, 0x62, 0x0d, 0x0a]);
63
63
  });
64
64
  });
65
+
66
+ /**
67
+ * The conflict contract, against the real handler.
68
+ *
69
+ * A save that names the mtime it was built from must be REFUSED when the disk has
70
+ * moved — that is the whole point, and it is the branch a unit test on
71
+ * `checkWriteConflict` cannot prove because it never reaches the route. The three
72
+ * "must still write" branches matter just as much: a guard that refuses a legitimate
73
+ * save is worse than no guard.
74
+ */
75
+ describe('fs save conflict', () => {
76
+ const CONFLICT = path.join(process.cwd(), 'tmp-conflict-probe.ts');
77
+
78
+ afterEach(() => {
79
+ fs.rmSync(CONFLICT, { force: true });
80
+ });
81
+
82
+ async function saveWith(baseMtime: number | undefined, content: string) {
83
+ const form = new FormData();
84
+ form.append('actionType', 'save');
85
+ form.append('root', process.cwd());
86
+ form.append('path', 'tmp-conflict-probe.ts');
87
+ form.append('content', content);
88
+ form.append('eol', 'lf');
89
+ if (baseMtime !== undefined) form.append('baseMtime', String(baseMtime));
90
+ return action({ request: new Request('http://localhost/api/fs/action', { method: 'POST', body: form }) } as never);
91
+ }
92
+
93
+ test('a matching base writes and answers the mtime it wrote', async () => {
94
+ fs.writeFileSync(CONFLICT, 'first\n');
95
+ const base = Math.round(fs.statSync(CONFLICT).mtimeMs);
96
+ const res = await saveWith(base, 'mine\n');
97
+ expect(res.status).toBe(200);
98
+ const body = (await res.json()) as { success?: boolean; mtimeMs?: number };
99
+ expect(body.success).toBe(true);
100
+ expect(typeof body.mtimeMs).toBe('number');
101
+ expect(fs.readFileSync(CONFLICT, 'utf8')).toBe('mine\n');
102
+ });
103
+
104
+ test('a base the disk moved past is a 409, and NOTHING is written', async () => {
105
+ fs.writeFileSync(CONFLICT, 'first\n');
106
+ const base = Math.round(fs.statSync(CONFLICT).mtimeMs);
107
+ // Another writer — an agent, another tab — moves the file. The mtime is set
108
+ // explicitly rather than by writing again: two writes inside one millisecond
109
+ // leave `mtimeMs` identical, which is the documented limit of this guard (see
110
+ // `write-conflict.ts`) rather than something a test should paper over.
111
+ fs.writeFileSync(CONFLICT, 'theirs\n');
112
+ const moved = new Date(base + 5_000);
113
+ fs.utimesSync(CONFLICT, moved, moved);
114
+ const res = await saveWith(base, 'mine again\n');
115
+ expect(res.status).toBe(409);
116
+ const body = (await res.json()) as { conflict?: boolean; mtimeMs?: number };
117
+ expect(body.conflict).toBe(true);
118
+ expect(typeof body.mtimeMs).toBe('number');
119
+ // The refusal is the point: the other writer's bytes survive.
120
+ expect(fs.readFileSync(CONFLICT, 'utf8')).toBe('theirs\n');
121
+ });
122
+
123
+ test('no base writes unconditionally — a handle-backed file and an older client', async () => {
124
+ fs.writeFileSync(CONFLICT, 'first\n');
125
+ expect((await saveWith(undefined, 'no base\n')).status).toBe(200);
126
+ expect(fs.readFileSync(CONFLICT, 'utf8')).toBe('no base\n');
127
+ });
128
+
129
+ test('a base the disk agrees with after adoption writes — the "Keep mine" retry', async () => {
130
+ fs.writeFileSync(CONFLICT, 'first\n');
131
+ fs.writeFileSync(CONFLICT, 'theirs\n');
132
+ const moved = new Date(Date.now() + 5_000);
133
+ fs.utimesSync(CONFLICT, moved, moved);
134
+ const adopted = Math.round(fs.statSync(CONFLICT).mtimeMs);
135
+ expect((await saveWith(adopted, 'adopted\n')).status).toBe(200);
136
+ expect(fs.readFileSync(CONFLICT, 'utf8')).toBe('adopted\n');
137
+ });
138
+
139
+ test('a base with the file DELETED recreates it — recreating is the user’s decision', async () => {
140
+ fs.writeFileSync(CONFLICT, 'first\n');
141
+ const base = Math.round(fs.statSync(CONFLICT).mtimeMs);
142
+ fs.rmSync(CONFLICT, { force: true });
143
+ expect((await saveWith(base, 'recreated\n')).status).toBe(200);
144
+ expect(fs.readFileSync(CONFLICT, 'utf8')).toBe('recreated\n');
145
+ });
146
+ });
@@ -8,6 +8,8 @@ import { runShell } from '@/server/lib/fs/shell';
8
8
  import { revealInFileManager } from '@/server/lib/fs/reveal';
9
9
  import { duplicateEntry, nextDuplicateName, pasteEntry, toRelPath } from '@/server/lib/fs/transfer';
10
10
  import { normalizeRelativePath } from '@/server/lib/fs/relative-path';
11
+ import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
12
+ import { checkWriteConflict, parseBaseMtime, stableMtime } from '@/server/lib/fs/write-conflict';
11
13
  import { transferRefusal } from '@/shared/lib/fs/clipboard';
12
14
  import { toDiskText } from '@/shared/lib/code/line-endings';
13
15
 
@@ -101,9 +103,60 @@ export async function action({ request }: ActionFunctionArgs) {
101
103
  // CRLF and show up as a full-file diff. `eol` is the ending the client
102
104
  // read the file with; without it the payload is written untouched.
103
105
  const content = eol === 'crlf' || eol === 'lf' ? toDiskText(raw, eol) : raw;
106
+ // The buffer names the mtime it was read from. A file that moved since then
107
+ // is a CONFLICT, not a failure: the verdict carries the current value so the
108
+ // panel can offer Reload/Keep. A save with no base — a handle-backed file, an
109
+ // older client — writes unconditionally, which is the pre-existing contract.
110
+ const verdict = await checkWriteConflict(
111
+ fullPath,
112
+ parseBaseMtime(formData.get('baseMtime')),
113
+ async (target) => {
114
+ const stat = await Bun.file(target).stat().catch(() => null);
115
+ return stat && !stat.isDirectory() ? { mtimeMs: stat.mtimeMs } : null;
116
+ },
117
+ );
118
+ if (!verdict.write) {
119
+ return json(
120
+ {
121
+ error: 'This file changed on disk since it was opened.',
122
+ conflict: true,
123
+ mtimeMs: verdict.diskMtimeMs,
124
+ },
125
+ { status: 409 },
126
+ );
127
+ }
104
128
  await fs.promises.mkdir(path.dirname(fullPath), { recursive: true });
105
129
  await Bun.write(fullPath, content);
106
- return json({ success: true });
130
+ const written = await Bun.file(fullPath).stat().catch(() => null);
131
+ return json({ success: true, mtimeMs: written ? stableMtime(written.mtimeMs) : null });
132
+ } else if (actionType === 'saveAs') {
133
+ // Write the buffer to a NEW path. The destination is `path` (a directory) plus
134
+ // `name` (ONE segment), both resolved against this route's own scope — a
135
+ // client-supplied absolute path is exactly the shape that would write outside the
136
+ // workspace, so it is never trusted.
137
+ //
138
+ // No `baseMtime`: a file that did not exist a moment ago has nothing to compare
139
+ // against, and sending the ORIGINAL's mtime would refuse every Save As.
140
+ const directory = (formData.get('path') as string) ?? '';
141
+ const name = ((formData.get('name') as string) ?? '').trim();
142
+ if (!isSinglePathSegment(name)) {
143
+ return json({ error: 'Enter a file name without a path separator' }, { status: 400 });
144
+ }
145
+ const destination = resolveWithinRoot(scopedRoot, path.join(directory || '.', name));
146
+ if (!destination) return json({ error: 'Invalid path' }, { status: 403 });
147
+ // An existing destination is REFUSED, not overwritten: overwriting is what `save`
148
+ // is for, and a dialog that silently replaced a file the user did not name is the
149
+ // worst outcome of a mis-click. The same rule `create` applies.
150
+ if ((await Bun.file(destination).stat().catch(() => null)) !== null) {
151
+ return json({ error: `${name} already exists` }, { status: 409 });
152
+ }
153
+ const raw = (formData.get('content') as string) ?? '';
154
+ const eol = formData.get('eol');
155
+ const content = eol === 'crlf' || eol === 'lf' ? toDiskText(raw, eol) : raw;
156
+ await fs.promises.mkdir(path.dirname(destination), { recursive: true });
157
+ await Bun.write(destination, content);
158
+ // Relative to the LISTED root, which is the identity a tab needs.
159
+ return json({ success: true, path: toRelPath(scopedRoot, destination) });
107
160
  } else if (actionType === 'create') {
108
161
  // The Files panel's "New file"/"New folder": an empty entry beside the
109
162
  // folder that was right-clicked. The NAME may carry segments
@@ -22,6 +22,7 @@
22
22
  import { json, type LoaderFunctionArgs } from '@/server/lib/remix-compat';
23
23
  import { isMockMode } from '@/server/mock.server';
24
24
  import { getDefaultFsRoot, resolveRoot, resolveWithinRoot } from '@/server/lib/fs/root';
25
+ import { stableMtime } from '@/server/lib/fs/write-conflict';
25
26
 
26
27
  export async function fileExists({ request }: LoaderFunctionArgs) {
27
28
  const url = new URL(request.url);
@@ -48,6 +49,15 @@ export async function fileExists({ request }: LoaderFunctionArgs) {
48
49
  // about a folder only by accident. The question here is whether the FILE the
49
50
  // tab names is still there, so a folder standing in its place is a "no" —
50
51
  // the file was deleted and something else took its path.
52
+ //
53
+ // The mtime travels beside the answer because the editor's change detection asks
54
+ // this exact question — "does the file the buffer came from still look like the
55
+ // one it read?" — and a second route for one `stat` would be a second scope
56
+ // check to keep in step. `null` when there is no file to report on.
51
57
  const stat = await Bun.file(fullPath).stat().catch(() => null);
52
- return json({ exists: stat !== null && !stat.isDirectory() });
58
+ const exists = stat !== null && !stat.isDirectory();
59
+ // Rounded to a whole millisecond: `node:fs` and `Bun.file()` disagree on the
60
+ // fractional part, and the editor compares this value against the one the read
61
+ // route reported. See `stableMtime`.
62
+ return json({ exists, mtimeMs: exists ? stableMtime(stat.mtimeMs) : null });
53
63
  }
@@ -6,6 +6,7 @@
6
6
  import { json, type LoaderFunctionArgs } from '@/server/lib/remix-compat';
7
7
  import { listDirectoryEntries } from '@/server/lib/fs/listing';
8
8
  import { errorResponse } from '@/server/lib/route-adapter';
9
+ import { stableMtime } from '@/server/lib/fs/write-conflict';
9
10
  import { homedir } from 'os';
10
11
  import { dirname, isAbsolute, join, resolve } from 'path';
11
12
  import fs from 'fs';
@@ -278,7 +279,11 @@ export async function readFile({ request }: LoaderFunctionArgs) {
278
279
  }
279
280
 
280
281
  const content = await file.text();
281
- return json({ content });
282
+ // The mtime travels with the bytes: the save path sends it back as
283
+ // `baseMtime`, and the server refuses a write whose base is no longer what is
284
+ // on disk. A buffer with no base (a handle-backed file, an older client) still
285
+ // writes unconditionally — see `save-file.ts`.
286
+ return json({ content, mtimeMs: stableMtime(stat.mtimeMs) });
282
287
  } catch (error) {
283
288
  return errorResponse(error);
284
289
  }
@@ -22,7 +22,7 @@ import {
22
22
  import type { FindOptions } from '@/shared/lib/code/editor/find-scan';
23
23
  import { findMatches } from '@/shared/lib/code/editor/find-scan';
24
24
 
25
- const PLAIN: FindOptions = { matchCase: false, wholeWord: false, isRegex: false };
25
+ const PLAIN: FindOptions = { matchCase: false, wholeWord: false, isRegex: false, inSelection: false };
26
26
 
27
27
  describe('replaceMatch', () => {
28
28
  test('literal replacement inserts the field verbatim, dollar signs included', () => {
@@ -26,7 +26,7 @@ import {
26
26
  type FindOptions,
27
27
  } from '@/shared/lib/code/editor/find-scan';
28
28
 
29
- const PLAIN: FindOptions = { matchCase: false, wholeWord: false, isRegex: false };
29
+ const PLAIN: FindOptions = { matchCase: false, wholeWord: false, isRegex: false, inSelection: false };
30
30
 
31
31
  describe('findMatches', () => {
32
32
  test('finds literal occurrences in document order, ignoring case by default', () => {
@@ -36,6 +36,15 @@ export interface FindOptions {
36
36
  matchCase: boolean;
37
37
  wholeWord: boolean;
38
38
  isRegex: boolean;
39
+ /**
40
+ * Restrict the scan to `[inSelection.start, inSelection.end)`.
41
+ *
42
+ * `false` (the default) scans the whole document. The RANGE is carried beside the
43
+ * flag rather than folded into it, because the widget has to show "in selection" as a
44
+ * toggle whose meaning depends on where the selection was when it was armed — and
45
+ * because a range that the user then moves must not silently change what is searched.
46
+ */
47
+ inSelection: boolean;
39
48
  }
40
49
 
41
50
  /** Half-open `[start, end)` offset range in the document. */
@@ -60,6 +69,7 @@ export const DEFAULT_FIND_OPTIONS: FindOptions = {
60
69
  matchCase: false,
61
70
  wholeWord: false,
62
71
  isRegex: false,
72
+ inSelection: false,
63
73
  };
64
74
 
65
75
  /**
@@ -130,7 +140,12 @@ function asText(source: string): Text {
130
140
  * `\s`, `\W`, `\D`, `\b`-free character classes or `[^`. Both return document
131
141
  * offsets, so the caller never learns which one ran.
132
142
  */
133
- export function findMatches(text: string, query: string, options: FindOptions): FindResult {
143
+ export function findMatches(
144
+ text: string,
145
+ query: string,
146
+ options: FindOptions,
147
+ range?: { start: number; end: number } | null,
148
+ ): FindResult {
134
149
  if (!query) return { matches: [], truncated: false, invalid: false };
135
150
  const pattern = buildFindRegex(query, options);
136
151
  if (!pattern) return { matches: [], truncated: false, invalid: true };
@@ -145,9 +160,15 @@ export function findMatches(text: string, query: string, options: FindOptions):
145
160
  return { matches: [], truncated: false, invalid: true };
146
161
  }
147
162
 
163
+ // The range is applied HERE rather than by slicing the text: the match offsets must
164
+ // stay document offsets, or every caller that selects or replaces by them (the bar,
165
+ // the marks, the write path) would be working in a coordinate system of their own.
166
+ const bounds = options.inSelection && range ? range : null;
167
+
148
168
  while (matches.length < MAX_FIND_MATCHES && !cursor.next().done) {
149
169
  const { from, to } = cursor.value;
150
170
  if (from === to) continue;
171
+ if (bounds && (from < bounds.start || to > bounds.end)) continue;
151
172
  matches.push({ start: from, end: to });
152
173
  }
153
174