Skip to content

The open-source app everyone uses to manage agents at work

fix(grok): stage the environment test from a host directory, and survive an absent workspace (#13416)

Devin Foley5054c9ef9b27
diff --git a/packages/adapter-utils/src/sandbox-file-sync.test.ts b/packages/adapter-utils/src/sandbox-file-sync.test.ts
index 99401f6905..cb6e96bdfe 100644
--- a/packages/adapter-utils/src/sandbox-file-sync.test.ts
+++ b/packages/adapter-utils/src/sandbox-file-sync.test.ts
@@ -126,6 +126,45 @@ describe("sandbox native file sync", () => {
expect(await readFile(path.join(repo, "outside.txt"), "utf8")).toBe("outside boundary\n");
});
+ it("prepares a runtime whose workspace directory does not exist without failing the ignore scan", async () => {
+ // An env test staging only credential assets can hand the runtime a
+ // workspace path that never existed on this host. A directory with no
+ // files has nothing for ignore rules to govern, so the scan is skipped
+ // rather than failed (git-ignore-scan-failed took down the whole
+ // preparation in production).
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-native-absent-workspace-"));
+ cleanupDirs.push(rootDir);
+ const remoteDir = path.join(rootDir, "remote");
+
+ const { client } = makeNativeClient();
+ const prepared = await prepareSandboxManagedRuntime({
+ spec: { transport: "sandbox", provider: "test", sandboxId: "s1", remoteCwd: remoteDir, timeoutMs: 30_000, apiKey: null },
+ adapterKey: "test-adapter",
+ client,
+ workspaceLocalDir: path.join(rootDir, "never-created"),
+ });
+ await prepared.restoreWorkspace();
+ });
+
+ it("fails preparation when the workspace cannot be read for a reason other than absence", async () => {
+ // Only absence means "nothing to sync". A workspace that is there but
+ // unreadable must not quietly become an empty remote workspace, so any
+ // other access error still fails the preparation. A path whose parent is
+ // a file gives a deterministic non-ENOENT error on every platform.
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-native-unreadable-workspace-"));
+ cleanupDirs.push(rootDir);
+ const notADirectory = path.join(rootDir, "a-file");
+ await writeFile(notADirectory, "not a directory\n");
+
+ const { client } = makeNativeClient();
+ await expect(prepareSandboxManagedRuntime({
+ spec: { transport: "sandbox", provider: "test", sandboxId: "s1", remoteCwd: path.join(rootDir, "remote"), timeoutMs: 30_000, apiKey: null },
+ adapterKey: "test-adapter",
+ client,
+ workspaceLocalDir: path.join(notADirectory, "workspace"),
+ })).rejects.toMatchObject({ code: "ENOTDIR" });
+ });
+
it("prefers the native path for default-provision asset inbound and workspace outbound", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-native-sync-"));
cleanupDirs.push(rootDir);
diff --git a/packages/adapter-utils/src/sandbox-managed-runtime.ts b/packages/adapter-utils/src/sandbox-managed-runtime.ts
index 4ca1ea9ed2..10eb454f8d 100644
--- a/packages/adapter-utils/src/sandbox-managed-runtime.ts
+++ b/packages/adapter-utils/src/sandbox-managed-runtime.ts
@@ -1084,7 +1084,21 @@ export async function prepareSandboxManagedRuntime(input: {
}): Promise<PreparedSandboxManagedRuntime> {
const workspaceRemoteDir = input.workspaceRemoteDir ?? input.spec.remoteCwd;
const runtimeRootDir = path.posix.join(workspaceRemoteDir, ".paperclip-runtime", input.adapterKey);
- const syncWorkspace = input.syncWorkspace !== false;
+ // A workspace directory that does not exist on this host has nothing to
+ // stage, no files for ignore rules to govern, and nothing to restore into —
+ // callers that only stage credential assets (the adapter env tests) hand
+ // the runtime a fresh path. Treat that one case as "do not sync" rather
+ // than letting the ignore scan or the staging walk die on ENOENT. Any other
+ // access failure still fails the preparation: a workspace that exists but
+ // cannot be read must not silently become an empty remote workspace.
+ const syncWorkspace = input.syncWorkspace !== false &&
+ (await fs.access(input.workspaceLocalDir).then(
+ () => true,
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return false;
+ throw error;
+ },
+ ));
const workspaceInboundMode = input.workspaceInboundMode ?? "host_current";
const stageWorkspace =
syncWorkspace && workspaceInboundMode !== "adopt_remote";
diff --git a/packages/adapters/grok-local/src/server/test.test.ts b/packages/adapters/grok-local/src/server/test.test.ts
index 0e96382f40..3f0e6a6c5e 100644
--- a/packages/adapters/grok-local/src/server/test.test.ts
+++ b/packages/adapters/grok-local/src/server/test.test.ts
@@ -3,16 +3,23 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
const ensureDirectoryMock = vi.hoisted(() => vi.fn(async () => {}));
const ensureCommandMock = vi.hoisted(() => vi.fn(async () => {}));
const runProcessMock = vi.hoisted(() => vi.fn());
+const prepareRuntimeMock = vi.hoisted(() => vi.fn());
+const stageGrokHomeMock = vi.hoisted(() => vi.fn(async () => "/tmp/staged-grok-home"));
vi.mock("@paperclipai/adapter-utils/execution-target", () => ({
describeAdapterExecutionTarget: () => "local",
ensureAdapterExecutionTargetCommandResolvable: ensureCommandMock,
ensureAdapterExecutionTargetDirectory: ensureDirectoryMock,
+ prepareAdapterExecutionTargetRuntime: prepareRuntimeMock,
resolveAdapterExecutionTargetCwd: (_target: unknown, configuredCwd: string, fallbackCwd: string) =>
configuredCwd || fallbackCwd,
runAdapterExecutionTargetProcess: runProcessMock,
}));
+vi.mock("./grok-home.js", () => ({ stageGrokHomeForSync: stageGrokHomeMock }));
+vi.mock("./grok-auth-copyback.js", () => ({ copyBackGrokAuth: vi.fn(async () => {}) }));
+
+import { existsSync } from "node:fs";
import { parseGrokModelsOutput, testEnvironment } from "./test.js";
describe("parseGrokModelsOutput", () => {
@@ -38,6 +45,8 @@ describe("grok_local testEnvironment", () => {
ensureDirectoryMock.mockClear();
ensureCommandMock.mockClear();
runProcessMock.mockReset();
+ prepareRuntimeMock.mockReset();
+ stageGrokHomeMock.mockClear();
});
it("reports a healthy authenticated host with a working hello probe", async () => {
@@ -249,6 +258,58 @@ describe("grok_local testEnvironment", () => {
);
});
+ it("stages the managed account through a host temp workspace, never the remote cwd", async () => {
+ // The remote cwd is a path inside the sandbox. Handing it to the runtime
+ // as `workspaceLocalDir` made the host-side ignore scan fail on a
+ // directory that does not exist (git-ignore-scan-failed in production).
+ let workspaceLocalDirAtCall: string | undefined;
+ let workspaceExistedAtCall: boolean | undefined;
+ prepareRuntimeMock.mockImplementationOnce(async (input: { workspaceLocalDir: string }) => {
+ workspaceLocalDirAtCall = input.workspaceLocalDir;
+ workspaceExistedAtCall = existsSync(input.workspaceLocalDir);
+ return { assetDirs: { home: "/sandbox/assets/home" }, restoreWorkspace: async () => {} };
+ });
+ runProcessMock
+ .mockResolvedValueOnce({ exitCode: 0, signal: null, timedOut: false, stdout: "You are logged in with grok.com.\n\nDefault model: grok-4\n\nAvailable models:\n * grok-4", stderr: "" })
+ .mockResolvedValueOnce({ exitCode: 0, signal: null, timedOut: false, stdout: [JSON.stringify({ type: "text", data: "hello" }), JSON.stringify({ type: "end", stopReason: "EndTurn", sessionId: "s", requestId: "r" })].join("\n"), stderr: "" });
+
+ const result = await testEnvironment({
+ companyId: "company-1",
+ adapterType: "grok_local",
+ config: { command: "grok", cwd: "/sandbox/workspace", managedAiConnection: { provider: "xai" } },
+ executionTarget: { kind: "remote", transport: "sandbox" } as never,
+ });
+
+ expect(prepareRuntimeMock).toHaveBeenCalledOnce();
+ expect(prepareRuntimeMock).toHaveBeenCalledWith(
+ expect.objectContaining({ workspaceRemoteDir: "/sandbox/workspace" }),
+ );
+ expect(workspaceLocalDirAtCall).not.toBe("/sandbox/workspace");
+ expect(workspaceExistedAtCall).toBe(true);
+ // The staged home dir the runtime uploaded is what the probe must use.
+ expect(runProcessMock.mock.calls[0]?.[4]).toMatchObject({ env: expect.objectContaining({ GROK_HOME: "/sandbox/assets/home" }) });
+ expect(result.status).toBe("pass");
+ });
+
+ it("reports a failed runtime preparation as a check instead of crashing", async () => {
+ prepareRuntimeMock.mockRejectedValueOnce(
+ new Error("Workspace ignore scan failed: git-ignore-scan-failed"),
+ );
+
+ const result = await testEnvironment({
+ companyId: "company-1",
+ adapterType: "grok_local",
+ config: { command: "grok", cwd: "/sandbox/workspace", managedAiConnection: { provider: "xai" } },
+ executionTarget: { kind: "remote", transport: "sandbox" } as never,
+ });
+
+ expect(result.status).toBe("fail");
+ const unprepared = result.checks.find((check: { code: string }) => check.code === "grok_environment_unprepared");
+ expect(unprepared).toMatchObject({ level: "error" });
+ // A failed staging means there is no environment worth probing.
+ expect(runProcessMock).not.toHaveBeenCalled();
+ });
+
it("emits no adapter_auth_missing check for a local target with missing authentication", async () => {
// The canonical check gates sandbox login eligibility only. A local target
// has no sandbox login to offer, so the check must not appear.
diff --git a/packages/adapters/grok-local/src/server/test.ts b/packages/adapters/grok-local/src/server/test.ts
index 27aabc38bb..bb814c9761 100644
--- a/packages/adapters/grok-local/src/server/test.ts
+++ b/packages/adapters/grok-local/src/server/test.ts
@@ -18,7 +18,8 @@ import {
resolveAdapterExecutionTargetCwd,
runAdapterExecutionTargetProcess,
} from "@paperclipai/adapter-utils/execution-target";
-import { rm } from "node:fs/promises";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
import path from "node:path";
import { stageGrokHomeForSync } from "./grok-home.js";
import { copyBackGrokAuth } from "./grok-auth-copyback.js";
@@ -151,22 +152,43 @@ export async function testEnvironment(
const env = normalizeEnv(config.env);
let stagedHome: string | undefined;
+ let runtimeWorkspaceLocalDir: string | undefined;
let restore: (() => Promise<void>) | undefined;
try {
if (config.managedAiConnection && targetIsRemote) {
- const hostHome = env.GROK_HOME;
- stagedHome = await stageGrokHomeForSync(hostHome, { runId });
- const prepared = await prepareAdapterExecutionTargetRuntime({
- runId, target, adapterKey: "grok", workspaceLocalDir: cwd,
- assets: [{ key: "home", localDir: stagedHome, followSymlinks: true,
- restore: async ({ assetDir, readFile }) => { await copyBackGrokAuth({
- readSandboxAuth: () => readFile(path.posix.join(assetDir, "auth.json")),
- hostHomeDir: hostHome, log: () => {},
- }); },
- }],
- });
- env.GROK_HOME = prepared.assetDirs.home;
- restore = () => prepared.restoreWorkspace(() => {});
+ try {
+ const hostHome = env.GROK_HOME;
+ stagedHome = await stageGrokHomeForSync(hostHome, { runId });
+ // `cwd` is the remote target path here, never a host directory, so the
+ // runtime gets an empty host workspace to stage from and the remote
+ // path separately — the same split codex-local and opencode-local
+ // draw. Handing it the remote path as `workspaceLocalDir` made the
+ // host-side ignore scan fail on a directory that does not exist.
+ runtimeWorkspaceLocalDir = await mkdtemp(
+ path.join(os.tmpdir(), `paperclip-grok-envtest-${runId}-`),
+ );
+ const prepared = await prepareAdapterExecutionTargetRuntime({
+ runId, target, adapterKey: "grok",
+ workspaceLocalDir: runtimeWorkspaceLocalDir,
+ workspaceRemoteDir: cwd,
+ assets: [{ key: "home", localDir: stagedHome, followSymlinks: true,
+ restore: async ({ assetDir, readFile }) => { await copyBackGrokAuth({
+ readSandboxAuth: () => readFile(path.posix.join(assetDir, "auth.json")),
+ hostHomeDir: hostHome, log: () => {},
+ }); },
+ }],
+ });
+ env.GROK_HOME = prepared.assetDirs.home;
+ restore = () => prepared.restoreWorkspace(() => {});
+ } catch (err) {
+ // The environment test reports what is wrong with the environment; a
+ // credential-staging failure is a finding, not a crash.
+ checks.push({
+ code: "grok_environment_unprepared",
+ level: "error",
+ message: err instanceof Error ? err.message : "Could not stage the managed account into the environment",
+ });
+ }
}
const runtimeEnv = ensurePathInEnv({ ...process.env, ...env });
@@ -187,7 +209,10 @@ export async function testEnvironment(
}
const canRunProbe =
- checks.every((check) => check.code !== "grok_cwd_invalid" && check.code !== "grok_command_unresolvable");
+ checks.every((check) =>
+ check.code !== "grok_cwd_invalid" &&
+ check.code !== "grok_command_unresolvable" &&
+ check.code !== "grok_environment_unprepared");
const configuredModel = asString(config.model, DEFAULT_GROK_LOCAL_MODEL).trim();
@@ -366,5 +391,16 @@ export async function testEnvironment(
checks,
testedAt: new Date().toISOString(),
};
- } finally { try { await restore?.(); } finally { if (stagedHome) await rm(stagedHome, { recursive: true, force: true }); } }
+ } finally {
+ try { await restore?.(); } finally {
+ // Both temporary directories are removed even when one removal fails,
+ // and neither failure turns an answered environment test into a thrown
+ // error: these are best-effort temp directories, and the caller asked
+ // for checks.
+ await Promise.allSettled([
+ stagedHome ? rm(stagedHome, { recursive: true, force: true }) : undefined,
+ runtimeWorkspaceLocalDir ? rm(runtimeWorkspaceLocalDir, { recursive: true, force: true }) : undefined,
+ ]);
+ }
+ }
}