From 8ee8556e3e5e740f95593e8d395779a9c7ca5f08 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:50:30 +0100 Subject: [PATCH 01/14] feat: work moving to another machine can bring its uncommitted files delegate_task takes workFiles: "transfer" for a task on a linked environment. The source streams a gzip tar of the thread's changed, staged and untracked files (secrets stay behind) to a one-time upload the target issues through a new peer-only MCP tool. The target checks the archive, refuses a HEAD mismatch or any path with local changes, applies the files, and removes the archive on every path. A failed transfer launches nothing. The thread menu and command palette get "Continue on another machine", which asks the server for a work-files summary, asks whether to transfer the files only when there are some, and starts a thread on the linked machine from a handoff of this thread's conversation. --- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/mcp/McpHttpServer.ts | 18 +- apps/server/src/mcp/McpInvocationContext.ts | 7 + apps/server/src/mcp/OrchestratorMcpService.ts | 6 + .../src/mcp/toolkits/workFiles/handlers.ts | 26 + .../src/mcp/toolkits/workFiles/tools.ts | 29 ++ .../src/observability/RpcInstrumentation.ts | 2 + .../src/peer/ContinueOnEnvironment.test.ts | 200 +++++++ apps/server/src/peer/ContinueOnEnvironment.ts | 219 ++++++++ apps/server/src/peer/PeerLinks.testkit.ts | 5 +- apps/server/src/peer/RemoteDelegation.test.ts | 83 +++ apps/server/src/peer/RemoteDelegation.ts | 92 +++- apps/server/src/peer/WorkFiles.test.ts | 302 +++++++++++ apps/server/src/peer/WorkFiles.ts | 487 ++++++++++++++++++ .../server/src/peer/WorkFilesTransfer.test.ts | 238 +++++++++ apps/server/src/peer/WorkFilesTransfer.ts | 389 ++++++++++++++ apps/server/src/server.ts | 7 + apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 10 + apps/web/src/components/CommandPalette.tsx | 20 + apps/web/src/components/Sidebar.tsx | 6 + .../chat/ContinueOnMachineDialog.tsx | 224 ++++++++ .../chat/continueOnMachineDialogState.ts | 17 + .../src/components/threadActionMenu.logic.ts | 12 + apps/web/src/contextMenuFallback.ts | 7 + .../web/src/hooks/useThreadActionMenu.test.ts | 1 + apps/web/src/hooks/useThreadActionMenu.ts | 6 + apps/web/src/routes/__root.tsx | 2 + apps/web/src/state/entities.ts | 15 + docs/user/remote-access.md | 15 + .../client-runtime/src/state/peerLinks.ts | 14 + .../contracts/src/clientRpcPermissions.ts | 3 + packages/contracts/src/environment.ts | 3 + packages/contracts/src/index.ts | 1 + packages/contracts/src/orchestratorMcp.ts | 7 + packages/contracts/src/rpc.ts | 23 + packages/contracts/src/workFiles.ts | 65 +++ .../shared/src/t3McpToolPresentation.test.ts | 9 + packages/shared/src/t3McpToolPresentation.ts | 18 +- 39 files changed, 2565 insertions(+), 26 deletions(-) create mode 100644 apps/server/src/mcp/toolkits/workFiles/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/workFiles/tools.ts create mode 100644 apps/server/src/peer/ContinueOnEnvironment.test.ts create mode 100644 apps/server/src/peer/ContinueOnEnvironment.ts create mode 100644 apps/server/src/peer/WorkFiles.test.ts create mode 100644 apps/server/src/peer/WorkFiles.ts create mode 100644 apps/server/src/peer/WorkFilesTransfer.test.ts create mode 100644 apps/server/src/peer/WorkFilesTransfer.ts create mode 100644 apps/web/src/components/chat/ContinueOnMachineDialog.tsx create mode 100644 apps/web/src/components/chat/continueOnMachineDialogState.ts create mode 100644 packages/contracts/src/workFiles.ts diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 912a30f563684..5c3f4c84ff2e2 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -289,6 +289,7 @@ export const make = Effect.gen(function* () { ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}), serverBrowser: true, peerLinks: true, + continueOnEnvironment: true, mcpModeLimitHeader: true, linkFence: true, mcpApprovalCodes: true, diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 39f679154bcfe..4f40c8eda1007 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -72,6 +72,8 @@ import { } from "./toolkits/preview/tools.ts"; import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts"; import { WorktreeToolkit } from "./toolkits/worktree/tools.ts"; +import * as WorkFilesHandlers from "./toolkits/workFiles/handlers.ts"; +import { WorkFilesToolkit } from "./toolkits/workFiles/tools.ts"; import * as WorktreeMcpService from "./WorktreeMcpService.ts"; import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts"; import * as ToolSearchHandlers from "./toolkits/toolSearch/handlers.ts"; @@ -1337,7 +1339,14 @@ const layerToolExposure = Layer.effect( const server = yield* McpServer.McpServer; return McpToolExposure.make( () => - server.tools.map(({ tool }) => ({ name: tool.name, description: tool.description ?? "" })), + server.tools + // Agents never search for tools only a linked environment calls. + .filter( + ({ annotations }) => + Context.getOrUndefined(annotations, McpSchema.EnabledWhen) !== + McpInvocationContext.onlyForLinkedEnvironments, + ) + .map(({ tool }) => ({ name: tool.name, description: tool.description ?? "" })), () => server.notifications["notifications/tools/list_changed"]({}), ); }), @@ -1371,4 +1380,9 @@ export const layerToolSearch = Layer.mergeAll( layerDeferredListing, ).pipe(Layer.provide(layerToolExposure)); -export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolSearch)); +/** Outside layerTools: only linked environments list it, never an agent. */ +export const layerWorkFilesToolkit = toolkitRegistration(WorkFilesToolkit, WorkFilesHandlers.layer); + +export const layer = layerMcpTransport( + Layer.mergeAll(layerTools, layerToolSearch, layerWorkFilesToolkit), +); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index eb102be177782..ccb3930489fd4 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -182,6 +182,13 @@ export const hiddenWhileLinksOff = (): boolean => { return scope?.linkedEnvironments !== false; }; +/** `McpSchema.EnabledWhen` for tools only a linked environment calls, never an agent. */ +export const onlyForLinkedEnvironments = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope?.client?.linked === true; +}; + export type McpCapabilityError = C extends "preview" ? PreviewAutomationUnavailableError : McpCapabilityUnavailableError; diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index c52716f2ba2d4..b070bc99b47b1 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2548,6 +2548,12 @@ const make = Effect.gen(function* () { ? awaitTask(scope, taskId, taskId, input.timeoutMs) : readTask(scope, taskId, false, true); } + if (input.workFiles === "transfer") { + return yield* failure( + "invalid_request", + "workFiles 'transfer' needs target.environmentId on another machine; a task here already shares this checkout.", + ); + } const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task"); if ( input.target?.projectId !== undefined && diff --git a/apps/server/src/mcp/toolkits/workFiles/handlers.ts b/apps/server/src/mcp/toolkits/workFiles/handlers.ts new file mode 100644 index 0000000000000..95efc66f5e311 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workFiles/handlers.ts @@ -0,0 +1,26 @@ +import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import * as WorkFilesTransfer from "../../../peer/WorkFilesTransfer.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { WorkFilesToolkit } from "./tools.ts"; + +export const layer = McpToolAccess.toLayer(WorkFilesToolkit, { + // The same access a launch from a link needs: no read-only link, no stopped caller. + t3_work_files_receive: McpToolAccess.writes( + (request) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + if (scope.client?.linked !== true) { + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: "Only a linked environment can send work files here.", + }); + } + const transfer = yield* WorkFilesTransfer.WorkFilesTransfer; + return yield* transfer.issueReceive({ request, sessionId: scope.client.sessionId }); + }), + { linkedCallers: "allowed" }, + ), +}); diff --git a/apps/server/src/mcp/toolkits/workFiles/tools.ts b/apps/server/src/mcp/toolkits/workFiles/tools.ts new file mode 100644 index 0000000000000..75d97179cfb2b --- /dev/null +++ b/apps/server/src/mcp/toolkits/workFiles/tools.ts @@ -0,0 +1,29 @@ +import { + OrchestratorMcpFailure, + WorkFilesReceiveInput, + WorkFilesReceiveResult, +} from "@t3tools/contracts"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; + +import * as WorkFilesTransfer from "../../../peer/WorkFilesTransfer.ts"; +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +/** Called by a linked environment bringing a thread's files here; agents never see it. */ +export const WorkFilesReceiveTool = Tool.make("t3_work_files_receive", { + description: + "Linked environments only: get a one-time upload for work files into a project's checkout.", + parameters: WorkFilesReceiveInput, + success: WorkFilesReceiveResult, + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + WorkFilesTransfer.WorkFilesTransfer, + ], +}) + .annotate(Tool.Destructive, true) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.onlyForLinkedEnvironments); + +export const WorkFilesToolkit = Toolkit.make(WorkFilesReceiveTool); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 3f120a39f1870..c7c8411fa4e3f 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -164,6 +164,8 @@ const RPC_AGGREGATES = { [WS_METHODS.projectsEnsureScratch]: "orchestration", [WS_METHODS.projectsCreateNew]: "orchestration", [WS_METHODS.projectsCreateFromThread]: "orchestration", + [WS_METHODS.threadsWorkFilesSummary]: "orchestration", + [WS_METHODS.threadsContinueOnEnvironment]: "orchestration", [WS_METHODS.shellOpenInEditor]: "workspace", [WS_METHODS.filesystemBrowse]: "workspace", [WS_METHODS.filesystemGetMetadata]: "workspace", diff --git a/apps/server/src/peer/ContinueOnEnvironment.test.ts b/apps/server/src/peer/ContinueOnEnvironment.test.ts new file mode 100644 index 0000000000000..a6d48157e0b21 --- /dev/null +++ b/apps/server/src/peer/ContinueOnEnvironment.test.ts @@ -0,0 +1,200 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { + EnvironmentId, + OrchestratorMcpFailure, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as ContinueOnEnvironment from "./ContinueOnEnvironment.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; +import * as WorkFilesTransfer from "./WorkFilesTransfer.ts"; + +const here = EnvironmentId.make("environment-laptop"); +const box = EnvironmentId.make("environment-box"); +const threadId = ThreadId.make("thread:laptop"); +const boxProject = ProjectId.make("project:box"); +const instanceId = ProviderInstanceId.make("codex"); + +const item = (id: string, type: "user_message" | "assistant_message", text: string) => ({ + id, + type, + text, + threadId, + runId: "run:1", + providerThreadId: null, + status: "completed", +}); + +/** The laptop's thread, the box's answers, and what was asked of the box, in order. */ +const setup = ( + sendResult: Effect.Effect<{ files: number; deletions: number }, OrchestratorMcpFailure>, +) => { + const calls: Array<{ tool: string; arguments: Record }> = []; + const layer = ContinueOnEnvironment.layer.pipe( + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadRecords: () => + Effect.succeed({ + thread: { + id: threadId, + projectId: ProjectId.make("project:laptop"), + title: "Fix the flaky test", + worktreePath: "/home/user/app", + runtimeMode: "full-access", + interactionMode: "default", + modelSelection: { instanceId, model: "gpt-5.4" }, + }, + turnItems: [ + item("item:1", "user_message", "The login test fails on CI."), + item( + "item:2", + "assistant_message", + "It races the session cookie; I patched auth.ts.", + ), + ], + runs: [], + } as never), + }), + ), + Layer.provide( + Layer.mock(ProjectService.ProjectService)({ + getById: () => Effect.succeedSome({ workspaceRoot: "/home/user/app" } as never), + }), + ), + Layer.provide( + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ + resolve: () => Effect.succeed({ canonicalKey: "github.com/acme/app" } as never), + }), + ), + Layer.provide( + Layer.mock(PeerLinks.PeerLinks)({ + enabled: Effect.succeed(true), + get: () => Effect.succeedSome({ environmentId: box, label: "Box" } as never), + }), + ), + Layer.provide( + Layer.mock(PeerMcpClient.PeerMcpClient)({ + call: (input) => + Effect.sync(() => { + calls.push({ tool: input.tool, arguments: input.arguments }); + switch (input.tool) { + case "t3_project_list": + return { + projects: [ + { + id: boxProject, + title: "app", + repositoryIdentity: { canonicalKey: "github.com/acme/app" }, + }, + ], + nextCursor: null, + }; + case "orchestrator_capabilities": + return { providers: [{ providerInstanceId: instanceId }] }; + case "t3_thread_launch": + return { threadId: ThreadId.make("thread:box"), projectId: boxProject }; + default: + return {}; + } + }) as never, + }), + ), + Layer.provide( + Layer.mock(WorkFilesTransfer.WorkFilesTransfer)({ + send: (input) => + Effect.suspend(() => { + calls.push({ tool: "send", arguments: { cwd: input.cwd, projectId: input.projectId } }); + return sendResult; + }), + }), + ), + Layer.provide( + Layer.succeed(ServerEnvironment.ServerEnvironment, { + getEnvironmentId: Effect.succeed(here), + getDescriptor: Effect.die("unused"), + }), + ), + Layer.provide(NodeCrypto.layer), + ); + return { calls, layer }; +}; + +it.effect("starts a thread there from this one's conversation, after its files land", () => { + const { calls, layer } = setup(Effect.succeed({ files: 2, deletions: 1 })); + return Effect.gen(function* () { + const service = yield* ContinueOnEnvironment.ContinueOnEnvironment; + const result = yield* service.continueThread({ + threadId, + environmentId: box, + workFiles: "transfer", + }); + expect(result).toEqual({ + environmentId: box, + threadId: ThreadId.make("thread:box"), + projectId: boxProject, + label: "Box", + transferredFiles: 2, + }); + expect(calls.map((call) => call.tool)).toEqual([ + "t3_project_list", + "send", + "orchestrator_capabilities", + "t3_thread_launch", + ]); + expect(calls[1]?.arguments).toEqual({ cwd: "/home/user/app", projectId: boxProject }); + const launch = calls[3]!.arguments; + expect(launch).toMatchObject({ + projectId: boxProject, + title: "Fix the flaky test", + modelSelection: { instanceId, model: "gpt-5.4" }, + }); + // The handoff carries the conversation and says the files came along. + expect(launch.message).toContain("The login test fails on CI."); + expect(launch.message).toContain("It races the session cookie; I patched auth.ts."); + expect(launch.message).toContain("2 files written, 1 deleted"); + }).pipe(Effect.provide(layer)); +}); + +it.effect("launches nothing there when the files cannot go", () => { + const { calls, layer } = setup( + Effect.fail( + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "app.ts (it has local changes there)", + }), + ), + ); + return Effect.gen(function* () { + const service = yield* ContinueOnEnvironment.ContinueOnEnvironment; + const refused = yield* service + .continueThread({ threadId, environmentId: box, workFiles: "transfer" }) + .pipe(Effect.flip); + expect(refused.message).toBe("Box: app.ts (it has local changes there)"); + expect(calls.map((call) => call.tool)).toEqual(["t3_project_list", "send"]); + }).pipe(Effect.provide(layer)); +}); + +it.effect("without files, sends nothing and says the checkout has only what is committed", () => { + const { calls, layer } = setup(Effect.die("no send")); + return Effect.gen(function* () { + const service = yield* ContinueOnEnvironment.ContinueOnEnvironment; + const result = yield* service.continueThread({ + threadId, + environmentId: box, + workFiles: "skip", + }); + expect(result.transferredFiles).toBe(0); + expect(calls.map((call) => call.tool)).not.toContain("send"); + expect(calls.at(-1)?.arguments.message).toContain("this checkout has only what is committed"); + }).pipe(Effect.provide(layer)); +}); diff --git a/apps/server/src/peer/ContinueOnEnvironment.ts b/apps/server/src/peer/ContinueOnEnvironment.ts new file mode 100644 index 0000000000000..a3aca1c88cf74 --- /dev/null +++ b/apps/server/src/peer/ContinueOnEnvironment.ts @@ -0,0 +1,219 @@ +import { + type EnvironmentId, + ModelSelection, + type OrchestratorMcpFailure, + type ProjectId, + type ThreadContinueOnEnvironmentInput, + type ThreadContinueOnEnvironmentResult, + type ThreadId, + WorkFilesReceiveResult, + WorkFilesTransferError, + type WorkFilesSummary, +} from "@t3tools/contracts"; +import { + DEFAULT_HANDOFF_TOKEN_CAP, + historicalMessage, + renderHistory, + selectHistory, +} from "@t3tools/provider-core/server/handoffBudget"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import type * as Tool from "effect/ai/Tool"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; +import { WorkFilesReceiveTool } from "../mcp/toolkits/workFiles/tools.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; +import { findRemoteProject, RemoteCapabilitiesTool } from "./RemoteDelegation.ts"; +import * as WorkFilesTransfer from "./WorkFilesTransfer.ts"; + +/** + * Continues a thread's work on a linked environment for the user: the + * thread's files go to the same repository's checkout there if asked, and a + * new thread there starts from a handoff of this one's conversation. This + * thread stays as it is. + */ +export class ContinueOnEnvironment extends Context.Service< + ContinueOnEnvironment, + { + /** What the thread's working directory would carry. */ + readonly summarize: ( + threadId: ThreadId, + ) => Effect.Effect; + readonly continueThread: ( + input: ThreadContinueOnEnvironmentInput, + ) => Effect.Effect; + } +>()("t3/peer/ContinueOnEnvironment") {} + +const refused = (message: string) => new WorkFilesTransferError({ message }); + +const LaunchResult = ProjectToolkit.tools.t3_thread_launch.successSchema; +const ProjectListResult = ProjectToolkit.tools.t3_project_list.successSchema; +const CapabilitiesResult = RemoteCapabilitiesTool.successSchema; +const encodeModelSelection = Schema.encodeSync(ModelSelection); +const encodeReceiveInput = Schema.encodeSync(WorkFilesReceiveTool.parametersSchema); + +const make = Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const projects = yield* ProjectService.ProjectService; + const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const peers = yield* PeerMcpClient.PeerMcpClient; + const links = yield* PeerLinks.PeerLinks; + const transfer = yield* WorkFilesTransfer.WorkFilesTransfer; + const random = yield* SecureRandom.SecureRandom; + const environment = yield* ServerEnvironment.ServerEnvironment; + + const loadThread = Effect.fn("ContinueOnEnvironment.loadThread")(function* (threadId: ThreadId) { + const records = yield* threads + .getThreadRecords(threadId, ["turnItems", "runs"]) + .pipe(Effect.mapError(() => refused("This thread was not found."))); + const project = yield* projects.getById(records.thread.projectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + const cwd = records.thread.worktreePath ?? project?.workspaceRoot; + if (cwd === undefined) return yield* refused("This thread has no working directory."); + return { records, project, cwd }; + }); + + const summarize: ContinueOnEnvironment["Service"]["summarize"] = Effect.fn( + "ContinueOnEnvironment.summarize", + )(function* (threadId) { + const { cwd } = yield* loadThread(threadId); + const selection = yield* transfer + .select(cwd) + .pipe(Effect.mapError((error) => refused(error.message))); + return WorkFilesTransfer.summaryOf(selection); + }); + + const continueThread: ContinueOnEnvironment["Service"]["continueThread"] = Effect.fn( + "ContinueOnEnvironment.continueThread", + )(function* (input) { + if (!(yield* links.enabled)) { + return yield* refused("Linked environments is off here. Turn it on in Settings → Labs."); + } + const link = yield* links.get(input.environmentId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + if (link === undefined) return yield* refused("This environment is not linked to that one."); + const { records, project, cwd } = yield* loadThread(input.threadId); + const { thread } = records; + const hereId = yield* environment.getEnvironmentId; + // Calls there carry this thread's modes and name it, as its own agent's calls would. + const call = >( + tool: string, + args: Record, + success: S, + ) => + peers.call({ + environmentId: input.environmentId, + tool, + arguments: args, + limits: { runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode }, + sender: { environmentId: hereId, threadId: thread.id, title: thread.title }, + success, + }); + const there = (error: OrchestratorMcpFailure) => refused(`${link.label}: ${error.message}`); + + const key = + project === undefined + ? undefined + : (yield* repositoryIdentities.resolve(project.workspaceRoot))?.canonicalKey; + if (key === undefined) { + return yield* refused( + "This thread's project has no git remote, so no project there can be matched to it.", + ); + } + const projectId: ProjectId = yield* findRemoteProject( + key, + (cursor) => + call("t3_project_list", { cursor, limit: 100 }, ProjectListResult) as Effect.Effect< + Tool.Success, + OrchestratorMcpFailure + >, + ).pipe( + Effect.mapError((error) => + error.code === "invalid_request" + ? refused( + `No single project on ${link.label} has this repository (${key}). Add it there, then try again.`, + ) + : there(error), + ), + ); + + const transferred = + input.workFiles === "transfer" + ? yield* transfer + .send({ + cwd, + environmentId: input.environmentId, + projectId, + receive: (request) => + call( + WorkFilesReceiveTool.name, + encodeReceiveInput(request) as Record, + WorkFilesReceiveResult, + ), + }) + .pipe(Effect.mapError(there)) + : { files: 0, deletions: 0 }; + + // The same instance there keeps the thread's model; otherwise the project there picks one. + const capabilities = yield* call("orchestrator_capabilities", {}, CapabilitiesResult).pipe( + Effect.mapError(there), + ); + const sameInstance = capabilities.providers.some( + (provider) => provider.providerInstanceId === thread.modelSelection.instanceId, + ); + + const filesLine = + input.workFiles === "transfer" + ? `Its working files were copied into this checkout (${transferred.files} files written, ${transferred.deletions} deleted).` + : "Its working files were not copied; this checkout has only what is committed."; + const selected = selectHistory({ + messages: records.turnItems.flatMap((item) => { + const message = historicalMessage(item); + return message === null ? [] : [message]; + }), + coverage: [ + `This thread continues thread "${thread.title}" (${thread.id}) from environment ${hereId}, moved here by the user.`, + filesLine, + ].join("\n"), + budget: DEFAULT_HANDOFF_TOKEN_CAP, + }); + const message = `${renderHistory(selected.messages, selected.context)}\n\nContinue the work from where it stopped.`; + + const launched = yield* call( + "t3_thread_launch", + { + projectId, + title: thread.title, + ...(sameInstance ? { modelSelection: encodeModelSelection(thread.modelSelection) } : {}), + message, + clientRequestId: `continue:${thread.id}:${yield* random.uuidV4()}`, + }, + LaunchResult, + ).pipe(Effect.mapError(there)); + return { + environmentId: input.environmentId as EnvironmentId, + threadId: launched.threadId, + projectId: launched.projectId, + label: link.label, + transferredFiles: transferred.files, + }; + }); + + return ContinueOnEnvironment.of({ summarize, continueThread }); +}); + +export const layer = Layer.effect(ContinueOnEnvironment, make); diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts index a9e15472eec93..e5176512e773c 100644 --- a/apps/server/src/peer/PeerLinks.testkit.ts +++ b/apps/server/src/peer/PeerLinks.testkit.ts @@ -64,9 +64,11 @@ export const descriptorOf = ( * socket. The descriptor can be swapped, as when its address comes to answer * as another environment, and every bearer it receives is recorded. */ -export const servePeer = ( +export const servePeer = ( initial: ExecutionEnvironmentDescriptor, tools: Layer.Layer, + /** More routes it serves beside `/mcp`, such as an upload a tool there issues. */ + routes: Layer.Layer = Layer.empty as Layer.Layer, ) => Effect.gen(function* () { const descriptor = yield* Ref.make(initial); @@ -140,6 +142,7 @@ export const servePeer = ( ), Layer.provide(McpOAuth.layerMcpClientAuthenticator), ), + routes, ).pipe( Layer.provide(layerRecordBearers), Layer.provide(layerEnvironment), diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 6d09b6b1b3a68..e744cb105ca6c 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -8,6 +8,7 @@ import { MessageId, type ModelSelection, NodeId, + OrchestratorMcpFailure, type OrchestrationV2Run, ProjectId, ProviderDriverKind, @@ -68,6 +69,7 @@ import * as PeerLinks from "./PeerLinks.ts"; import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts"; import * as RemoteDelegation from "./RemoteDelegation.ts"; import * as PeerLinkRequests from "./PeerLinkRequests.ts"; +import * as WorkFilesTransfer from "./WorkFilesTransfer.ts"; // The laptop's agent delegates a task to the box through a link. The box is // its real /mcp behind real OAuth, with one thread the test finishes; the @@ -644,6 +646,10 @@ const makeLaptop = ( >, /** The laptop's links from before a restart, which keep their sessions there. */ kept?: Context.Context>>, + /** Sending work files; by default any send fails the test, as `workFiles: "skip"` sends none. */ + workFiles: Partial = { + send: () => Effect.die("no work files are sent unless a task asks"), + }, ) => Effect.gen(function* () { const linking = kept ?? (yield* layerLinkingEnvironment(laptop).pipe(Layer.build)); @@ -696,6 +702,7 @@ const makeLaptop = ( ), ), Layer.provide(Layer.succeedContext(linking)), + Layer.provide(Layer.mock(WorkFilesTransfer.WorkFilesTransfer)(workFiles)), Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), Layer.provide(NodeCrypto.layer), Layer.provideMerge(layerThreads), @@ -1284,6 +1291,82 @@ it.effect("refuses worktree isolation for a task there before launching anything ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("sends the work files before launching there, and launches nothing when they fail", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const sent: Array<{ cwd: string; projectId: string; launchedFirst: boolean }> = []; + let fail = true; + const a = yield* makeLaptop(database, offers, undefined, { + send: (input) => + Effect.gen(function* () { + sent.push({ + cwd: input.cwd, + projectId: input.projectId, + launchedFirst: (yield* Ref.get(thread.launched)) !== null, + }); + if (fail) { + return yield* new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "The checkout there is at abc, but the files apply to def.", + }); + } + return { files: 3, deletions: 0 }; + }), + }); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegate = a.call("delegate_task", { + task: "Run the suite on the box with my edits.", + target: { environmentId: box.environmentId }, + workFiles: "transfer", + }); + + const refused = yield* delegate; + expect(refused.isError).toBe(true); + expect(JSON.stringify(refused.content)).toContain( + "Nothing was launched, because the work files could not be transferred: The checkout there is at abc", + ); + expect(yield* Ref.get(thread.launched)).toBeNull(); + expect((yield* a.orchestrator.getThreadProjection(parentThreadId)).subagents).toHaveLength(0); + + fail = false; + const accepted = yield* delegate; + expect(accepted.isError, JSON.stringify(accepted.content)).toBe(false); + expect(yield* Ref.get(thread.launched)).not.toBeNull(); + // From this thread's checkout, into the project there with this repository, before the launch. + expect(sent).toEqual([ + { cwd: "/home/me/app", projectId: boxProject, launchedFirst: false }, + { cwd: "/home/me/app", projectId: boxProject, launchedFirst: false }, + ]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("refuses to transfer work files to a task on this machine", () => + Effect.scoped( + Effect.gen(function* () { + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* seedParent(a); + const result = yield* a.call("delegate_task", { + task: "Run the suite here.", + workFiles: "transfer", + }); + expect(result.isError).toBe(true); + expect(JSON.stringify(result.content)).toContain("needs target.environmentId"); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("follows an open task again after the laptop restarts", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 3b01c48b01db0..0fac203dabdf7 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -48,6 +48,8 @@ import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolv import { forkParked } from "../serverActivation.ts"; import * as PeerForwarding from "./PeerForwarding.ts"; import * as PeerLinks from "./PeerLinks.ts"; +import * as WorkFilesTransfer from "./WorkFilesTransfer.ts"; +import { WorkFilesReceiveTool } from "../mcp/toolkits/workFiles/tools.ts"; /** How long one follow of a remote task waits on its thread there before checking again. */ const FOLLOW_WAIT_MS = 10 * 60 * 1_000; @@ -68,8 +70,37 @@ export const FollowRetrySchedule = Context.Reference> type ThreadScope = McpInvocationContext.McpThreadInvocationScope; +/** The one project there whose repository is `key`, paging through `list`. */ +export const findRemoteProject = Effect.fn("RemoteDelegation.findRemoteProject")(function* ( + key: string, + list: ( + cursor: number, + ) => Effect.Effect< + Tool.Success, + OrchestratorMcpFailure + >, +) { + const matches: Array<{ readonly id: ProjectId; readonly title: string }> = []; + let cursor: number | null = 0; + while (cursor !== null) { + const listed: Tool.Success = yield* list(cursor); + matches.push( + ...listed.projects.filter((project) => project.repositoryIdentity?.canonicalKey === key), + ); + cursor = listed.nextCursor; + } + if (matches.length === 1) return matches[0]!.id; + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + matches.length === 0 + ? `No project there has this repository (${key}). Pass target.projectId; t3_project_list with this environmentId lists them. To bring the repository there, use t3_project_clone and then t3_project_create with this environmentId.` + : `Several projects there have this repository: ${matches.map((project) => `${project.title} (${project.id})`).join(", ")}. Pass target.projectId.`, + }); +}); + /** `orchestrator_capabilities` there. Its toolkit imports this module, so it is described here. */ -const RemoteCapabilitiesTool = Tool.make("orchestrator_capabilities", { +export const RemoteCapabilitiesTool = Tool.make("orchestrator_capabilities", { parameters: OrchestratorMcpCapabilitiesInput, success: OrchestratorMcpCapabilitiesResult, failure: OrchestratorMcpFailure, @@ -150,6 +181,7 @@ const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; const random = yield* SecureRandom.SecureRandom; + const workFiles = yield* WorkFilesTransfer.WorkFilesTransfer; const hereId = yield* ServerEnvironment.ServerEnvironment.pipe( Effect.flatMap((environment) => environment.getEnvironmentId), ); @@ -189,27 +221,12 @@ const make = Effect.gen(function* () { message: "Pass target.projectId: this thread's project has no repository to match there.", }); } - const matches: Array<{ readonly id: ProjectId; readonly title: string }> = []; - let cursor: number | null = 0; - while (cursor !== null) { - const listed: Tool.Success = - yield* forwarding.call(scope, ProjectToolkit.tools.t3_project_list, environmentId, { - cursor, - limit: 100, - }); - matches.push( - ...listed.projects.filter((project) => project.repositoryIdentity?.canonicalKey === key), - ); - cursor = listed.nextCursor; - } - if (matches.length === 1) return matches[0]!.id; - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: - matches.length === 0 - ? `No project there has this repository (${key}). Pass target.projectId; t3_project_list with this environmentId lists them. To bring the repository there, use t3_project_clone and then t3_project_create with this environmentId.` - : `Several projects there have this repository: ${matches.map((project) => `${project.title} (${project.id})`).join(", ")}. Pass target.projectId.`, - }); + return yield* findRemoteProject(key, (cursor) => + forwarding.call(scope, ProjectToolkit.tools.t3_project_list, environmentId, { + cursor, + limit: 100, + }), + ); }); /** The instance there of the driver the caller named, preferring the one this thread runs on, as a task here does. */ @@ -327,6 +344,37 @@ const make = Effect.gen(function* () { parent.thread.projectId, target.projectId, ); + if (input.workFiles === "transfer") { + const here = yield* projects.getById(parent.thread.projectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + const cwd = parent.thread.worktreePath ?? here?.workspaceRoot; + if (cwd === undefined) { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: "This thread has no working directory to transfer files from.", + }); + } + // The files land before the launch, so a failed transfer launches nothing. + yield* workFiles + .send({ + cwd, + environmentId: target.environmentId, + projectId, + receive: (request) => + forwarding.call(scope, WorkFilesReceiveTool, target.environmentId, request), + }) + .pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ + code: error.code, + message: `Nothing was launched, because the work files could not be transferred: ${error.message}`, + }), + ), + ); + } // One key for the launch there and the record here, so a retry finds both. // Both are scoped to the provider session, as every key a caller passes is: // the forwarder scopes the launch's, and the record's names it. diff --git a/apps/server/src/peer/WorkFiles.test.ts b/apps/server/src/peer/WorkFiles.test.ts new file mode 100644 index 0000000000000..f2ee62d7d4b90 --- /dev/null +++ b/apps/server/src/peer/WorkFiles.test.ts @@ -0,0 +1,302 @@ +// @effect-diagnostics nodeBuiltinImport:off - Fixtures drive git and tar directly on real folders. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; + +import { + applyWorkFiles, + archiveStream, + isSafeRelativePath, + listArchive, + selectWorkFiles, + WORK_FILES_MAX_BYTES, + WORK_FILES_MAX_COUNT, +} from "./WorkFiles.ts"; + +// Real git and tar on real directories: both sides of a transfer run the system tools. + +const tempDir = Effect.acquireRelease( + Effect.sync(() => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-work-files-"))), + (dir) => Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), +); + +const write = (root: string, path: string, content: string) => { + NodeFS.mkdirSync(NodePath.dirname(NodePath.join(root, path)), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(root, path), content); +}; + +const git = (cwd: string, ...args: string[]) => + NodeChildProcess.execFileSync("git", args, { + cwd, + encoding: "utf8", + env: { + ...process.env, + GIT_AUTHOR_NAME: "t", + GIT_AUTHOR_EMAIL: "t@example.com", + GIT_COMMITTER_NAME: "t", + GIT_COMMITTER_EMAIL: "t@example.com", + GIT_CONFIG_GLOBAL: "/dev/null", + }, + }).trim(); + +/** A repository with one commit of `files`. */ +const repository = (root: string, files: Record) => { + git(root, "init", "-q", "-b", "main"); + for (const [path, content] of Object.entries(files)) write(root, path, content); + git(root, "add", "-A"); + git(root, "commit", "-q", "-m", "initial"); + return git(root, "rev-parse", "HEAD"); +}; + +const tar = (cwd: string, ...args: string[]) => + NodeChildProcess.execFileSync("tar", args, { + cwd, + env: { ...process.env, COPYFILE_DISABLE: "1" }, + }); + +/** The archive the source would send for `files` under `root`, written to `archivePath`. */ +const writeArchive = (root: string, files: ReadonlyArray, archivePath: string) => + archiveStream(root, files).pipe( + Stream.runFold( + () => [] as Uint8Array[], + (chunks, chunk) => { + chunks.push(chunk); + return chunks; + }, + ), + Effect.map((chunks) => NodeFS.writeFileSync(archivePath, Buffer.concat(chunks))), + ); + +it.live( + "a git checkout carries its changed, staged, untracked and deleted files, not its secrets", + () => + Effect.gen(function* () { + const root = yield* tempDir; + const head = repository(root, { + "src/app.ts": "one", + "src/old.ts": "old", + "README.md": "readme", + ".gitignore": "ignored.log\n", + }); + write(root, "src/app.ts", "two"); + write(root, "src/staged.ts", "staged"); + git(root, "add", "src/staged.ts"); + write(root, "notes/new.md", "new"); + write(root, "ignored.log", "noise"); + write(root, ".env.local", "TOKEN=1"); + write(root, "certs/server.pem", "pem"); + NodeFS.rmSync(NodePath.join(root, "src/old.ts")); + NodeFS.symlinkSync("README.md", NodePath.join(root, "link.md")); + + const selection = yield* selectWorkFiles(root); + expect(selection.head).toBe(head); + expect(selection.files.map((file) => file.path)).toEqual([ + "notes/new.md", + "src/app.ts", + "src/staged.ts", + ]); + expect(selection.deletions).toEqual(["src/old.ts"]); + expect(selection.leftBehind).toEqual([".env.local", "certs/server.pem"]); + expect(selection.totalBytes).toBe(3 + 3 + 6); + expect(selection.refusal).toBeNull(); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("a folder outside git carries every file but dependencies, build output and secrets", () => + Effect.gen(function* () { + const root = yield* tempDir; + write(root, "index.html", "

"); + write(root, "src/main.js", "main"); + write(root, "node_modules/lib/index.js", "lib"); + write(root, "dist/main.js", "built"); + write(root, ".git/HEAD", "not a repository"); + write(root, "id_rsa", "secret"); + write(root, "deploy/.netrc", "secret"); + + const selection = yield* selectWorkFiles(root); + expect(selection.head).toBeNull(); + expect(selection.files.map((file) => file.path)).toEqual(["index.html", "src/main.js"]); + expect(selection.deletions).toEqual([]); + expect(selection.leftBehind).toEqual(["deploy/.netrc", "id_rsa"]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("refuses a set over either limit with its numbers", () => + Effect.gen(function* () { + const big = yield* tempDir; + // Sparse, so the test writes no 100 MiB. + NodeFS.truncateSync( + (write(big, "huge.bin", ""), NodePath.join(big, "huge.bin")), + WORK_FILES_MAX_BYTES + 1, + ); + expect((yield* selectWorkFiles(big)).refusal).toBe( + "The work files are 1 files and 100.0 MiB; the limit is 5,000 files and 100.0 MiB.", + ); + + const many = yield* tempDir; + for (let index = 0; index <= WORK_FILES_MAX_COUNT; index++) write(many, `f/${index}`, ""); + expect((yield* selectWorkFiles(many)).refusal).toMatch( + /^The work files are more than 5,000 files and 0\.0 MiB; the limit is 5,000 files/, + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it("keeps archive and deletion paths inside the checkout on every platform", () => { + for (const path of ["/etc/passwd", "../up", "a/../../up", "C:/x", "a\\b", ""]) { + expect(isSafeRelativePath(path), path).toBe(false); + } + for (const path of ["a", "a/b.txt", ".github/x.yml", "a..b"]) { + expect(isSafeRelativePath(path), path).toBe(true); + } +}); + +it.live.each([ + [ + "an absolute path", + (dir: string) => tar(dir, "-czPf", "bad.tgz", NodePath.join(dir, "src", "x")), + ], + [ + "a path with ..", + (dir: string) => tar(NodePath.join(dir, "src"), "-czPf", "../bad.tgz", "../src/x"), + ], + [ + "a symlink", + (dir: string) => { + NodeFS.symlinkSync("/etc", NodePath.join(dir, "src", "link")); + tar(dir, "-czf", "bad.tgz", "src/link"); + }, + ], + [ + "a hard link", + (dir: string) => { + NodeFS.linkSync(NodePath.join(dir, "src", "x"), NodePath.join(dir, "src", "y")); + tar(dir, "-czf", "bad.tgz", "src/x", "src/y"); + }, + ], +] as const)("refuses an archive with %s", ([, make]) => + Effect.gen(function* () { + const dir = yield* tempDir; + write(dir, "src/x", "x"); + make(dir); + const refused = yield* listArchive(NodePath.join(dir, "bad.tgz"), dir).pipe(Effect.flip); + expect(refused.reason).toBe("invalid_archive"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +/** A source and a target checkout of the same commit, and the source's archive of `files`. */ +const pair = (files: Record) => + Effect.gen(function* () { + const source = yield* tempDir; + const target = yield* tempDir; + const scratch = yield* tempDir; + repository(source, files); + // A clone, not a copy: git may still be writing objects after the commit. + git(target, "clone", "-q", source, "."); + return { + source, + target, + archivePath: NodePath.join(scratch, "work.tgz"), + stagingDir: NodePath.join(scratch, "staging"), + }; + }); + +it.live("applies the work to the same commit there, deletions included", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ + "a.ts": "a", + "gone.ts": "g", + }); + write(source, "a.ts", "changed"); + write(source, "deep/new.ts", "new"); + NodeFS.rmSync(NodePath.join(source, "gone.ts")); + const selection = yield* selectWorkFiles(source); + yield* writeArchive( + source, + selection.files.map((file) => file.path), + archivePath, + ); + + const input = { + archivePath, + stagingDir, + root: target, + head: selection.head, + deletions: selection.deletions, + }; + expect(yield* applyWorkFiles(input)).toEqual({ files: 2, deletions: 1 }); + expect(NodeFS.readFileSync(NodePath.join(target, "a.ts"), "utf8")).toBe("changed"); + expect(NodeFS.readFileSync(NodePath.join(target, "deep/new.ts"), "utf8")).toBe("new"); + expect(NodeFS.existsSync(NodePath.join(target, "gone.ts"))).toBe(false); + // The same work again changes nothing and is not a conflict. + NodeFS.rmSync(stagingDir, { recursive: true }); + expect(yield* applyWorkFiles(input)).toEqual({ files: 2, deletions: 0 }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("refuses a checkout on another commit, naming both", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ "a.ts": "a" }); + write(target, "b.ts", "b"); + git(target, "add", "b.ts"); + git(target, "commit", "-q", "-m", "ahead"); + write(source, "a.ts", "changed"); + const selection = yield* selectWorkFiles(source); + yield* writeArchive(source, ["a.ts"], archivePath); + + const refused = yield* applyWorkFiles({ + archivePath, + stagingDir, + root: target, + head: selection.head, + deletions: [], + }).pipe(Effect.flip); + expect(refused.reason).toBe("head_mismatch"); + expect(refused.message).toContain(selection.head!); + expect(refused.message).toContain(git(target, "rev-parse", "HEAD")); + expect(NodeFS.readFileSync(NodePath.join(target, "a.ts"), "utf8")).toBe("a"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("never overwrites a file with local changes there, and changes nothing", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ + "a.ts": "a", + "b.ts": "b", + "c.ts": "c", + }); + write(source, "a.ts", "from source"); + write(source, "b.ts", "from source"); + write(source, "new.ts", "from source"); + NodeFS.rmSync(NodePath.join(source, "c.ts")); + write(target, "b.ts", "edited there"); + write(target, "new.ts", "untracked there"); + write(target, "c.ts", "edited there"); + const selection = yield* selectWorkFiles(source); + yield* writeArchive( + source, + selection.files.map((file) => file.path), + archivePath, + ); + + const refused = yield* applyWorkFiles({ + archivePath, + stagingDir, + root: target, + head: selection.head, + deletions: selection.deletions, + }).pipe(Effect.flip); + expect(refused.reason).toBe("conflict"); + expect(refused.message).toContain("b.ts (it has local changes there)"); + expect(refused.message).toContain("new.ts (it has local changes there)"); + expect(refused.message).toContain("c.ts (it has local changes there)"); + expect(refused.message).not.toContain("a.ts"); + expect(NodeFS.readFileSync(NodePath.join(target, "a.ts"), "utf8")).toBe("a"); + expect(NodeFS.readFileSync(NodePath.join(target, "c.ts"), "utf8")).toBe("edited there"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/peer/WorkFiles.ts b/apps/server/src/peer/WorkFiles.ts new file mode 100644 index 0000000000000..d55f751586345 --- /dev/null +++ b/apps/server/src/peer/WorkFiles.ts @@ -0,0 +1,487 @@ +// @effect-diagnostics nodeBuiltinImport:off -- lstat, link counts and exclusive copies are filesystem boundaries missing from Effect's API. +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import { unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; + +export const WORK_FILES_MAX_BYTES = 100 * 1024 * 1024; +export const WORK_FILES_MAX_COUNT = 5_000; +/** Room for tar headers and gzip framing on top of the file bytes. */ +export const WORK_FILES_MAX_ARCHIVE_BYTES = WORK_FILES_MAX_BYTES + 16 * 1024 * 1024; + +const SKIPPED_DIRECTORIES = new Set([ + ".git", + "node_modules", + "dist", + "build", + "out", + "target", + "coverage", + ".next", + ".nuxt", + ".output", + ".svelte-kit", + ".turbo", + ".cache", + "__pycache__", +]); + +export class WorkFilesError extends Schema.TaggedError()("WorkFilesError", { + reason: Schema.Literals(["over_limit", "head_mismatch", "conflict", "invalid_archive", "failed"]), + message: Schema.String, +}) {} + +const failed = (message: string) => new WorkFilesError({ reason: "failed", message }); + +/** Files that look like credentials never leave the machine they are on. */ +const looksLikeSecret = (path: string) => { + const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase(); + return ( + name.startsWith(".env") || + name.endsWith(".pem") || + name.endsWith(".key") || + name.endsWith(".p12") || + name.startsWith("id_rsa") || + name === ".npmrc" || + name === ".netrc" + ); +}; + +export interface WorkFilesSelection { + readonly root: string; + /** The commit the files apply to; null outside git, "" in a repository with no commits. */ + readonly head: string | null; + readonly files: ReadonlyArray<{ readonly path: string; readonly size: number }>; + readonly deletions: ReadonlyArray; + readonly leftBehind: ReadonlyArray; + readonly totalBytes: number; + /** Why the set cannot go, with the numbers; nothing is sent when set. */ + readonly refusal: string | null; +} + +const formatMiB = (bytes: number) => `${(bytes / (1024 * 1024)).toFixed(1)} MiB`; + +const fileSystemCall = (what: string, run: () => Promise) => + Effect.tryPromise({ try: run, catch: () => failed(`Could not ${what}.`) }); + +const lstatOrNull = (path: string) => Effect.promise(() => NodeFSP.lstat(path).catch(() => null)); + +interface ProcessResult { + readonly code: number; + readonly stdout: Uint8Array; + readonly stderr: string; +} + +const collect = (stream: Stream.Stream) => + stream.pipe( + Stream.runFold( + () => [] as Uint8Array[], + (chunks, chunk) => { + chunks.push(chunk); + return chunks; + }, + ), + Effect.map((chunks) => Buffer.concat(chunks)), + ); + +/** Runs a command to completion; git and tar never prompt, so stdin is closed or the given stream. */ +const runProcess = Effect.fn("WorkFiles.runProcess")(function* ( + command: string, + args: ReadonlyArray, + options: { readonly cwd: string; readonly stdin?: Uint8Array }, +) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const platform = yield* HostProcess.Platform; + return yield* Effect.scoped( + Effect.gen(function* () { + const child = yield* spawner.spawn( + ChildProcess.make(command, args, { + cwd: options.cwd, + env: { ...unsetInheritedRepositoryEnv(process.env, platform), LC_ALL: "C" }, + extendEnv: true, + stdin: options.stdin === undefined ? "ignore" : Stream.make(options.stdin), + }), + ); + const [stdout, stderr] = yield* Effect.all([collect(child.stdout), collect(child.stderr)], { + concurrency: "unbounded", + }); + const code = yield* child.exitCode; + return { + code: Number(code), + stdout, + stderr: stderr.toString("utf8"), + } satisfies ProcessResult; + }), + ).pipe(Effect.mapError(() => failed(`Could not run ${command}. Is it installed and on PATH?`))); +}); + +const nulSeparated = (bytes: Uint8Array) => + Buffer.from(bytes) + .toString("utf8") + .split("\0") + .filter((entry) => entry.length > 0); + +const git = (cwd: string, args: ReadonlyArray) => runProcess("git", args, { cwd }); + +/** The commit checked out at `cwd`, "" before the first commit, or null outside git. */ +export const gitHead = Effect.fn("WorkFiles.gitHead")(function* (cwd: string) { + const inside = yield* git(cwd, ["rev-parse", "--is-inside-work-tree"]); + if (inside.code !== 0) return null; + const head = yield* git(cwd, ["rev-parse", "--verify", "-q", "HEAD"]); + return head.code === 0 ? Buffer.from(head.stdout).toString("utf8").trim() : ""; +}); + +/** Paths under `cwd`, relative to it, that differ from HEAD: modified, staged, deleted, or untracked and not ignored. */ +const gitChangedPaths = Effect.fn("WorkFiles.gitChangedPaths")(function* (cwd: string) { + const [worktree, staged] = yield* Effect.all([ + git(cwd, ["ls-files", "-m", "-d", "-o", "--exclude-standard", "-z"]), + git(cwd, ["diff", "--cached", "--name-only", "--relative", "--no-renames", "-z"]), + ]); + if (worktree.code !== 0 || staged.code !== 0) { + return yield* failed("Could not read git status."); + } + return new Set([...nulSeparated(worktree.stdout), ...nulSeparated(staged.stdout)]); +}); + +const gitTrackedPaths = Effect.fn("WorkFiles.gitTrackedPaths")(function* (cwd: string) { + const tracked = yield* git(cwd, ["ls-files", "-z"]); + if (tracked.code !== 0) return yield* failed("Could not list tracked files."); + return new Set(nulSeparated(tracked.stdout)); +}); + +/** Every file under `root` outside skipped directories, stopping once past the count limit. */ +const walk = Effect.fn("WorkFiles.walk")(function* (root: string) { + const found: string[] = []; + const pending = [""]; + while (pending.length > 0 && found.length <= WORK_FILES_MAX_COUNT) { + const directory = pending.pop()!; + const entries = yield* fileSystemCall("read the working directory", () => + NodeFSP.readdir(NodePath.join(root, directory), { withFileTypes: true }), + ); + for (const entry of entries) { + const relative = directory === "" ? entry.name : `${directory}/${entry.name}`; + if (entry.isDirectory()) { + if (!SKIPPED_DIRECTORIES.has(entry.name)) pending.push(relative); + } else if (entry.isFile()) { + found.push(relative); + } + } + } + return found; +}); + +/** The files a thread's work consists of at `root`, checked against the limits. */ +export const selectWorkFiles = Effect.fn("WorkFiles.select")(function* (root: string) { + const head = yield* gitHead(root); + const candidates = head === null ? yield* walk(root) : [...(yield* gitChangedPaths(root))]; + const files: Array<{ path: string; size: number }> = []; + const deletions: string[] = []; + const leftBehind: string[] = []; + const inodes = new Map(); + let totalBytes = 0; + for (const path of candidates.toSorted()) { + const stat = yield* lstatOrNull(NodePath.join(root, path)); + if (stat === null) { + if (head !== null) deletions.push(path); + continue; + } + // Symlinks and submodule directories are not work files. + if (!stat.isFile()) continue; + if (looksLikeSecret(path)) { + leftBehind.push(path); + continue; + } + if (stat.nlink > 1) { + const inode = `${stat.dev}:${stat.ino}`; + const other = inodes.get(inode); + if (other !== undefined) { + return yield* failed( + `${path} and ${other} are hard links to one file; tar cannot send both.`, + ); + } + inodes.set(inode, path); + } + files.push({ path, size: stat.size }); + totalBytes += stat.size; + } + const overCount = files.length > WORK_FILES_MAX_COUNT; + const refusal = + overCount || totalBytes > WORK_FILES_MAX_BYTES + ? `The work files are ${overCount && head === null ? `more than ${WORK_FILES_MAX_COUNT.toLocaleString("en-US")}` : files.length.toLocaleString("en-US")} files and ${formatMiB(totalBytes)}; the limit is ${WORK_FILES_MAX_COUNT.toLocaleString("en-US")} files and ${formatMiB(WORK_FILES_MAX_BYTES)}.` + : null; + return { + root, + head, + files, + deletions, + leftBehind, + totalBytes, + refusal, + } satisfies WorkFilesSelection; +}); + +/** bsdtar (macOS, Windows) writes macOS metadata unless told not to; GNU tar has no such flag. */ +const tarKind = (cwd: string) => + runProcess("tar", ["--version"], { cwd }).pipe( + Effect.map((result) => + Buffer.from(result.stdout).toString("utf8").includes("bsdtar") ? "bsd" : "gnu", + ), + ); + +/** + * A gzip tar of `files` under `root`, streamed from the system tar with no + * file written here. The stream fails when tar does. + */ +export const archiveStream = (root: string, files: ReadonlyArray) => + Stream.unwrap( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const kind = yield* tarKind(root); + const child = yield* spawner.spawn( + ChildProcess.make( + "tar", + [ + ...(kind === "bsd" ? ["--no-mac-metadata", "--no-xattrs"] : []), + "-czf", + "-", + "--null", + "-T", + "-", + ], + { + cwd: root, + env: { COPYFILE_DISABLE: "1" }, + extendEnv: true, + stdin: Stream.make(new TextEncoder().encode(files.map((file) => `${file}\0`).join(""))), + }, + ), + ); + const finished = child.exitCode.pipe( + Effect.flatMap((code) => + Number(code) === 0 + ? Effect.void + : Effect.fail(failed(`tar could not archive the work files (exit ${code}).`)), + ), + ); + return child.stdout.pipe(Stream.concat(Stream.fromEffect(finished).pipe(Stream.drain))); + }), + ).pipe( + Stream.mapError((error) => + error._tag === "WorkFilesError" ? error : failed("tar could not archive the work files."), + ), + ); + +const invalid = (message: string) => new WorkFilesError({ reason: "invalid_archive", message }); + +/** A relative path that stays inside the directory it is joined to, on any platform. */ +export const isSafeRelativePath = (path: string) => + path.length > 0 && + !path.startsWith("/") && + !/^[A-Za-z]:/.test(path) && + !path.includes("\\") && + !path.includes("\0") && + path.split("/").every((segment) => segment !== ".."); + +/** + * The regular files an archive holds, refusing absolute paths, `..`, and any + * entry that is not a file or directory, such as a symlink or hard link. + */ +export const listArchive = Effect.fn("WorkFiles.listArchive")(function* ( + archivePath: string, + cwd: string, +) { + const [names, verbose] = yield* Effect.all([ + runProcess("tar", ["-tzf", archivePath], { cwd }), + runProcess("tar", ["-tvzf", archivePath], { cwd }), + ]); + if (names.code !== 0 || verbose.code !== 0) { + return yield* invalid("The archive could not be read."); + } + const lines = (bytes: Uint8Array) => + Buffer.from(bytes) + .toString("utf8") + .split("\n") + .filter((line) => line.length > 0); + for (const line of lines(verbose.stdout)) { + // Each entry's listing starts with its type; a name with a newline lands here too and is refused. + if (line[0] !== "-" && line[0] !== "d") { + return yield* invalid( + "The archive holds a link or special file; only regular files are accepted.", + ); + } + } + const files: string[] = []; + for (const raw of lines(names.stdout)) { + const name = raw.startsWith("./") ? raw.slice(2) : raw; + const path = name.endsWith("/") ? name.slice(0, -1) : name; + if (path === "" || path === ".") continue; + if (!isSafeRelativePath(path)) { + return yield* invalid(`The archive holds an unsafe path: "${raw}".`); + } + if (!name.endsWith("/")) files.push(path); + } + if (files.length > WORK_FILES_MAX_COUNT) { + return yield* invalid(`The archive holds more than ${WORK_FILES_MAX_COUNT} files.`); + } + return files; +}); + +/** Checks the extracted tree is only directories and single-link files, exactly those listed. */ +const verifyStaging = Effect.fn("WorkFiles.verifyStaging")(function* ( + staging: string, + expected: ReadonlySet, +) { + const pending = [""]; + let seen = 0; + while (pending.length > 0) { + const directory = pending.pop()!; + const entries = yield* fileSystemCall("read the extracted files", () => + NodeFSP.readdir(NodePath.join(staging, directory), { withFileTypes: true }), + ); + for (const entry of entries) { + const relative = directory === "" ? entry.name : `${directory}/${entry.name}`; + if (entry.isDirectory()) { + pending.push(relative); + continue; + } + const stat = yield* lstatOrNull(NodePath.join(staging, relative)); + if (stat === null || !stat.isFile() || stat.nlink > 1 || !expected.has(relative)) { + return yield* invalid(`The archive extracted an unexpected entry: ${relative}.`); + } + seen += 1; + } + } + if (seen !== expected.size) + return yield* invalid("The archive did not extract every listed file."); +}); + +/** Why writing `path` under `root` could change something it must not, or null when it is safe. */ +const targetConflict = Effect.fn("WorkFiles.targetConflict")(function* ( + root: string, + path: string, + local: { readonly changed: ReadonlySet; readonly tracked: ReadonlySet } | null, + incoming: string | null, +) { + const segments = path.split("/"); + for (let index = 1; index < segments.length; index++) { + const parent = yield* lstatOrNull(NodePath.join(root, ...segments.slice(0, index))); + if (parent === null) return null; + if (!parent.isDirectory()) return "a parent folder is a link or a file there"; + } + const stat = yield* lstatOrNull(NodePath.join(root, ...segments)); + if (stat === null) return null; + if (!stat.isFile()) return "it is a link or a folder there"; + // An identical file is no change, so sending the same work again is a no-op. + if (incoming !== null) { + const [here, there] = yield* Effect.all([ + fileSystemCall("read a file there", () => NodeFSP.readFile(NodePath.join(root, ...segments))), + fileSystemCall("read an extracted file", () => NodeFSP.readFile(incoming)), + ]); + if (here.equals(there)) return null; + } + if (local === null) { + // Outside git nothing records local changes, so only an identical file may be replaced. + return incoming === null ? null : "it already exists there with other content"; + } + if (local.changed.has(path)) return "it has local changes there"; + if (!local.tracked.has(path)) return "it is an untracked file there"; + return null; +}); + +export interface ApplyWorkFilesInput { + readonly archivePath: string; + readonly stagingDir: string; + readonly root: string; + /** The source's HEAD; null when the source is not a git checkout. */ + readonly head: string | null; + readonly deletions: ReadonlyArray; +} + +/** + * Applies a received archive to `root`: checks it, extracts it to + * `stagingDir`, refuses on a HEAD mismatch or any path with local changes, + * then copies the files in and applies the deletions. The caller owns + * removing `archivePath` and `stagingDir`. + */ +export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: ApplyWorkFilesInput) { + const files = yield* listArchive(input.archivePath, input.root); + for (const path of input.deletions) { + if (!isSafeRelativePath(path)) { + return yield* invalid(`A deletion names an unsafe path: "${path}".`); + } + } + const head = yield* gitHead(input.root); + if (input.head !== null) { + if (head === null) { + return yield* new WorkFilesError({ + reason: "head_mismatch", + message: + "The files come from a git checkout, but the checkout there is not a git repository.", + }); + } + if (head !== input.head) { + return yield* new WorkFilesError({ + reason: "head_mismatch", + message: `The checkout there is at ${head || "no commit"}, but the files apply to ${input.head || "no commit"}. Check out the same commit there first.`, + }); + } + } + yield* fileSystemCall("create the staging folder", () => + NodeFSP.mkdir(input.stagingDir, { recursive: true }), + ); + const extracted = yield* runProcess("tar", ["-xzf", input.archivePath, "-C", input.stagingDir], { + cwd: input.stagingDir, + }); + if (extracted.code !== 0) return yield* invalid("The archive could not be extracted."); + yield* verifyStaging(input.stagingDir, new Set(files)); + const local = + head === null + ? null + : { + changed: yield* gitChangedPaths(input.root), + tracked: yield* gitTrackedPaths(input.root), + }; + const conflicts: string[] = []; + for (const path of files) { + const reason = yield* targetConflict( + input.root, + path, + local, + NodePath.join(input.stagingDir, ...path.split("/")), + ); + if (reason !== null) conflicts.push(`${path} (${reason})`); + } + for (const path of input.deletions) { + const reason = yield* targetConflict(input.root, path, local, null); + if (reason !== null) conflicts.push(`${path} (${reason})`); + } + if (conflicts.length > 0) { + return yield* new WorkFilesError({ + reason: "conflict", + message: `Nothing was changed there, because these paths would overwrite local work: ${conflicts.slice(0, 20).join(", ")}${conflicts.length > 20 ? `, and ${conflicts.length - 20} more` : ""}.`, + }); + } + for (const path of files) { + const destination = NodePath.join(input.root, ...path.split("/")); + yield* fileSystemCall(`write ${path}`, async () => { + await NodeFSP.mkdir(NodePath.dirname(destination), { recursive: true }); + await NodeFSP.copyFile(NodePath.join(input.stagingDir, ...path.split("/")), destination); + }); + } + let deleted = 0; + for (const path of input.deletions) { + const destination = NodePath.join(input.root, ...path.split("/")); + if ((yield* lstatOrNull(destination)) === null) continue; + yield* fileSystemCall(`delete ${path}`, () => NodeFSP.rm(destination)); + deleted += 1; + } + return { files: files.length, deletions: deleted }; +}); diff --git a/apps/server/src/peer/WorkFilesTransfer.test.ts b/apps/server/src/peer/WorkFilesTransfer.test.ts new file mode 100644 index 0000000000000..9f6f862495185 --- /dev/null +++ b/apps/server/src/peer/WorkFilesTransfer.test.ts @@ -0,0 +1,238 @@ +// @effect-diagnostics nodeBuiltinImport:off - Fixtures drive git directly on real folders. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { NodeHttpServer } from "@effect/platform-node"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + type AuthMcpClientAccess, + ProjectId, + WorkFilesReceiveInput, + WorkFilesReceiveResult, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpBody from "effect/http/HttpBody"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../config.ts"; +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; +import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts"; +import * as WorkFilesTransfer from "./WorkFilesTransfer.ts"; + +// The laptop sends a thread's files to the box over a real link: the box's +// real /mcp issues the upload and its real route applies it to a checkout. + +const laptop = descriptorOf("environment-laptop", "Laptop"); +const box = descriptorOf("environment-box", "Box"); +const boxProject = ProjectId.make("project:box"); + +const tempDir = Effect.acquireRelease( + Effect.sync(() => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-work-files-e2e-"))), + (dir) => Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), +); + +const git = (cwd: string, ...args: string[]) => + NodeChildProcess.execFileSync("git", args, { + cwd, + encoding: "utf8", + env: { + ...process.env, + GIT_AUTHOR_NAME: "t", + GIT_AUTHOR_EMAIL: "t@example.com", + GIT_COMMITTER_NAME: "t", + GIT_COMMITTER_EMAIL: "t@example.com", + GIT_CONFIG_GLOBAL: "/dev/null", + }, + }).trim(); + +const write = (root: string, path: string, content: string) => { + NodeFS.mkdirSync(NodePath.dirname(NodePath.join(root, path)), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(root, path), content); +}; + +/** The same commit checked out on both machines. */ +const checkouts = Effect.gen(function* () { + const source = yield* tempDir; + const target = yield* tempDir; + git(source, "init", "-q", "-b", "main"); + write(source, "app.ts", "v1"); + write(source, "old.ts", "old"); + git(source, "add", "-A"); + git(source, "commit", "-q", "-m", "initial"); + // A clone, not a copy: git may still be writing objects after the commit. + git(target, "clone", "-q", source, "."); + return { source, target }; +}); + +/** One environment's WorkFilesTransfer, with its own state directory and signing key. */ +const layerTransfer = (stateRoot: string, workspaceRoot: string) => + WorkFilesTransfer.layer.pipe( + Layer.provide( + Layer.mock(ProjectService.ProjectService)({ + getById: (id) => + Effect.succeed( + id === boxProject + ? Option.some({ id, workspaceRoot, deletedAt: null } as never) + : Option.none(), + ), + }), + ), + Layer.provideMerge(ServerSecretStore.layer), + Layer.provideMerge(ServerConfig.layerTest(stateRoot, { prefix: "t3-work-files-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + +/** The box: /mcp with the receive tool, and the upload route, sharing one transfer service. */ +const serveBox = (target: string) => + Effect.gen(function* () { + const stateRoot = yield* tempDir; + const transfer = yield* layerTransfer(stateRoot, target).pipe( + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), + Layer.provide(FetchHttpClient.layer), + Layer.build, + ); + const shared = Layer.succeedContext(transfer); + const peer = yield* servePeer( + box, + McpHttpServer.layerWorkFilesToolkit.pipe( + Layer.provide(shared), + Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})), + ), + WorkFilesTransfer.layerReceiveRoute.pipe(Layer.provide(shared)), + ); + const config = Context.get(transfer, ServerConfig.ServerConfig); + return { peer, receiveDir: NodePath.join(config.stateDir, "work-files") }; + }); + +/** The laptop, linked to the box with `access`, sending from `source`. */ +const laptopSending = ( + peer: Effect.Success>["peer"], + source: string, + access: AuthMcpClientAccess, +) => + Effect.gen(function* () { + const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build); + const stateRoot = yield* tempDir; + const here = yield* layerTransfer(stateRoot, source).pipe( + Layer.provide(Layer.succeedContext(linking)), + Layer.provide(FetchHttpClient.layer), + Layer.build, + ); + yield* linkTo(Context.get(linking, PeerLinks.PeerLinks), peer, access); + const peers = Context.get(linking, PeerMcpClient.PeerMcpClient); + const transfer = Context.get(here, WorkFilesTransfer.WorkFilesTransfer); + return transfer.send({ + cwd: source, + environmentId: box.environmentId, + projectId: boxProject, + receive: (request) => + peers.call({ + environmentId: box.environmentId, + tool: "t3_work_files_receive", + arguments: encodeReceiveInput(request) as Record, + limits: { runtimeMode: "full-access", interactionMode: "default" }, + success: WorkFilesReceiveResult, + }), + }); + }); + +const encodeReceiveInput = Schema.encodeSync(WorkFilesReceiveInput); + +const leftovers = (dir: string) => (NodeFS.existsSync(dir) ? NodeFS.readdirSync(dir) : []); + +it.live("sends a checkout's work to the same commit on the box, leaving no archive", () => + Effect.gen(function* () { + const { source, target } = yield* checkouts; + const { peer, receiveDir } = yield* serveBox(target); + write(source, "app.ts", "v2"); + write(source, "src/new.ts", "new"); + write(source, ".env", "SECRET=1"); + NodeFS.rmSync(NodePath.join(source, "old.ts")); + + const send = yield* laptopSending(peer, source, "auto"); + expect(yield* send).toEqual({ files: 2, deletions: 1 }); + expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v2"); + expect(NodeFS.readFileSync(NodePath.join(target, "src/new.ts"), "utf8")).toBe("new"); + expect(NodeFS.existsSync(NodePath.join(target, "old.ts"))).toBe(false); + // The secret stayed here. + expect(NodeFS.existsSync(NodePath.join(target, ".env"))).toBe(false); + expect(leftovers(receiveDir)).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), +); + +it.live("a refusal there changes nothing and still removes the archive and staging", () => + Effect.gen(function* () { + const { source, target } = yield* checkouts; + const { peer, receiveDir } = yield* serveBox(target); + write(source, "app.ts", "from laptop"); + write(target, "app.ts", "edited on the box"); + + const send = yield* laptopSending(peer, source, "auto"); + const refused = yield* send.pipe(Effect.flip); + expect(refused.message).toContain("app.ts (it has local changes there)"); + expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("edited on the box"); + expect(leftovers(receiveDir)).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), +); + +it.live("refuses before sending anything when the box is on another commit", () => + Effect.gen(function* () { + const { source, target } = yield* checkouts; + const { peer, receiveDir } = yield* serveBox(target); + write(target, "extra.ts", "x"); + git(target, "add", "extra.ts"); + git(target, "commit", "-q", "-m", "ahead"); + write(source, "app.ts", "v2"); + + const send = yield* laptopSending(peer, source, "auto"); + const refused = yield* send.pipe(Effect.flip); + expect(refused.message).toContain(git(source, "rev-parse", "HEAD")); + expect(refused.message).toContain(git(target, "rev-parse", "HEAD")); + expect(leftovers(receiveDir)).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), +); + +it.live("a read-only link cannot send files", () => + Effect.gen(function* () { + const { source, target } = yield* checkouts; + const { peer } = yield* serveBox(target); + write(source, "app.ts", "v2"); + + const send = yield* laptopSending(peer, source, "read-only"); + const refused = yield* send.pipe(Effect.flip); + expect(refused.code).toBe("capability_denied"); + expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v1"); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), +); + +it.live("the upload route takes nothing without a link session and its own token", () => + Effect.gen(function* () { + const { target } = yield* checkouts; + const { peer } = yield* serveBox(target); + const client = yield* HttpClient.HttpClient; + const anonymous = yield* client.execute( + HttpClientRequest.post( + `${peer.url}${WorkFilesTransfer.WORK_FILES_RECEIVE_ROUTE_PREFIX}/forged.token`, + ).pipe(HttpClientRequest.setBody(HttpBody.text("x"))), + ); + expect(anonymous.status).toBe(401); + }).pipe( + Effect.scoped, + Effect.provide(Layer.merge(NodeHttpServer.layerTest, FetchHttpClient.layer)), + ), +); diff --git a/apps/server/src/peer/WorkFilesTransfer.ts b/apps/server/src/peer/WorkFilesTransfer.ts new file mode 100644 index 0000000000000..fe409cf4eb35c --- /dev/null +++ b/apps/server/src/peer/WorkFilesTransfer.ts @@ -0,0 +1,389 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the received archive is written and removed with plain filesystem calls. +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; + +import { + type EnvironmentId, + OrchestratorMcpFailure, + type ProjectId, + WorkFilesApplied, + type WorkFilesReceiveInput, + type WorkFilesReceiveResult, + type WorkFilesSummary, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as HttpBody from "effect/http/HttpBody"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as HttpRouter from "effect/http/HttpRouter"; +import * as HttpServerRequest from "effect/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as PayloadSigner from "../auth/PayloadSigner.ts"; +import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts"; +import * as ServerConfig from "../config.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import { + applyWorkFiles, + archiveStream, + gitHead, + selectWorkFiles, + WORK_FILES_MAX_ARCHIVE_BYTES, + WorkFilesError, + type WorkFilesSelection, +} from "./WorkFiles.ts"; + +export const WORK_FILES_RECEIVE_ROUTE_PREFIX = "/api/work-files/receive"; +const RECEIVE_TICKET_TTL_MS = 5 * 60_000; + +const ReceiveClaims = Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("work-files-receive"), + receiveId: Schema.String, + expiresAt: Schema.Number, +}); +const receiveClaimsJson = Schema.fromJsonString(ReceiveClaims); +const decodeReceiveClaims = Schema.decodeUnknownOption(receiveClaimsJson); +const encodeReceiveClaims = Schema.encodeSync(receiveClaimsJson); +const isWorkFilesError = Schema.is(WorkFilesError); +const appliedJson = Schema.fromJsonString(WorkFilesApplied); +const decodeApplied = Schema.decodeUnknownOption(appliedJson); +const encodeApplied = Schema.encodeSync(appliedJson); + +function claimsOf(payload: string) { + try { + return Option.getOrNull(decodeReceiveClaims(base64UrlDecodeUtf8(payload))); + } catch { + return null; + } +} + +interface PendingReceive { + readonly root: string; + readonly head: string | null; + readonly deletions: ReadonlyArray; + /** The link session that asked; only it may upload. */ + readonly sessionId: string; + readonly expiresAt: number; +} + +export interface ReceiveResponse { + readonly status: number; + readonly body: string; +} + +export const summaryOf = (selection: WorkFilesSelection): WorkFilesSummary => ({ + directory: selection.root, + fileCount: selection.files.length, + totalBytes: selection.totalBytes, + deletionCount: selection.deletions.length, + leftBehindCount: selection.leftBehind.length, + refusal: selection.refusal, +}); + +const transferFailure = (message: string) => + new OrchestratorMcpFailure({ code: "orchestration_error", message }); + +/** + * Carries a thread's working files to a project's checkout in a linked + * environment. The source streams a gzip tar over the link to a one-time + * upload the target issued; the target checks and applies it, and neither + * side keeps the archive. + */ +export class WorkFilesTransfer extends Context.Service< + WorkFilesTransfer, + { + /** The files `cwd` would carry, with any limit it breaks. */ + readonly select: (cwd: string) => Effect.Effect; + /** + * Sends the work files at `cwd` to `projectId` in `environmentId`. `receive` + * asks that environment for the upload, through the caller's own route there. + * A selection with nothing to carry sends nothing. + */ + readonly send: (input: { + readonly cwd: string; + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; + readonly receive: ( + request: WorkFilesReceiveInput, + ) => Effect.Effect; + }) => Effect.Effect; + /** Here as the target: a one-time upload into `projectId`'s checkout for link session `sessionId`. */ + readonly issueReceive: (input: { + readonly request: WorkFilesReceiveInput; + readonly sessionId: string; + }) => Effect.Effect; + /** Here as the target: checks and applies an upload `issueReceive` allowed. */ + readonly receive: (input: { + readonly token: string; + readonly sessionId: string; + readonly body: Stream.Stream; + }) => Effect.Effect; + } +>()("t3/peer/WorkFilesTransfer") {} + +/** Streams `body` into `path`; false when it passes `maxBytes`, without reading the rest. */ +const writeCapped = (body: Stream.Stream, path: string, maxBytes: number) => + Effect.acquireUseRelease( + Effect.sync(() => NodeFS.createWriteStream(path, { flags: "wx" })), + (file) => + Effect.gen(function* () { + let received = 0; + let over = false; + yield* body.pipe( + Stream.takeWhile((chunk) => { + received += chunk.byteLength; + over = received > maxBytes; + return !over; + }), + Stream.runForEach((chunk) => + Effect.callback((resume) => { + file.write(chunk, (error) => { + resume(error ? Effect.fail(error) : Effect.void); + }); + }), + ), + ); + return !over; + }), + (file) => + Effect.callback((resume) => { + file.end(() => resume(Effect.void)); + }), + ); + +const make = Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const projects = yield* ProjectService.ProjectService; + const links = yield* PeerLinks.PeerLinks; + const httpClient = yield* HttpClient.HttpClient; + const random = yield* SecureRandom.SecureRandom; + const signer = yield* PayloadSigner.make("work-files-receive-signing-key"); + const processes = yield* Effect.context(); + const pending = new Map(); + const receiveDir = NodePath.join(config.stateDir, "work-files"); + + const select: WorkFilesTransfer["Service"]["select"] = (cwd) => + selectWorkFiles(cwd).pipe(Effect.provideContext(processes)); + + const send: WorkFilesTransfer["Service"]["send"] = Effect.fn("WorkFilesTransfer.send")( + function* (input) { + const selection = yield* select(input.cwd).pipe( + Effect.mapError((error) => transferFailure(error.message)), + ); + if (selection.refusal !== null) return yield* transferFailure(selection.refusal); + if (selection.files.length === 0 && selection.deletions.length === 0) { + return { files: 0, deletions: 0 }; + } + const ticket = yield* input.receive({ + projectId: input.projectId, + head: selection.head, + deletions: selection.deletions, + }); + const resolved = yield* links + .resolve(input.environmentId) + .pipe(Effect.mapError((error) => transferFailure(error.message))); + const body = archiveStream( + selection.root, + selection.files.map((file) => file.path), + ).pipe(Stream.provideContext(processes)); + const response = yield* httpClient + .execute( + HttpClientRequest.post(`${resolved.url}${ticket.relativeUrl}`).pipe( + HttpClientRequest.setHeaders({ authorization: `Bearer ${resolved.token}` }), + HttpClientRequest.setBody(HttpBody.stream(body, "application/gzip")), + ), + ) + .pipe( + Effect.mapError(() => + transferFailure( + "The work files could not be sent; the linked environment stopped answering.", + ), + ), + ); + const text = yield* response.text.pipe(Effect.orElseSucceed(() => "")); + if (response.status !== 200) { + return yield* transferFailure( + text.length > 0 + ? `The linked environment refused the work files: ${text}` + : `The linked environment refused the work files (HTTP ${response.status}).`, + ); + } + return yield* Effect.fromOption(decodeApplied(text)).pipe( + Effect.mapError(() => + transferFailure("The linked environment answered in an unexpected shape."), + ), + ); + }, + ); + + const issueReceive: WorkFilesTransfer["Service"]["issueReceive"] = Effect.fn( + "WorkFilesTransfer.issueReceive", + )(function* ({ request, sessionId }) { + const project = yield* projects.getById(request.projectId).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + if (project === undefined || project.deletedAt !== null) { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: `Project ${request.projectId} was not found here.`, + }); + } + const root = project.workspaceRoot; + // Refused before any bytes move; applying checks again. + if (request.head !== null) { + const head = yield* gitHead(root).pipe( + Effect.provideContext(processes), + Effect.mapError((error) => transferFailure(error.message)), + ); + if (head !== request.head) { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + head === null + ? "The files come from a git checkout, but the project's checkout here is not a git repository." + : `The checkout here is at ${head || "no commit"}, but the files apply to ${request.head || "no commit"}. Check out the same commit here first.`, + }); + } + } + const now = yield* Clock.currentTimeMillis; + for (const [id, entry] of pending) if (entry.expiresAt <= now) pending.delete(id); + const receiveId = (yield* random.uuidV4()).replaceAll("-", ""); + const expiresAt = now + RECEIVE_TICKET_TTL_MS; + pending.set(receiveId, { + root, + head: request.head, + deletions: request.deletions, + sessionId, + expiresAt, + }); + const payload = base64UrlEncode( + encodeReceiveClaims({ version: 1, kind: "work-files-receive", receiveId, expiresAt }), + ); + const signature = yield* signer + .sign(payload) + .pipe(Effect.mapError(() => transferFailure("Could not sign the upload."))); + return { relativeUrl: `${WORK_FILES_RECEIVE_ROUTE_PREFIX}/${payload}.${signature}`, expiresAt }; + }); + + /** The pending upload a token names, taken so it is used once. */ + const takeTicket = Effect.fn("WorkFilesTransfer.takeTicket")(function* ( + token: string, + sessionId: string, + ) { + const [payload, signature, extra] = token.split("."); + if (!payload || !signature || extra !== undefined) return undefined; + const verified = yield* signer + .verify(payload, signature) + .pipe(Effect.orElseSucceed(() => false)); + if (!verified) return undefined; + const claims = claimsOf(payload); + if (claims === null) return undefined; + const entry = pending.get(claims.receiveId); + if (entry === undefined || entry.sessionId !== sessionId) return undefined; + pending.delete(claims.receiveId); + if (Math.min(entry.expiresAt, claims.expiresAt) <= (yield* Clock.currentTimeMillis)) { + return undefined; + } + return { receiveId: claims.receiveId, entry }; + }); + + const receive: WorkFilesTransfer["Service"]["receive"] = Effect.fn("WorkFilesTransfer.receive")( + function* ({ token, sessionId, body }) { + const ticket = yield* takeTicket(token, sessionId); + if (ticket === undefined) + return { status: 404, body: "This upload is unknown, used, or expired." }; + const archivePath = NodePath.join(receiveDir, `${ticket.receiveId}.tgz`); + const stagingDir = NodePath.join(receiveDir, ticket.receiveId); + const cleanup = Effect.promise(() => + Promise.all([ + NodeFSP.rm(archivePath, { force: true }), + NodeFSP.rm(stagingDir, { recursive: true, force: true }), + ]).catch(() => undefined), + ); + return yield* Effect.gen(function* () { + yield* Effect.promise(() => NodeFSP.mkdir(receiveDir, { recursive: true })); + const stored = yield* writeCapped(body, archivePath, WORK_FILES_MAX_ARCHIVE_BYTES); + if (!stored) { + return { + status: 413, + body: `The archive is over the ${WORK_FILES_MAX_ARCHIVE_BYTES} byte limit.`, + }; + } + const applied = yield* applyWorkFiles({ + archivePath, + stagingDir, + root: ticket.entry.root, + head: ticket.entry.head, + deletions: ticket.entry.deletions, + }).pipe(Effect.provideContext(processes)); + return { status: 200, body: encodeApplied(applied) }; + }).pipe( + Effect.catch((error) => + Effect.succeed( + isWorkFilesError(error) + ? { status: error.reason === "failed" ? 500 : 409, body: error.message } + : { status: 500, body: "The work files could not be received." }, + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("work-files.receive-failed", { cause }).pipe( + Effect.as({ status: 500, body: "The work files could not be received." }), + ), + ), + Effect.ensuring(cleanup), + ); + }, + ); + + return WorkFilesTransfer.of({ select, send, issueReceive, receive }); +}); + +export const layer = Layer.effect(WorkFilesTransfer, make); + +/** + * `POST /api/work-files/receive/`: a linked environment's upload, + * authorized by its link session with operate access and the one-time token + * that session was issued. + */ +export const layerReceiveRoute = Layer.unwrap( + Effect.gen(function* () { + // Captured here: route handlers only see the server's request-level services. + const transfer = yield* WorkFilesTransfer; + const auth = yield* EnvironmentAuth.EnvironmentAuth; + return HttpRouter.add( + "POST", + `${WORK_FILES_RECEIVE_ROUTE_PREFIX}/*`, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const client = yield* auth.authenticateMcpClient(request).pipe(Effect.option); + if (Option.isNone(client)) return HttpServerResponse.text("Unauthorized", { status: 401 }); + if (!client.value.peerLink || client.value.access === "read-only") { + return HttpServerResponse.text("This link cannot change files here.", { status: 403 }); + } + const path = request.url.split("?", 1)[0] ?? ""; + const token = path.slice(`${WORK_FILES_RECEIVE_ROUTE_PREFIX}/`.length); + // Keep the request stream in the route scope until the response is sent. + const bodyPull = yield* Stream.toPull(request.stream); + const result = yield* transfer.receive({ + token, + sessionId: client.value.sessionId, + body: Stream.fromPull(Effect.succeed(bodyPull)), + }); + return HttpServerResponse.text(result.body, { status: result.status }); + }), + ); + }), +); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index dae95787afe82..203ef162cdbd3 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -85,6 +85,8 @@ import * as TerminalManager from "./terminal/Manager.ts"; import * as McpHttpServer from "./mcp/McpHttpServer.ts"; import * as PeerForwarding from "./peer/PeerForwarding.ts"; import * as RemoteDelegation from "./peer/RemoteDelegation.ts"; +import * as ContinueOnEnvironment from "./peer/ContinueOnEnvironment.ts"; +import * as WorkFilesTransfer from "./peer/WorkFilesTransfer.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PeerMcpClient from "./peer/PeerMcpClient.ts"; @@ -813,6 +815,7 @@ const layerMakeRoutes = Layer.mergeAll( ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, ServerHttp.layerAttachmentUploadRoute, + WorkFilesTransfer.layerReceiveRoute, GuestHttp.layer, DeviceHubProxy.layer, ServerBrowserStream.routeLayer, @@ -832,8 +835,12 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide( PullRequestReviewGuideService.layer.pipe(Layer.provide(PullRequestReviewGuides.layer)), ), + // Continue on another machine, from the thread menu. + Layer.provide(ContinueOnEnvironment.layer), // delegate_task to a linked environment, from /mcp and the follower above. Layer.provide(RemoteDelegation.layer.pipe(Layer.provide(ProjectionStoreV2.layer))), + // Work files sent to and received from linked environments. + Layer.provide(WorkFilesTransfer.layer), // Links agents ask for: shown in a thread from /mcp, answered over WebSocket. Layer.provide(PeerLinkRequests.layer), // Share the service so HTTP/WS clients single-flight reads and invalidate each other's cached patches. diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index c4470e0905c8a..e369221696df2 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -85,6 +85,7 @@ import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as RpcAuthorization from "./auth/RpcAuthorization.ts"; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; +import * as ContinueOnEnvironment from "./peer/ContinueOnEnvironment.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as PreviewManager from "./preview/Manager.ts"; @@ -828,6 +829,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(PairingGrantStore.PairingGrantStore)({}), Layer.mock(PeerLinks.PeerLinks)({}), Layer.mock(PeerLinkRequests.PeerLinkRequests)({}), + Layer.mock(ContinueOnEnvironment.ContinueOnEnvironment)({}), Layer.mock(PortScanner.PortDiscovery)({ trackAgent: () => () => undefined }), Layer.mock(PreviewManager.PreviewManager)({}), Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 66512ab6a22c0..eeef9105138b7 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -222,6 +222,7 @@ import * as ProjectService from "./project/ProjectService.ts"; import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; +import * as ContinueOnEnvironment from "./peer/ContinueOnEnvironment.ts"; import { mutateProjectWithClone } from "./project/ProjectMutation.ts"; import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts"; import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; @@ -1438,6 +1439,7 @@ export const layerWsRpc = ( const projectService = yield* ProjectService.ProjectService; const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion; + const continueOnEnvironment = yield* ContinueOnEnvironment.ContinueOnEnvironment; const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor; const threadSearch = yield* ThreadSearch.ThreadSearch; @@ -2648,6 +2650,10 @@ export const layerWsRpc = ( [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), + [WS_METHODS.threadsWorkFilesSummary]: (input) => + continueOnEnvironment.summarize(input.threadId), + [WS_METHODS.threadsContinueOnEnvironment]: (input) => + continueOnEnvironment.continueThread(input), [WS_METHODS.peerLinksAnswerRequest]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(peerLinkRequests.answer(input)), @@ -3521,6 +3527,7 @@ export const layer = Layer.unwrap( const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const peerLinks = yield* PeerLinks.PeerLinks; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; + const continueOnEnvironment = yield* ContinueOnEnvironment.ContinueOnEnvironment; const sql = yield* SqlClient.SqlClient; return HttpRouter.add( "GET", @@ -3610,6 +3617,9 @@ export const layer = Layer.unwrap( ), Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)), Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)), + Layer.provide( + Layer.succeed(ContinueOnEnvironment.ContinueOnEnvironment, continueOnEnvironment), + ), Layer.provide( SourceControlDiscovery.layer.pipe( Layer.provide( diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index fe21bd2e3a635..0cc7bda53a6f1 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -79,6 +79,7 @@ import { SquarePenIcon, TextSearchIcon, UserPlusIcon, + MonitorUpIcon, } from "lucide-react"; import { openThreadFind } from "./chat/threadFindStore"; import { dispatchPreviewAction } from "./preview/previewActionBus"; @@ -138,6 +139,7 @@ import { } from "../state/environments"; import { useAnyEnvironmentHiding, + useEnvironmentCanContinueElsewhere, useHiddenThreadKeys, useEnvironmentThreadRefs, useProjects, @@ -257,6 +259,7 @@ import { ProjectFilePicker } from "./files/ProjectFilePicker"; import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog"; import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; import { openGuestShareDialog } from "./chat/guestShareDialogState"; +import { openContinueOnMachineDialog } from "./chat/continueOnMachineDialogState"; import { openUseInAnotherApp } from "./mcp/UseInAnotherAppDialog"; import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog"; import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch"; @@ -493,6 +496,9 @@ function OpenCommandPaletteDialog(props: { const activeThreadServerConfig = useServerConfigs().get( activeThread?.environmentId ?? ("" as EnvironmentId), ); + const canContinueActiveThreadElsewhere = useEnvironmentCanContinueElsewhere( + activeThread?.environmentId ?? null, + ); const canShareActiveThreadWithGuest = useAtomValue( canShareWithGuestAtom(activeThread?.environmentId ?? ("" as EnvironmentId)), ); @@ -1484,6 +1490,20 @@ function OpenCommandPaletteDialog(props: { }); } + if (activeThread !== null && canContinueActiveThreadElsewhere) { + const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); + actionItems.push({ + kind: "action", + value: "action:continue-thread-elsewhere", + searchTerms: ["continue", "machine", "move", "transfer", "remote", "linked", "handoff"], + title: "Continue on another machine", + icon: , + run: async () => { + openContinueOnMachineDialog(threadRef); + }, + }); + } + if (activeThread !== null) { const thread = activeThread; actionItems.push({ diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a94b9e9497c6b..131cea25e47d9 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -140,6 +140,7 @@ import { usePrimaryEnvironmentId, } from "../state/environments"; import { + readEnvironmentCanContinueElsewhere, readThreadShell, useAllEnvironmentProjectSnapshotsReady, useDelegatedUnderParent, @@ -158,6 +159,7 @@ import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { canShareWithGuestAtom } from "./chat/guestShareAvailability"; import { openGuestShareDialog } from "./chat/guestShareDialogState"; +import { openContinueOnMachineDialog } from "./chat/continueOnMachineDialogState"; import { buildThreadRouteParams, resolveActiveThreadRouteRef, @@ -2670,6 +2672,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve canShareWithGuestAtom(threadRef.environmentId), ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), + canContinueElsewhere: readEnvironmentCanContinueElsewhere(threadRef.environmentId), supports: { settlement: configLoaded, autoSettleOptOut: supportsAutoSettleOptOut, @@ -2794,6 +2797,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve case "share-guest": openGuestShareDialog(threadRef); return; + case "continue-elsewhere": + openContinueOnMachineDialog(threadRef); + return; case "regenerate-title": { if (isRegeneratingTitle) return; const toast = titleRegenerationToast([ diff --git a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx new file mode 100644 index 0000000000000..b927354bf4bfa --- /dev/null +++ b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx @@ -0,0 +1,224 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { + PeerLinkSummary, + ScopedThreadRef, + WorkFilesMode, + WorkFilesSummary, +} from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { useState } from "react"; + +import { formatBytes } from "~/lib/formatBytes"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { readEnvironmentServerConfigLoaded } from "~/state/entities"; +import { peerLinkEnvironment } from "~/state/peerLinks"; +import { useEnvironmentQuery } from "~/state/query"; +import { useAtomCommand } from "~/state/use-atom-command"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { + AlertDialog, + AlertDialogClose, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogPopup, + AlertDialogTitle, +} from "../ui/alert-dialog"; +import { Button } from "../ui/button"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { continueOnMachineThreadAtom } from "./continueOnMachineDialogState"; + +export function ContinueOnMachineDialogHost() { + const threadRef = useAtomValue(continueOnMachineThreadAtom); + if (threadRef === null) return null; + return ( + appAtomRegistry.set(continueOnMachineThreadAtom, null)} + /> + ); +} + +type Stage = + | { readonly kind: "pick" } + | { readonly kind: "checking"; readonly link: PeerLinkSummary } + | { readonly kind: "ask"; readonly link: PeerLinkSummary; readonly summary: WorkFilesSummary } + | { readonly kind: "running"; readonly link: PeerLinkSummary; readonly mode: WorkFilesMode }; + +const failureMessage = (error: unknown) => + error instanceof Error ? error.message : "An unexpected error occurred."; + +/** What the files are, in one sentence, with what stays behind. */ +function workFilesDescription(summary: WorkFilesSummary): string { + const files = `${summary.fileCount.toLocaleString()} ${summary.fileCount === 1 ? "file" : "files"}`; + const deletions = + summary.deletionCount === 0 + ? "" + : ` and ${summary.deletionCount.toLocaleString()} ${summary.deletionCount === 1 ? "deletion" : "deletions"}`; + const secrets = + summary.leftBehindCount === 0 + ? "Files that look like secrets stay on this machine." + : `${summary.leftBehindCount.toLocaleString()} ${summary.leftBehindCount === 1 ? "file that looks" : "files that look"} like secrets ${summary.leftBehindCount === 1 ? "stays" : "stay"} on this machine.`; + return `${files}${deletions} (${formatBytes(summary.totalBytes)}) from ${summary.directory}. ${secrets}`; +} + +function ContinueOnMachineDialog({ + threadRef, + onClose, +}: { + readonly threadRef: ScopedThreadRef; + readonly onClose: () => void; +}) { + const navigate = useNavigate(); + const links = useEnvironmentQuery( + peerLinkEnvironment.list({ environmentId: threadRef.environmentId, input: {} }), + ); + const summarize = useAtomCommand(peerLinkEnvironment.workFilesSummary, { reportFailure: false }); + const continueThread = useAtomCommand(peerLinkEnvironment.continueThread, { + reportFailure: false, + }); + const [stage, setStage] = useState({ kind: "pick" }); + const reachable = (links.data?.links ?? []).filter((link) => link.status === "reachable"); + const busy = stage.kind === "checking" || stage.kind === "running"; + + const fail = (link: PeerLinkSummary, error: unknown) => + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Could not continue on ${link.label}`, + description: failureMessage(error), + }), + ); + + const run = async (link: PeerLinkSummary, mode: WorkFilesMode) => { + setStage({ kind: "running", link, mode }); + const result = await continueThread({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, environmentId: link.environmentId, workFiles: mode }, + }); + onClose(); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) fail(link, squashAtomCommandFailure(result)); + return; + } + const continued = result.value; + const target = scopeThreadRef(continued.environmentId, continued.threadId); + // This client can open it only while it is connected to that machine too. + const canOpen = readEnvironmentServerConfigLoaded(continued.environmentId); + toastManager.add( + stackedThreadToast({ + type: "success", + title: `Continued on ${continued.label}`, + description: + mode === "transfer" + ? `A new thread there picked up this one, with ${continued.transferredFiles.toLocaleString()} work files.` + : "A new thread there picked up this one.", + ...(canOpen + ? { + actionProps: { + children: "Open thread", + onClick: () => { + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target), + }); + }, + }, + } + : {}), + data: { hideCopyButton: true }, + }), + ); + }; + + const choose = async (link: PeerLinkSummary) => { + setStage({ kind: "checking", link }); + const result = await summarize({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }); + if (result._tag === "Failure") { + onClose(); + if (!isAtomCommandInterrupted(result)) fail(link, squashAtomCommandFailure(result)); + return; + } + const summary = result.value; + // Nothing to carry: there is no question to ask. + if (summary.fileCount === 0 && summary.deletionCount === 0) { + await run(link, "skip"); + return; + } + setStage({ kind: "ask", link, summary }); + }; + + if (stage.kind === "ask" || (stage.kind === "running" && stage.mode === "transfer")) { + const summary = stage.kind === "ask" ? stage.summary : null; + return ( + !open && !busy && onClose()}> + + + Transfer the current work files too? + + {summary === null + ? `Sending the work files to ${stage.link.label}…` + : (summary.refusal ?? workFilesDescription(summary))} + + + + }> + Cancel + + + + + + + ); + } + + return ( + !open && !busy && onClose()}> + + + Continue on another machine + + {busy + ? `Starting a thread on ${stage.link.label}…` + : links.isPending + ? "Checking your linked machines…" + : reachable.length === 0 + ? "None of this machine's linked machines answers now. Link one in Settings → Connections." + : "A new thread there starts from this conversation, in the same repository. This thread stays as it is."} + + + {!busy && reachable.length > 0 ? ( +

+ ) : null} + + }> + Cancel + + + + + ); +} diff --git a/apps/web/src/components/chat/continueOnMachineDialogState.ts b/apps/web/src/components/chat/continueOnMachineDialogState.ts new file mode 100644 index 0000000000000..529d63e9816e7 --- /dev/null +++ b/apps/web/src/components/chat/continueOnMachineDialogState.ts @@ -0,0 +1,17 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { appAtomRegistry } from "~/rpc/atomRegistry"; + +/** + * Which thread is moving to another machine. The thread menu and the command palette both + * close as their command runs, so the root renders the dialog once. + */ +export const continueOnMachineThreadAtom = Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel("continue-on-machine:dialog-thread"), +); + +export function openContinueOnMachineDialog(threadRef: ScopedThreadRef): void { + appAtomRegistry.set(continueOnMachineThreadAtom, threadRef); +} diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 1e3eddd0b9389..4fb1dd43e4bdc 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -6,6 +6,7 @@ export type ThreadActionMenuId = | "new-thread-on-branch" | "filter-by-project" | "turn-into-project" + | "continue-elsewhere" | "project-settings" | "pin" | "unpin" @@ -95,6 +96,8 @@ export interface ThreadActionMenuState { readonly canShareWithGuest?: boolean; /** A No project thread with its own folder, on a server that can promote it. */ readonly canTurnIntoProject?: boolean; + /** A server with linked machines, which can start this thread's work on one of them. */ + readonly canContinueElsewhere?: boolean; } /** Local navigation, read markers, and copying remain available to read-only clients. */ @@ -203,6 +206,15 @@ export function buildThreadActionMenuItems( }, ] : []), + ...(state.canContinueElsewhere + ? [ + { + id: "continue-elsewhere" as const, + label: "Continue on another machine", + icon: "monitor-up", + }, + ] + : []), ...(state.supports.autoSettleOptOut ? [ { diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 2649e09a50a01..7184ab4814ced 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -124,6 +124,13 @@ const ICON_PATHS: Record ({ scope === AuthOrchestrationOperateScope && state.granted.has(environmentId), })); vi.mock("../state/entities", () => ({ + readEnvironmentCanContinueElsewhere: () => false, readEnvironmentServerConfigLoaded: () => true, readEnvironmentSupportsAutoSettleOptOut: () => true, readThreadShell: () => ({ diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index bf22bd066b9a4..2d6c9934c1c5b 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -1,6 +1,7 @@ import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { requestCustomSnooze } from "../components/CustomSnoozeDialog"; import { openGuestShareDialog } from "../components/chat/guestShareDialogState"; +import { openContinueOnMachineDialog } from "../components/chat/continueOnMachineDialogState"; import { type AtomCommandResult, isAtomCommandInterrupted, @@ -29,6 +30,7 @@ import { threadEnvironment } from "../state/threads"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { readEnvironmentScope } from "../state/session"; import { + readEnvironmentCanContinueElsewhere, readEnvironmentServerConfigLoaded, readEnvironmentSupportsAutoSettleOptOut, readThreadShell, @@ -153,6 +155,7 @@ export function useThreadActionMenu(input: { snoozePresets, canShareWithGuest, canTurnIntoProject: canTurnThreadIntoProject(threadRef), + canContinueElsewhere: readEnvironmentCanContinueElsewhere(threadRef.environmentId), }); const clicked = await settlePromise(() => api.contextMenu.show(items, position)); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -268,6 +271,9 @@ export function useThreadActionMenu(input: { case "share-guest": openGuestShareDialog(threadRef); return; + case "continue-elsewhere": + openContinueOnMachineDialog(threadRef); + return; case "turn-into-project": { const result = await turnThreadIntoProject(threadRef); if (result._tag === "Success") { diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index a59604a63f426..3df1eca1338cf 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -18,6 +18,7 @@ import { AppSidebarLayout } from "../components/AppSidebarLayout"; import { CommandPalette } from "../components/CommandPalette"; import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog"; import { GuestShareDialogHost } from "../components/chat/GuestShareControls"; +import { ContinueOnMachineDialogHost } from "../components/chat/ContinueOnMachineDialog"; import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog"; import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog"; import { ConfirmDialogHost } from "../components/ConfirmDialogHost"; @@ -191,6 +192,7 @@ function RootRouteBranch() { + diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 51760393f92d9..941bd5eb6e7cc 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -30,6 +30,7 @@ import type { } from "@t3tools/contracts"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { Atom } from "effect/reactivity"; +import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentProjects } from "./projects"; import { environmentPresentations } from "./presentation"; @@ -360,6 +361,20 @@ export function readEnvironmentServerConfigLoaded(environmentId: EnvironmentId): return appAtomRegistry.get(environmentServerConfigsAtom).has(environmentId); } +const canContinueElsewhere = (config: Parameters[0]) => + offersLinkedEnvironments(config) && + config?.environment.capabilities.continueOnEnvironment === true; + +/** Whether the environment can continue a thread on one of its linked machines. */ +export function readEnvironmentCanContinueElsewhere(environmentId: EnvironmentId): boolean { + return canContinueElsewhere(appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)); +} + +export function useEnvironmentCanContinueElsewhere(environmentId: EnvironmentId | null): boolean { + const configs = useServerConfigs(); + return environmentId !== null && canContinueElsewhere(configs.get(environmentId)); +} + export function readEnvironmentSupportsAutoSettleOptOut(environmentId: EnvironmentId): boolean { return ( appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 910e5e90506d0..eb8d92ace8e63 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -363,6 +363,21 @@ ends, as for any delegated task. It keeps following the task across restarts. If the other machine revokes the link, or the link is removed here, the task fails with that reason. +To move a thread's work yourself, choose **Continue on another machine** in the +thread menu or the command palette and pick a linked machine. A new thread +starts there, in the project with the same repository, from this thread's +conversation, and this thread stays as it is. If the thread's folder has +uncommitted changes, you choose whether to transfer them too. An agent can ask +for the same with `workFiles: "transfer"` on `delegate_task`. + +- In a git checkout, the changed, staged, deleted and untracked (not ignored) + files go, and the other machine's checkout must be on the same commit. + Outside git, every file goes except `.git`, `node_modules` and build output. +- Files that look like secrets, such as `.env` files and private keys, stay on + this machine. +- Nothing is changed there if any of those files has its own local changes + there. The transfer is at most 100 MiB and 5,000 files. + ## Manage or revoke access On the host, **Settings → Sharing & access** lets authorized administrators create diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 9295bf1b40156..fcbba6f67f262 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -30,6 +30,20 @@ export function createPeerLinkEnvironmentAtoms( onSuccess: ({ environmentId }, registry) => Effect.sync(() => registry.refresh(list({ environmentId, input: {} }))), }), + /** What a thread's working directory would carry to another machine. */ + workFilesSummary: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:work-files-summary", + tag: WS_METHODS.threadsWorkFilesSummary, + }), + /** A new thread on a linked machine that picks up this one's work. One per thread at a time. */ + continueThread: createEnvironmentRpcCommand(runtime, { + label: "environment-data:peer-links:continue-thread", + tag: WS_METHODS.threadsContinueOnEnvironment, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId]), + }, + }), // An agent's link card. One answer per card at a time. answerRequest: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:answer-request", diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 8681c1ea8abeb..94ed2f78e8ca7 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -78,6 +78,9 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope, // A link lets every agent here reach the other environment: Settings' bar. [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope, + // Lists the thread's working files, which only continuing elsewhere needs. + [WS_METHODS.threadsWorkFilesSummary]: AuthOrchestrationOperateScope, + [WS_METHODS.threadsContinueOnEnvironment]: AuthOrchestrationOperateScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 0bbb463197747..8346608630b8d 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -172,6 +172,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ in them. Absent on servers from before linking, which clients must not offer linking for. */ peerLinks: Schema.optionalKey(Schema.Boolean), + /** Server continues a thread on a linked environment, with its work files + if asked. Older servers lack the RPC, so clients offer it only when set. */ + continueOnEnvironment: Schema.optionalKey(Schema.Boolean), /** Server's `/mcp` narrows an OAuth client's modes from `T3-Mode-Limit`, so a linked environment's calls keep its agent's limits. Another environment links to this one only when it is set. */ diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 8dd47df33a21f..661b056ee0324 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -44,6 +44,7 @@ export * from "./guestStream.ts"; export * from "./applicationEvent.ts"; export * from "./orchestratorMcp.ts"; export * from "./peerLink.ts"; +export * from "./workFiles.ts"; export * from "./threadMetadataMcp.ts"; export * from "./threadPullRequest.ts"; export * from "./threadSearch.ts"; diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 99081420d91cc..7af1e0dacdb36 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -33,6 +33,7 @@ import { ThreadPullRequestLinkSource, } from "./threadPullRequest.ts"; import { secretRequestPageUrl } from "./secretRequest.ts"; +import { WorkFilesMode } from "./workFiles.ts"; import { hasOnlyPairedSurrogates } from "./threadMetadataMcp.ts"; import { LastThreadTitleRegeneration, ThreadTitleRegeneration } from "./threadTitle.ts"; import { @@ -194,6 +195,12 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({ }), ), interactionMode: Schema.optional(OrchestratorMcpInteractionMode), + workFiles: Schema.optional( + WorkFilesMode.annotate({ + description: + "Remote target only. 'transfer': first copy your uncommitted files (not secrets) to that checkout, which must be on your commit.", + }), + ), }); export type OrchestratorMcpDelegateTaskInput = typeof OrchestratorMcpDelegateTaskInput.Type; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index adba6dbaca71b..b4df2e13aa5e2 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -26,6 +26,13 @@ import { PeerLinkRequestError, PeerLinkSummary, } from "./peerLink.ts"; +import { + ThreadContinueOnEnvironmentInput, + ThreadContinueOnEnvironmentResult, + ThreadWorkFilesSummaryInput, + WorkFilesSummary, + WorkFilesTransferError, +} from "./workFiles.ts"; import { ChatGptReconnectProfileInput, ChatGptReconnectProfile, @@ -523,6 +530,8 @@ export const WS_METHODS = { peerLinksLink: "peerLinks.link", peerLinksUnlink: "peerLinks.unlink", peerLinksAnswerRequest: "peerLinks.answerRequest", + threadsWorkFilesSummary: "threads.workFilesSummary", + threadsContinueOnEnvironment: "threads.continueOnEnvironment", serverUpdateSettings: "server.updateSettings", serverDiscoverSourceControl: "server.discoverSourceControl", serverCheckSecretSource: "server.checkSecretSource", @@ -864,6 +873,18 @@ const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest, error: Schema.Union([PeerLinkRequestError, EnvironmentAuthorizationError]), }); +const WsThreadsWorkFilesSummaryRpc = Rpc.make(WS_METHODS.threadsWorkFilesSummary, { + payload: ThreadWorkFilesSummaryInput, + success: WorkFilesSummary, + error: Schema.Union([WorkFilesTransferError, EnvironmentAuthorizationError]), +}); + +const WsThreadsContinueOnEnvironmentRpc = Rpc.make(WS_METHODS.threadsContinueOnEnvironment, { + payload: ThreadContinueOnEnvironmentInput, + success: ThreadContinueOnEnvironmentResult, + error: Schema.Union([WorkFilesTransferError, EnvironmentAuthorizationError]), +}); + const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, { payload: Schema.Struct({ patch: ServerSettingsPatch, @@ -2138,6 +2159,8 @@ export const WsRpcGroup = RpcGroup.make( WsPeerLinksLinkRpc, WsPeerLinksUnlinkRpc, WsPeerLinksAnswerRequestRpc, + WsThreadsWorkFilesSummaryRpc, + WsThreadsContinueOnEnvironmentRpc, WsServerDiscoverSourceControlRpc, WsServerCheckSecretSourceRpc, WsServerSearchAcpRegistryRpc, diff --git a/packages/contracts/src/workFiles.ts b/packages/contracts/src/workFiles.ts new file mode 100644 index 0000000000000..3e5bff281d764 --- /dev/null +++ b/packages/contracts/src/workFiles.ts @@ -0,0 +1,65 @@ +import * as Schema from "effect/Schema"; + +import { EnvironmentId, ProjectId, ThreadId } from "./baseSchemas.ts"; + +/** Whether work moving to another environment brings its working directory's files. */ +export const WorkFilesMode = Schema.Literals(["transfer", "skip"]); +export type WorkFilesMode = typeof WorkFilesMode.Type; + +/** What a thread's working directory would carry to another environment. */ +export const WorkFilesSummary = Schema.Struct({ + directory: Schema.String, + fileCount: Schema.Int, + totalBytes: Schema.Int, + deletionCount: Schema.Int, + /** Files that look like secrets, which stay on this machine. */ + leftBehindCount: Schema.Int, + /** Why the files cannot go, with the numbers; null when they can. */ + refusal: Schema.NullOr(Schema.String), +}); +export type WorkFilesSummary = typeof WorkFilesSummary.Type; + +export const ThreadWorkFilesSummaryInput = Schema.Struct({ threadId: ThreadId }); +export type ThreadWorkFilesSummaryInput = typeof ThreadWorkFilesSummaryInput.Type; + +export const ThreadContinueOnEnvironmentInput = Schema.Struct({ + threadId: ThreadId, + /** A linked environment this one reaches. */ + environmentId: EnvironmentId, + workFiles: WorkFilesMode, +}); +export type ThreadContinueOnEnvironmentInput = typeof ThreadContinueOnEnvironmentInput.Type; + +export const ThreadContinueOnEnvironmentResult = Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + projectId: ProjectId, + /** What this environment calls the other one. */ + label: Schema.String, + transferredFiles: Schema.Int, +}); +export type ThreadContinueOnEnvironmentResult = typeof ThreadContinueOnEnvironmentResult.Type; + +export class WorkFilesTransferError extends Schema.TaggedError()( + "WorkFilesTransferError", + { message: Schema.String }, +) {} + +/** Asks a linked environment for a one-time upload to its project's checkout. */ +export const WorkFilesReceiveInput = Schema.Struct({ + projectId: ProjectId, + /** The source checkout's HEAD; null outside git, "" before the first commit. */ + head: Schema.NullOr(Schema.String), + deletions: Schema.Array(Schema.String).check(Schema.isMaxLength(5_000)), +}); +export type WorkFilesReceiveInput = typeof WorkFilesReceiveInput.Type; + +export const WorkFilesReceiveResult = Schema.Struct({ + /** POST the gzip tar here, on the same origin, with the link's bearer token. */ + relativeUrl: Schema.String, + expiresAt: Schema.Number, +}); +export type WorkFilesReceiveResult = typeof WorkFilesReceiveResult.Type; + +export const WorkFilesApplied = Schema.Struct({ files: Schema.Int, deletions: Schema.Int }); +export type WorkFilesApplied = typeof WorkFilesApplied.Type; diff --git a/packages/shared/src/t3McpToolPresentation.test.ts b/packages/shared/src/t3McpToolPresentation.test.ts index 4d30e4972d605..5e583c51b5fde 100644 --- a/packages/shared/src/t3McpToolPresentation.test.ts +++ b/packages/shared/src/t3McpToolPresentation.test.ts @@ -53,6 +53,15 @@ describe("resolveT3McpToolDefinition", () => { "Used", ); }); + + it("labels a delegation that carries work files apart from one that does not", () => { + expect( + resolveT3McpToolDefinition("delegate_task", { workFiles: "transfer" })?.displayName, + ).toBe("Delegate a child task with work files"); + expect(resolveT3McpToolDefinition("delegate_task", { workFiles: "skip" })?.displayName).toBe( + "Delegate a child task", + ); + }); }); describe("resolveT3McpSummaryAction", () => { diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 7a6c2fab91187..b9a49cef8a2a8 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -450,6 +450,19 @@ const ACTION_TOOLS: Readonly string | undefin ], }; +const DELEGATE_WITH_WORK_FILES = tool( + ["Delegate", "Delegating", "Delegated", "a child task with work files"], + "delegate", +); + +/** Calls whose input changes what they do enough to need their own labels. */ +const INPUT_VARIANTS: Readonly< + Record T3McpToolDefinition | undefined> +> = { + delegate_task: ({ workFiles }) => + workFiles === "transfer" ? DELEGATE_WITH_WORK_FILES : undefined, +}; + /** Pass the call's input so an action tool resolves to the labels and summary of its action. */ export function resolveT3McpToolDefinition( toolName: string | null | undefined, @@ -457,7 +470,10 @@ export function resolveT3McpToolDefinition( ): T3McpToolDefinition | null { const name = toolName == null ? null : resolveT3McpToolName(toolName); if (name === null || !Object.hasOwn(T3_MCP_TOOLS, name)) return null; - const action = asSummaryInput(input)?.action; + const fields = asSummaryInput(input); + const variant = fields === undefined ? undefined : INPUT_VARIANTS[name]?.(fields); + if (variant !== undefined) return variant; + const action = fields?.action; const actionTool = typeof action === "string" ? ACTION_TOOLS[name]?.(action) : undefined; return actionTool !== undefined && Object.hasOwn(T3_MCP_TOOLS, actionTool) ? T3_MCP_TOOLS[actionTool]! From 40a7eaf7befbd49ec372c44f9d3b4ffb1204ce61 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:19:18 +0100 Subject: [PATCH 02/14] fix: a continued thread names the machine it came from --- apps/server/src/peer/ContinueOnEnvironment.test.ts | 4 +++- apps/server/src/peer/ContinueOnEnvironment.ts | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/server/src/peer/ContinueOnEnvironment.test.ts b/apps/server/src/peer/ContinueOnEnvironment.test.ts index a6d48157e0b21..efb78b4b338e5 100644 --- a/apps/server/src/peer/ContinueOnEnvironment.test.ts +++ b/apps/server/src/peer/ContinueOnEnvironment.test.ts @@ -121,7 +121,7 @@ const setup = ( Layer.provide( Layer.succeed(ServerEnvironment.ServerEnvironment, { getEnvironmentId: Effect.succeed(here), - getDescriptor: Effect.die("unused"), + getDescriptor: Effect.succeed({ environmentId: here, label: "laptop" } as never), }), ), Layer.provide(NodeCrypto.layer), @@ -162,6 +162,8 @@ it.effect("starts a thread there from this one's conversation, after its files l expect(launch.message).toContain("The login test fails on CI."); expect(launch.message).toContain("It races the session cookie; I patched auth.ts."); expect(launch.message).toContain("2 files written, 1 deleted"); + // It names this machine as people know it, not only by id. + expect(launch.message).toContain(`from laptop (environment ${here})`); }).pipe(Effect.provide(layer)); }); diff --git a/apps/server/src/peer/ContinueOnEnvironment.ts b/apps/server/src/peer/ContinueOnEnvironment.ts index a3aca1c88cf74..cc47e44d68ccc 100644 --- a/apps/server/src/peer/ContinueOnEnvironment.ts +++ b/apps/server/src/peer/ContinueOnEnvironment.ts @@ -108,7 +108,7 @@ const make = Effect.gen(function* () { if (link === undefined) return yield* refused("This environment is not linked to that one."); const { records, project, cwd } = yield* loadThread(input.threadId); const { thread } = records; - const hereId = yield* environment.getEnvironmentId; + const here = yield* environment.getDescriptor; // Calls there carry this thread's modes and name it, as its own agent's calls would. const call = >( tool: string, @@ -120,7 +120,7 @@ const make = Effect.gen(function* () { tool, arguments: args, limits: { runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode }, - sender: { environmentId: hereId, threadId: thread.id, title: thread.title }, + sender: { environmentId: here.environmentId, threadId: thread.id, title: thread.title }, success, }); const there = (error: OrchestratorMcpFailure) => refused(`${link.label}: ${error.message}`); @@ -186,7 +186,7 @@ const make = Effect.gen(function* () { return message === null ? [] : [message]; }), coverage: [ - `This thread continues thread "${thread.title}" (${thread.id}) from environment ${hereId}, moved here by the user.`, + `This thread continues thread "${thread.title}" (${thread.id}) from ${here.label} (environment ${here.environmentId}), moved here by the user.`, filesLine, ].join("\n"), budget: DEFAULT_HANDOFF_TOKEN_CAP, From b962ac8bf46976e39c907de30a42fb60128694fc Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:41:23 +0100 Subject: [PATCH 03/14] fix: work files stay out of .git, need edit access, and apply all or nothing Receiving checks names, types and expanded size from the tar headers in Node, holds a lock per checkout, keeps local deletions, hard links and secret deletions untouched, and restores every file when a write or delete fails. A write failure on the receive folder is a refusal instead of a crash, the walk counts only files it can send, and a delegate_task retry for a recorded task sends no files again. --- .../src/mcp/toolkits/workFiles/handlers.ts | 6 +- apps/server/src/peer/RemoteDelegation.test.ts | 6 + apps/server/src/peer/RemoteDelegation.ts | 27 +- apps/server/src/peer/WorkFiles.test.ts | 211 ++++++++- apps/server/src/peer/WorkFiles.ts | 431 +++++++++++++++--- .../server/src/peer/WorkFilesTransfer.test.ts | 59 ++- apps/server/src/peer/WorkFilesTransfer.ts | 39 +- docs/user/remote-access.md | 2 + 8 files changed, 677 insertions(+), 104 deletions(-) diff --git a/apps/server/src/mcp/toolkits/workFiles/handlers.ts b/apps/server/src/mcp/toolkits/workFiles/handlers.ts index 95efc66f5e311..b8e4ce4fa192a 100644 --- a/apps/server/src/mcp/toolkits/workFiles/handlers.ts +++ b/apps/server/src/mcp/toolkits/workFiles/handlers.ts @@ -7,7 +7,7 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import { WorkFilesToolkit } from "./tools.ts"; export const layer = McpToolAccess.toLayer(WorkFilesToolkit, { - // The same access a launch from a link needs: no read-only link, no stopped caller. + // Receiving files edits the checkout: no link below auto-accept-edits, no stopped caller. t3_work_files_receive: McpToolAccess.writes( (request) => Effect.gen(function* () { @@ -18,6 +18,10 @@ export const layer = McpToolAccess.toLayer(WorkFilesToolkit, { message: "Only a linked environment can send work files here.", }); } + const refusal = WorkFilesTransfer.receiveAccessRefusal(scope.client.access); + if (refusal !== null) { + return yield* new OrchestratorMcpFailure({ code: "capability_denied", message: refusal }); + } const transfer = yield* WorkFilesTransfer.WorkFilesTransfer; return yield* transfer.issueReceive({ request, sessionId: scope.client.sessionId }); }), diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index e744cb105ca6c..f30fc8a151ae6 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -1325,6 +1325,7 @@ it.effect("sends the work files before launching there, and launches nothing whe task: "Run the suite on the box with my edits.", target: { environmentId: box.environmentId }, workFiles: "transfer", + clientRequestId: "suite-with-edits", }); const refused = yield* delegate; @@ -1344,6 +1345,11 @@ it.effect("sends the work files before launching there, and launches nothing whe { cwd: "/home/me/app", projectId: boxProject, launchedFirst: false }, { cwd: "/home/me/app", projectId: boxProject, launchedFirst: false }, ]); + // A retry of the launched task finds it and sends nothing again. + const retried = yield* delegate; + expect(retried.isError, JSON.stringify(retried.content)).toBe(false); + expect(retried.structuredContent).toEqual(accepted.structuredContent); + expect(sent).toHaveLength(2); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 0fac203dabdf7..f658725995e73 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -30,6 +30,7 @@ import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as Tool from "effect/ai/Tool"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { withExecutedModelNote } from "@t3tools/provider-core/server/subagentProjection"; import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; @@ -344,7 +345,24 @@ const make = Effect.gen(function* () { parent.thread.projectId, target.projectId, ); - if (input.workFiles === "transfer") { + // One key for the launch there and the record here, so a retry finds both. + // Both are scoped to the provider session, as every key a caller passes is: + // the forwarder scopes the launch's, and the record's names it. + const key = input.clientRequestId ?? (yield* random.uuidV4()); + const commandId = CommandId.make( + `command:mcp:${encodeURIComponent(scope.requestNamespace)}:remote-delegate:${encodeURIComponent(key)}`, + ); + // A retry of a recorded task launched it already, and its files went first. + const recordedBefore = + input.clientRequestId !== undefined && + (yield* threads.getThreadRecords(scope.thread.threadId, ["subagents"]).pipe( + Effect.map(({ subagents }) => { + const taskId = IdAllocator.derive.delegatedTaskNode({ commandId }); + return subagents.some((task) => task.id === taskId); + }), + Effect.orElseSucceed(() => false), + )); + if (input.workFiles === "transfer" && !recordedBefore) { const here = yield* projects.getById(parent.thread.projectId).pipe( Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), @@ -375,10 +393,6 @@ const make = Effect.gen(function* () { ), ); } - // One key for the launch there and the record here, so a retry finds both. - // Both are scoped to the provider session, as every key a caller passes is: - // the forwarder scopes the launch's, and the record's names it. - const key = input.clientRequestId ?? (yield* random.uuidV4()); const task = taskPrompt(input); const title = input.title ?? parent.thread.title; const launched = yield* forwarding.call( @@ -405,9 +419,6 @@ const make = Effect.gen(function* () { Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), ); - const commandId = CommandId.make( - `command:mcp:${encodeURIComponent(scope.requestNamespace)}:remote-delegate:${encodeURIComponent(key)}`, - ); const remoteChild: OrchestrationV2RemoteTaskChild = { environmentId: target.environmentId, threadId: launched.threadId, diff --git a/apps/server/src/peer/WorkFiles.test.ts b/apps/server/src/peer/WorkFiles.test.ts index f2ee62d7d4b90..21a87f51fe97e 100644 --- a/apps/server/src/peer/WorkFiles.test.ts +++ b/apps/server/src/peer/WorkFiles.test.ts @@ -3,6 +3,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import * as NodeZlib from "node:zlib"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; @@ -60,6 +61,23 @@ const tar = (cwd: string, ...args: string[]) => env: { ...process.env, COPYFILE_DISABLE: "1" }, }); +/** One ustar entry: a header with `name` and `type`, then `body` padded to a block. */ +const tarEntry = (name: string, type: string, body: Buffer) => { + const header = Buffer.alloc(512); + header.write(name, 0, 100, "utf8"); + header.write("0000644\0", 100); + header.write("0000000\0", 108); + header.write("0000000\0", 116); + header.write(`${body.length.toString(8).padStart(11, "0")}\0`, 124); + header.write("00000000000\0", 136); + header.write(type, 156); + header.write("ustar\u000000", 257, "binary"); + header.fill(" ", 148, 156); + const sum = header.reduce((total, byte) => total + byte, 0); + header.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148); + return Buffer.concat([header, body, Buffer.alloc((512 - (body.length % 512)) % 512)]); +}; + /** The archive the source would send for `files` under `root`, written to `archivePath`. */ const writeArchive = (root: string, files: ReadonlyArray, archivePath: string) => archiveStream(root, files).pipe( @@ -83,6 +101,7 @@ it.live( "src/old.ts": "old", "README.md": "readme", ".gitignore": "ignored.log\n", + "config/.env": "TOKEN=0", }); write(root, "src/app.ts", "two"); write(root, "src/staged.ts", "staged"); @@ -92,6 +111,8 @@ it.live( write(root, ".env.local", "TOKEN=1"); write(root, "certs/server.pem", "pem"); NodeFS.rmSync(NodePath.join(root, "src/old.ts")); + // A deleted secret stays where it is on both sides. + NodeFS.rmSync(NodePath.join(root, "config/.env")); NodeFS.symlinkSync("README.md", NodePath.join(root, "link.md")); const selection = yield* selectWorkFiles(root); @@ -102,7 +123,7 @@ it.live( "src/staged.ts", ]); expect(selection.deletions).toEqual(["src/old.ts"]); - expect(selection.leftBehind).toEqual([".env.local", "certs/server.pem"]); + expect(selection.leftBehind).toEqual([".env.local", "certs/server.pem", "config/.env"]); expect(selection.totalBytes).toBe(3 + 3 + 6); expect(selection.refusal).toBeNull(); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), @@ -116,6 +137,7 @@ it.live("a folder outside git carries every file but dependencies, build output write(root, "node_modules/lib/index.js", "lib"); write(root, "dist/main.js", "built"); write(root, ".git/HEAD", "not a repository"); + write(root, "vendor/.GIT/hooks/post-checkout", "hook"); write(root, "id_rsa", "secret"); write(root, "deploy/.netrc", "secret"); @@ -144,14 +166,35 @@ it.live("refuses a set over either limit with its numbers", () => expect((yield* selectWorkFiles(many)).refusal).toMatch( /^The work files are more than 5,000 files and 0\.0 MiB; the limit is 5,000 files/, ); + + // Secrets stay behind and do not count, so they cannot push later files out of the walk. + const secrets = yield* tempDir; + for (let folder = 0; folder < 10; folder++) { + for (let index = 0; index < 400; index++) write(secrets, `d${folder}/${index}`, ""); + for (let index = 0; index < 200; index++) write(secrets, `d${folder}/${index}.pem`, ""); + } + const underLimit = yield* selectWorkFiles(secrets); + expect(underLimit.refusal).toBeNull(); + expect(underLimit.files).toHaveLength(4_000); + expect(underLimit.leftBehind).toHaveLength(2_000); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); it("keeps archive and deletion paths inside the checkout on every platform", () => { - for (const path of ["/etc/passwd", "../up", "a/../../up", "C:/x", "a\\b", ""]) { + for (const path of [ + "/etc/passwd", + "../up", + "a/../../up", + "C:/x", + "a\\b", + "", + ".git/hooks/post-checkout", + ".GIT/config", + "sub/.Git/hooks/pre-commit", + ]) { expect(isSafeRelativePath(path), path).toBe(false); } - for (const path of ["a", "a/b.txt", ".github/x.yml", "a..b"]) { + for (const path of ["a", "a/b.txt", ".github/x.yml", "a..b", ".gitignore", "x.git/y"]) { expect(isSafeRelativePath(path), path).toBe(true); } }); @@ -165,6 +208,13 @@ it.live.each([ "a path with ..", (dir: string) => tar(NodePath.join(dir, "src"), "-czPf", "../bad.tgz", "../src/x"), ], + [ + "a git hook", + (dir: string) => { + write(dir, ".git/hooks/post-checkout", "#!/bin/sh\n"); + tar(dir, "-czf", "bad.tgz", "src/x", ".git/hooks/post-checkout"); + }, + ], [ "a symlink", (dir: string) => { @@ -184,7 +234,7 @@ it.live.each([ const dir = yield* tempDir; write(dir, "src/x", "x"); make(dir); - const refused = yield* listArchive(NodePath.join(dir, "bad.tgz"), dir).pipe(Effect.flip); + const refused = yield* listArchive(NodePath.join(dir, "bad.tgz")).pipe(Effect.flip); expect(refused.reason).toBe("invalid_archive"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -269,8 +319,20 @@ it.live("never overwrites a file with local changes there, and changes nothing", "a.ts": "a", "b.ts": "b", "c.ts": "c", + "d.ts": "d", + "e.ts": "e", + "f.ts": "f", }); + const outside = yield* tempDir; write(source, "a.ts", "from source"); + write(source, "d.ts", "from source"); + write(source, "e.ts", "from source"); + write(source, "f.ts", "from source"); + // Deleted there, unstaged and staged: the source's edit must not bring them back. + NodeFS.rmSync(NodePath.join(target, "d.ts")); + git(target, "rm", "-q", "e.ts"); + // Another name for f.ts outside the checkout would change with it. + NodeFS.linkSync(NodePath.join(target, "f.ts"), NodePath.join(outside, "f.ts")); write(source, "b.ts", "from source"); write(source, "new.ts", "from source"); NodeFS.rmSync(NodePath.join(source, "c.ts")); @@ -295,8 +357,149 @@ it.live("never overwrites a file with local changes there, and changes nothing", expect(refused.message).toContain("b.ts (it has local changes there)"); expect(refused.message).toContain("new.ts (it has local changes there)"); expect(refused.message).toContain("c.ts (it has local changes there)"); + expect(refused.message).toContain("d.ts (it was deleted there)"); + expect(refused.message).toContain("e.ts (it was deleted there)"); + expect(refused.message).toContain("f.ts (it is a hard link to another file there)"); expect(refused.message).not.toContain("a.ts"); expect(NodeFS.readFileSync(NodePath.join(target, "a.ts"), "utf8")).toBe("a"); expect(NodeFS.readFileSync(NodePath.join(target, "c.ts"), "utf8")).toBe("edited there"); + expect(NodeFS.existsSync(NodePath.join(target, "d.ts"))).toBe(false); + expect(NodeFS.readFileSync(NodePath.join(outside, "f.ts"), "utf8")).toBe("f"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("a write or delete that fails partway puts back every file it changed", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ + "a.ts": "a", + "gone.ts": "gone", + "locked/z.ts": "z", + }); + write(source, "a.ts", "changed"); + write(source, "deep/new/file.ts", "new"); + NodeFS.rmSync(NodePath.join(source, "gone.ts")); + NodeFS.rmSync(NodePath.join(source, "locked/z.ts")); + const selection = yield* selectWorkFiles(source); + expect(selection.deletions).toEqual(["gone.ts", "locked/z.ts"]); + yield* writeArchive( + source, + selection.files.map((file) => file.path), + archivePath, + ); + // The last deletion fails, after the writes and the first deletion ran. + const locked = NodePath.join(target, "locked"); + NodeFS.chmodSync(locked, 0o500); + yield* Effect.addFinalizer(() => Effect.sync(() => NodeFS.chmodSync(locked, 0o700))); + + const refused = yield* applyWorkFiles({ + archivePath, + stagingDir, + root: target, + head: selection.head, + deletions: selection.deletions, + }).pipe(Effect.flip); + expect(refused.message).toBe("Could not delete locked/z.ts there; nothing was changed there."); + expect(NodeFS.readFileSync(NodePath.join(target, "a.ts"), "utf8")).toBe("a"); + expect(NodeFS.readFileSync(NodePath.join(target, "gone.ts"), "utf8")).toBe("gone"); + expect(NodeFS.existsSync(NodePath.join(target, "deep"))).toBe(false); + expect(git(target, "status", "--porcelain")).toBe(""); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("reads non-ASCII and long names from the archive itself", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ "a.ts": "a" }); + const prefixed = `${"p".repeat(120)}/${"n".repeat(30)}.md`; + const long = `${"l".repeat(90)}/${"o".repeat(90)}/${"g".repeat(90)}/${"x".repeat(90)}.md`; + write(source, "café.md", "c"); + write(source, prefixed, "p"); + write(source, long, "l"); + const selection = yield* selectWorkFiles(source); + yield* writeArchive( + source, + selection.files.map((file) => file.path), + archivePath, + ); + expect(selection.files.map((file) => file.path.normalize("NFC")).toSorted()).toEqual( + [long, prefixed, "café.md"].toSorted(), + ); + expect(yield* listArchive(archivePath)).toEqual(selection.files.map((file) => file.path)); + expect( + yield* applyWorkFiles({ + archivePath, + stagingDir, + root: target, + head: selection.head, + deletions: [], + }), + ).toEqual({ files: 3, deletions: 0 }); + expect(NodeFS.readFileSync(NodePath.join(target, "café.md"), "utf8")).toBe("c"); + expect(NodeFS.readFileSync(NodePath.join(target, long), "utf8")).toBe("l"); + + // GNU tar's own long-name entry, as Linux writes it. + const gnu = NodePath.join(stagingDir, "..", "gnu.tgz"); + const gnuName = `${"g".repeat(150)}/naïve.md`; + NodeFS.writeFileSync( + gnu, + NodeZlib.gzipSync( + Buffer.concat([ + tarEntry("././@LongLink", "L", Buffer.from(`${gnuName}\0`)), + tarEntry(gnuName.slice(0, 100), "0", Buffer.from("body")), + Buffer.alloc(1024), + ]), + ), + ); + expect(yield* listArchive(gnu)).toEqual([gnuName]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("refuses an archive that expands past the size limit before extracting it", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ "a.ts": "a" }); + // Sparse, so the test writes no 100 MiB; it gzips to well under a megabyte. + write(source, "huge.bin", ""); + NodeFS.truncateSync(NodePath.join(source, "huge.bin"), WORK_FILES_MAX_BYTES + 1); + yield* writeArchive(source, ["huge.bin"], archivePath); + + const refused = yield* applyWorkFiles({ + archivePath, + stagingDir, + root: target, + head: git(source, "rev-parse", "HEAD"), + deletions: [], + }).pipe(Effect.flip); + expect(refused.reason).toBe("over_limit"); + expect(NodeFS.existsSync(stagingDir)).toBe(false); + expect(NodeFS.existsSync(NodePath.join(target, "huge.bin"))).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("transfers into one checkout apply one at a time", () => + Effect.gen(function* () { + const { source, target } = yield* pair({ "a.ts": "a" }); + const head = git(source, "rev-parse", "HEAD"); + const sends = yield* Effect.forEach( + Array.from({ length: 12 }, (_, index) => index), + (index) => + Effect.gen(function* () { + const dir = yield* tempDir; + write(source, "new.ts", `send ${index}`); + yield* writeArchive(source, ["new.ts"], NodePath.join(dir, "work.tgz")); + return { + archivePath: NodePath.join(dir, "work.tgz"), + stagingDir: NodePath.join(dir, "staging"), + // The same checkout, named another way by every other send. + root: index % 2 === 0 ? target : `${target}/.`, + head, + deletions: [], + }; + }), + ); + + const results = yield* Effect.forEach(sends, (input) => Effect.result(applyWorkFiles(input)), { + concurrency: "unbounded", + }); + // The first to apply wins; every later one sees its file as local work. + expect(results.filter((result) => result._tag === "Success")).toHaveLength(1); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/peer/WorkFiles.ts b/apps/server/src/peer/WorkFiles.ts index d55f751586345..58302ed01b913 100644 --- a/apps/server/src/peer/WorkFiles.ts +++ b/apps/server/src/peer/WorkFiles.ts @@ -1,9 +1,13 @@ // @effect-diagnostics nodeBuiltinImport:off -- lstat, link counts and exclusive copies are filesystem boundaries missing from Effect's API. +import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; +import * as NodeStream from "node:stream"; +import * as NodeZlib from "node:zlib"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -34,11 +38,16 @@ const SKIPPED_DIRECTORIES = new Set([ "__pycache__", ]); +/** A repository's own folder; its hooks run on the next checkout, so no transfer writes into one. */ +const isGitFolder = (segment: string) => segment.toLowerCase() === ".git"; + export class WorkFilesError extends Schema.TaggedError()("WorkFilesError", { reason: Schema.Literals(["over_limit", "head_mismatch", "conflict", "invalid_archive", "failed"]), message: Schema.String, }) {} +const isWorkFilesError = Schema.is(WorkFilesError); + const failed = (message: string) => new WorkFilesError({ reason: "failed", message }); /** Files that look like credentials never leave the machine they are on. */ @@ -157,11 +166,15 @@ const gitTrackedPaths = Effect.fn("WorkFiles.gitTrackedPaths")(function* (cwd: s return new Set(nulSeparated(tracked.stdout)); }); -/** Every file under `root` outside skipped directories, stopping once past the count limit. */ +/** + * Every file under `root` outside skipped directories, stopping once past the + * count limit. Secrets stay behind, so they do not count toward it. + */ const walk = Effect.fn("WorkFiles.walk")(function* (root: string) { const found: string[] = []; const pending = [""]; - while (pending.length > 0 && found.length <= WORK_FILES_MAX_COUNT) { + let eligible = 0; + while (pending.length > 0 && eligible <= WORK_FILES_MAX_COUNT) { const directory = pending.pop()!; const entries = yield* fileSystemCall("read the working directory", () => NodeFSP.readdir(NodePath.join(root, directory), { withFileTypes: true }), @@ -169,9 +182,12 @@ const walk = Effect.fn("WorkFiles.walk")(function* (root: string) { for (const entry of entries) { const relative = directory === "" ? entry.name : `${directory}/${entry.name}`; if (entry.isDirectory()) { - if (!SKIPPED_DIRECTORIES.has(entry.name)) pending.push(relative); + if (!SKIPPED_DIRECTORIES.has(entry.name) && !isGitFolder(entry.name)) { + pending.push(relative); + } } else if (entry.isFile()) { found.push(relative); + if (!looksLikeSecret(relative)) eligible += 1; } } } @@ -188,17 +204,20 @@ export const selectWorkFiles = Effect.fn("WorkFiles.select")(function* (root: st const inodes = new Map(); let totalBytes = 0; for (const path of candidates.toSorted()) { + // The receiving side refuses these, so they are never sent. + if (!isSafeRelativePath(path)) continue; const stat = yield* lstatOrNull(NodePath.join(root, path)); - if (stat === null) { - if (head !== null) deletions.push(path); - continue; - } // Symlinks and submodule directories are not work files. - if (!stat.isFile()) continue; + if (stat !== null && !stat.isFile()) continue; + // A secret is neither sent nor deleted there. if (looksLikeSecret(path)) { leftBehind.push(path); continue; } + if (stat === null) { + if (head !== null) deletions.push(path); + continue; + } if (stat.nlink > 1) { const inode = `${stat.dev}:${stat.ino}`; const other = inodes.get(inode); @@ -281,55 +300,217 @@ export const archiveStream = (root: string, files: ReadonlyArray) => const invalid = (message: string) => new WorkFilesError({ reason: "invalid_archive", message }); -/** A relative path that stays inside the directory it is joined to, on any platform. */ +/** A relative path that stays inside the directory it is joined to, on any platform, and outside `.git`. */ export const isSafeRelativePath = (path: string) => path.length > 0 && !path.startsWith("/") && !/^[A-Za-z]:/.test(path) && !path.includes("\\") && !path.includes("\0") && - path.split("/").every((segment) => segment !== ".."); + path.split("/").every((segment) => segment !== ".." && !isGitFolder(segment)); + +interface ArchiveEntry { + readonly path: string; + readonly type: "file" | "directory"; + readonly size: number; +} + +const TAR_BLOCK = 512; +/** Pax and GNU long-name records hold a few names; a bigger one is not an archive a T3 server wrote. */ +const TAR_MAX_METADATA_BYTES = 1024 * 1024; +const TAR_MAX_ENTRIES = WORK_FILES_MAX_COUNT * 4; + +const nulTerminated = (bytes: Buffer) => { + const end = bytes.indexOf(0); + return (end === -1 ? bytes : bytes.subarray(0, end)).toString("utf8"); +}; + +/** A tar number field: octal text, or GNU's base-256 with the high bit set. */ +const tarNumber = (field: Buffer) => { + if ((field[0]! & 0x80) !== 0) { + if (field[0] === 0xff) return null; + let value = field[0]! & 0x7f; + for (const byte of field.subarray(1)) value = value * 256 + byte; + return value; + } + const text = nulTerminated(field).trim(); + return text === "" ? 0 : /^[0-7]+$/.test(text) ? Number.parseInt(text, 8) : null; +}; + +/** Pax records, ` =\n` each, with the length counting bytes. */ +const paxRecords = (data: Buffer) => { + const records = new Map(); + let offset = 0; + while (offset < data.length) { + const space = data.indexOf(0x20, offset); + const length = + space === -1 ? Number.NaN : Number(data.subarray(offset, space).toString("latin1")); + if ( + !Number.isInteger(length) || + offset + length > data.length || + length <= space - offset + 1 + ) { + throw invalid("The archive has a malformed pax header."); + } + const record = data.subarray(space + 1, offset + length - 1).toString("utf8"); + const equals = record.indexOf("="); + if (equals === -1) throw invalid("The archive has a malformed pax header."); + records.set(record.slice(0, equals), record.slice(equals + 1)); + offset += length; + } + return records; +}; + +const checksumMatches = (header: Buffer) => { + const stored = tarNumber(header.subarray(148, 156)); + let unsigned = 0; + let signed = 0; + for (let index = 0; index < TAR_BLOCK; index++) { + const byte = index >= 148 && index < 156 ? 0x20 : header[index]!; + unsigned += byte; + signed += byte > 127 ? byte - 256 : byte; + } + return stored === unsigned || stored === signed; +}; /** - * The regular files an archive holds, refusing absolute paths, `..`, and any - * entry that is not a file or directory, such as a symlink or hard link. + * The entries of a gzip tar, read from its headers here rather than from a tar + * listing, which escapes non-ASCII names. Refuses links and special files, and + * stops as soon as the files pass the count or expanded size limit. */ -export const listArchive = Effect.fn("WorkFiles.listArchive")(function* ( - archivePath: string, - cwd: string, -) { - const [names, verbose] = yield* Effect.all([ - runProcess("tar", ["-tzf", archivePath], { cwd }), - runProcess("tar", ["-tvzf", archivePath], { cwd }), - ]); - if (names.code !== 0 || verbose.code !== 0) { - return yield* invalid("The archive could not be read."); - } - const lines = (bytes: Uint8Array) => - Buffer.from(bytes) - .toString("utf8") - .split("\n") - .filter((line) => line.length > 0); - for (const line of lines(verbose.stdout)) { - // Each entry's listing starts with its type; a name with a newline lands here too and is refused. - if (line[0] !== "-" && line[0] !== "d") { - return yield* invalid( - "The archive holds a link or special file; only regular files are accepted.", - ); +const readArchiveEntries = async (archivePath: string) => { + const gunzip = NodeZlib.createGunzip(); + NodeStream.pipeline(NodeFS.createReadStream(archivePath), gunzip, () => undefined); + const entries: ArchiveEntry[] = []; + let buffer: Buffer = Buffer.alloc(0); + let skip = 0; + let collecting: { readonly type: string; readonly size: number } | null = null; + let pax = new Map(); + let longName: string | null = null; + let fileCount = 0; + let expandedBytes = 0; + let ended = false; + try { + for await (const chunk of gunzip as AsyncIterable) { + buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]); + let offset = 0; + while (!ended) { + if (skip > 0) { + const taken = Math.min(skip, buffer.length - offset); + skip -= taken; + offset += taken; + if (skip > 0) break; + continue; + } + if (collecting !== null) { + if (buffer.length - offset < collecting.size) break; + const data = Buffer.from(buffer.subarray(offset, offset + collecting.size)); + offset += collecting.size; + skip = (TAR_BLOCK - (collecting.size % TAR_BLOCK)) % TAR_BLOCK; + if (collecting.type === "x") pax = paxRecords(data); + if (collecting.type === "L") longName = nulTerminated(data); + collecting = null; + continue; + } + if (buffer.length - offset < TAR_BLOCK) break; + const header = buffer.subarray(offset, offset + TAR_BLOCK); + offset += TAR_BLOCK; + if (header.every((byte) => byte === 0)) { + ended = true; + break; + } + if (!checksumMatches(header)) throw invalid("The archive could not be read."); + const flag = header[156] === 0 ? "0" : String.fromCharCode(header[156]!); + const headerSize = tarNumber(header.subarray(124, 136)); + const paxSize = pax.get("size"); + // The bytes stored in the archive, which a sparse file's map and data make smaller than the file. + const size = paxSize === undefined ? headerSize : Number(paxSize); + const sparseSize = + pax.get("GNU.sparse.realsize") ?? + pax.get("GNU.sparse.size") ?? + (flag === "S" ? tarNumber(header.subarray(483, 495)) : null); + const expanded = sparseSize === null ? size : Number(sparseSize); + if ( + size === null || + expanded === null || + !Number.isSafeInteger(size) || + !Number.isSafeInteger(expanded) || + size < 0 || + expanded < 0 + ) { + throw invalid("The archive could not be read."); + } + // Metadata for the entry after it: pax records, a global pax header, GNU long names. + if (flag === "x" || flag === "g" || flag === "L" || flag === "K") { + if (size > TAR_MAX_METADATA_BYTES) throw invalid("The archive has an oversized header."); + collecting = { type: flag, size }; + continue; + } + const ustarPrefix = + header.subarray(257, 263).toString("latin1") === "ustar\0" + ? nulTerminated(header.subarray(345, 500)) + : ""; + const headerName = nulTerminated(header.subarray(0, 100)); + const path = + longName ?? + pax.get("GNU.sparse.name") ?? + pax.get("path") ?? + (ustarPrefix === "" ? headerName : `${ustarPrefix}/${headerName}`); + pax = new Map(); + longName = null; + const isDirectory = flag === "5" || ((flag === "0" || flag === "7") && path.endsWith("/")); + if (!isDirectory && flag !== "0" && flag !== "7" && flag !== "S") { + throw invalid( + "The archive holds a link or special file; only regular files are accepted.", + ); + } + entries.push({ path, type: isDirectory ? "directory" : "file", size: expanded }); + if (entries.length > TAR_MAX_ENTRIES) { + throw invalid(`The archive holds more than ${TAR_MAX_ENTRIES} entries.`); + } + if (!isDirectory) { + fileCount += 1; + expandedBytes += expanded; + if (fileCount > WORK_FILES_MAX_COUNT) { + throw invalid(`The archive holds more than ${WORK_FILES_MAX_COUNT} files.`); + } + if (expandedBytes > WORK_FILES_MAX_BYTES) { + throw new WorkFilesError({ + reason: "over_limit", + message: `The archive expands to more than ${formatMiB(WORK_FILES_MAX_BYTES)}, the limit.`, + }); + } + skip = size + ((TAR_BLOCK - (size % TAR_BLOCK)) % TAR_BLOCK); + } + } + buffer = buffer.subarray(offset); + if (ended) break; } + } finally { + gunzip.destroy(); } + if (!ended) throw invalid("The archive could not be read."); + return entries; +}; + +/** + * The regular files an archive holds, refusing absolute paths, `..`, `.git`, + * any entry that is not a file or directory, and a set over the limits. + */ +export const listArchive = Effect.fn("WorkFiles.listArchive")(function* (archivePath: string) { + const entries = yield* Effect.tryPromise({ + try: () => readArchiveEntries(archivePath), + catch: (error) => (isWorkFilesError(error) ? error : invalid("The archive could not be read.")), + }); const files: string[] = []; - for (const raw of lines(names.stdout)) { - const name = raw.startsWith("./") ? raw.slice(2) : raw; + for (const entry of entries) { + const name = entry.path.startsWith("./") ? entry.path.slice(2) : entry.path; const path = name.endsWith("/") ? name.slice(0, -1) : name; if (path === "" || path === ".") continue; if (!isSafeRelativePath(path)) { - return yield* invalid(`The archive holds an unsafe path: "${raw}".`); + return yield* invalid(`The archive holds an unsafe path: "${entry.path}".`); } - if (!name.endsWith("/")) files.push(path); - } - if (files.length > WORK_FILES_MAX_COUNT) { - return yield* invalid(`The archive holds more than ${WORK_FILES_MAX_COUNT} files.`); + if (entry.type === "file") files.push(path); } return files; }); @@ -337,8 +518,10 @@ export const listArchive = Effect.fn("WorkFiles.listArchive")(function* ( /** Checks the extracted tree is only directories and single-link files, exactly those listed. */ const verifyStaging = Effect.fn("WorkFiles.verifyStaging")(function* ( staging: string, - expected: ReadonlySet, + listed: ReadonlyArray, ) { + // Some tars change a name's Unicode normalization on the way to disk, as macOS bsdtar does. + const expected = new Set(listed.map((path) => path.normalize("NFC"))); const pending = [""]; let seen = 0; while (pending.length > 0) { @@ -353,7 +536,12 @@ const verifyStaging = Effect.fn("WorkFiles.verifyStaging")(function* ( continue; } const stat = yield* lstatOrNull(NodePath.join(staging, relative)); - if (stat === null || !stat.isFile() || stat.nlink > 1 || !expected.has(relative)) { + if ( + stat === null || + !stat.isFile() || + stat.nlink > 1 || + !expected.has(relative.normalize("NFC")) + ) { return yield* invalid(`The archive extracted an unexpected entry: ${relative}.`); } seen += 1; @@ -371,13 +559,15 @@ const targetConflict = Effect.fn("WorkFiles.targetConflict")(function* ( incoming: string | null, ) { const segments = path.split("/"); + // Missing there is a new file, unless someone deleted it there: writing it would undo that. + const missing = incoming !== null && local?.changed.has(path) ? "it was deleted there" : null; for (let index = 1; index < segments.length; index++) { const parent = yield* lstatOrNull(NodePath.join(root, ...segments.slice(0, index))); - if (parent === null) return null; + if (parent === null) return missing; if (!parent.isDirectory()) return "a parent folder is a link or a file there"; } const stat = yield* lstatOrNull(NodePath.join(root, ...segments)); - if (stat === null) return null; + if (stat === null) return missing; if (!stat.isFile()) return "it is a link or a folder there"; // An identical file is no change, so sending the same work again is a no-op. if (incoming !== null) { @@ -386,6 +576,8 @@ const targetConflict = Effect.fn("WorkFiles.targetConflict")(function* ( fileSystemCall("read an extracted file", () => NodeFSP.readFile(incoming)), ]); if (here.equals(there)) return null; + // Copying onto it would change its other names too. + if (stat.nlink > 1) return "it is a hard link to another file there"; } if (local === null) { // Outside git nothing records local changes, so only an identical file may be replaced. @@ -405,19 +597,125 @@ export interface ApplyWorkFilesInput { readonly deletions: ReadonlyArray; } +/** One lock per checkout, by its resolved path, held from the conflict checks through the copy. */ +const checkoutLocks = new Map(); + +const checkoutLock = (root: string) => + Effect.promise(() => NodeFSP.realpath(root).catch(() => NodePath.resolve(root))).pipe( + Effect.map((key) => { + const existing = checkoutLocks.get(key); + if (existing !== undefined) return existing; + const lock = Semaphore.makeUnsafe(1); + checkoutLocks.set(key, lock); + return lock; + }), + ); + /** - * Applies a received archive to `root`: checks it, extracts it to + * Copies the staged files into `root` and applies the deletions, backing up + * each file it replaces or deletes. On any failure it puts those back and + * removes the files and folders it added, so a refusal changes nothing. + */ +const copyIn = async (input: { + readonly root: string; + readonly staged: string; + readonly backups: string; + readonly files: ReadonlyArray; + readonly deletions: ReadonlyArray; +}) => { + const changed: Array<{ readonly destination: string; readonly backup: string | null }> = []; + const createdFolders: string[] = []; + const exists = (path: string) => + NodeFSP.lstat(path).then( + () => true, + () => false, + ); + const backUp = async (path: string, destination: string) => { + const backup = NodePath.join(input.backups, ...path.split("/")); + await NodeFSP.mkdir(NodePath.dirname(backup), { recursive: true }); + await NodeFSP.copyFile(destination, backup); + return backup; + }; + let step = ""; + try { + for (const path of input.files) { + step = `write ${path}`; + const segments = path.split("/"); + const destination = NodePath.join(input.root, ...segments); + let backup: string | null = null; + if (await exists(destination)) { + backup = await backUp(path, destination); + } else { + for (let index = 1; index < segments.length; index++) { + const folder = NodePath.join(input.root, ...segments.slice(0, index)); + if (!(await exists(folder))) createdFolders.push(folder); + } + await NodeFSP.mkdir(NodePath.dirname(destination), { recursive: true }); + } + changed.push({ destination, backup }); + await NodeFSP.copyFile(NodePath.join(input.staged, ...segments), destination); + } + let deleted = 0; + for (const path of input.deletions) { + step = `delete ${path}`; + const destination = NodePath.join(input.root, ...path.split("/")); + if (!(await exists(destination))) continue; + changed.push({ destination, backup: await backUp(path, destination) }); + await NodeFSP.rm(destination); + deleted += 1; + } + return deleted; + } catch { + const unrestored: string[] = []; + for (const { destination, backup } of changed.toReversed()) { + await ( + backup === null + ? NodeFSP.rm(destination, { force: true }) + : NodeFSP.copyFile(backup, destination) + ).catch(() => unrestored.push(NodePath.relative(input.root, destination))); + } + for (const folder of createdFolders.toReversed()) { + await NodeFSP.rmdir(folder).catch(() => undefined); + } + throw failed( + unrestored.length === 0 + ? `Could not ${step} there; nothing was changed there.` + : `Could not ${step} there, and could not put back ${unrestored.join(", ")}.`, + ); + } +}; + +export interface ApplyWorkFilesInput { + readonly archivePath: string; + readonly stagingDir: string; + readonly root: string; + /** The source's HEAD; null when the source is not a git checkout. */ + readonly head: string | null; + readonly deletions: ReadonlyArray; +} + +/** + * Applies a received archive to `root`: checks it, extracts it under * `stagingDir`, refuses on a HEAD mismatch or any path with local changes, - * then copies the files in and applies the deletions. The caller owns - * removing `archivePath` and `stagingDir`. + * then copies the files in and applies the deletions, undoing them all if any + * fails. The caller owns removing `archivePath` and `stagingDir`. */ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: ApplyWorkFilesInput) { - const files = yield* listArchive(input.archivePath, input.root); + const files = yield* listArchive(input.archivePath); for (const path of input.deletions) { if (!isSafeRelativePath(path)) { return yield* invalid(`A deletion names an unsafe path: "${path}".`); } } + const lock = yield* checkoutLock(input.root); + return yield* Semaphore.withPermit(lock, applyLocked(input, files)); +}); + +const applyLocked = Effect.fn("WorkFiles.applyLocked")(function* ( + input: ApplyWorkFilesInput, + files: ReadonlyArray, +) { + const staged = NodePath.join(input.stagingDir, "files"); const head = yield* gitHead(input.root); if (input.head !== null) { if (head === null) { @@ -435,13 +733,13 @@ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: App } } yield* fileSystemCall("create the staging folder", () => - NodeFSP.mkdir(input.stagingDir, { recursive: true }), + NodeFSP.mkdir(staged, { recursive: true }), ); - const extracted = yield* runProcess("tar", ["-xzf", input.archivePath, "-C", input.stagingDir], { - cwd: input.stagingDir, + const extracted = yield* runProcess("tar", ["-xzf", input.archivePath, "-C", staged], { + cwd: staged, }); if (extracted.code !== 0) return yield* invalid("The archive could not be extracted."); - yield* verifyStaging(input.stagingDir, new Set(files)); + yield* verifyStaging(staged, files); const local = head === null ? null @@ -455,7 +753,7 @@ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: App input.root, path, local, - NodePath.join(input.stagingDir, ...path.split("/")), + NodePath.join(staged, ...path.split("/")), ); if (reason !== null) conflicts.push(`${path} (${reason})`); } @@ -469,19 +767,16 @@ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: App message: `Nothing was changed there, because these paths would overwrite local work: ${conflicts.slice(0, 20).join(", ")}${conflicts.length > 20 ? `, and ${conflicts.length - 20} more` : ""}.`, }); } - for (const path of files) { - const destination = NodePath.join(input.root, ...path.split("/")); - yield* fileSystemCall(`write ${path}`, async () => { - await NodeFSP.mkdir(NodePath.dirname(destination), { recursive: true }); - await NodeFSP.copyFile(NodePath.join(input.stagingDir, ...path.split("/")), destination); - }); - } - let deleted = 0; - for (const path of input.deletions) { - const destination = NodePath.join(input.root, ...path.split("/")); - if ((yield* lstatOrNull(destination)) === null) continue; - yield* fileSystemCall(`delete ${path}`, () => NodeFSP.rm(destination)); - deleted += 1; - } + const deleted = yield* Effect.tryPromise({ + try: () => + copyIn({ + root: input.root, + staged, + backups: NodePath.join(input.stagingDir, "backup"), + files, + deletions: input.deletions, + }), + catch: (error) => (isWorkFilesError(error) ? error : failed("Could not apply the work files.")), + }); return { files: files.length, deletions: deleted }; }); diff --git a/apps/server/src/peer/WorkFilesTransfer.test.ts b/apps/server/src/peer/WorkFilesTransfer.test.ts index 9f6f862495185..171a6fcc3973d 100644 --- a/apps/server/src/peer/WorkFilesTransfer.test.ts +++ b/apps/server/src/peer/WorkFilesTransfer.test.ts @@ -190,6 +190,26 @@ it.live("a refusal there changes nothing and still removes the archive and stagi }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), ); +it.live("a receive folder the box cannot write to refuses the files and keeps it running", () => + Effect.gen(function* () { + const { source, target } = yield* checkouts; + const { peer, receiveDir } = yield* serveBox(target); + NodeFS.mkdirSync(receiveDir, { recursive: true }); + NodeFS.chmodSync(receiveDir, 0o500); + yield* Effect.addFinalizer(() => Effect.sync(() => NodeFS.chmodSync(receiveDir, 0o700))); + write(source, "app.ts", "v2"); + + const send = yield* laptopSending(peer, source, "auto"); + const refused = yield* send.pipe(Effect.flip); + expect(refused.message).toContain("The linked environment refused the work files"); + expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v1"); + + // The box still answers, and a writable folder takes the same work. + NodeFS.chmodSync(receiveDir, 0o700); + expect(yield* send).toEqual({ files: 1, deletions: 0 }); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), +); + it.live("refuses before sending anything when the box is on another commit", () => Effect.gen(function* () { const { source, target } = yield* checkouts; @@ -207,17 +227,20 @@ it.live("refuses before sending anything when the box is on another commit", () }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), ); -it.live("a read-only link cannot send files", () => - Effect.gen(function* () { - const { source, target } = yield* checkouts; - const { peer } = yield* serveBox(target); - write(source, "app.ts", "v2"); +it.live.each(["read-only", "approval-required"] as const)( + "refuses files from a link with %s access", + (access) => + Effect.gen(function* () { + const { source, target } = yield* checkouts; + const { peer } = yield* serveBox(target); + write(source, "app.ts", "v2"); - const send = yield* laptopSending(peer, source, "read-only"); - const refused = yield* send.pipe(Effect.flip); - expect(refused.code).toBe("capability_denied"); - expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v1"); - }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), + const send = yield* laptopSending(peer, source, access); + const refused = yield* send.pipe(Effect.flip); + expect(refused.code).toBe("capability_denied"); + if (access !== "read-only") expect(refused.message).toContain(access); + expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v1"); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), ); it.live("the upload route takes nothing without a link session and its own token", () => @@ -231,6 +254,22 @@ it.live("the upload route takes nothing without a link session and its own token ).pipe(HttpClientRequest.setBody(HttpBody.text("x"))), ); expect(anonymous.status).toBe(401); + + // A supervised link may read, but receiving files edits the checkout. + const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build); + const links = Context.get(linking, PeerLinks.PeerLinks); + yield* linkTo(links, peer, "approval-required"); + const resolved = yield* links.resolve(box.environmentId); + const supervised = yield* client.execute( + HttpClientRequest.post( + `${resolved.url}${WorkFilesTransfer.WORK_FILES_RECEIVE_ROUTE_PREFIX}/forged.token`, + ).pipe( + HttpClientRequest.setHeaders({ authorization: `Bearer ${resolved.token}` }), + HttpClientRequest.setBody(HttpBody.text("x")), + ), + ); + expect(supervised.status).toBe(403); + expect(yield* supervised.text).toContain("approval-required"); }).pipe( Effect.scoped, Effect.provide(Layer.merge(NodeHttpServer.layerTest, FetchHttpClient.layer)), diff --git a/apps/server/src/peer/WorkFilesTransfer.ts b/apps/server/src/peer/WorkFilesTransfer.ts index fe409cf4eb35c..ae484037ebdf0 100644 --- a/apps/server/src/peer/WorkFilesTransfer.ts +++ b/apps/server/src/peer/WorkFilesTransfer.ts @@ -1,10 +1,11 @@ // @effect-diagnostics nodeBuiltinImport:off -- the received archive is written and removed with plain filesystem calls. -import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import { + type AuthMcpClientAccess, type EnvironmentId, + isRuntimeModeAbove, OrchestratorMcpFailure, type ProjectId, WorkFilesApplied, @@ -92,6 +93,14 @@ export const summaryOf = (selection: WorkFilesSelection): WorkFilesSummary => ({ refusal: selection.refusal, }); +/** Receiving files edits the checkout, so a link needs at least auto-accept-edits; null when it has it. */ +export const receiveAccessRefusal = (access: AuthMcpClientAccess) => + access === "read-only" || isRuntimeModeAbove("auto-accept-edits", access) + ? `This link has ${access} access, which cannot change files here; sending work files needs auto-accept-edits access or broader.` + : null; + +const receiveFailed = (message: string) => new WorkFilesError({ reason: "failed", message }); + const transferFailure = (message: string) => new OrchestratorMcpFailure({ code: "orchestration_error", message }); @@ -133,10 +142,16 @@ export class WorkFilesTransfer extends Context.Service< } >()("t3/peer/WorkFilesTransfer") {} -/** Streams `body` into `path`; false when it passes `maxBytes`, without reading the rest. */ +/** + * Streams `body` into `path`; false when it passes `maxBytes`, without reading + * the rest. A file that cannot be created or written fails with a refusal. + */ const writeCapped = (body: Stream.Stream, path: string, maxBytes: number) => Effect.acquireUseRelease( - Effect.sync(() => NodeFS.createWriteStream(path, { flags: "wx" })), + Effect.tryPromise({ + try: () => NodeFSP.open(path, "wx"), + catch: () => receiveFailed("Could not store the archive here."), + }), (file) => Effect.gen(function* () { let received = 0; @@ -148,19 +163,15 @@ const writeCapped = (body: Stream.Stream, path: string, maxBy return !over; }), Stream.runForEach((chunk) => - Effect.callback((resume) => { - file.write(chunk, (error) => { - resume(error ? Effect.fail(error) : Effect.void); - }); + Effect.tryPromise({ + try: () => file.write(chunk), + catch: () => receiveFailed("Could not store the archive here."), }), ), ); return !over; }), - (file) => - Effect.callback((resume) => { - file.end(() => resume(Effect.void)); - }), + (file) => Effect.promise(() => file.close().catch(() => undefined)), ); const make = Effect.gen(function* () { @@ -355,7 +366,7 @@ export const layer = Layer.effect(WorkFilesTransfer, make); /** * `POST /api/work-files/receive/`: a linked environment's upload, - * authorized by its link session with operate access and the one-time token + * authorized by its link session with edit access and the one-time token * that session was issued. */ export const layerReceiveRoute = Layer.unwrap( @@ -370,9 +381,11 @@ export const layerReceiveRoute = Layer.unwrap( const request = yield* HttpServerRequest.HttpServerRequest; const client = yield* auth.authenticateMcpClient(request).pipe(Effect.option); if (Option.isNone(client)) return HttpServerResponse.text("Unauthorized", { status: 401 }); - if (!client.value.peerLink || client.value.access === "read-only") { + if (!client.value.peerLink) { return HttpServerResponse.text("This link cannot change files here.", { status: 403 }); } + const refusal = receiveAccessRefusal(client.value.access); + if (refusal !== null) return HttpServerResponse.text(refusal, { status: 403 }); const path = request.url.split("?", 1)[0] ?? ""; const token = path.slice(`${WORK_FILES_RECEIVE_ROUTE_PREFIX}/`.length); // Keep the request stream in the route scope until the response is sent. diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index eb8d92ace8e63..1110492e48730 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -377,6 +377,8 @@ for the same with `workFiles: "transfer"` on `delegate_task`. this machine. - Nothing is changed there if any of those files has its own local changes there. The transfer is at most 100 MiB and 5,000 files. +- The link to the other machine needs Auto-accept edits access or broader. + A Read only or Supervised link cannot change files there. ## Manage or revoke access From 76792dd7677519e9049feef00d5cb2d249ec6fb1 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:56:05 +0100 Subject: [PATCH 04/14] fix: work files refuse global pax headers, Windows .git aliases and non-git deletions, and finish an apply before an interruption lands --- apps/server/src/peer/WorkFiles.test.ts | 141 +++++++++++++++++++++- apps/server/src/peer/WorkFiles.ts | 122 ++++++++++++++----- apps/server/src/peer/WorkFilesTransfer.ts | 1 + 3 files changed, 232 insertions(+), 32 deletions(-) diff --git a/apps/server/src/peer/WorkFiles.test.ts b/apps/server/src/peer/WorkFiles.test.ts index 21a87f51fe97e..7831d508b2c98 100644 --- a/apps/server/src/peer/WorkFiles.test.ts +++ b/apps/server/src/peer/WorkFiles.test.ts @@ -8,7 +8,9 @@ import * as NodeZlib from "node:zlib"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Stream from "effect/Stream"; +import * as Tracer from "effect/Tracer"; import { applyWorkFiles, @@ -191,6 +193,13 @@ it("keeps archive and deletion paths inside the checkout on every platform", () ".git/hooks/post-checkout", ".GIT/config", "sub/.Git/hooks/pre-commit", + // Names Windows resolves to .git. + ".git./hooks/post-checkout", + ".git /config", + ".git::$INDEX_ALLOCATION/hooks/post-checkout", + "GIT~1/config", + "sub/git~2/hooks/pre-commit", + "a/b:stream", ]) { expect(isSafeRelativePath(path), path).toBe(false); } @@ -275,6 +284,7 @@ it.live("applies the work to the same commit there, deletions included", () => const input = { archivePath, stagingDir, + keptBackupsDir: NodePath.join(stagingDir, "..", "kept"), root: target, head: selection.head, deletions: selection.deletions, @@ -302,6 +312,7 @@ it.live("refuses a checkout on another commit, naming both", () => const refused = yield* applyWorkFiles({ archivePath, stagingDir, + keptBackupsDir: NodePath.join(stagingDir, "..", "kept"), root: target, head: selection.head, deletions: [], @@ -349,6 +360,7 @@ it.live("never overwrites a file with local changes there, and changes nothing", const refused = yield* applyWorkFiles({ archivePath, stagingDir, + keptBackupsDir: NodePath.join(stagingDir, "..", "kept"), root: target, head: selection.head, deletions: selection.deletions, @@ -394,6 +406,7 @@ it.live("a write or delete that fails partway puts back every file it changed", const refused = yield* applyWorkFiles({ archivePath, stagingDir, + keptBackupsDir: NodePath.join(stagingDir, "..", "kept"), root: target, head: selection.head, deletions: selection.deletions, @@ -406,6 +419,105 @@ it.live("a write or delete that fails partway puts back every file it changed", }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.live("a rollback that cannot put a file back keeps its backup and names where", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ "ro.ts": "original" }); + write(source, "ro.ts", "changed"); + yield* writeArchive(source, ["ro.ts"], archivePath); + // Writing fails, and so does putting the backup back. + const readOnly = NodePath.join(target, "ro.ts"); + NodeFS.chmodSync(readOnly, 0o444); + yield* Effect.addFinalizer(() => Effect.sync(() => NodeFS.chmodSync(readOnly, 0o644))); + const keptBackupsDir = NodePath.join(stagingDir, "..", "kept"); + + const refused = yield* applyWorkFiles({ + archivePath, + stagingDir, + keptBackupsDir, + root: target, + head: git(source, "rev-parse", "HEAD"), + deletions: [], + }).pipe(Effect.flip); + const [kept] = NodeFS.readdirSync(keptBackupsDir); + const keptPath = NodePath.join(keptBackupsDir, kept!); + expect(refused.message).toContain("could not put back ro.ts"); + expect(refused.message).toContain(keptPath); + expect(NodeFS.readFileSync(NodePath.join(keptPath, "ro.ts"), "utf8")).toBe("original"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("an apply interrupted after it takes the lock finishes before it ends", () => + Effect.gen(function* () { + const { source, target, archivePath, stagingDir } = yield* pair({ "a.ts": "a" }); + const paths = Array.from({ length: 200 }, (_, index) => `many/${index}.ts`); + for (const path of paths) write(source, path, "new"); + yield* writeArchive(source, paths, archivePath); + let locked!: () => void; + const lockTaken = new Promise((resolve) => (locked = resolve)); + const tracer = Tracer.make({ + span(options) { + if (options.name === "WorkFiles.applyLocked") locked(); + return new Tracer.NativeSpan(options); + }, + }); + + const fiber = yield* applyWorkFiles({ + archivePath, + stagingDir, + keptBackupsDir: NodePath.join(stagingDir, "..", "kept"), + root: target, + head: git(source, "rev-parse", "HEAD"), + deletions: [], + }).pipe(Effect.withTracer(tracer), Effect.forkChild); + yield* Effect.promise(() => lockTaken); + // The caller removes staging once this returns, so the copy must be over. + yield* Fiber.interrupt(fiber); + for (const path of paths) { + expect(NodeFS.readFileSync(NodePath.join(target, path), "utf8"), path).toBe("new"); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("refuses deletions from a folder outside git, and secret names from any sender", () => + Effect.gen(function* () { + const target = yield* tempDir; + const scratch = yield* tempDir; + write(target, "a.ts", "a"); + write(scratch, "empty/keep.ts", "k"); + const archivePath = NodePath.join(scratch, "work.tgz"); + yield* writeArchive(NodePath.join(scratch, "empty"), ["keep.ts"], archivePath); + const input = { + archivePath, + stagingDir: NodePath.join(scratch, "staging"), + keptBackupsDir: NodePath.join(scratch, "kept"), + root: target, + head: null, + deletions: ["a.ts"], + }; + const outsideGit = yield* applyWorkFiles(input).pipe(Effect.flip); + expect(outsideGit.reason).toBe("invalid_archive"); + expect(NodeFS.readFileSync(NodePath.join(target, "a.ts"), "utf8")).toBe("a"); + + const { + source, + target: checkout, + stagingDir, + } = yield* pair({ + "a.ts": "a", + "config/.env": "TOKEN=0", + }); + const secret = yield* applyWorkFiles({ + ...input, + stagingDir, + root: checkout, + head: git(source, "rev-parse", "HEAD"), + deletions: ["config/.env"], + }).pipe(Effect.flip); + expect(secret.reason).toBe("invalid_archive"); + expect(NodeFS.existsSync(NodePath.join(checkout, "config/.env"))).toBe(true); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.live("reads non-ASCII and long names from the archive itself", () => Effect.gen(function* () { const { source, target, archivePath, stagingDir } = yield* pair({ "a.ts": "a" }); @@ -423,11 +535,14 @@ it.live("reads non-ASCII and long names from the archive itself", () => expect(selection.files.map((file) => file.path.normalize("NFC")).toSorted()).toEqual( [long, prefixed, "café.md"].toSorted(), ); - expect(yield* listArchive(archivePath)).toEqual(selection.files.map((file) => file.path)); + expect((yield* listArchive(archivePath)).map((file) => file.path)).toEqual( + selection.files.map((file) => file.path), + ); expect( yield* applyWorkFiles({ archivePath, stagingDir, + keptBackupsDir: NodePath.join(stagingDir, "..", "kept"), root: target, head: selection.head, deletions: [], @@ -449,7 +564,27 @@ it.live("reads non-ASCII and long names from the archive itself", () => ]), ), ); - expect(yield* listArchive(gnu)).toEqual([gnuName]); + expect((yield* listArchive(gnu)).map((file) => file.path)).toEqual([gnuName]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("refuses a global pax header, which GNU tar applies to every entry after it", () => + Effect.gen(function* () { + const dir = yield* tempDir; + const archive = NodePath.join(dir, "global.tgz"); + // Lists as one empty file, yet GNU tar would extract 150 MiB of what follows. + NodeFS.writeFileSync( + archive, + NodeZlib.gzipSync( + Buffer.concat([ + tarEntry("pax_global_header", "g", Buffer.from("18 size=157286400\n")), + tarEntry("empty.txt", "0", Buffer.alloc(0)), + Buffer.alloc(1024), + ]), + ), + ); + const refused = yield* listArchive(archive).pipe(Effect.flip); + expect(refused.reason).toBe("invalid_archive"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -464,6 +599,7 @@ it.live("refuses an archive that expands past the size limit before extracting i const refused = yield* applyWorkFiles({ archivePath, stagingDir, + keptBackupsDir: NodePath.join(stagingDir, "..", "kept"), root: target, head: git(source, "rev-parse", "HEAD"), deletions: [], @@ -488,6 +624,7 @@ it.live("transfers into one checkout apply one at a time", () => return { archivePath: NodePath.join(dir, "work.tgz"), stagingDir: NodePath.join(dir, "staging"), + keptBackupsDir: NodePath.join(dir, "kept"), // The same checkout, named another way by every other send. root: index % 2 === 0 ? target : `${target}/.`, head, diff --git a/apps/server/src/peer/WorkFiles.ts b/apps/server/src/peer/WorkFiles.ts index 58302ed01b913..44d8ffe5335bd 100644 --- a/apps/server/src/peer/WorkFiles.ts +++ b/apps/server/src/peer/WorkFiles.ts @@ -5,6 +5,7 @@ import * as NodePath from "node:path"; import * as NodeStream from "node:stream"; import * as NodeZlib from "node:zlib"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; @@ -41,6 +42,17 @@ const SKIPPED_DIRECTORIES = new Set([ /** A repository's own folder; its hooks run on the next checkout, so no transfer writes into one. */ const isGitFolder = (segment: string) => segment.toLowerCase() === ".git"; +/** + * Names Windows may resolve to another one, `.git` among them: a trailing dot + * or space, an NTFS stream after a colon, or the 8.3 name `GIT~1`. Refused on + * every platform, as git's `is_ntfs_dotgit` does, since the sender's is unknown. + */ +const isWindowsAlias = (segment: string) => + segment.endsWith(".") || + segment.endsWith(" ") || + segment.includes(":") || + /^git~\d$/i.test(segment); + export class WorkFilesError extends Schema.TaggedError()("WorkFilesError", { reason: Schema.Literals(["over_limit", "head_mismatch", "conflict", "invalid_archive", "failed"]), message: Schema.String, @@ -307,7 +319,9 @@ export const isSafeRelativePath = (path: string) => !/^[A-Za-z]:/.test(path) && !path.includes("\\") && !path.includes("\0") && - path.split("/").every((segment) => segment !== ".." && !isGitFolder(segment)); + path + .split("/") + .every((segment) => segment !== ".." && !isGitFolder(segment) && !isWindowsAlias(segment)); interface ArchiveEntry { readonly path: string; @@ -440,8 +454,10 @@ const readArchiveEntries = async (archivePath: string) => { ) { throw invalid("The archive could not be read."); } - // Metadata for the entry after it: pax records, a global pax header, GNU long names. - if (flag === "x" || flag === "g" || flag === "L" || flag === "K") { + // GNU tar applies a global header's size to every later entry; T3 never writes one. + if (flag === "g") throw invalid("The archive has a global pax header."); + // Metadata for the entry after it: pax records and GNU long names. + if (flag === "x" || flag === "L" || flag === "K") { if (size > TAR_MAX_METADATA_BYTES) throw invalid("The archive has an oversized header."); collecting = { type: flag, size }; continue; @@ -502,7 +518,7 @@ export const listArchive = Effect.fn("WorkFiles.listArchive")(function* (archive try: () => readArchiveEntries(archivePath), catch: (error) => (isWorkFilesError(error) ? error : invalid("The archive could not be read.")), }); - const files: string[] = []; + const files: Array<{ readonly path: string; readonly size: number }> = []; for (const entry of entries) { const name = entry.path.startsWith("./") ? entry.path.slice(2) : entry.path; const path = name.endsWith("/") ? name.slice(0, -1) : name; @@ -510,18 +526,18 @@ export const listArchive = Effect.fn("WorkFiles.listArchive")(function* (archive if (!isSafeRelativePath(path)) { return yield* invalid(`The archive holds an unsafe path: "${entry.path}".`); } - if (entry.type === "file") files.push(path); + if (entry.type === "file") files.push({ path, size: entry.size }); } return files; }); -/** Checks the extracted tree is only directories and single-link files, exactly those listed. */ +/** Checks the extracted tree is only directories and single-link files, exactly those listed at their listed sizes. */ const verifyStaging = Effect.fn("WorkFiles.verifyStaging")(function* ( staging: string, - listed: ReadonlyArray, + listed: ReadonlyArray<{ readonly path: string; readonly size: number }>, ) { // Some tars change a name's Unicode normalization on the way to disk, as macOS bsdtar does. - const expected = new Set(listed.map((path) => path.normalize("NFC"))); + const expected = new Map(listed.map((file) => [file.path.normalize("NFC"), file.size])); const pending = [""]; let seen = 0; while (pending.length > 0) { @@ -540,7 +556,7 @@ const verifyStaging = Effect.fn("WorkFiles.verifyStaging")(function* ( stat === null || !stat.isFile() || stat.nlink > 1 || - !expected.has(relative.normalize("NFC")) + expected.get(relative.normalize("NFC")) !== stat.size ) { return yield* invalid(`The archive extracted an unexpected entry: ${relative}.`); } @@ -579,24 +595,13 @@ const targetConflict = Effect.fn("WorkFiles.targetConflict")(function* ( // Copying onto it would change its other names too. if (stat.nlink > 1) return "it is a hard link to another file there"; } - if (local === null) { - // Outside git nothing records local changes, so only an identical file may be replaced. - return incoming === null ? null : "it already exists there with other content"; - } + // Outside git nothing records local changes, so only an identical file may be replaced. + if (local === null) return "it already exists there with other content"; if (local.changed.has(path)) return "it has local changes there"; if (!local.tracked.has(path)) return "it is an untracked file there"; return null; }); -export interface ApplyWorkFilesInput { - readonly archivePath: string; - readonly stagingDir: string; - readonly root: string; - /** The source's HEAD; null when the source is not a git checkout. */ - readonly head: string | null; - readonly deletions: ReadonlyArray; -} - /** One lock per checkout, by its resolved path, held from the conflict checks through the copy. */ const checkoutLocks = new Map(); @@ -611,6 +616,24 @@ const checkoutLock = (root: string) => }), ); +/** Moves the backups of files a rollback could not restore out of staging, into a new dated folder. */ +const keepBackups = async ( + keptBackupsDir: string, + stamp: string, + backups: string, + unrestored: ReadonlyArray<{ readonly backup: string | null }>, +) => { + await NodeFSP.mkdir(keptBackupsDir, { recursive: true }); + const kept = await NodeFSP.mkdtemp(NodePath.join(keptBackupsDir, `${stamp}-`)); + for (const { backup } of unrestored) { + if (backup === null) continue; + const destination = NodePath.join(kept, NodePath.relative(backups, backup)); + await NodeFSP.mkdir(NodePath.dirname(destination), { recursive: true }); + await NodeFSP.rename(backup, destination); + } + return kept; +}; + /** * Copies the staged files into `root` and applies the deletions, backing up * each file it replaces or deletes. On any failure it puts those back and @@ -620,6 +643,9 @@ const copyIn = async (input: { readonly root: string; readonly staged: string; readonly backups: string; + readonly keptBackupsDir: string; + /** Names the folder kept backups go in. */ + readonly stamp: string; readonly files: ReadonlyArray; readonly deletions: ReadonlyArray; }) => { @@ -666,21 +692,30 @@ const copyIn = async (input: { } return deleted; } catch { - const unrestored: string[] = []; + const unrestored: Array<{ readonly path: string; readonly backup: string | null }> = []; for (const { destination, backup } of changed.toReversed()) { await ( backup === null ? NodeFSP.rm(destination, { force: true }) : NodeFSP.copyFile(backup, destination) - ).catch(() => unrestored.push(NodePath.relative(input.root, destination))); + ).catch(() => unrestored.push({ path: NodePath.relative(input.root, destination), backup })); } for (const folder of createdFolders.toReversed()) { await NodeFSP.rmdir(folder).catch(() => undefined); } + if (unrestored.length === 0) + throw failed(`Could not ${step} there; nothing was changed there.`); + const names = unrestored.map((file) => file.path).join(", "); + const kept = await keepBackups( + input.keptBackupsDir, + input.stamp, + input.backups, + unrestored, + ).catch(() => null); throw failed( - unrestored.length === 0 - ? `Could not ${step} there; nothing was changed there.` - : `Could not ${step} there, and could not put back ${unrestored.join(", ")}.`, + kept === null + ? `Could not ${step} there, and could not put back ${names}; their backups are lost.` + : `Could not ${step} there, and could not put back ${names}; their earlier contents are in ${kept}.`, ); } }; @@ -688,6 +723,8 @@ const copyIn = async (input: { export interface ApplyWorkFilesInput { readonly archivePath: string; readonly stagingDir: string; + /** Where backups a failed rollback could not put back are kept, in a dated folder. */ + readonly keptBackupsDir: string; readonly root: string; /** The source's HEAD; null when the source is not a git checkout. */ readonly head: string | null; @@ -702,19 +739,33 @@ export interface ApplyWorkFilesInput { */ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: ApplyWorkFilesInput) { const files = yield* listArchive(input.archivePath); + // A folder outside git has no record of what the source deleted. + if (input.head === null && input.deletions.length > 0) { + return yield* invalid("The files come from a folder outside git, which cannot send deletions."); + } for (const path of input.deletions) { if (!isSafeRelativePath(path)) { return yield* invalid(`A deletion names an unsafe path: "${path}".`); } } + // The sender keeps these behind, so another sender is not T3. + for (const path of [...files.map((file) => file.path), ...input.deletions]) { + if (looksLikeSecret(path)) { + return yield* invalid(`The work files name a credential file: "${path}".`); + } + } const lock = yield* checkoutLock(input.root); - return yield* Semaphore.withPermit(lock, applyLocked(input, files)); + // A half-applied copy cannot be left behind: once the lock is held, the apply + // and any rollback run to the end before an interruption lands, and only + // then are the lock and the caller's staging released. + return yield* Semaphore.withPermit(lock, Effect.uninterruptible(applyLocked(input, files))); }); const applyLocked = Effect.fn("WorkFiles.applyLocked")(function* ( input: ApplyWorkFilesInput, - files: ReadonlyArray, + listed: ReadonlyArray<{ readonly path: string; readonly size: number }>, ) { + const files = listed.map((file) => file.path); const staged = NodePath.join(input.stagingDir, "files"); const head = yield* gitHead(input.root); if (input.head !== null) { @@ -735,11 +786,19 @@ const applyLocked = Effect.fn("WorkFiles.applyLocked")(function* ( yield* fileSystemCall("create the staging folder", () => NodeFSP.mkdir(staged, { recursive: true }), ); + const needed = listed.reduce((total, file) => total + file.size, 0); + const space = yield* fileSystemCall("check free disk space", () => NodeFSP.statfs(staged)); + if (space.bavail * space.bsize < needed) { + return yield* new WorkFilesError({ + reason: "over_limit", + message: `The work files are ${formatMiB(needed)}, more than the free disk space there.`, + }); + } const extracted = yield* runProcess("tar", ["-xzf", input.archivePath, "-C", staged], { cwd: staged, }); if (extracted.code !== 0) return yield* invalid("The archive could not be extracted."); - yield* verifyStaging(staged, files); + yield* verifyStaging(staged, listed); const local = head === null ? null @@ -767,12 +826,15 @@ const applyLocked = Effect.fn("WorkFiles.applyLocked")(function* ( message: `Nothing was changed there, because these paths would overwrite local work: ${conflicts.slice(0, 20).join(", ")}${conflicts.length > 20 ? `, and ${conflicts.length - 20} more` : ""}.`, }); } + const stamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-"); const deleted = yield* Effect.tryPromise({ try: () => copyIn({ root: input.root, staged, backups: NodePath.join(input.stagingDir, "backup"), + keptBackupsDir: input.keptBackupsDir, + stamp, files, deletions: input.deletions, }), diff --git a/apps/server/src/peer/WorkFilesTransfer.ts b/apps/server/src/peer/WorkFilesTransfer.ts index ae484037ebdf0..a722bb8dc6a58 100644 --- a/apps/server/src/peer/WorkFilesTransfer.ts +++ b/apps/server/src/peer/WorkFilesTransfer.ts @@ -336,6 +336,7 @@ const make = Effect.gen(function* () { const applied = yield* applyWorkFiles({ archivePath, stagingDir, + keptBackupsDir: NodePath.join(config.stateDir, "work-files-backups"), root: ticket.entry.root, head: ticket.entry.head, deletions: ticket.entry.deletions, From 5c914f62bb6e9af8f6f63fee9f674409f83a52e0 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:17:24 +0100 Subject: [PATCH 05/14] chore: agent context budget counts the workFiles field --- apps/server/src/provider/agentContextBudget.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 65f2b6b6c451e..c5d535ed4493d 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5597, "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 48094 + "mcpToolListJsonBytes": 48295 } From 31eb5c2ad5b64c126c78759f3eeeb1d8ca254b2f Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:22:37 +0100 Subject: [PATCH 06/14] fix: work files with a colon or a trailing dot travel again, and only the copy ignores an interruption The Windows rule refused every name with a colon or a trailing dot or space, and the sender dropped those files without saying so. It now refuses only names Windows resolves to .git. Only the copy into the checkout is uninterruptible, so a hung git process can still be cancelled and the checkout lock is released. --- apps/server/src/peer/WorkFiles.test.ts | 20 ++++++++++++++++---- apps/server/src/peer/WorkFiles.ts | 25 ++++++++++++++----------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/apps/server/src/peer/WorkFiles.test.ts b/apps/server/src/peer/WorkFiles.test.ts index 7831d508b2c98..daa0c4b4a47dd 100644 --- a/apps/server/src/peer/WorkFiles.test.ts +++ b/apps/server/src/peer/WorkFiles.test.ts @@ -199,11 +199,23 @@ it("keeps archive and deletion paths inside the checkout on every platform", () ".git::$INDEX_ALLOCATION/hooks/post-checkout", "GIT~1/config", "sub/git~2/hooks/pre-commit", - "a/b:stream", + ".Git. ./config", ]) { expect(isSafeRelativePath(path), path).toBe(false); } - for (const path of ["a", "a/b.txt", ".github/x.yml", "a..b", ".gitignore", "x.git/y"]) { + for (const path of [ + "a", + "a/b.txt", + ".github/x.yml", + "a..b", + ".gitignore", + "x.git/y", + // Ordinary names that only look odd on Windows still travel. + "log-10:30.txt", + "draft.", + "notes ", + "a/b:stream", + ]) { expect(isSafeRelativePath(path), path).toBe(true); } }); @@ -446,7 +458,7 @@ it.live("a rollback that cannot put a file back keeps its backup and names where }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.live("an apply interrupted after it takes the lock finishes before it ends", () => +it.live("an apply interrupted while it copies finishes the copy before it ends", () => Effect.gen(function* () { const { source, target, archivePath, stagingDir } = yield* pair({ "a.ts": "a" }); const paths = Array.from({ length: 200 }, (_, index) => `many/${index}.ts`); @@ -456,7 +468,7 @@ it.live("an apply interrupted after it takes the lock finishes before it ends", const lockTaken = new Promise((resolve) => (locked = resolve)); const tracer = Tracer.make({ span(options) { - if (options.name === "WorkFiles.applyLocked") locked(); + if (options.name === "WorkFiles.copyIn") locked(); return new Tracer.NativeSpan(options); }, }); diff --git a/apps/server/src/peer/WorkFiles.ts b/apps/server/src/peer/WorkFiles.ts index 44d8ffe5335bd..4003897af69af 100644 --- a/apps/server/src/peer/WorkFiles.ts +++ b/apps/server/src/peer/WorkFiles.ts @@ -43,15 +43,17 @@ const SKIPPED_DIRECTORIES = new Set([ const isGitFolder = (segment: string) => segment.toLowerCase() === ".git"; /** - * Names Windows may resolve to another one, `.git` among them: a trailing dot - * or space, an NTFS stream after a colon, or the 8.3 name `GIT~1`. Refused on - * every platform, as git's `is_ntfs_dotgit` does, since the sender's is unknown. + * Names Windows resolves to `.git`: trailing dots or spaces, an NTFS stream after + * a colon, or the 8.3 name `GIT~1`. Refused on every platform, as git's + * `is_ntfs_dotgit` does, since the receiver's platform is unknown to the sender. */ -const isWindowsAlias = (segment: string) => - segment.endsWith(".") || - segment.endsWith(" ") || - segment.includes(":") || - /^git~\d$/i.test(segment); +const isWindowsGitAlias = (segment: string) => { + const name = segment + .toLowerCase() + .split(":")[0]! + .replace(/[. ]+$/, ""); + return name === ".git" || /^git~\d$/.test(name); +}; export class WorkFilesError extends Schema.TaggedError()("WorkFilesError", { reason: Schema.Literals(["over_limit", "head_mismatch", "conflict", "invalid_archive", "failed"]), @@ -321,7 +323,7 @@ export const isSafeRelativePath = (path: string) => !path.includes("\0") && path .split("/") - .every((segment) => segment !== ".." && !isGitFolder(segment) && !isWindowsAlias(segment)); + .every((segment) => segment !== ".." && !isGitFolder(segment) && !isWindowsGitAlias(segment)); interface ArchiveEntry { readonly path: string; @@ -758,7 +760,7 @@ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: App // A half-applied copy cannot be left behind: once the lock is held, the apply // and any rollback run to the end before an interruption lands, and only // then are the lock and the caller's staging released. - return yield* Semaphore.withPermit(lock, Effect.uninterruptible(applyLocked(input, files))); + return yield* Semaphore.withPermit(lock, applyLocked(input, files)); }); const applyLocked = Effect.fn("WorkFiles.applyLocked")(function* ( @@ -827,6 +829,7 @@ const applyLocked = Effect.fn("WorkFiles.applyLocked")(function* ( }); } const stamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-"); + // The caller removes staging when this ends, so a started copy runs to its end or rollback. const deleted = yield* Effect.tryPromise({ try: () => copyIn({ @@ -839,6 +842,6 @@ const applyLocked = Effect.fn("WorkFiles.applyLocked")(function* ( deletions: input.deletions, }), catch: (error) => (isWorkFilesError(error) ? error : failed("Could not apply the work files.")), - }); + }).pipe(Effect.withSpan("WorkFiles.copyIn"), Effect.uninterruptible); return { files: files.length, deletions: deleted }; }); From 7c8b2c6dc312d2ef87f12ad3180f889bd8a5244e Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:45:25 +0100 Subject: [PATCH 07/14] feat: Work files bring secrets along Continue on another machine and delegate_task workFiles: "transfer" now send every uncommitted and untracked file, .env files and keys included. The sender no longer leaves secret-looking files behind and the receiver no longer refuses them, so leftBehindCount leaves the summary. Git-ignored files still stay, and the .git, path, link, size, conflict, access and all-or-nothing checks stay. --- apps/server/src/peer/WorkFiles.test.ts | 41 ++++++++----------- apps/server/src/peer/WorkFiles.ts | 37 +---------------- .../server/src/peer/WorkFilesTransfer.test.ts | 7 ++-- apps/server/src/peer/WorkFilesTransfer.ts | 1 - .../src/provider/agentContextBudget.json | 2 +- .../chat/ContinueOnMachineDialog.tsx | 6 +-- docs/user/remote-access.md | 7 ++-- packages/contracts/src/orchestratorMcp.ts | 2 +- packages/contracts/src/workFiles.ts | 2 - 9 files changed, 28 insertions(+), 77 deletions(-) diff --git a/apps/server/src/peer/WorkFiles.test.ts b/apps/server/src/peer/WorkFiles.test.ts index daa0c4b4a47dd..547cb32856038 100644 --- a/apps/server/src/peer/WorkFiles.test.ts +++ b/apps/server/src/peer/WorkFiles.test.ts @@ -94,7 +94,7 @@ const writeArchive = (root: string, files: ReadonlyArray, archivePath: s ); it.live( - "a git checkout carries its changed, staged, untracked and deleted files, not its secrets", + "a git checkout carries its changed, staged, untracked and deleted files, secrets included", () => Effect.gen(function* () { const root = yield* tempDir; @@ -113,25 +113,25 @@ it.live( write(root, ".env.local", "TOKEN=1"); write(root, "certs/server.pem", "pem"); NodeFS.rmSync(NodePath.join(root, "src/old.ts")); - // A deleted secret stays where it is on both sides. NodeFS.rmSync(NodePath.join(root, "config/.env")); NodeFS.symlinkSync("README.md", NodePath.join(root, "link.md")); const selection = yield* selectWorkFiles(root); expect(selection.head).toBe(head); expect(selection.files.map((file) => file.path)).toEqual([ + ".env.local", + "certs/server.pem", "notes/new.md", "src/app.ts", "src/staged.ts", ]); - expect(selection.deletions).toEqual(["src/old.ts"]); - expect(selection.leftBehind).toEqual([".env.local", "certs/server.pem", "config/.env"]); - expect(selection.totalBytes).toBe(3 + 3 + 6); + expect(selection.deletions).toEqual(["config/.env", "src/old.ts"]); + expect(selection.totalBytes).toBe(7 + 3 + 3 + 3 + 6); expect(selection.refusal).toBeNull(); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.live("a folder outside git carries every file but dependencies, build output and secrets", () => +it.live("a folder outside git carries every file but dependencies and build output", () => Effect.gen(function* () { const root = yield* tempDir; write(root, "index.html", "

"); @@ -145,9 +145,13 @@ it.live("a folder outside git carries every file but dependencies, build output const selection = yield* selectWorkFiles(root); expect(selection.head).toBeNull(); - expect(selection.files.map((file) => file.path)).toEqual(["index.html", "src/main.js"]); + expect(selection.files.map((file) => file.path)).toEqual([ + "deploy/.netrc", + "id_rsa", + "index.html", + "src/main.js", + ]); expect(selection.deletions).toEqual([]); - expect(selection.leftBehind).toEqual(["deploy/.netrc", "id_rsa"]); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -168,17 +172,6 @@ it.live("refuses a set over either limit with its numbers", () => expect((yield* selectWorkFiles(many)).refusal).toMatch( /^The work files are more than 5,000 files and 0\.0 MiB; the limit is 5,000 files/, ); - - // Secrets stay behind and do not count, so they cannot push later files out of the walk. - const secrets = yield* tempDir; - for (let folder = 0; folder < 10; folder++) { - for (let index = 0; index < 400; index++) write(secrets, `d${folder}/${index}`, ""); - for (let index = 0; index < 200; index++) write(secrets, `d${folder}/${index}.pem`, ""); - } - const underLimit = yield* selectWorkFiles(secrets); - expect(underLimit.refusal).toBeNull(); - expect(underLimit.files).toHaveLength(4_000); - expect(underLimit.leftBehind).toHaveLength(2_000); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -490,7 +483,7 @@ it.live("an apply interrupted while it copies finishes the copy before it ends", }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.live("refuses deletions from a folder outside git, and secret names from any sender", () => +it.live("refuses deletions from a folder outside git, and applies a secret file's deletion", () => Effect.gen(function* () { const target = yield* tempDir; const scratch = yield* tempDir; @@ -518,15 +511,15 @@ it.live("refuses deletions from a folder outside git, and secret names from any "a.ts": "a", "config/.env": "TOKEN=0", }); - const secret = yield* applyWorkFiles({ + const applied = yield* applyWorkFiles({ ...input, stagingDir, root: checkout, head: git(source, "rev-parse", "HEAD"), deletions: ["config/.env"], - }).pipe(Effect.flip); - expect(secret.reason).toBe("invalid_archive"); - expect(NodeFS.existsSync(NodePath.join(checkout, "config/.env"))).toBe(true); + }); + expect(applied).toEqual({ files: 1, deletions: 1 }); + expect(NodeFS.existsSync(NodePath.join(checkout, "config/.env"))).toBe(false); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/peer/WorkFiles.ts b/apps/server/src/peer/WorkFiles.ts index 4003897af69af..94cddc23b60d1 100644 --- a/apps/server/src/peer/WorkFiles.ts +++ b/apps/server/src/peer/WorkFiles.ts @@ -64,27 +64,12 @@ const isWorkFilesError = Schema.is(WorkFilesError); const failed = (message: string) => new WorkFilesError({ reason: "failed", message }); -/** Files that look like credentials never leave the machine they are on. */ -const looksLikeSecret = (path: string) => { - const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase(); - return ( - name.startsWith(".env") || - name.endsWith(".pem") || - name.endsWith(".key") || - name.endsWith(".p12") || - name.startsWith("id_rsa") || - name === ".npmrc" || - name === ".netrc" - ); -}; - export interface WorkFilesSelection { readonly root: string; /** The commit the files apply to; null outside git, "" in a repository with no commits. */ readonly head: string | null; readonly files: ReadonlyArray<{ readonly path: string; readonly size: number }>; readonly deletions: ReadonlyArray; - readonly leftBehind: ReadonlyArray; readonly totalBytes: number; /** Why the set cannot go, with the numbers; nothing is sent when set. */ readonly refusal: string | null; @@ -180,15 +165,11 @@ const gitTrackedPaths = Effect.fn("WorkFiles.gitTrackedPaths")(function* (cwd: s return new Set(nulSeparated(tracked.stdout)); }); -/** - * Every file under `root` outside skipped directories, stopping once past the - * count limit. Secrets stay behind, so they do not count toward it. - */ +/** Every file under `root` outside skipped directories, stopping once past the count limit. */ const walk = Effect.fn("WorkFiles.walk")(function* (root: string) { const found: string[] = []; const pending = [""]; - let eligible = 0; - while (pending.length > 0 && eligible <= WORK_FILES_MAX_COUNT) { + while (pending.length > 0 && found.length <= WORK_FILES_MAX_COUNT) { const directory = pending.pop()!; const entries = yield* fileSystemCall("read the working directory", () => NodeFSP.readdir(NodePath.join(root, directory), { withFileTypes: true }), @@ -201,7 +182,6 @@ const walk = Effect.fn("WorkFiles.walk")(function* (root: string) { } } else if (entry.isFile()) { found.push(relative); - if (!looksLikeSecret(relative)) eligible += 1; } } } @@ -214,7 +194,6 @@ export const selectWorkFiles = Effect.fn("WorkFiles.select")(function* (root: st const candidates = head === null ? yield* walk(root) : [...(yield* gitChangedPaths(root))]; const files: Array<{ path: string; size: number }> = []; const deletions: string[] = []; - const leftBehind: string[] = []; const inodes = new Map(); let totalBytes = 0; for (const path of candidates.toSorted()) { @@ -223,11 +202,6 @@ export const selectWorkFiles = Effect.fn("WorkFiles.select")(function* (root: st const stat = yield* lstatOrNull(NodePath.join(root, path)); // Symlinks and submodule directories are not work files. if (stat !== null && !stat.isFile()) continue; - // A secret is neither sent nor deleted there. - if (looksLikeSecret(path)) { - leftBehind.push(path); - continue; - } if (stat === null) { if (head !== null) deletions.push(path); continue; @@ -255,7 +229,6 @@ export const selectWorkFiles = Effect.fn("WorkFiles.select")(function* (root: st head, files, deletions, - leftBehind, totalBytes, refusal, } satisfies WorkFilesSelection; @@ -750,12 +723,6 @@ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: App return yield* invalid(`A deletion names an unsafe path: "${path}".`); } } - // The sender keeps these behind, so another sender is not T3. - for (const path of [...files.map((file) => file.path), ...input.deletions]) { - if (looksLikeSecret(path)) { - return yield* invalid(`The work files name a credential file: "${path}".`); - } - } const lock = yield* checkoutLock(input.root); // A half-applied copy cannot be left behind: once the lock is held, the apply // and any rollback run to the end before an interruption lands, and only diff --git a/apps/server/src/peer/WorkFilesTransfer.test.ts b/apps/server/src/peer/WorkFilesTransfer.test.ts index 171a6fcc3973d..b1ec6b4177b34 100644 --- a/apps/server/src/peer/WorkFilesTransfer.test.ts +++ b/apps/server/src/peer/WorkFilesTransfer.test.ts @@ -161,16 +161,15 @@ it.live("sends a checkout's work to the same commit on the box, leaving no archi const { peer, receiveDir } = yield* serveBox(target); write(source, "app.ts", "v2"); write(source, "src/new.ts", "new"); - write(source, ".env", "SECRET=1"); + write(source, ".env.local", "TOKEN=1"); NodeFS.rmSync(NodePath.join(source, "old.ts")); const send = yield* laptopSending(peer, source, "auto"); - expect(yield* send).toEqual({ files: 2, deletions: 1 }); + expect(yield* send).toEqual({ files: 3, deletions: 1 }); expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v2"); expect(NodeFS.readFileSync(NodePath.join(target, "src/new.ts"), "utf8")).toBe("new"); expect(NodeFS.existsSync(NodePath.join(target, "old.ts"))).toBe(false); - // The secret stayed here. - expect(NodeFS.existsSync(NodePath.join(target, ".env"))).toBe(false); + expect(NodeFS.readFileSync(NodePath.join(target, ".env.local"), "utf8")).toBe("TOKEN=1"); expect(leftovers(receiveDir)).toEqual([]); }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/peer/WorkFilesTransfer.ts b/apps/server/src/peer/WorkFilesTransfer.ts index a722bb8dc6a58..6b0d1d5381c39 100644 --- a/apps/server/src/peer/WorkFilesTransfer.ts +++ b/apps/server/src/peer/WorkFilesTransfer.ts @@ -89,7 +89,6 @@ export const summaryOf = (selection: WorkFilesSelection): WorkFilesSummary => ({ fileCount: selection.files.length, totalBytes: selection.totalBytes, deletionCount: selection.deletions.length, - leftBehindCount: selection.leftBehind.length, refusal: selection.refusal, }); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index c5d535ed4493d..267f9143117aa 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5597, "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 48295 + "mcpToolListJsonBytes": 48281 } diff --git a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx index b927354bf4bfa..bff00b450200c 100644 --- a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx +++ b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx @@ -61,11 +61,7 @@ function workFilesDescription(summary: WorkFilesSummary): string { summary.deletionCount === 0 ? "" : ` and ${summary.deletionCount.toLocaleString()} ${summary.deletionCount === 1 ? "deletion" : "deletions"}`; - const secrets = - summary.leftBehindCount === 0 - ? "Files that look like secrets stay on this machine." - : `${summary.leftBehindCount.toLocaleString()} ${summary.leftBehindCount === 1 ? "file that looks" : "files that look"} like secrets ${summary.leftBehindCount === 1 ? "stays" : "stay"} on this machine.`; - return `${files}${deletions} (${formatBytes(summary.totalBytes)}) from ${summary.directory}. ${secrets}`; + return `${files}${deletions} (${formatBytes(summary.totalBytes)}) from ${summary.directory}. Every uncommitted and untracked file goes, secrets included. Git-ignored files stay on this machine.`; } function ContinueOnMachineDialog({ diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 1110492e48730..7930c23dd1d9e 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -370,11 +370,10 @@ conversation, and this thread stays as it is. If the thread's folder has uncommitted changes, you choose whether to transfer them too. An agent can ask for the same with `workFiles: "transfer"` on `delegate_task`. -- In a git checkout, the changed, staged, deleted and untracked (not ignored) - files go, and the other machine's checkout must be on the same commit. +- In a git checkout, the changed, staged, deleted and untracked files go, + secrets such as an untracked `.env` file included. Git-ignored files stay on + this machine, and the other machine's checkout must be on the same commit. Outside git, every file goes except `.git`, `node_modules` and build output. -- Files that look like secrets, such as `.env` files and private keys, stay on - this machine. - Nothing is changed there if any of those files has its own local changes there. The transfer is at most 100 MiB and 5,000 files. - The link to the other machine needs Auto-accept edits access or broader. diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 7af1e0dacdb36..4f34d35f048a3 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -198,7 +198,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({ workFiles: Schema.optional( WorkFilesMode.annotate({ description: - "Remote target only. 'transfer': first copy your uncommitted files (not secrets) to that checkout, which must be on your commit.", + "Remote target only. 'transfer': first copy your uncommitted files to that checkout, which must be on your commit.", }), ), }); diff --git a/packages/contracts/src/workFiles.ts b/packages/contracts/src/workFiles.ts index 3e5bff281d764..0fbd3b5f1a531 100644 --- a/packages/contracts/src/workFiles.ts +++ b/packages/contracts/src/workFiles.ts @@ -12,8 +12,6 @@ export const WorkFilesSummary = Schema.Struct({ fileCount: Schema.Int, totalBytes: Schema.Int, deletionCount: Schema.Int, - /** Files that look like secrets, which stay on this machine. */ - leftBehindCount: Schema.Int, /** Why the files cannot go, with the numbers; null when they can. */ refusal: Schema.NullOr(Schema.String), }); From 1f0b1597095b115c1511059921803b12ee0340cb Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:45:26 +0100 Subject: [PATCH 08/14] feat(web): Continue on another machine opens the new thread When this window is connected to the target machine, the app waits for the new thread to arrive and opens it, which also reveals it in the sidebar. A saved machine that is switched off gets a toast action that turns it on and opens the thread. A machine this window has never connected to gets a toast action that opens Add environment at the address the peer link uses, so the user pairs with a code from that machine. The peer link's own credential stays on the server. --- .../chat/ContinueOnMachineDialog.tsx | 92 ++++++++++++++++--- .../chat/continueOnMachine.logic.test.ts | 29 ++++++ .../chat/continueOnMachine.logic.ts | 22 +++++ .../settings/AddEnvironmentDialog.tsx | 5 +- .../settings/ConnectionsSettings.tsx | 11 ++- .../src/routes/_chat.settings.connections.tsx | 3 + docs/user/remote-access.md | 5 + 7 files changed, 150 insertions(+), 17 deletions(-) create mode 100644 apps/web/src/components/chat/continueOnMachine.logic.test.ts create mode 100644 apps/web/src/components/chat/continueOnMachine.logic.ts diff --git a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx index bff00b450200c..a09a523048b46 100644 --- a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx +++ b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx @@ -13,9 +13,11 @@ import type { import { useNavigate } from "@tanstack/react-router"; import { useState } from "react"; +import { environmentCatalog } from "~/connection/catalog"; import { formatBytes } from "~/lib/formatBytes"; import { appAtomRegistry } from "~/rpc/atomRegistry"; -import { readEnvironmentServerConfigLoaded } from "~/state/entities"; +import { waitForThreadShell } from "~/state/entities"; +import { readEnvironment } from "~/state/environments"; import { peerLinkEnvironment } from "~/state/peerLinks"; import { useEnvironmentQuery } from "~/state/query"; import { useAtomCommand } from "~/state/use-atom-command"; @@ -31,8 +33,12 @@ import { } from "../ui/alert-dialog"; import { Button } from "../ui/button"; import { stackedThreadToast, toastManager } from "../ui/toast"; +import { continuedThreadFollowThrough } from "./continueOnMachine.logic"; import { continueOnMachineThreadAtom } from "./continueOnMachineDialogState"; +/** A new thread reaches this window over the target's own connection, which may be reconnecting. */ +const CONTINUED_THREAD_WAIT_MS = 15_000; + export function ContinueOnMachineDialogHost() { const threadRef = useAtomValue(continueOnMachineThreadAtom); if (threadRef === null) return null; @@ -79,6 +85,9 @@ function ContinueOnMachineDialog({ const continueThread = useAtomCommand(peerLinkEnvironment.continueThread, { reportFailure: false, }); + const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, { + reportFailure: false, + }); const [stage, setStage] = useState({ kind: "pick" }); const reachable = (links.data?.links ?? []).filter((link) => link.status === "reachable"); const busy = stage.kind === "checking" || stage.kind === "running"; @@ -105,32 +114,85 @@ function ContinueOnMachineDialog({ } const continued = result.value; const target = scopeThreadRef(continued.environmentId, continued.threadId); - // This client can open it only while it is connected to that machine too. - const canOpen = readEnvironmentServerConfigLoaded(continued.environmentId); + const openThread = () => + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(target) }); + // Opens the thread as a new local one opens, once this window's connection there has it. + const openWhenItArrives = async () => { + if (await waitForThreadShell(target, CONTINUED_THREAD_WAIT_MS)) { + openThread(); + return; + } + toastManager.add( + stackedThreadToast({ + type: "warning", + title: `The thread on ${continued.label} has not reached this window yet`, + description: `Check ${continued.label} in Settings → Connections, then open it.`, + actionProps: { children: "Open thread", onClick: openThread }, + data: { hideCopyButton: true }, + }), + ); + }; + const turnOnAndOpen = async () => { + const enabled = await setEnvironmentEnabled({ + environmentId: continued.environmentId, + enabled: true, + }); + if (enabled._tag === "Failure") { + if (!isAtomCommandInterrupted(enabled)) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Could not turn on ${continued.label}`, + description: failureMessage(squashAtomCommandFailure(enabled)), + }), + ); + } + return; + } + await openWhenItArrives(); + }; + const saved = readEnvironment(continued.environmentId); + const followThrough = continuedThreadFollowThrough({ + saved: saved === null ? null : { enabled: saved.entry.enabled }, + linkUrls: link.urls, + }); + const picked = + mode === "transfer" + ? `A new thread there picked up this one, with ${continued.transferredFiles.toLocaleString()} work files.` + : "A new thread there picked up this one."; toastManager.add( stackedThreadToast({ type: "success", title: `Continued on ${continued.label}`, description: - mode === "transfer" - ? `A new thread there picked up this one, with ${continued.transferredFiles.toLocaleString()} work files.` - : "A new thread there picked up this one.", - ...(canOpen + followThrough.kind === "open" + ? picked + : followThrough.kind === "turn-on" + ? `${picked} Turn on ${continued.label} here to open it.` + : `${picked} Connect this window to ${continued.label} to open it.`, + ...(followThrough.kind === "turn-on" ? { actionProps: { - children: "Open thread", - onClick: () => { - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(target), - }); - }, + children: `Turn on ${continued.label}`, + onClick: () => void turnOnAndOpen(), }, } - : {}), + : followThrough.kind === "connect" + ? { + actionProps: { + children: `Connect ${continued.label}`, + onClick: () => + void navigate({ + to: "/settings/connections", + search: followThrough.host === null ? {} : { connect: followThrough.host }, + }), + }, + } + : {}), data: { hideCopyButton: true }, }), ); + if (followThrough.kind === "open") await openWhenItArrives(); }; const choose = async (link: PeerLinkSummary) => { diff --git a/apps/web/src/components/chat/continueOnMachine.logic.test.ts b/apps/web/src/components/chat/continueOnMachine.logic.test.ts new file mode 100644 index 0000000000000..447473b4220aa --- /dev/null +++ b/apps/web/src/components/chat/continueOnMachine.logic.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { continuedThreadFollowThrough } from "./continueOnMachine.logic"; + +describe("continuedThreadFollowThrough", () => { + it.each([ + ["a machine this window has on", { enabled: true }, { kind: "open" }], + ["a machine this window has switched off", { enabled: false }, { kind: "turn-on" }], + [ + "a machine this window does not know", + null, + { kind: "connect", host: "https://box.example.test" }, + ], + ] as const)("follows through to %s", (_name, saved, expected) => { + expect( + continuedThreadFollowThrough({ + saved, + linkUrls: ["https://box.example.test", "https://box-alt.example.test"], + }), + ).toEqual(expected); + }); + + it("asks for an address when the link has none to offer", () => { + expect(continuedThreadFollowThrough({ saved: null, linkUrls: [] })).toEqual({ + kind: "connect", + host: null, + }); + }); +}); diff --git a/apps/web/src/components/chat/continueOnMachine.logic.ts b/apps/web/src/components/chat/continueOnMachine.logic.ts new file mode 100644 index 0000000000000..2894d073cd789 --- /dev/null +++ b/apps/web/src/components/chat/continueOnMachine.logic.ts @@ -0,0 +1,22 @@ +/** + * How this window gets to a thread another machine started. The source server reaches that + * machine through its own peer link, which this window cannot use, so the window opens the + * thread only through a connection of its own. + */ +export type ContinuedThreadFollowThrough = + /** This window has the machine on: open the thread once it arrives. */ + | { readonly kind: "open" } + /** This window has the machine saved but switched off. */ + | { readonly kind: "turn-on" } + /** This window does not know the machine: pair with it at the address the link uses. */ + | { readonly kind: "connect"; readonly host: string | null }; + +export function continuedThreadFollowThrough(input: { + /** This window's saved connection to the machine, if any. */ + readonly saved: { readonly enabled: boolean } | null; + /** The addresses the source server linked the machine at. */ + readonly linkUrls: ReadonlyArray; +}): ContinuedThreadFollowThrough { + if (input.saved === null) return { kind: "connect", host: input.linkUrls[0] ?? null }; + return input.saved.enabled ? { kind: "open" } : { kind: "turn-on" }; +} diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx index ed366c4b03e7c..466f4e4950396 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx @@ -74,6 +74,7 @@ const sshHostSuggestionValue = (target: DesktopDiscoveredSshHost) => export function AddEnvironmentDialog({ open, routeTarget, + initialHost = null, error, savedEnvironments, onOpenChange, @@ -81,6 +82,8 @@ export function AddEnvironmentDialog({ }: { readonly open: boolean; readonly routeTarget: EnvironmentPresentation | null; + /** The address to pair with when the dialog mounts open. */ + readonly initialHost?: string | null; readonly error: string | null; readonly savedEnvironments: ReadonlyArray; readonly onOpenChange: (open: boolean) => void; @@ -114,7 +117,7 @@ export function AddEnvironmentDialog({ return keys; })(); const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote"); - const [savedBackendHost, setSavedBackendHost] = useState(""); + const [savedBackendHost, setSavedBackendHost] = useState(open ? (initialHost ?? "") : ""); const [savedBackendPairingCode, setSavedBackendPairingCode] = useState(""); const [savedBackendSshHost, setSavedBackendSshHost] = useState(""); const [savedBackendSshUsername, setSavedBackendSshUsername] = useState(""); diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index da529e44c3515..0d5e8d7e58b6d 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -330,7 +330,15 @@ function ConnectionsSettingsContent({ string | null >(null); const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false); - const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false); + // A link that names an address to pair with opens Add environment on it. The settings + // layout remounts this page when the link changes. + const connectHost = useSearch({ + strict: false, + select: (search) => (typeof search.connect === "string" ? search.connect : null), + }); + const [addBackendDialogOpen, setAddBackendDialogOpen] = useState( + view === "environments" && connectHost !== null, + ); const [routeTarget, setRouteTarget] = useState(null); const [savedBackendError, setSavedBackendError] = useState(null); const handleAddBackendDialogOpenChange = (open: boolean) => { @@ -1606,6 +1614,7 @@ function ConnectionsSettingsContent({ ) => + typeof raw.connect === "string" && raw.connect.trim() ? { connect: raw.connect.trim() } : {}, component: SettingsConnectionsRoute, }); diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 7930c23dd1d9e..936ccbb7e491c 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -370,6 +370,11 @@ conversation, and this thread stays as it is. If the thread's folder has uncommitted changes, you choose whether to transfer them too. An agent can ask for the same with `workFiles: "transfer"` on `delegate_task`. +The app opens the new thread when this window is connected to that machine too. +If the machine is saved here but switched off, the confirmation offers to turn +it on. If this window has never connected to it, the confirmation offers to +connect it at the address the link uses, with a pairing code from that machine. + - In a git checkout, the changed, staged, deleted and untracked files go, secrets such as an untracked `.env` file included. Git-ignored files stay on this machine, and the other machine's checkout must be on the same commit. From ea3513c37844051d2b32109e123d3590bbd64057 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:59:08 +0100 Subject: [PATCH 09/14] fix(web): a Connect link opens Add environment with its address when Connections is already open --- .../AddEnvironmentDialog.browser.test.tsx | 23 +++++++++++++++++++ .../settings/AddEnvironmentDialog.tsx | 9 ++++++++ .../settings/ConnectionsSettings.tsx | 12 ++++++++-- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx index 6b4d0a08a629f..c8b3768d5323e 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx @@ -97,6 +97,29 @@ describe("AddEnvironmentDialog", () => { await expectDefaultModeAfterReopen(); }); + it("fills in each new address a Connect link names, also while it is open", async () => { + using _bridge = setup(); + const dialog = (initialHost: string) => ( + + {}} + onErrorChange={() => {}} + initialHost={initialHost} + /> + + ); + await using screen = await render(dialog("https://studio.example.com")); + const host = page.getByPlaceholder("backend.example.com"); + await expect.element(host).toHaveValue("https://studio.example.com"); + + await screen.rerender(dialog("https://devbox.example.com")); + await expect.element(host).toHaveValue("https://devbox.example.com"); + }); + it("clears the form after dismissing it on SSH", async () => { using _bridge = setup(); await using _screen = await render(); diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.tsx index 466f4e4950396..c90f250f3ec33 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.tsx @@ -125,6 +125,15 @@ export function AddEnvironmentDialog({ const [sshHostSuggestionsOpen, setSshHostSuggestionsOpen] = useState(false); const highlightedSshHostRef = useRef(undefined); const [isAddingSavedBackend, setIsAddingSavedBackend] = useState(false); + const [lastOpen, setLastOpen] = useState(open); + const [lastInitialHost, setLastInitialHost] = useState(initialHost); + if (open !== lastOpen || initialHost !== lastInitialHost) { + const opened = open && !lastOpen; + setLastOpen(open); + setLastInitialHost(initialHost); + if (open && initialHost !== null && (opened || initialHost !== lastInitialHost)) + setSavedBackendHost(initialHost); + } const savedBackendSessionRef = useRef(0); const isSshDiscoveryActive = desktopBridge !== undefined && open && savedBackendMode === "ssh"; const desktopSshHosts = useEnvironmentQuery( diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 0d5e8d7e58b6d..81203d1eee21c 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -330,8 +330,8 @@ function ConnectionsSettingsContent({ string | null >(null); const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false); - // A link that names an address to pair with opens Add environment on it. The settings - // layout remounts this page when the link changes. + // A link that names an address to pair with opens Add environment on it, also when this + // page is already open. const connectHost = useSearch({ strict: false, select: (search) => (typeof search.connect === "string" ? search.connect : null), @@ -341,6 +341,14 @@ function ConnectionsSettingsContent({ ); const [routeTarget, setRouteTarget] = useState(null); const [savedBackendError, setSavedBackendError] = useState(null); + const [openedForConnectHost, setOpenedForConnectHost] = useState(connectHost); + if (connectHost !== openedForConnectHost) { + setOpenedForConnectHost(connectHost); + if (view === "environments" && connectHost !== null) { + setAddBackendDialogOpen(true); + setRouteTarget(null); + } + } const handleAddBackendDialogOpenChange = (open: boolean) => { setAddBackendDialogOpen(open); if (open) { From 82e118e63ee1c12b5f91eb406c08840cbe08b416 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:03:17 +0100 Subject: [PATCH 10/14] fix(web): a continued thread opens only if you stayed put, and Connect links keep just the address Waiting for the continued thread no longer pulls someone who moved on to it; they get an Open thread button. The connect search param keeps only the origin and is cleared when Add environment closes. The files prompt reads right for folders outside git too. --- .../chat/ContinueOnMachineDialog.tsx | 25 +++++++++++++------ .../chat/continueOnMachine.logic.test.ts | 13 +++++++++- .../chat/continueOnMachine.logic.ts | 12 +++++++++ .../ConnectionsSettings.logic.test.ts | 13 ++++++++++ .../settings/ConnectionsSettings.logic.ts | 14 +++++++++++ .../settings/ConnectionsSettings.tsx | 5 +++- .../src/routes/_chat.settings.connections.tsx | 8 ++++-- 7 files changed, 79 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx index a09a523048b46..153845e0f3462 100644 --- a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx +++ b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx @@ -10,7 +10,7 @@ import type { WorkFilesMode, WorkFilesSummary, } from "@t3tools/contracts"; -import { useNavigate } from "@tanstack/react-router"; +import { useNavigate, useRouter } from "@tanstack/react-router"; import { useState } from "react"; import { environmentCatalog } from "~/connection/catalog"; @@ -33,7 +33,7 @@ import { } from "../ui/alert-dialog"; import { Button } from "../ui/button"; import { stackedThreadToast, toastManager } from "../ui/toast"; -import { continuedThreadFollowThrough } from "./continueOnMachine.logic"; +import { afterContinuedThreadWait, continuedThreadFollowThrough } from "./continueOnMachine.logic"; import { continueOnMachineThreadAtom } from "./continueOnMachineDialogState"; /** A new thread reaches this window over the target's own connection, which may be reconnecting. */ @@ -67,7 +67,7 @@ function workFilesDescription(summary: WorkFilesSummary): string { summary.deletionCount === 0 ? "" : ` and ${summary.deletionCount.toLocaleString()} ${summary.deletionCount === 1 ? "deletion" : "deletions"}`; - return `${files}${deletions} (${formatBytes(summary.totalBytes)}) from ${summary.directory}. Every uncommitted and untracked file goes, secrets included. Git-ignored files stay on this machine.`; + return `${files}${deletions} (${formatBytes(summary.totalBytes)}) from ${summary.directory}. Every changed and new file goes, secrets included. Ignored files, node_modules, and build output stay on this machine.`; } function ContinueOnMachineDialog({ @@ -78,6 +78,7 @@ function ContinueOnMachineDialog({ readonly onClose: () => void; }) { const navigate = useNavigate(); + const router = useRouter(); const links = useEnvironmentQuery( peerLinkEnvironment.list({ environmentId: threadRef.environmentId, input: {} }), ); @@ -118,15 +119,25 @@ function ContinueOnMachineDialog({ void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(target) }); // Opens the thread as a new local one opens, once this window's connection there has it. const openWhenItArrives = async () => { - if (await waitForThreadShell(target, CONTINUED_THREAD_WAIT_MS)) { + const location = router.latestLocation; + const arrived = await waitForThreadShell(target, CONTINUED_THREAD_WAIT_MS); + const next = afterContinuedThreadWait({ + arrived, + movedOn: router.latestLocation !== location, + }); + if (next === "open") { openThread(); return; } toastManager.add( stackedThreadToast({ - type: "warning", - title: `The thread on ${continued.label} has not reached this window yet`, - description: `Check ${continued.label} in Settings → Connections, then open it.`, + type: arrived ? "info" : "warning", + title: arrived + ? `The thread on ${continued.label} is ready` + : `The thread on ${continued.label} has not reached this window yet`, + description: arrived + ? "Open it when you're ready." + : `Check ${continued.label} in Settings → Connections, then open it.`, actionProps: { children: "Open thread", onClick: openThread }, data: { hideCopyButton: true }, }), diff --git a/apps/web/src/components/chat/continueOnMachine.logic.test.ts b/apps/web/src/components/chat/continueOnMachine.logic.test.ts index 447473b4220aa..26282dee09539 100644 --- a/apps/web/src/components/chat/continueOnMachine.logic.test.ts +++ b/apps/web/src/components/chat/continueOnMachine.logic.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { continuedThreadFollowThrough } from "./continueOnMachine.logic"; +import { afterContinuedThreadWait, continuedThreadFollowThrough } from "./continueOnMachine.logic"; describe("continuedThreadFollowThrough", () => { it.each([ @@ -27,3 +27,14 @@ describe("continuedThreadFollowThrough", () => { }); }); }); + +describe("afterContinuedThreadWait", () => { + it.each([ + [{ arrived: true, movedOn: false }, "open"], + [{ arrived: true, movedOn: true }, "offer"], + [{ arrived: false, movedOn: false }, "missing"], + [{ arrived: false, movedOn: true }, "missing"], + ] as const)("%o: %s", (input, expected) => { + expect(afterContinuedThreadWait(input)).toBe(expected); + }); +}); diff --git a/apps/web/src/components/chat/continueOnMachine.logic.ts b/apps/web/src/components/chat/continueOnMachine.logic.ts index 2894d073cd789..0bad2ab622c35 100644 --- a/apps/web/src/components/chat/continueOnMachine.logic.ts +++ b/apps/web/src/components/chat/continueOnMachine.logic.ts @@ -20,3 +20,15 @@ export function continuedThreadFollowThrough(input: { if (input.saved === null) return { kind: "connect", host: input.linkUrls[0] ?? null }; return input.saved.enabled ? { kind: "open" } : { kind: "turn-on" }; } + +/** + * What to do once waiting for the continued thread ends. Opening it after the user moved + * elsewhere would pull them away from what they are doing, so they get a button instead. + */ +export function afterContinuedThreadWait(input: { + readonly arrived: boolean; + readonly movedOn: boolean; +}): "open" | "offer" | "missing" { + if (!input.arrived) return "missing"; + return input.movedOn ? "offer" : "open"; +} diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts index 4cd58ef38af64..689585ec324b0 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts +++ b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts @@ -1,6 +1,7 @@ import { type DesktopWslState, EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; import { + connectLinkOrigin, applyWslEnableSelection, isServerNetworkAccessible, resolveAccessEnvironmentId, @@ -215,3 +216,15 @@ describe("isServerNetworkAccessible", () => { expect(isServerNetworkAccessible(row)).toBe(row.expected); }); }); + +describe("connectLinkOrigin", () => { + it.each([ + ["https://devbox.example.com:3773/pair#token=SECRET", "https://devbox.example.com:3773"], + [" http://192.0.2.10:3773/ ", "http://192.0.2.10:3773"], + ["javascript:alert(1)", null], + ["not a url", null], + [42, null], + ] as const)("%o: %s", (value, expected) => { + expect(connectLinkOrigin(value)).toBe(expected); + }); +}); diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.ts index d3716ae993a96..94a807a79504b 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.logic.ts +++ b/apps/web/src/components/settings/ConnectionsSettings.logic.ts @@ -467,3 +467,17 @@ export function resolveAccessEnvironmentId(input: { ?.environmentId ?? null ); } + +/** + * The origin a `connect` link names, or null. Only the origin is kept, so a link can never + * carry a pairing token into the address bar or history. + */ +export function connectLinkOrigin(value: unknown): string | null { + if (typeof value !== "string") return null; + try { + const url = new URL(value.trim()); + return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null; + } catch { + return null; + } +} diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 81203d1eee21c..5a0eb8244319f 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -1,5 +1,5 @@ import { SessionPermissions } from "./SessionPermissions"; -import { useSearch } from "@tanstack/react-router"; +import { useNavigate, useSearch } from "@tanstack/react-router"; import { ChevronRightIcon, EllipsisIcon } from "lucide-react"; import { useAtomValue } from "@effect/atom-react"; import { type ReactNode, useState } from "react"; @@ -332,6 +332,7 @@ function ConnectionsSettingsContent({ const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false); // A link that names an address to pair with opens Add environment on it, also when this // page is already open. + const navigate = useNavigate(); const connectHost = useSearch({ strict: false, select: (search) => (typeof search.connect === "string" ? search.connect : null), @@ -355,6 +356,8 @@ function ConnectionsSettingsContent({ setRouteTarget(null); } else { setSavedBackendError(null); + // Closing forgets the link's address, so reload or Back doesn't reopen the dialog. + if (connectHost !== null) void navigate({ to: ".", search: {}, replace: true }); } }; const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] = diff --git a/apps/web/src/routes/_chat.settings.connections.tsx b/apps/web/src/routes/_chat.settings.connections.tsx index f174b16710a84..399e21f86d947 100644 --- a/apps/web/src/routes/_chat.settings.connections.tsx +++ b/apps/web/src/routes/_chat.settings.connections.tsx @@ -1,5 +1,6 @@ import { createFileRoute } from "@tanstack/react-router"; import { ConnectionsSettings } from "../components/settings/ConnectionsSettings"; +import { connectLinkOrigin } from "../components/settings/ConnectionsSettings.logic"; function SettingsConnectionsRoute() { return ; @@ -7,7 +8,10 @@ function SettingsConnectionsRoute() { export const Route = createFileRoute("/_chat/settings/connections")({ // `connect` opens Add environment at that address, as "Continue on another machine" does. - validateSearch: (raw: Record) => - typeof raw.connect === "string" && raw.connect.trim() ? { connect: raw.connect.trim() } : {}, + // Only the origin stays, so the link can never carry a pairing token. + validateSearch: (raw: Record) => { + const origin = connectLinkOrigin(raw.connect); + return origin === null ? {} : { connect: origin }; + }, component: SettingsConnectionsRoute, }); From 56e034c3bd0b2991ace28acd51f76d1672738412 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:05:58 +0100 Subject: [PATCH 11/14] fix(server): work files honor a link's narrowed mode, and the upload stores whole chunks --- .../src/mcp/toolkits/workFiles/handlers.ts | 8 ++++- .../server/src/peer/WorkFilesTransfer.test.ts | 33 +++++++++++-------- apps/server/src/peer/WorkFilesTransfer.ts | 3 +- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/apps/server/src/mcp/toolkits/workFiles/handlers.ts b/apps/server/src/mcp/toolkits/workFiles/handlers.ts index b8e4ce4fa192a..3ca0b15217955 100644 --- a/apps/server/src/mcp/toolkits/workFiles/handlers.ts +++ b/apps/server/src/mcp/toolkits/workFiles/handlers.ts @@ -18,7 +18,13 @@ export const layer = McpToolAccess.toLayer(WorkFilesToolkit, { message: "Only a linked environment can send work files here.", }); } - const refusal = WorkFilesTransfer.receiveAccessRefusal(scope.client.access); + // A request the link narrowed (`T3-Mode-Limit`) is held to its narrower mode. + const narrowed = McpInvocationContext.clientModeCeiling(scope.client).runtimeMode; + const refusal = + WorkFilesTransfer.receiveAccessRefusal(scope.client.access) ?? + (WorkFilesTransfer.receiveAccessRefusal(narrowed) === null + ? null + : `The thread sending these files runs in ${narrowed} mode, which cannot change files here; sending work files needs auto-accept-edits or broader.`); if (refusal !== null) { return yield* new OrchestratorMcpFailure({ code: "capability_denied", message: refusal }); } diff --git a/apps/server/src/peer/WorkFilesTransfer.test.ts b/apps/server/src/peer/WorkFilesTransfer.test.ts index b1ec6b4177b34..10c8872a36c11 100644 --- a/apps/server/src/peer/WorkFilesTransfer.test.ts +++ b/apps/server/src/peer/WorkFilesTransfer.test.ts @@ -10,6 +10,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { type AuthMcpClientAccess, ProjectId, + type RuntimeMode, WorkFilesReceiveInput, WorkFilesReceiveResult, } from "@t3tools/contracts"; @@ -124,6 +125,7 @@ const laptopSending = ( peer: Effect.Success>["peer"], source: string, access: AuthMcpClientAccess, + runtimeMode: RuntimeMode = "full-access", ) => Effect.gen(function* () { const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build); @@ -145,7 +147,7 @@ const laptopSending = ( environmentId: box.environmentId, tool: "t3_work_files_receive", arguments: encodeReceiveInput(request) as Record, - limits: { runtimeMode: "full-access", interactionMode: "default" }, + limits: { runtimeMode, interactionMode: "default" }, success: WorkFilesReceiveResult, }), }); @@ -226,20 +228,23 @@ it.live("refuses before sending anything when the box is on another commit", () }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), ); -it.live.each(["read-only", "approval-required"] as const)( - "refuses files from a link with %s access", - (access) => - Effect.gen(function* () { - const { source, target } = yield* checkouts; - const { peer } = yield* serveBox(target); - write(source, "app.ts", "v2"); +it.live.each([ + ["read-only", "full-access", "read-only"], + ["approval-required", "full-access", "approval-required"], + // An auto link calling for a thread that runs in approval-required mode. + ["auto", "approval-required", "approval-required mode"], +] as const)("refuses files from a link with %s access for a %s thread", ([access, mode, named]) => + Effect.gen(function* () { + const { source, target } = yield* checkouts; + const { peer } = yield* serveBox(target); + write(source, "app.ts", "v2"); - const send = yield* laptopSending(peer, source, access); - const refused = yield* send.pipe(Effect.flip); - expect(refused.code).toBe("capability_denied"); - if (access !== "read-only") expect(refused.message).toContain(access); - expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v1"); - }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), + const send = yield* laptopSending(peer, source, access, mode); + const refused = yield* send.pipe(Effect.flip); + expect(refused.code).toBe("capability_denied"); + if (access !== "read-only") expect(refused.message).toContain(named); + expect(NodeFS.readFileSync(NodePath.join(target, "app.ts"), "utf8")).toBe("v1"); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), ); it.live("the upload route takes nothing without a link session and its own token", () => diff --git a/apps/server/src/peer/WorkFilesTransfer.ts b/apps/server/src/peer/WorkFilesTransfer.ts index 6b0d1d5381c39..7661aed7f934f 100644 --- a/apps/server/src/peer/WorkFilesTransfer.ts +++ b/apps/server/src/peer/WorkFilesTransfer.ts @@ -163,7 +163,8 @@ const writeCapped = (body: Stream.Stream, path: string, maxBy }), Stream.runForEach((chunk) => Effect.tryPromise({ - try: () => file.write(chunk), + // `write` may store only part of a chunk; `writeFile` loops until all of it is. + try: () => file.writeFile(chunk), catch: () => receiveFailed("Could not store the archive here."), }), ), From 5422b76a824d2ac3c913074b5521f901238c1b4b Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:07:02 +0100 Subject: [PATCH 12/14] fix(server): work files refuse a path named twice and bound header records, and compare sizes before reading --- apps/server/src/peer/WorkFiles.test.ts | 26 +++++++++++++++++++++ apps/server/src/peer/WorkFiles.ts | 32 ++++++++++++++++++++++---- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/apps/server/src/peer/WorkFiles.test.ts b/apps/server/src/peer/WorkFiles.test.ts index 547cb32856038..dbb6bbef23aaf 100644 --- a/apps/server/src/peer/WorkFiles.test.ts +++ b/apps/server/src/peer/WorkFiles.test.ts @@ -301,6 +301,11 @@ it.live("applies the work to the same commit there, deletions included", () => // The same work again changes nothing and is not a conflict. NodeFS.rmSync(stagingDir, { recursive: true }); expect(yield* applyWorkFiles(input)).toEqual({ files: 2, deletions: 0 }); + // A path both written and deleted would lose its backup, so it is refused untouched. + NodeFS.rmSync(stagingDir, { recursive: true }); + const twice = yield* applyWorkFiles({ ...input, deletions: ["a.ts"] }).pipe(Effect.flip); + expect(twice.reason).toBe("invalid_archive"); + expect(NodeFS.readFileSync(NodePath.join(target, "a.ts"), "utf8")).toBe("changed"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -593,6 +598,27 @@ it.live("refuses a global pax header, which GNU tar applies to every entry after }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.live("refuses an archive of header records that would take unbounded work to read", () => + Effect.gen(function* () { + const dir = yield* tempDir; + const archive = NodePath.join(dir, "names.tgz"); + // 65 long-name records of 1 MiB each gzip to under 100 KiB and name no file. + const longName = tarEntry("././@LongLink", "L", Buffer.alloc(1024 * 1024)); + NodeFS.writeFileSync( + archive, + NodeZlib.gzipSync( + Buffer.concat([ + ...Array.from({ length: 65 }, () => longName), + tarEntry("empty.txt", "0", Buffer.alloc(0)), + Buffer.alloc(1024), + ]), + ), + ); + const refused = yield* listArchive(archive).pipe(Effect.flip); + expect(refused.reason).toBe("invalid_archive"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.live("refuses an archive that expands past the size limit before extracting it", () => Effect.gen(function* () { const { source, target, archivePath, stagingDir } = yield* pair({ "a.ts": "a" }); diff --git a/apps/server/src/peer/WorkFiles.ts b/apps/server/src/peer/WorkFiles.ts index 94cddc23b60d1..d56cce3ddea00 100644 --- a/apps/server/src/peer/WorkFiles.ts +++ b/apps/server/src/peer/WorkFiles.ts @@ -308,6 +308,8 @@ const TAR_BLOCK = 512; /** Pax and GNU long-name records hold a few names; a bigger one is not an archive a T3 server wrote. */ const TAR_MAX_METADATA_BYTES = 1024 * 1024; const TAR_MAX_ENTRIES = WORK_FILES_MAX_COUNT * 4; +/** All pax and long-name records together, headers included; far above what real names need. */ +const TAR_MAX_METADATA_TOTAL_BYTES = 64 * 1024 * 1024; const nulTerminated = (bytes: Buffer) => { const end = bytes.indexOf(0); @@ -378,6 +380,7 @@ const readArchiveEntries = async (archivePath: string) => { let longName: string | null = null; let fileCount = 0; let expandedBytes = 0; + let metadataBytes = 0; let ended = false; try { for await (const chunk of gunzip as AsyncIterable) { @@ -434,6 +437,10 @@ const readArchiveEntries = async (archivePath: string) => { // Metadata for the entry after it: pax records and GNU long names. if (flag === "x" || flag === "L" || flag === "K") { if (size > TAR_MAX_METADATA_BYTES) throw invalid("The archive has an oversized header."); + metadataBytes += TAR_BLOCK + size; + if (metadataBytes > TAR_MAX_METADATA_TOTAL_BYTES) { + throw invalid("The archive has too many header records."); + } collecting = { type: flag, size }; continue; } @@ -562,11 +569,19 @@ const targetConflict = Effect.fn("WorkFiles.targetConflict")(function* ( if (!stat.isFile()) return "it is a link or a folder there"; // An identical file is no change, so sending the same work again is a no-op. if (incoming !== null) { - const [here, there] = yield* Effect.all([ - fileSystemCall("read a file there", () => NodeFSP.readFile(NodePath.join(root, ...segments))), - fileSystemCall("read an extracted file", () => NodeFSP.readFile(incoming)), - ]); - if (here.equals(there)) return null; + // Sizes first, so a large file there is read only when it could be identical. + const incomingSize = yield* fileSystemCall("read an extracted file", () => + NodeFSP.lstat(incoming).then((file) => file.size), + ); + if (incomingSize === stat.size) { + const [here, there] = yield* Effect.all([ + fileSystemCall("read a file there", () => + NodeFSP.readFile(NodePath.join(root, ...segments)), + ), + fileSystemCall("read an extracted file", () => NodeFSP.readFile(incoming)), + ]); + if (here.equals(there)) return null; + } // Copying onto it would change its other names too. if (stat.nlink > 1) return "it is a hard link to another file there"; } @@ -723,6 +738,13 @@ export const applyWorkFiles = Effect.fn("WorkFiles.apply")(function* (input: App return yield* invalid(`A deletion names an unsafe path: "${path}".`); } } + // A second write or delete of one path would back up the first one's result, not the original. + const seen = new Set(); + for (const path of [...files.map((file) => file.path), ...input.deletions]) { + const key = path.normalize("NFC"); + if (seen.has(key)) return yield* invalid(`The work files name ${path} more than once.`); + seen.add(key); + } const lock = yield* checkoutLock(input.root); // A half-applied copy cannot be left behind: once the lock is held, the apply // and any rollback run to the end before an interruption lands, and only From 814f86a6029862741feb4134891ca0cb05f8beb5 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:11:25 +0100 Subject: [PATCH 13/14] fix(server): a continued thread carries its forked and visible history, keeps working when the model is missing there, and a delegate retry reads only its task --- .../src/peer/ContinueOnEnvironment.test.ts | 159 +++++++++++++----- apps/server/src/peer/ContinueOnEnvironment.ts | 62 ++++--- apps/server/src/peer/RemoteDelegation.ts | 10 +- apps/server/src/server.ts | 2 +- 4 files changed, 163 insertions(+), 70 deletions(-) diff --git a/apps/server/src/peer/ContinueOnEnvironment.test.ts b/apps/server/src/peer/ContinueOnEnvironment.test.ts index efb78b4b338e5..70efc318c4cd7 100644 --- a/apps/server/src/peer/ContinueOnEnvironment.test.ts +++ b/apps/server/src/peer/ContinueOnEnvironment.test.ts @@ -11,6 +11,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; @@ -22,22 +23,64 @@ import * as WorkFilesTransfer from "./WorkFilesTransfer.ts"; const here = EnvironmentId.make("environment-laptop"); const box = EnvironmentId.make("environment-box"); const threadId = ThreadId.make("thread:laptop"); +const originThreadId = ThreadId.make("thread:origin"); const boxProject = ProjectId.make("project:box"); const instanceId = ProviderInstanceId.make("codex"); -const item = (id: string, type: "user_message" | "assistant_message", text: string) => ({ - id, - type, - text, - threadId, - runId: "run:1", - providerThreadId: null, - status: "completed", -}); +const item = ( + id: string, + type: "user_message" | "assistant_message", + text: string, + runId = "run:1", + owner = threadId, +) => ({ id, type, text, threadId: owner, runId, providerThreadId: null, status: "completed" }); + +const run = (id: string, ordinal: number, status: string) => ({ id, ordinal, status }); + +/** The thread this one was forked from, and the rows each run left, run:2 rolled back. */ +const projection = { + [originThreadId]: { + thread: { id: originThreadId, lineage: {} }, + runs: [run("run:o1", 1, "completed")], + attempts: [], + turnItems: [item("item:o1", "user_message", "Make login stable.", "run:o1", originThreadId)], + }, + [threadId]: { + turnItems: [ + item("item:1", "user_message", "The login test fails on CI."), + item("item:2", "assistant_message", "It races the session cookie; I patched auth.ts."), + item("item:3", "assistant_message", "Rewrote the whole auth module.", "run:2"), + ], + }, +} as Record | object>>; + +/** The box's answer to each tool the laptop calls. */ +const projectAnswer = (tool: string) => { + switch (tool) { + case "t3_project_list": + return { + projects: [ + { + id: boxProject, + title: "app", + repositoryIdentity: { canonicalKey: "github.com/acme/app" }, + }, + ], + nextCursor: null, + }; + case "orchestrator_capabilities": + return { providers: [{ providerInstanceId: instanceId }] }; + case "t3_thread_launch": + return { threadId: ThreadId.make("thread:box"), projectId: boxProject }; + default: + return {}; + } +}; /** The laptop's thread, the box's answers, and what was asked of the box, in order. */ const setup = ( sendResult: Effect.Effect<{ files: number; deletions: number }, OrchestratorMcpFailure>, + options: { readonly modelThere?: boolean } = {}, ) => { const calls: Array<{ tool: string; arguments: Record }> = []; const layer = ContinueOnEnvironment.layer.pipe( @@ -53,19 +96,28 @@ const setup = ( runtimeMode: "full-access", interactionMode: "default", modelSelection: { instanceId, model: "gpt-5.4" }, + forkedFrom: { type: "run", threadId: originThreadId, runId: "run:o1" }, + lineage: {}, }, - turnItems: [ - item("item:1", "user_message", "The login test fails on CI."), - item( - "item:2", - "assistant_message", - "It races the session cookie; I patched auth.ts.", - ), - ], - runs: [], + runs: [run("run:1", 1, "completed"), run("run:2", 2, "rolled_back")], + attempts: [], } as never), }), ), + Layer.provide( + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadRecords: (id, fields, filter) => + Effect.sync(() => { + const records = projection[id]!; + if (!fields.includes("turnItems" as never)) return records as never; + const runIds = filter?.turnItemRunIds; + const items = records.turnItems as ReadonlyArray<{ readonly runId: string }>; + return { + turnItems: items.filter((row) => runIds?.includes(row.runId as never) ?? true), + } as never; + }), + }), + ), Layer.provide( Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: "/home/user/app" } as never), @@ -85,27 +137,21 @@ const setup = ( Layer.provide( Layer.mock(PeerMcpClient.PeerMcpClient)({ call: (input) => - Effect.sync(() => { + Effect.suspend(() => { calls.push({ tool: input.tool, arguments: input.arguments }); - switch (input.tool) { - case "t3_project_list": - return { - projects: [ - { - id: boxProject, - title: "app", - repositoryIdentity: { canonicalKey: "github.com/acme/app" }, - }, - ], - nextCursor: null, - }; - case "orchestrator_capabilities": - return { providers: [{ providerInstanceId: instanceId }] }; - case "t3_thread_launch": - return { threadId: ThreadId.make("thread:box"), projectId: boxProject }; - default: - return {}; + if ( + input.tool === "t3_thread_launch" && + options.modelThere === false && + input.arguments.modelSelection !== undefined + ) { + return Effect.fail( + new OrchestratorMcpFailure({ + code: "model_unavailable", + message: "Model gpt-5.4 is not advertised by provider codex.", + }), + ); } + return Effect.succeed(projectAnswer(input.tool)); }) as never, }), ), @@ -147,11 +193,11 @@ it.effect("starts a thread there from this one's conversation, after its files l }); expect(calls.map((call) => call.tool)).toEqual([ "t3_project_list", - "send", "orchestrator_capabilities", + "send", "t3_thread_launch", ]); - expect(calls[1]?.arguments).toEqual({ cwd: "/home/user/app", projectId: boxProject }); + expect(calls[2]?.arguments).toEqual({ cwd: "/home/user/app", projectId: boxProject }); const launch = calls[3]!.arguments; expect(launch).toMatchObject({ projectId: boxProject, @@ -161,6 +207,9 @@ it.effect("starts a thread there from this one's conversation, after its files l // The handoff carries the conversation and says the files came along. expect(launch.message).toContain("The login test fails on CI."); expect(launch.message).toContain("It races the session cookie; I patched auth.ts."); + // It starts from the task the thread was forked from, and leaves out the rolled-back run. + expect(launch.message).toContain("Make login stable."); + expect(launch.message).not.toContain("Rewrote the whole auth module."); expect(launch.message).toContain("2 files written, 1 deleted"); // It names this machine as people know it, not only by id. expect(launch.message).toContain(`from laptop (environment ${here})`); @@ -182,11 +231,15 @@ it.effect("launches nothing there when the files cannot go", () => { .continueThread({ threadId, environmentId: box, workFiles: "transfer" }) .pipe(Effect.flip); expect(refused.message).toBe("Box: app.ts (it has local changes there)"); - expect(calls.map((call) => call.tool)).toEqual(["t3_project_list", "send"]); + expect(calls.map((call) => call.tool)).toEqual([ + "t3_project_list", + "orchestrator_capabilities", + "send", + ]); }).pipe(Effect.provide(layer)); }); -it.effect("without files, sends nothing and says the checkout has only what is committed", () => { +it.effect("without files, sends nothing and says the files were not copied", () => { const { calls, layer } = setup(Effect.die("no send")); return Effect.gen(function* () { const service = yield* ContinueOnEnvironment.ContinueOnEnvironment; @@ -197,6 +250,28 @@ it.effect("without files, sends nothing and says the checkout has only what is c }); expect(result.transferredFiles).toBe(0); expect(calls.map((call) => call.tool)).not.toContain("send"); - expect(calls.at(-1)?.arguments.message).toContain("this checkout has only what is committed"); + expect(calls.at(-1)?.arguments.message).toContain("Its working files were not copied here."); }).pipe(Effect.provide(layer)); }); + +it.effect( + "starts the thread with the project's model there when that instance lacks this one", + () => { + const { calls, layer } = setup(Effect.succeed({ files: 1, deletions: 0 }), { + modelThere: false, + }); + return Effect.gen(function* () { + const service = yield* ContinueOnEnvironment.ContinueOnEnvironment; + const result = yield* service.continueThread({ + threadId, + environmentId: box, + workFiles: "transfer", + }); + expect(result.threadId).toBe(ThreadId.make("thread:box")); + const launches = calls.filter((call) => call.tool === "t3_thread_launch"); + expect(launches).toHaveLength(2); + expect(launches[1]!.arguments.modelSelection).toBeUndefined(); + expect(launches[1]!.arguments.clientRequestId).toBe(launches[0]!.arguments.clientRequestId); + }).pipe(Effect.provide(layer)); + }, +); diff --git a/apps/server/src/peer/ContinueOnEnvironment.ts b/apps/server/src/peer/ContinueOnEnvironment.ts index cc47e44d68ccc..880e65b431f3c 100644 --- a/apps/server/src/peer/ContinueOnEnvironment.ts +++ b/apps/server/src/peer/ContinueOnEnvironment.ts @@ -25,6 +25,8 @@ import * as Schema from "effect/Schema"; import type * as Tool from "effect/ai/Tool"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { readForkHistoryItems } from "../orchestration-v2/ContextHandoffService.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; import { WorkFilesReceiveTool } from "../mcp/toolkits/workFiles/tools.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; @@ -64,6 +66,7 @@ const encodeReceiveInput = Schema.encodeSync(WorkFilesReceiveTool.parametersSche const make = Effect.gen(function* () { const threads = yield* ThreadManagement.ThreadManagementService; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; const projects = yield* ProjectService.ProjectService; const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; const peers = yield* PeerMcpClient.PeerMcpClient; @@ -74,7 +77,7 @@ const make = Effect.gen(function* () { const loadThread = Effect.fn("ContinueOnEnvironment.loadThread")(function* (threadId: ThreadId) { const records = yield* threads - .getThreadRecords(threadId, ["turnItems", "runs"]) + .getThreadRecords(threadId, ["runs", "attempts"]) .pipe(Effect.mapError(() => refused("This thread was not found."))); const project = yield* projects.getById(records.thread.projectId).pipe( Effect.map(Option.getOrUndefined), @@ -151,6 +154,14 @@ const make = Effect.gen(function* () { ), ); + // Asked before any files go, so a refusal here leaves the checkout there as it was. + const capabilities = yield* call("orchestrator_capabilities", {}, CapabilitiesResult).pipe( + Effect.mapError(there), + ); + const sameInstance = capabilities.providers.some( + (provider) => provider.providerInstanceId === thread.modelSelection.instanceId, + ); + const transferred = input.workFiles === "transfer" ? yield* transfer @@ -168,20 +179,16 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError(there)) : { files: 0, deletions: 0 }; - // The same instance there keeps the thread's model; otherwise the project there picks one. - const capabilities = yield* call("orchestrator_capabilities", {}, CapabilitiesResult).pipe( - Effect.mapError(there), - ); - const sameInstance = capabilities.providers.some( - (provider) => provider.providerInstanceId === thread.modelSelection.instanceId, - ); - const filesLine = input.workFiles === "transfer" ? `Its working files were copied into this checkout (${transferred.files} files written, ${transferred.deletions} deleted).` - : "Its working files were not copied; this checkout has only what is committed."; + : "Its working files were not copied here."; + // What the thread shows: its fork ancestors' rows, then its own, without rolled-back runs. + const history = yield* readForkHistoryItems(projectionStore, records, { + ordinal: Number.POSITIVE_INFINITY, + }).pipe(Effect.mapError(() => refused("This thread's conversation could not be read."))); const selected = selectHistory({ - messages: records.turnItems.flatMap((item) => { + messages: history.flatMap((item) => { const message = historicalMessage(item); return message === null ? [] : [message]; }), @@ -193,17 +200,28 @@ const make = Effect.gen(function* () { }); const message = `${renderHistory(selected.messages, selected.context)}\n\nContinue the work from where it stopped.`; - const launched = yield* call( - "t3_thread_launch", - { - projectId, - title: thread.title, - ...(sameInstance ? { modelSelection: encodeModelSelection(thread.modelSelection) } : {}), - message, - clientRequestId: `continue:${thread.id}:${yield* random.uuidV4()}`, - }, - LaunchResult, - ).pipe(Effect.mapError(there)); + const clientRequestId = `continue:${thread.id}:${yield* random.uuidV4()}`; + const launch = (keepModel: boolean) => + call( + "t3_thread_launch", + { + projectId, + title: thread.title, + ...(keepModel ? { modelSelection: encodeModelSelection(thread.modelSelection) } : {}), + message, + clientRequestId, + }, + LaunchResult, + ); + // The same instance there keeps the thread's model. Otherwise, or when that instance + // does not have the model, the project there picks one, since the files are there now. + const launched = yield* launch(sameInstance).pipe( + Effect.catchIf( + (error) => sameInstance && error.code === "model_unavailable", + () => launch(false), + ), + Effect.mapError(there), + ); return { environmentId: input.environmentId as EnvironmentId, threadId: launched.threadId, diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index f658725995e73..59c119d666fd1 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -355,11 +355,11 @@ const make = Effect.gen(function* () { // A retry of a recorded task launched it already, and its files went first. const recordedBefore = input.clientRequestId !== undefined && - (yield* threads.getThreadRecords(scope.thread.threadId, ["subagents"]).pipe( - Effect.map(({ subagents }) => { - const taskId = IdAllocator.derive.delegatedTaskNode({ commandId }); - return subagents.some((task) => task.id === taskId); - }), + (yield* readTask( + scope.thread.threadId, + IdAllocator.derive.delegatedTaskNode({ commandId }), + ).pipe( + Effect.map(({ task }) => task !== undefined), Effect.orElseSucceed(() => false), )); if (input.workFiles === "transfer" && !recordedBefore) { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 203ef162cdbd3..21c750a279b74 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -836,7 +836,7 @@ const layerMakeRoutes = Layer.mergeAll( PullRequestReviewGuideService.layer.pipe(Layer.provide(PullRequestReviewGuides.layer)), ), // Continue on another machine, from the thread menu. - Layer.provide(ContinueOnEnvironment.layer), + Layer.provide(ContinueOnEnvironment.layer.pipe(Layer.provide(ProjectionStoreV2.layer))), // delegate_task to a linked environment, from /mcp and the follower above. Layer.provide(RemoteDelegation.layer.pipe(Layer.provide(ProjectionStoreV2.layer))), // Work files sent to and received from linked environments. From 8f4a20f7470b925f173d998a29a9ddc6b56e8616 Mon Sep 17 00:00:00 2001 From: eyeveil <64274427+eyeveil@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:13:08 +0100 Subject: [PATCH 14/14] fix(web): a work-files read failure still offers Continue without files, a continued thread opens only if you stayed where you asked, and a new Connect address drops the typed code --- .../chat/ContinueOnMachineDialog.tsx | 51 +++++++++++++------ .../AddEnvironmentDialog.browser.test.tsx | 6 ++- .../settings/AddEnvironmentDialog.tsx | 5 +- 3 files changed, 45 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx index 153845e0f3462..4e797c185c8f4 100644 --- a/apps/web/src/components/chat/ContinueOnMachineDialog.tsx +++ b/apps/web/src/components/chat/ContinueOnMachineDialog.tsx @@ -54,7 +54,19 @@ export function ContinueOnMachineDialogHost() { type Stage = | { readonly kind: "pick" } | { readonly kind: "checking"; readonly link: PeerLinkSummary } - | { readonly kind: "ask"; readonly link: PeerLinkSummary; readonly summary: WorkFilesSummary } + | { + readonly kind: "ask"; + readonly link: PeerLinkSummary; + readonly summary: WorkFilesSummary; + readonly error: null; + } + /** The files could not be read; continuing without them is still possible. */ + | { + readonly kind: "ask"; + readonly link: PeerLinkSummary; + readonly summary: null; + readonly error: string; + } | { readonly kind: "running"; readonly link: PeerLinkSummary; readonly mode: WorkFilesMode }; const failureMessage = (error: unknown) => @@ -103,6 +115,8 @@ function ContinueOnMachineDialog({ ); const run = async (link: PeerLinkSummary, mode: WorkFilesMode) => { + // Where the user was when they asked; moving anywhere else while it runs means they moved on. + const askedAt = router.latestLocation; setStage({ kind: "running", link, mode }); const result = await continueThread({ environmentId: threadRef.environmentId, @@ -118,8 +132,7 @@ function ContinueOnMachineDialog({ const openThread = () => void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(target) }); // Opens the thread as a new local one opens, once this window's connection there has it. - const openWhenItArrives = async () => { - const location = router.latestLocation; + const openWhenItArrives = async (location: typeof askedAt) => { const arrived = await waitForThreadShell(target, CONTINUED_THREAD_WAIT_MS); const next = afterContinuedThreadWait({ arrived, @@ -144,6 +157,7 @@ function ContinueOnMachineDialog({ ); }; const turnOnAndOpen = async () => { + const clickedAt = router.latestLocation; const enabled = await setEnvironmentEnabled({ environmentId: continued.environmentId, enabled: true, @@ -160,7 +174,7 @@ function ContinueOnMachineDialog({ } return; } - await openWhenItArrives(); + await openWhenItArrives(clickedAt); }; const saved = readEnvironment(continued.environmentId); const followThrough = continuedThreadFollowThrough({ @@ -203,7 +217,7 @@ function ContinueOnMachineDialog({ data: { hideCopyButton: true }, }), ); - if (followThrough.kind === "open") await openWhenItArrives(); + if (followThrough.kind === "open") await openWhenItArrives(askedAt); }; const choose = async (link: PeerLinkSummary) => { @@ -213,8 +227,12 @@ function ContinueOnMachineDialog({ input: { threadId: threadRef.threadId }, }); if (result._tag === "Failure") { - onClose(); - if (!isAtomCommandInterrupted(result)) fail(link, squashAtomCommandFailure(result)); + if (isAtomCommandInterrupted(result)) { + onClose(); + return; + } + const error = failureMessage(squashAtomCommandFailure(result)); + setStage({ kind: "ask", link, summary: null, error }); return; } const summary = result.value; @@ -223,21 +241,24 @@ function ContinueOnMachineDialog({ await run(link, "skip"); return; } - setStage({ kind: "ask", link, summary }); + setStage({ kind: "ask", link, summary, error: null }); }; if (stage.kind === "ask" || (stage.kind === "running" && stage.mode === "transfer")) { - const summary = stage.kind === "ask" ? stage.summary : null; + const description = + stage.kind !== "ask" + ? `Sending the work files to ${stage.link.label}…` + : stage.error !== null + ? `The work files could not be read: ${stage.error}` + : (stage.summary.refusal ?? workFilesDescription(stage.summary)); + const canTransfer = + stage.kind === "ask" && stage.error === null && stage.summary.refusal == null; return ( !open && !busy && onClose()}> Transfer the current work files too? - - {summary === null - ? `Sending the work files to ${stage.link.label}…` - : (summary.refusal ?? workFilesDescription(summary))} - + {description} }> @@ -247,7 +268,7 @@ function ContinueOnMachineDialog({ Continue without files