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 RuntimeRequestId,
15 ThreadId,
16 TurnItemId,
17} from "@t3tools/contracts";
18import { RelayAgentActivityState } from "@t3tools/contracts/relay";
19import * as DateTime from "effect/DateTime";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as Fiber from "effect/Fiber";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Queue from "effect/Queue";
26import * as Ref from "effect/Ref";
27import * as Schema from "effect/Schema";
28import * as Stream from "effect/Stream";
29import * as TestClock from "effect/testing/TestClock";
30import * as FetchHttpClient from "effect/http/FetchHttpClient";
31
32import * as EnvironmentKeys from "../cloud/environmentKeys.ts";
33import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
34import {
35 PUBLISH_AGENT_ACTIVITY_SECRET,
36 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
37 RELAY_ISSUER_SECRET,
38 RELAY_URL_SECRET,
39} from "../cloud/config.ts";
40import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
41import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
42import * as SqlitePersistence from "../persistence/Sqlite.ts";
43import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
44import * as ProjectService from "../project/ProjectService.ts";
45import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";
46
47const THREAD_ID = ThreadId.make("relay-thread");
48const SECOND_THREAD_ID = ThreadId.make("relay-thread-2");
49const PROJECT_ID = ProjectId.make("relay-project");
50const NOW = "2026-09-04T12:00:00.000Z";
51
52function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
53 return {
54 id: THREAD_ID,
55 projectId: PROJECT_ID,
56 title: "Thread",
57 providerInstanceId: ProviderInstanceId.make("codex"),
58 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
59 runtimeMode: "full-access",
60 interactionMode: "default",
61 worktreePath: null,
62 activeProviderThreadId: null,
63 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
64 forkedFrom: null,
65 createdBy: "user",
66 creationSource: "web",
67 activeRunId: null,
68 latestVisibleMessage: null,
69 hasActionableProposedPlan: false,
70 itemCount: 0,
71 visibleItemCount: 0,
72 lastVisitedAt: null,
73 deletedAt: null,
74 branch: null,
75 linkedPullRequest: null,
76 status: "running",
77 activityRunStatus: null,
78 pendingRuntimeRequest: null,
79 pendingBackgroundTasks: [],
80 latestRunId: null,
81 latestRunRequestedAt: null,
82 latestRunStartedAt: null,
83 latestRunCompletedAt: null,
84 latestUserMessageAt: null,
85 createdAt: DateTime.makeUnsafe(NOW),
86 updatedAt: DateTime.makeUnsafe(NOW),
87 archivedAt: null,
88 settledOverride: null,
89 settledAt: null,
90 snoozedUntil: null,
91 snoozedAt: null,
92 pinnedAt: null,
93 ...overrides,
94 };
95}
96
97const CHILD_THREAD_ID = ThreadId.make("relay-child-thread");
98
99function waitingChild(
100 overrides: Partial<OrchestrationV2ThreadShell> = {},
101): OrchestrationV2ThreadShell {
102 return shell({
103 id: CHILD_THREAD_ID,
104 title: "Child",
105 lineage: {
106 rootThreadId: THREAD_ID,
107 parentThreadId: THREAD_ID,
108 relationshipToParent: "subagent",
109 },
110 createdBy: "agent",
111 creationSource: "mcp",
112 activityRunStatus: "running",
113 pendingRuntimeRequest: {
114 id: RuntimeRequestId.make("child-request"),
115 kind: "command",
116 createdAt: DateTime.makeUnsafe(NOW),
117 },
118 ...overrides,
119 });
120}
121
122const PublishPayload = Schema.Struct({ state: Schema.NullOr(RelayAgentActivityState) });
123const decodePublishPayload = Schema.decodeUnknownSync(Schema.fromJsonString(PublishPayload));
124const unused = () => Effect.die("Unexpected test dependency call");
125
126describe("startup agent activity", () => {
127 it("publishes active work and only terminal runs completed after startup", () => {
128 const startedAt = DateTime.toEpochMillis(DateTime.makeUnsafe(NOW));
129 const oldCompleted = ThreadId.make("old-completed");
130 const newCompleted = ThreadId.make("new-completed");
131 const oldFailed = ThreadId.make("old-failed");
132 const newFailed = ThreadId.make("new-failed");
133 const ids = AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
134 environmentId: EnvironmentId.make("relay-env"),
135 startedAt,
136 projects: [{ id: PROJECT_ID, title: "Project" }],
137 threads: [
138 shell(),
139 shell({
140 id: oldCompleted,
141 status: "completed",
142 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
143 }),
144 shell({
145 id: newCompleted,
146 status: "completed",
147 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
148 }),
149 shell({
150 id: oldFailed,
151 status: "failed",
152 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
153 }),
154 shell({
155 id: newFailed,
156 status: "failed",
157 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
158 }),
159 shell({ id: ThreadId.make("idle"), status: "idle" }),
160 shell({ id: ThreadId.make("missing-project"), projectId: ProjectId.make("missing") }),
161 ],
162 });
163 assert.deepStrictEqual(ids, [THREAD_ID, newCompleted, newFailed]);
164 });
165});
166
167const makeTestRelay = Effect.fnUntraced(function* (
168 options: {
169 readonly respond?: (attempt: number) => Response;
170 readonly failSecretRead?: (name: string) => boolean;
171 readonly linked?: boolean;
172 readonly readShell?: (threadId: ThreadId) => Effect.Effect<OrchestrationV2ThreadShell | null>;
173 readonly domainEvents?: Stream.Stream<OrchestrationV2DomainEvent>;
174 readonly catchUpThreads?: ReadonlyArray<OrchestrationV2ThreadShell>;
175 } = {},
176) {
177 const values = new Map<string, Uint8Array>(
178 options.linked === false
179 ? []
180 : [
181 [PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")],
182 [RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")],
183 [RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")],
184 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")],
185 ],
186 );
187 const secretReads: string[] = [];
188 const secrets = ServerSecretStore.ServerSecretStore.of({
189 get: (name) =>
190 Effect.suspend(() => {
191 secretReads.push(name);
192 if (options.failSecretRead?.(name)) {
193 return Effect.fail(
194 new ServerSecretStore.SecretStoreReadError({
195 resource: name,
196 cause: "temporary read failure",
197 }),
198 );
199 }
200 return Effect.succeed(Option.fromUndefinedOr(values.get(name)));
201 }),
202 create: (name, value) => Effect.sync(() => void values.set(name, value)),
203 set: (name, value) => Effect.sync(() => void values.set(name, value)),
204 remove: (name) => Effect.sync(() => void values.delete(name)),
205 getOrCreateRandom: unused,
206 });
207 const currentShell = yield* Ref.make<OrchestrationV2ThreadShell | null>(shell());
208 const shellReads: ThreadId[] = [];
209 const catchUp = { activitySnapshotReads: 0 };
210 const threads = ThreadManagementService.ThreadManagementService.of({
211 getThreadShell: unused,
212 getShellSnapshot: unused,
213 getAgentAwarenessSnapshot: (threadId) =>
214 threadId === undefined
215 ? Effect.sync(() => {
216 catchUp.activitySnapshotReads += 1;
217 return { snapshotSequence: 1, threads: options.catchUpThreads ?? [] };
218 })
219 : Effect.sync(() => shellReads.push(threadId)).pipe(
220 Effect.andThen(options.readShell?.(threadId) ?? Ref.get(currentShell)),
221 Effect.map((thread) => ({
222 snapshotSequence: 1,
223 threads: thread === null ? [] : [thread],
224 })),
225 ),
226 listActiveSubagentThreadIds: unused,
227 listAppOwnedChildThreadIds: unused,
228 countThreads: unused,
229 listActiveShellIndex: () => Effect.succeed([]),
230 listOlderSettledThreads: unused,
231 readShellSnapshot: unused,
232 getThreadTitles: unused,
233 getThreadLinkMetadata: unused,
234 ensureLegacyTranscript: unused,
235 dispatch: unused,
236 searchThread: () => Effect.die("unused"),
237 searchThreadStream: () => Stream.empty,
238 getThreadHistoryPage: () => Effect.die("unused"),
239 getTimelinePage: () => Effect.die("Unused timeline read"),
240 getMessageCount: () => Effect.die("unused message count"),
241 getTurnItem: () => Effect.die("unused turn item read"),
242 getThreadRecords: () => Effect.die("unused record read"),
243 getThreadProjection: unused,
244 getCheckpointContext: unused,
245 getThreadSnapshot: unused,
246 getThreadTranscript: unused,
247 getThreadSnapshotWindow: unused,
248 getProjectThreadRecords: () => Effect.die("unused project record read"),
249 listProjectThreads: unused,
250 sendToThread: unused,
251 assertProviderInstanceEnabled: unused,
252 isProviderInstanceEnabledForProject: unused,
253 hasReceipt: unused,
254 waitForThread: unused,
255 settleAfterRun: unused,
256 settleThread: unused,
257 interruptThread: unused,
258 stopWorkflow: () => Effect.die("unused stopWorkflow"),
259 forceStopThread: () => Effect.die("unused forceStopThread"),
260 awaitBackgroundTasks: unused,
261 stopDelegatedTasks: unused,
262 getThreadEventSequence: unused,
263 recoverDelegatedTask: unused,
264 cancelDelegatedTask: unused,
265 delegatedTaskResultPending: unused,
266 streamStoredEvents: Stream.empty,
267 streamStoredEventsFrom: () => Stream.empty,
268 streamDomainEvents: options.domainEvents ?? Stream.empty,
269 });
270 const publications: Array<{
271 readonly url: string;
272 readonly authorization: string | null;
273 readonly state: RelayAgentActivityState | null;
274 }> = [];
275 const fetch: typeof globalThis.fetch = Object.assign(
276 (
277 input: Parameters<typeof globalThis.fetch>[0],
278 init?: Parameters<typeof globalThis.fetch>[1],
279 ) => {
280 const body = init?.body;
281 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
282 return Promise.reject(new Error("Expected a serialized activity publish payload"));
283 }
284 const payload = decodePublishPayload(
285 typeof body === "string" ? body : new TextDecoder().decode(body),
286 );
287 publications.push({
288 url: String(input),
289 authorization: new Headers(init?.headers).get("authorization"),
290 state: payload.state,
291 });
292 return Promise.resolve(
293 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
294 );
295 },
296 { preconnect: () => {} },
297 );
298 const project = {
299 id: PROJECT_ID,
300 title: "Project",
301 workspaceRoot: "/workspace",
302 defaultModelSelection: null,
303 scripts: [],
304 createdAt: NOW,
305 updatedAt: NOW,
306 deletedAt: null,
307 };
308 const relay = yield* AgentAwarenessRelay.make.pipe(
309 Effect.provide(EnvironmentKeys.layer),
310 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
311 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
312 Effect.provideService(ServerEnvironment.ServerEnvironment, {
313 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
314 getDescriptor: unused(),
315 }),
316 Effect.provideService(ProjectService.ProjectService, {
317 create: unused,
318 bootstrap: unused,
319 update: unused,
320 delete: unused,
321 getByWorkspaceRoot: unused,
322 workspaceScanDirectory: unused,
323 snapshot: Effect.succeed({ projects: [project], updatedAt: NOW }),
324 listPage: unused,
325 getShell: unused,
326 listShells: unused,
327 getById: () => Effect.succeedSome(project),
328 }),
329 Effect.provideService(FetchHttpClient.Fetch, fetch),
330 Effect.provide(NodeCrypto.layer),
331 );
332 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
333});
334
335describe("AgentAwarenessRelay", () => {
336 it.effect("publishes the parent as needing approval while its subagent waits", () =>
337 Effect.gen(function* () {
338 const shells = yield* Ref.make(
339 new Map<ThreadId, OrchestrationV2ThreadShell>([
340 [THREAD_ID, shell({ status: "running" })],
341 [CHILD_THREAD_ID, waitingChild({ pendingRuntimeRequest: null })],
342 ]),
343 );
344 const setShell = (next: OrchestrationV2ThreadShell) =>
345 Ref.update(shells, (current) => new Map(current).set(next.id, next));
346 const { relay, publications } = yield* makeTestRelay({
347 readShell: (threadId) =>
348 Ref.get(shells).pipe(Effect.map((current) => current.get(threadId) ?? null)),
349 });
350 yield* relay.publishThread(THREAD_ID);
351 yield* setShell(shell({ status: "completed" }));
352 yield* setShell(waitingChild());
353 yield* relay.publishThread(CHILD_THREAD_ID);
354 assert.equal(publications.length, 2);
355 assert.isTrue(publications[1]?.url.includes(`/threads/${THREAD_ID}/`) ?? false);
356 assert.equal(publications[1]?.state?.phase, "waiting_for_approval");
357
358 // A rename keeps the same request's alert time, so the phone doesn't re-alert.
359 yield* setShell(
360 shell({
361 status: "completed",
362 title: "Renamed thread",
363 updatedAt: DateTime.makeUnsafe("2026-09-04T12:01:00.000Z"),
364 }),
365 );
366 yield* relay.publishThread(THREAD_ID);
367 assert.equal(publications.length, 3);
368 assert.equal(publications[2]?.state?.threadTitle, "Renamed thread");
369 assert.equal(publications[2]?.state?.updatedAt, publications[1]?.state?.updatedAt);
370
371 yield* setShell(waitingChild({ pendingRuntimeRequest: null }));
372 yield* relay.publishThread(CHILD_THREAD_ID);
373 yield* TestClock.adjust("5 seconds");
374 yield* relay.drain;
375 assert.equal(publications.length, 4);
376 assert.equal(publications[3]?.state?.phase, "completed");
377 }),
378 );
379
380 it.effect("republishes a completed parent for its waiting child after a relink", () =>
381 Effect.gen(function* () {
382 const parent = shell({ status: "completed" });
383 const child = waitingChild();
384 const { relay, secrets, publications } = yield* makeTestRelay({
385 catchUpThreads: [parent, child],
386 readShell: (id) => Effect.succeed(id === child.id ? child : parent),
387 });
388 yield* relay.start();
389 yield* TestClock.adjust("1 second");
390 yield* relay.drain;
391 assert.equal(publications.length, 1);
392 assert.equal(publications[0]?.state?.phase, "waiting_for_approval");
393
394 yield* secrets.set(
395 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
396 new TextEncoder().encode("credential-2"),
397 );
398 yield* relay.requestCatchUp();
399 yield* TestClock.adjust("1 second");
400 yield* relay.drain;
401 assert.equal(publications.length, 2);
402 assert.equal(publications[1]?.state?.phase, "waiting_for_approval");
403 }).pipe(Effect.scoped),
404 );
405
406 it.effect("keeps a child's alert time when the parent's own request comes and goes", () =>
407 Effect.gen(function* () {
408 const shells = yield* Ref.make(
409 new Map<ThreadId, OrchestrationV2ThreadShell>([
410 [THREAD_ID, shell()],
411 [CHILD_THREAD_ID, waitingChild()],
412 ]),
413 );
414 const setParent = (next: OrchestrationV2ThreadShell) =>
415 Ref.update(shells, (current) => new Map(current).set(THREAD_ID, next));
416 const { relay, publications } = yield* makeTestRelay({
417 readShell: (threadId) =>
418 Ref.get(shells).pipe(Effect.map((current) => current.get(threadId) ?? null)),
419 });
420 yield* relay.publishThread(CHILD_THREAD_ID);
421 yield* setParent(
422 shell({
423 updatedAt: DateTime.makeUnsafe("2026-09-04T12:01:00.000Z"),
424 pendingRuntimeRequest: {
425 id: RuntimeRequestId.make("parent-request"),
426 kind: "command",
427 createdAt: DateTime.makeUnsafe("2026-09-04T12:01:00.000Z"),
428 },
429 }),
430 );
431 yield* relay.publishThread(THREAD_ID);
432 yield* setParent(shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T12:02:00.000Z") }));
433 yield* relay.publishThread(THREAD_ID);
434 assert.deepStrictEqual(
435 publications.map(({ state }) => state?.phase),
436 ["waiting_for_approval", "waiting_for_approval", "waiting_for_approval"],
437 );
438 assert.equal(publications[2]?.state?.updatedAt, publications[0]?.state?.updatedAt);
439 }),
440 );
441
442 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
443 Effect.gen(function* () {
444 const started = yield* Deferred.make<void>();
445 const release = yield* Deferred.make<void>();
446 const rerunStarted = yield* Deferred.make<void>();
447 const releaseRerun = yield* Deferred.make<void>();
448 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
449 let revision = 1;
450 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
451 Effect.gen(function* () {
452 const currentRevision = revision;
453 const index = processed.length;
454 processed.push({ threadId, revision: currentRevision });
455 if (index === 0) {
456 yield* Deferred.succeed(started, undefined);
457 yield* Deferred.await(release);
458 } else if (threadId === THREAD_ID) {
459 yield* Deferred.succeed(rerunStarted, undefined);
460 yield* Deferred.await(releaseRerun);
461 }
462 }),
463 );
464 yield* worker.enqueue(THREAD_ID);
465 yield* Deferred.await(started);
466 revision = 2;
467 for (let i = 0; i < 100; i++) {
468 yield* worker.enqueue(SECOND_THREAD_ID);
469 yield* worker.enqueue(THREAD_ID);
470 }
471 const drained = yield* Deferred.make<void>();
472 const draining = yield* worker.drain.pipe(
473 Effect.andThen(Deferred.succeed(drained, undefined)),
474 Effect.forkChild,
475 );
476 yield* Deferred.succeed(release, undefined);
477 yield* Deferred.await(rerunStarted);
478 assert.isFalse(yield* Deferred.isDone(drained));
479 yield* Deferred.succeed(releaseRerun, undefined);
480 yield* Fiber.join(draining);
481 assert.deepEqual(processed, [
482 { threadId: THREAD_ID, revision: 1 },
483 { threadId: SECOND_THREAD_ID, revision: 2 },
484 { threadId: THREAD_ID, revision: 2 },
485 ]);
486 }),
487 );
488
489 it.effect("deduplicates state and republishes title changes", () =>
490 Effect.gen(function* () {
491 const { relay, currentShell, publications } = yield* makeTestRelay();
492 yield* relay.publishThread(THREAD_ID);
493 yield* Ref.set(
494 currentShell,
495 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
496 );
497 yield* relay.publishThread(THREAD_ID);
498 assert.equal(publications.length, 1);
499 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
500 yield* relay.publishThread(THREAD_ID);
501 assert.equal(publications.length, 2);
502 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
503 }),
504 );
505
506 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
507 Effect.gen(function* () {
508 const { relay, secrets, publications } = yield* makeTestRelay();
509 yield* relay.publishThread(THREAD_ID);
510 yield* secrets.set(
511 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
512 new TextEncoder().encode("credential-2"),
513 );
514 yield* relay.publishThread(THREAD_ID);
515 assert.equal(publications.length, 2);
516 assert.equal(publications[0]?.authorization, "Bearer credential-1");
517 assert.equal(publications[1]?.authorization, "Bearer credential-2");
518 yield* secrets.set(
519 RELAY_URL_SECRET,
520 new TextEncoder().encode("https://new-relay.example.test"),
521 );
522 yield* relay.publishThread(THREAD_ID);
523 assert.equal(publications.length, 3);
524 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
525 }),
526 );
527
528 it.effect.each(["completed", "failed"] as const)(
529 "publishes a tombstone when a %s thread is settled through a domain event",
530 (status) =>
531 Effect.gen(function* () {
532 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
533 const pulls = yield* Queue.unbounded<void>();
534 const { relay, currentShell, publications } = yield* makeTestRelay({
535 domainEvents: Stream.fromEffectRepeat(
536 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
537 ),
538 });
539 yield* relay.start();
540 yield* Queue.take(pulls);
541 yield* relay.publishThread(THREAD_ID);
542 const terminal = shell({ status });
543 yield* Ref.set(currentShell, terminal);
544 yield* relay.publishThread(THREAD_ID);
545 yield* TestClock.adjust("5 seconds");
546 yield* relay.drain;
547 assert.equal(publications[1]?.state?.phase, status);
548
549 const now = yield* DateTime.now;
550 const settled = {
551 ...terminal,
552 settledOverride: "settled" as const,
553 settledAt: now,
554 lastVisitedAt: null,
555 };
556 yield* Ref.set(currentShell, settled);
557 yield* Queue.offer(events, {
558 id: EventId.make("event:settled"),
559 type: "thread.settled",
560 threadId: THREAD_ID,
561 occurredAt: now,
562 payload: settled,
563 });
564 yield* Queue.take(pulls);
565 yield* relay.drain;
566 assert.equal(publications.length, 2);
567 yield* TestClock.adjust("5 seconds");
568 yield* relay.drain;
569 assert.equal(publications.length, 3);
570 assert.equal(publications[2]?.state, null);
571 }).pipe(Effect.scoped),
572 );
573
574 it.effect("holds a completion through a continuation gap, then publishes it once", () =>
575 Effect.gen(function* () {
576 const { relay, currentShell, publications } = yield* makeTestRelay();
577 yield* relay.publishThread(THREAD_ID);
578 yield* Ref.set(currentShell, shell({ status: "completed" }));
579 yield* relay.publishThread(THREAD_ID);
580 yield* Ref.set(currentShell, shell());
581 yield* relay.publishThread(THREAD_ID);
582 yield* TestClock.adjust("5 seconds");
583 yield* relay.drain;
584 assert.deepEqual(
585 publications.map((publication) => publication.state?.phase),
586 ["running"],
587 );
588
589 yield* Ref.set(currentShell, shell({ status: "completed" }));
590 yield* relay.publishThread(THREAD_ID);
591 assert.equal(publications.length, 1);
592 yield* TestClock.adjust("5 seconds");
593 yield* relay.drain;
594 assert.deepEqual(
595 publications.map((publication) => publication.state?.phase),
596 ["running", "completed"],
597 );
598 }),
599 );
600
601 it.effect("still publishes a completion when the thread settles during the hold", () =>
602 Effect.gen(function* () {
603 const { relay, currentShell, publications } = yield* makeTestRelay();
604 yield* relay.publishThread(THREAD_ID);
605 const completed = shell({ status: "completed" });
606 yield* Ref.set(currentShell, completed);
607 yield* relay.publishThread(THREAD_ID);
608 yield* Ref.set(currentShell, {
609 ...completed,
610 settledOverride: "settled",
611 settledAt: yield* DateTime.now,
612 lastVisitedAt: null,
613 });
614 yield* relay.publishThread(THREAD_ID);
615 yield* TestClock.adjust("5 seconds");
616 yield* relay.drain;
617 assert.deepEqual(
618 publications.map((publication) => publication.state?.phase ?? null),
619 ["running", "completed"],
620 );
621
622 yield* TestClock.adjust("5 seconds");
623 yield* relay.drain;
624 assert.deepEqual(
625 publications.map((publication) => publication.state?.phase ?? null),
626 ["running", "completed", null],
627 );
628 }),
629 );
630
631 it.effect("publishes a cleared thread's tombstone once while it stays cleared", () =>
632 Effect.gen(function* () {
633 const { relay, currentShell, publications } = yield* makeTestRelay();
634 yield* relay.publishThread(THREAD_ID);
635 const completed = shell({ status: "completed" });
636 yield* Ref.set(currentShell, completed);
637 yield* relay.publishThread(THREAD_ID);
638 yield* TestClock.adjust("5 seconds");
639 yield* relay.drain;
640 yield* Ref.set(currentShell, {
641 ...completed,
642 settledOverride: "settled",
643 settledAt: yield* DateTime.now,
644 lastVisitedAt: null,
645 });
646 yield* relay.publishThread(THREAD_ID);
647 yield* TestClock.adjust("5 seconds");
648 yield* relay.drain;
649 assert.deepEqual(
650 publications.map((publication) => publication.state?.phase ?? null),
651 ["running", "completed", null],
652 );
653
654 for (let i = 0; i < 3; i++) {
655 yield* relay.publishThread(THREAD_ID);
656 yield* TestClock.adjust("5 seconds");
657 yield* relay.drain;
658 }
659 assert.deepEqual(
660 publications.map((publication) => publication.state?.phase ?? null),
661 ["running", "completed", null],
662 );
663 }),
664 );
665
666 it.effect("does not alert an old completion after publishing its thread's tombstone", () =>
667 Effect.gen(function* () {
668 const oldCompleted = shell({
669 status: "completed",
670 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
671 });
672 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
673 const { relay, currentShell, publications } = yield* makeTestRelay();
674 yield* Ref.set(currentShell, {
675 ...oldCompleted,
676 settledOverride: "settled",
677 settledAt: DateTime.makeUnsafe(NOW),
678 lastVisitedAt: null,
679 });
680 yield* relay.publishThread(THREAD_ID);
681 yield* TestClock.adjust("5 seconds");
682 yield* relay.drain;
683 assert.deepEqual(
684 publications.map((publication) => publication.state),
685 [null],
686 );
687
688 yield* Ref.set(currentShell, oldCompleted);
689 yield* relay.publishThread(THREAD_ID);
690 yield* TestClock.adjust("5 seconds");
691 yield* relay.drain;
692 assert.deepEqual(
693 publications.map((publication) => publication.state),
694 [null],
695 );
696 }),
697 );
698
699 it.effect("alerts a completion settled during its hold after an earlier tombstone", () =>
700 Effect.gen(function* () {
701 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
702 const { relay, currentShell, publications } = yield* makeTestRelay();
703 const settledAt = DateTime.makeUnsafe(NOW);
704 yield* Ref.set(currentShell, {
705 ...shell({ status: "completed" }),
706 settledOverride: "settled",
707 settledAt,
708 lastVisitedAt: null,
709 });
710 yield* relay.publishThread(THREAD_ID);
711 yield* TestClock.adjust("5 seconds");
712 yield* relay.drain;
713
714 const completed = shell({
715 status: "completed",
716 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:06.000Z"),
717 });
718 yield* Ref.set(currentShell, completed);
719 yield* relay.publishThread(THREAD_ID);
720 yield* Ref.set(currentShell, {
721 ...completed,
722 settledOverride: "settled",
723 settledAt,
724 lastVisitedAt: null,
725 });
726 yield* relay.publishThread(THREAD_ID);
727 yield* TestClock.adjust("5 seconds");
728 yield* relay.drain;
729 yield* TestClock.adjust("5 seconds");
730 yield* relay.drain;
731 assert.deepEqual(
732 publications.map((publication) => publication.state?.phase ?? null),
733 [null, "completed", null],
734 );
735 }),
736 );
737
738 it.effect("drops a held completion when a queued continuation hides the thread", () =>
739 Effect.gen(function* () {
740 const { relay, currentShell, publications } = yield* makeTestRelay();
741 yield* relay.publishThread(THREAD_ID);
742 yield* Ref.set(currentShell, shell({ status: "completed" }));
743 yield* relay.publishThread(THREAD_ID);
744 yield* Ref.set(currentShell, shell({ status: "queued" }));
745 yield* relay.publishThread(THREAD_ID);
746 yield* TestClock.adjust("5 seconds");
747 yield* relay.drain;
748 assert.notInclude(
749 publications.map((publication) => publication.state?.phase ?? null),
750 "completed",
751 );
752 }),
753 );
754
755 it.effect("retries a failed completion even after the thread settles", () =>
756 Effect.gen(function* () {
757 const { relay, currentShell, publications } = yield* makeTestRelay({
758 respond: (attempt) =>
759 attempt === 2
760 ? new Response("unavailable", { status: 503 })
761 : Response.json({ ok: true, deliveries: [] }),
762 });
763 yield* relay.publishThread(THREAD_ID);
764 const completed = shell({ status: "completed" });
765 yield* Ref.set(currentShell, completed);
766 yield* relay.publishThread(THREAD_ID);
767 yield* TestClock.adjust("5 seconds");
768 yield* relay.drain;
769 yield* Ref.set(currentShell, {
770 ...completed,
771 settledOverride: "settled",
772 settledAt: yield* DateTime.now,
773 lastVisitedAt: null,
774 });
775 yield* TestClock.adjust("1 second");
776 yield* relay.drain;
777 assert.deepEqual(
778 publications.map((publication) => publication.state?.phase ?? null),
779 ["running", "completed", "completed"],
780 );
781
782 yield* TestClock.adjust("5 seconds");
783 yield* relay.drain;
784 assert.equal(publications.at(-1)?.state ?? null, null);
785 }),
786 );
787
788 it.effect("keeps settled live work until its awaited monitor finishes", () =>
789 Effect.gen(function* () {
790 const { relay, currentShell, publications } = yield* makeTestRelay();
791 yield* relay.publishThread(THREAD_ID);
792 const held = shell({
793 status: "completed",
794 settledOverride: "settled",
795 pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
796 });
797 yield* Ref.set(currentShell, held);
798 yield* relay.publishThread(THREAD_ID);
799 yield* TestClock.adjust("5 seconds");
800 yield* relay.drain;
801 assert.equal(publications.length, 1);
802 assert.equal(publications[0]?.state?.phase, "running");
803
804 yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
805 yield* relay.publishThread(THREAD_ID);
806 yield* TestClock.adjust("5 seconds");
807 yield* relay.drain;
808 assert.equal(publications.length, 2);
809 assert.equal(publications[1]?.state, null);
810 }),
811 );
812 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
813 Effect.gen(function* () {
814 const store = yield* ProjectionStore.ProjectionStoreV2;
815 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
816 const pulls = yield* Queue.unbounded<void>();
817 const { relay, shellReads, publications } = yield* makeTestRelay({
818 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
819 domainEvents: Stream.fromEffectRepeat(
820 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
821 ),
822 });
823 yield* relay.start();
824 yield* Queue.take(pulls);
825 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
826 yield* store.apply(event);
827 yield* Queue.offer(events, event);
828 yield* Queue.take(pulls);
829 yield* relay.drain;
830 });
831
832 const now = yield* DateTime.now;
833 const runId = RunId.make("run:held-item");
834 const run = {
835 id: runId,
836 threadId: THREAD_ID,
837 ordinal: 1,
838 providerInstanceId: ProviderInstanceId.make("codex"),
839 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
840 providerThreadId: null,
841 userMessageId: MessageId.make("message:held-item"),
842 rootNodeId: null,
843 activeAttemptId: null,
844 status: "running" as const,
845 requestedAt: now,
846 startedAt: now,
847 completedAt: null,
848 checkpointId: null,
849 contextHandoffId: null,
850 };
851 const item = (
852 id: string,
853 fields: Pick<OrchestrationV2TurnItem, "status"> &
854 (
855 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
856 | {
857 readonly type: "assistant_message";
858 readonly messageId: MessageId;
859 readonly text: string;
860 readonly streaming: boolean;
861 }
862 ),
863 ): OrchestrationV2TurnItem => ({
864 id: TurnItemId.make(id),
865 threadId: THREAD_ID,
866 runId,
867 nodeId: NodeId.make("node:held-item"),
868 providerThreadId: null,
869 providerTurnId: null,
870 nativeItemRef: null,
871 parentItemId: null,
872 ordinal: 1,
873 title: null,
874 startedAt: now,
875 completedAt: null,
876 updatedAt: now,
877 ...fields,
878 });
879 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
880 ({
881 id: EventId.make(id),
882 type: "turn-item.updated",
883 threadId: THREAD_ID,
884 runId,
885 occurredAt: now,
886 payload,
887 }) satisfies OrchestrationV2DomainEvent;
888 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
889
890 yield* deliver({
891 id: EventId.make("event:held-item:thread"),
892 type: "thread.created",
893 threadId: THREAD_ID,
894 occurredAt: now,
895 payload: {
896 createdBy: "user",
897 creationSource: "web",
898 id: THREAD_ID,
899 projectId: PROJECT_ID,
900 title: "Thread",
901 providerInstanceId: ProviderInstanceId.make("codex"),
902 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
903 runtimeMode: "full-access",
904 interactionMode: "default",
905 branch: null,
906 worktreePath: null,
907 activeProviderThreadId: null,
908 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
909 forkedFrom: null,
910 createdAt: now,
911 updatedAt: now,
912 archivedAt: null,
913 settledOverride: null,
914 settledAt: null,
915 lastVisitedAt: null,
916 deletedAt: null,
917 },
918 });
919 yield* deliver({
920 id: EventId.make("event:held-item:run"),
921 type: "run.created",
922 threadId: THREAD_ID,
923 runId,
924 occurredAt: now,
925 payload: run,
926 });
927 yield* deliver(
928 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
929 );
930 yield* deliver({
931 id: EventId.make("event:held-item:run-completed"),
932 type: "run.updated",
933 threadId: THREAD_ID,
934 runId,
935 occurredAt: now,
936 payload: { ...run, status: "completed", completedAt: now },
937 });
938 assert.deepEqual(
939 publications.map((publication) => publication.state?.phase),
940 ["running"],
941 );
942
943 const readsBeforeOutput = shellReads.length;
944 yield* deliver(
945 itemEvent(
946 "event:held-item:reply",
947 item("item:reply", {
948 type: "assistant_message",
949 messageId: MessageId.make("message:held-item:reply"),
950 text: "Still watching",
951 streaming: true,
952 status: "running",
953 }),
954 ),
955 );
956 yield* deliver(
957 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
958 );
959 assert.equal(shellReads.length, readsBeforeOutput);
960
961 yield* deliver(
962 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
963 );
964 yield* TestClock.adjust("5 seconds");
965 yield* relay.drain;
966 assert.deepEqual(
967 publications.map((publication) => publication.state?.phase),
968 ["running", "completed"],
969 );
970 }).pipe(
971 Effect.scoped,
972 Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
973 ),
974 );
975});
976
977it.effect("catches up after startup without polling after success", () =>
978 Effect.gen(function* () {
979 const { relay, secrets, secretReads, catchUp, publications } = yield* makeTestRelay({
980 catchUpThreads: [shell()],
981 });
982 yield* relay.start();
983 yield* TestClock.adjust("1 second");
984 yield* relay.drain;
985 assert.equal(catchUp.activitySnapshotReads, 1);
986 assert.equal(publications.length, 1);
987 assert.include(publications[0]?.state, {
988 threadId: THREAD_ID,
989 projectTitle: "Project",
990 threadTitle: "Thread",
991 phase: "running",
992 });
993
994 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
995 yield* relay.requestCatchUp();
996 yield* TestClock.adjust("1 second");
997 assert.equal(catchUp.activitySnapshotReads, 1);
998
999 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
1000 yield* relay.requestCatchUp();
1001 yield* TestClock.adjust("1 second");
1002 assert.equal(catchUp.activitySnapshotReads, 2);
1003
1004 const readsBeforeIdle = secretReads.length;
1005 yield* TestClock.adjust("10 minutes");
1006 assert.equal(catchUp.activitySnapshotReads, 2);
1007 assert.equal(secretReads.length, readsBeforeIdle);
1008
1009 yield* secrets.set(
1010 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
1011 new TextEncoder().encode("credential-2"),
1012 );
1013 yield* relay.requestCatchUp();
1014 yield* TestClock.adjust("1 second");
1015 yield* relay.drain;
1016 assert.equal(catchUp.activitySnapshotReads, 3);
1017 assert.equal(publications.length, 2);
1018 assert.equal(publications[1]?.state?.threadId, THREAD_ID);
1019 }).pipe(Effect.scoped),
1020);