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

AgentAwarenessRelay.test.ts

716 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.succeed(
274 Option.some({
275 id: PROJECT_ID,
276 title: "Project",
277 workspaceRoot: "/workspace",
278 defaultModelSelection: null,
279 scripts: [],
280 createdAt: NOW,
281 updatedAt: NOW,
282 deletedAt: null,
283 }),
284 ),
285 }),
286 Effect.provideService(FetchHttpClient.Fetch, fetch),
287 Effect.provide(NodeCrypto.layer),
288 );
289 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
290});
291​
292describe("AgentAwarenessRelay", () => {
293 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
294 Effect.gen(function* () {
295 const started = yield* Deferred.make<void>();
296 const release = yield* Deferred.make<void>();
297 const rerunStarted = yield* Deferred.make<void>();
298 const releaseRerun = yield* Deferred.make<void>();
299 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
300 let revision = 1;
301 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
302 Effect.gen(function* () {
303 const currentRevision = revision;
304 const index = processed.length;
305 processed.push({ threadId, revision: currentRevision });
306 if (index === 0) {
307 yield* Deferred.succeed(started, undefined);
308 yield* Deferred.await(release);
309 } else if (threadId === THREAD_ID) {
310 yield* Deferred.succeed(rerunStarted, undefined);
311 yield* Deferred.await(releaseRerun);
312 }
313 }),
314 );
315 yield* worker.enqueue(THREAD_ID);
316 yield* Deferred.await(started);
317 revision = 2;
318 for (let i = 0; i < 100; i++) {
319 yield* worker.enqueue(SECOND_THREAD_ID);
320 yield* worker.enqueue(THREAD_ID);
321 }
322 const drained = yield* Deferred.make<void>();
323 const draining = yield* worker.drain.pipe(
324 Effect.andThen(Deferred.succeed(drained, undefined)),
325 Effect.forkChild,
326 );
327 yield* Deferred.succeed(release, undefined);
328 yield* Deferred.await(rerunStarted);
329 assert.isFalse(yield* Deferred.isDone(drained));
330 yield* Deferred.succeed(releaseRerun, undefined);
331 yield* Fiber.join(draining);
332 assert.deepEqual(processed, [
333 { threadId: THREAD_ID, revision: 1 },
334 { threadId: SECOND_THREAD_ID, revision: 2 },
335 { threadId: THREAD_ID, revision: 2 },
336 ]);
337 }),
338 );
339​
340 it.effect("deduplicates state and republishes title changes", () =>
341 Effect.gen(function* () {
342 const { relay, currentShell, publications } = yield* makeTestRelay();
343 yield* relay.publishThread(THREAD_ID);
344 yield* Ref.set(
345 currentShell,
346 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
347 );
348 yield* relay.publishThread(THREAD_ID);
349 assert.equal(publications.length, 1);
350 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
351 yield* relay.publishThread(THREAD_ID);
352 assert.equal(publications.length, 2);
353 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
354 }),
355 );
356​
357 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
358 Effect.gen(function* () {
359 const { relay, secrets, publications } = yield* makeTestRelay();
360 yield* relay.publishThread(THREAD_ID);
361 yield* secrets.set(
362 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
363 new TextEncoder().encode("credential-2"),
364 );
365 yield* relay.publishThread(THREAD_ID);
366 assert.equal(publications.length, 2);
367 assert.equal(publications[0]?.authorization, "Bearer credential-1");
368 assert.equal(publications[1]?.authorization, "Bearer credential-2");
369 yield* secrets.set(
370 RELAY_URL_SECRET,
371 new TextEncoder().encode("https://new-relay.example.test"),
372 );
373 yield* relay.publishThread(THREAD_ID);
374 assert.equal(publications.length, 3);
375 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
376 }),
377 );
378​
379 it.effect.each(["completed", "failed"] as const)(
380 "publishes a tombstone when a %s thread is settled through a domain event",
381 (status) =>
382 Effect.gen(function* () {
383 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
384 const pulls = yield* Queue.unbounded<void>();
385 const { relay, currentShell, publications } = yield* makeTestRelay({
386 domainEvents: Stream.fromEffectRepeat(
387 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
388 ),
389 });
390 yield* relay.start();
391 yield* Queue.take(pulls);
392 yield* relay.publishThread(THREAD_ID);
393 const terminal = shell({ status });
394 yield* Ref.set(currentShell, terminal);
395 yield* relay.publishThread(THREAD_ID);
396 yield* TestClock.adjust("5 seconds");
397 yield* relay.drain;
398 assert.equal(publications[1]?.state?.phase, status);
399​
400 const now = yield* DateTime.now;
401 const settled = {
402 ...terminal,
403 settledOverride: "settled" as const,
404 settledAt: now,
405 lastVisitedAt: null,
406 };
407 yield* Ref.set(currentShell, settled);
408 yield* Queue.offer(events, {
409 id: EventId.make("event:settled"),
410 type: "thread.settled",
411 threadId: THREAD_ID,
412 occurredAt: now,
413 payload: settled,
414 });
415 yield* Queue.take(pulls);
416 yield* relay.drain;
417 assert.equal(publications.length, 2);
418 yield* TestClock.adjust("5 seconds");
419 yield* relay.drain;
420 assert.equal(publications.length, 3);
421 assert.equal(publications[2]?.state, null);
422 }).pipe(Effect.scoped),
423 );
424​
425 it.effect("holds a completion through a continuation gap, then publishes it once", () =>
426 Effect.gen(function* () {
427 const { relay, currentShell, publications } = yield* makeTestRelay();
428 yield* relay.publishThread(THREAD_ID);
429 yield* Ref.set(currentShell, shell({ status: "completed" }));
430 yield* relay.publishThread(THREAD_ID);
431 yield* Ref.set(currentShell, shell());
432 yield* relay.publishThread(THREAD_ID);
433 yield* TestClock.adjust("5 seconds");
434 yield* relay.drain;
435 assert.deepEqual(
436 publications.map((publication) => publication.state?.phase),
437 ["running"],
438 );
439​
440 yield* Ref.set(currentShell, shell({ status: "completed" }));
441 yield* relay.publishThread(THREAD_ID);
442 assert.equal(publications.length, 1);
443 yield* TestClock.adjust("5 seconds");
444 yield* relay.drain;
445 assert.deepEqual(
446 publications.map((publication) => publication.state?.phase),
447 ["running", "completed"],
448 );
449 }),
450 );
451​
452 it.effect("still publishes a completion when the thread settles during the hold", () =>
453 Effect.gen(function* () {
454 const { relay, currentShell, publications } = yield* makeTestRelay();
455 yield* relay.publishThread(THREAD_ID);
456 const completed = shell({ status: "completed" });
457 yield* Ref.set(currentShell, completed);
458 yield* relay.publishThread(THREAD_ID);
459 yield* Ref.set(currentShell, {
460 ...completed,
461 settledOverride: "settled",
462 settledAt: yield* DateTime.now,
463 lastVisitedAt: null,
464 });
465 yield* relay.publishThread(THREAD_ID);
466 yield* TestClock.adjust("5 seconds");
467 yield* relay.drain;
468 assert.deepEqual(
469 publications.map((publication) => publication.state?.phase ?? null),
470 ["running", "completed"],
471 );
472​
473 yield* TestClock.adjust("5 seconds");
474 yield* relay.drain;
475 assert.deepEqual(
476 publications.map((publication) => publication.state?.phase ?? null),
477 ["running", "completed", null],
478 );
479 }),
480 );
481​
482 it.effect("drops a held completion when a queued continuation hides the thread", () =>
483 Effect.gen(function* () {
484 const { relay, currentShell, publications } = yield* makeTestRelay();
485 yield* relay.publishThread(THREAD_ID);
486 yield* Ref.set(currentShell, shell({ status: "completed" }));
487 yield* relay.publishThread(THREAD_ID);
488 yield* Ref.set(currentShell, shell({ status: "queued" }));
489 yield* relay.publishThread(THREAD_ID);
490 yield* TestClock.adjust("5 seconds");
491 yield* relay.drain;
492 assert.notInclude(
493 publications.map((publication) => publication.state?.phase ?? null),
494 "completed",
495 );
496 }),
497 );
498​
499 it.effect("retries a failed completion even after the thread settles", () =>
500 Effect.gen(function* () {
501 const { relay, currentShell, publications } = yield* makeTestRelay({
502 respond: (attempt) =>
503 attempt === 2
504 ? new Response("unavailable", { status: 503 })
505 : Response.json({ ok: true, deliveries: [] }),
506 });
507 yield* relay.publishThread(THREAD_ID);
508 const completed = shell({ status: "completed" });
509 yield* Ref.set(currentShell, completed);
510 yield* relay.publishThread(THREAD_ID);
511 yield* TestClock.adjust("5 seconds");
512 yield* relay.drain;
513 yield* Ref.set(currentShell, {
514 ...completed,
515 settledOverride: "settled",
516 settledAt: yield* DateTime.now,
517 lastVisitedAt: null,
518 });
519 yield* TestClock.adjust("1 second");
520 yield* relay.drain;
521 assert.deepEqual(
522 publications.map((publication) => publication.state?.phase ?? null),
523 ["running", "completed", "completed"],
524 );
525​
526 yield* TestClock.adjust("5 seconds");
527 yield* relay.drain;
528 assert.equal(publications.at(-1)?.state ?? null, null);
529 }),
530 );
531​
532 it.effect("keeps settled live work until its awaited monitor finishes", () =>
533 Effect.gen(function* () {
534 const { relay, currentShell, publications } = yield* makeTestRelay();
535 yield* relay.publishThread(THREAD_ID);
536 const held = shell({
537 status: "completed",
538 settledOverride: "settled",
539 pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
540 });
541 yield* Ref.set(currentShell, held);
542 yield* relay.publishThread(THREAD_ID);
543 yield* TestClock.adjust("5 seconds");
544 yield* relay.drain;
545 assert.equal(publications.length, 1);
546 assert.equal(publications[0]?.state?.phase, "running");
547​
548 yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
549 yield* relay.publishThread(THREAD_ID);
550 yield* TestClock.adjust("5 seconds");
551 yield* relay.drain;
552 assert.equal(publications.length, 2);
553 assert.equal(publications[1]?.state, null);
554 }),
555 );
556 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
557 Effect.gen(function* () {
558 const store = yield* ProjectionStore.ProjectionStoreV2;
559 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
560 const pulls = yield* Queue.unbounded<void>();
561 const { relay, shellReads, publications } = yield* makeTestRelay({
562 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
563 domainEvents: Stream.fromEffectRepeat(
564 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
565 ),
566 });
567 yield* relay.start();
568 yield* Queue.take(pulls);
569 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
570 yield* store.apply(event);
571 yield* Queue.offer(events, event);
572 yield* Queue.take(pulls);
573 yield* relay.drain;
574 });
575​
576 const now = yield* DateTime.now;
577 const runId = RunId.make("run:held-item");
578 const run = {
579 id: runId,
580 threadId: THREAD_ID,
581 ordinal: 1,
582 providerInstanceId: ProviderInstanceId.make("codex"),
583 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
584 providerThreadId: null,
585 userMessageId: MessageId.make("message:held-item"),
586 rootNodeId: null,
587 activeAttemptId: null,
588 status: "running" as const,
589 requestedAt: now,
590 startedAt: now,
591 completedAt: null,
592 checkpointId: null,
593 contextHandoffId: null,
594 };
595 const item = (
596 id: string,
597 fields: Pick<OrchestrationV2TurnItem, "status"> &
598 (
599 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
600 | {
601 readonly type: "assistant_message";
602 readonly messageId: MessageId;
603 readonly text: string;
604 readonly streaming: boolean;
605 }
606 ),
607 ): OrchestrationV2TurnItem => ({
608 id: TurnItemId.make(id),
609 threadId: THREAD_ID,
610 runId,
611 nodeId: NodeId.make("node:held-item"),
612 providerThreadId: null,
613 providerTurnId: null,
614 nativeItemRef: null,
615 parentItemId: null,
616 ordinal: 1,
617 title: null,
618 startedAt: now,
619 completedAt: null,
620 updatedAt: now,
621 ...fields,
622 });
623 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
624 ({
625 id: EventId.make(id),
626 type: "turn-item.updated",
627 threadId: THREAD_ID,
628 runId,
629 occurredAt: now,
630 payload,
631 }) satisfies OrchestrationV2DomainEvent;
632 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
633​
634 yield* deliver({
635 id: EventId.make("event:held-item:thread"),
636 type: "thread.created",
637 threadId: THREAD_ID,
638 occurredAt: now,
639 payload: {
640 createdBy: "user",
641 creationSource: "web",
642 id: THREAD_ID,
643 projectId: PROJECT_ID,
644 title: "Thread",
645 providerInstanceId: ProviderInstanceId.make("codex"),
646 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
647 runtimeMode: "full-access",
648 interactionMode: "default",
649 branch: null,
650 worktreePath: null,
651 activeProviderThreadId: null,
652 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
653 forkedFrom: null,
654 createdAt: now,
655 updatedAt: now,
656 archivedAt: null,
657 settledOverride: null,
658 settledAt: null,
659 lastVisitedAt: null,
660 deletedAt: null,
661 },
662 });
663 yield* deliver({
664 id: EventId.make("event:held-item:run"),
665 type: "run.created",
666 threadId: THREAD_ID,
667 runId,
668 occurredAt: now,
669 payload: run,
670 });
671 yield* deliver(
672 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
673 );
674 yield* deliver({
675 id: EventId.make("event:held-item:run-completed"),
676 type: "run.updated",
677 threadId: THREAD_ID,
678 runId,
679 occurredAt: now,
680 payload: { ...run, status: "completed", completedAt: now },
681 });
682 assert.deepEqual(
683 publications.map((publication) => publication.state?.phase),
684 ["running"],
685 );
686​
687 const readsBeforeOutput = shellReads.length;
688 yield* deliver(
689 itemEvent(
690 "event:held-item:reply",
691 item("item:reply", {
692 type: "assistant_message",
693 messageId: MessageId.make("message:held-item:reply"),
694 text: "Still watching",
695 streaming: true,
696 status: "running",
697 }),
698 ),
699 );
700 yield* deliver(
701 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
702 );
703 assert.equal(shellReads.length, readsBeforeOutput);
704​
705 yield* deliver(
706 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
707 );
708 yield* TestClock.adjust("5 seconds");
709 yield* relay.drain;
710 assert.deepEqual(
711 publications.map((publication) => publication.state?.phase),
712 ["running", "completed"],
713 );
714 }).pipe(Effect.scoped, Effect.provide(ProjectionStore.layerMemory)),
715 );
716});