@kabmo-labs/kabmo 0.28.0 → 0.30.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 (232) hide show
  1. package/bunfig.toml +6 -0
  2. package/dist/client/index.html +2 -2
  3. package/dist/client/index.js +481 -472
  4. package/dist/client/static/js/{index-xzvyrxya.js → index-5vjbp04s.js} +1193 -1049
  5. package/dist/client/static/js/index-naa91727.css +1 -0
  6. package/dist/client/static/{manifest-q6h8k9e0.webmanifest → manifest-vdvdqpre.webmanifest} +1 -0
  7. package/package.json +3 -2
  8. package/public/manifest.webmanifest +1 -0
  9. package/src/client/components/common/ComposerTextarea.test.tsx +109 -0
  10. package/src/client/components/common/ComposerTextarea.tsx +6 -0
  11. package/src/client/components/common/ReloadPageButton.test.tsx +14 -0
  12. package/src/client/components/common/ReloadPageButton.tsx +11 -2
  13. package/src/client/components/common/diagram-viewer/read-block.test.ts +71 -0
  14. package/src/client/components/common/diagram-viewer/read-block.ts +40 -16
  15. package/src/client/components/common/file-icon/index.tsx +7 -1
  16. package/src/client/components/common/harness-glyph/brands.ts +7 -1
  17. package/src/client/components/common/image-viewer/index.tsx +37 -165
  18. package/src/client/components/common/picker-search/index.tsx +70 -0
  19. package/src/client/components/common/search-select/index.tsx +2 -7
  20. package/src/client/components/common/zoom-pan-stage/index.tsx +258 -0
  21. package/src/client/components/common/zoom-pan-stage/zoom-pan-stage.test.tsx +87 -0
  22. package/src/client/components/layout/session-sidebar/ClassicView.tsx +1 -1
  23. package/src/client/components/layout/session-sidebar/SessionListNotice.tsx +7 -3
  24. package/src/client/components/layout/session-sidebar/about-modal/HarnessRow.tsx +4 -1
  25. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +12 -1
  26. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.test.tsx +82 -0
  27. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +23 -3
  28. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +1 -0
  29. package/src/client/components/layout/session-sidebar/modern/index.tsx +1 -1
  30. package/src/client/components/layout/session-sidebar/scheduler-modal/TaskList.tsx +6 -4
  31. package/src/client/components/layout/session-sidebar/session-list-states.test.tsx +8 -0
  32. package/src/client/components/mobile/mobile-right-sidebar/EditorSurface.tsx +25 -0
  33. package/src/client/components/mobile/mobile-session-sidebar/ClassicDrawer.tsx +1 -1
  34. package/src/client/components/settings/Sidebar.tsx +6 -8
  35. package/src/client/components/settings/categories/HarnessSettings.tsx +4 -2
  36. package/src/client/components/settings/categories/PanelPluginSettings.tsx +2 -2
  37. package/src/client/components/settings/categories/PluginSettings.tsx +1 -1
  38. package/src/client/components/settings/categories/harness-settings/ConfigForm.tsx +3 -6
  39. package/src/client/components/settings/categories/panel-plugins/GitFreshness.test.tsx +36 -0
  40. package/src/client/components/settings/categories/panel-plugins/Section.tsx +1 -3
  41. package/src/client/components/settings/categories/panel-plugins/Toolbar.tsx +18 -4
  42. package/src/client/components/settings/categories/plugin-settings/MarketplacePane.tsx +64 -61
  43. package/src/client/components/settings/categories/plugin-settings/SidebarList.tsx +15 -4
  44. package/src/client/components/settings/groups.test.tsx +2 -2
  45. package/src/client/components/workspace/chat-timeline/IrcNotice.test.tsx +55 -0
  46. package/src/client/components/workspace/chat-timeline/IrcNotice.tsx +71 -0
  47. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +4 -1
  48. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.test.ts +19 -0
  49. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +8 -3
  50. package/src/client/components/workspace/chat-timeline/chat-input/WaitingDependencyPicker.search.test.tsx +72 -0
  51. package/src/client/components/workspace/chat-timeline/chat-input/WaitingDependencyPicker.tsx +42 -15
  52. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.test.tsx +28 -0
  53. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +28 -10
  54. package/src/client/components/workspace/chat-timeline/target-picker/WorkspacePicker.test.tsx +47 -1
  55. package/src/client/components/workspace/chat-timeline/target-picker/WorkspacePicker.tsx +55 -5
  56. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +3 -2
  57. package/src/client/components/workspace/editor/FilePane.tsx +32 -0
  58. package/src/client/components/workspace/editor/Toolbar.tsx +4 -0
  59. package/src/client/components/workspace/editor/toolbar-clusters.test.ts +1 -0
  60. package/src/client/components/workspace/editor/toolbar-clusters.tsx +5 -2
  61. package/src/client/components/workspace/editor/viewers/CsvGrid.tsx +52 -5
  62. package/src/client/components/workspace/editor/viewers/DataGrid.tsx +227 -41
  63. package/src/client/components/workspace/editor/viewers/DrawioView.tsx +93 -0
  64. package/src/client/components/workspace/editor/viewers/GridRow.tsx +91 -0
  65. package/src/client/components/workspace/editor/viewers/GridToolbar.tsx +53 -0
  66. package/src/client/components/workspace/editor/viewers/SheetView.tsx +152 -57
  67. package/src/client/components/workspace/editor/viewers/dispatch.tsx +42 -9
  68. package/src/client/components/workspace/editor/viewers/drawio-pages.test.ts +80 -0
  69. package/src/client/components/workspace/editor/viewers/drawio-pages.ts +63 -0
  70. package/src/client/components/workspace/editor/viewers/grid.test.ts +296 -0
  71. package/src/client/components/workspace/editor/viewers/use-cell-edit.ts +64 -0
  72. package/src/client/components/workspace/editor/viewers/use-grid-interaction.ts +216 -0
  73. package/src/client/components/workspace/editor/viewers/viewers.test.ts +47 -2
  74. package/src/client/components/workspace/editor/viewers/workbook.ts +149 -0
  75. package/src/client/components/workspace/file-explorer/ArchiveModals.tsx +262 -0
  76. package/src/client/components/workspace/file-explorer/ContextMenu.tsx +30 -6
  77. package/src/client/components/workspace/file-explorer/Modals.tsx +8 -3
  78. package/src/client/components/workspace/file-explorer/RootOverlays.tsx +60 -0
  79. package/src/client/components/workspace/file-explorer/RowLabel.tsx +6 -2
  80. package/src/client/components/workspace/file-explorer/TreeItem.tsx +39 -49
  81. package/src/client/components/workspace/file-explorer/TreeItemModals.tsx +80 -0
  82. package/src/client/components/workspace/file-explorer/index.tsx +53 -29
  83. package/src/client/components/workspace/file-explorer/selection.test.tsx +109 -0
  84. package/src/client/data/settings/omp-schema.json +169 -22
  85. package/src/client/glass-palette.test.ts +72 -0
  86. package/src/client/glass.css +39 -14
  87. package/src/client/glass.test.ts +28 -67
  88. package/src/client/hooks/chat/composer/history.test.ts +267 -0
  89. package/src/client/hooks/chat/composer/history.ts +146 -0
  90. package/src/client/hooks/chat/timeline/ask-frames.test.ts +54 -0
  91. package/src/client/hooks/chat/timeline/ask-frames.ts +29 -1
  92. package/src/client/hooks/chat/timeline/timeline-rail.test.ts +34 -2
  93. package/src/client/hooks/chat/timeline/user-turns.ts +31 -2
  94. package/src/client/hooks/editor/file-editor-types.ts +15 -0
  95. package/src/client/hooks/editor/save-bytes.ts +79 -0
  96. package/src/client/hooks/editor/use-dirty-tracking.test.ts +73 -0
  97. package/src/client/hooks/editor/use-dirty-tracking.ts +96 -0
  98. package/src/client/hooks/editor/use-file-cache.ts +1 -0
  99. package/src/client/hooks/editor/use-file-editor.test.ts +30 -0
  100. package/src/client/hooks/editor/use-file-editor.ts +20 -17
  101. package/src/client/hooks/editor/use-file-read.ts +21 -2
  102. package/src/client/hooks/editor/use-grid-selection.ts +160 -0
  103. package/src/client/hooks/models/use-harness-update.test.ts +35 -2
  104. package/src/client/hooks/models/use-harness-update.ts +49 -10
  105. package/src/client/hooks/workspace/diff-file.test.ts +72 -0
  106. package/src/client/hooks/workspace/diff-file.ts +12 -6
  107. package/src/client/hooks/workspace/file-archive.ts +220 -0
  108. package/src/client/hooks/workspace/file-clipboard.test.ts +4 -4
  109. package/src/client/hooks/workspace/file-clipboard.ts +37 -26
  110. package/src/client/hooks/workspace/file-selection.test.ts +67 -0
  111. package/src/client/hooks/workspace/file-selection.ts +156 -0
  112. package/src/client/hooks/workspace/file-tree-actions-clipboard.test.ts +5 -5
  113. package/src/client/hooks/workspace/file-tree-actions.ts +36 -8
  114. package/src/client/lib/editor/workbook-drafts.ts +42 -0
  115. package/src/client/lib/launch/file-handlers.ts +2 -2
  116. package/src/client/lib/scrollbar-activity.test.ts +21 -88
  117. package/src/client/lib/scrollbar-activity.ts +71 -73
  118. package/src/client/lib/scrollbar-events.ts +143 -0
  119. package/src/client/lib/scrollbar-input.test.ts +126 -0
  120. package/src/client/lib/scrollbar-probe.test-util.ts +107 -0
  121. package/src/client/tailwind.css +32 -1
  122. package/src/server/db.server.test.ts +50 -1
  123. package/src/server/db.server.ts +36 -3
  124. package/src/server/lib/chat/prompt-history.server.test.ts +92 -0
  125. package/src/server/lib/chat/prompt-history.server.ts +65 -0
  126. package/src/server/lib/chat/schema.server.ts +35 -0
  127. package/src/server/lib/db/schema.ts +3 -0
  128. package/src/server/lib/fs/archive.test.ts +198 -0
  129. package/src/server/lib/fs/archive.ts +278 -0
  130. package/src/server/lib/fs/git-diff.test.ts +26 -1
  131. package/src/server/lib/fs/git-diff.ts +43 -15
  132. package/src/server/lib/harness/launch-table.ts +19 -0
  133. package/src/server/lib/harness/provider-entry.ts +1 -1
  134. package/src/server/lib/harness/provider-file.server.ts +1 -1
  135. package/src/server/lib/harness/provider-sources.server.ts +2 -1
  136. package/src/server/lib/harness/provider-write.server.ts +2 -1
  137. package/src/server/lib/harness/update-job-store.ts +12 -0
  138. package/src/server/lib/harness/update-queue.server.ts +15 -10
  139. package/src/server/lib/omp/rpc/frame-fold-signals.test.ts +5 -1
  140. package/src/server/lib/omp/rpc/frame-fold.test.ts +5 -1
  141. package/src/server/lib/omp/rpc/lifecycle.test.ts +4 -0
  142. package/src/server/lib/omp/session/auto-title.server.test.ts +4 -0
  143. package/src/server/lib/omp/session/delete.server.ts +1 -0
  144. package/src/server/lib/omp/session/goal-driver.test.ts +5 -1
  145. package/src/server/lib/omp/session/goal-settings.test.ts +5 -1
  146. package/src/server/lib/panels/auto-update.server.test.ts +5 -2
  147. package/src/server/lib/panels/git-update.server.test.ts +5 -2
  148. package/src/server/lib/panels/install.server.test.ts +5 -2
  149. package/src/server/lib/panels/remove.server.test.ts +5 -2
  150. package/src/server/routes/agent/command.ts +11 -0
  151. package/src/server/routes/agent/new.ts +5 -0
  152. package/src/server/routes/chat/index.ts +5 -0
  153. package/src/server/routes/chat/prompt-history.test.ts +67 -0
  154. package/src/server/routes/chat/prompt-history.ts +31 -0
  155. package/src/server/routes/chat/stream.test.ts +21 -0
  156. package/src/server/routes/chat/stream.ts +5 -0
  157. package/src/server/routes/fs/action-archive.test.ts +128 -0
  158. package/src/server/routes/fs/action-bulk.ts +106 -0
  159. package/src/server/routes/fs/action-save-bytes.test.ts +59 -0
  160. package/src/server/routes/fs/action-transfer.test.ts +26 -0
  161. package/src/server/routes/fs/action.ts +91 -11
  162. package/src/server/routes/fs/archive.ts +20 -0
  163. package/src/server/routes/fs/grant.test.ts +5 -2
  164. package/src/server/routes/fs/index.ts +2 -0
  165. package/src/server/routes/fs/scope.test.ts +6 -2
  166. package/src/server/routes/harness/import-action.ts +1 -1
  167. package/src/server/routes/harness/root.ts +6 -1
  168. package/src/server/routes/harness/summary.test.ts +50 -0
  169. package/src/server/routes/harness/update-status.ts +41 -2
  170. package/src/server/routes/harness/update.test.ts +56 -2
  171. package/src/server/routes/sessions/delete.test.ts +4 -0
  172. package/src/shared/lib/chat/ask-form/index.ts +39 -31
  173. package/src/shared/lib/chat/ask-form/labels.ts +46 -0
  174. package/src/shared/lib/chat/ask-form/tokens.ts +11 -2
  175. package/src/shared/lib/chat/ask-form.test.ts +57 -0
  176. package/src/shared/lib/chat/ask-questions.ts +31 -0
  177. package/src/shared/lib/chat/composer/history.test.ts +67 -0
  178. package/src/shared/lib/chat/composer/history.ts +61 -0
  179. package/src/shared/lib/chat/irc-notice.ts +42 -0
  180. package/src/shared/lib/chat/timeline/fork-anchor.test.ts +2 -0
  181. package/src/shared/lib/chat/todo/parser.ts +6 -4
  182. package/src/shared/lib/fs/archive.test.ts +101 -0
  183. package/src/shared/lib/fs/archive.ts +191 -0
  184. package/src/shared/lib/fs/clipboard.test.ts +32 -7
  185. package/src/shared/lib/fs/clipboard.ts +59 -14
  186. package/src/shared/lib/fs/csv.test.ts +50 -0
  187. package/src/shared/lib/fs/csv.ts +40 -0
  188. package/src/shared/lib/fs/document-kind.test.ts +13 -6
  189. package/src/shared/lib/fs/document-kind.ts +18 -6
  190. package/src/shared/lib/fs/file-kind-classify.test.ts +4 -0
  191. package/src/shared/lib/fs/file-kind.test.ts +2 -7
  192. package/src/shared/lib/fs/file-kind.ts +4 -2
  193. package/src/shared/lib/fs/grid-edit.test.ts +24 -0
  194. package/src/shared/lib/fs/grid-edit.ts +29 -0
  195. package/src/shared/lib/fs/grid-selection.test.ts +137 -0
  196. package/src/shared/lib/fs/grid-selection.ts +138 -0
  197. package/src/shared/lib/harness/brand-color.ts +5 -0
  198. package/src/shared/lib/harness/catalog.test.ts +22 -0
  199. package/src/shared/lib/harness/catalog.ts +12 -1
  200. package/src/shared/lib/harness/config-fields.test.ts +25 -0
  201. package/src/shared/lib/harness/config-fields.ts +33 -3
  202. package/src/shared/lib/harness/dialects.ts +1 -1
  203. package/src/shared/lib/harness/mcp-facts.ts +4 -0
  204. package/src/shared/lib/harness/provider-contracts.ts +109 -0
  205. package/src/shared/lib/harness/provider-facts.test.ts +2 -1
  206. package/src/shared/lib/harness/provider-facts.ts +24 -115
  207. package/src/shared/lib/harness/provider-lookup.ts +37 -0
  208. package/src/shared/lib/harness/providers.ts +2 -1
  209. package/src/shared/lib/harness/updates.ts +10 -0
  210. package/src/shared/lib/icons/tint-hues.generated.ts +14 -13
  211. package/src/shared/lib/omp/session/mapper.test.ts +31 -0
  212. package/src/shared/lib/omp/session/mapper.ts +17 -0
  213. package/src/shared/lib/omp/session/messages-map-notice.test.ts +68 -0
  214. package/src/shared/lib/omp/session/messages-map.test.ts +1 -35
  215. package/src/shared/lib/omp/session/messages-map.ts +17 -0
  216. package/src/shared/lib/omp/session/wait.ts +10 -1
  217. package/src/shared/lib/settings/sections.ts +8 -4
  218. package/src/shared/lib/ui/picker-filter.test.ts +23 -0
  219. package/src/shared/lib/ui/picker-filter.ts +20 -0
  220. package/src/shared/types/chat.ts +4 -0
  221. package/src/shared/types/harness.ts +5 -1
  222. package/src/shared/types/omp/session.ts +18 -0
  223. package/src/shared/types/settings/state.ts +6 -6
  224. package/src/shared/types/todo.ts +3 -1
  225. package/src/test-support/file-actions.test-util.ts +4 -0
  226. package/src/test-support/file-archive.test-util.ts +41 -0
  227. package/src/test-support/file-clipboard.test-util.ts +9 -6
  228. package/src/test-support/file-editor.test-util.ts +3 -2
  229. package/src/test-support/glass-css.ts +30 -0
  230. package/src/test-support/harness-table.test-util.ts +2 -0
  231. package/src/test-support/preload.ts +46 -0
  232. package/dist/client/static/js/index-81f7berm.css +0 -1
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Writing a BINARY document back to disk — the workbook the grid edited.
8
+ *
9
+ * The text save path (`save-file.ts`) cannot carry these bytes: its payload is a
10
+ * multipart text field, which is UTF-8 and normalizes line endings, so a ZIP
11
+ * container would arrive corrupted. The bytes therefore travel as a Blob, and
12
+ * the server writes them verbatim.
13
+ *
14
+ * The two origins are the same two the read path has: a workspace path goes
15
+ * through `/api/fs/action`, and a file the OS handed over has no server path —
16
+ * only a live handle — so it is written through `createWritable`.
17
+ *
18
+ * `baseMtimeMs` is the conflict base, exactly as the text path sends it. A
19
+ * binary viewer has no mtime from its read (`/api/fs/raw` does not report one),
20
+ * so it omits the field and the write is unconditional — the pre-existing
21
+ * contract for a save with no expectation.
22
+ */
23
+
24
+ import { writeThroughHandle } from '@/client/lib/launch/file-handlers';
25
+
26
+ export interface SavableBytesTarget {
27
+ path?: string;
28
+ root?: string;
29
+ repo?: string;
30
+ handleId?: string;
31
+ }
32
+
33
+ export type BytesSaveOutcome =
34
+ | { status: 'written'; mtimeMs: number | null }
35
+ | { status: 'conflict'; diskMtimeMs: number | null }
36
+ | { status: 'needs-permission' }
37
+ | { status: 'failed'; error: string | null };
38
+
39
+ interface SaveBytesResponse {
40
+ success?: unknown;
41
+ error?: unknown;
42
+ mtimeMs?: unknown;
43
+ }
44
+
45
+ export async function saveFileBytes(
46
+ target: SavableBytesTarget,
47
+ bytes: Uint8Array,
48
+ options: { interactive: boolean; baseMtimeMs?: number | null },
49
+ ): Promise<BytesSaveOutcome> {
50
+ if (target.handleId) {
51
+ const result = await writeThroughHandle(target.handleId, bytes, { interactive: options.interactive });
52
+ if (result === 'written') return { status: 'written', mtimeMs: null };
53
+ if (result === 'needs-permission') return { status: 'needs-permission' };
54
+ return { status: 'failed', error: 'The browser refused the write.' };
55
+ }
56
+ if (!target.path) return { status: 'failed', error: 'This file has no path to write to.' };
57
+
58
+ const formData = new FormData();
59
+ formData.append('actionType', 'saveBytes');
60
+ formData.append('path', target.path);
61
+ formData.append('bytes', new Blob([bytes]));
62
+ if (target.root) formData.append('root', target.root);
63
+ if (target.repo && target.repo !== '.') formData.append('repo', target.repo);
64
+ if (typeof options.baseMtimeMs === 'number') formData.append('baseMtime', String(options.baseMtimeMs));
65
+
66
+ try {
67
+ const res = await fetch('/api/fs/action', { method: 'POST', body: formData });
68
+ const data = (await res.json().catch(() => null)) as SaveBytesResponse | null;
69
+ if (res.status === 409) {
70
+ return { status: 'conflict', diskMtimeMs: typeof data?.mtimeMs === 'number' ? data.mtimeMs : null };
71
+ }
72
+ if (res.ok && data?.success) {
73
+ return { status: 'written', mtimeMs: typeof data.mtimeMs === 'number' ? data.mtimeMs : null };
74
+ }
75
+ return { status: 'failed', error: typeof data?.error === 'string' ? data.error : null };
76
+ } catch {
77
+ return { status: 'failed', error: null };
78
+ }
79
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The dirty set is the tab strip's and the close guard's one answer, and it has
8
+ * two sources: a text buffer that differs from its baseline, and a BINARY
9
+ * document (a workbook) whose edits live in the viewer's own draft store — for
10
+ * which all this side keeps is a flag.
11
+ *
12
+ * Driven through `useFileEditor`, because that is the only caller: the hook is
13
+ * an extraction of its state, and a test that mounted it alone would pin the
14
+ * wiring rather than the answer the tab strip reads.
15
+ */
16
+
17
+ import { describe, expect, test } from 'bun:test';
18
+ import { TARGET, createEditorHarness, freshState, stubFetch } from '@/test-support/file-editor.test-util';
19
+
20
+ const editor = createEditorHarness();
21
+
22
+ describe('useDirtyTracking', () => {
23
+ test('a binary document marks its own tab dirty, and its save clears the flag', async () => {
24
+ const state = freshState();
25
+ stubFetch(state);
26
+ await editor.mount();
27
+ expect(editor.mounted?.isDirty).toBe(false);
28
+
29
+ await editor.run(() => editor.mounted?.setBinaryDirty(true));
30
+ expect(editor.mounted?.isDirty).toBe(true);
31
+ expect([...(editor.mounted?.dirtyKeys ?? [])]).toEqual([String(TARGET.id)]);
32
+
33
+ await editor.run(() => editor.mounted?.setBinaryDirty(false));
34
+ expect(editor.mounted?.isDirty).toBe(false);
35
+ expect([...(editor.mounted?.dirtyKeys ?? [])]).toEqual([]);
36
+ });
37
+
38
+ // An INLINE target (an attachment chip) deliberately, because it never reads:
39
+ // a tab closed on a read file leaves its baseline behind on purpose, and that
40
+ // baseline alone would read as dirty and hide the flag this test is about.
41
+ test('retain drops the flag of a closed tab', async () => {
42
+ const state = freshState();
43
+ stubFetch(state);
44
+ await editor.mount({ id: 9, name: 'book.xlsx', path: 'book.xlsx', content: 'x' });
45
+ await editor.run(() => editor.mounted?.setBinaryDirty(true));
46
+ expect(editor.mounted?.isDirty).toBe(true);
47
+
48
+ // A closed tab's flag would otherwise keep the close guard armed for a file
49
+ // that is not on screen.
50
+ await editor.run(() => editor.mounted?.retain([]));
51
+ expect(editor.mounted?.isDirty).toBe(false);
52
+ expect([...(editor.mounted?.dirtyKeys ?? [])]).toEqual([]);
53
+ });
54
+
55
+ test('a text edit and a workbook flag in one tab are one answer', async () => {
56
+ const state = freshState();
57
+ stubFetch(state);
58
+ await editor.mount();
59
+
60
+ await editor.run(() => editor.mounted?.setBinaryDirty(true));
61
+ editor.mounted?.onChange('edited by hand');
62
+ await editor.settle();
63
+ expect([...(editor.mounted?.dirtyKeys ?? [])]).toEqual([String(TARGET.id)]);
64
+
65
+ // Saving the text leaves the workbook's own draft unsaved, so the tab stays
66
+ // dirty until the viewer clears its flag.
67
+ editor.mounted?.saveNow();
68
+ await editor.settle();
69
+ expect(editor.mounted?.isDirty).toBe(true);
70
+ await editor.run(() => editor.mounted?.setBinaryDirty(false));
71
+ expect(editor.mounted?.isDirty).toBe(false);
72
+ });
73
+ });
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Which open files have unsaved edits.
8
+ *
9
+ * Two sources, one answer: the TEXT buffers (a buffer that differs from the
10
+ * baseline it was read at) and the BINARY documents (a workbook whose draft
11
+ * lives in the viewer's own store, so all this side keeps is a flag). The dirty
12
+ * set is DERIVED from those two rather than tracked separately — a second copy
13
+ * would be a second thing to keep in step, and the comparison is a string
14
+ * identity check per open buffer.
15
+ *
16
+ * Split out of `use-file-editor.ts` so that file stays under the repo's
17
+ * per-file ceiling; the text comparison stays with the caller because it owns
18
+ * the buffer and its line-ending normalization.
19
+ */
20
+
21
+ import { useCallback, useMemo, useState } from 'preact/hooks';
22
+ import { editorTargetKey as targetKey } from '@/client/hooks/editor/target-key';
23
+ import type { FileEditorTarget } from '@/client/hooks/editor/file-editor-types';
24
+
25
+ interface Options {
26
+ target: FileEditorTarget | null;
27
+ /** The active file's cache key, `''` when nothing is open. */
28
+ key: string;
29
+ /** Whether the active TEXT buffer differs from its baseline. */
30
+ textDirty: boolean;
31
+ contents: Record<string, string>;
32
+ baselines: Record<string, string>;
33
+ /** Drops the caches of tabs that are no longer open — see `useFileCache`. */
34
+ retain: (ids: Array<number | string>) => void;
35
+ }
36
+
37
+ export function useDirtyTracking({ target, key, textDirty, contents, baselines, retain }: Options) {
38
+ /**
39
+ * Files whose BINARY document (a workbook) holds unsaved edits.
40
+ *
41
+ * Kept beside the text caches rather than inside them because the value is a
42
+ * flag, not a buffer: the edited workbook itself lives in the viewer's draft
43
+ * store, and this set is what the tab strip and the close guard read.
44
+ */
45
+ const [binaryDirtyKeys, setBinaryDirtyKeys] = useState<ReadonlySet<string>>(() => new Set());
46
+
47
+ const isDirty = textDirty || binaryDirtyKeys.has(key);
48
+
49
+ const dirtyKeys = useMemo(() => {
50
+ const next = new Set<string>(binaryDirtyKeys);
51
+ for (const [bufferKey, text] of Object.entries(contents)) {
52
+ const baseline = baselines[bufferKey];
53
+ if (baseline !== undefined && text !== baseline) next.add(bufferKey);
54
+ }
55
+ return next;
56
+ }, [contents, baselines, binaryDirtyKeys]);
57
+
58
+ const setBinaryDirty = useCallback(
59
+ (dirty: boolean) => {
60
+ if (!target) return;
61
+ const fileKey = targetKey(target);
62
+ setBinaryDirtyKeys((previous) => {
63
+ if (previous.has(fileKey) === dirty) return previous;
64
+ const next = new Set(previous);
65
+ if (dirty) next.add(fileKey);
66
+ else next.delete(fileKey);
67
+ return next;
68
+ });
69
+ },
70
+ [target],
71
+ );
72
+
73
+ /**
74
+ * `retain` also drops the binary flags of tabs that are no longer open: a
75
+ * closed tab's flag would otherwise keep the close guard armed for a file
76
+ * that is not on screen.
77
+ */
78
+ const retainAll = useCallback(
79
+ (ids: Array<number | string>) => {
80
+ retain(ids);
81
+ const keep = new Set(ids.map(String));
82
+ setBinaryDirtyKeys((previous) => {
83
+ let changed = false;
84
+ const next = new Set<string>();
85
+ for (const fileKey of previous) {
86
+ if (keep.has(fileKey)) next.add(fileKey);
87
+ else changed = true;
88
+ }
89
+ return changed ? next : previous;
90
+ });
91
+ },
92
+ [retain],
93
+ );
94
+
95
+ return { isDirty, dirtyKeys, setBinaryDirty, retain: retainAll };
96
+ }
@@ -92,6 +92,7 @@ export function useFileCache({
92
92
  if (!keep.has(loaded)) loadedRef.current.delete(loaded);
93
93
  }
94
94
  setContents((previous) => retainKeys(previous, keep));
95
+ setBaselines((previous) => retainKeys(previous, keep));
95
96
  setLineEndings((previous) => retainKeys(previous, keep));
96
97
  setMtimes((previous) => retainKeys(previous, keep));
97
98
  setHashes((previous) => retainKeys(previous, keep));
@@ -74,6 +74,9 @@ describe('useFileEditor revalidation', () => {
74
74
 
75
75
  await editor.mount();
76
76
  expect(editor.mounted?.isLoading).toBe(true);
77
+ // The reload glyph is about RE-reads; the opening read is already reported
78
+ // by `isLoading`, so both must not spin it.
79
+ expect(editor.mounted?.isReading).toBe(false);
77
80
  expect(editor.mounted?.loaded).toBe(false);
78
81
 
79
82
  release();
@@ -83,6 +86,33 @@ describe('useFileEditor revalidation', () => {
83
86
  expect(editor.mounted?.content).toBe(DISK);
84
87
  });
85
88
 
89
+ // The manual "Reload from disk" re-reads content that is already on screen,
90
+ // where `isLoading` deliberately stays false (a spinner over live content is
91
+ // the bug it prevents) — so the toolbar's reload glyph had nothing to spin
92
+ // for. `isReading` is that signal, and only for a re-read.
93
+ test('a re-read reports isReading and never isLoading', async () => {
94
+ const state = freshState();
95
+ stubFetch(state);
96
+ await editor.mount();
97
+ expect(editor.mounted?.isReading).toBe(false);
98
+
99
+ let release: () => void = () => {};
100
+ const gate = new Promise<void>((resolve) => { release = resolve; });
101
+ const realFetch = globalThis.fetch;
102
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
103
+ await gate;
104
+ return realFetch(input, init);
105
+ }) as typeof fetch;
106
+
107
+ await editor.run(() => editor.mounted?.reset());
108
+ expect(editor.mounted?.isReading).toBe(true);
109
+ expect(editor.mounted?.isLoading).toBe(false);
110
+
111
+ release();
112
+ await editor.settle();
113
+ expect(editor.mounted?.isReading).toBe(false);
114
+ });
115
+
86
116
  // A textarea's API value drops every CR, so a CRLF file reaches the buffer as
87
117
  // LF — and multipart/form-data turns a bare LF back into CRLF, so the payload
88
118
  // cannot carry the ending. The file's own ending therefore travels as its own
@@ -1,4 +1,4 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState } from 'preact/hooks';
1
+ import { useCallback, useEffect, useRef, useState } from 'preact/hooks';
2
2
  import { getLanguageFromPath } from '@/shared/lib/code/language';
3
3
  import { resolveViewer } from '@/client/hooks/editor/resolve-viewer';
4
4
  import { toDiskText, toLf, type LineEnding } from '@/shared/lib/code/line-endings';
@@ -10,6 +10,7 @@ import { useFileWrites } from '@/client/hooks/editor/use-file-writes';
10
10
  import { useWriteConflict } from '@/client/hooks/editor/use-write-conflict';
11
11
  import { useDiskSync } from '@/client/hooks/editor/use-disk-sync';
12
12
  import { useFileCache } from '@/client/hooks/editor/use-file-cache';
13
+ import { useDirtyTracking } from '@/client/hooks/editor/use-dirty-tracking';
13
14
  import { editorTargetKey as targetKey } from '@/client/hooks/editor/target-key';
14
15
  import type { FileEditorSaveStatus, FileEditorTarget, UseFileEditorOptions, UseFileEditorResult } from '@/client/hooks/editor/file-editor-types';
15
16
 
@@ -68,20 +69,7 @@ export function useFileEditor(
68
69
  // An inline `content` (attachment chip) can carry CRLF too, and the buffer it
69
70
  // feeds is LF-only — normalizing here keeps `isDirty` comparing like with like.
70
71
  const content = target ? (contents[key] ?? (target.content !== undefined ? toLf(target.content) : '')) : '';
71
- const isDirty = content !== (baselines[key] ?? content);
72
- /**
73
- * The dirty set, derived from the two caches rather than tracked separately:
74
- * a second copy would be a second thing to keep in step, and the comparison is
75
- * a string identity check per open buffer.
76
- */
77
- const dirtyKeys = useMemo(() => {
78
- const next = new Set<string>();
79
- for (const [bufferKey, text] of Object.entries(contents)) {
80
- const baseline = baselines[bufferKey];
81
- if (baseline !== undefined && text !== baseline) next.add(bufferKey);
82
- }
83
- return next;
84
- }, [contents, baselines]);
72
+ const textDirty = content !== (baselines[key] ?? content);
85
73
 
86
74
  // The viewer, its bytes and the image URL — see `resolve-viewer.ts` for the
87
75
  // three rules this derivation encodes (the kind comes from the path; a
@@ -127,11 +115,24 @@ export function useFileEditor(
127
115
  setHashes,
128
116
  });
129
117
 
118
+ /**
119
+ * The dirty set (text buffers plus binary flags) lives in its own hook — see
120
+ * `use-dirty-tracking.ts` for why it is derived rather than tracked.
121
+ */
122
+ const { isDirty, dirtyKeys, setBinaryDirty, retain: retainAll } = useDirtyTracking({
123
+ target,
124
+ key,
125
+ textDirty,
126
+ contents,
127
+ baselines,
128
+ retain,
129
+ });
130
+
130
131
  /**
131
132
  * The read path lives in its own hook — see `use-file-read.ts` for the two
132
133
  * flags it reports and why the kind refusal is separate from a failed read.
133
134
  */
134
- const { isLoading, loadError, unsupported } = useFileRead({
135
+ const { isLoading, isReading, loadError, unsupported } = useFileRead({
135
136
  target,
136
137
  key,
137
138
  isBinaryViewer,
@@ -296,6 +297,7 @@ export function useFileEditor(
296
297
  content,
297
298
  onChange,
298
299
  isLoading,
300
+ isReading,
299
301
  // A byte viewer has no buffer to wait for, and inline content is already in
300
302
  // hand; otherwise the key's entry exists only once the read resolved.
301
303
  loaded: target ? isBinaryViewer || target.content !== undefined || contents[key] !== undefined : false,
@@ -304,6 +306,7 @@ export function useFileEditor(
304
306
  saveStatus,
305
307
  copied,
306
308
  isDirty,
309
+ setBinaryDirty,
307
310
  eol: lineEndings[key] ?? 'lf',
308
311
  setEol,
309
312
  baseMtimeMs: mtimes[key] ?? null,
@@ -325,7 +328,7 @@ export function useFileEditor(
325
328
  copy,
326
329
  download,
327
330
  reset,
328
- retain,
331
+ retain: retainAll,
329
332
  saveMissingConfirm: writes.saveMissingConfirm,
330
333
  confirmSaveMissing: writes.confirmSaveMissing,
331
334
  cancelSaveMissing: writes.cancelSaveMissing,
@@ -89,6 +89,17 @@ export interface UseFileReadOptions {
89
89
 
90
90
  export interface FileReadState {
91
91
  isLoading: boolean;
92
+ /**
93
+ * A read is in flight over content that is already on screen — the manual
94
+ * "Reload from disk" (or a workspace refresh), never the first load.
95
+ *
96
+ * `isLoading` deliberately stays `false` for those reads (a spinner over live
97
+ * content is the bug it prevents), so the toolbar's reload glyph had no state
98
+ * to spin for. This is that state, and it is false during a first load so the
99
+ * glyph does not spin while the opening read is what the overlay already
100
+ * reports.
101
+ */
102
+ isReading: boolean;
92
103
  loadError: string | null;
93
104
  /** Set only for a refusal about the file's kind; see the module note. */
94
105
  unsupported: string | null;
@@ -112,12 +123,14 @@ export function useFileRead({
112
123
  remember,
113
124
  }: UseFileReadOptions): FileReadState {
114
125
  const [isLoading, setIsLoading] = useState(false);
126
+ const [reading, setReading] = useState(false);
115
127
  const [loadError, setLoadError] = useState<string | null>(null);
116
128
  const [unsupported, setUnsupported] = useState<string | null>(null);
117
129
 
118
130
  // Read the active file once per key. A cancelled guard keeps a late response
119
131
  // from a previous file from overwriting the one now on screen.
120
132
  useEffect(() => {
133
+ setReading(false);
121
134
  if (!target) return;
122
135
  const fileKey = targetKey(target);
123
136
  if (loadedRef.current.has(fileKey)) return;
@@ -162,6 +175,7 @@ export function useFileRead({
162
175
  if (target.root) params.set('root', target.root);
163
176
  if (target.repo && target.repo !== '.') params.set('repo', target.repo);
164
177
  readingRef.current += 1;
178
+ setReading(true);
165
179
  fetch(`/api/fs/read?${params.toString()}`)
166
180
  .then(async (res) => {
167
181
  const data = (await res.json().catch(() => null)) as
@@ -207,7 +221,10 @@ export function useFileRead({
207
221
  })
208
222
  .finally(() => {
209
223
  readingRef.current -= 1;
210
- if (!cancelled) setIsLoading(false);
224
+ if (!cancelled) {
225
+ setIsLoading(false);
226
+ setReading(false);
227
+ }
211
228
  });
212
229
 
213
230
  return () => {
@@ -215,5 +232,7 @@ export function useFileRead({
215
232
  };
216
233
  }, [key, target, remember, revision, isBinaryViewer, loadedRef, contentsRef, baselinesRef, pendingRef, readingRef]);
217
234
 
218
- return { isLoading, loadError, unsupported };
235
+ // A first load keeps `isLoading` true for the same read, so the reload glyph
236
+ // must not also claim it: this flag is about re-reads only.
237
+ return { isLoading, isReading: reading && !isLoading, loadError, unsupported };
219
238
  }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The selection state of the spreadsheet grid.
8
+ *
9
+ * Two cells, not one: the ANCHOR is where the selection started and the FOCUS
10
+ * is where the pointer or the keyboard is now. A plain click collapses both
11
+ * onto the same cell, a drag or a shift-click moves only the focus, and the
12
+ * drawn range is the rectangle between them. Keeping the anchor is what makes
13
+ * shift-click extend instead of restart, which is the behaviour every
14
+ * spreadsheet has and the one a single `selected` cell cannot express.
15
+ *
16
+ * The hook owns no DOM: the grid delegates pointer events from one listener and
17
+ * asks this for the verdict, so a 2000-row sheet does not mount 200 000
18
+ * handlers.
19
+ */
20
+
21
+ import { useCallback, useMemo, useRef, useState } from 'preact/hooks';
22
+ import {
23
+ cellRange,
24
+ clampCell,
25
+ moveCell,
26
+ selectAllRange,
27
+ type GridCell,
28
+ type GridRange,
29
+ } from '@/shared/lib/fs/grid-selection';
30
+
31
+ export interface GridSelection {
32
+ /** The drawn rectangle, or null when nothing is selected. */
33
+ range: GridRange | null;
34
+ /** The cell the keyboard acts on, or null. */
35
+ active: GridCell | null;
36
+ /** True while a pointer drag is extending the selection. */
37
+ dragging: boolean;
38
+ /** Start a selection at `cell`; `extend` keeps the anchor (shift-click). */
39
+ begin: (cell: GridCell, extend: boolean) => void;
40
+ /** Move the focus while dragging. */
41
+ extendTo: (cell: GridCell) => void;
42
+ /** End a drag. */
43
+ endDrag: () => void;
44
+ /** Move the active cell by a delta; `extend` keeps the anchor. */
45
+ move: (rowDelta: number, columnDelta: number, extend: boolean) => void;
46
+ /** Select the whole grid. */
47
+ selectAll: () => void;
48
+ /** Select a whole column; `extend` keeps the anchor. */
49
+ selectColumn: (col: number, extend: boolean) => void;
50
+ /** Select a whole row; `extend` keeps the anchor. */
51
+ selectRow: (row: number, extend: boolean) => void;
52
+ /** Drop the selection. */
53
+ clear: () => void;
54
+ }
55
+
56
+ export function useGridSelection(rowCount: number, columnCount: number): GridSelection {
57
+ const [anchor, setAnchor] = useState<GridCell | null>(null);
58
+ const [focus, setFocus] = useState<GridCell | null>(null);
59
+ const [dragging, setDragging] = useState(false);
60
+ // The pointer handlers read the live flag, not the render's copy: a
61
+ // pointerover can arrive before the state update that started the drag has
62
+ // been committed.
63
+ const draggingRef = useRef(false);
64
+
65
+ const clamp = useCallback(
66
+ (cell: GridCell) => clampCell(cell, rowCount, columnCount),
67
+ [rowCount, columnCount],
68
+ );
69
+
70
+ const begin = useCallback(
71
+ (cell: GridCell, extend: boolean) => {
72
+ const next = clamp(cell);
73
+ if (extend && anchor) {
74
+ setFocus(next);
75
+ } else {
76
+ setAnchor(next);
77
+ setFocus(next);
78
+ }
79
+ draggingRef.current = true;
80
+ setDragging(true);
81
+ },
82
+ [anchor, clamp],
83
+ );
84
+
85
+ const extendTo = useCallback(
86
+ (cell: GridCell) => {
87
+ if (!draggingRef.current) return;
88
+ setFocus(clamp(cell));
89
+ },
90
+ [clamp],
91
+ );
92
+
93
+ const endDrag = useCallback(() => {
94
+ draggingRef.current = false;
95
+ setDragging(false);
96
+ }, []);
97
+
98
+ const move = useCallback(
99
+ (rowDelta: number, columnDelta: number, extend: boolean) => {
100
+ const from = focus ?? { row: 0, col: 0 };
101
+ const next = moveCell(from, rowDelta, columnDelta, rowCount, columnCount);
102
+ if (extend && anchor) {
103
+ setFocus(next);
104
+ } else {
105
+ setAnchor(next);
106
+ setFocus(next);
107
+ }
108
+ },
109
+ [anchor, focus, rowCount, columnCount],
110
+ );
111
+
112
+ const selectAll = useCallback(() => {
113
+ const all = selectAllRange(rowCount, columnCount);
114
+ if (!all) return;
115
+ setAnchor({ row: all.top, col: all.left });
116
+ setFocus({ row: all.bottom, col: all.right });
117
+ }, [rowCount, columnCount]);
118
+
119
+ const selectColumn = useCallback(
120
+ (col: number, extend: boolean) => {
121
+ const next = clamp({ row: rowCount - 1, col });
122
+ if (extend && anchor) {
123
+ setFocus(next);
124
+ } else {
125
+ setAnchor(clamp({ row: 0, col }));
126
+ setFocus(next);
127
+ }
128
+ },
129
+ [anchor, clamp, rowCount],
130
+ );
131
+
132
+ const selectRow = useCallback(
133
+ (row: number, extend: boolean) => {
134
+ const next = clamp({ row, col: columnCount - 1 });
135
+ if (extend && anchor) {
136
+ setFocus(next);
137
+ } else {
138
+ setAnchor(clamp({ row, col: 0 }));
139
+ setFocus(next);
140
+ }
141
+ },
142
+ [anchor, clamp, columnCount],
143
+ );
144
+
145
+ const clear = useCallback(() => {
146
+ setAnchor(null);
147
+ setFocus(null);
148
+ }, []);
149
+
150
+ // The range is derived, and clamped on read: a sheet switch or a live CSV
151
+ // edit can shrink the grid under a selection that was valid a render ago.
152
+ const range = useMemo(() => {
153
+ if (!anchor || !focus) return null;
154
+ return cellRange(clamp(anchor), clamp(focus));
155
+ }, [anchor, focus, clamp]);
156
+
157
+ const active = useMemo(() => (focus ? clamp(focus) : null), [focus, clamp]);
158
+
159
+ return { range, active, dragging, begin, extendTo, endDrag, move, selectAll, selectColumn, selectRow, clear };
160
+ }
@@ -35,6 +35,8 @@ let postReplies: { status: number; body: unknown }[] = [];
35
35
  let statusJobs: HarnessUpdateJob[] = [];
36
36
  /** Called when the card re-reads the version rows (the probe-arrival signal). */
37
37
  let onVersionsRead: (() => void) | null = null;
38
+ /** Called when the stub answers one status poll — the "a poll landed" signal. */
39
+ let onStatusRead: (() => void) | null = null;
38
40
 
39
41
  function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
40
42
  return {
@@ -66,17 +68,24 @@ beforeEach(() => {
66
68
  statusJobs = [];
67
69
  postReplies = [];
68
70
  onVersionsRead = null;
71
+ onStatusRead = null;
69
72
  (globalThis as unknown as Record<string, unknown>).fetch = async (input: unknown, init?: { method?: string }) => {
70
73
  calls.push(`${init?.method ?? 'GET'} ${String(input)}`);
71
74
  if (init?.method === 'POST') {
72
75
  const reply = postReplies.length > 1 ? postReplies.shift()! : postReplies[0];
73
76
  return new Response(JSON.stringify(reply?.body ?? {}), { status: reply?.status ?? 202 });
74
77
  }
78
+ if (init?.method === 'DELETE') {
79
+ return new Response(JSON.stringify({ dismissed: true }), { status: 200 });
80
+ }
75
81
  if (String(input).includes('/api/harness/versions')) {
76
82
  onVersionsRead?.();
77
83
  onVersionsRead = null;
78
84
  return new Response(JSON.stringify({ harnesses: [] }), { status: 200 });
79
85
  }
86
+ const statusRead = onStatusRead;
87
+ onStatusRead = null;
88
+ statusRead?.();
80
89
  return new Response(JSON.stringify({ jobs: statusJobs }), { status: 200 });
81
90
  };
82
91
  });
@@ -280,7 +289,31 @@ describe('useHarnessUpdate', () => {
280
289
  expect(current.problem).toBeNull();
281
290
  expect(harness.current().jobs).toEqual([]);
282
291
  expect(await harness.settlement(0)).toEqual({ message: 'claude is already up to date (adapter 0.102.0)', ok: true });
283
- // One read — the mount's — and no poll for a job that does not exist.
284
- expect(GETS()).toHaveLength(1);
292
+ });
293
+
294
+ test('dismissing a settled result deletes the record and a stale poll cannot paint it back', async () => {
295
+ // The defect: "claude updated (adapter) — it now reports 0.106.0" stayed on
296
+ // the row with no way out. The delete is server-side (a closed card must not
297
+ // resurrect it), and the RUN key is remembered so a poll that started before
298
+ // the delete cannot re-add the record it still carries.
299
+ statusJobs = [finished({ message: 'claude updated (adapter) — it now reports 0.106.0', probe: 'pending' })];
300
+ const harness = mount();
301
+ await flush();
302
+ expect(harness.current().jobs).toHaveLength(1);
303
+
304
+ await act(async () => {
305
+ expect(await harness.current().dismiss('claude')).toBeNull();
306
+ });
307
+ expect(calls).toContain('DELETE /api/harness/update/status');
308
+ expect(harness.current().jobs).toEqual([]);
309
+
310
+ // A pending probe keeps the poll alive, and the stub keeps answering with
311
+ // the record that was just deleted: the next poll landing must not restore it.
312
+ const nextPoll = Promise.withResolvers<void>();
313
+ onStatusRead = nextPoll.resolve;
314
+ await act(async () => {
315
+ await nextPoll.promise;
316
+ });
317
+ expect(harness.current().jobs).toEqual([]);
285
318
  });
286
319
  });