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

AgentAwarenessRelay.test.ts

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