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

AgentAwarenessRelay.test.ts

914 lines33.9 KB

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