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

AgentAwarenessRelay.test.ts

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