Open History to see the last commit
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 Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as Schema from "effect/Schema";
27import * as Stream from "effect/Stream";
28import * as TestClock from "effect/testing/TestClock";
29import * as FetchHttpClient from "effect/http/FetchHttpClient";
30
31import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
32import {
33 PUBLISH_AGENT_ACTIVITY_SECRET,
34 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
35 RELAY_ISSUER_SECRET,
36 RELAY_URL_SECRET,
37} from "../cloud/config.ts";
38import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
39import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
40import * as SqlitePersistence from "../persistence/Sqlite.ts";
41import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
42import * as ProjectService from "../project/ProjectService.ts";
43import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";
44
45const THREAD_ID = ThreadId.make("relay-thread");
46const SECOND_THREAD_ID = ThreadId.make("relay-thread-2");
47const PROJECT_ID = ProjectId.make("relay-project");
48const NOW = "2026-09-04T12:00:00.000Z";
49
50function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
51 return {
52 id: THREAD_ID,
53 projectId: PROJECT_ID,
54 title: "Thread",
55 providerInstanceId: ProviderInstanceId.make("codex"),
56 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
57 runtimeMode: "full-access",
58 interactionMode: "default",
59 worktreePath: null,
60 activeProviderThreadId: null,
61 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
62 forkedFrom: null,
63 createdBy: "user",
64 creationSource: "web",
65 activeRunId: null,
66 latestVisibleMessage: null,
67 hasActionableProposedPlan: false,
68 itemCount: 0,
69 visibleItemCount: 0,
70 lastVisitedAt: null,
71 deletedAt: null,
72 branch: null,
73 linkedPullRequest: null,
74 status: "running",
75 activityRunStatus: null,
76 pendingRuntimeRequest: null,
77 pendingBackgroundTasks: [],
78 latestRunId: null,
79 latestRunRequestedAt: null,
80 latestRunStartedAt: null,
81 latestRunCompletedAt: null,
82 latestUserMessageAt: null,
83 createdAt: DateTime.makeUnsafe(NOW),
84 updatedAt: DateTime.makeUnsafe(NOW),
85 archivedAt: null,
86 settledOverride: null,
87 settledAt: null,
88 snoozedUntil: null,
89 snoozedAt: null,
90 pinnedAt: null,
91 ...overrides,
92 };
93}
94
95const PublishPayload = Schema.Struct({ state: Schema.NullOr(RelayAgentActivityState) });
96const decodePublishPayload = Schema.decodeUnknownSync(Schema.fromJsonString(PublishPayload));
97const unused = () => Effect.die("Unexpected test dependency call");
98
99describe("startup agent activity", () => {
100 it("publishes active work and only terminal runs completed after startup", () => {
101 const startedAt = DateTime.toEpochMillis(DateTime.makeUnsafe(NOW));
102 const oldCompleted = ThreadId.make("old-completed");
103 const newCompleted = ThreadId.make("new-completed");
104 const oldFailed = ThreadId.make("old-failed");
105 const newFailed = ThreadId.make("new-failed");
106 const ids = AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
107 environmentId: EnvironmentId.make("relay-env"),
108 startedAt,
109 projects: [{ id: PROJECT_ID, title: "Project" }],
110 threads: [
111 shell(),
112 shell({
113 id: oldCompleted,
114 status: "completed",
115 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
116 }),
117 shell({
118 id: newCompleted,
119 status: "completed",
120 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
121 }),
122 shell({
123 id: oldFailed,
124 status: "failed",
125 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
126 }),
127 shell({
128 id: newFailed,
129 status: "failed",
130 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
131 }),
132 shell({ id: ThreadId.make("idle"), status: "idle" }),
133 shell({ id: ThreadId.make("missing-project"), projectId: ProjectId.make("missing") }),
134 ],
135 });
136 assert.deepStrictEqual(ids, [THREAD_ID, newCompleted, newFailed]);
137 });
138});
139
140const makeTestRelay = Effect.fnUntraced(function* (
141 options: {
142 readonly respond?: (attempt: number) => Response;
143 readonly failSecretRead?: (name: string) => boolean;
144 readonly linked?: boolean;
145 readonly readShell?: (threadId: ThreadId) => Effect.Effect<OrchestrationV2ThreadShell | null>;
146 readonly domainEvents?: Stream.Stream<OrchestrationV2DomainEvent>;
147 } = {},
148) {
149 const values = new Map<string, Uint8Array>(
150 options.linked === false
151 ? []
152 : [
153 [PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")],
154 [RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")],
155 [RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")],
156 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")],
157 ],
158 );
159 const secretReads: string[] = [];
160 const secrets = ServerSecretStore.ServerSecretStore.of({
161 get: (name) =>
162 Effect.suspend(() => {
163 secretReads.push(name);
164 if (options.failSecretRead?.(name)) {
165 return Effect.fail(
166 new ServerSecretStore.SecretStoreReadError({
167 resource: name,
168 cause: "temporary read failure",
169 }),
170 );
171 }
172 return Effect.succeed(Option.fromUndefinedOr(values.get(name)));
173 }),
174 create: (name, value) => Effect.sync(() => void values.set(name, value)),
175 set: (name, value) => Effect.sync(() => void values.set(name, value)),
176 remove: (name) => Effect.sync(() => void values.delete(name)),
177 getOrCreateRandom: unused,
178 });
179 const currentShell = yield* Ref.make<OrchestrationV2ThreadShell | null>(shell());
180 const shellReads: ThreadId[] = [];
181 const catchUp = { shellSnapshotReads: 0 };
182 const threads = ThreadManagementService.ThreadManagementService.of({
183 getThreadShell: (threadId) =>
184 Effect.sync(() => shellReads.push(threadId)).pipe(
185 Effect.andThen(options.readShell?.(threadId) ?? Ref.get(currentShell)),
186 ),
187 getShellSnapshot: () =>
188 Effect.sync(() => {
189 catchUp.shellSnapshotReads += 1;
190 return { schemaVersion: 2, snapshotSequence: 1, threads: [], archivedThreads: [] };
191 }),
192 listActiveSubagentThreadIds: unused,
193 listOlderSettledThreads: unused,
194 readShellSnapshot: unused,
195 ensureLegacyTranscript: unused,
196 dispatch: unused,
197 searchThread: () => Effect.die("unused"),
198 searchThreadStream: () => Stream.empty,
199 getThreadHistoryPage: () => Effect.die("unused"),
200 getTimelinePage: () => Effect.die("Unused timeline read"),
201 getMessageCount: () => Effect.die("unused message count"),
202 getTurnItem: () => Effect.die("unused turn item read"),
203 getThreadRecords: () => Effect.die("unused record read"),
204 getThreadProjection: unused,
205 getCheckpointContext: unused,
206 getThreadSnapshot: unused,
207 getThreadTranscript: unused,
208 getThreadSnapshotWindow: unused,
209 getProjectThreadRecords: () => Effect.die("unused project record read"),
210 listProjectThreads: unused,
211 sendToThread: unused,
212 assertProviderInstanceEnabled: unused,
213 isProviderInstanceEnabledForProject: unused,
214 hasReceipt: unused,
215 waitForThread: unused,
216 settleAfterRun: unused,
217 settleThread: unused,
218 interruptThread: unused,
219 stopWorkflow: () => Effect.die("unused stopWorkflow"),
220 awaitBackgroundTasks: unused,
221 stopDelegatedTasks: unused,
222 getThreadEventSequence: unused,
223 recoverDelegatedTask: unused,
224 delegatedTaskResultPending: unused,
225 streamStoredEvents: Stream.empty,
226 streamStoredEventsFrom: () => Stream.empty,
227 streamDomainEvents: options.domainEvents ?? Stream.empty,
228 });
229 const publications: Array<{
230 readonly url: string;
231 readonly authorization: string | null;
232 readonly state: RelayAgentActivityState | null;
233 }> = [];
234 const fetch: typeof globalThis.fetch = Object.assign(
235 (
236 input: Parameters<typeof globalThis.fetch>[0],
237 init?: Parameters<typeof globalThis.fetch>[1],
238 ) => {
239 const body = init?.body;
240 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
241 return Promise.reject(new Error("Expected a serialized activity publish payload"));
242 }
243 const payload = decodePublishPayload(
244 typeof body === "string" ? body : new TextDecoder().decode(body),
245 );
246 publications.push({
247 url: String(input),
248 authorization: new Headers(init?.headers).get("authorization"),
249 state: payload.state,
250 });
251 return Promise.resolve(
252 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
253 );
254 },
255 { preconnect: () => {} },
256 );
257 const relay = yield* AgentAwarenessRelay.make.pipe(
258 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
259 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
260 Effect.provideService(ServerEnvironment.ServerEnvironment, {
261 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
262 getDescriptor: unused(),
263 }),
264 Effect.provideService(ProjectService.ProjectService, {
265 create: unused,
266 bootstrap: unused,
267 update: unused,
268 delete: unused,
269 getByWorkspaceRoot: unused,
270 snapshot: Effect.succeed({ projects: [] } as never),
271 listPage: unused,
272 getShell: unused,
273 listShells: unused,
274 getById: () =>
275 Effect.succeedSome({
276 id: PROJECT_ID,
277 title: "Project",
278 workspaceRoot: "/workspace",
279 defaultModelSelection: null,
280 scripts: [],
281 createdAt: NOW,
282 updatedAt: NOW,
283 deletedAt: null,
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(
715 Effect.scoped,
716 Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
717 ),
718 );
719});