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 pullRequests: [],
338 latestTurn: null,
339 createdAt: now,
340 updatedAt: now,
341 archivedAt: null,
342 settledOverride: null,
343 settledAt: null,
344 session: null,
345 latestUserMessageAt: null,
346 hasPendingApprovals: false,
347 hasPendingUserInput: false,
348 hasActionableProposedPlan: false,
349 } satisfies Omit<OrchestrationThreadShell, "id">;
350
351 expect(
352 AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
353 environmentId,
354 projects: [
355 {
356 id: projectId,
357 title: "T3 Code",
358 },
359 ],
360 threads: [
361 {
362 ...baseThread,
363 id: activeThreadId,
364 latestTurn: {
365 turnId: "turn-1" as TurnId,
366 state: "running",
367 requestedAt: now,
368 startedAt: now,
369 completedAt: null,
370 assistantMessageId: null,
371 },
372 },
373 {
374 ...baseThread,
375 id: idleThreadId,
376 },
377 {
378 ...baseThread,
379 id: "thread-missing-project" as ThreadId,
380 projectId: "missing-project" as ProjectId,
381 latestTurn: {
382 turnId: "turn-2" as TurnId,
383 state: "running",
384 requestedAt: now,
385 startedAt: now,
386 completedAt: null,
387 assistantMessageId: null,
388 },
389 },
390 ],
391 }),
392 ).toEqual([activeThreadId]);
393 });
394
395 it.effect("signs the activity publish JWT and rejects tampering", () =>
396 Effect.gen(function* () {
397 const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
398 privateKeyEncoding: { format: "pem", type: "pkcs8" },
399 publicKeyEncoding: { format: "pem", type: "spki" },
400 });
401 const payload = {
402 iss: "t3-env:env",
403 aud: "https://relay.example.test",
404 sub: "env",
405 jti: "nonce-1",
406 iat: 100,
407 exp: 200,
408 environmentId: state.environmentId,
409 threadId: state.threadId,
410 state,
411 } satisfies RelayAgentActivityPublishProofPayload;
412 const proof = yield* AgentAwarenessRelay.signRelayAgentActivityPublishProof({
413 privateKey: keyPair.privateKey,
414 payload,
415 });
416 const verify = (token: string) =>
417 verifyRelayJwt({
418 publicKey: keyPair.publicKey,
419 token,
420 typ: RELAY_ACTIVITY_PUBLISH_TYP,
421 issuer: "t3-env:env",
422 audience: "https://relay.example.test",
423 nowEpochSeconds: 150,
424 });
425
426 expect(yield* verify(proof)).toMatchObject({ jti: "nonce-1", state });
427
428 const [header, body, signature = ""] = proof.split(".");
429 const corruptedSignature = `${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`;
430 const rejection = yield* Effect.flip(verify(`${header}.${body}.${corruptedSignature}`));
431 expect(rejection).toBeDefined();
432 }),
433 );
434
435 it.effect("keeps the listener armed and skips imported thread work", () =>
436 Effect.scoped(
437 Effect.gen(function* () {
438 const events = yield* Queue.unbounded<OrchestrationEvent>();
439 const threadShellRequested = yield* Deferred.make<void>();
440 const releaseThreadShell = yield* Deferred.make<void>();
441 const threadShellRequests: Array<ThreadId> = [];
442 let fetchCallCount = 0;
443 const secrets = makeMemorySecretStore();
444 const now = "2026-05-25T00:00:00.000Z";
445 const projectId = "project-1" as ProjectId;
446 const threadId = "thread-1" as ThreadId;
447 const importedThreadId = "import:codex:session-1" as ThreadId;
448 const environmentId = "env-1" as EnvironmentId;
449
450 const originalFetch = globalThis.fetch;
451 globalThis.fetch = (() => {
452 fetchCallCount += 1;
453 return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
454 }) as unknown as typeof fetch;
455 yield* Effect.addFinalizer(() =>
456 Effect.sync(() => {
457 globalThis.fetch = originalFetch;
458 }),
459 );
460
461 const project = {
462 id: projectId,
463 title: "T3 Code",
464 workspaceRoot: "/workspace",
465 repositoryIdentity: null,
466 defaultModelSelection: null,
467 scripts: [],
468 createdAt: now,
469 updatedAt: now,
470 } satisfies OrchestrationProjectShell;
471
472 const thread = {
473 id: threadId,
474 projectId,
475 title: "Run remote agent",
476 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
477 runtimeMode: "full-access",
478 interactionMode: "default",
479 branch: null,
480 worktreePath: null,
481 pullRequests: [],
482 latestTurn: {
483 turnId: "turn-1" as TurnId,
484 state: "running",
485 requestedAt: now,
486 startedAt: now,
487 completedAt: null,
488 assistantMessageId: null,
489 },
490 createdAt: now,
491 updatedAt: now,
492 archivedAt: null,
493 settledOverride: null,
494 settledAt: null,
495 session: {
496 threadId,
497 status: "running",
498 providerName: "Codex",
499 runtimeMode: "full-access",
500 activeTurnId: "turn-1" as TurnId,
501 lastError: null,
502 updatedAt: now,
503 },
504 latestUserMessageAt: now,
505 hasPendingApprovals: false,
506 hasPendingUserInput: false,
507 hasActionableProposedPlan: false,
508 } satisfies OrchestrationThreadShell;
509
510 const orchestrationEngine = {
511 readEvents: () => Stream.empty,
512 readThreadEvents: () => Stream.empty,
513 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
514 dispatch: () => Effect.succeed({ sequence: 1 }),
515 streamDomainEvents: Stream.fromQueue(events),
516 subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),
517 latestSequence: Effect.succeed(0),
518 } satisfies OrchestrationEngineShape;
519
520 const snapshotQuery = {
521 getShellSnapshot: () =>
522 Effect.succeed({
523 snapshotSequence: 1,
524 projects: [],
525 threads: [],
526 updatedAt: now,
527 } satisfies OrchestrationShellSnapshot),
528 getThreadShellById: (requestedThreadId: ThreadId) =>
529 Effect.gen(function* () {
530 threadShellRequests.push(requestedThreadId);
531 if (requestedThreadId !== threadId) return Option.none();
532 yield* Deferred.succeed(threadShellRequested, undefined);
533 yield* Deferred.await(releaseThreadShell);
534 return Option.some(thread);
535 }),
536 getProjectShellById: () => Effect.succeed(Option.some(project)),
537 } as unknown as ProjectionSnapshotQueryShape;
538
539 const descriptor = {
540 environmentId,
541 label: "Test Desktop",
542 platform: {
543 os: "darwin",
544 arch: "arm64",
545 },
546 serverVersion: "0.0.0-test",
547 capabilities: {
548 repositoryIdentity: true,
549 },
550 } satisfies ExecutionEnvironmentDescriptor;
551
552 const layer = Layer.mergeAll(
553 Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
554 Layer.succeed(ServerEnvironment.ServerEnvironment, {
555 getEnvironmentId: Effect.succeed(environmentId),
556 getDescriptor: Effect.succeed(descriptor),
557 }),
558 Layer.succeed(OrchestrationEngineService, orchestrationEngine),
559 Layer.succeed(ProjectionSnapshotQuery, snapshotQuery),
560 );
561
562 yield* Effect.gen(function* () {
563 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
564 yield* relay.start();
565 yield* secrets.setString(RELAY_URL_SECRET, "https://relay.example.test");
566 yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
567 yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
568 yield* Queue.offer(events, {
569 type: "thread.created",
570 sequence: 1,
571 eventId: "evt-import-created",
572 commandId: CommandId.make("cmd-import-created"),
573 aggregateKind: "thread",
574 aggregateId: importedThreadId,
575 metadata: { historyImport: true },
576 payload: { threadId: importedThreadId },
577 occurredAt: now,
578 } as unknown as OrchestrationEvent);
579 yield* Queue.offer(events, {
580 type: "thread.settled",
581 sequence: 2,
582 eventId: "evt-import-settled",
583 commandId: CommandId.make("cmd-import-settled"),
584 aggregateKind: "thread",
585 aggregateId: importedThreadId,
586 metadata: { historyImport: true },
587 payload: { threadId: importedThreadId },
588 occurredAt: now,
589 } as unknown as OrchestrationEvent);
590 yield* Queue.offer(events, {
591 type: "thread.activity-appended",
592 sequence: 3,
593 eventId: "evt-1",
594 commandId: CommandId.make("cmd-1"),
595 aggregateKind: "thread",
596 aggregateId: threadId,
597 actor: { kind: "server" },
598 metadata: {},
599 payload: {
600 threadId,
601 activity: {
602 kind: "approval.requested",
603 },
604 },
605 occurredAt: now,
606 } as unknown as OrchestrationEvent);
607
608 yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds"));
609 expect(threadShellRequests).toEqual([threadId]);
610 expect(fetchCallCount).toBe(0);
611 yield* Deferred.succeed(releaseThreadShell, undefined);
612 }).pipe(
613 Effect.provide(
614 AgentAwarenessRelay.layer.pipe(
615 Layer.provide(layer),
616 Layer.provideMerge(NodeServices.layer),
617 ),
618 ),
619 );
620 }),
621 ),
622 );
623
624 it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () =>
625 Effect.scoped(
626 Effect.gen(function* () {
627 const originalFetch = globalThis.fetch;
628 const events = yield* Queue.unbounded<OrchestrationEvent>();
629 let resolveFetchSeen: (url: URL) => void = () => {};
630 const fetchSeen = new Promise<URL>((resolve) => {
631 resolveFetchSeen = resolve;
632 });
633 const userSpans: Array<string> = [];
634 const productSpans: Array<string> = [];
635 const collectingTracer = (spans: Array<string>) =>
636 Tracer.make({
637 span: (options) => {
638 const span = new Tracer.NativeSpan(options);
639 const end = span.end.bind(span);
640 span.end = (endTime, exit) => {
641 end(endTime, exit);
642 spans.push(span.name);
643 };
644 return span;
645 },
646 });
647 const secrets = makeMemorySecretStore();
648 const now = "2026-05-25T00:00:00.000Z";
649 const projectId = "project-1" as ProjectId;
650 const threadId = "thread-1" as ThreadId;
651 const environmentId = "env-1" as EnvironmentId;
652
653 const project = {
654 id: projectId,
655 title: "T3 Code",
656 workspaceRoot: "/workspace",
657 repositoryIdentity: null,
658 defaultModelSelection: null,
659 scripts: [],
660 createdAt: now,
661 updatedAt: now,
662 } satisfies OrchestrationProjectShell;
663
664 const thread = {
665 id: threadId,
666 projectId,
667 title: "Run remote agent",
668 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
669 runtimeMode: "full-access",
670 interactionMode: "default",
671 branch: null,
672 worktreePath: null,
673 pullRequests: [],
674 latestTurn: {
675 turnId: "turn-1" as TurnId,
676 state: "running",
677 requestedAt: now,
678 startedAt: now,
679 completedAt: null,
680 assistantMessageId: null,
681 },
682 createdAt: now,
683 updatedAt: now,
684 archivedAt: null,
685 settledOverride: null,
686 settledAt: null,
687 session: {
688 threadId,
689 status: "running",
690 providerName: "Codex",
691 runtimeMode: "full-access",
692 activeTurnId: "turn-1" as TurnId,
693 lastError: null,
694 updatedAt: now,
695 },
696 latestUserMessageAt: now,
697 hasPendingApprovals: false,
698 hasPendingUserInput: false,
699 hasActionableProposedPlan: false,
700 } satisfies OrchestrationThreadShell;
701
702 const descriptor = {
703 environmentId,
704 label: "Test Desktop",
705 platform: {
706 os: "darwin",
707 arch: "arm64",
708 },
709 serverVersion: "0.0.0-test",
710 capabilities: {
711 repositoryIdentity: true,
712 },
713 } satisfies ExecutionEnvironmentDescriptor;
714
715 globalThis.fetch = ((input: Parameters<typeof fetch>[0]) => {
716 const url = new URL(
717 typeof input === "string" || input instanceof URL
718 ? input
719 : (input as unknown as { readonly url: string }).url,
720 );
721 resolveFetchSeen(url);
722 return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
723 }) as unknown as typeof fetch;
724 yield* Effect.addFinalizer(() =>
725 Effect.sync(() => {
726 globalThis.fetch = originalFetch;
727 }),
728 );
729
730 const layer = Layer.mergeAll(
731 Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
732 Layer.succeed(ServerEnvironment.ServerEnvironment, {
733 getEnvironmentId: Effect.succeed(environmentId),
734 getDescriptor: Effect.succeed(descriptor),
735 }),
736 Layer.succeed(OrchestrationEngineService, {
737 readEvents: () => Stream.empty,
738 readThreadEvents: () => Stream.empty,
739 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
740 dispatch: () => Effect.succeed({ sequence: 1 }),
741 streamDomainEvents: Stream.fromQueue(events),
742 subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),
743 latestSequence: Effect.succeed(0),
744 } satisfies OrchestrationEngineShape),
745 Layer.succeed(ProjectionSnapshotQuery, {
746 getShellSnapshot: () =>
747 Effect.succeed({
748 snapshotSequence: 1,
749 projects: [project],
750 threads: [thread],
751 updatedAt: now,
752 } satisfies OrchestrationShellSnapshot),
753 getThreadShellById: () => Effect.succeed(Option.some(thread)),
754 getProjectShellById: () => Effect.succeed(Option.some(project)),
755 } as unknown as ProjectionSnapshotQueryShape),
756 );
757
758 yield* Effect.gen(function* () {
759 const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
760 yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test");
761 yield* secrets.setString(RELAY_ISSUER_SECRET, "https://issuer.example.test");
762 yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
763 yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
764 yield* relay.start();
765 yield* Queue.offer(events, {
766 type: "thread.activity-appended",
767 sequence: 1,
768 eventId: "evt-1",
769 commandId: CommandId.make("cmd-1"),
770 aggregateKind: "thread",
771 aggregateId: threadId,
772 actor: { kind: "server" },
773 metadata: {},
774 payload: {
775 threadId,
776 activity: {
777 kind: "approval.requested",
778 },
779 },
780 occurredAt: now,
781 } as unknown as OrchestrationEvent);
782
783 const url = yield* Effect.promise(() => fetchSeen).pipe(Effect.timeout("2 seconds"));
784 expect(url.origin).toBe("https://transport.example.test");
785 expect(productSpans).toContain("makePublishProof");
786 expect(userSpans).not.toContain("makePublishProof");
787 }).pipe(
788 Effect.provide(
789 AgentAwarenessRelay.layer.pipe(
790 Layer.provide(layer),
791 Layer.provideMerge(NodeServices.layer),
792 ),
793 ),
794 Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
795 Effect.withTracer(collectingTracer(userSpans)),
796 );
797 }),
798 ),
799 );
800});