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

refactor([issue-3180]): widen the workspace guard to the CoS agent path and share the resolver

[._.]/ Adam Eivye261b9c829c0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e86fe4c15a..588257d879 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,7 +7,7 @@
## 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] 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. Now PortOS names the directory it chose for every run and in the CoS task log; a run whose workspace doesn't exist stops with a message telling you which path to fix; and a CoS task whose app has no usable Repository Path is blocked before the agent starts, rather than turned loose in the PortOS checkout. A path saved as `~/Projects/MyApp` is also accepted. 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
diff --git a/server/lib/README.md b/server/lib/README.md
index dbba6420bd..eb166d92cc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -119,7 +119,6 @@ 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. |
@@ -157,6 +156,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).
| `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/spawnCwd.js b/server/lib/spawnCwd.js
index cdff73960f..c4449e4178 100644
--- a/server/lib/spawnCwd.js
+++ b/server/lib/spawnCwd.js
@@ -1,33 +1,44 @@
/**
- * Spawn working-directory resolution for provider runs.
+ * Spawn working-directory resolution for provider runs and agents.
*
- * 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).
+ * Every AI provider run and CoS agent 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.
+ * matter: it logs the effective cwd for every spawn, and it rejects a workspace
+ * that was requested but does not exist on disk (a typo'd or moved repo path)
+ * rather than quietly running somewhere else.
+ *
+ * Note this can only catch a workspace that *resolved to something wrong*. The
+ * other half of #3180 — an app that resolves to no path at all — has to be
+ * 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.
*/
-import { existsSync, statSync } from 'fs';
+import { statSync } from 'fs';
+import { expandHome } from './fileUtils.js';
/**
- * Resolve the working directory for a provider run.
+ * Resolve the working directory for a spawned run or agent.
*
* @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
+ * @param {string} [label] - short run/agent 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() : '';
+ // expandHome so a repoPath saved as `~/Projects/App` resolves instead of
+ // hard-failing as "does not exist" — `repoPath` is only validated as a
+ // non-empty string, and every other user-supplied-path boundary in the repo
+ // expands it too.
+ const requested = expandHome(typeof workspacePath === 'string' ? workspacePath.trim() : '');
if (!requested) {
console.log(`📂 ${label} cwd: ${fallbackRoot} (no workspace selected)`);
@@ -37,13 +48,14 @@ export function resolveSpawnCwd(workspacePath, fallbackRoot, label = 'run') {
// 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)) {
+ const stats = statSync(requested, { throwIfNoEntry: false });
+ if (!stats) {
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()) {
+ if (!stats.isDirectory()) {
throw new Error(
`Workspace path is not a directory: ${requested}. `
+ `Set the app's Repository Path to the repo folder, not a file.`
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index 6ed5c1425a..e45f83a297 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
-import { tmpdir } from 'os';
+import { tmpdir, homedir } from 'os';
import { join } from 'path';
import { resolveSpawnCwd } from './spawnCwd.js';
@@ -56,3 +56,14 @@ describe('resolveSpawnCwd', () => {
expect(() => resolveSpawnCwd(file, '/fallback')).toThrow(/not a directory/);
});
});
+
+describe('resolveSpawnCwd — home expansion', () => {
+ // repoPath is only validated as a non-empty string, so a user can save
+ // `~/Projects/App`. Without expansion the new guard would hard-fail it with a
+ // message naming a path that was never meant to be literal.
+ it('expands a leading ~ instead of rejecting it as missing', () => {
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ expect(resolveSpawnCwd('~', '/fallback')).toBe(homedir());
+ logSpy.mockRestore();
+ });
+});
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.js
index 1a44498ebf..e80bccae3b 100644
--- a/server/lib/tuiPromptRunner.js
+++ b/server/lib/tuiPromptRunner.js
@@ -38,7 +38,7 @@ import { join, resolve } from 'path';
import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';
import { createStreamingAnsiStripper, stripAnsi } from './ansiStrip.js';
import { createImmediateFallbackSignalDetector, createTerminalModelErrorDetector } from './aiToolkit/errorDetection.js';
-import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun } from '../services/runner.js';
+import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun, resolveRunCwd } from '../services/runner.js';
import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached } from '../services/shell.js';
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
@@ -58,7 +58,6 @@ 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)
@@ -131,22 +130,11 @@ export async function executeTuiRun({ runId, provider, prompt, workspacePath, on
// 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;
- }
+ const { cwd: workingDir, failure } = await resolveRunCwd({
+ runId, workspacePath, label: `TUI run ${runId}`, onData, onComplete,
+ });
+ if (failure) return failure;
// TUI screens redraw their banner, input chrome, and status bar on every
// keystroke — scraping the PTY stream for the model's reply is
diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.js
index ba44bf1629..2565f19ba4 100644
--- a/server/lib/tuiPromptRunner.test.js
+++ b/server/lib/tuiPromptRunner.test.js
@@ -24,6 +24,10 @@ const { ptyInstances, ptySpawnMock, runnerMocks, shellMocks, runsTmpDirRef } = v
registerActiveRun: vi.fn(),
unregisterActiveRun: vi.fn(),
getRunsPath: vi.fn(),
+ // Real implementation (and its bad-workspace failure path) is covered by
+ // lib/spawnCwd.test.js + services/runner.test.js; here it just needs to
+ // hand back the cwd so the PTY spawn assertions below still see it.
+ resolveRunCwd: vi.fn(async ({ workspacePath }) => ({ cwd: workspacePath })),
},
// shell.js is mocked so the runner's Shell-view registration is observable
// here without dragging in the real session registry singleton.
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index d4da700a6e..d7c33a503b 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -1992,22 +1992,28 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR
}
/**
- * Get workspace path for an app.
+ * Get the workspace path for an app, or `null` when it can't be resolved.
*
- * 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.
+ * This used to substitute the PortOS repo root for every failure — registry
+ * missing, app not found, app carrying no `repoPath` — which made an
+ * unresolvable app indistinguishable from a working one: the agent quietly
+ * wrote its files into the PortOS checkout and nothing said otherwise
+ * (issue #3180). A downstream existence check can't recover that case either,
+ * because the substituted root is a real directory.
+ *
+ * So this returns an explicit `null` sentinel and lets each caller decide
+ * whether "no workspace" is legal for it (per the sentinel-and-validate rule in
+ * CLAUDE.md — absent must not collapse into a valid-looking value). The reason
+ * is logged here, where it's known.
+ *
+ * @returns {Promise<string|null>} the app's repoPath, or null if unresolvable
*/
export async function getAppWorkspace(appName) {
const appsFile = join(ROOT_DIR, 'data/apps.json');
+ const unresolved = (why) => { console.warn(`⚠️ ${why} — no agent workspace resolved`); return null; };
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;
- }
+ if (!data) return unresolved(`No apps registry at ${appsFile}`);
// Handle both object format { apps: { id: {...} } } and array format [...]
const apps = data.apps || data;
@@ -2017,14 +2023,8 @@ export async function getAppWorkspace(appName) {
// Object format - keys are app IDs
: (apps[appName] || Object.values(apps).find(a => a.name === appName));
- 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;
- }
+ if (!app) return unresolved(`App '${appName}' not found in apps registry`);
+ if (!app.repoPath) return unresolved(`App '${appName}' has no repoPath`);
return app.repoPath;
}
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index cd1a7099e5..d4cdeac825 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -54,22 +54,23 @@ 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 });
+ // Refuse to run an agent whose app didn't resolve to a usable directory.
+ // Previously both failures fell through to the PortOS root and the agent
+ // silently did its work in the PortOS checkout instead of the user's app
+ // (issue #3180) — a wrong-repo commit is far worse than a blocked task, and
+ // the block carries the exact thing to fix. Validated ONCE here rather than in
+ // each of the three spawn helpers (TUI / runner / direct), which all take
+ // their cwd from this function.
+ if (task.metadata?.app && !workspacePath) {
+ const reason = `App '${task.metadata.app}' has no usable Repository Path — set it in Apps, then re-run this task. `
+ + `(The agent was not started, so it could not write into the PortOS directory by mistake.)`;
+ emitLog('error', `❌ ${reason}`, { taskId: task.id });
+ return { outcome: 'blocked', reason };
+ }
+ if (!existsSync(workspacePath)) {
+ const reason = `Workspace path does not exist: ${workspacePath} — fix this app's Repository Path in Apps, then re-run this task.`;
+ emitLog('error', `❌ ${reason}`, { taskId: task.id, workspace: workspacePath });
+ return { outcome: 'blocked', reason };
}
let jiraTicket = null;
@@ -278,6 +279,11 @@ export async function prepareAgentWorkspace({ agentId, task }) {
}
} // end !isReadOnly
+ // Announce the FINAL cwd — emitted here, after any worktree reassignment
+ // above, so the task log names the directory the agent actually runs in
+ // rather than the repo it was cut from (#3180).
+ emitLog('info', `📂 Agent workspace: ${workspacePath}`, { taskId: task.id, workspace: workspacePath });
+
return {
outcome: 'ready',
workspacePath,
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index b5e641f756..b0011df56b 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -37,6 +37,7 @@ vi.mock('./agentPromptBuilder.js', () => ({
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
import { ensureLatest } from './git.js';
import { detectConflicts } from './taskConflict.js';
+import { getAppWorkspace } from './agentPromptBuilder.js';
beforeEach(() => { vi.clearAllMocks(); });
@@ -69,3 +70,33 @@ describe('prepareAgentWorkspace', () => {
expect(detectConflicts).toHaveBeenCalled();
});
});
+
+describe('prepareAgentWorkspace — workspace validation (#3180)', () => {
+ // Both shapes used to fall through to the PortOS root, so the agent did its
+ // work in the PortOS checkout instead of the user's app. A blocked task the
+ // user can fix beats a wrong-repo commit they have to discover later.
+ it('blocks when the task names an app that resolves to no repo path', async () => {
+ getAppWorkspace.mockResolvedValue(null);
+ const task = { id: 't-no-path', taskType: 'user', metadata: { app: 'primes' } };
+ const r = await prepareAgentWorkspace({ agentId: 'agent-np', task });
+ expect(r.outcome).toBe('blocked');
+ expect(r.reason).toContain('primes');
+ expect(r.reason).toContain('Repository Path');
+ });
+
+ it('blocks when the resolved workspace does not exist on disk', async () => {
+ getAppWorkspace.mockResolvedValue('/definitely/not/a/real/repo/path');
+ const task = { id: 't-missing', taskType: 'user', metadata: { app: 'primes' } };
+ const r = await prepareAgentWorkspace({ agentId: 'agent-ms', task });
+ expect(r.outcome).toBe('blocked');
+ expect(r.reason).toContain('/definitely/not/a/real/repo/path');
+ });
+
+ it('proceeds when the app resolves to a real directory', async () => {
+ getAppWorkspace.mockResolvedValue(process.cwd());
+ const task = { id: 't-ok', taskType: 'user', metadata: { app: 'primes', readOnly: true } };
+ const r = await prepareAgentWorkspace({ agentId: 'agent-ok', task });
+ expect(r.outcome).toBe('ready');
+ expect(r.workspacePath).toBe(process.cwd());
+ });
+});
diff --git a/server/services/runner.js b/server/services/runner.js
index 7851d4535b..535e64efbe 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -127,6 +127,34 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erro
return metadata;
}
+/**
+ * Resolve a run's spawn cwd, turning an unusable workspace into a normal failed
+ * run rather than a throw.
+ *
+ * Shared by both spawning runners (`executeCliRun` here, `executeTuiRun` in
+ * `lib/tuiPromptRunner.js`) because the /runs route invokes them WITHOUT
+ * awaiting: a bare throw would surface only as an unhandled rejection and the
+ * UI would show the run hanging forever. Returning the failure instead keeps
+ * the "report it through the run record" contract in one place, so a third
+ * runner can't reintroduce the hang by forgetting the try/catch.
+ *
+ * @returns {Promise<{cwd: string, failure?: undefined} | {cwd?: undefined, failure: object}>}
+ * `cwd` on success; `failure` (the finalized metadata) when the workspace is unusable.
+ */
+export async function resolveRunCwd({ runId, workspacePath, label, startTime = Date.now(), onData, onComplete }) {
+ try {
+ return { cwd: resolveSpawnCwd(workspacePath, PATHS.root, label) };
+ } catch (err) {
+ const message = `❌ ${err.message}`;
+ onData?.(message);
+ const failure = await finalizeRunRecord({
+ runId, output: message, exitCode: null, success: false, error: err.message, startTime,
+ });
+ onComplete?.(failure);
+ return { failure };
+ }
+}
+
/**
* Fire the `onRunStarted` lifecycle hook — used by execution paths that
* don't go through the toolkit's executeCliRun/executeApiRun (which fire
@@ -200,25 +228,15 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
killProcessTree(childProcess);
};
- // Resolve (and log) the working directory before spawning. A supplied-but-
+ // Resolve (and log) the working directory before spawning, so 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;
- }
+ // the prompt would land in the wrong repo (#3180). Placed ahead of
+ // prepareCliPrompt so a bad workspace short-circuits before any temp-file I/O.
+ const { cwd: effectiveCwd, failure } = await resolveRunCwd({
+ runId, workspacePath, label: `Run ${runId}`, startTime, onData, onComplete,
+ });
+ if (failure) return;
// Build provider-specific args for prompt delivery
const builtArgs = buildCliArgs(provider);
@@ -313,7 +331,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
// 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;
+ metadata.workspacePath ??= effectiveCwd;
try {
if (timeoutHandle) clearTimeout(timeoutHandle);
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index a264ea8ad8..e8a717e98f 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -26,20 +26,25 @@ vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {
};
});
-vi.mock('../lib/fileUtils.js', () => ({
- 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) => {
- const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
- const { writeFile } = await import('fs/promises');
- return writeFile(filePath, payload);
- }),
-}));
+// Spread the real module and override only the three I/O entry points. A
+// hand-listed mock silently drops everything else — the cwd resolution reaches
+// for PATHS and expandHome, and an absent expandHome failed every run rather
+// than only the bad-workspace one (#3180).
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ tryReadFile: vi.fn().mockResolvedValue(null),
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ // 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) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ }),
+ };
+});
vi.mock('fs/promises', () => ({
writeFile: vi.fn().mockResolvedValue(undefined),
@@ -72,6 +77,10 @@ function fakeToolkit(errorDetection = null) {
};
}
+// Let executeCliRun run to its spawn(): it awaits ensureDir and the cwd
+// resolution first, so a single microtask tick is not enough.
+const flushMicrotasks = () => new Promise((resolve) => setImmediate(resolve));
+
function makeChild() {
const child = new EventEmitter();
child.stdout = new EventEmitter();
@@ -158,7 +167,7 @@ describe('executeCliRun — Codex sentinel suppression', () => {
executeCliRun({ runId: 'run-extra-usage', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: resolve, timeout: 60000 });
});
- await Promise.resolve();
+ await flushMicrotasks();
child.stderr.emit('data', Buffer.from('Now using extra '));
expect(child.kill).not.toHaveBeenCalled();
child.stderr.emit('data', Buffer.from('usage\n'));
@@ -190,7 +199,7 @@ describe('executeCliRun — Codex sentinel suppression', () => {
executeCliRun({ runId: 'run-fallback-exit0', provider, prompt: 'test prompt', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: resolve, timeout: 60000 });
});
- await Promise.resolve();
+ await flushMicrotasks();
child.stderr.emit('data', Buffer.from('Now using extra usage\n'));
expect(child.kill).toHaveBeenCalledWith('SIGTERM');
@@ -739,34 +748,25 @@ describe('executeCliRun — workspace validation (#3180)', () => {
// 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.
+ // Also asserts the call RESOLVES rather than rejecting: the /runs route
+ // invokes executeCliRun without awaiting it, so a bare throw would surface
+ // only as an unhandled rejection and leave the run looking stuck.
it('fails the run instead of spawning when the workspace does not exist', async () => {
const onComplete = vi.fn();
const onData = vi.fn();
- await executeCliRun({
+ await expect(executeCliRun({
runId: 'run-bad-workspace',
provider,
prompt: 'test prompt',
workspacePath: '/definitely/not/a/real/repo/path',
onData,
onComplete,
- });
+ })).resolves.toBeUndefined();
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 8ef86f70ea..9de714ccce 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -42,26 +42,32 @@ const SAFE_ENV_PREFIXES = [
// 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.
+// credentials and config). Only names NOT already covered by a prefix above are
+// listed: PATHEXT/USERPROFILE/HOMEDRIVE/HOMEPATH already match PATH/USER/HOME.
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',
+ 'SYSTEMROOT', 'SYSTEMDRIVE', 'WINDIR', 'COMSPEC',
+ 'APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES', 'PROGRAMDATA', 'PROGRAMW6432',
+ 'COMMONPROGRAMFILES', 'TEMP', 'TMP',
'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE', 'OS', 'PSMODULEPATH'
];
+// Precomputed so the merge doesn't run per session.
+const SAFE_ENV_PREFIXES_ALL = [...SAFE_ENV_PREFIXES, ...SAFE_ENV_PREFIXES_WIN32];
+
/**
* 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.
+ * On Windows, matching folds case: Windows env names are case-insensitive and
+ * arrive in mixed case, so the real variable is `Path`, not `PATH`. A
+ * case-sensitive `startsWith('PATH')` dropped the child's entire PATH there
+ * (while keeping the coincidentally-upper-case `PATHEXT`), leaving the shell
+ * unable to resolve any CLI provider.
+ *
+ * POSIX matching stays case-SENSITIVE — folding it would WIDEN the allowlist,
+ * not preserve it. PortOS starts under `npm run`, which exports dozens of
+ * lower-case `npm_config_*` / `npm_package_*` vars (including values from a
+ * user's `.npmrc`); upper-casing keys would let every one of them through the
+ * `NPM_` prefix into an attachable shell.
*
* Exported for tests; `platform` is injectable so the Windows branch is
* testable from any host.
@@ -71,13 +77,12 @@ const SAFE_ENV_PREFIXES_WIN32 = [
* @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 isWin32 = platform === 'win32';
+ const prefixes = isWin32 ? SAFE_ENV_PREFIXES_ALL : SAFE_ENV_PREFIXES;
const safeEnv = {};
for (const [key, value] of Object.entries(env)) {
- const upper = key.toUpperCase();
- if (prefixes.some(prefix => upper === prefix || upper.startsWith(prefix))) {
+ const candidate = isWin32 ? key.toUpperCase() : key;
+ if (prefixes.some(prefix => candidate.startsWith(prefix))) {
safeEnv[key] = value;
}
}
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index 0d20700096..becc05924e 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -632,3 +632,20 @@ describe('buildSafeEnv', () => {
expect(safe).not.toHaveProperty('ANTHROPIC_API_KEY');
});
});
+
+describe('buildSafeEnv — POSIX case sensitivity', () => {
+ // Folding case on POSIX would WIDEN the allowlist, not preserve it: PortOS
+ // starts under `npm run`, which exports dozens of lower-case npm_config_*
+ // vars (including values read from the user's .npmrc). Upper-casing keys
+ // would push every one of them through the 'NPM_' prefix into an attachable
+ // shell, so POSIX matching stays case-sensitive.
+ it('does not admit lower-case npm_config_* through the NPM_ prefix', () => {
+ const safe = shell.buildSafeEnv(
+ { PATH: '/usr/bin', npm_config_registry: 'https://example.com', npm_config_mysecret: 'hunter2' },
+ 'linux'
+ );
+ expect(safe).toHaveProperty('PATH');
+ expect(safe).not.toHaveProperty('npm_config_registry');
+ expect(safe).not.toHaveProperty('npm_config_mysecret');
+ });
+});