Skip to content

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

fix([issue-3180]): stop agents silently running in the PortOS folder when an app's repoPath is bad

[._.]/ Adam Eivy57f9740ada84
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 731e7a6da4..e86fe4c15a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,11 @@
- **Malware scans now leave a durable, reviewable report trail.** Git-link scans save an owned markdown artifact, surface it from the completed agent summary and Review Hub, and mark repositories with an explicit `DANGEROUS` verdict using a skull danger treatment on the Git links card.
- **Slashdo-free TUI agent PRs now complete their lifecycle.** Codex, Antigravity, OpenCode, and lean Claude agents hand committed work back to PortOS so it can generate a non-empty PR description, run configured reviewers, and merge after the selected gates pass instead of leaving an ownerless PR open.
+## Agent workspaces
+
+- **[issue-3180] Agents no longer run in the PortOS folder when your app's repository path is wrong** — picking an app as the workspace (in a CoS task, or Settings → Providers → Run Prompt) and asking the agent to create a file could put the file in the PortOS directory instead of your app. If the app's Repository Path was empty, mistyped, or pointed somewhere that no longer exists, PortOS quietly fell back to its own folder and said nothing, so the run looked like it had worked. PortOS now names the directory it chose for every run (and in the CoS task log), warns when an app doesn't resolve to a repository path, and stops a run whose configured path doesn't exist with a message telling you which path to fix. Troubleshooting steps — including why `PORTOS_WORKSPACE_ROOTS` is unrelated to this — are in `docs/TROUBLESHOOTING.md`.
+- **[issue-3180] Agent terminals on Windows get a working environment** — the environment filter for agent shell sessions was written for macOS/Linux and dropped variables Windows needs, including `Path` itself (Windows spells it mixed-case, which the filter didn't match), plus `SystemRoot`, `ComSpec`, `TEMP`, and the per-user `APPDATA` folders where the coding CLIs keep their configuration and credentials. Windows sessions now keep those while still withholding API keys and tokens.
+
## Quota burn
- **[issue-3179] Quota-burn no longer spends window budget on runs that never happened** — a scheduled quota-burn run counted against the family's per-window dispatch cap as soon as it was considered, even when it was subsequently skipped and no agent was ever started. Those phantom dispatches ate the budget, so a family configured for e.g. 5 burns per reset window could fire far fewer — and a family capped at 1 could never fire at all, because the skipped run consumed the only slot before the next gate re-read it. A burn is now counted once its agent has actually run, and a burn that is queued or in progress holds its slot in the meantime, so the cap stays accurate without letting a second app or a repeated "Run" overshoot it.
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index e996aa5b05..7f10263c9f 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -146,6 +146,25 @@ which claude
2. Check file path in CoS config matches your TASKS.md location
3. Trigger manual evaluation via UI
+### Agent Writes Files Into the PortOS Folder Instead of My App
+
+**Symptom**: You pick an app as the workspace (in a CoS task, or **Settings → Providers → Run Prompt**) and ask the agent to create a file. It lands in the PortOS directory instead of the app's repo. Giving the agent an **absolute** path in the prompt works fine.
+
+**Cause**: The agent's working directory comes from the selected app's **Repository Path** (`repoPath`) — nothing else. If that value is empty, points at a folder that doesn't exist, or the app can't be resolved, PortOS falls back to its own directory, and a prompt naming a relative file (`HelloWorld.md`) writes there.
+
+**`PORTOS_WORKSPACE_ROOTS` does not control this.** That variable only scopes which directories the repo-detection and command-execution routes are allowed to read. Setting it will not change where an agent runs, and it is not required for agent workspaces to work.
+
+**Solution**:
+1. Open **Apps**, edit the app, and confirm **Repository Path** is the absolute path to the repo — e.g. `C:\Users\Example\Projects\MyApp` on Windows, `/Users/example/Projects/MyApp` on macOS/Linux. A path with a typo, a trailing quote, or a since-moved folder is the usual culprit.
+2. Re-run. PortOS logs the working directory it chose for every run:
+ ```
+ 📂 Run <run-id> cwd: C:\Users\Example\Projects\MyApp
+ ```
+ CoS tasks show the same thing in the task log as `📂 Agent workspace: …`. If you instead see a `⚠️` line saying the app did not resolve to a repo path, the app record is the problem — go back to step 1.
+3. If the configured path does not exist, the run now fails immediately with `Workspace path does not exist: …` rather than silently running in the PortOS folder. Fix the path and run again.
+
+**Note for Windows**: use a real filesystem path with drive letter (`C:\...`). Both `C:\Users\...` and `C:/Users/...` work; a path inside OneDrive-redirected folders is fine as long as it exists locally.
+
### Memory System Not Working
**Symptom**: Memory search returns no results, embeddings fail.
diff --git a/server/lib/README.md b/server/lib/README.md
index 1d530311dc..dbba6420bd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -119,6 +119,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoFile(repoId,filename)` resolves ONE known file in the newest snapshot **without walking it** (the whole-snapshot stat in `inspectModelCache` is prohibitive for an aggregate repo that hosts hundreds of GB of unrelated weights), and `repairCachedFile(path)` is the matching single-file repair (unlinks one snapshot entry AND the blob behind its symlink). `verifySafetensorsStructure(path,size)` is the reusable header/size structural check (reads only the header region) — also used by the Civitai/HF LoRA install path to reject truncated downloads. |
| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
| `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `icLoraWeightCandidates(spec)`, `findCachedIcLoraWeight(spec)`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping each remix mode (`ic-control`, `ic-colorize`, `ic-ingredients`) → its HF repo/filename, reference-count rule, per-weight `referenceDownscaleFactor` (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video' | 'image'`). A `requiresPreDownload` spec (Ingredients) suppresses `resolveIcLoraWeight`'s bare-repo-id fallback — the pipeline would `snapshot_download` it, and its candidates are a gated first-party repo plus a ~708 GB aggregate mirror, so the weight must be pre-fetched single-file instead. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. |
+| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a provider run spawns into, and throws when a workspace was requested but is missing / not a directory. Used by `services/runner.js` (CLI) and `lib/tuiPromptRunner.js` (TUI) so a bad app `repoPath` fails the run with an actionable message instead of silently spawning in the PortOS checkout (#3180). |
| `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. |
| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate; uses `SSE_HEADERS` from `sseHeaders.js`) — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |
| `installLogger.js` | `createInstallLogger({installer,target})` → `{start,onEvent,success,failure,cancel}` — server-console chokepoint for install/venv-setup SSE flows (the install-side analogue of `sseDownload.js`). Logs a START line, throttled heartbeats + `stage` milestones (not every raw pip/bash line), and the OUTCOME (success/fail/cancel) with elapsed time. `onEvent(ev)` auto-detects terminal `complete`/`error` SSE events. Used by the music/video runtime installers and the FLUX.2 venv bootstrap. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 38455d272e..ae5ec98ccf 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -127,6 +127,7 @@ export * from './createNewestWinsGuard.js';
export * from './dataRoot.js';
export * from './fileUtils.js';
export * from './fileWriteQueue.js';
+export * from './spawnCwd.js';
export * from './schemaVersions.js';
export * from './imageClean.js';
export * from './imageWatermark.js';
diff --git a/server/lib/spawnCwd.js b/server/lib/spawnCwd.js
new file mode 100644
index 0000000000..cdff73960f
--- /dev/null
+++ b/server/lib/spawnCwd.js
@@ -0,0 +1,55 @@
+/**
+ * Spawn working-directory resolution for provider runs.
+ *
+ * Every AI provider run gets a `workspacePath` (the selected app's repoPath) and
+ * spawns its CLI/TUI with that as the child's cwd. When the value is missing the
+ * spawn falls back to the PortOS repo root — which is a reasonable default, but
+ * used to be *silent*: a prompt like "create HelloWorld.md" then wrote into the
+ * PortOS checkout while the UI still showed the app as the selected workspace,
+ * with nothing anywhere saying which directory had actually been used
+ * (issue #3180).
+ *
+ * This module makes that decision explicit and loud in the two ways that
+ * matter: it logs the effective cwd for every run, and it refuses to spawn when
+ * the caller asked for a specific workspace that does not exist on disk (a
+ * typo'd or moved repo path) rather than quietly running somewhere else.
+ */
+
+import { existsSync, statSync } from 'fs';
+
+/**
+ * Resolve the working directory for a provider run.
+ *
+ * @param {string|undefined|null} workspacePath - caller-supplied workspace (app repoPath)
+ * @param {string} fallbackRoot - directory to use when no workspace was supplied
+ * @param {string} [label] - short run identifier used in the log line
+ * @returns {string} the directory to hand to `spawn`/`pty.spawn` as `cwd`
+ * @throws {Error} when `workspacePath` was supplied but is not an existing directory
+ */
+export function resolveSpawnCwd(workspacePath, fallbackRoot, label = 'run') {
+ const requested = typeof workspacePath === 'string' ? workspacePath.trim() : '';
+
+ if (!requested) {
+ console.log(`📂 ${label} cwd: ${fallbackRoot} (no workspace selected)`);
+ return fallbackRoot;
+ }
+
+ // Fail loudly instead of silently running in the PortOS checkout. A bad
+ // repoPath is a configuration error the user can fix; running the agent
+ // somewhere else and reporting success is not recoverable after the fact.
+ if (!existsSync(requested)) {
+ throw new Error(
+ `Workspace path does not exist: ${requested}. `
+ + `Fix the Repository Path for this app (Apps → edit → Repository Path) and run again.`
+ );
+ }
+ if (!statSync(requested).isDirectory()) {
+ throw new Error(
+ `Workspace path is not a directory: ${requested}. `
+ + `Set the app's Repository Path to the repo folder, not a file.`
+ );
+ }
+
+ console.log(`📂 ${label} cwd: ${requested}`);
+ return requested;
+}
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
new file mode 100644
index 0000000000..6ed5c1425a
--- /dev/null
+++ b/server/lib/spawnCwd.test.js
@@ -0,0 +1,58 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { resolveSpawnCwd } from './spawnCwd.js';
+
+describe('resolveSpawnCwd', () => {
+ let dir;
+ let logSpy;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'spawncwd-'));
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ logSpy.mockRestore();
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('returns the workspace when it exists', () => {
+ expect(resolveSpawnCwd(dir, '/fallback')).toBe(dir);
+ });
+
+ it('falls back to the root when no workspace was supplied', () => {
+ expect(resolveSpawnCwd(undefined, '/fallback')).toBe('/fallback');
+ expect(resolveSpawnCwd(null, '/fallback')).toBe('/fallback');
+ expect(resolveSpawnCwd('', '/fallback')).toBe('/fallback');
+ // A whitespace-only value is a blank field, not a real path — it must not
+ // reach existsSync and fail as "does not exist".
+ expect(resolveSpawnCwd(' ', '/fallback')).toBe('/fallback');
+ });
+
+ it('logs the effective cwd so a run is never silently misrouted', () => {
+ resolveSpawnCwd(dir, '/fallback', 'Run abc');
+ expect(logSpy.mock.calls.flat().join('\n')).toContain('Run abc');
+ expect(logSpy.mock.calls.flat().join('\n')).toContain(dir);
+
+ logSpy.mockClear();
+ resolveSpawnCwd('', '/fallback', 'Run xyz');
+ expect(logSpy.mock.calls.flat().join('\n')).toContain('no workspace selected');
+ });
+
+ // The #3180 regression: a workspace was requested but does not exist. The old
+ // behavior spawned in the PortOS root anyway, so the agent's relative file
+ // writes landed in the wrong repo with no error anywhere.
+ it('throws instead of falling back when the requested workspace is missing', () => {
+ const missing = join(dir, 'no-such-repo');
+ expect(() => resolveSpawnCwd(missing, '/fallback')).toThrow(/does not exist/);
+ expect(() => resolveSpawnCwd(missing, '/fallback')).toThrow(/Repository Path/);
+ });
+
+ it('throws when the requested workspace is a file, not a directory', () => {
+ const file = join(dir, 'a-file.txt');
+ writeFileSync(file, 'x');
+ expect(() => resolveSpawnCwd(file, '/fallback')).toThrow(/not a directory/);
+ });
+});
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index bef4619e74..1a44498ebf 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 { resolveSpawnCwd } 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)
@@ -122,14 +123,31 @@ export async function executeTuiRun({ runId, provider, prompt, workspacePath, on
const promptDelayMs = provider.tuiPromptDelayMs ?? DEFAULT_TUI_PROMPT_DELAY_MS;
const idleThresholdMs = idleMs ?? provider.tuiOneShotIdleMs ?? DEFAULT_ONE_SHOT_IDLE_MS;
const totalTimeoutMs = timeout ?? provider.timeout ?? DEFAULT_TIMEOUT_MS;
- const workingDir = (typeof workspacePath === 'string' && workspacePath) ? workspacePath : PATHS.root;
-
// Mirror runner.js#executeCliRun's runs-path resolution so TUI runs land
// under the runner-config dataDir (not always PATHS.runs) — otherwise a
// non-default dataDir would split metadata + output across two trees.
const runDir = join(getRunsPath(), runId);
await ensureDir(runDir);
+ // Logs the effective cwd, and rejects a workspace that was requested but is
+ // missing on disk instead of silently spawning in the PortOS root (#3180).
+ // Reported through the run's own completion record rather than thrown: the
+ // /runs route invokes executeTuiRun without awaiting, so a bare throw would
+ // surface only as an unhandled rejection and the run would look stuck.
+ // Sequenced after ensureDir so finalizeRunRecord has a run dir to write into.
+ let workingDir;
+ try {
+ workingDir = resolveSpawnCwd(workspacePath, PATHS.root, `TUI run ${runId}`);
+ } catch (err) {
+ const message = `❌ ${err.message}`;
+ onData?.(message);
+ const metadata = await finalizeRunRecord({
+ runId, output: message, exitCode: null, success: false, error: err.message, startTime: Date.now(),
+ });
+ onComplete?.(metadata);
+ return metadata;
+ }
+
// TUI screens redraw their banner, input chrome, and status bar on every
// keystroke — scraping the PTY stream for the model's reply is
// fundamentally lossy (box-drawing chars, "5%" cost meters, "bypass
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.js
index c42c43c618..ba44bf1629 100644
--- a/server/lib/tuiPromptRunner.test.js
+++ b/server/lib/tuiPromptRunner.test.js
@@ -3,6 +3,11 @@ import { mkdtemp, rm, writeFile, mkdir } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
+// executeTuiRun validates that a requested workspace actually exists before
+// spawning (#3180 — a bad repoPath used to silently run in the PortOS root), so
+// these tests need a real directory rather than a synthetic '/cwd' sentinel.
+const TEST_WORKSPACE = process.cwd();
+
// node-pty + runner hooks are mocked so executeTuiRun can be driven
// synchronously from the test without spawning a real terminal. fileUtils
// stays real for everything except `ensureDir` (which would otherwise create
@@ -311,7 +316,7 @@ describe('executeTuiRun', () => {
const provider = {
id: 'claude', type: 'tui', command: 'echo', defaultModel: 'claude-3.5',
};
- const promise = executeTuiRun({ runId: 'run-A', provider, prompt: 'do thing big enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-A', provider, prompt: 'do thing big enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });
await flushAsync();
expect(ptySpawnMock).toHaveBeenCalledTimes(1);
@@ -331,7 +336,7 @@ describe('executeTuiRun', () => {
it('registers a read-only Shell view (labelled by source) and tears it down on finish', async () => {
const provider = { id: 'claude', type: 'tui', command: 'claude', defaultModel: 'claude-fable-5' };
const promise = executeTuiRun({
- runId: 'run-view', provider, prompt: 'review this manuscript', workspacePath: '/work',
+ runId: 'run-view', provider, prompt: 'review this manuscript', workspacePath: TEST_WORKSPACE,
label: 'pipeline-manuscript-completeness',
});
await flushAsync();
@@ -342,7 +347,7 @@ describe('executeTuiRun', () => {
expect.objectContaining({
label: 'pipeline-manuscript-completeness',
kind: 'tui-run',
- cwd: '/work',
+ cwd: TEST_WORKSPACE,
}),
);
expect(shellMocks.unregisterExternalSession).not.toHaveBeenCalled();
@@ -354,7 +359,7 @@ describe('executeTuiRun', () => {
it('falls back to a command·model label when no source label is supplied', async () => {
const provider = { id: 'codex', type: 'tui', command: 'codex', defaultModel: 'gpt-x' };
- const promise = executeTuiRun({ runId: 'run-nolabel', provider, prompt: 'do the thing', workspacePath: '/w' });
+ const promise = executeTuiRun({ runId: 'run-nolabel', provider, prompt: 'do the thing', workspacePath: TEST_WORKSPACE });
await flushAsync();
expect(shellMocks.registerExternalSession).toHaveBeenCalledWith(
'run-nolabel', ptyInstances[0], expect.objectContaining({ label: 'codex · gpt-x' }),
@@ -376,7 +381,7 @@ describe('executeTuiRun', () => {
id: 'claude', type: 'tui', command: 'echo',
envVars: { CUSTOM_PROVIDER_VAR: 'on' },
};
- const promise = executeTuiRun({ runId: 'run-B', provider, prompt: 'p large enough to clear the guard', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-B', provider, prompt: 'p large enough to clear the guard', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });
await flushAsync();
const env = ptySpawnMock.mock.calls[0][2].env;
@@ -404,7 +409,7 @@ describe('executeTuiRun', () => {
tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500,
};
const onComplete = vi.fn();
- const promise = executeTuiRun({ runId: 'run-idle', provider, prompt: 'do thing big enough to clear the prompt guard', workspacePath: '/cwd', onData: undefined, onComplete, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-idle', provider, prompt: 'do thing big enough to clear the prompt guard', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete, timeout: 60000 });
await flushAsync();
const pty = ptyInstances[0];
@@ -450,7 +455,7 @@ describe('executeTuiRun', () => {
tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500,
};
const onComplete = vi.fn();
- const promise = executeTuiRun({ runId: 'run-watched', provider, prompt: 'do thing big enough to clear the prompt guard', workspacePath: '/cwd', onComplete, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-watched', provider, prompt: 'do thing big enough to clear the prompt guard', workspacePath: TEST_WORKSPACE, onComplete, timeout: 60000 });
await flushAsync();
const pty = ptyInstances[0];
@@ -492,7 +497,7 @@ describe('executeTuiRun', () => {
tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500,
};
const runId = 'run-respfile';
- const promise = executeTuiRun({ runId, provider, prompt: 'review this manuscript thoroughly enough to clear the guard', workspacePath: '/cwd', timeout: 60000 });
+ const promise = executeTuiRun({ runId, provider, prompt: 'review this manuscript thoroughly enough to clear the guard', workspacePath: TEST_WORKSPACE, timeout: 60000 });
await flushAsync();
const pty = ptyInstances[0];
@@ -532,7 +537,7 @@ describe('executeTuiRun', () => {
// hard-timeout salvage despite the result already being on disk.
const provider = { id: 'claude', type: 'tui', command: 'claude', tuiPromptDelayMs: 50 };
const runId = 'run-silent-respfile';
- const promise = executeTuiRun({ runId, provider, prompt: 'do the task quietly then write the file', workspacePath: '/cwd', timeout: 60000 });
+ const promise = executeTuiRun({ runId, provider, prompt: 'do the task quietly then write the file', workspacePath: TEST_WORKSPACE, timeout: 60000 });
await flushAsync();
const pty = ptyInstances[0];
@@ -574,7 +579,7 @@ describe('executeTuiRun', () => {
await mkdir(runDir, { recursive: true });
await writeFile(join(runDir, 'tui-response.txt'), 'the completed review body');
- const promise = executeTuiRun({ runId, provider, prompt: 'a prompt long enough to clear the guard', workspacePath: '/cwd', timeout: 500 });
+ const promise = executeTuiRun({ runId, provider, prompt: 'a prompt long enough to clear the guard', workspacePath: TEST_WORKSPACE, timeout: 500 });
await flushAsync();
await vi.advanceTimersByTimeAsync(600); // hard timeout fires
await flushAsync();
@@ -594,7 +599,7 @@ describe('executeTuiRun', () => {
toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],
});
const provider = { id: 'claude', type: 'tui', command: 'echo' };
- const promise = executeTuiRun({ runId: 'run-timeout', provider, prompt: 'a prompt long enough to clear the guard', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 500 });
+ const promise = executeTuiRun({ runId: 'run-timeout', provider, prompt: 'a prompt long enough to clear the guard', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 500 });
await flushAsync();
// No data emitted → no firstOutputAt → ready-watch never triggers paste
@@ -620,7 +625,7 @@ describe('executeTuiRun', () => {
});
shellMocks.isExternalSessionAttached.mockReturnValue(true); // a viewer is watching
const provider = { id: 'claude', type: 'tui', command: 'echo' };
- const promise = executeTuiRun({ runId: 'run-tmo-watched', provider, prompt: 'a prompt long enough to clear the guard', workspacePath: '/cwd', timeout: 500 });
+ const promise = executeTuiRun({ runId: 'run-tmo-watched', provider, prompt: 'a prompt long enough to clear the guard', workspacePath: TEST_WORKSPACE, timeout: 500 });
await flushAsync();
// The hard timeout fires even though a viewer is attached — only idle
@@ -638,7 +643,7 @@ describe('executeTuiRun', () => {
it('early-fails with reason "command-not-found" and exitCode 127 when "command not found" appears pre-paste', async () => {
const provider = { id: 'codex', type: 'tui', command: 'no-such-tui' };
- const promise = executeTuiRun({ runId: 'run-missing', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-missing', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });
await flushAsync();
// Shell banner echoing the missing-command error before paste.
@@ -657,7 +662,7 @@ describe('executeTuiRun', () => {
it('early-fails with reason "fallback-signal" when Claude switches to extra usage', async () => {
const provider = { id: 'claude', type: 'tui', command: 'claude' };
const onComplete = vi.fn();
- const promise = executeTuiRun({ runId: 'run-extra-usage', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-extra-usage', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete, timeout: 60000 });
await flushAsync();
ptyInstances[0].emitData('Now using extra ');
@@ -683,7 +688,7 @@ describe('executeTuiRun', () => {
it('early-fails with reason "fallback-signal" when the model id is rejected (Bedrock invalid identifier) instead of idling to a bogus-scrape success', async () => {
const provider = { id: 'claude', type: 'tui', command: 'claude' };
const onComplete = vi.fn();
- const promise = executeTuiRun({ runId: 'run-bad-model', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-bad-model', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete, timeout: 60000 });
await flushAsync();
// Claude Code renders the terminal model-id rejection inline and then sits
@@ -708,7 +713,7 @@ describe('executeTuiRun', () => {
it('finishes with reason "exit" + exitCode 0 when the PTY closes cleanly', async () => {
const provider = { id: 'claude', type: 'tui', command: 'echo' };
- const promise = executeTuiRun({ runId: 'run-exit', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-exit', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });
await flushAsync();
ptyInstances[0].emitExit({ exitCode: 0 });
@@ -735,7 +740,7 @@ describe('executeTuiRun', () => {
});
const provider = { id: 'claude', type: 'tui', command: 'echo' };
const onComplete = vi.fn();
- const promise = executeTuiRun({ runId: 'run-finish-throws', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onComplete, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-finish-throws', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onComplete, timeout: 60000 });
await flushAsync();
ptyInstances[0].emitExit({ exitCode: 0 });
@@ -767,7 +772,7 @@ describe('executeTuiRun', () => {
// success-then-failure. The run promise must still resolve exactly once.
const provider = { id: 'claude', type: 'tui', command: 'echo' };
const onComplete = vi.fn(() => { throw new Error('boom: caller onComplete blew up'); });
- const promise = executeTuiRun({ runId: 'run-oncomplete-throws', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onComplete, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-oncomplete-throws', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onComplete, timeout: 60000 });
await flushAsync();
ptyInstances[0].emitExit({ exitCode: 0 });
@@ -780,7 +785,7 @@ describe('executeTuiRun', () => {
it('finishes with reason "killed" and surfaces the signal in the error when the PTY is terminated', async () => {
const provider = { id: 'claude', type: 'tui', command: 'echo' };
- const promise = executeTuiRun({ runId: 'run-killed', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-killed', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });
await flushAsync();
ptyInstances[0].emitData('some screen output');
@@ -798,7 +803,7 @@ describe('executeTuiRun', () => {
it('finishes with a tail-bearing error message when the PTY exits non-zero with prior output', async () => {
const provider = { id: 'claude', type: 'tui', command: 'echo' };
- const promise = executeTuiRun({ runId: 'run-nonzero', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });
+ const promise = executeTuiRun({ runId: 'run-nonzero', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });
await flushAsync();
ptyInstances[0].emitData('fatal: provider config malformed at line 42');
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 2de892e250..d4da700a6e 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -1993,26 +1993,39 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR
/**
* Get workspace path for an app.
+ *
+ * Falls back to the PortOS repo root when the app can't be resolved or carries
+ * no `repoPath`. That fallback is deliberate (an agent still needs *a* cwd) but
+ * it used to be silent, which is indistinguishable from "the workspace worked"
+ * — the agent just quietly wrote its files into the PortOS checkout instead of
+ * the target app (issue #3180). Every fallback now says why.
*/
export async function getAppWorkspace(appName) {
const appsFile = join(ROOT_DIR, 'data/apps.json');
const data = await readJSONFile(appsFile, null);
if (!data) {
+ console.warn(`⚠️ No apps registry at ${appsFile} — agent workspace falls back to PortOS root`);
return ROOT_DIR;
}
// Handle both object format { apps: { id: {...} } } and array format [...]
const apps = data.apps || data;
- if (Array.isArray(apps)) {
- const app = apps.find(a => a.name === appName || a.id === appName);
- return app?.repoPath || ROOT_DIR;
- }
+ const app = Array.isArray(apps)
+ ? apps.find(a => a.name === appName || a.id === appName)
+ // Object format - keys are app IDs
+ : (apps[appName] || Object.values(apps).find(a => a.name === appName));
- // Object format - keys are app IDs
- const app = apps[appName] || Object.values(apps).find(a => a.name === appName);
- return app?.repoPath || ROOT_DIR;
+ if (!app) {
+ console.warn(`⚠️ App '${appName}' not found in apps registry — agent workspace falls back to PortOS root`);
+ return ROOT_DIR;
+ }
+ if (!app.repoPath) {
+ console.warn(`⚠️ App '${appName}' has no repoPath — agent workspace falls back to PortOS root`);
+ return ROOT_DIR;
+ }
+ return app.repoPath;
}
/**
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 1f19de66f0..cd1a7099e5 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -54,6 +54,24 @@ export async function prepareAgentWorkspace({ agentId, task }) {
? (await getAppById(task.metadata.app).catch(() => null))?.name || null
: null;
+ // Surface the resolved cwd in the task log. The agent runs with this as its
+ // working directory, so a prompt that names a relative file ("create
+ // HelloWorld.md") writes HERE — and when resolution silently fell back to the
+ // PortOS root the files landed in the PortOS checkout with nothing in the log
+ // to explain it (issue #3180). Both failure shapes are now visible to the user
+ // in the UI, not just in server stdout.
+ if (task.metadata?.app && workspacePath === ROOT_DIR) {
+ emitLog('warn', `⚠️ App '${task.metadata.app}' did not resolve to a repo path — the agent will run in the PortOS directory, not your app. Check the app's Repository Path in Apps.`, {
+ taskId: task.id, workspace: workspacePath
+ });
+ } else if (!existsSync(workspacePath)) {
+ emitLog('warn', `⚠️ Workspace path does not exist: ${workspacePath} — the agent will likely fail to start or write to the wrong place.`, {
+ taskId: task.id, workspace: workspacePath
+ });
+ } else {
+ emitLog('info', `📂 Agent workspace: ${workspacePath}`, { taskId: task.id, workspace: workspacePath });
+ }
+
let jiraTicket = null;
let jiraBranchName = null;
let worktreeInfo = null;
diff --git a/server/services/runner.js b/server/services/runner.js
index f58da650e2..7851d4535b 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -5,7 +5,8 @@
import { spawn } from 'child_process';
import { writeFile, readFile } from 'fs/promises';
import { join } from 'path';
-import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, tryReadFile, PATHS } from '../lib/fileUtils.js';
+import { resolveSpawnCwd } from '../lib/spawnCwd.js';
import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
@@ -199,6 +200,26 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
killProcessTree(childProcess);
};
+ // Resolve (and log) the working directory before spawning. A supplied-but-
+ // missing workspace fails the run with an actionable message instead of
+ // silently spawning in the PortOS checkout, where relative file writes from
+ // the prompt would land in the wrong repo (#3180). Reported through the run's
+ // own completion path rather than thrown: the toolkit route invokes this
+ // without awaiting, so a bare throw would surface only as an unhandled
+ // rejection and the UI would show the run hanging.
+ let effectiveCwd;
+ try {
+ effectiveCwd = resolveSpawnCwd(workspacePath, PATHS.root, `Run ${runId}`);
+ } catch (err) {
+ const message = `❌ ${err.message}`;
+ onData?.(message);
+ const metadata = await finalizeRunRecord({
+ runId, output: message, exitCode: null, success: false, error: err.message, startTime,
+ });
+ onComplete?.(metadata);
+ return;
+ }
+
// Build provider-specific args for prompt delivery
const builtArgs = buildCliArgs(provider);
// Rewrite the argv for prompt delivery and learn whether to still write stdin:
@@ -227,7 +248,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
const { command: spawnCommand, args: spawnArgs } = prepareWindowsSafeSpawn(resolvedCommand, args);
childProcess = spawn(spawnCommand, spawnArgs, {
- cwd: workspacePath,
+ cwd: effectiveCwd,
env: childEnv,
windowsHide: true
});
@@ -289,7 +310,10 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
if (metadata.providerId == null && provider.id) metadata.providerId = provider.id;
if (metadata.providerName == null && (provider.name || provider.id)) metadata.providerName = provider.name || provider.id;
if (metadata.model == null && provider.defaultModel) metadata.model = provider.defaultModel;
- if (metadata.workspacePath == null && workspacePath) metadata.workspacePath = workspacePath;
+ // Record the cwd the child ACTUALLY ran in, not the requested one — when no
+ // workspace was selected these differ, and the /runs replay claiming a
+ // workspace the run never used is the confusion this fixes (#3180).
+ if (metadata.workspacePath == null && effectiveCwd) metadata.workspacePath = effectiveCwd;
try {
if (timeoutHandle) clearTimeout(timeoutHandle);
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index fb7f30bd51..a264ea8ad8 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -1,6 +1,11 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import EventEmitter from 'events';
+// executeCliRun validates that a requested workspace actually exists before
+// spawning (#3180 — a bad repoPath used to silently run in the PortOS root), so
+// these tests need a real directory rather than a synthetic '/workspace' path.
+const TEST_WORKSPACE = process.cwd();
+
vi.mock('child_process', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, spawn: vi.fn() };
@@ -22,8 +27,11 @@ vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {
});
vi.mock('../lib/fileUtils.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
+ tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(undefined),
+ // executeCliRun resolves its spawn cwd against PATHS.root when no workspace
+ // is supplied; the mock must carry it or every run short-circuits (#3180).
+ PATHS: { root: process.cwd(), data: '/tmp/test-runner', runs: '/tmp/test-runner/runs' },
// atomicWrite replaced the raw writeFile(JSON.stringify) metadata sites (#1837);
// route it through the mocked fs/promises.writeFile so it resolves cleanly.
atomicWrite: vi.fn(async (filePath, data) => {
@@ -97,7 +105,7 @@ describe('executeCliRun — Codex sentinel suppression', () => {
child.emit('close', 0);
});
- await executeCliRun({ runId: 'run-1', provider, prompt: 'test prompt', workspacePath: '/workspace' });
+ await executeCliRun({ runId: 'run-1', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE });
const [, capturedArgs] = spawn.mock.calls.at(-1);
expect(capturedArgs).not.toContain('--model');
@@ -124,7 +132,7 @@ describe('executeCliRun — Codex sentinel suppression', () => {
child.emit('close', 0);
});
- await executeCliRun({ runId: 'run-2', provider, prompt: 'test prompt', workspacePath: '/workspace' });
+ await executeCliRun({ runId: 'run-2', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE });
const [, capturedArgs] = spawn.mock.calls.at(-1);
const modelIdx = capturedArgs.indexOf('--model');
@@ -147,7 +155,7 @@ describe('executeCliRun — Codex sentinel suppression', () => {
};
const completed = new Promise((resolve) => {
- executeCliRun({ runId: 'run-extra-usage', provider, prompt: 'test prompt', workspacePath: '/workspace', onData: undefined, onComplete: resolve, timeout: 60000 });
+ executeCliRun({ runId: 'run-extra-usage', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: resolve, timeout: 60000 });
});
await Promise.resolve();
@@ -179,7 +187,7 @@ describe('executeCliRun — Codex sentinel suppression', () => {
};
const completed = new Promise((resolve) => {
- executeCliRun({ runId: 'run-fallback-exit0', provider, prompt: 'test prompt', workspacePath: '/workspace', onData: undefined, onComplete: resolve, timeout: 60000 });
+ executeCliRun({ runId: 'run-fallback-exit0', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: resolve, timeout: 60000 });
});
await Promise.resolve();
@@ -216,7 +224,7 @@ describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {
child.emit('close', 0);
});
- await executeCliRun({ runId: 'run-resolved', provider, prompt: 'test prompt', workspacePath: '/workspace' });
+ await executeCliRun({ runId: 'run-resolved', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE });
const [command, args, options] = spawn.mock.calls.at(-1);
expect(command).toBe('cmd.exe');
@@ -244,7 +252,7 @@ describe('executeCliRun — Windows .cmd/.bat shim spawning (#1865)', () => {
child.emit('close', 0);
});
- await executeCliRun({ runId: 'run-unresolved', provider, prompt: 'test prompt', workspacePath: '/workspace' });
+ await executeCliRun({ runId: 'run-unresolved', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE });
const [command, , options] = spawn.mock.calls.at(-1);
expect(command).toBe('codex');
@@ -270,7 +278,7 @@ describe('executeCliRun — close handler crash guard', () => {
defaultModel: 'codex-configured-default', timeout: 5000,
};
const onComplete = vi.fn();
- await executeCliRun({ runId, provider, prompt: 'test prompt', workspacePath: '/workspace', onComplete });
+ await executeCliRun({ runId, provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onComplete });
child.stdout.emit('data', Buffer.from('output'));
child.emit('close', 0);
@@ -317,7 +325,7 @@ describe('executeCliRun — close handler crash guard', () => {
defaultModel: 'codex-configured-default', timeout: 5000,
};
const onComplete = vi.fn();
- await executeCliRun({ runId: 'run-success-hook-throws', provider, prompt: 'test prompt', workspacePath: '/workspace', onComplete });
+ await executeCliRun({ runId: 'run-success-hook-throws', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onComplete });
child.stdout.emit('data', Buffer.from('output'));
child.emit('close', 0);
@@ -345,7 +353,7 @@ describe('executeCliRun — close handler crash guard', () => {
defaultModel: 'codex-configured-default', timeout: 5000,
};
const onComplete = vi.fn();
- await executeCliRun({ runId: 'run-async-hook-rejects', provider, prompt: 'test prompt', workspacePath: '/workspace', onComplete });
+ await executeCliRun({ runId: 'run-async-hook-rejects', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onComplete });
child.stdout.emit('data', Buffer.from('output'));
child.emit('close', 0);
@@ -386,7 +394,7 @@ describe('executeCliRun — close handler crash guard', () => {
runId: 'run-spawn-error',
provider,
prompt: 'test prompt',
- workspacePath: '/workspace',
+ workspacePath: TEST_WORKSPACE,
onComplete,
});
@@ -719,3 +727,46 @@ describe('emitRunStarted — payload-flattening contract', () => {
})).not.toThrow();
});
});
+
+describe('executeCliRun — workspace validation (#3180)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ setAIToolkit(fakeToolkit(), { dataDir: '/tmp/test-runner' });
+ });
+
+ const provider = { id: 'codex', name: 'Codex', command: 'codex', args: [], timeout: 5000 };
+
+ // The bug: a workspace that doesn't exist used to fall through to spawn(),
+ // which quietly ran the agent in the PortOS checkout. A prompt naming a
+ // relative file then wrote into the wrong repo with no error anywhere.
+ it('fails the run instead of spawning when the workspace does not exist', async () => {
+ const onComplete = vi.fn();
+ const onData = vi.fn();
+
+ await executeCliRun({
+ runId: 'run-bad-workspace',
+ provider,
+ prompt: 'test prompt',
+ workspacePath: '/definitely/not/a/real/repo/path',
+ onData,
+ onComplete,
+ });
+
+ expect(spawn).not.toHaveBeenCalled();
+ expect(onData).toHaveBeenCalledWith(expect.stringContaining('Workspace path does not exist'));
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ expect(onComplete.mock.calls[0][0]).toMatchObject({ success: false });
+ });
+
+ // The /runs route invokes executeCliRun without awaiting it, so this path
+ // must report through onComplete rather than rejecting — a bare throw would
+ // surface only as an unhandled rejection and leave the run looking stuck.
+ it('reports the failure via onComplete rather than rejecting', async () => {
+ await expect(executeCliRun({
+ runId: 'run-bad-workspace-2',
+ provider,
+ prompt: 'test prompt',
+ workspacePath: '/definitely/not/a/real/repo/path',
+ })).resolves.toBeUndefined();
+ });
+});
diff --git a/server/services/shell.js b/server/services/shell.js
index e93951bb0b..8ef86f70ea 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -38,10 +38,46 @@ const SAFE_ENV_PREFIXES = [
'KUBECONFIG', 'LESS', 'PAGER', 'MANPATH', 'INFOPATH', 'ZDOTDIR', 'STARSHIP_'
];
-function buildSafeEnv() {
+// Windows-only additions. The list above is POSIX-shaped: on Windows it drops
+// variables the OS itself needs to create a working process, so a PTY session
+// started from it launches into a crippled shell (no DLL search root, no temp
+// dir, no per-user app data — which is where `claude`/`codex` keep their
+// credentials and config). Enumerated explicitly rather than by prefix because
+// these have no common stem, and kept separate so POSIX sessions are unchanged.
+const SAFE_ENV_PREFIXES_WIN32 = [
+ 'SYSTEMROOT', 'SYSTEMDRIVE', 'WINDIR', 'COMSPEC', 'PATHEXT',
+ 'USERPROFILE', 'USERNAME', 'USERDOMAIN', 'HOMEDRIVE', 'HOMEPATH',
+ 'APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES', 'PROGRAMFILES(X86)',
+ 'PROGRAMDATA', 'PROGRAMW6432', 'COMMONPROGRAMFILES', 'TEMP', 'TMP',
+ 'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE', 'OS', 'PSMODULEPATH'
+];
+
+/**
+ * Filter `process.env` down to the allowlist above.
+ *
+ * Matching is case-INSENSITIVE because Windows environment variable names are
+ * case-insensitive and Windows supplies them in mixed case: the real variable
+ * is `Path`, not `PATH`, so a case-sensitive `startsWith('PATH')` dropped the
+ * child's entire PATH on Windows while keeping `PATHEXT` (which happens to be
+ * upper-case) — the shell then couldn't resolve any CLI provider. POSIX env
+ * names are conventionally upper-case already, so folding case is a no-op
+ * there.
+ *
+ * Exported for tests; `platform` is injectable so the Windows branch is
+ * testable from any host.
+ *
+ * @param {NodeJS.ProcessEnv} [env] - source environment; defaults to `process.env`
+ * @param {string} [platform] - `process.platform` value; defaults to the real one
+ * @returns {Record<string, string>} filtered environment
+ */
+export function buildSafeEnv(env = process.env, platform = process.platform) {
+ const prefixes = platform === 'win32'
+ ? [...SAFE_ENV_PREFIXES, ...SAFE_ENV_PREFIXES_WIN32]
+ : SAFE_ENV_PREFIXES;
const safeEnv = {};
- for (const [key, value] of Object.entries(process.env)) {
- if (SAFE_ENV_PREFIXES.some(prefix => key === prefix || key.startsWith(prefix))) {
+ for (const [key, value] of Object.entries(env)) {
+ const upper = key.toUpperCase();
+ if (prefixes.some(prefix => upper === prefix || upper.startsWith(prefix))) {
safeEnv[key] = value;
}
}
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index b9f68df52f..0d20700096 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -583,3 +583,52 @@ describe('getSession / getSessionProcess / getSessionCount', () => {
expect(shell.getSessionCount()).toBe(2);
});
});
+
+describe('buildSafeEnv', () => {
+ // Windows environment variable names are case-insensitive and arrive in mixed
+ // case: the real variable is `Path`, not `PATH`. A case-SENSITIVE prefix match
+ // dropped it (while keeping the coincidentally-upper-case `PATHEXT`), leaving
+ // the agent shell unable to resolve any CLI provider (#3180).
+ it('keeps mixed-case Windows variables that a case-sensitive match dropped', () => {
+ const env = {
+ Path: 'C:\\Windows\\system32',
+ PATHEXT: '.COM;.EXE;.BAT;.CMD',
+ SystemRoot: 'C:\\Windows',
+ windir: 'C:\\Windows',
+ ComSpec: 'C:\\Windows\\system32\\cmd.exe',
+ TEMP: 'C:\\Users\\Example\\AppData\\Local\\Temp',
+ APPDATA: 'C:\\Users\\Example\\AppData\\Roaming',
+ LOCALAPPDATA: 'C:\\Users\\Example\\AppData\\Local',
+ ProgramFiles: 'C:\\Program Files',
+ USERPROFILE: 'C:\\Users\\Example',
+ };
+ const safe = shell.buildSafeEnv(env, 'win32');
+ for (const key of Object.keys(env)) {
+ expect(safe, `expected ${key} to survive the allowlist`).toHaveProperty(key);
+ }
+ });
+
+ it('still strips secrets on Windows', () => {
+ const safe = shell.buildSafeEnv(
+ { Path: 'C:\\Windows', ANTHROPIC_API_KEY: 'sk-secret', GITHUB_TOKEN: 'ghp_secret' },
+ 'win32'
+ );
+ expect(safe).toHaveProperty('Path');
+ expect(safe).not.toHaveProperty('ANTHROPIC_API_KEY');
+ expect(safe).not.toHaveProperty('GITHUB_TOKEN');
+ });
+
+ // The Windows names must not widen the POSIX allowlist — a Linux/macOS box
+ // with an `OS` or `TEMP` var set should filter exactly as it did before.
+ it('does not apply the Windows additions on POSIX', () => {
+ const safe = shell.buildSafeEnv(
+ { PATH: '/usr/bin', HOME: '/home/example', APPDATA: 'x', SystemRoot: 'y', ANTHROPIC_API_KEY: 'sk-secret' },
+ 'linux'
+ );
+ expect(safe).toHaveProperty('PATH');
+ expect(safe).toHaveProperty('HOME');
+ expect(safe).not.toHaveProperty('APPDATA');
+ expect(safe).not.toHaveProperty('SystemRoot');
+ expect(safe).not.toHaveProperty('ANTHROPIC_API_KEY');
+ });
+});