@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,267 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * ArrowUp recall in the composer: the cursor, the scope, the draft restore, and
8
+ * the keys it must leave to the caret.
9
+ *
10
+ * The hook is mounted against a REAL textarea, because half of its contract is
11
+ * about where the caret sits (a multi-line draft keeps its arrows) and the
12
+ * other half about what lands in the box.
13
+ *
14
+ * No wall clock: the fetch is a stub this file answers, and
15
+ * `requestAnimationFrame` is installed synchronously, so "settled" is a
16
+ * microtask, never a duration.
17
+ */
18
+
19
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
20
+ import { Window } from 'happy-dom';
21
+ import { h, render } from 'preact';
22
+ import { act } from 'preact/test-utils';
23
+ import { useState } from 'preact/hooks';
24
+ import { useComposerHistory, type ComposerHistory } from '@/client/hooks/chat/composer/history';
25
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
26
+
27
+ const nativeFetch = globalThis.fetch;
28
+ const nativeFrame = globalThis.requestAnimationFrame;
29
+ const nativeKeyboardEvent = globalThis.KeyboardEvent;
30
+
31
+ let container: HTMLElement | undefined;
32
+ let holder: {
33
+ api: ComposerHistory | null;
34
+ value: string;
35
+ setValue: (value: string) => void;
36
+ sessionId: string | null;
37
+ rerender: () => void;
38
+ };
39
+ let textareaRef: { current: HTMLTextAreaElement | null };
40
+ let requested: string[] = [];
41
+ let prompts: string[] = [];
42
+
43
+ beforeAll(() => {
44
+ const win = new Window({ url: 'http://localhost' });
45
+ installDomGlobals(win);
46
+ // `DOM_TEST_GLOBALS` does not carry `KeyboardEvent`; this suite builds real
47
+ // key events, so it installs the window's own class and puts it back.
48
+ (globalThis as unknown as Record<string, unknown>).KeyboardEvent = win.KeyboardEvent;
49
+ });
50
+
51
+ beforeEach(() => {
52
+ requested = [];
53
+ prompts = ['newest prompt', 'older prompt'];
54
+ // Synchronous frames: the hook only uses one to place the caret after the
55
+ // value has landed, which is the render this file already drives.
56
+ globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => {
57
+ callback(0);
58
+ return 0;
59
+ }) as typeof globalThis.requestAnimationFrame;
60
+ globalThis.fetch = ((input: string | URL | Request) => {
61
+ requested.push(String(input));
62
+ return Promise.resolve(new Response(JSON.stringify({ prompts })));
63
+ }) as unknown as typeof fetch;
64
+ textareaRef = { current: null };
65
+ holder = {
66
+ api: null,
67
+ value: '',
68
+ setValue: () => {},
69
+ sessionId: 'session-1',
70
+ rerender: () => {},
71
+ };
72
+ });
73
+
74
+ afterEach(() => {
75
+ if (container) render(null, container);
76
+ container?.remove();
77
+ container = undefined;
78
+ });
79
+
80
+ afterAll(() => {
81
+ globalThis.fetch = nativeFetch;
82
+ globalThis.requestAnimationFrame = nativeFrame;
83
+ if (nativeKeyboardEvent === undefined) {
84
+ delete (globalThis as unknown as Record<string, unknown>).KeyboardEvent;
85
+ } else {
86
+ globalThis.KeyboardEvent = nativeKeyboardEvent;
87
+ }
88
+ restoreDomGlobals();
89
+ });
90
+
91
+ function mount(sessionId: string | null): void {
92
+ holder.sessionId = sessionId;
93
+ function Probe() {
94
+ const [value, setValue] = useState('');
95
+ const [, bump] = useState(0);
96
+ holder.value = value;
97
+ holder.setValue = setValue;
98
+ holder.rerender = () => bump((turn) => turn + 1);
99
+ holder.api = useComposerHistory({
100
+ value,
101
+ onChange: (next) => {
102
+ setValue(next);
103
+ if (textareaRef.current) textareaRef.current.value = next;
104
+ },
105
+ sessionId: holder.sessionId,
106
+ textareaRef,
107
+ });
108
+ return h('textarea', {
109
+ ref: (node: HTMLTextAreaElement | null) => {
110
+ textareaRef.current = node;
111
+ },
112
+ });
113
+ }
114
+ container = document.body.appendChild(document.createElement('div'));
115
+ act(() => {
116
+ render(h(Probe, null), container!);
117
+ });
118
+ }
119
+
120
+ /** Let the hook's fetch → then chain run out. Microtasks only, no duration. */
121
+ async function settle(): Promise<void> {
122
+ for (let turn = 0; turn < 4; turn++) await Promise.resolve();
123
+ }
124
+
125
+ /** Type a draft and put the caret where the next arrow will read it. */
126
+ function writeDraft(value: string, caret = value.length): void {
127
+ act(() => holder.setValue(value));
128
+ if (!textareaRef.current) return;
129
+ textareaRef.current.value = value;
130
+ textareaRef.current.setSelectionRange(caret, caret);
131
+ }
132
+
133
+ function press(key: string, init: KeyboardEventInit = {}): boolean {
134
+ const event = new KeyboardEvent('keydown', { key, cancelable: true, ...init });
135
+ let consumed = false;
136
+ act(() => {
137
+ consumed = holder.api!.handleKey(event as never);
138
+ });
139
+ return consumed;
140
+ }
141
+
142
+ describe('useComposerHistory', () => {
143
+ test('ArrowUp recalls the newest prompt, then the older one', async () => {
144
+ mount('session-1');
145
+ expect(press('ArrowUp')).toBe(true);
146
+ await settle();
147
+ expect(holder.value).toBe('newest prompt');
148
+ expect(press('ArrowUp')).toBe(true);
149
+ expect(holder.value).toBe('older prompt');
150
+ // The list is exhausted: the key is still ours, and nothing changes.
151
+ expect(press('ArrowUp')).toBe(true);
152
+ expect(holder.value).toBe('older prompt');
153
+ });
154
+
155
+ test('ArrowDown walks back to the draft the list was entered from', async () => {
156
+ mount('session-1');
157
+ writeDraft('work in progress');
158
+
159
+ press('ArrowUp');
160
+ await settle();
161
+ expect(holder.value).toBe('newest prompt');
162
+ press('ArrowUp');
163
+ expect(holder.value).toBe('older prompt');
164
+ press('ArrowDown');
165
+ expect(holder.value).toBe('newest prompt');
166
+ press('ArrowDown');
167
+ expect(holder.value).toBe('work in progress');
168
+ });
169
+
170
+ test('ArrowDown from the draft is left to the caret', () => {
171
+ mount('session-1');
172
+ expect(press('ArrowDown')).toBe(false);
173
+ expect(requested).toHaveLength(0);
174
+ });
175
+
176
+ test('a pending new chat asks for the merged list', async () => {
177
+ mount('new-1790756769131');
178
+ press('ArrowUp');
179
+ await settle();
180
+ expect(requested).toEqual(['/api/chat/prompt-history']);
181
+ });
182
+
183
+ test('an open chat scopes the list to its own id', async () => {
184
+ mount('01a1b49f-0000-7000-8000-000000000001');
185
+ press('ArrowUp');
186
+ await settle();
187
+ expect(requested).toEqual(['/api/chat/prompt-history?sessionId=01a1b49f-0000-7000-8000-000000000001']);
188
+ });
189
+
190
+ test('a modified arrow is never consumed', () => {
191
+ mount('session-1');
192
+ expect(press('ArrowUp', { shiftKey: true })).toBe(false);
193
+ expect(press('ArrowUp', { metaKey: true })).toBe(false);
194
+ expect(press('ArrowUp', { ctrlKey: true })).toBe(false);
195
+ expect(press('ArrowUp', { altKey: true })).toBe(false);
196
+ });
197
+
198
+ test('ArrowUp below the first line moves the caret instead', () => {
199
+ mount('session-1');
200
+ writeDraft('first line\nsecond line');
201
+ expect(press('ArrowUp')).toBe(false);
202
+ expect(requested).toHaveLength(0);
203
+ });
204
+
205
+ test('ArrowUp on the first line of a multi-line draft recalls', async () => {
206
+ mount('session-1');
207
+ writeDraft('first line\nsecond line', 3);
208
+ expect(press('ArrowUp')).toBe(true);
209
+ await settle();
210
+ expect(holder.value).toBe('newest prompt');
211
+ });
212
+
213
+ test('ArrowDown above the last line moves the caret instead', async () => {
214
+ mount('session-1');
215
+ press('ArrowUp');
216
+ await settle();
217
+ writeDraft('line one\nline two', 2);
218
+ expect(press('ArrowDown')).toBe(false);
219
+ expect(holder.value).toBe('line one\nline two');
220
+ });
221
+
222
+ test('a failed fetch recalls nothing and the next ArrowUp asks again', async () => {
223
+ globalThis.fetch = ((input: string | URL | Request) => {
224
+ requested.push(String(input));
225
+ return Promise.resolve(new Response('{}', { status: 500 }));
226
+ }) as unknown as typeof fetch;
227
+ mount('session-1');
228
+ expect(press('ArrowUp')).toBe(true);
229
+ await settle();
230
+ expect(holder.value).toBe('');
231
+ expect(press('ArrowUp')).toBe(true);
232
+ await settle();
233
+ expect(requested).toHaveLength(2);
234
+ });
235
+
236
+ test('a session switch forgets the list', async () => {
237
+ mount('session-1');
238
+ press('ArrowUp');
239
+ await settle();
240
+ expect(holder.value).toBe('newest prompt');
241
+
242
+ prompts = ['other chat prompt'];
243
+ act(() => {
244
+ holder.sessionId = 'session-2';
245
+ holder.rerender();
246
+ });
247
+ expect(press('ArrowUp')).toBe(true);
248
+ await settle();
249
+ expect(holder.value).toBe('other chat prompt');
250
+ expect(requested.at(-1)).toBe('/api/chat/prompt-history?sessionId=session-2');
251
+ });
252
+
253
+ test('an emptied draft starts the next recall at the newest entry', async () => {
254
+ mount('session-1');
255
+ press('ArrowUp');
256
+ await settle();
257
+ press('ArrowUp');
258
+ expect(holder.value).toBe('older prompt');
259
+
260
+ // Sending clears the composer; the next recall is a fresh walk.
261
+ writeDraft('');
262
+ prompts = ['just sent', 'newest prompt', 'older prompt'];
263
+ press('ArrowUp');
264
+ await settle();
265
+ expect(holder.value).toBe('just sent');
266
+ });
267
+ });
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * ArrowUp / ArrowDown prompt recall for the chat composer.
8
+ *
9
+ * The list is fetched, never derived from the mounted transcript: the timeline
10
+ * only mounts a window of a long chat (`useChatTimeline` pages the newest
11
+ * rows), so a recall built from `messages` would forget everything the user
12
+ * paged past. The server owns the list and scopes it — one chat's own prompts
13
+ * on an open session, every session's prompts merged on a pending `new-…`
14
+ * chat — so this hook only holds the cursor.
15
+ *
16
+ * One GET per entry into the list (each `ArrowUp` from the draft), so a chat
17
+ * that just sent a prompt recalls it without polling: the fetch is what makes
18
+ * the newest entry the newest. Everything after that is in memory, and the
19
+ * fetch is lazy — a composer nobody presses ArrowUp in costs nothing.
20
+ *
21
+ * The rules, each of which has a failing case in the unit test:
22
+ * - `-1` is the draft the user was typing. ArrowUp from there ENTERS the list;
23
+ * ArrowDown from there is a plain caret move and is left alone.
24
+ * - Neither end wraps: past the newest entry, and back down past the oldest to
25
+ * the draft, nothing happens.
26
+ * - Arrow moves only at the list's edges of the TEXT: ArrowUp on the second
27
+ * line of a multi-line draft must move the caret, not recall.
28
+ * - A modified arrow (Shift/Ctrl/Cmd/Alt) is never consumed — Shift+ArrowUp is
29
+ * a selection.
30
+ */
31
+
32
+ import { useCallback, useEffect, useRef } from 'preact/hooks';
33
+ import type { KeyboardEvent, RefObject } from 'preact/compat';
34
+ import {
35
+ canRecallDown,
36
+ canRecallUp,
37
+ stepHistoryCursor,
38
+ type HistoryDirection,
39
+ } from '@/shared/lib/chat/composer/history';
40
+
41
+ export interface ComposerHistoryOptions {
42
+ value: string;
43
+ onChange: (value: string) => void;
44
+ /** The open chat. A pending `new-…` id (or `null`) asks for the merged list. */
45
+ sessionId: string | null;
46
+ textareaRef: RefObject<HTMLTextAreaElement | null>;
47
+ }
48
+
49
+ export interface ComposerHistory {
50
+ /** Consume the key when it recalled something; false leaves the caret alone. */
51
+ handleKey: (event: KeyboardEvent<HTMLTextAreaElement>) => boolean;
52
+ }
53
+
54
+ export async function fetchPromptHistory(sessionId: string | null): Promise<string[]> {
55
+ const scope = sessionId && !sessionId.startsWith('new-') ? sessionId : null;
56
+ const query = scope ? `?sessionId=${encodeURIComponent(scope)}` : '';
57
+ const response = await fetch(`/api/chat/prompt-history${query}`);
58
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
59
+ const body = (await response.json()) as { prompts?: unknown };
60
+ return Array.isArray(body.prompts) ? body.prompts.filter((text): text is string => typeof text === 'string') : [];
61
+ }
62
+
63
+ export function useComposerHistory({ value, onChange, sessionId, textareaRef }: ComposerHistoryOptions): ComposerHistory {
64
+ /** Newest first, as the route answers it. */
65
+ const entriesRef = useRef<string[]>([]);
66
+ const cursorRef = useRef(-1);
67
+ /** The draft the list was entered from, restored on the way back down. */
68
+ const draftRef = useRef('');
69
+
70
+ // A list belongs to ONE session: carrying it across a switch would offer the
71
+ // prompts of the chat the user just left.
72
+ useEffect(() => {
73
+ entriesRef.current = [];
74
+ cursorRef.current = -1;
75
+ draftRef.current = '';
76
+ }, [sessionId]);
77
+
78
+ // An emptied draft is a SENT prompt (or a cleared one): the next ArrowUp must
79
+ // start from the newest entry again, not continue from where the last recall
80
+ // left off.
81
+ useEffect(() => {
82
+ if (value === '') cursorRef.current = -1;
83
+ }, [value]);
84
+
85
+ const apply = useCallback((text: string) => {
86
+ onChange(text);
87
+ // The value lands on the next render; the caret must follow the text that
88
+ // arrived, not the one the textarea still holds in this tick.
89
+ requestAnimationFrame(() => {
90
+ const element = textareaRef.current;
91
+ if (!element) return;
92
+ element.setSelectionRange(text.length, text.length);
93
+ });
94
+ }, [onChange, textareaRef]);
95
+
96
+ const step = useCallback((direction: HistoryDirection): boolean => {
97
+ const next = stepHistoryCursor(entriesRef.current.length, cursorRef.current, direction);
98
+ if (next === null) return false;
99
+ cursorRef.current = next;
100
+ apply(next === -1 ? draftRef.current : entriesRef.current[next]);
101
+ return true;
102
+ }, [apply]);
103
+
104
+ const handleKey = useCallback((event: KeyboardEvent<HTMLTextAreaElement>): boolean => {
105
+ const key = event.key;
106
+ if (key !== 'ArrowUp' && key !== 'ArrowDown') return false;
107
+ if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return false;
108
+ // An IME composition owns the arrows: picking a candidate is not a recall.
109
+ if (event.isComposing) return false;
110
+
111
+ const element = textareaRef.current;
112
+ if (!element) return false;
113
+ const caret = element.selectionStart ?? value.length;
114
+ const direction: HistoryDirection = key === 'ArrowUp' ? 'up' : 'down';
115
+
116
+ if (cursorRef.current !== -1) {
117
+ // Inside the list. Down is only recall while the caret is on the last
118
+ // line; up never leaves the list early (both ends refuse, no wrap).
119
+ if (direction === 'down' && !canRecallDown(value, caret)) return false;
120
+ event.preventDefault();
121
+ step(direction);
122
+ return true;
123
+ }
124
+
125
+ // In the draft. Down is an ordinary caret move; up has to start on the
126
+ // first line, and only then is the list fetched.
127
+ if (direction === 'down' || !canRecallUp(value, caret)) return false;
128
+ event.preventDefault();
129
+ draftRef.current = value;
130
+ void fetchPromptHistory(sessionId)
131
+ .then((entries) => {
132
+ entriesRef.current = entries;
133
+ // The cursor may have been reset by a session switch while this was in
134
+ // flight; the effect cleared the draft, so start from the top again.
135
+ cursorRef.current = -1;
136
+ draftRef.current = value;
137
+ step('up');
138
+ })
139
+ // Nothing was substituted: the caret simply did not move, and the next
140
+ // ArrowUp asks again.
141
+ .catch(() => {});
142
+ return true;
143
+ }, [sessionId, step, textareaRef, value]);
144
+
145
+ return { handleKey };
146
+ }
@@ -181,4 +181,58 @@ describe('splitAskFrames', () => {
181
181
  expect(split.framesByTool.size).toBe(0);
182
182
  expect(split.modalRequest).toBe(gate);
183
183
  });
184
+
185
+ test('a select whose title matches no question is claimed by its option rows', () => {
186
+ // The parser-drift safety net: the two derivations of a form's question text
187
+ // can disagree on a shape neither was written for, and the title is the only
188
+ // key that drifts. The offered rows are the same list either way.
189
+ const frame: ExtensionUiDialogRequest = {
190
+ type: 'extension_ui_request',
191
+ id: 'f1',
192
+ method: 'select',
193
+ title: 'Which language? And more',
194
+ options: ['A', 'B', 'Other (type your own)'],
195
+ };
196
+
197
+ const split = splitAskFrames(askHistory(['Which language?']), [frame], true);
198
+
199
+ expect(split.framesByTool.get('call_ask')?.[0]?.map((held) => held.id)).toEqual(['f1']);
200
+ expect(split.modalRequest).toBeNull();
201
+ });
202
+
203
+ test('an approval gate is never claimed by an ask, even when its rows match', () => {
204
+ // The gate check runs before the row match: a gate whose choices happen to
205
+ // equal a question's options must still reach the modal, or "Approve" would
206
+ // be posted as that question's answer.
207
+ const [history] = askHistory(['Which language?']);
208
+ history.toolCalls![0].input = {
209
+ questions: [{ question: 'Which language?', options: [{ label: 'Approve' }, { label: 'Deny' }] }],
210
+ };
211
+ const gate: ExtensionUiDialogRequest = {
212
+ type: 'extension_ui_request',
213
+ id: 'g1',
214
+ method: 'select',
215
+ title: 'Allow tool: read\nReason: Restricted folder: /tmp/secret',
216
+ options: ['Approve', 'Deny'],
217
+ };
218
+ const split = splitAskFrames([history], [gate], true);
219
+
220
+ expect(split.framesByTool.size).toBe(0);
221
+ expect(split.modalRequest).toBe(gate);
222
+ });
223
+
224
+ test('a picker with unrelated rows keeps the modal', () => {
225
+ const picker: ExtensionUiDialogRequest = {
226
+ type: 'extension_ui_request',
227
+ id: 'p1',
228
+ method: 'select',
229
+ title: 'Choose a branch',
230
+ options: ['main', 'release/1.0'],
231
+ };
232
+
233
+ const split = splitAskFrames(askHistory(['Which language?']), [picker], true);
234
+
235
+ expect(split.framesByTool.size).toBe(0);
236
+ expect(split.modalRequest).toBe(picker);
237
+ });
184
238
  });
@@ -42,7 +42,7 @@
42
42
  import { createContext, useContext } from 'preact/compat';
43
43
  import type { ChatMessageData } from '@/shared/types';
44
44
  import type { ExtensionUiDialogRequest } from '@/shared/types/omp/agent';
45
- import { askQuestionForTitle, groupAskFrames, isAskSettled, isAskToolCall, normalizeAskText, parseAskQuestions } from '@/shared/lib/chat/ask-questions';
45
+ import { askQuestionForOptions, askQuestionForTitle, groupAskFrames, isAskSettled, isAskToolCall, normalizeAskText, parseAskQuestions } from '@/shared/lib/chat/ask-questions';
46
46
  import { parseAskResult } from '@/shared/lib/chat/ask-results';
47
47
  import type { AskQuestion } from '@/shared/lib/chat/ask-form/types';
48
48
  import { isApprovalGateFrame } from '@/shared/lib/chat/omp/approval-gate';
@@ -110,6 +110,8 @@ export function splitAskFrames(
110
110
 
111
111
  const owned = new Map<string, ExtensionUiDialogRequest[]>();
112
112
  const claimed = new Set<ExtensionUiDialogRequest>();
113
+ /** Frames claimed by their option rows, with the question index they name. */
114
+ const optionPlacements = new Map<ExtensionUiDialogRequest, number>();
113
115
  const orphanAsks: ExtensionUiDialogRequest[] = [];
114
116
  let lastOwner: string | null = null;
115
117
 
@@ -190,6 +192,25 @@ export function splitAskFrames(
190
192
  // "Approve"/"Deny" rendered as the ANSWERS to an unrelated question and
191
193
  // the answer went to the wrong tool call. A gate is excluded from the
192
194
  // fallback exactly like a `confirm`, and reaches the modal instead.
195
+ //
196
+ // A `select` whose title matches nothing is still the ask's when its ROWS
197
+ // are the question's rows: the two parsers can disagree on a form shape
198
+ // neither was written for, and the title is the only key that drifts. The
199
+ // option list is the same list either way, so it is the fallback key — and
200
+ // an exact set match of two or more labels cannot steal an extension
201
+ // picker or a gate.
202
+ if (!owner && request.method === 'select' && !isApprovalGateFrame(request)) {
203
+ for (let index = openAsks.length - 1; index >= 0; index -= 1) {
204
+ const candidate = openAsks[index];
205
+ const matched = askQuestionForOptions(candidate.questions, request.options);
206
+ if (matched === -1) continue;
207
+ owner = candidate.toolId;
208
+ // The title walk already placed it in `groupAskFrames`; a frame claimed
209
+ // by its rows has no title to place by, so its row is recorded here.
210
+ optionPlacements.set(request, matched);
211
+ break;
212
+ }
213
+ }
193
214
  if (!owner && request.method !== 'confirm' && !isApprovalGateFrame(request)) owner = lastOwner;
194
215
  if (!owner) continue;
195
216
  claimed.add(request);
@@ -212,6 +233,13 @@ export function splitAskFrames(
212
233
  }
213
234
  continue;
214
235
  }
236
+ // A frame claimed by its rows already knows the question it belongs to.
237
+ const byOptions = optionPlacements.get(frame);
238
+ if (byOptions !== undefined) {
239
+ if (placed[byOptions]) placed[byOptions].push(frame);
240
+ else loose.push(frame);
241
+ continue;
242
+ }
215
243
  loose.push(frame);
216
244
  }
217
245
  // Everything that was not part of a grouped frame keeps the per-question
@@ -138,11 +138,43 @@ describe('useUserTurns', () => {
138
138
  * entry pointed at a DOM id the reconciliation had already replaced. This is
139
139
  * the duplicate a user sees right after sending a prompt.
140
140
  */
141
- test('the same turn under its optimistic and echoed ids is listed once', async () => {
141
+ test('the same turn under its optimistic and echoed ids is listed once, under the mounted id', async () => {
142
142
  const text = 'send this once';
143
143
  committed = { turns: [{ id: 'omp-echo-id', index: 7, preview: text }] };
144
144
  await open('s1', [userMessage('msg-1791000000000-user', text)]);
145
- expect(rail?.turns.map((turn) => turn.id)).toEqual(['omp-echo-id']);
145
+ // The DOM row is still the optimistic bubble, so the tick has to name THAT
146
+ // id: the committed index names a node the timeline does not render until
147
+ // omp echoes the turn, and a jump to a missing id reveals nothing.
148
+ expect(rail?.turns.map((turn) => turn.id)).toEqual(['msg-1791000000000-user']);
149
+ expect(rail?.turns[0].index).toBe(7);
150
+ });
151
+
152
+ test('a jump on the paired entry reaches the mounted row instead of paging to a missing id', async () => {
153
+ const text = 'send this once';
154
+ committed = { turns: [{ id: 'prev-turn', index: 3, preview: 'earlier' }, { id: 'omp-echo-id', index: 7, preview: text }] };
155
+ await open('s1', [userMessage('prev-turn', 'earlier'), userMessage('msg-1791000000000-user', text)]);
156
+ let reached = false;
157
+ await act(async () => {
158
+ reached = await rail!.jumpToTurn(rail!.turns[1].id, rail!.turns[1].index);
159
+ });
160
+ expect(reached).toBe(true);
161
+ expect(revealed).toEqual(['msg-1791000000000-user']);
162
+ });
163
+
164
+ test('an older committed turn is not re-pointed at a newer live row with the same text', async () => {
165
+ const text = 'same text';
166
+ committed = {
167
+ turns: [
168
+ { id: 'older-turn', index: 2, preview: text },
169
+ { id: 'previous-turn', index: 8, preview: 'another prompt' },
170
+ ],
171
+ };
172
+ await open('s1', [userMessage('previous-turn', 'another prompt'), userMessage('msg-1791000000000-user', text)]);
173
+ expect(rail?.turns.map((turn) => [turn.id, turn.index])).toEqual([
174
+ ['older-turn', 2],
175
+ ['previous-turn', 8],
176
+ ['msg-1791000000000-user', -1],
177
+ ]);
146
178
  });
147
179
 
148
180
  test('a genuinely new turn is still appended even when another shares a prefix', async () => {
@@ -140,17 +140,46 @@ export function useUserTurns(deps: UseUserTurnsDeps): UserTurnsState {
140
140
  // `TURN_PREVIEW_CHARS`, so a real match is byte-identical, while a prefix
141
141
  // test would swallow a genuine short prompt that opens with an earlier
142
142
  // turn's words.
143
+ //
144
+ // The pair is also NEWER than every committed turn the client still has
145
+ // mounted. That is what makes the match the same turn rather than two
146
+ // prompts that happen to read alike: the entry this live row stands for was
147
+ // committed after everything on screen, so an older tick can never be
148
+ // re-pointed at it (which would strand the older turn).
149
+ const newestMountedCommitted = indexed.reduce(
150
+ (newest, turn) => (mountedIds.has(turn.id) ? Math.max(newest, turn.index) : newest),
151
+ -1,
152
+ );
143
153
  const paired = new Set<string>();
154
+ // Committed entry id → the id its row is mounted under RIGHT NOW.
155
+ //
156
+ // The committed index names the id omp recorded, and the mounted row does
157
+ // not carry it yet: omp echoes the user turn LATE (after the assistant
158
+ // segment), and until that echo the bubble the composer mounted keeps its
159
+ // optimistic `msg-…-user` id. Listing the committed id named a DOM node
160
+ // that does not exist, so a rail click on the newest turn paged nowhere and
161
+ // then waited out the reveal's deadline — the reported "cannot jump to the
162
+ // message I just sent until I reload". The listing therefore takes the
163
+ // DOM id from the row it is already drawing, and keeps the entry's own
164
+ // index (the paging cursor). Once the echo reconciles, the ids agree and
165
+ // this map is empty.
166
+ const rowIdFor = new Map<string, string>();
144
167
  const extra = mountedTurns.filter((turn) => {
145
168
  if (knownIds.has(turn.id)) return false;
146
169
  const match = orphanedCommitted.find(
147
- (entry) => !paired.has(entry.id) && entry.preview === turn.preview,
170
+ (entry) => entry.index > newestMountedCommitted && !paired.has(entry.id) && entry.preview === turn.preview,
148
171
  );
149
172
  if (!match) return true;
150
173
  paired.add(match.id);
174
+ rowIdFor.set(match.id, turn.id);
151
175
  return false;
152
176
  });
153
- return extra.length > 0 ? [...indexed, ...extra] : indexed;
177
+ const listed = extra.length > 0 ? [...indexed, ...extra] : indexed;
178
+ if (rowIdFor.size === 0) return listed;
179
+ return listed.map((turn) => {
180
+ const rowId = rowIdFor.get(turn.id);
181
+ return rowId ? { ...turn, id: rowId } : turn;
182
+ });
154
183
  }, [indexed, mountedTurns]);
155
184
 
156
185
  const jump = async (id: string, index: number): Promise<boolean> => {
@@ -62,6 +62,12 @@ export interface UseFileEditorResult {
62
62
  content: string;
63
63
  onChange: (next: string) => void;
64
64
  isLoading: boolean;
65
+ /**
66
+ * A re-read of a file already on screen is in flight — the manual
67
+ * "Reload from disk" or a workspace refresh. False for the first load, whose
68
+ * read `isLoading` already reports.
69
+ */
70
+ isReading: boolean;
65
71
  /**
66
72
  * The current file's bytes have arrived (or it is an image / carries inline
67
73
  * content). Distinguishes "the buffer is empty" from "the buffer is not read
@@ -80,6 +86,15 @@ export interface UseFileEditorResult {
80
86
  saveStatus: FileEditorSaveStatus;
81
87
  copied: boolean;
82
88
  isDirty: boolean;
89
+ /**
90
+ * Report unsaved edits in a BINARY document (a workbook the grid edited).
91
+ *
92
+ * The text buffer's dirty flag cannot describe them: a workbook has no text
93
+ * buffer, and its edits live in the viewer's draft. Without this the tab
94
+ * looked clean while a workbook held unsaved cells, so closing it discarded
95
+ * them without a word.
96
+ */
97
+ setBinaryDirty: (dirty: boolean) => void;
83
98
  /**
84
99
  * The ACTIVE buffer's own line ending, which the next save restores.
85
100
  *