Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-3193]): pin PWD to the spawn cwd so OpenCode stops running in the PortOS folder
[._.]/ Adam Eivyd5184599004d
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 441aa73b9f..431a2ade07 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -17,6 +17,7 @@ import http from 'http';import { Server as SocketServer } from 'socket.io';import { ensureDir, PATHS, sleep } from '../lib/fileUtils.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { createStreamJsonParser } from './streamJsonParser.js';@@ -187,7 +188,13 @@ app.post('/spawn', async (req, res) => {// Ensure workspacePath is validconst cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;- const childEnv = (() => { const e = { ...process.env, ...envVars }; delete e.CLAUDECODE; return e; })();+ // withSpawnCwdEnv pins PWD to `cwd`. Passing `cwd` to spawn() changes the+ // child's real working directory but leaves the inherited PWD naming the+ // PortOS checkout this runner was started in — and OpenCode resolves its+ // project root as `process.env.PWD ?? process.cwd()`, so every CoS agent on+ // that provider wrote into the PortOS folder while this handler's own log line+ // correctly reported the app's workspace. See issue #3193.+ const childEnv = (() => { const e = withSpawnCwdEnv({ ...process.env, ...envVars }, cwd); delete e.CLAUDECODE; return e; })();// Resolve a bare npm-installed CLI (opencode/codex/claude/… — a .cmd/.bat// shim on Windows) to its real path and wrap a shim as `cmd.exe /c <path>` sodiff --git a/server/lib/README.md b/server/lib/README.mdindex 8d4bf49544..4623211602 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -157,7 +157,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. || `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. Used by `appBuilder.js`, `appUpdater.js`, and the CoS agent spawners. |-| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180).+| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every AI CLI/TUI spawn site.| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex fbb28306e5..0e093be742 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -408,7 +408,21 @@ export function createRunnerService(config = {}) {const args = [...(provider.args || [])];console.log(`🚀 Executing CLI: ${provider.command} ${args.join(' ')} (${prompt.length} chars via stdin)`);- const childEnv = { ...process.env, ...provider.envVars };+ // PWD is pinned to the spawn cwd: passing `cwd` to spawn() changes the+ // child's real working directory but leaves the inherited PWD naming the+ // directory the host process was started in, and OpenCode resolves its+ // project root as `process.env.PWD ?? process.cwd()` — so it would run in+ // the host's directory instead of `workspacePath` (issue #3193). Inlined+ // rather than importing PortOS's `withSpawnCwdEnv` because this toolkit is+ // vendored and must not import out to other PortOS modules. The+ // case-insensitive filter matters on Windows, where a spread of+ // `process.env` can surface this variable as `Pwd`/`pwd` and a second+ // `PWD` key would hand the child two spellings of one variable.+ const childEnv = Object.fromEntries(+ Object.entries({ ...process.env, ...provider.envVars })+ .filter(([key]) => !(workspacePath && /^pwd$/i.test(key))),+ );+ if (workspacePath) childEnv.PWD = workspacePath;// Resolved against `childEnv` (not bare process.env) so a// provider-configured PATH override is honored.const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex 05e4d4218b..11b4f5a1a6 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -20,6 +20,7 @@ import { spawn } from 'child_process';import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';import { buildOpencodeEnvVars } from './opencodeConfig.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';+import { withSpawnCwdEnv } from './spawnCwd.js';/*** Resolve which CLI provider + model a feature should use from the providers@@ -107,7 +108,14 @@ export function runCliProviderPrompt(args = {}) {// models map for OpenCode Ollama providers (empty/no-op otherwise) so the// injected `--model ollama/<id>` isn't rejected as "not valid" — see// issue-2190. effectiveProvider carries the per-call model as defaultModel.- const childEnv = { ...baseEnv, ...provider.envVars, ...buildOpencodeEnvVars(effectiveProvider, effectiveProvider.defaultModel) };+ // withSpawnCwdEnv pins PWD to the directory this child actually runs in, so+ // a CLI that reads its project root from PWD (OpenCode does) can't fall back+ // to the PortOS checkout the server was started in — see issue #3193.+ const effectiveCwd = cwd || process.cwd();+ const childEnv = withSpawnCwdEnv(+ { ...baseEnv, ...provider.envVars, ...buildOpencodeEnvVars(effectiveProvider, effectiveProvider.defaultModel) },+ effectiveCwd,+ );delete childEnv.CLAUDECODE;// npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap@@ -120,7 +128,7 @@ export function runCliProviderPrompt(args = {}) {const resolvedCommand = resolveWindowsExecutable(provider.command, undefined, childEnv) || provider.command;const { command: spawnCommand, args: wrappedArgs } = prepareWindowsSafeSpawn(resolvedCommand, spawnArgs);const child = spawn(spawnCommand, wrappedArgs, {- cwd: cwd || process.cwd(),+ cwd: effectiveCwd,stdio: ['pipe', 'pipe', 'pipe'],env: childEnv,windowsHide: true,diff --git a/server/lib/spawnCwd.js b/server/lib/spawnCwd.jsindex 60081ded69..14b163911b 100644--- a/server/lib/spawnCwd.js+++ b/server/lib/spawnCwd.js@@ -19,6 +19,10 @@* caught where the app is looked up, because "no path" arrives here* indistinguishable from "no app selected". `getAppWorkspace` returns `null`* for that case rather than silently substituting the PortOS root.+ *+ * `withSpawnCwdEnv` covers the remaining failure mode: a CLI that resolves its+ * own working directory from the inherited `PWD` env var rather than from the+ * cwd it was actually spawned in (issue #3193).*/import { statSync } from 'fs';@@ -78,3 +82,51 @@ export function resolveSpawnCwd(workspacePath, fallbackRoot, label = 'run') {console.log(`📂 ${label} cwd: ${requested}`);return requested;}++// Windows environment-variable names are case-insensitive, so a spread of+// `process.env` can surface this variable as `Pwd`/`pwd`. Adding a separate+// `PWD` key to that object would hand the child two spellings of one variable+// with no defined winner — so every case variant is dropped before the correct+// value is set.+const PWD_KEY_RE = /^pwd$/i;++/**+ * Return a copy of `env` whose `PWD` names the directory the child will+ * actually run in.+ *+ * Passing `cwd` to `spawn()` changes the child's real working directory but+ * does NOT rewrite `PWD` in the inherited environment — that variable is+ * maintained by the shell, so a child spawned from the long-running PortOS+ * server inherits `PWD=<the PortOS checkout>` no matter where it was pointed.+ * Most CLIs never notice, because they read `process.cwd()`. OpenCode does:+ * `opencode run` resolves its project root as `process.env.PWD ?? process.cwd()`+ * (`packages/opencode/src/cli/cmd/run.ts`), so it ran every PortOS agent in the+ * PortOS folder while the spawn logs correctly reported the app's workspace —+ * "create HelloWorld.md" landed in the PortOS checkout, and asking the agent to+ * print its own working directory printed the PortOS path (issue #3193,+ * follow-up to #3180). Codex/Claude/Gemini were unaffected, which is why the+ * bug looked OpenCode-specific.+ *+ * Upstream closed that behavior as won't-fix and documented exporting a correct+ * `PWD` as the supported workaround, so PortOS pins it at every spawn site.+ * This is the right fix generally, not just for OpenCode: a `PWD` that+ * disagrees with the child's actual cwd is wrong for any process that reads it,+ * and pinning it costs nothing for the ones that don't.+ *+ * @param {NodeJS.ProcessEnv|object} env - env the child would otherwise receive+ * @param {string|undefined|null} cwd - the directory being passed to `spawn` as `cwd`+ * @returns {object} a copy of `env` with `PWD` set to `cwd` (unchanged copy when `cwd` is absent)+ */+export function withSpawnCwdEnv(env, cwd) {+ const next = {};+ const pin = typeof cwd === 'string' && cwd.length > 0;+ for (const [key, value] of Object.entries(env || {})) {+ // Only strip the stale variants when there's a real value to replace them+ // with — otherwise a caller that spawns without an explicit cwd would have+ // its inherited PWD deleted, which is a different (and equally wrong) lie.+ if (pin && PWD_KEY_RE.test(key)) continue;+ next[key] = value;+ }+ if (pin) next.PWD = cwd;+ return next;+}diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.jsindex 2e4325236b..3c06a5b6bc 100644--- a/server/lib/spawnCwd.test.js+++ b/server/lib/spawnCwd.test.js@@ -1,8 +1,8 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';import { tmpdir, homedir } from 'os';import { join } from 'path';-import { resolveSpawnCwd } from './spawnCwd.js';+import { resolveSpawnCwd, withSpawnCwdEnv } from './spawnCwd.js';describe('resolveSpawnCwd', () => {let dir;@@ -131,3 +131,93 @@ describe('resolveSpawnCwd — supplied-but-unusable never reaches the fallback',}});});++describe('withSpawnCwdEnv', () => {+ // The bug (#3193): spawn({ cwd }) changes the child's real working directory+ // but leaves the inherited PWD naming wherever the SERVER was started. OpenCode+ // resolves its project root as `process.env.PWD ?? process.cwd()`, so it ran+ // every agent in the PortOS checkout while the spawn logs correctly reported+ // the app's workspace.+ it('pins PWD to the spawn cwd, overriding a stale inherited value', () => {+ const env = withSpawnCwdEnv({ PATH: '/usr/bin', PWD: '/repos/PortOS' }, '/repos/my-app');+ expect(env.PWD).toBe('/repos/my-app');+ expect(env.PATH).toBe('/usr/bin');+ });++ it('sets PWD even when the inherited env had none', () => {+ expect(withSpawnCwdEnv({ PATH: '/usr/bin' }, '/repos/my-app').PWD).toBe('/repos/my-app');+ });++ // Windows env names are case-insensitive, so a spread of process.env can carry+ // `Pwd`. Leaving that key alongside a new `PWD` would hand the child two+ // spellings of one variable with no defined winner — i.e. it could still read+ // the stale one and land back in the PortOS folder.+ it('drops case-variant PWD keys so the child sees exactly one', () => {+ for (const variant of ['Pwd', 'pwd', 'pWd']) {+ const env = withSpawnCwdEnv({ [variant]: '/repos/PortOS', PATH: '/usr/bin' }, '/repos/my-app');+ const pwdKeys = Object.keys(env).filter((k) => /^pwd$/i.test(k));+ expect(pwdKeys, `${variant} must not survive alongside PWD`).toEqual(['PWD']);+ expect(env.PWD).toBe('/repos/my-app');+ }+ });++ // "No cwd was passed to spawn" means the child inherits the parent's real+ // working directory — so the inherited PWD is CORRECT there and deleting it+ // would substitute a different lie for the one being fixed.+ it('leaves the inherited PWD untouched when there is no cwd to pin', () => {+ for (const absent of [undefined, null, '']) {+ const env = withSpawnCwdEnv({ PWD: '/repos/PortOS', PATH: '/usr/bin' }, absent);+ expect(env.PWD).toBe('/repos/PortOS');+ expect(env.PATH).toBe('/usr/bin');+ }+ });++ it('copies rather than mutating the caller env', () => {+ const original = { PWD: '/repos/PortOS' };+ const env = withSpawnCwdEnv(original, '/repos/my-app');+ expect(original.PWD).toBe('/repos/PortOS');+ expect(env).not.toBe(original);+ });++ it('tolerates a null/undefined env', () => {+ expect(withSpawnCwdEnv(null, '/repos/my-app')).toEqual({ PWD: '/repos/my-app' });+ expect(withSpawnCwdEnv(undefined, undefined)).toEqual({});+ });+});++// Source invariant: every place PortOS spawns an AI CLI/TUI into a user+// workspace must pin PWD, or that provider silently runs in the PortOS checkout+// again (#3193). A unit-tested helper is worthless if a new spawn site forgets+// to call it, and the failure is invisible in normal use — the spawn logs still+// print the right cwd, only the FILES land in the wrong repo. So assert the call+// at each site rather than trusting convention.+describe('every AI CLI/TUI spawn site pins PWD to its spawn cwd', () => {+ const SPAWN_SITES = [+ // The #3193 repro: CoS task → runner → OpenCode agent.+ ['../cos-runner/index.js', 'withSpawnCwdEnv('],+ // Settings → Providers → Run Prompt (the #3180 repro path).+ ['../services/runner.js', 'withSpawnCwdEnv('],+ // CoS agent spawned in-process rather than through the runner.+ ['../services/agentCliSpawning.js', 'withSpawnCwdEnv('],+ // Every PTY session: the user's Shell page and agent-TUI sessions, which+ // inject the CLI command into this shell.+ ['../services/shell.js', 'withSpawnCwdEnv('],+ // Fire-and-collect CLI prompts (vision, app detect, feature helpers).+ ['./cliProviderRun.js', 'withSpawnCwdEnv('],+ // TUI-driven one-shot prompt runs (PTY spawned directly, no login shell to+ // rewrite PWD for us).+ ['./tuiPromptRunner.js', 'withSpawnCwdEnv('],+ // `/usage` quota scraping — spawns the TUI in a throwaway sandbox dir.+ ['./tuiUsageScrape.js', 'withSpawnCwdEnv('],+ // The vendored toolkit must not import out to other PortOS modules, so it+ // inlines the same pin instead of calling the shared helper.+ ['./aiToolkit/runner.js', 'childEnv.PWD = workspacePath'],+ ];++ for (const [relPath, marker] of SPAWN_SITES) {+ it(`${relPath} pins PWD`, () => {+ const src = readFileSync(new URL(relPath, import.meta.url), 'utf8');+ expect(src, `${relPath} spawns an AI CLI/TUI — it must pin PWD to the spawn cwd (see withSpawnCwdEnv)`).toContain(marker);+ });+ }+});diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex e80bccae3b..153c459e5d 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -58,6 +58,7 @@ import {detectMissingTuiBinary,} from './tuiHandshake.js';import { buildOpencodeEnvVars } from './opencodeConfig.js';+import { withSpawnCwdEnv } from './spawnCwd.js';// One-shot defaults that don't apply to the long-running agent path:// - hard run cap (5 min vs unbounded for agents)@@ -176,8 +177,14 @@ ${prompt}`;// for the same reason.// For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with// the models map so --model is accepted (the static env var lacked this).+ // withSpawnCwdEnv pins PWD to the directory this TUI actually runs in, so a+ // CLI that reads its project root from PWD (OpenCode does) can't fall back to+ // the PortOS checkout the server was started in — see issue #3193.const opencodeEnv = buildOpencodeEnvVars(provider, provider.defaultModel);- const childEnv = { ...process.env, ...(provider.envVars || {}), ...opencodeEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' };+ const childEnv = withSpawnCwdEnv(+ { ...process.env, ...(provider.envVars || {}), ...opencodeEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' },+ workingDir,+ );delete childEnv.CLAUDECODE;let ptyProcess;diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.jsindex a7362bf682..2dfa12dd75 100644--- a/server/lib/tuiUsageScrape.js+++ b/server/lib/tuiUsageScrape.js@@ -4,6 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import { stripAnsi } from './ansiStrip.js';import { sleep } from './fileUtils.js';+import { withSpawnCwdEnv } from './spawnCwd.js';/*** Drive an interactive coding-agent TUI (Antigravity `agy`, Grok Build `grok`)@@ -98,7 +99,13 @@ export async function scrapeTuiUsage({// Provider envVars (auth/config) merged over process.env, then the PTY hints.// CLAUDECODE leaks when PortOS itself runs under Claude Code; strip it so a// spawned TUI doesn't think it's nested (mirrors tuiPromptRunner.js).- const env = { ...process.env, ...extraEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' };+ // withSpawnCwdEnv pins PWD to the sandbox dir so a CLI that reads its project+ // root from PWD (OpenCode does) scrapes usage from the sandbox rather than+ // opening the PortOS checkout as a project. See issue #3193.+ const env = withSpawnCwdEnv(+ { ...process.env, ...extraEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' },+ sandboxDir,+ );delete env.CLAUDECODE;let pty;diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex d97643112b..983ca5e1b3 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -34,6 +34,7 @@ import { agentGuardEnv } from '../lib/agentGuard/index.js';import { resolveForgeTokenEnv } from './git.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';import { resolvePrCompletion } from '../lib/prDisposition.js';const AGENTS_DIR = PATHS.cosAgents;@@ -491,7 +492,9 @@ export async function spawnDirectly({// can't `pm2 kill` the shared daemon. opencodeEnv comes LAST to override// the static OPENCODE_CONFIG_CONTENT in provider.envVars; forgeTokenEnv sits// before provider.envVars so an explicit provider GH_TOKEN override still wins.- const childEnv = (() => { const e = { ...process.env, ...forgeTokenEnv, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })();+ // withSpawnCwdEnv pins PWD to `cwd` so a CLI that reads its project root from+ // PWD (OpenCode does) can't fall back to the PortOS checkout — see issue #3193.+ const childEnv = (() => { const e = withSpawnCwdEnv({ ...process.env, ...forgeTokenEnv, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }, cwd); delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })();// Resolve a bare npm-installed CLI (a .cmd/.bat shim on Windows) to its real// path and wrap a shim as `cmd.exe /c <path>` so spawn() under shell:falsediff --git a/server/services/runner.js b/server/services/runner.jsindex f4b5ef7fb6..1074de0ab2 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -6,7 +6,7 @@ import { spawn } from 'child_process';import { writeFile, readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, ensureDir, tryReadFile, PATHS } from '../lib/fileUtils.js';-import { resolveSpawnCwd } from '../lib/spawnCwd.js';+import { resolveSpawnCwd, withSpawnCwdEnv } from '../lib/spawnCwd.js';import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';@@ -266,7 +266,13 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on// buildOpencodeEnvVars rebuilds OPENCODE_CONFIG_CONTENT with a declared models// map for OpenCode Ollama providers (empty/no-op otherwise) so the injected// `--model ollama/<id>` isn't rejected as "not valid" — see issue-2190.- const childEnv = { ...process.env, ...provider.envVars, ...buildOpencodeEnvVars(provider, provider.defaultModel) };+ // withSpawnCwdEnv pins PWD to the directory this child actually runs in, so a+ // CLI that reads its project root from PWD (OpenCode does) can't fall back to+ // the PortOS checkout the server itself was started in — see issue #3193.+ const childEnv = withSpawnCwdEnv(+ { ...process.env, ...provider.envVars, ...buildOpencodeEnvVars(provider, provider.defaultModel) },+ effectiveCwd,+ );delete childEnv.CLAUDECODE;Object.assign(childEnv, agentGuardEnv(childEnv));diff --git a/server/services/shell.js b/server/services/shell.jsindex f3e62f3cbf..9ca3f3cab5 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -1,6 +1,7 @@import * as pty from 'node-pty';import os from 'os';import { v4 as uuidv4 } from '../lib/uuid.js';+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';// Store active shell sessions (persist across socket reconnects)const shellSessions = new Map();@@ -148,7 +149,12 @@ export function createShellSession(socket, options = {}) {cols,rows,cwd,- env: {+ // withSpawnCwdEnv pins PWD to this session's cwd. An interactive login+ // shell normally rewrites PWD itself at startup, but a non-login shell may+ // not — and an agent-TUI session injects a CLI command into this shell, so+ // an inherited PWD naming the PortOS checkout would send a PWD-reading CLI+ // (OpenCode does) to the wrong repo. See issue #3193.+ env: withSpawnCwdEnv({...buildSafeEnv(), // filters process.env to prevent leaking inherited secrets (e.g. shell-inherited API keys)// options.env is the caller's explicit opt-in env (e.g. TUI provider API keys for codex/claude).// Callers are responsible for not passing vars they don't want visible inside attachable shells.@@ -156,7 +162,7 @@ export function createShellSession(socket, options = {}) {...(options.env || {}),TERM: 'xterm-256color',COLORTERM: 'truecolor'- }+ }, cwd)});} catch (err) {console.error(`❌ Failed to spawn PTY: ${err.message}`);