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 type OrchestrationV2ThreadShell,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9} from "@t3tools/contracts";
10import { RelayAgentActivityState } from "@t3tools/contracts/relay";
11import * as DateTime from "effect/DateTime";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Option from "effect/Option";
16import * as Ref from "effect/Ref";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import * as TestClock from "effect/testing/TestClock";
20import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";
21
22import { SecretStoreReadError, ServerSecretStore } from "../auth/ServerSecretStore.ts";
23import {
24 PUBLISH_AGENT_ACTIVITY_SECRET,
25 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
26 RELAY_ISSUER_SECRET,
27 RELAY_URL_SECRET,
28} from "../cloud/config.ts";
29import { ServerEnvironment } from "../environment/ServerEnvironment.ts";
30import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
31import { ProjectService } from "../project/ProjectService.ts";
32import {
33 make,
34 makeAgentAwarenessPublishWorker,
35 resolveAgentAwarenessRelayActiveThreadIds,
36 shouldPublishAgentAwarenessEvent,
37} from "./AgentAwarenessRelay.ts";
38
39const THREAD_ID = ThreadId.make("relay-thread");
40const SECOND_THREAD_ID = ThreadId.make("relay-thread-2");
41const PROJECT_ID = ProjectId.make("relay-project");
42const NOW = "2026-09-04T12:00:00.000Z";
43
44function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
45 return {
46 id: THREAD_ID,
47 projectId: PROJECT_ID,
48 title: "Thread",
49 providerInstanceId: ProviderInstanceId.make("codex"),
50 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test-model" },
51 runtimeMode: "full-access",
52 interactionMode: "default",
53 worktreePath: null,
54 activeProviderThreadId: null,
55 lineage: { rootThreadId: THREAD_ID, parentThreadId: null, relationshipToParent: null },
56 forkedFrom: null,
57 createdBy: "user",
58 creationSource: "web",
59 activeRunId: null,
60 latestVisibleMessage: null,
61 hasActionableProposedPlan: false,
62 itemCount: 0,
63 visibleItemCount: 0,
64 lastVisitedAt: null,
65 deletedAt: null,
66 branch: null,
67 linkedPullRequest: null,
68 status: "running",
69 activityRunStatus: null,
70 pendingRuntimeRequest: null,
71 pendingBackgroundTasks: [],
72 latestRunId: null,
73 latestRunRequestedAt: null,
74 latestRunStartedAt: null,
75 latestRunCompletedAt: null,
76 latestUserMessageAt: null,
77 createdAt: DateTime.makeUnsafe(NOW),
78 updatedAt: DateTime.makeUnsafe(NOW),
79 archivedAt: null,
80 settledOverride: null,
81 settledAt: null,
82 snoozedUntil: null,
83 snoozedAt: null,
84 pinnedAt: null,
85 ...overrides,
86 };
87}
88
89const PublishPayload = Schema.Struct({ state: Schema.NullOr(RelayAgentActivityState) });
90const decodePublishPayload = Schema.decodeUnknownSync(Schema.fromJsonString(PublishPayload));
91const unused = () => Effect.die("Unexpected test dependency call");
92
93describe("startup agent activity", () => {
94 it("publishes active work and only terminal runs completed after startup", () => {
95 const startedAt = DateTime.toEpochMillis(DateTime.makeUnsafe(NOW));
96 const oldCompleted = ThreadId.make("old-completed");
97 const newCompleted = ThreadId.make("new-completed");
98 const oldFailed = ThreadId.make("old-failed");
99 const newFailed = ThreadId.make("new-failed");
100 const ids = resolveAgentAwarenessRelayActiveThreadIds({
101 environmentId: EnvironmentId.make("relay-env"),
102 startedAt,
103 projects: [{ id: PROJECT_ID, title: "Project" }],
104 threads: [
105 shell(),
106 shell({
107 id: oldCompleted,
108 status: "completed",
109 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
110 }),
111 shell({
112 id: newCompleted,
113 status: "completed",
114 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
115 }),
116 shell({
117 id: oldFailed,
118 status: "failed",
119 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"),
120 }),
121 shell({
122 id: newFailed,
123 status: "failed",
124 latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:01.000Z"),
125 }),
126 shell({ id: ThreadId.make("idle"), status: "idle" }),
127 shell({ id: ThreadId.make("missing-project"), projectId: ProjectId.make("missing") }),
128 ],
129 });
130 assert.deepStrictEqual(ids, [THREAD_ID, newCompleted, newFailed]);
131 });
132});
133
134const makeTestRelay = Effect.fnUntraced(function* (
135 options: {
136 readonly respond?: (attempt: number) => Response;
137 readonly failSecretRead?: (name: string) => boolean;
138 } = {},
139) {
140 const values = new Map<string, Uint8Array>([
141 [PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")],
142 [RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")],
143 [RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")],
144 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")],
145 ]);
146 const secretReads: string[] = [];
147 const secrets = ServerSecretStore.of({
148 get: (name) =>
149 Effect.suspend(() => {
150 secretReads.push(name);
151 if (options.failSecretRead?.(name)) {
152 return Effect.fail(
153 new SecretStoreReadError({ resource: name, cause: "temporary read failure" }),
154 );
155 }
156 return Effect.succeed(Option.fromUndefinedOr(values.get(name)));
157 }),
158 create: (name, value) => Effect.sync(() => void values.set(name, value)),
159 set: (name, value) => Effect.sync(() => void values.set(name, value)),
160 remove: (name) => Effect.sync(() => void values.delete(name)),
161 getOrCreateRandom: unused,
162 });
163 const currentShell = yield* Ref.make<OrchestrationV2ThreadShell | null>(shell());
164 const shellReads: ThreadId[] = [];
165 const threads = ThreadManagementService.of({
166 getThreadShell: (threadId) =>
167 Effect.sync(() => shellReads.push(threadId)).pipe(Effect.andThen(Ref.get(currentShell))),
168 getShellSnapshot: unused,
169 ensureLegacyTranscript: unused,
170 dispatch: unused,
171 getTimelinePage: () => Effect.die("Unused timeline read"),
172 getMessageCount: () => Effect.die("unused message count"),
173 getThreadRecords: () => Effect.die("unused record read"),
174 getThreadProjection: unused,
175 getCheckpointContext: unused,
176 getThreadSnapshot: unused,
177 getThreadSnapshotWindow: unused,
178 getProjectThreadRecords: () => Effect.die("unused project record read"),
179 getProjectThread: unused,
180 listProjectThreads: unused,
181 sendToThread: unused,
182 waitForThread: unused,
183 interruptThread: unused,
184 getThreadEventSequence: unused,
185 streamStoredEvents: Stream.empty,
186 streamStoredEventsFrom: () => Stream.empty,
187 streamDomainEvents: Stream.empty,
188 });
189 const publications: Array<{
190 readonly url: string;
191 readonly authorization: string | null;
192 readonly state: RelayAgentActivityState | null;
193 }> = [];
194 const fetch: typeof globalThis.fetch = Object.assign(
195 (
196 input: Parameters<typeof globalThis.fetch>[0],
197 init?: Parameters<typeof globalThis.fetch>[1],
198 ) => {
199 const body = init?.body;
200 if (typeof body !== "string" && !(body instanceof Uint8Array)) {
201 return Promise.reject(new Error("Expected a serialized activity publish payload"));
202 }
203 const payload = decodePublishPayload(
204 typeof body === "string" ? body : new TextDecoder().decode(body),
205 );
206 publications.push({
207 url: String(input),
208 authorization: new Headers(init?.headers).get("authorization"),
209 state: payload.state,
210 });
211 return Promise.resolve(
212 options.respond?.(publications.length) ?? Response.json({ ok: true, deliveries: [] }),
213 );
214 },
215 { preconnect: () => {} },
216 );
217 const relay = yield* make.pipe(
218 Effect.provideService(ServerSecretStore, secrets),
219 Effect.provideService(ThreadManagementService, threads),
220 Effect.provideService(ServerEnvironment, {
221 getEnvironmentId: Effect.succeed(EnvironmentId.make("relay-environment")),
222 getDescriptor: unused(),
223 }),
224 Effect.provideService(ProjectService, {
225 create: unused,
226 bootstrap: unused,
227 update: unused,
228 delete: unused,
229 getByWorkspaceRoot: unused,
230 snapshot: unused(),
231 getById: () =>
232 Effect.succeed(
233 Option.some({
234 id: PROJECT_ID,
235 title: "Project",
236 workspaceRoot: "/workspace",
237 defaultModelSelection: null,
238 scripts: [],
239 createdAt: NOW,
240 updatedAt: NOW,
241 deletedAt: null,
242 }),
243 ),
244 }),
245 Effect.provideService(FetchHttpClient.Fetch, fetch),
246 Effect.provide(NodeCrypto.layer),
247 );
248 return { relay, secrets, secretReads, currentShell, shellReads, publications };
249});
250
251describe("AgentAwarenessRelay", () => {
252 it("ignores transcript and tool updates but retains activity and metadata changes", () => {
253 for (const type of [
254 "message.updated",
255 "turn-item.updated",
256 "provider-turn.updated",
257 "thread.visited",
258 "thread.pinned",
259 ] as const) {
260 assert.isFalse(shouldPublishAgentAwarenessEvent({ type }));
261 }
262 for (const type of [
263 "run.created",
264 "run.updated",
265 "runtime-request.updated",
266 "thread.metadata-updated",
267 "thread.model-selection-updated",
268 "thread.provider-switched",
269 "thread.archived",
270 "thread.unarchived",
271 "thread.deleted",
272 ] as const) {
273 assert.isTrue(shouldPublishAgentAwarenessEvent({ type }));
274 }
275 });
276
277 it("does not publish imported thread creation as new agent activity", () => {
278 assert.isFalse(
279 shouldPublishAgentAwarenessEvent({
280 type: "thread.created",
281 payload: { historyOrigin: "v1_import" },
282 }),
283 );
284 assert.isTrue(shouldPublishAgentAwarenessEvent({ type: "thread.created", payload: {} }));
285 });
286
287 it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () =>
288 Effect.gen(function* () {
289 const started = yield* Deferred.make<void>();
290 const release = yield* Deferred.make<void>();
291 const rerunStarted = yield* Deferred.make<void>();
292 const releaseRerun = yield* Deferred.make<void>();
293 const processed: Array<{ threadId: ThreadId; revision: number }> = [];
294 let revision = 1;
295 const worker = yield* makeAgentAwarenessPublishWorker((threadId) =>
296 Effect.gen(function* () {
297 const currentRevision = revision;
298 const index = processed.length;
299 processed.push({ threadId, revision: currentRevision });
300 if (index === 0) {
301 yield* Deferred.succeed(started, undefined);
302 yield* Deferred.await(release);
303 } else if (threadId === THREAD_ID) {
304 yield* Deferred.succeed(rerunStarted, undefined);
305 yield* Deferred.await(releaseRerun);
306 }
307 }),
308 );
309 yield* worker.enqueue(THREAD_ID);
310 yield* Deferred.await(started);
311 revision = 2;
312 for (let i = 0; i < 100; i++) {
313 yield* worker.enqueue(SECOND_THREAD_ID);
314 yield* worker.enqueue(THREAD_ID);
315 }
316 const drained = yield* Deferred.make<void>();
317 const draining = yield* worker.drain.pipe(
318 Effect.andThen(Deferred.succeed(drained, undefined)),
319 Effect.forkChild,
320 );
321 yield* Deferred.succeed(release, undefined);
322 yield* Deferred.await(rerunStarted);
323 assert.isFalse(yield* Deferred.isDone(drained));
324 yield* Deferred.succeed(releaseRerun, undefined);
325 yield* Fiber.join(draining);
326 assert.deepEqual(processed, [
327 { threadId: THREAD_ID, revision: 1 },
328 { threadId: SECOND_THREAD_ID, revision: 2 },
329 { threadId: THREAD_ID, revision: 2 },
330 ]);
331 }),
332 );
333
334 it.effect("deduplicates state and republishes title changes", () =>
335 Effect.gen(function* () {
336 const { relay, currentShell, publications } = yield* makeTestRelay();
337 yield* relay.publishThread(THREAD_ID);
338 yield* Ref.set(
339 currentShell,
340 shell({ updatedAt: DateTime.makeUnsafe("2026-09-04T13:00:00Z") }),
341 );
342 yield* relay.publishThread(THREAD_ID);
343 assert.equal(publications.length, 1);
344 yield* Ref.set(currentShell, shell({ title: "Renamed thread" }));
345 yield* relay.publishThread(THREAD_ID);
346 assert.equal(publications.length, 2);
347 assert.equal(publications[1]?.state?.threadTitle, "Renamed thread");
348 }),
349 );
350
351 it.effect("stops before shell reads when disabled and republishes after re-enabling", () =>
352 Effect.gen(function* () {
353 const { relay, secrets, secretReads, shellReads, publications } = yield* makeTestRelay();
354 yield* relay.publishThread(THREAD_ID);
355 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
356 const previousReads = secretReads.length;
357 yield* relay.publishThread(THREAD_ID);
358 assert.deepEqual(secretReads.slice(previousReads), [PUBLISH_AGENT_ACTIVITY_SECRET]);
359 assert.equal(shellReads.length, 1);
360 assert.equal(publications.length, 1);
361 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true"));
362 yield* relay.publishThread(THREAD_ID);
363 assert.equal(publications.length, 2);
364 }),
365 );
366
367 it.effect("republishes unchanged state with fresh credentials after relinking", () =>
368 Effect.gen(function* () {
369 const { relay, secrets, publications } = yield* makeTestRelay();
370 yield* relay.publishThread(THREAD_ID);
371 yield* secrets.set(
372 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
373 new TextEncoder().encode("credential-2"),
374 );
375 yield* relay.publishThread(THREAD_ID);
376 assert.equal(publications.length, 2);
377 assert.equal(publications[0]?.authorization, "Bearer credential-1");
378 assert.equal(publications[1]?.authorization, "Bearer credential-2");
379 yield* secrets.set(
380 RELAY_URL_SECRET,
381 new TextEncoder().encode("https://new-relay.example.test"),
382 );
383 yield* relay.publishThread(THREAD_ID);
384 assert.equal(publications.length, 3);
385 assert.isTrue(publications[2]?.url.startsWith("https://new-relay.example.test/") ?? false);
386 }),
387 );
388
389 it.effect("retries a failed final state without another thread event", () =>
390 Effect.gen(function* () {
391 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
392 respond: (attempt) =>
393 attempt === 2
394 ? new Response("relay unavailable", { status: 503 })
395 : Response.json({ ok: true, deliveries: [] }),
396 });
397 yield* relay.publishThread(THREAD_ID);
398 yield* Ref.set(
399 currentShell,
400 shell({
401 status: "completed",
402 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
403 }),
404 );
405 yield* relay.publishThread(THREAD_ID);
406 assert.equal(publications.length, 2);
407 yield* TestClock.adjust("1 second");
408 yield* relay.drain;
409 assert.equal(publications.length, 3);
410 assert.equal(publications[2]?.state?.phase, "completed");
411 yield* TestClock.adjust("1 minute");
412 yield* relay.drain;
413 assert.equal(shellReads.length, 3);
414 }),
415 );
416
417 it.effect("retries the latest shell and credentials with first-completion confirmation", () =>
418 Effect.gen(function* () {
419 const { relay, secrets, currentShell, publications } = yield* makeTestRelay({
420 respond: (attempt) =>
421 attempt === 1
422 ? new Response("relay unavailable", { status: 503 })
423 : Response.json({ ok: true, deliveries: [] }),
424 });
425 yield* relay.publishThread(THREAD_ID);
426 yield* Ref.set(
427 currentShell,
428 shell({
429 status: "completed",
430 title: "Final title",
431 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
432 }),
433 );
434 yield* secrets.set(
435 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
436 new TextEncoder().encode("credential-2"),
437 );
438 yield* TestClock.adjust("1 second");
439 yield* relay.drain;
440 assert.equal(publications.length, 1);
441 yield* TestClock.adjust("5 seconds");
442 yield* relay.drain;
443 assert.equal(publications.length, 2);
444 assert.equal(publications[1]?.authorization, "Bearer credential-2");
445 assert.equal(publications[1]?.state?.phase, "completed");
446 assert.equal(publications[1]?.state?.threadTitle, "Final title");
447 }),
448 );
449
450 it.effect("cancels a stale retry when a newer update publishes successfully", () =>
451 Effect.gen(function* () {
452 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
453 respond: (attempt) =>
454 attempt === 1
455 ? new Response("relay unavailable", { status: 503 })
456 : Response.json({ ok: true, deliveries: [] }),
457 });
458 yield* relay.publishThread(THREAD_ID);
459 yield* Ref.set(currentShell, shell({ title: "New title" }));
460 yield* relay.publishThread(THREAD_ID);
461 assert.equal(publications.length, 2);
462 assert.equal(publications[1]?.state?.threadTitle, "New title");
463 yield* TestClock.adjust("1 minute");
464 yield* relay.drain;
465 assert.equal(shellReads.length, 2);
466 }),
467 );
468
469 it.effect.each(["disable", "unlink"] as const)(
470 "stops retries before shell reads after %s",
471 (change) =>
472 Effect.gen(function* () {
473 const { relay, secrets, shellReads, publications } = yield* makeTestRelay({
474 respond: () => new Response("relay unavailable", { status: 503 }),
475 });
476 yield* relay.publishThread(THREAD_ID);
477 if (change === "disable") {
478 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
479 } else {
480 yield* secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET);
481 }
482 yield* TestClock.adjust("1 second");
483 yield* relay.drain;
484 yield* TestClock.adjust("1 minute");
485 yield* relay.drain;
486 assert.equal(publications.length, 1);
487 assert.equal(shellReads.length, 1);
488 }),
489 );
490
491 it.effect("recovers from a transient configuration read failure", () =>
492 Effect.gen(function* () {
493 let failRead = false;
494 const { relay, shellReads, publications } = yield* makeTestRelay({
495 failSecretRead: (name) => failRead && name === PUBLISH_AGENT_ACTIVITY_SECRET,
496 });
497 failRead = true;
498 yield* relay.publishThread(THREAD_ID);
499 assert.equal(shellReads.length, 0);
500 failRead = false;
501 yield* TestClock.adjust("1 second");
502 yield* relay.drain;
503 assert.equal(publications.length, 1);
504 assert.equal(publications[0]?.state?.phase, "running");
505 }),
506 );
507
508 it.effect("bounds retry attempts and resets the budget for a newer update", () =>
509 Effect.gen(function* () {
510 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
511 respond: () => new Response("relay unavailable", { status: 503 }),
512 });
513 yield* relay.publishThread(THREAD_ID);
514 let attempts = 1;
515 for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) {
516 yield* TestClock.adjust(delay - 1);
517 yield* relay.drain;
518 assert.equal(publications.length, attempts);
519 yield* TestClock.adjust(1);
520 yield* relay.drain;
521 attempts += 1;
522 assert.equal(publications.length, attempts);
523 }
524 yield* TestClock.adjust("1 minute");
525 yield* relay.drain;
526 assert.equal(publications.length, 6);
527 assert.equal(shellReads.length, 6);
528 yield* Ref.set(currentShell, shell({ title: "New update" }));
529 yield* relay.publishThread(THREAD_ID);
530 yield* TestClock.adjust("1 second");
531 yield* relay.drain;
532 assert.equal(publications.length, 8);
533 assert.equal(publications[7]?.state?.threadTitle, "New update");
534 }),
535 );
536
537 it.effect("retries a confirmed completion without restarting its confirmation window", () =>
538 Effect.gen(function* () {
539 const { relay, currentShell, publications } = yield* makeTestRelay({
540 respond: (attempt) =>
541 attempt <= 2
542 ? new Response("relay unavailable", { status: 503 })
543 : Response.json({ ok: true, deliveries: [] }),
544 });
545 yield* Ref.set(
546 currentShell,
547 shell({
548 status: "completed",
549 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
550 }),
551 );
552 yield* relay.publishThread(THREAD_ID);
553 yield* TestClock.adjust("5 seconds");
554 yield* relay.drain;
555 assert.equal(publications.length, 1);
556 yield* TestClock.adjust("1 second");
557 yield* relay.drain;
558 assert.equal(publications.length, 2);
559 yield* TestClock.adjust("2 seconds");
560 yield* relay.drain;
561 assert.equal(publications.length, 3);
562 assert.isTrue(publications.every((publication) => publication.state?.phase === "completed"));
563 yield* TestClock.adjust("1 minute");
564 yield* relay.drain;
565 assert.equal(publications.length, 3);
566 }),
567 );
568
569 it.effect("does not reset an exhausted retry budget for old confirmation timers", () =>
570 Effect.gen(function* () {
571 let unavailable = false;
572 const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({
573 respond: () =>
574 unavailable
575 ? new Response("relay unavailable", { status: 503 })
576 : Response.json({ ok: true, deliveries: [] }),
577 });
578 yield* relay.publishThread(THREAD_ID);
579 // Leave six obsolete confirmations at 5,000 through 5,005 milliseconds.
580 for (let i = 0; i < 6; i++) {
581 yield* Ref.set(currentShell, null);
582 yield* relay.publishThread(THREAD_ID);
583 yield* Ref.set(currentShell, shell());
584 yield* relay.publishThread(THREAD_ID);
585 yield* TestClock.adjust(1);
586 }
587 unavailable = true;
588 yield* Ref.set(currentShell, shell({ status: "failed" }));
589 yield* relay.publishThread(THREAD_ID);
590 yield* TestClock.adjust(1_000);
591 yield* relay.drain;
592 yield* TestClock.adjust(2_000);
593 yield* relay.drain;
594 yield* TestClock.adjust(1_994);
595 yield* relay.drain;
596 for (let i = 0; i < 5; i++) {
597 yield* TestClock.adjust(1);
598 yield* relay.drain;
599 }
600 const attempts = publications.length;
601 const reads = shellReads.length;
602 yield* TestClock.adjust("1 minute");
603 yield* relay.drain;
604 assert.equal(publications.length, attempts);
605 assert.equal(shellReads.length, reads);
606 }),
607 );
608
609 it.effect("confirms tombstones and cancels stale confirmations when activity recovers", () =>
610 Effect.gen(function* () {
611 const { relay, currentShell, publications } = yield* makeTestRelay();
612 yield* relay.publishThread(THREAD_ID);
613 yield* Ref.set(currentShell, null);
614 yield* relay.publishThread(THREAD_ID);
615 assert.equal(publications.length, 1);
616 yield* Ref.set(currentShell, shell());
617 yield* relay.publishThread(THREAD_ID);
618 yield* TestClock.adjust("5 seconds");
619 yield* relay.drain;
620 assert.equal(publications.length, 1);
621 yield* Ref.set(currentShell, null);
622 yield* relay.publishThread(THREAD_ID);
623 assert.equal(publications.length, 1);
624 yield* TestClock.adjust("5 seconds");
625 yield* relay.drain;
626 assert.equal(publications.length, 2);
627 assert.equal(publications[1]?.state, null);
628 }),
629 );
630
631 it.effect("confirms a first completed state and respects disabling during confirmation", () =>
632 Effect.gen(function* () {
633 const { relay, secrets, currentShell, publications } = yield* makeTestRelay();
634 yield* Ref.set(
635 currentShell,
636 shell({
637 status: "completed",
638 latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }),
639 }),
640 );
641 yield* relay.publishThread(THREAD_ID);
642 assert.equal(publications.length, 0);
643 yield* TestClock.adjust("5 seconds");
644 yield* relay.drain;
645 assert.equal(publications[0]?.state?.phase, "completed");
646 yield* Ref.set(currentShell, null);
647 yield* relay.publishThread(THREAD_ID);
648 yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false"));
649 yield* TestClock.adjust("5 seconds");
650 yield* relay.drain;
651 assert.equal(publications.length, 1);
652 }),
653 );
654});