Open History to see the last commit
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 };
82}
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(["provider", "mcp"] as const)(
124 "a %s child does not inherit parent settlement protections and settles once idle",
125 (creationSource) =>
126 Effect.gen(function* () {
127 const store = yield* ProjectionStore.ProjectionStoreV2;
128 const parentThread = {
129 ...makeParentThread(),
130 pinnedAt: parentCreatedAt,
131 pinOrderKey: "a0",
132 autoSettleDisabledAt: parentCreatedAt,
133 };
134 const childThread = makeSubagentChildThread({
135 parentThread,
136 childThreadId,
137 parentNodeId: NodeId.make("node:subagent-parent"),
138 activeProviderThreadId: null,
139 providerInstanceId: childProviderInstanceId,
140 modelSelection: childModelSelection,
141 title: "Child",
142 now: childCreatedAt,
143 createdBy: "agent",
144 creationSource,
145 });
146
147 assert.equal(parentThread.pinnedAt, parentCreatedAt);
148 assert.equal(parentThread.pinOrderKey, "a0");
149 assert.isNull(childThread.pinnedAt);
150 assert.isNull(childThread.pinOrderKey);
151 assert.isNull(childThread.autoSettleDisabledAt);
152
153 for (const thread of [parentThread, childThread]) {
154 yield* store.apply({
155 id: EventId.make(`event:${thread.id}`),
156 type: "thread.created",
157 threadId: thread.id,
158 occurredAt: thread.createdAt,
159 payload: thread,
160 });
161 }
162 const savedParent = yield* store.getThread(parentThreadId);
163 assert.deepEqual(savedParent.pinnedAt, parentCreatedAt);
164 assert.equal(savedParent.pinOrderKey, "a0");
165 assert.deepEqual(savedParent.autoSettleDisabledAt, parentCreatedAt);
166 const candidates = yield* store.getSettlementCandidates();
167 assert.deepEqual(
168 candidates.map((candidate) => candidate.id),
169 [childThreadId],
170 );
171 const settledAt = resolveAutoSettlementAt({
172 thread: candidates[0]!,
173 pullRequest: null,
174 nowMs: DateTime.toEpochMillis(DateTime.add(childCreatedAt, { days: 4 })),
175 autoSettleAfterDays: 3,
176 autoSettleOnMerge: false,
177 });
178 assert.equal(settledAt && DateTime.formatIso(settledAt), DateTime.formatIso(childCreatedAt));
179 }).pipe(
180 Effect.provide(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory))),
181 ),
182);
183
184function taskFixture() {
185 const projection = ProjectionStore.emptyProjection({
186 type: "thread.created",
187 id: EventId.make("task-fixture"),
188 threadId: parentThreadId,
189 occurredAt: parentCreatedAt,
190 payload: makeParentThread(),
191 });
192 const run: OrchestrationV2Run = {
193 id: RunId.make("initial"),
194 threadId: parentThreadId,
195 ordinal: 1,
196 providerInstanceId: parentProviderInstanceId,
197 modelSelection: parentModelSelection,
198 providerThreadId: null,
199 userMessageId: MessageId.make("prompt"),
200 rootNodeId: NodeId.make("root"),
201 activeAttemptId: RunAttemptId.make("attempt"),
202 status: "completed",
203 requestedAt: parentCreatedAt,
204 startedAt: parentCreatedAt,
205 completedAt: childCreatedAt,
206 checkpointId: null,
207 contextHandoffId: null,
208 };
209 return { projection: { ...projection, runs: [run] }, run };
210}
211
212it("reports the run that ended last, not the highest ordinal", () => {
213 const { projection, run } = taskFixture();
214 const ended = (ordinal: number, completedAt: string): OrchestrationV2Run => ({
215 ...run,
216 id: RunId.make(`run:${ordinal}`),
217 ordinal,
218 completedAt: DateTime.makeUnsafe(completedAt),
219 });
220 const progress = delegatedTaskProgress({
221 ...projection,
222 runs: [
223 { ...run, status: "cancelled" },
224 ended(4, "2026-07-24T10:00:00.000Z"),
225 ended(2, "2026-07-24T10:05:00.000Z"),
226 ended(3, "2026-07-24T10:10:00.000Z"),
227 ],
228 });
229 assert.equal(progress.state, "result_available");
230 assert.equal(progress.resultRun?.ordinal, 3);
231});
232
233it("waits for nested work and retains the report across monitor acknowledgements", () => {
234 const { projection, run } = taskFixture();
235 assert.equal(
236 delegatedTaskProgress({ ...projection, subagents: [{ status: "running" }] }).state,
237 "waiting_for_children",
238 );
239 assert.equal(
240 delegatedTaskProgress({ ...projection, subagents: [{ status: "completed" }] }).state,
241 "result_available",
242 );
243 assert.equal(
244 delegatedTaskProgress({ ...projection, subagents: [{ status: "idle" }] }).state,
245 "result_available",
246 );
247 for (const state of ["pending", "claimed"] as const) {
248 assert.equal(
249 delegatedTaskProgress({
250 ...projection,
251 subagents: [{ status: "idle", completionDelivery: { state, observedByRunId: null } }],
252 }).state,
253 "result_available",
254 );
255 assert.equal(
256 delegatedTaskProgress({
257 ...projection,
258 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
259 }).state,
260 "waiting_for_children",
261 );
262 }
263 for (const state of ["acknowledged", "delivered", "disposed"] as const) {
264 assert.equal(
265 delegatedTaskProgress({
266 ...projection,
267 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
268 }).state,
269 "result_available",
270 );
271 }
272 assert.equal(
273 delegatedTaskProgress({
274 ...projection,
275 providerThreads: [
276 { pendingBackgroundTasks: [{ taskId: "background-audit", kind: "command" }] },
277 ],
278 }).state,
279 "waiting_for_children",
280 );
281 const pending = {
282 ...run,
283 id: RunId.make("followup"),
284 ordinal: 2,
285 status: "queued" as const,
286 startedAt: null,
287 };
288 assert.equal(delegatedTaskProgress({ ...projection, runs: [run, pending] }).state, "working");
289 const cancelled = { ...run, status: "cancelled" as const };
290 const held = delegatedTaskProgress({
291 ...projection,
292 runs: [cancelled, { ...pending, queueHeld: true }],
293 });
294 assert.equal(held.state, "result_available");
295 assert.equal(held.resultRun?.id, cancelled.id);
296 const report = { ...pending, status: "completed" as const, startedAt: parentCreatedAt };
297 const monitor = { ...report, id: RunId.make("monitor"), ordinal: 3 };
298 const artifacts = makeSubagentConversationArtifacts({
299 messageId: MessageId.make("monitor-message"),
300 turnItemId: TurnItemId.make("monitor-item"),
301 threadId: parentThreadId,
302 rootNodeId: NodeId.make("root"),
303 providerThreadId: null,
304 providerTurnId: null,
305 nativeItemRef: null,
306 role: "user",
307 text: "Monitor update",
308 ordinal: 3,
309 now: childCreatedAt,
310 });
311 const progress = delegatedTaskProgress({
312 ...projection,
313 runs: [run, report, monitor],
314 messages: [
315 {
316 ...artifacts.message,
317 runId: monitor.id,
318 notification: {
319 source: { kind: "monitor" },
320 outcome: "updated",
321 summary: "Monitor update",
322 },
323 },
324 ],
325 });
326 assert.equal(progress.state, "result_available");
327 assert.equal(progress.resultRun?.id, report.id);
328});
329
330it("exposes the provider failure rather than a progress message from the failed run", () => {
331 const { projection, run } = taskFixture();
332 const failedRun = { ...run, status: "failed" as const };
333 const artifacts = makeSubagentConversationArtifacts({
334 messageId: MessageId.make("progress"),
335 turnItemId: TurnItemId.make("error"),
336 threadId: parentThreadId,
337 rootNodeId: NodeId.make("root"),
338 providerThreadId: null,
339 providerTurnId: null,
340 nativeItemRef: null,
341 role: "assistant",
342 text: "Starting the audit.",
343 ordinal: 1,
344 now: childCreatedAt,
345 });
346 if (artifacts.turnItem.type !== "assistant_message") throw new Error("Expected assistant item");
347 const failure = {
348 class: "unknown" as const,
349 message: "You've hit your usage limit. Try again Sep 14 at 7:20 PM.",
350 code: null,
351 retryable: false,
352 };
353 const result = subagentResultForRun(
354 {
355 ...projection,
356 messages: [{ ...artifacts.message, runId: run.id }],
357 turnItems: [{ ...artifacts.turnItem, type: "error", runId: run.id, failure }],
358 },
359 failedRun,
360 );
361 assert.equal(result.text, failure.message);
362 assert.equal(result.turnItemId, artifacts.turnItem.id);
363 assert.isNull(result.messageId);
364});
365
366it("orders a task's assistant messages by turn item, not by timestamps", () => {
367 const { projection, run } = taskFixture();
368 const at = DateTime.makeUnsafe("2026-07-24T10:05:00.000Z");
369 const message = (id: string, text: string, ordinal: number) => {
370 const artifacts = makeSubagentConversationArtifacts({
371 messageId: MessageId.make(id),
372 turnItemId: TurnItemId.make(id),
373 threadId: parentThreadId,
374 rootNodeId: NodeId.make("root"),
375 providerThreadId: null,
376 providerTurnId: null,
377 nativeItemRef: null,
378 role: "assistant",
379 text,
380 ordinal,
381 now: at,
382 });
383 return {
384 message: { ...artifacts.message, runId: run.id },
385 turnItem: { ...artifacts.turnItem, runId: run.id },
386 };
387 };
388 const progress = message("progress", "Starting step 0.", 1);
389 const report = message("report", "All steps passed.", 2);
390 const result = subagentResultForRun(
391 {
392 ...projection,
393 messages: [progress.message, report.message],
394 turnItems: [report.turnItem, progress.turnItem],
395 },
396 run,
397 );
398 assert.equal(result.text, "All steps passed.");
399 assert.equal(result.messageId, report.message.id);
400 assert.equal(result.turnItemId, report.turnItem.id);
401});
402
403it.effect("ends an orphaned native subagent's node when only its record already ended", () =>
404 Effect.gen(function* () {
405 const id = NodeId.make("node:orphaned-native-subagent");
406 const subagent = { id, origin: "provider_native", status: "running", runId: null };
407 const events = yield* endOrphanedNativeSubagent({
408 projection: {
409 subagents: [subagent],
410 nodes: [{ id, status: "running", runId: null }],
411 turnItems: [],
412 } as never,
413 subagentId: id,
414 status: "cancelled",
415 now: yield* DateTime.now,
416 emitted: [
417 { type: "subagent.updated", payload: { ...subagent, status: "cancelled" } },
418 ] as never,
419 allocateEventId: () => Effect.succeed(EventId.make("event:orphaned-native-subagent")),
420 });
421 assert.deepEqual(
422 events.map((event) => [event.type, event.type === "node.updated" && event.payload.status]),
423 [["node.updated", "cancelled"]],
424 );
425 }),
426);
427
428it.effect("ends a runless root turn's items when its node already ended", () =>
429 Effect.gen(function* () {
430 const root = {
431 id: NodeId.make("node:runless-root"),
432 kind: "root_turn",
433 status: "running",
434 runId: null,
435 };
436 const item = (id: string) => ({ id, nodeId: root.id, runId: null, status: "running" });
437 const events = yield* endRunlessRootTurns({
438 threadId: childThreadId,
439 providerInstanceId: parentProviderInstanceId,
440 projection: {
441 nodes: [root],
442 providerTurns: [],
443 turnItems: [item("turn-item:command"), item("turn-item:reasoning")],
444 } as never,
445 status: "cancelled",
446 now: yield* DateTime.now,
447 emitted: [
448 {
449 type: "turn-item.updated",
450 payload: { ...item("turn-item:command"), status: "cancelled" },
451 },
452 { type: "node.updated", payload: { ...root, status: "cancelled" } },
453 ] as never,
454 allocateEventId: () => Effect.succeed(EventId.make("event:runless-root")),
455 });
456 assert.deepEqual(
457 events.map(
458 (event) => `${event.type} ${event.type === "turn-item.updated" && event.payload.id}`,
459 ),
460 ["turn-item.updated turn-item:reasoning"],
461 );
462 }),
463);