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

AgentAwarenessRelay.test.ts

1,019 lines37.0 KB

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