@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
@@ -0,0 +1,196 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Spawning a child session: the relation is written before the first prompt,
8
+ * the depth cap is checked before anything is spawned, and a failure after the
9
+ * spawn tears the child down instead of leaving a session nobody owns.
10
+ */
11
+
12
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
13
+ import { mkdtempSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
17
+ import { getDb } from '@/server/db.server';
18
+ import { ensureSessionRelationsSchema } from '@/server/lib/sessions/schema.server';
19
+ import { saveHarnessSession } from '@/server/lib/harness/session-store.server';
20
+ import { createSessionRelation, getSessionRelation } from '@/server/lib/sessions/relations.server';
21
+ import {
22
+ SessionSpawnError,
23
+ spawnChildSession,
24
+ type SpawnSessionDeps,
25
+ type SpawnedSession,
26
+ } from '@/server/lib/sessions/spawn.server';
27
+
28
+ let root = '';
29
+
30
+ beforeEach(async () => {
31
+ await isolateDb();
32
+ await ensureSessionRelationsSchema(await getDb());
33
+ root = mkdtempSync(join(tmpdir(), 'kabmo-spawn-'));
34
+ const db = await getDb();
35
+ await db.run(
36
+ 'INSERT INTO workspace_folders (id, name, project_path) VALUES (?, ?, ?)',
37
+ [1, 'one', root],
38
+ );
39
+ });
40
+
41
+ afterEach(async () => {
42
+ await releaseDb();
43
+ });
44
+
45
+ function fakeSession(sessionId: string, options: { failPrompt?: boolean } = {}): SpawnedSession & {
46
+ sent: Record<string, unknown>[];
47
+ destroyed: boolean;
48
+ } {
49
+ const sent: Record<string, unknown>[] = [];
50
+ const state = {
51
+ sessionId,
52
+ sent,
53
+ destroyed: false,
54
+ async send(command: Record<string, unknown>) {
55
+ if (options.failPrompt) throw new Error('provider refused');
56
+ sent.push(command);
57
+ return { agentInvoked: true };
58
+ },
59
+ async destroyAndWait() {
60
+ state.destroyed = true;
61
+ },
62
+ };
63
+ return state;
64
+ }
65
+
66
+ function depsFor(session: SpawnedSession, onStart?: (cwd: string) => void): SpawnSessionDeps {
67
+ return {
68
+ async startRpc(cwd) {
69
+ onStart?.(cwd);
70
+ return { session, realSessionId: session.sessionId };
71
+ },
72
+ async startAcp() {
73
+ throw new Error('not used');
74
+ },
75
+ };
76
+ }
77
+
78
+ describe('spawnChildSession', () => {
79
+ test('writes the relation before sending, and reports the depth', async () => {
80
+ await saveHarnessSession({
81
+ sessionId: 'parent',
82
+ harness: 'omp-rpc',
83
+ agentSessionId: '',
84
+ cwd: root,
85
+ });
86
+ const child = fakeSession('child');
87
+ const result = await spawnChildSession(
88
+ { parentSessionId: 'parent', prompt: 'review this' },
89
+ depsFor(child),
90
+ );
91
+
92
+ expect(result).toEqual({
93
+ sessionId: 'child',
94
+ harness: 'omp-rpc',
95
+ parentSessionId: 'parent',
96
+ depth: 1,
97
+ });
98
+ expect(child.sent).toHaveLength(1);
99
+ expect(child.sent[0]).toMatchObject({ type: 'prompt' });
100
+ expect(String(child.sent[0].message)).toStartWith('[kabmo dispatched worker]');
101
+ expect(String(child.sent[0].message)).toContain('your coordinator is session parent');
102
+ expect(String(child.sent[0].message)).toEndWith('TASK\nreview this');
103
+ expect(await getSessionRelation('child')).toMatchObject({
104
+ parentSessionId: 'parent',
105
+ lifecycleOwnerSessionId: 'parent',
106
+ depth: 1,
107
+ });
108
+ });
109
+
110
+ test('refuses a fifth level before spawning anything', async () => {
111
+ await createSessionRelation({ sessionId: 'l1' });
112
+ await createSessionRelation({ sessionId: 'l2', parentSessionId: 'l1' });
113
+ await createSessionRelation({ sessionId: 'l3', parentSessionId: 'l2' });
114
+ await createSessionRelation({ sessionId: 'l4', parentSessionId: 'l3' });
115
+ await createSessionRelation({ sessionId: 'l5', parentSessionId: 'l4' });
116
+ await saveHarnessSession({
117
+ sessionId: 'l5',
118
+ harness: 'omp-rpc',
119
+ agentSessionId: '',
120
+ cwd: root,
121
+ });
122
+
123
+ let started = false;
124
+ await expect(
125
+ spawnChildSession(
126
+ { parentSessionId: 'l5', prompt: 'too deep' },
127
+ depsFor(fakeSession('child'), () => {
128
+ started = true;
129
+ }),
130
+ ),
131
+ ).rejects.toMatchObject({ code: 'spawn_failed' });
132
+ expect(started).toBe(false);
133
+ });
134
+
135
+ test('refuses a child outside the parent workspace folder', async () => {
136
+ const other = mkdtempSync(join(tmpdir(), 'kabmo-other-'));
137
+ const db = await getDb();
138
+ await db.run('INSERT INTO workspace_folders (id, name, project_path) VALUES (?, ?, ?)', [
139
+ 2,
140
+ 'two',
141
+ other,
142
+ ]);
143
+ await saveHarnessSession({
144
+ sessionId: 'parent',
145
+ harness: 'omp-rpc',
146
+ agentSessionId: '',
147
+ cwd: root,
148
+ });
149
+
150
+ await expect(
151
+ spawnChildSession(
152
+ { parentSessionId: 'parent', cwd: other, prompt: 'elsewhere' },
153
+ depsFor(fakeSession('child')),
154
+ ),
155
+ ).rejects.toMatchObject({ code: 'parent_folder_mismatch' });
156
+ });
157
+
158
+ test('an ACP worker with no explicit model leaves the harness default alone', async () => {
159
+ await saveHarnessSession({
160
+ sessionId: 'parent',
161
+ harness: 'claude',
162
+ agentSessionId: 'agent-parent',
163
+ cwd: root,
164
+ });
165
+ let captured: { provider: string; modelId: string } | null | undefined;
166
+ const child = fakeSession('child');
167
+ const deps: SpawnSessionDeps = {
168
+ async startRpc() {
169
+ throw new Error('not used');
170
+ },
171
+ async startAcp(request) {
172
+ captured = request.model;
173
+ return { session: child, realSessionId: child.sessionId };
174
+ },
175
+ };
176
+
177
+ await spawnChildSession({ parentSessionId: 'parent', prompt: 'review this' }, deps);
178
+ expect(captured).toBeNull();
179
+ });
180
+
181
+ test('a refused first prompt destroys the child and records nothing', async () => {
182
+ await saveHarnessSession({
183
+ sessionId: 'parent',
184
+ harness: 'omp-rpc',
185
+ agentSessionId: '',
186
+ cwd: root,
187
+ });
188
+ const child = fakeSession('child', { failPrompt: true });
189
+
190
+ await expect(
191
+ spawnChildSession({ parentSessionId: 'parent', prompt: 'hello' }, depsFor(child)),
192
+ ).rejects.toBeInstanceOf(SessionSpawnError);
193
+ expect(child.destroyed).toBe(true);
194
+ expect(await getSessionRelation('child')).toMatchObject({ parentSessionId: 'parent' });
195
+ });
196
+ });
@@ -0,0 +1,310 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Spawn a child session — the delegation half of the tree.
8
+ *
9
+ * The child is a normal session: same spawn paths, same transport, same
10
+ * permissions. What makes it a child is one relation row plus the notification
11
+ * edge; nothing about the agent process knows it was delegated. That is
12
+ * deliberate: a child that outlives its parent is an ordinary session, and a
13
+ * parent that dies must not take the child's transcript with it.
14
+ *
15
+ * Validation happens BEFORE the spawn, and the relation is written before the
16
+ * first prompt: a fast provider can finish a turn in under a second, and a
17
+ * completion with no relation row would be a notification nobody receives.
18
+ */
19
+
20
+ import { loadPersistedAccessMode } from '@/shared/lib/omp/config/access-mode.server';
21
+ import {
22
+ agentEnvironment,
23
+ createAgentToken,
24
+ rememberAgentToken,
25
+ } from '@/server/lib/sessions/agent-token.server';
26
+ import type { ApprovalMode } from '@/shared/lib/omp/config/access-mode';
27
+ import { projectModelForCwd } from '@/server/lib/workspace/project-model.server';
28
+ import { startAcpSession } from '@/server/lib/harness/spawn.server';
29
+ import { getLiveSession, harnessOfSession, startNewRpcSession } from '@/server/lib/omp/rpc/session-registry';
30
+ import { harnessProbeModels } from '@/server/lib/harness/probe-cache.server';
31
+ import { getDb } from '@/server/db.server';
32
+ import { HARNESS_IDS, harnessDescriptor, type HarnessId } from '@/shared/lib/harness/catalog';
33
+ import type { SelectedModel } from '@/shared/types/models';
34
+ import { MAX_SESSION_DEPTH } from '@/server/lib/sessions/relation-types';
35
+ import {
36
+ createSessionRelation,
37
+ getSessionRelation,
38
+ } from '@/server/lib/sessions/relations.server';
39
+ import {
40
+ folderIdForCwd,
41
+ isSessionArchived,
42
+ resolveSessionRef,
43
+ sessionExists,
44
+ } from '@/server/lib/sessions/resolve.server';
45
+
46
+ export type SessionSpawnErrorCode =
47
+ | 'cwd_required'
48
+ | 'harness_unknown'
49
+ | 'parent_not_found'
50
+ | 'parent_archived'
51
+ | 'parent_folder_mismatch'
52
+ | 'model_unknown'
53
+ | 'spawn_failed';
54
+
55
+ export class SessionSpawnError extends Error {
56
+ constructor(
57
+ readonly code: SessionSpawnErrorCode,
58
+ message: string,
59
+ ) {
60
+ super(message);
61
+ this.name = 'SessionSpawnError';
62
+ }
63
+ }
64
+
65
+ /** The slice of a spawned session this service uses. */
66
+ export interface SpawnedSession {
67
+ readonly sessionId: string;
68
+ send(command: Record<string, unknown>): Promise<unknown>;
69
+ destroyAndWait(): Promise<void>;
70
+ }
71
+
72
+ export interface SpawnSessionDeps {
73
+ startRpc(
74
+ cwd: string,
75
+ accessMode: ApprovalMode,
76
+ env: Record<string, string>,
77
+ ): Promise<{ session: SpawnedSession; realSessionId: string }>;
78
+ startAcp(request: {
79
+ harness: HarnessId;
80
+ sessionId: string;
81
+ cwd: string;
82
+ model: SelectedModel | null;
83
+ thinkingLevel: string | null;
84
+ accessMode: ApprovalMode;
85
+ env: Record<string, string>;
86
+ }): Promise<{ session: SpawnedSession; realSessionId: string }>;
87
+ }
88
+
89
+ const defaultDeps: SpawnSessionDeps = {
90
+ startRpc: (cwd, accessMode, env) => startNewRpcSession(cwd, accessMode, env),
91
+ startAcp: (request) => startAcpSession(request),
92
+ };
93
+
94
+ export interface SpawnChildSessionInput {
95
+ /** Omit for a root session created through this path. */
96
+ parentSessionId?: string | null;
97
+ harness?: string | null;
98
+ cwd?: string | null;
99
+ prompt: string;
100
+ model?: SelectedModel | null;
101
+ thinkingLevel?: string | null;
102
+ lifecycleOwnerSessionId?: string | null;
103
+ visibility?: 'visible' | 'hidden';
104
+ parentNotifications?: 'auto' | 'stuck' | 'off';
105
+ }
106
+
107
+ export interface SpawnChildSessionResult {
108
+ sessionId: string;
109
+ harness: HarnessId;
110
+ parentSessionId: string | null;
111
+ depth: number;
112
+ }
113
+
114
+ function harnessOf(value: string | null | undefined): HarnessId | null {
115
+ if (!value) return null;
116
+ return HARNESS_IDS.includes(value as HarnessId) ? (value as HarnessId) : null;
117
+ }
118
+
119
+ /**
120
+ * Resolve the parent's execution context and the child's cwd.
121
+ *
122
+ * The folder check is refused only when BOTH folders resolve: a session whose
123
+ * cwd sits outside every registered workspace has no folder to compare, and
124
+ * refusing on that would block work the sidebar would happily show.
125
+ */
126
+ async function resolveParent(
127
+ parentSessionId: string,
128
+ requestedCwd: string | null,
129
+ ): Promise<{ cwd: string; harness: HarnessId | null }> {
130
+ if (!(await sessionExists(parentSessionId))) {
131
+ throw new SessionSpawnError('parent_not_found', `Parent session ${parentSessionId} not found`);
132
+ }
133
+ if (await isSessionArchived(parentSessionId)) {
134
+ throw new SessionSpawnError('parent_archived', 'Cannot spawn under an archived session');
135
+ }
136
+ const parent = await resolveSessionRef(parentSessionId);
137
+ const cwd = requestedCwd || parent.cwd;
138
+ if (!cwd) {
139
+ throw new SessionSpawnError(
140
+ 'cwd_required',
141
+ 'The parent has no working directory; pass one explicitly',
142
+ );
143
+ }
144
+ if (requestedCwd && parent.cwd) {
145
+ const [parentFolder, childFolder] = await Promise.all([
146
+ folderIdForCwd(parent.cwd),
147
+ folderIdForCwd(requestedCwd),
148
+ ]);
149
+ if (parentFolder !== null && childFolder !== null && parentFolder !== childFolder) {
150
+ throw new SessionSpawnError(
151
+ 'parent_folder_mismatch',
152
+ 'A child session must stay in its parent workspace folder',
153
+ );
154
+ }
155
+ }
156
+ return { cwd, harness: parent.harness };
157
+ }
158
+
159
+ /**
160
+ * The model a worker runs on, by the one order that cannot invent a value.
161
+ *
162
+ * Explicit wins. Next is the SAME harness's live parent — a Claude reviewer
163
+ * inherits Claude's model, never omp's model id. Then the harness's own
164
+ * configured default is resolved by `startAcpSession`, so ACP gets null here.
165
+ * `omp-rpc` keeps its project default because that is a real omp model id.
166
+ */
167
+ async function resolveSpawnModel(
168
+ requested: SelectedModel | null,
169
+ harness: HarnessId,
170
+ parentSessionId: string | null,
171
+ cwd: string,
172
+ ): Promise<SelectedModel | null> {
173
+ if (requested) {
174
+ if (harness !== 'omp-rpc') {
175
+ const models = await harnessProbeModels(harness);
176
+ const exact = `${requested.provider}/${requested.modelId}`;
177
+ const listed = models.length === 0
178
+ || models.some((model) => model.value === exact || model.value === requested.modelId);
179
+ if (!listed) {
180
+ throw new SessionSpawnError(
181
+ 'model_unknown',
182
+ `${harnessDescriptor(harness)?.label ?? harness} does not list model ${exact}`,
183
+ );
184
+ }
185
+ }
186
+ return requested;
187
+ }
188
+ const parent = parentSessionId ? getLiveSession(parentSessionId) : undefined;
189
+ if (parent && harnessOfSession(parent) === harness && parent.runModel) {
190
+ return { provider: parent.runModel.provider, modelId: parent.runModel.modelId };
191
+ }
192
+ if (harness === 'omp-rpc') {
193
+ return projectModelForCwd(await getDb(), cwd).catch(() => null);
194
+ }
195
+ return null;
196
+ }
197
+
198
+ /** What a child receives before its task: identity, the one control verb, and
199
+ * the completion rule. Kabmo, not the orchestrator, writes this. */
200
+ function dispatchedWorkerPrompt(parentSessionId: string, sessionId: string, task: string): string {
201
+ return [
202
+ '[kabmo dispatched worker]',
203
+ `You are session ${sessionId}; your coordinator is session ${parentSessionId}.`,
204
+ 'The coordinator cannot see this chat.',
205
+ '',
206
+ ' # Read another session:',
207
+ ' kabmo session output <id>',
208
+ ' # Ask the coordinator or report a blocker, then end your turn:',
209
+ ` kabmo session tell ${parentSessionId} --message-file - --mode auto`,
210
+ '',
211
+ 'Do only this task. When you finish, your final message is your report: what you did,',
212
+ 'what you found, what is left. Do not send a separate acknowledgement.',
213
+ '[/kabmo dispatched worker]',
214
+ '',
215
+ 'TASK',
216
+ task,
217
+ ].join('\n');
218
+ }
219
+
220
+ /** Spawn a session, record its relation, then dispatch the first prompt. */
221
+ export async function spawnChildSession(
222
+ input: SpawnChildSessionInput,
223
+ deps: SpawnSessionDeps = defaultDeps,
224
+ ): Promise<SpawnChildSessionResult> {
225
+ const prompt = input.prompt.trim();
226
+ if (!prompt) {
227
+ throw new SessionSpawnError('spawn_failed', 'A first prompt is required');
228
+ }
229
+ const parentSessionId = input.parentSessionId ?? null;
230
+ const requestedHarness = input.harness ?? null;
231
+ const parent = parentSessionId
232
+ ? await resolveParent(parentSessionId, input.cwd ?? null)
233
+ : null;
234
+ const cwd = parent?.cwd ?? input.cwd ?? null;
235
+ if (!cwd) {
236
+ throw new SessionSpawnError('cwd_required', 'A working directory is required');
237
+ }
238
+
239
+ const requested = harnessOf(requestedHarness);
240
+ if (requestedHarness && requested === null) {
241
+ throw new SessionSpawnError('harness_unknown', `Unknown harness: ${requestedHarness}`);
242
+ }
243
+ const harness = requested ?? parent?.harness ?? 'omp-rpc';
244
+ const parentRelation = parentSessionId ? await getSessionRelation(parentSessionId) : null;
245
+ const depth = (parentRelation?.depth ?? 0) + 1;
246
+ if (depth > MAX_SESSION_DEPTH) {
247
+ throw new SessionSpawnError(
248
+ 'spawn_failed',
249
+ `A session tree is limited to ${MAX_SESSION_DEPTH} levels`,
250
+ );
251
+ }
252
+
253
+ const accessMode = await loadPersistedAccessMode();
254
+ const token = createAgentToken();
255
+ const env = agentEnvironment(token);
256
+ const model = await resolveSpawnModel(input.model ?? null, harness, parentSessionId, cwd);
257
+ const started =
258
+ harness === 'omp-rpc'
259
+ ? await deps.startRpc(cwd, accessMode, env)
260
+ : await deps.startAcp({
261
+ harness,
262
+ sessionId: `__new__${Bun.randomUUIDv7()}`,
263
+ cwd,
264
+ model,
265
+ thinkingLevel: input.thinkingLevel ?? null,
266
+ accessMode,
267
+ env,
268
+ });
269
+
270
+ try {
271
+ await rememberAgentToken(started.realSessionId, token);
272
+ await createSessionRelation({
273
+ sessionId: started.realSessionId,
274
+ parentSessionId,
275
+ lifecycleOwnerSessionId: input.lifecycleOwnerSessionId ?? parentSessionId,
276
+ visibility: input.visibility ?? 'visible',
277
+ parentNotifications: input.parentNotifications ?? 'auto',
278
+ });
279
+ } catch (error) {
280
+ // The child exists but cannot be placed in the tree; leaving it running
281
+ // would be a session nobody owns.
282
+ await started.session.destroyAndWait().catch(() => {});
283
+ throw new SessionSpawnError(
284
+ 'spawn_failed',
285
+ error instanceof Error ? error.message : 'Could not record the session relation',
286
+ );
287
+ }
288
+
289
+ try {
290
+ const message = parentSessionId
291
+ ? dispatchedWorkerPrompt(parentSessionId, started.realSessionId, prompt)
292
+ : prompt;
293
+ await started.session.send({ type: 'prompt', message });
294
+ } catch (error) {
295
+ await started.session.destroyAndWait().catch(() => {});
296
+ throw new SessionSpawnError(
297
+ 'spawn_failed',
298
+ `${harnessDescriptor(harness)?.label ?? harness} refused the first prompt: ${
299
+ error instanceof Error ? error.message : String(error)
300
+ }`,
301
+ );
302
+ }
303
+
304
+ return {
305
+ sessionId: started.realSessionId,
306
+ harness,
307
+ parentSessionId,
308
+ depth,
309
+ };
310
+ }
@@ -8,8 +8,8 @@
8
8
  * exactly once: the replay's last line followed immediately by live output.
9
9
  *
10
10
  * The two ways this breaks are both silent, and both are duplicate/garbled text
11
- * in xterm rather than an error. Output is appended to `history` and queued for
12
- * delivery, so a replay captured BEFORE the queue is flushed carries the pending
11
+ * in the terminal rather than an error. Output is appended to `history` and
12
+ * queued for delivery, so a replay captured BEFORE the queue is flushed carries the pending
13
13
  * bytes and the queued frame carries them again (each line printed twice); a
14
14
  * frame delivered before the replay arrives ahead of it in the wrong order.
15
15
  * `attachTerminal` flushes first for exactly this reason, and this is the test
@@ -9,8 +9,8 @@
9
9
  * receives must equal the concatenation of the reads, in the same order, and the
10
10
  * framing must be bounded.
11
11
  *
12
- * Two failures it must not have, both of which xterm renders as garbage rather
13
- * than as an error: dropping a trailing partial frame (a prompt that never
12
+ * Two failures it must not have, both of which the renderer draws as garbage
13
+ * rather than as an error: dropping a trailing partial frame (a prompt that never
14
14
  * appears until the next keypress) and reordering (an escape sequence split
15
15
  * across two reads, reassembled after a later one).
16
16
  *
@@ -21,7 +21,7 @@
21
21
  * concatenated after exit are byte-identical), and `history.append` already
22
22
  * retains those views for its 512 KiB scrollback, so a defensive copy per
23
23
  * read would cost exactly what the coalescing is there to save.
24
- * - **Split sequences.** xterm parses a byte stream across `write` calls, so a
24
+ * - **Split sequences.** the parser reads a byte stream across `write` calls, so a
25
25
  * frame boundary mid-escape is harmless — dropping bytes is not, which is why
26
26
  * a flush never discards anything it accepted.
27
27
  * - **Buffer without a bound.** The flush is size- or time-triggered, so a
@@ -0,0 +1,99 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * A resize moves the PTY *and* the grid the retained history is replayed at.
8
+ *
9
+ * The replay size used to be frozen at the session's spawn size. That is wrong
10
+ * the moment the panel is resized: the history is the shell's screen stream, and
11
+ * after a resize the shell's screen is the new grid, so replaying at the old one
12
+ * re-wraps every line written since. Measured on the real panel: after a resize
13
+ * each reload laid the history out at the old 40×31, then fitted to 41×47, so the
14
+ * transcript shifted and the shell redrew its prompt on the resize that followed
15
+ * — one more block of history per reload, which is exactly the "the rows march
16
+ * down on every reload" report.
17
+ *
18
+ * The records here are fakes (no PTY): the decision is the session's, and the
19
+ * probe is the real one because "did the size change" is what the test is about.
20
+ */
21
+
22
+ import { afterEach, describe, expect, test } from 'bun:test';
23
+ import { resizeTerminal } from '@/server/lib/terminal/runtime.server';
24
+ import { terminalStore, type TerminalStore } from '@/server/lib/terminal/store';
25
+ import { createTerminalOutputQueue } from '@/server/lib/terminal/output';
26
+ import type { TerminalSession } from '@/server/lib/terminal/session.server';
27
+
28
+ function fakeSession(over: Partial<TerminalSession> = {}): TerminalSession {
29
+ return {
30
+ id: 'resize-test',
31
+ cwd: '/tmp',
32
+ shell: '/bin/sh',
33
+ term: { resize: () => {}, write: () => {} } as unknown as TerminalSession['term'],
34
+ proc: null,
35
+ history: { append: () => {}, replay: () => new Uint8Array(), size: () => 0 } as unknown as TerminalSession['history'],
36
+ output: createTerminalOutputQueue(() => {}),
37
+ viewers: new Set(),
38
+ cols: 80,
39
+ rows: 24,
40
+ replayCols: 80,
41
+ replayRows: 24,
42
+ status: 'running',
43
+ exitCode: null,
44
+ signal: null,
45
+ lastActivity: Date.now(),
46
+ ...over,
47
+ };
48
+ }
49
+
50
+ function store(): TerminalStore {
51
+ return terminalStore();
52
+ }
53
+
54
+ afterEach(() => {
55
+ const { sessions, resizeTimers } = store();
56
+ for (const timer of resizeTimers.values()) clearTimeout(timer);
57
+ resizeTimers.clear();
58
+ for (const session of sessions.values()) session.output.dispose();
59
+ sessions.clear();
60
+ });
61
+
62
+ describe('resizeTerminal', () => {
63
+ test('moves the PTY and the replay grid together', () => {
64
+ const session = fakeSession();
65
+ store().sessions.set(session.id, session);
66
+
67
+ resizeTerminal(session.id, 41, 47);
68
+
69
+ expect(session.cols).toBe(41);
70
+ expect(session.rows).toBe(47);
71
+ // The replay follows, or every reload re-wraps the history at the old size.
72
+ expect(session.replayCols).toBe(41);
73
+ expect(session.replayRows).toBe(47);
74
+ });
75
+
76
+ test('does nothing for the size the session already has', () => {
77
+ let resizes = 0;
78
+ const session = fakeSession({
79
+ term: { resize: () => { resizes += 1; }, write: () => {} } as unknown as TerminalSession['term'],
80
+ });
81
+ store().sessions.set(session.id, session);
82
+
83
+ resizeTerminal(session.id, 80, 24);
84
+
85
+ expect(resizes).toBe(0);
86
+ });
87
+
88
+ test('clamps a grid to the protocol bounds before applying it', () => {
89
+ const session = fakeSession();
90
+ store().sessions.set(session.id, session);
91
+
92
+ resizeTerminal(session.id, 1, 100_000);
93
+
94
+ expect(session.cols).toBe(2);
95
+ expect(session.rows).toBe(500);
96
+ expect(session.replayCols).toBe(2);
97
+ expect(session.replayRows).toBe(500);
98
+ });
99
+ });