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