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

AgentAwarenessRelay.test.ts

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