@kabmo-labs/kabmo 0.24.0 → 0.25.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 (205) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +579 -510
  3. package/dist/client/static/js/index-bc9aa4mx.css +1 -0
  4. package/dist/client/static/js/{index-jcr5twtp.js → index-ga8cbpt4.js} +1072 -1174
  5. package/package.json +2 -4
  6. package/src/cli/lib/args.js +24 -1
  7. package/src/cli/lib/args.test.js +16 -0
  8. package/src/cli/lib/commands/session.js +233 -0
  9. package/src/cli/lib/commands/session.test.js +103 -0
  10. package/src/cli/main.js +1 -1
  11. package/src/client/components/common/ComposerPicker.tsx +3 -0
  12. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  13. package/src/client/components/common/code-surface/shiki.ts +28 -7
  14. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
  15. package/src/client/components/common/session-actions-menu/index.tsx +33 -2
  16. package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
  17. package/src/client/components/common/session-row/index.tsx +27 -1
  18. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  19. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
  20. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
  21. package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
  22. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +36 -5
  23. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
  24. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  25. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
  26. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
  27. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -35
  28. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
  29. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
  30. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
  31. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  32. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  33. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
  34. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  35. package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
  36. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  37. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  38. package/src/client/components/workspace/chat-timeline/index.tsx +3 -1
  39. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  40. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  41. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  42. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  43. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  44. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  45. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  46. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  47. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  48. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  49. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  50. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  51. package/src/client/data/settings/omp-schema.json +1 -1
  52. package/src/client/data/theme/terminal.test.ts +25 -0
  53. package/src/client/data/theme/terminal.ts +96 -79
  54. package/src/client/hooks/chat/composer/items.test.ts +12 -26
  55. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  56. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  57. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  58. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  59. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  60. package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
  61. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  62. package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
  63. package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
  64. package/src/client/hooks/chat/timeline/send.test.ts +3 -1
  65. package/src/client/hooks/chat/timeline/send.ts +51 -50
  66. package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
  67. package/src/client/hooks/models/use-harness-update.test.ts +193 -0
  68. package/src/client/hooks/models/use-harness-update.ts +202 -0
  69. package/src/client/hooks/workspace/child-expansion.ts +33 -0
  70. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  71. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  72. package/src/client/lib/session-tree.test.ts +50 -0
  73. package/src/client/lib/session-tree.ts +59 -0
  74. package/src/client/tailwind.css +17 -11
  75. package/src/server/index.ts +2 -0
  76. package/src/server/lib/auth/guard.ts +10 -0
  77. package/src/server/lib/btw/session-copy.server.ts +6 -44
  78. package/src/server/lib/btw/session-copy.test.ts +2 -1
  79. package/src/server/lib/db/schema.ts +4 -0
  80. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  81. package/src/server/lib/db/seed.test.ts +1 -1
  82. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  83. package/src/server/lib/harness/acp/background-work.ts +320 -0
  84. package/src/server/lib/harness/acp/client.ts +2 -2
  85. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  86. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  87. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  88. package/src/server/lib/harness/acp/prompt.ts +19 -3
  89. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  90. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  91. package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
  92. package/src/server/lib/harness/acp/session-handshake.ts +27 -1
  93. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  94. package/src/server/lib/harness/acp/session-requests.ts +47 -0
  95. package/src/server/lib/harness/acp/session-turns.ts +20 -5
  96. package/src/server/lib/harness/acp/session.test-util.ts +23 -1
  97. package/src/server/lib/harness/acp/session.ts +59 -59
  98. package/src/server/lib/harness/acp/turn.test.ts +81 -0
  99. package/src/server/lib/harness/acp/turn.ts +26 -9
  100. package/src/server/lib/harness/acp/verbs.ts +12 -2
  101. package/src/server/lib/harness/launch.ts +3 -1
  102. package/src/server/lib/harness/spawn.server.ts +15 -2
  103. package/src/server/lib/harness/update-job-store.test.ts +126 -0
  104. package/src/server/lib/harness/update-job-store.ts +109 -0
  105. package/src/server/lib/harness/update-job.server.ts +203 -0
  106. package/src/server/lib/harness/update-worker.test.ts +153 -0
  107. package/src/server/lib/harness/update-worker.ts +197 -0
  108. package/src/server/lib/lifecycle/paths.ts +23 -0
  109. package/src/server/lib/omp/rpc/manager.ts +5 -5
  110. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  111. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  112. package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
  113. package/src/server/lib/omp/session/delete-flow.server.ts +47 -0
  114. package/src/server/lib/omp/session/delete.server.ts +5 -0
  115. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  116. package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
  117. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  118. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  119. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  120. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  121. package/src/server/lib/sessions/answers.server.ts +37 -0
  122. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  123. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  124. package/src/server/lib/sessions/fork.server.test.ts +209 -0
  125. package/src/server/lib/sessions/fork.server.ts +304 -0
  126. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  127. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  128. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  129. package/src/server/lib/sessions/notify.server.ts +212 -0
  130. package/src/server/lib/sessions/relation-types.ts +76 -0
  131. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  132. package/src/server/lib/sessions/relations.server.ts +337 -0
  133. package/src/server/lib/sessions/resolve.server.ts +106 -0
  134. package/src/server/lib/sessions/schema.server.ts +82 -0
  135. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  136. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  137. package/src/server/lib/sessions/spawn.server.test.ts +196 -0
  138. package/src/server/lib/sessions/spawn.server.ts +310 -0
  139. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  140. package/src/server/lib/terminal/output.test.ts +2 -2
  141. package/src/server/lib/terminal/output.ts +1 -1
  142. package/src/server/lib/terminal/resize.test.ts +99 -0
  143. package/src/server/lib/terminal/runtime.server.ts +26 -6
  144. package/src/server/lib/terminal/send-result.test.ts +18 -1
  145. package/src/server/lib/terminal/send-result.ts +26 -2
  146. package/src/server/lib/terminal/session.server.ts +6 -6
  147. package/src/server/lib/usage/new-api.test.ts +92 -0
  148. package/src/server/lib/usage/new-api.ts +131 -0
  149. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  150. package/src/server/lib/usage/provider-key.ts +33 -0
  151. package/src/server/lib/usage/providers.server.ts +10 -3
  152. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  153. package/src/server/lib/usage/vendor-http.ts +41 -0
  154. package/src/server/lib/usage/window.ts +55 -0
  155. package/src/server/routes/agent/command.ts +14 -1
  156. package/src/server/routes/agent/harness-command.ts +6 -0
  157. package/src/server/routes/agent/new.ts +15 -0
  158. package/src/server/routes/harness/add-provider.test.ts +9 -1
  159. package/src/server/routes/harness/import-action.ts +4 -0
  160. package/src/server/routes/harness/import.test.ts +1 -1
  161. package/src/server/routes/harness/index.ts +5 -1
  162. package/src/server/routes/harness/update-status.ts +26 -0
  163. package/src/server/routes/harness/update.test.ts +119 -0
  164. package/src/server/routes/harness/update.ts +59 -147
  165. package/src/server/routes/sessions/answer.ts +24 -0
  166. package/src/server/routes/sessions/batch-delete.ts +11 -5
  167. package/src/server/routes/sessions/delete.ts +4 -2
  168. package/src/server/routes/sessions/fork.ts +74 -0
  169. package/src/server/routes/sessions/index.ts +14 -0
  170. package/src/server/routes/sessions/relations.ts +85 -0
  171. package/src/server/routes/sessions/session.ts +4 -0
  172. package/src/server/routes/sessions/spawn.ts +134 -0
  173. package/src/server/routes/terminal/ws.ts +3 -3
  174. package/src/shared/lib/chat/composer/client.ts +31 -2
  175. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  176. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  177. package/src/shared/lib/chat/notice-text.ts +1 -1
  178. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  179. package/src/shared/lib/code/ansi.ts +1 -1
  180. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  181. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  182. package/src/shared/lib/harness/provider-facts.test.ts +27 -0
  183. package/src/shared/lib/harness/providers.ts +35 -1
  184. package/src/shared/lib/harness/update-job.ts +33 -0
  185. package/src/shared/lib/harness/update-plan.test.ts +21 -6
  186. package/src/shared/lib/harness/update-plan.ts +12 -4
  187. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  188. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  189. package/src/shared/lib/theme/catalog.test.ts +13 -9
  190. package/src/shared/lib/theme/color.test.ts +2 -2
  191. package/src/shared/lib/theme/color.ts +4 -4
  192. package/src/shared/lib/theme/theme.test.ts +1 -1
  193. package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
  194. package/src/shared/lib/workspace/terminal/input.ts +33 -0
  195. package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
  196. package/src/shared/lib/workspace/terminal/keys.ts +7 -7
  197. package/src/shared/types/chat.ts +1 -1
  198. package/src/shared/types/harness-update.ts +65 -0
  199. package/src/shared/types/omp/agent.ts +19 -2
  200. package/src/shared/types/workspace.ts +4 -0
  201. package/src/test-support/fake-omp-fork.ts +16 -2
  202. package/src/test-support/harness-table.test-util.ts +15 -1
  203. package/dist/client/static/js/index-z3w7n85q.css +0 -1
  204. package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
  205. package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
@@ -4,26 +4,43 @@
4
4
  */
5
5
 
6
6
  /**
7
- * Prompt assembly for Kabmo composer: rewrite composer-level mentions
8
- * into what oh-my-pi actually receives, then inline the text attachments the
9
- * user dropped in. Extracted from the send path so that hook stays under the
10
- * repo's per-file size ceiling.
7
+ * Prompt assembly for Kabmo composer: rewrite composer-level mentions into what
8
+ * the agent actually receives, then inline the text attachments the user
9
+ * dropped in. Extracted from the send path so that hook stays under the repo's
10
+ * per-file size ceiling.
11
11
  */
12
12
 
13
13
  import { composeMessageWithTextAttachments } from '@/shared/lib/chat/attachments';
14
14
  import { loadAgentNames } from '@/shared/lib/chat/composer/client';
15
+ import {
16
+ delegationErrorText,
17
+ formatDelegationPrompt,
18
+ parseHarnessMentions,
19
+ } from '@/shared/lib/chat/composer/delegation';
15
20
  import { translateAgentMentions, translateFileMentions } from '@/shared/lib/chat/composer/translate';
16
21
 
17
22
  type TextFileAttachment = Parameters<typeof composeMessageWithTextAttachments>[1][number];
18
23
 
24
+ /** A mention the composer cannot send, with the sentence the user needs. */
25
+ export class DelegationPromptError extends Error {
26
+ constructor(readonly reason: string) {
27
+ super(reason);
28
+ this.name = 'DelegationPromptError';
29
+ }
30
+ }
31
+
19
32
  /**
20
- * Build the outgoing prompt. `@agent` mentions are rewritten into an explicit
21
- * task-tool delegation directive at send time (oh-my-pi has no `@agent`
22
- * syntax); translation failures fall back to the raw prompt.
33
+ * Build the outgoing prompt.
23
34
  *
24
- * A file whose bytes could not be read is left OUT rather than inlined empty:
25
- * an empty fenced block tells the model the file exists and says nothing, which
26
- * is worse than not mentioning it. The composer reports the omission.
35
+ * `@harness` mentions are compiled into an orchestrator contract plus one exact
36
+ * `kabmo session spawn` command per worker; the paragraph's own words become
37
+ * that worker's TASK. A bare `@claude` carries no model, so the spawn uses the
38
+ * harness's configured default (or the agent's own).
39
+ *
40
+ * `@agent` mentions are omp's subagent syntax and are rewritten only for the
41
+ * harnesses that have it. A file whose bytes could not be read is left OUT
42
+ * rather than inlined empty: an empty fenced block tells the model the file
43
+ * exists and says nothing, which is worse than not mentioning it.
27
44
  */
28
45
  export async function buildPromptText(
29
46
  text: string,
@@ -31,16 +48,26 @@ export async function buildPromptText(
31
48
  options: { includeAgents?: boolean } = {},
32
49
  ): Promise<string> {
33
50
  const readable = textFiles.filter((file) => !('missing' in file && file.missing));
34
- let translated = text;
35
- // `@agent` is omp's subagent syntax and the rewrite names omp's `task` tool.
36
- // An ACP agent has neither, so the mention is left as the user typed it
37
- // rather than turned into an instruction it cannot follow.
38
- if (options.includeAgents !== false) {
39
- try {
40
- const names = await loadAgentNames();
41
- if (names.length > 0) translated = translateAgentMentions(text, names).text;
42
- } catch {
43
- // keep the raw prompt
51
+ const names = options.includeAgents === false
52
+ ? []
53
+ : await loadAgentNames().catch(() => []);
54
+ const plan = parseHarnessMentions(text, { agentNames: names });
55
+ const refusal = delegationErrorText(plan);
56
+ if (refusal) throw new DelegationPromptError(refusal);
57
+
58
+ let translated: string;
59
+ if (plan.delegations.length > 0) {
60
+ // The orchestrator's own paragraphs still get omp's agent rewrite; a
61
+ // worker task does not, because that text is read by a different harness
62
+ // and `task` is not its vocabulary.
63
+ if (options.includeAgents !== false && names.length > 0) {
64
+ plan.orchestratorText = translateAgentMentions(plan.orchestratorText, names).text;
65
+ }
66
+ translated = formatDelegationPrompt(plan);
67
+ } else {
68
+ translated = text;
69
+ if (options.includeAgents !== false && names.length > 0) {
70
+ translated = translateAgentMentions(translated, names).text;
44
71
  }
45
72
  }
46
73
  // File mentions are namespaced (`@file:`) by the picker; strip the namespace
@@ -142,6 +142,45 @@ describe('executeSend', () => {
142
142
  expect(h1.params).toEqual(['sessionId=uuid-9']);
143
143
  });
144
144
 
145
+ test('a failed spawn reports the server reason and never simulates a reply', async () => {
146
+ const h1 = makeSendHarness({
147
+ isOmpSession: false,
148
+ sessionId: 'new-1',
149
+ folders: [{ id: 4, name: 'demo', project_path: '/tmp/demo' }],
150
+ selectedFolderId: 4,
151
+ agent: { spawnResult: null, spawnError: 'Cannot start dsh: deepseek-harness refused model "m"' },
152
+ });
153
+ await act(async () => {
154
+ const result = await h1.sends.executeSend('first prompt', []);
155
+ expect(result.ok).toBe(false);
156
+ expect(result.error).toContain('deepseek-harness refused model');
157
+ });
158
+ // Nothing may be left on screen for a turn the agent never took, and the
159
+ // failure may not fall through to the simulated stream — that is what made
160
+ // a refused ACP spawn look like a slow chat that then "answered".
161
+ expect(h1.state.messages).toEqual([]);
162
+ expect(h1.reported).toEqual(['Prompt not sent: Cannot start dsh: deepseek-harness refused model "m"']);
163
+ expect(h1.generating).toEqual([true, false]);
164
+ });
165
+
166
+ test('mock mode falls through to the simulated stream instead of reporting', async () => {
167
+ // Mock has no agent process BY DESIGN, so there is no failure to report —
168
+ // the demo shell answers from the simulated stream. Measured on the CI E2E
169
+ // legs: `POST /api/agent/new` answered 400 (no `omp` on the runner) and the
170
+ // landing composer did nothing at all, so no chat ever opened.
171
+ const h1 = makeSendHarness({
172
+ isOmpSession: false,
173
+ sessionId: 'new-1',
174
+ folders: [{ id: 4, name: 'demo', project_path: '/tmp/demo' }],
175
+ selectedFolderId: 4,
176
+ agent: { spawnResult: null, spawnError: 'Mock mode runs no agent process', spawnCode: 'mock_mode' },
177
+ });
178
+ await act(async () => {
179
+ await h1.sends.executeSend('first prompt', []);
180
+ });
181
+ expect(h1.reported).not.toContainEqual(expect.stringContaining('Prompt not sent'));
182
+ });
183
+
145
184
  test('a harness picked on the pending view rides the spawn body', async () => {
146
185
  const h1 = makeSendHarness({
147
186
  isOmpSession: false,
@@ -12,8 +12,9 @@
12
12
  import type { Dispatch, SetStateAction } from 'preact/compat';
13
13
  import type { AgentImage, Attachment, ChatMessageData, PromptDispatchResult } from '@/shared/types';
14
14
  import { streamChatResponse } from '@/client/hooks/chat/stream';
15
+ import { buildPromptText } from '@/client/hooks/chat/timeline/prompt-text';
15
16
  import { createMockStreamCallbacks } from '@/shared/lib/chat/timeline/stream-callbacks';
16
- import { attachmentImage, attachmentName, attachmentSize, attachmentType } from '@/shared/lib/chat/attachments';
17
+ import { readTextAttachments, attachmentImage, attachmentName, attachmentSize, attachmentType, type ReadTextAttachment } from '@/shared/lib/chat/attachments';
17
18
 
18
19
  /** The image payload of a delivery: the attachments that carry real bytes. A
19
20
  * replayed attachment has no live `File`, so it is dropped unless the data
@@ -62,6 +63,34 @@ export function buildOptimisticRows(args: {
62
63
  };
63
64
  }
64
65
 
66
+ /** What the send path needs from a prompt, before it decides which transport runs it. */
67
+ export type PromptAssembly =
68
+ | { ok: true; textFiles: ReadTextAttachment[]; promptText: string }
69
+ | { ok: false; error: string };
70
+
71
+ /**
72
+ * Read attachments and assemble the outgoing prompt once.
73
+ *
74
+ * A delegation refusal (two harnesses in one paragraph, an unknown harness, an
75
+ * empty task) is a send-time failure, not a prompt to send anyway: the caller
76
+ * reports it before any optimistic bubble exists.
77
+ */
78
+ export async function assemblePrompt(
79
+ text: string,
80
+ attachments: Attachment[],
81
+ includeAgents: boolean,
82
+ ): Promise<PromptAssembly> {
83
+ const textFiles = await readTextAttachments(attachments);
84
+ try {
85
+ return { ok: true, textFiles, promptText: await buildPromptText(text, textFiles, { includeAgents }) };
86
+ } catch (error) {
87
+ return {
88
+ ok: false,
89
+ error: error instanceof Error ? error.message : 'Prompt could not be assembled',
90
+ };
91
+ }
92
+ }
93
+
65
94
  /** The simulated SSE path, taken by a Kabmo-created session and as the
66
95
  * fallback when a real spawn is impossible (MOCK mode, no workspace cwd). */
67
96
  export async function streamMockFallback(args: {
@@ -99,7 +99,9 @@ function makeAgent(overrides: Partial<AgentCalls> = {}): AgentRecorder {
99
99
  },
100
100
  sendNewPrompt: async (text: string, cwd: string, _images: unknown, options: unknown) => {
101
101
  calls.newPrompts.push({ text, cwd, options });
102
- return calls.spawnResult;
102
+ return calls.spawnResult
103
+ ? { ok: true as const, session: calls.spawnResult }
104
+ : { ok: false as const, error: 'spawn failed' };
103
105
  },
104
106
  steerOmpRun: async (text: string, images: unknown) => {
105
107
  calls.steers.push({ text, images });
@@ -130,6 +130,10 @@ export interface AgentCalls {
130
130
  sendPromptBusy: boolean;
131
131
  /** The server-supplied reason, when the send was refused. */
132
132
  sendPromptError: string | undefined;
133
+ /** The reason a fresh spawn failed, when `spawnResult` is null. */
134
+ spawnError?: string;
135
+ /** The server's discriminator, e.g. `mock_mode`. */
136
+ spawnCode?: string;
133
137
  spawnResult: { sessionId: string; model?: { provider: string; modelId: string }; harness?: string } | null;
134
138
  }
135
139
 
@@ -158,7 +162,9 @@ export function makeAgent(overrides: Partial<AgentCalls> = {}): AgentRecorder {
158
162
  },
159
163
  sendNewPrompt: async (text: string, cwd: string, _images: unknown, options: unknown) => {
160
164
  calls.newPrompts.push({ text, cwd, options });
161
- return calls.spawnResult;
165
+ return calls.spawnResult
166
+ ? { ok: true as const, session: calls.spawnResult }
167
+ : { ok: false as const, error: calls.spawnError ?? 'spawn failed', ...(calls.spawnCode ? { code: calls.spawnCode } : {}) };
162
168
  },
163
169
  steerOmpRun: async (text: string, images: unknown) => {
164
170
  calls.interrupts.push({ text, images });
@@ -99,7 +99,9 @@ function makeAgent(overrides: Partial<AgentCalls> = {}): AgentRecorder {
99
99
  },
100
100
  sendNewPrompt: async (text: string, cwd: string, _images: unknown, options: unknown) => {
101
101
  calls.newPrompts.push({ text, cwd, options });
102
- return calls.spawnResult;
102
+ return calls.spawnResult
103
+ ? { ok: true as const, session: calls.spawnResult }
104
+ : { ok: false as const, error: 'spawn failed' };
103
105
  },
104
106
  steerOmpRun: async (text: string, images: unknown) => {
105
107
  calls.interrupts.push({ text, images });
@@ -15,10 +15,8 @@ import type { ChatTimelineSendDeps, ChatTimelineSendResult } from '@/client/hook
15
15
 
16
16
  export type { ChatTimelineSendDeps, ChatTimelineSendResult };
17
17
  import type { AgentImage, Attachment, PromptDispatchResult, QueuedMessageModel } from '@/shared/types';
18
- import { buildPromptText } from '@/client/hooks/chat/timeline/prompt-text';
19
18
  import { flushDeferredPick } from '@/client/hooks/chat/timeline/deferred-model';
20
- import { readTextAttachments } from '@/shared/lib/chat/attachments';
21
- import { buildOptimisticRows, collectImages, streamMockFallback } from '@/client/hooks/chat/timeline/send-helpers';
19
+ import { buildOptimisticRows, collectImages, assemblePrompt, streamMockFallback } from '@/client/hooks/chat/timeline/send-helpers';
22
20
  import { adoptPendingSession, markPendingSessionSent } from '@/client/hooks/chat/omp/pending-sessions';
23
21
  import { recordSpawnHarness } from '@/client/hooks/chat/timeline/spawn-harness';
24
22
  import { postModeCommand } from '@/client/hooks/chat/timeline/mode-post';
@@ -67,24 +65,10 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
67
65
  const includeAgents = !harness || harness === 'omp-rpc' || harness === 'omp-acp';
68
66
 
69
67
  /**
70
- * Start the armed goal in `sessionId`, from the operator's own prompt.
71
- *
72
- * Awaited BEFORE the prompt leaves, so the order is a fact. Resolves TRUE when
73
- * the goal consumed the prompt — the caller must then not send it again.
74
- *
75
- * - `create` — the record is written with `startTurn: false`, and the prompt
76
- * that follows is the goal's first turn. The prompt is still sent.
77
- * - `guided` — there is no objective yet (the model writes it at the end of
78
- * the interview), so the operator's message IS the interview's opening
79
- * turn: the extension renders its kickoff prompt with their words folded
80
- * in (`<rough-goal>`) and runs that as turn one. The raw message is
81
- * therefore NOT sent separately — it is already inside that turn.
82
- *
83
- * A refusal is reported rather than swallowed, and the prompt still goes out
84
- * for `create`: the goal the operator set is missing, but their words are not
85
- * the goal's business. A refused `guided` cannot fall back the same way — the
86
- * interview kickoff is the extension's text — so it resolves false and the
87
- * caller sends the message as an ordinary prompt.
68
+ * Start the armed goal before the prompt leaves. `guided` folds the operator's
69
+ * words into the interview's opening turn (the caller must not send it again);
70
+ * `create` writes the record and lets the prompt be its first turn. A refusal
71
+ * is reported, and the prompt still goes out for `create`.
88
72
  */
89
73
  const startArmedGoal = useCallback(async (targetId: string, armed: ArmedGoal, promptText: string): Promise<boolean> => {
90
74
  const posted = armed.kind === 'guided'
@@ -114,11 +98,11 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
114
98
  text: string,
115
99
  attachments: Attachment[],
116
100
  ): Promise<{ promptText: string; images?: AgentImage[] }> => {
117
- const textFiles = await readTextAttachments(attachments);
118
- const promptText = await buildPromptText(text, textFiles, { includeAgents });
119
- pendingUserDisplaysRef.current = [...pendingUserDisplaysRef.current.slice(-7), { sent: promptText, display: text }];
120
- return { promptText, images: collectImages(attachments) };
121
- }, [includeAgents]);
101
+ const assembled = await assemblePrompt(text, attachments, includeAgents);
102
+ if (!assembled.ok) throw new Error(assembled.error);
103
+ pendingUserDisplaysRef.current = [...pendingUserDisplaysRef.current.slice(-7), { sent: assembled.promptText, display: text }];
104
+ return { promptText: assembled.promptText, images: collectImages(attachments) };
105
+ }, [includeAgents, pendingUserDisplaysRef]);
122
106
 
123
107
  // Steer the running omp agent (interrupt-and-reply). Returns the outcome so
124
108
  // the caller can report a refusal: the composer is cleared before this runs.
@@ -126,11 +110,19 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
126
110
  // A steer IS a new prompt: a pick made during the interrupted turn belongs
127
111
  // to it, so it is pushed before the interrupt-and-reply starts the turn.
128
112
  await flushDeferredPick(ompAgent, deferredComposerPickRef);
129
- const { promptText, images } = await prepareDeliverable(text, attachments);
130
- const result = await ompAgent.steerOmpRun(promptText, images);
113
+ let deliverable: { promptText: string; images?: AgentImage[] };
114
+ try {
115
+ deliverable = await prepareDeliverable(text, attachments);
116
+ } catch (error) {
117
+ const message = error instanceof Error ? error.message : String(error);
118
+ reportActionError(message);
119
+ setInputValue(text);
120
+ return { ok: false, busy: false, error: message };
121
+ }
122
+ const result = await ompAgent.steerOmpRun(deliverable.promptText, deliverable.images);
131
123
  if (!result.ok) setInputValue(text);
132
124
  return result;
133
- }, [ompAgent, prepareDeliverable, setInputValue, deferredComposerPickRef]);
125
+ }, [ompAgent, prepareDeliverable, setInputValue, deferredComposerPickRef, reportActionError]);
134
126
 
135
127
  const executeSend = useCallback(async (
136
128
  text: string,
@@ -151,12 +143,15 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
151
143
  const userMsgId = `msg-${Date.now()}-user`;
152
144
  const aiPlaceholderId = `msg-${Date.now() + 1}-ai`;
153
145
 
154
- // Read text-file contents once: used for the editor (attachment.content)
155
- // and for inlining into the prompt. Reads a persisted `content` when the
156
- // attachment is a replay (queue delivery, retry) and has no live File.
157
- const textFiles = await readTextAttachments(attachments);
146
+ // A delegation refusal (two harnesses in one paragraph, an unknown
147
+ // harness, an empty task) must land before any optimistic bubble exists.
148
+ const assembled = await assemblePrompt(text, attachments, includeAgents);
149
+ if (!assembled.ok) {
150
+ reportActionError(assembled.error);
151
+ return { ok: false, busy: false, error: assembled.error };
152
+ }
153
+ const { textFiles, promptText } = assembled;
158
154
  const textContentById = new Map(textFiles.map((file) => [file.id, file.content]));
159
-
160
155
  const now = Date.now();
161
156
  const { newUserMsg, initialAiMsg } = buildOptimisticRows({
162
157
  text,
@@ -214,13 +209,7 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
214
209
  }
215
210
  }
216
211
  const images = collectImages(attachments);
217
- // Inline text-file contents into the prompt: the model sees the full file
218
- // content as fenced blocks, not just the filename.
219
- const promptText = await buildPromptText(text, textFiles, { includeAgents });
220
- // The armed goal is created HERE, at the fence of the prompt that will be
221
- // its first turn — never earlier (nothing to act on) and never after the
222
- // prompt (the goal would miss its opening turn). An armed INTERVIEW
223
- // consumes this prompt as its kickoff, so nothing is sent after it.
212
+ // `promptText` was assembled once above, so no refusal can reach here.
224
213
  const armed = goalArmRef.current;
225
214
  const consumed = armed && sessionId ? await startArmedGoal(sessionId, armed, promptText) : false;
226
215
  if (consumed) return { ok: true, busy: false };
@@ -250,7 +239,6 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
250
239
  const cwd = spawnWorktreeRef.current || currentFolder?.project_path || currentFolder?.name;
251
240
  if (cwd) {
252
241
  const images = collectImages(attachments);
253
- const promptText = await buildPromptText(text, textFiles, { includeAgents });
254
242
  optimisticUserIdRef.current = userMsgId;
255
243
  const composerModel = pendingComposerModelRef.current;
256
244
  const composerThinking = pendingThinkingLevelRef.current;
@@ -283,20 +271,21 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
283
271
  },
284
272
  armed ? (id) => startArmedGoal(id, armed, promptText) : undefined,
285
273
  );
286
- if (spawned) {
274
+ if (spawned.ok) {
275
+ const { session } = spawned;
287
276
  // The harness the SERVER answered with: `new.ts` reports it for an ACP
288
277
  // spawn and omits it for the RPC branch, which means omp. Read rather
289
278
  // than replayed from the request, so a pick the server did not honour
290
279
  // cannot be reported as the agent running the chat.
291
- recordSpawnHarness(spawned.sessionId, spawned.harness ?? 'omp-rpc');
280
+ recordSpawnHarness(session.sessionId, session.harness ?? 'omp-rpc');
292
281
  spawnSelectionRef.current = null;
293
- adoptedSessionIdRef.current = spawned.sessionId;
282
+ adoptedSessionIdRef.current = session.sessionId;
294
283
  // The sidebar's row moves with the id: `new-…` was the client's own
295
284
  // placeholder, and the spawn answers with omp's real one, which omp
296
285
  // has still not written a transcript for. Without this the row
297
286
  // vanished at exactly the moment the URL stopped naming the pending
298
287
  // id, which is the gap this store exists to close.
299
- adoptPendingSession(sessionId, spawned.sessionId, currentFolder?.id ?? null);
288
+ adoptPendingSession(sessionId, session.sessionId, currentFolder?.id ?? null);
300
289
  // The placeholder ref is already armed (with its row) before the
301
290
  // spawn — see the note at the assignment; re-arming here would be
302
291
  // harmless but is redundant.
@@ -304,18 +293,18 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
304
293
  // composer taking over from the pending view reports the run's real
305
294
  // setting instead of a catalog default (the JSONL that carries it is
306
295
  // not locatable yet).
307
- seedSession({ model: spawned.model, thinkingLevel: composerThinking });
296
+ seedSession({ model: session.model, thinkingLevel: composerThinking });
308
297
  pendingComposerModelRef.current = null;
309
298
  pendingThinkingLevelRef.current = null;
310
299
  pendingHarnessRef.current = null;
311
- fetch(`/api/chat/${encodeURIComponent(spawned.sessionId)}`, {
300
+ fetch(`/api/chat/${encodeURIComponent(session.sessionId)}`, {
312
301
  method: 'POST',
313
302
  headers: { 'Content-Type': 'application/json' },
314
303
  body: JSON.stringify({ messages: [newUserMsg] }),
315
304
  }).catch(err => console.error('Error persisting spawned user turn:', err));
316
305
  setSearchParams(prev => {
317
306
  const next = new URLSearchParams(prev);
318
- next.set('sessionId', spawned.sessionId);
307
+ next.set('sessionId', session.sessionId);
319
308
  return next;
320
309
  }, { replace: true });
321
310
  // The sidebar already re-read at prompt dispatch (sendNewPrompt
@@ -323,6 +312,18 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
323
312
  // waiting for the JSONL to carry the user turn.
324
313
  return { ok: true, busy: false };
325
314
  }
315
+ // `mock_mode` is not a failure — mock has no agent process BY DESIGN, so
316
+ // the demo shell answers from the simulated stream below.
317
+ if (spawned.code !== 'mock_mode') {
318
+ // A real spawn failure REPORTS: falling through here once made a failed
319
+ // ACP spawn look like a slow chat that then "answered".
320
+ setLocalMessages(prev => prev.filter(m => m.id !== userMsgId && m.id !== aiPlaceholderId));
321
+ aiPlaceholderIdRef.current = null;
322
+ optimisticUserIdRef.current = null;
323
+ setGenerating(false);
324
+ reportActionError(`Prompt not sent: ${spawned.error}`);
325
+ return { ok: false, busy: false, error: spawned.error };
326
+ }
326
327
  }
327
328
  }
328
329
 
@@ -343,6 +344,6 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
343
344
  setGeneratingVerb,
344
345
  scrollToBottom,
345
346
  });
346
- }, [appSettings, folders, isOmpSession, harness, ompAgent, selectedFolderId, sessionId, scrollToBottom, jumpToBottom, persistMessages, seedSession, pendingComposerModelRef, pendingThinkingLevelRef, deferredComposerPickRef, accessModeRef, setLocalMessages]);
347
+ }, [appSettings, folders, isOmpSession, harness, ompAgent, selectedFolderId, sessionId, scrollToBottom, jumpToBottom, persistMessages, seedSession, pendingComposerModelRef, pendingThinkingLevelRef, deferredComposerPickRef, accessModeRef, setLocalMessages, reportActionError]);
347
348
  return { steerOmpAgent, executeSend };
348
349
  }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Fork the current chat at a clicked row.
8
+ *
9
+ * The API call and the navigation live together because the refusal has to be
10
+ * shown where the action was taken. The server answers a typed code and a
11
+ * message; the hook surfaces the message and never navigates on a failure —
12
+ * a silent tip fork would be worse than the error.
13
+ */
14
+
15
+ import { useCallback } from 'preact/hooks';
16
+
17
+ type ToastKind = 'success' | 'error';
18
+
19
+ export function useForkSession(
20
+ sessionId: string | null | undefined,
21
+ pushToast: (message: string, type?: ToastKind) => void,
22
+ ): (messageId: string) => Promise<void> {
23
+ return useCallback(
24
+ async (messageId: string) => {
25
+ if (!sessionId) return;
26
+ try {
27
+ const response = await fetch(`/api/sessions/${encodeURIComponent(sessionId)}/fork`, {
28
+ method: 'POST',
29
+ headers: { 'content-type': 'application/json' },
30
+ body: JSON.stringify({ anchorEntryId: messageId }),
31
+ });
32
+ const body = (await response.json().catch(() => null)) as
33
+ | { sessionId?: string; error?: string }
34
+ | null;
35
+ if (!response.ok || !body?.sessionId) {
36
+ pushToast(body?.error ?? 'Could not fork this session.', 'error');
37
+ return;
38
+ }
39
+ // A full navigation is deliberate: the fork is a different session with
40
+ // its own transcript, and the workspace's session param is the source of
41
+ // truth the sidebar and the composer read on mount.
42
+ window.location.assign(`/?sessionId=${encodeURIComponent(body.sessionId)}`);
43
+ } catch {
44
+ pushToast('Could not fork this session.', 'error');
45
+ }
46
+ },
47
+ [sessionId, pushToast],
48
+ );
49
+ }