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

AgentAwarenessRelay.test.ts

715 lines26.0 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import {
4 EnvironmentId,
5 EventId,
6 MessageId,
7 NodeId,
8 type OrchestrationV2DomainEvent,
9 type OrchestrationV2ThreadShell,
10 type OrchestrationV2TurnItem,
11 ProjectId,
12 ProviderInstanceId,
13 RunId,
14 ThreadId,
15 TurnItemId,
16} from "@t3tools/contracts";
17import { RelayAgentActivityState } from "@t3tools/contracts/relay";
18import * as DateTime from "effect/DateTime";
19import * as Deferred from "effect/Deferred";
20import * as Effect from "effect/Effect";
21import * as Fiber from "effect/Fiber";
22import * as Option from "effect/Option";
23import * as Queue from "effect/Queue";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import * as Stream from "effect/Stream";
27import * as TestClock from "effect/testing/TestClock";
28import * as FetchHttpClient from "effect/http/FetchHttpClient";
29​
30import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
31import {
32 PUBLISH_AGENT_ACTIVITY_SECRET,
33 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
34 RELAY_ISSUER_SECRET,
35 RELAY_URL_SECRET,
36} from "../cloud/config.ts";
37import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
38import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
39import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
40import * as ProjectService from "../project/ProjectService.ts";
41import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";
42​
43const THREAD_ID = ThreadId.make("relay-thread");
44const SECOND_THREAD_ID = ThreadId.make("relay-thread-2");
45const PROJECT_ID = ProjectId.make("relay-project");
46const NOW = "2026-09-04T12:00:00.000Z";
47​
48function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
49 return {
50 id: THREAD_ID,
51 projectId: PROJECT_ID,
52 title: "Thread",
53 providerInstanceId: ProviderInstanceId.make("codex"),
54 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
55 runtimeMode: "full-access",
56 interactionMode: "default",
57 worktreePath: null,
58 activeProviderThreadId: null,
59 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
60 forkedFrom: null,
61 createdBy: "user",
62 creationSource: "web",
63 activeRunId: null,
64 latestVisibleMessage: null,
65 hasActionableProposedPlan: false,
66 itemCount: 0,
67 visibleItemCount: 0,
68 lastVisitedAt: null,
69 deletedAt: null,
70 branch: null,
71 linkedPullRequest: null,
72 status: "running",
73 activityRunStatus: null,
74 pendingRuntimeRequest: null,
75 pendingBackgroundTasks: [],
76 latestRunId: null,
77 latestRunRequestedAt: null,
78 latestRunStartedAt: null,
79 latestRunCompletedAt: null,
80 latestUserMessageAt: null,
81 createdAt: DateTime.makeUnsafe(NOW),
82 updatedAt: DateTime.makeUnsafe(NOW),
83 archivedAt: null,
84 settledOverride: null,
85 settledAt: null,
86 snoozedUntil: null,
87 snoozedAt: null,
88 pinnedAt: null,
89 ...overrides,
90 };
92​
93const PublishPayload = Schema.Struct({ state: Schema.NullOr(RelayAgentActivityState) });
94const decodePublishPayload = Schema.decodeUnknownSync(Schema.fromJsonString(PublishPayload));
95const unused = () => Effect.die("Unexpected test dependency call");
96​
97describe("startup agent activity", () => {
98 it("publishes active work and only terminal runs completed after startup", () => {
99 const startedAt = DateTime.toEpochMillis(DateTime.makeUnsafe(NOW));
100 const oldCompleted = ThreadId.make("old-completed");
101 const newCompleted = ThreadId.make("new-completed");
102 const oldFailed = ThreadId.make("old-failed");
103 const newFailed = ThreadId.make("new-failed");
104 const ids = AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
105 environmentId: EnvironmentId.make("relay-env"),
106 startedAt,
107 projects: [{ id: PROJECT_ID, title: "Project" }],
108 threads: [
109 shell(),
110 shell({
111 id: oldCompleted,
112 status: "completed",
113 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
114 }),
115 shell({
116 id: newCompleted,
117 status: "completed",
118 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
119 }),
120 shell({
121 id: oldFailed,
122 status: "failed",
123 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
124 }),
125 shell({
126 id: newFailed,
127 status: "failed",
128 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
129 }),
130 shell({ id: ThreadId.make("idle"), status: "idle" }),
131 shell({ id: ThreadId.make("missing-project"), projectId: ProjectId.make("missing") }),
132 ],
133 });
134 assert.deepStrictEqual(ids, [THREAD_ID, newCompleted, newFailed]);
135 });
136});
137​
138const makeTestRelay = Effect.fnUntraced(function* (
139 options: {
140 readonly respond?: (attempt: number) => Response;
141 readonly failSecretRead?: (name: string) => boolean;
142 readonly linked?: boolean;
143 readonly readShell?: (threadId: ThreadId) => Effect.Effect<OrchestrationV2ThreadShell | null>;
144 readonly domainEvents?: Stream.Stream<OrchestrationV2DomainEvent>;
145 } = {},
146) {
147 const values = new Map<string, Uint8Array>(
148 options.linked === false
149 ? []
150 : [
151 [PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")],
152 [RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")],
153 [RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")],
154 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")],
155 ],
156 );
157 const secretReads: string[] = [];
158 const secrets = ServerSecretStore.ServerSecretStore.of({
159 get: (name) =>
160 Effect.suspend(() => {
161 secretReads.push(name);
162 if (options.failSecretRead?.(name)) {
163 return Effect.fail(
164 new ServerSecretStore.SecretStoreReadError({
165 resource: name,
166 cause: "temporary read failure",
167 }),
168 );
169 }
170 return Effect.succeed(Option.fromUndefinedOr(values.get(name)));
171 }),
172 create: (name, value) => Effect.sync(() => void values.set(name, value)),
173 set: (name, value) => Effect.sync(() => void values.set(name, value)),
174 remove: (name) => Effect.sync(() => void values.delete(name)),
175 getOrCreateRandom: unused,
176 });
177 const currentShell = yield* Ref.make<OrchestrationV2ThreadShell | null>(shell());
178 const shellReads: ThreadId[] = [];
179 const catchUp = { shellSnapshotReads: 0 };
180 const threads = ThreadManagementService.ThreadManagementService.of({
181 getThreadShell: (threadId) =>
182 Effect.sync(() => shellReads.push(threadId)).pipe(
183 Effect.andThen(options.readShell?.(threadId) ?? Ref.get(currentShell)),
184 ),
185 getShellSnapshot: () =>
186 Effect.sync(() => {
187 catchUp.shellSnapshotReads += 1;
188 return { schemaVersion: 2, snapshotSequence: 1, threads: [], archivedThreads: [] };
189 }),
190 listActiveSubagentThreadIds: unused,
191 readShellSnapshot: unused,
192 ensureLegacyTranscript: unused,
193 dispatch: unused,
194 searchThread: () => Effect.die("unused"),
195 searchThreadStream: () => Stream.empty,
196 getThreadHistoryPage: () => Effect.die("unused"),
197 getTimelinePage: () => Effect.die("Unused timeline read"),
198 getMessageCount: () => Effect.die("unused message count"),
199 getTurnItem: () => Effect.die("unused turn item read"),
200 getThreadRecords: () => Effect.die("unused record read"),
201 getThreadProjection: unused,
202 getCheckpointContext: unused,
203 getThreadSnapshot: unused,
204 getThreadTranscript: unused,
205 getThreadSnapshotWindow: unused,
206 getProjectThreadRecords: () => Effect.die("unused project record read"),
207 getProjectThread: unused,
208 listProjectThreads: unused,
209 sendToThread: unused,
210 assertProviderInstanceEnabled: unused,
211 isProviderInstanceEnabledForProject: unused,
212 hasReceipt: unused,
213 waitForThread: unused,
214 settleAfterRun: unused,
215 settleThread: unused,
216 interruptThread: unused,
217 stopWorkflow: () => Effect.die("unused stopWorkflow"),
218 awaitBackgroundTasks: unused,
219 stopDelegatedTasks: unused,
220 getThreadEventSequence: unused,
221 recoverDelegatedTask: unused,
222 delegatedTaskResultPending: unused,
223 streamStoredEvents: Stream.empty,
224 streamStoredEventsFrom: () => Stream.empty,
225 streamDomainEvents: options.domainEvents ?? Stream.empty,
226 });
227 const publications: Array<{
228 readonly url: string;
229 readonly authorization: string | null;
230 readonly state: RelayAgentActivityState | null;
231 }> = [];
232 const fetch: typeof globalThis.fetch = Object.assign(
233 (
234 input: Parameters<typeof globalThis.fetch>[0],
235 init?: Parameters<typeof globalThis.fetch>[1],
236 ) => {
237 const body = init?.body;
238 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
239 return Promise.reject(new Error("Expected a serialized activity publish payload"));
240 }
241 const payload = decodePublishPayload(
242 typeof body === "string" ? body : new TextDecoder().decode(body),
243 );
244 publications.push({
245 url: String(input),
246 authorization: new Headers(init?.headers).get("authorization"),
247 state: payload.state,
248 });
249 return Promise.resolve(
250 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
251 );
252 },
253 { preconnect: () => {} },
254 );
255 const relay = yield* AgentAwarenessRelay.make.pipe(
256 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
257 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
258 Effect.provideService(ServerEnvironment.ServerEnvironment, {
259 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
260 getDescriptor: unused(),
261 }),
262 Effect.provideService(ProjectService.ProjectService, {
263 create: unused,
264 bootstrap: unused,
265 update: unused,
266 delete: unused,
267 getByWorkspaceRoot: unused,
268 snapshot: Effect.succeed({ projects: [] } as never),
269 getShell: unused,
270 listShells: unused,
271 getById: () =>
272 Effect.succeed(
273 Option.some({
274 id: PROJECT_ID,
275 title: "Project",
276 workspaceRoot: "/workspace",
277 defaultModelSelection: null,
278 scripts: [],
279 createdAt: NOW,
280 updatedAt: NOW,
281 deletedAt: null,
282 }),
283 ),
284 }),
285 Effect.provideService(FetchHttpClient.Fetch, fetch),
286 Effect.provide(NodeCrypto.layer),
287 );
288 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
289});
290​
291describe("AgentAwarenessRelay", () => {
292 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
293 Effect.gen(function* () {
294 const started = yield* Deferred.make<void>();
295 const release = yield* Deferred.make<void>();
296 const rerunStarted = yield* Deferred.make<void>();
297 const releaseRerun = yield* Deferred.make<void>();
298 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
299 let revision = 1;
300 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
301 Effect.gen(function* () {
302 const currentRevision = revision;
303 const index = processed.length;
304 processed.push({ threadId, revision: currentRevision });
305 if (index === 0) {
306 yield* Deferred.succeed(started, undefined);
307 yield* Deferred.await(release);
308 } else if (threadId === THREAD_ID) {
309 yield* Deferred.succeed(rerunStarted, undefined);
310 yield* Deferred.await(releaseRerun);
311 }
312 }),
313 );
314 yield* worker.enqueue(THREAD_ID);
315 yield* Deferred.await(started);
316 revision = 2;
317 for (let i = 0; i < 100; i++) {
318 yield* worker.enqueue(SECOND_THREAD_ID);
319 yield* worker.enqueue(THREAD_ID);
320 }
321 const drained = yield* Deferred.make<void>();
322 const draining = yield* worker.drain.pipe(
323 Effect.andThen(Deferred.succeed(drained, undefined)),
324 Effect.forkChild,
325 );
326 yield* Deferred.succeed(release, undefined);
327 yield* Deferred.await(rerunStarted);
328 assert.isFalse(yield* Deferred.isDone(drained));
329 yield* Deferred.succeed(releaseRerun, undefined);
330 yield* Fiber.join(draining);
331 assert.deepEqual(processed, [
332 { threadId: THREAD_ID, revision: 1 },
333 { threadId: SECOND_THREAD_ID, revision: 2 },
334 { threadId: THREAD_ID, revision: 2 },
335 ]);
336 }),
337 );
338​
339 it.effect("deduplicates state and republishes title changes", () =>
340 Effect.gen(function* () {
341 const { relay, currentShell, publications } = yield* makeTestRelay();
342 yield* relay.publishThread(THREAD_ID);
343 yield* Ref.set(
344 currentShell,
345 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
346 );
347 yield* relay.publishThread(THREAD_ID);
348 assert.equal(publications.length, 1);
349 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
350 yield* relay.publishThread(THREAD_ID);
351 assert.equal(publications.length, 2);
352 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
353 }),
354 );
355​
356 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
357 Effect.gen(function* () {
358 const { relay, secrets, publications } = yield* makeTestRelay();
359 yield* relay.publishThread(THREAD_ID);
360 yield* secrets.set(
361 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
362 new TextEncoder().encode("credential-2"),
363 );
364 yield* relay.publishThread(THREAD_ID);
365 assert.equal(publications.length, 2);
366 assert.equal(publications[0]?.authorization, "Bearer credential-1");
367 assert.equal(publications[1]?.authorization, "Bearer credential-2");
368 yield* secrets.set(
369 RELAY_URL_SECRET,
370 new TextEncoder().encode("https://new-relay.example.test"),
371 );
372 yield* relay.publishThread(THREAD_ID);
373 assert.equal(publications.length, 3);
374 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
375 }),
376 );
377​
378 it.effect.each(["completed", "failed"] as const)(
379 "publishes a tombstone when a %s thread is settled through a domain event",
380 (status) =>
381 Effect.gen(function* () {
382 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
383 const pulls = yield* Queue.unbounded<void>();
384 const { relay, currentShell, publications } = yield* makeTestRelay({
385 domainEvents: Stream.fromEffectRepeat(
386 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
387 ),
388 });
389 yield* relay.start();
390 yield* Queue.take(pulls);
391 yield* relay.publishThread(THREAD_ID);
392 const terminal = shell({ status });
393 yield* Ref.set(currentShell, terminal);
394 yield* relay.publishThread(THREAD_ID);
395 yield* TestClock.adjust("5 seconds");
396 yield* relay.drain;
397 assert.equal(publications[1]?.state?.phase, status);
398​
399 const now = yield* DateTime.now;
400 const settled = {
401 ...terminal,
402 settledOverride: "settled" as const,
403 settledAt: now,
404 lastVisitedAt: null,
405 };
406 yield* Ref.set(currentShell, settled);
407 yield* Queue.offer(events, {
408 id: EventId.make("event:settled"),
409 type: "thread.settled",
410 threadId: THREAD_ID,
411 occurredAt: now,
412 payload: settled,
413 });
414 yield* Queue.take(pulls);
415 yield* relay.drain;
416 assert.equal(publications.length, 2);
417 yield* TestClock.adjust("5 seconds");
418 yield* relay.drain;
419 assert.equal(publications.length, 3);
420 assert.equal(publications[2]?.state, null);
421 }).pipe(Effect.scoped),
422 );
423​
424 it.effect("holds a completion through a continuation gap, then publishes it once", () =>
425 Effect.gen(function* () {
426 const { relay, currentShell, publications } = yield* makeTestRelay();
427 yield* relay.publishThread(THREAD_ID);
428 yield* Ref.set(currentShell, shell({ status: "completed" }));
429 yield* relay.publishThread(THREAD_ID);
430 yield* Ref.set(currentShell, shell());
431 yield* relay.publishThread(THREAD_ID);
432 yield* TestClock.adjust("5 seconds");
433 yield* relay.drain;
434 assert.deepEqual(
435 publications.map((publication) => publication.state?.phase),
436 ["running"],
437 );
438​
439 yield* Ref.set(currentShell, shell({ status: "completed" }));
440 yield* relay.publishThread(THREAD_ID);
441 assert.equal(publications.length, 1);
442 yield* TestClock.adjust("5 seconds");
443 yield* relay.drain;
444 assert.deepEqual(
445 publications.map((publication) => publication.state?.phase),
446 ["running", "completed"],
447 );
448 }),
449 );
450​
451 it.effect("still publishes a completion when the thread settles during the hold", () =>
452 Effect.gen(function* () {
453 const { relay, currentShell, publications } = yield* makeTestRelay();
454 yield* relay.publishThread(THREAD_ID);
455 const completed = shell({ status: "completed" });
456 yield* Ref.set(currentShell, completed);
457 yield* relay.publishThread(THREAD_ID);
458 yield* Ref.set(currentShell, {
459 ...completed,
460 settledOverride: "settled",
461 settledAt: yield* DateTime.now,
462 lastVisitedAt: null,
463 });
464 yield* relay.publishThread(THREAD_ID);
465 yield* TestClock.adjust("5 seconds");
466 yield* relay.drain;
467 assert.deepEqual(
468 publications.map((publication) => publication.state?.phase ?? null),
469 ["running", "completed"],
470 );
471​
472 yield* TestClock.adjust("5 seconds");
473 yield* relay.drain;
474 assert.deepEqual(
475 publications.map((publication) => publication.state?.phase ?? null),
476 ["running", "completed", null],
477 );
478 }),
479 );
480​
481 it.effect("drops a held completion when a queued continuation hides the thread", () =>
482 Effect.gen(function* () {
483 const { relay, currentShell, publications } = yield* makeTestRelay();
484 yield* relay.publishThread(THREAD_ID);
485 yield* Ref.set(currentShell, shell({ status: "completed" }));
486 yield* relay.publishThread(THREAD_ID);
487 yield* Ref.set(currentShell, shell({ status: "queued" }));
488 yield* relay.publishThread(THREAD_ID);
489 yield* TestClock.adjust("5 seconds");
490 yield* relay.drain;
491 assert.notInclude(
492 publications.map((publication) => publication.state?.phase ?? null),
493 "completed",
494 );
495 }),
496 );
497​
498 it.effect("retries a failed completion even after the thread settles", () =>
499 Effect.gen(function* () {
500 const { relay, currentShell, publications } = yield* makeTestRelay({
501 respond: (attempt) =>
502 attempt === 2
503 ? new Response("unavailable", { status: 503 })
504 : Response.json({ ok: true, deliveries: [] }),
505 });
506 yield* relay.publishThread(THREAD_ID);
507 const completed = shell({ status: "completed" });
508 yield* Ref.set(currentShell, completed);
509 yield* relay.publishThread(THREAD_ID);
510 yield* TestClock.adjust("5 seconds");
511 yield* relay.drain;
512 yield* Ref.set(currentShell, {
513 ...completed,
514 settledOverride: "settled",
515 settledAt: yield* DateTime.now,
516 lastVisitedAt: null,
517 });
518 yield* TestClock.adjust("1 second");
519 yield* relay.drain;
520 assert.deepEqual(
521 publications.map((publication) => publication.state?.phase ?? null),
522 ["running", "completed", "completed"],
523 );
524​
525 yield* TestClock.adjust("5 seconds");
526 yield* relay.drain;
527 assert.equal(publications.at(-1)?.state ?? null, null);
528 }),
529 );
530​
531 it.effect("keeps settled live work until its awaited monitor finishes", () =>
532 Effect.gen(function* () {
533 const { relay, currentShell, publications } = yield* makeTestRelay();
534 yield* relay.publishThread(THREAD_ID);
535 const held = shell({
536 status: "completed",
537 settledOverride: "settled",
538 pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
539 });
540 yield* Ref.set(currentShell, held);
541 yield* relay.publishThread(THREAD_ID);
542 yield* TestClock.adjust("5 seconds");
543 yield* relay.drain;
544 assert.equal(publications.length, 1);
545 assert.equal(publications[0]?.state?.phase, "running");
546​
547 yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
548 yield* relay.publishThread(THREAD_ID);
549 yield* TestClock.adjust("5 seconds");
550 yield* relay.drain;
551 assert.equal(publications.length, 2);
552 assert.equal(publications[1]?.state, null);
553 }),
554 );
555 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
556 Effect.gen(function* () {
557 const store = yield* ProjectionStore.ProjectionStoreV2;
558 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
559 const pulls = yield* Queue.unbounded<void>();
560 const { relay, shellReads, publications } = yield* makeTestRelay({
561 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
562 domainEvents: Stream.fromEffectRepeat(
563 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
564 ),
565 });
566 yield* relay.start();
567 yield* Queue.take(pulls);
568 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
569 yield* store.apply(event);
570 yield* Queue.offer(events, event);
571 yield* Queue.take(pulls);
572 yield* relay.drain;
573 });
574​
575 const now = yield* DateTime.now;
576 const runId = RunId.make("run:held-item");
577 const run = {
578 id: runId,
579 threadId: THREAD_ID,
580 ordinal: 1,
581 providerInstanceId: ProviderInstanceId.make("codex"),
582 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
583 providerThreadId: null,
584 userMessageId: MessageId.make("message:held-item"),
585 rootNodeId: null,
586 activeAttemptId: null,
587 status: "running" as const,
588 requestedAt: now,
589 startedAt: now,
590 completedAt: null,
591 checkpointId: null,
592 contextHandoffId: null,
593 };
594 const item = (
595 id: string,
596 fields: Pick<OrchestrationV2TurnItem, "status"> &
597 (
598 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
599 | {
600 readonly type: "assistant_message";
601 readonly messageId: MessageId;
602 readonly text: string;
603 readonly streaming: boolean;
604 }
605 ),
606 ): OrchestrationV2TurnItem => ({
607 id: TurnItemId.make(id),
608 threadId: THREAD_ID,
609 runId,
610 nodeId: NodeId.make("node:held-item"),
611 providerThreadId: null,
612 providerTurnId: null,
613 nativeItemRef: null,
614 parentItemId: null,
615 ordinal: 1,
616 title: null,
617 startedAt: now,
618 completedAt: null,
619 updatedAt: now,
620 ...fields,
621 });
622 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
623 ({
624 id: EventId.make(id),
625 type: "turn-item.updated",
626 threadId: THREAD_ID,
627 runId,
628 occurredAt: now,
629 payload,
630 }) satisfies OrchestrationV2DomainEvent;
631 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
632​
633 yield* deliver({
634 id: EventId.make("event:held-item:thread"),
635 type: "thread.created",
636 threadId: THREAD_ID,
637 occurredAt: now,
638 payload: {
639 createdBy: "user",
640 creationSource: "web",
641 id: THREAD_ID,
642 projectId: PROJECT_ID,
643 title: "Thread",
644 providerInstanceId: ProviderInstanceId.make("codex"),
645 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
646 runtimeMode: "full-access",
647 interactionMode: "default",
648 branch: null,
649 worktreePath: null,
650 activeProviderThreadId: null,
651 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
652 forkedFrom: null,
653 createdAt: now,
654 updatedAt: now,
655 archivedAt: null,
656 settledOverride: null,
657 settledAt: null,
658 lastVisitedAt: null,
659 deletedAt: null,
660 },
661 });
662 yield* deliver({
663 id: EventId.make("event:held-item:run"),
664 type: "run.created",
665 threadId: THREAD_ID,
666 runId,
667 occurredAt: now,
668 payload: run,
669 });
670 yield* deliver(
671 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
672 );
673 yield* deliver({
674 id: EventId.make("event:held-item:run-completed"),
675 type: "run.updated",
676 threadId: THREAD_ID,
677 runId,
678 occurredAt: now,
679 payload: { ...run, status: "completed", completedAt: now },
680 });
681 assert.deepEqual(
682 publications.map((publication) => publication.state?.phase),
683 ["running"],
684 );
685​
686 const readsBeforeOutput = shellReads.length;
687 yield* deliver(
688 itemEvent(
689 "event:held-item:reply",
690 item("item:reply", {
691 type: "assistant_message",
692 messageId: MessageId.make("message:held-item:reply"),
693 text: "Still watching",
694 streaming: true,
695 status: "running",
696 }),
697 ),
698 );
699 yield* deliver(
700 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
701 );
702 assert.equal(shellReads.length, readsBeforeOutput);
703​
704 yield* deliver(
705 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
706 );
707 yield* TestClock.adjust("5 seconds");
708 yield* relay.drain;
709 assert.deepEqual(
710 publications.map((publication) => publication.state?.phase),
711 ["running", "completed"],
712 );
713 }).pipe(Effect.scoped, Effect.provide(ProjectionStore.layerMemory)),
714 );
715});