From bba0428c3bb433c0f028db55fafec5c3fd3076f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Thu, 12 Nov 2026 09:44:24 +0000 Subject: [PATCH] The device's terminal picks a shell that exists; plainer refusals pickShell: $SHELL where it exists, else bash, zsh, sh, as a login shell; on Windows pwsh, then powershell, then ComSpec/cmd, without -l. A spawn that fails (the runtime's PTY is POSIX's) is a one-line refusal, not an internal error. The refusals for terminals switched off, a folder outside the allowed ones, a missing folder and too many terminals say what to do. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 10 ++++++++++ src/acp/agent.ts | 40 ++++++++++++++++++++++++---------------- src/acp/shellrc.ts | 31 +++++++++++++++++++++++++++---- tests/acp.test.ts | 2 +- tests/shellrc.test.ts | 24 +++++++++++++++++++++++- 5 files changed, 85 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fa2734..bb82d41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,16 @@ Harness spec 3.7.0: one display in every client. answer for three situations; the spec now has one each — no page of the chat is open (and where to open it), the page did not answer, the run took too long. +### Changed + +- **The terminal opened from the web UI or Desktop picks a shell that exists.** `$SHELL` when + it is there, else bash, zsh or sh; on Windows PowerShell 7, then Windows PowerShell, then + `cmd.exe` — started without `-l`, which none of them takes. (The runtime's pseudo-terminal is + documented for Linux and macOS only, and there is no Windows build of the CLI yet: where a + terminal cannot be opened, the refusal now says so in a sentence.) +- **Plainer refusals when a terminal or a folder cannot be used**: each says what to do — + `lembas remote terminal on`, `lembas remote add `, close one of the open terminals. + ## [2.0.0-beta.8] — 2026-11-10 ### Added diff --git a/src/acp/agent.ts b/src/acp/agent.ts index f8d648b..4431d22 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -30,7 +30,7 @@ import { PLAN_META } from "../session/engine.ts" import { ToolError } from "../tool/tool.ts" import { dropAttachments, preparePrompt, storedAttachments } from "./prompt.ts" import { addPendingDeleted, clearPendingDeleted, pendingDeleted } from "./pending.ts" -import { shellLaunch } from "./shellrc.ts" +import { pickShell, shellLaunch } from "./shellrc.ts" import { sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts" import { expandHome } from "../config/paths.ts" import { asMode, MODES, type Mode } from "../config/schema.ts" @@ -82,7 +82,7 @@ export function refusalFor(L: Limits | undefined, dir: string): string | undefin if (L.sharedOnly) return "remote work is off on this machine (remote.enabled); only the sessions its terminal shares (/remote) can be reached" if (L.enabled === false) return "remote work is off on this machine — lembas remote enable there (remote.enabled)" if (!L.roots.length) return "this device allows no folders for remote work yet — lembas remote add there (remote.roots)" - if (!underRoots(dir, L.roots)) return `${dir} is outside the directories this device accepts remote work in (remote.roots)` + if (!underRoots(dir, L.roots)) return `${dir} is outside the directories this device accepts remote work in — to allow it, run lembas remote add there (remote.roots)` if (L.requireTrust && trustOf(findProject(dir).root) !== "trusted" && !trustedWithin(realPath(dir))) return `${dir} is not in a trusted project on this device — trust it there first (lembas trust)` return undefined @@ -1342,27 +1342,35 @@ export class AcpAgent { * model's, so the hardline and the modes do not apply, exactly as in a terminal opened here. */ private terminalOpen(p: any) { const L = this.limits - if (!L?.terminal) throw new RpcError(INVALID_PARAMS, "this device does not open terminals for the web UI (remote.terminal is off)") + if (!L?.terminal) throw new RpcError(INVALID_PARAMS, "Terminals are switched off on this computer. To allow them, run `lembas remote terminal on` there (remote.terminal).") const cwd = typeof p?.cwd === "string" && p.cwd.trim() ? resolve(expandHome(p.cwd.trim())) : resolve(expandHome(L.roots[0] ?? "~")) const refused = this.refusal(cwd) if (refused) throw new RpcError(INVALID_PARAMS, refused) - if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a directory on this machine`) - if (this.terminals.size >= MAX_TERMINALS) throw new RpcError(INVALID_PARAMS, `this device already has ${MAX_TERMINALS} terminals open for the web UI`) + if (!existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${cwd} is not a folder on this computer — choose one that exists`) + if (this.terminals.size >= MAX_TERMINALS) throw new RpcError(INVALID_PARAMS, `This computer already has ${MAX_TERMINALS} terminals open — close one, then open another.`) const id = crypto.randomUUID() const cols = Math.max(20, Math.min(500, Number(p?.cols) || 80)) const rows = Math.max(5, Math.min(300, Number(p?.rows) || 24)) - const shell = process.env.SHELL || "/bin/bash" + const picked = pickShell() + if (!picked) throw new RpcError(INVALID_PARAMS, "No shell was found on this computer to open a terminal with — set SHELL to one (on Windows: install PowerShell).") // Marks for the web UI's terminal: the user's own startup files first, then OSC 133/7. - const launch = shellLaunch(shell, id, L.terminalIntegration !== false) - const proc = Bun.spawn(launch.argv, { - cwd, - env: { ...process.env, TERM: "xterm-256color", ...launch.env }, - terminal: { - cols, - rows, - data: (_t: unknown, d: Uint8Array) => this.peer.notify("_lembas/terminal/output", { terminalId: id, data: Buffer.from(d).toString("base64") }), - }, - } as Parameters[1]) + const launch = shellLaunch(picked.shell, id, L.terminalIntegration !== false, process.env, picked.args) + let proc: ReturnType + try { + proc = Bun.spawn(launch.argv, { + cwd, + env: { ...process.env, TERM: "xterm-256color", ...launch.env }, + terminal: { + cols, + rows, + data: (_t: unknown, d: Uint8Array) => this.peer.notify("_lembas/terminal/output", { terminalId: id, data: Buffer.from(d).toString("base64") }), + }, + } as Parameters[1]) + } catch (e) { + // The runtime's pseudo-terminal is POSIX's: where it has none (Windows), say so plainly. + launch.cleanup() + throw new RpcError(INVALID_PARAMS, `A terminal could not be opened on this computer (${basename(picked.shell)}): ${(e as Error).message.split("\n")[0]}`) + } const pty = (proc as unknown as { terminal: Terminal["pty"] }).terminal this.terminals.set(id, { proc, pty, cleanup: launch.cleanup }) void proc.exited.then((code) => { diff --git a/src/acp/shellrc.ts b/src/acp/shellrc.ts index 6a1138f..694f165 100644 --- a/src/acp/shellrc.ts +++ b/src/acp/shellrc.ts @@ -9,7 +9,7 @@ // files (which it sources), zsh a ZDOTDIR whose files source the user's own and hand ZDOTDIR back, // fish a command run after its config. Any other shell starts as it did before, without marks. // `remote.terminal_integration: false` turns it off. -import { mkdirSync, rmSync, writeFileSync } from "node:fs" +import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs" import { basename, join } from "node:path" import { paths } from "../config/paths.ts" @@ -167,11 +167,34 @@ export interface ShellLaunch { cleanup(): void } +/** The shell a terminal opened from the web UI runs, and how it is started without the marks. + * POSIX: `$SHELL` when it is there, else the first of bash, zsh and sh that is — as a login + * shell (`-l`). Windows: PowerShell 7 (`pwsh`), then Windows PowerShell, then `%ComSpec%` / + * `cmd.exe` — none of which takes `-l`. Undefined when the machine has none of them. */ +export function pickShell( + os: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, + has: (path: string) => boolean = existsSync, + which: (cmd: string) => string | null = Bun.which, +): { shell: string; args: string[] } | undefined { + if (os === "win32") { + for (const name of ["pwsh.exe", "powershell.exe"]) { + const found = which(name) + if (found) return { shell: found, args: ["-NoLogo"] } + } + const cmd = (env.ComSpec && has(env.ComSpec) ? env.ComSpec : undefined) ?? which("cmd.exe") + return cmd ? { shell: cmd, args: [] } : undefined + } + const shell = [env.SHELL, "/bin/bash", "/bin/zsh", "/bin/sh"].find((s): s is string => !!s && has(s)) + return shell ? { shell, args: ["-l"] } : undefined +} + /** How to start `shell` for terminal `id`: with the marks when it is bash, zsh or fish and - * `integration` is on; as `$SHELL -l` otherwise. */ -export function shellLaunch(shell: string, id: string, integration: boolean, env: NodeJS.ProcessEnv = process.env): ShellLaunch { + * `integration` is on; as `$SHELL -l` (or with `plainArgs`, for a shell that takes no `-l`) + * otherwise. */ +export function shellLaunch(shell: string, id: string, integration: boolean, env: NodeJS.ProcessEnv = process.env, plainArgs: string[] = ["-l"]): ShellLaunch { const kind = shellKind(shell) - const plain: ShellLaunch = { kind, integration: false, argv: [shell, "-l"], env: {}, cleanup: () => {} } + const plain: ShellLaunch = { kind, integration: false, argv: [shell, ...plainArgs], env: {}, cleanup: () => {} } if (!integration || kind === "other") return plain const dir = join(paths.state, "terminal", id.replace(/[^\w-]/g, "_")) const cleanup = () => rmSync(dir, { recursive: true, force: true }) diff --git a/tests/acp.test.ts b/tests/acp.test.ts index e012bf5..44c2e1b 100644 --- a/tests/acp.test.ts +++ b/tests/acp.test.ts @@ -269,7 +269,7 @@ test("the terminal: a real shell through the link, only where remote.terminal sa const root = project() const off = await client({ roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true }) expect(off.init._meta.lembas.capabilities).toEqual(["directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", "attachments", "ask", "plan", "model", "turns", "context", "library", "prototypes", "plan_state", "rewind", "jobs", "show", "progress", "tree", "agents", "scheduled"]) - await expect(off.c.request("_lembas/terminal/open", { cwd: root })).rejects.toThrow("remote.terminal is off") + await expect(off.c.request("_lembas/terminal/open", { cwd: root })).rejects.toThrow("lembas remote terminal on") const { c, init } = await client({ roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true, terminal: true }) expect(init._meta.lembas.capabilities).toContain("terminal") diff --git a/tests/shellrc.test.ts b/tests/shellrc.test.ts index e7d26c2..12df29e 100644 --- a/tests/shellrc.test.ts +++ b/tests/shellrc.test.ts @@ -5,7 +5,7 @@ import { afterEach, expect, test } from "bun:test" import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" -import { shellKind, shellLaunch, type ShellLaunch } from "../src/acp/shellrc.ts" +import { pickShell, shellKind, shellLaunch, type ShellLaunch } from "../src/acp/shellrc.ts" const launched: ShellLaunch[] = [] afterEach(() => { @@ -17,6 +17,28 @@ const launch = (...a: Parameters) => { return l } +test("the shell a terminal runs: $SHELL where it exists, else bash, zsh, sh; on Windows PowerShell, then cmd", () => { + const has = (...paths: string[]) => (p: string) => paths.includes(p) + const none = () => null + // POSIX: the person's own shell, as a login shell. + expect(pickShell("linux", { SHELL: "/usr/bin/fish" }, has("/usr/bin/fish", "/bin/bash"), none)).toEqual({ shell: "/usr/bin/fish", args: ["-l"] }) + // A SHELL that is not there (a container, a stale variable) is passed over, not started. + expect(pickShell("linux", { SHELL: "/opt/gone/zsh" }, has("/bin/bash", "/bin/sh"), none)).toEqual({ shell: "/bin/bash", args: ["-l"] }) + // No bash (a minimal image): zsh, then sh. + expect(pickShell("darwin", {}, has("/bin/zsh", "/bin/sh"), none)).toEqual({ shell: "/bin/zsh", args: ["-l"] }) + expect(pickShell("linux", {}, has("/bin/sh"), none)).toEqual({ shell: "/bin/sh", args: ["-l"] }) + expect(pickShell("linux", {}, has(), none)).toBeUndefined() + // Windows: no -l anywhere; PowerShell 7 before Windows PowerShell before cmd. SHELL is not read. + const which = (...found: string[]) => (c: string) => (found.includes(c) ? `C:\\bin\\${c}` : null) + expect(pickShell("win32", { SHELL: "/usr/bin/bash" }, has(), which("pwsh.exe", "powershell.exe", "cmd.exe"))).toEqual({ shell: "C:\\bin\\pwsh.exe", args: ["-NoLogo"] }) + expect(pickShell("win32", {}, has(), which("powershell.exe", "cmd.exe"))).toEqual({ shell: "C:\\bin\\powershell.exe", args: ["-NoLogo"] }) + expect(pickShell("win32", { ComSpec: "C:\\Windows\\System32\\cmd.exe" }, has("C:\\Windows\\System32\\cmd.exe"), which())).toEqual({ shell: "C:\\Windows\\System32\\cmd.exe", args: [] }) + expect(pickShell("win32", { ComSpec: "C:\\gone.exe" }, has(), which("cmd.exe"))).toEqual({ shell: "C:\\bin\\cmd.exe", args: [] }) + expect(pickShell("win32", {}, has(), which())).toBeUndefined() + // A shell that takes no -l starts without it, and without marks. + expect(shellLaunch("C:\\bin\\pwsh.exe", "t1", true, {}, ["-NoLogo"])).toMatchObject({ kind: "other", integration: false, argv: ["C:\\bin\\pwsh.exe", "-NoLogo"] }) +}) + test("which shells get marks: bash, zsh and fish; anything else starts as before", () => { expect(shellKind("/usr/bin/bash")).toBe("bash") expect(shellKind("/bin/zsh")).toBe("zsh")