Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: roll back partial app directory when scaffolding fails and bound scaffold subprocesses (#9650)
Adam Eivy0068a1b14676
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex b32c616cfe..7622a4ddb9 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -1,5 +1,5 @@import { Router } from 'express';-import { writeFile, readdir, stat } from 'fs/promises';+import { writeFile, readdir, stat, rm } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { join, dirname, resolve, sep } from 'path';import { fileURLToPath } from 'url';@@ -18,6 +18,9 @@ import { toTargetName } from '../services/xcodeScripts.js';import { scaffoldPortOS } from './scaffoldPortOS.js';const execAsync = promisify(exec);++// Bound dependency installs so a stalled registry can't strand the request.+const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -279,10 +282,38 @@ async function scaffoldApp(req, res) {steps.push({ name, status, error, timestamp: Date.now() });};- // Create directory+ // Create directory. Everything from here until the app is registered runs+ // under a rollback guard: a failed attempt must not leave a partial directory+ // behind, or a retry with the same name is blocked by DIR_EXISTS.await ensureDir(repoPath);addStep('Create directory', 'done');+ let app;+ try {+ app = await buildAndRegisterApp({ name, template, dirName, parentDir, repoPath, uiPort, apiPort, createGitHubRepo, githubOrg, addStep });+ } catch (err) {+ await rm(repoPath, { recursive: true, force: true })+ .catch(rmErr => console.error(`❌ Failed to clean up partial scaffold ${repoPath}: ${rmErr.message}`));+ console.error(`❌ Scaffold of ${dirName} failed, removed partial directory: ${err.message}`);+ throw err;+ }++ notifyAppsChanged('create', app.id);+ addStep('Register in PortOS', 'done');++ res.json({+ success: true,+ app,+ repoPath,+ steps+ });+}++// Generate template files, install, git-init, and register the app. Returns the+// registered app; throws before registration on any failure so the caller can+// roll back the directory.+async function buildAndRegisterApp({ name, template, dirName, parentDir, repoPath, uiPort, apiPort, createGitHubRepo, githubOrg, addStep }) {+// Generate project files based on templateif (template === 'vite-react' || template === 'vite-express') {await scaffoldVite({ repoPath, dirName, parentDir, template, uiPort, apiPort, addStep });@@ -439,7 +470,7 @@ module.exports = {// Run npm install (skip for Xcode projects — no npm)if (template !== 'ios-native' && template !== 'xcode-multiplatform') {const installCmd = template === 'portos-stack' ? 'npm run install:all' : 'npm install';- const { stderr: installErr } = await execAsync(installCmd, { cwd: repoPath })+ const { stderr: installErr } = await execAsync(installCmd, { cwd: repoPath, timeout: INSTALL_TIMEOUT_MS }).catch(err => ({ stderr: err.message }));if (installErr && !installErr.includes('npm warn')) {@@ -586,16 +617,7 @@ Thumbs.dbenvFile: '.env'});- notifyAppsChanged('create', app.id);-- addStep('Register in PortOS', 'done');-- res.json({- success: true,- app,- repoPath,- steps- });+ return app;}// POST /api/scaffold - Create a new app from templatediff --git a/server/routes/scaffold.test.js b/server/routes/scaffold.test.jsindex a1e05f19f2..7a1ad08fd8 100644--- a/server/routes/scaffold.test.js+++ b/server/routes/scaffold.test.js@@ -20,6 +20,7 @@ vi.mock('../lib/fileUtils.js', () => ({vi.mock('fs/promises', () => ({writeFile: vi.fn().mockResolvedValue(undefined),readdir: vi.fn().mockResolvedValue([]),+ rm: vi.fn().mockResolvedValue(undefined),stat: vi.fn().mockResolvedValue({ isDirectory: () => true })}));@@ -59,7 +60,7 @@ vi.mock('../services/xcodeScripts.js', () => ({ toTargetName: vi.fn(() => 'TestAimport scaffoldRoutes from './scaffold.js';import { ensureDir } from '../lib/fileUtils.js';-import { writeFile, readdir } from 'fs/promises';+import { writeFile, readdir, rm } from 'fs/promises';import { spawn, exec } from '../lib/childProcess.js';import { createApp } from '../services/apps.js';import { scaffoldVite } from './scaffoldVite.js';@@ -159,6 +160,42 @@ describe('POST /api/scaffold — request validation before filesystem mutation (expect(createApp).toHaveBeenCalledTimes(1);});+ // Regression (#9650): a failed scaffold left the directory behind, so a retry+ // with the same name was permanently blocked by DIR_EXISTS.+ it('removes the partial directory on failure so a retry with the same name succeeds', async () => {+ const repoPath = join('/tmp/workspace', 'my-app');+ const onDisk = new Set(['/tmp/workspace']);+ existsSync.mockImplementation((p) => onDisk.has(p));+ ensureDir.mockImplementation(async (p) => { onDisk.add(p); });+ rm.mockImplementation(async (p) => { onDisk.delete(p); });+ scaffoldVite.mockRejectedValueOnce(new Error('npm create failed'));++ const failed = await request(app)+ .post('/api/scaffold')+ .send({ ...validBody, template: 'vite-react', uiPort: 3100 });++ expect(failed.status).toBe(500);+ expect(rm).toHaveBeenCalledWith(repoPath, { recursive: true, force: true });+ expect(createApp).not.toHaveBeenCalled();+ expect(onDisk.has(repoPath)).toBe(false);++ const retry = await request(app)+ .post('/api/scaffold')+ .send({ ...validBody, template: 'vite-react', uiPort: 3100 });++ expect(retry.status).toBe(200);+ expect(createApp).toHaveBeenCalledTimes(1);++ existsSync.mockImplementation((p) => p === '/tmp/workspace');+ ensureDir.mockResolvedValue(undefined);+ });++ it('does not remove the directory when registration already succeeded', async () => {+ const res = await request(app).post('/api/scaffold').send(validBody);+ expect(res.status).toBe(200);+ expect(rm).not.toHaveBeenCalled();+ });+// The scaffolders take a single options object (#2841) — a positional call// would silently pass `dirName` as `repoPath` and scaffold into the wrong tree.it('dispatches to scaffoldVite with a named-options object', async () => {diff --git a/server/routes/scaffoldVite.js b/server/routes/scaffoldVite.jsindex bfcde1c673..7d1204bcc1 100644--- a/server/routes/scaffoldVite.js+++ b/server/routes/scaffoldVite.js@@ -4,27 +4,37 @@ import { join } from 'path';import { spawn } from '../lib/childProcess.js';import { atomicWrite, ensureDir } from '../lib/fileUtils.js';import { safeJSONParse } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';import { CORS_SNIPPET } from '../lib/scaffoldSnippets.js';+const CREATE_VITE_TIMEOUT_MS = 5 * 60 * 1000;+export async function scaffoldVite({ repoPath, dirName, parentDir, template, uiPort, apiPort, addStep }) {// Create using npm create vite// Security: Use spawn with array args instead of execAsync to prevent shell injection- const { stderr } = await new Promise((resolve) => {- const child = spawn('npm', ['create', 'vite@latest', dirName, '--', '--template', 'react'], {+ // Non-interactive (--yes, stdin closed) and bounded so an npx prompt or a+ // stalled registry can't hang the request; failure aborts before we touch+ // files that were never created.+ const { code, stderr } = await new Promise((resolve) => {+ const child = spawn('npm', ['create', '--yes', 'vite@latest', dirName, '--', '--template', 'react'], {cwd: parentDir,- shell: process.platform === 'win32'+ shell: process.platform === 'win32',+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: CREATE_VITE_TIMEOUT_MS,+ killSignal: 'SIGKILL'});let stderr = '';child.stderr.on('data', (data) => { stderr += data.toString(); });- child.on('close', () => resolve({ stderr }));- child.on('error', (err) => resolve({ stderr: err.message }));+ child.on('close', (code, signal) => resolve({ code: code ?? (signal ? 1 : 0), stderr }));+ child.on('error', (err) => resolve({ code: 1, stderr: err.message }));});- if (stderr && !stderr.includes('npm warn')) {- addStep('Create Vite project', 'error', stderr);- } else {- addStep('Create Vite project', 'done');+ if (code !== 0) {+ const detail = stderr.trim().split('\n').slice(-3).join(' ') || `exit code ${code}`;+ addStep('Create Vite project', 'error', stderr || detail);+ throw new ServerError(`Failed to create Vite project: ${detail}`, { status: 500, code: 'SCAFFOLD_FAILED' });}+ addStep('Create Vite project', 'done');// Update vite.config.js with portif (uiPort) {diff --git a/server/routes/scaffoldVite.test.js b/server/routes/scaffoldVite.test.jsnew file mode 100644index 0000000000..33c0243522--- /dev/null+++ b/server/routes/scaffoldVite.test.js@@ -0,0 +1,62 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { EventEmitter } from 'events';++vi.mock('../lib/childProcess.js', () => ({ spawn: vi.fn() }));+vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue(undefined),+ readFile: vi.fn()+}));+vi.mock('fs', () => ({ existsSync: vi.fn(() => false) }));+vi.mock('../lib/fileUtils.js', () => ({+ atomicWrite: vi.fn(),+ ensureDir: vi.fn(),+ safeJSONParse: vi.fn()+}));++import { scaffoldVite } from './scaffoldVite.js';+import { spawn } from '../lib/childProcess.js';+import { readFile } from 'fs/promises';++function fakeChild({ code = 0, stderr = '', error } = {}) {+ const proc = new EventEmitter();+ proc.stderr = new EventEmitter();+ setImmediate(() => {+ if (stderr) proc.stderr.emit('data', Buffer.from(stderr));+ if (error) proc.emit('error', error);+ else proc.emit('close', code, null);+ });+ return proc;+}++const opts = (addStep) => ({+ repoPath: '/w/app', dirName: 'app', parentDir: '/w', template: 'vite-express',+ uiPort: 3100, apiPort: 3101, addStep+});++describe('scaffoldVite failure handling (#9650)', () => {+ beforeEach(() => vi.clearAllMocks());++ it('runs npm create non-interactively with a timeout', async () => {+ spawn.mockReturnValueOnce(fakeChild({ code: 1, stderr: 'boom' }));+ await scaffoldVite(opts(vi.fn())).catch(() => {});+ const [cmd, args, o] = spawn.mock.calls[0];+ expect(cmd).toBe('npm');+ expect(args).toContain('--yes');+ expect(o.stdio[0]).toBe('ignore');+ expect(o.timeout).toBeGreaterThan(0);+ });++ it('aborts on a non-zero exit instead of reading the missing package.json', async () => {+ const addStep = vi.fn();+ spawn.mockReturnValueOnce(fakeChild({ code: 1, stderr: 'npm error ENOTFOUND' }));+ await expect(scaffoldVite(opts(addStep))).rejects.toMatchObject({ code: 'SCAFFOLD_FAILED' });+ expect(addStep).toHaveBeenCalledWith('Create Vite project', 'error', expect.stringContaining('ENOTFOUND'));+ expect(readFile).not.toHaveBeenCalled();+ });++ it('aborts when the spawn itself errors', async () => {+ spawn.mockReturnValueOnce(fakeChild({ error: new Error('spawn npm ENOENT') }));+ await expect(scaffoldVite(opts(vi.fn()))).rejects.toMatchObject({ code: 'SCAFFOLD_FAILED' });+ expect(readFile).not.toHaveBeenCalled();+ });+});