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

PeerForwarding.test.ts

824 lines33.5 KB

1import * as DocumentText from "../provider/DocumentText.ts";
2import { NodeHttpServer } from "@effect/platform-node";
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import {
6 EnvironmentId,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadShell,
9 type SourceControlCloneRepositoryInput,
10 ProjectId,
11 OrchestratorMcpFailure,
12 ProviderInstanceId,
13 RunId,
14 ThreadId,
15} from "@t3tools/contracts";
16import { expect, it } from "@effect/vitest";
17import * as Context from "effect/Context";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Ref from "effect/Ref";
23import * as TestClock from "effect/testing/TestClock";
24import { McpSchema, McpServer } from "effect/ai";
25​
26import * as ServerConfig from "../config.ts";
27import type { ProjectionTimelinePageOptions } from "../orchestration-v2/ProjectionStore.ts";
28import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
29import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
30import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
31import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
32import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
33import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
34import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
35import * as ProjectCloneTracker from "../project/ProjectCloneTracker.ts";
36import * as ProjectService from "../project/ProjectService.ts";
37import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
38import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
39import * as SecretRequests from "../secrets/SecretRequests.ts";
40import * as ServerSettings from "../serverSettings.ts";
41import * as RemoteDelegation from "./RemoteDelegation.ts";
42import * as McpHttpServer from "../mcp/McpHttpServer.ts";
43import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
44import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
45import * as PeerForwarding from "./PeerForwarding.ts";
46import * as PeerLinks from "./PeerLinks.ts";
47import * as PeerLinkRequests from "./PeerLinkRequests.ts";
48import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
49​
50const laptop = descriptorOf("environment-laptop", "Laptop");
51const box = descriptorOf("environment-box", "Box");
52const boxProject = ProjectId.make("project:box");
53const boxThread = ThreadId.make("thread:box-auto");
54const boxRun = RunId.make("run:box-auto");
55​
56/** What B's thread service was asked to do. */
57interface Seen {
58 readonly sends: ReadonlyArray<ThreadManagement.ThreadManagementSendInput>;
59 readonly waits: ReadonlyArray<ThreadManagement.ThreadManagementWaitInput>;
60 readonly reads: ReadonlyArray<ProjectionTimelinePageOptions>;
61 readonly launches: ReadonlyArray<ThreadLaunch.ThreadLaunchInput>;
62 readonly projects: ReadonlyArray<ProjectService.ProjectCreateInput>;
63 readonly clones: ReadonlyArray<SourceControlCloneRepositoryInput>;
64 /** Commands dispatched and delegated-task stops, as `<type> <threadId>`. */
65 readonly stops: ReadonlyArray<string>;
67const nothingSeen: Seen = {
68 sends: [],
69 waits: [],
70 reads: [],
71 launches: [],
72 projects: [],
73 clones: [],
74 stops: [],
75};
76​
77/** The box user's own thread, which no link started. */
78const usersThread = ThreadId.make("thread:box-users-own");
79​
80/**
81 * B's threads: one `auto` thread in `boxProject` that the laptop's link
82 * started, whose run finishes on the third wait, and the box user's own.
83 * Every send and wait is recorded.
84 */
85const boxThreads = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) => {
86 const base = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
87 const linked = Ref.get(linkSession).pipe(
88 Effect.map((sessionId) => ({ ...base, linkOrigin: { sessionId, label: "T3 Code · Laptop" } })),
89 );
90 const users = { ...liveThreadShell(usersThread, { runtimeMode: "auto" }), projectId: boxProject };
91 const run = (status: OrchestrationV2Run["status"]) =>
92 ({
93 id: boxRun,
94 ordinal: 1,
95 status,
96 modelSelection: base.modelSelection,
97 requestedAt: base.createdAt,
98 startedAt: null,
99 completedAt: null,
100 }) as unknown as OrchestrationV2Run;
101 const shellOf = (threadId: ThreadId): Effect.Effect<OrchestrationV2ThreadShell | null> =>
102 threadId === boxThread ? linked : Effect.succeed(threadId === usersThread ? users : null);
103 const projectionOf = (threadId: ThreadId) =>
104 shellOf(threadId).pipe(
105 Effect.map(
106 (thread) =>
107 ({ thread, runs: [run("running")], runtimeRequests: [], providerTurns: [] }) as never,
108 ),
109 );
110 return Layer.mock(ThreadManagement.ThreadManagementService)({
111 getThreadShell: shellOf,
112 getProjectThreadRecords: (input) => projectionOf(input.threadId),
113 getThreadRecords: (threadId) => projectionOf(threadId),
114 getRunCount: () => Effect.succeed(1),
115 getTimelinePage: (_threadId, options) =>
116 Ref.update(seen, (current) => ({ ...current, reads: [...current.reads, options] })).pipe(
117 Effect.as({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }),
118 ),
119 listProjectThreads: () => linked.pipe(Effect.map((shell) => [shell] as never)),
120 getShellSnapshot: () => linked.pipe(Effect.map((shell) => ({ threads: [shell] }) as never)),
121 sendToThread: (input) =>
122 Ref.update(seen, (current) => ({ ...current, sends: [...current.sends, input] })).pipe(
123 Effect.as({ run: run("running"), delivery: "started" } as never),
124 ),
125 dispatch: (command) =>
126 Ref.update(seen, (current) => ({
127 ...current,
128 stops: [
129 ...current.stops,
130 `${command.type} ${"threadId" in command ? command.threadId : ""}`,
131 ],
132 })).pipe(
133 // The stop asks the provider to interrupt the thread's running turn.
134 Effect.as({
135 sequence: 0,
136 storedEvents: [
137 {
138 sequence: 1,
139 commandId: command.commandId,
140 event: {
141 type: "turn-item.updated",
142 runId: boxRun,
143 payload: {
144 type: "run_interrupt_request",
145 providerTurnId: "provider-turn:box-auto",
146 },
147 },
148 },
149 ],
150 } as never),
151 ),
152 stopDelegatedTasks: (input) =>
153 Ref.update(seen, (current) => ({
154 ...current,
155 stops: [...current.stops, `delegated-tasks.stop ${input.threadId}`],
156 })),
157 waitForThread: (input) =>
158 Ref.update(seen, (current) => ({ ...current, waits: [...current.waits, input] })).pipe(
159 Effect.as({ threadId: input.threadId, run: run("completed"), timedOut: false }),
160 ),
161 });
162};
163​
164/** B launches whatever it is asked to, and records it. */
165const boxLaunches = (seen: Ref.Ref<Seen>) =>
166 Layer.mock(ThreadLaunch.ThreadLaunchService)({
167 launch: (input) =>
168 Ref.update(seen, (current) => ({ ...current, launches: [...current.launches, input] })).pipe(
169 Effect.as({
170 threadId: input.threadId,
171 projection: {
172 thread: {
173 id: input.threadId,
174 projectId: input.projectId,
175 modelSelection: input.modelSelection,
176 title: input.title,
177 },
178 runs: [],
179 },
180 resumed: false,
181 } as unknown as ThreadLaunch.ThreadLaunchResult),
182 ),
183 });
184​
185/** B clones and registers whatever it is asked to, and records it. */
186const boxProjects = (seen: Ref.Ref<Seen>) =>
187 Layer.merge(
188 Layer.mock(ProjectService.ProjectService)({
189 getById: (id) =>
190 Effect.succeed(
191 id === boxProject
192 ? Option.some({
193 id,
194 title: "t3code",
195 workspaceRoot: "/box/t3code",
196 defaultModelSelection: null,
197 scripts: [],
198 createdAt: "2026-10-18T00:00:00.000Z",
199 updatedAt: "2026-10-18T00:00:00.000Z",
200 deletedAt: null,
201 })
202 : Option.none(),
203 ),
204 create: (input) =>
205 Ref.update(seen, (current) => ({
206 ...current,
207 projects: [...current.projects, input],
208 })).pipe(
209 Effect.as({
210 id: input.projectId,
211 title: input.title,
212 workspaceRoot: input.workspaceRoot,
213 defaultModelSelection: null,
214 scripts: [],
215 createdAt: "2026-10-18T00:00:00.000Z",
216 updatedAt: "2026-10-18T00:00:00.000Z",
217 deletedAt: null,
218 }),
219 ),
220 }),
221 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
222 cloneRepository: (input) =>
223 Ref.update(seen, (current) => ({ ...current, clones: [...current.clones, input] })).pipe(
224 Effect.as({
225 cwd: input.destinationPath,
226 remoteUrl: "https://github.com/pingdotgg/t3code.git",
227 repository: null,
228 }),
229 ),
230 }),
231 );
232​
233/**
234 * The orchestrator and project toolkits on B's real `/mcp`, behind its real
235 * OAuth. `linkSession` is filled in once A links, so B's fixture thread reads
236 * as one that link started.
237 */
238const serveBox = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) =>
239 servePeer(
240 box,
241 Layer.mergeAll(
242 McpHttpServer.layerOrchestratorToolkit,
243 McpHttpServer.layerProjectRegistration,
244 McpHttpServer.layerThreadToolkit,
245 ).pipe(
246 Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
247 Layer.provide(NodeCrypto.layer),
248 Layer.provide(boxThreads(seen, linkSession)),
249 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
250 Layer.provide(boxLaunches(seen)),
251 Layer.provide(
252 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
253 ),
254 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
255 Layer.provide(boxProjects(seen)),
256 Layer.provide(
257 ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-forwarding-box-" }).pipe(
258 Layer.provide(NodeServices.layer),
259 ),
260 ),
261 Layer.provide(NodeServices.layer),
262 Layer.provide(
263 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
264 ),
265 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
266 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
267 Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})),
268 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
269 Layer.provide(ServerSettings.layerTest()),
270 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
271 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
272 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
273 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
274 ),
275 );
276​
277const mcpClient = McpSchema.McpServerClient.of({
278 clientId: 1,
279 protocolVersion: "2025-06-18",
280 clientCapabilities: {},
281 clientInfo: { name: "peer-forwarding-test", version: "1" },
282 initializePayload: {
283 protocolVersion: "2025-06-18",
284 capabilities: {},
285 clientInfo: { name: "peer-forwarding-test", version: "1" },
286 },
287 getClient: Effect.die("unused"),
288});
289​
290/**
291 * Environment A: its own orchestrator toolkit with forwarding, and a thread
292 * caller whose modes the test picks. Its local threads never matter here.
293 */
294const makeLaptop = Effect.gen(function* () {
295 const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
296 const layerHere = Layer.mergeAll(
297 McpHttpServer.layerOrchestratorToolkit,
298 McpHttpServer.layerProjectRegistration,
299 McpHttpServer.layerThreadToolkit,
300 ).pipe(
301 Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
302 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
303 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
304 Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
305 Layer.provide(
306 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
307 ),
308 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
309 Layer.provide(Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({})),
310 Layer.provide(
311 ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-forwarding-laptop-" }).pipe(
312 Layer.provide(NodeServices.layer),
313 ),
314 ),
315 Layer.provide(NodeServices.layer),
316 Layer.provide(PeerForwarding.layer),
317 Layer.provide(Layer.succeedContext(linking)),
318 Layer.provide(NodeCrypto.layer),
319 Layer.provideMerge(
320 Layer.mock(ThreadManagement.ThreadManagementService)({
321 getThreadShell: (threadId) =>
322 Effect.succeed(
323 threadId === ThreadId.make("thread:laptop-from-desk")
324 ? {
325 ...liveThreadShell(threadId, { runtimeMode: "full-access" }),
326 // Work another environment's link started on this laptop.
327 linkOrigin: { sessionId: "session:desk", label: "T3 Code · Desk" },
328 }
329 : liveThreadShell(
330 threadId,
331 threadId === ThreadId.make("thread:laptop-plan")
332 ? { runtimeMode: "full-access", interactionMode: "plan" }
333 : { runtimeMode: "full-access" },
334 ),
335 ),
336 getProjectThreadRecords: ({ threadId }) =>
337 Effect.succeed({
338 thread: liveThreadShell(threadId, { runtimeMode: "full-access" }),
339 } as never),
340 }),
341 ),
342 Layer.provide(
343 Layer.mergeAll(
344 Layer.mock(ProviderRegistry.ProviderRegistry)({}),
345 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}),
346 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
347 Layer.mock(ProjectService.ProjectService)({}),
348 Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}),
349 Layer.mock(SecretRequests.SecretRequests)({}),
350 ServerSettings.layerTest(),
351 // No thread here delegated to the box, so a send there is no follow-up.
352 Layer.mock(RemoteDelegation.RemoteDelegation)({
353 followUp: (_scope, _environmentId, _request, sent) => Effect.succeed(sent),
354 }),
355 Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
356 ),
357 ),
358 Layer.fresh,
359 );
360 const here = yield* Layer.build(layerHere);
361 const server = Context.get(here, McpServer.McpServer);
362 const scopeOf = (
363 caller: string,
364 capabilities: ReadonlySet<McpInvocationContext.McpCapability> = new Set(["orchestration"]),
365 ): McpInvocationContext.McpInvocationScope => ({
366 environmentId: laptop.environmentId,
367 requestNamespace: `provider-session:${caller}`,
368 thread: {
369 threadId: ThreadId.make(caller),
370 providerSessionId: `provider-session:${caller}`,
371 providerInstanceId: ProviderInstanceId.make("codex"),
372 },
373 client: undefined,
374 capabilities,
375 issuedAt: 1,
376 });
377 const call = (
378 caller: string,
379 name: string,
380 args: Record<string, unknown>,
381 capabilities?: ReadonlySet<McpInvocationContext.McpCapability>,
382 ) =>
383 server
384 .callTool({ name, arguments: args })
385 .pipe(
386 Effect.provideService(
387 McpInvocationContext.McpInvocationContext,
388 scopeOf(caller, capabilities),
389 ),
390 Effect.provideService(McpSchema.McpServerClient, mcpClient),
391 );
392 return { links: Context.get(linking, PeerLinks.PeerLinks), call };
393});
394​
395const failureOf = (result: McpSchema.CallToolResult) => {
396 const text = result.content[0];
397 return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
398};
399​
400it.effect("an agent here works on a linked environment's threads within its own modes", () =>
401 Effect.scoped(
402 Effect.gen(function* () {
403 const seen = yield* Ref.make<Seen>(nothingSeen);
404 const linkSession = yield* Ref.make("");
405 const b = yield* serveBox(seen, linkSession);
406 const a = yield* makeLaptop;
407 yield* linkTo(a.links, b, "auto");
408 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
409​
410 const listed = yield* a.call("thread:laptop-full", "t3_environment_links", {});
411 expect(listed.structuredContent).toMatchObject({
412 environmentId: laptop.environmentId,
413 links: [
414 { environmentId: box.environmentId, label: "Box", status: "reachable", access: "auto" },
415 ],
416 });
417​
418 const threads = yield* a.call("thread:laptop-full", "t3_thread_list", {
419 environmentId: box.environmentId,
420 projectId: boxProject,
421 });
422 expect(threads.isError).toBe(false);
423 expect(threads.structuredContent).toMatchObject({
424 projectId: boxProject,
425 threads: [{ threadId: boxThread, runtimeMode: "auto" }],
426 });
427​
428 // A full-access agent here is held to the link's `auto` there, which
429 // the box's `auto` thread is within.
430 const sent = yield* a.call("thread:laptop-full", "t3_thread_send", {
431 environmentId: box.environmentId,
432 threadId: boxThread,
433 message: "Carry on there.",
434 clientRequestId: "send-1",
435 });
436 expect(sent.isError).toBe(false);
437 expect(sent.structuredContent).toMatchObject({ threadId: boxThread, delivery: "started" });
438 // The box records which thread here sent it.
439 expect((yield* Ref.get(seen)).sends[0]?.linkedSender).toEqual({
440 environmentId: laptop.environmentId,
441 threadId: "thread:laptop-full",
442 title: "thread:laptop-full",
443 });
444​
445 // A plan-mode agent here may not steer that thread there: the box
446 // refuses it, because the call carries the agent's own modes.
447 const planned = yield* a.call("thread:laptop-plan", "t3_thread_send", {
448 environmentId: box.environmentId,
449 threadId: boxThread,
450 message: "Change course.",
451 });
452 expect(failureOf(planned)).toMatchObject({ code: "interaction_mode_escalation_denied" });
453 expect((yield* Ref.get(seen)).sends).toHaveLength(1);
454​
455 // stop=true stops the thread there as its Stop button does: the whole
456 // thread and the tasks it delegated, not just the running turn.
457 const stopped = yield* a.call("thread:laptop-full", "t3_thread_interrupt", {
458 environmentId: box.environmentId,
459 threadId: boxThread,
460 stop: true,
461 clientRequestId: "stop-1",
462 });
463 expect(stopped.structuredContent).toMatchObject({
464 threadId: boxThread,
465 runId: boxRun,
466 status: "interrupt_requested",
467 });
468 expect((yield* Ref.get(seen)).stops).toEqual([
469 `thread.stop ${boxThread}`,
470 `delegated-tasks.stop ${boxThread}`,
471 ]);
472 }),
473 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
474);
475​
476it.effect("keeps a forwarded wait short and its retries scoped to the caller", () =>
477 Effect.scoped(
478 Effect.gen(function* () {
479 const seen = yield* Ref.make<Seen>(nothingSeen);
480 const linkSession = yield* Ref.make("");
481 const b = yield* serveBox(seen, linkSession);
482 const a = yield* makeLaptop;
483 yield* linkTo(a.links, b, "auto");
484 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
485​
486 const waited = yield* a.call("thread:laptop-full", "t3_thread_wait", {
487 environmentId: box.environmentId,
488 threadId: boxThread,
489 timeoutMs: 600_000,
490 });
491 expect(waited.structuredContent).toEqual({
492 threadId: boxThread,
493 runId: boxRun,
494 status: "completed",
495 timedOut: false,
496 });
497 // One capped piece, so the caller's MCP request returns before its client times out.
498 expect((yield* Ref.get(seen)).waits.map(({ timeoutMs }) => timeoutMs)).toEqual([45_000]);
499​
500 const send = (caller: string, clientRequestId: string) =>
501 a.call(caller, "t3_thread_send", {
502 environmentId: box.environmentId,
503 threadId: boxThread,
504 message: "Once.",
505 clientRequestId,
506 });
507 yield* send("thread:laptop-full", "same-key");
508 yield* send("thread:laptop-full", "same-key");
509 yield* send("thread:laptop-other", "same-key");
510 const [first, retried, other] = (yield* Ref.get(seen)).sends.map((input) => input.commandId);
511 // The box sees every caller here as the one link, so the key is scoped
512 // to its caller before it leaves: a retry matches, another agent's same
513 // key does not.
514 expect(retried).toBe(first);
515 expect(other).not.toBe(first);
516 expect(first).not.toContain("same-key");
517 }),
518 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
519);
520​
521it.effect("launches in a linked environment with the caller's modes, retry-safe", () =>
522 Effect.scoped(
523 Effect.gen(function* () {
524 const seen = yield* Ref.make<Seen>(nothingSeen);
525 const linkSession = yield* Ref.make("");
526 const b = yield* serveBox(seen, linkSession);
527 const a = yield* makeLaptop;
528 yield* linkTo(a.links, b, "full-access");
529 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
530 const codex = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };
531 const launch = (caller: string, args: Record<string, unknown> = {}) =>
532 a.call(caller, "t3_thread_launch", {
533 environmentId: box.environmentId,
534 projectId: boxProject,
535 title: "Run the suite there",
536 modelSelection: codex,
537 message: "Run the suite.",
538 clientRequestId: "launch-1",
539 ...args,
540 });
541​
542 const first = yield* launch("thread:laptop-plan");
543 expect(first.isError).toBe(false);
544 expect(first.structuredContent).toMatchObject({
545 projectId: boxProject,
546 modelSelection: codex,
547 });
548 const retried = yield* launch("thread:laptop-plan");
549 const [launched, relaunched] = (yield* Ref.get(seen)).launches;
550 // The thread there runs with the caller's own modes here, below the
551 // link's full access, and a retry asks for the same thread.
552 expect(launched).toMatchObject({ runtimeMode: "full-access", interactionMode: "plan" });
553 expect(relaunched?.threadId).toBe(launched?.threadId);
554 expect(retried.structuredContent).toEqual(first.structuredContent);
555​
556 // An escalation past the caller's own modes is refused here.
557 const escalated = yield* launch("thread:laptop-plan", { interactionMode: "default" });
558 expect(failureOf(escalated)).toMatchObject({ code: "interaction_mode_escalation_denied" });
559 // A pending upload lives here, so it cannot go along.
560 yield* Ref.set(b.bearers, []);
561 const withUpload = yield* launch("thread:laptop-full", {
562 clientRequestId: "launch-2",
563 attachments: [
564 { type: "image", id: "upload-1", name: "a.png", mimeType: "image/png", sizeBytes: 1 },
565 ],
566 });
567 expect(failureOf(withUpload)).toMatchObject({ code: "invalid_request" });
568 expect(yield* Ref.get(b.bearers)).toEqual([]);
569 expect((yield* Ref.get(seen)).launches).toHaveLength(2);
570 }),
571 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
572);
573​
574it.effect("brings a repository to a linked environment, only through full access", () =>
575 Effect.scoped(
576 Effect.gen(function* () {
577 const seen = yield* Ref.make<Seen>(nothingSeen);
578 const b = yield* serveBox(seen, yield* Ref.make(""));
579 const a = yield* makeLaptop;
580 const clone = { repository: "pingdotgg/t3code", destinationPath: "/home/box/t3code" };
581 const register = { title: "t3code", workspaceRoot: "/home/box/t3code" };
582​
583 yield* linkTo(a.links, b, "full-access");
584 const cloned = yield* a.call("thread:laptop-full", "t3_project_clone", {
585 environmentId: box.environmentId,
586 ...clone,
587 });
588 expect(cloned.structuredContent).toMatchObject({ cwd: clone.destinationPath });
589 const created = yield* a.call("thread:laptop-full", "t3_project_create", {
590 environmentId: box.environmentId,
591 ...register,
592 });
593 expect(created.structuredContent).toMatchObject(register);
594 expect((yield* Ref.get(seen)).clones).toEqual([clone]);
595 expect((yield* Ref.get(seen)).projects).toMatchObject([register]);
596​
597 // A plan-mode agent here may not, and nothing leaves.
598 yield* Ref.set(b.bearers, []);
599 const planned = yield* a.call("thread:laptop-plan", "t3_project_create", {
600 environmentId: box.environmentId,
601 ...register,
602 });
603 expect(failureOf(planned)).toMatchObject({ code: "capability_denied" });
604 expect(yield* Ref.get(b.bearers)).toEqual([]);
605​
606 // Nor may a full-access agent through a link with less: the box holds it.
607 yield* linkTo(a.links, b, "auto");
608 for (const [name, args] of [
609 ["t3_project_clone", clone],
610 ["t3_project_create", register],
611 ] as const) {
612 const refused = yield* a.call("thread:laptop-full", name, {
613 environmentId: box.environmentId,
614 ...args,
615 });
616 const failure = failureOf(refused);
617 expect(failure, name).toMatchObject({ code: "capability_denied" });
618 // The agent's thread is full access; what holds it is the link's access.
619 expect(failure.message, name).toContain("linked environment");
620 expect(failure.message, name).not.toContain("calling thread");
621 }
622 expect((yield* Ref.get(seen)).clones).toHaveLength(1);
623 expect((yield* Ref.get(seen)).projects).toHaveLength(1);
624 }),
625 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
626);
627​
628it.effect("runs any tool that takes a linked environment there", () =>
629 Effect.scoped(
630 Effect.gen(function* () {
631 const seen = yield* Ref.make<Seen>(nothingSeen);
632 const linkSession = yield* Ref.make("");
633 const b = yield* serveBox(seen, linkSession);
634 const a = yield* makeLaptop;
635 yield* linkTo(a.links, b, "auto");
636 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
637​
638 const there = yield* a.call("thread:laptop-full", "t3_thread_configure", {
639 environmentId: box.environmentId,
640 threadId: boxThread,
641 });
642 expect(there.structuredContent).toMatchObject({ threadId: boxThread, runtimeMode: "auto" });
643 const archived = yield* a.call("thread:laptop-full", "t3_thread_organize", {
644 environmentId: box.environmentId,
645 threadId: boxThread,
646 action: "archive",
647 });
648 expect(archived.isError).toBe(false);
649 expect((yield* Ref.get(seen)).stops).toEqual([`thread.archive ${boxThread}`]);
650 // A cursorless read from an agent here gets the newest page there, as it does locally.
651 const read = yield* a.call("thread:laptop-full", "t3_thread_read", {
652 environmentId: box.environmentId,
653 threadId: boxThread,
654 });
655 expect(read.isError).toBe(false);
656 expect((yield* Ref.get(seen)).reads).toEqual([
657 { beforePosition: Number.MAX_SAFE_INTEGER, limit: 10, view: "messages" },
658 ]);
659​
660 // This environment's own id keeps the call here.
661 const own = yield* a.call("thread:laptop-full", "t3_thread_configure", {
662 environmentId: laptop.environmentId,
663 });
664 expect(own.structuredContent).toMatchObject({
665 threadId: "thread:laptop-full",
666 runtimeMode: "full-access",
667 });
668 }),
669 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
670);
671​
672it.effect("refuses what a linked environment cannot take before anything leaves", () =>
673 Effect.scoped(
674 Effect.gen(function* () {
675 const seen = yield* Ref.make<Seen>(nothingSeen);
676 const linkSession = yield* Ref.make("");
677 const b = yield* serveBox(seen, linkSession);
678 const a = yield* makeLaptop;
679 yield* linkTo(a.links, b, "auto");
680 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
681 yield* Ref.set(b.bearers, []);
682​
683 const unknown = yield* a.call("thread:laptop-full", "t3_thread_read", {
684 environmentId: EnvironmentId.make("environment-elsewhere"),
685 threadId: boxThread,
686 });
687 expect(failureOf(unknown)).toMatchObject({ code: "invalid_request" });
688 expect(yield* Ref.get(b.bearers)).toEqual([]);
689​
690 // The box sees only the link's credential, so one that may not control
691 // threads here may not reach them there either.
692 const previewOnly = new Set<McpInvocationContext.McpCapability>(["preview"]);
693 for (const [name, args] of [
694 ["t3_environment_links", {}],
695 ["t3_project_list", { environmentId: box.environmentId }],
696 ["t3_thread_list", { environmentId: box.environmentId, projectId: boxProject }],
697 ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
698 ["t3_thread_wait", { environmentId: box.environmentId, threadId: boxThread }],
699 [
700 "t3_thread_send",
701 { environmentId: box.environmentId, threadId: boxThread, message: "Carry on there." },
702 ],
703 [
704 "t3_thread_organize",
705 { environmentId: box.environmentId, threadId: boxThread, action: "archive" },
706 ],
707 [
708 "t3_thread_launch",
709 {
710 environmentId: box.environmentId,
711 projectId: boxProject,
712 title: "Start there",
713 modelSelection: { instanceId: "codex", model: "gpt-5" },
714 message: "Start there.",
715 },
716 ],
717 ] as const) {
718 const refused = yield* a.call("thread:laptop-full", name, args, previewOnly);
719 expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" });
720 }
721 expect(yield* Ref.get(b.bearers)).toEqual([]);
722​
723 // Work a desk's link started here never uses this laptop's links: the
724 // box would see the laptop, not the desk, so its fence could not hold.
725 for (const [name, args] of [
726 ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
727 [
728 "t3_thread_send",
729 { environmentId: box.environmentId, threadId: boxThread, message: "From the desk." },
730 ],
731 [
732 "t3_thread_launch",
733 { environmentId: box.environmentId, projectId: boxProject, title: "x" },
734 ],
735 ] as const) {
736 const relayed = yield* a.call("thread:laptop-from-desk", name, args);
737 expect(failureOf(relayed), name).toMatchObject({ code: "capability_denied" });
738 }
739 expect(yield* Ref.get(b.bearers)).toEqual([]);
740 }),
741 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
742);
743​
744it.effect("refuses a launch there above the link's access, naming the link", () =>
745 Effect.scoped(
746 Effect.gen(function* () {
747 const seen = yield* Ref.make<Seen>(nothingSeen);
748 const linkSession = yield* Ref.make("");
749 const b = yield* serveBox(seen, linkSession);
750 const a = yield* makeLaptop;
751 yield* linkTo(a.links, b, "auto");
752 yield* Ref.set(linkSession, (yield* b.linkedSessions)[0]!.sessionId);
753​
754 // A full-access agent here asks for more than the link allows there.
755 const launchAboveLink = a.call("thread:laptop-full", "t3_thread_launch", {
756 environmentId: box.environmentId,
757 projectId: boxProject,
758 title: "Run the suite there",
759 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
760 message: "Run the suite.",
761 runtimeMode: "full-access",
762 });
763 const { message } = failureOf(yield* launchAboveLink);
764 expect(message).toContain('"Box"');
765 expect(message).toContain("auto");
766 expect(message).toContain("full-access");
767 expect(message).not.toContain("parent mode");
768 expect((yield* Ref.get(seen)).launches).toEqual([]);
769​
770 // Once the link has expired, that is what the agent needs to hear.
771 yield* TestClock.adjust(Duration.days(31));
772 expect(failureOf(yield* launchAboveLink).message).toContain("expired");
773 }),
774 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
775);
776​
777const refusedRead = (message: string) =>
778 new OrchestratorMcpFailure({ code: "invalid_request", message });
779const beforePositionRefusal = refusedRead(
780 `Invalid parameters for tool 't3_thread_read': Unknown argument "beforePosition". Accepted arguments: limit, view.`,
781);
782​
783it("recognizes only a validation refusal of beforePosition", () => {
784 const cases: Array<[OrchestratorMcpFailure, boolean]> = [
785 [beforePositionRefusal, true],
786 [
787 refusedRead(
788 `Invalid parameters for tool 't3_thread_read': Unknown arguments "runLimit", "beforePosition". Accepted arguments: limit.`,
789 ),
790 true,
791 ],
792 [refusedRead(`Invalid parameters for tool 't3_thread_read': Unknown argument "limit".`), false],
793 // A thread id can carry the same words; only the refusal's code and prefix count.
794 [
795 new OrchestratorMcpFailure({
796 code: "thread_not_found",
797 message: `Thread Unknown argument "beforePosition". Accepted arguments: x. is no longer available.`,
798 }),
799 false,
800 ],
801 ];
802 for (const [failure, expected] of cases) {
803 expect(PeerForwarding.refusesBeforePosition(failure)).toBe(expected);
804 }
805});
806​
807it.effect("retries a newest-page read without its cursor when the peer refuses the cursor", () =>
808 Effect.gen(function* () {
809 const sent: Array<unknown> = [];
810 const olderPeer = (args: unknown): Effect.Effect<string, OrchestratorMcpFailure> => {
811 sent.push(args);
812 return "beforePosition" in (args as object)
813 ? Effect.fail(beforePositionRefusal)
814 : Effect.succeed("forward page");
815 };
816 const params = { threadId: "thread:box-auto", limit: 35 };
817 const newest = { ...params, beforePosition: Number.MAX_SAFE_INTEGER };
818​
819 const page = yield* PeerForwarding.readNewestOrRetry(olderPeer, newest, params);
820​
821 expect(page).toBe("forward page");
822 expect(sent).toEqual([newest, params]);
823 }),
824);