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