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-11743]): bound scaffold commands and report CLI failures (#11783)

[._.]/2ec548273f39
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index 6cd2395e45..788824a363 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -295,7 +295,6 @@ describe('every cwd-passing spawn pins PWD', () => {
['services/dbAdmin.js', 'psql/pg_dump, not an AI CLI'],
['routes/scaffold.js', 'npm/git scaffolding, not an AI CLI'],
['routes/scaffoldVite.js', 'npm scaffolding, not an AI CLI'],
- ['services/xcodeScaffold.js', 'xcodegen, not an AI CLI'],
['routes/apps/launch.js', "detached launch into the user's own terminal; the CLI reads process.cwd()"],
]);
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.js
index 810bea466c..40da0a81df 100644
--- a/server/routes/scaffold.js
+++ b/server/routes/scaffold.js
@@ -3,7 +3,8 @@ import { writeFile, readdir, stat, rm } from 'fs/promises';
import { existsSync, realpathSync } from 'fs';
import { join, dirname, resolve, sep } from 'path';
import { fileURLToPath } from 'url';
-import { exec, spawn } from '../lib/childProcess.js';
+import { exec } from '../lib/childProcess.js';
+import { runCliBounded } from '../lib/runCliBounded.js';
import { promisify } from 'util';
import { platform } from 'os';
import { createApp, getReservedPorts, notifyAppsChanged } from '../services/apps.js';
@@ -474,7 +475,18 @@ module.exports = {
}
// Initialize git
- await execAsync('git init', { cwd: repoPath });
+ const runGit = async (args) => {
+ const result = await runCliBounded('git', args, {
+ cwd: repoPath,
+ timeoutMs: 30_000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
+ });
+ if (result.code !== 0) {
+ throw new Error(`git ${args[0]} failed: ${result.stderr.trim() || result.stdout.trim() || `exited with code ${result.code}`}`);
+ }
+ };
+ await runGit(['init']);
// Create .gitignore
let gitignoreContent;
@@ -535,16 +547,8 @@ Thumbs.db
}
await writeFile(join(repoPath, '.gitignore'), gitignoreContent);
- // Use spawn with shell:false to avoid shell injection
- const spawnGit = (args) => new Promise((resolve, reject) => {
- const proc = spawn('git', args, { cwd: repoPath, shell: false });
- let stderr = '';
- proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
- proc.on('close', (code) => code === 0 ? resolve() : reject(new Error(`git ${args[0]} failed: ${stderr.trim()}`)));
- proc.on('error', reject);
- });
- await spawnGit(['add', '-A']);
- await spawnGit(['commit', '-m', 'Initial commit']);
+ await runGit(['add', '-A']);
+ await runGit(['commit', '-m', 'Initial commit']);
addStep('Initialize git', 'done');
// Create GitHub repo if requested
@@ -553,16 +557,15 @@ Thumbs.db
const repoName = githubOrg ? `${githubOrg}/${dirName}` : dirName;
const ghArgs = ['repo', 'create', repoName, '--source=.', '--push', '--private'];
- const { stderr: ghErr } = await new Promise((resolve) => {
- const child = spawn('gh', ghArgs, { cwd: repoPath, shell: false });
- let stderr = '';
- child.stderr.on('data', (data) => { stderr += data.toString(); });
- child.on('close', () => resolve({ stderr }));
- child.on('error', (err) => resolve({ stderr: err.message }));
+ const result = await runCliBounded('gh', ghArgs, {
+ cwd: repoPath,
+ timeoutMs: 60_000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, GH_PROMPT_DISABLED: '1', GIT_TERMINAL_PROMPT: '0' },
});
- if (ghErr && !ghErr.includes('Created repository')) {
- addStep('Create GitHub repo', 'error', ghErr);
+ if (result.code !== 0) {
+ addStep('Create GitHub repo', 'error', result.stderr.trim() || result.stdout.trim() || `gh repo create exited with code ${result.code}`);
} else {
addStep('Create GitHub repo', 'done');
}
diff --git a/server/routes/scaffold.test.js b/server/routes/scaffold.test.js
index 7a1ad08fd8..08c4a841fa 100644
--- a/server/routes/scaffold.test.js
+++ b/server/routes/scaffold.test.js
@@ -2,7 +2,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { join, resolve } from 'path';
import { existsSync } from 'fs';
import express from 'express';
-import { EventEmitter } from 'events';
import { request } from '../lib/testHelper.js';
// --- Mock the filesystem + subprocess boundary so we can assert ZERO
@@ -32,13 +31,6 @@ vi.mock('fs', () => ({
vi.mock('../lib/childProcess.js', () => ({
exec: vi.fn((cmd, opts, cb) => cb(null, { stdout: '', stderr: '' })),
- spawn: vi.fn(() => {
- const proc = new EventEmitter();
- proc.stderr = new EventEmitter();
- // Resolve the spawn promise on the next tick with a success exit code.
- setImmediate(() => proc.emit('close', 0));
- return proc;
- })
}));
vi.mock('../services/apps.js', () => ({
@@ -58,10 +50,15 @@ vi.mock('../services/xcodeScaffold.js', () => ({ scaffoldXcode: vi.fn().mockReso
vi.mock('./scaffoldPortOS.js', () => ({ scaffoldPortOS: vi.fn().mockResolvedValue(undefined) }));
vi.mock('../services/xcodeScripts.js', () => ({ toTargetName: vi.fn(() => 'TestApp') }));
+vi.mock('../lib/runCliBounded.js', () => ({
+ runCliBounded: vi.fn().mockResolvedValue({ code: 0, stdout: '', stderr: '' }),
+}));
+
import scaffoldRoutes from './scaffold.js';
import { ensureDir } from '../lib/fileUtils.js';
import { writeFile, readdir, rm } from 'fs/promises';
-import { spawn, exec } from '../lib/childProcess.js';
+import { exec } from '../lib/childProcess.js';
+import { runCliBounded } from '../lib/runCliBounded.js';
import { createApp } from '../services/apps.js';
import { scaffoldVite } from './scaffoldVite.js';
import { scaffoldPortOS } from './scaffoldPortOS.js';
@@ -78,7 +75,7 @@ function makeApp() {
function expectZeroMutations() {
expect(ensureDir).not.toHaveBeenCalled();
expect(writeFile).not.toHaveBeenCalled();
- expect(spawn).not.toHaveBeenCalled();
+ expect(runCliBounded).not.toHaveBeenCalled();
expect(exec).not.toHaveBeenCalled();
expect(createApp).not.toHaveBeenCalled();
}
@@ -160,6 +157,60 @@ describe('POST /api/scaffold — request validation before filesystem mutation (
expect(createApp).toHaveBeenCalledTimes(1);
});
+ it('bounds every git stage without prompting or disabling hooks and signing', async () => {
+ const res = await request(app).post('/api/scaffold').send(validBody);
+ expect(res.status).toBe(200);
+ expect(runCliBounded.mock.calls.map(([cmd, args]) => [cmd, args])).toEqual([
+ ['git', ['init']], ['git', ['add', '-A']], ['git', ['commit', '-m', 'Initial commit']],
+ ]);
+ for (const [, , options] of runCliBounded.mock.calls) {
+ expect(options).toMatchObject({
+ cwd: join('/tmp/workspace', 'my-app'), timeoutMs: 30_000,
+ stdio: ['ignore', 'pipe', 'pipe'], env: { GIT_TERMINAL_PROMPT: '0' },
+ });
+ }
+ });
+
+ it.each([0, 2])('rolls back instead of registering an app when git stage %i times out', async (stage) => {
+ for (let i = 0; i < stage; i++) runCliBounded.mockResolvedValueOnce({ code: 0, stdout: '', stderr: '' });
+ runCliBounded.mockResolvedValueOnce({ code: -1, stdout: '', stderr: 'timed out' });
+ const res = await request(app).post('/api/scaffold').send(validBody);
+ expect(res.status).toBe(500);
+ expect(rm).toHaveBeenCalledWith(join('/tmp/workspace', 'my-app'), { recursive: true, force: true });
+ expect(createApp).not.toHaveBeenCalled();
+ });
+
+ it('accepts successful GitHub creation even when the CLI prints progress on stderr', async () => {
+ runCliBounded.mockImplementation(async (command) => ({
+ code: 0, stdout: '', stderr: command === 'gh' ? 'Pushing to remote' : '',
+ }));
+ const res = await request(app).post('/api/scaffold').send({ ...validBody, createGitHubRepo: true });
+ expect(res.status).toBe(200);
+ expect(res.body.steps).toContainEqual(expect.objectContaining({ name: 'Create GitHub repo', status: 'done' }));
+ runCliBounded.mockResolvedValue({ code: 0, stdout: '', stderr: '' });
+ });
+
+ it.each([
+ [{ code: 1, stdout: 'Remote creation failed', stderr: '' }, 'Remote creation failed'],
+ [{ code: 2, stdout: '', stderr: '' }, 'gh repo create exited with code 2'],
+ [{ code: -1, stdout: '', stderr: 'timed out' }, 'timed out'],
+ [{ code: 1, stdout: '', stderr: 'Created repository but push failed' }, 'Created repository but push failed'],
+ ])('reports failed GitHub creation while preserving the registered local app (%j)', async (failure, detail) => {
+ runCliBounded.mockResolvedValueOnce({ code: 0, stdout: '', stderr: '' })
+ .mockResolvedValueOnce({ code: 0, stdout: '', stderr: '' })
+ .mockResolvedValueOnce({ code: 0, stdout: '', stderr: '' })
+ .mockResolvedValueOnce(failure);
+ const res = await request(app).post('/api/scaffold').send({ ...validBody, createGitHubRepo: true });
+ expect(res.status).toBe(200);
+ expect(res.body.steps).toContainEqual(expect.objectContaining({ name: 'Create GitHub repo', status: 'error', error: detail }));
+ expect(createApp).toHaveBeenCalledTimes(1);
+ expect(rm).not.toHaveBeenCalled();
+ expect(runCliBounded).toHaveBeenLastCalledWith('gh',
+ ['repo', 'create', 'my-app', '--source=.', '--push', '--private'],
+ expect.objectContaining({ timeoutMs: 60_000, stdio: ['ignore', 'pipe', 'pipe'],
+ env: expect.objectContaining({ GH_PROMPT_DISABLED: '1', GIT_TERMINAL_PROMPT: '0' }) }));
+ });
+
// 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 () => {
diff --git a/server/services/xcodeScaffold.js b/server/services/xcodeScaffold.js
index 5981f38d9e..a88fc90dd9 100644
--- a/server/services/xcodeScaffold.js
+++ b/server/services/xcodeScaffold.js
@@ -1,7 +1,6 @@
import { writeFile, chmod } from 'fs/promises';
import { join } from 'path';
-import { exec } from '../lib/childProcess.js';
-import { promisify } from 'util';
+import { runCliBounded } from '../lib/runCliBounded.js';
import { ensureDir, ensureDirs } from '../lib/fileUtils.js';
import { writeAgentInstructions } from '../lib/agentInstructionsFile.js';
import {
@@ -10,8 +9,6 @@ import {
generateDeployScript, generateScreenshotScript, generateMacScreenshotScript
} from './xcodeScripts.js';
-const execAsync = promisify(exec);
-
/** Every platform this scaffolder knows how to emit, in `project.yml` order. */
const XCODE_PLATFORMS = ['ios', 'macos', 'watchos'];
@@ -561,11 +558,12 @@ final class ScreenshotTests: XCTestCase {
addStep(multi ? 'Create multi-platform Xcode project' : 'Create iOS project', 'done');
// Run xcodegen if available
- const { stderr: xgenErr } = await execAsync('xcodegen generate', { cwd: repoPath })
- .catch(err => ({ stderr: err.message }));
+ const result = await runCliBounded('xcodegen', ['generate'], {
+ cwd: repoPath, timeoutMs: 60_000, stdio: ['ignore', 'pipe', 'pipe'],
+ });
- if (xgenErr && !xgenErr.includes('Created project')) {
- addStep('Generate Xcode project', 'error', xgenErr);
+ if (result.code !== 0) {
+ addStep('Generate Xcode project', 'error', result.stderr.trim() || result.stdout.trim() || `xcodegen exited with code ${result.code}`);
} else {
addStep('Generate Xcode project', 'done');
}
diff --git a/server/services/xcodeScaffold.test.js b/server/services/xcodeScaffold.test.js
index ef0fe81bea..1f63e793b6 100644
--- a/server/services/xcodeScaffold.test.js
+++ b/server/services/xcodeScaffold.test.js
@@ -3,13 +3,11 @@ import { mkdtemp, rm, readdir, readFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join, relative, sep } from 'path';
-// xcodegen is an external binary that may or may not exist on the machine
-// running the suite — stub the spawn so the scaffolder's file emission is what
-// is under test, not the generator's availability.
-vi.mock('../lib/childProcess.js', async importOriginal => ({
- ...await importOriginal(),
- exec: vi.fn((cmd, opts, cb) => cb(null, { stdout: 'Created project', stderr: '' }))
+// Keep project generation at its external-process boundary.
+vi.mock('../lib/runCliBounded.js', () => ({
+ runCliBounded: vi.fn().mockResolvedValue({ code: 0, stdout: 'Created project', stderr: '' }),
}));
+import { runCliBounded } from '../lib/runCliBounded.js';
import { scaffoldXcode } from './xcodeScaffold.js';
@@ -36,6 +34,16 @@ describe('scaffoldXcode', () => {
await rm(repoPath, { recursive: true, force: true });
});
+ it('bounds xcodegen and records a timeout without losing emitted project files', async () => {
+ runCliBounded.mockResolvedValueOnce({ code: -1, stdout: '', stderr: 'timed out' });
+ await scaffoldXcode(repoPath, 'Sample App', 'sample-app', addStep, { platforms: ['ios'] });
+ expect(runCliBounded).toHaveBeenLastCalledWith('xcodegen', ['generate'], {
+ cwd: repoPath, timeoutMs: 60_000, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ expect(steps).toContainEqual(['Generate Xcode project', 'error']);
+ expect(await listFiles(repoPath)).toContain('project.yml');
+ });
+
it('emits an iOS-only project for platforms: ["ios"]', async () => {
await scaffoldXcode(repoPath, 'Sample App', 'sample-app', addStep, { platforms: ['ios'] });