Files
PaperClipAI/packages/adapters/grok-local/src/server/test.test.ts
T
Devin Foley 5054c9ef9b fix(grok): stage the environment test from a host directory, and survive an absent workspace (#13416)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - An agent runs through an adapter. Before you use an environment, the
adapter's environment test probes it and reports structured checks
> - The grok adapter's environment test stages the managed account into
a remote environment first. It gave the runtime its resolved `cwd` as
the host workspace directory
> - For a remote target that `cwd` is a path inside the sandbox. It does
not exist on the host that runs the test
> - A new workspace ignore scan reads that host directory. The scan
failed on the missing directory, and the error escaped the environment
test
> - The user got a server error instead of a result with checks
> - This pull request stages from a host temporary directory, sends the
remote path separately, and reports a staging failure as a check
> - The benefit is that the grok environment test always answers with
checks, and a workspace directory that does not exist no longer stops a
runtime preparation

## Linked Issues or Issue Description

No existing issue. The problem, in the bug report format:

**What happened**
The grok environment test failed with `Error: Workspace ignore scan
failed: git-ignore-scan-failed`. The route returned a server error, so
the user saw no checks at all.

**Expected behavior**
The environment test always returns `{status, checks}`. Every other
problem it finds (an invalid working directory, a command it cannot
resolve, a probe that times out) becomes a check with a level. A
credential staging problem must do the same.

**Steps to reproduce**
1. Configure a grok agent with a managed AI connection.
2. Point the agent at a remote (sandbox) environment.
3. Run the environment test for that environment.

**Paperclip version or commit**
Present on master. Both halves landed on 2026-09-12: the call site in
#13247, and the scan that it trips in #13353.

## What Changed

- `packages/adapters/grok-local/src/server/test.ts` stages the managed
account through a fresh host temporary directory and passes the remote
path as `workspaceRemoteDir`. This is the split `codex-local` and
`opencode-local` already use.
- A failure while staging becomes a `grok_environment_unprepared` check
with level `error`, instead of an exception that escapes the function.
The probe does not run after it, because there is no prepared
environment to probe.
- The temporary directory is removed in the existing `finally` block.
- `packages/adapter-utils/src/sandbox-managed-runtime.ts` treats a
`workspaceLocalDir` that does not exist as "nothing to sync". A
directory that is not there has no files for ignore rules to govern,
nothing to stage, and nothing to restore.
- Tests: the grok environment test now covers the managed-connection
remote branch, which had no coverage. `sandbox-file-sync.test.ts` covers
a preparation whose workspace directory does not exist.

## Verification

```
npx vitest run packages/adapters/grok-local/src/server/test.test.ts     # 9 passed
npx vitest run packages/adapter-utils/src/sandbox-file-sync.test.ts \
              packages/adapter-utils/src/sandbox-managed-runtime.test.ts # 90 passed
cd packages/adapter-utils && npx tsc --noEmit                            # clean
cd packages/adapters/grok-local && npx tsc --noEmit                      # clean
```

The two new grok tests fail against the old call site: the first asserts
the runtime never receives the remote path as its host workspace
directory, and the second asserts a staging failure becomes a check
instead of an exception.

## Risks

Low risk, and limited to environment preparation.

- The adapter change only affects the managed-connection remote branch
of one adapter's environment test.
- The `adapter-utils` change makes a preparation that used to throw now
continue with no workspace sync. A real workspace is unaffected, because
the directory exists in that case and the scan runs exactly as before.
- No migration. No API change.

## Model Used

- Claude Fable 5 (`claude-fable-5`), 1M context, extended thinking, run
through Claude Code with tool use and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes — no
documented behavior changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green — pending first run
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
pending first review
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-09-14 09:34:50 -07:00

343 lines
12 KiB
TypeScript

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", () => {
it("extracts auth state and models from `grok models` output", () => {
expect(parseGrokModelsOutput([
"You are logged in with grok.com.",
"",
"Default model: grok-build",
"",
"Available models:",
" * grok-build (default)",
" * grok-code",
].join("\n"))).toEqual({
authenticated: true,
defaultModel: "grok-build",
models: ["grok-build", "grok-code"],
});
});
});
describe("grok_local testEnvironment", () => {
beforeEach(() => {
ensureDirectoryMock.mockClear();
ensureCommandMock.mockClear();
runProcessMock.mockReset();
prepareRuntimeMock.mockReset();
stageGrokHomeMock.mockClear();
});
it("reports a healthy authenticated host with a working hello probe", async () => {
runProcessMock
.mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: [
"You are logged in with grok.com.",
"",
"Default model: grok-build",
"",
"Available models:",
" * grok-build (default)",
].join("\n"),
stderr: "",
})
.mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: [
JSON.stringify({ type: "text", data: "hello" }),
JSON.stringify({ type: "end", stopReason: "EndTurn", sessionId: "sess-1", requestId: "req-1" }),
].join("\n"),
stderr: "",
});
const result = await testEnvironment({
companyId: "company-1",
adapterType: "grok_local",
config: {
command: "grok",
cwd: "/tmp/project",
model: "grok-build",
},
});
expect(result.status).toBe("pass");
expect(result.checks.map((check: { code: string }) => check.code)).toEqual(
expect.arrayContaining([
"grok_command_resolvable",
"grok_models_probe_passed",
"grok_model_configured",
"grok_hello_probe_passed",
]),
);
expect(runProcessMock).toHaveBeenNthCalledWith(
2,
expect.any(String),
null,
"grok",
expect.arrayContaining([
"--output-format",
"streaming-json",
"--always-approve",
"--permission-mode",
"dontAsk",
"--disable-web-search",
"--single",
"Respond with exactly hello.",
]),
expect.any(Object),
);
});
it("does not warn when the default-sentinel model is absent from the real model list", async () => {
// Real grok never lists the "grok-build" sentinel; execute.ts never sends
// it. The probe must treat the default as valid (info), not warn.
runProcessMock
.mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: [
"You are logged in with grok.com.",
"",
"Default model: grok-4.20-0309-non-reasoning",
"",
"Available models:",
" * grok-4.20-0309-non-reasoning (default)",
" * grok-4",
].join("\n"),
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: "/tmp/project" }, // no model → default sentinel
});
const codes = result.checks.map((check: { code: string }) => check.code);
expect(codes).toContain("grok_model_configured");
expect(codes).not.toContain("grok_model_not_found");
expect(result.status).toBe("pass");
});
it("warns when an explicitly configured real model is not available", async () => {
runProcessMock
.mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: [
"You are logged in with grok.com.",
"",
"Default model: grok-4",
"",
"Available models:",
" * grok-4",
].join("\n"),
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: "/tmp/project", model: "grok-nonexistent" },
});
expect(result.checks.map((check: { code: string }) => check.code)).toContain("grok_model_not_found");
});
it("downgrades auth failures to warnings", async () => {
runProcessMock
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "Not logged in. Run `grok login`.",
})
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "Not logged in. Run `grok login`.",
});
const result = await testEnvironment({
companyId: "company-1",
adapterType: "grok_local",
config: {
command: "grok",
cwd: "/tmp/project",
},
});
expect(result.status).toBe("warn");
expect(result.checks.map((check: { code: string }) => check.code)).toEqual(
expect.arrayContaining([
"grok_auth_required",
"grok_hello_probe_auth_required",
]),
);
});
it("emits the canonical adapter_auth_missing check for a sandbox target with missing authentication", async () => {
// The user interface reads this neutral canonical code to decide login
// eligibility for the sandbox; it does not parse the message text.
runProcessMock
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "Not logged in. Run `grok login`.",
})
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "Not logged in. Run `grok login`.",
});
const result = await testEnvironment({
companyId: "company-1",
adapterType: "grok_local",
config: { command: "grok", cwd: "/tmp/project" },
executionTarget: { kind: "remote", transport: "sandbox" } as never,
});
expect(result.checks.some((check: { code: string }) => check.code === "adapter_auth_missing")).toBe(
true,
);
});
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.
runProcessMock
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "Not logged in. Run `grok login`.",
})
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "Not logged in. Run `grok login`.",
});
const result = await testEnvironment({
companyId: "company-1",
adapterType: "grok_local",
config: { command: "grok", cwd: "/tmp/project" },
});
expect(result.checks.some((check: { code: string }) => check.code === "adapter_auth_missing")).toBe(
false,
);
});
});