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