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

AgentAwarenessRelay.test.ts

714 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 listOlderSettledThreads: unused,
192 readShellSnapshot: unused,
193 ensureLegacyTranscript: unused,
194 dispatch: unused,
195 searchThread: () => Effect.die("unused"),
196 searchThreadStream: () => Stream.empty,
197 getThreadHistoryPage: () => Effect.die("unused"),
198 getTimelinePage: () => Effect.die("Unused timeline read"),
199 getMessageCount: () => Effect.die("unused message count"),
200 getTurnItem: () => Effect.die("unused turn item read"),
201 getThreadRecords: () => Effect.die("unused record read"),
202 getThreadProjection: unused,
203 getCheckpointContext: unused,
204 getThreadSnapshot: unused,
205 getThreadTranscript: unused,
206 getThreadSnapshotWindow: unused,
207 getProjectThreadRecords: () => Effect.die("unused project record read"),
208 getProjectThread: unused,
209 listProjectThreads: unused,
210 sendToThread: unused,
211 assertProviderInstanceEnabled: unused,
212 isProviderInstanceEnabledForProject: unused,
213 hasReceipt: unused,
214 waitForThread: unused,
215 settleAfterRun: unused,
216 settleThread: unused,
217 interruptThread: unused,
218 stopWorkflow: () => Effect.die("unused stopWorkflow"),
219 awaitBackgroundTasks: unused,
220 stopDelegatedTasks: unused,
221 getThreadEventSequence: unused,
222 recoverDelegatedTask: unused,
223 delegatedTaskResultPending: unused,
224 streamStoredEvents: Stream.empty,
225 streamStoredEventsFrom: () => Stream.empty,
226 streamDomainEvents: options.domainEvents ?? Stream.empty,
227 });
228 const publications: Array<{
229 readonly url: string;
230 readonly authorization: string | null;
231 readonly state: RelayAgentActivityState | null;
232 }> = [];
233 const fetch: typeof globalThis.fetch = Object.assign(
234 (
235 input: Parameters<typeof globalThis.fetch>[0],
236 init?: Parameters<typeof globalThis.fetch>[1],
237 ) => {
238 const body = init?.body;
239 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
240 return Promise.reject(new Error("Expected a serialized activity publish payload"));
241 }
242 const payload = decodePublishPayload(
243 typeof body === "string" ? body : new TextDecoder().decode(body),
244 );
245 publications.push({
246 url: String(input),
247 authorization: new Headers(init?.headers).get("authorization"),
248 state: payload.state,
249 });
250 return Promise.resolve(
251 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
252 );
253 },
254 { preconnect: () => {} },
255 );
256 const relay = yield* AgentAwarenessRelay.make.pipe(
257 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
258 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
259 Effect.provideService(ServerEnvironment.ServerEnvironment, {
260 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
261 getDescriptor: unused(),
262 }),
263 Effect.provideService(ProjectService.ProjectService, {
264 create: unused,
265 bootstrap: unused,
266 update: unused,
267 delete: unused,
268 getByWorkspaceRoot: unused,
269 snapshot: Effect.succeed({ projects: [] } as never),
270 getShell: unused,
271 listShells: unused,
272 getById: () =>
273 Effect.succeedSome({
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 Effect.provideService(FetchHttpClient.Fetch, fetch),
285 Effect.provide(NodeCrypto.layer),
286 );
287 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
288});
289​
290describe("AgentAwarenessRelay", () => {
291 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
292 Effect.gen(function* () {
293 const started = yield* Deferred.make<void>();
294 const release = yield* Deferred.make<void>();
295 const rerunStarted = yield* Deferred.make<void>();
296 const releaseRerun = yield* Deferred.make<void>();
297 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
298 let revision = 1;
299 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
300 Effect.gen(function* () {
301 const currentRevision = revision;
302 const index = processed.length;
303 processed.push({ threadId, revision: currentRevision });
304 if (index === 0) {
305 yield* Deferred.succeed(started, undefined);
306 yield* Deferred.await(release);
307 } else if (threadId === THREAD_ID) {
308 yield* Deferred.succeed(rerunStarted, undefined);
309 yield* Deferred.await(releaseRerun);
310 }
311 }),
312 );
313 yield* worker.enqueue(THREAD_ID);
314 yield* Deferred.await(started);
315 revision = 2;
316 for (let i = 0; i < 100; i++) {
317 yield* worker.enqueue(SECOND_THREAD_ID);
318 yield* worker.enqueue(THREAD_ID);
319 }
320 const drained = yield* Deferred.make<void>();
321 const draining = yield* worker.drain.pipe(
322 Effect.andThen(Deferred.succeed(drained, undefined)),
323 Effect.forkChild,
324 );
325 yield* Deferred.succeed(release, undefined);
326 yield* Deferred.await(rerunStarted);
327 assert.isFalse(yield* Deferred.isDone(drained));
328 yield* Deferred.succeed(releaseRerun, undefined);
329 yield* Fiber.join(draining);
330 assert.deepEqual(processed, [
331 { threadId: THREAD_ID, revision: 1 },
332 { threadId: SECOND_THREAD_ID, revision: 2 },
333 { threadId: THREAD_ID, revision: 2 },
334 ]);
335 }),
336 );
337​
338 it.effect("deduplicates state and republishes title changes", () =>
339 Effect.gen(function* () {
340 const { relay, currentShell, publications } = yield* makeTestRelay();
341 yield* relay.publishThread(THREAD_ID);
342 yield* Ref.set(
343 currentShell,
344 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
345 );
346 yield* relay.publishThread(THREAD_ID);
347 assert.equal(publications.length, 1);
348 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
349 yield* relay.publishThread(THREAD_ID);
350 assert.equal(publications.length, 2);
351 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
352 }),
353 );
354​
355 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
356 Effect.gen(function* () {
357 const { relay, secrets, publications } = yield* makeTestRelay();
358 yield* relay.publishThread(THREAD_ID);
359 yield* secrets.set(
360 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
361 new TextEncoder().encode("credential-2"),
362 );
363 yield* relay.publishThread(THREAD_ID);
364 assert.equal(publications.length, 2);
365 assert.equal(publications[0]?.authorization, "Bearer credential-1");
366 assert.equal(publications[1]?.authorization, "Bearer credential-2");
367 yield* secrets.set(
368 RELAY_URL_SECRET,
369 new TextEncoder().encode("https://new-relay.example.test"),
370 );
371 yield* relay.publishThread(THREAD_ID);
372 assert.equal(publications.length, 3);
373 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
374 }),
375 );
376​
377 it.effect.each(["completed", "failed"] as const)(
378 "publishes a tombstone when a %s thread is settled through a domain event",
379 (status) =>
380 Effect.gen(function* () {
381 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
382 const pulls = yield* Queue.unbounded<void>();
383 const { relay, currentShell, publications } = yield* makeTestRelay({
384 domainEvents: Stream.fromEffectRepeat(
385 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
386 ),
387 });
388 yield* relay.start();
389 yield* Queue.take(pulls);
390 yield* relay.publishThread(THREAD_ID);
391 const terminal = shell({ status });
392 yield* Ref.set(currentShell, terminal);
393 yield* relay.publishThread(THREAD_ID);
394 yield* TestClock.adjust("5 seconds");
395 yield* relay.drain;
396 assert.equal(publications[1]?.state?.phase, status);
397​
398 const now = yield* DateTime.now;
399 const settled = {
400 ...terminal,
401 settledOverride: "settled" as const,
402 settledAt: now,
403 lastVisitedAt: null,
404 };
405 yield* Ref.set(currentShell, settled);
406 yield* Queue.offer(events, {
407 id: EventId.make("event:settled"),
408 type: "thread.settled",
409 threadId: THREAD_ID,
410 occurredAt: now,
411 payload: settled,
412 });
413 yield* Queue.take(pulls);
414 yield* relay.drain;
415 assert.equal(publications.length, 2);
416 yield* TestClock.adjust("5 seconds");
417 yield* relay.drain;
418 assert.equal(publications.length, 3);
419 assert.equal(publications[2]?.state, null);
420 }).pipe(Effect.scoped),
421 );
422​
423 it.effect("holds a completion through a continuation gap, then publishes it once", () =>
424 Effect.gen(function* () {
425 const { relay, currentShell, publications } = yield* makeTestRelay();
426 yield* relay.publishThread(THREAD_ID);
427 yield* Ref.set(currentShell, shell({ status: "completed" }));
428 yield* relay.publishThread(THREAD_ID);
429 yield* Ref.set(currentShell, shell());
430 yield* relay.publishThread(THREAD_ID);
431 yield* TestClock.adjust("5 seconds");
432 yield* relay.drain;
433 assert.deepEqual(
434 publications.map((publication) => publication.state?.phase),
435 ["running"],
436 );
437​
438 yield* Ref.set(currentShell, shell({ status: "completed" }));
439 yield* relay.publishThread(THREAD_ID);
440 assert.equal(publications.length, 1);
441 yield* TestClock.adjust("5 seconds");
442 yield* relay.drain;
443 assert.deepEqual(
444 publications.map((publication) => publication.state?.phase),
445 ["running", "completed"],
446 );
447 }),
448 );
449​
450 it.effect("still publishes a completion when the thread settles during the hold", () =>
451 Effect.gen(function* () {
452 const { relay, currentShell, publications } = yield* makeTestRelay();
453 yield* relay.publishThread(THREAD_ID);
454 const completed = shell({ status: "completed" });
455 yield* Ref.set(currentShell, completed);
456 yield* relay.publishThread(THREAD_ID);
457 yield* Ref.set(currentShell, {
458 ...completed,
459 settledOverride: "settled",
460 settledAt: yield* DateTime.now,
461 lastVisitedAt: null,
462 });
463 yield* relay.publishThread(THREAD_ID);
464 yield* TestClock.adjust("5 seconds");
465 yield* relay.drain;
466 assert.deepEqual(
467 publications.map((publication) => publication.state?.phase ?? null),
468 ["running", "completed"],
469 );
470​
471 yield* TestClock.adjust("5 seconds");
472 yield* relay.drain;
473 assert.deepEqual(
474 publications.map((publication) => publication.state?.phase ?? null),
475 ["running", "completed", null],
476 );
477 }),
478 );
479​
480 it.effect("drops a held completion when a queued continuation hides the thread", () =>
481 Effect.gen(function* () {
482 const { relay, currentShell, publications } = yield* makeTestRelay();
483 yield* relay.publishThread(THREAD_ID);
484 yield* Ref.set(currentShell, shell({ status: "completed" }));
485 yield* relay.publishThread(THREAD_ID);
486 yield* Ref.set(currentShell, shell({ status: "queued" }));
487 yield* relay.publishThread(THREAD_ID);
488 yield* TestClock.adjust("5 seconds");
489 yield* relay.drain;
490 assert.notInclude(
491 publications.map((publication) => publication.state?.phase ?? null),
492 "completed",
493 );
494 }),
495 );
496​
497 it.effect("retries a failed completion even after the thread settles", () =>
498 Effect.gen(function* () {
499 const { relay, currentShell, publications } = yield* makeTestRelay({
500 respond: (attempt) =>
501 attempt === 2
502 ? new Response("unavailable", { status: 503 })
503 : Response.json({ ok: true, deliveries: [] }),
504 });
505 yield* relay.publishThread(THREAD_ID);
506 const completed = shell({ status: "completed" });
507 yield* Ref.set(currentShell, completed);
508 yield* relay.publishThread(THREAD_ID);
509 yield* TestClock.adjust("5 seconds");
510 yield* relay.drain;
511 yield* Ref.set(currentShell, {
512 ...completed,
513 settledOverride: "settled",
514 settledAt: yield* DateTime.now,
515 lastVisitedAt: null,
516 });
517 yield* TestClock.adjust("1 second");
518 yield* relay.drain;
519 assert.deepEqual(
520 publications.map((publication) => publication.state?.phase ?? null),
521 ["running", "completed", "completed"],
522 );
523​
524 yield* TestClock.adjust("5 seconds");
525 yield* relay.drain;
526 assert.equal(publications.at(-1)?.state ?? null, null);
527 }),
528 );
529​
530 it.effect("keeps settled live work until its awaited monitor finishes", () =>
531 Effect.gen(function* () {
532 const { relay, currentShell, publications } = yield* makeTestRelay();
533 yield* relay.publishThread(THREAD_ID);
534 const held = shell({
535 status: "completed",
536 settledOverride: "settled",
537 pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
538 });
539 yield* Ref.set(currentShell, held);
540 yield* relay.publishThread(THREAD_ID);
541 yield* TestClock.adjust("5 seconds");
542 yield* relay.drain;
543 assert.equal(publications.length, 1);
544 assert.equal(publications[0]?.state?.phase, "running");
545​
546 yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
547 yield* relay.publishThread(THREAD_ID);
548 yield* TestClock.adjust("5 seconds");
549 yield* relay.drain;
550 assert.equal(publications.length, 2);
551 assert.equal(publications[1]?.state, null);
552 }),
553 );
554 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
555 Effect.gen(function* () {
556 const store = yield* ProjectionStore.ProjectionStoreV2;
557 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
558 const pulls = yield* Queue.unbounded<void>();
559 const { relay, shellReads, publications } = yield* makeTestRelay({
560 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
561 domainEvents: Stream.fromEffectRepeat(
562 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
563 ),
564 });
565 yield* relay.start();
566 yield* Queue.take(pulls);
567 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
568 yield* store.apply(event);
569 yield* Queue.offer(events, event);
570 yield* Queue.take(pulls);
571 yield* relay.drain;
572 });
573​
574 const now = yield* DateTime.now;
575 const runId = RunId.make("run:held-item");
576 const run = {
577 id: runId,
578 threadId: THREAD_ID,
579 ordinal: 1,
580 providerInstanceId: ProviderInstanceId.make("codex"),
581 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
582 providerThreadId: null,
583 userMessageId: MessageId.make("message:held-item"),
584 rootNodeId: null,
585 activeAttemptId: null,
586 status: "running" as const,
587 requestedAt: now,
588 startedAt: now,
589 completedAt: null,
590 checkpointId: null,
591 contextHandoffId: null,
592 };
593 const item = (
594 id: string,
595 fields: Pick<OrchestrationV2TurnItem, "status"> &
596 (
597 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
598 | {
599 readonly type: "assistant_message";
600 readonly messageId: MessageId;
601 readonly text: string;
602 readonly streaming: boolean;
603 }
604 ),
605 ): OrchestrationV2TurnItem => ({
606 id: TurnItemId.make(id),
607 threadId: THREAD_ID,
608 runId,
609 nodeId: NodeId.make("node:held-item"),
610 providerThreadId: null,
611 providerTurnId: null,
612 nativeItemRef: null,
613 parentItemId: null,
614 ordinal: 1,
615 title: null,
616 startedAt: now,
617 completedAt: null,
618 updatedAt: now,
619 ...fields,
620 });
621 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
622 ({
623 id: EventId.make(id),
624 type: "turn-item.updated",
625 threadId: THREAD_ID,
626 runId,
627 occurredAt: now,
628 payload,
629 }) satisfies OrchestrationV2DomainEvent;
630 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
631​
632 yield* deliver({
633 id: EventId.make("event:held-item:thread"),
634 type: "thread.created",
635 threadId: THREAD_ID,
636 occurredAt: now,
637 payload: {
638 createdBy: "user",
639 creationSource: "web",
640 id: THREAD_ID,
641 projectId: PROJECT_ID,
642 title: "Thread",
643 providerInstanceId: ProviderInstanceId.make("codex"),
644 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
645 runtimeMode: "full-access",
646 interactionMode: "default",
647 branch: null,
648 worktreePath: null,
649 activeProviderThreadId: null,
650 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
651 forkedFrom: null,
652 createdAt: now,
653 updatedAt: now,
654 archivedAt: null,
655 settledOverride: null,
656 settledAt: null,
657 lastVisitedAt: null,
658 deletedAt: null,
659 },
660 });
661 yield* deliver({
662 id: EventId.make("event:held-item:run"),
663 type: "run.created",
664 threadId: THREAD_ID,
665 runId,
666 occurredAt: now,
667 payload: run,
668 });
669 yield* deliver(
670 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
671 );
672 yield* deliver({
673 id: EventId.make("event:held-item:run-completed"),
674 type: "run.updated",
675 threadId: THREAD_ID,
676 runId,
677 occurredAt: now,
678 payload: { ...run, status: "completed", completedAt: now },
679 });
680 assert.deepEqual(
681 publications.map((publication) => publication.state?.phase),
682 ["running"],
683 );
684​
685 const readsBeforeOutput = shellReads.length;
686 yield* deliver(
687 itemEvent(
688 "event:held-item:reply",
689 item("item:reply", {
690 type: "assistant_message",
691 messageId: MessageId.make("message:held-item:reply"),
692 text: "Still watching",
693 streaming: true,
694 status: "running",
695 }),
696 ),
697 );
698 yield* deliver(
699 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
700 );
701 assert.equal(shellReads.length, readsBeforeOutput);
702​
703 yield* deliver(
704 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
705 );
706 yield* TestClock.adjust("5 seconds");
707 yield* relay.drain;
708 assert.deepEqual(
709 publications.map((publication) => publication.state?.phase),
710 ["running", "completed"],
711 );
712 }).pipe(Effect.scoped, Effect.provide(ProjectionStore.layerMemory)),
713 );
714});