GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — fix(cli): use process cwd for run root by 1052326311 · Pull Request #56389 · anomalyco/opencode Conversation
| |||||||||||||||||||||||||||||||||||||||||||||
|
The following comment was made by an LLM, it may be inaccurate: |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
The fix works. I ran the #56386 reproduction from source with a mock model. On the base, the relative write landed in the stale $PWD directory. With this PR it lands in the real process cwd, with and without --standalone. bun test test/run/ (14 pass) and the CLI typecheck pass, and the new stale-PWD test fails on the base as expected.
Public API: unchanged. The default directory for opencode run now comes from the process cwd instead of $PWD; no flags, config keys or env vars change. Symlinked directories behave as before: localDirectory() already returned the resolved process.cwd() after chdir, so the session directory was never the symlink path.
Concerns:
packages/cli/src/mini.ts (localDirectory()) and packages/cli/src/run/v1.ts (runV1Bridge) still use process.env.PWD ?? process.cwd(). Those entry points will still chdir to a stale $PWD. Please apply the same change there so all of them agree (see the inline comment).Related: #54823
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| async function run(input: RunCommandInput, options: ExecutionOptions) { | ||
| if (input.fork && !input.continue && !input.session) fail("--fork requires --continue or --session") | ||
| const root = options.root ?? process.env.PWD ?? process.cwd() | ||
| const root = options.root ?? process.cwd() |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
This fixes the v2 run path, but the same process.env.PWD ?? process.cwd() fallback is still in packages/cli/src/mini.ts (localDirectory(), ~line 202) and packages/cli/src/run/v1.ts (runV1Bridge, line 29). runV1Bridge passes its own root explicitly, so it bypasses this fix. Please change those two places as well, so a stale inherited PWD is ignored everywhere and not only here.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| import { tmpdir } from "../../../core/test/fixture/tmpdir" | ||
| import { isolatedEnv } from "../fixture/environment" | ||
|
|
||
| for (const stale of [true, false]) |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
For a two-line fix this is a lot of test: about 140 lines, an inline SSE mock model, and a full CLI child process (about 2s each) per case. Please keep only the stale-PWD case, which is the one that fails on the base, and drop the matching-PWD variant of the loop. That case passed before the fix and adds little.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| @@ -0,0 +1,13 @@ | |||
| import { runNonInteractiveWithOptions } from "../../src/run/run" | |||
|
|
|||
| await runNonInteractiveWithOptions( | |||
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
This fixture is fragile. It gets run() to stop early by passing an unreachable endpoint (127.0.0.1:1) and a missing attachment, then sets process.exitCode = 0 unconditionally, so the run's real failure is hidden. If the order of checks in run() changes, the test could pass or fail for reasons unrelated to the root. The explicit root path did not change in this PR, so I'd drop this fixture and the explicit-root test.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Follow-up Before the change, the v1 write landed under stale |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Independent verification on macOS arm64, Bun 1.4.3: head One coverage gap from the PR description is easy to close: the v1 bridge with an explicit relative directory. I extended the existing test with a third scenario (
Test-only diff: fixture + root.test.tsdiff --git a/packages/cli/test/fixture/run-v1.ts b/packages/cli/test/fixture/run-v1.ts index 093691c83e..b12fb37d0e 100644 --- a/packages/cli/test/fixture/run-v1.ts +++ b/packages/cli/test/fixture/run-v1.ts @@ -7,6 +7,7 @@ await runV1Bridge({ format: "json", file: [], model: "mock/m", + directory: process.env.RUN_DIRECTORY, standaloneCommand: [ process.execPath, "--conditions=browser", diff --git a/packages/cli/test/run/root.test.ts b/packages/cli/test/run/root.test.ts index 60d23babba..7f7977574c 100644 --- a/packages/cli/test/run/root.test.ts +++ b/packages/cli/test/run/root.test.ts @@ -4,16 +4,26 @@ import path from "node:path" import { tmpdir } from "../../../core/test/fixture/tmpdir" import { isolatedEnv } from "../fixture/environment" -for (const v1 of [false, true]) +const scenarios = [ + { name: "run uses the process cwd when PWD points elsewhere" }, + { name: "V1 run bridge uses the process cwd when PWD points elsewhere", v1: true }, + { + name: "V1 run bridge resolves an explicit relative directory from the process cwd", + v1: true, + directory: "sub", + }, +] + +for (const scenario of scenarios) test( - v1 - ? "V1 run bridge uses the process cwd when PWD points elsewhere" - : "run uses the process cwd when PWD points elsewhere", + scenario.name, async () => { await using root = await tmpdir("opencode-cli-run-root-") const actual = path.join(root.path, "actual") const elsewhere = path.join(root.path, "elsewhere") - await Promise.all([mkdir(actual), mkdir(elsewhere)]) + const target = scenario.directory ? path.join(actual, scenario.directory) : actual + const stale = scenario.directory ? path.join(elsewhere, scenario.directory) : elsewhere + await Promise.all([mkdir(target, { recursive: true }), mkdir(stale, { recursive: true })]) const model = Bun.serve({ port: 0, @@ -63,7 +73,7 @@ for (const v1 of [false, true]) try { const preload = path.join(import.meta.dir, "../../../tui/node_modules/@opentui/solid/scripts/preload.js") const child = Bun.spawn( - v1 + scenario.v1 ? [ process.execPath, "--conditions=browser", @@ -87,6 +97,7 @@ for (const v1 of [false, true]) cwd: actual, env: isolatedEnv(root.path, { PWD: elsewhere, + ...(scenario.directory ? { RUN_DIRECTORY: scenario.directory } : {}), BUN_OPTIONS: `--conditions=browser --preload=${preload}`, OPENCODE_CONFIG_CONTENT: JSON.stringify({ autoupdate: false, @@ -113,8 +124,8 @@ for (const v1 of [false, true]) child.exited, ]) expect({ exitCode, stdout, stderr }).toMatchObject({ exitCode: 0 }) - expect(await Bun.file(path.join(elsewhere, "marker.txt")).exists()).toBe(false) - expect(await Bun.file(path.join(actual, "marker.txt")).text()).toBe("hi") + expect(await Bun.file(path.join(stale, "marker.txt")).exists()).toBe(false) + expect(await Bun.file(path.join(target, "marker.txt")).text()).toBe("hi") } finally { model.stop(true) } Happy to open a follow-up PR with this once the fix lands, or you can apply it here directly. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
Your follow-up One: Two: rewriting The matching- If this is noise on top of work that is already done, say so and I will close it. pwd-fix.patch — 5 files, +121/−8From f39504b489857dac2f6c3bf9fbb867a72b1bbd53 Mon Sep 17 00:00:00 2001 From: Jonathan Correa Paiva <[email protected]> Date: Thu, 5 Nov 2026 04:31:16 -0300 Subject: [PATCH] fix(cli): only trust $PWD when it points at the current directory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `$PWD` is the path the user typed, so it preserves symlinked names that `process.cwd()` resolves away. The CLI took it unconditionally though, so a parent that spawned us with a different `cwd` — the standard way to set a child's directory, in Python `subprocess(cwd=...)` or `Bun.spawn({ cwd })` — silently moved the whole session to the inherited path and wrote files in the wrong place. Bash discards a `PWD` that does not match the real cwd; do the same by comparing `dev`/`ino` instead of resolving symlinks, so two bind mounts of the same directory still count as the same directory. A `PWD` that no longer exists now falls back to the real cwd instead of aborting. When we do chdir, rewrite `process.env.PWD` as well, so children we spawn do not inherit the stale value. That is what `cd` does. Refs #56386 Co-authored-by: Sinder <[email protected]> --- packages/cli/src/mini.ts | 6 +- packages/cli/src/run/run.ts | 6 +- packages/cli/src/run/v1.ts | 5 +- packages/cli/src/util/process.ts | 35 ++++++++++ packages/cli/test/working-directory.test.ts | 77 +++++++++++++++++++++ 5 files changed, 121 insertions(+), 8 deletions(-) create mode 100644 packages/cli/test/working-directory.test.ts diff --git a/packages/cli/src/mini.ts b/packages/cli/src/mini.ts index c567e19..efb76de 100644 --- a/packages/cli/src/mini.ts +++ b/packages/cli/src/mini.ts @@ -4,6 +4,7 @@ import type { MiniFrontendInput } from "@opencode/tui/mini" import { noTimeoutFetch } from "@opencode/util/no-timeout-fetch" import { setTimeout } from "node:timers/promises" import { readStdin } from "./util/io" +import { enterDirectory, workingDirectory } from "./util/process" import { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from "./mini-host" import { parseSessionTargetModel, resolveSessionTarget, type SessionTargetPreparation } from "./session-target" import { Env } from "./env" @@ -202,10 +203,9 @@ function validate(input: MiniCommandInput) { } function localDirectory(): string { - const root = process.env.PWD ?? process.cwd() + const root = workingDirectory() try { - process.chdir(root) - return process.cwd() + return enterDirectory(root) } catch { throw new MiniInputError(`Failed to change directory to ${root}`) } diff --git a/packages/cli/src/run/run.ts b/packages/cli/src/run/run.ts index 24e20a6..76cbeed 100644 --- a/packages/cli/src/run/run.ts +++ b/packages/cli/src/run/run.ts @@ -12,6 +12,7 @@ import { runNonInteractivePrompt } from "./noninteractive" import { UI } from "./ui" import { Env } from "../env" import { errorMessage } from "../util/error" +import { enterDirectory, workingDirectory } from "../util/process" export type RunCommandInput = { server: ServerConnection.Resolved @@ -75,7 +76,7 @@ async function run(input: RunCommandInput, options: ExecutionOptions) { if (input.fork && !input.continue && !input.session) fail("--fork requires --continue or --session") if (input.worktree !== undefined && (input.continue || input.session)) fail("--worktree starts a new session and cannot be combined with --continue or --session") - const root = options.root ?? process.env.PWD ?? process.cwd() + const root = options.root ?? workingDirectory() const local = localDirectory(root) const directory = options.useServerDirectory ? undefined : (options.directory ?? local) const message = mergeInput(formatMessage(input.message), process.stdin.isTTY ? undefined : await readStdin()) @@ -183,8 +184,7 @@ function formatMessage(message: string[]) { function localDirectory(root: string) { try { - process.chdir(root) - return process.cwd() + return enterDirectory(root) } catch { fail(`Failed to change directory to ${root}`) } diff --git a/packages/cli/src/run/v1.ts b/packages/cli/src/run/v1.ts index b5bd602..e752e72 100644 --- a/packages/cli/src/run/v1.ts +++ b/packages/cli/src/run/v1.ts @@ -3,6 +3,7 @@ import { Effect } from "effect" import path from "node:path" import { Standalone } from "../services/standalone" import { errorMessage } from "../util/error" +import { enterDirectory, workingDirectory } from "../util/process" import { reportRunError, runNonInteractiveWithOptions, type RunCommandInput } from "./run" export type V1RunCommandInput = { @@ -26,11 +27,11 @@ export type V1RunCommandInput = { } export function runV1Bridge(input: V1RunCommandInput) { - const root = process.env.PWD ?? process.cwd() + const root = workingDirectory() const attached = input.server !== undefined const local = !attached && input.directory ? path.resolve(root, input.directory) : root try { - process.chdir(local) + enterDirectory(local) } catch { reportRunError(input, `Failed to change directory to ${local}`) return Promise.resolve() diff --git a/packages/cli/src/util/process.ts b/packages/cli/src/util/process.ts index 4721a12..a6f7076 100644 --- a/packages/cli/src/util/process.ts +++ b/packages/cli/src/util/process.ts @@ -1,7 +1,42 @@ +import { statSync } from "node:fs" import path from "node:path" const entrypoint = process.argv[1] ? path.resolve(process.argv[1]) : undefined +/** + * The workspace root, preferring `$PWD` when it is trustworthy. + * + * `$PWD` is the path the user typed, so it keeps symlinked names that + * `process.cwd()` resolves away. Trust it only when it points at the same + * directory as the real cwd: bash discards an inconsistent `PWD` instead of + * chdir-ing into it, and a parent that spawns us with `cwd=X` while inheriting + * `PWD=Y` must not silently move us to `Y`. Compare device and inode rather + * than resolving both paths, so two bind mounts of the same directory still + * count as the same directory. + */ +export function workingDirectory() { + const pwd = process.env.PWD + if (!pwd) return process.cwd() + try { + const logical = statSync(pwd) + const actual = statSync(process.cwd()) + if (logical.dev === actual.dev && logical.ino === actual.ino) return pwd + } catch { + // A `PWD` that no longer exists is stale, fall back to the real cwd. + } + return process.cwd() +} + +/** + * chdir that also rewrites `$PWD`, so spawned children do not inherit the old + * value. This is what `cd` does in a shell. + */ +export function enterDirectory(root: string) { + process.chdir(root) + process.env.PWD = path.resolve(root) + return process.cwd() +} + export function selfCommand() { const runtime = path.basename(process.execPath, path.extname(process.execPath)).toLowerCase() if (runtime !== "bun" && runtime !== "node" && runtime !== "nodejs") return [process.execPath] diff --git a/packages/cli/test/working-directory.test.ts b/packages/cli/test/working-directory.test.ts new file mode 100644 index 0000000..925ccc8 --- /dev/null +++ b/packages/cli/test/working-directory.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, test } from "bun:test" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { enterDirectory, workingDirectory } from "../src/util/process" + +function directory(prefix: string) { + return fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix))) +} + +function linked(target: string) { + const link = path.join(directory("opencode-pwd-link-"), "profile") + fs.symlinkSync(target, link) + return link +} + +function withCwd(directory: string, run: () => void) { + const before = process.cwd() + const pwd = process.env.PWD + process.chdir(directory) + try { + run() + } finally { + process.chdir(before) + if (pwd === undefined) delete process.env.PWD + else process.env.PWD = pwd + } +} + +describe("workingDirectory", () => { + test("falls back to the real cwd when PWD is not set", () => { + const dir = directory("opencode-pwd-missing-") + withCwd(dir, () => { + delete process.env.PWD + expect(workingDirectory()).toBe(process.cwd()) + }) + }) + + test("keeps PWD when it reaches the same directory through a symlink", () => { + const dir = directory("opencode-pwd-target-") + const link = linked(dir) + withCwd(dir, () => { + process.env.PWD = link + expect(workingDirectory()).toBe(link) + }) + }) + + test("ignores a stale PWD that points at another directory", () => { + const dir = directory("opencode-pwd-here-") + const elsewhere = directory("opencode-pwd-elsewhere-") + withCwd(dir, () => { + process.env.PWD = elsewhere + expect(workingDirectory()).toBe(process.cwd()) + }) + }) + + test("falls back to the real cwd when PWD no longer exists", () => { + const dir = directory("opencode-pwd-gone-") + withCwd(dir, () => { + process.env.PWD = path.join(dir, "does-not-exist") + expect(workingDirectory()).toBe(process.cwd()) + }) + }) +}) + +describe("enterDirectory", () => { + test("leaves PWD pointing at the chosen root so children do not inherit the stale path", () => { + const dir = directory("opencode-pwd-chosen-") + const stale = directory("opencode-pwd-stale-") + withCwd(dir, () => { + process.env.PWD = stale + enterDirectory(workingDirectory()) + expect(process.env.PWD).toBe(process.cwd()) + expect(process.env.PWD).not.toBe(stale) + }) + }) +}) -- 2.34.1 |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Thanks for the concrete patch and test results. I checked the current PR head against #56386: mini, run, and the v1 bridge now choose process.cwd() before chdir, and the existing localDirectory path already returns the physical cwd. The proposed stat-based helper would restore a preference for logical PWD paths and change that contract beyond the reported wrong-workspace fix, so I am keeping this PR on the process-cwd behavior. The inherited PWD passed to child processes is a distinct concern; I found no packages/cli/src consumer of process.env.PWD on this head, and would want a concrete child consumer/reproduction before changing the environment at these entry points. The explicit relative-directory regression in this PR remains valuable and is retained. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Thanks for taking the time to lay that out. You're right on the stat helper. It changes the contract, and that's not what this PR is fixing. I was solving a problem nobody reported here. And you're right about the child PWD too. I can't name a consumer, so drop it. If one shows up with a reproduction I'll open a separate issue rather than bolt Glad the relative-directory case stays. That one earned it. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Independent 2.3.0/macOS reproduction confirms this. #64126 adds a focused automated regression test for the |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Automated PR Cleanup Thank you for contributing to opencode. Due to the high volume of PRs from users and AI agents, we periodically close older PRs using automated criteria so maintainers can focus review time on the most active and community-supported contributions. This PR was closed because it matched the following cleanup criteria:
PRs created within the last month are not affected by this cleanup. If you believe this PR was closed incorrectly, or if you are still actively working on it, please leave a comment explaining why it should be reopened. A maintainer can review and reopen it if appropriate. Thanks again for taking the time to contribute. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
cli: run resolves the workspace from $PWD instead of the process cwd (still on 2.0.32)
There was an error while loading. Please reload this page.