@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,212 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Child outcomes → one message in the parent's queue.
8
+ *
9
+ * A turn end is the event a parent asked about, but waking it once per child
10
+ * turns a fan-out into a notification storm: ten children finishing within a
11
+ * second would open ten turns, each obliged to read the other nine. So outcomes
12
+ * land in `session_notices` first, coalesce for a short window, and become ONE
13
+ * `queued_messages` row — the queue already owns durability, retry and busy
14
+ * handling, and a second delivery path would drift from it.
15
+ *
16
+ * Only a delegated child notifies. A fork has no parent edge; a child whose
17
+ * `parentNotifications` is `off` or whose outcome is filtered by `stuck` writes
18
+ * nothing.
19
+ */
20
+
21
+ import { getDb } from '@/server/db.server';
22
+ import { appendQueueItem } from '@/server/lib/queue/store.server';
23
+ import { deliverQueueNow } from '@/server/lib/queue/delivery.server';
24
+ import { getSessionRelation } from '@/server/lib/sessions/relations.server';
25
+ import { isSessionArchived } from '@/server/lib/sessions/resolve.server';
26
+ import { ensureSessionLive } from '@/server/lib/sessions/dispatch.server';
27
+
28
+ export const NOTICE_WINDOW_MS = 2_000;
29
+ const OUTPUT_EXCERPT_LIMIT = 4_000;
30
+ const TRUNCATION_MARKER = '\n\n[... output truncated ...]';
31
+ const COALESCE_KEY = 'child-outcomes';
32
+
33
+ export interface ChildOutcomeNotice {
34
+ sessionId: string;
35
+ title?: string | null;
36
+ status: 'completed' | 'failed' | 'interrupted';
37
+ /** The child's final assistant text, when the transport could read it. */
38
+ output?: string | null;
39
+ /** Why it failed or was interrupted, when known. */
40
+ failure?: string | null;
41
+ }
42
+
43
+ interface NoticeRow {
44
+ id: string;
45
+ parent_session_id: string;
46
+ coalesce_key: string;
47
+ state: string;
48
+ send_at: number;
49
+ }
50
+
51
+ declare global {
52
+ // eslint-disable-next-line no-var
53
+ var __kabmoNoticeTimers: Map<string, ReturnType<typeof setTimeout>> | undefined;
54
+ }
55
+
56
+ function timers(): Map<string, ReturnType<typeof setTimeout>> {
57
+ globalThis.__kabmoNoticeTimers ??= new Map();
58
+ return globalThis.__kabmoNoticeTimers;
59
+ }
60
+
61
+ function excerpt(text: string | null | undefined): string {
62
+ const trimmed = text?.trim();
63
+ if (!trimmed) return 'No final output was recorded.';
64
+ if (trimmed.length <= OUTPUT_EXCERPT_LIMIT) return trimmed;
65
+ const keep = Math.max(0, OUTPUT_EXCERPT_LIMIT - TRUNCATION_MARKER.length);
66
+ return `${trimmed.slice(0, keep).trimEnd()}${TRUNCATION_MARKER}`;
67
+ }
68
+
69
+ function describe(item: ChildOutcomeNotice): string {
70
+ const title = item.title?.trim();
71
+ return title ? `"${title}" (${item.sessionId})` : item.sessionId;
72
+ }
73
+
74
+ function oneLine(text: string): string {
75
+ return text.replace(/\s+/g, ' ').trim();
76
+ }
77
+
78
+ function renderOutcome(item: ChildOutcomeNotice): string {
79
+ const label = describe(item);
80
+ if (item.status === 'completed') {
81
+ return `Child session ${label} completed:\n\n${excerpt(item.output)}`;
82
+ }
83
+ const reason =
84
+ item.status === 'interrupted'
85
+ ? item.failure || 'it was interrupted'
86
+ : item.failure || 'it failed';
87
+ return `Child session ${label} ${reason}.\n\nReview the session before deciding the next step.`;
88
+ }
89
+
90
+ /** One notice body, for one child or a coalesced batch. */
91
+ export function renderChildOutcomeNotice(items: readonly ChildOutcomeNotice[]): string {
92
+ if (items.length === 1 && items[0]) return renderOutcome(items[0]);
93
+ const lines = items.map((item) => {
94
+ const label = describe(item);
95
+ if (item.status === 'completed') {
96
+ return `- ${label} completed: ${oneLine(excerpt(item.output))}`;
97
+ }
98
+ return `- ${label} ${item.failure || item.status}.`;
99
+ });
100
+ return `Child session updates:\n\n${lines.join('\n')}`;
101
+ }
102
+
103
+ function mergeOutcome(
104
+ previous: readonly ChildOutcomeNotice[],
105
+ next: ChildOutcomeNotice,
106
+ ): ChildOutcomeNotice[] {
107
+ const index = previous.findIndex((item) => item.sessionId === next.sessionId);
108
+ if (index === -1) return [...previous, next];
109
+ return previous.map((item, position) => (position === index ? next : item));
110
+ }
111
+
112
+ function shouldNotify(
113
+ status: ChildOutcomeNotice['status'],
114
+ preference: 'auto' | 'stuck' | 'off',
115
+ ): boolean {
116
+ if (preference === 'off') return false;
117
+ if (preference === 'stuck') return status !== 'completed';
118
+ return true;
119
+ }
120
+
121
+ /**
122
+ * Record one outcome, coalescing it into the parent's open window.
123
+ *
124
+ * Best-effort by contract: this runs from a turn-settle hook, and a database
125
+ * failure must not turn a finished turn into a failed one. The caller wraps it.
126
+ */
127
+ export async function noteChildOutcome(outcome: ChildOutcomeNotice): Promise<void> {
128
+ const relation = await getSessionRelation(outcome.sessionId);
129
+ if (!relation?.parentSessionId || relation.originKind !== null) return;
130
+ if (!shouldNotify(outcome.status, relation.parentNotifications)) return;
131
+
132
+ const parentSessionId = relation.parentSessionId;
133
+ if (await isSessionArchived(parentSessionId)) return;
134
+
135
+ const db = await getDb();
136
+ const now = Date.now();
137
+ const sendAt = now + NOTICE_WINDOW_MS;
138
+ const existing = await db.get<NoticeRow>(
139
+ 'SELECT * FROM session_notices WHERE parent_session_id = ? AND coalesce_key = ?',
140
+ [parentSessionId, COALESCE_KEY],
141
+ );
142
+ const previous = existing
143
+ ? (JSON.parse(existing.state) as ChildOutcomeNotice[])
144
+ : [];
145
+ const state = JSON.stringify(mergeOutcome(previous, outcome));
146
+ await db.run(
147
+ `INSERT INTO session_notices
148
+ (id, parent_session_id, coalesce_key, state, send_at, created_at, updated_at)
149
+ VALUES (?, ?, ?, ?, ?, ?, ?)
150
+ ON CONFLICT(parent_session_id, coalesce_key) DO UPDATE SET
151
+ state = excluded.state,
152
+ send_at = excluded.send_at,
153
+ updated_at = excluded.updated_at`,
154
+ [crypto.randomUUID(), parentSessionId, COALESCE_KEY, state, sendAt, now, now],
155
+ );
156
+
157
+ clearTimeout(timers().get(parentSessionId));
158
+ timers().set(
159
+ parentSessionId,
160
+ setTimeout(() => {
161
+ timers().delete(parentSessionId);
162
+ void flushNotice(parentSessionId).catch((error) => {
163
+ console.error(
164
+ `[sessions] could not deliver child outcomes to ${parentSessionId}:`,
165
+ error instanceof Error ? error.message : error,
166
+ );
167
+ });
168
+ }, NOTICE_WINDOW_MS),
169
+ );
170
+ }
171
+
172
+ /** Drop a pending window without materialising it (tests and session purge). */
173
+ export function cancelNoticeTimer(parentSessionId: string): void {
174
+ clearTimeout(timers().get(parentSessionId));
175
+ timers().delete(parentSessionId);
176
+ }
177
+
178
+ /**
179
+ * Turn an open window into one queue row, without waking the parent.
180
+ *
181
+ * Split from `flushNotice` so a test can prove the merge and the text without
182
+ * spawning a process. Returns null when another caller already claimed it.
183
+ */
184
+ export async function materializeNotice(parentSessionId: string): Promise<string | null> {
185
+ const db = await getDb();
186
+ const row = await db.get<NoticeRow>(
187
+ 'SELECT * FROM session_notices WHERE parent_session_id = ? AND coalesce_key = ?',
188
+ [parentSessionId, COALESCE_KEY],
189
+ );
190
+ if (!row) return null;
191
+ // The DELETE is the claim: two timers (a hot reload, a second instance)
192
+ // cannot both turn one window into two queue rows.
193
+ const claimed = await db.run(
194
+ 'DELETE FROM session_notices WHERE parent_session_id = ? AND coalesce_key = ?',
195
+ [parentSessionId, COALESCE_KEY],
196
+ );
197
+ if (claimed.changes === 0) return null;
198
+
199
+ const items = JSON.parse(row.state) as ChildOutcomeNotice[];
200
+ if (items.length === 0) return null;
201
+ const text = renderChildOutcomeNotice(items);
202
+ await appendQueueItem(parentSessionId, { text });
203
+ return text;
204
+ }
205
+
206
+ /** Materialize the window, then make sure the parent is awake to read it. */
207
+ export async function flushNotice(parentSessionId: string): Promise<void> {
208
+ const text = await materializeNotice(parentSessionId);
209
+ if (text === null) return;
210
+ const session = await ensureSessionLive(parentSessionId);
211
+ if (session) await deliverQueueNow(session);
212
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The vocabulary of a session tree: its shape, its error codes, and the row
8
+ * decoder. Split from the service so a route can name a refusal's code without
9
+ * importing the write path.
10
+ */
11
+
12
+ export const MAX_SESSION_DEPTH = 4;
13
+
14
+ export type SessionVisibility = 'visible' | 'hidden';
15
+ export type ParentNotifications = 'auto' | 'stuck' | 'off';
16
+ export type SessionOriginKind = 'fork';
17
+
18
+ export interface SessionRelation {
19
+ sessionId: string;
20
+ parentSessionId: string | null;
21
+ lifecycleOwnerSessionId: string | null;
22
+ sourceSessionId: string | null;
23
+ originKind: SessionOriginKind | null;
24
+ visibility: SessionVisibility;
25
+ parentNotifications: ParentNotifications;
26
+ depth: number;
27
+ createdAt: number;
28
+ }
29
+
30
+ export type SessionRelationErrorCode =
31
+ | 'invalid_argument'
32
+ | 'self_parent'
33
+ | 'cycle'
34
+ | 'depth_exceeded'
35
+ | 'fork_requires_source'
36
+ | 'fork_is_not_a_child'
37
+ | 'not_fork';
38
+
39
+ export class SessionRelationError extends Error {
40
+ constructor(
41
+ readonly code: SessionRelationErrorCode,
42
+ message: string,
43
+ ) {
44
+ super(message);
45
+ this.name = 'SessionRelationError';
46
+ }
47
+ }
48
+
49
+ export interface RelationRow {
50
+ session_id: string;
51
+ parent_session_id: string | null;
52
+ lifecycle_owner_session_id: string | null;
53
+ source_session_id: string | null;
54
+ origin_kind: string | null;
55
+ visibility: string;
56
+ parent_notifications: string;
57
+ depth: number;
58
+ created_at: number;
59
+ }
60
+
61
+ export function fromRow(row: RelationRow): SessionRelation {
62
+ return {
63
+ sessionId: row.session_id,
64
+ parentSessionId: row.parent_session_id,
65
+ lifecycleOwnerSessionId: row.lifecycle_owner_session_id,
66
+ sourceSessionId: row.source_session_id,
67
+ originKind: row.origin_kind === 'fork' ? 'fork' : null,
68
+ visibility: row.visibility === 'hidden' ? 'hidden' : 'visible',
69
+ parentNotifications:
70
+ row.parent_notifications === 'stuck' || row.parent_notifications === 'off'
71
+ ? row.parent_notifications
72
+ : 'auto',
73
+ depth: row.depth,
74
+ createdAt: row.created_at,
75
+ };
76
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Session trees: depth, cycles, the fork edge, and cleanup edges.
8
+ *
9
+ * A session has no row of its own, so these cases use bare ids — which is the
10
+ * point of the module: the tree is a relationship store, and every rule here
11
+ * must hold for an omp file and an ACP session alike.
12
+ */
13
+
14
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
15
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
16
+ import { getDb } from '@/server/db.server';
17
+ import { ensureSessionRelationsSchema } from '@/server/lib/sessions/schema.server';
18
+ import {
19
+ MAX_SESSION_DEPTH,
20
+ SessionRelationError,
21
+ } from '@/server/lib/sessions/relation-types';
22
+ import {
23
+ createSessionRelation,
24
+ deleteSessionRelations,
25
+ getSessionRelation,
26
+ listChildRelations,
27
+ listForkRelations,
28
+ listOwnedRelations,
29
+ setParentNotifications,
30
+ setSessionParent,
31
+ setSessionVisibility,
32
+ } from '@/server/lib/sessions/relations.server';
33
+
34
+ beforeEach(async () => {
35
+ await isolateDb();
36
+ // The relations tables are created by `initSchema`; the explicit call keeps
37
+ // this suite runnable when it is the first to open the temp database.
38
+ await ensureSessionRelationsSchema(await getDb());
39
+ });
40
+
41
+ afterEach(async () => {
42
+ await releaseDb();
43
+ });
44
+
45
+ /** The error code a rejected call reported, or null when it resolved. */
46
+ async function rejectionCode(run: () => Promise<unknown>): Promise<string | null> {
47
+ try {
48
+ await run();
49
+ return null;
50
+ } catch (error) {
51
+ return error instanceof SessionRelationError ? error.code : `unexpected:${String(error)}`;
52
+ }
53
+ }
54
+
55
+ describe('session relations', () => {
56
+ test('a child of a root starts at depth 1 and carries the parent edge', async () => {
57
+ const relation = await createSessionRelation({
58
+ sessionId: 'child',
59
+ parentSessionId: 'root',
60
+ lifecycleOwnerSessionId: 'root',
61
+ });
62
+ expect(relation).toMatchObject({
63
+ sessionId: 'child',
64
+ parentSessionId: 'root',
65
+ lifecycleOwnerSessionId: 'root',
66
+ depth: 1,
67
+ visibility: 'visible',
68
+ parentNotifications: 'auto',
69
+ originKind: null,
70
+ });
71
+ expect(await listChildRelations('root')).toHaveLength(1);
72
+ });
73
+
74
+ test(`the tree stops at ${MAX_SESSION_DEPTH} levels`, async () => {
75
+ await createSessionRelation({ sessionId: 'l1', parentSessionId: 'root' });
76
+ await createSessionRelation({ sessionId: 'l2', parentSessionId: 'l1' });
77
+ await createSessionRelation({ sessionId: 'l3', parentSessionId: 'l2' });
78
+ // l4 is the fourth level and is allowed.
79
+ const fourth = await createSessionRelation({ sessionId: 'l4', parentSessionId: 'l3' });
80
+ expect(fourth.depth).toBe(4);
81
+
82
+ expect(
83
+ await rejectionCode(() =>
84
+ createSessionRelation({ sessionId: 'l5', parentSessionId: 'l4' }),
85
+ ),
86
+ ).toBe('depth_exceeded');
87
+ });
88
+
89
+ test('a session cannot be reparented under its own descendant', async () => {
90
+ await createSessionRelation({ sessionId: 'a' });
91
+ await createSessionRelation({ sessionId: 'b', parentSessionId: 'a' });
92
+ await createSessionRelation({ sessionId: 'c', parentSessionId: 'b' });
93
+
94
+ expect(await rejectionCode(() => setSessionParent('a', 'c'))).toBe('cycle');
95
+ expect(await rejectionCode(() => setSessionParent('a', 'a'))).toBe('self_parent');
96
+ });
97
+
98
+ test('reparenting recomputes every descendant depth', async () => {
99
+ await createSessionRelation({ sessionId: 'a' });
100
+ await createSessionRelation({ sessionId: 'b', parentSessionId: 'a' });
101
+ await createSessionRelation({ sessionId: 'c', parentSessionId: 'b' });
102
+
103
+ await setSessionParent('b', null);
104
+ expect((await getSessionRelation('b'))?.depth).toBe(0);
105
+ expect((await getSessionRelation('c'))?.depth).toBe(1);
106
+ expect((await getSessionRelation('c'))?.parentSessionId).toBe('b');
107
+
108
+ await setSessionParent('b', 'a');
109
+ expect((await getSessionRelation('b'))?.depth).toBe(1);
110
+ expect((await getSessionRelation('c'))?.depth).toBe(2);
111
+ });
112
+
113
+ test('reparenting a branch refuses when the moved subtree would exceed the cap', async () => {
114
+ await createSessionRelation({ sessionId: 'a' });
115
+ await createSessionRelation({ sessionId: 'b', parentSessionId: 'a' });
116
+ await createSessionRelation({ sessionId: 'c', parentSessionId: 'b' });
117
+ await createSessionRelation({ sessionId: 'd', parentSessionId: 'c' });
118
+ await createSessionRelation({ sessionId: 'deep1', parentSessionId: 'root1' });
119
+ await createSessionRelation({ sessionId: 'deep2', parentSessionId: 'deep1' });
120
+ await createSessionRelation({ sessionId: 'deep3', parentSessionId: 'deep2' });
121
+
122
+ // `a` is 4 tall; `deep3` is level 3, so a + 3 would be 6.
123
+ expect(await rejectionCode(() => setSessionParent('a', 'deep3'))).toBe('depth_exceeded');
124
+ });
125
+
126
+ test('a fork is a source edge, never a parent edge', async () => {
127
+ const fork = await createSessionRelation({
128
+ sessionId: 'fork-1',
129
+ sourceSessionId: 'source',
130
+ originKind: 'fork',
131
+ });
132
+ expect(fork).toMatchObject({
133
+ parentSessionId: null,
134
+ sourceSessionId: 'source',
135
+ originKind: 'fork',
136
+ depth: 0,
137
+ });
138
+ expect((await listForkRelations('source')).map((row) => row.sessionId)).toEqual(['fork-1']);
139
+
140
+ expect(
141
+ await rejectionCode(() =>
142
+ createSessionRelation({
143
+ sessionId: 'fork-2',
144
+ sourceSessionId: 'source',
145
+ parentSessionId: 'parent',
146
+ originKind: 'fork',
147
+ }),
148
+ ),
149
+ ).toBe('fork_is_not_a_child');
150
+ expect(
151
+ await rejectionCode(() =>
152
+ createSessionRelation({ sessionId: 'fork-3', originKind: 'fork' }),
153
+ ),
154
+ ).toBe('fork_requires_source');
155
+ expect(
156
+ await rejectionCode(() =>
157
+ createSessionRelation({ sessionId: 'plain', sourceSessionId: 'source' }),
158
+ ),
159
+ ).toBe('not_fork');
160
+ });
161
+
162
+ test('visibility and notifications are presentation and delivery, independently', async () => {
163
+ await createSessionRelation({ sessionId: 'child', parentSessionId: 'root' });
164
+ await setSessionVisibility('child', 'hidden');
165
+ await setParentNotifications('child', 'stuck');
166
+ expect(await getSessionRelation('child')).toMatchObject({
167
+ visibility: 'hidden',
168
+ parentNotifications: 'stuck',
169
+ parentSessionId: 'root',
170
+ });
171
+ expect(await listChildRelations('root')).toHaveLength(1);
172
+ });
173
+
174
+ test('a cleanup owner sees every dependent, across parents', async () => {
175
+ await createSessionRelation({ sessionId: 'a', lifecycleOwnerSessionId: 'boss' });
176
+ await createSessionRelation({
177
+ sessionId: 'b',
178
+ parentSessionId: 'a',
179
+ lifecycleOwnerSessionId: 'boss',
180
+ });
181
+ await createSessionRelation({ sessionId: 'c', lifecycleOwnerSessionId: 'other' });
182
+ expect((await listOwnedRelations('boss')).map((row) => row.sessionId)).toEqual(['a', 'b']);
183
+ });
184
+
185
+ test('deleting a session clears incoming edges but keeps a fork source row', async () => {
186
+ await createSessionRelation({ sessionId: 'parent', lifecycleOwnerSessionId: 'owner' });
187
+ await createSessionRelation({ sessionId: 'child', parentSessionId: 'parent' });
188
+ await createSessionRelation({
189
+ sessionId: 'fork-1',
190
+ sourceSessionId: 'parent',
191
+ originKind: 'fork',
192
+ });
193
+
194
+ await deleteSessionRelations('parent');
195
+ expect(await getSessionRelation('parent')).toBeNull();
196
+ // The fork's own row survives; only its source edge is cleared.
197
+ expect(await getSessionRelation('fork-1')).toMatchObject({
198
+ sourceSessionId: null,
199
+ originKind: null,
200
+ });
201
+ // A child is released to the root rather than left pointing at a dead id.
202
+ expect(await getSessionRelation('child')).toMatchObject({
203
+ parentSessionId: null,
204
+ depth: 0,
205
+ });
206
+ });
207
+ });