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

SubagentProjection.test.ts

478 lines15.8 KB

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