@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,492 lines 54.7 KB
Raw
1 import { NodeHttpServer } from "@effect/platform-node";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import {
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";
20 import { expect, it } from "@effect/vitest";
21 import * as Clock from "effect/Clock";
22 import * as Context from "effect/Context";
23 import * as DateTime from "effect/DateTime";
24 import * as Deferred from "effect/Deferred";
25 import * as Duration from "effect/Duration";
26 import * as Effect from "effect/Effect";
27 import * as Fiber from "effect/Fiber";
28 import * as HttpServer from "effect/http/HttpServer";
29 import * as HttpServerResponse from "effect/http/HttpServerResponse";
30 import * as Layer from "effect/Layer";
31 import * as Option from "effect/Option";
32 import * as Schema from "effect/Schema";
33 import * as SqlClient from "effect/sql/SqlClient";
34 import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
35
36 import * as ServerConfig from "../config.ts";
37 import * as McpHttpServer from "../mcp/McpHttpServer.ts";
38 import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
39 import * as McpToolAccess from "../mcp/McpToolAccess.ts";
40 import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
41 import * as EventSink from "../orchestration-v2/EventSink.ts";
42 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
43 import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
44 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
45 import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
46 import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
47 import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
48 import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
49 import * as SqlitePersistence from "../persistence/Sqlite.ts";
50 import * as ProjectService from "../project/ProjectService.ts";
51 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
52 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
53 import * as SecretRequests from "../secrets/SecretRequests.ts";
54 import * as ServerSettings from "../serverSettings.ts";
55 import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
56 import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
57 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
58 import * as PeerForwarding from "./PeerForwarding.ts";
59 import * as PeerLinkRequests from "./PeerLinkRequests.ts";
60 import * as PeerLinks from "./PeerLinks.ts";
61 import {
62 descriptorOf,
63 layerLinkingEnvironment,
64 linkTo,
65 servePeer,
66 type ServedPeer,
67 } from "./PeerLinks.testkit.ts";
68 import * 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
74 const laptop = descriptorOf("environment-laptop", "Laptop");
75 const box = descriptorOf("environment-box", "Box");
76 const instanceId = ProviderInstanceId.make("codex");
77 const driver = ProviderDriverKind.make("codex");
78 const modelSelection = { instanceId, model: "gpt-5.4" };
79 const threadId = ThreadId.make("thread:laptop");
80 const runId = RunId.make("run:laptop");
81 const rootNode = NodeId.make("node:laptop:root");
82
83 /** The box needs no tools of its own: linking only signs in to its /mcp. */
84 const NoTools = Toolkit.make(
85 Tool.make("noop", { success: Schema.Struct({}), failure: OrchestratorMcpFailure }),
86 );
87 const serveBox = servePeer(
88 box,
89 McpHttpServer.toolkitRegistration(
90 NoTools,
91 McpToolAccess.toLayer(NoTools, { noop: McpToolAccess.reads(() => Effect.succeed({})) }),
92 ),
93 );
94
95 const 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
103 const 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
116 const 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. */
130 const 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 });
208 const makeLaptop = makeLaptopWith();
209 type Laptop = Effect.Success<typeof makeLaptop>;
210
211 /** The laptop's thread, mid-turn when its agent asks, in `runtimeMode`. */
212 const 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
320 const 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. */
328 const 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. */
336 const 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. */
345 const 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. */
368 const 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. */
404 const 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 */
420 const 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
437 const 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. */
443 const 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
462 const 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
471 it.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
641 it.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
656 it.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
679 it.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
698 it.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
747 it.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
768 it.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
783 it.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
807 it.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
874 it.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
891 it.live("settling the thread closes its open card, so it no longer reads as asking", () =>
892 withBoth((a, b) =>
893 Effect.gen(function* () {
894 yield* seedThread(a);
895 yield* a.call({ url: b.url });
896 yield* pendingCard(a);
897 yield* endRun(a);
898 yield* a.orchestrator.dispatch({
899 type: "thread.settle",
900 commandId: CommandId.make("command:settle:laptop"),
901 threadId,
902 });
903 expect(yield* cardOf(a)).toMatchObject({ status: "cancelled", linkStatus: "cancelled" });
904 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
905 }),
906 ),
907 );
908
909 it.live("a code the box refuses fails the request with its reason, and links nothing", () =>
910 withBoth((a, b) =>
911 Effect.gen(function* () {
912 yield* seedThread(a);
913 yield* a.call({ url: b.url });
914 const card = yield* pendingCard(a);
915 yield* a.requests.answer({
916 threadId,
917 turnItemId: card.id,
918 answer: {
919 type: "link",
920 urls: [b.url],
921 access: "auto",
922 pairingCode: "not-a-real-code",
923 },
924 });
925 const failed = yield* cardOf(a);
926 expect(failed).toMatchObject({ status: "failed", linkStatus: "failed" });
927 const reason = failed?.type === "link_request" ? failed.failure : undefined;
928 expect(reason?.length).toBeGreaterThan(0);
929 const { messages } = yield* outcomeMessages(a);
930 expect(messages[0]).toMatchObject({ notification: { outcome: "failed" } });
931 expect(messages[0]!.text).toContain(reason);
932 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
933 expect(yield* storedText(a)).not.toContain("not-a-real-code");
934 }),
935 ),
936 );
937
938 it.live("a card an older server left naming a machine beside its address links no machine", () =>
939 withBoth((a, b) =>
940 Effect.gen(function* () {
941 yield* seedThread(a);
942 yield* a.orchestrator.dispatch({
943 type: "link_request.record",
944 commandId: CommandId.make("command:pending:older"),
945 threadId,
946 runId,
947 nodeId: rootNode,
948 turnItemId: TurnItemId.make("turn-item:link-request:older"),
949 url: b.url,
950 environmentId: box.environmentId,
951 label: "Box",
952 reason: "",
953 linkStatus: "pending",
954 });
955 const card = yield* pendingCard(a);
956 // An older client takes the machine from the card and mints a code on it.
957 const pairing = yield* b.auth.issuePairingCredential();
958 yield* a.requests.answer({
959 threadId,
960 turnItemId: card.id,
961 answer: {
962 type: "link",
963 environmentId: box.environmentId,
964 label: "Box",
965 urls: [b.url],
966 access: "auto",
967 pairingCode: pairing.credential,
968 },
969 });
970 expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
971 expect(Option.isNone(yield* a.links.get(box.environmentId))).toBe(true);
972 expect(yield* b.linkedSessions).toEqual([]);
973 }),
974 ),
975 );
976
977 it.live("an agent below full access may not ask, and no card is shown", () =>
978 withBoth((a, b) =>
979 Effect.gen(function* () {
980 yield* seedThread(a, "auto");
981 const refused = yield* a.call({ url: b.url });
982 expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
983 expect(yield* cardOf(a)).toBeUndefined();
984 }),
985 ),
986 );
987
988 it.live("work another environment's link started may not ask, and no card is shown", () =>
989 withBoth((a, b) =>
990 Effect.gen(function* () {
991 yield* seedThread(a, "full-access", { sessionId: "session:desk", label: "T3 Code · Desk" });
992 const refused = yield* a.call({ url: b.url });
993 expect(errorOf(refused)).toMatchObject({ code: "capability_denied" });
994 expect(errorOf(refused).message).toContain("T3 Code · Desk");
995 expect(yield* cardOf(a)).toBeUndefined();
996 }),
997 ),
998 );
999
1000 it.live(
1001 "an agent that names no machine leaves the pick to the user, who links one by its addresses",
1002 () =>
1003 withBoth((a, b) =>
1004 Effect.gen(function* () {
1005 yield* seedThread(a);
1006 const asked = yield* a.call({ reason: "Delegate the build to the vps.", hint: "vps" });
1007 expect(asked.structuredContent).toMatchObject({ status: "pending" });
1008 const card = yield* pendingCard(a);
1009 expect(card).toMatchObject({ reason: "Delegate the build to the vps.", hint: "vps" });
1010 expect(card.url).toBeUndefined();
1011 expect(card.environmentId).toBeUndefined();
1012
1013 // The user picks the box; their client knows a stale address for it first.
1014 const pairing = yield* b.auth.issuePairingCredential();
1015 yield* a.requests.answer({
1016 threadId,
1017 turnItemId: card.id,
1018 answer: {
1019 type: "link",
1020 environmentId: box.environmentId,
1021 label: "Box",
1022 urls: ["http://127.0.0.1:9", b.url],
1023 access: "auto",
1024 pairingCode: pairing.credential,
1025 },
1026 });
1027 expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))).toMatchObject({
1028 urls: [b.url],
1029 access: "auto",
1030 });
1031 expect(yield* cardOf(a)).toMatchObject({
1032 linkStatus: "linked",
1033 linkedEnvironmentId: box.environmentId,
1034 });
1035 expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("linked Box");
1036 }),
1037 ),
1038 );
1039
1040 it.live("naming a machine that is already linked returns the link at once, with no card", () =>
1041 withBoth((a, b) =>
1042 Effect.gen(function* () {
1043 yield* seedThread(a);
1044 const pairing = yield* b.auth.issuePairingCredential();
1045 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
1046 const asked = yield* a.call({ environmentId: box.environmentId });
1047 expect(asked.structuredContent).toEqual({
1048 status: "linked",
1049 environmentId: box.environmentId,
1050 label: "Box",
1051 access: "auto",
1052 });
1053 expect(yield* cardOf(a)).toBeUndefined();
1054
1055 // Not both: the address could name another machine than the id.
1056 const both = yield* a.call({ environmentId: box.environmentId, url: b.url });
1057 expect(errorOf(both)).toMatchObject({ code: "invalid_request" });
1058 }),
1059 ),
1060 );
1061
1062 it.live("a retry naming a machine linked meanwhile closes the card it left as linked", () =>
1063 withBoth((a, b) =>
1064 Effect.gen(function* () {
1065 yield* seedThread(a);
1066 yield* a.call({ url: b.url, clientRequestId: "link-box" });
1067 yield* pendingCard(a);
1068 // Linked from Settings meanwhile, not through the card.
1069 const pairing = yield* b.auth.issuePairingCredential();
1070 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
1071
1072 const retried = yield* a.call({
1073 environmentId: box.environmentId,
1074 clientRequestId: "link-box",
1075 });
1076 expect(retried.structuredContent).toEqual({
1077 status: "linked",
1078 environmentId: box.environmentId,
1079 label: "Box",
1080 access: "auto",
1081 });
1082 expect(yield* cardOf(a)).toMatchObject({
1083 linkStatus: "linked",
1084 linkedEnvironmentId: box.environmentId,
1085 });
1086 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
1087 }),
1088 ),
1089 );
1090
1091 it.live("a link that expired goes through the card, so the user can link it again", () =>
1092 withBoth((a, b) =>
1093 Effect.gen(function* () {
1094 yield* seedThread(a);
1095 yield* linkTo(a.links, b, "read-only");
1096 const asked = yield* a.call({ environmentId: box.environmentId }).pipe(afterLinksExpire);
1097 expect(asked.structuredContent).toMatchObject({ status: "pending" });
1098 const card = yield* pendingCard(a);
1099
1100 // Keeping the expired link is no answer: the card fails and says why.
1101 yield* a.requests
1102 .answer({
1103 threadId,
1104 turnItemId: card.id,
1105 answer: { type: "use-existing", environmentId: box.environmentId },
1106 })
1107 .pipe(afterLinksExpire);
1108 expect(yield* cardOf(a)).toMatchObject({ linkStatus: "failed" });
1109 expect((yield* outcomeMessages(a)).messages[0]!.text).toContain("expired");
1110 }),
1111 ),
1112 );
1113
1114 it.live("a link made before links were fenced goes through the card, as an expired one", () =>
1115 withBoth((a, b) =>
1116 Effect.gen(function* () {
1117 yield* seedThread(a);
1118 yield* linkTo(a.links, b);
1119 yield* a.linksSql`UPDATE peer_environment_links SET fenced = 0`;
1120 const asked = yield* a.call({ environmentId: box.environmentId });
1121 expect(asked.structuredContent).toMatchObject({ status: "pending" });
1122 yield* pendingCard(a);
1123 }),
1124 ),
1125 );
1126
1127 it.live(
1128 "a card for a machine named by id keeps it, and the user may keep a link it already has",
1129 () =>
1130 withBoth((a, b) =>
1131 Effect.gen(function* () {
1132 yield* seedThread(a);
1133 yield* a.call({ environmentId: box.environmentId });
1134 const card = yield* pendingCard(a);
1135 expect(card.environmentId).toBe(box.environmentId);
1136 // Linked from Settings meanwhile; the card answers with that link.
1137 const pairing = yield* b.auth.issuePairingCredential();
1138 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "read-only" });
1139 yield* a.requests.answer({
1140 threadId,
1141 turnItemId: card.id,
1142 answer: { type: "use-existing", environmentId: box.environmentId },
1143 });
1144 expect(yield* cardOf(a)).toMatchObject({
1145 linkStatus: "linked",
1146 linkedAccess: "read-only",
1147 });
1148 expect((yield* b.linkedSessions).length).toBe(1);
1149 }),
1150 ),
1151 );
1152
1153 const linkCards = (a: Laptop) =>
1154 a.orchestrator
1155 .getThreadProjection(threadId)
1156 .pipe(
1157 Effect.map((projection) =>
1158 projection.turnItems.flatMap((item) => (item.type === "link_request" ? [item] : [])),
1159 ),
1160 );
1161
1162 const ask = (a: Laptop, args: Record<string, unknown>) =>
1163 Effect.gen(function* () {
1164 const asked = yield* a.call(args);
1165 const { turnItemId } = asked.structuredContent as { readonly turnItemId: TurnItemId };
1166 return (yield* linkCards(a)).find((card) => card.id === turnItemId)!;
1167 });
1168
1169 const linkBox = (a: Laptop, b: ServedPeer, cardId: TurnItemId) =>
1170 Effect.gen(function* () {
1171 const pairing = yield* b.auth.issuePairingCredential();
1172 yield* a.requests.answer({
1173 threadId,
1174 turnItemId: cardId,
1175 answer: {
1176 type: "link",
1177 urls: [b.url],
1178 access: "full-access",
1179 pairingCode: pairing.credential,
1180 },
1181 });
1182 return pairing.credential;
1183 });
1184
1185 const recordCard = (
1186 a: Laptop,
1187 key: string,
1188 fields: {
1189 readonly url?: string;
1190 readonly environmentId?: typeof box.environmentId;
1191 readonly hint?: string;
1192 readonly requestedAccess?: "read-only" | "full-access";
1193 },
1194 ) =>
1195 Effect.gen(function* () {
1196 const id = TurnItemId.make(`turn-item:link-request:${key}`);
1197 yield* a.orchestrator.dispatch({
1198 type: "link_request.record",
1199 commandId: CommandId.make(`command:pending:${key}`),
1200 threadId,
1201 runId,
1202 nodeId: rootNode,
1203 turnItemId: id,
1204 reason: "",
1205 linkStatus: "pending",
1206 ...fields,
1207 });
1208 return id;
1209 });
1210
1211 it.live("a link ends older cards that asked for the same machine by hint, id or address", () =>
1212 withBoth((a, b) =>
1213 Effect.gen(function* () {
1214 yield* seedThread(a);
1215 // The agent first asks by the user's word, then again by the box's address.
1216 const older = yield* ask(a, {
1217 reason: "Delegate to the box.",
1218 hint: "Box",
1219 requestedAccess: "full-access",
1220 clientRequestId: "by-hint",
1221 });
1222 const byId = yield* ask(a, {
1223 environmentId: box.environmentId,
1224 requestedAccess: "full-access",
1225 clientRequestId: "by-id",
1226 });
1227 const byAddress = yield* recordCard(a, "by-address", {
1228 url: b.url,
1229 requestedAccess: "full-access",
1230 });
1231 const newer = yield* ask(a, {
1232 url: b.url,
1233 reason: "Delegate to the box.",
1234 hint: "Box",
1235 requestedAccess: "full-access",
1236 clientRequestId: "by-url",
1237 });
1238 const credential = yield* linkBox(a, b, newer.id);
1239
1240 const cards = yield* linkCards(a);
1241 expect(cards.find((card) => card.id === newer.id)).toMatchObject({
1242 status: "completed",
1243 linkStatus: "linked",
1244 linkedEnvironmentId: box.environmentId,
1245 });
1246 // The older card keeps what it asked and ends; it no longer asks the user.
1247 expect(cards.find((card) => card.id === older.id)).toMatchObject({
1248 status: "cancelled",
1249 linkStatus: "cancelled",
1250 hint: "Box",
1251 reason: "Delegate to the box.",
1252 requestedAccess: "full-access",
1253 });
1254 for (const id of [byId.id, byAddress]) {
1255 expect(cards.find((card) => card.id === id)).toMatchObject({ linkStatus: "cancelled" });
1256 }
1257 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
1258 expect(
1259 ProjectionStore.threadShellFromProjection(
1260 yield* a.orchestrator.getThreadProjection(threadId),
1261 ).pendingRuntimeRequest,
1262 ).toBeNull();
1263 // The agent hears of the one link it made, and nothing about the card that link ended.
1264 expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
1265 expect(yield* storedText(a)).not.toContain(credential);
1266 }),
1267 ),
1268 );
1269
1270 it.live("a link leaves open the cards that asked for something else, or asked later", () =>
1271 withBoth((a, b) =>
1272 Effect.gen(function* () {
1273 yield* seedThread(a);
1274 const other = descriptorOf("environment-other", "Other");
1275 const left = [
1276 // Another machine, and a word that names neither.
1277 yield* recordCard(a, "other-hint", { hint: "vps", requestedAccess: "full-access" }),
1278 yield* recordCard(a, "no-hint", { requestedAccess: "full-access" }),
1279 // The same word, but for less access than the link was asked with.
1280 yield* recordCard(a, "less-access", { hint: "Box", requestedAccess: "read-only" }),
1281 // The same word, on a card that named another machine.
1282 yield* recordCard(a, "other-id", {
1283 environmentId: other.environmentId,
1284 hint: "Box",
1285 requestedAccess: "full-access",
1286 }),
1287 yield* recordCard(a, "other-address", {
1288 url: "http://127.0.0.1:9",
1289 hint: "Box",
1290 requestedAccess: "full-access",
1291 }),
1292 // A word the label only contains.
1293 yield* recordCard(a, "partial-hint", { hint: "Bo", requestedAccess: "full-access" }),
1294 ];
1295 const linked = yield* ask(a, { url: b.url, hint: "Box", requestedAccess: "full-access" });
1296 const later = yield* recordCard(a, "later", { hint: "Box", requestedAccess: "full-access" });
1297 yield* linkBox(a, b, linked.id);
1298
1299 const cards = yield* linkCards(a);
1300 expect(cards.find((card) => card.id === linked.id)).toMatchObject({ linkStatus: "linked" });
1301 for (const id of [...left, later]) {
1302 expect(cards.find((card) => card.id === id)).toMatchObject({
1303 status: "waiting",
1304 linkStatus: "pending",
1305 });
1306 }
1307 }),
1308 ),
1309 );
1310
1311 it.live("a later card's failed link leaves the older card open", () =>
1312 withBoth((a, b) =>
1313 Effect.gen(function* () {
1314 yield* seedThread(a);
1315 const older = yield* ask(a, { hint: "Box", requestedAccess: "full-access" });
1316 const byAddress = yield* recordCard(a, "by-address", {
1317 url: b.url,
1318 requestedAccess: "full-access",
1319 });
1320 const newer = yield* ask(a, { url: b.url, hint: "Box", requestedAccess: "full-access" });
1321 yield* a.requests.answer({
1322 threadId,
1323 turnItemId: newer.id,
1324 answer: { type: "link", urls: [b.url], access: "full-access", pairingCode: "not-a-code" },
1325 });
1326
1327 const cards = yield* linkCards(a);
1328 expect(cards.find((card) => card.id === newer.id)).toMatchObject({ linkStatus: "failed" });
1329 for (const id of [older.id, byAddress]) {
1330 expect(cards.find((card) => card.id === id)).toMatchObject({
1331 status: "waiting",
1332 linkStatus: "pending",
1333 });
1334 }
1335 expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
1336 { kind: "user_input" },
1337 );
1338
1339 // The older card still takes its answer, and the failed one stays as it ended.
1340 yield* linkBox(a, b, older.id);
1341 const after = yield* linkCards(a);
1342 expect(after.find((card) => card.id === older.id)).toMatchObject({ linkStatus: "linked" });
1343 expect(after.find((card) => card.id === newer.id)).toMatchObject({ linkStatus: "failed" });
1344 }),
1345 ),
1346 );
1347
1348 const withHeldLinks = <A, E, R>(
1349 hold: (access: PeerLinkCreateInput["access"]) => Effect.Effect<void> | undefined,
1350 body: (a: Laptop, b: ServedPeer) => Effect.Effect<A, E, R>,
1351 ) =>
1352 Effect.scoped(
1353 Effect.gen(function* () {
1354 const b = yield* serveBox;
1355 const a = yield* makeLaptopWith((links) => ({
1356 ...links,
1357 link: (input) =>
1358 (hold(input.access) ?? Effect.void).pipe(Effect.andThen(links.link(input))),
1359 }));
1360 return yield* body(a, b);
1361 }),
1362 ).pipe(Effect.provide(NodeHttpServer.layerTest));
1363
1364 it.live("an older card answered while a newer one links the same machine keeps its own link", () =>
1365 Effect.gen(function* () {
1366 const reached = yield* Deferred.make<void>();
1367 const release = yield* Deferred.make<void>();
1368 const fullAccessHeld = Deferred.succeed(reached, undefined).pipe(
1369 Effect.andThen(Deferred.await(release)),
1370 );
1371 yield* withHeldLinks(
1372 (access) => (access === "full-access" ? fullAccessHeld : undefined),
1373 (a, b) =>
1374 Effect.gen(function* () {
1375 yield* seedThread(a);
1376 // Both cards suggest the same machine and access.
1377 const older = yield* ask(a, {
1378 url: b.url,
1379 requestedAccess: "full-access",
1380 clientRequestId: "older",
1381 });
1382 const newer = yield* ask(a, {
1383 url: b.url,
1384 requestedAccess: "full-access",
1385 clientRequestId: "newer",
1386 });
1387 const olderCode = yield* b.auth.issuePairingCredential();
1388 const newerCode = yield* b.auth.issuePairingCredential();
1389
1390 // The user grants full access on the older card, which stalls while linking.
1391 const olderAnswer = yield* a.requests
1392 .answer({
1393 threadId,
1394 turnItemId: older.id,
1395 answer: {
1396 type: "link",
1397 urls: [b.url],
1398 access: "full-access",
1399 pairingCode: olderCode.credential,
1400 },
1401 })
1402 .pipe(Effect.forkChild);
1403 yield* Deferred.await(reached);
1404
1405 // Meanwhile the newer card links with read-only access and finishes.
1406 yield* a.requests.answer({
1407 threadId,
1408 turnItemId: newer.id,
1409 answer: {
1410 type: "link",
1411 urls: [b.url],
1412 access: "read-only",
1413 pairingCode: newerCode.credential,
1414 },
1415 });
1416 // The older card is still being answered, so the newer link leaves it open.
1417 expect((yield* linkCards(a)).find((card) => card.id === older.id)).toMatchObject({
1418 status: "waiting",
1419 linkStatus: "pending",
1420 });
1421
1422 yield* Deferred.succeed(release, undefined);
1423 yield* Fiber.join(olderAnswer);
1424
1425 const cards = yield* linkCards(a);
1426 const stored = Option.getOrThrow(yield* a.links.get(box.environmentId));
1427 expect(cards.find((card) => card.id === newer.id)).toMatchObject({
1428 status: "completed",
1429 linkStatus: "linked",
1430 linkedAccess: "read-only",
1431 });
1432 // The older card says what the link the box now has grants, and the agent hears it.
1433 expect(stored.access).toBe("full-access");
1434 expect(cards.find((card) => card.id === older.id)).toMatchObject({
1435 status: "completed",
1436 linkStatus: "linked",
1437 linkedEnvironmentId: stored.environmentId,
1438 linkedAccess: stored.access,
1439 });
1440 const { messages } = yield* outcomeMessages(a);
1441 expect(messages.map((message) => message.notification?.outcome)).toEqual([
1442 "completed",
1443 "completed",
1444 ]);
1445 }),
1446 );
1447 }),
1448 );
1449
1450 it.live("a card a newer link ended links nothing when answered after", () =>
1451 Effect.gen(function* () {
1452 let links = 0;
1453 yield* withHeldLinks(
1454 () => Effect.sync(() => void links++),
1455 (a, b) =>
1456 Effect.gen(function* () {
1457 yield* seedThread(a);
1458 const older = yield* ask(a, {
1459 url: b.url,
1460 requestedAccess: "full-access",
1461 clientRequestId: "older",
1462 });
1463 const newer = yield* ask(a, {
1464 url: b.url,
1465 requestedAccess: "full-access",
1466 clientRequestId: "newer",
1467 });
1468 yield* linkBox(a, b, newer.id);
1469 expect(links).toBe(1);
1470
1471 const pairing = yield* b.auth.issuePairingCredential();
1472 const late = yield* a.requests
1473 .answer({
1474 threadId,
1475 turnItemId: older.id,
1476 answer: {
1477 type: "link",
1478 urls: [b.url],
1479 access: "read-only",
1480 pairingCode: pairing.credential,
1481 },
1482 })
1483 .pipe(Effect.flip);
1484 expect(late.reason).toBe("already_answered");
1485 expect(links).toBe(1);
1486 expect(Option.getOrThrow(yield* a.links.get(box.environmentId)).access).toBe(
1487 "full-access",
1488 );
1489 }),
1490 );
1491 }),
1492 );