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

AgentAwarenessRelay.test.ts

861 lines31.1 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("publishes a cleared thread's tombstone once while it stays cleared", () =>
486 Effect.gen(function* () {
487 const { relay, currentShell, publications } = yield* makeTestRelay();
488 yield* relay.publishThread(THREAD_ID);
489 const completed = shell({ status: "completed" });
490 yield* Ref.set(currentShell, completed);
491 yield* relay.publishThread(THREAD_ID);
492 yield* TestClock.adjust("5 seconds");
493 yield* relay.drain;
494 yield* Ref.set(currentShell, {
495 ...completed,
496 settledOverride: "settled",
497 settledAt: yield* DateTime.now,
498 lastVisitedAt: null,
499 });
500 yield* relay.publishThread(THREAD_ID);
501 yield* TestClock.adjust("5 seconds");
502 yield* relay.drain;
503 assert.deepEqual(
504 publications.map((publication) => publication.state?.phase ?? null),
505 ["running", "completed", null],
506 );
507​
508 for (let i = 0; i < 3; i++) {
509 yield* relay.publishThread(THREAD_ID);
510 yield* TestClock.adjust("5 seconds");
511 yield* relay.drain;
512 }
513 assert.deepEqual(
514 publications.map((publication) => publication.state?.phase ?? null),
515 ["running", "completed", null],
516 );
517 }),
518 );
519​
520 it.effect("does not alert an old completion after publishing its thread's tombstone", () =>
521 Effect.gen(function* () {
522 const oldCompleted = shell({
523 status: "completed",
524 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
525 });
526 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
527 const { relay, currentShell, publications } = yield* makeTestRelay();
528 yield* Ref.set(currentShell, {
529 ...oldCompleted,
530 settledOverride: "settled",
531 settledAt: DateTime.makeUnsafe(NOW),
532 lastVisitedAt: null,
533 });
534 yield* relay.publishThread(THREAD_ID);
535 yield* TestClock.adjust("5 seconds");
536 yield* relay.drain;
537 assert.deepEqual(
538 publications.map((publication) => publication.state),
539 [null],
540 );
541​
542 yield* Ref.set(currentShell, oldCompleted);
543 yield* relay.publishThread(THREAD_ID);
544 yield* TestClock.adjust("5 seconds");
545 yield* relay.drain;
546 assert.deepEqual(
547 publications.map((publication) => publication.state),
548 [null],
549 );
550 }),
551 );
552​
553 it.effect("alerts a completion settled during its hold after an earlier tombstone", () =>
554 Effect.gen(function* () {
555 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
556 const { relay, currentShell, publications } = yield* makeTestRelay();
557 const settledAt = DateTime.makeUnsafe(NOW);
558 yield* Ref.set(currentShell, {
559 ...shell({ status: "completed" }),
560 settledOverride: "settled",
561 settledAt,
562 lastVisitedAt: null,
563 });
564 yield* relay.publishThread(THREAD_ID);
565 yield* TestClock.adjust("5 seconds");
566 yield* relay.drain;
567​
568 const completed = shell({
569 status: "completed",
570 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:06.000Z"),
571 });
572 yield* Ref.set(currentShell, completed);
573 yield* relay.publishThread(THREAD_ID);
574 yield* Ref.set(currentShell, {
575 ...completed,
576 settledOverride: "settled",
577 settledAt,
578 lastVisitedAt: null,
579 });
580 yield* relay.publishThread(THREAD_ID);
581 yield* TestClock.adjust("5 seconds");
582 yield* relay.drain;
583 yield* TestClock.adjust("5 seconds");
584 yield* relay.drain;
585 assert.deepEqual(
586 publications.map((publication) => publication.state?.phase ?? null),
587 [null, "completed", null],
588 );
589 }),
590 );
591​
592 it.effect("drops a held completion when a queued continuation hides the thread", () =>
593 Effect.gen(function* () {
594 const { relay, currentShell, publications } = yield* makeTestRelay();
595 yield* relay.publishThread(THREAD_ID);
596 yield* Ref.set(currentShell, shell({ status: "completed" }));
597 yield* relay.publishThread(THREAD_ID);
598 yield* Ref.set(currentShell, shell({ status: "queued" }));
599 yield* relay.publishThread(THREAD_ID);
600 yield* TestClock.adjust("5 seconds");
601 yield* relay.drain;
602 assert.notInclude(
603 publications.map((publication) => publication.state?.phase ?? null),
604 "completed",
605 );
606 }),
607 );
608​
609 it.effect("retries a failed completion even after the thread settles", () =>
610 Effect.gen(function* () {
611 const { relay, currentShell, publications } = yield* makeTestRelay({
612 respond: (attempt) =>
613 attempt === 2
614 ? new Response("unavailable", { status: 503 })
615 : Response.json({ ok: true, deliveries: [] }),
616 });
617 yield* relay.publishThread(THREAD_ID);
618 const completed = shell({ status: "completed" });
619 yield* Ref.set(currentShell, completed);
620 yield* relay.publishThread(THREAD_ID);
621 yield* TestClock.adjust("5 seconds");
622 yield* relay.drain;
623 yield* Ref.set(currentShell, {
624 ...completed,
625 settledOverride: "settled",
626 settledAt: yield* DateTime.now,
627 lastVisitedAt: null,
628 });
629 yield* TestClock.adjust("1 second");
630 yield* relay.drain;
631 assert.deepEqual(
632 publications.map((publication) => publication.state?.phase ?? null),
633 ["running", "completed", "completed"],
634 );
635​
636 yield* TestClock.adjust("5 seconds");
637 yield* relay.drain;
638 assert.equal(publications.at(-1)?.state ?? null, null);
639 }),
640 );
641​
642 it.effect("keeps settled live work until its awaited monitor finishes", () =>
643 Effect.gen(function* () {
644 const { relay, currentShell, publications } = yield* makeTestRelay();
645 yield* relay.publishThread(THREAD_ID);
646 const held = shell({
647 status: "completed",
648 settledOverride: "settled",
649 pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
650 });
651 yield* Ref.set(currentShell, held);
652 yield* relay.publishThread(THREAD_ID);
653 yield* TestClock.adjust("5 seconds");
654 yield* relay.drain;
655 assert.equal(publications.length, 1);
656 assert.equal(publications[0]?.state?.phase, "running");
657​
658 yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
659 yield* relay.publishThread(THREAD_ID);
660 yield* TestClock.adjust("5 seconds");
661 yield* relay.drain;
662 assert.equal(publications.length, 2);
663 assert.equal(publications[1]?.state, null);
664 }),
665 );
666 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
667 Effect.gen(function* () {
668 const store = yield* ProjectionStore.ProjectionStoreV2;
669 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
670 const pulls = yield* Queue.unbounded<void>();
671 const { relay, shellReads, publications } = yield* makeTestRelay({
672 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
673 domainEvents: Stream.fromEffectRepeat(
674 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
675 ),
676 });
677 yield* relay.start();
678 yield* Queue.take(pulls);
679 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
680 yield* store.apply(event);
681 yield* Queue.offer(events, event);
682 yield* Queue.take(pulls);
683 yield* relay.drain;
684 });
685​
686 const now = yield* DateTime.now;
687 const runId = RunId.make("run:held-item");
688 const run = {
689 id: runId,
690 threadId: THREAD_ID,
691 ordinal: 1,
692 providerInstanceId: ProviderInstanceId.make("codex"),
693 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
694 providerThreadId: null,
695 userMessageId: MessageId.make("message:held-item"),
696 rootNodeId: null,
697 activeAttemptId: null,
698 status: "running" as const,
699 requestedAt: now,
700 startedAt: now,
701 completedAt: null,
702 checkpointId: null,
703 contextHandoffId: null,
704 };
705 const item = (
706 id: string,
707 fields: Pick<OrchestrationV2TurnItem, "status"> &
708 (
709 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
710 | {
711 readonly type: "assistant_message";
712 readonly messageId: MessageId;
713 readonly text: string;
714 readonly streaming: boolean;
715 }
716 ),
717 ): OrchestrationV2TurnItem => ({
718 id: TurnItemId.make(id),
719 threadId: THREAD_ID,
720 runId,
721 nodeId: NodeId.make("node:held-item"),
722 providerThreadId: null,
723 providerTurnId: null,
724 nativeItemRef: null,
725 parentItemId: null,
726 ordinal: 1,
727 title: null,
728 startedAt: now,
729 completedAt: null,
730 updatedAt: now,
731 ...fields,
732 });
733 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
734 ({
735 id: EventId.make(id),
736 type: "turn-item.updated",
737 threadId: THREAD_ID,
738 runId,
739 occurredAt: now,
740 payload,
741 }) satisfies OrchestrationV2DomainEvent;
742 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
743​
744 yield* deliver({
745 id: EventId.make("event:held-item:thread"),
746 type: "thread.created",
747 threadId: THREAD_ID,
748 occurredAt: now,
749 payload: {
750 createdBy: "user",
751 creationSource: "web",
752 id: THREAD_ID,
753 projectId: PROJECT_ID,
754 title: "Thread",
755 providerInstanceId: ProviderInstanceId.make("codex"),
756 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
757 runtimeMode: "full-access",
758 interactionMode: "default",
759 branch: null,
760 worktreePath: null,
761 activeProviderThreadId: null,
762 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
763 forkedFrom: null,
764 createdAt: now,
765 updatedAt: now,
766 archivedAt: null,
767 settledOverride: null,
768 settledAt: null,
769 lastVisitedAt: null,
770 deletedAt: null,
771 },
772 });
773 yield* deliver({
774 id: EventId.make("event:held-item:run"),
775 type: "run.created",
776 threadId: THREAD_ID,
777 runId,
778 occurredAt: now,
779 payload: run,
780 });
781 yield* deliver(
782 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
783 );
784 yield* deliver({
785 id: EventId.make("event:held-item:run-completed"),
786 type: "run.updated",
787 threadId: THREAD_ID,
788 runId,
789 occurredAt: now,
790 payload: { ...run, status: "completed", completedAt: now },
791 });
792 assert.deepEqual(
793 publications.map((publication) => publication.state?.phase),
794 ["running"],
795 );
796​
797 const readsBeforeOutput = shellReads.length;
798 yield* deliver(
799 itemEvent(
800 "event:held-item:reply",
801 item("item:reply", {
802 type: "assistant_message",
803 messageId: MessageId.make("message:held-item:reply"),
804 text: "Still watching",
805 streaming: true,
806 status: "running",
807 }),
808 ),
809 );
810 yield* deliver(
811 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
812 );
813 assert.equal(shellReads.length, readsBeforeOutput);
814​
815 yield* deliver(
816 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
817 );
818 yield* TestClock.adjust("5 seconds");
819 yield* relay.drain;
820 assert.deepEqual(
821 publications.map((publication) => publication.state?.phase),
822 ["running", "completed"],
823 );
824 }).pipe(
825 Effect.scoped,
826 Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
827 ),
828 );
829});
830​
831it.effect("catches up after startup without polling after success", () =>
832 Effect.gen(function* () {
833 const { relay, secrets, secretReads, catchUp } = yield* makeTestRelay();
834 yield* relay.start();
835 yield* TestClock.adjust("1 second");
836 assert.equal(catchUp.shellSnapshotReads, 1);
837​
838 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
839 yield* relay.requestCatchUp();
840 yield* TestClock.adjust("1 second");
841 assert.equal(catchUp.shellSnapshotReads, 1);
842​
843 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
844 yield* relay.requestCatchUp();
845 yield* TestClock.adjust("1 second");
846 assert.equal(catchUp.shellSnapshotReads, 2);
847​
848 const readsBeforeIdle = secretReads.length;
849 yield* TestClock.adjust("10 minutes");
850 assert.equal(catchUp.shellSnapshotReads, 2);
851 assert.equal(secretReads.length, readsBeforeIdle);
852​
853 yield* secrets.set(
854 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
855 new TextEncoder().encode("credential-2"),
856 );
857 yield* relay.requestCatchUp();
858 yield* TestClock.adjust("1 second");
859 assert.equal(catchUp.shellSnapshotReads, 3);
860 }).pipe(Effect.scoped),
861);