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 Deferred from "effect/Deferred";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Queue from "effect/Queue";
28import * as Stream from "effect/Stream";
29import * as Tracer from "effect/Tracer";
30
31import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
32import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
33import {
34 OrchestrationEngineService,
35 type OrchestrationEngineShape,
36} from "../orchestration/Services/OrchestrationEngine.ts";
37import {
38 ProjectionSnapshotQuery,
39 type ProjectionSnapshotQueryShape,
40} from "../orchestration/Services/ProjectionSnapshotQuery.ts";
41import {
42 isAgentActivityPublishingEnabledValue,
43 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
44 RELAY_ISSUER_SECRET,
45 RELAY_URL_SECRET,
46 PUBLISH_AGENT_ACTIVITY_SECRET,
47} from "../cloud/config.ts";
48import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";
49
50const state: RelayAgentActivityState = {
51 environmentId: "env" as RelayAgentActivityState["environmentId"],
52 threadId: "thread" as RelayAgentActivityState["threadId"],
53 projectTitle: "Project",
54 threadTitle: "Thread",
55 modelTitle: "gpt-5.4",
56 phase: "running",
57 headline: "Running",
58 updatedAt: "2026-05-25T00:00:00.000Z",
59 deepLink: "/threads/env/thread",
60};
61
62const encodeSecret = (value: string): Uint8Array => new TextEncoder().encode(value);
63
64function makeMemorySecretStore() {
65 const values = new Map<string, Uint8Array>();
66 const store = {
67 get: ((name) =>
68 Effect.sync(() => {
69 const value = values.get(name);
70 return value === undefined ? Option.none() : Option.some(Uint8Array.from(value));
71 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["get"],
72 set: ((name, value) =>
73 Effect.sync(() => {
74 values.set(name, Uint8Array.from(value));
75 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["set"],
76 create: ((name, value) =>
77 Effect.sync(() => {
78 values.set(name, Uint8Array.from(value));
79 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["create"],
80 getOrCreateRandom: ((name, bytes) =>
81 Effect.sync(() => {
82 const existing = values.get(name);
83 if (existing) {
84 return existing;
85 }
86 const generated = new Uint8Array(bytes);
87 values.set(name, generated);
88 return generated;
89 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["getOrCreateRandom"],
90 remove: ((name) =>
91 Effect.sync(() => {
92 values.delete(name);
93 })) satisfies ServerSecretStore.ServerSecretStore["Service"]["remove"],
94 } satisfies ServerSecretStore.ServerSecretStore["Service"];
95 return {
96 store,
97 setString: (name: string, value: string) => store.set(name, encodeSecret(value)),
98 };
99}
100
101describe.sequential("signRelayAgentActivityPublishProof", () => {
102 it("distinguishes pending link credentials from disabled publication", () => {
103 expect(
104 AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
105 relayConfigured: false,
106 publishEnabled: false,
107 }),
108 ).toBe("waiting-for-link");
109 expect(
110 AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
111 relayConfigured: true,
112 publishEnabled: false,
113 }),
114 ).toBe("disabled");
115 expect(
116 AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
117 relayConfigured: true,
118 publishEnabled: true,
119 }),
120 ).toBe("enabled");
121 });
122
123 it("derives the thread id from the aggregate id for thread events without payload thread ids", () => {
124 const threadId = "thread-aggregate-1" as ThreadId;
125 const now = "2026-05-25T00:00:00.000Z";
126 const event = {
127 type: "thread.activity-appended",
128 sequence: 1,
129 eventId: "evt-aggregate-1",
130 commandId: CommandId.make("cmd-1"),
131 aggregateKind: "thread",
132 aggregateId: threadId,
133 actor: { kind: "server" },
134 payload: {},
135 occurredAt: now,
136 } as unknown as OrchestrationEvent;
137
138 expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
139 });
140
141 it("does not publish imported, start-intent, streaming, or non-awareness events", () => {
142 const now = "2026-05-25T00:00:00.000Z";
143 const base = {
144 sequence: 1,
145 eventId: "evt-1",
146 commandId: CommandId.make("cmd-1"),
147 aggregateKind: "thread",
148 aggregateId: "thread-1" as ThreadId,
149 occurredAt: now,
150 metadata: {},
151 };
152
153 expect(
154 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
155 ...base,
156 type: "thread.message-sent",
157 payload: {
158 threadId: "thread-1" as ThreadId,
159 streaming: true,
160 },
161 } as unknown as OrchestrationEvent),
162 ).toBe(false);
163 expect(
164 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
165 ...base,
166 type: "thread.activity-appended",
167 payload: {
168 threadId: "thread-1" as ThreadId,
169 activity: {
170 kind: "task.progress",
171 },
172 },
173 } as unknown as OrchestrationEvent),
174 ).toBe(false);
175 expect(
176 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
177 ...base,
178 type: "thread.activity-appended",
179 payload: {
180 threadId: "thread-1" as ThreadId,
181 activity: {
182 kind: "approval.requested",
183 },
184 },
185 } as unknown as OrchestrationEvent),
186 ).toBe(true);
187 expect(
188 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
189 ...base,
190 type: "thread.message-sent",
191 payload: {
192 threadId: "thread-1" as ThreadId,
193 streaming: false,
194 },
195 } as unknown as OrchestrationEvent),
196 ).toBe(false);
197 expect(
198 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
199 ...base,
200 type: "thread.turn-start-requested",
201 payload: {
202 threadId: "thread-1" as ThreadId,
203 },
204 } as unknown as OrchestrationEvent),
205 ).toBe(false);
206 expect(
207 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
208 ...base,
209 type: "thread.created",
210 metadata: { historyImport: true },
211 payload: { threadId: "thread-1" as ThreadId },
212 } as unknown as OrchestrationEvent),
213 ).toBe(false);
214 expect(
215 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
216 ...base,
217 type: "thread.settled",
218 metadata: { historyImport: true },
219 payload: { threadId: "thread-1" as ThreadId },
220 } as unknown as OrchestrationEvent),
221 ).toBe(false);
222 expect(
223 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
224 ...base,
225 type: "thread.created",
226 payload: { threadId: "thread-1" as ThreadId },
227 } as unknown as OrchestrationEvent),
228 ).toBe(true);
229 expect(
230 AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
231 ...base,
232 type: "thread.settled",
233 payload: { threadId: "thread-1" as ThreadId },
234 } as unknown as OrchestrationEvent),
235 ).toBe(true);
236 });
237
238 it("deduplicates awareness state updates whose only change is their event timestamp", () => {
239 expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).toBe(
240 AgentAwarenessRelay.agentAwarenessPublishIdentity({
241 ...state,
242 updatedAt: "2026-05-25T00:10:00.000Z",
243 }),
244 );
245 expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).not.toBe(
246 AgentAwarenessRelay.agentAwarenessPublishIdentity({
247 ...state,
248 phase: "completed",
249 headline: "Agent finished",
250 }),
251 );
252 });
253
254 it("requires an explicit opt-in before publishing agent activity", () => {
255 expect(isAgentActivityPublishingEnabledValue(null)).toBe(false);
256 expect(isAgentActivityPublishingEnabledValue("false")).toBe(false);
257 expect(isAgentActivityPublishingEnabledValue("TRUE")).toBe(false);
258 expect(isAgentActivityPublishingEnabledValue("true")).toBe(true);
259 });
260
261 it("redacts failed activity details and caps other relay detail", () => {
262 expect(
263 AgentAwarenessRelay.sanitizeRelayAgentActivityState({
264 ...state,
265 phase: "failed",
266 detail: "Provider process exited with secret token.",
267 }),
268 ).toMatchObject({
269 phase: "failed",
270 detail: "The agent run failed.",
271 });
272 expect(
273 AgentAwarenessRelay.sanitizeRelayAgentActivityState({
274 ...state,
275 detail: "x".repeat(200),
276 })?.detail,
277 ).toHaveLength(160);
278 });
279
280 it("resolves a null publish state when a thread or project snapshot disappeared", () => {
281 const environmentId = "env-1" as EnvironmentId;
282 const threadId = "thread-1" as ThreadId;
283 const thread = {
284 id: threadId,
285 projectId: "project-1" as ProjectId,
286 title: "Deleted thread",
287 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
288 session: null,
289 latestTurn: null,
290 updatedAt: "2026-05-25T00:00:00.000Z",
291 hasPendingApprovals: false,
292 hasPendingUserInput: false,
293 } as OrchestrationThreadShell;
294
295 expect(
296 AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
297 environmentId,
298 threadId,
299 thread: Option.none(),
300 project: Option.none(),
301 }),
302 ).toEqual({
303 projectId: null,
304 state: null,
305 reason: "thread-not-found",
306 });
307
308 expect(
309 AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
310 environmentId,
311 threadId,
312 thread: Option.some(thread),
313 project: Option.none(),
314 }),
315 ).toEqual({
316 projectId: "project-1",
317 state: null,
318 reason: "project-not-found",
319 });
320 });
321
322 it("selects only active shell snapshot threads for startup catch-up", () => {
323 const now = "2026-05-25T00:00:00.000Z";
324 const environmentId = "env-1" as EnvironmentId;
325 const projectId = "project-1" as ProjectId;
326 const activeThreadId = "thread-active" as ThreadId;
327 const idleThreadId = "thread-idle" as ThreadId;
328
329 const baseThread = {
330 projectId,
331 title: "Run remote agent",
332 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
333 runtimeMode: "full-access",
334 interactionMode: "default",
335 branch: null,
336 worktreePath: null,
337 latestTurn: null,
338 createdAt: now,
339 updatedAt: now,
340 archivedAt: null,
341 settledOverride: null,
342 settledAt: null,
343 session: null,
344 latestUserMessageAt: null,
345 hasPendingApprovals: false,
346 hasPendingUserInput: false,
347 hasActionableProposedPlan: false,
348 } satisfies Omit<OrchestrationThreadShell, "id">;
349
350 expect(
351 AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
352 environmentId,
353 projects: [
354 {
355 id: projectId,
356 title: "T3 Code",
357 },
358 ],
359 threads: [
360 {
361 ...baseThread,
362 id: activeThreadId,
363 latestTurn: {
364 turnId: "turn-1" as TurnId,
365 state: "running",
366 requestedAt: now,
367 startedAt: now,
368 completedAt: null,
369 assistantMessageId: null,
370 },
371 },
372 {
373 ...baseThread,
374 id: idleThreadId,
375 },
376 {
377 ...baseThread,
378 id: "thread-missing-project" as ThreadId,
379 projectId: "missing-project" as ProjectId,
380 latestTurn: {
381 turnId: "turn-2" as TurnId,
382 state: "running",
383 requestedAt: now,
384 startedAt: now,
385 completedAt: null,
386 assistantMessageId: null,
387 },
388 },
389 ],
390 }),
391 ).toEqual([activeThreadId]);
392 });
393
394 it.effect("signs the activity publish JWT and rejects tampering", () =>
395 Effect.gen(function* () {
396 const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
397 privateKeyEncoding: { format: "pem", type: "pkcs8" },
398 publicKeyEncoding: { format: "pem", type: "spki" },
399 });
400 const payload = {
401 iss: "t3-env:env",
402 aud: "https://relay.example.test",
403 sub: "env",
404 jti: "nonce-1",
405 iat: 100,
406 exp: 200,
407 environmentId: state.environmentId,
408 threadId: state.threadId,
409 state,
410 } satisfies RelayAgentActivityPublishProofPayload;
411 const proof = yield* AgentAwarenessRelay.signRelayAgentActivityPublishProof({
412 privateKey: keyPair.privateKey,
413 payload,
414 });
415 const verify = (token: string) =>
416 verifyRelayJwt({
417 publicKey: keyPair.publicKey,
418 token,
419 typ: RELAY_ACTIVITY_PUBLISH_TYP,
420 issuer: "t3-env:env",
421 audience: "https://relay.example.test",
422 nowEpochSeconds: 150,
423 });
424
425 expect(yield* verify(proof)).toMatchObject({ jti: "nonce-1", state });
426
427 const [header, body, signature = ""] = proof.split(".");
428 const corruptedSignature = `${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`;
429 const rejection = yield* Effect.flip(verify(`${header}.${body}.${corruptedSignature}`));
430 expect(rejection).toBeDefined();
431 }),
432 );
433
434 it.effect("keeps the listener armed and skips imported thread work", () =>
435 Effect.scoped(
436 Effect.gen(function* () {
437 const events = yield* Queue.unbounded<OrchestrationEvent>();
438 const threadShellRequested = yield* Deferred.make<void>();
439 const releaseThreadShell = yield* Deferred.make<void>();
440 const threadShellRequests: Array<ThreadId> = [];
441 let fetchCallCount = 0;
442 const secrets = makeMemorySecretStore();
443 const now = "2026-05-25T00:00:00.000Z";
444 const projectId = "project-1" as ProjectId;
445 const threadId = "thread-1" as ThreadId;
446 const importedThreadId = "import:codex:session-1" as ThreadId;
447 const environmentId = "env-1" as EnvironmentId;
448
449 const originalFetch = globalThis.fetch;
450 globalThis.fetch = (() => {
451 fetchCallCount += 1;
452 return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
453 }) as unknown as typeof fetch;
454 yield* Effect.addFinalizer(() =>
455 Effect.sync(() => {
456 globalThis.fetch = originalFetch;
457 }),
458 );
459
460 const project = {
461 id: projectId,
462 title: "T3 Code",
463 workspaceRoot: "/workspace",
464 repositoryIdentity: null,
465 defaultModelSelection: null,
466 scripts: [],
467 createdAt: now,
468 updatedAt: now,
469 } satisfies OrchestrationProjectShell;
470
471 const thread = {
472 id: threadId,
473 projectId,
474 title: "Run remote agent",
475 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
476 runtimeMode: "full-access",
477 interactionMode: "default",
478 branch: null,
479 worktreePath: null,
480 latestTurn: {
481 turnId: "turn-1" as TurnId,
482 state: "running",
483 requestedAt: now,
484 startedAt: now,
485 completedAt: null,
486 assistantMessageId: null,
487 },
488 createdAt: now,
489 updatedAt: now,
490 archivedAt: null,
491 settledOverride: null,
492 settledAt: null,
493 session: {
494 threadId,
495 status: "running",
496 providerName: "Codex",
497 runtimeMode: "full-access",
498 activeTurnId: "turn-1" as TurnId,
499 lastError: null,
500 updatedAt: now,
501 },
502 latestUserMessageAt: now,
503 hasPendingApprovals: false,
504 hasPendingUserInput: false,
505 hasActionableProposedPlan: false,
506 } satisfies OrchestrationThreadShell;
507
508 const orchestrationEngine = {
509 readEvents: () => Stream.empty,
510 readThreadEvents: () => Stream.empty,
511 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
512 dispatch: () => Effect.succeed({ sequence: 1 }),
513 streamDomainEvents: Stream.fromQueue(events),
514 subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),
515 latestSequence: Effect.succeed(0),
516 } satisfies OrchestrationEngineShape;
517
518 const snapshotQuery = {
519 getShellSnapshot: () =>
520 Effect.succeed({
521 snapshotSequence: 1,
522 projects: [],
523 threads: [],
524 updatedAt: now,
525 } satisfies OrchestrationShellSnapshot),
526 getThreadShellById: (requestedThreadId: ThreadId) =>
527 Effect.gen(function* () {
528 threadShellRequests.push(requestedThreadId);
529 if (requestedThreadId !== threadId) return Option.none();
530 yield* Deferred.succeed(threadShellRequested, undefined);
531 yield* Deferred.await(releaseThreadShell);
532 return Option.some(thread);
533 }),
534 getProjectShellById: () => Effect.succeed(Option.some(project)),
535 } as unknown as ProjectionSnapshotQueryShape;
536
537 const descriptor = {
538 environmentId,
539 label: "Test Desktop",
540 platform: {
541 os: "darwin",
542 arch: "arm64",
543 },
544 serverVersion: "0.0.0-test",
545 capabilities: {
546 repositoryIdentity: true,
547 },
548 } satisfies ExecutionEnvironmentDescriptor;
549
550 const layer = Layer.mergeAll(
551 Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
552 Layer.succeed(ServerEnvironment.ServerEnvironment, {
553 getEnvironmentId: Effect.succeed(environmentId),
554 getDescriptor: Effect.succeed(descriptor),
555 }),
556 Layer.succeed(OrchestrationEngineService, orchestrationEngine),
557 Layer.succeed(ProjectionSnapshotQuery, snapshotQuery),
558 );
559
560 yield* Effect.gen(function* () {
561 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
562 yield* relay.start();
563 yield* secrets.setString(RELAY_URL_SECRET, "https://relay.example.test");
564 yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
565 yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
566 yield* Queue.offer(events, {
567 type: "thread.created",
568 sequence: 1,
569 eventId: "evt-import-created",
570 commandId: CommandId.make("cmd-import-created"),
571 aggregateKind: "thread",
572 aggregateId: importedThreadId,
573 metadata: { historyImport: true },
574 payload: { threadId: importedThreadId },
575 occurredAt: now,
576 } as unknown as OrchestrationEvent);
577 yield* Queue.offer(events, {
578 type: "thread.settled",
579 sequence: 2,
580 eventId: "evt-import-settled",
581 commandId: CommandId.make("cmd-import-settled"),
582 aggregateKind: "thread",
583 aggregateId: importedThreadId,
584 metadata: { historyImport: true },
585 payload: { threadId: importedThreadId },
586 occurredAt: now,
587 } as unknown as OrchestrationEvent);
588 yield* Queue.offer(events, {
589 type: "thread.activity-appended",
590 sequence: 3,
591 eventId: "evt-1",
592 commandId: CommandId.make("cmd-1"),
593 aggregateKind: "thread",
594 aggregateId: threadId,
595 actor: { kind: "server" },
596 metadata: {},
597 payload: {
598 threadId,
599 activity: {
600 kind: "approval.requested",
601 },
602 },
603 occurredAt: now,
604 } as unknown as OrchestrationEvent);
605
606 yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds"));
607 expect(threadShellRequests).toEqual([threadId]);
608 expect(fetchCallCount).toBe(0);
609 yield* Deferred.succeed(releaseThreadShell, undefined);
610 }).pipe(
611 Effect.provide(
612 AgentAwarenessRelay.layer.pipe(
613 Layer.provide(layer),
614 Layer.provideMerge(NodeServices.layer),
615 ),
616 ),
617 );
618 }),
619 ),
620 );
621
622 it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () =>
623 Effect.scoped(
624 Effect.gen(function* () {
625 const originalFetch = globalThis.fetch;
626 const events = yield* Queue.unbounded<OrchestrationEvent>();
627 let resolveFetchSeen: (url: URL) => void = () => {};
628 const fetchSeen = new Promise<URL>((resolve) => {
629 resolveFetchSeen = resolve;
630 });
631 const userSpans: Array<string> = [];
632 const productSpans: Array<string> = [];
633 const collectingTracer = (spans: Array<string>) =>
634 Tracer.make({
635 span: (options) => {
636 const span = new Tracer.NativeSpan(options);
637 const end = span.end.bind(span);
638 span.end = (endTime, exit) => {
639 end(endTime, exit);
640 spans.push(span.name);
641 };
642 return span;
643 },
644 });
645 const secrets = makeMemorySecretStore();
646 const now = "2026-05-25T00:00:00.000Z";
647 const projectId = "project-1" as ProjectId;
648 const threadId = "thread-1" as ThreadId;
649 const environmentId = "env-1" as EnvironmentId;
650
651 const project = {
652 id: projectId,
653 title: "T3 Code",
654 workspaceRoot: "/workspace",
655 repositoryIdentity: null,
656 defaultModelSelection: null,
657 scripts: [],
658 createdAt: now,
659 updatedAt: now,
660 } satisfies OrchestrationProjectShell;
661
662 const thread = {
663 id: threadId,
664 projectId,
665 title: "Run remote agent",
666 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
667 runtimeMode: "full-access",
668 interactionMode: "default",
669 branch: null,
670 worktreePath: null,
671 latestTurn: {
672 turnId: "turn-1" as TurnId,
673 state: "running",
674 requestedAt: now,
675 startedAt: now,
676 completedAt: null,
677 assistantMessageId: null,
678 },
679 createdAt: now,
680 updatedAt: now,
681 archivedAt: null,
682 settledOverride: null,
683 settledAt: null,
684 session: {
685 threadId,
686 status: "running",
687 providerName: "Codex",
688 runtimeMode: "full-access",
689 activeTurnId: "turn-1" as TurnId,
690 lastError: null,
691 updatedAt: now,
692 },
693 latestUserMessageAt: now,
694 hasPendingApprovals: false,
695 hasPendingUserInput: false,
696 hasActionableProposedPlan: false,
697 } satisfies OrchestrationThreadShell;
698
699 const descriptor = {
700 environmentId,
701 label: "Test Desktop",
702 platform: {
703 os: "darwin",
704 arch: "arm64",
705 },
706 serverVersion: "0.0.0-test",
707 capabilities: {
708 repositoryIdentity: true,
709 },
710 } satisfies ExecutionEnvironmentDescriptor;
711
712 globalThis.fetch = ((input: Parameters<typeof fetch>[0]) => {
713 const url = new URL(
714 typeof input === "string" || input instanceof URL
715 ? input
716 : (input as unknown as { readonly url: string }).url,
717 );
718 resolveFetchSeen(url);
719 return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
720 }) as unknown as typeof fetch;
721 yield* Effect.addFinalizer(() =>
722 Effect.sync(() => {
723 globalThis.fetch = originalFetch;
724 }),
725 );
726
727 const layer = Layer.mergeAll(
728 Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
729 Layer.succeed(ServerEnvironment.ServerEnvironment, {
730 getEnvironmentId: Effect.succeed(environmentId),
731 getDescriptor: Effect.succeed(descriptor),
732 }),
733 Layer.succeed(OrchestrationEngineService, {
734 readEvents: () => Stream.empty,
735 readThreadEvents: () => Stream.empty,
736 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
737 dispatch: () => Effect.succeed({ sequence: 1 }),
738 streamDomainEvents: Stream.fromQueue(events),
739 subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),
740 latestSequence: Effect.succeed(0),
741 } satisfies OrchestrationEngineShape),
742 Layer.succeed(ProjectionSnapshotQuery, {
743 getShellSnapshot: () =>
744 Effect.succeed({
745 snapshotSequence: 1,
746 projects: [project],
747 threads: [thread],
748 updatedAt: now,
749 } satisfies OrchestrationShellSnapshot),
750 getThreadShellById: () => Effect.succeed(Option.some(thread)),
751 getProjectShellById: () => Effect.succeed(Option.some(project)),
752 } as unknown as ProjectionSnapshotQueryShape),
753 );
754
755 yield* Effect.gen(function* () {
756 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
757 yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test");
758 yield* secrets.setString(RELAY_ISSUER_SECRET, "https://issuer.example.test");
759 yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
760 yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
761 yield* relay.start();
762 yield* Queue.offer(events, {
763 type: "thread.activity-appended",
764 sequence: 1,
765 eventId: "evt-1",
766 commandId: CommandId.make("cmd-1"),
767 aggregateKind: "thread",
768 aggregateId: threadId,
769 actor: { kind: "server" },
770 metadata: {},
771 payload: {
772 threadId,
773 activity: {
774 kind: "approval.requested",
775 },
776 },
777 occurredAt: now,
778 } as unknown as OrchestrationEvent);
779
780 const url = yield* Effect.promise(() => fetchSeen).pipe(Effect.timeout("2 seconds"));
781 expect(url.origin).toBe("https://transport.example.test");
782 expect(productSpans).toContain("makePublishProof");
783 expect(userSpans).not.toContain("makePublishProof");
784 }).pipe(
785 Effect.provide(
786 AgentAwarenessRelay.layer.pipe(
787 Layer.provide(layer),
788 Layer.provideMerge(NodeServices.layer),
789 ),
790 ),
791 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
792 Effect.withTracer(collectingTracer(userSpans)),
793 );
794 }),
795 ),
796 );
797});