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 Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as Schema from "effect/Schema";
27import * as Stream from "effect/Stream";
28import * as TestClock from "effect/testing/TestClock";
29import * as FetchHttpClient from "effect/http/FetchHttpClient";
30
31import * as EnvironmentKeys from "../cloud/environmentKeys.ts";
32import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
33import {
34 PUBLISH_AGENT_ACTIVITY_SECRET,
35 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
36 RELAY_ISSUER_SECRET,
37 RELAY_URL_SECRET,
38} from "../cloud/config.ts";
39import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
40import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
41import * as SqlitePersistence from "../persistence/Sqlite.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 readonly catchUpThreads?: ReadonlyArray<OrchestrationV2ThreadShell>;
149 } = {},
150) {
151 const values = new Map<string, Uint8Array>(
152 options.linked === false
153 ? []
154 : [
155 [PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")],
156 [RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")],
157 [RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")],
158 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")],
159 ],
160 );
161 const secretReads: string[] = [];
162 const secrets = ServerSecretStore.ServerSecretStore.of({
163 get: (name) =>
164 Effect.suspend(() => {
165 secretReads.push(name);
166 if (options.failSecretRead?.(name)) {
167 return Effect.fail(
168 new ServerSecretStore.SecretStoreReadError({
169 resource: name,
170 cause: "temporary read failure",
171 }),
172 );
173 }
174 return Effect.succeed(Option.fromUndefinedOr(values.get(name)));
175 }),
176 create: (name, value) => Effect.sync(() => void values.set(name, value)),
177 set: (name, value) => Effect.sync(() => void values.set(name, value)),
178 remove: (name) => Effect.sync(() => void values.delete(name)),
179 getOrCreateRandom: unused,
180 });
181 const currentShell = yield* Ref.make<OrchestrationV2ThreadShell | null>(shell());
182 const shellReads: ThreadId[] = [];
183 const catchUp = { activitySnapshotReads: 0 };
184 const threads = ThreadManagementService.ThreadManagementService.of({
185 getThreadShell: unused,
186 getShellSnapshot: unused,
187 getAgentAwarenessSnapshot: (threadId) =>
188 threadId === undefined
189 ? Effect.sync(() => {
190 catchUp.activitySnapshotReads += 1;
191 return { snapshotSequence: 1, threads: options.catchUpThreads ?? [] };
192 })
193 : Effect.sync(() => shellReads.push(threadId)).pipe(
194 Effect.andThen(options.readShell?.(threadId) ?? Ref.get(currentShell)),
195 Effect.map((thread) => ({
196 snapshotSequence: 1,
197 threads: thread === null ? [] : [thread],
198 })),
199 ),
200 listActiveSubagentThreadIds: unused,
201 listAppOwnedChildThreadIds: unused,
202 countThreads: unused,
203 listActiveShellIndex: () => Effect.succeed([]),
204 listOlderSettledThreads: unused,
205 readShellSnapshot: unused,
206 getThreadTitles: unused,
207 ensureLegacyTranscript: unused,
208 dispatch: unused,
209 searchThread: () => Effect.die("unused"),
210 searchThreadStream: () => Stream.empty,
211 getThreadHistoryPage: () => Effect.die("unused"),
212 getTimelinePage: () => Effect.die("Unused timeline read"),
213 getMessageCount: () => Effect.die("unused message count"),
214 getTurnItem: () => Effect.die("unused turn item read"),
215 getThreadRecords: () => Effect.die("unused record read"),
216 getThreadProjection: unused,
217 getCheckpointContext: unused,
218 getThreadSnapshot: unused,
219 getThreadTranscript: unused,
220 getThreadSnapshotWindow: unused,
221 getProjectThreadRecords: () => Effect.die("unused project record read"),
222 listProjectThreads: unused,
223 sendToThread: unused,
224 assertProviderInstanceEnabled: unused,
225 isProviderInstanceEnabledForProject: unused,
226 hasReceipt: unused,
227 waitForThread: unused,
228 settleAfterRun: unused,
229 settleThread: unused,
230 interruptThread: unused,
231 stopWorkflow: () => Effect.die("unused stopWorkflow"),
232 forceStopThread: () => Effect.die("unused forceStopThread"),
233 awaitBackgroundTasks: unused,
234 stopDelegatedTasks: unused,
235 getThreadEventSequence: unused,
236 recoverDelegatedTask: unused,
237 delegatedTaskResultPending: unused,
238 streamStoredEvents: Stream.empty,
239 streamStoredEventsFrom: () => Stream.empty,
240 streamDomainEvents: options.domainEvents ?? Stream.empty,
241 });
242 const publications: Array<{
243 readonly url: string;
244 readonly authorization: string | null;
245 readonly state: RelayAgentActivityState | null;
246 }> = [];
247 const fetch: typeof globalThis.fetch = Object.assign(
248 (
249 input: Parameters<typeof globalThis.fetch>[0],
250 init?: Parameters<typeof globalThis.fetch>[1],
251 ) => {
252 const body = init?.body;
253 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
254 return Promise.reject(new Error("Expected a serialized activity publish payload"));
255 }
256 const payload = decodePublishPayload(
257 typeof body === "string" ? body : new TextDecoder().decode(body),
258 );
259 publications.push({
260 url: String(input),
261 authorization: new Headers(init?.headers).get("authorization"),
262 state: payload.state,
263 });
264 return Promise.resolve(
265 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
266 );
267 },
268 { preconnect: () => {} },
269 );
270 const project = {
271 id: PROJECT_ID,
272 title: "Project",
273 workspaceRoot: "/workspace",
274 defaultModelSelection: null,
275 scripts: [],
276 createdAt: NOW,
277 updatedAt: NOW,
278 deletedAt: null,
279 };
280 const relay = yield* AgentAwarenessRelay.make.pipe(
281 Effect.provide(EnvironmentKeys.layer),
282 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
283 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
284 Effect.provideService(ServerEnvironment.ServerEnvironment, {
285 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
286 getDescriptor: unused(),
287 }),
288 Effect.provideService(ProjectService.ProjectService, {
289 create: unused,
290 bootstrap: unused,
291 update: unused,
292 delete: unused,
293 getByWorkspaceRoot: unused,
294 snapshot: Effect.succeed({ projects: [project], updatedAt: NOW }),
295 listPage: unused,
296 getShell: unused,
297 listShells: unused,
298 getById: () => Effect.succeedSome(project),
299 }),
300 Effect.provideService(FetchHttpClient.Fetch, fetch),
301 Effect.provide(NodeCrypto.layer),
302 );
303 return { relay, secrets, secretReads, currentShell, shellReads, publications, catchUp };
304});
305
306describe("AgentAwarenessRelay", () => {
307 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
308 Effect.gen(function* () {
309 const started = yield* Deferred.make<void>();
310 const release = yield* Deferred.make<void>();
311 const rerunStarted = yield* Deferred.make<void>();
312 const releaseRerun = yield* Deferred.make<void>();
313 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
314 let revision = 1;
315 const worker = yield* AgentAwarenessRelay.makeAgentAwarenessPublishWorker((threadId) =>
316 Effect.gen(function* () {
317 const currentRevision = revision;
318 const index = processed.length;
319 processed.push({ threadId, revision: currentRevision });
320 if (index === 0) {
321 yield* Deferred.succeed(started, undefined);
322 yield* Deferred.await(release);
323 } else if (threadId === THREAD_ID) {
324 yield* Deferred.succeed(rerunStarted, undefined);
325 yield* Deferred.await(releaseRerun);
326 }
327 }),
328 );
329 yield* worker.enqueue(THREAD_ID);
330 yield* Deferred.await(started);
331 revision = 2;
332 for (let i = 0; i < 100; i++) {
333 yield* worker.enqueue(SECOND_THREAD_ID);
334 yield* worker.enqueue(THREAD_ID);
335 }
336 const drained = yield* Deferred.make<void>();
337 const draining = yield* worker.drain.pipe(
338 Effect.andThen(Deferred.succeed(drained, undefined)),
339 Effect.forkChild,
340 );
341 yield* Deferred.succeed(release, undefined);
342 yield* Deferred.await(rerunStarted);
343 assert.isFalse(yield* Deferred.isDone(drained));
344 yield* Deferred.succeed(releaseRerun, undefined);
345 yield* Fiber.join(draining);
346 assert.deepEqual(processed, [
347 { threadId: THREAD_ID, revision: 1 },
348 { threadId: SECOND_THREAD_ID, revision: 2 },
349 { threadId: THREAD_ID, revision: 2 },
350 ]);
351 }),
352 );
353
354 it.effect("deduplicates state and republishes title changes", () =>
355 Effect.gen(function* () {
356 const { relay, currentShell, publications } = yield* makeTestRelay();
357 yield* relay.publishThread(THREAD_ID);
358 yield* Ref.set(
359 currentShell,
360 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
361 );
362 yield* relay.publishThread(THREAD_ID);
363 assert.equal(publications.length, 1);
364 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
365 yield* relay.publishThread(THREAD_ID);
366 assert.equal(publications.length, 2);
367 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
368 }),
369 );
370
371 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
372 Effect.gen(function* () {
373 const { relay, secrets, publications } = yield* makeTestRelay();
374 yield* relay.publishThread(THREAD_ID);
375 yield* secrets.set(
376 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
377 new TextEncoder().encode("credential-2"),
378 );
379 yield* relay.publishThread(THREAD_ID);
380 assert.equal(publications.length, 2);
381 assert.equal(publications[0]?.authorization, "Bearer credential-1");
382 assert.equal(publications[1]?.authorization, "Bearer credential-2");
383 yield* secrets.set(
384 RELAY_URL_SECRET,
385 new TextEncoder().encode("https://new-relay.example.test"),
386 );
387 yield* relay.publishThread(THREAD_ID);
388 assert.equal(publications.length, 3);
389 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
390 }),
391 );
392
393 it.effect.each(["completed", "failed"] as const)(
394 "publishes a tombstone when a %s thread is settled through a domain event",
395 (status) =>
396 Effect.gen(function* () {
397 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
398 const pulls = yield* Queue.unbounded<void>();
399 const { relay, currentShell, publications } = yield* makeTestRelay({
400 domainEvents: Stream.fromEffectRepeat(
401 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
402 ),
403 });
404 yield* relay.start();
405 yield* Queue.take(pulls);
406 yield* relay.publishThread(THREAD_ID);
407 const terminal = shell({ status });
408 yield* Ref.set(currentShell, terminal);
409 yield* relay.publishThread(THREAD_ID);
410 yield* TestClock.adjust("5 seconds");
411 yield* relay.drain;
412 assert.equal(publications[1]?.state?.phase, status);
413
414 const now = yield* DateTime.now;
415 const settled = {
416 ...terminal,
417 settledOverride: "settled" as const,
418 settledAt: now,
419 lastVisitedAt: null,
420 };
421 yield* Ref.set(currentShell, settled);
422 yield* Queue.offer(events, {
423 id: EventId.make("event:settled"),
424 type: "thread.settled",
425 threadId: THREAD_ID,
426 occurredAt: now,
427 payload: settled,
428 });
429 yield* Queue.take(pulls);
430 yield* relay.drain;
431 assert.equal(publications.length, 2);
432 yield* TestClock.adjust("5 seconds");
433 yield* relay.drain;
434 assert.equal(publications.length, 3);
435 assert.equal(publications[2]?.state, null);
436 }).pipe(Effect.scoped),
437 );
438
439 it.effect("holds a completion through a continuation gap, then publishes it once", () =>
440 Effect.gen(function* () {
441 const { relay, currentShell, publications } = yield* makeTestRelay();
442 yield* relay.publishThread(THREAD_ID);
443 yield* Ref.set(currentShell, shell({ status: "completed" }));
444 yield* relay.publishThread(THREAD_ID);
445 yield* Ref.set(currentShell, shell());
446 yield* relay.publishThread(THREAD_ID);
447 yield* TestClock.adjust("5 seconds");
448 yield* relay.drain;
449 assert.deepEqual(
450 publications.map((publication) => publication.state?.phase),
451 ["running"],
452 );
453
454 yield* Ref.set(currentShell, shell({ status: "completed" }));
455 yield* relay.publishThread(THREAD_ID);
456 assert.equal(publications.length, 1);
457 yield* TestClock.adjust("5 seconds");
458 yield* relay.drain;
459 assert.deepEqual(
460 publications.map((publication) => publication.state?.phase),
461 ["running", "completed"],
462 );
463 }),
464 );
465
466 it.effect("still publishes a completion when the thread settles during the hold", () =>
467 Effect.gen(function* () {
468 const { relay, currentShell, publications } = yield* makeTestRelay();
469 yield* relay.publishThread(THREAD_ID);
470 const completed = shell({ status: "completed" });
471 yield* Ref.set(currentShell, completed);
472 yield* relay.publishThread(THREAD_ID);
473 yield* Ref.set(currentShell, {
474 ...completed,
475 settledOverride: "settled",
476 settledAt: yield* DateTime.now,
477 lastVisitedAt: null,
478 });
479 yield* relay.publishThread(THREAD_ID);
480 yield* TestClock.adjust("5 seconds");
481 yield* relay.drain;
482 assert.deepEqual(
483 publications.map((publication) => publication.state?.phase ?? null),
484 ["running", "completed"],
485 );
486
487 yield* TestClock.adjust("5 seconds");
488 yield* relay.drain;
489 assert.deepEqual(
490 publications.map((publication) => publication.state?.phase ?? null),
491 ["running", "completed", null],
492 );
493 }),
494 );
495
496 it.effect("publishes a cleared thread's tombstone once while it stays cleared", () =>
497 Effect.gen(function* () {
498 const { relay, currentShell, publications } = yield* makeTestRelay();
499 yield* relay.publishThread(THREAD_ID);
500 const completed = shell({ status: "completed" });
501 yield* Ref.set(currentShell, completed);
502 yield* relay.publishThread(THREAD_ID);
503 yield* TestClock.adjust("5 seconds");
504 yield* relay.drain;
505 yield* Ref.set(currentShell, {
506 ...completed,
507 settledOverride: "settled",
508 settledAt: yield* DateTime.now,
509 lastVisitedAt: null,
510 });
511 yield* relay.publishThread(THREAD_ID);
512 yield* TestClock.adjust("5 seconds");
513 yield* relay.drain;
514 assert.deepEqual(
515 publications.map((publication) => publication.state?.phase ?? null),
516 ["running", "completed", null],
517 );
518
519 for (let i = 0; i < 3; i++) {
520 yield* relay.publishThread(THREAD_ID);
521 yield* TestClock.adjust("5 seconds");
522 yield* relay.drain;
523 }
524 assert.deepEqual(
525 publications.map((publication) => publication.state?.phase ?? null),
526 ["running", "completed", null],
527 );
528 }),
529 );
530
531 it.effect("does not alert an old completion after publishing its thread's tombstone", () =>
532 Effect.gen(function* () {
533 const oldCompleted = shell({
534 status: "completed",
535 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
536 });
537 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
538 const { relay, currentShell, publications } = yield* makeTestRelay();
539 yield* Ref.set(currentShell, {
540 ...oldCompleted,
541 settledOverride: "settled",
542 settledAt: DateTime.makeUnsafe(NOW),
543 lastVisitedAt: null,
544 });
545 yield* relay.publishThread(THREAD_ID);
546 yield* TestClock.adjust("5 seconds");
547 yield* relay.drain;
548 assert.deepEqual(
549 publications.map((publication) => publication.state),
550 [null],
551 );
552
553 yield* Ref.set(currentShell, oldCompleted);
554 yield* relay.publishThread(THREAD_ID);
555 yield* TestClock.adjust("5 seconds");
556 yield* relay.drain;
557 assert.deepEqual(
558 publications.map((publication) => publication.state),
559 [null],
560 );
561 }),
562 );
563
564 it.effect("alerts a completion settled during its hold after an earlier tombstone", () =>
565 Effect.gen(function* () {
566 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW)));
567 const { relay, currentShell, publications } = yield* makeTestRelay();
568 const settledAt = DateTime.makeUnsafe(NOW);
569 yield* Ref.set(currentShell, {
570 ...shell({ status: "completed" }),
571 settledOverride: "settled",
572 settledAt,
573 lastVisitedAt: null,
574 });
575 yield* relay.publishThread(THREAD_ID);
576 yield* TestClock.adjust("5 seconds");
577 yield* relay.drain;
578
579 const completed = shell({
580 status: "completed",
581 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:06.000Z"),
582 });
583 yield* Ref.set(currentShell, completed);
584 yield* relay.publishThread(THREAD_ID);
585 yield* Ref.set(currentShell, {
586 ...completed,
587 settledOverride: "settled",
588 settledAt,
589 lastVisitedAt: null,
590 });
591 yield* relay.publishThread(THREAD_ID);
592 yield* TestClock.adjust("5 seconds");
593 yield* relay.drain;
594 yield* TestClock.adjust("5 seconds");
595 yield* relay.drain;
596 assert.deepEqual(
597 publications.map((publication) => publication.state?.phase ?? null),
598 [null, "completed", null],
599 );
600 }),
601 );
602
603 it.effect("drops a held completion when a queued continuation hides the thread", () =>
604 Effect.gen(function* () {
605 const { relay, currentShell, publications } = yield* makeTestRelay();
606 yield* relay.publishThread(THREAD_ID);
607 yield* Ref.set(currentShell, shell({ status: "completed" }));
608 yield* relay.publishThread(THREAD_ID);
609 yield* Ref.set(currentShell, shell({ status: "queued" }));
610 yield* relay.publishThread(THREAD_ID);
611 yield* TestClock.adjust("5 seconds");
612 yield* relay.drain;
613 assert.notInclude(
614 publications.map((publication) => publication.state?.phase ?? null),
615 "completed",
616 );
617 }),
618 );
619
620 it.effect("retries a failed completion even after the thread settles", () =>
621 Effect.gen(function* () {
622 const { relay, currentShell, publications } = yield* makeTestRelay({
623 respond: (attempt) =>
624 attempt === 2
625 ? new Response("unavailable", { status: 503 })
626 : Response.json({ ok: true, deliveries: [] }),
627 });
628 yield* relay.publishThread(THREAD_ID);
629 const completed = shell({ status: "completed" });
630 yield* Ref.set(currentShell, completed);
631 yield* relay.publishThread(THREAD_ID);
632 yield* TestClock.adjust("5 seconds");
633 yield* relay.drain;
634 yield* Ref.set(currentShell, {
635 ...completed,
636 settledOverride: "settled",
637 settledAt: yield* DateTime.now,
638 lastVisitedAt: null,
639 });
640 yield* TestClock.adjust("1 second");
641 yield* relay.drain;
642 assert.deepEqual(
643 publications.map((publication) => publication.state?.phase ?? null),
644 ["running", "completed", "completed"],
645 );
646
647 yield* TestClock.adjust("5 seconds");
648 yield* relay.drain;
649 assert.equal(publications.at(-1)?.state ?? null, null);
650 }),
651 );
652
653 it.effect("keeps settled live work until its awaited monitor finishes", () =>
654 Effect.gen(function* () {
655 const { relay, currentShell, publications } = yield* makeTestRelay();
656 yield* relay.publishThread(THREAD_ID);
657 const held = shell({
658 status: "completed",
659 settledOverride: "settled",
660 pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
661 });
662 yield* Ref.set(currentShell, held);
663 yield* relay.publishThread(THREAD_ID);
664 yield* TestClock.adjust("5 seconds");
665 yield* relay.drain;
666 assert.equal(publications.length, 1);
667 assert.equal(publications[0]?.state?.phase, "running");
668
669 yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
670 yield* relay.publishThread(THREAD_ID);
671 yield* TestClock.adjust("5 seconds");
672 yield* relay.drain;
673 assert.equal(publications.length, 2);
674 assert.equal(publications[1]?.state, null);
675 }),
676 );
677 it.effect("publishes a held completion when its background item ends, not on tool output", () =>
678 Effect.gen(function* () {
679 const store = yield* ProjectionStore.ProjectionStoreV2;
680 const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
681 const pulls = yield* Queue.unbounded<void>();
682 const { relay, shellReads, publications } = yield* makeTestRelay({
683 readShell: (threadId) => store.getThreadShell(threadId).pipe(Effect.orDie),
684 domainEvents: Stream.fromEffectRepeat(
685 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
686 ),
687 });
688 yield* relay.start();
689 yield* Queue.take(pulls);
690 const deliver = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) {
691 yield* store.apply(event);
692 yield* Queue.offer(events, event);
693 yield* Queue.take(pulls);
694 yield* relay.drain;
695 });
696
697 const now = yield* DateTime.now;
698 const runId = RunId.make("run:held-item");
699 const run = {
700 id: runId,
701 threadId: THREAD_ID,
702 ordinal: 1,
703 providerInstanceId: ProviderInstanceId.make("codex"),
704 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
705 providerThreadId: null,
706 userMessageId: MessageId.make("message:held-item"),
707 rootNodeId: null,
708 activeAttemptId: null,
709 status: "running" as const,
710 requestedAt: now,
711 startedAt: now,
712 completedAt: null,
713 checkpointId: null,
714 contextHandoffId: null,
715 };
716 const item = (
717 id: string,
718 fields: Pick<OrchestrationV2TurnItem, "status"> &
719 (
720 | { readonly type: "dynamic_tool"; readonly toolName: string; readonly input: unknown }
721 | {
722 readonly type: "assistant_message";
723 readonly messageId: MessageId;
724 readonly text: string;
725 readonly streaming: boolean;
726 }
727 ),
728 ): OrchestrationV2TurnItem => ({
729 id: TurnItemId.make(id),
730 threadId: THREAD_ID,
731 runId,
732 nodeId: NodeId.make("node:held-item"),
733 providerThreadId: null,
734 providerTurnId: null,
735 nativeItemRef: null,
736 parentItemId: null,
737 ordinal: 1,
738 title: null,
739 startedAt: now,
740 completedAt: null,
741 updatedAt: now,
742 ...fields,
743 });
744 const itemEvent = (id: string, payload: OrchestrationV2TurnItem) =>
745 ({
746 id: EventId.make(id),
747 type: "turn-item.updated",
748 threadId: THREAD_ID,
749 runId,
750 occurredAt: now,
751 payload,
752 }) satisfies OrchestrationV2DomainEvent;
753 const background = { type: "dynamic_tool" as const, toolName: "watch", input: {} };
754
755 yield* deliver({
756 id: EventId.make("event:held-item:thread"),
757 type: "thread.created",
758 threadId: THREAD_ID,
759 occurredAt: now,
760 payload: {
761 createdBy: "user",
762 creationSource: "web",
763 id: THREAD_ID,
764 projectId: PROJECT_ID,
765 title: "Thread",
766 providerInstanceId: ProviderInstanceId.make("codex"),
767 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
768 runtimeMode: "full-access",
769 interactionMode: "default",
770 branch: null,
771 worktreePath: null,
772 activeProviderThreadId: null,
773 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
774 forkedFrom: null,
775 createdAt: now,
776 updatedAt: now,
777 archivedAt: null,
778 settledOverride: null,
779 settledAt: null,
780 lastVisitedAt: null,
781 deletedAt: null,
782 },
783 });
784 yield* deliver({
785 id: EventId.make("event:held-item:run"),
786 type: "run.created",
787 threadId: THREAD_ID,
788 runId,
789 occurredAt: now,
790 payload: run,
791 });
792 yield* deliver(
793 itemEvent("event:held-item:tool", item("item:tool", { ...background, status: "running" })),
794 );
795 yield* deliver({
796 id: EventId.make("event:held-item:run-completed"),
797 type: "run.updated",
798 threadId: THREAD_ID,
799 runId,
800 occurredAt: now,
801 payload: { ...run, status: "completed", completedAt: now },
802 });
803 assert.deepEqual(
804 publications.map((publication) => publication.state?.phase),
805 ["running"],
806 );
807
808 const readsBeforeOutput = shellReads.length;
809 yield* deliver(
810 itemEvent(
811 "event:held-item:reply",
812 item("item:reply", {
813 type: "assistant_message",
814 messageId: MessageId.make("message:held-item:reply"),
815 text: "Still watching",
816 streaming: true,
817 status: "running",
818 }),
819 ),
820 );
821 yield* deliver(
822 itemEvent("event:held-item:tick", item("item:tool", { ...background, status: "running" })),
823 );
824 assert.equal(shellReads.length, readsBeforeOutput);
825
826 yield* deliver(
827 itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })),
828 );
829 yield* TestClock.adjust("5 seconds");
830 yield* relay.drain;
831 assert.deepEqual(
832 publications.map((publication) => publication.state?.phase),
833 ["running", "completed"],
834 );
835 }).pipe(
836 Effect.scoped,
837 Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
838 ),
839 );
840});
841
842it.effect("catches up after startup without polling after success", () =>
843 Effect.gen(function* () {
844 const { relay, secrets, secretReads, catchUp, publications } = yield* makeTestRelay({
845 catchUpThreads: [shell()],
846 });
847 yield* relay.start();
848 yield* TestClock.adjust("1 second");
849 yield* relay.drain;
850 assert.equal(catchUp.activitySnapshotReads, 1);
851 assert.equal(publications.length, 1);
852 assert.include(publications[0]?.state, {
853 threadId: THREAD_ID,
854 projectTitle: "Project",
855 threadTitle: "Thread",
856 phase: "running",
857 });
858
859 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
860 yield* relay.requestCatchUp();
861 yield* TestClock.adjust("1 second");
862 assert.equal(catchUp.activitySnapshotReads, 1);
863
864 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
865 yield* relay.requestCatchUp();
866 yield* TestClock.adjust("1 second");
867 assert.equal(catchUp.activitySnapshotReads, 2);
868
869 const readsBeforeIdle = secretReads.length;
870 yield* TestClock.adjust("10 minutes");
871 assert.equal(catchUp.activitySnapshotReads, 2);
872 assert.equal(secretReads.length, readsBeforeIdle);
873
874 yield* secrets.set(
875 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
876 new TextEncoder().encode("credential-2"),
877 );
878 yield* relay.requestCatchUp();
879 yield* TestClock.adjust("1 second");
880 yield* relay.drain;
881 assert.equal(catchUp.activitySnapshotReads, 3);
882 assert.equal(publications.length, 2);
883 assert.equal(publications[1]?.state?.threadId, THREAD_ID);
884 }).pipe(Effect.scoped),
885);