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

PeerForwarding.test.ts

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