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