From b87b720ddb98a525c8b6fc370bb40f5adfe688bf Mon Sep 17 00:00:00 2001 From: Ashish Jha Date: Tue, 17 Nov 2026 23:48:38 +0530 Subject: [PATCH 1/2] fix: expand ~ and resolve relative workspace paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The workspace path reached `docker run -v :/workspace` exactly as typed. The onboard prompt returns raw text, so `~/silo-workspace` (one of the examples the CLI reference gives) was saved as-is and mkdir created a literal "./~/silo-workspace", while a bare name such as `ws` would make Docker mount a named volume instead of the host folder. `start --workspace` passed its value through the same way. --mount sources already went through expandHostPath() in start.ts. Move it to src/utils/paths.ts and use it for the workspace too: - onboard expands the answer before creating the directory and saving it. - start expands --workspace and the configured path, so configs saved before this fix work without re-running onboard. - doctor checks the expanded path, so a "~/…" config isn't reported as a missing directory, and its fix hint no longer suggests mkdir -p "~/…" (quoted, so a shell creates a literal "~"). Fixes #23 --- docs/cli-reference.md | 2 +- src/commands/doctor.ts | 13 ++++++++---- src/commands/onboard.ts | 6 +++++- src/commands/start.ts | 14 ++++++------- src/utils/paths.ts | 20 ++++++++++++++++++ tests/cli.test.ts | 38 ++++++++++++++++++++++++---------- tests/commands/onboard.test.ts | 24 +++++++++++++++++++++ tests/utils/paths.test.ts | 30 +++++++++++++++++++++++++++ 8 files changed, 122 insertions(+), 25 deletions(-) create mode 100644 src/utils/paths.ts create mode 100644 tests/utils/paths.test.ts diff --git a/docs/cli-reference.md b/docs/cli-reference.md index c5a7ef5..b20a19d 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -105,7 +105,7 @@ silo start [--policy ] [--rebuild] [--name ] [--workspace ] [ | `-p, --policy ` | string | from onboard | Path to a YAML policy file | | `--rebuild` | boolean | `false` | Rebuild the sandbox image before starting | | `-n, --name ` | string | from config | Name the agent (creates container `silo-`) | -| `-w, --workspace ` | string | from config | Override the workspace path for this agent | +| `-w, --workspace ` | string | from config | Override the workspace path for this agent. `~` and relative paths are resolved to an absolute path | | `--desktop` | boolean | `false` | Mount the host Desktop at `/host/Desktop` | | `--mount ` | string | — | Mount a host path into `/host/...`, e.g. `~/Downloads:/host/Downloads:ro` | | `-f, --framework ` | string | — | Start with a specific framework (uses framework image) | diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts index ae8f63e..cb8dcd3 100644 --- a/src/commands/doctor.ts +++ b/src/commands/doctor.ts @@ -22,6 +22,7 @@ import { resolve } from "node:path"; import { execa } from "execa"; import { readConfig, configPath } from "../config/manager.js"; import { log, printBanner, section } from "../utils/logger.js"; +import { expandHostPath } from "../utils/paths.js"; import { isContainerRunning, containerExists } from "../utils/system.js"; import { isProxyAlive, readPid } from "../utils/pid.js"; import { proxyLogPath } from "../proxy/spawn.js"; @@ -331,18 +332,22 @@ export async function runDoctor(): Promise { } // ── 9. Workspace ────────────────────────────────────────────────────── - if (existsSync(config.sandbox.workspacePath)) { + // Check the path start will actually mount: a config saved with "~/…" + // would otherwise be reported missing, and `mkdir -p "~/…"` (quoted, so + // the shell won't expand it) would create a literal "~" directory. + const workspacePath = expandHostPath(config.sandbox.workspacePath); + if (existsSync(workspacePath)) { results.push({ name: "Workspace", status: "pass", - message: config.sandbox.workspacePath, + message: workspacePath, }); } else { results.push({ name: "Workspace", status: "warn", - message: `Directory does not exist: ${config.sandbox.workspacePath}`, - fix: `Create it with: mkdir -p "${config.sandbox.workspacePath}"`, + message: `Directory does not exist: ${workspacePath}`, + fix: `Create it with: mkdir -p "${workspacePath}"`, }); } diff --git a/src/commands/onboard.ts b/src/commands/onboard.ts index 790b0f7..70f8d49 100644 --- a/src/commands/onboard.ts +++ b/src/commands/onboard.ts @@ -11,6 +11,7 @@ import { writeConfig, readConfig } from "../config/manager.js"; import type { SiloConfig, LLMProvider } from "../config/schema.js"; import { log, section } from "../utils/logger.js"; import { assertDockerAvailable } from "../utils/system.js"; +import { expandHostPath } from "../utils/paths.js"; import { defaultPolicyPath, writePolicyFile, @@ -316,7 +317,7 @@ export async function runOnboard(opts: { force: boolean }): Promise { section("Step 4 — Workspace"); const defaultWorkspace = join(homedir(), "silo-workspace"); - const { workspacePath } = await inquirer.prompt<{ workspacePath: string }>([ + const { workspacePath: workspaceAnswer } = await inquirer.prompt<{ workspacePath: string }>([ { type: "input", name: "workspacePath", @@ -326,6 +327,9 @@ export async function runOnboard(opts: { force: boolean }): Promise { v.trim().length > 0 ? true : "Path cannot be empty.", }, ]); + // The prompt returns the text as typed: expand ~ and make it absolute, or + // mkdir creates a literal "./~/…" and Docker can't bind-mount it. + const workspacePath = expandHostPath(workspaceAnswer.trim()); log.blank(); section("Step 5 — Resource Limits"); diff --git a/src/commands/start.ts b/src/commands/start.ts index 3a4d803..fa02d01 100644 --- a/src/commands/start.ts +++ b/src/commands/start.ts @@ -3,7 +3,7 @@ import chalk from "chalk"; import { execa } from "execa"; import { existsSync } from "node:fs"; import { homedir } from "node:os"; -import { join, resolve } from "node:path"; +import { join } from "node:path"; import { readConfig, patchConfig } from "../config/manager.js"; import { startContainer } from "../docker/runner.js"; import { SILO_NETWORK } from "../docker/templates.js"; @@ -25,6 +25,7 @@ import { import type { FrameworkDefinition } from "../frameworks/registry.js"; import type { HostMount, IntegrationConfig } from "../config/schema.js"; import { applyPreset, getPreset } from "../policy/presets.js"; +import { expandHostPath } from "../utils/paths.js"; interface StartOptions { policy?: string; @@ -131,7 +132,10 @@ export async function runStart(opts: StartOptions): Promise { containerName, image, memoryLimit: browserMemory.memoryLimit, - ...(opts.workspace ? { workspacePath: opts.workspace } : {}), + // Expand ~ and resolve relative paths, for --workspace and for configs + // saved before onboard did this. A raw path becomes `-v :/workspace`, + // which Docker rejects (~/ws) or turns into a named volume (ws). + workspacePath: expandHostPath(opts.workspace ?? config.sandbox.workspacePath), ...(opts.policy ? { policyFile: opts.policy } : {}), ...(hostMounts.length > 0 ? { hostMounts } : {}), ...(framework ? { activeFramework: framework.id } : {}), @@ -426,12 +430,6 @@ function parseHostMountSpec(spec: string): HostMount { return { source, target, mode }; } -function expandHostPath(path: string): string { - if (path === "~") return homedir(); - if (path.startsWith("~/")) return resolve(homedir(), path.slice(2)); - return resolve(path); -} - export function ensureBrowserMemoryLimit(memoryLimit: string): { memoryLimit: string; bumped: boolean; diff --git a/src/utils/paths.ts b/src/utils/paths.ts new file mode 100644 index 0000000..8e8cf17 --- /dev/null +++ b/src/utils/paths.ts @@ -0,0 +1,20 @@ +/** + * Host path helpers. + */ +import { homedir } from "node:os"; +import { resolve } from "node:path"; + +/** + * Turn a user-supplied host path into the absolute path Docker needs. + * + * Expands a leading `~` (a shell would, but prompts, flags read from config + * and YAML don't) and resolves relative paths against the current directory. + * Docker rejects a `~/…` bind-mount source and treats a bare name such as `ws` + * as a named volume, so a raw path either fails or silently mounts something + * other than the host folder the user meant. + */ +export function expandHostPath(path: string): string { + if (path === "~") return homedir(); + if (path.startsWith("~/")) return resolve(homedir(), path.slice(2)); + return resolve(path); +} diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 0c5f7a0..e926e8f 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -75,15 +75,28 @@ esac describe("exit codes when a command fails", () => { let fakeBin: string; let configuredHome: string; + let legacyHome: string; beforeAll(async () => { fakeBin = mkdtempSync(join(tmpdir(), "silo-fake-docker-")); writeFileSync(join(fakeBin, "docker"), FAKE_DOCKER); chmodSync(join(fakeBin, "docker"), 0o755); - // A real, valid config written through the config manager. - configuredHome = mkdtempSync(join(tmpdir(), "silo-cli-home-")); - mkdirSync(join(configuredHome, "ws")); + configuredHome = await homeWithConfig((h) => join(h, "ws")); + // A config saved before workspace paths were expanded: "~/ws" verbatim. + legacyHome = await homeWithConfig(() => "~/ws"); + }, 30_000); + + afterAll(() => { + rmSync(fakeBin, { recursive: true, force: true }); + rmSync(configuredHome, { recursive: true, force: true }); + rmSync(legacyHome, { recursive: true, force: true }); + }); + + /** A temp HOME holding a real, valid config written through the config manager. */ + async function homeWithConfig(workspace: (homeDir: string) => string): Promise { + const homeDir = mkdtempSync(join(tmpdir(), "silo-cli-home-")); + mkdirSync(join(homeDir, "ws")); const write = ` const { writeConfig } = await import("./src/config/manager.ts"); const { SiloConfigSchema } = await import("./src/config/schema.ts"); @@ -91,18 +104,14 @@ describe("exit codes when a command fails", () => { version: "1", llm: { provider: "openai", apiKey: "sk-test-key", model: "gpt-4o" }, sandbox: { image: "silo-sandbox:latest", containerName: "silo-agent", - workspacePath: ${JSON.stringify(join(configuredHome, "ws"))}, cpuLimit: "1.0", memoryLimit: "1g", autoOpenLogs: false }, + workspacePath: ${JSON.stringify(workspace(homeDir))}, cpuLimit: "1.0", memoryLimit: "1g", autoOpenLogs: false }, }));`; await execa("node", ["--import", "tsx", "--input-type=module", "-e", write], { cwd: repoRoot, - env: isolatedEnv(configuredHome), + env: isolatedEnv(homeDir), }); - }, 30_000); - - afterAll(() => { - rmSync(fakeBin, { recursive: true, force: true }); - rmSync(configuredHome, { recursive: true, force: true }); - }); + return homeDir; + } function siloWith(homeDir: string, fail: string, ...args: string[]) { return execa("node", ["--import", "tsx", "src/cli.ts", ...args], { @@ -139,4 +148,11 @@ describe("exit codes when a command fails", () => { const result = await siloWith(configuredHome, "", "snapshot", "delete", "present"); expect(result.exitCode).toBe(0); }, 30_000); + + it("doctor checks the expanded workspace path from an older ~/ config", async () => { + const result = await siloWith(legacyHome, "", "doctor"); + const out = result.stdout + result.stderr; + expect(out).toContain(`Workspace: ${join(legacyHome, "ws")}`); + expect(out).not.toMatch(/Directory does not exist/); + }, 30_000); }); diff --git a/tests/commands/onboard.test.ts b/tests/commands/onboard.test.ts index 92b0894..eaf0f67 100644 --- a/tests/commands/onboard.test.ts +++ b/tests/commands/onboard.test.ts @@ -1,4 +1,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; +import { homedir } from "node:os"; +import { join, resolve } from "node:path"; /** * Unit tests for the onboard command. @@ -84,6 +86,28 @@ describe("onboard command", () => { expect(saved.version).toBe("1"); }); + it.each([ + ["~/silo-ws", () => join(homedir(), "silo-ws")], + ["silo-ws", () => resolve(process.cwd(), "silo-ws")], + ])("saves the workspace %s as an absolute path", async (answer, expected) => { + const inquirer = (await import("inquirer")).default; + const { writeConfig } = await import("../../src/config/manager.js"); + + vi.mocked(inquirer.prompt) + .mockResolvedValueOnce({ provider: "anthropic" }) + .mockResolvedValueOnce({ apiKey: "sk-ant-test-key-1234" }) + .mockResolvedValueOnce({ model: "claude-sonnet-4-6" }) + .mockResolvedValueOnce({ workspacePath: answer }) + .mockResolvedValueOnce({ cpuLimit: "1.0", memoryLimit: "512m" }) + .mockResolvedValueOnce({ securityMode: "strict" }); + + const { runOnboard } = await import("../../src/commands/onboard.js"); + await runOnboard({ force: false }); + + const saved = (writeConfig as ReturnType).mock.calls[0][0]; + expect(saved.sandbox.workspacePath).toBe(expected()); + }); + it("exits early when already configured and --force is not passed", async () => { const { readConfig, writeConfig } = await import("../../src/config/manager.js"); (readConfig as ReturnType).mockReturnValueOnce({ diff --git a/tests/utils/paths.test.ts b/tests/utils/paths.test.ts new file mode 100644 index 0000000..1c81911 --- /dev/null +++ b/tests/utils/paths.test.ts @@ -0,0 +1,30 @@ +import { describe, it, expect } from "vitest"; +import { homedir } from "node:os"; +import { join, resolve } from "node:path"; +import { expandHostPath } from "../../src/utils/paths.js"; + +describe("expandHostPath", () => { + it("expands a bare ~ to the home directory", () => { + expect(expandHostPath("~")).toBe(homedir()); + }); + + it("expands ~/ paths against the home directory", () => { + expect(expandHostPath("~/silo-workspace")).toBe(join(homedir(), "silo-workspace")); + }); + + it("resolves a bare name to an absolute path, not a Docker volume name", () => { + expect(expandHostPath("ws")).toBe(resolve(process.cwd(), "ws")); + }); + + it("resolves relative segments", () => { + expect(expandHostPath("./a/../b")).toBe(resolve(process.cwd(), "b")); + }); + + it("leaves an absolute path unchanged", () => { + expect(expandHostPath("/tmp/workspace")).toBe("/tmp/workspace"); + }); + + it("does not treat ~user as the current user's home", () => { + expect(expandHostPath("~other/ws")).toBe(resolve(process.cwd(), "~other/ws")); + }); +}); From 2972f64807b3ae624b8e61f753ff6365d4a5998f Mon Sep 17 00:00:00 2001 From: Ashish Jha Date: Wed, 18 Nov 2026 01:50:41 +0530 Subject: [PATCH 2/2] fix: keep legacy volume workspaces and refuse ambiguous paths Review follow-up for #24. - Older configs could hold a bare name such as `ws`, which Docker mounted as the named volume `ws`. Switching that to `$CWD/ws` would hide the user's files. A new resolveWorkspaceMount() keeps mounting the volume when it exists, with a warning and steps to move to a host folder, and otherwise refuses a relative configured path instead of guessing a base folder. - An empty --workspace ("-w $WS" with WS unset) falls back to the config again, instead of resolving to the current directory. - start refuses a workspace folder that doesn't exist, as --mount already does (on Linux, Docker would create it owned by root). - expandHome()/expandHostPath() also expand Windows-style "~\". - doctor reports exactly what start would mount; status shows the ~-expanded path. - Tests: resolveWorkspaceMount unit tests (injected volume lookup), the -v source in buildRunFlags, and CLI tests for doctor recognising a volume and start refusing a bare name with no volume or a missing folder. --- docs/cli-reference.md | 4 +- src/commands/doctor.ts | 27 +++++------- src/commands/start.ts | 20 ++++++--- src/commands/status.ts | 5 ++- src/utils/paths.ts | 25 +++++++++-- src/utils/system.ts | 12 +++++ src/utils/workspace.ts | 80 +++++++++++++++++++++++++++++++++ tests/cli.test.ts | 31 ++++++++++++- tests/docker/templates.test.ts | 19 ++++++++ tests/utils/paths.test.ts | 25 ++++++++++- tests/utils/workspace.test.ts | 81 ++++++++++++++++++++++++++++++++++ 11 files changed, 299 insertions(+), 30 deletions(-) create mode 100644 src/utils/workspace.ts create mode 100644 tests/utils/workspace.test.ts diff --git a/docs/cli-reference.md b/docs/cli-reference.md index b20a19d..14cd4e9 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -105,7 +105,7 @@ silo start [--policy ] [--rebuild] [--name ] [--workspace ] [ | `-p, --policy ` | string | from onboard | Path to a YAML policy file | | `--rebuild` | boolean | `false` | Rebuild the sandbox image before starting | | `-n, --name ` | string | from config | Name the agent (creates container `silo-`) | -| `-w, --workspace ` | string | from config | Override the workspace path for this agent. `~` and relative paths are resolved to an absolute path | +| `-w, --workspace ` | string | from config | Override the workspace path for this agent. `~` and relative paths are resolved to an absolute path; an empty value falls back to the config | | `--desktop` | boolean | `false` | Mount the host Desktop at `/host/Desktop` | | `--mount ` | string | — | Mount a host path into `/host/...`, e.g. `~/Downloads:/host/Downloads:ro` | | `-f, --framework ` | string | — | Start with a specific framework (uses framework image) | @@ -160,6 +160,8 @@ Capability profiles are additive: silo stop — shut down the sandbox ``` +**Workspace mount:** `/workspace` is bind-mounted from the configured folder, which must already exist (as with `--mount`). `~` is expanded. A relative path saved in the config is refused, because the folder it points to would depend on where you run `silo start`; set an absolute path instead. Older configs could hold a bare name such as `ws`, which Docker mounts as the *named volume* `ws`. If that volume exists, `start` keeps mounting it and prints how to move the files to a host folder. + --- ### `silo stop` diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts index cb8dcd3..300ee28 100644 --- a/src/commands/doctor.ts +++ b/src/commands/doctor.ts @@ -22,7 +22,7 @@ import { resolve } from "node:path"; import { execa } from "execa"; import { readConfig, configPath } from "../config/manager.js"; import { log, printBanner, section } from "../utils/logger.js"; -import { expandHostPath } from "../utils/paths.js"; +import { resolveWorkspaceMount } from "../utils/workspace.js"; import { isContainerRunning, containerExists } from "../utils/system.js"; import { isProxyAlive, readPid } from "../utils/pid.js"; import { proxyLogPath } from "../proxy/spawn.js"; @@ -332,23 +332,16 @@ export async function runDoctor(): Promise { } // ── 9. Workspace ────────────────────────────────────────────────────── - // Check the path start will actually mount: a config saved with "~/…" - // would otherwise be reported missing, and `mkdir -p "~/…"` (quoted, so - // the shell won't expand it) would create a literal "~" directory. - const workspacePath = expandHostPath(config.sandbox.workspacePath); - if (existsSync(workspacePath)) { - results.push({ - name: "Workspace", - status: "pass", - message: workspacePath, - }); + // Check what `silo start` would actually mount, so a config saved with + // "~/…" isn't reported missing, a bare name that is really a Docker volume + // is recognised, and the mkdir hint uses the expanded path. + const workspace = await resolveWorkspaceMount(undefined, config.sandbox.workspacePath); + if (!workspace.ok) { + results.push({ name: "Workspace", status: "warn", message: workspace.error, fix: workspace.hint }); + } else if (workspace.volume) { + results.push({ name: "Workspace", status: "warn", message: workspace.warning ?? workspace.source, fix: workspace.hint }); } else { - results.push({ - name: "Workspace", - status: "warn", - message: `Directory does not exist: ${workspacePath}`, - fix: `Create it with: mkdir -p "${workspacePath}"`, - }); + results.push({ name: "Workspace", status: "pass", message: workspace.source }); } reportResults(results); diff --git a/src/commands/start.ts b/src/commands/start.ts index fa02d01..2f6ec54 100644 --- a/src/commands/start.ts +++ b/src/commands/start.ts @@ -26,6 +26,7 @@ import type { FrameworkDefinition } from "../frameworks/registry.js"; import type { HostMount, IntegrationConfig } from "../config/schema.js"; import { applyPreset, getPreset } from "../policy/presets.js"; import { expandHostPath } from "../utils/paths.js"; +import { resolveWorkspaceMount } from "../utils/workspace.js"; interface StartOptions { policy?: string; @@ -85,6 +86,16 @@ export async function runStart(opts: StartOptions): Promise { process.exit(1); } + // ── Resolve the workspace mount ────────────────────────────────────────── + const workspace = await resolveWorkspaceMount(opts.workspace, config.sandbox.workspacePath); + if (!workspace.ok) { + log.error(workspace.error); + log.info(workspace.hint); + process.exit(1); + } + if (workspace.warning) log.warn(workspace.warning); + if (workspace.hint) log.info(workspace.hint); + // ── Guard: already running ─────────────────────────────────────────────── if (await isContainerRunning(containerName)) { log.warn(`Sandbox "${containerName}" is already running.`); @@ -132,10 +143,9 @@ export async function runStart(opts: StartOptions): Promise { containerName, image, memoryLimit: browserMemory.memoryLimit, - // Expand ~ and resolve relative paths, for --workspace and for configs - // saved before onboard did this. A raw path becomes `-v :/workspace`, - // which Docker rejects (~/ws) or turns into a named volume (ws). - workspacePath: expandHostPath(opts.workspace ?? config.sandbox.workspacePath), + // Becomes `-v :/workspace`: an absolute host folder, or an existing + // named volume from an older config (see resolveWorkspaceMount). + workspacePath: workspace.source, ...(opts.policy ? { policyFile: opts.policy } : {}), ...(hostMounts.length > 0 ? { hostMounts } : {}), ...(framework ? { activeFramework: framework.id } : {}), @@ -169,7 +179,7 @@ export async function runStart(opts: StartOptions): Promise { } log.info(`Agent: ${chalk.dim(containerName)}`); - log.info(`Workspace: ${chalk.dim(effectiveSandbox.workspacePath)}`); + log.info(`Workspace: ${chalk.dim(effectiveSandbox.workspacePath)}${workspace.volume ? chalk.dim(" (Docker volume)") : ""}`); if (opts.browser) { log.info(`Browser: ${chalk.dim("enabled (Chromium inside sandbox)")}`); log.info(`Memory: ${chalk.dim(effectiveSandbox.memoryLimit)}${browserMemory.bumped ? chalk.dim(` (auto-raised for browser mode from ${config.sandbox.memoryLimit})`) : ""}`); diff --git a/src/commands/status.ts b/src/commands/status.ts index a38f165..9a536be 100644 --- a/src/commands/status.ts +++ b/src/commands/status.ts @@ -4,6 +4,7 @@ import { readConfig, configPath } from "../config/manager.js"; import { inspectContainer, containerStats } from "../docker/runner.js"; import { log, printBanner, section } from "../utils/logger.js"; import { isContainerRunning, containerExists } from "../utils/system.js"; +import { expandHome } from "../utils/paths.js"; import { isProxyAlive, readPid, pidFilePath } from "../utils/pid.js"; import { readAuditLog, auditLogPath, getSessionId } from "../audit/audit.js"; @@ -65,7 +66,9 @@ export async function runStatus(): Promise { ["Container", containerName], ["Status", statusLabel], ["Image", image], - ["Workspace", chalk.dim(config.sandbox.workspacePath)], + // Expand ~ to match what `silo start` mounts; a relative legacy value is + // shown as stored (start refuses it rather than guessing a base folder). + ["Workspace", chalk.dim(expandHome(config.sandbox.workspacePath))], ["CPU limit", config.sandbox.cpuLimit], ["Memory limit", config.sandbox.memoryLimit], ); diff --git a/src/utils/paths.ts b/src/utils/paths.ts index 8e8cf17..3289874 100644 --- a/src/utils/paths.ts +++ b/src/utils/paths.ts @@ -2,7 +2,18 @@ * Host path helpers. */ import { homedir } from "node:os"; -import { resolve } from "node:path"; +import { join, resolve } from "node:path"; + +/** + * Expand a leading `~` to the home directory, the way a shell would, and + * leave everything else untouched. Covers `~`, `~/x` and Windows-style `~\x`. + * `~user/x` is not expanded. + */ +export function expandHome(path: string): string { + if (path === "~") return homedir(); + if (/^~[\\/]/.test(path)) return join(homedir(), path.slice(2)); + return path; +} /** * Turn a user-supplied host path into the absolute path Docker needs. @@ -14,7 +25,13 @@ import { resolve } from "node:path"; * other than the host folder the user meant. */ export function expandHostPath(path: string): string { - if (path === "~") return homedir(); - if (path.startsWith("~/")) return resolve(homedir(), path.slice(2)); - return resolve(path); + return resolve(expandHome(path)); +} + +/** + * True when Docker would read this `-v` source as a named volume rather than + * a host path: its rule for local volume names is `[a-zA-Z0-9][a-zA-Z0-9_.-]*`. + */ +export function isVolumeName(path: string): boolean { + return /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(path); } diff --git a/src/utils/system.ts b/src/utils/system.ts index 9d123ac..b27850b 100644 --- a/src/utils/system.ts +++ b/src/utils/system.ts @@ -46,6 +46,18 @@ export async function containerExists(name: string): Promise { } } +/** + * Returns true if a Docker named volume with the given name exists. + */ +export async function dockerVolumeExists(name: string): Promise { + try { + await execa("docker", ["volume", "inspect", name], { stdio: "ignore" }); + return true; + } catch { + return false; + } +} + /** * Returns the current Node.js version as a semver string. */ diff --git a/src/utils/workspace.ts b/src/utils/workspace.ts new file mode 100644 index 0000000..7ab4fc4 --- /dev/null +++ b/src/utils/workspace.ts @@ -0,0 +1,80 @@ +/** + * Deciding what `silo start` mounts at /workspace. + */ +import { existsSync } from "node:fs"; +import { isAbsolute, resolve } from "node:path"; +import { expandHome, isVolumeName } from "./paths.js"; +import { dockerVolumeExists } from "./system.js"; + +export type WorkspaceMount = + | { + ok: true; + /** The `-v :/workspace` source: an absolute path, or a volume name. */ + source: string; + /** True when `source` is an existing Docker named volume, not a host folder. */ + volume: boolean; + /** Set when the caller should tell the user something about the mount. */ + warning?: string; + hint?: string; + } + | { ok: false; error: string; hint: string }; + +/** + * Work out the workspace mount from `--workspace` and the configured path. + * + * - A non-empty `--workspace` wins. An empty one (`-w "$WS"` with `WS` unset) + * falls back to the config rather than resolving to the current directory. + * - `~` forms are expanded and absolute paths are used as they are. The folder + * must already exist, as `--mount` sources must: on Linux, Docker would + * otherwise create it owned by root, and the sandbox user can't write to it. + * - A bare name such as `ws` used to reach Docker unchanged, which mounts the + * named volume `ws`. If that volume exists, the user's files are in it, so + * keep mounting it and say so, rather than switching to an empty folder. + * - Any other relative path in the config has no reliable base directory (it + * depends on where `silo start` runs), so ask for an absolute path instead. + * On the command line, a relative path is resolved against the current + * directory, which is what a shell user means. + */ +export async function resolveWorkspaceMount( + flag: string | undefined, + configured: string, + volumeExists: (name: string) => Promise = dockerVolumeExists, +): Promise { + const fromFlag = Boolean(flag); + const raw = flag || configured; + const expanded = expandHome(raw); + + if (!isAbsolute(expanded)) { + if (isVolumeName(raw) && (await volumeExists(raw))) { + return { + ok: true, + source: raw, + volume: true, + warning: + `Workspace "${raw}" is a Docker named volume, not a host folder. Earlier SILO ` + + `versions mounted bare names this way, so your files are in that volume. Still mounting it.`, + hint: + `To move to a host folder, copy the files out ` + + `(docker run --rm -v ${raw}:/from -v /path/to/folder:/to alpine cp -a /from/. /to/) ` + + `and set that folder as the workspace.`, + }; + } + if (!fromFlag) { + return { + ok: false, + error: `The workspace path in your config, "${raw}", is relative, so the folder it points to depends on where you run silo.`, + hint: "Set an absolute path: re-run `silo onboard --force`, or pass `--workspace /path/to/folder`.", + }; + } + } + + const source = resolve(expanded); + if (!existsSync(source)) { + return { + ok: false, + error: `Workspace folder does not exist: ${source}`, + hint: `Create it with: mkdir -p "${source}"`, + }; + } + return { ok: true, source, volume: false }; +} diff --git a/tests/cli.test.ts b/tests/cli.test.ts index e926e8f..ace0b9e 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -68,6 +68,7 @@ case "$1" in ps) printf 'silo-a\\nsilo-b\\n'; exit 0 ;; rm) for a in "$@"; do [ "rm:$a" = "$FAKE_DOCKER_FAIL" ] && { echo "Error: could not remove $a" >&2; exit 1; }; done; exit 0 ;; rmi) [ "$FAKE_DOCKER_FAIL" = "rmi" ] && { echo "Error: No such image" >&2; exit 1; }; exit 0 ;; + volume) [ "$2" = "inspect" ] && [ -n "$FAKE_DOCKER_VOLUME" ] && [ "$3" = "$FAKE_DOCKER_VOLUME" ] && exit 0; exit 1 ;; *) exit 1 ;; esac `; @@ -76,6 +77,8 @@ describe("exit codes when a command fails", () => { let fakeBin: string; let configuredHome: string; let legacyHome: string; + let bareNameHome: string; + let missingWorkspaceHome: string; beforeAll(async () => { fakeBin = mkdtempSync(join(tmpdir(), "silo-fake-docker-")); @@ -85,12 +88,17 @@ describe("exit codes when a command fails", () => { configuredHome = await homeWithConfig((h) => join(h, "ws")); // A config saved before workspace paths were expanded: "~/ws" verbatim. legacyHome = await homeWithConfig(() => "~/ws"); + // Older configs could hold a bare name, which Docker mounted as a named volume. + bareNameHome = await homeWithConfig(() => "ws"); + missingWorkspaceHome = await homeWithConfig((h) => join(h, "deleted-workspace")); }, 30_000); afterAll(() => { rmSync(fakeBin, { recursive: true, force: true }); rmSync(configuredHome, { recursive: true, force: true }); rmSync(legacyHome, { recursive: true, force: true }); + rmSync(bareNameHome, { recursive: true, force: true }); + rmSync(missingWorkspaceHome, { recursive: true, force: true }); }); /** A temp HOME holding a real, valid config written through the config manager. */ @@ -114,9 +122,13 @@ describe("exit codes when a command fails", () => { } function siloWith(homeDir: string, fail: string, ...args: string[]) { + return siloEnv(homeDir, { FAKE_DOCKER_FAIL: fail }, ...args); + } + + function siloEnv(homeDir: string, fakeEnv: Record, ...args: string[]) { return execa("node", ["--import", "tsx", "src/cli.ts", ...args], { cwd: repoRoot, - env: { ...isolatedEnv(homeDir), PATH: `${fakeBin}:${process.env.PATH}`, FAKE_DOCKER_FAIL: fail }, + env: { ...isolatedEnv(homeDir), PATH: `${fakeBin}:${process.env.PATH}`, ...fakeEnv }, reject: false, }); } @@ -155,4 +167,21 @@ describe("exit codes when a command fails", () => { expect(out).toContain(`Workspace: ${join(legacyHome, "ws")}`); expect(out).not.toMatch(/Directory does not exist/); }, 30_000); + + it("doctor recognises an older bare-name workspace as an existing Docker volume", async () => { + const result = await siloEnv(bareNameHome, { FAKE_DOCKER_VOLUME: "ws" }, "doctor"); + expect(result.stdout + result.stderr).toMatch(/Workspace "ws" is a Docker named volume/); + }, 30_000); + + it("start refuses a bare-name workspace with no such volume instead of mounting a folder", async () => { + const result = await siloEnv(bareNameHome, {}, "start"); + expect(result.stdout + result.stderr).toMatch(/"ws", is relative/); + expect(result.exitCode).toBe(1); + }, 30_000); + + it("start refuses a workspace folder that doesn't exist", async () => { + const result = await siloEnv(missingWorkspaceHome, {}, "start"); + expect(result.stdout + result.stderr).toMatch(/Workspace folder does not exist/); + expect(result.exitCode).toBe(1); + }, 30_000); }); diff --git a/tests/docker/templates.test.ts b/tests/docker/templates.test.ts index 4956d58..32576b8 100644 --- a/tests/docker/templates.test.ts +++ b/tests/docker/templates.test.ts @@ -320,3 +320,22 @@ describe("buildRunFlags gateway modes", () => { expect(flags[flags.length - 1]).toBe("silo-sandbox:latest"); }); }); + +// --------------------------------------------------------------------------- +// Workspace mount +// --------------------------------------------------------------------------- + +describe("buildRunFlags workspace mount", () => { + function volumeFlag(workspacePath: string): string | undefined { + const flags = buildRunFlags({ ...baseSandbox, workspacePath }, baseProxy); + return flags.find((f, i) => flags[i - 1] === "--volume" && f.endsWith(":/workspace:rw")); + } + + it("mounts the resolved host folder read-write at /workspace", () => { + expect(volumeFlag("/home/user/project")).toBe("/home/user/project:/workspace:rw"); + }); + + it("passes a named volume through unchanged (an older bare-name config)", () => { + expect(volumeFlag("ws")).toBe("ws:/workspace:rw"); + }); +}); diff --git a/tests/utils/paths.test.ts b/tests/utils/paths.test.ts index 1c81911..a62fd56 100644 --- a/tests/utils/paths.test.ts +++ b/tests/utils/paths.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from "vitest"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; -import { expandHostPath } from "../../src/utils/paths.js"; +import { expandHome, expandHostPath, isVolumeName } from "../../src/utils/paths.js"; describe("expandHostPath", () => { it("expands a bare ~ to the home directory", () => { @@ -27,4 +27,27 @@ describe("expandHostPath", () => { it("does not treat ~user as the current user's home", () => { expect(expandHostPath("~other/ws")).toBe(resolve(process.cwd(), "~other/ws")); }); + + it("expands a Windows-style ~\\ path", () => { + expect(expandHostPath("~\\ws")).toBe(join(homedir(), "ws")); + }); +}); + +describe("expandHome", () => { + it("expands only a leading ~ and leaves relative paths relative", () => { + expect(expandHome("~/ws")).toBe(join(homedir(), "ws")); + expect(expandHome("ws")).toBe("ws"); + expect(expandHome("./ws")).toBe("./ws"); + expect(expandHome("/abs/ws")).toBe("/abs/ws"); + }); +}); + +describe("isVolumeName", () => { + it.each(["ws", "my-data", "data_1", "v1.2"])("treats %s as a Docker volume name", (name) => { + expect(isVolumeName(name)).toBe(true); + }); + + it.each(["./ws", "~/ws", "/abs", "a/b", "", ".hidden", "-x"])("does not treat %s as a volume name", (name) => { + expect(isVolumeName(name)).toBe(false); + }); }); diff --git a/tests/utils/workspace.test.ts b/tests/utils/workspace.test.ts new file mode 100644 index 0000000..365b963 --- /dev/null +++ b/tests/utils/workspace.test.ts @@ -0,0 +1,81 @@ +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { resolveWorkspaceMount } from "../../src/utils/workspace.js"; + +// No Docker here: volume lookups are injected. +const noVolumes = vi.fn(async () => false); +const volumes = (...names: string[]) => vi.fn(async (name: string) => names.includes(name)); + +describe("resolveWorkspaceMount", () => { + let dir: string; + + beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "silo-ws-")); + }); + + afterAll(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it("uses an absolute configured folder as it is", async () => { + expect(await resolveWorkspaceMount(undefined, dir, noVolumes)).toEqual({ ok: true, source: dir, volume: false }); + }); + + it("prefers a non-empty --workspace over the config", async () => { + const result = await resolveWorkspaceMount(dir, "/somewhere/else", noVolumes); + expect(result).toMatchObject({ ok: true, source: dir }); + }); + + it("falls back to the config when --workspace is empty, instead of the current directory", async () => { + const result = await resolveWorkspaceMount("", dir, noVolumes); + expect(result).toMatchObject({ ok: true, source: dir }); + expect(result).not.toMatchObject({ source: process.cwd() }); + }); + + it("expands ~ in the configured path", async () => { + expect(await resolveWorkspaceMount(undefined, "~", noVolumes)).toMatchObject({ ok: true, source: homedir() }); + }); + + it("keeps mounting an existing named volume from an older bare-name config, with a warning", async () => { + const volumeExists = volumes("ws"); + const result = await resolveWorkspaceMount(undefined, "ws", volumeExists); + expect(volumeExists).toHaveBeenCalledWith("ws"); + expect(result).toMatchObject({ ok: true, source: "ws", volume: true }); + expect(result.ok && result.warning).toMatch(/Docker named volume/); + expect(result.ok && result.hint).toMatch(/docker run --rm -v ws:\/from/); + }); + + it("refuses a bare-name config with no such volume rather than guessing a folder", async () => { + const result = await resolveWorkspaceMount(undefined, "ws", noVolumes); + expect(result).toMatchObject({ ok: false }); + expect(!result.ok && result.error).toMatch(/is relative/); + }); + + it("refuses a relative configured path that Docker never accepted", async () => { + const volumeExists = vi.fn(async () => true); + const result = await resolveWorkspaceMount(undefined, "./my-project", volumeExists); + expect(result).toMatchObject({ ok: false }); + expect(volumeExists).not.toHaveBeenCalled(); // "./my-project" can't be a volume name + }); + + it("resolves a relative --workspace against the current directory", async () => { + const result = await resolveWorkspaceMount("src", "/unused", noVolumes); + expect(result).toMatchObject({ ok: true, source: resolve(process.cwd(), "src"), volume: false }); + }); + + it("still honours an existing volume named on the command line", async () => { + expect(await resolveWorkspaceMount("ws", "/unused", volumes("ws"))).toMatchObject({ ok: true, source: "ws", volume: true }); + }); + + it("refuses a folder that doesn't exist, like --mount does", async () => { + const missing = join(dir, "missing"); + const result = await resolveWorkspaceMount(undefined, missing, noVolumes); + expect(result).toEqual({ + ok: false, + error: `Workspace folder does not exist: ${missing}`, + hint: `Create it with: mkdir -p "${missing}"`, + }); + }); +});