Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SubagentProjection.test.ts

316 lines10.3 KB

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";
18​
19import {
20 makeSubagentChildThread,
21 delegatedTaskProgress,
22 subagentResultForRun,
23 makeSubagentConversationArtifacts,
24} from "./SubagentProjection.ts";
25​
26import { emptyProjection } from "./ProjectionStore.ts";
27​
28const parentThreadId = ThreadId.make("thread:subagent-snoozed-parent");
29const childThreadId = ThreadId.make("thread:subagent-awake-child");
30const parentProviderInstanceId = ProviderInstanceId.make("codex");
31const childProviderInstanceId = ProviderInstanceId.make("claude");
32const parentModelSelection = {
33 instanceId: parentProviderInstanceId,
34 model: "gpt-5.4",
35} satisfies ModelSelection;
36const childModelSelection = {
37 instanceId: childProviderInstanceId,
38 model: "claude-opus-4-1",
39} satisfies ModelSelection;
40const parentCreatedAt = DateTime.makeUnsafe("2026-07-24T09:00:00.000Z");
41const snoozedAt = DateTime.makeUnsafe("2026-07-24T09:05:00.000Z");
42const snoozedUntil = DateTime.makeUnsafe("2026-07-25T09:00:00.000Z");
43const childCreatedAt = DateTime.makeUnsafe("2026-07-24T09:10:00.000Z");
44​
45function makeParentThread(): OrchestrationV2AppThread {
46 return {
47 createdBy: "user",
48 creationSource: "web",
49 id: parentThreadId,
50 projectId: ProjectId.make("project:subagent-snooze"),
51 title: "Snoozed parent",
52 providerInstanceId: parentProviderInstanceId,
53 modelSelection: parentModelSelection,
54 runtimeMode: "full-access",
55 interactionMode: "plan",
56 branch: "feature/source",
57 worktreePath: "/tmp/source-worktree",
58 activeProviderThreadId: ProviderThreadId.make("provider-thread:subagent-snoozed-parent"),
59 lineage: {
60 parentThreadId: null,
61 relationshipToParent: null,
62 rootThreadId: parentThreadId,
63 },
64 forkedFrom: null,
65 createdAt: parentCreatedAt,
66 updatedAt: snoozedAt,
67 archivedAt: null,
68 settledOverride: null,
69 settledAt: null,
70 lastVisitedAt: null,
71 snoozedUntil,
72 snoozedAt,
73 deletedAt: null,
74 historyOrigin: "v1_import",
75 };
77​
78it("keeps a subagent child awake when its parent thread is snoozed", () => {
79 const parentThread = makeParentThread();
80 const childProviderThreadId = ProviderThreadId.make("provider-thread:subagent-awake-child");
81 const parentNodeId = NodeId.make("node:subagent-parent");
82 const childThread = makeSubagentChildThread({
83 parentThread,
84 childThreadId,
85 parentNodeId,
86 activeProviderThreadId: childProviderThreadId,
87 providerInstanceId: childProviderInstanceId,
88 modelSelection: childModelSelection,
89 title: "Awake child",
90 now: childCreatedAt,
91 createdBy: "agent",
92 creationSource: "provider",
93 });
94​
95 assert.isNull(childThread.snoozedUntil);
96 assert.isNull(childThread.snoozedAt);
97 assert.equal(childThread.projectId, parentThread.projectId);
98 assert.equal(childThread.runtimeMode, parentThread.runtimeMode);
99 assert.equal(childThread.interactionMode, parentThread.interactionMode);
100 assert.equal(childThread.branch, parentThread.branch);
101 assert.equal(childThread.worktreePath, parentThread.worktreePath);
102 assert.equal(childThread.providerInstanceId, childProviderInstanceId);
103 assert.deepEqual(childThread.modelSelection, childModelSelection);
104 assert.equal(childThread.activeProviderThreadId, childProviderThreadId);
105 assert.isUndefined(childThread.historyOrigin);
106 assert.deepEqual(childThread.lineage, {
107 parentThreadId,
108 relationshipToParent: "subagent",
109 rootThreadId: parentThreadId,
110 });
111 assert.deepEqual(childThread.forkedFrom, {
112 type: "node",
113 nodeId: parentNodeId,
114 });
115});
116​
117it("attributes native subagent prompts to their parent thread", () => {
118 for (const role of ["user", "assistant"] as const) {
119 const artifacts = makeSubagentConversationArtifacts({
120 messageId: MessageId.make(`native-${role}`),
121 turnItemId: TurnItemId.make(`native-${role}`),
122 threadId: childThreadId,
123 senderThreadId: parentThreadId,
124 rootNodeId: NodeId.make("child-root"),
125 providerThreadId: null,
126 providerTurnId: null,
127 nativeItemRef: null,
128 role,
129 text: role === "user" ? "Review the changes" : "Review complete",
130 ordinal: 100,
131 now: childCreatedAt,
132 });
133 assert.equal(artifacts.message.threadId, childThreadId);
134 assert.equal(artifacts.message.senderThreadId, role === "user" ? parentThreadId : undefined);
135 if (artifacts.turnItem.type === "user_message") {
136 assert.equal(artifacts.turnItem.senderThreadId, parentThreadId);
137 }
138 }
139});
140​
141function taskFixture() {
142 const projection = emptyProjection({
143 type: "thread.created",
144 id: EventId.make("task-fixture"),
145 threadId: parentThreadId,
146 occurredAt: parentCreatedAt,
147 payload: makeParentThread(),
148 });
149 const run: OrchestrationV2Run = {
150 id: RunId.make("initial"),
151 threadId: parentThreadId,
152 ordinal: 1,
153 providerInstanceId: parentProviderInstanceId,
154 modelSelection: parentModelSelection,
155 providerThreadId: null,
156 userMessageId: MessageId.make("prompt"),
157 rootNodeId: NodeId.make("root"),
158 activeAttemptId: RunAttemptId.make("attempt"),
159 status: "completed",
160 requestedAt: parentCreatedAt,
161 startedAt: parentCreatedAt,
162 completedAt: childCreatedAt,
163 checkpointId: null,
164 contextHandoffId: null,
165 };
166 return { projection: { ...projection, runs: [run] }, run };
168​
169it("reports the run that ended last, not the highest ordinal", () => {
170 const { projection, run } = taskFixture();
171 // A restart continuation (ordinal 4) ran ahead of held queued runs 2 and 3.
172 const ended = (ordinal: number, completedAt: string): OrchestrationV2Run => ({
173 ...run,
174 id: RunId.make(`run:${ordinal}`),
175 ordinal,
176 completedAt: DateTime.makeUnsafe(completedAt),
177 });
178 const progress = delegatedTaskProgress({
179 ...projection,
180 runs: [
181 { ...run, status: "cancelled" },
182 ended(4, "2026-07-24T10:00:00.000Z"),
183 ended(2, "2026-07-24T10:05:00.000Z"),
184 ended(3, "2026-07-24T10:10:00.000Z"),
185 ],
186 });
187 assert.equal(progress.state, "result_available");
188 assert.equal(progress.resultRun?.ordinal, 3);
189});
190​
191it("waits for nested work and retains the report across monitor acknowledgements", () => {
192 const { projection, run } = taskFixture();
193 assert.equal(
194 delegatedTaskProgress({ ...projection, subagents: [{ status: "running" }] }).state,
195 "waiting_for_children",
196 );
197 assert.equal(
198 delegatedTaskProgress({ ...projection, subagents: [{ status: "completed" }] }).state,
199 "result_available",
200 );
201 assert.equal(
202 delegatedTaskProgress({ ...projection, subagents: [{ status: "idle" }] }).state,
203 "result_available",
204 );
205 for (const state of ["pending", "claimed"] as const) {
206 assert.equal(
207 delegatedTaskProgress({
208 ...projection,
209 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
210 }).state,
211 "waiting_for_children",
212 );
213 }
214 for (const state of ["acknowledged", "delivered", "disposed"] as const) {
215 assert.equal(
216 delegatedTaskProgress({
217 ...projection,
218 subagents: [{ status: "completed", completionDelivery: { state, observedByRunId: null } }],
219 }).state,
220 "result_available",
221 );
222 }
223 assert.equal(
224 delegatedTaskProgress({
225 ...projection,
226 providerThreads: [
227 { pendingBackgroundTasks: [{ taskId: "background-audit", kind: "command" }] },
228 ],
229 }).state,
230 "waiting_for_children",
231 );
232 const pending = {
233 ...run,
234 id: RunId.make("followup"),
235 ordinal: 2,
236 status: "queued" as const,
237 startedAt: null,
238 };
239 assert.equal(delegatedTaskProgress({ ...projection, runs: [run, pending] }).state, "working");
240 // Stop or a restart holds queued wakes for the user; they are not work the task owes.
241 const cancelled = { ...run, status: "cancelled" as const };
242 const held = delegatedTaskProgress({
243 ...projection,
244 runs: [cancelled, { ...pending, queueHeld: true }],
245 });
246 assert.equal(held.state, "result_available");
247 assert.equal(held.resultRun?.id, cancelled.id);
248 const report = { ...pending, status: "completed" as const, startedAt: parentCreatedAt };
249 const monitor = { ...report, id: RunId.make("monitor"), ordinal: 3 };
250 const artifacts = makeSubagentConversationArtifacts({
251 messageId: MessageId.make("monitor-message"),
252 turnItemId: TurnItemId.make("monitor-item"),
253 threadId: parentThreadId,
254 rootNodeId: NodeId.make("root"),
255 providerThreadId: null,
256 providerTurnId: null,
257 nativeItemRef: null,
258 role: "user",
259 text: "Monitor update",
260 ordinal: 3,
261 now: childCreatedAt,
262 });
263 const progress = delegatedTaskProgress({
264 ...projection,
265 runs: [run, report, monitor],
266 messages: [
267 {
268 ...artifacts.message,
269 runId: monitor.id,
270 notification: {
271 source: { kind: "monitor" },
272 outcome: "updated",
273 summary: "Monitor update",
274 },
275 },
276 ],
277 });
278 assert.equal(progress.state, "result_available");
279 assert.equal(progress.resultRun?.id, report.id);
280});
281​
282it("exposes the provider failure rather than a progress message from the failed run", () => {
283 const { projection, run } = taskFixture();
284 const failedRun = { ...run, status: "failed" as const };
285 const artifacts = makeSubagentConversationArtifacts({
286 messageId: MessageId.make("progress"),
287 turnItemId: TurnItemId.make("error"),
288 threadId: parentThreadId,
289 rootNodeId: NodeId.make("root"),
290 providerThreadId: null,
291 providerTurnId: null,
292 nativeItemRef: null,
293 role: "assistant",
294 text: "Starting the audit.",
295 ordinal: 1,
296 now: childCreatedAt,
297 });
298 if (artifacts.turnItem.type !== "assistant_message") throw new Error("Expected assistant item");
299 const failure = {
300 class: "unknown" as const,
301 message: "You've hit your usage limit. Try again Sep 14 at 7:20 PM.",
302 code: null,
303 retryable: false,
304 };
305 const result = subagentResultForRun(
306 {
307 ...projection,
308 messages: [{ ...artifacts.message, runId: run.id }],
309 turnItems: [{ ...artifacts.turnItem, type: "error", runId: run.id, failure }],
310 },
311 failedRun,
312 );
313 assert.equal(result.text, failure.message);
314 assert.equal(result.turnItemId, artifacts.turnItem.id);
315 assert.isNull(result.messageId);
316});