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