Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerLinkRequests.test.ts

1,474 lines54.1 KB

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 type PeerLinkCreateInput,
11 ProjectId,
12 ProviderDriverKind,
13 ProviderInstanceId,
14 ProviderThreadId,
15 type RuntimeMode,
16 RunId,
17 ThreadId,
18 TurnItemId,
19} from "@t3tools/contracts";
20import { expect, it } from "@effect/vitest";
21import * as Clock from "effect/Clock";
22import * as Context from "effect/Context";
23import * as DateTime from "effect/DateTime";
24import * as Deferred from "effect/Deferred";
25import * as Duration from "effect/Duration";
26import * as Effect from "effect/Effect";
27import * as Fiber from "effect/Fiber";
28import * as HttpServer from "effect/http/HttpServer";
29import * as HttpServerResponse from "effect/http/HttpServerResponse";
30import * as Layer from "effect/Layer";
31import * as Option from "effect/Option";
32import * as Schema from "effect/Schema";
33import * as SqlClient from "effect/sql/SqlClient";
34import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
35​
36import * as ServerConfig from "../config.ts";
37import * as McpHttpServer from "../mcp/McpHttpServer.ts";
38import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
39import * as McpToolAccess from "../mcp/McpToolAccess.ts";
40import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
41import * as EventSink from "../orchestration-v2/EventSink.ts";
42import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
43import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
44import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
45import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
46import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
47import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
48import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
49import * as SqlitePersistence from "../persistence/Sqlite.ts";
50import * as ProjectService from "../project/ProjectService.ts";
51import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
52import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
53import * as SecretRequests from "../secrets/SecretRequests.ts";
54import * as ServerSettings from "../serverSettings.ts";
55import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
56import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
57import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
58import * as PeerForwarding from "./PeerForwarding.ts";
59import * as PeerLinkRequests from "./PeerLinkRequests.ts";
60import * as PeerLinks from "./PeerLinks.ts";
61import {
62 descriptorOf,
63 layerLinkingEnvironment,
64 linkTo,
65 servePeer,
66 type ServedPeer,
67} from "./PeerLinks.testkit.ts";
68import * as RemoteDelegation from "./RemoteDelegation.ts";
69​
70// The laptop's agent asks the user to link the box. The laptop is its real
71// orchestrator and toolkit; the box is its real descriptor and MCP OAuth on a
72// socket. The user's answer goes through PeerLinkRequests, as the card's does.
73​
74const laptop = descriptorOf("environment-laptop", "Laptop");
75const box = descriptorOf("environment-box", "Box");
76const instanceId = ProviderInstanceId.make("codex");
77const driver = ProviderDriverKind.make("codex");
78const modelSelection = { instanceId, model: "gpt-5.4" };
79const threadId = ThreadId.make("thread:laptop");
80const runId = RunId.make("run:laptop");
81const rootNode = NodeId.make("node:laptop:root");
82​
83/** The box needs no tools of its own: linking only signs in to its /mcp. */
84const NoTools = Toolkit.make(
85 Tool.make("noop", { success: Schema.Struct({}), failure: OrchestratorMcpFailure }),
86);
87const serveBox = servePeer(
88 box,
89 McpHttpServer.toolkitRegistration(
90 NoTools,
91 McpToolAccess.toLayer(NoTools, { noop: McpToolAccess.reads(() => Effect.succeed({})) }),
92 ),
93);
94​
95const adapter = {
96 instanceId,
97 driver,
98 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
99 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
100 openSession: () => Effect.die("No provider process needed"),
101} as ProviderAdapter.ProviderAdapterV2["Service"];
102​
103const mcpClient = McpSchema.McpServerClient.of({
104 clientId: 1,
105 protocolVersion: "2025-06-18",
106 clientCapabilities: {},
107 clientInfo: { name: "peer-link-requests", version: "1" },
108 initializePayload: {
109 protocolVersion: "2025-06-18",
110 capabilities: {},
111 clientInfo: { name: "peer-link-requests", version: "1" },
112 },
113 getClient: Effect.die("unused"),
114});
115​
116const scope: McpInvocationContext.McpInvocationScope = {
117 environmentId: laptop.environmentId,
118 requestNamespace: "provider-session:laptop",
119 thread: {
120 threadId,
121 providerSessionId: "provider-session:laptop",
122 providerInstanceId: instanceId,
123 },
124 client: undefined,
125 capabilities: new Set(["orchestration"]),
126 issuedAt: 1,
127};
128​
129/** A real orchestrator and links; the wrapper can hold a link in progress. */
130const makeLaptopWith = (
131 wrapLinks?: (links: PeerLinks.PeerLinks["Service"]) => PeerLinks.PeerLinks["Service"],
132) =>
133 Effect.gen(function* () {
134 const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
135 const answering =
136 wrapLinks === undefined
137 ? linking
138 : Context.add(
139 linking,
140 PeerLinks.PeerLinks,
141 wrapLinks(Context.get(linking, PeerLinks.PeerLinks)),
142 );
143 // The orchestrator's own database, apart from the one links are kept in.
144 const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
145 const layerDatabase = Layer.succeedContext(database);
146 const layerOrchestrator = Layer.mergeAll(
147 layerDatabase,
148 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
149 ProviderReplayHarness.layerWithRegistry(
150 { name: "peer-link-requests" },
151 ProviderAdapterRegistry.layerFromAdapters([adapter]),
152 { databaseLayer: layerDatabase, runEffectWorker: false },
153 ),
154 ).pipe(
155 Layer.provide(
156 Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
157 offer: () => Effect.void,
158 take: Effect.never,
159 }),
160 ),
161 );
162 const layerThreads = ThreadManagement.layer.pipe(
163 Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
164 Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
165 );
166 const layerHere = McpHttpServer.layerOrchestratorToolkit.pipe(
167 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
168 Layer.provideMerge(PeerLinkRequests.layer),
169 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
170 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
171 Layer.provide(Layer.succeedContext(answering)),
172 Layer.provide(NodeCrypto.layer),
173 Layer.provideMerge(layerThreads),
174 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
175 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
176 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
177 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
178 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
179 Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
180 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
181 Layer.provide(
182 ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-requests-" }).pipe(
183 Layer.provide(NodeServices.layer),
184 ),
185 ),
186 Layer.provide(NodeServices.layer),
187 Layer.fresh,
188 );
189 const here = yield* Layer.build(layerHere);
190 const server = Context.get(here, McpServer.McpServer);
191 return {
192 links: Context.get(linking, PeerLinks.PeerLinks),
193 linksSql: Context.get(linking, SqlClient.SqlClient),
194 requests: Context.get(here, PeerLinkRequests.PeerLinkRequests),
195 orchestrator: Context.get(here, Orchestrator.OrchestratorV2),
196 sink: Context.get(here, EventSink.EventSinkV2),
197 projections: Context.get(here, ProjectionStore.ProjectionStoreV2),
198 sql: Context.get(database, SqlClient.SqlClient),
199 call: (args: Record<string, unknown>, callScope = scope) =>
200 server
201 .callTool({ name: "t3_environment_link", arguments: args })
202 .pipe(
203 Effect.provideService(McpInvocationContext.McpInvocationContext, callScope),
204 Effect.provideService(McpSchema.McpServerClient, mcpClient),
205 ),
206 };
207 });
208const makeLaptop = makeLaptopWith();
209type Laptop = Effect.Success<typeof makeLaptop>;
210​
211/** The laptop's thread, mid-turn when its agent asks, in `runtimeMode`. */
212const seedThread = (
213 a: Laptop,
214 runtimeMode: RuntimeMode = "full-access",
215 linkOrigin?: { readonly sessionId: string; readonly label: string },
216) =>
217 Effect.gen(function* () {
218 const now = yield* DateTime.now;
219 const providerThreadId = ProviderThreadId.make("provider-thread:laptop");
220 yield* a.orchestrator.dispatch({
221 type: "thread.create",
222 createdBy: "user",
223 creationSource: "web",
224 commandId: CommandId.make("command:create:laptop"),
225 threadId,
226 projectId: ProjectId.make("project:laptop"),
227 title: "Laptop",
228 modelSelection,
229 runtimeMode,
230 interactionMode: "default",
231 branch: null,
232 worktreePath: null,
233 ...(linkOrigin === undefined ? {} : { linkOrigin }),
234 });
235 yield* a.sink.write({
236 commandId: CommandId.make("command:seed:laptop"),
237 events: [
238 {
239 id: EventId.make("event:seed-provider-thread"),
240 type: "provider-thread.updated",
241 threadId,
242 driver,
243 providerInstanceId: instanceId,
244 occurredAt: now,
245 payload: {
246 id: providerThreadId,
247 driver,
248 providerInstanceId: instanceId,
249 providerSessionId: null,
250 appThreadId: threadId,
251 ownerNodeId: rootNode,
252 nativeThreadRef: { driver, nativeId: "native:laptop", strength: "strong" },
253 nativeConversationHeadRef: null,
254 status: "active",
255 firstRunOrdinal: 1,
256 lastRunOrdinal: 1,
257 handoffIds: [],
258 forkedFrom: null,
259 createdAt: now,
260 updatedAt: now,
261 },
262 },
263 {
264 id: EventId.make("event:seed-node"),
265 type: "node.updated",
266 threadId,
267 runId,
268 nodeId: rootNode,
269 driver,
270 providerInstanceId: instanceId,
271 occurredAt: now,
272 payload: {
273 id: rootNode,
274 threadId,
275 runId,
276 parentNodeId: null,
277 rootNodeId: rootNode,
278 kind: "root_turn",
279 status: "running",
280 countsForRun: true,
281 providerThreadId,
282 providerTurnId: null,
283 nativeItemRef: null,
284 runtimeRequestId: null,
285 checkpointScopeId: null,
286 startedAt: now,
287 completedAt: null,
288 },
289 },
290 {
291 id: EventId.make("event:seed-run"),
292 type: "run.updated",
293 threadId,
294 runId,
295 nodeId: rootNode,
296 providerInstanceId: instanceId,
297 occurredAt: now,
298 payload: {
299 id: runId,
300 threadId,
301 ordinal: 1,
302 providerInstanceId: instanceId,
303 modelSelection,
304 providerThreadId,
305 userMessageId: MessageId.make("message:seed-user"),
306 rootNodeId: rootNode,
307 activeAttemptId: null,
308 status: "running",
309 requestedAt: now,
310 startedAt: now,
311 completedAt: null,
312 checkpointId: null,
313 contextHandoffId: null,
314 },
315 },
316 ],
317 });
318 });
319​
320const cardOf = (a: Laptop) =>
321 a.orchestrator
322 .getThreadProjection(threadId)
323 .pipe(
324 Effect.map((projection) => projection.turnItems.find((item) => item.type === "link_request")),
325 );
326​
327/** The open card the agent's call left, as the user's client sees it. */
328const pendingCard = (a: Laptop) =>
329 Effect.gen(function* () {
330 const card = yield* cardOf(a);
331 expect(card).toMatchObject({ status: "waiting", linkStatus: "pending" });
332 return card as Extract<NonNullable<typeof card>, { readonly type: "link_request" }>;
333 });
334​
335/** The outcome notifications the thread received: what the agent reads and the user sees. */
336const outcomeMessages = (a: Laptop) =>
337 a.orchestrator.getThreadProjection(threadId).pipe(
338 Effect.map((projection) => ({
339 messages: projection.messages.filter((message) => message.notification !== undefined),
340 items: projection.turnItems.filter((item) => item.type === "notification"),
341 })),
342 );
343​
344/** The agent's turn ends; the card outlives it. */
345const endRun = (a: Laptop) =>
346 Effect.gen(function* () {
347 const projection = yield* a.orchestrator.getThreadProjection(threadId);
348 const run = projection.runs.find((candidate) => candidate.id === runId)!;
349 const now = yield* DateTime.now;
350 yield* a.sink.write({
351 commandId: CommandId.make("command:end-run:laptop"),
352 events: [
353 {
354 id: EventId.make("event:end-run"),
355 type: "run.updated",
356 threadId,
357 runId,
358 nodeId: rootNode,
359 providerInstanceId: instanceId,
360 occurredAt: now,
361 payload: { ...run, status: "completed", completedAt: now },
362 },
363 ],
364 });
365 });
366​
367/** A steer restarts the agent's turn: its run gets a new root node. */
368const restartRun = (a: Laptop) =>
369 Effect.gen(function* () {
370 const projection = yield* a.orchestrator.getThreadProjection(threadId);
371 const run = projection.runs.find((candidate) => candidate.id === runId)!;
372 const node = projection.nodes.find((candidate) => candidate.id === rootNode)!;
373 const restarted = NodeId.make("node:laptop:root:2");
374 const now = yield* DateTime.now;
375 yield* a.sink.write({
376 commandId: CommandId.make("command:restart-run:laptop"),
377 events: [
378 {
379 id: EventId.make("event:restart-node"),
380 type: "node.updated",
381 threadId,
382 runId,
383 nodeId: restarted,
384 driver,
385 providerInstanceId: instanceId,
386 occurredAt: now,
387 payload: { ...node, id: restarted, rootNodeId: restarted, startedAt: now },
388 },
389 {
390 id: EventId.make("event:restart-run"),
391 type: "run.updated",
392 threadId,
393 runId,
394 nodeId: restarted,
395 providerInstanceId: instanceId,
396 occurredAt: now,
397 payload: { ...run, rootNodeId: restarted },
398 },
399 ],
400 });
401 });
402​
403/** What `request` records for a new card, as if it read the run before anything changed. */
404const recordPendingCard = (a: Laptop, key: string) =>
405 a.orchestrator.dispatch({
406 type: "link_request.record",
407 commandId: CommandId.make(`command:pending:${key}`),
408 threadId,
409 runId,
410 nodeId: rootNode,
411 turnItemId: TurnItemId.make(`turn-item:link-request:${key}`),
412 reason: "",
413 linkStatus: "pending",
414 });
415​
416/**
417 * Every row of every table in the laptop's database, as text, to scan for
418 * anything leaked: events, projections, receipts and outbox alike.
419 */
420const storedText = (a: Laptop) =>
421 Effect.gen(function* () {
422 const tables = yield* a.sql<{ name: string }>`
423 SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
424 `;
425 const rows = yield* Effect.forEach(tables, ({ name }) =>
426 a.sql.unsafe<Record<string, unknown>>(`SELECT * FROM "${name}"`),
427 );
428 const text = rows
429 .flat()
430 .map((row) => JSON.stringify(row))
431 .join("\n");
432 // The scan saw the card itself, so it read what the thread recorded.
433 expect(text).toContain("link_request");
434 return text;
435 });
436​
437const errorOf = (result: McpSchema.CallToolResult) => {
438 const text = result.content[0];
439 return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
440};
441​
442/** Runs `effect` a year from now, when every link made today has expired. */
443const afterLinksExpire = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
444 Effect.gen(function* () {
445 const clock = yield* Clock.Clock;
446 const ahead = Duration.days(365);
447 const later = () => clock.currentTimeMillisUnsafe() + Duration.toMillis(ahead);
448 const laterNanos = () => clock.currentTimeNanosUnsafe() + Duration.toNanosUnsafe(ahead);
449 return yield* effect.pipe(
450 Effect.provideService(Clock.Clock, {
451 currentTimeMillisUnsafe: later,
452 currentTimeMillis: Effect.sync(later),
453 currentTimeNanosUnsafe: laterNanos,
454 currentTimeNanos: Effect.sync(laterNanos),
455 monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(),
456 monotonicTimeNanos: clock.monotonicTimeNanos,
457 sleep: (duration) => clock.sleep(duration),
458 }),
459 );
460 });
461​
462const withBoth = <A, E, R>(body: (a: Laptop, b: ServedPeer) => Effect.Effect<A, E, R>) =>
463 Effect.scoped(
464 Effect.gen(function* () {
465 const b = yield* serveBox;
466 const a = yield* makeLaptop;
467 return yield* body(a, b);
468 }),
469 ).pipe(Effect.provide(NodeHttpServer.layerTest));
470​
471it.live("the agent asks without waiting, and the user links the box after its turn ended", () =>
472 withBoth((a, b) =>
473 Effect.gen(function* () {
474 yield* seedThread(a);
475 const asked = yield* a.call({
476 url: b.url,
477 reason: "Run the suite on the box.",
478 requestedAccess: "approval-required",
479 clientRequestId: "link-box",
480 });
481 const card = yield* pendingCard(a);
482 // The call returns at once: no tool call outlives a provider's timeout.
483 expect(asked.isError).toBe(false);
484 expect(asked.structuredContent).toEqual({ status: "pending", turnItemId: card.id });
485 expect(card).toMatchObject({
486 url: b.url,
487 reason: "Run the suite on the box.",
488 requestedAccess: "approval-required",
489 });
490 // Anything can answer at an address as the box, so the card names no machine.
491 expect(card.environmentId).toBeUndefined();
492 expect(card.label).toBeUndefined();
493 // The agent waits on the user, so the thread asks for input.
494 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
495 { kind: "user_input" },
496 );
497​
498 for (const secretStatus of ["pending", "saved"] as const) {
499 yield* a.orchestrator.dispatch({
500 type: "secret_request.record",
501 commandId: CommandId.make("command:secret-" + secretStatus),
502 threadId,
503 runId,
504 nodeId: rootNode,
505 turnItemId: TurnItemId.make("turn-item:snoozed-secret"),
506 label: "Credential",
507 reason: "Connect",
508 secretStatus,
509 });
510 if (secretStatus === "pending") {
511 yield* a.orchestrator.dispatch({
512 type: "thread.snooze",
513 commandId: CommandId.make("command:snooze-secret"),
514 threadId,
515 snoozedUntil: "2099-01-01T00:00:00.000Z",
516 });
517 expect((yield* a.projections.getThread(threadId)).snoozedUntil).not.toBeNull();
518 } else {
519 expect((yield* a.projections.getThread(threadId)).snoozedUntil).toBeNull();
520 }
521 }
522​
523 // The agent ends its turn; the card stays answerable, and the thread still asks.
524 yield* endRun(a);
525 expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
526 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
527 { kind: "user_input" },
528 );
529 expect(
530 ProjectionStore.threadShellFromProjection(
531 yield* a.orchestrator.getThreadProjection(threadId),
532 ).pendingRuntimeRequest,
533 ).toMatchObject({ kind: "user_input" });
534 expect(yield* a.projections.getSettlementCandidates(threadId)).toEqual([]);
535​
536 // Once the user writes in the thread again, the card stops asking but stays answerable.
537 const wroteAt = DateTime.add(card.startedAt!, { seconds: 1 });
538 yield* a.sink.write({
539 commandId: CommandId.make("command:user-writes:laptop"),
540 events: [
541 {
542 id: EventId.make("event:user-writes"),
543 type: "message.updated",
544 threadId,
545 occurredAt: wroteAt,
546 payload: {
547 createdBy: "user",
548 creationSource: "web",
549 id: MessageId.make("message:user-writes"),
550 threadId,
551 runId: null,
552 nodeId: null,
553 role: "user",
554 text: "Something else",
555 attachments: [],
556 streaming: false,
557 createdAt: wroteAt,
558 updatedAt: wroteAt,
559 },
560 },
561 ],
562 });
563 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
564 expect(
565 ProjectionStore.threadShellFromProjection(
566 yield* a.orchestrator.getThreadProjection(threadId),
567 ).pendingRuntimeRequest,
568 ).toBeNull();
569 expect(
570 (yield* a.projections.getSettlementCandidates(threadId)).map((thread) => thread.id),
571 ).toEqual([threadId]);
572 expect(yield* cardOf(a)).toMatchObject({ status: "waiting", linkStatus: "pending" });
573​
574 yield* a.orchestrator.dispatch({
575 type: "thread.snooze",
576 commandId: CommandId.make("command:snooze-link"),
577 threadId,
578 snoozedUntil: "2099-01-01T00:00:00.000Z",
579 });
580 expect((yield* a.projections.getThread(threadId)).snoozedUntil).not.toBeNull();
581​
582 // The user's client mints a code on the box and picks more than the agent suggested.
583 const pairing = yield* b.auth.issuePairingCredential();
584 yield* a.requests.answer({
585 threadId,
586 turnItemId: card.id,
587 answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
588 });
589​
590 expect((yield* a.projections.getThread(threadId)).snoozedUntil).toBeNull();
591​
592 const link = yield* a.links.get(box.environmentId);
593 expect(Option.getOrUndefined(link)?.access).toBe("auto");
594 expect(yield* cardOf(a)).toMatchObject({
595 status: "completed",
596 linkStatus: "linked",
597 linkedEnvironmentId: box.environmentId,
598 linkedLabel: "Box",
599 linkedAccess: "auto",
600 });
601 expect((yield* b.linkedSessions).length).toBe(1);
602​
603 // The agent hears it as a notification in its thread, not a user message.
604 const { messages, items } = yield* outcomeMessages(a);
605 expect(messages).toHaveLength(1);
606 expect(messages[0]).toMatchObject({
607 role: "user",
608 createdBy: "agent",
609 creationSource: "server",
610 notification: { outcome: "completed", summary: "Linked Box" },
611 });
612 expect(messages[0]!.text).toContain(box.environmentId);
613 expect(messages[0]!.text).toContain("auto");
614 expect(items).toHaveLength(1);
615 expect(items[0]).toMatchObject({ type: "notification", summary: "Linked Box" });
616​
617 // The code appears in nothing the thread recorded or the agent received.
618 expect(yield* storedText(a)).not.toContain(pairing.credential);
619​
620 // A card is answered once.
621 const again = yield* a.requests
622 .answer({ threadId, turnItemId: card.id, answer: { type: "decline" } })
623 .pipe(Effect.flip);
624 expect(again.reason).toBe("already_answered");
625​
626 // A retry that lost the first result gets the card's outcome, and records nothing.
627 const before = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.length;
628 const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
629 expect(retried.structuredContent).toEqual({
630 status: "linked",
631 environmentId: box.environmentId,
632 label: "Box",
633 access: "auto",
634 });
635 expect((yield* a.orchestrator.getThreadProjection(threadId)).turnItems).toHaveLength(before);
636 expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
637 }),
638 ),
639);
640​
641it.live("a retry of a pending request returns pending and shows no second card", () =>
642 withBoth((a, b) =>
643 Effect.gen(function* () {
644 yield* seedThread(a);
645 const first = yield* a.call({ url: b.url, clientRequestId: "link-box" });
646 const retried = yield* a.call({ url: b.url, clientRequestId: "link-box" });
647 expect(retried.structuredContent).toEqual(first.structuredContent);
648 const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
649 (item) => item.type === "link_request",
650 );
651 expect(cards).toHaveLength(1);
652 }),
653 ),
654);
655​
656it.live("a new MCP credential reusing a clientRequestId gets a card of its own", () =>
657 withBoth((a, b) =>
658 Effect.gen(function* () {
659 yield* seedThread(a);
660 const first = yield* a.call({ url: b.url, clientRequestId: "link" });
661 const later = yield* a.call(
662 { environmentId: box.environmentId, clientRequestId: "link" },
663 {
664 ...scope,
665 requestNamespace: "provider-session:laptop-2",
666 thread: { ...scope.thread!, providerSessionId: "provider-session:laptop-2" },
667 },
668 );
669 expect(later.structuredContent).toMatchObject({ status: "pending" });
670 expect(later.structuredContent).not.toEqual(first.structuredContent);
671 const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
672 (item) => item.type === "link_request",
673 );
674 expect(cards).toHaveLength(2);
675 }),
676 ),
677);
678​
679it.live("a declined request links nothing and tells the agent", () =>
680 withBoth((a, b) =>
681 Effect.gen(function* () {
682 yield* seedThread(a);
683 yield* a.call({ url: b.url });
684 const card = yield* pendingCard(a);
685 yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
686 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
687 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "declined" });
688 const { messages } = yield* outcomeMessages(a);
689 expect(messages).toHaveLength(1);
690 expect(messages[0]).toMatchObject({
691 notification: { outcome: "cancelled", summary: `Declined to link ${b.url}` },
692 });
693 expect(messages[0]!.text).toContain("declined");
694 }),
695 ),
696);
697​
698it.live("stopping the thread closes its open card, which then takes no answer", () =>
699 withBoth((a, b) =>
700 Effect.gen(function* () {
701 yield* seedThread(a);
702 yield* a.call({ url: b.url });
703 const card = yield* pendingCard(a);
704 yield* a.orchestrator.dispatch({
705 type: "thread.stop",
706 commandId: CommandId.make("command:stop:laptop"),
707 threadId,
708 });
709 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
710 const late = yield* a.requests
711 .answer({
712 threadId,
713 turnItemId: card.id,
714 answer: { type: "link", urls: [b.url], access: "auto", pairingCode: "late-code" },
715 })
716 .pipe(Effect.flip);
717 expect(late.reason).toBe("already_answered");
718 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
719 // An answer already linking when Stop landed keeps the card closed and wakes nobody.
720 yield* a.orchestrator.dispatch({
721 type: "link_request.record",
722 commandId: CommandId.make("command:late-answer:laptop"),
723 threadId,
724 runId,
725 nodeId: rootNode,
726 turnItemId: card.id,
727 url: card.url,
728 reason: card.reason,
729 linkStatus: "declined",
730 wake: {
731 messageId: MessageId.make("message:late-answer"),
732 text: "The user declined.",
733 notification: {
734 source: { kind: "background_task" },
735 outcome: "cancelled",
736 summary: "Declined",
737 },
738 },
739 });
740 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
741 // The user stopped the thread: nothing wakes the agent.
742 expect((yield* outcomeMessages(a)).messages).toHaveLength(0);
743 }),
744 ),
745);
746​
747it.live("a request that read the run before Stop shows no card once Stop lands", () =>
748 withBoth((a, b) =>
749 Effect.gen(function* () {
750 yield* seedThread(a);
751 yield* a.call({ url: b.url });
752 const open = yield* pendingCard(a);
753 yield* a.orchestrator.dispatch({
754 type: "thread.stop",
755 commandId: CommandId.make("command:stop:laptop"),
756 threadId,
757 });
758 const late = yield* recordPendingCard(a, "after-stop").pipe(Effect.flip);
759 expect(String(late.cause)).toContain("not active");
760 const cards = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.filter(
761 (item) => item.type === "link_request",
762 );
763 expect(cards.map((card) => card.id)).toEqual([open.id]);
764 }),
765 ),
766);
767​
768it.live("a card shows up only while its run is going, and takes an answer after", () =>
769 withBoth((a, b) =>
770 Effect.gen(function* () {
771 yield* seedThread(a);
772 yield* a.call({ url: b.url });
773 const card = yield* pendingCard(a);
774 yield* endRun(a);
775 const late = yield* recordPendingCard(a, "after-end").pipe(Effect.flip);
776 expect(String(late.cause)).toContain("not active");
777 yield* a.requests.answer({ threadId, turnItemId: card.id, answer: { type: "decline" } });
778 expect(yield* cardOf(a)).toMatchObject({ linkStatus: "declined" });
779 }),
780 ),
781);
782​
783it.live("a steer that restarts the turn leaves its open card answerable", () =>
784 withBoth((a, b) =>
785 Effect.gen(function* () {
786 yield* seedThread(a);
787 yield* a.call({ url: b.url });
788 const card = yield* pendingCard(a);
789 yield* restartRun(a);
790 const pairing = yield* b.auth.issuePairingCredential();
791 yield* a.requests.answer({
792 threadId,
793 turnItemId: card.id,
794 answer: { type: "link", urls: [b.url], access: "auto", pairingCode: pairing.credential },
795 });
796 // The card keeps the node it was asked from, and the agent hears the answer.
797 expect(yield* cardOf(a)).toMatchObject({
798 linkStatus: "linked",
799 nodeId: rootNode,
800 linkedEnvironmentId: box.environmentId,
801 });
802 expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
803 }),
804 ),
805);
806​
807it.live("a slow machine holds up only its own card's answer", () =>
808 withBoth((a, b) =>
809 Effect.scoped(
810 Effect.gen(function* () {
811 // A machine that takes the descriptor request and answers when the test says.
812 const reached = yield* Deferred.make<void>();
813 const release = yield* Deferred.make<void>();
814 const slow = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest));
815 const server = Context.get(slow, HttpServer.HttpServer);
816 yield* server.serve(
817 Deferred.succeed(reached, undefined).pipe(
818 Effect.andThen(Deferred.await(release)),
819 Effect.as(HttpServerResponse.empty({ status: 404 })),
820 ),
821 );
822 if (server.address._tag === "UnixPathAddress") return yield* Effect.die("expected TCP");
823 const slowUrl = `http://127.0.0.1:${server.address.port}`;
824​
825 yield* seedThread(a);
826 // Recorded directly: asking would probe the slow machine before the answer does.
827 const slowCard = { id: TurnItemId.make("turn-item:link-request:slow") };
828 yield* a.orchestrator.dispatch({
829 type: "link_request.record",
830 commandId: CommandId.make("command:pending:slow"),
831 threadId,
832 runId,
833 nodeId: rootNode,
834 turnItemId: slowCard.id,
835 url: slowUrl,
836 reason: "",
837 linkStatus: "pending",
838 });
839 yield* a.call({ url: b.url, clientRequestId: "box" });
840 const boxCard = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
841 (item) => item.type === "link_request" && item.url === b.url,
842 )!;
843​
844 const slowAnswer = yield* a.requests
845 .answer({
846 threadId,
847 turnItemId: slowCard.id,
848 answer: { type: "link", urls: [slowUrl], access: "auto", pairingCode: "code" },
849 })
850 .pipe(Effect.forkChild);
851 yield* Deferred.await(reached);
852​
853 // While the slow machine holds its card, the user answers the other one.
854 yield* a.requests.answer({ threadId, turnItemId: boxCard.id, answer: { type: "decline" } });
855 const items = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems;
856 expect(items.find((item) => item.id === boxCard.id)).toMatchObject({
857 linkStatus: "declined",
858 });
859 expect(items.find((item) => item.id === slowCard.id)).toMatchObject({
860 linkStatus: "pending",
861 });
862​
863 yield* Deferred.succeed(release, undefined);
864 yield* Fiber.join(slowAnswer);
865 const failed = (yield* a.orchestrator.getThreadProjection(threadId)).turnItems.find(
866 (item) => item.id === slowCard.id,
867 );
868 expect(failed).toMatchObject({ linkStatus: "failed" });
869 }),
870 ),
871 ),
872);
873​
874it.live("archiving the thread closes its open card", () =>
875 withBoth((a, b) =>
876 Effect.gen(function* () {
877 yield* seedThread(a);
878 yield* a.call({ url: b.url });
879 yield* pendingCard(a);
880 yield* endRun(a);
881 yield* a.orchestrator.dispatch({
882 type: "thread.archive",
883 commandId: CommandId.make("command:archive:laptop"),
884 threadId,
885 });
886 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
887 }),
888 ),
889);
890​
891it.live("a code the box refuses fails the request with its reason, and links nothing", () =>
892 withBoth((a, b) =>
893 Effect.gen(function* () {
894 yield* seedThread(a);
895 yield* a.call({ url: b.url });
896 const card = yield* pendingCard(a);
897 yield* a.requests.answer({
898 threadId,
899 turnItemId: card.id,
900 answer: {
901 type: "link",
902 urls: [b.url],
903 access: "auto",
904 pairingCode: "not-a-real-code",
905 },
906 });
907 const failed = yield* cardOf(a);
908 expect(failed).toMatchObject({ status: "failed", linkStatus: "failed" });
909 const reason = failed?.type === "link_request" ? failed.failure : undefined;
910 expect(reason?.length).toBeGreaterThan(0);
911 const { messages } = yield* outcomeMessages(a);
912 expect(messages[0]).toMatchObject({ notification: { outcome: "failed" } });
913 expect(messages[0]!.text).toContain(reason);
914 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
915 expect(yield* storedText(a)).not.toContain("not-a-real-code");
916 }),
917 ),
918);
919​
920it.live("a card an older server left naming a machine beside its address links no machine", () =>
921 withBoth((a, b) =>
922 Effect.gen(function* () {
923 yield* seedThread(a);
924 yield* a.orchestrator.dispatch({
925 type: "link_request.record",
926 commandId: CommandId.make("command:pending:older"),
927 threadId,
928 runId,
929 nodeId: rootNode,
930 turnItemId: TurnItemId.make("turn-item:link-request:older"),
931 url: b.url,
932 environmentId: box.environmentId,
933 label: "Box",
934 reason: "",
935 linkStatus: "pending",
936 });
937 const card = yield* pendingCard(a);
938 // An older client takes the machine from the card and mints a code on it.
939 const pairing = yield* b.auth.issuePairingCredential();
940 yield* a.requests.answer({
941 threadId,
942 turnItemId: card.id,
943 answer: {
944 type: "link",
945 environmentId: box.environmentId,
946 label: "Box",
947 urls: [b.url],
948 access: "auto",
949 pairingCode: pairing.credential,
950 },
951 });
952 expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
953 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
954 expect(yield* b.linkedSessions).toEqual([]);
955 }),
956 ),
957);
958​
959it.live("an agent below full access may not ask, and no card is shown", () =>
960 withBoth((a, b) =>
961 Effect.gen(function* () {
962 yield* seedThread(a, "auto");
963 const refused = yield* a.call({ url: b.url });
964 expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
965 expect(yield* cardOf(a)).toBeUndefined();
966 }),
967 ),
968);
969​
970it.live("work another environment's link started may not ask, and no card is shown", () =>
971 withBoth((a, b) =>
972 Effect.gen(function* () {
973 yield* seedThread(a, "full-access", { sessionId: "session:desk", label: "T3 Code · Desk" });
974 const refused = yield* a.call({ url: b.url });
975 expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
976 expect(errorOf(refused).message).toContain("T3 Code · Desk");
977 expect(yield* cardOf(a)).toBeUndefined();
978 }),
979 ),
980);
981​
982it.live(
983 "an agent that names no machine leaves the pick to the user, who links one by its addresses",
984 () =>
985 withBoth((a, b) =>
986 Effect.gen(function* () {
987 yield* seedThread(a);
988 const asked = yield* a.call({ reason: "Delegate the build to the vps.", hint: "vps" });
989 expect(asked.structuredContent).toMatchObject({ status: "pending" });
990 const card = yield* pendingCard(a);
991 expect(card).toMatchObject({ reason: "Delegate the build to the vps.", hint: "vps" });
992 expect(card.url).toBeUndefined();
993 expect(card.environmentId).toBeUndefined();
994​
995 // The user picks the box; their client knows a stale address for it first.
996 const pairing = yield* b.auth.issuePairingCredential();
997 yield* a.requests.answer({
998 threadId,
999 turnItemId: card.id,
1000 answer: {
1001 type: "link",
1002 environmentId: box.environmentId,
1003 label: "Box",
1004 urls: ["http://127.0.0.1:9", b.url],
1005 access: "auto",
1006 pairingCode: pairing.credential,
1007 },
1008 });
1009 expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))).toMatchObject({
1010 urls: [b.url],
1011 access: "auto",
1012 });
1013 expect(yield* cardOf(a)).toMatchObject({
1014 linkStatus: "linked",
1015 linkedEnvironmentId: box.environmentId,
1016 });
1017 expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("linked Box");
1018 }),
1019 ),
1021​
1022it.live("naming a machine that is already linked returns the link at once, with no card", () =>
1023 withBoth((a, b) =>
1024 Effect.gen(function* () {
1025 yield* seedThread(a);
1026 const pairing = yield* b.auth.issuePairingCredential();
1027 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
1028 const asked = yield* a.call({ environmentId: box.environmentId });
1029 expect(asked.structuredContent).toEqual({
1030 status: "linked",
1031 environmentId: box.environmentId,
1032 label: "Box",
1033 access: "auto",
1034 });
1035 expect(yield* cardOf(a)).toBeUndefined();
1036​
1037 // Not both: the address could name another machine than the id.
1038 const both = yield* a.call({ environmentId: box.environmentId, url: b.url });
1039 expect(errorOf(both)).toMatchObject({ code: "invalid_request" });
1040 }),
1041 ),
1043​
1044it.live("a retry naming a machine linked meanwhile closes the card it left as linked", () =>
1045 withBoth((a, b) =>
1046 Effect.gen(function* () {
1047 yield* seedThread(a);
1048 yield* a.call({ url: b.url, clientRequestId: "link-box" });
1049 yield* pendingCard(a);
1050 // Linked from Settings meanwhile, not through the card.
1051 const pairing = yield* b.auth.issuePairingCredential();
1052 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
1053​
1054 const retried = yield* a.call({
1055 environmentId: box.environmentId,
1056 clientRequestId: "link-box",
1057 });
1058 expect(retried.structuredContent).toEqual({
1059 status: "linked",
1060 environmentId: box.environmentId,
1061 label: "Box",
1062 access: "auto",
1063 });
1064 expect(yield* cardOf(a)).toMatchObject({
1065 linkStatus: "linked",
1066 linkedEnvironmentId: box.environmentId,
1067 });
1068 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
1069 }),
1070 ),
1072​
1073it.live("a link that expired goes through the card, so the user can link it again", () =>
1074 withBoth((a, b) =>
1075 Effect.gen(function* () {
1076 yield* seedThread(a);
1077 yield* linkTo(a.links, b, "read-only");
1078 const asked = yield* a.call({ environmentId: box.environmentId }).pipe(afterLinksExpire);
1079 expect(asked.structuredContent).toMatchObject({ status: "pending" });
1080 const card = yield* pendingCard(a);
1081​
1082 // Keeping the expired link is no answer: the card fails and says why.
1083 yield* a.requests
1084 .answer({
1085 threadId,
1086 turnItemId: card.id,
1087 answer: { type: "use-existing", environmentId: box.environmentId },
1088 })
1089 .pipe(afterLinksExpire);
1090 expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
1091 expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("expired");
1092 }),
1093 ),
1095​
1096it.live("a link made before links were fenced goes through the card, as an expired one", () =>
1097 withBoth((a, b) =>
1098 Effect.gen(function* () {
1099 yield* seedThread(a);
1100 yield* linkTo(a.links, b);
1101 yield* a.linksSql`UPDATE peer_environment_links SET fenced = 0`;
1102 const asked = yield* a.call({ environmentId: box.environmentId });
1103 expect(asked.structuredContent).toMatchObject({ status: "pending" });
1104 yield* pendingCard(a);
1105 }),
1106 ),
1108​
1109it.live(
1110 "a card for a machine named by id keeps it, and the user may keep a link it already has",
1111 () =>
1112 withBoth((a, b) =>
1113 Effect.gen(function* () {
1114 yield* seedThread(a);
1115 yield* a.call({ environmentId: box.environmentId });
1116 const card = yield* pendingCard(a);
1117 expect(card.environmentId).toBe(box.environmentId);
1118 // Linked from Settings meanwhile; the card answers with that link.
1119 const pairing = yield* b.auth.issuePairingCredential();
1120 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "read-only" });
1121 yield* a.requests.answer({
1122 threadId,
1123 turnItemId: card.id,
1124 answer: { type: "use-existing", environmentId: box.environmentId },
1125 });
1126 expect(yield* cardOf(a)).toMatchObject({
1127 linkStatus: "linked",
1128 linkedAccess: "read-only",
1129 });
1130 expect((yield* b.linkedSessions).length).toBe(1);
1131 }),
1132 ),
1134​
1135const linkCards = (a: Laptop) =>
1136 a.orchestrator
1137 .getThreadProjection(threadId)
1138 .pipe(
1139 Effect.map((projection) =>
1140 projection.turnItems.flatMap((item) => (item.type === "link_request" ? [item] : [])),
1141 ),
1142 );
1143​
1144const ask = (a: Laptop, args: Record<string, unknown>) =>
1145 Effect.gen(function* () {
1146 const asked = yield* a.call(args);
1147 const { turnItemId } = asked.structuredContent as { readonly turnItemId: TurnItemId };
1148 return (yield* linkCards(a)).find((card) => card.id === turnItemId)!;
1149 });
1150​
1151const linkBox = (a: Laptop, b: ServedPeer, cardId: TurnItemId) =>
1152 Effect.gen(function* () {
1153 const pairing = yield* b.auth.issuePairingCredential();
1154 yield* a.requests.answer({
1155 threadId,
1156 turnItemId: cardId,
1157 answer: {
1158 type: "link",
1159 urls: [b.url],
1160 access: "full-access",
1161 pairingCode: pairing.credential,
1162 },
1163 });
1164 return pairing.credential;
1165 });
1166​
1167const recordCard = (
1168 a: Laptop,
1169 key: string,
1170 fields: {
1171 readonly url?: string;
1172 readonly environmentId?: typeof box.environmentId;
1173 readonly hint?: string;
1174 readonly requestedAccess?: "read-only" | "full-access";
1175 },
1176) =>
1177 Effect.gen(function* () {
1178 const id = TurnItemId.make(`turn-item:link-request:${key}`);
1179 yield* a.orchestrator.dispatch({
1180 type: "link_request.record",
1181 commandId: CommandId.make(`command:pending:${key}`),
1182 threadId,
1183 runId,
1184 nodeId: rootNode,
1185 turnItemId: id,
1186 reason: "",
1187 linkStatus: "pending",
1188 ...fields,
1189 });
1190 return id;
1191 });
1192​
1193it.live("a link ends older cards that asked for the same machine by hint, id or address", () =>
1194 withBoth((a, b) =>
1195 Effect.gen(function* () {
1196 yield* seedThread(a);
1197 // The agent first asks by the user's word, then again by the box's address.
1198 const older = yield* ask(a, {
1199 reason: "Delegate to the box.",
1200 hint: "Box",
1201 requestedAccess: "full-access",
1202 clientRequestId: "by-hint",
1203 });
1204 const byId = yield* ask(a, {
1205 environmentId: box.environmentId,
1206 requestedAccess: "full-access",
1207 clientRequestId: "by-id",
1208 });
1209 const byAddress = yield* recordCard(a, "by-address", {
1210 url: b.url,
1211 requestedAccess: "full-access",
1212 });
1213 const newer = yield* ask(a, {
1214 url: b.url,
1215 reason: "Delegate to the box.",
1216 hint: "Box",
1217 requestedAccess: "full-access",
1218 clientRequestId: "by-url",
1219 });
1220 const credential = yield* linkBox(a, b, newer.id);
1221​
1222 const cards = yield* linkCards(a);
1223 expect(cards.find((card) => card.id === newer.id)).toMatchObject({
1224 status: "completed",
1225 linkStatus: "linked",
1226 linkedEnvironmentId: box.environmentId,
1227 });
1228 // The older card keeps what it asked and ends; it no longer asks the user.
1229 expect(cards.find((card) => card.id === older.id)).toMatchObject({
1230 status: "cancelled",
1231 linkStatus: "cancelled",
1232 hint: "Box",
1233 reason: "Delegate to the box.",
1234 requestedAccess: "full-access",
1235 });
1236 for (const id of [byId.id, byAddress]) {
1237 expect(cards.find((card) => card.id === id)).toMatchObject({ linkStatus: "cancelled" });
1239 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
1240 expect(
1241 ProjectionStore.threadShellFromProjection(
1242 yield* a.orchestrator.getThreadProjection(threadId),
1243 ).pendingRuntimeRequest,
1244 ).toBeNull();
1245 // The agent hears of the one link it made, and nothing about the card that link ended.
1246 expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
1247 expect(yield* storedText(a)).not.toContain(credential);
1248 }),
1249 ),
1251​
1252it.live("a link leaves open the cards that asked for something else, or asked later", () =>
1253 withBoth((a, b) =>
1254 Effect.gen(function* () {
1255 yield* seedThread(a);
1256 const other = descriptorOf("environment-other", "Other");
1257 const left = [
1258 // Another machine, and a word that names neither.
1259 yield* recordCard(a, "other-hint", { hint: "vps", requestedAccess: "full-access" }),
1260 yield* recordCard(a, "no-hint", { requestedAccess: "full-access" }),
1261 // The same word, but for less access than the link was asked with.
1262 yield* recordCard(a, "less-access", { hint: "Box", requestedAccess: "read-only" }),
1263 // The same word, on a card that named another machine.
1264 yield* recordCard(a, "other-id", {
1265 environmentId: other.environmentId,
1266 hint: "Box",
1267 requestedAccess: "full-access",
1268 }),
1269 yield* recordCard(a, "other-address", {
1270 url: "http://127.0.0.1:9",
1271 hint: "Box",
1272 requestedAccess: "full-access",
1273 }),
1274 // A word the label only contains.
1275 yield* recordCard(a, "partial-hint", { hint: "Bo", requestedAccess: "full-access" }),
1276 ];
1277 const linked = yield* ask(a, { url: b.url, hint: "Box", requestedAccess: "full-access" });
1278 const later = yield* recordCard(a, "later", { hint: "Box", requestedAccess: "full-access" });
1279 yield* linkBox(a, b, linked.id);
1280​
1281 const cards = yield* linkCards(a);
1282 expect(cards.find((card) => card.id === linked.id)).toMatchObject({ linkStatus: "linked" });
1283 for (const id of [...left, later]) {
1284 expect(cards.find((card) => card.id === id)).toMatchObject({
1285 status: "waiting",
1286 linkStatus: "pending",
1287 });
1289 }),
1290 ),
1292​
1293it.live("a later card's failed link leaves the older card open", () =>
1294 withBoth((a, b) =>
1295 Effect.gen(function* () {
1296 yield* seedThread(a);
1297 const older = yield* ask(a, { hint: "Box", requestedAccess: "full-access" });
1298 const byAddress = yield* recordCard(a, "by-address", {
1299 url: b.url,
1300 requestedAccess: "full-access",
1301 });
1302 const newer = yield* ask(a, { url: b.url, hint: "Box", requestedAccess: "full-access" });
1303 yield* a.requests.answer({
1304 threadId,
1305 turnItemId: newer.id,
1306 answer: { type: "link", urls: [b.url], access: "full-access", pairingCode: "not-a-code" },
1307 });
1308​
1309 const cards = yield* linkCards(a);
1310 expect(cards.find((card) => card.id === newer.id)).toMatchObject({ linkStatus: "failed" });
1311 for (const id of [older.id, byAddress]) {
1312 expect(cards.find((card) => card.id === id)).toMatchObject({
1313 status: "waiting",
1314 linkStatus: "pending",
1315 });
1317 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
1318 { kind: "user_input" },
1319 );
1320​
1321 // The older card still takes its answer, and the failed one stays as it ended.
1322 yield* linkBox(a, b, older.id);
1323 const after = yield* linkCards(a);
1324 expect(after.find((card) => card.id === older.id)).toMatchObject({ linkStatus: "linked" });
1325 expect(after.find((card) => card.id === newer.id)).toMatchObject({ linkStatus: "failed" });
1326 }),
1327 ),
1329​
1330const withHeldLinks = <A, E, R>(
1331 hold: (access: PeerLinkCreateInput["access"]) => Effect.Effect<void> | undefined,
1332 body: (a: Laptop, b: ServedPeer) => Effect.Effect<A, E, R>,
1333) =>
1334 Effect.scoped(
1335 Effect.gen(function* () {
1336 const b = yield* serveBox;
1337 const a = yield* makeLaptopWith((links) => ({
1338 ...links,
1339 link: (input) =>
1340 (hold(input.access) ?? Effect.void).pipe(Effect.andThen(links.link(input))),
1341 }));
1342 return yield* body(a, b);
1343 }),
1344 ).pipe(Effect.provide(NodeHttpServer.layerTest));
1345​
1346it.live("an older card answered while a newer one links the same machine keeps its own link", () =>
1347 Effect.gen(function* () {
1348 const reached = yield* Deferred.make<void>();
1349 const release = yield* Deferred.make<void>();
1350 const fullAccessHeld = Deferred.succeed(reached, undefined).pipe(
1351 Effect.andThen(Deferred.await(release)),
1352 );
1353 yield* withHeldLinks(
1354 (access) => (access === "full-access" ? fullAccessHeld : undefined),
1355 (a, b) =>
1356 Effect.gen(function* () {
1357 yield* seedThread(a);
1358 // Both cards suggest the same machine and access.
1359 const older = yield* ask(a, {
1360 url: b.url,
1361 requestedAccess: "full-access",
1362 clientRequestId: "older",
1363 });
1364 const newer = yield* ask(a, {
1365 url: b.url,
1366 requestedAccess: "full-access",
1367 clientRequestId: "newer",
1368 });
1369 const olderCode = yield* b.auth.issuePairingCredential();
1370 const newerCode = yield* b.auth.issuePairingCredential();
1371​
1372 // The user grants full access on the older card, which stalls while linking.
1373 const olderAnswer = yield* a.requests
1374 .answer({
1375 threadId,
1376 turnItemId: older.id,
1377 answer: {
1378 type: "link",
1379 urls: [b.url],
1380 access: "full-access",
1381 pairingCode: olderCode.credential,
1382 },
1383 })
1384 .pipe(Effect.forkChild);
1385 yield* Deferred.await(reached);
1386​
1387 // Meanwhile the newer card links with read-only access and finishes.
1388 yield* a.requests.answer({
1389 threadId,
1390 turnItemId: newer.id,
1391 answer: {
1392 type: "link",
1393 urls: [b.url],
1394 access: "read-only",
1395 pairingCode: newerCode.credential,
1396 },
1397 });
1398 // The older card is still being answered, so the newer link leaves it open.
1399 expect((yield* linkCards(a)).find((card) => card.id === older.id)).toMatchObject({
1400 status: "waiting",
1401 linkStatus: "pending",
1402 });
1403​
1404 yield* Deferred.succeed(release, undefined);
1405 yield* Fiber.join(olderAnswer);
1406​
1407 const cards = yield* linkCards(a);
1408 const stored = Option.getOrThrow(yield* a.links.get(box.environmentId));
1409 expect(cards.find((card) => card.id === newer.id)).toMatchObject({
1410 status: "completed",
1411 linkStatus: "linked",
1412 linkedAccess: "read-only",
1413 });
1414 // The older card says what the link the box now has grants, and the agent hears it.
1415 expect(stored.access).toBe("full-access");
1416 expect(cards.find((card) => card.id === older.id)).toMatchObject({
1417 status: "completed",
1418 linkStatus: "linked",
1419 linkedEnvironmentId: stored.environmentId,
1420 linkedAccess: stored.access,
1421 });
1422 const { messages } = yield* outcomeMessages(a);
1423 expect(messages.map((message) => message.notification?.outcome)).toEqual([
1424 "completed",
1425 "completed",
1426 ]);
1427 }),
1428 );
1429 }),
1431​
1432it.live("a card a newer link ended links nothing when answered after", () =>
1433 Effect.gen(function* () {
1434 let links = 0;
1435 yield* withHeldLinks(
1436 () => Effect.sync(() => void links++),
1437 (a, b) =>
1438 Effect.gen(function* () {
1439 yield* seedThread(a);
1440 const older = yield* ask(a, {
1441 url: b.url,
1442 requestedAccess: "full-access",
1443 clientRequestId: "older",
1444 });
1445 const newer = yield* ask(a, {
1446 url: b.url,
1447 requestedAccess: "full-access",
1448 clientRequestId: "newer",
1449 });
1450 yield* linkBox(a, b, newer.id);
1451 expect(links).toBe(1);
1452​
1453 const pairing = yield* b.auth.issuePairingCredential();
1454 const late = yield* a.requests
1455 .answer({
1456 threadId,
1457 turnItemId: older.id,
1458 answer: {
1459 type: "link",
1460 urls: [b.url],
1461 access: "read-only",
1462 pairingCode: pairing.credential,
1463 },
1464 })
1465 .pipe(Effect.flip);
1466 expect(late.reason).toBe("already_answered");
1467 expect(links).toBe(1);
1468 expect(Option.getOrThrow(yield* a.links.get(box.environmentId)).access).toBe(
1469 "full-access",
1470 );
1471 }),
1472 );
1473 }),