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.effect("ends an orphaned native subagent's node when only its record already ended", () =>
320 Effect.gen(function* () {
321 const id = NodeId.make("node:orphaned-native-subagent");
322 const subagent = { id, origin: "provider_native", status: "running", runId: null };
323 const events = yield* endOrphanedNativeSubagent({
324 projection: {
325 subagents: [subagent],
326 nodes: [{ id, status: "running", runId: null }],
327 turnItems: [],
328 } as never,
329 subagentId: id,
330 status: "cancelled",
331 now: yield* DateTime.now,
332 emitted: [
333 { type: "subagent.updated", payload: { ...subagent, status: "cancelled" } },
334 ] as never,
335 allocateEventId: () => Effect.succeed(EventId.make("event:orphaned-native-subagent")),
336 });
337 assert.deepEqual(
338 events.map((event) => [event.type, event.type === "node.updated" && event.payload.status]),
339 [["node.updated", "cancelled"]],
340 );
341 }),
342);
343
344it.effect("ends a runless root turn's items when its node already ended", () =>
345 Effect.gen(function* () {
346 const root = {
347 id: NodeId.make("node:runless-root"),
348 kind: "root_turn",
349 status: "running",
350 runId: null,
351 };
352 const item = (id: string) => ({ id, nodeId: root.id, runId: null, status: "running" });
353 const events = yield* endRunlessRootTurns({
354 threadId: childThreadId,
355 providerInstanceId: parentProviderInstanceId,
356 projection: {
357 nodes: [root],
358 turnItems: [item("turn-item:command"), item("turn-item:reasoning")],
359 } as never,
360 status: "cancelled",
361 now: yield* DateTime.now,
362 emitted: [
363 {
364 type: "turn-item.updated",
365 payload: { ...item("turn-item:command"), status: "cancelled" },
366 },
367 { type: "node.updated", payload: { ...root, status: "cancelled" } },
368 ] as never,
369 allocateEventId: () => Effect.succeed(EventId.make("event:runless-root")),
370 });
371 assert.deepEqual(
372 events.map(
373 (event) => `${event.type} ${event.type === "turn-item.updated" && event.payload.id}`,
374 ),
375 ["turn-item.updated turn-item:reasoning"],
376 );
377 }),
378);