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