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