Open History to see the last commit
1import { NodeHttpServer } from "@effect/platform-node";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import {
5 CommandId,
6 EventId,
7 MessageId,
8 NodeId,
9 OrchestratorMcpFailure,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ProviderThreadId,
14 type RuntimeMode,
15 RunId,
16 ThreadId,
17 TurnItemId,
18} from "@t3tools/contracts";
19import { expect, it } from "@effect/vitest";
20import * as Clock from "effect/Clock";
21import * as Context from "effect/Context";
22import * as DateTime from "effect/DateTime";
23import * as Deferred from "effect/Deferred";
24import * as Duration from "effect/Duration";
25import * as Effect from "effect/Effect";
26import * as Fiber from "effect/Fiber";
27import * as HttpServer from "effect/http/HttpServer";
28import * as HttpServerResponse from "effect/http/HttpServerResponse";
29import * as Layer from "effect/Layer";
30import * as Option from "effect/Option";
31import * as Schema from "effect/Schema";
32import * as SqlClient from "effect/sql/SqlClient";
33import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
34
35import * as ServerConfig from "../config.ts";
36import * as McpHttpServer from "../mcp/McpHttpServer.ts";
37import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
38import * as McpToolAccess from "../mcp/McpToolAccess.ts";
39import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
40import * as EventSink from "../orchestration-v2/EventSink.ts";
41import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
42import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
43import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
44import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
45import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
46import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
47import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
48import * as SqlitePersistence from "../persistence/Sqlite.ts";
49import * as ProjectService from "../project/ProjectService.ts";
50import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
51import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
52import * as SecretRequests from "../secrets/SecretRequests.ts";
53import * as ServerSettings from "../serverSettings.ts";
54import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
55import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
56import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
57import * as PeerForwarding from "./PeerForwarding.ts";
58import * as PeerLinkRequests from "./PeerLinkRequests.ts";
59import * as PeerLinks from "./PeerLinks.ts";
60import {
61 descriptorOf,
62 layerLinkingEnvironment,
63 linkTo,
64 servePeer,
65 type ServedPeer,
66} from "./PeerLinks.testkit.ts";
67import * as RemoteDelegation from "./RemoteDelegation.ts";
68
69// The laptop's agent asks the user to link the box. The laptop is its real
70// orchestrator and toolkit; the box is its real descriptor and MCP OAuth on a
71// socket. The user's answer goes through PeerLinkRequests, as the card's does.
72
73const laptop = descriptorOf("environment-laptop", "Laptop");
74const box = descriptorOf("environment-box", "Box");
75const instanceId = ProviderInstanceId.make("codex");
76const driver = ProviderDriverKind.make("codex");
77const modelSelection = { instanceId, model: "gpt-5.4" };
78const threadId = ThreadId.make("thread:laptop");
79const runId = RunId.make("run:laptop");
80const rootNode = NodeId.make("node:laptop:root");
81
82/** The box needs no tools of its own: linking only signs in to its /mcp. */
83const NoTools = Toolkit.make(
84 Tool.make("noop", { success: Schema.Struct({}), failure: OrchestratorMcpFailure }),
85);
86const serveBox = servePeer(
87 box,
88 McpHttpServer.toolkitRegistration(
89 NoTools,
90 McpToolAccess.toLayer(NoTools, { noop: McpToolAccess.reads(() => Effect.succeed({})) }),
91 ),
92);
93
94const adapter = {
95 instanceId,
96 driver,
97 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
98 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
99 openSession: () => Effect.die("No provider process needed"),
100} as ProviderAdapter.ProviderAdapterV2["Service"];
101
102const mcpClient = McpSchema.McpServerClient.of({
103 clientId: 1,
104 protocolVersion: "2025-06-18",
105 clientCapabilities: {},
106 clientInfo: { name: "peer-link-requests", version: "1" },
107 initializePayload: {
108 protocolVersion: "2025-06-18",
109 capabilities: {},
110 clientInfo: { name: "peer-link-requests", version: "1" },
111 },
112 getClient: Effect.die("unused"),
113});
114
115const scope: McpInvocationContext.McpInvocationScope = {
116 environmentId: laptop.environmentId,
117 requestNamespace: "provider-session:laptop",
118 thread: {
119 threadId,
120 providerSessionId: "provider-session:laptop",
121 providerInstanceId: instanceId,
122 },
123 client: undefined,
124 capabilities: new Set(["orchestration"]),
125 issuedAt: 1,
126};
127
128/** The laptop: a real orchestrator, its orchestrator toolkit, and its links. */
129const makeLaptop = Effect.gen(function* () {
130 const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
131 // The orchestrator's own database, apart from the one links are kept in.
132 const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
133 const layerDatabase = Layer.succeedContext(database);
134 const layerOrchestrator = Layer.mergeAll(
135 layerDatabase,
136 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
137 ProviderReplayHarness.layerWithRegistry(
138 { name: "peer-link-requests" },
139 ProviderAdapterRegistry.layerFromAdapters([adapter]),
140 { databaseLayer: layerDatabase, runEffectWorker: false },
141 ),
142 ).pipe(
143 Layer.provide(
144 Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
145 offer: () => Effect.void,
146 take: Effect.never,
147 }),
148 ),
149 );
150 const layerThreads = ThreadManagement.layer.pipe(
151 Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
152 Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
153 );
154 const layerHere = McpHttpServer.layerOrchestratorToolkit.pipe(
155 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
156 Layer.provideMerge(PeerLinkRequests.layer),
157 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
158 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
159 Layer.provide(Layer.succeedContext(linking)),
160 Layer.provide(NodeCrypto.layer),
161 Layer.provideMerge(layerThreads),
162 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
163 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
164 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
165 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
166 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
167 Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
168 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
169 Layer.provide(
170 ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-requests-" }).pipe(
171 Layer.provide(NodeServices.layer),
172 ),
173 ),
174 Layer.provide(NodeServices.layer),
175 Layer.fresh,
176 );
177 const here = yield* Layer.build(layerHere);
178 const server = Context.get(here, McpServer.McpServer);
179 return {
180 links: Context.get(linking, PeerLinks.PeerLinks),
181 linksSql: Context.get(linking, SqlClient.SqlClient),
182 requests: Context.get(here, PeerLinkRequests.PeerLinkRequests),
183 orchestrator: Context.get(here, Orchestrator.OrchestratorV2),
184 sink: Context.get(here, EventSink.EventSinkV2),
185 projections: Context.get(here, ProjectionStore.ProjectionStoreV2),
186 sql: Context.get(database, SqlClient.SqlClient),
187 call: (args: Record<string, unknown>, callScope = scope) =>
188 server
189 .callTool({ name: "t3_environment_link", arguments: args })
190 .pipe(
191 Effect.provideService(McpInvocationContext.McpInvocationContext, callScope),
192 Effect.provideService(McpSchema.McpServerClient, mcpClient),
193 ),
194 };
195});
196type Laptop = Effect.Success<typeof makeLaptop>;
197
198/** The laptop's thread, mid-turn when its agent asks, in `runtimeMode`. */
199const seedThread = (
200 a: Laptop,
201 runtimeMode: RuntimeMode = "full-access",
202 linkOrigin?: { readonly sessionId: string; readonly label: string },
203) =>
204 Effect.gen(function* () {
205 const now = yield* DateTime.now;
206 const providerThreadId = ProviderThreadId.make("provider-thread:laptop");
207 yield* a.orchestrator.dispatch({
208 type: "thread.create",
209 createdBy: "user",
210 creationSource: "web",
211 commandId: CommandId.make("command:create:laptop"),
212 threadId,
213 projectId: ProjectId.make("project:laptop"),
214 title: "Laptop",
215 modelSelection,
216 runtimeMode,
217 interactionMode: "default",
218 branch: null,
219 worktreePath: null,
220 ...(linkOrigin === undefined ? {} : { linkOrigin }),
221 });
222 yield* a.sink.write({
223 commandId: CommandId.make("command:seed:laptop"),
224 events: [
225 {
226 id: EventId.make("event:seed-provider-thread"),
227 type: "provider-thread.updated",
228 threadId,
229 driver,
230 providerInstanceId: instanceId,
231 occurredAt: now,
232 payload: {
233 id: providerThreadId,
234 driver,
235 providerInstanceId: instanceId,
236 providerSessionId: null,
237 appThreadId: threadId,
238 ownerNodeId: rootNode,
239 nativeThreadRef: { driver, nativeId: "native:laptop", strength: "strong" },
240 nativeConversationHeadRef: null,
241 status: "active",
242 firstRunOrdinal: 1,
243 lastRunOrdinal: 1,
244 handoffIds: [],
245 forkedFrom: null,
246 createdAt: now,
247 updatedAt: now,
248 },
249 },
250 {
251 id: EventId.make("event:seed-node"),
252 type: "node.updated",
253 threadId,
254 runId,
255 nodeId: rootNode,
256 driver,
257 providerInstanceId: instanceId,
258 occurredAt: now,
259 payload: {
260 id: rootNode,
261 threadId,
262 runId,
263 parentNodeId: null,
264 rootNodeId: rootNode,
265 kind: "root_turn",
266 status: "running",
267 countsForRun: true,
268 providerThreadId,
269 providerTurnId: null,
270 nativeItemRef: null,
271 runtimeRequestId: null,
272 checkpointScopeId: null,
273 startedAt: now,
274 completedAt: null,
275 },
276 },
277 {
278 id: EventId.make("event:seed-run"),
279 type: "run.updated",
280 threadId,
281 runId,
282 nodeId: rootNode,
283 providerInstanceId: instanceId,
284 occurredAt: now,
285 payload: {
286 id: runId,
287 threadId,
288 ordinal: 1,
289 providerInstanceId: instanceId,
290 modelSelection,
291 providerThreadId,
292 userMessageId: MessageId.make("message:seed-user"),
293 rootNodeId: rootNode,
294 activeAttemptId: null,
295 status: "running",
296 requestedAt: now,
297 startedAt: now,
298 completedAt: null,
299 checkpointId: null,
300 contextHandoffId: null,
301 },
302 },
303 ],
304 });
305 });
306
307const cardOf = (a: Laptop) =>
308 a.orchestrator
309 .getThreadProjection(threadId)
310 .pipe(
311 Effect.map((projection) => projection.turnItems.find((item) => item.type === "link_request")),
312 );
313
314/** The open card the agent's call left, as the user's client sees it. */
315const pendingCard = (a: Laptop) =>
316 Effect.gen(function* () {
317 const card = yield* cardOf(a);
318 expect(card).toMatchObject({ status: "waiting", linkStatus: "pending" });
319 return card as Extract<NonNullable<typeof card>, { readonly type: "link_request" }>;
320 });
321
322/** The outcome notifications the thread received: what the agent reads and the user sees. */
323const outcomeMessages = (a: Laptop) =>
324 a.orchestrator.getThreadProjection(threadId).pipe(
325 Effect.map((projection) => ({
326 messages: projection.messages.filter((message) => message.notification !== undefined),
327 items: projection.turnItems.filter((item) => item.type === "notification"),
328 })),
329 );
330
331/** The agent's turn ends; the card outlives it. */
332const endRun = (a: Laptop) =>
333 Effect.gen(function* () {
334 const projection = yield* a.orchestrator.getThreadProjection(threadId);
335 const run = projection.runs.find((candidate) => candidate.id === runId)!;
336 const now = yield* DateTime.now;
337 yield* a.sink.write({
338 commandId: CommandId.make("command:end-run:laptop"),
339 events: [
340 {
341 id: EventId.make("event:end-run"),
342 type: "run.updated",
343 threadId,
344 runId,
345 nodeId: rootNode,
346 providerInstanceId: instanceId,
347 occurredAt: now,
348 payload: { ...run, status: "completed", completedAt: now },
349 },
350 ],
351 });
352 });
353
354/** A steer restarts the agent's turn: its run gets a new root node. */
355const restartRun = (a: Laptop) =>
356 Effect.gen(function* () {
357 const projection = yield* a.orchestrator.getThreadProjection(threadId);
358 const run = projection.runs.find((candidate) => candidate.id === runId)!;
359 const node = projection.nodes.find((candidate) => candidate.id === rootNode)!;
360 const restarted = NodeId.make("node:laptop:root:2");
361 const now = yield* DateTime.now;
362 yield* a.sink.write({
363 commandId: CommandId.make("command:restart-run:laptop"),
364 events: [
365 {
366 id: EventId.make("event:restart-node"),
367 type: "node.updated",
368 threadId,
369 runId,
370 nodeId: restarted,
371 driver,
372 providerInstanceId: instanceId,
373 occurredAt: now,
374 payload: { ...node, id: restarted, rootNodeId: restarted, startedAt: now },
375 },
376 {
377 id: EventId.make("event:restart-run"),
378 type: "run.updated",
379 threadId,
380 runId,
381 nodeId: restarted,
382 providerInstanceId: instanceId,
383 occurredAt: now,
384 payload: { ...run, rootNodeId: restarted },
385 },
386 ],
387 });
388 });
389
390/** What `request` records for a new card, as if it read the run before anything changed. */
391const recordPendingCard = (a: Laptop, key: string) =>
392 a.orchestrator.dispatch({
393 type: "link_request.record",
394 commandId: CommandId.make(`command:pending:${key}`),
395 threadId,
396 runId,
397 nodeId: rootNode,
398 turnItemId: TurnItemId.make(`turn-item:link-request:${key}`),
399 reason: "",
400 linkStatus: "pending",
401 });
402
403/**
404 * Every row of every table in the laptop's database, as text, to scan for
405 * anything leaked: events, projections, receipts and outbox alike.
406 */
407const storedText = (a: Laptop) =>
408 Effect.gen(function* () {
409 const tables = yield* a.sql<{ name: string }>`
410 SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
411 `;
412 const rows = yield* Effect.forEach(tables, ({ name }) =>
413 a.sql.unsafe<Record<string, unknown>>(`SELECT * FROM "${name}"`),
414 );
415 const text = rows
416 .flat()
417 .map((row) => JSON.stringify(row))
418 .join("\n");
419 // The scan saw the card itself, so it read what the thread recorded.
420 expect(text).toContain("link_request");
421 return text;
422 });
423
424const errorOf = (result: McpSchema.CallToolResult) => {
425 const text = result.content[0];
426 return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
427};
428
429/** Runs `effect` a year from now, when every link made today has expired. */
430const afterLinksExpire = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
431 Effect.gen(function* () {
432 const clock = yield* Clock.Clock;
433 const ahead = Duration.days(365);
434 const later = () => clock.currentTimeMillisUnsafe() + Duration.toMillis(ahead);
435 const laterNanos = () => clock.currentTimeNanosUnsafe() + Duration.toNanosUnsafe(ahead);
436 return yield* effect.pipe(
437 Effect.provideService(Clock.Clock, {
438 currentTimeMillisUnsafe: later,
439 currentTimeMillis: Effect.sync(later),
440 currentTimeNanosUnsafe: laterNanos,
441 currentTimeNanos: Effect.sync(laterNanos),
442 monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(),
443 monotonicTimeNanos: clock.monotonicTimeNanos,
444 sleep: (duration) => clock.sleep(duration),
445 }),
446 );
447 });
448
449const withBoth = <A, E, R>(body: (a: Laptop, b: ServedPeer) => Effect.Effect<A, E, R>) =>
450 Effect.scoped(
451 Effect.gen(function* () {
452 const b = yield* serveBox;
453 const a = yield* makeLaptop;
454 return yield* body(a, b);
455 }),
456 ).pipe(Effect.provide(NodeHttpServer.layerTest));
457
458it.live("the agent asks without waiting, and the user links the box after its turn ended", () =>
459 withBoth((a, b) =>
460 Effect.gen(function* () {
461 yield* seedThread(a);
462 const asked = yield* a.call({
463 url: b.url,
464 reason: "Run the suite on the box.",
465 requestedAccess: "approval-required",
466 clientRequestId: "link-box",
467 });
468 const card = yield* pendingCard(a);
469 // The call returns at once: no tool call outlives a provider's timeout.
470 expect(asked.isError).toBe(false);
471 expect(asked.structuredContent).toEqual({ status: "pending", turnItemId: card.id });
472 // The card names the box, found by asking its address.
473 expect(card).toMatchObject({
474 url: b.url,
475 reason: "Run the suite on the box.",
476 environmentId: box.environmentId,
477 label: "Box",
478 requestedAccess: "approval-required",
479 });
480 // The agent waits on the user, so the thread asks for input.
481 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
482 { kind: "user_input" },
483 );
484
485 // The agent ends its turn; the card stays answerable, and the thread still asks.
486 yield* endRun(a);
487 expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
488 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
489 { kind: "user_input" },
490 );
491 expect(
492 ProjectionStore.threadShellFromProjection(
493 yield* a.orchestrator.getThreadProjection(threadId),
494 ).pendingRuntimeRequest,
495 ).toMatchObject({ kind: "user_input" });
496 expect(yield* a.projections.getSettlementCandidates(threadId)).toEqual([]);
497
498 // Once the user writes in the thread again, the card stops asking but stays answerable.
499 const wroteAt = DateTime.add(card.startedAt!, { seconds: 1 });
500 yield* a.sink.write({
501 commandId: CommandId.make("command:user-writes:laptop"),
502 events: [
503 {
504 id: EventId.make("event:user-writes"),
505 type: "message.updated",
506 threadId,
507 occurredAt: wroteAt,
508 payload: {
509 createdBy: "user",
510 creationSource: "web",
511 id: MessageId.make("message:user-writes"),
512 threadId,
513 runId: null,
514 nodeId: null,
515 role: "user",
516 text: "Something else",
517 attachments: [],
518 streaming: false,
519 createdAt: wroteAt,
520 updatedAt: wroteAt,
521 },
522 },
523 ],
524 });
525 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
526 expect(
527 ProjectionStore.threadShellFromProjection(
528 yield* a.orchestrator.getThreadProjection(threadId),
529 ).pendingRuntimeRequest,
530 ).toBeNull();
531 expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
532
533 // The user's client mints a code on the box and picks more than the agent suggested.
534 const pairing = yield* b.auth.issuePairingCredential();
535 yield* a.requests.answer({
536 threadId,
537 turnItemId: card.id,
538 answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
539 });
540
541 const link = yield* a.links.get(box.environmentId);
542 expect(Option.getOrUndefined(link)?.access).toBe("auto");
543 expect(yield* cardOf(a)).toMatchObject({
544 status: "completed",
545 linkStatus: "linked",
546 linkedEnvironmentId: box.environmentId,
547 linkedLabel: "Box",
548 linkedAccess: "auto",
549 });
550 expect((yield* b.linkedSessions).length).toBe(1);
551
552 // The agent hears it as a notification in its thread, not a user message.
553 const { messages, items } = yield* outcomeMessages(a);
554 expect(messages).toHaveLength(1);
555 expect(messages[0]).toMatchObject({
556 role: "user",
557 createdBy: "agent",
558 creationSource: "server",
559 notification: { outcome: "completed", summary: "Linked Box" },
560 });
561 expect(messages[0]!.text).toContain(box.environmentId);
562 expect(messages[0]!.text).toContain("auto");
563 expect(items).toHaveLength(1);
564 expect(items[0]).toMatchObject({ type: "notification", summary: "Linked Box" });
565
566 // The code appears in nothing the thread recorded or the agent received.
567 expect(yield* storedText(a)).not.toContain(pairing.credential);
568
569 // A card is answered once.
570 const again = yield* a.requests
571 .answer({ threadId, turnItemId: card.id, answer: { type: "decline" } })
572 .pipe(Effect.flip);
573 expect(again.reason).toBe("already_answered");
574
575 // A retry that lost the first result gets the card's outcome, and records nothing.
576 const before = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.length;
577 const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
578 expect(retried.structuredContent).toEqual({
579 status: "linked",
580 environmentId: box.environmentId,
581 label: "Box",
582 access: "auto",
583 });
584 expect((yield* a.orchestrator.getThreadProjection(threadId)).turnItems).toHaveLength(before);
585 expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
586 }),
587 ),
588);
589
590it.live("a retry of a pending request returns pending and shows no second card", () =>
591 withBoth((a, b) =>
592 Effect.gen(function* () {
593 yield* seedThread(a);
594 const first = yield* a.call({ url: b.url, clientRequestId: "link-box" });
595 const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
596 expect(retried.structuredContent).toEqual(first.structuredContent);
597 const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
598 (item) => item.type === "link_request",
599 );
600 expect(cards).toHaveLength(1);
601 }),
602 ),
603);
604
605it.live("a new MCP credential reusing a clientRequestId gets a card of its own", () =>
606 withBoth((a, b) =>
607 Effect.gen(function* () {
608 yield* seedThread(a);
609 const first = yield* a.call({ url: b.url, clientRequestId: "link" });
610 const later = yield* a.call(
611 { environmentId: box.environmentId, clientRequestId: "link" },
612 {
613 ...scope,
614 requestNamespace: "provider-session:laptop-2",
615 thread: { ...scope.thread!, providerSessionId: "provider-session:laptop-2" },
616 },
617 );
618 expect(later.structuredContent).toMatchObject({ status: "pending" });
619 expect(later.structuredContent).not.toEqual(first.structuredContent);
620 const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
621 (item) => item.type === "link_request",
622 );
623 expect(cards).toHaveLength(2);
624 }),
625 ),
626);
627
628it.live("a declined request links nothing and tells the agent", () =>
629 withBoth((a, b) =>
630 Effect.gen(function* () {
631 yield* seedThread(a);
632 yield* a.call({ url: b.url });
633 const card = yield* pendingCard(a);
634 yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
635 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
636 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "declined" });
637 const { messages } = yield* outcomeMessages(a);
638 expect(messages).toHaveLength(1);
639 expect(messages[0]).toMatchObject({
640 notification: { outcome: "cancelled", summary: "Declined to link Box" },
641 });
642 expect(messages[0]!.text).toContain("declined");
643 }),
644 ),
645);
646
647it.live("stopping the thread closes its open card, which then takes no answer", () =>
648 withBoth((a, b) =>
649 Effect.gen(function* () {
650 yield* seedThread(a);
651 yield* a.call({ url: b.url });
652 const card = yield* pendingCard(a);
653 yield* a.orchestrator.dispatch({
654 type: "thread.stop",
655 commandId: CommandId.make("command:stop:laptop"),
656 threadId,
657 });
658 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
659 const late = yield* a.requests
660 .answer({
661 threadId,
662 turnItemId: card.id,
663 answer: { type: "link", urls: [b.url], access: "auto", pairingCode: "late-code" },
664 })
665 .pipe(Effect.flip);
666 expect(late.reason).toBe("already_answered");
667 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
668 // An answer already linking when Stop landed keeps the card closed and wakes nobody.
669 yield* a.orchestrator.dispatch({
670 type: "link_request.record",
671 commandId: CommandId.make("command:late-answer:laptop"),
672 threadId,
673 runId,
674 nodeId: rootNode,
675 turnItemId: card.id,
676 url: card.url,
677 reason: card.reason,
678 linkStatus: "declined",
679 wake: {
680 messageId: MessageId.make("message:late-answer"),
681 text: "The user declined.",
682 notification: {
683 source: { kind: "background_task" },
684 outcome: "cancelled",
685 summary: "Declined",
686 },
687 },
688 });
689 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
690 // The user stopped the thread: nothing wakes the agent.
691 expect((yield* outcomeMessages(a)).messages).toHaveLength(0);
692 }),
693 ),
694);
695
696it.live("a request that read the run before Stop shows no card once Stop lands", () =>
697 withBoth((a, b) =>
698 Effect.gen(function* () {
699 yield* seedThread(a);
700 yield* a.call({ url: b.url });
701 const open = yield* pendingCard(a);
702 yield* a.orchestrator.dispatch({
703 type: "thread.stop",
704 commandId: CommandId.make("command:stop:laptop"),
705 threadId,
706 });
707 const late = yield* recordPendingCard(a, "after-stop").pipe(Effect.flip);
708 expect(String(late.cause)).toContain("not active");
709 const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
710 (item) => item.type === "link_request",
711 );
712 expect(cards.map((card) => card.id)).toEqual([open.id]);
713 }),
714 ),
715);
716
717it.live("a card shows up only while its run is going, and takes an answer after", () =>
718 withBoth((a, b) =>
719 Effect.gen(function* () {
720 yield* seedThread(a);
721 yield* a.call({ url: b.url });
722 const card = yield* pendingCard(a);
723 yield* endRun(a);
724 const late = yield* recordPendingCard(a, "after-end").pipe(Effect.flip);
725 expect(String(late.cause)).toContain("not active");
726 yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
727 expect(yield* cardOf(a)).toMatchObject({ linkStatus: "declined" });
728 }),
729 ),
730);
731
732it.live("a steer that restarts the turn leaves its open card answerable", () =>
733 withBoth((a, b) =>
734 Effect.gen(function* () {
735 yield* seedThread(a);
736 yield* a.call({ url: b.url });
737 const card = yield* pendingCard(a);
738 yield* restartRun(a);
739 const pairing = yield* b.auth.issuePairingCredential();
740 yield* a.requests.answer({
741 threadId,
742 turnItemId: card.id,
743 answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
744 });
745 // The card keeps the node it was asked from, and the agent hears the answer.
746 expect(yield* cardOf(a)).toMatchObject({
747 linkStatus: "linked",
748 nodeId: rootNode,
749 linkedEnvironmentId: box.environmentId,
750 });
751 expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
752 }),
753 ),
754);
755
756it.live("a slow machine holds up only its own card's answer", () =>
757 withBoth((a, b) =>
758 Effect.scoped(
759 Effect.gen(function* () {
760 // A machine that takes the descriptor request and answers when the test says.
761 const reached = yield* Deferred.make<void>();
762 const release = yield* Deferred.make<void>();
763 const slow = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest));
764 const server = Context.get(slow, HttpServer.HttpServer);
765 yield* server.serve(
766 Deferred.succeed(reached, undefined).pipe(
767 Effect.andThen(Deferred.await(release)),
768 Effect.as(HttpServerResponse.empty({ status: 404 })),
769 ),
770 );
771 if (server.address._tag === "UnixPathAddress") return yield* Effect.die("expected TCP");
772 const slowUrl = `http://127.0.0.1:${server.address.port}`;
773
774 yield* seedThread(a);
775 // Recorded directly: asking would probe the slow machine before the answer does.
776 const slowCard = { id: TurnItemId.make("turn-item:link-request:slow") };
777 yield* a.orchestrator.dispatch({
778 type: "link_request.record",
779 commandId: CommandId.make("command:pending:slow"),
780 threadId,
781 runId,
782 nodeId: rootNode,
783 turnItemId: slowCard.id,
784 url: slowUrl,
785 reason: "",
786 linkStatus: "pending",
787 });
788 yield* a.call({ url: b.url, clientRequestId: "box" });
789 const boxCard = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
790 (item) => item.type === "link_request" && item.url === b.url,
791 )!;
792
793 const slowAnswer = yield* a.requests
794 .answer({
795 threadId,
796 turnItemId: slowCard.id,
797 answer: { type: "link", urls: [slowUrl], access: "auto", pairingCode: "code" },
798 })
799 .pipe(Effect.forkChild);
800 yield* Deferred.await(reached);
801
802 // While the slow machine holds its card, the user answers the other one.
803 yield* a.requests.answer({ threadId, turnItemId: boxCard.id, answer: { type: "decline" } });
804 const items = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems;
805 expect(items.find((item) => item.id === boxCard.id)).toMatchObject({
806 linkStatus: "declined",
807 });
808 expect(items.find((item) => item.id === slowCard.id)).toMatchObject({
809 linkStatus: "pending",
810 });
811
812 yield* Deferred.succeed(release, undefined);
813 yield* Fiber.join(slowAnswer);
814 const failed = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
815 (item) => item.id === slowCard.id,
816 );
817 expect(failed).toMatchObject({ linkStatus: "failed" });
818 }),
819 ),
820 ),
821);
822
823it.live("archiving the thread closes its open card", () =>
824 withBoth((a, b) =>
825 Effect.gen(function* () {
826 yield* seedThread(a);
827 yield* a.call({ url: b.url });
828 yield* pendingCard(a);
829 yield* endRun(a);
830 yield* a.orchestrator.dispatch({
831 type: "thread.archive",
832 commandId: CommandId.make("command:archive:laptop"),
833 threadId,
834 });
835 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
836 }),
837 ),
838);
839
840it.live("a code the box refuses fails the request with its reason, and links nothing", () =>
841 withBoth((a, b) =>
842 Effect.gen(function* () {
843 yield* seedThread(a);
844 yield* a.call({ url: b.url });
845 const card = yield* pendingCard(a);
846 yield* a.requests.answer({
847 threadId,
848 turnItemId: card.id,
849 answer: {
850 type: "link",
851 urls: [b.url],
852 access: "auto",
853 pairingCode: "not-a-real-code",
854 },
855 });
856 const failed = yield* cardOf(a);
857 expect(failed).toMatchObject({ status: "failed", linkStatus: "failed" });
858 const reason = failed?.type === "link_request" ? failed.failure : undefined;
859 expect(reason?.length).toBeGreaterThan(0);
860 const { messages } = yield* outcomeMessages(a);
861 expect(messages[0]).toMatchObject({ notification: { outcome: "failed" } });
862 expect(messages[0]!.text).toContain(reason);
863 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
864 expect(yield* storedText(a)).not.toContain("not-a-real-code");
865 }),
866 ),
867);
868
869it.live("an agent below full access may not ask, and no card is shown", () =>
870 withBoth((a, b) =>
871 Effect.gen(function* () {
872 yield* seedThread(a, "auto");
873 const refused = yield* a.call({ url: b.url });
874 expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
875 expect(yield* cardOf(a)).toBeUndefined();
876 }),
877 ),
878);
879
880it.live("work another environment's link started may not ask, and no card is shown", () =>
881 withBoth((a, b) =>
882 Effect.gen(function* () {
883 yield* seedThread(a, "full-access", { sessionId: "session:desk", label: "T3 Code · Desk" });
884 const refused = yield* a.call({ url: b.url });
885 expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
886 expect(errorOf(refused).message).toContain("T3 Code · Desk");
887 expect(yield* cardOf(a)).toBeUndefined();
888 }),
889 ),
890);
891
892it.live(
893 "an agent that names no machine leaves the pick to the user, who links one by its addresses",
894 () =>
895 withBoth((a, b) =>
896 Effect.gen(function* () {
897 yield* seedThread(a);
898 const asked = yield* a.call({ reason: "Delegate the build to the vps.", hint: "vps" });
899 expect(asked.structuredContent).toMatchObject({ status: "pending" });
900 const card = yield* pendingCard(a);
901 expect(card).toMatchObject({ reason: "Delegate the build to the vps.", hint: "vps" });
902 expect(card.url).toBeUndefined();
903 expect(card.environmentId).toBeUndefined();
904
905 // The user picks the box; their client knows a stale address for it first.
906 const pairing = yield* b.auth.issuePairingCredential();
907 yield* a.requests.answer({
908 threadId,
909 turnItemId: card.id,
910 answer: {
911 type: "link",
912 environmentId: box.environmentId,
913 label: "Box",
914 urls: ["http://127.0.0.1:9", b.url],
915 access: "auto",
916 pairingCode: pairing.credential,
917 },
918 });
919 expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))).toMatchObject({
920 urls: [b.url],
921 access: "auto",
922 });
923 expect(yield* cardOf(a)).toMatchObject({
924 linkStatus: "linked",
925 linkedEnvironmentId: box.environmentId,
926 });
927 expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("linked Box");
928 }),
929 ),
930);
931
932it.live("naming a machine that is already linked returns the link at once, with no card", () =>
933 withBoth((a, b) =>
934 Effect.gen(function* () {
935 yield* seedThread(a);
936 const pairing = yield* b.auth.issuePairingCredential();
937 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
938 const asked = yield* a.call({ environmentId: box.environmentId });
939 expect(asked.structuredContent).toEqual({
940 status: "linked",
941 environmentId: box.environmentId,
942 label: "Box",
943 access: "auto",
944 });
945 expect(yield* cardOf(a)).toBeUndefined();
946
947 // Not both: the address could name another machine than the id.
948 const both = yield* a.call({ environmentId: box.environmentId, url: b.url });
949 expect(errorOf(both)).toMatchObject({ code: "invalid_request" });
950 }),
951 ),
952);
953
954it.live("a retry naming a machine linked meanwhile closes the card it left as linked", () =>
955 withBoth((a, b) =>
956 Effect.gen(function* () {
957 yield* seedThread(a);
958 yield* a.call({ url: b.url, clientRequestId: "link-box" });
959 yield* pendingCard(a);
960 // Linked from Settings meanwhile, not through the card.
961 const pairing = yield* b.auth.issuePairingCredential();
962 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
963
964 const retried = yield* a.call({
965 environmentId: box.environmentId,
966 clientRequestId: "link-box",
967 });
968 expect(retried.structuredContent).toEqual({
969 status: "linked",
970 environmentId: box.environmentId,
971 label: "Box",
972 access: "auto",
973 });
974 expect(yield* cardOf(a)).toMatchObject({
975 linkStatus: "linked",
976 linkedEnvironmentId: box.environmentId,
977 });
978 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
979 }),
980 ),
981);
982
983it.live("a link that expired goes through the card, so the user can link it again", () =>
984 withBoth((a, b) =>
985 Effect.gen(function* () {
986 yield* seedThread(a);
987 yield* linkTo(a.links, b, "read-only");
988 const asked = yield* a.call({ environmentId: box.environmentId }).pipe(afterLinksExpire);
989 expect(asked.structuredContent).toMatchObject({ status: "pending" });
990 const card = yield* pendingCard(a);
991
992 // Keeping the expired link is no answer: the card fails and says why.
993 yield* a.requests
994 .answer({
995 threadId,
996 turnItemId: card.id,
997 answer: { type: "use-existing", environmentId: box.environmentId },
998 })
999 .pipe(afterLinksExpire);
1000 expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
1001 expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("expired");
1002 }),
1003 ),
1004);
1005
1006it.live("a link made before links were fenced goes through the card, as an expired one", () =>
1007 withBoth((a, b) =>
1008 Effect.gen(function* () {
1009 yield* seedThread(a);
1010 yield* linkTo(a.links, b);
1011 yield* a.linksSql`UPDATE peer_environment_links SET fenced = 0`;
1012 const asked = yield* a.call({ environmentId: box.environmentId });
1013 expect(asked.structuredContent).toMatchObject({ status: "pending" });
1014 yield* pendingCard(a);
1015 }),
1016 ),
1017);
1018
1019it.live(
1020 "a card for a machine named by id keeps it, and the user may keep a link it already has",
1021 () =>
1022 withBoth((a, b) =>
1023 Effect.gen(function* () {
1024 yield* seedThread(a);
1025 yield* a.call({ environmentId: box.environmentId });
1026 const card = yield* pendingCard(a);
1027 expect(card.environmentId).toBe(box.environmentId);
1028 // Linked from Settings meanwhile; the card answers with that link.
1029 const pairing = yield* b.auth.issuePairingCredential();
1030 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "read-only" });
1031 yield* a.requests.answer({
1032 threadId,
1033 turnItemId: card.id,
1034 answer: { type: "use-existing", environmentId: box.environmentId },
1035 });
1036 expect(yield* cardOf(a)).toMatchObject({
1037 linkStatus: "linked",
1038 linkedAccess: "read-only",
1039 });
1040 expect((yield* b.linkedSessions).length).toBe(1);
1041 }),
1042 ),
1043);