Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3
4import type {
5 EnvironmentId,
6 ExecutionEnvironmentDescriptor,
7 OrchestrationEvent,
8 OrchestrationProjectShell,
9 OrchestrationShellSnapshot,
10 OrchestrationThreadShell,
11 ProjectId,
12 ThreadId,
13 TurnId,
14} from "@t3tools/contracts";
15import type {
16 RelayAgentActivityPublishProofPayload,
17 RelayAgentActivityState,
18} from "@t3tools/contracts/relay";
19import { CommandId, ProviderInstanceId } from "@t3tools/contracts";
20import { RelayClientTracer } from "@t3tools/shared/relayTracing";
21import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
22import { describe, expect, it } from "@effect/vitest";
23import * as DateTime from "effect/DateTime";
24import * as Deferred from "effect/Deferred";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Queue from "effect/Queue";
29import * as Stream from "effect/Stream";
30import * as Tracer from "effect/Tracer";
31import * as TestClock from "effect/testing/TestClock";
32
33import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
34import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
35import {
36 OrchestrationEngineService,
37 type OrchestrationEngineShape,
38} from "../orchestration/Services/OrchestrationEngine.ts";
39import {
40 ProjectionSnapshotQuery,
41 type ProjectionSnapshotQueryShape,
42} from "../orchestration/Services/ProjectionSnapshotQuery.ts";
43import {
44 isAgentActivityPublishingEnabledValue,
45 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
46 RELAY_ISSUER_SECRET,
47 RELAY_URL_SECRET,
48 PUBLISH_AGENT_ACTIVITY_SECRET,
49} from "../cloud/config.ts";
50import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";
51
52const state: RelayAgentActivityState = {
53 environmentId: "env" as RelayAgentActivityState["environmentId"],
54 threadId: "thread" as RelayAgentActivityState["threadId"],
55 projectTitle: "Project",
56 threadTitle: "Thread",
57 modelTitle: "gpt-5.4",
58 phase: "running",
59 headline: "Running",
60 updatedAt: "2026-05-25T00:00:00.000Z",
61 deepLink: "/threads/env/thread",
62};
63
64const encodeSecret = (value: string): Uint8Array => new TextEncoder().encode(value);
65
66function makeMemorySecretStore() {
67 const values = new Map<string, Uint8Array>();
68 const store = {
69 get: ((name) =>
70 Effect.sync(() => {
71 const value = values.get(name);
72 return value === undefined ? Option.none() : Option.some(Uint8Array.from(value));
73 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["get"],
74 set: ((name, value) =>
75 Effect.sync(() => {
76 values.set(name, Uint8Array.from(value));
77 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["set"],
78 create: ((name, value) =>
79 Effect.sync(() => {
80 values.set(name, Uint8Array.from(value));
81 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["create"],
82 getOrCreateRandom: ((name, bytes) =>
83 Effect.sync(() => {
84 const existing = values.get(name);
85 if (existing) {
86 return existing;
87 }
88 const generated = new Uint8Array(bytes);
89 values.set(name, generated);
90 return generated;
91 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["getOrCreateRandom"],
92 remove: ((name) =>
93 Effect.sync(() => {
94 values.delete(name);
95 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["remove"],
96 } satisfies ServerSecretStore.ServerSecretStore["Service"];
97 return {
98 store,
99 setString: (name: string, value: string) => store.set(name, encodeSecret(value)),
100 };
101}
102
103describe("signRelayAgentActivityPublishProof", { concurrent: false }, () => {
104 it("distinguishes pending link credentials from disabled publication", () => {
105 expect(
106 AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
107 relayConfigured: false,
108 publishEnabled: false,
109 }),
110 ).toBe("waiting-for-link");
111 expect(
112 AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
113 relayConfigured: true,
114 publishEnabled: false,
115 }),
116 ).toBe("disabled");
117 expect(
118 AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
119 relayConfigured: true,
120 publishEnabled: true,
121 }),
122 ).toBe("enabled");
123 });
124
125 it("derives the thread id from the aggregate id for thread events without payload thread ids", () => {
126 const threadId = "thread-aggregate-1" as ThreadId;
127 const now = "2026-05-25T00:00:00.000Z";
128 const event = {
129 type: "thread.activity-appended",
130 sequence: 1,
131 eventId: "evt-aggregate-1",
132 commandId: CommandId.make("cmd-1"),
133 aggregateKind: "thread",
134 aggregateId: threadId,
135 actor: { kind: "server" },
136 payload: {},
137 occurredAt: now,
138 } as unknown as OrchestrationEvent;
139
140 expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
141 });
142
143 it("does not publish imported, start-intent, streaming, or non-awareness events", () => {
144 const now = "2026-05-25T00:00:00.000Z";
145 const base = {
146 sequence: 1,
147 eventId: "evt-1",
148 commandId: CommandId.make("cmd-1"),
149 aggregateKind: "thread",
150 aggregateId: "thread-1" as ThreadId,
151 occurredAt: now,
152 metadata: {},
153 };
154
155 expect(
156 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
157 ...base,
158 type: "thread.message-sent",
159 payload: {
160 threadId: "thread-1" as ThreadId,
161 streaming: true,
162 },
163 } as unknown as OrchestrationEvent),
164 ).toBe(false);
165 expect(
166 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
167 ...base,
168 type: "thread.activity-appended",
169 payload: {
170 threadId: "thread-1" as ThreadId,
171 activity: {
172 kind: "task.progress",
173 },
174 },
175 } as unknown as OrchestrationEvent),
176 ).toBe(false);
177 expect(
178 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
179 ...base,
180 type: "thread.activity-appended",
181 payload: {
182 threadId: "thread-1" as ThreadId,
183 activity: {
184 kind: "approval.requested",
185 },
186 },
187 } as unknown as OrchestrationEvent),
188 ).toBe(true);
189 expect(
190 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
191 ...base,
192 type: "thread.message-sent",
193 payload: {
194 threadId: "thread-1" as ThreadId,
195 streaming: false,
196 },
197 } as unknown as OrchestrationEvent),
198 ).toBe(false);
199 expect(
200 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
201 ...base,
202 type: "thread.turn-start-requested",
203 payload: {
204 threadId: "thread-1" as ThreadId,
205 },
206 } as unknown as OrchestrationEvent),
207 ).toBe(false);
208 expect(
209 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
210 ...base,
211 type: "thread.created",
212 metadata: { historyImport: true },
213 payload: { threadId: "thread-1" as ThreadId },
214 } as unknown as OrchestrationEvent),
215 ).toBe(false);
216 expect(
217 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
218 ...base,
219 type: "thread.settled",
220 metadata: { historyImport: true },
221 payload: { threadId: "thread-1" as ThreadId },
222 } as unknown as OrchestrationEvent),
223 ).toBe(false);
224 expect(
225 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
226 ...base,
227 type: "thread.created",
228 payload: { threadId: "thread-1" as ThreadId },
229 } as unknown as OrchestrationEvent),
230 ).toBe(true);
231 expect(
232 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
233 ...base,
234 type: "thread.settled",
235 payload: { threadId: "thread-1" as ThreadId },
236 } as unknown as OrchestrationEvent),
237 ).toBe(true);
238 });
239
240 it("deduplicates awareness state updates whose only change is their event timestamp", () => {
241 expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).toBe(
242 AgentAwarenessRelay.agentAwarenessPublishIdentity({
243 ...state,
244 updatedAt: "2026-05-25T00:10:00.000Z",
245 }),
246 );
247 expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).not.toBe(
248 AgentAwarenessRelay.agentAwarenessPublishIdentity({
249 ...state,
250 phase: "completed",
251 headline: "Agent finished",
252 }),
253 );
254 });
255
256 it("requires an explicit opt-in before publishing agent activity", () => {
257 expect(isAgentActivityPublishingEnabledValue(null)).toBe(false);
258 expect(isAgentActivityPublishingEnabledValue("false")).toBe(false);
259 expect(isAgentActivityPublishingEnabledValue("TRUE")).toBe(false);
260 expect(isAgentActivityPublishingEnabledValue("true")).toBe(true);
261 });
262
263 it("redacts failed activity details and caps other relay detail", () => {
264 expect(
265 AgentAwarenessRelay.sanitizeRelayAgentActivityState({
266 ...state,
267 phase: "failed",
268 detail: "Provider process exited with secret token.",
269 }),
270 ).toMatchObject({
271 phase: "failed",
272 detail: "The agent run failed.",
273 });
274 expect(
275 AgentAwarenessRelay.sanitizeRelayAgentActivityState({
276 ...state,
277 detail: "x".repeat(200),
278 })?.detail,
279 ).toHaveLength(160);
280 });
281
282 it("resolves a null publish state when a thread or project snapshot disappeared", () => {
283 const environmentId = "env-1" as EnvironmentId;
284 const threadId = "thread-1" as ThreadId;
285 const thread = {
286 id: threadId,
287 projectId: "project-1" as ProjectId,
288 title: "Deleted thread",
289 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
290 session: null,
291 latestTurn: null,
292 updatedAt: "2026-05-25T00:00:00.000Z",
293 hasPendingApprovals: false,
294 hasPendingUserInput: false,
295 } as OrchestrationThreadShell;
296
297 expect(
298 AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
299 environmentId,
300 threadId,
301 thread: Option.none(),
302 project: Option.none(),
303 }),
304 ).toEqual({
305 projectId: null,
306 state: null,
307 reason: "thread-not-found",
308 });
309
310 expect(
311 AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
312 environmentId,
313 threadId,
314 thread: Option.some(thread),
315 project: Option.none(),
316 }),
317 ).toEqual({
318 projectId: "project-1",
319 state: null,
320 reason: "project-not-found",
321 });
322 });
323
324 it("selects only active shell snapshot threads for startup catch-up", () => {
325 const now = "2026-05-25T00:00:00.000Z";
326 const environmentId = "env-1" as EnvironmentId;
327 const projectId = "project-1" as ProjectId;
328 const activeThreadId = "thread-active" as ThreadId;
329 const idleThreadId = "thread-idle" as ThreadId;
330 const oldCompletedId = "thread-old-completed" as ThreadId;
331 const newCompletedId = "thread-new-completed" as ThreadId;
332 const freshMessageId = "thread-fresh-message" as ThreadId;
333
334 const baseThread = {
335 projectId,
336 title: "Run remote agent",
337 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
338 runtimeMode: "full-access",
339 interactionMode: "default",
340 branch: null,
341 worktreePath: null,
342 pullRequests: [],
343 latestTurn: null,
344 createdAt: now,
345 updatedAt: now,
346 archivedAt: null,
347 settledOverride: null,
348 settledAt: null,
349 session: null,
350 latestUserMessageAt: null,
351 hasPendingApprovals: false,
352 hasPendingUserInput: false,
353 hasActionableProposedPlan: false,
354 } satisfies Omit<OrchestrationThreadShell, "id">;
355
356 expect(
357 AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
358 environmentId,
359 startedAt: Date.parse(now),
360 projects: [
361 {
362 id: projectId,
363 title: "T3 Code",
364 },
365 ],
366 threads: [
367 {
368 ...baseThread,
369 id: activeThreadId,
370 latestTurn: {
371 turnId: "turn-1" as TurnId,
372 state: "running",
373 requestedAt: now,
374 startedAt: now,
375 completedAt: null,
376 assistantMessageId: null,
377 },
378 },
379 {
380 ...baseThread,
381 id: idleThreadId,
382 },
383 {
384 ...baseThread,
385 id: oldCompletedId,
386 latestTurn: {
387 turnId: "turn-old" as TurnId,
388 state: "completed",
389 requestedAt: "2026-05-24T00:00:00.000Z",
390 startedAt: "2026-05-24T00:00:00.000Z",
391 completedAt: "2026-05-24T00:01:00.000Z",
392 assistantMessageId: null,
393 },
394 },
395 {
396 ...baseThread,
397 id: newCompletedId,
398 latestTurn: {
399 turnId: "turn-new" as TurnId,
400 state: "completed",
401 requestedAt: "2026-05-25T00:00:01.000Z",
402 startedAt: "2026-05-25T00:00:01.000Z",
403 completedAt: "2026-05-25T00:00:02.000Z",
404 assistantMessageId: null,
405 },
406 },
407 {
408 ...baseThread,
409 id: freshMessageId,
410 latestUserMessageAt: "2026-05-25T00:00:01.000Z",
411 session: {
412 threadId: freshMessageId,
413 status: "ready",
414 providerName: "Codex",
415 runtimeMode: "full-access",
416 activeTurnId: null,
417 lastError: null,
418 updatedAt: "2026-05-25T00:00:02.000Z",
419 },
420 },
421 {
422 ...baseThread,
423 id: "thread-missing-project" as ThreadId,
424 projectId: "missing-project" as ProjectId,
425 latestTurn: {
426 turnId: "turn-2" as TurnId,
427 state: "running",
428 requestedAt: now,
429 startedAt: now,
430 completedAt: null,
431 assistantMessageId: null,
432 },
433 },
434 ],
435 }),
436 ).toEqual([activeThreadId, newCompletedId]);
437 });
438
439 it.effect("signs the activity publish JWT and rejects tampering", () =>
440 Effect.gen(function* () {
441 const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
442 privateKeyEncoding: { format: "pem", type: "pkcs8" },
443 publicKeyEncoding: { format: "pem", type: "spki" },
444 });
445 const payload = {
446 iss: "t3-env:env",
447 aud: "https://relay.example.test",
448 sub: "env",
449 jti: "nonce-1",
450 iat: 100,
451 exp: 200,
452 environmentId: state.environmentId,
453 threadId: state.threadId,
454 state,
455 } satisfies RelayAgentActivityPublishProofPayload;
456 const proof = yield* AgentAwarenessRelay.signRelayAgentActivityPublishProof({
457 privateKey: keyPair.privateKey,
458 payload,
459 });
460 const verify = (token: string) =>
461 verifyRelayJwt({
462 publicKey: keyPair.publicKey,
463 token,
464 typ: RELAY_ACTIVITY_PUBLISH_TYP,
465 issuer: "t3-env:env",
466 audience: "https://relay.example.test",
467 nowEpochSeconds: 150,
468 });
469
470 expect(yield* verify(proof)).toMatchObject({ jti: "nonce-1", state });
471
472 const [header, body, signature = ""] = proof.split(".");
473 const corruptedSignature = `${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`;
474 const rejection = yield* Effect.flip(verify(`${header}.${body}.${corruptedSignature}`));
475 expect(rejection).toBeDefined();
476 }),
477 );
478
479 it.effect("keeps the listener armed and skips imported thread work", () =>
480 Effect.scoped(
481 Effect.gen(function* () {
482 const events = yield* Queue.unbounded<OrchestrationEvent>();
483 const threadShellRequested = yield* Deferred.make<void>();
484 const releaseThreadShell = yield* Deferred.make<void>();
485 const threadShellRequests: Array<ThreadId> = [];
486 let fetchCallCount = 0;
487 const secrets = makeMemorySecretStore();
488 const now = "2026-05-25T00:00:00.000Z";
489 const projectId = "project-1" as ProjectId;
490 const threadId = "thread-1" as ThreadId;
491 const importedThreadId = "import:codex:session-1" as ThreadId;
492 const environmentId = "env-1" as EnvironmentId;
493
494 const originalFetch = globalThis.fetch;
495 globalThis.fetch = (() => {
496 fetchCallCount += 1;
497 return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
498 }) as unknown as typeof fetch;
499 yield* Effect.addFinalizer(() =>
500 Effect.sync(() => {
501 globalThis.fetch = originalFetch;
502 }),
503 );
504
505 const project = {
506 id: projectId,
507 title: "T3 Code",
508 workspaceRoot: "/workspace",
509 repositoryIdentity: null,
510 defaultModelSelection: null,
511 scripts: [],
512 createdAt: now,
513 updatedAt: now,
514 } satisfies OrchestrationProjectShell;
515
516 const thread = {
517 id: threadId,
518 projectId,
519 title: "Run remote agent",
520 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
521 runtimeMode: "full-access",
522 interactionMode: "default",
523 branch: null,
524 worktreePath: null,
525 pullRequests: [],
526 latestTurn: {
527 turnId: "turn-1" as TurnId,
528 state: "running",
529 requestedAt: now,
530 startedAt: now,
531 completedAt: null,
532 assistantMessageId: null,
533 },
534 createdAt: now,
535 updatedAt: now,
536 archivedAt: null,
537 settledOverride: null,
538 settledAt: null,
539 session: {
540 threadId,
541 status: "running",
542 providerName: "Codex",
543 runtimeMode: "full-access",
544 activeTurnId: "turn-1" as TurnId,
545 lastError: null,
546 updatedAt: now,
547 },
548 latestUserMessageAt: now,
549 hasPendingApprovals: false,
550 hasPendingUserInput: false,
551 hasActionableProposedPlan: false,
552 } satisfies OrchestrationThreadShell;
553
554 const orchestrationEngine = {
555 readEvents: () => Stream.empty,
556 readThreadEvents: () => Stream.empty,
557 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
558 dispatch: () => Effect.succeed({ sequence: 1 }),
559 streamDomainEvents: Stream.fromQueue(events),
560 subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),
561 latestSequence: Effect.succeed(0),
562 } satisfies OrchestrationEngineShape;
563
564 const snapshotQuery = {
565 getShellSnapshot: () =>
566 Effect.succeed({
567 snapshotSequence: 1,
568 projects: [],
569 threads: [],
570 updatedAt: now,
571 } satisfies OrchestrationShellSnapshot),
572 getThreadShellById: (requestedThreadId: ThreadId) =>
573 Effect.gen(function* () {
574 threadShellRequests.push(requestedThreadId);
575 if (requestedThreadId !== threadId) return Option.none();
576 yield* Deferred.succeed(threadShellRequested, undefined);
577 yield* Deferred.await(releaseThreadShell);
578 return Option.some(thread);
579 }),
580 getProjectShellById: () => Effect.succeedSome(project),
581 } as unknown as ProjectionSnapshotQueryShape;
582
583 const descriptor = {
584 environmentId,
585 label: "Test Desktop",
586 platform: {
587 os: "darwin",
588 arch: "arm64",
589 },
590 serverVersion: "0.0.0-test",
591 capabilities: {
592 repositoryIdentity: true,
593 },
594 } satisfies ExecutionEnvironmentDescriptor;
595
596 const layer = Layer.mergeAll(
597 Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
598 Layer.succeed(ServerEnvironment.ServerEnvironment, {
599 getEnvironmentId: Effect.succeed(environmentId),
600 getDescriptor: Effect.succeed(descriptor),
601 }),
602 Layer.succeed(OrchestrationEngineService, orchestrationEngine),
603 Layer.succeed(ProjectionSnapshotQuery, snapshotQuery),
604 );
605
606 yield* Effect.gen(function* () {
607 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
608 yield* relay.start();
609 yield* secrets.setString(RELAY_URL_SECRET, "https://relay.example.test");
610 yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
611 yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
612 yield* Queue.offer(events, {
613 type: "thread.created",
614 sequence: 1,
615 eventId: "evt-import-created",
616 commandId: CommandId.make("cmd-import-created"),
617 aggregateKind: "thread",
618 aggregateId: importedThreadId,
619 metadata: { historyImport: true },
620 payload: { threadId: importedThreadId },
621 occurredAt: now,
622 } as unknown as OrchestrationEvent);
623 yield* Queue.offer(events, {
624 type: "thread.settled",
625 sequence: 2,
626 eventId: "evt-import-settled",
627 commandId: CommandId.make("cmd-import-settled"),
628 aggregateKind: "thread",
629 aggregateId: importedThreadId,
630 metadata: { historyImport: true },
631 payload: { threadId: importedThreadId },
632 occurredAt: now,
633 } as unknown as OrchestrationEvent);
634 yield* Queue.offer(events, {
635 type: "thread.activity-appended",
636 sequence: 3,
637 eventId: "evt-1",
638 commandId: CommandId.make("cmd-1"),
639 aggregateKind: "thread",
640 aggregateId: threadId,
641 actor: { kind: "server" },
642 metadata: {},
643 payload: {
644 threadId,
645 activity: {
646 kind: "approval.requested",
647 },
648 },
649 occurredAt: now,
650 } as unknown as OrchestrationEvent);
651
652 yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds"));
653 expect(threadShellRequests).toEqual([threadId]);
654 expect(fetchCallCount).toBe(0);
655 yield* Deferred.succeed(releaseThreadShell, undefined);
656 }).pipe(
657 Effect.provide(
658 AgentAwarenessRelay.layer.pipe(
659 Layer.provide(layer),
660 Layer.provideMerge(NodeServices.layer),
661 ),
662 ),
663 );
664 }),
665 ),
666 );
667
668 it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () =>
669 Effect.scoped(
670 Effect.gen(function* () {
671 const originalFetch = globalThis.fetch;
672 const events = yield* Queue.unbounded<OrchestrationEvent>();
673 let resolveFetchSeen: (url: URL) => void = () => {};
674 const fetchSeen = new Promise<URL>((resolve) => {
675 resolveFetchSeen = resolve;
676 });
677 const userSpans: Array<string> = [];
678 const productSpans: Array<string> = [];
679 const collectingTracer = (spans: Array<string>) =>
680 Tracer.make({
681 span: (options) => {
682 const span = new Tracer.NativeSpan(options);
683 const end = span.end.bind(span);
684 span.end = (endTime, exit) => {
685 end(endTime, exit);
686 spans.push(span.name);
687 };
688 return span;
689 },
690 });
691 const secrets = makeMemorySecretStore();
692 const now = "2026-05-25T00:00:00.000Z";
693 const projectId = "project-1" as ProjectId;
694 const threadId = "thread-1" as ThreadId;
695 const environmentId = "env-1" as EnvironmentId;
696
697 const project = {
698 id: projectId,
699 title: "T3 Code",
700 workspaceRoot: "/workspace",
701 repositoryIdentity: null,
702 defaultModelSelection: null,
703 scripts: [],
704 createdAt: now,
705 updatedAt: now,
706 } satisfies OrchestrationProjectShell;
707
708 const thread = {
709 id: threadId,
710 projectId,
711 title: "Run remote agent",
712 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
713 runtimeMode: "full-access",
714 interactionMode: "default",
715 branch: null,
716 worktreePath: null,
717 pullRequests: [],
718 latestTurn: {
719 turnId: "turn-1" as TurnId,
720 state: "running",
721 requestedAt: now,
722 startedAt: now,
723 completedAt: null,
724 assistantMessageId: null,
725 },
726 createdAt: now,
727 updatedAt: now,
728 archivedAt: null,
729 settledOverride: null,
730 settledAt: null,
731 session: {
732 threadId,
733 status: "running",
734 providerName: "Codex",
735 runtimeMode: "full-access",
736 activeTurnId: "turn-1" as TurnId,
737 lastError: null,
738 updatedAt: now,
739 },
740 latestUserMessageAt: now,
741 hasPendingApprovals: false,
742 hasPendingUserInput: false,
743 hasActionableProposedPlan: false,
744 } satisfies OrchestrationThreadShell;
745
746 const descriptor = {
747 environmentId,
748 label: "Test Desktop",
749 platform: {
750 os: "darwin",
751 arch: "arm64",
752 },
753 serverVersion: "0.0.0-test",
754 capabilities: {
755 repositoryIdentity: true,
756 },
757 } satisfies ExecutionEnvironmentDescriptor;
758
759 globalThis.fetch = ((input: Parameters<typeof fetch>[0]) => {
760 const url = new URL(
761 typeof input === "string" || input instanceof URL
762 ? input
763 : (input as unknown as { readonly url: string }).url,
764 );
765 resolveFetchSeen(url);
766 return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
767 }) as unknown as typeof fetch;
768 yield* Effect.addFinalizer(() =>
769 Effect.sync(() => {
770 globalThis.fetch = originalFetch;
771 }),
772 );
773
774 const layer = Layer.mergeAll(
775 Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
776 Layer.succeed(ServerEnvironment.ServerEnvironment, {
777 getEnvironmentId: Effect.succeed(environmentId),
778 getDescriptor: Effect.succeed(descriptor),
779 }),
780 Layer.succeed(OrchestrationEngineService, {
781 readEvents: () => Stream.empty,
782 readThreadEvents: () => Stream.empty,
783 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
784 dispatch: () => Effect.succeed({ sequence: 1 }),
785 streamDomainEvents: Stream.fromQueue(events),
786 subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),
787 latestSequence: Effect.succeed(0),
788 } satisfies OrchestrationEngineShape),
789 Layer.succeed(ProjectionSnapshotQuery, {
790 getShellSnapshot: () =>
791 Effect.succeed({
792 snapshotSequence: 1,
793 projects: [project],
794 threads: [thread],
795 updatedAt: now,
796 } satisfies OrchestrationShellSnapshot),
797 getThreadShellById: () => Effect.succeedSome(thread),
798 getProjectShellById: () => Effect.succeedSome(project),
799 } as unknown as ProjectionSnapshotQueryShape),
800 );
801
802 yield* Effect.gen(function* () {
803 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
804 yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test");
805 yield* secrets.setString(RELAY_ISSUER_SECRET, "https://issuer.example.test");
806 yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
807 yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
808 yield* relay.start();
809 yield* Queue.offer(events, {
810 type: "thread.activity-appended",
811 sequence: 1,
812 eventId: "evt-1",
813 commandId: CommandId.make("cmd-1"),
814 aggregateKind: "thread",
815 aggregateId: threadId,
816 actor: { kind: "server" },
817 metadata: {},
818 payload: {
819 threadId,
820 activity: {
821 kind: "approval.requested",
822 },
823 },
824 occurredAt: now,
825 } as unknown as OrchestrationEvent);
826
827 const url = yield* Effect.promise(() => fetchSeen).pipe(Effect.timeout("2 seconds"));
828 expect(url.origin).toBe("https://transport.example.test");
829 expect(productSpans).toContain("makePublishProof");
830 expect(userSpans).not.toContain("makePublishProof");
831 }).pipe(
832 Effect.provide(
833 AgentAwarenessRelay.layer.pipe(
834 Layer.provide(layer),
835 Layer.provideMerge(NodeServices.layer),
836 ),
837 ),
838 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
839 Effect.withTracer(collectingTracer(userSpans)),
840 );
841 }),
842 ),
843 );
844
845 it.effect("does not alert for historical completions after startup", () =>
846 Effect.scoped(
847 Effect.gen(function* () {
848 const secrets = makeMemorySecretStore();
849 const now = yield* DateTime.now;
850 const old = DateTime.formatIso(DateTime.add(now, { days: -7 }));
851 const threadId = "thread-old" as ThreadId;
852 const projectId = "project-1" as ProjectId;
853 const environmentId = "env-1" as EnvironmentId;
854 const project = {
855 id: projectId,
856 title: "T3 Code",
857 workspaceRoot: "/workspace",
858 repositoryIdentity: null,
859 defaultModelSelection: null,
860 scripts: [],
861 createdAt: old,
862 updatedAt: old,
863 } satisfies OrchestrationProjectShell;
864 const completedTurn = {
865 turnId: "turn-1" as TurnId,
866 state: "completed",
867 requestedAt: old,
868 startedAt: old,
869 completedAt: old,
870 assistantMessageId: null,
871 } as const;
872 const completedThread = {
873 id: threadId,
874 projectId,
875 title: "Old task",
876 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
877 runtimeMode: "full-access",
878 interactionMode: "default",
879 branch: null,
880 worktreePath: null,
881 pullRequests: [],
882 latestTurn: completedTurn,
883 createdAt: old,
884 updatedAt: old,
885 archivedAt: null,
886 settledOverride: null,
887 settledAt: null,
888 session: null,
889 latestUserMessageAt: old,
890 hasPendingApprovals: false,
891 hasPendingUserInput: false,
892 hasActionableProposedPlan: false,
893 } satisfies OrchestrationThreadShell;
894 let currentThread: OrchestrationThreadShell | null = completedThread;
895 let publishes = 0;
896 const originalFetch = globalThis.fetch;
897 globalThis.fetch = (() => {
898 publishes += 1;
899 return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
900 }) as unknown as typeof fetch;
901 yield* Effect.addFinalizer(() =>
902 Effect.sync(() => {
903 globalThis.fetch = originalFetch;
904 }),
905 );
906 yield* secrets.setString(RELAY_URL_SECRET, "https://relay.example.test");
907 yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
908 yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
909
910 const layer = Layer.mergeAll(
911 Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
912 Layer.succeed(ServerEnvironment.ServerEnvironment, {
913 getEnvironmentId: Effect.succeed(environmentId),
914 getDescriptor: Effect.die("unused descriptor"),
915 }),
916 Layer.succeed(OrchestrationEngineService, {} as OrchestrationEngineShape),
917 Layer.succeed(ProjectionSnapshotQuery, {
918 getThreadShellById: () => Effect.sync(() => Option.fromNullishOr(currentThread)),
919 getProjectShellById: () => Effect.succeedSome(project),
920 } as unknown as ProjectionSnapshotQueryShape),
921 );
922
923 yield* Effect.gen(function* () {
924 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
925 yield* relay.publishThread(threadId);
926 expect(publishes).toBe(0);
927
928 currentThread = {
929 ...completedThread,
930 latestTurn: null,
931 latestUserMessageAt: DateTime.formatIso(DateTime.add(now, { seconds: 1 })),
932 session: {
933 threadId,
934 status: "ready",
935 providerName: "Codex",
936 runtimeMode: "full-access",
937 activeTurnId: null,
938 lastError: null,
939 updatedAt: DateTime.formatIso(DateTime.add(now, { seconds: 2 })),
940 },
941 };
942 expect(
943 AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
944 environmentId,
945 threadId,
946 thread: Option.some(currentThread),
947 project: Option.some(project),
948 }).state?.phase,
949 ).toBe("completed");
950 yield* relay.publishThread(threadId);
951 expect(publishes).toBe(0);
952
953 currentThread = {
954 ...completedThread,
955 session: {
956 threadId,
957 status: "error",
958 providerName: "Codex",
959 runtimeMode: "full-access",
960 activeTurnId: null,
961 lastError: "old failure",
962 updatedAt: old,
963 },
964 };
965 yield* relay.publishThread(threadId);
966 expect(publishes).toBe(0);
967 }).pipe(
968 Effect.provide(
969 AgentAwarenessRelay.layer.pipe(
970 Layer.provide(layer),
971 Layer.provideMerge(NodeServices.layer),
972 ),
973 ),
974 );
975 }),
976 ),
977 );
978});
979
980describe("startup catch-up", { concurrent: false }, () => {
981 // An unlinked relay with publishing off. `link` writes the link secrets and
982 // `enablePublishing` the opt-in. Counts link checks (relay URL reads) and
983 // catch-up publishes (shell snapshot reads).
984 function makeUnlinkedRelay() {
985 const secrets = makeMemorySecretStore();
986 const counts = { linkChecks: 0, catchUpPublishes: 0 };
987 const countingStore = {
988 ...secrets.store,
989 get: (name: string) =>
990 Effect.suspend(() => {
991 if (name === RELAY_URL_SECRET) counts.linkChecks += 1;
992 return secrets.store.get(name);
993 }),
994 } satisfies ServerSecretStore.ServerSecretStore["Service"];
995
996 const layer = AgentAwarenessRelay.layer.pipe(
997 Layer.provide(
998 Layer.mergeAll(
999 Layer.succeed(ServerSecretStore.ServerSecretStore, countingStore),
1000 Layer.succeed(ServerEnvironment.ServerEnvironment, {
1001 getEnvironmentId: Effect.succeed("env-1" as EnvironmentId),
1002 getDescriptor: Effect.die("unused descriptor"),
1003 }),
1004 Layer.succeed(OrchestrationEngineService, {
1005 streamDomainEvents: Stream.never,
1006 } as unknown as OrchestrationEngineShape),
1007 Layer.succeed(ProjectionSnapshotQuery, {
1008 getShellSnapshot: () =>
1009 Effect.sync(() => {
1010 counts.catchUpPublishes += 1;
1011 return {
1012 snapshotSequence: 1,
1013 projects: [],
1014 threads: [],
1015 updatedAt: "2026-05-25T00:00:00.000Z",
1016 } satisfies OrchestrationShellSnapshot;
1017 }),
1018 } as unknown as ProjectionSnapshotQueryShape),
1019 ),
1020 ),
1021 Layer.provideMerge(NodeServices.layer),
1022 );
1023 const link = Effect.all(
1024 [
1025 secrets.setString(RELAY_URL_SECRET, "https://relay.example.test"),
1026 secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential"),
1027 ],
1028 { discard: true },
1029 );
1030 const enablePublishing = secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
1031 return { counts, layer, link, enablePublishing };
1032 }
1033
1034 it.effect("checks an unlinked environment once a minute and still catches up once linked", () => {
1035 const { counts, layer, link, enablePublishing } = makeUnlinkedRelay();
1036 return Effect.gen(function* () {
1037 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
1038 yield* enablePublishing;
1039 yield* relay.start();
1040
1041 // Get past the backoff ramp, then count checks in a steady window.
1042 yield* TestClock.adjust("10 minutes");
1043 const checksBeforeWindow = counts.linkChecks;
1044 yield* TestClock.adjust("10 minutes");
1045 expect(counts.linkChecks - checksBeforeWindow).toBe(10);
1046 expect(counts.catchUpPublishes).toBe(0);
1047
1048 yield* link;
1049 yield* TestClock.adjust("1 minute");
1050 expect(counts.catchUpPublishes).toBe(1);
1051 }).pipe(Effect.provide(layer), Effect.scoped);
1052 });
1053
1054 it.effect("publishes at once when this process links while the check is backed off", () => {
1055 const { counts, layer, link, enablePublishing } = makeUnlinkedRelay();
1056 return Effect.gen(function* () {
1057 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
1058 yield* enablePublishing;
1059 yield* relay.start();
1060
1061 // Backed off to 60 s: the next check is still seconds away.
1062 yield* TestClock.adjust("10 minutes");
1063 yield* link;
1064 yield* TestClock.adjust("1 second");
1065 expect(counts.catchUpPublishes).toBe(0);
1066
1067 yield* relay.requestCatchUp();
1068 yield* TestClock.adjust("1 second");
1069 expect(counts.catchUpPublishes).toBe(1);
1070 }).pipe(Effect.provide(layer), Effect.scoped);
1071 });
1072
1073 it.effect("catches up within 5 s when another process enables publishing on a link", () => {
1074 const { counts, layer, link, enablePublishing } = makeUnlinkedRelay();
1075 return Effect.gen(function* () {
1076 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
1077 yield* link;
1078 yield* relay.start();
1079
1080 yield* TestClock.adjust("10 minutes");
1081 expect(counts.catchUpPublishes).toBe(0);
1082
1083 // `t3 connect publish` writes the opt-in without waking this process.
1084 yield* enablePublishing;
1085 yield* TestClock.adjust("5 seconds");
1086 expect(counts.catchUpPublishes).toBe(1);
1087 }).pipe(Effect.provide(layer), Effect.scoped);
1088 });
1089});