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

AgentAwarenessRelay.test.ts

938 lines34.7 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/unstable/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 ensureLegacyTranscript: unused,
194 dispatch: unused,
195 getTimelinePage: () => Effect.die("Unused timeline read"),
196 getMessageCount: () => Effect.die("unused message count"),
197 getThreadRecords: () => Effect.die("unused record read"),
198 getThreadProjection: unused,
199 getCheckpointContext: unused,
200 getThreadSnapshot: unused,
201 getThreadSnapshotWindow: unused,
202 getProjectThreadRecords: () => Effect.die("unused project record read"),
203 getProjectThread: unused,
204 listProjectThreads: unused,
205 sendToThread: unused,
206 waitForThread: unused,
207 interruptThread: unused,
208 getThreadEventSequence: unused,
209 streamStoredEvents: Stream.empty,
210 streamStoredEventsFrom: () => Stream.empty,
211 streamDomainEvents: options.domainEvents ?? Stream.empty,
212 });
213 const publications: Array<{
214 readonly url: string;
215 readonly authorization: string | null;
216 readonly state: RelayAgentActivityState | null;
217 }> = [];
218 const fetch: typeof globalThis.fetch = Object.assign(
219 (
220 input: Parameters<typeof globalThis.fetch>[0],
221 init?: Parameters<typeof globalThis.fetch>[1],
222 ) => {
223 const body = init?.body;
224 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
225 return Promise.reject(new Error("Expected a serialized activity publish payload"));
226 }
227 const payload = decodePublishPayload(
228 typeof body === "string" ? body : new TextDecoder().decode(body),
229 );
230 publications.push({
231 url: String(input),
232 authorization: new Headers(init?.headers).get("authorization"),
233 state: payload.state,
234 });
235 return Promise.resolve(
236 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
237 );
238 },
239 { preconnect: () => {} },
240 );
241 const relay = yield* AgentAwarenessRelay.make.pipe(
242 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
243 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
244 Effect.provideService(ServerEnvironment.ServerEnvironment, {
245 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
246 getDescriptor: unused(),
247 }),
248 Effect.provideService(ProjectService.ProjectService, {
249 create: unused,
250 bootstrap: unused,
251 update: unused,
252 delete: unused,
253 getByWorkspaceRoot: unused,
254 snapshot: Effect.succeed({ projects: [] } as never),
255 getShell: unused,
256 listShells: unused,
257 getById: () =>
258 Effect.succeed(
259 Option.some({
260 id: PROJECT_ID,
261 title: "Project",
262 workspaceRoot: "/workspace",
263 defaultModelSelection: null,
264 scripts: [],
265 createdAt: NOW,
266 updatedAt: NOW,
267 deletedAt: null,
268 }),
269 ),
270 }),
271 Effect.provideService(FetchHttpClient.Fetch, fetch),
272 Effect.provide(NodeCrypto.layer),
273 );
274 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
275});
276​
277describe("AgentAwarenessRelay", () => {
278 it("ignores transcript and tool updates but retains activity and metadata changes", () => {
279 for (const type of [
280 "message.updated",
281 "turn-item.updated",
282 "provider-turn.updated",
283 "thread.visited",
284 "thread.pinned",
285 ] as const) {
286 assert.isFalse(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));
287 }
288 for (const type of [
289 "run.created",
290 "run.updated",
291 "runtime-request.updated",
292 // Pending background work changes can release a held completion.
293 "subagent.updated",
294 "provider-thread.updated",
295 "thread.metadata-updated",
296 "thread.model-selection-updated",
297 "thread.provider-switched",
298 "thread.archived",
299 "thread.unarchived",
300 "thread.deleted",
301 ] as const) {
302 assert.isTrue(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));
303 }
304 });
305​
306 it("does not publish imported thread creation as new agent activity", () => {
307 assert.isFalse(
308 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
309 type: "thread.created",
310 payload: { historyOrigin: "v1_import" },
311 }),
312 );
313 assert.isTrue(
314 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type: "thread.created", payload: {} }),
315 );
316 });
317​
318 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
319 Effect.gen(function* () {
320 const started = yield* Deferred.make<void>();
321 const release = yield* Deferred.make<void>();
322 const rerunStarted = yield* Deferred.make<void>();
323 const releaseRerun = yield* Deferred.make<void>();
324 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
325 let revision = 1;
326 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
327 Effect.gen(function* () {
328 const currentRevision = revision;
329 const index = processed.length;
330 processed.push({ threadId, revision: currentRevision });
331 if (index === 0) {
332 yield* Deferred.succeed(started, undefined);
333 yield* Deferred.await(release);
334 } else if (threadId === THREAD_ID) {
335 yield* Deferred.succeed(rerunStarted, undefined);
336 yield* Deferred.await(releaseRerun);
337 }
338 }),
339 );
340 yield* worker.enqueue(THREAD_ID);
341 yield* Deferred.await(started);
342 revision = 2;
343 for (let i = 0; i < 100; i++) {
344 yield* worker.enqueue(SECOND_THREAD_ID);
345 yield* worker.enqueue(THREAD_ID);
346 }
347 const drained = yield* Deferred.make<void>();
348 const draining = yield* worker.drain.pipe(
349 Effect.andThen(Deferred.succeed(drained, undefined)),
350 Effect.forkChild,
351 );
352 yield* Deferred.succeed(release, undefined);
353 yield* Deferred.await(rerunStarted);
354 assert.isFalse(yield* Deferred.isDone(drained));
355 yield* Deferred.succeed(releaseRerun, undefined);
356 yield* Fiber.join(draining);
357 assert.deepEqual(processed, [
358 { threadId: THREAD_ID, revision: 1 },
359 { threadId: SECOND_THREAD_ID, revision: 2 },
360 { threadId: THREAD_ID, revision: 2 },
361 ]);
362 }),
363 );
364​
365 it.effect("deduplicates state and republishes title changes", () =>
366 Effect.gen(function* () {
367 const { relay, currentShell, publications } = yield* makeTestRelay();
368 yield* relay.publishThread(THREAD_ID);
369 yield* Ref.set(
370 currentShell,
371 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
372 );
373 yield* relay.publishThread(THREAD_ID);
374 assert.equal(publications.length, 1);
375 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
376 yield* relay.publishThread(THREAD_ID);
377 assert.equal(publications.length, 2);
378 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
379 }),
380 );
381​
382 it.effect("stops before shell reads when disabled and republishes after re-enabling", () =>
383 Effect.gen(function* () {
384 const { relay, secrets, secretReads, shellReads, publications } = yield* makeTestRelay();
385 yield* relay.publishThread(THREAD_ID);
386 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
387 const previousReads = secretReads.length;
388 yield* relay.publishThread(THREAD_ID);
389 assert.deepEqual(secretReads.slice(previousReads), [PUBLISH_AGENT_ACTIVITY_SECRET]);
390 assert.equal(shellReads.length, 1);
391 assert.equal(publications.length, 1);
392 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
393 yield* relay.publishThread(THREAD_ID);
394 assert.equal(publications.length, 2);
395 }),
396 );
397​
398 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
399 Effect.gen(function* () {
400 const { relay, secrets, publications } = yield* makeTestRelay();
401 yield* relay.publishThread(THREAD_ID);
402 yield* secrets.set(
403 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
404 new TextEncoder().encode("credential-2"),
405 );
406 yield* relay.publishThread(THREAD_ID);
407 assert.equal(publications.length, 2);
408 assert.equal(publications[0]?.authorization, "Bearer credential-1");
409 assert.equal(publications[1]?.authorization, "Bearer credential-2");
410 yield* secrets.set(
411 RELAY_URL_SECRET,
412 new TextEncoder().encode("https://new-relay.example.test"),
413 );
414 yield* relay.publishThread(THREAD_ID);
415 assert.equal(publications.length, 3);
416 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
417 }),
418 );
419​
420 it.effect("retries a failed final state without another thread event", () =>
421 Effect.gen(function* () {
422 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
423 respond: (attempt) =>
424 attempt === 2
425 ? new Response("relay unavailable", { status: 503 })
426 : Response.json({ ok: true, deliveries: [] }),
427 });
428 yield* relay.publishThread(THREAD_ID);
429 yield* Ref.set(
430 currentShell,
431 shell({
432 status: "completed",
433 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
434 }),
435 );
436 yield* relay.publishThread(THREAD_ID);
437 assert.equal(publications.length, 2);
438 yield* TestClock.adjust("1 second");
439 yield* relay.drain;
440 assert.equal(publications.length, 3);
441 assert.equal(publications[2]?.state?.phase, "completed");
442 yield* TestClock.adjust("1 minute");
443 yield* relay.drain;
444 assert.equal(shellReads.length, 3);
445 }),
446 );
447​
448 it.effect("retries the latest shell and credentials with first-completion confirmation", () =>
449 Effect.gen(function* () {
450 const { relay, secrets, currentShell, publications } = yield* makeTestRelay({
451 respond: (attempt) =>
452 attempt === 1
453 ? new Response("relay unavailable", { status: 503 })
454 : Response.json({ ok: true, deliveries: [] }),
455 });
456 yield* relay.publishThread(THREAD_ID);
457 yield* Ref.set(
458 currentShell,
459 shell({
460 status: "completed",
461 title: "Final title",
462 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
463 }),
464 );
465 yield* secrets.set(
466 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
467 new TextEncoder().encode("credential-2"),
468 );
469 yield* TestClock.adjust("1 second");
470 yield* relay.drain;
471 assert.equal(publications.length, 1);
472 yield* TestClock.adjust("5 seconds");
473 yield* relay.drain;
474 assert.equal(publications.length, 2);
475 assert.equal(publications[1]?.authorization, "Bearer credential-2");
476 assert.equal(publications[1]?.state?.phase, "completed");
477 assert.equal(publications[1]?.state?.threadTitle, "Final title");
478 }),
479 );
480​
481 it.effect("cancels a stale retry when a newer update publishes successfully", () =>
482 Effect.gen(function* () {
483 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
484 respond: (attempt) =>
485 attempt === 1
486 ? new Response("relay unavailable", { status: 503 })
487 : Response.json({ ok: true, deliveries: [] }),
488 });
489 yield* relay.publishThread(THREAD_ID);
490 yield* Ref.set(currentShell, shell({ title: "New title" }));
491 yield* relay.publishThread(THREAD_ID);
492 assert.equal(publications.length, 2);
493 assert.equal(publications[1]?.state?.threadTitle, "New title");
494 yield* TestClock.adjust("1 minute");
495 yield* relay.drain;
496 assert.equal(shellReads.length, 2);
497 }),
498 );
499​
500 it.effect.each(["disable", "unlink"] as const)(
501 "stops retries before shell reads after %s",
502 (change) =>
503 Effect.gen(function* () {
504 const { relay, secrets, shellReads, publications } = yield* makeTestRelay({
505 respond: () => new Response("relay unavailable", { status: 503 }),
506 });
507 yield* relay.publishThread(THREAD_ID);
508 if (change === "disable") {
509 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
510 } else {
511 yield* secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET);
512 }
513 yield* TestClock.adjust("1 second");
514 yield* relay.drain;
515 yield* TestClock.adjust("1 minute");
516 yield* relay.drain;
517 assert.equal(publications.length, 1);
518 assert.equal(shellReads.length, 1);
519 }),
520 );
521​
522 it.effect("recovers from a transient configuration read failure", () =>
523 Effect.gen(function* () {
524 let failRead = false;
525 const { relay, shellReads, publications } = yield* makeTestRelay({
526 failSecretRead: (name) => failRead && name === PUBLISH_AGENT_ACTIVITY_SECRET,
527 });
528 failRead = true;
529 yield* relay.publishThread(THREAD_ID);
530 assert.equal(shellReads.length, 0);
531 failRead = false;
532 yield* TestClock.adjust("1 second");
533 yield* relay.drain;
534 assert.equal(publications.length, 1);
535 assert.equal(publications[0]?.state?.phase, "running");
536 }),
537 );
538​
539 it.effect("bounds retry attempts and resets the budget for a newer update", () =>
540 Effect.gen(function* () {
541 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
542 respond: () => new Response("relay unavailable", { status: 503 }),
543 });
544 yield* relay.publishThread(THREAD_ID);
545 let attempts = 1;
546 for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) {
547 yield* TestClock.adjust(delay - 1);
548 yield* relay.drain;
549 assert.equal(publications.length, attempts);
550 yield* TestClock.adjust(1);
551 yield* relay.drain;
552 attempts += 1;
553 assert.equal(publications.length, attempts);
554 }
555 yield* TestClock.adjust("1 minute");
556 yield* relay.drain;
557 assert.equal(publications.length, 6);
558 assert.equal(shellReads.length, 6);
559 yield* Ref.set(currentShell, shell({ title: "New update" }));
560 yield* relay.publishThread(THREAD_ID);
561 yield* TestClock.adjust("1 second");
562 yield* relay.drain;
563 assert.equal(publications.length, 8);
564 assert.equal(publications[7]?.state?.threadTitle, "New update");
565 }),
566 );
567​
568 it.effect("retries a confirmed completion without restarting its confirmation window", () =>
569 Effect.gen(function* () {
570 const { relay, currentShell, publications } = yield* makeTestRelay({
571 respond: (attempt) =>
572 attempt <= 2
573 ? new Response("relay unavailable", { status: 503 })
574 : Response.json({ ok: true, deliveries: [] }),
575 });
576 yield* Ref.set(
577 currentShell,
578 shell({
579 status: "completed",
580 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
581 }),
582 );
583 yield* relay.publishThread(THREAD_ID);
584 yield* TestClock.adjust("5 seconds");
585 yield* relay.drain;
586 assert.equal(publications.length, 1);
587 yield* TestClock.adjust("1 second");
588 yield* relay.drain;
589 assert.equal(publications.length, 2);
590 yield* TestClock.adjust("2 seconds");
591 yield* relay.drain;
592 assert.equal(publications.length, 3);
593 assert.isTrue(publications.every((publication) => publication.state?.phase === "completed"));
594 yield* TestClock.adjust("1 minute");
595 yield* relay.drain;
596 assert.equal(publications.length, 3);
597 }),
598 );
599​
600 it.effect("does not reset an exhausted retry budget for old confirmation timers", () =>
601 Effect.gen(function* () {
602 let unavailable = false;
603 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
604 respond: () =>
605 unavailable
606 ? new Response("relay unavailable", { status: 503 })
607 : Response.json({ ok: true, deliveries: [] }),
608 });
609 yield* relay.publishThread(THREAD_ID);
610 // Leave six obsolete confirmations at 5,000 through 5,005 milliseconds.
611 for (let i = 0; i < 6; i++) {
612 yield* Ref.set(currentShell, null);
613 yield* relay.publishThread(THREAD_ID);
614 yield* Ref.set(currentShell, shell());
615 yield* relay.publishThread(THREAD_ID);
616 yield* TestClock.adjust(1);
617 }
618 unavailable = true;
619 yield* Ref.set(currentShell, shell({ status: "failed" }));
620 yield* relay.publishThread(THREAD_ID);
621 yield* TestClock.adjust(1_000);
622 yield* relay.drain;
623 yield* TestClock.adjust(2_000);
624 yield* relay.drain;
625 yield* TestClock.adjust(1_994);
626 yield* relay.drain;
627 for (let i = 0; i < 5; i++) {
628 yield* TestClock.adjust(1);
629 yield* relay.drain;
630 }
631 const attempts = publications.length;
632 const reads = shellReads.length;
633 yield* TestClock.adjust("1 minute");
634 yield* relay.drain;
635 assert.equal(publications.length, attempts);
636 assert.equal(shellReads.length, reads);
637 }),
638 );
639​
640 it.effect("confirms tombstones and cancels stale confirmations when activity recovers", () =>
641 Effect.gen(function* () {
642 const { relay, currentShell, publications } = yield* makeTestRelay();
643 yield* relay.publishThread(THREAD_ID);
644 yield* Ref.set(currentShell, null);
645 yield* relay.publishThread(THREAD_ID);
646 assert.equal(publications.length, 1);
647 yield* Ref.set(currentShell, shell());
648 yield* relay.publishThread(THREAD_ID);
649 yield* TestClock.adjust("5 seconds");
650 yield* relay.drain;
651 assert.equal(publications.length, 1);
652 yield* Ref.set(currentShell, null);
653 yield* relay.publishThread(THREAD_ID);
654 assert.equal(publications.length, 1);
655 yield* TestClock.adjust("5 seconds");
656 yield* relay.drain;
657 assert.equal(publications.length, 2);
658 assert.equal(publications[1]?.state, null);
659 }),
660 );
661​
662 it.effect.each([
663 { label: "live", archived: false },
664 { label: "archived", archived: true },
665 ])("never publishes tombstones for $label subagent threads", ({ archived }) =>
666 Effect.gen(function* () {
667 const { relay, currentShell, publications } = yield* makeTestRelay();
668 yield* Ref.set(
669 currentShell,
670 shell({
671 lineage: {
672 rootThreadId: THREAD_ID,
673 parentThreadId: THREAD_ID,
674 relationshipToParent: "subagent",
675 },
676 ...(archived ? { archivedAt: yield* DateTime.now } : {}),
677 }),
678 );
679 yield* relay.publishThread(THREAD_ID);
680 yield* TestClock.adjust("5 seconds");
681 yield* relay.drain;
682 assert.equal(publications.length, 0);
683 }),
684 );
685​
686 it.effect("confirms a first completed state and respects disabling during confirmation", () =>
687 Effect.gen(function* () {
688 const { relay, secrets, currentShell, publications } = yield* makeTestRelay();
689 yield* Ref.set(
690 currentShell,
691 shell({
692 status: "completed",
693 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
694 }),
695 );
696 yield* relay.publishThread(THREAD_ID);
697 assert.equal(publications.length, 0);
698 yield* TestClock.adjust("5 seconds");
699 yield* relay.drain;
700 assert.equal(publications[0]?.state?.phase, "completed");
701 yield* Ref.set(currentShell, null);
702 yield* relay.publishThread(THREAD_ID);
703 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
704 yield* TestClock.adjust("5 seconds");
705 yield* relay.drain;
706 assert.equal(publications.length, 1);
707 }),
708 );
709 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
710 Effect.gen(function* () {
711 const store = yield* ProjectionStore.ProjectionStoreV2;
712 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
713 // The relay pulls the next event only after it has handled the previous one.
714 const pulls = yield* Queue.unbounded<void>();
715 const { relay, shellReads, publications } = yield* makeTestRelay({
716 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
717 domainEvents: Stream.fromEffectRepeat(
718 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
719 ),
720 });
721 yield* relay.start();
722 yield* Queue.take(pulls);
723 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
724 yield* store.apply(event);
725 yield* Queue.offer(events, event);
726 yield* Queue.take(pulls);
727 yield* relay.drain;
728 });
729​
730 const now = yield* DateTime.now;
731 const runId = RunId.make("run:held-item");
732 const run = {
733 id: runId,
734 threadId: THREAD_ID,
735 ordinal: 1,
736 providerInstanceId: ProviderInstanceId.make("codex"),
737 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
738 providerThreadId: null,
739 userMessageId: MessageId.make("message:held-item"),
740 rootNodeId: null,
741 activeAttemptId: null,
742 status: "running" as const,
743 requestedAt: now,
744 startedAt: now,
745 completedAt: null,
746 checkpointId: null,
747 contextHandoffId: null,
748 };
749 const item = (
750 id: string,
751 fields: Pick<OrchestrationV2TurnItem, "status"> &
752 (
753 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
754 | {
755 readonly type: "assistant_message";
756 readonly messageId: MessageId;
757 readonly text: string;
758 readonly streaming: boolean;
759 }
760 ),
761 ): OrchestrationV2TurnItem => ({
762 id: TurnItemId.make(id),
763 threadId: THREAD_ID,
764 runId,
765 nodeId: NodeId.make("node:held-item"),
766 providerThreadId: null,
767 providerTurnId: null,
768 nativeItemRef: null,
769 parentItemId: null,
770 ordinal: 1,
771 title: null,
772 startedAt: now,
773 completedAt: null,
774 updatedAt: now,
775 ...fields,
776 });
777 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
778 ({
779 id: EventId.make(id),
780 type: "turn-item.updated",
781 threadId: THREAD_ID,
782 runId,
783 occurredAt: now,
784 payload,
785 }) satisfies OrchestrationV2DomainEvent;
786 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
787​
788 yield* deliver({
789 id: EventId.make("event:held-item:thread"),
790 type: "thread.created",
791 threadId: THREAD_ID,
792 occurredAt: now,
793 payload: {
794 createdBy: "user",
795 creationSource: "web",
796 id: THREAD_ID,
797 projectId: PROJECT_ID,
798 title: "Thread",
799 providerInstanceId: ProviderInstanceId.make("codex"),
800 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
801 runtimeMode: "full-access",
802 interactionMode: "default",
803 branch: null,
804 worktreePath: null,
805 activeProviderThreadId: null,
806 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
807 forkedFrom: null,
808 createdAt: now,
809 updatedAt: now,
810 archivedAt: null,
811 settledOverride: null,
812 settledAt: null,
813 lastVisitedAt: null,
814 deletedAt: null,
815 },
816 });
817 yield* deliver({
818 id: EventId.make("event:held-item:run"),
819 type: "run.created",
820 threadId: THREAD_ID,
821 runId,
822 occurredAt: now,
823 payload: run,
824 });
825 yield* deliver(
826 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
827 );
828 yield* deliver({
829 id: EventId.make("event:held-item:run-completed"),
830 type: "run.updated",
831 threadId: THREAD_ID,
832 runId,
833 occurredAt: now,
834 payload: { ...run, status: "completed", completedAt: now },
835 });
836 assert.deepEqual(
837 publications.map((publication) => publication.state?.phase),
838 ["running"],
839 );
840​
841 // Streaming output never reaches the shell read.
842 const readsBeforeOutput = shellReads.length;
843 yield* deliver(
844 itemEvent(
845 "event:held-item:reply",
846 item("item:reply", {
847 type: "assistant_message",
848 messageId: MessageId.make("message:held-item:reply"),
849 text: "Still watching",
850 streaming: true,
851 status: "running",
852 }),
853 ),
854 );
855 yield* deliver(
856 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
857 );
858 assert.equal(shellReads.length, readsBeforeOutput);
859​
860 yield* deliver(
861 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
862 );
863 assert.deepEqual(
864 publications.map((publication) => publication.state?.phase),
865 ["running", "completed"],
866 );
867 }).pipe(Effect.scoped, Effect.provide(ProjectionStore.layerMemory)),
868 );
869});
870​
871describe("startup catch-up", { concurrent: false }, () => {
872 const link = (secrets: ServerSecretStore.ServerSecretStore["Service"]) =>
873 Effect.all(
874 [
875 secrets.set(RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")),
876 secrets.set(RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")),
877 secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")),
878 ],
879 { discard: true },
880 );
881 const enablePublishing = (secrets: ServerSecretStore.ServerSecretStore["Service"]) =>
882 secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
883 const linkChecks = (secretReads: ReadonlyArray<string>) =>
884 secretReads.filter((name) => name === RELAY_URL_SECRET).length;
885​
886 it.effect("checks an unlinked environment once a minute and still catches up once linked", () =>
887 Effect.gen(function* () {
888 const { relay, secrets, secretReads, catchUp } = yield* makeTestRelay({ linked: false });
889 yield* enablePublishing(secrets);
890 yield* relay.start();
891​
892 // Get past the backoff ramp, then count checks in a steady window.
893 yield* TestClock.adjust("10 minutes");
894 const checksBeforeWindow = linkChecks(secretReads);
895 yield* TestClock.adjust("10 minutes");
896 assert.equal(linkChecks(secretReads) - checksBeforeWindow, 10);
897 assert.equal(catchUp.shellSnapshotReads, 0);
898​
899 yield* link(secrets);
900 yield* TestClock.adjust("1 minute");
901 assert.equal(catchUp.shellSnapshotReads, 1);
902 }).pipe(Effect.scoped),
903 );
904​
905 it.effect("publishes at once when this process links while the check is backed off", () =>
906 Effect.gen(function* () {
907 const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false });
908 yield* enablePublishing(secrets);
909 yield* relay.start();
910​
911 // Backed off to 60 s: the next check is still seconds away.
912 yield* TestClock.adjust("10 minutes");
913 yield* link(secrets);
914 yield* TestClock.adjust("1 second");
915 assert.equal(catchUp.shellSnapshotReads, 0);
916​
917 yield* relay.requestCatchUp();
918 yield* TestClock.adjust("1 second");
919 assert.equal(catchUp.shellSnapshotReads, 1);
920 }).pipe(Effect.scoped),
921 );
922​
923 it.effect("catches up within 5 s when another process enables publishing on a link", () =>
924 Effect.gen(function* () {
925 const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false });
926 yield* link(secrets);
927 yield* relay.start();
928​
929 yield* TestClock.adjust("10 minutes");
930 assert.equal(catchUp.shellSnapshotReads, 0);
931​
932 // `t3 connect publish` writes the opt-in without waking this process.
933 yield* enablePublishing(secrets);
934 yield* TestClock.adjust("5 seconds");
935 assert.equal(catchUp.shellSnapshotReads, 1);
936 }).pipe(Effect.scoped),
937 );
938});