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