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