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 delegatedTaskResultPending: unused,
265 streamStoredEvents: Stream.empty,
266 streamStoredEventsFrom: () => Stream.empty,
267 streamDomainEvents: options.domainEvents ?? Stream.empty,
268 });
269 const publications: Array<{
270 readonly url: string;
271 readonly authorization: string | null;
272 readonly state: RelayAgentActivityState | null;
273 }> = [];
274 const fetch: typeof globalThis.fetch = Object.assign(
275 (
276 input: Parameters<typeof globalThis.fetch>[0],
277 init?: Parameters<typeof globalThis.fetch>[1],
278 ) => {
279 const body = init?.body;
280 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
281 return Promise.reject(new Error("Expected a serialized activity publish payload"));
282 }
283 const payload = decodePublishPayload(
284 typeof body === "string" ? body : new TextDecoder().decode(body),
285 );
286 publications.push({
287 url: String(input),
288 authorization: new Headers(init?.headers).get("authorization"),
289 state: payload.state,
290 });
291 return Promise.resolve(
292 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
293 );
294 },
295 { preconnect: () => {} },
296 );
297 const project = {
298 id: PROJECT_ID,
299 title: "Project",
300 workspaceRoot: "/workspace",
301 defaultModelSelection: null,
302 scripts: [],
303 createdAt: NOW,
304 updatedAt: NOW,
305 deletedAt: null,
306 };
307 const relay = yield* AgentAwarenessRelay.make.pipe(
308 Effect.provide(EnvironmentKeys.layer),
309 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
310 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
311 Effect.provideService(ServerEnvironment.ServerEnvironment, {
312 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
313 getDescriptor: unused(),
314 }),
315 Effect.provideService(ProjectService.ProjectService, {
316 create: unused,
317 bootstrap: unused,
318 update: unused,
319 delete: unused,
320 getByWorkspaceRoot: unused,
321 snapshot: Effect.succeed({ projects: [project], updatedAt: NOW }),
322 listPage: unused,
323 getShell: unused,
324 listShells: unused,
325 getById: () => Effect.succeedSome(project),
326 }),
327 Effect.provideService(FetchHttpClient.Fetch, fetch),
328 Effect.provide(NodeCrypto.layer),
329 );
330 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
331});
332
333describe("AgentAwarenessRelay", () => {
334 it.effect("publishes the parent as needing approval while its subagent waits", () =>
335 Effect.gen(function* () {
336 const shells = yield* Ref.make(
337 new Map<ThreadId, OrchestrationV2ThreadShell>([
338 [THREAD_ID, shell({ status: "running" })],
339 [CHILD_THREAD_ID, waitingChild({ pendingRuntimeRequest: null })],
340 ]),
341 );
342 const setShell = (next: OrchestrationV2ThreadShell) =>
343 Ref.update(shells, (current) => new Map(current).set(next.id, next));
344 const { relay, publications } = yield* makeTestRelay({
345 readShell: (threadId) =>
346 Ref.get(shells).pipe(Effect.map((current) => current.get(threadId) ?? null)),
347 });
348 yield* relay.publishThread(THREAD_ID);
349 yield* setShell(shell({ status: "completed" }));
350 yield* setShell(waitingChild());
351 yield* relay.publishThread(CHILD_THREAD_ID);
352 assert.equal(publications.length, 2);
353 assert.isTrue(publications[1]?.url.includes(`/threads/${THREAD_ID}/`) ?? false);
354 assert.equal(publications[1]?.state?.phase, "waiting_for_approval");
355
356 // A rename keeps the same request's alert time, so the phone doesn't re-alert.
357 yield* setShell(
358 shell({
359 status: "completed",
360 title: "Renamed thread",
361 updatedAt: DateTime.makeUnsafe("2026-09-04T12:01:00.000Z"),
362 }),
363 );
364 yield* relay.publishThread(THREAD_ID);
365 assert.equal(publications.length, 3);
366 assert.equal(publications[2]?.state?.threadTitle, "Renamed thread");
367 assert.equal(publications[2]?.state?.updatedAt, publications[1]?.state?.updatedAt);
368
369 yield* setShell(waitingChild({ pendingRuntimeRequest: null }));
370 yield* relay.publishThread(CHILD_THREAD_ID);
371 yield* TestClock.adjust("5 seconds");
372 yield* relay.drain;
373 assert.equal(publications.length, 4);
374 assert.equal(publications[3]?.state?.phase, "completed");
375 }),
376 );
377
378 it.effect("republishes a completed parent for its waiting child after a relink", () =>
379 Effect.gen(function* () {
380 const parent = shell({ status: "completed" });
381 const child = waitingChild();
382 const { relay, secrets, publications } = yield* makeTestRelay({
383 catchUpThreads: [parent, child],
384 readShell: (id) => Effect.succeed(id === child.id ? child : parent),
385 });
386 yield* relay.start();
387 yield* TestClock.adjust("1 second");
388 yield* relay.drain;
389 assert.equal(publications.length, 1);
390 assert.equal(publications[0]?.state?.phase, "waiting_for_approval");
391
392 yield* secrets.set(
393 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
394 new TextEncoder().encode("credential-2"),
395 );
396 yield* relay.requestCatchUp();
397 yield* TestClock.adjust("1 second");
398 yield* relay.drain;
399 assert.equal(publications.length, 2);
400 assert.equal(publications[1]?.state?.phase, "waiting_for_approval");
401 }).pipe(Effect.scoped),
402 );
403
404 it.effect("keeps a child's alert time when the parent's own request comes and goes", () =>
405 Effect.gen(function* () {
406 const shells = yield* Ref.make(
407 new Map<ThreadId, OrchestrationV2ThreadShell>([
408 [THREAD_ID, shell()],
409 [CHILD_THREAD_ID, waitingChild()],
410 ]),
411 );
412 const setParent = (next: OrchestrationV2ThreadShell) =>
413 Ref.update(shells, (current) => new Map(current).set(THREAD_ID, next));
414 const { relay, publications } = yield* makeTestRelay({
415 readShell: (threadId) =>
416 Ref.get(shells).pipe(Effect.map((current) => current.get(threadId) ?? null)),
417 });
418 yield* relay.publishThread(CHILD_THREAD_ID);
419 yield* setParent(
420 shell({
421 updatedAt: DateTime.makeUnsafe("2026-09-04T12:01:00.000Z"),
422 pendingRuntimeRequest: {
423 id: RuntimeRequestId.make("parent-request"),
424 kind: "command",
425 createdAt: DateTime.makeUnsafe("2026-09-04T12:01:00.000Z"),
426 },
427 }),
428 );
429 yield* relay.publishThread(THREAD_ID);
430 yield* setParent(shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T12:02:00.000Z") }));
431 yield* relay.publishThread(THREAD_ID);
432 assert.deepStrictEqual(
433 publications.map(({ state }) => state?.phase),
434 ["waiting_for_approval", "waiting_for_approval", "waiting_for_approval"],
435 );
436 assert.equal(publications[2]?.state?.updatedAt, publications[0]?.state?.updatedAt);
437 }),
438 );
439
440 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
441 Effect.gen(function* () {
442 const started = yield* Deferred.make<void>();
443 const release = yield* Deferred.make<void>();
444 const rerunStarted = yield* Deferred.make<void>();
445 const releaseRerun = yield* Deferred.make<void>();
446 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
447 let revision = 1;
448 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
449 Effect.gen(function* () {
450 const currentRevision = revision;
451 const index = processed.length;
452 processed.push({ threadId, revision: currentRevision });
453 if (index === 0) {
454 yield* Deferred.succeed(started, undefined);
455 yield* Deferred.await(release);
456 } else if (threadId === THREAD_ID) {
457 yield* Deferred.succeed(rerunStarted, undefined);
458 yield* Deferred.await(releaseRerun);
459 }
460 }),
461 );
462 yield* worker.enqueue(THREAD_ID);
463 yield* Deferred.await(started);
464 revision = 2;
465 for (let i = 0; i < 100; i++) {
466 yield* worker.enqueue(SECOND_THREAD_ID);
467 yield* worker.enqueue(THREAD_ID);
468 }
469 const drained = yield* Deferred.make<void>();
470 const draining = yield* worker.drain.pipe(
471 Effect.andThen(Deferred.succeed(drained, undefined)),
472 Effect.forkChild,
473 );
474 yield* Deferred.succeed(release, undefined);
475 yield* Deferred.await(rerunStarted);
476 assert.isFalse(yield* Deferred.isDone(drained));
477 yield* Deferred.succeed(releaseRerun, undefined);
478 yield* Fiber.join(draining);
479 assert.deepEqual(processed, [
480 { threadId: THREAD_ID, revision: 1 },
481 { threadId: SECOND_THREAD_ID, revision: 2 },
482 { threadId: THREAD_ID, revision: 2 },
483 ]);
484 }),
485 );
486
487 it.effect("deduplicates state and republishes title changes", () =>
488 Effect.gen(function* () {
489 const { relay, currentShell, publications } = yield* makeTestRelay();
490 yield* relay.publishThread(THREAD_ID);
491 yield* Ref.set(
492 currentShell,
493 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
494 );
495 yield* relay.publishThread(THREAD_ID);
496 assert.equal(publications.length, 1);
497 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
498 yield* relay.publishThread(THREAD_ID);
499 assert.equal(publications.length, 2);
500 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
501 }),
502 );
503
504 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
505 Effect.gen(function* () {
506 const { relay, secrets, publications } = yield* makeTestRelay();
507 yield* relay.publishThread(THREAD_ID);
508 yield* secrets.set(
509 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
510 new TextEncoder().encode("credential-2"),
511 );
512 yield* relay.publishThread(THREAD_ID);
513 assert.equal(publications.length, 2);
514 assert.equal(publications[0]?.authorization, "Bearer credential-1");
515 assert.equal(publications[1]?.authorization, "Bearer credential-2");
516 yield* secrets.set(
517 RELAY_URL_SECRET,
518 new TextEncoder().encode("https://new-relay.example.test"),
519 );
520 yield* relay.publishThread(THREAD_ID);
521 assert.equal(publications.length, 3);
522 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
523 }),
524 );
525
526 it.effect.each(["completed", "failed"] as const)(
527 "publishes a tombstone when a %s thread is settled through a domain event",
528 (status) =>
529 Effect.gen(function* () {
530 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
531 const pulls = yield* Queue.unbounded<void>();
532 const { relay, currentShell, publications } = yield* makeTestRelay({
533 domainEvents: Stream.fromEffectRepeat(
534 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
535 ),
536 });
537 yield* relay.start();
538 yield* Queue.take(pulls);
539 yield* relay.publishThread(THREAD_ID);
540 const terminal = shell({ status });
541 yield* Ref.set(currentShell, terminal);
542 yield* relay.publishThread(THREAD_ID);
543 yield* TestClock.adjust("5 seconds");
544 yield* relay.drain;
545 assert.equal(publications[1]?.state?.phase, status);
546
547 const now = yield* DateTime.now;
548 const settled = {
549 ...terminal,
550 settledOverride: "settled" as const,
551 settledAt: now,
552 lastVisitedAt: null,
553 };
554 yield* Ref.set(currentShell, settled);
555 yield* Queue.offer(events, {
556 id: EventId.make("event:settled"),
557 type: "thread.settled",
558 threadId: THREAD_ID,
559 occurredAt: now,
560 payload: settled,
561 });
562 yield* Queue.take(pulls);
563 yield* relay.drain;
564 assert.equal(publications.length, 2);
565 yield* TestClock.adjust("5 seconds");
566 yield* relay.drain;
567 assert.equal(publications.length, 3);
568 assert.equal(publications[2]?.state, null);
569 }).pipe(Effect.scoped),
570 );
571
572 it.effect("holds a completion through a continuation gap, then publishes it once", () =>
573 Effect.gen(function* () {
574 const { relay, currentShell, publications } = yield* makeTestRelay();
575 yield* relay.publishThread(THREAD_ID);
576 yield* Ref.set(currentShell, shell({ status: "completed" }));
577 yield* relay.publishThread(THREAD_ID);
578 yield* Ref.set(currentShell, shell());
579 yield* relay.publishThread(THREAD_ID);
580 yield* TestClock.adjust("5 seconds");
581 yield* relay.drain;
582 assert.deepEqual(
583 publications.map((publication) => publication.state?.phase),
584 ["running"],
585 );
586
587 yield* Ref.set(currentShell, shell({ status: "completed" }));
588 yield* relay.publishThread(THREAD_ID);
589 assert.equal(publications.length, 1);
590 yield* TestClock.adjust("5 seconds");
591 yield* relay.drain;
592 assert.deepEqual(
593 publications.map((publication) => publication.state?.phase),
594 ["running", "completed"],
595 );
596 }),
597 );
598
599 it.effect("still publishes a completion when the thread settles during the hold", () =>
600 Effect.gen(function* () {
601 const { relay, currentShell, publications } = yield* makeTestRelay();
602 yield* relay.publishThread(THREAD_ID);
603 const completed = shell({ status: "completed" });
604 yield* Ref.set(currentShell, completed);
605 yield* relay.publishThread(THREAD_ID);
606 yield* Ref.set(currentShell, {
607 ...completed,
608 settledOverride: "settled",
609 settledAt: yield* DateTime.now,
610 lastVisitedAt: null,
611 });
612 yield* relay.publishThread(THREAD_ID);
613 yield* TestClock.adjust("5 seconds");
614 yield* relay.drain;
615 assert.deepEqual(
616 publications.map((publication) => publication.state?.phase ?? null),
617 ["running", "completed"],
618 );
619
620 yield* TestClock.adjust("5 seconds");
621 yield* relay.drain;
622 assert.deepEqual(
623 publications.map((publication) => publication.state?.phase ?? null),
624 ["running", "completed", null],
625 );
626 }),
627 );
628
629 it.effect("publishes a cleared thread's tombstone once while it stays cleared", () =>
630 Effect.gen(function* () {
631 const { relay, currentShell, publications } = yield* makeTestRelay();
632 yield* relay.publishThread(THREAD_ID);
633 const completed = shell({ status: "completed" });
634 yield* Ref.set(currentShell, completed);
635 yield* relay.publishThread(THREAD_ID);
636 yield* TestClock.adjust("5 seconds");
637 yield* relay.drain;
638 yield* Ref.set(currentShell, {
639 ...completed,
640 settledOverride: "settled",
641 settledAt: yield* DateTime.now,
642 lastVisitedAt: null,
643 });
644 yield* relay.publishThread(THREAD_ID);
645 yield* TestClock.adjust("5 seconds");
646 yield* relay.drain;
647 assert.deepEqual(
648 publications.map((publication) => publication.state?.phase ?? null),
649 ["running", "completed", null],
650 );
651
652 for (let i = 0; i < 3; i++) {
653 yield* relay.publishThread(THREAD_ID);
654 yield* TestClock.adjust("5 seconds");
655 yield* relay.drain;
656 }
657 assert.deepEqual(
658 publications.map((publication) => publication.state?.phase ?? null),
659 ["running", "completed", null],
660 );
661 }),
662 );
663
664 it.effect("does not alert an old completion after publishing its thread's tombstone", () =>
665 Effect.gen(function* () {
666 const oldCompleted = shell({
667 status: "completed",
668 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
669 });
670 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
671 const { relay, currentShell, publications } = yield* makeTestRelay();
672 yield* Ref.set(currentShell, {
673 ...oldCompleted,
674 settledOverride: "settled",
675 settledAt: DateTime.makeUnsafe(NOW),
676 lastVisitedAt: null,
677 });
678 yield* relay.publishThread(THREAD_ID);
679 yield* TestClock.adjust("5 seconds");
680 yield* relay.drain;
681 assert.deepEqual(
682 publications.map((publication) => publication.state),
683 [null],
684 );
685
686 yield* Ref.set(currentShell, oldCompleted);
687 yield* relay.publishThread(THREAD_ID);
688 yield* TestClock.adjust("5 seconds");
689 yield* relay.drain;
690 assert.deepEqual(
691 publications.map((publication) => publication.state),
692 [null],
693 );
694 }),
695 );
696
697 it.effect("alerts a completion settled during its hold after an earlier tombstone", () =>
698 Effect.gen(function* () {
699 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
700 const { relay, currentShell, publications } = yield* makeTestRelay();
701 const settledAt = DateTime.makeUnsafe(NOW);
702 yield* Ref.set(currentShell, {
703 ...shell({ status: "completed" }),
704 settledOverride: "settled",
705 settledAt,
706 lastVisitedAt: null,
707 });
708 yield* relay.publishThread(THREAD_ID);
709 yield* TestClock.adjust("5 seconds");
710 yield* relay.drain;
711
712 const completed = shell({
713 status: "completed",
714 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:06.000Z"),
715 });
716 yield* Ref.set(currentShell, completed);
717 yield* relay.publishThread(THREAD_ID);
718 yield* Ref.set(currentShell, {
719 ...completed,
720 settledOverride: "settled",
721 settledAt,
722 lastVisitedAt: null,
723 });
724 yield* relay.publishThread(THREAD_ID);
725 yield* TestClock.adjust("5 seconds");
726 yield* relay.drain;
727 yield* TestClock.adjust("5 seconds");
728 yield* relay.drain;
729 assert.deepEqual(
730 publications.map((publication) => publication.state?.phase ?? null),
731 [null, "completed", null],
732 );
733 }),
734 );
735
736 it.effect("drops a held completion when a queued continuation hides the thread", () =>
737 Effect.gen(function* () {
738 const { relay, currentShell, publications } = yield* makeTestRelay();
739 yield* relay.publishThread(THREAD_ID);
740 yield* Ref.set(currentShell, shell({ status: "completed" }));
741 yield* relay.publishThread(THREAD_ID);
742 yield* Ref.set(currentShell, shell({ status: "queued" }));
743 yield* relay.publishThread(THREAD_ID);
744 yield* TestClock.adjust("5 seconds");
745 yield* relay.drain;
746 assert.notInclude(
747 publications.map((publication) => publication.state?.phase ?? null),
748 "completed",
749 );
750 }),
751 );
752
753 it.effect("retries a failed completion even after the thread settles", () =>
754 Effect.gen(function* () {
755 const { relay, currentShell, publications } = yield* makeTestRelay({
756 respond: (attempt) =>
757 attempt === 2
758 ? new Response("unavailable", { status: 503 })
759 : Response.json({ ok: true, deliveries: [] }),
760 });
761 yield* relay.publishThread(THREAD_ID);
762 const completed = shell({ status: "completed" });
763 yield* Ref.set(currentShell, completed);
764 yield* relay.publishThread(THREAD_ID);
765 yield* TestClock.adjust("5 seconds");
766 yield* relay.drain;
767 yield* Ref.set(currentShell, {
768 ...completed,
769 settledOverride: "settled",
770 settledAt: yield* DateTime.now,
771 lastVisitedAt: null,
772 });
773 yield* TestClock.adjust("1 second");
774 yield* relay.drain;
775 assert.deepEqual(
776 publications.map((publication) => publication.state?.phase ?? null),
777 ["running", "completed", "completed"],
778 );
779
780 yield* TestClock.adjust("5 seconds");
781 yield* relay.drain;
782 assert.equal(publications.at(-1)?.state ?? null, null);
783 }),
784 );
785
786 it.effect("keeps settled live work until its awaited monitor finishes", () =>
787 Effect.gen(function* () {
788 const { relay, currentShell, publications } = yield* makeTestRelay();
789 yield* relay.publishThread(THREAD_ID);
790 const held = shell({
791 status: "completed",
792 settledOverride: "settled",
793 pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
794 });
795 yield* Ref.set(currentShell, held);
796 yield* relay.publishThread(THREAD_ID);
797 yield* TestClock.adjust("5 seconds");
798 yield* relay.drain;
799 assert.equal(publications.length, 1);
800 assert.equal(publications[0]?.state?.phase, "running");
801
802 yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
803 yield* relay.publishThread(THREAD_ID);
804 yield* TestClock.adjust("5 seconds");
805 yield* relay.drain;
806 assert.equal(publications.length, 2);
807 assert.equal(publications[1]?.state, null);
808 }),
809 );
810 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
811 Effect.gen(function* () {
812 const store = yield* ProjectionStore.ProjectionStoreV2;
813 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
814 const pulls = yield* Queue.unbounded<void>();
815 const { relay, shellReads, publications } = yield* makeTestRelay({
816 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
817 domainEvents: Stream.fromEffectRepeat(
818 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
819 ),
820 });
821 yield* relay.start();
822 yield* Queue.take(pulls);
823 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
824 yield* store.apply(event);
825 yield* Queue.offer(events, event);
826 yield* Queue.take(pulls);
827 yield* relay.drain;
828 });
829
830 const now = yield* DateTime.now;
831 const runId = RunId.make("run:held-item");
832 const run = {
833 id: runId,
834 threadId: THREAD_ID,
835 ordinal: 1,
836 providerInstanceId: ProviderInstanceId.make("codex"),
837 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
838 providerThreadId: null,
839 userMessageId: MessageId.make("message:held-item"),
840 rootNodeId: null,
841 activeAttemptId: null,
842 status: "running" as const,
843 requestedAt: now,
844 startedAt: now,
845 completedAt: null,
846 checkpointId: null,
847 contextHandoffId: null,
848 };
849 const item = (
850 id: string,
851 fields: Pick<OrchestrationV2TurnItem, "status"> &
852 (
853 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
854 | {
855 readonly type: "assistant_message";
856 readonly messageId: MessageId;
857 readonly text: string;
858 readonly streaming: boolean;
859 }
860 ),
861 ): OrchestrationV2TurnItem => ({
862 id: TurnItemId.make(id),
863 threadId: THREAD_ID,
864 runId,
865 nodeId: NodeId.make("node:held-item"),
866 providerThreadId: null,
867 providerTurnId: null,
868 nativeItemRef: null,
869 parentItemId: null,
870 ordinal: 1,
871 title: null,
872 startedAt: now,
873 completedAt: null,
874 updatedAt: now,
875 ...fields,
876 });
877 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
878 ({
879 id: EventId.make(id),
880 type: "turn-item.updated",
881 threadId: THREAD_ID,
882 runId,
883 occurredAt: now,
884 payload,
885 }) satisfies OrchestrationV2DomainEvent;
886 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
887
888 yield* deliver({
889 id: EventId.make("event:held-item:thread"),
890 type: "thread.created",
891 threadId: THREAD_ID,
892 occurredAt: now,
893 payload: {
894 createdBy: "user",
895 creationSource: "web",
896 id: THREAD_ID,
897 projectId: PROJECT_ID,
898 title: "Thread",
899 providerInstanceId: ProviderInstanceId.make("codex"),
900 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
901 runtimeMode: "full-access",
902 interactionMode: "default",
903 branch: null,
904 worktreePath: null,
905 activeProviderThreadId: null,
906 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
907 forkedFrom: null,
908 createdAt: now,
909 updatedAt: now,
910 archivedAt: null,
911 settledOverride: null,
912 settledAt: null,
913 lastVisitedAt: null,
914 deletedAt: null,
915 },
916 });
917 yield* deliver({
918 id: EventId.make("event:held-item:run"),
919 type: "run.created",
920 threadId: THREAD_ID,
921 runId,
922 occurredAt: now,
923 payload: run,
924 });
925 yield* deliver(
926 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
927 );
928 yield* deliver({
929 id: EventId.make("event:held-item:run-completed"),
930 type: "run.updated",
931 threadId: THREAD_ID,
932 runId,
933 occurredAt: now,
934 payload: { ...run, status: "completed", completedAt: now },
935 });
936 assert.deepEqual(
937 publications.map((publication) => publication.state?.phase),
938 ["running"],
939 );
940
941 const readsBeforeOutput = shellReads.length;
942 yield* deliver(
943 itemEvent(
944 "event:held-item:reply",
945 item("item:reply", {
946 type: "assistant_message",
947 messageId: MessageId.make("message:held-item:reply"),
948 text: "Still watching",
949 streaming: true,
950 status: "running",
951 }),
952 ),
953 );
954 yield* deliver(
955 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
956 );
957 assert.equal(shellReads.length, readsBeforeOutput);
958
959 yield* deliver(
960 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
961 );
962 yield* TestClock.adjust("5 seconds");
963 yield* relay.drain;
964 assert.deepEqual(
965 publications.map((publication) => publication.state?.phase),
966 ["running", "completed"],
967 );
968 }).pipe(
969 Effect.scoped,
970 Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
971 ),
972 );
973});
974
975it.effect("catches up after startup without polling after success", () =>
976 Effect.gen(function* () {
977 const { relay, secrets, secretReads, catchUp, publications } = yield* makeTestRelay({
978 catchUpThreads: [shell()],
979 });
980 yield* relay.start();
981 yield* TestClock.adjust("1 second");
982 yield* relay.drain;
983 assert.equal(catchUp.activitySnapshotReads, 1);
984 assert.equal(publications.length, 1);
985 assert.include(publications[0]?.state, {
986 threadId: THREAD_ID,
987 projectTitle: "Project",
988 threadTitle: "Thread",
989 phase: "running",
990 });
991
992 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
993 yield* relay.requestCatchUp();
994 yield* TestClock.adjust("1 second");
995 assert.equal(catchUp.activitySnapshotReads, 1);
996
997 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
998 yield* relay.requestCatchUp();
999 yield* TestClock.adjust("1 second");
1000 assert.equal(catchUp.activitySnapshotReads, 2);
1001
1002 const readsBeforeIdle = secretReads.length;
1003 yield* TestClock.adjust("10 minutes");
1004 assert.equal(catchUp.activitySnapshotReads, 2);
1005 assert.equal(secretReads.length, readsBeforeIdle);
1006
1007 yield* secrets.set(
1008 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
1009 new TextEncoder().encode("credential-2"),
1010 );
1011 yield* relay.requestCatchUp();
1012 yield* TestClock.adjust("1 second");
1013 yield* relay.drain;
1014 assert.equal(catchUp.activitySnapshotReads, 3);
1015 assert.equal(publications.length, 2);
1016 assert.equal(publications[1]?.state?.threadId, THREAD_ID);
1017 }).pipe(Effect.scoped),
1018);