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

AgentAwarenessRelay.test.ts

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