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

SubagentProjection.test.ts

553 lines18.3 KB

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