@kabmo-labs/kabmo 0.28.0 → 0.29.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 (225) 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-43z47ngg.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.css +39 -14
  86. package/src/client/glass.test.ts +37 -0
  87. package/src/client/hooks/chat/composer/history.test.ts +267 -0
  88. package/src/client/hooks/chat/composer/history.ts +146 -0
  89. package/src/client/hooks/chat/timeline/ask-frames.test.ts +54 -0
  90. package/src/client/hooks/chat/timeline/ask-frames.ts +29 -1
  91. package/src/client/hooks/chat/timeline/timeline-rail.test.ts +34 -2
  92. package/src/client/hooks/chat/timeline/user-turns.ts +31 -2
  93. package/src/client/hooks/editor/file-editor-types.ts +15 -0
  94. package/src/client/hooks/editor/save-bytes.ts +79 -0
  95. package/src/client/hooks/editor/use-file-editor.test.ts +30 -0
  96. package/src/client/hooks/editor/use-file-editor.ts +53 -5
  97. package/src/client/hooks/editor/use-file-read.ts +21 -2
  98. package/src/client/hooks/editor/use-grid-selection.ts +160 -0
  99. package/src/client/hooks/models/use-harness-update.test.ts +35 -2
  100. package/src/client/hooks/models/use-harness-update.ts +49 -10
  101. package/src/client/hooks/workspace/diff-file.test.ts +72 -0
  102. package/src/client/hooks/workspace/diff-file.ts +12 -6
  103. package/src/client/hooks/workspace/file-archive.ts +220 -0
  104. package/src/client/hooks/workspace/file-clipboard.test.ts +4 -4
  105. package/src/client/hooks/workspace/file-clipboard.ts +37 -26
  106. package/src/client/hooks/workspace/file-selection.test.ts +67 -0
  107. package/src/client/hooks/workspace/file-selection.ts +156 -0
  108. package/src/client/hooks/workspace/file-tree-actions-clipboard.test.ts +5 -5
  109. package/src/client/hooks/workspace/file-tree-actions.ts +36 -8
  110. package/src/client/lib/editor/workbook-drafts.ts +42 -0
  111. package/src/client/lib/launch/file-handlers.ts +2 -2
  112. package/src/client/lib/scrollbar-activity.test.ts +21 -88
  113. package/src/client/lib/scrollbar-activity.ts +71 -73
  114. package/src/client/lib/scrollbar-events.ts +143 -0
  115. package/src/client/lib/scrollbar-input.test.ts +126 -0
  116. package/src/client/lib/scrollbar-probe.test-util.ts +107 -0
  117. package/src/client/tailwind.css +32 -1
  118. package/src/server/db.server.test.ts +50 -1
  119. package/src/server/db.server.ts +36 -3
  120. package/src/server/lib/chat/prompt-history.server.test.ts +92 -0
  121. package/src/server/lib/chat/prompt-history.server.ts +65 -0
  122. package/src/server/lib/chat/schema.server.ts +35 -0
  123. package/src/server/lib/db/schema.ts +3 -0
  124. package/src/server/lib/fs/archive.test.ts +139 -0
  125. package/src/server/lib/fs/archive.ts +259 -0
  126. package/src/server/lib/fs/git-diff.test.ts +26 -1
  127. package/src/server/lib/fs/git-diff.ts +43 -15
  128. package/src/server/lib/harness/launch-table.ts +19 -0
  129. package/src/server/lib/harness/provider-entry.ts +1 -1
  130. package/src/server/lib/harness/provider-file.server.ts +1 -1
  131. package/src/server/lib/harness/provider-sources.server.ts +2 -1
  132. package/src/server/lib/harness/provider-write.server.ts +2 -1
  133. package/src/server/lib/harness/update-job-store.ts +12 -0
  134. package/src/server/lib/harness/update-queue.server.ts +15 -10
  135. package/src/server/lib/omp/rpc/frame-fold-signals.test.ts +5 -1
  136. package/src/server/lib/omp/rpc/frame-fold.test.ts +5 -1
  137. package/src/server/lib/omp/rpc/lifecycle.test.ts +4 -0
  138. package/src/server/lib/omp/session/auto-title.server.test.ts +4 -0
  139. package/src/server/lib/omp/session/delete.server.ts +1 -0
  140. package/src/server/lib/omp/session/goal-driver.test.ts +5 -1
  141. package/src/server/lib/omp/session/goal-settings.test.ts +5 -1
  142. package/src/server/lib/panels/auto-update.server.test.ts +5 -2
  143. package/src/server/lib/panels/git-update.server.test.ts +5 -2
  144. package/src/server/lib/panels/install.server.test.ts +5 -2
  145. package/src/server/lib/panels/remove.server.test.ts +5 -2
  146. package/src/server/routes/agent/command.ts +11 -0
  147. package/src/server/routes/agent/new.ts +5 -0
  148. package/src/server/routes/chat/index.ts +5 -0
  149. package/src/server/routes/chat/prompt-history.test.ts +67 -0
  150. package/src/server/routes/chat/prompt-history.ts +31 -0
  151. package/src/server/routes/chat/stream.test.ts +21 -0
  152. package/src/server/routes/chat/stream.ts +5 -0
  153. package/src/server/routes/fs/action-archive.test.ts +128 -0
  154. package/src/server/routes/fs/action-bulk.ts +106 -0
  155. package/src/server/routes/fs/action-save-bytes.test.ts +59 -0
  156. package/src/server/routes/fs/action-transfer.test.ts +26 -0
  157. package/src/server/routes/fs/action.ts +91 -11
  158. package/src/server/routes/fs/archive.ts +20 -0
  159. package/src/server/routes/fs/grant.test.ts +5 -2
  160. package/src/server/routes/fs/index.ts +2 -0
  161. package/src/server/routes/fs/scope.test.ts +6 -2
  162. package/src/server/routes/harness/import-action.ts +1 -1
  163. package/src/server/routes/harness/root.ts +6 -1
  164. package/src/server/routes/harness/summary.test.ts +50 -0
  165. package/src/server/routes/harness/update-status.ts +41 -2
  166. package/src/server/routes/harness/update.test.ts +56 -2
  167. package/src/server/routes/sessions/delete.test.ts +4 -0
  168. package/src/shared/lib/chat/ask-form/index.ts +39 -31
  169. package/src/shared/lib/chat/ask-form/labels.ts +46 -0
  170. package/src/shared/lib/chat/ask-form/tokens.ts +11 -2
  171. package/src/shared/lib/chat/ask-form.test.ts +57 -0
  172. package/src/shared/lib/chat/ask-questions.ts +31 -0
  173. package/src/shared/lib/chat/composer/history.test.ts +67 -0
  174. package/src/shared/lib/chat/composer/history.ts +61 -0
  175. package/src/shared/lib/chat/irc-notice.ts +42 -0
  176. package/src/shared/lib/chat/timeline/fork-anchor.test.ts +2 -0
  177. package/src/shared/lib/chat/todo/parser.ts +6 -4
  178. package/src/shared/lib/fs/archive.test.ts +101 -0
  179. package/src/shared/lib/fs/archive.ts +191 -0
  180. package/src/shared/lib/fs/clipboard.test.ts +32 -7
  181. package/src/shared/lib/fs/clipboard.ts +59 -14
  182. package/src/shared/lib/fs/csv.test.ts +50 -0
  183. package/src/shared/lib/fs/csv.ts +40 -0
  184. package/src/shared/lib/fs/document-kind.test.ts +13 -6
  185. package/src/shared/lib/fs/document-kind.ts +18 -6
  186. package/src/shared/lib/fs/file-kind-classify.test.ts +4 -0
  187. package/src/shared/lib/fs/file-kind.test.ts +2 -7
  188. package/src/shared/lib/fs/file-kind.ts +4 -2
  189. package/src/shared/lib/fs/grid-edit.test.ts +24 -0
  190. package/src/shared/lib/fs/grid-edit.ts +29 -0
  191. package/src/shared/lib/fs/grid-selection.test.ts +137 -0
  192. package/src/shared/lib/fs/grid-selection.ts +138 -0
  193. package/src/shared/lib/harness/brand-color.ts +5 -0
  194. package/src/shared/lib/harness/catalog.test.ts +22 -0
  195. package/src/shared/lib/harness/catalog.ts +12 -1
  196. package/src/shared/lib/harness/config-fields.test.ts +25 -0
  197. package/src/shared/lib/harness/config-fields.ts +33 -3
  198. package/src/shared/lib/harness/dialects.ts +1 -1
  199. package/src/shared/lib/harness/mcp-facts.ts +4 -0
  200. package/src/shared/lib/harness/provider-contracts.ts +109 -0
  201. package/src/shared/lib/harness/provider-facts.test.ts +2 -1
  202. package/src/shared/lib/harness/provider-facts.ts +24 -115
  203. package/src/shared/lib/harness/provider-lookup.ts +37 -0
  204. package/src/shared/lib/harness/providers.ts +2 -1
  205. package/src/shared/lib/harness/updates.ts +10 -0
  206. package/src/shared/lib/omp/session/mapper.test.ts +31 -0
  207. package/src/shared/lib/omp/session/mapper.ts +17 -0
  208. package/src/shared/lib/omp/session/messages-map-notice.test.ts +68 -0
  209. package/src/shared/lib/omp/session/messages-map.test.ts +1 -35
  210. package/src/shared/lib/omp/session/messages-map.ts +17 -0
  211. package/src/shared/lib/omp/session/wait.ts +10 -1
  212. package/src/shared/lib/settings/sections.ts +8 -4
  213. package/src/shared/lib/ui/picker-filter.test.ts +23 -0
  214. package/src/shared/lib/ui/picker-filter.ts +20 -0
  215. package/src/shared/types/chat.ts +4 -0
  216. package/src/shared/types/harness.ts +5 -1
  217. package/src/shared/types/omp/session.ts +18 -0
  218. package/src/shared/types/settings/state.ts +6 -6
  219. package/src/shared/types/todo.ts +3 -1
  220. package/src/test-support/file-actions.test-util.ts +4 -0
  221. package/src/test-support/file-archive.test-util.ts +41 -0
  222. package/src/test-support/file-clipboard.test-util.ts +9 -6
  223. package/src/test-support/harness-table.test-util.ts +2 -0
  224. package/src/test-support/preload.ts +46 -0
  225. 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
+ }
@@ -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
@@ -61,6 +61,14 @@ export function useFileEditor(
61
61
  */
62
62
  const [hashes, setHashes] = useState<Record<string, string | null>>({});
63
63
  const [saveStatus, setSaveStatus] = useState<FileEditorSaveStatus>('idle');
64
+ /**
65
+ * Files whose BINARY document (a workbook) holds unsaved edits.
66
+ *
67
+ * Kept beside the text caches rather than inside them because the value is a
68
+ * flag, not a buffer: the edited workbook itself lives in the viewer's draft
69
+ * store, and this set is what the tab strip and the close guard read.
70
+ */
71
+ const [binaryDirtyKeys, setBinaryDirtyKeys] = useState<ReadonlySet<string>>(() => new Set());
64
72
  /** Bumped by `reset()` to re-run the read effect for the active file. */
65
73
  const [revision, setRevision] = useState(0);
66
74
 
@@ -68,20 +76,21 @@ export function useFileEditor(
68
76
  // An inline `content` (attachment chip) can carry CRLF too, and the buffer it
69
77
  // feeds is LF-only — normalizing here keeps `isDirty` comparing like with like.
70
78
  const content = target ? (contents[key] ?? (target.content !== undefined ? toLf(target.content) : '')) : '';
71
- const isDirty = content !== (baselines[key] ?? content);
79
+ const textDirty = content !== (baselines[key] ?? content);
80
+ const isDirty = textDirty || binaryDirtyKeys.has(key);
72
81
  /**
73
82
  * The dirty set, derived from the two caches rather than tracked separately:
74
83
  * a second copy would be a second thing to keep in step, and the comparison is
75
84
  * a string identity check per open buffer.
76
85
  */
77
86
  const dirtyKeys = useMemo(() => {
78
- const next = new Set<string>();
87
+ const next = new Set<string>(binaryDirtyKeys);
79
88
  for (const [bufferKey, text] of Object.entries(contents)) {
80
89
  const baseline = baselines[bufferKey];
81
90
  if (baseline !== undefined && text !== baseline) next.add(bufferKey);
82
91
  }
83
92
  return next;
84
- }, [contents, baselines]);
93
+ }, [contents, baselines, binaryDirtyKeys]);
85
94
 
86
95
  // The viewer, its bytes and the image URL — see `resolve-viewer.ts` for the
87
96
  // three rules this derivation encodes (the kind comes from the path; a
@@ -131,7 +140,7 @@ export function useFileEditor(
131
140
  * The read path lives in its own hook — see `use-file-read.ts` for the two
132
141
  * flags it reports and why the kind refusal is separate from a failed read.
133
142
  */
134
- const { isLoading, loadError, unsupported } = useFileRead({
143
+ const { isLoading, isReading, loadError, unsupported } = useFileRead({
135
144
  target,
136
145
  key,
137
146
  isBinaryViewer,
@@ -265,6 +274,43 @@ export function useFileEditor(
265
274
  setSaveStatus('idle');
266
275
  }, [key]);
267
276
 
277
+ const setBinaryDirty = useCallback(
278
+ (dirty: boolean) => {
279
+ if (!target) return;
280
+ const fileKey = targetKey(target);
281
+ setBinaryDirtyKeys((previous) => {
282
+ if (previous.has(fileKey) === dirty) return previous;
283
+ const next = new Set(previous);
284
+ if (dirty) next.add(fileKey);
285
+ else next.delete(fileKey);
286
+ return next;
287
+ });
288
+ },
289
+ [target],
290
+ );
291
+
292
+ /**
293
+ * `retain` also drops the binary flags of tabs that are no longer open: a
294
+ * closed tab's flag would otherwise keep the close guard armed for a file
295
+ * that is not on screen.
296
+ */
297
+ const retainAll = useCallback(
298
+ (ids: Array<number | string>) => {
299
+ retain(ids);
300
+ const keep = new Set(ids.map(String));
301
+ setBinaryDirtyKeys((previous) => {
302
+ let changed = false;
303
+ const next = new Set<string>();
304
+ for (const fileKey of previous) {
305
+ if (keep.has(fileKey)) next.add(fileKey);
306
+ else changed = true;
307
+ }
308
+ return changed ? next : previous;
309
+ });
310
+ },
311
+ [retain],
312
+ );
313
+
268
314
  const onChange = useCallback(
269
315
  (next: string) => {
270
316
  if (!target || isBinaryViewer) return;
@@ -296,6 +342,7 @@ export function useFileEditor(
296
342
  content,
297
343
  onChange,
298
344
  isLoading,
345
+ isReading,
299
346
  // A byte viewer has no buffer to wait for, and inline content is already in
300
347
  // hand; otherwise the key's entry exists only once the read resolved.
301
348
  loaded: target ? isBinaryViewer || target.content !== undefined || contents[key] !== undefined : false,
@@ -304,6 +351,7 @@ export function useFileEditor(
304
351
  saveStatus,
305
352
  copied,
306
353
  isDirty,
354
+ setBinaryDirty,
307
355
  eol: lineEndings[key] ?? 'lf',
308
356
  setEol,
309
357
  baseMtimeMs: mtimes[key] ?? null,
@@ -325,7 +373,7 @@ export function useFileEditor(
325
373
  copy,
326
374
  download,
327
375
  reset,
328
- retain,
376
+ retain: retainAll,
329
377
  saveMissingConfirm: writes.saveMissingConfirm,
330
378
  confirmSaveMissing: writes.confirmSaveMissing,
331
379
  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
  });
@@ -74,10 +74,16 @@ export interface HarnessUpdateController {
74
74
  /** Start an update; resolves to a refusal, or null when the run was started
75
75
  * (immediately or queued behind the one already installing). */
76
76
  start: (id: string) => Promise<string | null>;
77
+ /** Drop a settled record (the result is read and has nothing left to say);
78
+ * resolves to the refusal, or null when the record was deleted. */
79
+ dismiss: (id: string) => Promise<string | null>;
77
80
  }
78
81
 
79
82
  type Settled = (message: string, ok: boolean) => void;
80
83
 
84
+ /** One run's identity: a new update for the same harness replaces the record. */
85
+ const runKey = (job: HarnessUpdateJob): string => `${job.harness}:${job.startedAt}`;
86
+
81
87
  export function useHarnessUpdate(
82
88
  onSettled: Settled,
83
89
  { pollMs = HARNESS_UPDATE_POLL_MS, enabled = true }: HarnessUpdateOptions = {},
@@ -91,6 +97,13 @@ export function useHarnessUpdate(
91
97
  const reported = useRef(new Set<string>());
92
98
  // Runs whose post-install probe answer has already been reflected in the rows.
93
99
  const probed = useRef(new Set<string>());
100
+ // The runs this card dismissed, keyed by `harness:startedAt`. A poll already
101
+ // in flight when the delete landed would otherwise paint the record back for
102
+ // one frame; the key, not the harness, stays out so a NEW run is shown.
103
+ const dismissed = useRef(new Set<string>());
104
+ // The jobs as last rendered, so `dismiss` can name the run it is dropping
105
+ // without waiting for a render.
106
+ const shown = useRef<HarnessUpdateJob[]>([]);
94
107
  // The callback is read through a ref so an inline arrow from the caller does
95
108
  // not restart the mount effect (and re-adopt the records) on every render.
96
109
  const settled = useRef(onSettled);
@@ -99,13 +112,12 @@ export function useHarnessUpdate(
99
112
  /** Fold one harness's record into the list, keeping the newer one. */
100
113
  const merge = useCallback((incoming: HarnessUpdateJob | null) => {
101
114
  if (!incoming) return;
102
- setJobs((current) => {
103
- const index = current.findIndex((job) => job.harness === incoming.harness);
104
- if (index < 0) return [...current, incoming];
105
- const next = current.slice();
106
- next[index] = incoming;
107
- return next;
108
- });
115
+ const index = shown.current.findIndex((job) => job.harness === incoming.harness);
116
+ const next = index < 0
117
+ ? [...shown.current, incoming]
118
+ : shown.current.map((job) => (job.harness === incoming.harness ? incoming : job));
119
+ shown.current = next;
120
+ setJobs(next);
109
121
  }, []);
110
122
 
111
123
  /**
@@ -117,8 +129,12 @@ export function useHarnessUpdate(
117
129
  * are two separate moments, not one.
118
130
  */
119
131
  const observe = useCallback((incoming: HarnessUpdateJob[]) => {
120
- setJobs(incoming);
121
- for (const job of incoming) {
132
+ // A poll that was already in flight when a dismissal deleted the record
133
+ // still carries it; a dismissed run must not be painted back.
134
+ const visible = incoming.filter((job) => !dismissed.current.has(runKey(job)));
135
+ shown.current = visible;
136
+ setJobs(visible);
137
+ for (const job of visible) {
122
138
  if (jobUnfinished(job)) {
123
139
  watched.current.add(job.harness);
124
140
  reported.current.delete(job.harness);
@@ -246,5 +262,28 @@ export function useHarnessUpdate(
246
262
  return payload.error ?? 'Update failed';
247
263
  }, [follow, merge]);
248
264
 
249
- return { jobs, start };
265
+ const dismiss = useCallback(async (id: string): Promise<string | null> => {
266
+ let response: Response;
267
+ try {
268
+ response = await fetch('/api/harness/update/status', {
269
+ method: 'DELETE',
270
+ headers: { 'Content-Type': 'application/json' },
271
+ body: JSON.stringify({ harness: id }),
272
+ });
273
+ } catch (cause) {
274
+ return cause instanceof Error ? cause.message : 'Could not dismiss the update result';
275
+ }
276
+ const payload = (await response.json().catch(() => ({}))) as { error?: string };
277
+ if (!response.ok) return payload.error ?? `Could not dismiss the update result (HTTP ${response.status})`;
278
+ // Remember the RUN, not the harness: the record is gone on disk, and this
279
+ // keeps a poll that predates the delete from painting it back.
280
+ const target = shown.current.find((job) => job.harness === id);
281
+ if (target) dismissed.current.add(runKey(target));
282
+ const next = shown.current.filter((job) => job.harness !== id);
283
+ shown.current = next;
284
+ setJobs(next);
285
+ return null;
286
+ }, []);
287
+
288
+ return { jobs, start, dismiss };
250
289
  }