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