Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SubagentProjection.test.ts

456 lines15.2 KB

1import { assert, it } from "@effect/vitest";
2import {
3 type ModelSelection,
4 NodeId,
5 RunId,
6 RunAttemptId,
7 MessageId,
8 EventId,
9 TurnItemId,
10 type OrchestrationV2Run,
11 type OrchestrationV2AppThread,
12 ProjectId,
13 ProviderInstanceId,
14 ProviderThreadId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20​
21import {
22 makeSubagentChildThread,
23 delegatedTaskProgress,
24 subagentResultForRun,
25 makeSubagentConversationArtifacts,
26 endOrphanedNativeSubagent,
27 endRunlessRootTurns,
28} from "@t3tools/provider-core/server/subagentProjection";
29​
30import * as SqlitePersistence from "../persistence/Sqlite.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32import { resolveAutoSettlementAt } from "./ThreadSettlementService.ts";
33​
34const parentThreadId = ThreadId.make("thread:subagent-snoozed-parent");
35const childThreadId = ThreadId.make("thread:subagent-awake-child");
36const parentProviderInstanceId = ProviderInstanceId.make("codex");
37const childProviderInstanceId = ProviderInstanceId.make("claude");
38const parentModelSelection = {
39 instanceId: parentProviderInstanceId,
40 model: "gpt-5.4",
41} satisfies ModelSelection;
42const childModelSelection = {
43 instanceId: childProviderInstanceId,
44 model: "claude-opus-4-1",
45} satisfies ModelSelection;
46const parentCreatedAt = DateTime.makeUnsafe("2026-07-24T09:00:00.000Z");
47const snoozedAt = DateTime.makeUnsafe("2026-07-24T09:05:00.000Z");
48const snoozedUntil = DateTime.makeUnsafe("2026-07-25T09:00:00.000Z");
49const childCreatedAt = DateTime.makeUnsafe("2026-07-24T09:10:00.000Z");
50​
51function makeParentThread(): OrchestrationV2AppThread {
52 return {
53 createdBy: "user",
54 creationSource: "web",
55 id: parentThreadId,
56 projectId: ProjectId.make("project:subagent-snooze"),
57 title: "Snoozed parent",
58 providerInstanceId: parentProviderInstanceId,
59 modelSelection: parentModelSelection,
60 runtimeMode: "full-access",
61 interactionMode: "plan",
62 branch: "feature/source",
63 worktreePath: "/tmp/source-worktree",
64 activeProviderThreadId: ProviderThreadId.make("provider-thread:subagent-snoozed-parent"),
65 lineage: {
66 parentThreadId: null,
67 relationshipToParent: null,
68 rootThreadId: parentThreadId,
69 },
70 forkedFrom: null,
71 createdAt: parentCreatedAt,
72 updatedAt: snoozedAt,
73 archivedAt: null,
74 settledOverride: null,
75 settledAt: null,
76 lastVisitedAt: null,
77 snoozedUntil,
78 snoozedAt,
79 deletedAt: null,
80 historyOrigin: "v1_import",
81 };
83​
84it("keeps a subagent child awake when its parent thread is snoozed", () => {
85 const parentThread = makeParentThread();
86 const childProviderThreadId = ProviderThreadId.make("provider-thread:subagent-awake-child");
87 const parentNodeId = NodeId.make("node:subagent-parent");
88 const childThread = makeSubagentChildThread({
89 parentThread,
90 childThreadId,
91 parentNodeId,
92 activeProviderThreadId: childProviderThreadId,
93 providerInstanceId: childProviderInstanceId,
94 modelSelection: childModelSelection,
95 title: "Awake child",
96 now: childCreatedAt,
97 createdBy: "agent",
98 creationSource: "provider",
99 });
100​
101 assert.isNull(childThread.snoozedUntil);
102 assert.isNull(childThread.snoozedAt);
103 assert.equal(childThread.projectId, parentThread.projectId);
104 assert.equal(childThread.runtimeMode, parentThread.runtimeMode);
105 assert.equal(childThread.interactionMode, parentThread.interactionMode);
106 assert.equal(childThread.branch, parentThread.branch);
107 assert.equal(childThread.worktreePath, parentThread.worktreePath);
108 assert.equal(childThread.providerInstanceId, childProviderInstanceId);
109 assert.deepEqual(childThread.modelSelection, childModelSelection);
110 assert.equal(childThread.activeProviderThreadId, childProviderThreadId);
111 assert.isUndefined(childThread.historyOrigin);
112 assert.deepEqual(childThread.lineage, {
113 parentThreadId,
114 relationshipToParent: "subagent",
115 rootThreadId: parentThreadId,
116 });
117 assert.deepEqual(childThread.forkedFrom, {
118 type: "node",
119 nodeId: parentNodeId,
120 });
121});
122​
123it.effect.each([
124 ["sql", ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory))],
125] as const)(
126 "%s: a pinned parent's subagent child is born unpinned and settles once idle",
127 ([, testLayer]) =>
128 Effect.gen(function* () {
129 const store = yield* ProjectionStore.ProjectionStoreV2;
130 const parentThread = { ...makeParentThread(), pinnedAt: parentCreatedAt, pinOrderKey: "a0" };
131 const childThread = makeSubagentChildThread({
132 parentThread,
133 childThreadId,
134 parentNodeId: NodeId.make("node:subagent-parent"),
135 activeProviderThreadId: null,
136 providerInstanceId: childProviderInstanceId,
137 modelSelection: childModelSelection,
138 title: "Child",
139 now: childCreatedAt,
140 createdBy: "agent",
141 creationSource: "provider",
142 });
143​
144 assert.equal(parentThread.pinnedAt, parentCreatedAt);
145 assert.equal(parentThread.pinOrderKey, "a0");
146 assert.isNull(childThread.pinnedAt);
147 assert.isNull(childThread.pinOrderKey);
148​
149 for (const thread of [parentThread, childThread]) {
150 yield* store.apply({
151 id: EventId.make(`event:${thread.id}`),
152 type: "thread.created",
153 threadId: thread.id,
154 occurredAt: thread.createdAt,
155 payload: thread,
156 });
157 }
158 const savedParent = yield* store.getThread(parentThreadId);
159 assert.deepEqual(savedParent.pinnedAt, parentCreatedAt);
160 assert.equal(savedParent.pinOrderKey, "a0");
161 const candidates = yield* store.getSettlementCandidates();
162 assert.deepEqual(
163 candidates.map((candidate) => candidate.id),
164 [childThreadId],
165 );
166 const settledAt = resolveAutoSettlementAt({
167 thread: candidates[0]!,
168 pullRequest: null,
169 nowMs: DateTime.toEpochMillis(DateTime.add(childCreatedAt, { days: 4 })),
170 autoSettleAfterDays: 3,
171 autoSettleOnMerge: false,
172 });
173 assert.equal(settledAt && DateTime.formatIso(settledAt), DateTime.formatIso(childCreatedAt));
174 }).pipe(Effect.provide(testLayer)),
175);
176​
177function taskFixture() {
178 const projection = ProjectionStore.emptyProjection({
179 type: "thread.created",
180 id: EventId.make("task-fixture"),
181 threadId: parentThreadId,
182 occurredAt: parentCreatedAt,
183 payload: makeParentThread(),
184 });
185 const run: OrchestrationV2Run = {
186 id: RunId.make("initial"),
187 threadId: parentThreadId,
188 ordinal: 1,
189 providerInstanceId: parentProviderInstanceId,
190 modelSelection: parentModelSelection,
191 providerThreadId: null,
192 userMessageId: MessageId.make("prompt"),
193 rootNodeId: NodeId.make("root"),
194 activeAttemptId: RunAttemptId.make("attempt"),
195 status: "completed",
196 requestedAt: parentCreatedAt,
197 startedAt: parentCreatedAt,
198 completedAt: childCreatedAt,
199 checkpointId: null,
200 contextHandoffId: null,
201 };
202 return { projection: { ...projection, runs: [run] }, run };
204​
205it("reports the run that ended last, not the highest ordinal", () => {
206 const { projection, run } = taskFixture();
207 const ended = (ordinal: number, completedAt: string): OrchestrationV2Run => ({
208 ...run,
209 id: RunId.make(`run:${ordinal}`),
210 ordinal,
211 completedAt: DateTime.makeUnsafe(completedAt),
212 });
213 const progress = delegatedTaskProgress({
214 ...projection,
215 runs: [
216 { ...run, status: "cancelled" },
217 ended(4, "2026-07-24T10:00:00.000Z"),
218 ended(2, "2026-07-24T10:05:00.000Z"),
219 ended(3, "2026-07-24T10:10:00.000Z"),
220 ],
221 });
222 assert.equal(progress.state, "result_available");
223 assert.equal(progress.resultRun?.ordinal, 3);
224});
225​
226it("waits for nested work and retains the report across monitor acknowledgements", () => {
227 const { projection, run } = taskFixture();
228 assert.equal(
229 delegatedTaskProgress({ ...projection, subagents: [{ status: "running" }] }).state,
230 "waiting_for_children",
231 );
232 assert.equal(
233 delegatedTaskProgress({ ...projection, subagents: [{ status: "completed" }] }).state,
234 "result_available",
235 );
236 assert.equal(
237 delegatedTaskProgress({ ...projection, subagents: [{ status: "idle" }] }).state,
238 "result_available",
239 );
240 for (const state of ["pending", "claimed"] as const) {
241 assert.equal(
242 delegatedTaskProgress({
243 ...projection,
244 subagents: [{ status: "idle", completionDelivery: { state, observedByRunId: null } }],
245 }).state,
246 "result_available",
247 );
248 assert.equal(
249 delegatedTaskProgress({
250 ...projection,
251 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
252 }).state,
253 "waiting_for_children",
254 );
255 }
256 for (const state of ["acknowledged", "delivered", "disposed"] as const) {
257 assert.equal(
258 delegatedTaskProgress({
259 ...projection,
260 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
261 }).state,
262 "result_available",
263 );
264 }
265 assert.equal(
266 delegatedTaskProgress({
267 ...projection,
268 providerThreads: [
269 { pendingBackgroundTasks: [{ taskId: "background-audit", kind: "command" }] },
270 ],
271 }).state,
272 "waiting_for_children",
273 );
274 const pending = {
275 ...run,
276 id: RunId.make("followup"),
277 ordinal: 2,
278 status: "queued" as const,
279 startedAt: null,
280 };
281 assert.equal(delegatedTaskProgress({ ...projection, runs: [run, pending] }).state, "working");
282 const cancelled = { ...run, status: "cancelled" as const };
283 const held = delegatedTaskProgress({
284 ...projection,
285 runs: [cancelled, { ...pending, queueHeld: true }],
286 });
287 assert.equal(held.state, "result_available");
288 assert.equal(held.resultRun?.id, cancelled.id);
289 const report = { ...pending, status: "completed" as const, startedAt: parentCreatedAt };
290 const monitor = { ...report, id: RunId.make("monitor"), ordinal: 3 };
291 const artifacts = makeSubagentConversationArtifacts({
292 messageId: MessageId.make("monitor-message"),
293 turnItemId: TurnItemId.make("monitor-item"),
294 threadId: parentThreadId,
295 rootNodeId: NodeId.make("root"),
296 providerThreadId: null,
297 providerTurnId: null,
298 nativeItemRef: null,
299 role: "user",
300 text: "Monitor update",
301 ordinal: 3,
302 now: childCreatedAt,
303 });
304 const progress = delegatedTaskProgress({
305 ...projection,
306 runs: [run, report, monitor],
307 messages: [
308 {
309 ...artifacts.message,
310 runId: monitor.id,
311 notification: {
312 source: { kind: "monitor" },
313 outcome: "updated",
314 summary: "Monitor update",
315 },
316 },
317 ],
318 });
319 assert.equal(progress.state, "result_available");
320 assert.equal(progress.resultRun?.id, report.id);
321});
322​
323it("exposes the provider failure rather than a progress message from the failed run", () => {
324 const { projection, run } = taskFixture();
325 const failedRun = { ...run, status: "failed" as const };
326 const artifacts = makeSubagentConversationArtifacts({
327 messageId: MessageId.make("progress"),
328 turnItemId: TurnItemId.make("error"),
329 threadId: parentThreadId,
330 rootNodeId: NodeId.make("root"),
331 providerThreadId: null,
332 providerTurnId: null,
333 nativeItemRef: null,
334 role: "assistant",
335 text: "Starting the audit.",
336 ordinal: 1,
337 now: childCreatedAt,
338 });
339 if (artifacts.turnItem.type !== "assistant_message") throw new Error("Expected assistant item");
340 const failure = {
341 class: "unknown" as const,
342 message: "You've hit your usage limit. Try again Sep 14 at 7:20 PM.",
343 code: null,
344 retryable: false,
345 };
346 const result = subagentResultForRun(
347 {
348 ...projection,
349 messages: [{ ...artifacts.message, runId: run.id }],
350 turnItems: [{ ...artifacts.turnItem, type: "error", runId: run.id, failure }],
351 },
352 failedRun,
353 );
354 assert.equal(result.text, failure.message);
355 assert.equal(result.turnItemId, artifacts.turnItem.id);
356 assert.isNull(result.messageId);
357});
358​
359it("orders a task's assistant messages by turn item, not by timestamps", () => {
360 const { projection, run } = taskFixture();
361 const at = DateTime.makeUnsafe("2026-07-24T10:05:00.000Z");
362 const message = (id: string, text: string, ordinal: number) => {
363 const artifacts = makeSubagentConversationArtifacts({
364 messageId: MessageId.make(id),
365 turnItemId: TurnItemId.make(id),
366 threadId: parentThreadId,
367 rootNodeId: NodeId.make("root"),
368 providerThreadId: null,
369 providerTurnId: null,
370 nativeItemRef: null,
371 role: "assistant",
372 text,
373 ordinal,
374 now: at,
375 });
376 return {
377 message: { ...artifacts.message, runId: run.id },
378 turnItem: { ...artifacts.turnItem, runId: run.id },
379 };
380 };
381 const progress = message("progress", "Starting step 0.", 1);
382 const report = message("report", "All steps passed.", 2);
383 const result = subagentResultForRun(
384 {
385 ...projection,
386 messages: [progress.message, report.message],
387 turnItems: [report.turnItem, progress.turnItem],
388 },
389 run,
390 );
391 assert.equal(result.text, "All steps passed.");
392 assert.equal(result.messageId, report.message.id);
393 assert.equal(result.turnItemId, report.turnItem.id);
394});
395​
396it.effect("ends an orphaned native subagent's node when only its record already ended", () =>
397 Effect.gen(function* () {
398 const id = NodeId.make("node:orphaned-native-subagent");
399 const subagent = { id, origin: "provider_native", status: "running", runId: null };
400 const events = yield* endOrphanedNativeSubagent({
401 projection: {
402 subagents: [subagent],
403 nodes: [{ id, status: "running", runId: null }],
404 turnItems: [],
405 } as never,
406 subagentId: id,
407 status: "cancelled",
408 now: yield* DateTime.now,
409 emitted: [
410 { type: "subagent.updated", payload: { ...subagent, status: "cancelled" } },
411 ] as never,
412 allocateEventId: () => Effect.succeed(EventId.make("event:orphaned-native-subagent")),
413 });
414 assert.deepEqual(
415 events.map((event) => [event.type, event.type === "node.updated" && event.payload.status]),
416 [["node.updated", "cancelled"]],
417 );
418 }),
419);
420​
421it.effect("ends a runless root turn's items when its node already ended", () =>
422 Effect.gen(function* () {
423 const root = {
424 id: NodeId.make("node:runless-root"),
425 kind: "root_turn",
426 status: "running",
427 runId: null,
428 };
429 const item = (id: string) => ({ id, nodeId: root.id, runId: null, status: "running" });
430 const events = yield* endRunlessRootTurns({
431 threadId: childThreadId,
432 providerInstanceId: parentProviderInstanceId,
433 projection: {
434 nodes: [root],
435 providerTurns: [],
436 turnItems: [item("turn-item:command"), item("turn-item:reasoning")],
437 } as never,
438 status: "cancelled",
439 now: yield* DateTime.now,
440 emitted: [
441 {
442 type: "turn-item.updated",
443 payload: { ...item("turn-item:command"), status: "cancelled" },
444 },
445 { type: "node.updated", payload: { ...root, status: "cancelled" } },
446 ] as never,
447 allocateEventId: () => Effect.succeed(EventId.make("event:runless-root")),
448 });
449 assert.deepEqual(
450 events.map(
451 (event) => `${event.type} ${event.type === "turn-item.updated" && event.payload.id}`,
452 ),
453 ["turn-item.updated turn-item:reasoning"],
454 );
455 }),
456);