Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EnvironmentId,
5 EventId,
6 MessageId,
7 NodeId,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderThreadId,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as Context from "effect/Context";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Ref from "effect/Ref";
20
21import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
22import * as EventSink from "./EventSink.ts";
23import * as Orchestrator from "./Orchestrator.ts";
24import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
27import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
28import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
29import * as SqlitePersistence from "../persistence/Sqlite.ts";
30
31// A delegated task whose child runs in a linked environment is recorded on
32// its parent without a child thread here, and completing it wakes the parent
33// the way a local child's result does.
34
35const instanceId = ProviderInstanceId.make("codex");
36const driver = ProviderDriverKind.make("codex");
37const modelSelection = { instanceId, model: "gpt-5.4" };
38const adapter = {
39 instanceId,
40 driver,
41 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
42 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
43 openSession: () => Effect.die("No provider process needed for delegated task records"),
44} as ProviderAdapter.ProviderAdapterV2["Service"];
45
46/** Every parent wake the orchestrator offers, for the tests to read. */
47class Offers extends Context.Service<
48 Offers,
49 Ref.Ref<ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>>
50>()("t3/orchestration-v2/RemoteDelegatedTask.test/Offers") {}
51const layerOffers = Layer.effect(
52 Offers,
53 Ref.make<ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>>([]),
54);
55const layerDatabase = SqlitePersistence.layerMemory;
56const layerTest = Layer.mergeAll(
57 layerDatabase,
58 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
59 ProviderReplayHarness.layerWithRegistry(
60 { name: "remote-delegated-task" },
61 ProviderAdapterRegistry.layerFromAdapters([adapter]),
62 { databaseLayer: layerDatabase, runEffectWorker: false },
63 ),
64).pipe(
65 Layer.provide(
66 Layer.effect(
67 ProviderContinuationRequests.ProviderContinuationRequests,
68 Offers.pipe(
69 Effect.map((offers) => ({
70 offer: (request: ProviderContinuationRequests.ProviderContinuationRequest) =>
71 Ref.update(offers, (seen) => [...seen, request]),
72 take: Effect.never,
73 })),
74 ),
75 ),
76 ),
77 Layer.provideMerge(layerOffers),
78);
79
80/** A parent thread whose run is live, as when its agent calls delegate_task. */
81const seedLiveParent = (name: string) =>
82 Effect.gen(function* () {
83 const orchestrator = yield* Orchestrator.OrchestratorV2;
84 const sink = yield* EventSink.EventSinkV2;
85 const now = yield* DateTime.now;
86 const threadId = ThreadId.make(`thread:${name}`);
87 const runId = RunId.make(`run:${name}`);
88 const rootNodeId = NodeId.make(`node:${name}:root`);
89 const providerThreadId = ProviderThreadId.make(`provider-thread:${name}`);
90 yield* orchestrator.dispatch({
91 type: "thread.create",
92 createdBy: "user",
93 creationSource: "web",
94 commandId: CommandId.make(`command:create:${name}`),
95 threadId,
96 projectId: ProjectId.make("project:remote-delegated-task"),
97 title: "Parent",
98 modelSelection,
99 runtimeMode: "full-access",
100 interactionMode: "default",
101 branch: null,
102 worktreePath: null,
103 });
104 yield* sink.write({
105 commandId: CommandId.make(`command:seed:${name}`),
106 events: [
107 {
108 id: EventId.make(`event:seed-provider-thread:${name}`),
109 type: "provider-thread.updated",
110 threadId,
111 driver,
112 providerInstanceId: instanceId,
113 occurredAt: now,
114 payload: {
115 id: providerThreadId,
116 driver,
117 providerInstanceId: instanceId,
118 providerSessionId: null,
119 appThreadId: threadId,
120 ownerNodeId: rootNodeId,
121 nativeThreadRef: { driver, nativeId: `native:${name}`, strength: "strong" },
122 nativeConversationHeadRef: null,
123 status: "active",
124 firstRunOrdinal: 1,
125 lastRunOrdinal: 1,
126 handoffIds: [],
127 forkedFrom: null,
128 createdAt: now,
129 updatedAt: now,
130 },
131 },
132 {
133 id: EventId.make(`event:seed-node:${name}`),
134 type: "node.updated",
135 threadId,
136 runId,
137 nodeId: rootNodeId,
138 driver,
139 providerInstanceId: instanceId,
140 occurredAt: now,
141 payload: {
142 id: rootNodeId,
143 threadId,
144 runId,
145 parentNodeId: null,
146 rootNodeId,
147 kind: "root_turn",
148 status: "running",
149 countsForRun: true,
150 providerThreadId,
151 providerTurnId: null,
152 nativeItemRef: null,
153 runtimeRequestId: null,
154 checkpointScopeId: null,
155 startedAt: now,
156 completedAt: null,
157 },
158 },
159 {
160 id: EventId.make(`event:seed-run:${name}`),
161 type: "run.updated",
162 threadId,
163 runId,
164 nodeId: rootNodeId,
165 providerInstanceId: instanceId,
166 occurredAt: now,
167 payload: {
168 id: runId,
169 threadId,
170 ordinal: 1,
171 providerInstanceId: instanceId,
172 modelSelection,
173 providerThreadId,
174 userMessageId: MessageId.make(`message:seed-user:${name}`),
175 rootNodeId,
176 activeAttemptId: null,
177 status: "running",
178 requestedAt: now,
179 startedAt: now,
180 completedAt: null,
181 checkpointId: null,
182 contextHandoffId: null,
183 },
184 },
185 ],
186 });
187 return { threadId, runId, rootNodeId };
188 });
189
190const remoteChild = {
191 environmentId: EnvironmentId.make("environment:box"),
192 threadId: ThreadId.make("thread:on-the-box"),
193 label: "Box",
194};
195
196it.layer(layerTest)("a delegated task in a linked environment", (it) => {
197 it.effect("is recorded on its parent without a child thread here, once", () =>
198 Effect.gen(function* () {
199 const orchestrator = yield* Orchestrator.OrchestratorV2;
200 const parent = yield* seedLiveParent("records");
201 const request = {
202 type: "delegated_task.remote.request" as const,
203 commandId: CommandId.make("command:remote-delegate:records"),
204 parentThreadId: parent.threadId,
205 parentRunId: parent.runId,
206 parentNodeId: parent.rootNodeId,
207 task: "Run the suite there.",
208 driver: ProviderDriverKind.make("remote"),
209 modelSelection,
210 remoteChild,
211 completionWake: "always" as const,
212 };
213 yield* orchestrator.dispatch(request);
214 yield* orchestrator.dispatch(request);
215 const projection = yield* orchestrator.getThreadProjection(parent.threadId);
216 assert.equal(projection.subagents.length, 1);
217 const [task] = projection.subagents;
218 assert.equal(task?.childThreadId, null);
219 assert.deepEqual(task?.remoteChild, remoteChild);
220 assert.equal(task?.status, "running");
221 const item = projection.turnItems.find((candidate) => candidate.type === "subagent");
222 assert.deepEqual(item?.type === "subagent" ? item.remoteChild : undefined, remoteChild);
223 // No thread was created here for the child.
224 assert.equal(yield* orchestrator.getThreadShell(remoteChild.threadId), null);
225 }),
226 );
227
228 it.effect("keeps a newer stop recoverable after an older acknowledgement", () =>
229 Effect.gen(function* () {
230 const orchestrator = yield* Orchestrator.OrchestratorV2;
231 const projections = yield* ProjectionStore.ProjectionStoreV2;
232 const parent = yield* seedLiveParent("stop-generation");
233 yield* orchestrator.dispatch({
234 type: "delegated_task.remote.request",
235 commandId: CommandId.make("command:remote-delegate:stop-generation"),
236 parentThreadId: parent.threadId,
237 parentRunId: parent.runId,
238 parentNodeId: parent.rootNodeId,
239 task: "Run a check.",
240 driver: ProviderDriverKind.make("remote"),
241 modelSelection,
242 remoteChild,
243 });
244 const task = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;
245 const openFor = projections.getOpenRemoteDelegatedTasks.pipe(
246 Effect.map((open) => open.filter((entry) => entry.parentThreadId === parent.threadId)),
247 );
248 const complete = {
249 type: "delegated_task.remote.complete" as const,
250 parentThreadId: parent.threadId,
251 taskId: task.id,
252 status: "completed" as const,
253 result: "Original result.",
254 };
255 yield* orchestrator.dispatch({
256 ...complete,
257 commandId: CommandId.make("command:result:stop-generation"),
258 stoppedThere: "ran-out",
259 });
260 for (const count of [1, 2]) {
261 yield* orchestrator.dispatch({
262 type: "delegated_task.remote.stop",
263 parentThreadId: parent.threadId,
264 taskId: task.id,
265 commandId: CommandId.make(`command:stop-generation:${count}`),
266 });
267 }
268 // Reports from before generation tracking cannot clear a later numbered Stop either.
269 for (const stopCount of [undefined, 1]) {
270 const rejected = yield* orchestrator
271 .dispatch({
272 ...complete,
273 commandId: CommandId.make(`command:stale-stop:${stopCount}`),
274 stoppedThere: "stopped",
275 ...(stopCount === undefined ? {} : { stopCount }),
276 })
277 .pipe(Effect.flip);
278 assert.equal(rejected._tag, "OrchestratorDispatchError");
279 assert.deepEqual(yield* openFor, [{ parentThreadId: parent.threadId, taskId: task.id }]);
280 }
281 yield* orchestrator.dispatch({
282 ...complete,
283 commandId: CommandId.make("command:current-stop:2"),
284 stoppedThere: "stopped",
285 stopCount: 2,
286 });
287 const settled = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;
288 assert.equal(settled.result, "Original result.");
289 assert.equal(settled.status, "completed");
290 assert.equal(settled.remoteChild?.stoppedThere, true);
291 assert.deepEqual(yield* openFor, []);
292 }),
293 );
294
295 it.effect("owes a stop there for a Stop here that loses the race to its result", () =>
296 Effect.gen(function* () {
297 const orchestrator = yield* Orchestrator.OrchestratorV2;
298 const projections = yield* ProjectionStore.ProjectionStoreV2;
299 const parent = yield* seedLiveParent("stop-after-result");
300 yield* orchestrator.dispatch({
301 type: "delegated_task.remote.request",
302 commandId: CommandId.make("command:remote-delegate:stop-after-result"),
303 parentThreadId: parent.threadId,
304 parentRunId: parent.runId,
305 parentNodeId: parent.rootNodeId,
306 task: "Run a check.",
307 driver: ProviderDriverKind.make("remote"),
308 modelSelection,
309 remoteChild,
310 });
311 const task = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;
312 const complete = {
313 type: "delegated_task.remote.complete" as const,
314 parentThreadId: parent.threadId,
315 taskId: task.id,
316 };
317 yield* orchestrator.dispatch({
318 ...complete,
319 commandId: CommandId.make("command:result:stop-after-result"),
320 status: "completed",
321 result: "Done there.",
322 stoppedThere: "ran-out",
323 });
324 // The parent's Stop read the task before its result landed.
325 yield* orchestrator.dispatch({
326 ...complete,
327 commandId: CommandId.make("command:parent-stop:stop-after-result"),
328 status: "interrupted",
329 result: "Stopped with its parent.",
330 });
331
332 const stopped = (yield* orchestrator.getThreadProjection(parent.threadId)).subagents[0]!;
333 assert.equal(stopped.status, "completed");
334 assert.equal(stopped.result, "Done there.");
335 assert.equal(stopped.remoteChild?.stoppedThere, false);
336 assert.equal(stopped.remoteChild?.stopCount, 1);
337 const open = yield* projections.getOpenRemoteDelegatedTasks;
338 assert.deepEqual(
339 open.filter((entry) => entry.parentThreadId === parent.threadId),
340 [{ parentThreadId: parent.threadId, taskId: task.id }],
341 );
342 }),
343 );
344
345 it.effect("wakes its parent with the result when it completes there", () =>
346 Effect.gen(function* () {
347 const orchestrator = yield* Orchestrator.OrchestratorV2;
348 const parent = yield* seedLiveParent("completes");
349 const recorded = yield* orchestrator.dispatch({
350 type: "delegated_task.remote.request",
351 commandId: CommandId.make("command:remote-delegate:completes"),
352 parentThreadId: parent.threadId,
353 parentRunId: parent.runId,
354 parentNodeId: parent.rootNodeId,
355 task: "Run the suite there.",
356 driver: ProviderDriverKind.make("remote"),
357 modelSelection,
358 remoteChild,
359 completionWake: "always",
360 });
361 const taskEvent = recorded.storedEvents.find(
362 (stored) => stored.event.type === "subagent.updated",
363 );
364 const taskId =
365 taskEvent?.event.type === "subagent.updated" ? taskEvent.event.payload.id : undefined;
366 assert.isDefined(taskId);
367 // Until it completes, it is open, and a restarted follower picks it up.
368 const projections = yield* ProjectionStore.ProjectionStoreV2;
369 const openFor = projections.getOpenRemoteDelegatedTasks.pipe(
370 Effect.map((open) => open.filter((task) => task.parentThreadId === parent.threadId)),
371 );
372 assert.deepEqual(yield* openFor, [{ parentThreadId: parent.threadId, taskId: taskId! }]);
373 const offers = yield* Offers;
374 yield* Ref.set(offers, []);
375 const complete = (result: string) =>
376 orchestrator.dispatch({
377 type: "delegated_task.remote.complete",
378 commandId: CommandId.make(`command:remote-complete:${result}`),
379 parentThreadId: parent.threadId,
380 taskId: taskId!,
381 status: "completed",
382 result,
383 stoppedThere: "ran-out",
384 });
385 yield* complete("All 412 tests pass on the box.");
386 // A second report is refused, so the first result stands.
387 const late = yield* complete("A late, different answer.").pipe(Effect.flip);
388 assert.equal(late._tag, "OrchestratorDispatchError");
389
390 const projection = yield* orchestrator.getThreadProjection(parent.threadId);
391 const task = projection.subagents.find((candidate) => candidate.id === taskId);
392 assert.equal(task?.status, "completed");
393 assert.equal(task?.result, "All 412 tests pass on the box.");
394 // The live parent run claimed it, so task_status acknowledges it as for a local child.
395 assert.equal(task?.completionDelivery?.state, "claimed");
396 // Nothing is left for the follower to pick up after a restart.
397 assert.deepEqual(yield* openFor, []);
398 const item = projection.turnItems.find(
399 (candidate) => candidate.type === "subagent" && candidate.subagentId === taskId,
400 );
401 assert.equal(item?.status, "completed");
402 // The parent's live run is offered the delivery, as for a local child.
403 const delivery = projection.runs.find((run) => run.id === parent.runId)?.delegatedCompletion
404 ?.delivery;
405 assert.deepEqual(delivery?.taskIds, [taskId]);
406 const offered = yield* Ref.get(offers);
407 assert.equal(offered.length, 1);
408 assert.equal(offered[0]?.threadId, parent.threadId);
409 }),
410 );
411});