@kabmo-labs/kabmo 0.25.0 → 0.26.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 (188) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +440 -436
  3. package/dist/client/static/js/{index-ga8cbpt4.js → index-95b3n20k.js} +945 -945
  4. package/dist/client/static/js/index-p2yw9ywf.css +1 -0
  5. package/package.json +1 -1
  6. package/src/client/components/common/session-actions-menu/index.tsx +38 -12
  7. package/src/client/components/common/session-branch/BranchGuides.tsx +93 -0
  8. package/src/client/components/common/session-branch/SubagentRow.tsx +77 -0
  9. package/src/client/components/common/session-branch/index.tsx +169 -0
  10. package/src/client/components/common/session-branch/session-branch.test.tsx +240 -0
  11. package/src/client/components/common/session-branch/style.ts +29 -0
  12. package/src/client/components/common/session-row/StatusSlot.tsx +15 -3
  13. package/src/client/components/common/session-row/index.tsx +24 -25
  14. package/src/client/components/common/session-row/session-row.test.tsx +11 -0
  15. package/src/client/components/common/session-state-provider/index.tsx +1 -1
  16. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +64 -68
  17. package/src/client/components/layout/session-sidebar/SessionItem.batch.test.ts +3 -3
  18. package/src/client/components/layout/session-sidebar/SessionItem.test.ts +25 -2
  19. package/src/client/components/layout/session-sidebar/SessionItem.tsx +33 -30
  20. package/src/client/components/layout/session-sidebar/about-modal/HarnessRow.tsx +261 -0
  21. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +35 -225
  22. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +36 -16
  23. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +11 -3
  24. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +13 -4
  25. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -13
  26. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +59 -57
  27. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +57 -61
  28. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.test.ts +5 -0
  29. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +33 -30
  30. package/src/client/components/settings/Sidebar.tsx +1 -1
  31. package/src/client/components/settings/categories/NotificationSettings.test.tsx +92 -0
  32. package/src/client/components/settings/categories/NotificationSettings.tsx +112 -2
  33. package/src/client/components/settings/categories/harness-settings/HarnessCard.tsx +1 -1
  34. package/src/client/components/workspace/chat-timeline/AiMessageFooter.fork.test.ts +94 -0
  35. package/src/client/components/workspace/chat-timeline/AiMessageFooter.tsx +31 -5
  36. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +28 -39
  37. package/src/client/components/workspace/chat-timeline/MessageList.tsx +7 -5
  38. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +10 -0
  39. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +12 -3
  40. package/src/client/components/workspace/chat-timeline/chat-input/AttachmentToolbar.tsx +2 -0
  41. package/src/client/components/workspace/chat-timeline/chat-input/ModeToggles.tsx +15 -1
  42. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.test.tsx +85 -0
  43. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.tsx +84 -0
  44. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +2 -0
  45. package/src/client/components/workspace/chat-timeline/chat-input/modes-props.ts +5 -0
  46. package/src/client/components/workspace/chat-timeline/index.tsx +10 -21
  47. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +115 -0
  48. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +173 -0
  49. package/src/client/components/workspace/chat-timeline/target-picker/parent-session-options.test.ts +49 -0
  50. package/src/client/hooks/chat/composer/items.test.ts +19 -0
  51. package/src/client/hooks/chat/omp/folder-auto-expand.ts +1 -1
  52. package/src/client/hooks/chat/omp/pending-adoption.ts +51 -0
  53. package/src/client/hooks/chat/omp/pending-child.test.ts +73 -0
  54. package/src/client/hooks/chat/omp/pending-entry.ts +59 -0
  55. package/src/client/hooks/chat/omp/pending-rows.ts +6 -2
  56. package/src/client/hooks/chat/omp/pending-sessions.test.ts +1 -2
  57. package/src/client/hooks/chat/omp/pending-sessions.ts +45 -69
  58. package/src/client/hooks/chat/omp/pending-waiting.ts +1 -1
  59. package/src/client/hooks/chat/omp/run-switch.ts +1 -1
  60. package/src/client/hooks/chat/omp/session-list.tsx +4 -0
  61. package/src/client/hooks/chat/subagents/roster.ts +122 -0
  62. package/src/client/hooks/chat/timeline/child-spawn.test.ts +55 -0
  63. package/src/client/hooks/chat/timeline/child-spawn.ts +45 -0
  64. package/src/client/hooks/chat/timeline/fork-request.test.ts +54 -0
  65. package/src/client/hooks/chat/timeline/fork-request.ts +43 -0
  66. package/src/client/hooks/chat/timeline/mode-availability.test.ts +1 -1
  67. package/src/client/hooks/chat/timeline/mode-availability.ts +33 -0
  68. package/src/client/hooks/chat/timeline/mode-markers.ts +7 -1
  69. package/src/client/hooks/chat/timeline/mode-post.ts +15 -3
  70. package/src/client/hooks/chat/timeline/modes-contract.ts +9 -4
  71. package/src/client/hooks/chat/timeline/modes.test.ts +56 -18
  72. package/src/client/hooks/chat/timeline/modes.ts +42 -29
  73. package/src/client/hooks/chat/timeline/pending-branch.ts +205 -0
  74. package/src/client/hooks/chat/timeline/pending-dispatch.ts +253 -0
  75. package/src/client/hooks/chat/timeline/send.ts +17 -103
  76. package/src/client/hooks/chat/timeline/session-harness.ts +6 -0
  77. package/src/client/hooks/chat/timeline/stop-with-queue.ts +42 -0
  78. package/src/client/hooks/chat/timeline/use-fork-session.ts +40 -31
  79. package/src/client/hooks/models/use-harness-update.test.ts +137 -44
  80. package/src/client/hooks/models/use-harness-update.ts +133 -85
  81. package/src/client/hooks/ui/input-required-alert.ts +12 -5
  82. package/src/client/hooks/ui/notifications.ts +45 -0
  83. package/src/client/hooks/ui/run-outcome-alert.ts +48 -0
  84. package/src/client/hooks/workspace/expanded-sessions.ts +36 -7
  85. package/src/client/lib/native/open-session.ts +33 -0
  86. package/src/client/lib/notifications/os.test.ts +125 -0
  87. package/src/client/lib/notifications/os.ts +130 -0
  88. package/src/client/lib/plugins/sidebar-bridge.ts +2 -20
  89. package/src/client/lib/router/open-session.test.ts +75 -0
  90. package/src/client/lib/router/open-session.ts +34 -0
  91. package/src/client/lib/signals.ts +5 -1
  92. package/src/client/main.tsx +6 -0
  93. package/src/server/lib/db/schema.ts +1 -0
  94. package/src/server/lib/harness/acp/calls.ts +15 -1
  95. package/src/server/lib/harness/acp/client-capabilities.test.ts +55 -0
  96. package/src/server/lib/harness/acp/client-capabilities.ts +61 -0
  97. package/src/server/lib/harness/acp/client-fs.test.ts +135 -0
  98. package/src/server/lib/harness/acp/client-fs.ts +131 -0
  99. package/src/server/lib/harness/acp/client-initialize.test.ts +70 -0
  100. package/src/server/lib/harness/acp/client-initialize.ts +84 -0
  101. package/src/server/lib/harness/acp/client.ts +31 -21
  102. package/src/server/lib/harness/acp/commands.test.ts +5 -5
  103. package/src/server/lib/harness/acp/commands.ts +14 -2
  104. package/src/server/lib/harness/acp/frames-timing.test.ts +68 -0
  105. package/src/server/lib/harness/acp/frames-v2.test.ts +85 -0
  106. package/src/server/lib/harness/acp/frames.ts +71 -158
  107. package/src/server/lib/harness/acp/mapper.test.ts +40 -0
  108. package/src/server/lib/harness/acp/mapper.ts +12 -0
  109. package/src/server/lib/harness/acp/permissions.ts +6 -0
  110. package/src/server/lib/harness/acp/protocol.ts +41 -2
  111. package/src/server/lib/harness/acp/session-facts.ts +1 -1
  112. package/src/server/lib/harness/acp/session-handshake.test.ts +90 -1
  113. package/src/server/lib/harness/acp/session-handshake.ts +83 -6
  114. package/src/server/lib/harness/acp/session-idle.ts +7 -6
  115. package/src/server/lib/harness/acp/session-notifications.ts +41 -2
  116. package/src/server/lib/harness/acp/session-observers.test.ts +63 -0
  117. package/src/server/lib/harness/acp/session-permissions.test.ts +29 -0
  118. package/src/server/lib/harness/acp/session-permissions.ts +36 -0
  119. package/src/server/lib/harness/acp/session-requests.test.ts +92 -0
  120. package/src/server/lib/harness/acp/session-requests.ts +48 -6
  121. package/src/server/lib/harness/acp/session-turns.ts +8 -3
  122. package/src/server/lib/harness/acp/session-usage.ts +4 -0
  123. package/src/server/lib/harness/acp/session-web-state.ts +30 -2
  124. package/src/server/lib/harness/acp/session.test-util.ts +19 -1
  125. package/src/server/lib/harness/acp/session.ts +60 -60
  126. package/src/server/lib/harness/acp/tool-calls.ts +223 -0
  127. package/src/server/lib/harness/acp/turn.test.ts +102 -0
  128. package/src/server/lib/harness/acp/turn.ts +81 -6
  129. package/src/server/lib/harness/acp/v2.test.ts +144 -0
  130. package/src/server/lib/harness/acp/v2.ts +220 -0
  131. package/src/server/lib/harness/acp/verbs.ts +46 -6
  132. package/src/server/lib/harness/launch.test.ts +25 -0
  133. package/src/server/lib/harness/launch.ts +21 -9
  134. package/src/server/lib/harness/session.ts +3 -0
  135. package/src/server/lib/harness/update-job-store.test.ts +37 -12
  136. package/src/server/lib/harness/update-job-store.ts +22 -16
  137. package/src/server/lib/harness/update-job.server.ts +66 -175
  138. package/src/server/lib/harness/update-queue.server.ts +292 -0
  139. package/src/server/lib/harness/update-queue.test.ts +265 -0
  140. package/src/server/lib/harness/update-spawn.server.ts +96 -0
  141. package/src/server/lib/harness/update-worker.ts +8 -3
  142. package/src/server/lib/lifecycle/after-listen.ts +9 -0
  143. package/src/server/lib/lifecycle/paths.ts +14 -9
  144. package/src/server/lib/omp/rpc/run-settle.server.ts +10 -1
  145. package/src/server/lib/omp/rpc/subagent-liveness.ts +5 -5
  146. package/src/server/lib/omp/rpc/terminal-settle.ts +5 -1
  147. package/src/server/lib/omp/session/delete-flow.server.ts +1 -0
  148. package/src/server/lib/omp/session/sidebar-data.server.ts +10 -12
  149. package/src/server/lib/sessions/fork.server.test.ts +68 -0
  150. package/src/server/lib/sessions/fork.server.ts +31 -6
  151. package/src/server/lib/sessions/spawn.server.test.ts +41 -0
  152. package/src/server/lib/sessions/spawn.server.ts +27 -2
  153. package/src/server/routes/agent/harness-command.ts +6 -5
  154. package/src/server/routes/chat/stream.ts +7 -2
  155. package/src/server/routes/harness/update-status.ts +18 -12
  156. package/src/server/routes/harness/update.test.ts +53 -16
  157. package/src/server/routes/harness/update.ts +13 -8
  158. package/src/server/routes/sessions/body-readers.ts +43 -0
  159. package/src/server/routes/sessions/fork.ts +19 -4
  160. package/src/server/routes/sessions/routes.test.ts +1 -2
  161. package/src/server/routes/sessions/session.ts +19 -0
  162. package/src/server/routes/sessions/spawn.ts +16 -13
  163. package/src/shared/lib/chat/omp/agent-events.ts +11 -0
  164. package/src/shared/lib/chat/omp/session-modes-signal.test.ts +41 -0
  165. package/src/shared/lib/harness/mode-signal.ts +20 -0
  166. package/src/shared/lib/harness/session-modes.ts +24 -0
  167. package/src/shared/lib/harness/update-job.ts +53 -6
  168. package/src/shared/lib/icons/tint-hues.generated.ts +34 -34
  169. package/src/shared/lib/notifications/outcomes.test.ts +96 -0
  170. package/src/shared/lib/notifications/outcomes.ts +64 -0
  171. package/src/shared/lib/notifications/settings.test.ts +49 -0
  172. package/src/shared/lib/notifications/settings.ts +34 -0
  173. package/src/shared/lib/omp/session/default-title.ts +5 -4
  174. package/src/shared/lib/omp/session/prewarm-misc.test.ts +3 -2
  175. package/src/shared/lib/omp/session/schema-migrations.ts +4 -0
  176. package/src/shared/lib/omp/session/stream-state.server.test.ts +19 -0
  177. package/src/shared/lib/omp/session/stream-state.server.ts +24 -4
  178. package/src/shared/lib/settings/defaults.ts +3 -0
  179. package/src/shared/types/harness-update.ts +24 -0
  180. package/src/shared/types/realtime.ts +2 -0
  181. package/src/shared/types/settings/state.ts +10 -0
  182. package/src/shared/types/workspace.ts +4 -0
  183. package/src/test-support/harness-table.test-util.ts +25 -9
  184. package/dist/client/static/js/index-bc9aa4mx.css +0 -1
  185. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +0 -113
  186. package/src/client/components/common/subagent-list/index.tsx +0 -165
  187. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +0 -66
  188. package/src/client/hooks/workspace/child-expansion.ts +0 -33
@@ -0,0 +1,253 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The first send of a pending chat that has no omp session yet.
8
+ *
9
+ * Two shapes, one decision: a chat started from "New child session" has a
10
+ * `parentSessionId` in the pending store and is created through
11
+ * `/api/sessions/spawn`; every other pending chat is a top-level session and
12
+ * goes through `POST /api/agent/new`. Both adopt the id the server answers
13
+ * with, keep the optimistic rows, and are the ONLY place a pending id becomes
14
+ * a real one.
15
+ *
16
+ * Split from `send.ts` for the per-file ceiling; it owns no rendering.
17
+ */
18
+
19
+ import type { Attachment, ChatMessageData, PromptDispatchResult } from '@/shared/types';
20
+ import type { ArmedGoal } from '@/shared/lib/omp/mode/actions';
21
+ import type { ChatTimelineSendDeps } from '@/client/hooks/chat/timeline/send-props';
22
+ import { adoptPendingSession, pendingEntryFor } from '@/client/hooks/chat/omp/pending-sessions';
23
+ import { recordSpawnHarness } from '@/client/hooks/chat/timeline/spawn-harness';
24
+ import { childSpawnBody } from '@/client/hooks/chat/timeline/child-spawn';
25
+ import { forkRequestBody } from '@/client/hooks/chat/timeline/fork-request';
26
+ import { collectImages } from '@/client/hooks/chat/timeline/send-helpers';
27
+
28
+ type PendingDispatchDeps = Pick<
29
+ ChatTimelineSendDeps,
30
+ | 'folders'
31
+ | 'selectedFolderId'
32
+ | 'sessionId'
33
+ | 'ompAgent'
34
+ | 'setLocalMessages'
35
+ | 'setGenerating'
36
+ | 'aiPlaceholderIdRef'
37
+ | 'adoptedSessionIdRef'
38
+ | 'optimisticUserIdRef'
39
+ | 'seedSession'
40
+ | 'pendingComposerModelRef'
41
+ | 'pendingThinkingLevelRef'
42
+ | 'pendingHarnessRef'
43
+ | 'accessModeRef'
44
+ | 'spawnSelectionRef'
45
+ | 'goalArmRef'
46
+ | 'spawnWorktreeRef'
47
+ | 'reportActionError'
48
+ | 'setSearchParams'
49
+ >;
50
+
51
+ export interface PendingDispatchInput {
52
+ text: string;
53
+ attachments: Attachment[];
54
+ /** The assembled prompt: text attachments inlined, `@agent` translated. */
55
+ promptText: string;
56
+ userMsgId: string;
57
+ aiPlaceholderId: string;
58
+ newUserMsg: ChatMessageData;
59
+ /** A New Chat card's inherited harness, which outranks a stale pending pick. */
60
+ options?: { harness?: string | null };
61
+ startArmedGoal: (sessionId: string, armed: ArmedGoal, promptText: string) => Promise<boolean>;
62
+ }
63
+
64
+ /** Roll the optimistic turn back after a refused dispatch. */
65
+ function rollback(
66
+ deps: PendingDispatchDeps,
67
+ userMsgId: string,
68
+ aiPlaceholderId: string,
69
+ error: string,
70
+ ): PromptDispatchResult {
71
+ deps.setLocalMessages((prev) => prev.filter((m) => m.id !== userMsgId && m.id !== aiPlaceholderId));
72
+ deps.aiPlaceholderIdRef.current = null;
73
+ deps.optimisticUserIdRef.current = null;
74
+ deps.setGenerating(false);
75
+ deps.reportActionError(`Prompt not sent: ${error}`);
76
+ return { ok: false, busy: false, error };
77
+ }
78
+
79
+ /** Persist the user's turn for a session omp has not scanned yet. */
80
+ function persistUserTurn(sessionId: string, newUserMsg: ChatMessageData): void {
81
+ fetch(`/api/chat/${encodeURIComponent(sessionId)}`, {
82
+ method: 'POST',
83
+ headers: { 'Content-Type': 'application/json' },
84
+ body: JSON.stringify({ messages: [newUserMsg] }),
85
+ }).catch((err) => console.error('Error persisting spawned user turn:', err));
86
+ }
87
+
88
+ export async function dispatchPendingChat(
89
+ deps: PendingDispatchDeps,
90
+ input: PendingDispatchInput,
91
+ ): Promise<PromptDispatchResult | null> {
92
+ const currentFolder = deps.folders.find((f) => String(f.id) === String(deps.selectedFolderId));
93
+ // A worktree pick wins: the chat is BORN there, so no relocation is ever
94
+ // needed and the child's cwd is right for its whole life.
95
+ const cwd = deps.spawnWorktreeRef.current || currentFolder?.project_path || currentFolder?.name;
96
+ if (!cwd) return null;
97
+
98
+ const images = collectImages(input.attachments);
99
+ deps.optimisticUserIdRef.current = input.userMsgId;
100
+ const composerModel = deps.pendingComposerModelRef.current;
101
+ const composerThinking = deps.pendingThinkingLevelRef.current;
102
+ const entry = pendingEntryFor(deps.sessionId);
103
+ const parentSessionId = entry?.parentSessionId ?? null;
104
+
105
+ if (entry?.forkSourceSessionId) {
106
+ const response = await fetch(
107
+ `/api/sessions/${encodeURIComponent(entry.forkSourceSessionId)}/fork`,
108
+ {
109
+ method: 'POST',
110
+ headers: { 'content-type': 'application/json' },
111
+ body: JSON.stringify(
112
+ forkRequestBody(entry.forkAnchorEntryId ?? null, {
113
+ prompt: input.promptText,
114
+ images,
115
+ model: composerModel,
116
+ thinkingLevel: composerThinking,
117
+ accessMode: deps.accessModeRef.current,
118
+ }),
119
+ ),
120
+ },
121
+ );
122
+ const body = (await response.json().catch(() => null)) as {
123
+ sessionId?: string;
124
+ error?: string;
125
+ code?: string;
126
+ } | null;
127
+ if (!response.ok || !body?.sessionId) {
128
+ if (body?.code === 'mock_mode') return null;
129
+ return rollback(deps, input.userMsgId, input.aiPlaceholderId, body?.error ?? `HTTP ${response.status}`);
130
+ }
131
+
132
+ // A fork keeps the source's agent; the source row's harness was carried
133
+ // into the pending entry when the Fork button opened this chat.
134
+ recordSpawnHarness(body.sessionId, entry.harness ?? 'omp-rpc');
135
+ deps.adoptedSessionIdRef.current = body.sessionId;
136
+ adoptPendingSession(deps.sessionId, body.sessionId, currentFolder?.id ?? null);
137
+ if (composerModel) deps.seedSession({ model: composerModel });
138
+ deps.pendingComposerModelRef.current = null;
139
+ deps.pendingThinkingLevelRef.current = null;
140
+ deps.pendingHarnessRef.current = null;
141
+ persistUserTurn(body.sessionId, input.newUserMsg);
142
+ deps.setSearchParams((prev) => {
143
+ const next = new URLSearchParams(prev);
144
+ next.set('sessionId', body.sessionId!);
145
+ next.delete('forkFrom');
146
+ next.delete('forkAt');
147
+ next.delete('parentSessionId');
148
+ return next;
149
+ }, { replace: true });
150
+ return { ok: true, busy: false };
151
+ }
152
+
153
+ if (parentSessionId) {
154
+ const response = await fetch('/api/sessions/spawn', {
155
+ method: 'POST',
156
+ headers: { 'content-type': 'application/json' },
157
+ body: JSON.stringify(
158
+ childSpawnBody(parentSessionId, input.promptText, {
159
+ harness: input.options?.harness ?? deps.pendingHarnessRef.current,
160
+ model: composerModel,
161
+ thinkingLevel: composerThinking,
162
+ accessMode: deps.accessModeRef.current,
163
+ images,
164
+ }),
165
+ ),
166
+ });
167
+ const body = (await response.json().catch(() => null)) as {
168
+ sessionId?: string;
169
+ harness?: string;
170
+ model?: { provider: string; modelId: string } | null;
171
+ error?: string;
172
+ code?: string;
173
+ } | null;
174
+ if (!response.ok || !body?.sessionId) {
175
+ // MOCK mode has no agent process BY DESIGN; the simulated stream below
176
+ // answers the demo shell instead of reporting a failure.
177
+ if (body?.code === 'mock_mode') return null;
178
+ return rollback(deps, input.userMsgId, input.aiPlaceholderId, body?.error ?? `HTTP ${response.status}`);
179
+ }
180
+
181
+ recordSpawnHarness(body.sessionId, body.harness ?? 'omp-rpc');
182
+ deps.adoptedSessionIdRef.current = body.sessionId;
183
+ adoptPendingSession(deps.sessionId, body.sessionId, currentFolder?.id ?? null);
184
+ // The child's resolved model is the one its first turn runs on; seed it so
185
+ // the composer replacing the pending view reports it before omp's JSONL
186
+ // carries a model_change entry.
187
+ deps.seedSession({
188
+ ...(body.model ? { model: body.model } : {}),
189
+ ...(composerThinking ? { thinkingLevel: composerThinking } : {}),
190
+ });
191
+ deps.pendingComposerModelRef.current = null;
192
+ deps.pendingThinkingLevelRef.current = null;
193
+ deps.pendingHarnessRef.current = null;
194
+ persistUserTurn(body.sessionId, input.newUserMsg);
195
+ deps.setSearchParams((prev) => {
196
+ const next = new URLSearchParams(prev);
197
+ next.set('sessionId', body.sessionId!);
198
+ // The parameter belonged to the pending chat; a real session's URL must
199
+ // not keep a stale parent hint for a later pending chat.
200
+ next.delete('parentSessionId');
201
+ return next;
202
+ }, { replace: true });
203
+ return { ok: true, busy: false };
204
+ }
205
+
206
+ // Top-level pending chat: the existing `/api/agent/new` spawn.
207
+ const spawnModes = deps.spawnSelectionRef.current;
208
+ const armed = deps.goalArmRef.current;
209
+ const spawned = await deps.ompAgent.sendNewPrompt(
210
+ input.promptText,
211
+ cwd,
212
+ images,
213
+ {
214
+ model: composerModel,
215
+ thinkingLevel: composerThinking,
216
+ accessMode: deps.accessModeRef.current,
217
+ modes: spawnModes,
218
+ ...((input.options?.harness ?? deps.pendingHarnessRef.current)
219
+ ? { harness: input.options?.harness ?? deps.pendingHarnessRef.current }
220
+ : {}),
221
+ },
222
+ armed ? (id) => input.startArmedGoal(id, armed, input.promptText) : undefined,
223
+ );
224
+ if (spawned.ok) {
225
+ const { session } = spawned;
226
+ // The harness the SERVER answered with: `new.ts` reports it for an ACP
227
+ // spawn and omits it for the RPC branch, which means omp. Read rather than
228
+ // replayed from the request, so a pick the server did not honour cannot be
229
+ // reported as the agent running the chat.
230
+ recordSpawnHarness(session.sessionId, session.harness ?? 'omp-rpc');
231
+ deps.spawnSelectionRef.current = null;
232
+ deps.adoptedSessionIdRef.current = session.sessionId;
233
+ // The pending row moves with the id; without this it vanished the moment
234
+ // the URL stopped naming the pending id.
235
+ adoptPendingSession(deps.sessionId, session.sessionId, currentFolder?.id ?? null);
236
+ deps.seedSession({ model: session.model, thinkingLevel: composerThinking });
237
+ deps.pendingComposerModelRef.current = null;
238
+ deps.pendingThinkingLevelRef.current = null;
239
+ deps.pendingHarnessRef.current = null;
240
+ persistUserTurn(session.sessionId, input.newUserMsg);
241
+ deps.setSearchParams((prev) => {
242
+ const next = new URLSearchParams(prev);
243
+ next.set('sessionId', session.sessionId);
244
+ next.delete('parentSessionId');
245
+ return next;
246
+ }, { replace: true });
247
+ return { ok: true, busy: false };
248
+ }
249
+ if (spawned.code !== 'mock_mode') {
250
+ return rollback(deps, input.userMsgId, input.aiPlaceholderId, spawned.error);
251
+ }
252
+ return null;
253
+ }
@@ -17,8 +17,8 @@ export type { ChatTimelineSendDeps, ChatTimelineSendResult };
17
17
  import type { AgentImage, Attachment, PromptDispatchResult, QueuedMessageModel } from '@/shared/types';
18
18
  import { flushDeferredPick } from '@/client/hooks/chat/timeline/deferred-model';
19
19
  import { buildOptimisticRows, collectImages, assemblePrompt, streamMockFallback } from '@/client/hooks/chat/timeline/send-helpers';
20
- import { adoptPendingSession, markPendingSessionSent } from '@/client/hooks/chat/omp/pending-sessions';
21
- import { recordSpawnHarness } from '@/client/hooks/chat/timeline/spawn-harness';
20
+ import { markPendingSessionSent } from '@/client/hooks/chat/omp/pending-sessions';
21
+ import { dispatchPendingChat } from '@/client/hooks/chat/timeline/pending-dispatch';
22
22
  import { postModeCommand } from '@/client/hooks/chat/timeline/mode-post';
23
23
  import type { ArmedGoal } from '@/shared/lib/omp/mode/actions';
24
24
  import { blockTuiOnlySend } from '@/client/hooks/chat/timeline/tui-only-guard';
@@ -41,23 +41,18 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
41
41
  scrollToBottom,
42
42
  jumpToBottom,
43
43
  aiPlaceholderIdRef,
44
- adoptedSessionIdRef,
45
44
  optimisticUserIdRef,
46
45
  pendingUserDisplaysRef,
47
46
  seedSession,
48
47
  pendingComposerModelRef,
49
48
  pendingThinkingLevelRef,
50
- pendingHarnessRef,
51
49
  deferredComposerPickRef,
52
50
  accessModeRef,
53
- spawnSelectionRef,
54
51
  goalArmRef,
55
52
  disarmGoal,
56
- spawnWorktreeRef,
57
53
  abortControllerRef,
58
54
  setInputValue,
59
55
  reportActionError,
60
- setSearchParams,
61
56
  } = deps;
62
57
 
63
58
  // `@agent` mentions are omp's subagent syntax. An ACP harness has no such
@@ -229,103 +224,22 @@ export function useChatTimelineSend(deps: ChatTimelineSendDeps): ChatTimelineSen
229
224
  return result;
230
225
  }
231
226
 
232
- // No active session (fresh "New Session"): in real mode spawn a brand-new
233
- // omp session and adopt its id; fall back to the mock/simulated path only
234
- // when the spawn fails (e.g. MOCK=true or no workspace context).
235
- if (!isOmpSession) {
236
- const currentFolder = folders.find(f => String(f.id) === String(selectedFolderId));
237
- // A worktree pick wins: the chat is BORN there, so no relocation is ever
238
- // needed and the child's cwd is right for its whole life.
239
- const cwd = spawnWorktreeRef.current || currentFolder?.project_path || currentFolder?.name;
240
- if (cwd) {
241
- const images = collectImages(attachments);
242
- optimisticUserIdRef.current = userMsgId;
243
- const composerModel = pendingComposerModelRef.current;
244
- const composerThinking = pendingThinkingLevelRef.current;
245
- // The mode picks made on the pending view ride the spawn. Read once,
246
- // here, and cleared below on success: a selection that outlived its
247
- // spawn would re-apply to the NEXT new session the user opens.
248
- const spawnModes = spawnSelectionRef.current;
249
- // An armed goal is recorded between the spawn and the prompt: the id
250
- // exists by then, and the prompt below is the goal's first turn. Not
251
- // after the prompt — a fast turn could finish before the record landed,
252
- // leaving a goal with no turn to act on.
253
- const armed = goalArmRef.current;
254
- const spawned = await ompAgent.sendNewPrompt(
227
+ // No active session (fresh "New Session"): a top-level chat or a pending
228
+ // child spawns its real session and adopts its id. `null` means the
229
+ // simulated path below owns it (no cwd, MOCK mode).
230
+ const pending = !isOmpSession
231
+ ? await dispatchPendingChat(deps, {
232
+ text,
233
+ attachments,
255
234
  promptText,
256
- cwd,
257
- images,
258
- {
259
- model: composerModel,
260
- thinkingLevel: composerThinking,
261
- accessMode: accessModeRef.current,
262
- modes: spawnModes,
263
- // A harness picked on the pending view rides the spawn; cleared on
264
- // success below so it cannot leak onto the next new chat. A New
265
- // Chat opened from an ACP answer passes the SOURCE chat's harness
266
- // explicitly (that dialog has no picker), and it must outrank the
267
- // ref a previous pick left behind.
268
- ...((options?.harness ?? pendingHarnessRef.current)
269
- ? { harness: options?.harness ?? pendingHarnessRef.current }
270
- : {}),
271
- },
272
- armed ? (id) => startArmedGoal(id, armed, promptText) : undefined,
273
- );
274
- if (spawned.ok) {
275
- const { session } = spawned;
276
- // The harness the SERVER answered with: `new.ts` reports it for an ACP
277
- // spawn and omits it for the RPC branch, which means omp. Read rather
278
- // than replayed from the request, so a pick the server did not honour
279
- // cannot be reported as the agent running the chat.
280
- recordSpawnHarness(session.sessionId, session.harness ?? 'omp-rpc');
281
- spawnSelectionRef.current = null;
282
- adoptedSessionIdRef.current = session.sessionId;
283
- // The sidebar's row moves with the id: `new-…` was the client's own
284
- // placeholder, and the spawn answers with omp's real one, which omp
285
- // has still not written a transcript for. Without this the row
286
- // vanished at exactly the moment the URL stopped naming the pending
287
- // id, which is the gap this store exists to close.
288
- adoptPendingSession(sessionId, session.sessionId, currentFolder?.id ?? null);
289
- // The placeholder ref is already armed (with its row) before the
290
- // spawn — see the note at the assignment; re-arming here would be
291
- // harmless but is redundant.
292
- // The spawn already applied this level to the session; seed it so the
293
- // composer taking over from the pending view reports the run's real
294
- // setting instead of a catalog default (the JSONL that carries it is
295
- // not locatable yet).
296
- seedSession({ model: session.model, thinkingLevel: composerThinking });
297
- pendingComposerModelRef.current = null;
298
- pendingThinkingLevelRef.current = null;
299
- pendingHarnessRef.current = null;
300
- fetch(`/api/chat/${encodeURIComponent(session.sessionId)}`, {
301
- method: 'POST',
302
- headers: { 'Content-Type': 'application/json' },
303
- body: JSON.stringify({ messages: [newUserMsg] }),
304
- }).catch(err => console.error('Error persisting spawned user turn:', err));
305
- setSearchParams(prev => {
306
- const next = new URLSearchParams(prev);
307
- next.set('sessionId', session.sessionId);
308
- return next;
309
- }, { replace: true });
310
- // The sidebar already re-read at prompt dispatch (sendNewPrompt
311
- // signals it), so the new session shows its live badge without
312
- // waiting for the JSONL to carry the user turn.
313
- return { ok: true, busy: false };
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
- }
327
- }
328
- }
235
+ userMsgId,
236
+ aiPlaceholderId,
237
+ newUserMsg,
238
+ ...(options ? { options } : {}),
239
+ startArmedGoal,
240
+ })
241
+ : null;
242
+ if (pending) return pending;
329
243
 
330
244
  // Mock / Kabmo-created session: existing simulated SSE path.
331
245
  const currentFolder = folders.find(f => String(f.id) === String(selectedFolderId));
@@ -100,6 +100,12 @@ export function resolveSessionHarness(
100
100
  picked: string | undefined,
101
101
  ): { harness: string | undefined; fromRow: boolean } {
102
102
  if (!sessionId) return { harness: undefined, fromRow: false };
103
+ // A pending row carries the harness as a MARK for its future self, not as a
104
+ // spawned fact: treating it as the row `fromRow` locked the picker on the
105
+ // composer that is supposed to choose it.
106
+ if (sessionId.startsWith('new-')) {
107
+ return { harness: spawnedHarnessFor(sessionId) ?? picked, fromRow: false };
108
+ }
103
109
  for (const folder of folders) {
104
110
  for (const entry of folder.sessions ?? []) {
105
111
  if (entry.id === sessionId) return { harness: entry.harness, fromRow: true };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Stop a run and offer the delivery of the follow-ups it leaves queued.
8
+ *
9
+ * Stop-all semantics: the queue is NOT discarded, so the one useful next action
10
+ * is "send the head now" — surfaced on the toast rather than on a row the user
11
+ * has to find. Kept out of the timeline component because it is one verb and its
12
+ * dependencies, not the layout.
13
+ */
14
+
15
+ import { useCallback } from 'preact/hooks';
16
+ import type { ToastsHandle } from '@/client/hooks/ui/toasts';
17
+
18
+ export function useStopWithQueuedPrompts<T>(
19
+ stopGenerating: () => number,
20
+ messageQueue: readonly T[],
21
+ sendNow: (item: T) => void,
22
+ pushToast: ToastsHandle['pushToast'],
23
+ ): () => void {
24
+ return useCallback(() => {
25
+ const heldCount = stopGenerating();
26
+ if (heldCount === 0) return;
27
+ pushToast(
28
+ `Stopped. ${heldCount} message${heldCount > 1 ? 's' : ''} still queued — nothing was sent.`,
29
+ 'success',
30
+ {
31
+ action: {
32
+ label: 'Send now',
33
+ onClick: () => {
34
+ const first = messageQueue[0];
35
+ if (first) sendNow(first);
36
+ },
37
+ },
38
+ duration: 8000,
39
+ },
40
+ );
41
+ }, [stopGenerating, pushToast, messageQueue, sendNow]);
42
+ }
@@ -4,46 +4,55 @@
4
4
  */
5
5
 
6
6
  /**
7
- * Fork the current chat at a clicked row.
7
+ * Open a FORK as the same pending-chat composer New Session uses.
8
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.
9
+ * Fork used to create the branch before the operator could say what to do in
10
+ * it. Now it navigates to a `new-…` chat that carries the source and anchor in
11
+ * the pending store, so the normal empty-workspace composer (model, thinking,
12
+ * access, attachments) writes the branch's first turn. The POST happens on
13
+ * SEND, in `pending-dispatch.ts`.
13
14
  */
14
15
 
15
16
  import { useCallback } from 'preact/hooks';
16
-
17
- type ToastKind = 'success' | 'error';
17
+ import { useSearchParams } from '@/client/lib/router/search-params';
18
+ import { startPendingSession } from '@/client/hooks/chat/omp/pending-sessions';
19
+ import { setHarnessPick } from '@/client/hooks/chat/timeline/session-harness';
20
+ import { formatNewSessionTitle } from '@/shared/lib/omp/session/default-title';
21
+ import type { WorkspaceFolderData } from '@/shared/types';
18
22
 
19
23
  export function useForkSession(
20
24
  sessionId: string | null | undefined,
21
- pushToast: (message: string, type?: ToastKind) => void,
22
- ): (messageId: string) => Promise<void> {
25
+ folders: WorkspaceFolderData[],
26
+ selectedFolderId: number | null,
27
+ ): (messageId: string) => void {
28
+ const [, setSearchParams] = useSearchParams();
29
+
23
30
  return useCallback(
24
- async (messageId: string) => {
31
+ (messageId: string) => {
25
32
  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
- }
33
+ const source = folders
34
+ .flatMap((folder) => folder.sessions ?? [])
35
+ .find((session) => String(session.id) === sessionId);
36
+ const folderId = source?.folder_id ?? selectedFolderId ?? null;
37
+ const pendingId = startPendingSession(folderId, {
38
+ title: formatNewSessionTitle(new Date(), 'Fork'),
39
+ ...(source?.harness ? { harness: source.harness } : {}),
40
+ forkSourceSessionId: String(sessionId),
41
+ forkAnchorEntryId: messageId,
42
+ });
43
+ // The picker's first tab is the source's agent; the fork cannot change
44
+ // provider because that agent owns the history being branched.
45
+ if (source?.harness) setHarnessPick(pendingId, source.harness);
46
+ setSearchParams((prev) => {
47
+ const next = new URLSearchParams(prev);
48
+ next.set('sessionId', pendingId);
49
+ next.set('forkFrom', String(sessionId));
50
+ next.set('forkAt', messageId);
51
+ next.delete('parentSessionId');
52
+ if (folderId !== null && folderId !== undefined) next.set('folderId', String(folderId));
53
+ return next;
54
+ }, { replace: true });
46
55
  },
47
- [sessionId, pushToast],
56
+ [sessionId, folders, selectedFolderId, setSearchParams],
48
57
  );
49
58
  }