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