Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import {
4 EnvironmentId,
5 EventId,
6 MessageId,
7 NodeId,
8 type OrchestrationV2DomainEvent,
9 type OrchestrationV2ThreadShell,
10 type OrchestrationV2TurnItem,
11 ProjectId,
12 ProviderInstanceId,
13 RunId,
14 RuntimeRequestId,
15 ThreadId,
16 TurnItemId,
17} from "@t3tools/contracts";
18import { RelayAgentActivityState } from "@t3tools/contracts/relay";
19import { RelayClientTracer } from "@t3tools/shared/relayTracing";
20import * as DateTime from "effect/DateTime";
21import * as Deferred from "effect/Deferred";
22import * as Effect from "effect/Effect";
23import * as Fiber from "effect/Fiber";
24import * as Option from "effect/Option";
25import * as Queue from "effect/Queue";
26import * as Ref from "effect/Ref";
27import * as Schema from "effect/Schema";
28import * as Stream from "effect/Stream";
29import * as Tracer from "effect/Tracer";
30import * as TestClock from "effect/testing/TestClock";
31import * as FetchHttpClient from "effect/http/FetchHttpClient";
32
33import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
34import {
35 PUBLISH_AGENT_ACTIVITY_SECRET,
36 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
37 RELAY_ISSUER_SECRET,
38 RELAY_URL_SECRET,
39} from "../cloud/config.ts";
40import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
41import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
42import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
43import * as ProjectService from "../project/ProjectService.ts";
44import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";
45
46const THREAD_ID = ThreadId.make("relay-thread");
47const SECOND_THREAD_ID = ThreadId.make("relay-thread-2");
48const PROJECT_ID = ProjectId.make("relay-project");
49const NOW = "2026-09-04T12:00:00.000Z";
50
51function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
52 return {
53 id: THREAD_ID,
54 projectId: PROJECT_ID,
55 title: "Thread",
56 providerInstanceId: ProviderInstanceId.make("codex"),
57 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
58 runtimeMode: "full-access",
59 interactionMode: "default",
60 worktreePath: null,
61 activeProviderThreadId: null,
62 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
63 forkedFrom: null,
64 createdBy: "user",
65 creationSource: "web",
66 activeRunId: null,
67 latestVisibleMessage: null,
68 hasActionableProposedPlan: false,
69 itemCount: 0,
70 visibleItemCount: 0,
71 lastVisitedAt: null,
72 deletedAt: null,
73 branch: null,
74 linkedPullRequest: null,
75 status: "running",
76 activityRunStatus: null,
77 pendingRuntimeRequest: null,
78 pendingBackgroundTasks: [],
79 latestRunId: null,
80 latestRunRequestedAt: null,
81 latestRunStartedAt: null,
82 latestRunCompletedAt: null,
83 latestUserMessageAt: null,
84 createdAt: DateTime.makeUnsafe(NOW),
85 updatedAt: DateTime.makeUnsafe(NOW),
86 archivedAt: null,
87 settledOverride: null,
88 settledAt: null,
89 snoozedUntil: null,
90 snoozedAt: null,
91 pinnedAt: null,
92 ...overrides,
93 };
94}
95
96const PublishPayload = Schema.Struct({ state: Schema.NullOr(RelayAgentActivityState) });
97const decodePublishPayload = Schema.decodeUnknownSync(Schema.fromJsonString(PublishPayload));
98const unused = () => Effect.die("Unexpected test dependency call");
99
100describe("startup agent activity", () => {
101 it("publishes active work and only terminal runs completed after startup", () => {
102 const startedAt = DateTime.toEpochMillis(DateTime.makeUnsafe(NOW));
103 const oldCompleted = ThreadId.make("old-completed");
104 const newCompleted = ThreadId.make("new-completed");
105 const oldFailed = ThreadId.make("old-failed");
106 const newFailed = ThreadId.make("new-failed");
107 const ids = AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
108 environmentId: EnvironmentId.make("relay-env"),
109 startedAt,
110 projects: [{ id: PROJECT_ID, title: "Project" }],
111 threads: [
112 shell(),
113 shell({
114 id: oldCompleted,
115 status: "completed",
116 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
117 }),
118 shell({
119 id: newCompleted,
120 status: "completed",
121 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
122 }),
123 shell({
124 id: oldFailed,
125 status: "failed",
126 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
127 }),
128 shell({
129 id: newFailed,
130 status: "failed",
131 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
132 }),
133 shell({ id: ThreadId.make("idle"), status: "idle" }),
134 shell({ id: ThreadId.make("missing-project"), projectId: ProjectId.make("missing") }),
135 ],
136 });
137 assert.deepStrictEqual(ids, [THREAD_ID, newCompleted, newFailed]);
138 });
139});
140
141const makeTestRelay = Effect.fnUntraced(function* (
142 options: {
143 readonly respond?: (attempt: number) => Response;
144 readonly failSecretRead?: (name: string) => boolean;
145 readonly linked?: boolean;
146 readonly readShell?: (threadId: ThreadId) => Effect.Effect<OrchestrationV2ThreadShell | null>;
147 readonly domainEvents?: Stream.Stream<OrchestrationV2DomainEvent>;
148 } = {},
149) {
150 const values = new Map<string, Uint8Array>(
151 options.linked === false
152 ? []
153 : [
154 [PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")],
155 [RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")],
156 [RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")],
157 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")],
158 ],
159 );
160 const secretReads: string[] = [];
161 const secrets = ServerSecretStore.ServerSecretStore.of({
162 get: (name) =>
163 Effect.suspend(() => {
164 secretReads.push(name);
165 if (options.failSecretRead?.(name)) {
166 return Effect.fail(
167 new ServerSecretStore.SecretStoreReadError({
168 resource: name,
169 cause: "temporary read failure",
170 }),
171 );
172 }
173 return Effect.succeed(Option.fromUndefinedOr(values.get(name)));
174 }),
175 create: (name, value) => Effect.sync(() => void values.set(name, value)),
176 set: (name, value) => Effect.sync(() => void values.set(name, value)),
177 remove: (name) => Effect.sync(() => void values.delete(name)),
178 getOrCreateRandom: unused,
179 });
180 const currentShell = yield* Ref.make<OrchestrationV2ThreadShell | null>(shell());
181 const shellReads: ThreadId[] = [];
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 getThreadTranscript: unused,
207 getThreadSnapshotWindow: unused,
208 getProjectThreadRecords: () => Effect.die("unused project record read"),
209 getProjectThread: unused,
210 listProjectThreads: unused,
211 sendToThread: unused,
212 assertProviderInstanceEnabled: unused,
213 isProviderInstanceEnabledForProject: unused,
214 hasReceipt: unused,
215 waitForThread: unused,
216 settleAfterRun: unused,
217 settleThread: unused,
218 interruptThread: unused,
219 stopWorkflow: () => Effect.die("unused stopWorkflow"),
220 stopDelegatedTasks: unused,
221 getThreadEventSequence: unused,
222 recoverDelegatedTask: unused,
223 delegatedTaskResultPending: unused,
224 streamStoredEvents: Stream.empty,
225 streamStoredEventsFrom: () => Stream.empty,
226 streamDomainEvents: options.domainEvents ?? Stream.empty,
227 });
228 const publications: Array<{
229 readonly url: string;
230 readonly authorization: string | null;
231 readonly state: RelayAgentActivityState | null;
232 }> = [];
233 const fetch: typeof globalThis.fetch = Object.assign(
234 (
235 input: Parameters<typeof globalThis.fetch>[0],
236 init?: Parameters<typeof globalThis.fetch>[1],
237 ) => {
238 const body = init?.body;
239 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
240 return Promise.reject(new Error("Expected a serialized activity publish payload"));
241 }
242 const payload = decodePublishPayload(
243 typeof body === "string" ? body : new TextDecoder().decode(body),
244 );
245 publications.push({
246 url: String(input),
247 authorization: new Headers(init?.headers).get("authorization"),
248 state: payload.state,
249 });
250 return Promise.resolve(
251 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
252 );
253 },
254 { preconnect: () => {} },
255 );
256 const relay = yield* AgentAwarenessRelay.make.pipe(
257 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
258 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
259 Effect.provideService(ServerEnvironment.ServerEnvironment, {
260 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
261 getDescriptor: unused(),
262 }),
263 Effect.provideService(ProjectService.ProjectService, {
264 create: unused,
265 bootstrap: unused,
266 update: unused,
267 delete: unused,
268 getByWorkspaceRoot: unused,
269 snapshot: Effect.succeed({ projects: [] } as never),
270 getShell: unused,
271 listShells: unused,
272 getById: () =>
273 Effect.succeed(
274 Option.some({
275 id: PROJECT_ID,
276 title: "Project",
277 workspaceRoot: "/workspace",
278 defaultModelSelection: null,
279 scripts: [],
280 createdAt: NOW,
281 updatedAt: NOW,
282 deletedAt: null,
283 }),
284 ),
285 }),
286 Effect.provideService(FetchHttpClient.Fetch, fetch),
287 Effect.provide(NodeCrypto.layer),
288 );
289 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
290});
291
292describe("AgentAwarenessRelay", () => {
293 it("ignores transcript and tool updates but retains activity and metadata changes", () => {
294 for (const type of [
295 "message.updated",
296 "turn-item.updated",
297 "provider-turn.updated",
298 "thread.visited",
299 "thread.pinned",
300 ] as const) {
301 assert.isFalse(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));
302 }
303 for (const type of [
304 "run.created",
305 "run.updated",
306 "runtime-request.updated",
307 "subagent.updated",
308 "provider-thread.updated",
309 "thread.metadata-updated",
310 "thread.model-selection-updated",
311 "thread.provider-switched",
312 "thread.archived",
313 "thread.unarchived",
314 "thread.deleted",
315 ] as const) {
316 assert.isTrue(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));
317 }
318 });
319
320 it("does not publish imported thread creation as new agent activity", () => {
321 assert.isFalse(
322 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
323 type: "thread.created",
324 payload: { historyOrigin: "v1_import" },
325 }),
326 );
327 assert.isTrue(
328 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type: "thread.created", payload: {} }),
329 );
330 });
331
332 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
333 Effect.gen(function* () {
334 const started = yield* Deferred.make<void>();
335 const release = yield* Deferred.make<void>();
336 const rerunStarted = yield* Deferred.make<void>();
337 const releaseRerun = yield* Deferred.make<void>();
338 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
339 let revision = 1;
340 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
341 Effect.gen(function* () {
342 const currentRevision = revision;
343 const index = processed.length;
344 processed.push({ threadId, revision: currentRevision });
345 if (index === 0) {
346 yield* Deferred.succeed(started, undefined);
347 yield* Deferred.await(release);
348 } else if (threadId === THREAD_ID) {
349 yield* Deferred.succeed(rerunStarted, undefined);
350 yield* Deferred.await(releaseRerun);
351 }
352 }),
353 );
354 yield* worker.enqueue(THREAD_ID);
355 yield* Deferred.await(started);
356 revision = 2;
357 for (let i = 0; i < 100; i++) {
358 yield* worker.enqueue(SECOND_THREAD_ID);
359 yield* worker.enqueue(THREAD_ID);
360 }
361 const drained = yield* Deferred.make<void>();
362 const draining = yield* worker.drain.pipe(
363 Effect.andThen(Deferred.succeed(drained, undefined)),
364 Effect.forkChild,
365 );
366 yield* Deferred.succeed(release, undefined);
367 yield* Deferred.await(rerunStarted);
368 assert.isFalse(yield* Deferred.isDone(drained));
369 yield* Deferred.succeed(releaseRerun, undefined);
370 yield* Fiber.join(draining);
371 assert.deepEqual(processed, [
372 { threadId: THREAD_ID, revision: 1 },
373 { threadId: SECOND_THREAD_ID, revision: 2 },
374 { threadId: THREAD_ID, revision: 2 },
375 ]);
376 }),
377 );
378
379 it.effect("exports the publication span through the relay tracer", () => {
380 const relaySpans: string[] = [];
381 const localSpans: string[] = [];
382 const collectingTracer = (spans: string[]) =>
383 Tracer.make({
384 span: (options) => {
385 spans.push(options.name);
386 return new Tracer.NativeSpan(options);
387 },
388 });
389
390 return Effect.gen(function* () {
391 const { relay, publications } = yield* makeTestRelay();
392 yield* relay.publishThread(THREAD_ID);
393 assert.equal(publications.length, 1);
394 assert.include(relaySpans, "relay.agent_activity.publish");
395 assert.notInclude(localSpans, "relay.agent_activity.publish");
396 }).pipe(
397 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(relaySpans))),
398 Effect.withTracer(collectingTracer(localSpans)),
399 );
400 });
401
402 it.effect("deduplicates state and republishes title changes", () =>
403 Effect.gen(function* () {
404 const { relay, currentShell, publications } = yield* makeTestRelay();
405 yield* relay.publishThread(THREAD_ID);
406 yield* Ref.set(
407 currentShell,
408 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
409 );
410 yield* relay.publishThread(THREAD_ID);
411 assert.equal(publications.length, 1);
412 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
413 yield* relay.publishThread(THREAD_ID);
414 assert.equal(publications.length, 2);
415 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
416 }),
417 );
418
419 it.effect("stops before shell reads when disabled and republishes after re-enabling", () =>
420 Effect.gen(function* () {
421 const { relay, secrets, secretReads, shellReads, publications } = yield* makeTestRelay();
422 yield* relay.publishThread(THREAD_ID);
423 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
424 const previousReads = secretReads.length;
425 yield* relay.publishThread(THREAD_ID);
426 assert.deepEqual(secretReads.slice(previousReads), [PUBLISH_AGENT_ACTIVITY_SECRET]);
427 assert.equal(shellReads.length, 1);
428 assert.equal(publications.length, 1);
429 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
430 yield* relay.publishThread(THREAD_ID);
431 assert.equal(publications.length, 2);
432 }),
433 );
434
435 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
436 Effect.gen(function* () {
437 const { relay, secrets, publications } = yield* makeTestRelay();
438 yield* relay.publishThread(THREAD_ID);
439 yield* secrets.set(
440 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
441 new TextEncoder().encode("credential-2"),
442 );
443 yield* relay.publishThread(THREAD_ID);
444 assert.equal(publications.length, 2);
445 assert.equal(publications[0]?.authorization, "Bearer credential-1");
446 assert.equal(publications[1]?.authorization, "Bearer credential-2");
447 yield* secrets.set(
448 RELAY_URL_SECRET,
449 new TextEncoder().encode("https://new-relay.example.test"),
450 );
451 yield* relay.publishThread(THREAD_ID);
452 assert.equal(publications.length, 3);
453 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
454 }),
455 );
456
457 it.effect("a stalled response body releases later threads and uses bounded retries", () =>
458 Effect.gen(function* () {
459 const bodyStarted = Promise.withResolvers<void>();
460 const secondRead = yield* Deferred.make<void>();
461 const currentShell = yield* Ref.make(shell());
462 const { relay, publications } = yield* makeTestRelay({
463 readShell: (threadId) =>
464 threadId === SECOND_THREAD_ID
465 ? Deferred.succeed(secondRead, undefined).pipe(
466 Effect.as(shell({ id: SECOND_THREAD_ID })),
467 )
468 : Ref.get(currentShell),
469 respond: (attempt) => {
470 if (attempt !== 1) return new Response("relay unavailable", { status: 503 });
471 const response = new Response(null, {
472 headers: { "content-type": "application/json" },
473 });
474 return Object.assign(response, {
475 arrayBuffer: () => {
476 bodyStarted.resolve();
477 return new Promise<ArrayBuffer>(() => {});
478 },
479 });
480 },
481 });
482 const first = yield* relay.publishThread(THREAD_ID).pipe(Effect.forkChild);
483 yield* Effect.promise(() => bodyStarted.promise);
484 const second = yield* relay.publishThread(SECOND_THREAD_ID).pipe(Effect.forkChild);
485 yield* TestClock.adjust("9999 millis");
486 assert.equal(publications.length, 1);
487 yield* Ref.set(currentShell, shell({ title: "Latest title" }));
488 yield* TestClock.adjust("1 millis");
489 assert.isTrue(yield* Deferred.isDone(secondRead));
490 yield* Fiber.join(first);
491 yield* Fiber.join(second);
492 assert.equal(publications.length, 2);
493 assert.isTrue(publications[1]?.url.includes(SECOND_THREAD_ID) ?? false);
494 for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) {
495 const attempts = publications.length;
496 yield* TestClock.adjust(delay - 1);
497 yield* relay.drain;
498 assert.equal(publications.length, attempts);
499 yield* TestClock.adjust(1);
500 yield* relay.drain;
501 assert.equal(publications.length, attempts + 2);
502 assert.equal(publications[attempts]?.state?.threadTitle, "Latest title");
503 }
504 yield* TestClock.adjust("1 minute");
505 yield* relay.drain;
506 assert.equal(publications.length, 12);
507 }),
508 );
509
510 it.effect("retries a failed final state without another thread event", () =>
511 Effect.gen(function* () {
512 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
513 respond: (attempt) =>
514 attempt === 2
515 ? new Response("relay unavailable", { status: 503 })
516 : Response.json({ ok: true, deliveries: [] }),
517 });
518 yield* relay.publishThread(THREAD_ID);
519 yield* Ref.set(
520 currentShell,
521 shell({
522 status: "completed",
523 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
524 }),
525 );
526 yield* relay.publishThread(THREAD_ID);
527 assert.equal(publications.length, 2);
528 yield* TestClock.adjust("1 second");
529 yield* relay.drain;
530 assert.equal(publications.length, 3);
531 assert.equal(publications[2]?.state?.phase, "completed");
532 yield* TestClock.adjust("1 minute");
533 yield* relay.drain;
534 assert.equal(shellReads.length, 3);
535 }),
536 );
537
538 it.effect("retries the latest shell and credentials with first-completion confirmation", () =>
539 Effect.gen(function* () {
540 const { relay, secrets, currentShell, publications } = yield* makeTestRelay({
541 respond: (attempt) =>
542 attempt === 1
543 ? new Response("relay unavailable", { status: 503 })
544 : Response.json({ ok: true, deliveries: [] }),
545 });
546 yield* relay.publishThread(THREAD_ID);
547 yield* Ref.set(
548 currentShell,
549 shell({
550 status: "completed",
551 title: "Final title",
552 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
553 }),
554 );
555 yield* secrets.set(
556 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
557 new TextEncoder().encode("credential-2"),
558 );
559 yield* TestClock.adjust("1 second");
560 yield* relay.drain;
561 assert.equal(publications.length, 1);
562 yield* TestClock.adjust("5 seconds");
563 yield* relay.drain;
564 assert.equal(publications.length, 2);
565 assert.equal(publications[1]?.authorization, "Bearer credential-2");
566 assert.equal(publications[1]?.state?.phase, "completed");
567 assert.equal(publications[1]?.state?.threadTitle, "Final title");
568 }),
569 );
570
571 it.effect("cancels a stale retry when a newer update publishes successfully", () =>
572 Effect.gen(function* () {
573 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
574 respond: (attempt) =>
575 attempt === 1
576 ? new Response("relay unavailable", { status: 503 })
577 : Response.json({ ok: true, deliveries: [] }),
578 });
579 yield* relay.publishThread(THREAD_ID);
580 yield* Ref.set(currentShell, shell({ title: "New title" }));
581 yield* relay.publishThread(THREAD_ID);
582 assert.equal(publications.length, 2);
583 assert.equal(publications[1]?.state?.threadTitle, "New title");
584 yield* TestClock.adjust("1 minute");
585 yield* relay.drain;
586 assert.equal(shellReads.length, 2);
587 }),
588 );
589
590 it.effect.each(["disable", "unlink"] as const)(
591 "stops retries before shell reads after %s",
592 (change) =>
593 Effect.gen(function* () {
594 const { relay, secrets, shellReads, publications } = yield* makeTestRelay({
595 respond: () => new Response("relay unavailable", { status: 503 }),
596 });
597 yield* relay.publishThread(THREAD_ID);
598 if (change === "disable") {
599 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
600 } else {
601 yield* secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET);
602 }
603 yield* TestClock.adjust("1 second");
604 yield* relay.drain;
605 yield* TestClock.adjust("1 minute");
606 yield* relay.drain;
607 assert.equal(publications.length, 1);
608 assert.equal(shellReads.length, 1);
609 }),
610 );
611
612 it.effect("recovers from a transient configuration read failure", () =>
613 Effect.gen(function* () {
614 let failRead = false;
615 const { relay, shellReads, publications } = yield* makeTestRelay({
616 failSecretRead: (name) => failRead && name === PUBLISH_AGENT_ACTIVITY_SECRET,
617 });
618 failRead = true;
619 yield* relay.publishThread(THREAD_ID);
620 assert.equal(shellReads.length, 0);
621 failRead = false;
622 yield* TestClock.adjust("1 second");
623 yield* relay.drain;
624 assert.equal(publications.length, 1);
625 assert.equal(publications[0]?.state?.phase, "running");
626 }),
627 );
628
629 it.effect("bounds retry attempts and resets the budget for a newer update", () =>
630 Effect.gen(function* () {
631 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
632 respond: () => new Response("relay unavailable", { status: 503 }),
633 });
634 yield* relay.publishThread(THREAD_ID);
635 let attempts = 1;
636 for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) {
637 yield* TestClock.adjust(delay - 1);
638 yield* relay.drain;
639 assert.equal(publications.length, attempts);
640 yield* TestClock.adjust(1);
641 yield* relay.drain;
642 attempts += 1;
643 assert.equal(publications.length, attempts);
644 }
645 yield* TestClock.adjust("1 minute");
646 yield* relay.drain;
647 assert.equal(publications.length, 6);
648 assert.equal(shellReads.length, 6);
649 yield* Ref.set(currentShell, shell({ title: "New update" }));
650 yield* relay.publishThread(THREAD_ID);
651 yield* TestClock.adjust("1 second");
652 yield* relay.drain;
653 assert.equal(publications.length, 8);
654 assert.equal(publications[7]?.state?.threadTitle, "New update");
655 }),
656 );
657
658 it.effect("retries a confirmed completion without restarting its confirmation window", () =>
659 Effect.gen(function* () {
660 const { relay, currentShell, publications } = yield* makeTestRelay({
661 respond: (attempt) =>
662 attempt <= 2
663 ? new Response("relay unavailable", { status: 503 })
664 : Response.json({ ok: true, deliveries: [] }),
665 });
666 yield* Ref.set(
667 currentShell,
668 shell({
669 status: "completed",
670 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
671 }),
672 );
673 yield* relay.publishThread(THREAD_ID);
674 yield* TestClock.adjust("5 seconds");
675 yield* relay.drain;
676 assert.equal(publications.length, 1);
677 yield* TestClock.adjust("1 second");
678 yield* relay.drain;
679 assert.equal(publications.length, 2);
680 yield* TestClock.adjust("2 seconds");
681 yield* relay.drain;
682 assert.equal(publications.length, 3);
683 assert.isTrue(publications.every((publication) => publication.state?.phase === "completed"));
684 yield* TestClock.adjust("1 minute");
685 yield* relay.drain;
686 assert.equal(publications.length, 3);
687 }),
688 );
689
690 it.effect("does not reset an exhausted retry budget for old confirmation timers", () =>
691 Effect.gen(function* () {
692 let unavailable = false;
693 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
694 respond: () =>
695 unavailable
696 ? new Response("relay unavailable", { status: 503 })
697 : Response.json({ ok: true, deliveries: [] }),
698 });
699 yield* relay.publishThread(THREAD_ID);
700 for (let i = 0; i < 6; i++) {
701 yield* Ref.set(currentShell, null);
702 yield* relay.publishThread(THREAD_ID);
703 yield* Ref.set(currentShell, shell());
704 yield* relay.publishThread(THREAD_ID);
705 yield* TestClock.adjust(1);
706 }
707 unavailable = true;
708 yield* Ref.set(currentShell, shell({ status: "failed" }));
709 yield* relay.publishThread(THREAD_ID);
710 yield* TestClock.adjust(1_000);
711 yield* relay.drain;
712 yield* TestClock.adjust(2_000);
713 yield* relay.drain;
714 yield* TestClock.adjust(1_994);
715 yield* relay.drain;
716 for (let i = 0; i < 5; i++) {
717 yield* TestClock.adjust(1);
718 yield* relay.drain;
719 }
720 const attempts = publications.length;
721 const reads = shellReads.length;
722 yield* TestClock.adjust("1 minute");
723 yield* relay.drain;
724 assert.equal(publications.length, attempts);
725 assert.equal(shellReads.length, reads);
726 }),
727 );
728
729 it.effect("confirms tombstones and cancels stale confirmations when activity recovers", () =>
730 Effect.gen(function* () {
731 const { relay, currentShell, publications } = yield* makeTestRelay();
732 yield* relay.publishThread(THREAD_ID);
733 yield* Ref.set(currentShell, null);
734 yield* relay.publishThread(THREAD_ID);
735 assert.equal(publications.length, 1);
736 yield* Ref.set(currentShell, shell());
737 yield* relay.publishThread(THREAD_ID);
738 yield* TestClock.adjust("5 seconds");
739 yield* relay.drain;
740 assert.equal(publications.length, 1);
741 yield* Ref.set(currentShell, null);
742 yield* relay.publishThread(THREAD_ID);
743 assert.equal(publications.length, 1);
744 yield* TestClock.adjust("5 seconds");
745 yield* relay.drain;
746 assert.equal(publications.length, 2);
747 assert.equal(publications[1]?.state, null);
748 }),
749 );
750
751 it.effect.each([
752 { label: "live", archived: false },
753 { label: "archived", archived: true },
754 ])("never publishes tombstones for $label subagent threads", ({ archived }) =>
755 Effect.gen(function* () {
756 const { relay, currentShell, publications } = yield* makeTestRelay();
757 yield* Ref.set(
758 currentShell,
759 shell({
760 lineage: {
761 rootThreadId: THREAD_ID,
762 parentThreadId: THREAD_ID,
763 relationshipToParent: "subagent",
764 },
765 ...(archived ? { archivedAt: yield* DateTime.now } : {}),
766 }),
767 );
768 yield* relay.publishThread(THREAD_ID);
769 yield* TestClock.adjust("5 seconds");
770 yield* relay.drain;
771 assert.equal(publications.length, 0);
772 }),
773 );
774
775 it.effect.each(["completed", "failed"] as const)(
776 "settling a %s thread publishes a tombstone without re-alerting on unsettle",
777 (status) =>
778 Effect.gen(function* () {
779 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
780 const pulls = yield* Queue.unbounded<void>();
781 const { relay, currentShell, publications } = yield* makeTestRelay({
782 domainEvents: Stream.fromEffectRepeat(
783 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
784 ),
785 });
786 yield* relay.start();
787 yield* Queue.take(pulls);
788 const finished = shell({
789 status,
790 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
791 });
792 yield* Ref.set(currentShell, finished);
793 yield* relay.publishThread(THREAD_ID);
794 yield* TestClock.adjust("5 seconds");
795 yield* relay.drain;
796 assert.deepEqual(
797 publications.map(({ state }) => state?.phase),
798 [status],
799 );
800
801 for (const type of ["thread.settled", "thread.unsettled"] as const) {
802 const updated = {
803 ...finished,
804 settledOverride: type === "thread.settled" ? ("settled" as const) : ("active" as const),
805 updatedAt: yield* DateTime.now,
806 };
807 yield* Ref.set(currentShell, updated);
808 yield* Queue.offer(events, {
809 id: EventId.make(type),
810 type,
811 threadId: THREAD_ID,
812 occurredAt: updated.updatedAt,
813 payload: { ...updated, lastVisitedAt: updated.lastVisitedAt ?? null },
814 });
815 yield* Queue.take(pulls);
816 yield* relay.drain;
817 yield* TestClock.adjust("5 seconds");
818 yield* relay.drain;
819 assert.deepEqual(
820 publications.map(({ state }) => state?.phase ?? null),
821 [status, null],
822 );
823 }
824 }).pipe(Effect.scoped),
825 );
826
827 it.effect.each([
828 { work: "running", status: "running", phase: "running" },
829 { work: "user input", status: "completed", phase: "waiting_for_input" },
830 { work: "monitor", status: "completed", phase: "running" },
831 { work: "monitor", status: "failed", phase: "failed" },
832 ] as const)(
833 "keeps settled $work visible until it finishes ($status run)",
834 ({ work, status, phase }) =>
835 Effect.gen(function* () {
836 const { relay, currentShell, publications } = yield* makeTestRelay();
837 const active = shell({
838 status,
839 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
840 pendingRuntimeRequest:
841 work === "user input"
842 ? {
843 id: RuntimeRequestId.make("waiting"),
844 kind: "user_input",
845 createdAt: yield* DateTime.now,
846 }
847 : null,
848 pendingBackgroundTasks: work === "monitor" ? [{ taskId: "watch", kind: "monitor" }] : [],
849 });
850 yield* Ref.set(currentShell, active);
851 yield* relay.publishThread(THREAD_ID);
852 yield* TestClock.adjust("5 seconds");
853 yield* relay.drain;
854 assert.deepEqual(
855 publications.map(({ state }) => state?.phase),
856 [phase],
857 );
858
859 yield* Ref.set(currentShell, { ...active, settledOverride: "settled" });
860 yield* relay.publishThread(THREAD_ID);
861 yield* TestClock.adjust("5 seconds");
862 yield* relay.drain;
863 assert.deepEqual(
864 publications.map(({ state }) => state?.phase),
865 [phase],
866 );
867
868 yield* Ref.set(currentShell, {
869 ...active,
870 settledOverride: "settled",
871 status: status === "running" ? "completed" : status,
872 pendingRuntimeRequest: null,
873 pendingBackgroundTasks: [],
874 });
875 yield* relay.publishThread(THREAD_ID);
876 yield* TestClock.adjust("5 seconds");
877 yield* relay.drain;
878 assert.deepEqual(
879 publications.map(({ state }) => state?.phase ?? null),
880 [phase, null],
881 );
882 }),
883 );
884
885 it.effect("confirms a first completed state and respects disabling during confirmation", () =>
886 Effect.gen(function* () {
887 const { relay, secrets, currentShell, publications } = yield* makeTestRelay();
888 yield* Ref.set(
889 currentShell,
890 shell({
891 status: "completed",
892 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
893 }),
894 );
895 yield* relay.publishThread(THREAD_ID);
896 assert.equal(publications.length, 0);
897 yield* TestClock.adjust("5 seconds");
898 yield* relay.drain;
899 assert.equal(publications[0]?.state?.phase, "completed");
900 yield* Ref.set(currentShell, null);
901 yield* relay.publishThread(THREAD_ID);
902 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
903 yield* TestClock.adjust("5 seconds");
904 yield* relay.drain;
905 assert.equal(publications.length, 1);
906 }),
907 );
908 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
909 Effect.gen(function* () {
910 const store = yield* ProjectionStore.ProjectionStoreV2;
911 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
912 const pulls = yield* Queue.unbounded<void>();
913 const { relay, shellReads, publications } = yield* makeTestRelay({
914 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
915 domainEvents: Stream.fromEffectRepeat(
916 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
917 ),
918 });
919 yield* relay.start();
920 yield* Queue.take(pulls);
921 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
922 yield* store.apply(event);
923 yield* Queue.offer(events, event);
924 yield* Queue.take(pulls);
925 yield* relay.drain;
926 });
927
928 const now = yield* DateTime.now;
929 const runId = RunId.make("run:held-item");
930 const run = {
931 id: runId,
932 threadId: THREAD_ID,
933 ordinal: 1,
934 providerInstanceId: ProviderInstanceId.make("codex"),
935 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
936 providerThreadId: null,
937 userMessageId: MessageId.make("message:held-item"),
938 rootNodeId: null,
939 activeAttemptId: null,
940 status: "running" as const,
941 requestedAt: now,
942 startedAt: now,
943 completedAt: null,
944 checkpointId: null,
945 contextHandoffId: null,
946 };
947 const item = (
948 id: string,
949 fields: Pick<OrchestrationV2TurnItem, "status"> &
950 (
951 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
952 | {
953 readonly type: "assistant_message";
954 readonly messageId: MessageId;
955 readonly text: string;
956 readonly streaming: boolean;
957 }
958 ),
959 ): OrchestrationV2TurnItem => ({
960 id: TurnItemId.make(id),
961 threadId: THREAD_ID,
962 runId,
963 nodeId: NodeId.make("node:held-item"),
964 providerThreadId: null,
965 providerTurnId: null,
966 nativeItemRef: null,
967 parentItemId: null,
968 ordinal: 1,
969 title: null,
970 startedAt: now,
971 completedAt: null,
972 updatedAt: now,
973 ...fields,
974 });
975 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
976 ({
977 id: EventId.make(id),
978 type: "turn-item.updated",
979 threadId: THREAD_ID,
980 runId,
981 occurredAt: now,
982 payload,
983 }) satisfies OrchestrationV2DomainEvent;
984 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
985
986 yield* deliver({
987 id: EventId.make("event:held-item:thread"),
988 type: "thread.created",
989 threadId: THREAD_ID,
990 occurredAt: now,
991 payload: {
992 createdBy: "user",
993 creationSource: "web",
994 id: THREAD_ID,
995 projectId: PROJECT_ID,
996 title: "Thread",
997 providerInstanceId: ProviderInstanceId.make("codex"),
998 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
999 runtimeMode: "full-access",
1000 interactionMode: "default",
1001 branch: null,
1002 worktreePath: null,
1003 activeProviderThreadId: null,
1004 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
1005 forkedFrom: null,
1006 createdAt: now,
1007 updatedAt: now,
1008 archivedAt: null,
1009 settledOverride: null,
1010 settledAt: null,
1011 lastVisitedAt: null,
1012 deletedAt: null,
1013 },
1014 });
1015 yield* deliver({
1016 id: EventId.make("event:held-item:run"),
1017 type: "run.created",
1018 threadId: THREAD_ID,
1019 runId,
1020 occurredAt: now,
1021 payload: run,
1022 });
1023 yield* deliver(
1024 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
1025 );
1026 yield* deliver({
1027 id: EventId.make("event:held-item:run-completed"),
1028 type: "run.updated",
1029 threadId: THREAD_ID,
1030 runId,
1031 occurredAt: now,
1032 payload: { ...run, status: "completed", completedAt: now },
1033 });
1034 assert.deepEqual(
1035 publications.map((publication) => publication.state?.phase),
1036 ["running"],
1037 );
1038
1039 const readsBeforeOutput = shellReads.length;
1040 yield* deliver(
1041 itemEvent(
1042 "event:held-item:reply",
1043 item("item:reply", {
1044 type: "assistant_message",
1045 messageId: MessageId.make("message:held-item:reply"),
1046 text: "Still watching",
1047 streaming: true,
1048 status: "running",
1049 }),
1050 ),
1051 );
1052 yield* deliver(
1053 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
1054 );
1055 assert.equal(shellReads.length, readsBeforeOutput);
1056
1057 yield* deliver(
1058 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
1059 );
1060 assert.deepEqual(
1061 publications.map((publication) => publication.state?.phase),
1062 ["running", "completed"],
1063 );
1064 }).pipe(Effect.scoped, Effect.provide(ProjectionStore.layerMemory)),
1065 );
1066});
1067
1068describe("startup catch-up", { concurrent: false }, () => {
1069 const link = (secrets: ServerSecretStore.ServerSecretStore["Service"]) =>
1070 Effect.all(
1071 [
1072 secrets.set(RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")),
1073 secrets.set(RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")),
1074 secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")),
1075 ],
1076 { discard: true },
1077 );
1078 const enablePublishing = (secrets: ServerSecretStore.ServerSecretStore["Service"]) =>
1079 secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
1080 const linkChecks = (secretReads: ReadonlyArray<string>) =>
1081 secretReads.filter((name) => name === RELAY_URL_SECRET).length;
1082
1083 it.effect("checks an unlinked environment once a minute and still catches up once linked", () =>
1084 Effect.gen(function* () {
1085 const { relay, secrets, secretReads, catchUp } = yield* makeTestRelay({ linked: false });
1086 yield* enablePublishing(secrets);
1087 yield* relay.start();
1088
1089 yield* TestClock.adjust("10 minutes");
1090 const checksBeforeWindow = linkChecks(secretReads);
1091 yield* TestClock.adjust("10 minutes");
1092 assert.equal(linkChecks(secretReads) - checksBeforeWindow, 10);
1093 assert.equal(catchUp.shellSnapshotReads, 0);
1094
1095 yield* link(secrets);
1096 yield* TestClock.adjust("1 minute");
1097 assert.equal(catchUp.shellSnapshotReads, 1);
1098 }).pipe(Effect.scoped),
1099 );
1100
1101 it.effect("publishes at once when this process links while the check is backed off", () =>
1102 Effect.gen(function* () {
1103 const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false });
1104 yield* enablePublishing(secrets);
1105 yield* relay.start();
1106
1107 yield* TestClock.adjust("10 minutes");
1108 yield* link(secrets);
1109 yield* TestClock.adjust("1 second");
1110 assert.equal(catchUp.shellSnapshotReads, 0);
1111
1112 yield* relay.requestCatchUp();
1113 yield* TestClock.adjust("1 second");
1114 assert.equal(catchUp.shellSnapshotReads, 1);
1115 }).pipe(Effect.scoped),
1116 );
1117
1118 it.effect("catches up within 5 s when another process enables publishing on a link", () =>
1119 Effect.gen(function* () {
1120 const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false });
1121 yield* link(secrets);
1122 yield* relay.start();
1123
1124 yield* TestClock.adjust("10 minutes");
1125 assert.equal(catchUp.shellSnapshotReads, 0);
1126
1127 yield* enablePublishing(secrets);
1128 yield* TestClock.adjust("5 seconds");
1129 assert.equal(catchUp.shellSnapshotReads, 1);
1130 }).pipe(Effect.scoped),
1131 );
1132});