@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,152 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The editor panel's keyboard surface, as one hook.
8
+ *
9
+ * Three things live here because they are one decision: what the panel CONSUMES
10
+ * before the document sees it. The panel is the scope, not the window — another
11
+ * panel's text field keeps its own ⌘F and the composer is untouched — and only the
12
+ * commands the PANEL owns are consumed here, because the editor's own keymap runs
13
+ * inside the document where it has the buffer and the caret in hand.
14
+ *
15
+ * ## Capture is the mechanism
16
+ *
17
+ * The contenteditable has CodeMirror's handlers (the generated keymap, and
18
+ * `defaultKeymap` behind it) and would see these chords first otherwise. Capture
19
+ * on the panel's own root is what puts them in front, and it is also why the
20
+ * panel is the scope: the listener is on a container, not on `window`.
21
+ *
22
+ * ## ⌘S is the one chord handled on the WINDOW
23
+ *
24
+ * It has to work while focus is anywhere in the panel — including a field the
25
+ * panel does not own — and a browser's own Save dialog is the alternative. It is
26
+ * registered once and reads the save callback through a ref, so a re-render does
27
+ * not detach and reattach it.
28
+ */
29
+
30
+ import { useCallback, useEffect, useRef } from 'preact/hooks';
31
+ import type { TargetedKeyboardEvent } from 'preact';
32
+
33
+ import { EDITOR_KEY_BINDINGS, isFindBarCommand, type EditorCommand } from '@/shared/lib/code/editor/keymap';
34
+ import { resolveBinding } from '@/shared/lib/ui/key-binding';
35
+
36
+ interface UseEditorPanelKeysOptions {
37
+ find: {
38
+ open: boolean;
39
+ close: () => void;
40
+ runCommand: (command: EditorCommand) => void;
41
+ };
42
+ paletteOpen: boolean;
43
+ setPaletteOpen: (open: boolean) => void;
44
+ runCommand: (command: EditorCommand) => void;
45
+ saveNow: () => void;
46
+ /** Open the file picker. `⌘P` is about the WORKSPACE, not the buffer. */
47
+ openQuickOpen: () => void;
48
+ /** Restore the most recently closed tab; returns false with an empty stack. */
49
+ reopenClosed?: () => boolean;
50
+ }
51
+
52
+ export interface EditorPanelKeys {
53
+ /** Spread on the panel's root: the capture-phase dispatch. */
54
+ onKeyDownCapture: (event: TargetedKeyboardEvent<HTMLDivElement>) => void;
55
+ }
56
+
57
+ export function useEditorPanelKeys({
58
+ find,
59
+ paletteOpen,
60
+ setPaletteOpen,
61
+ runCommand,
62
+ saveNow,
63
+ openQuickOpen,
64
+ reopenClosed,
65
+ }: UseEditorPanelKeysOptions): EditorPanelKeys {
66
+ // The handler is rebuilt every render (it reads live find state), so the ref is
67
+ // what keeps the window listener attached once.
68
+ const findRef = useRef(find);
69
+ findRef.current = find;
70
+ const paletteRef = useRef({ paletteOpen, setPaletteOpen });
71
+ paletteRef.current = { paletteOpen, setPaletteOpen };
72
+ const runRef = useRef(runCommand);
73
+ runRef.current = runCommand;
74
+
75
+ const saveRef = useRef(saveNow);
76
+ saveRef.current = saveNow;
77
+ const quickOpenRef = useRef(openQuickOpen);
78
+ quickOpenRef.current = openQuickOpen;
79
+ const reopenRef = useRef(reopenClosed);
80
+ reopenRef.current = reopenClosed;
81
+
82
+ useEffect(() => {
83
+ const handler = (event: globalThis.KeyboardEvent) => {
84
+ if (!(event.ctrlKey || event.metaKey) || event.key !== 's') return;
85
+ // The browser's Save dialog is never what the user meant.
86
+ event.preventDefault();
87
+ saveRef.current();
88
+ };
89
+ window.addEventListener('keydown', handler);
90
+ return () => window.removeEventListener('keydown', handler);
91
+ }, []);
92
+
93
+ const onKeyDownCapture = useCallback((event: TargetedKeyboardEvent<HTMLDivElement>) => {
94
+ const current = findRef.current;
95
+ const palette = paletteRef.current;
96
+
97
+ if (event.key === 'Escape') {
98
+ if (palette.paletteOpen) {
99
+ event.preventDefault();
100
+ event.stopPropagation();
101
+ palette.setPaletteOpen(false);
102
+ return;
103
+ }
104
+ if (!current.open) return;
105
+ event.preventDefault();
106
+ event.stopPropagation();
107
+ current.close();
108
+ return;
109
+ }
110
+
111
+ // ⌘⇧T restores the last closed tab. Checked BEFORE ⌘⇧P for the same reason: a
112
+ // chord pair that differs only by its letter must not both match.
113
+ if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.code === 'KeyT') {
114
+ // Only consumed when there IS something to restore, so an empty stack leaves the
115
+ // key to the browser rather than swallowing it.
116
+ if (reopenRef.current?.()) {
117
+ event.preventDefault();
118
+ event.stopPropagation();
119
+ }
120
+ return;
121
+ }
122
+
123
+ // ⌘P opens the file picker, and it is checked BEFORE ⌘⇧P: the shift test below
124
+ // excludes it, so the two cannot both fire, but the reader should see the pair
125
+ // together.
126
+ if ((event.metaKey || event.ctrlKey) && !event.shiftKey && event.code === 'KeyP') {
127
+ event.preventDefault();
128
+ event.stopPropagation();
129
+ quickOpenRef.current();
130
+ return;
131
+ }
132
+
133
+ // ⌘⇧P opens the palette — the one chord that is not an editor command.
134
+ if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.code === 'KeyP') {
135
+ event.preventDefault();
136
+ event.stopPropagation();
137
+ palette.setPaletteOpen(true);
138
+ return;
139
+ }
140
+
141
+ // While the bar is open, an unmodified key in one of ITS fields belongs to the
142
+ // field — but F3 and the ⌘-chords below still dispatch, so stepping to the
143
+ // next match from inside the find field works.
144
+ const command = resolveBinding(EDITOR_KEY_BINDINGS, event);
145
+ if (!command || !isFindBarCommand(command)) return;
146
+ event.preventDefault();
147
+ event.stopPropagation();
148
+ runRef.current(command);
149
+ }, []);
150
+
151
+ return { onKeyDownCapture };
152
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The editor panel's tab-level bookkeeping, as one hook.
8
+ *
9
+ * Two effects that both answer "what does the TAB STRIP need to know", and both are
10
+ * easy to get wrong on their own:
11
+ *
12
+ * - **Which tabs hold unsaved edits.** The editor is the only component that caches
13
+ * the buffers, so it is the only one that can answer; the strip draws the dot, the
14
+ * close guard asks before closing, and the unload prompt arms itself. Only FILE
15
+ * tabs are published — a diff tab and an attachment chip have no file behind them,
16
+ * so "unsaved" means nothing there.
17
+ * - **The default preview mode for a rendered file.** A markdown page, a CSV grid and
18
+ * an SVG open in their RENDERED form, because that is what the user opened them to
19
+ * read. The default is seeded only when nothing was stored, so a user who switched
20
+ * to source keeps that choice.
21
+ */
22
+
23
+ import { useEffect } from 'preact/hooks';
24
+
25
+ import { RENDERED_VIEWERS, viewerKindFor } from '@/shared/lib/fs/document-kind';
26
+ import { getSessionValue } from '@/shared/lib/workspace/session-state/store';
27
+ import { setDirtyTabs } from '@/client/lib/editor-dirty-tabs';
28
+ import type { OpenedFile } from '@/shared/types/fs';
29
+
30
+ interface UseEditorTabStateOptions {
31
+ openedFiles: OpenedFile[];
32
+ /** Buffer keys holding edits that are not on disk (from `useFileEditor`). */
33
+ dirtyKeys: ReadonlySet<string>;
34
+ activeFile: OpenedFile | undefined;
35
+ /** The session store has loaded, so a stored choice can be read. */
36
+ previewReady: boolean;
37
+ setPreviewMode: (update: (previous: Record<string | number, boolean>) => Record<string | number, boolean>) => void;
38
+ sessionId: string | null;
39
+ }
40
+
41
+ export function useEditorTabState({
42
+ openedFiles,
43
+ dirtyKeys,
44
+ activeFile,
45
+ previewReady,
46
+ setPreviewMode,
47
+ sessionId,
48
+ }: UseEditorTabStateOptions): void {
49
+ useEffect(() => {
50
+ const ids = new Set(
51
+ openedFiles.filter((file) => !file.isDiff && file.content === undefined).map((file) => file.id),
52
+ );
53
+ setDirtyTabs([...dirtyKeys].filter((key) => ids.has(key)));
54
+ }, [dirtyKeys, openedFiles]);
55
+
56
+ useEffect(() => {
57
+ if (!previewReady) return;
58
+ const id = activeFile?.id;
59
+ if (!activeFile || id === undefined || id === null) return;
60
+ // Only a file with a RENDERED view has a default worth setting; a code file has
61
+ // no preview to open.
62
+ if (!RENDERED_VIEWERS[viewerKindFor(activeFile.name)]) return;
63
+ const stored = getSessionValue<Record<string | number, boolean>>(sessionId, 'editor.previewMode');
64
+ if (stored && stored[id] !== undefined) return;
65
+ setPreviewMode((previous) => (previous[id] === undefined ? { ...previous, [id]: true } : previous));
66
+ // `previewMode` is deliberately absent: the effect seeds a MISSING entry, and
67
+ // re-running it because the map moved would re-seed the file the user just
68
+ // switched to source.
69
+ // eslint-disable-next-line react-hooks/exhaustive-deps
70
+ }, [previewReady, activeFile]);
71
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The external-change strip AND its "Keep mine" answer, as one call.
8
+ *
9
+ * They are one concern: the strip exists so the user can choose between two answers, and
10
+ * the answer needs the mtime the probe found. Wiring them separately in the panel meant the
11
+ * answer read `externalChange?.mtimeMs` from a value the same component held — a second
12
+ * place for the two to disagree about which change is being answered.
13
+ *
14
+ * "Keep mine" ADOPTS the disk mtime and writes nothing: the buffer stays dirty and the
15
+ * autosave owns the write. That is the difference between this and the CONFLICT strip's
16
+ * Keep mine, which writes immediately — a conflict is a save the server refused, so the
17
+ * user's answer is "try again with the new base".
18
+ */
19
+
20
+ import type { DiskChange } from '@/client/hooks/editor/use-external-change';
21
+ import { useExternalChange } from '@/client/hooks/editor/use-external-change';
22
+
23
+ interface ExternalFile {
24
+ path?: string;
25
+ root?: string;
26
+ repo?: string;
27
+ isDiff?: boolean;
28
+ }
29
+
30
+ interface UseExternalChangeNoticeOptions {
31
+ file: ExternalFile | undefined;
32
+ /** The mtime the buffer was read at. */
33
+ baseMtimeMs: number | null;
34
+ dirty: boolean;
35
+ /** Bumped whenever something may have written the tree. */
36
+ revision: number;
37
+ /** Take the disk mtime as this buffer's base, writing nothing. */
38
+ adoptDiskMtime: (diskMtimeMs: number) => void;
39
+ }
40
+
41
+ export interface ExternalChangeNotice {
42
+ externalChange: DiskChange | null;
43
+ /** Adopt the disk mtime so the next save is not refused. */
44
+ keepMine: () => void;
45
+ }
46
+
47
+ export function useExternalChangeNotice({
48
+ file,
49
+ baseMtimeMs,
50
+ dirty,
51
+ revision,
52
+ adoptDiskMtime,
53
+ }: UseExternalChangeNoticeOptions): ExternalChangeNotice {
54
+ const externalChange = useExternalChange({
55
+ // A diff tab's path names a CHANGE, not a document: there is no file behind it to
56
+ // compare an mtime against.
57
+ path: file && !file.isDiff ? file.path ?? null : null,
58
+ root: file?.root,
59
+ repo: file?.repo,
60
+ baseMtimeMs,
61
+ dirty,
62
+ revision,
63
+ });
64
+
65
+ const keepMine = () => {
66
+ const mtime = externalChange?.mtimeMs;
67
+ if (mtime != null) adoptDiskMtime(mtime);
68
+ };
69
+
70
+ return { externalChange, keepMine };
71
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The external-change probe.
8
+ *
9
+ * Three rules, and each is a silent failure if broken:
10
+ *
11
+ * - a REFUSED probe is not a verdict — offering a Reload over a dropped request is
12
+ * worse than saying nothing;
13
+ * - a file that is GONE is the tab strip's strike-through, not a change strip;
14
+ * - a MATCHING mtime is no change at all, which is what keeps the strip off a file
15
+ * nobody touched.
16
+ */
17
+
18
+ import { afterEach, describe, expect, test } from 'bun:test';
19
+
20
+ import { probeExternalChange } from '@/client/hooks/editor/use-external-change';
21
+
22
+ const nativeFetch = Bun.fetch;
23
+
24
+ afterEach(() => {
25
+ globalThis.fetch = nativeFetch;
26
+ });
27
+
28
+ /** Answer the probe with `body`, or refuse it. */
29
+ function stub(body: unknown, ok = true): void {
30
+ globalThis.fetch = (async () => ({
31
+ ok,
32
+ json: async () => body,
33
+ })) as unknown as typeof fetch;
34
+ }
35
+
36
+ describe('probeExternalChange', () => {
37
+ test('a matching mtime is no change', async () => {
38
+ stub({ exists: true, mtimeMs: 100 });
39
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({ kind: 'unchanged' });
40
+ });
41
+
42
+ test('a moved mtime is a change, carrying both sides', async () => {
43
+ stub({ exists: true, mtimeMs: 200 });
44
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({
45
+ kind: 'changed',
46
+ mtimeMs: 200,
47
+ baseMtimeMs: 100,
48
+ });
49
+ });
50
+
51
+ test('a missing file is not a change — the tab strip owns that fact', async () => {
52
+ stub({ exists: false, mtimeMs: null });
53
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({ kind: 'gone' });
54
+ });
55
+
56
+ test('a refused probe is NO VERDICT, never a change', async () => {
57
+ stub({}, false);
58
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({ kind: 'unknown' });
59
+ });
60
+
61
+ test('a malformed body is no verdict', async () => {
62
+ stub({ exists: 'yes' });
63
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({ kind: 'unknown' });
64
+ stub(null);
65
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({ kind: 'unknown' });
66
+ });
67
+
68
+ test('a dropped connection is no verdict', async () => {
69
+ globalThis.fetch = (async () => { throw new Error('offline'); }) as unknown as typeof fetch;
70
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({ kind: 'unknown' });
71
+ });
72
+
73
+ test('a file that exists with no mtime to report is no verdict', async () => {
74
+ stub({ exists: true });
75
+ expect(await probeExternalChange('/a.ts', null, null, 100)).toEqual({ kind: 'unknown' });
76
+ });
77
+
78
+ test('the scope travels with the probe, so a nested repo is read from its own tree', async () => {
79
+ const seen: string[] = [];
80
+ globalThis.fetch = (async (input: unknown) => {
81
+ seen.push(String(input));
82
+ return { ok: true, json: async () => ({ exists: true, mtimeMs: 100 }) };
83
+ }) as unknown as typeof fetch;
84
+ await probeExternalChange('a.ts', '/repo', 'nested', 100);
85
+ expect(seen[0]).toContain('root=%2Frepo');
86
+ expect(seen[0]).toContain('repo=nested');
87
+ });
88
+ });
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * "This file changed on disk while you were editing it."
8
+ *
9
+ * The editor never noticed: it subscribed to no realtime topic, and the only re-read
10
+ * was a manual Refresh. With the 800 ms autosave that is a data-loss path — an agent
11
+ * (or another tab, or `git checkout`) writes a file the user has open, and the next
12
+ * keystroke writes the stale buffer over it.
13
+ *
14
+ * ## Why the `fs:` topic's own revision and not a file watcher
15
+ *
16
+ * `workspace-dirty` already republishes every watched `fs:`/`git:` topic after each
17
+ * tool call and each run end, and the panel's `refreshKey` carries the same signal
18
+ * for its own writes. A server-side `fs.watch` per open file would be a new
19
+ * process-wide resource for one strip.
20
+ *
21
+ * ## The probe asks ONE question, and a refusal is not a verdict
22
+ *
23
+ * The topic payload is a directory listing; what this needs is one file's mtime.
24
+ * `/api/fs/exists` already answers the scope question with the same allow-list and
25
+ * the same containment, so it grew an `mtimeMs`. A refused or dropped probe says
26
+ * nothing about the file, and reporting it as "changed" would offer a Reload over a
27
+ * perfectly current buffer — so only a real answer counts, and `unknown` is its own
28
+ * outcome rather than a silent "fine".
29
+ *
30
+ * ## Only a DIRTY buffer asks
31
+ *
32
+ * A clean buffer has nothing to lose: re-reading it silently is what the read effect
33
+ * already does on a refresh. The strip exists for the case where the user's edits and
34
+ * the disk's bytes disagree, which is precisely `isDirty`.
35
+ */
36
+
37
+ import { useEffect, useRef, useState } from 'preact/hooks';
38
+
39
+ /** What a probe learned. */
40
+ export type ExternalChangeVerdict =
41
+ /** The disk still holds the bytes this buffer was built from. */
42
+ | { kind: 'unchanged' }
43
+ /** The disk moved: both sides, so the strip can say when. */
44
+ | { kind: 'changed'; mtimeMs: number; baseMtimeMs: number }
45
+ /** The file is gone; the tab strip's strike-through owns that fact. */
46
+ | { kind: 'gone' }
47
+ /** No answer — a refused request, a malformed body, a file with no mtime. */
48
+ | { kind: 'unknown' };
49
+
50
+ /** The change a buffer has to be told about, or null. */
51
+ export interface DiskChange {
52
+ mtimeMs: number;
53
+ baseMtimeMs: number;
54
+ }
55
+
56
+ /**
57
+ * Ask the server whether `path` still has the mtime the buffer was built from.
58
+ *
59
+ * Exported because the three "no verdict" branches are the whole rule, and they are
60
+ * only testable without a mounted component.
61
+ */
62
+ export async function probeExternalChange(
63
+ path: string,
64
+ root: string | null,
65
+ repo: string | null,
66
+ baseMtimeMs: number,
67
+ ): Promise<ExternalChangeVerdict> {
68
+ const params = new URLSearchParams({ path });
69
+ if (root) params.set('root', root);
70
+ if (repo && repo !== '.') params.set('repo', repo);
71
+ try {
72
+ const res = await fetch(`/api/fs/exists?${params.toString()}`);
73
+ const data = (await res.json().catch(() => null)) as { exists?: unknown; mtimeMs?: unknown } | null;
74
+ if (!res.ok || !data || typeof data.exists !== 'boolean') return { kind: 'unknown' };
75
+ if (data.exists === false) return { kind: 'gone' };
76
+ if (typeof data.mtimeMs !== 'number') return { kind: 'unknown' };
77
+ return data.mtimeMs === baseMtimeMs
78
+ ? { kind: 'unchanged' }
79
+ : { kind: 'changed', mtimeMs: data.mtimeMs, baseMtimeMs };
80
+ } catch {
81
+ return { kind: 'unknown' };
82
+ }
83
+ }
84
+
85
+ interface UseExternalChangeOptions {
86
+ /** The file the buffer came from; `null` for an inline attachment or a handle. */
87
+ path: string | null;
88
+ root?: string | null;
89
+ repo?: string | null;
90
+ /** The mtime the buffer was read at — the value the save path would send. */
91
+ baseMtimeMs: number | null;
92
+ /** Only a dirty buffer has anything to lose. */
93
+ dirty: boolean;
94
+ /**
95
+ * Bumped whenever something may have written the tree.
96
+ *
97
+ * The panel's `refreshKey` already carries this (a save, a Files-panel delete, a
98
+ * workspace refresh), and the realtime topic adds the agent's own writes.
99
+ */
100
+ revision: number;
101
+ }
102
+
103
+ /**
104
+ * The disk change this buffer has to be told about, or null.
105
+ *
106
+ * The probe runs on `revision` (a write somewhere) and on the base moving (a save
107
+ * that landed). A save updates `baseMtimeMs` to what the server wrote, and
108
+ * re-probing with the NEW base is what clears the strip — comparing against a base
109
+ * the probe never saw would leave it up over a file the user just saved.
110
+ */
111
+ export function useExternalChange({
112
+ path,
113
+ root = null,
114
+ repo = null,
115
+ baseMtimeMs,
116
+ dirty,
117
+ revision,
118
+ }: UseExternalChangeOptions): DiskChange | null {
119
+ const [change, setChange] = useState<DiskChange | null>(null);
120
+ /** The base the last probe asked about, so a re-render does not re-probe. */
121
+ const askedRef = useRef<number | null>(null);
122
+
123
+ useEffect(() => {
124
+ if (!path || !dirty || baseMtimeMs === null) {
125
+ setChange(null);
126
+ askedRef.current = null;
127
+ return;
128
+ }
129
+ if (askedRef.current === baseMtimeMs) return;
130
+ let cancelled = false;
131
+ void probeExternalChange(path, root, repo, baseMtimeMs).then((verdict) => {
132
+ if (cancelled) return;
133
+ askedRef.current = baseMtimeMs;
134
+ // `unknown` deliberately leaves the previous answer alone: a dropped probe
135
+ // must not raise a strip, and it must not clear one the user is reading
136
+ // either — the next revision asks again.
137
+ if (verdict.kind === 'unknown') return;
138
+ setChange(verdict.kind === 'changed' ? { mtimeMs: verdict.mtimeMs, baseMtimeMs: verdict.baseMtimeMs } : null);
139
+ });
140
+ return () => {
141
+ cancelled = true;
142
+ };
143
+ }, [path, root, repo, baseMtimeMs, dirty, revision]);
144
+
145
+ return change;
146
+ }