Skip to content

Commit 9ab6df9

Browse files
authored
fix(openshell): remote workspace is never seeded when the gateway restarts between sandbox create and first exec (#129809)
The remote-mode seed obligation lived only in process memory (remoteSeedPending), so a gateway restart between sandbox create and the first exec adopted the sandbox via 'sandbox get' and silently skipped the one-time seed, leaving an empty remote-canonical workspace with no visible failure. Adopted remote sandboxes now probe the managed roots once per process at the ensure boundary and arm the seed only when every root is missing or empty, so recovery can never wipe operator content in an already-seeded workspace (the seed guard shipped in v2026.7.1, so legacy seeded sandboxes without any marker exist). The probe also heals a create that timed out client-side after the sandbox actually came up. Regression test simulates create -> restart -> first exec and fails pre-fix; a sibling test locks the never-reseed-non-empty-roots invariant.
1 parent d0e492d commit 9ab6df9

3 files changed

Lines changed: 184 additions & 4 deletions

File tree

‎docs/gateway/openshell.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,10 @@ Tradeoff: upload + download cost on every exec turn.
138138

139139
`mode: "remote"` makes the **OpenShell workspace canonical**:
140140

141-
- On first sandbox creation, OpenClaw seeds the remote workspace from local
142-
once.
141+
- On first use after sandbox creation, OpenClaw seeds the remote workspace
142+
from local once. If the Gateway restarts before that first use, the next use
143+
detects the still-empty remote workspace and seeds it; a workspace that
144+
already holds content is never re-seeded.
143145
- After that, `exec`, `read`, `write`, `edit`, and `apply_patch` operate
144146
directly on the remote workspace. OpenClaw does **not** sync remote changes
145147
back to local.
@@ -509,8 +511,8 @@ openclaw logs --follow
509511
3. Core writes the SSH config to a temp file and opens an SSH session through
510512
the same remote filesystem bridge as the generic SSH backend.
511513
4. In `mirror` mode: sync local to remote before exec, run, sync back after.
512-
5. In `remote` mode: seed once on create, then operate directly on the remote
513-
workspace.
514+
5. In `remote` mode: seed once on first use, then operate directly on the
515+
remote workspace.
514516

515517
## Related
516518

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Covers the remote-mode seed obligation across a gateway restart: adopting an
2+
// existing sandbox must probe the managed roots instead of trusting process
3+
// memory, and must never re-seed roots that already hold content.
4+
import fs from "node:fs/promises";
5+
import path from "node:path";
6+
import type { CreateSandboxBackendParams } from "openclaw/plugin-sdk/sandbox";
7+
import {
8+
resolvePreferredOpenClawTmpDir,
9+
tempWorkspace,
10+
type TempWorkspace,
11+
} from "openclaw/plugin-sdk/temp-path";
12+
import {
13+
createSandboxBrowserConfig,
14+
createSandboxPruneConfig,
15+
createSandboxSshConfig,
16+
} from "openclaw/plugin-sdk/test-fixtures";
17+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
18+
import { createOpenShellSandboxBackendFactory } from "./backend.js";
19+
import { resolveOpenShellPluginConfig } from "./config.js";
20+
21+
const sdkMocks = vi.hoisted(() => ({
22+
runSshSandboxCommand: vi.fn(),
23+
disposeSshSandboxSession: vi.fn(),
24+
}));
25+
26+
const cliMocks = vi.hoisted(() => ({
27+
runOpenShellCli: vi.fn(),
28+
createOpenShellSshSession: vi.fn(),
29+
}));
30+
31+
vi.mock("openclaw/plugin-sdk/sandbox", async (importOriginal) => {
32+
const actual = await importOriginal<typeof import("openclaw/plugin-sdk/sandbox")>();
33+
return {
34+
...actual,
35+
runSshSandboxCommand: sdkMocks.runSshSandboxCommand,
36+
disposeSshSandboxSession: sdkMocks.disposeSshSandboxSession,
37+
};
38+
});
39+
40+
vi.mock("./cli.js", async (importOriginal) => {
41+
const actual = await importOriginal<typeof import("./cli.js")>();
42+
return {
43+
...actual,
44+
runOpenShellCli: cliMocks.runOpenShellCli,
45+
createOpenShellSshSession: cliMocks.createOpenShellSshSession,
46+
};
47+
});
48+
49+
const tempWorkspaces: TempWorkspace[] = [];
50+
51+
function createOpenShellBackendSandboxConfig(): CreateSandboxBackendParams["cfg"] {
52+
return {
53+
mode: "all",
54+
backend: "openshell",
55+
scope: "session",
56+
workspaceAccess: "rw",
57+
workspaceRoot: "/tmp/openclaw-sandboxes",
58+
dockerTmpfsSource: "configured",
59+
docker: {
60+
image: "openclaw-sandbox:bookworm-slim",
61+
containerPrefix: "openclaw-sbx-",
62+
workdir: "/workspace",
63+
readOnlyRoot: false,
64+
tmpfs: [],
65+
network: "none",
66+
capDrop: [],
67+
binds: [],
68+
env: {},
69+
},
70+
ssh: createSandboxSshConfig("/tmp/openclaw-sandboxes"),
71+
browser: createSandboxBrowserConfig(),
72+
tools: { allow: ["*"], deny: [] },
73+
prune: createSandboxPruneConfig(),
74+
};
75+
}
76+
77+
async function createAdoptedRemoteBackend(params: { probeStdout: string }) {
78+
const workspace = await tempWorkspace({
79+
rootDir: resolvePreferredOpenClawTmpDir(),
80+
prefix: "openclaw-openshell-remote-seed-",
81+
});
82+
tempWorkspaces.push(workspace);
83+
await fs.writeFile(path.join(workspace.dir, "seed.txt"), "seed", "utf8");
84+
cliMocks.createOpenShellSshSession.mockResolvedValue({
85+
command: "ssh",
86+
configPath: "/tmp/openclaw-openshell-test-ssh-config",
87+
host: "openshell-test",
88+
});
89+
// `sandbox get` succeeds: the sandbox was created by a previous gateway
90+
// process that died before the first exec could run the one-time seed.
91+
cliMocks.runOpenShellCli.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
92+
sdkMocks.runSshSandboxCommand.mockImplementation(async ({ remoteCommand }) => ({
93+
stdout: String(remoteCommand).includes("ls -A")
94+
? Buffer.from(params.probeStdout)
95+
: Buffer.alloc(0),
96+
stderr: Buffer.alloc(0),
97+
code: 0,
98+
}));
99+
const backendFactory = createOpenShellSandboxBackendFactory({
100+
pluginConfig: resolveOpenShellPluginConfig({
101+
command: "openshell",
102+
mode: "remote",
103+
}),
104+
});
105+
return await backendFactory({
106+
sessionKey: "agent:main:turn",
107+
scopeKey: "agent:main",
108+
workspaceDir: workspace.dir,
109+
agentWorkspaceDir: workspace.dir,
110+
cfg: createOpenShellBackendSandboxConfig(),
111+
});
112+
}
113+
114+
function seedUploadCalls() {
115+
return cliMocks.runOpenShellCli.mock.calls.filter(
116+
([params]) => params.args[0] === "sandbox" && params.args[1] === "upload",
117+
);
118+
}
119+
120+
describe("openshell remote-mode seed across gateway restart", () => {
121+
beforeEach(() => {
122+
vi.clearAllMocks();
123+
});
124+
125+
afterEach(async () => {
126+
await Promise.all(tempWorkspaces.splice(0).map((workspace) => workspace.cleanup()));
127+
});
128+
129+
it("seeds an adopted sandbox whose managed roots are empty", async () => {
130+
const backend = await createAdoptedRemoteBackend({ probeStdout: "0\n" });
131+
132+
await backend.buildExecSpec({ command: "pwd", env: {}, usePty: false });
133+
134+
const uploads = seedUploadCalls();
135+
expect(uploads.length).toBeGreaterThan(0);
136+
expect(uploads[0]?.[0]).toMatchObject({
137+
args: expect.arrayContaining([expect.stringMatching(/\/seed\.txt$/), "/sandbox/"]),
138+
});
139+
});
140+
141+
it("never re-seeds when a managed root already holds content", async () => {
142+
const backend = await createAdoptedRemoteBackend({ probeStdout: "1\n" });
143+
144+
await backend.buildExecSpec({ command: "pwd", env: {}, usePty: false });
145+
146+
expect(seedUploadCalls()).toHaveLength(0);
147+
const wipeCalls = sdkMocks.runSshSandboxCommand.mock.calls.filter(([params]) =>
148+
String(params.remoteCommand).includes("rm -rf"),
149+
);
150+
expect(wipeCalls).toHaveLength(0);
151+
});
152+
});

‎extensions/openshell/src/backend.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ function buildOpenShellDirectoryUploadArgs(params: {
6363
];
6464
}
6565

66+
// Prints "0" when every managed root is missing or empty, "1" otherwise. Any
67+
// content in a managed root means the remote workspace was already seeded (or
68+
// holds operator data) and re-seeding would destroy remote-canonical state.
69+
const REMOTE_MANAGED_ROOTS_EMPTY_SCRIPT =
70+
'for root in "$@"; do if [ -d "$root" ] && [ -n "$(ls -A "$root")" ]; then printf "1\\n"; exit 0; fi; done; printf "0\\n"';
6671
const PINNED_REMOTE_PATH_MUTATION_SCRIPT = [
6772
"set -eu",
6873
'die() { echo "$1" >&2; exit 1; }',
@@ -689,6 +694,17 @@ class OpenShellSandboxBackendImpl {
689694
throw this.buildLegacyRuntimeUnavailableError(`OpenShell reports phase "${phase}".`);
690695
}
691696
}
697+
// The seed obligation must survive a gateway restart between `sandbox
698+
// create` and the first exec: process memory is gone, so adopted remote
699+
// sandboxes probe the managed roots instead. Only completely empty roots
700+
// arm the seed — the wipe step is then a no-op, so recovery can never
701+
// destroy operator content in a remote-canonical workspace.
702+
if (
703+
this.params.execContext.config.mode === "remote" &&
704+
(await this.remoteManagedRootsEmpty())
705+
) {
706+
this.remoteSeedPending = true;
707+
}
692708
return;
693709
}
694710
if (this.params.legacyRuntimeAdopted) {
@@ -902,6 +918,16 @@ class OpenShellSandboxBackendImpl {
902918
);
903919
}
904920

921+
private async remoteManagedRootsEmpty(): Promise<boolean> {
922+
const result = await this.runRemoteShellScriptInternal({
923+
script: REMOTE_MANAGED_ROOTS_EMPTY_SCRIPT,
924+
args: [this.params.remoteWorkspaceDir, this.params.remoteAgentWorkspaceDir],
925+
});
926+
// Anything other than an exact "0" reads as non-empty so the seed never
927+
// fires on ambiguous probe output.
928+
return result.stdout.toString("utf8").trim() === "0";
929+
}
930+
905931
private async maybeSeedRemoteWorkspace(): Promise<boolean> {
906932
if (!this.remoteSeedPending) {
907933
return false;

0 commit comments

Comments
 (0)