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: root the Codex render scratch dir at the OS temp dir, not a PATHS key

Stephen Hilderbrand74fb894ab931
diff --git a/server/lib/paths.test.js b/server/lib/paths.test.js
new file mode 100644
index 0000000000..40bf47175a
--- /dev/null
+++ b/server/lib/paths.test.js
@@ -0,0 +1,68 @@
+import { describe, it, expect } from 'vitest';
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { fileURLToPath } from 'url';
+import { dirname, relative } from 'path';
+import { globSync } from 'tinyglobby';
+import { PATHS } from './paths.js';
+
+const SERVER_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+/** Replace comment bodies with spaces, preserving length and line breaks. */
+const blankComments = (source) => source.replace(
+ /\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,
+ (chunk) => chunk.replace(/[^\n]/g, ' '),
+);
+
+// `PATHS` is a plain object, so a reference to a key that does not exist is not
+// a syntax or type error — it is `undefined`, and the failure only surfaces when
+// the value reaches an `fs` call at runtime. That is exactly how #11770 shipped:
+// `imageGen/codex.js` read `PATHS.tmp`, a key the object has never had, and the
+// suite stayed green because the provider's own test mock ASSIGNED `PATHS.tmp`
+// before importing it. Every Codex render then died on
+// `ERR_INVALID_ARG_TYPE: The "path" argument ... Received undefined` before the
+// child ever spawned.
+//
+// A static scan is the right shape here: the property access is what is wrong,
+// so checking it needs no process, no filesystem, and no provider. Dynamic
+// accesses (`PATHS[key]`) are deliberately out of scope — they are rare and
+// cannot be resolved without running the code.
+describe('PATHS key references', () => {
+ const files = globSync(['**/*.js'], {
+ cwd: SERVER_ROOT,
+ ignore: ['**/node_modules/**', '**/*.test.js'],
+ absolute: true,
+ });
+
+ it('scans a meaningful portion of the server tree', () => {
+ // Guards the glob itself: a broken pattern would otherwise make the
+ // assertion below pass vacuously against an empty file list.
+ expect(files.length).toBeGreaterThan(100);
+ });
+
+ it('every PATHS.<key> read in server source exists on the real object', async () => {
+ const valid = new Set(Object.keys(PATHS));
+ const offenders = [];
+ for (const file of files) {
+ const source = await readFile(file, 'utf8');
+ if (!source.includes('PATHS.')) continue;
+ // Prose names these keys freely ("an earlier revision read PATHS.tmp",
+ // "frames under PATHS.video-thumbnails"), so a scan of raw text reports
+ // comments as defects. Blanking comments to same-length whitespace keeps
+ // the reported line numbers honest. Only ever REMOVES text, so this can
+ // hide a real reference on a line that also holds a `//` inside a string
+ // (a URL) — a miss, never a false accusation.
+ const code = blankComments(source);
+ for (const match of code.matchAll(/\bPATHS\.([A-Za-z_$][\w$]*)/g)) {
+ const key = match[1];
+ if (valid.has(key)) continue;
+ const line = code.slice(0, match.index).split('\n').length;
+ offenders.push(`${relative(SERVER_ROOT, file)}:${line} → PATHS.${key}`);
+ }
+ }
+ expect(
+ offenders,
+ `These read a PATHS key that does not exist (they evaluate to undefined at runtime):\n${offenders.join('\n')}`,
+ ).toEqual([]);
+ });
+});
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index fe4306a6d4..cf06d1cd22 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -31,6 +31,7 @@ import { bufferedSpawn, prepareCliSpawn, killProcessTree } from '../../lib/buffe
import { readFile, readdir, stat, mkdtemp } from 'fs/promises';
import { existsSync } from 'fs';
import { join, isAbsolute, resolve, sep } from 'path';
+import { tmpdir } from 'os';
import { codexHomeDir } from '../../lib/codexUserConfig.js';
import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
import { maintenance } from '../../lib/maintenanceAdmission.js';
@@ -327,8 +328,15 @@ export async function generateImage({
...sentRecord,
createdAt: new Date().toISOString(),
};
- await ensureDir(PATHS.tmp);
- const scratchDir = await mkdtemp(join(PATHS.tmp, 'codex-image-'));
+ // Per-render scratch cwd for the child (#11734). Rooted at the OS temp dir —
+ // the same pattern every other ephemeral PortOS workspace uses, including the
+ // sibling Codex text turn in `services/codexAppServer.js`. Deliberately NOT a
+ // `PATHS` entry: `PATHS` names durable, documented directories under the
+ // install root that backup and federation reason about, and this one is
+ // created per render and removed when the job settles. An earlier revision
+ // read `PATHS.tmp`, which has never existed on the object — `ensureDir`
+ // received `undefined` and every Codex render died here before spawning.
+ const scratchDir = await mkdtemp(join(tmpdir(), 'portos-codex-image-'));
const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
try {
jobs.set(jobId, job);
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
index 8df99febe2..ad41a32385 100644
--- a/server/services/imageGen/codex.test.js
+++ b/server/services/imageGen/codex.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdir, writeFile, rm, readFile } from 'fs/promises';
-import { existsSync } from 'fs';
-import { join, relative, resolve } from 'path';
+import { existsSync, realpathSync } from 'fs';
+import { join, relative, resolve, basename } from 'path';
import { tmpdir } from 'os';
import { EventEmitter } from 'events';
import sharp from 'sharp';
@@ -80,7 +80,11 @@ vi.mock('../../lib/fileUtils.js', async () => {
// a spread-only override would leave the original PATHS.images intact
// for any function closing over the actual module's binding.
actual.PATHS.images = FAKE_IMAGES_DIR;
- actual.PATHS.tmp = join(TEST_HOME, 'tmp');
+ // NOTE: do not invent PATHS keys here. An earlier revision set `PATHS.tmp`,
+ // a key the real object has never had, so the suite exercised a property
+ // that exists only under test while every production render threw
+ // ERR_INVALID_ARG_TYPE on it. The render scratch dir is rooted at the OS
+ // temp dir and needs no PATHS entry; `pathsKeysAreReal` below pins that.
return {
...actual,
ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
@@ -90,6 +94,8 @@ vi.mock('../../lib/fileUtils.js', async () => {
// imageGenEvents is fine to import for real, but we don't want stray
// listeners between tests. Reset its emitter state in beforeEach.
const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+// Read back through the mocked module so this is the same PATHS the service sees.
+const { PATHS } = await import('../../lib/fileUtils.js');
const codex = await import('./codex.js');
const { imageGenEvents } = await import('../imageGenEvents.js');
const { spawn } = await import('../../lib/childProcess.js');
@@ -1061,7 +1067,14 @@ describe('Codex cached defaults and isolated workspace', () => {
imageGenEvents.on('failed', failed);
const job = await codex.generateImage({ prompt: 'synthetic' });
const call = spawnCalls[0];
- expect(call.options.cwd.startsWith(join(TEST_HOME, 'tmp', 'codex-image-'))).toBe(true);
+ // The property #11734 actually bought: the child's cwd is a fresh per-render
+ // directory under the OS temp root, NOT the server's own cwd (the PortOS
+ // checkout), so a hand-drawing codex cannot write into the working tree.
+ expect(basename(call.options.cwd).startsWith('portos-codex-image-')).toBe(true);
+ // realpath both sides: on macOS tmpdir() is /var/... while the resolved
+ // path is /private/var/..., so a raw prefix compare is platform-fragile.
+ expect(realpathSync(call.options.cwd).startsWith(realpathSync(tmpdir()))).toBe(true);
+ expect(call.options.cwd.startsWith(PATHS.installRoot)).toBe(false);
expect(call.options.env.PWD).toBe(call.options.cwd);
expect(call.args.at(-1)).toContain('Only the image_gen tool may produce this image');
await writeFile(join(call.options.cwd, 'drawing.svg'), '<svg/>');