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

SteeringCompletion.integration.test.ts

405 lines17.2 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 EventId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderThreadId,
11 ProviderTurnId,
12 ThreadId,
13 type OrchestrationV2DomainEvent,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Queue from "effect/Queue";
20import * as Stream from "effect/Stream";
21import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
22import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts";
23import { EventSinkV2 } from "./EventSink.ts";
24import { OrchestratorV2 } from "./Orchestrator.ts";
25import {
26 ProviderAdapterSteerRunError,
27 type ProviderAdapterV2Event,
28 type ProviderAdapterV2Shape,
29 type ProviderAdapterV2TurnInput,
30} from "./ProviderAdapter.ts";
31import { makeSingleLayer } from "./ProviderAdapterRegistry.ts";
32import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
33import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
34​
35const driver = ProviderDriverKind.make("codex");
36const instanceId = ProviderInstanceId.make("codex");
37const modelSelection = { instanceId, model: "test-model" };
38​
39for (const mailbox of [false, true]) {
40 for (const timing of [
41 "before delivery",
42 "during delivery",
43 "before dispatch",
44 "after delivery",
45 "without native steering",
46 "settled only",
47 ] as const) {
48 if (!mailbox && (timing === "without native steering" || timing === "settled only")) continue;
49 it.effect(
50 `delivers ${mailbox ? "mailbox notification" : "steering"} when completion wins ${timing}`,
51 () =>
52 Effect.scoped(
53 Effect.gen(function* () {
54 const cwd = yield* checkpointWorkspace(
55 `steering-completion-${timing.replaceAll(" ", "-")}`,
56 );
57 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
58 const started: ProviderAdapterV2TurnInput[] = [];
59 const steerEntered = yield* Deferred.make<void>();
60 const rejectSteer = yield* Deferred.make<void>();
61 let steerCalls = 0;
62 const capabilities = {
63 ...CodexProviderCapabilitiesV2,
64 turns: {
65 ...CodexProviderCapabilitiesV2.turns,
66 supportsActiveSteering: timing !== "without native steering",
67 },
68 };
69 const adapter: ProviderAdapterV2Shape = {
70 instanceId,
71 driver,
72 getCapabilities: () => Effect.succeed(capabilities),
73 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
74 openSession: (input) =>
75 Effect.gen(function* () {
76 const now = yield* DateTime.now;
77 return {
78 instanceId,
79 driver,
80 providerSessionId: input.providerSessionId,
81 providerSession: {
82 id: input.providerSessionId,
83 driver,
84 providerInstanceId: instanceId,
85 status: "ready",
86 cwd,
87 model: modelSelection.model,
88 capabilities,
89 createdAt: now,
90 updatedAt: now,
91 lastError: null,
92 },
93 events: Stream.fromQueue(events),
94 ensureThread: ({ threadId }) =>
95 Effect.succeed({
96 id: ProviderThreadId.make(`provider-thread:${threadId}`),
97 driver,
98 providerInstanceId: instanceId,
99 providerSessionId: input.providerSessionId,
100 appThreadId: threadId,
101 ownerNodeId: null,
102 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
103 nativeConversationHeadRef: null,
104 status: "idle",
105 firstRunOrdinal: null,
106 lastRunOrdinal: null,
107 handoffIds: [],
108 forkedFrom: null,
109 createdAt: now,
110 updatedAt: now,
111 }),
112 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
113 startTurn: (turn) =>
114 Effect.gen(function* () {
115 started.push(turn);
116 yield* Queue.offer(events, {
117 type: "provider_turn.updated",
118 driver,
119 providerTurn: {
120 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
121 providerThreadId: turn.providerThread.id,
122 nodeId: turn.rootNodeId,
123 runAttemptId: turn.attemptId,
124 nativeTurnRef: {
125 driver,
126 nativeId: `native:${turn.attemptId}`,
127 strength: "strong",
128 },
129 ordinal: turn.providerTurnOrdinal,
130 status: "running",
131 startedAt: now,
132 completedAt: null,
133 },
134 });
135 }),
136 steerTurn: (turn) =>
137 Effect.gen(function* () {
138 steerCalls += 1;
139 if (timing === "after delivery") return;
140 yield* Deferred.succeed(steerEntered, undefined);
141 yield* Deferred.await(rejectSteer);
142 return yield* new ProviderAdapterSteerRunError({
143 driver,
144 providerThreadId: turn.providerThread.id,
145 providerTurnId: turn.providerTurnId,
146 cause: "turn already completed",
147 });
148 }),
149 interruptTurn: () => Effect.void,
150 respondToRuntimeRequest: () => Effect.void,
151 readThreadSnapshot: () => Effect.die("unused"),
152 rollbackThread: () => Effect.die("unused"),
153 forkThread: () => Effect.die("unused"),
154 };
155 }),
156 };
157 yield* Effect.gen(function* () {
158 const orchestrator = yield* OrchestratorV2;
159 const worker = yield* OrchestrationEffectWorkerV2;
160 const threadId = ThreadId.make("thread:steering-completion");
161 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
162 orchestrator.streamDomainEvents.pipe(
163 Stream.filter(predicate),
164 Stream.take(1),
165 Stream.runDrain,
166 Effect.forkScoped,
167 );
168 yield* orchestrator.dispatch({
169 type: "thread.create",
170 commandId: CommandId.make("create"),
171 threadId,
172 projectId: ProjectId.make("project:steering-completion"),
173 title: "Steering race",
174 modelSelection,
175 runtimeMode: "full-access",
176 interactionMode: "default",
177 branch: null,
178 worktreePath: cwd,
179 createdBy: "user",
180 creationSource: "web",
181 });
182 yield* orchestrator.dispatch({
183 type: "message.dispatch",
184 commandId: CommandId.make("first"),
185 threadId,
186 messageId: MessageId.make("message:first"),
187 text: "first",
188 attachments: [],
189 dispatchMode: { type: "start_immediately" },
190 createdBy: "user",
191 creationSource: "web",
192 });
193 const running = yield* watch(
194 (event) =>
195 event.type === "provider-turn.updated" && event.payload.status === "running",
196 );
197 yield* worker.drain();
198 yield* Fiber.join(running);
199 const first = started[0]!;
200 const messageId = MessageId.make("message:steering");
201 const taskId = NodeId.make("task:mailbox");
202 if (mailbox) {
203 const sink = yield* EventSinkV2;
204 const current = yield* orchestrator.getThreadProjection(threadId);
205 const parentRun = current.runs.find((run) => run.id === first.runId)!;
206 const now = yield* DateTime.now;
207 yield* sink.write({
208 events: [
209 {
210 id: EventId.make("mailbox:cohort"),
211 type: "run.updated",
212 threadId,
213 runId: first.runId,
214 occurredAt: now,
215 payload: {
216 ...parentRun,
217 delegatedCompletion: {
218 disposition: "open",
219 nextGeneration: 2,
220 settledDeliveryCount: 0,
221 delivery: { generation: 1, messageId, taskIds: [taskId] },
222 },
223 },
224 },
225 {
226 id: EventId.make("mailbox:task"),
227 type: "subagent.updated",
228 threadId,
229 runId: first.runId,
230 nodeId: taskId,
231 occurredAt: now,
232 payload: {
233 id: taskId,
234 threadId,
235 runId: first.runId,
236 parentNodeId: first.rootNodeId,
237 origin: "app_owned",
238 createdBy: "agent",
239 driver,
240 providerInstanceId: instanceId,
241 providerThreadId: null,
242 childThreadId: null,
243 nativeTaskRef: null,
244 prompt: "Do background work",
245 title: "Background test",
246 model: null,
247 completionWake: timing === "settled only" ? "settled_only" : "always",
248 completionDelivery: { state: "claimed", observedByRunId: null },
249 status: "completed",
250 result: "done",
251 startedAt: now,
252 completedAt: now,
253 updatedAt: now,
254 },
255 },
256 ],
257 });
258 }
259 const dispatchSteer = orchestrator.dispatch({
260 type: "message.dispatch",
261 commandId: CommandId.make("steer"),
262 threadId,
263 messageId,
264 text: "fix the popover",
265 attachments: [
266 {
267 type: "image",
268 id: "steering-screenshot",
269 name: "image.png",
270 mimeType: "image/png",
271 sizeBytes: 10,
272 },
273 ],
274 dispatchMode: mailbox
275 ? { type: "queue_after_active" }
276 : { type: "steer_active", targetRunId: first.runId },
277 createdBy: mailbox ? "agent" : "user",
278 creationSource: mailbox ? "server" : "web",
279 ...(mailbox
280 ? {
281 delegatedCompletion: {
282 parentRunId: first.runId,
283 generation: 1,
284 taskIds: [taskId],
285 },
286 }
287 : {}),
288 });
289 if (timing !== "before dispatch") yield* dispatchSteer;
290 if (timing === "after delivery") yield* worker.drain();
291 const delivery =
292 timing === "during delivery" ? yield* worker.runOnce.pipe(Effect.forkScoped) : null;
293 if (delivery !== null) yield* Deferred.await(steerEntered);
294 const completed = yield* watch(
295 (event) =>
296 event.type === "run.updated" &&
297 event.payload.id === first.runId &&
298 event.payload.status === "waiting",
299 );
300 const projection = yield* orchestrator.getThreadProjection(threadId);
301 const turn = projection.providerTurns[0]!;
302 yield* Queue.offer(events, {
303 type: "provider_turn.updated",
304 driver,
305 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
306 });
307 yield* Queue.offer(events, {
308 type: "turn.terminal",
309 driver,
310 providerThreadId: turn.providerThreadId,
311 providerTurnId: turn.id,
312 runOrdinal: first.runOrdinal,
313 status: "completed",
314 failure: null,
315 threadDisposition: "reusable",
316 });
317 yield* Fiber.join(completed);
318 if (delivery !== null) {
319 yield* Deferred.succeed(rejectSteer, undefined);
320 yield* Fiber.join(delivery);
321 }
322 if (timing === "before dispatch") yield* dispatchSteer;
323 yield* worker.drain();
324 yield* orchestrator.resumeQueuedRuns;
325 yield* worker.drain();
326 if (timing === "after delivery") {
327 assert.equal(steerCalls, 1);
328 assert.equal(started.length, 1);
329 if (mailbox) {
330 const delivered = yield* orchestrator.getThreadProjection(threadId);
331 assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
332 assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
333 assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
334 assert.equal(delivered.runs[0]?.delegatedCompletion?.settledDeliveryCount, 0);
335 assert.equal(
336 delivered.turnItems.filter((item) => item.type === "notification").length,
337 1,
338 );
339 yield* orchestrator.dispatch({
340 type: "notification.delivery.accept",
341 commandId: CommandId.make("duplicate-acceptance"),
342 threadId,
343 messageId,
344 });
345 yield* worker.drain();
346 assert.equal(steerCalls, 1);
347 yield* orchestrator.dispatch({
348 type: "delegated_task.completion-delivery.acknowledge",
349 commandId: CommandId.make("read-result"),
350 parentThreadId: threadId,
351 taskId,
352 observedByRunId: first.runId,
353 });
354 const acknowledged = yield* orchestrator.getThreadProjection(threadId);
355 assert.equal(
356 acknowledged.subagents[0]?.completionDelivery?.state,
357 "acknowledged",
358 );
359 }
360 return;
361 }
362 assert.equal(started.length, 2);
363 assert.equal(started[1]?.message.messageId, messageId);
364 if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
365 else assert.equal(started[1]?.message.text, "fix the popover");
366 assert.deepEqual(started[1]?.message.attachments, [
367 {
368 type: "image",
369 id: "steering-screenshot",
370 name: "image.png",
371 mimeType: "image/png",
372 sizeBytes: 10,
373 },
374 ]);
375 assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
376 const final = yield* orchestrator.getThreadProjection(threadId);
377 assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
378 assert.equal(
379 final.messages.find((message) => message.id === messageId)?.runId,
380 started[1]?.runId,
381 );
382 assert.equal(
383 final.turnItems.filter((item) =>
384 mailbox
385 ? item.type === "notification"
386 : item.type === "user_message" && item.messageId === messageId,
387 ).length,
388 1,
389 );
390 yield* worker.drain();
391 assert.equal(started.length, 2);
392 }).pipe(
393 Effect.provide(
394 makeOrchestratorV2ReplayLayerWithRegistry(
395 { name: `steering-completion-${timing}` },
396 makeSingleLayer(adapter),
397 { runEffectWorker: false },
398 ),
399 ),
400 );
401 }),
402 ),
403 );
404 }