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

AgentAwarenessRelay.test.ts

996 lines36.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/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 readonly linked?: boolean;
143 readonly readShell?: (threadId: ThreadId) => Effect.Effect<OrchestrationV2ThreadShell | null>;
144 readonly domainEvents?: Stream.Stream<OrchestrationV2DomainEvent>;
145 } = {},
146) {
147 const values = new Map<string, Uint8Array>(
148 options.linked === false
149 ? []
150 : [
151 [PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")],
152 [RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")],
153 [RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")],
154 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")],
155 ],
156 );
157 const secretReads: string[] = [];
158 const secrets = ServerSecretStore.ServerSecretStore.of({
159 get: (name) =>
160 Effect.suspend(() => {
161 secretReads.push(name);
162 if (options.failSecretRead?.(name)) {
163 return Effect.fail(
164 new ServerSecretStore.SecretStoreReadError({
165 resource: name,
166 cause: "temporary read failure",
167 }),
168 );
169 }
170 return Effect.succeed(Option.fromUndefinedOr(values.get(name)));
171 }),
172 create: (name, value) => Effect.sync(() => void values.set(name, value)),
173 set: (name, value) => Effect.sync(() => void values.set(name, value)),
174 remove: (name) => Effect.sync(() => void values.delete(name)),
175 getOrCreateRandom: unused,
176 });
177 const currentShell = yield* Ref.make<OrchestrationV2ThreadShell | null>(shell());
178 const shellReads: ThreadId[] = [];
179 const catchUp = { shellSnapshotReads: 0 };
180 const threads = ThreadManagementService.ThreadManagementService.of({
181 getThreadShell: (threadId) =>
182 Effect.sync(() => shellReads.push(threadId)).pipe(
183 Effect.andThen(options.readShell?.(threadId) ?? Ref.get(currentShell)),
184 ),
185 getShellSnapshot: () =>
186 Effect.sync(() => {
187 catchUp.shellSnapshotReads += 1;
188 return { schemaVersion: 2, snapshotSequence: 1, threads: [], archivedThreads: [] };
189 }),
190 readShellSnapshot: unused,
191 ensureLegacyTranscript: unused,
192 dispatch: unused,
193 searchThread: () => Effect.die("unused"),
194 searchThreadStream: () => Stream.empty,
195 getThreadHistoryPage: () => Effect.die("unused"),
196 getTimelinePage: () => Effect.die("Unused timeline read"),
197 getMessageCount: () => Effect.die("unused message count"),
198 getTurnItem: () => Effect.die("unused turn item read"),
199 getThreadRecords: () => Effect.die("unused record read"),
200 getThreadProjection: unused,
201 getCheckpointContext: unused,
202 getThreadSnapshot: unused,
203 getThreadTranscript: unused,
204 getThreadSnapshotWindow: unused,
205 getProjectThreadRecords: () => Effect.die("unused project record read"),
206 getProjectThread: unused,
207 listProjectThreads: unused,
208 sendToThread: unused,
209 assertProviderInstanceEnabled: unused,
210 isProviderInstanceEnabledForProject: unused,
211 hasReceipt: unused,
212 waitForThread: unused,
213 settleAfterRun: unused,
214 settleThread: unused,
215 interruptThread: unused,
216 stopWorkflow: () => Effect.die("unused stopWorkflow"),
217 stopDelegatedTasks: unused,
218 getThreadEventSequence: unused,
219 recoverDelegatedTask: unused,
220 delegatedTaskResultPending: unused,
221 streamStoredEvents: Stream.empty,
222 streamStoredEventsFrom: () => Stream.empty,
223 streamDomainEvents: options.domainEvents ?? Stream.empty,
224 });
225 const publications: Array<{
226 readonly url: string;
227 readonly authorization: string | null;
228 readonly state: RelayAgentActivityState | null;
229 }> = [];
230 const fetch: typeof globalThis.fetch = Object.assign(
231 (
232 input: Parameters<typeof globalThis.fetch>[0],
233 init?: Parameters<typeof globalThis.fetch>[1],
234 ) => {
235 const body = init?.body;
236 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
237 return Promise.reject(new Error("Expected a serialized activity publish payload"));
238 }
239 const payload = decodePublishPayload(
240 typeof body === "string" ? body : new TextDecoder().decode(body),
241 );
242 publications.push({
243 url: String(input),
244 authorization: new Headers(init?.headers).get("authorization"),
245 state: payload.state,
246 });
247 return Promise.resolve(
248 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
249 );
250 },
251 { preconnect: () => {} },
252 );
253 const relay = yield* AgentAwarenessRelay.make.pipe(
254 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
255 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
256 Effect.provideService(ServerEnvironment.ServerEnvironment, {
257 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
258 getDescriptor: unused(),
259 }),
260 Effect.provideService(ProjectService.ProjectService, {
261 create: unused,
262 bootstrap: unused,
263 update: unused,
264 delete: unused,
265 getByWorkspaceRoot: unused,
266 snapshot: Effect.succeed({ projects: [] } as never),
267 getShell: unused,
268 listShells: unused,
269 getById: () =>
270 Effect.succeed(
271 Option.some({
272 id: PROJECT_ID,
273 title: "Project",
274 workspaceRoot: "/workspace",
275 defaultModelSelection: null,
276 scripts: [],
277 createdAt: NOW,
278 updatedAt: NOW,
279 deletedAt: null,
280 }),
281 ),
282 }),
283 Effect.provideService(FetchHttpClient.Fetch, fetch),
284 Effect.provide(NodeCrypto.layer),
285 );
286 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
287});
288​
289describe("AgentAwarenessRelay", () => {
290 it("ignores transcript and tool updates but retains activity and metadata changes", () => {
291 for (const type of [
292 "message.updated",
293 "turn-item.updated",
294 "provider-turn.updated",
295 "thread.visited",
296 "thread.pinned",
297 ] as const) {
298 assert.isFalse(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));
299 }
300 for (const type of [
301 "run.created",
302 "run.updated",
303 "runtime-request.updated",
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("a stalled response body releases later threads and uses bounded retries", () =>
432 Effect.gen(function* () {
433 const bodyStarted = Promise.withResolvers<void>();
434 const secondRead = yield* Deferred.make<void>();
435 const currentShell = yield* Ref.make(shell());
436 const { relay, publications } = yield* makeTestRelay({
437 readShell: (threadId) =>
438 threadId === SECOND_THREAD_ID
439 ? Deferred.succeed(secondRead, undefined).pipe(
440 Effect.as(shell({ id: SECOND_THREAD_ID })),
441 )
442 : Ref.get(currentShell),
443 respond: (attempt) => {
444 if (attempt !== 1) return new Response("relay unavailable", { status: 503 });
445 const response = new Response(null, {
446 headers: { "content-type": "application/json" },
447 });
448 return Object.assign(response, {
449 arrayBuffer: () => {
450 bodyStarted.resolve();
451 return new Promise<ArrayBuffer>(() => {});
452 },
453 });
454 },
455 });
456 const first = yield* relay.publishThread(THREAD_ID).pipe(Effect.forkChild);
457 yield* Effect.promise(() => bodyStarted.promise);
458 const second = yield* relay.publishThread(SECOND_THREAD_ID).pipe(Effect.forkChild);
459 yield* TestClock.adjust("9999 millis");
460 assert.equal(publications.length, 1);
461 yield* Ref.set(currentShell, shell({ title: "Latest title" }));
462 yield* TestClock.adjust("1 millis");
463 assert.isTrue(yield* Deferred.isDone(secondRead));
464 yield* Fiber.join(first);
465 yield* Fiber.join(second);
466 assert.equal(publications.length, 2);
467 assert.isTrue(publications[1]?.url.includes(SECOND_THREAD_ID) ?? false);
468 for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) {
469 const attempts = publications.length;
470 yield* TestClock.adjust(delay - 1);
471 yield* relay.drain;
472 assert.equal(publications.length, attempts);
473 yield* TestClock.adjust(1);
474 yield* relay.drain;
475 assert.equal(publications.length, attempts + 2);
476 assert.equal(publications[attempts]?.state?.threadTitle, "Latest title");
477 }
478 yield* TestClock.adjust("1 minute");
479 yield* relay.drain;
480 assert.equal(publications.length, 12);
481 }),
482 );
483​
484 it.effect("retries a failed final state without another thread event", () =>
485 Effect.gen(function* () {
486 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
487 respond: (attempt) =>
488 attempt === 2
489 ? new Response("relay unavailable", { status: 503 })
490 : Response.json({ ok: true, deliveries: [] }),
491 });
492 yield* relay.publishThread(THREAD_ID);
493 yield* Ref.set(
494 currentShell,
495 shell({
496 status: "completed",
497 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
498 }),
499 );
500 yield* relay.publishThread(THREAD_ID);
501 assert.equal(publications.length, 2);
502 yield* TestClock.adjust("1 second");
503 yield* relay.drain;
504 assert.equal(publications.length, 3);
505 assert.equal(publications[2]?.state?.phase, "completed");
506 yield* TestClock.adjust("1 minute");
507 yield* relay.drain;
508 assert.equal(shellReads.length, 3);
509 }),
510 );
511​
512 it.effect("retries the latest shell and credentials with first-completion confirmation", () =>
513 Effect.gen(function* () {
514 const { relay, secrets, currentShell, publications } = yield* makeTestRelay({
515 respond: (attempt) =>
516 attempt === 1
517 ? new Response("relay unavailable", { status: 503 })
518 : Response.json({ ok: true, deliveries: [] }),
519 });
520 yield* relay.publishThread(THREAD_ID);
521 yield* Ref.set(
522 currentShell,
523 shell({
524 status: "completed",
525 title: "Final title",
526 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
527 }),
528 );
529 yield* secrets.set(
530 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
531 new TextEncoder().encode("credential-2"),
532 );
533 yield* TestClock.adjust("1 second");
534 yield* relay.drain;
535 assert.equal(publications.length, 1);
536 yield* TestClock.adjust("5 seconds");
537 yield* relay.drain;
538 assert.equal(publications.length, 2);
539 assert.equal(publications[1]?.authorization, "Bearer credential-2");
540 assert.equal(publications[1]?.state?.phase, "completed");
541 assert.equal(publications[1]?.state?.threadTitle, "Final title");
542 }),
543 );
544​
545 it.effect("cancels a stale retry when a newer update publishes successfully", () =>
546 Effect.gen(function* () {
547 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
548 respond: (attempt) =>
549 attempt === 1
550 ? new Response("relay unavailable", { status: 503 })
551 : Response.json({ ok: true, deliveries: [] }),
552 });
553 yield* relay.publishThread(THREAD_ID);
554 yield* Ref.set(currentShell, shell({ title: "New title" }));
555 yield* relay.publishThread(THREAD_ID);
556 assert.equal(publications.length, 2);
557 assert.equal(publications[1]?.state?.threadTitle, "New title");
558 yield* TestClock.adjust("1 minute");
559 yield* relay.drain;
560 assert.equal(shellReads.length, 2);
561 }),
562 );
563​
564 it.effect.each(["disable", "unlink"] as const)(
565 "stops retries before shell reads after %s",
566 (change) =>
567 Effect.gen(function* () {
568 const { relay, secrets, shellReads, publications } = yield* makeTestRelay({
569 respond: () => new Response("relay unavailable", { status: 503 }),
570 });
571 yield* relay.publishThread(THREAD_ID);
572 if (change === "disable") {
573 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
574 } else {
575 yield* secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET);
576 }
577 yield* TestClock.adjust("1 second");
578 yield* relay.drain;
579 yield* TestClock.adjust("1 minute");
580 yield* relay.drain;
581 assert.equal(publications.length, 1);
582 assert.equal(shellReads.length, 1);
583 }),
584 );
585​
586 it.effect("recovers from a transient configuration read failure", () =>
587 Effect.gen(function* () {
588 let failRead = false;
589 const { relay, shellReads, publications } = yield* makeTestRelay({
590 failSecretRead: (name) => failRead && name === PUBLISH_AGENT_ACTIVITY_SECRET,
591 });
592 failRead = true;
593 yield* relay.publishThread(THREAD_ID);
594 assert.equal(shellReads.length, 0);
595 failRead = false;
596 yield* TestClock.adjust("1 second");
597 yield* relay.drain;
598 assert.equal(publications.length, 1);
599 assert.equal(publications[0]?.state?.phase, "running");
600 }),
601 );
602​
603 it.effect("bounds retry attempts and resets the budget for a newer update", () =>
604 Effect.gen(function* () {
605 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
606 respond: () => new Response("relay unavailable", { status: 503 }),
607 });
608 yield* relay.publishThread(THREAD_ID);
609 let attempts = 1;
610 for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) {
611 yield* TestClock.adjust(delay - 1);
612 yield* relay.drain;
613 assert.equal(publications.length, attempts);
614 yield* TestClock.adjust(1);
615 yield* relay.drain;
616 attempts += 1;
617 assert.equal(publications.length, attempts);
618 }
619 yield* TestClock.adjust("1 minute");
620 yield* relay.drain;
621 assert.equal(publications.length, 6);
622 assert.equal(shellReads.length, 6);
623 yield* Ref.set(currentShell, shell({ title: "New update" }));
624 yield* relay.publishThread(THREAD_ID);
625 yield* TestClock.adjust("1 second");
626 yield* relay.drain;
627 assert.equal(publications.length, 8);
628 assert.equal(publications[7]?.state?.threadTitle, "New update");
629 }),
630 );
631​
632 it.effect("retries a confirmed completion without restarting its confirmation window", () =>
633 Effect.gen(function* () {
634 const { relay, currentShell, publications } = yield* makeTestRelay({
635 respond: (attempt) =>
636 attempt <= 2
637 ? new Response("relay unavailable", { status: 503 })
638 : Response.json({ ok: true, deliveries: [] }),
639 });
640 yield* Ref.set(
641 currentShell,
642 shell({
643 status: "completed",
644 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
645 }),
646 );
647 yield* relay.publishThread(THREAD_ID);
648 yield* TestClock.adjust("5 seconds");
649 yield* relay.drain;
650 assert.equal(publications.length, 1);
651 yield* TestClock.adjust("1 second");
652 yield* relay.drain;
653 assert.equal(publications.length, 2);
654 yield* TestClock.adjust("2 seconds");
655 yield* relay.drain;
656 assert.equal(publications.length, 3);
657 assert.isTrue(publications.every((publication) => publication.state?.phase === "completed"));
658 yield* TestClock.adjust("1 minute");
659 yield* relay.drain;
660 assert.equal(publications.length, 3);
661 }),
662 );
663​
664 it.effect("does not reset an exhausted retry budget for old confirmation timers", () =>
665 Effect.gen(function* () {
666 let unavailable = false;
667 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
668 respond: () =>
669 unavailable
670 ? new Response("relay unavailable", { status: 503 })
671 : Response.json({ ok: true, deliveries: [] }),
672 });
673 yield* relay.publishThread(THREAD_ID);
674 for (let i = 0; i < 6; i++) {
675 yield* Ref.set(currentShell, null);
676 yield* relay.publishThread(THREAD_ID);
677 yield* Ref.set(currentShell, shell());
678 yield* relay.publishThread(THREAD_ID);
679 yield* TestClock.adjust(1);
680 }
681 unavailable = true;
682 yield* Ref.set(currentShell, shell({ status: "failed" }));
683 yield* relay.publishThread(THREAD_ID);
684 yield* TestClock.adjust(1_000);
685 yield* relay.drain;
686 yield* TestClock.adjust(2_000);
687 yield* relay.drain;
688 yield* TestClock.adjust(1_994);
689 yield* relay.drain;
690 for (let i = 0; i < 5; i++) {
691 yield* TestClock.adjust(1);
692 yield* relay.drain;
693 }
694 const attempts = publications.length;
695 const reads = shellReads.length;
696 yield* TestClock.adjust("1 minute");
697 yield* relay.drain;
698 assert.equal(publications.length, attempts);
699 assert.equal(shellReads.length, reads);
700 }),
701 );
702​
703 it.effect("confirms tombstones and cancels stale confirmations when activity recovers", () =>
704 Effect.gen(function* () {
705 const { relay, currentShell, publications } = yield* makeTestRelay();
706 yield* relay.publishThread(THREAD_ID);
707 yield* Ref.set(currentShell, null);
708 yield* relay.publishThread(THREAD_ID);
709 assert.equal(publications.length, 1);
710 yield* Ref.set(currentShell, shell());
711 yield* relay.publishThread(THREAD_ID);
712 yield* TestClock.adjust("5 seconds");
713 yield* relay.drain;
714 assert.equal(publications.length, 1);
715 yield* Ref.set(currentShell, null);
716 yield* relay.publishThread(THREAD_ID);
717 assert.equal(publications.length, 1);
718 yield* TestClock.adjust("5 seconds");
719 yield* relay.drain;
720 assert.equal(publications.length, 2);
721 assert.equal(publications[1]?.state, null);
722 }),
723 );
724​
725 it.effect.each([
726 { label: "live", archived: false },
727 { label: "archived", archived: true },
728 ])("never publishes tombstones for $label subagent threads", ({ archived }) =>
729 Effect.gen(function* () {
730 const { relay, currentShell, publications } = yield* makeTestRelay();
731 yield* Ref.set(
732 currentShell,
733 shell({
734 lineage: {
735 rootThreadId: THREAD_ID,
736 parentThreadId: THREAD_ID,
737 relationshipToParent: "subagent",
738 },
739 ...(archived ? { archivedAt: yield* DateTime.now } : {}),
740 }),
741 );
742 yield* relay.publishThread(THREAD_ID);
743 yield* TestClock.adjust("5 seconds");
744 yield* relay.drain;
745 assert.equal(publications.length, 0);
746 }),
747 );
748​
749 it.effect("confirms a first completed state and respects disabling during confirmation", () =>
750 Effect.gen(function* () {
751 const { relay, secrets, currentShell, publications } = yield* makeTestRelay();
752 yield* Ref.set(
753 currentShell,
754 shell({
755 status: "completed",
756 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
757 }),
758 );
759 yield* relay.publishThread(THREAD_ID);
760 assert.equal(publications.length, 0);
761 yield* TestClock.adjust("5 seconds");
762 yield* relay.drain;
763 assert.equal(publications[0]?.state?.phase, "completed");
764 yield* Ref.set(currentShell, null);
765 yield* relay.publishThread(THREAD_ID);
766 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
767 yield* TestClock.adjust("5 seconds");
768 yield* relay.drain;
769 assert.equal(publications.length, 1);
770 }),
771 );
772 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
773 Effect.gen(function* () {
774 const store = yield* ProjectionStore.ProjectionStoreV2;
775 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
776 const pulls = yield* Queue.unbounded<void>();
777 const { relay, shellReads, publications } = yield* makeTestRelay({
778 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
779 domainEvents: Stream.fromEffectRepeat(
780 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
781 ),
782 });
783 yield* relay.start();
784 yield* Queue.take(pulls);
785 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
786 yield* store.apply(event);
787 yield* Queue.offer(events, event);
788 yield* Queue.take(pulls);
789 yield* relay.drain;
790 });
791​
792 const now = yield* DateTime.now;
793 const runId = RunId.make("run:held-item");
794 const run = {
795 id: runId,
796 threadId: THREAD_ID,
797 ordinal: 1,
798 providerInstanceId: ProviderInstanceId.make("codex"),
799 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
800 providerThreadId: null,
801 userMessageId: MessageId.make("message:held-item"),
802 rootNodeId: null,
803 activeAttemptId: null,
804 status: "running" as const,
805 requestedAt: now,
806 startedAt: now,
807 completedAt: null,
808 checkpointId: null,
809 contextHandoffId: null,
810 };
811 const item = (
812 id: string,
813 fields: Pick<OrchestrationV2TurnItem, "status"> &
814 (
815 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
816 | {
817 readonly type: "assistant_message";
818 readonly messageId: MessageId;
819 readonly text: string;
820 readonly streaming: boolean;
821 }
822 ),
823 ): OrchestrationV2TurnItem => ({
824 id: TurnItemId.make(id),
825 threadId: THREAD_ID,
826 runId,
827 nodeId: NodeId.make("node:held-item"),
828 providerThreadId: null,
829 providerTurnId: null,
830 nativeItemRef: null,
831 parentItemId: null,
832 ordinal: 1,
833 title: null,
834 startedAt: now,
835 completedAt: null,
836 updatedAt: now,
837 ...fields,
838 });
839 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
840 ({
841 id: EventId.make(id),
842 type: "turn-item.updated",
843 threadId: THREAD_ID,
844 runId,
845 occurredAt: now,
846 payload,
847 }) satisfies OrchestrationV2DomainEvent;
848 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
849​
850 yield* deliver({
851 id: EventId.make("event:held-item:thread"),
852 type: "thread.created",
853 threadId: THREAD_ID,
854 occurredAt: now,
855 payload: {
856 createdBy: "user",
857 creationSource: "web",
858 id: THREAD_ID,
859 projectId: PROJECT_ID,
860 title: "Thread",
861 providerInstanceId: ProviderInstanceId.make("codex"),
862 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
863 runtimeMode: "full-access",
864 interactionMode: "default",
865 branch: null,
866 worktreePath: null,
867 activeProviderThreadId: null,
868 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
869 forkedFrom: null,
870 createdAt: now,
871 updatedAt: now,
872 archivedAt: null,
873 settledOverride: null,
874 settledAt: null,
875 lastVisitedAt: null,
876 deletedAt: null,
877 },
878 });
879 yield* deliver({
880 id: EventId.make("event:held-item:run"),
881 type: "run.created",
882 threadId: THREAD_ID,
883 runId,
884 occurredAt: now,
885 payload: run,
886 });
887 yield* deliver(
888 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
889 );
890 yield* deliver({
891 id: EventId.make("event:held-item:run-completed"),
892 type: "run.updated",
893 threadId: THREAD_ID,
894 runId,
895 occurredAt: now,
896 payload: { ...run, status: "completed", completedAt: now },
897 });
898 assert.deepEqual(
899 publications.map((publication) => publication.state?.phase),
900 ["running"],
901 );
902​
903 const readsBeforeOutput = shellReads.length;
904 yield* deliver(
905 itemEvent(
906 "event:held-item:reply",
907 item("item:reply", {
908 type: "assistant_message",
909 messageId: MessageId.make("message:held-item:reply"),
910 text: "Still watching",
911 streaming: true,
912 status: "running",
913 }),
914 ),
915 );
916 yield* deliver(
917 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
918 );
919 assert.equal(shellReads.length, readsBeforeOutput);
920​
921 yield* deliver(
922 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
923 );
924 assert.deepEqual(
925 publications.map((publication) => publication.state?.phase),
926 ["running", "completed"],
927 );
928 }).pipe(Effect.scoped, Effect.provide(ProjectionStore.layerMemory)),
929 );
930});
931​
932describe("startup catch-up", { concurrent: false }, () => {
933 const link = (secrets: ServerSecretStore.ServerSecretStore["Service"]) =>
934 Effect.all(
935 [
936 secrets.set(RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")),
937 secrets.set(RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")),
938 secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")),
939 ],
940 { discard: true },
941 );
942 const enablePublishing = (secrets: ServerSecretStore.ServerSecretStore["Service"]) =>
943 secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
944 const linkChecks = (secretReads: ReadonlyArray<string>) =>
945 secretReads.filter((name) => name === RELAY_URL_SECRET).length;
946​
947 it.effect("checks an unlinked environment once a minute and still catches up once linked", () =>
948 Effect.gen(function* () {
949 const { relay, secrets, secretReads, catchUp } = yield* makeTestRelay({ linked: false });
950 yield* enablePublishing(secrets);
951 yield* relay.start();
952​
953 yield* TestClock.adjust("10 minutes");
954 const checksBeforeWindow = linkChecks(secretReads);
955 yield* TestClock.adjust("10 minutes");
956 assert.equal(linkChecks(secretReads) - checksBeforeWindow, 10);
957 assert.equal(catchUp.shellSnapshotReads, 0);
958​
959 yield* link(secrets);
960 yield* TestClock.adjust("1 minute");
961 assert.equal(catchUp.shellSnapshotReads, 1);
962 }).pipe(Effect.scoped),
963 );
964​
965 it.effect("publishes at once when this process links while the check is backed off", () =>
966 Effect.gen(function* () {
967 const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false });
968 yield* enablePublishing(secrets);
969 yield* relay.start();
970​
971 yield* TestClock.adjust("10 minutes");
972 yield* link(secrets);
973 yield* TestClock.adjust("1 second");
974 assert.equal(catchUp.shellSnapshotReads, 0);
975​
976 yield* relay.requestCatchUp();
977 yield* TestClock.adjust("1 second");
978 assert.equal(catchUp.shellSnapshotReads, 1);
979 }).pipe(Effect.scoped),
980 );
981​
982 it.effect("catches up within 5 s when another process enables publishing on a link", () =>
983 Effect.gen(function* () {
984 const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false });
985 yield* link(secrets);
986 yield* relay.start();
987​
988 yield* TestClock.adjust("10 minutes");
989 assert.equal(catchUp.shellSnapshotReads, 0);
990​
991 yield* enablePublishing(secrets);
992 yield* TestClock.adjust("5 seconds");
993 assert.equal(catchUp.shellSnapshotReads, 1);
994 }).pipe(Effect.scoped),
995 );
996});