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

AgentAwarenessRelay.test.ts

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