Compare commits

..
Author SHA1 Message Date
Peter Steinberger 3dee99fe73 fix: improve sandbox image inspect handling (#1548) (thanks @sweepies) 2026-01-24 00:30:00 +00:00
google-labs-jules[bot] 4e92b620c4 fix(doctor): align sandbox image check with main logic
Updated `dockerImageExists` in `src/commands/doctor-sandbox.ts` to mirror the logic in `src/agents/sandbox/docker.ts`. It now re-throws errors unless they are explicitly "No such image" errors.
2026-01-24 00:13:26 +00:00
google-labs-jules[bot] 2091b4aed0 fix(sandbox): improve docker image existence check error handling
- Modifies `dockerImageExists` to inspect stderr when the exit code is non-zero.
- Returns `false` only if the error explicitly indicates "No such image".
- Throws an error with the stderr content for all other failures.
2026-01-24 00:13:26 +00:00
google-labs-jules[bot] 78ef609d7b chore(tests): remove reproduction test
Removed the test file `src/agents/sandbox/docker.test.ts` as requested in code review.
2026-01-24 00:13:26 +00:00
google-labs-jules[bot] d76d9b07bc fix(sandbox): simplify docker image check
Simplify the stderr check in `dockerImageExists` to only look for "No such image", as requested in code review.
2026-01-24 00:13:25 +00:00
google-labs-jules[bot] 39f4faff1e fix(sandbox): improve docker image existence check error handling
Previously, `dockerImageExists` assumed any error from `docker image inspect` meant the image did not exist. This masked other errors like socket permission issues.

This change:
- Modifies `dockerImageExists` to inspect stderr when the exit code is non-zero.
- Returns `false` only if the error explicitly indicates "No such image" or "No such object".
- Throws an error with the stderr content for all other failures.
- Adds a reproduction test in `src/agents/sandbox/docker.test.ts`.
2026-01-24 00:13:25 +00:00
11 changed files with 133 additions and 240 deletions

No files matched your search

-1
View File
@@ -7,7 +7,6 @@
- Tests: colocated `*.test.ts`.
- Docs: `docs/` (images, queue, Pi config). Built output lives in `dist/`.
- Plugins/extensions: live under `extensions/*` (workspace packages). Keep plugin-only deps in the extension `package.json`; do not add them to the root `package.json` unless core uses them.
- Plugins: install runs `npm install --omit=dev` in plugin dir; runtime deps must live in `dependencies`. Avoid `workspace:*` in `dependencies` (npm install breaks); put `clawdbot` in `devDependencies` or `peerDependencies` instead (runtime resolves `clawdbot/plugin-sdk` via jiti alias).
- Installers served from `https://clawd.bot/*`: live in the sibling repo `../clawd.bot` (`public/install.sh`, `public/install-cli.sh`, `public/install.ps1`).
- Messaging channels: always consider **all** built-in + extension channels when refactoring shared logic (routing, allowlists, pairing, command gating, onboarding, docs).
- Core channel docs: `docs/channels/`
+1 -2
View File
@@ -8,13 +8,12 @@ Docs: https://docs.clawd.bot
- CLI: restart the gateway by default after `clawdbot update`; add `--no-restart` to skip it.
- CLI: add live auth probes to `clawdbot models status` for per-profile verification.
- Markdown: add per-channel table conversion (bullets for Signal/WhatsApp, code blocks elsewhere). (#1495) Thanks @odysseus0.
- Docs: remove the misplaced Google Docs Editor entry from the showcase. (#1547) Thanks @aj47.
### Fixes
- Voice wake: auto-save wake words on blur/submit across iOS/Android and align limits with macOS.
- Tailscale: retry serve/funnel with sudo only for permission errors and keep original failure details. (#1551) Thanks @sweepies.
- Discord: limit autoThread mention bypass to bot-owned threads; keep ack reactions mention-gated. (#1511) Thanks @pvoo.
- Gateway: accept null optional fields in exec approval requests. (#1511) Thanks @pvoo.
- Sandbox: log docker image inspect failures during doctor checks. (#1548) Thanks @sweepies.
- TUI: forward unknown slash commands (for example, `/context`) to the Gateway.
- TUI: include Gateway slash commands in autocomplete and `/help`.
- CLI: skip usage lines in `clawdbot models status` when provider usage is unavailable.
+7 -1
View File
@@ -327,10 +327,16 @@ Full setup walkthrough (28m) by VelvetShark.
<Card title="OpenRouter Transcription" icon="microphone" href="https://clawdhub.com/obviyus/openrouter-transcribe">
**@obviyus** • `transcription` `multilingual` `skill`
Multi-lingual audio transcription via OpenRouter (Gemini, etc). Available on ClawdHub.
</Card>
<Card title="Google Docs Editor" icon="file-word">
**Community** • `docs` `editing` `skill`
Rich-text Google Docs editing skill. Built rapidly with Claude Code.
</Card>
</CardGroup>
## 🏗️ Infrastructure & Deployment
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { resolveDockerImageInspectResult } from "./sandbox/docker.js";
describe("ensureDockerImage", () => {
it("surfaces inspect failures with detail", async () => {
const result = resolveDockerImageInspectResult("custom-sandbox:latest", {
stdout: "",
stderr: "permission denied while trying to connect to the Docker daemon socket",
code: 1,
});
expect(result).toEqual({
exists: false,
error:
"Failed to inspect sandbox image: permission denied while trying to connect to the Docker daemon socket",
});
});
});
+15 -1
View File
@@ -46,11 +46,25 @@ export async function readDockerPort(containerName: string, port: number) {
return Number.isFinite(mapped) ? mapped : null;
}
export function resolveDockerImageInspectResult(
image: string,
result: { stdout: string; stderr: string; code: number },
): { exists: boolean; error?: string } {
if (result.code === 0) return { exists: true };
const stderr = result.stderr.trim();
if (/no such image/i.test(stderr)) return { exists: false };
const stdout = result.stdout.trim();
const detail = stderr || stdout || `docker image inspect ${image} failed (exit ${result.code})`;
return { exists: false, error: `Failed to inspect sandbox image: ${detail}` };
}
async function dockerImageExists(image: string) {
const result = await execDocker(["image", "inspect", image], {
allowFailure: true,
});
return result.code === 0;
const resolved = resolveDockerImageInspectResult(image, result);
if (resolved.error) throw new Error(resolved.error);
return resolved.exists;
}
export async function ensureDockerImage(image: string) {
@@ -0,0 +1,61 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ClawdbotConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import type { DoctorPrompter } from "./doctor-prompter.js";
const runExec = vi.fn();
const runCommandWithTimeout = vi.fn();
const note = vi.fn();
vi.mock("../process/exec.js", () => ({
runExec,
runCommandWithTimeout,
}));
vi.mock("../terminal/note.js", () => ({
note,
}));
describe("maybeRepairSandboxImages", () => {
beforeEach(() => {
runExec.mockReset();
runCommandWithTimeout.mockReset();
note.mockReset();
});
it("logs docker inspect errors and continues", async () => {
runExec.mockImplementation(async (_command: string, args: string[]) => {
if (args[0] === "version") return { stdout: "26.0.0", stderr: "" };
if (args[0] === "image" && args[1] === "inspect") {
const err = new Error(
"permission denied while trying to connect to the Docker daemon socket",
) as Error & { stderr?: string };
err.stderr = "permission denied while trying to connect to the Docker daemon socket";
throw err;
}
return { stdout: "", stderr: "" };
});
const { maybeRepairSandboxImages } = await import("./doctor-sandbox.js");
const cfg = {
agents: {
defaults: {
sandbox: {
mode: "all",
docker: { image: "custom-sandbox:latest" },
},
},
},
} satisfies ClawdbotConfig;
const runtime = { log: vi.fn(), error: vi.fn() } as RuntimeEnv;
const prompter = { confirmSkipInNonInteractive: vi.fn() } as DoctorPrompter;
await expect(maybeRepairSandboxImages(cfg, runtime, prompter)).resolves.toBe(cfg);
expect(note).toHaveBeenCalledWith(
expect.stringContaining("Unable to inspect sandbox base image (custom-sandbox:latest)"),
"Sandbox",
);
expect(runCommandWithTimeout).not.toHaveBeenCalled();
});
});
+20 -3
View File
@@ -78,8 +78,15 @@ async function dockerImageExists(image: string): Promise<boolean> {
try {
await runExec("docker", ["image", "inspect", image], { timeoutMs: 5_000 });
return true;
} catch {
return false;
} catch (error: any) {
const stderr = typeof error?.stderr === "string" ? error.stderr.trim() : "";
const stdout = typeof error?.stdout === "string" ? error.stdout.trim() : "";
const message = typeof error?.message === "string" ? error.message.trim() : "";
const detail = stderr || stdout || message;
if (/no such image/i.test(detail)) {
return false;
}
throw new Error(`Failed to inspect sandbox image: ${detail || "unknown error"}`);
}
}
@@ -143,7 +150,17 @@ async function handleMissingSandboxImage(
runtime: RuntimeEnv,
prompter: DoctorPrompter,
) {
const exists = await dockerImageExists(params.image);
let exists = false;
try {
exists = await dockerImageExists(params.image);
} catch (error: any) {
const stderr = typeof error?.stderr === "string" ? error.stderr.trim() : "";
const stdout = typeof error?.stdout === "string" ? error.stdout.trim() : "";
const message = typeof error?.message === "string" ? error.message.trim() : "";
const detail = stderr || stdout || message || "unknown error";
note(`Unable to inspect sandbox ${params.label} image (${params.image}): ${detail}`, "Sandbox");
return;
}
if (exists) return;
const buildHint = params.buildScript
-4
View File
@@ -251,10 +251,6 @@ export const sessionsHandlers: GatewayRequestHandlers = {
lastChannel: entry?.lastChannel,
lastTo: entry?.lastTo,
skillsSnapshot: entry?.skillsSnapshot,
// Reset token counts to 0 on session reset (#1523)
inputTokens: 0,
outputTokens: 0,
totalTokens: 0,
};
store[primaryKey] = nextEntry;
return nextEntry;
+2 -150
View File
@@ -1,21 +1,8 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vitest";
import * as tailscale from "./tailscale.js";
const {
ensureGoInstalled,
ensureTailscaledInstalled,
getTailnetHostname,
enableTailscaleServe,
disableTailscaleServe,
ensureFunnel,
} = tailscale;
import { ensureGoInstalled, ensureTailscaledInstalled, getTailnetHostname } from "./tailscale.js";
describe("tailscale helpers", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("parses DNS name from tailscale status", async () => {
const exec = vi.fn().mockResolvedValue({
stdout: JSON.stringify({
@@ -61,139 +48,4 @@ describe("tailscale helpers", () => {
await ensureTailscaledInstalled(exec as never, prompt, runtime);
expect(exec).toHaveBeenCalledWith("brew", ["install", "tailscale"]);
});
it("enableTailscaleServe attempts normal first, then sudo", async () => {
// 1. First attempt fails
// 2. Second attempt (sudo) succeeds
const exec = vi
.fn()
.mockRejectedValueOnce(new Error("permission denied"))
.mockResolvedValueOnce({ stdout: "" });
await enableTailscaleServe(3000, exec as never);
expect(exec).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/tailscale$/),
expect.arrayContaining(["serve", "--bg", "--yes", "3000"]),
expect.any(Object),
);
expect(exec).toHaveBeenNthCalledWith(
2,
"sudo",
expect.arrayContaining([
"-n",
expect.stringMatching(/tailscale$/),
"serve",
"--bg",
"--yes",
"3000",
]),
expect.any(Object),
);
});
it("enableTailscaleServe does NOT use sudo if first attempt succeeds", async () => {
const exec = vi.fn().mockResolvedValue({ stdout: "" });
await enableTailscaleServe(3000, exec as never);
expect(exec).toHaveBeenCalledTimes(1);
expect(exec).toHaveBeenCalledWith(
expect.stringMatching(/tailscale$/),
expect.arrayContaining(["serve", "--bg", "--yes", "3000"]),
expect.any(Object),
);
});
it("disableTailscaleServe uses fallback", async () => {
const exec = vi
.fn()
.mockRejectedValueOnce(new Error("permission denied"))
.mockResolvedValueOnce({ stdout: "" });
await disableTailscaleServe(exec as never);
expect(exec).toHaveBeenCalledTimes(2);
expect(exec).toHaveBeenNthCalledWith(
2,
"sudo",
expect.arrayContaining(["-n", expect.stringMatching(/tailscale$/), "serve", "reset"]),
expect.any(Object),
);
});
it("ensureFunnel uses fallback for enabling", async () => {
// Mock exec:
// 1. status (success)
// 2. enable (fails)
// 3. enable sudo (success)
const exec = vi
.fn()
.mockResolvedValueOnce({ stdout: JSON.stringify({ BackendState: "Running" }) }) // status
.mockRejectedValueOnce(new Error("permission denied")) // enable normal
.mockResolvedValueOnce({ stdout: "" }); // enable sudo
const runtime = {
error: vi.fn(),
log: vi.fn(),
exit: vi.fn() as unknown as (code: number) => never,
};
const prompt = vi.fn();
await ensureFunnel(8080, exec as never, runtime, prompt);
// 1. status
expect(exec).toHaveBeenNthCalledWith(
1,
expect.stringMatching(/tailscale$/),
expect.arrayContaining(["funnel", "status", "--json"]),
);
// 2. enable normal
expect(exec).toHaveBeenNthCalledWith(
2,
expect.stringMatching(/tailscale$/),
expect.arrayContaining(["funnel", "--yes", "--bg", "8080"]),
expect.any(Object),
);
// 3. enable sudo
expect(exec).toHaveBeenNthCalledWith(
3,
"sudo",
expect.arrayContaining([
"-n",
expect.stringMatching(/tailscale$/),
"funnel",
"--yes",
"--bg",
"8080",
]),
expect.any(Object),
);
});
it("enableTailscaleServe skips sudo on non-permission errors", async () => {
const exec = vi.fn().mockRejectedValueOnce(new Error("boom"));
await expect(enableTailscaleServe(3000, exec as never)).rejects.toThrow("boom");
expect(exec).toHaveBeenCalledTimes(1);
});
it("enableTailscaleServe rethrows original error if sudo fails", async () => {
const originalError = Object.assign(new Error("permission denied"), {
stderr: "permission denied",
});
const exec = vi
.fn()
.mockRejectedValueOnce(originalError)
.mockRejectedValueOnce(new Error("sudo: a password is required"));
await expect(enableTailscaleServe(3000, exec as never)).rejects.toBe(originalError);
expect(exec).toHaveBeenCalledTimes(2);
});
});
+8 -72
View File
@@ -206,64 +206,6 @@ export async function ensureTailscaledInstalled(
await exec("brew", ["install", "tailscale"]);
}
type ExecErrorDetails = {
stdout?: unknown;
stderr?: unknown;
message?: unknown;
code?: unknown;
};
function extractExecErrorText(err: unknown) {
const errOutput = err as ExecErrorDetails;
const stdout = typeof errOutput.stdout === "string" ? errOutput.stdout : "";
const stderr = typeof errOutput.stderr === "string" ? errOutput.stderr : "";
const message = typeof errOutput.message === "string" ? errOutput.message : "";
const code = typeof errOutput.code === "string" ? errOutput.code : "";
return { stdout, stderr, message, code };
}
function isPermissionDeniedError(err: unknown): boolean {
const { stdout, stderr, message, code } = extractExecErrorText(err);
if (code.toUpperCase() === "EACCES") return true;
const combined = `${stdout}\n${stderr}\n${message}`.toLowerCase();
return (
combined.includes("permission denied") ||
combined.includes("access denied") ||
combined.includes("operation not permitted") ||
combined.includes("not permitted") ||
combined.includes("requires root") ||
combined.includes("must be run as root") ||
combined.includes("must be run with sudo") ||
combined.includes("requires sudo") ||
combined.includes("need sudo")
);
}
// Helper to attempt a command, and retry with sudo if it fails.
async function execWithSudoFallback(
exec: typeof runExec,
bin: string,
args: string[],
opts: { maxBuffer?: number; timeoutMs?: number },
): Promise<{ stdout: string; stderr: string }> {
try {
return await exec(bin, args, opts);
} catch (err) {
if (!isPermissionDeniedError(err)) {
throw err;
}
logVerbose(`Command failed, retrying with sudo: ${bin} ${args.join(" ")}`);
try {
return await exec("sudo", ["-n", bin, ...args], opts);
} catch (sudoErr) {
const { stderr, message } = extractExecErrorText(sudoErr);
const detail = (stderr || message).trim();
if (detail) logVerbose(`Sudo retry failed: ${detail}`);
throw err;
}
}
}
export async function ensureFunnel(
port: number,
exec: typeof runExec = runExec,
@@ -295,16 +237,10 @@ export async function ensureFunnel(
}
logVerbose(`Enabling funnel on port ${port}…`);
// Attempt with fallback
const { stdout } = await execWithSudoFallback(
exec,
tailscaleBin,
["funnel", "--yes", "--bg", `${port}`],
{
maxBuffer: 200_000,
timeoutMs: 15_000,
},
);
const { stdout } = await exec(tailscaleBin, ["funnel", "--yes", "--bg", `${port}`], {
maxBuffer: 200_000,
timeoutMs: 15_000,
});
if (stdout.trim()) console.log(stdout.trim());
} catch (err) {
const errOutput = err as { stdout?: unknown; stderr?: unknown };
@@ -352,7 +288,7 @@ export async function ensureFunnel(
export async function enableTailscaleServe(port: number, exec: typeof runExec = runExec) {
const tailscaleBin = await getTailscaleBinary();
await execWithSudoFallback(exec, tailscaleBin, ["serve", "--bg", "--yes", `${port}`], {
await exec(tailscaleBin, ["serve", "--bg", "--yes", `${port}`], {
maxBuffer: 200_000,
timeoutMs: 15_000,
});
@@ -360,7 +296,7 @@ export async function enableTailscaleServe(port: number, exec: typeof runExec =
export async function disableTailscaleServe(exec: typeof runExec = runExec) {
const tailscaleBin = await getTailscaleBinary();
await execWithSudoFallback(exec, tailscaleBin, ["serve", "reset"], {
await exec(tailscaleBin, ["serve", "reset"], {
maxBuffer: 200_000,
timeoutMs: 15_000,
});
@@ -368,7 +304,7 @@ export async function disableTailscaleServe(exec: typeof runExec = runExec) {
export async function enableTailscaleFunnel(port: number, exec: typeof runExec = runExec) {
const tailscaleBin = await getTailscaleBinary();
await execWithSudoFallback(exec, tailscaleBin, ["funnel", "--bg", "--yes", `${port}`], {
await exec(tailscaleBin, ["funnel", "--bg", "--yes", `${port}`], {
maxBuffer: 200_000,
timeoutMs: 15_000,
});
@@ -376,7 +312,7 @@ export async function enableTailscaleFunnel(port: number, exec: typeof runExec =
export async function disableTailscaleFunnel(exec: typeof runExec = runExec) {
const tailscaleBin = await getTailscaleBinary();
await execWithSudoFallback(exec, tailscaleBin, ["funnel", "reset"], {
await exec(tailscaleBin, ["funnel", "reset"], {
maxBuffer: 200_000,
timeoutMs: 15_000,
});
-6
View File
@@ -408,12 +408,6 @@ export function createCommandHandlers(context: CommandHandlerContext) {
case "new":
case "reset":
try {
// Clear token counts immediately to avoid stale display (#1523)
state.sessionInfo.inputTokens = null;
state.sessionInfo.outputTokens = null;
state.sessionInfo.totalTokens = null;
tui.requestRender();
await client.resetSession(state.currentSessionKey);
chatLog.addSystem(`session ${state.currentSessionKey} reset`);
await loadHistory();