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

RemoteDelegatedTask.test.ts

424 lines16.6 KB

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