@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
@@ -10,6 +10,7 @@ import { readHandoverFromStdin } from '@/shared/lib/auth/handover';
10
10
  import { ssrRoutes } from '@/server/plugins/ssr';
11
11
  import { setListener } from '@/server/lib/lifecycle/listener';
12
12
  import { getDatabasePath } from '@/server/db.server';
13
+ import { initAgentTokens } from '@/server/lib/sessions/agent-token.server';
13
14
  import { logDetectedRegistry } from '@/server/lib/models/detected-registry.server';
14
15
  import { ompStartupError, ompStartupLogLines } from '@/server/lib/omp/core/startup';
15
16
  import { readInstanceRecord, removeInstanceRecord, writeInstanceRecord } from '@/server/lib/lifecycle/instance';
@@ -67,6 +68,7 @@ console.log(`[kabmo] mock mode: ${isMockMode() ? 'true (demo presets)' : 'f
67
68
  console.log(`[kabmo] ui auth: ${authNotice}${runPassword.source === 'argv' ? ' [from argv]' : ''}`);
68
69
  for (const line of ompStartupLogLines()) console.log(`[kabmo] ${line}`);
69
70
  console.log(`[kabmo] db: ${await getDatabasePath()}`);
71
+ await initAgentTokens();
70
72
 
71
73
  const port = Number(Bun.env.PORT) || 3000;
72
74
  const host = Bun.env.HOST || 'localhost';
@@ -28,6 +28,7 @@
28
28
 
29
29
  import { hashPassword, deriveCredentialKey, readSessionSecret, writeSessionSecret, type ActiveAuthConfig } from '@/server/lib/auth/config';
30
30
  import { readSessionCookie, verifySessionToken } from '@/server/lib/auth/token';
31
+ import { agentTokenScopeForPath, bearerToken, verifyAgentToken } from '@/server/lib/sessions/agent-token.server';
31
32
  import { rememberClientAddress } from '@/server/lib/auth/client-address';
32
33
  import type { CredentialHandover } from '@/shared/lib/auth/handover';
33
34
 
@@ -290,6 +291,15 @@ export function authGate(request: Request, clientAddress?: string): Response | u
290
291
  return undefined;
291
292
  }
292
293
 
294
+ // An agent subprocess carries a bearer token instead of a cookie. It is
295
+ // scoped by path to the session it names; spawn is the one path a child may
296
+ // call under its own token (to create its own children).
297
+ const scope = agentTokenScopeForPath(pathname);
298
+ if (scope) {
299
+ const agentSession = verifyAgentToken(bearerToken(request));
300
+ if (agentSession && (scope === 'any' || scope === agentSession)) return undefined;
301
+ }
302
+
293
303
  const wantsHtml = (request.headers.get('accept') ?? '').includes('text/html');
294
304
  return rejectionResponse(pathname, wantsHtml);
295
305
  }
@@ -35,7 +35,12 @@ import fs from 'fs';
35
35
  import * as path from 'path';
36
36
  import { getDatabasePath } from '@/server/db.server';
37
37
  import { clearSessionFileCaches } from '@/server/lib/omp/session/files';
38
- import { serializeTitleSlot } from '@/server/lib/omp/session/title-slot';
38
+ import {
39
+ buildTitleLine,
40
+ completeLines,
41
+ lastEntryId,
42
+ parseJsonObject,
43
+ } from '@/server/lib/omp/session/transcript-copy';
39
44
  import { isRecord } from '@/shared/lib/util/guards';
40
45
 
41
46
  /** Root holding every topic workspace, beside Kabmo database. */
@@ -45,37 +50,6 @@ export async function getBtwRoot(): Promise<string> {
45
50
  return root;
46
51
  }
47
52
 
48
- function parseJsonObject(line: string): Record<string, unknown> | null {
49
- try {
50
- const value: unknown = JSON.parse(line);
51
- return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
52
- } catch {
53
- return null;
54
- }
55
- }
56
-
57
- /**
58
- * The file's lines, minus a torn tail. A snapshot taken while the parent is
59
- * mid-append can end in a partial line; keeping it would make the side child
60
- * fail to load the transcript.
61
- */
62
- function completeLines(text: string): string[] {
63
- const lines = text.split('\n');
64
- if (lines[lines.length - 1] === '') lines.pop();
65
- const last = lines[lines.length - 1];
66
- if (last !== undefined && parseJsonObject(last) === null) lines.pop();
67
- return lines;
68
- }
69
-
70
- /** The transcript's leaf: the id of its last entry. */
71
- export function lastEntryId(lines: string[]): string | null {
72
- for (let index = lines.length - 1; index >= 0; index -= 1) {
73
- const record = parseJsonObject(lines[index]);
74
- if (record && typeof record.id === 'string') return record.id;
75
- }
76
- return null;
77
- }
78
-
79
53
  /** Read a transcript's leaf id straight from disk. */
80
54
  export async function readTranscriptLeaf(sessionFile: string): Promise<string | null> {
81
55
  try {
@@ -85,18 +59,6 @@ export async function readTranscriptLeaf(sessionFile: string): Promise<string |
85
59
  }
86
60
  }
87
61
 
88
- /** The title slot line, padded to the fixed slot omp rewrites in place, with
89
- * the trailing newline removed (the writer here joins lines itself).
90
- *
91
- * Delegates to the repo's slot serializer rather than re-deriving the width:
92
- * that one truncates the title by code point, so a question written in CJK
93
- * (up to 3 UTF-8 bytes each) still fits — clipping by character count alone
94
- * would overflow the slot and fail promotion outright. */
95
- export function buildTitleLine(title: string, source: string, updatedAt: string): string {
96
- const line = serializeTitleSlot({ title, source: source === 'auto' ? 'auto' : 'user', updatedAt });
97
- return line.endsWith('\n') ? line.slice(0, -1) : line;
98
- }
99
-
100
62
  export interface BtwWorkspace {
101
63
  dir: string;
102
64
  sessionFile: string;
@@ -13,7 +13,8 @@ import { afterEach, describe, expect, test } from 'bun:test';
13
13
  import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
14
14
  import { tmpdir } from 'os';
15
15
  import { join } from 'path';
16
- import { buildTitleLine, createBtwWorkspace, getBtwRoot, promoteBtwTopic, readTranscriptLeaf } from '@/server/lib/btw/session-copy.server';
16
+ import { buildTitleLine } from '@/server/lib/omp/session/transcript-copy';
17
+ import { createBtwWorkspace, getBtwRoot, promoteBtwTopic, readTranscriptLeaf } from '@/server/lib/btw/session-copy.server';
17
18
 
18
19
  const timestamp = '2026-09-23T08:41:10.683Z';
19
20
  const createdDirs: string[] = [];
@@ -23,6 +23,7 @@ import { ensureUsageIndexSchema } from '@/server/lib/usage/index-schema.server';
23
23
  import { ensureWorktreeSchema } from '@/server/lib/db/worktree-registry.server';
24
24
  import { ensureReviewSchema } from '@/server/lib/review/schema.server';
25
25
  import { ensureHarnessSchema } from '@/server/lib/harness/schema.server';
26
+ import { ensureSessionRelationsSchema } from '@/server/lib/sessions/schema.server';
26
27
  import { migrateWorkspaceFolderColumns } from '@/shared/lib/workspace/schema-migrations';
27
28
  import { migrateSessionStreamStateColumns } from '@/shared/lib/omp/session/schema-migrations';
28
29
 
@@ -141,6 +142,9 @@ export async function initSchema(db: DbClient): Promise<void> {
141
142
  // Harness ownership per session: the sidebar's mark needs it, and it has to
142
143
  // outlive the process that spawned the child (a restart, a second instance).
143
144
  await ensureHarnessSchema(db);
145
+ // Session trees: parent, cleanup ownership and fork origin. Keyed by the id
146
+ // the sidebar and the URL use, so it works for omp files and ACP sessions.
147
+ await ensureSessionRelationsSchema(db);
144
148
  await db.exec(`
145
149
  CREATE TABLE IF NOT EXISTS files (
146
150
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -22,7 +22,7 @@
22
22
  *
23
23
  * The `terminal/session.server.ts` helpers are pinned alongside because they
24
24
  * need no PTY: the viewer fan-out drop rule (a viewer that cannot keep up is
25
- * dropped, never skipped, or xterm's parser is left mid-sequence), the snapshot
25
+ * dropped, never skipped, or the renderer's parser is left mid-sequence), the snapshot
26
26
  * shape, and the process-group signalling fallback for a session with no child.
27
27
  * Anything requiring a real PTY spawn is deliberately not tested here.
28
28
  */
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * The `terminal/session.server.ts` helpers are pinned alongside because they
18
18
  * need no PTY: the viewer fan-out drop rule (a viewer that cannot keep up is
19
- * dropped, never skipped, or xterm's parser is left mid-sequence), the snapshot
19
+ * dropped, never skipped, or the renderer's parser is left mid-sequence), the snapshot
20
20
  * shape, and the process-group signalling fallback for a session with no child.
21
21
  * Anything requiring a real PTY spawn is deliberately not tested here.
22
22
  */
@@ -0,0 +1,262 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The delayed-answer probe: antigravity ends a turn when it SPAWNS a subagent
8
+ * and holds the completion until the next request (upstream #1461), so Kabmo
9
+ * replays the transcript with `session/load` and emits only the text the
10
+ * operator has not seen.
11
+ */
12
+
13
+ import { describe, expect, test } from 'bun:test';
14
+ import {
15
+ AcpBackgroundProbe,
16
+ backgroundNotice,
17
+ backgroundNoticeFrames,
18
+ spawnsBackgroundWork,
19
+ } from '@/server/lib/harness/acp/background-work';
20
+
21
+ const toolCall = (name: string) => ({
22
+ role: 'assistant',
23
+ content: [{ type: 'toolCall', id: 't1', name }],
24
+ });
25
+
26
+ const chunk = (update: Record<string, unknown>) => ({ update });
27
+ const textChunk = (kind: 'user_message_chunk' | 'agent_message_chunk', text: string) =>
28
+ chunk({ sessionUpdate: kind, content: { type: 'text', text } });
29
+
30
+ interface FakeTimer {
31
+ fn: () => void;
32
+ ms: number;
33
+ cancelled: boolean;
34
+ }
35
+
36
+ function isFakeTimer(value: unknown): value is FakeTimer {
37
+ return (
38
+ typeof value === 'object' &&
39
+ value !== null &&
40
+ 'fn' in value &&
41
+ 'ms' in value &&
42
+ 'cancelled' in value &&
43
+ typeof value.fn === 'function' &&
44
+ typeof value.ms === 'number' &&
45
+ typeof value.cancelled === 'boolean'
46
+ );
47
+ }
48
+
49
+ /** The probe arms a timer; cases drive it themselves so nothing sleeps. */
50
+ function timers() {
51
+ const scheduled: FakeTimer[] = [];
52
+ return {
53
+ schedule: (fn: () => void, ms: number): unknown => {
54
+ const handle: FakeTimer = { fn, ms, cancelled: false };
55
+ scheduled.push(handle);
56
+ return handle;
57
+ },
58
+ cancel: (handle: unknown): void => {
59
+ if (isFakeTimer(handle)) handle.cancelled = true;
60
+ },
61
+ next: (): FakeTimer | undefined => scheduled.shift(),
62
+ pending: () => scheduled.filter((handle) => !handle.cancelled),
63
+ };
64
+ }
65
+
66
+ async function settle(): Promise<void> {
67
+ for (let i = 0; i < 6; i += 1) await Promise.resolve();
68
+ }
69
+
70
+ describe('background work detection', () => {
71
+ test('a spawned subagent tool call is background work', () => {
72
+ expect(spawnsBackgroundWork(toolCall('invoke_subagent'))).toBe(true);
73
+ expect(spawnsBackgroundWork(toolCall('spawn_subagent'))).toBe(true);
74
+ });
75
+
76
+ test('an awaited tool call is not', () => {
77
+ expect(spawnsBackgroundWork(toolCall('run_command'))).toBe(false);
78
+ expect(spawnsBackgroundWork({ role: 'assistant', content: [{ type: 'text', text: 'hi' }] })).toBe(false);
79
+ expect(spawnsBackgroundWork(undefined)).toBe(false);
80
+ });
81
+ });
82
+
83
+ describe('delayed notice extraction', () => {
84
+ test('returns only the text past the answer already shown', () => {
85
+ expect(backgroundNotice('Sedang membuat…', 'Sedang membuat…\nBerikut gambarnya')).toBe('Berikut gambarnya');
86
+ });
87
+
88
+ test('a replay of the same answer is not a notice', () => {
89
+ expect(backgroundNotice('Sedang membuat…', 'Sedang membuat…')).toBeNull();
90
+ });
91
+
92
+ test('a diverged replay is not guessed at', () => {
93
+ expect(backgroundNotice('Sedang membuat…', 'Jawaban lain')).toBeNull();
94
+ });
95
+
96
+ test('an empty baseline accepts the whole segment', () => {
97
+ expect(backgroundNotice('', 'Berikut gambarnya')).toBe('Berikut gambarnya');
98
+ });
99
+ });
100
+
101
+ describe('background notice frames', () => {
102
+ test('form a complete run so the client releases its generating flag', () => {
103
+ const frames = backgroundNoticeFrames('Berikut gambarnya');
104
+ expect(frames.map((frame) => frame.type)).toEqual([
105
+ 'agent_start',
106
+ 'turn_start',
107
+ 'message_update',
108
+ 'message_end',
109
+ 'agent_end',
110
+ ]);
111
+ expect(frames[3]).toMatchObject({
112
+ type: 'message_end',
113
+ message: { role: 'assistant', content: [{ type: 'text', text: 'Berikut gambarnya' }] },
114
+ });
115
+ expect(frames[4]).toMatchObject({ type: 'agent_end', isTerminal: true });
116
+ });
117
+ });
118
+
119
+ describe('AcpBackgroundProbe', () => {
120
+ test('backs off and emits once a replay carries new text', async () => {
121
+ const clock = timers();
122
+ const emitted: string[] = [];
123
+ let probe!: AcpBackgroundProbe;
124
+ const replays = ['Sedang membuat…', 'Sedang membuat…\nBerikut gambarnya', 'Sedang membuat…\nBerikut gambarnya'];
125
+ let attempts = 0;
126
+ probe = new AcpBackgroundProbe({
127
+ load: async () => {
128
+ const text = replays[Math.min(attempts, replays.length - 1)];
129
+ attempts += 1;
130
+ probe.consume('session/update', textChunk('user_message_chunk', 'buat gambar'));
131
+ for (const piece of text.split('\n')) {
132
+ probe.consume('session/update', textChunk('agent_message_chunk', piece));
133
+ }
134
+ return {};
135
+ },
136
+ resetIdle: () => {},
137
+ emit: (text) => emitted.push(text),
138
+ firstDelayMs: 10,
139
+ maxDelayMs: 40,
140
+ now: () => 0,
141
+ schedule: clock.schedule,
142
+ cancel: clock.cancel,
143
+ });
144
+
145
+ probe.start('Sedang membuat…');
146
+ const first = clock.next();
147
+ expect(first?.ms).toBe(10);
148
+ first?.fn();
149
+ await settle();
150
+ expect(attempts).toBe(1);
151
+ expect(emitted).toEqual([]);
152
+ // No notice yet: the next attempt is scheduled with a doubled delay.
153
+ const second = clock.next();
154
+ expect(second?.ms).toBe(20);
155
+ second?.fn();
156
+ await settle();
157
+ expect(attempts).toBe(2);
158
+ // A first sighting is a prefix while the agent is still writing.
159
+ expect(emitted).toEqual([]);
160
+ const third = clock.next();
161
+ expect(third?.ms).toBe(10);
162
+ third?.fn();
163
+ await settle();
164
+ expect(attempts).toBe(3);
165
+ expect(emitted).toEqual(['Berikut gambarnya']);
166
+ expect(clock.pending()).toHaveLength(0);
167
+ });
168
+
169
+ test('swallows the replay, and stops swallowing once its load resolves', async () => {
170
+ const clock = timers();
171
+ const deferred = Promise.withResolvers<unknown>();
172
+ let probe!: AcpBackgroundProbe;
173
+ probe = new AcpBackgroundProbe({
174
+ load: () => deferred.promise,
175
+ resetIdle: () => {},
176
+ emit: () => {},
177
+ schedule: clock.schedule,
178
+ cancel: clock.cancel,
179
+ });
180
+
181
+ expect(probe.consume('session/update', textChunk('agent_message_chunk', 'x'))).toBe(false);
182
+ probe.start('wait');
183
+ clock.next()?.fn();
184
+ await settle();
185
+ expect(probe.consume('session/update', textChunk('agent_message_chunk', 'replay'))).toBe(true);
186
+
187
+ deferred.resolve({});
188
+ await settle();
189
+ expect(probe.consume('session/update', textChunk('agent_message_chunk', 'live'))).toBe(false);
190
+ });
191
+
192
+ test('a stopped probe still swallows the replay its load is waiting on', async () => {
193
+ const clock = timers();
194
+ const deferred = Promise.withResolvers<unknown>();
195
+ let probe!: AcpBackgroundProbe;
196
+ probe = new AcpBackgroundProbe({
197
+ load: () => deferred.promise,
198
+ resetIdle: () => {},
199
+ emit: () => {},
200
+ schedule: clock.schedule,
201
+ cancel: clock.cancel,
202
+ });
203
+
204
+ probe.start('wait');
205
+ clock.next()?.fn();
206
+ await settle();
207
+ probe.stop();
208
+ expect(probe.consume('session/update', textChunk('agent_message_chunk', 'replay'))).toBe(true);
209
+ deferred.resolve({});
210
+ await settle();
211
+ expect(probe.consume('session/update', textChunk('agent_message_chunk', 'live'))).toBe(false);
212
+ });
213
+
214
+ test('retries a failed load, then gives up instead of spinning', async () => {
215
+ const clock = timers();
216
+ let loads = 0;
217
+ const probe = new AcpBackgroundProbe({
218
+ load: async () => {
219
+ loads += 1;
220
+ throw new Error('session/load is busy');
221
+ },
222
+ resetIdle: () => {},
223
+ emit: () => {},
224
+ timeoutMs: 60_000,
225
+ firstDelayMs: 10,
226
+ now: () => 0,
227
+ schedule: clock.schedule,
228
+ cancel: clock.cancel,
229
+ });
230
+
231
+ probe.start('wait');
232
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
233
+ clock.next()?.fn();
234
+ await settle();
235
+ expect(loads).toBe(attempt);
236
+ }
237
+ expect(clock.pending()).toHaveLength(0);
238
+ });
239
+
240
+ test('gives up at its deadline instead of polling forever', async () => {
241
+ const clock = timers();
242
+ let loads = 0;
243
+ const probe = new AcpBackgroundProbe({
244
+ load: async () => {
245
+ loads += 1;
246
+ return {};
247
+ },
248
+ resetIdle: () => {},
249
+ emit: () => {},
250
+ timeoutMs: 0,
251
+ firstDelayMs: 10,
252
+ schedule: clock.schedule,
253
+ cancel: clock.cancel,
254
+ });
255
+
256
+ probe.start('wait');
257
+ clock.next()?.fn();
258
+ await settle();
259
+ expect(loads).toBe(1);
260
+ expect(clock.pending()).toHaveLength(0);
261
+ });
262
+ });