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