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: "idle", completionDelivery: { state, observedByRunId: null } }],
212 }).state,
213 "result_available",
214 );
215 assert.equal(
216 delegatedTaskProgress({
217 ...projection,
218 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
219 }).state,
220 "waiting_for_children",
221 );
222 }
223 for (const state of ["acknowledged", "delivered", "disposed"] as const) {
224 assert.equal(
225 delegatedTaskProgress({
226 ...projection,
227 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
228 }).state,
229 "result_available",
230 );
231 }
232 assert.equal(
233 delegatedTaskProgress({
234 ...projection,
235 providerThreads: [
236 { pendingBackgroundTasks: [{ taskId: "background-audit", kind: "command" }] },
237 ],
238 }).state,
239 "waiting_for_children",
240 );
241 const pending = {
242 ...run,
243 id: RunId.make("followup"),
244 ordinal: 2,
245 status: "queued" as const,
246 startedAt: null,
247 };
248 assert.equal(delegatedTaskProgress({ ...projection, runs: [run, pending] }).state, "working");
249 const cancelled = { ...run, status: "cancelled" as const };
250 const held = delegatedTaskProgress({
251 ...projection,
252 runs: [cancelled, { ...pending, queueHeld: true }],
253 });
254 assert.equal(held.state, "result_available");
255 assert.equal(held.resultRun?.id, cancelled.id);
256 const report = { ...pending, status: "completed" as const, startedAt: parentCreatedAt };
257 const monitor = { ...report, id: RunId.make("monitor"), ordinal: 3 };
258 const artifacts = makeSubagentConversationArtifacts({
259 messageId: MessageId.make("monitor-message"),
260 turnItemId: TurnItemId.make("monitor-item"),
261 threadId: parentThreadId,
262 rootNodeId: NodeId.make("root"),
263 providerThreadId: null,
264 providerTurnId: null,
265 nativeItemRef: null,
266 role: "user",
267 text: "Monitor update",
268 ordinal: 3,
269 now: childCreatedAt,
270 });
271 const progress = delegatedTaskProgress({
272 ...projection,
273 runs: [run, report, monitor],
274 messages: [
275 {
276 ...artifacts.message,
277 runId: monitor.id,
278 notification: {
279 source: { kind: "monitor" },
280 outcome: "updated",
281 summary: "Monitor update",
282 },
283 },
284 ],
285 });
286 assert.equal(progress.state, "result_available");
287 assert.equal(progress.resultRun?.id, report.id);
288});
289
290it("exposes the provider failure rather than a progress message from the failed run", () => {
291 const { projection, run } = taskFixture();
292 const failedRun = { ...run, status: "failed" as const };
293 const artifacts = makeSubagentConversationArtifacts({
294 messageId: MessageId.make("progress"),
295 turnItemId: TurnItemId.make("error"),
296 threadId: parentThreadId,
297 rootNodeId: NodeId.make("root"),
298 providerThreadId: null,
299 providerTurnId: null,
300 nativeItemRef: null,
301 role: "assistant",
302 text: "Starting the audit.",
303 ordinal: 1,
304 now: childCreatedAt,
305 });
306 if (artifacts.turnItem.type !== "assistant_message") throw new Error("Expected assistant item");
307 const failure = {
308 class: "unknown" as const,
309 message: "You've hit your usage limit. Try again Sep 14 at 7:20 PM.",
310 code: null,
311 retryable: false,
312 };
313 const result = subagentResultForRun(
314 {
315 ...projection,
316 messages: [{ ...artifacts.message, runId: run.id }],
317 turnItems: [{ ...artifacts.turnItem, type: "error", runId: run.id, failure }],
318 },
319 failedRun,
320 );
321 assert.equal(result.text, failure.message);
322 assert.equal(result.turnItemId, artifacts.turnItem.id);
323 assert.isNull(result.messageId);
324});
325
326it("reports the last assistant message when the provider finalizes them together", () => {
327 const { projection, run } = taskFixture();
328 // OpenCode stamps every assistant message of a turn with the turn's end time.
329 const finalizedAt = DateTime.makeUnsafe("2026-07-24T10:05:00.000Z");
330 const message = (id: string, text: string, ordinal: number, createdAt: string) => {
331 const artifacts = makeSubagentConversationArtifacts({
332 messageId: MessageId.make(id),
333 turnItemId: TurnItemId.make(id),
334 threadId: parentThreadId,
335 rootNodeId: NodeId.make("root"),
336 providerThreadId: null,
337 providerTurnId: null,
338 nativeItemRef: null,
339 role: "assistant",
340 text,
341 ordinal,
342 now: DateTime.makeUnsafe(createdAt),
343 });
344 return {
345 message: { ...artifacts.message, runId: run.id, updatedAt: finalizedAt },
346 turnItem: { ...artifacts.turnItem, runId: run.id },
347 };
348 };
349 const progress = message("progress", "Starting step 0.", 1, "2026-07-24T10:00:00.000Z");
350 const report = message("report", "All steps passed.", 2, "2026-07-24T10:04:00.000Z");
351 const result = subagentResultForRun(
352 {
353 ...projection,
354 messages: [progress.message, report.message],
355 turnItems: [progress.turnItem, report.turnItem],
356 },
357 run,
358 );
359 assert.equal(result.text, "All steps passed.");
360 assert.equal(result.messageId, report.message.id);
361});
362
363it("orders a task's assistant messages by turn item, not by timestamps", () => {
364 const { projection, run } = taskFixture();
365 const at = DateTime.makeUnsafe("2026-07-24T10:05:00.000Z");
366 const message = (id: string, text: string, ordinal: number) => {
367 const artifacts = makeSubagentConversationArtifacts({
368 messageId: MessageId.make(id),
369 turnItemId: TurnItemId.make(id),
370 threadId: parentThreadId,
371 rootNodeId: NodeId.make("root"),
372 providerThreadId: null,
373 providerTurnId: null,
374 nativeItemRef: null,
375 role: "assistant",
376 text,
377 ordinal,
378 now: at,
379 });
380 return {
381 message: { ...artifacts.message, runId: run.id },
382 turnItem: { ...artifacts.turnItem, runId: run.id },
383 };
384 };
385 const progress = message("progress", "Starting step 0.", 1);
386 const report = message("report", "All steps passed.", 2);
387 const result = subagentResultForRun(
388 {
389 ...projection,
390 messages: [progress.message, report.message],
391 turnItems: [report.turnItem, progress.turnItem],
392 },
393 run,
394 );
395 assert.equal(result.text, "All steps passed.");
396 assert.equal(result.messageId, report.message.id);
397 assert.equal(result.turnItemId, report.turnItem.id);
398});
399
400it.effect("ends an orphaned native subagent's node when only its record already ended", () =>
401 Effect.gen(function* () {
402 const id = NodeId.make("node:orphaned-native-subagent");
403 const subagent = { id, origin: "provider_native", status: "running", runId: null };
404 const events = yield* endOrphanedNativeSubagent({
405 projection: {
406 subagents: [subagent],
407 nodes: [{ id, status: "running", runId: null }],
408 turnItems: [],
409 } as never,
410 subagentId: id,
411 status: "cancelled",
412 now: yield* DateTime.now,
413 emitted: [
414 { type: "subagent.updated", payload: { ...subagent, status: "cancelled" } },
415 ] as never,
416 allocateEventId: () => Effect.succeed(EventId.make("event:orphaned-native-subagent")),
417 });
418 assert.deepEqual(
419 events.map((event) => [event.type, event.type === "node.updated" && event.payload.status]),
420 [["node.updated", "cancelled"]],
421 );
422 }),
423);
424
425it.effect("ends a runless root turn's items when its node already ended", () =>
426 Effect.gen(function* () {
427 const root = {
428 id: NodeId.make("node:runless-root"),
429 kind: "root_turn",
430 status: "running",
431 runId: null,
432 };
433 const item = (id: string) => ({ id, nodeId: root.id, runId: null, status: "running" });
434 const events = yield* endRunlessRootTurns({
435 threadId: childThreadId,
436 providerInstanceId: parentProviderInstanceId,
437 projection: {
438 nodes: [root],
439 turnItems: [item("turn-item:command"), item("turn-item:reasoning")],
440 } as never,
441 status: "cancelled",
442 now: yield* DateTime.now,
443 emitted: [
444 {
445 type: "turn-item.updated",
446 payload: { ...item("turn-item:command"), status: "cancelled" },
447 },
448 { type: "node.updated", payload: { ...root, status: "cancelled" } },
449 ] as never,
450 allocateEventId: () => Effect.succeed(EventId.make("event:runless-root")),
451 });
452 assert.deepEqual(
453 events.map(
454 (event) => `${event.type} ${event.type === "turn-item.updated" && event.payload.id}`,
455 ),
456 ["turn-item.updated turn-item:reasoning"],
457 );
458 }),
459);