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: Windows PM2 CMD window floods and fork mode crash on managed app start
[._.]/ Adam Eivyd18d3fad2e79
diff --git a/.changelog/v1.6.x.md b/.changelog/v1.6.x.mdindex adc2928ec9..1bbc2ab2e0 100644--- a/.changelog/v1.6.x.md+++ b/.changelog/v1.6.x.md@@ -19,6 +19,13 @@ Folder picker improvements for Windows: drive selector, home directory quick-nav## Fixes+### Windows CMD window flash and infinite restart loop+- Added `windowsHide: true` to **every** `spawn()`, `exec()`, `execSync()`, and `execAsync()` call across the entire server — previous fix only covered `pm2.js` and a few services, missing ~20 other spawn sites in routes, cos-runner, agents, scaffold, git cloner, brain, digital-twin, aiDetect, pm2Standardizer, taskConflict, platform, and detect+- Added `windowsHide: IS_WIN` to all 6 app definitions in `ecosystem.config.cjs` so PM2 daemon spawns PortOS processes without visible CMD windows+- Added `windowsHide: IS_WIN` to PM2 programmatic API calls (`pm2.start()` in `startApp` and `startWithCommand`) — these were the primary path for starting managed apps like sdlive+- Added `max_restarts: 10`, `min_uptime: '10s'`, and `restart_delay: 5000` to `startApp` and `startWithCommand` — previously had `autorestart: true` with no restart cap, causing infinite CMD window spawn loops when a managed app crashed on startup+- Fixed PM2 fork mode crash on Windows: when ecosystem configs use `script: 'npm'` (common pattern), PM2 resolves it to `npm.cmd` and tries to `require()` a batch file as JavaScript, causing `SyntaxError: Invalid or unexpected token` + infinite restart loop. On Windows, `startFromEcosystem` now loads the config, patches non-JS scripts with `interpreter: 'none'` (spawn mode), writes a temp config, and starts PM2 with it. Same fix applied to `startWithCommand` and `startApp`.+### FolderPicker: Error state handling- Directory load errors now display inline with a message and "Go to default directory" recovery button instead of silently failing- Select button is disabled when no path is loadeddiff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 0f84c6e2fc..3a74583da5 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -3,6 +3,7 @@// =============================================================================const path = require('path');const LOG_DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSS[Z]';+const IS_WIN = process.platform === 'win32';// Shared env inherited by all apps (merged into each app's env)const BASE_ENV = {@@ -30,6 +31,7 @@ module.exports = {cwd: __dirname,interpreter: 'node',log_date_format: LOG_DATE_FORMAT,+ windowsHide: IS_WIN,env: {...BASE_ENV,PORT: PORTS.API,@@ -44,6 +46,7 @@ module.exports = {cwd: __dirname,interpreter: 'node',log_date_format: LOG_DATE_FORMAT,+ windowsHide: IS_WIN,// CoS Agent Runner - isolated process for spawning Claude CLI agents// Does NOT restart when portos-server restarts, preventing orphaned agents// Security: Binds to localhost only - not exposed externally@@ -67,6 +70,7 @@ module.exports = {script: path.join(__dirname, 'client', 'node_modules', 'vite', 'bin', 'vite.js'),cwd: path.join(__dirname, 'client'),log_date_format: LOG_DATE_FORMAT,+ windowsHide: IS_WIN,args: `--host 0.0.0.0 --port ${PORTS.UI}`,env: {...BASE_ENV,@@ -80,6 +84,7 @@ module.exports = {cwd: __dirname,interpreter: 'node',log_date_format: LOG_DATE_FORMAT,+ windowsHide: IS_WIN,env: {...BASE_ENV,PORT: PORTS.AUTOFIXER,@@ -97,6 +102,7 @@ module.exports = {cwd: __dirname,interpreter: 'node',log_date_format: LOG_DATE_FORMAT,+ windowsHide: IS_WIN,env: {...BASE_ENV,PORT: PORTS.AUTOFIXER_UI@@ -113,6 +119,7 @@ module.exports = {cwd: __dirname,interpreter: 'node',log_date_format: LOG_DATE_FORMAT,+ windowsHide: IS_WIN,// Security: CDP binds to 127.0.0.1 by default (set CDP_HOST=0.0.0.0 to expose)// Remote access should go through portos-server proxy with authenticationenv: {diff --git a/package-lock.json b/package-lock.jsonindex 00aa5e97c6..cb673a5ec5 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "1.6.0",+ "version": "1.6.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "1.6.0",+ "version": "1.6.1","license": "MIT","dependencies": {"express": "^4.21.2",diff --git a/package.json b/package.jsonindex 441aee5a35..d27a2ea849 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.6.0",+ "version": "1.6.1","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/server/lib/platform.js b/server/lib/platform.jsindex b22d83e32e..73687e9d47 100644--- a/server/lib/platform.js+++ b/server/lib/platform.js@@ -14,7 +14,7 @@ export async function getListeningPorts() {if (platform === 'darwin') {// macOS: use lsof- const { stdout } = await execAsync('lsof -iTCP -sTCP:LISTEN -n -P').catch(() => ({ stdout: '' }));+ const { stdout } = await execAsync('lsof -iTCP -sTCP:LISTEN -n -P', { windowsHide: true }).catch(() => ({ stdout: '' }));const lines = stdout.split('\n').slice(1); // Skip headerfor (const line of lines) {const match = line.match(/:(\d+)\s+\(LISTEN\)/);@@ -24,7 +24,7 @@ export async function getListeningPorts() {}} else if (platform === 'linux') {// Linux: use ss- const { stdout } = await execAsync('ss -lntp').catch(() => ({ stdout: '' }));+ const { stdout } = await execAsync('ss -lntp', { windowsHide: true }).catch(() => ({ stdout: '' }));const lines = stdout.split('\n').slice(1); // Skip headerfor (const line of lines) {const match = line.match(/:(\d+)\s/);@@ -34,7 +34,7 @@ export async function getListeningPorts() {}} else {// Windows: use netstat- const { stdout } = await execAsync('netstat -an').catch(() => ({ stdout: '' }));+ const { stdout } = await execAsync('netstat -an', { windowsHide: true }).catch(() => ({ stdout: '' }));const lines = stdout.split('\n');for (const line of lines) {if (line.includes('LISTENING')) {diff --git a/server/routes/apps.js b/server/routes/apps.jsindex b84b6d96a9..5e0f30890a 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -361,7 +361,8 @@ router.post('/:id/open-editor', loadApp, asyncHandler(async (req, res) => {cwd: app.repoPath,detached: true,stdio: 'ignore',- shell: false // Security: Ensure no shell interpretation+ shell: false, // Security: Ensure no shell interpretation+ windowsHide: true});child.unref();@@ -393,7 +394,8 @@ router.post('/:id/open-folder', loadApp, asyncHandler(async (req, res) => {const child = spawn(cmd, args, {detached: true,- stdio: 'ignore'+ stdio: 'ignore',+ windowsHide: true});child.unref();diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 24b5fef7e3..da9392a7d0 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -666,7 +666,7 @@ router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {args = [link.localPath];}- spawn(cmd, args, { detached: true, stdio: 'ignore' }).unref();+ spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();console.log(`📂 Opened folder: ${link.localPath}`);res.json({ message: 'Folder opened', path: link.localPath });diff --git a/server/routes/detect.js b/server/routes/detect.jsindex 6213fbaae0..a10b71cf34 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -137,7 +137,7 @@ router.post('/port', asyncHandler(async (req, res) => {? `lsof -i :${port} -P -n | grep LISTEN`: `ss -lntp | grep :${port}`;- const { stdout } = await execAsync(command).catch(() => ({ stdout: '' }));+ const { stdout } = await execAsync(command, { windowsHide: true }).catch(() => ({ stdout: '' }));if (stdout.trim()) {result.inUse = true;@@ -166,7 +166,7 @@ router.post('/pm2', asyncHandler(async (req, res) => {throw new ServerError('Process name is required', { status: 400, code: 'MISSING_NAME' });}- const { stdout } = await execAsync('pm2 jlist').catch(() => ({ stdout: '[]' }));+ const { stdout } = await execAsync('pm2 jlist', { windowsHide: true }).catch(() => ({ stdout: '[]' }));const processes = safeJSONParse(stdout, []);const found = processes.find(p => p.name === name);diff --git a/server/routes/logs.js b/server/routes/logs.jsindex 0ca7976059..e276edd55b 100644--- a/server/routes/logs.js+++ b/server/routes/logs.js@@ -59,7 +59,8 @@ router.get('/:processName', asyncHandler(async (req, res) => {// Spawn pm2 logs with --raw flag for clean output// Security: safeProcessName is validated above to only contain safe charactersconst logProcess = spawn('pm2', ['logs', safeProcessName, '--raw', '--lines', String(lines)], {- shell: process.platform === 'win32'+ shell: process.platform === 'win32',+ windowsHide: true});let buffer = '';diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex 676c4cac54..270cfabaac 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -250,7 +250,8 @@ async function scaffoldApp(req, res) {const { stderr } = await new Promise((resolve) => {const child = spawn('npm', ['create', 'vite@latest', dirName, '--', '--template', 'react'], {cwd: parentDir,- shell: process.platform === 'win32'+ shell: process.platform === 'win32',+ windowsHide: true});let stderr = '';child.stderr.on('data', (data) => { stderr += data.toString(); });@@ -1147,7 +1148,7 @@ module.exports = {// Run npm installconst 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, windowsHide: true }).catch(err => ({ stderr: err.message }));if (installErr && !installErr.includes('npm warn')) {@@ -1157,7 +1158,7 @@ module.exports = {}// Initialize git- await execAsync('git init', { cwd: repoPath });+ await execAsync('git init', { cwd: repoPath, windowsHide: true });// Create .gitignore - more comprehensive for portos-stackconst gitignoreContent = template === 'portos-stack'@@ -1194,8 +1195,8 @@ Thumbs.db: 'node_modules\n.env\ndist\n';await writeFile(join(repoPath, '.gitignore'), gitignoreContent);- await execAsync('git add -A', { cwd: repoPath });- await execAsync('git commit -m "Initial commit"', { cwd: repoPath });+ await execAsync('git add -A', { cwd: repoPath, windowsHide: true });+ await execAsync('git commit -m "Initial commit"', { cwd: repoPath, windowsHide: true });addStep('Initialize git', 'done');// Create GitHub repo if requested@@ -1205,7 +1206,7 @@ Thumbs.dbconst ghArgs = ['repo', 'create', repoName, '--source=.', '--push', '--private'];const { stderr: ghErr } = await new Promise((resolve) => {- const child = spawn('gh', ghArgs, { cwd: repoPath, shell: false });+ const child = spawn('gh', ghArgs, { cwd: repoPath, shell: false, windowsHide: true });let stderr = '';child.stderr.on('data', (data) => { stderr += data.toString(); });child.on('close', () => resolve({ stderr }));diff --git a/server/services/agents.js b/server/services/agents.jsindex ed83b6d7c1..93b2172ffa 100644--- a/server/services/agents.js+++ b/server/services/agents.js@@ -122,7 +122,7 @@ async function findUnixProcesses(pattern) {// Security: Pattern is validated above to only contain safe charactersconst cmd = `ps -ww -eo pid,ppid,%cpu,%mem,etime,command | grep -i "${safePattern}" | grep -v grep`;- const result = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024 }).catch(() => ({ stdout: '' }));+ const result = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024, windowsHide: true }).catch(() => ({ stdout: '' }));const lines = result.stdout.trim().split('\n').filter(Boolean);const processes = [];@@ -173,7 +173,7 @@ async function findWindowsProcesses(pattern) {// Security: Pattern is validated above to only contain safe charactersconst cmd = `wmic process where "name like '%${safePattern}%'" get ProcessId,ParentProcessId,PercentProcessorTime,WorkingSetSize,CreationDate,CommandLine /format:csv`;- const result = await execAsync(cmd).catch(() => ({ stdout: '' }));+ const result = await execAsync(cmd, { windowsHide: true }).catch(() => ({ stdout: '' }));const lines = result.stdout.trim().split('\n').filter(Boolean);const processes = [];@@ -290,9 +290,9 @@ export async function killProcess(pid) {const platform = process.platform;if (platform === 'win32') {- await execAsync(`taskkill /PID ${safePid} /F`);+ await execAsync(`taskkill /PID ${safePid} /F`, { windowsHide: true });} else {- await execAsync(`kill -9 ${safePid}`);+ await execAsync(`kill -9 ${safePid}`, { windowsHide: true });}console.log(`🔪 Killed process ${safePid}`);@@ -313,7 +313,7 @@ export async function getProcessInfo(pid) {if (platform === 'darwin' || platform === 'linux') {const cmd = `ps -ww -p ${safePid} -o pid,ppid,%cpu,%mem,etime,command`;- const result = await execAsync(cmd).catch(() => null);+ const result = await execAsync(cmd, { windowsHide: true }).catch(() => null);if (!result) return null;const lines = result.stdout.trim().split('\n');diff --git a/server/services/aiDetect.js b/server/services/aiDetect.jsindex a41a043830..3a8300f0a0 100644--- a/server/services/aiDetect.js+++ b/server/services/aiDetect.js@@ -124,7 +124,8 @@ async function executeCliDetection(provider, prompt, cwd) {const child = spawn(provider.command, args, {cwd,env: process.env,- shell: false+ shell: false,+ windowsHide: true});child.stdout.on('data', (data) => {diff --git a/server/services/brain.js b/server/services/brain.jsindex c5cd3e65f8..b56cd2c2e1 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -56,7 +56,8 @@ async function callAI(promptStageName, variables, providerOverride, modelOverridconst child = spawn(provider.command, args, {env: { ...process.env, ...provider.envVars },- shell: false+ shell: false,+ windowsHide: true});child.stdout.on('data', (data) => {diff --git a/server/services/cos.js b/server/services/cos.jsindex 26f6693fc8..a0f01ca9e0 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1981,7 +1981,7 @@ export async function runHealthCheck() {};// Check PM2 processes- const pm2Result = await execAsync('pm2 jlist').catch(() => ({ stdout: '[]' }));+ const pm2Result = await execAsync('pm2 jlist', { windowsHide: true }).catch(() => ({ stdout: '[]' }));// pm2 jlist may output ANSI codes and warnings before JSON, extract the JSON array// Look for '[{' (array with objects) or '[]' (empty array) to avoid matching ANSI codes like [31mconst pm2Output = pm2Result.stdout || '[]';@@ -2063,7 +2063,7 @@ export async function runHealthCheck() {// Get system memoryconst memCmd = process.platform === 'win32' ? 'wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /VALUE' :process.platform === 'darwin' ? 'vm_stat' : 'free -m';- const memResult = await execAsync(memCmd).catch(() => ({ stdout: '' }));+ const memResult = await execAsync(memCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));metrics.memory = { raw: memResult.stdout.slice(0, 500) }; // Truncate for storage// Store health check result with lock to prevent race conditionsdiff --git a/server/services/digital-twin.js b/server/services/digital-twin.jsindex 72e1d708ce..3a7596710e 100644--- a/server/services/digital-twin.js+++ b/server/services/digital-twin.js@@ -328,7 +328,8 @@ async function callProviderAI(provider, model, prompt, { temperature = 0.3, max_const child = spawn(provider.command, args, {env: { ...process.env, ...provider.envVars },shell: false,- stdio: ['pipe', 'pipe', 'pipe']+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true});// Pipe prompt via stdindiff --git a/server/services/githubCloner.js b/server/services/githubCloner.jsindex 396d2ffee1..828a41d168 100644--- a/server/services/githubCloner.js+++ b/server/services/githubCloner.js@@ -126,7 +126,8 @@ export async function cloneRepo(url, options = {}) {return new Promise((resolve, reject) => {const child = spawn('git', args, {env: process.env,- shell: false+ shell: false,+ windowsHide: true});let stderr = '';@@ -177,7 +178,8 @@ export async function pullRepo(localPath) {const child = spawn('git', ['pull', '--ff-only'], {cwd: localPath,env: process.env,- shell: false+ shell: false,+ windowsHide: true});let stdout = '';@@ -223,7 +225,8 @@ export async function getRepoInfo(localPath) {const child = spawn('git', ['log', '-1', '--format=%H|%s|%ci'], {cwd: localPath,env: process.env,- shell: false+ shell: false,+ windowsHide: true});let stdout = '';diff --git a/server/services/pm2.js b/server/services/pm2.jsindex f060f4a876..1abc69bd90 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -1,10 +1,22 @@import pm2 from 'pm2';import { spawn } from 'child_process';import { existsSync } from 'fs';+import { readFile, writeFile, unlink } from 'fs/promises';+import { join } from 'path';+import { createRequire } from 'module';import { extractJSONArray, safeJSONParse } from '../lib/fileUtils.js';const IS_WIN = process.platform === 'win32';+/**+ * Check if a script path is a JS file that PM2 can fork directly.+ * On Windows, non-JS scripts (npm, npx, vite, etc.) resolve to .cmd batch files+ * which PM2's fork mode tries to require() as JavaScript — causing SyntaxError.+ */+function isJsScript(script) {+ return /\.(?:js|mjs|cjs|ts)$/.test(script);+}+/*** Build environment object with optional custom PM2_HOME* @param {string} pm2Home Optional custom PM2_HOME path@@ -76,16 +88,26 @@ function connectAndRun(action) {export async function startApp(name, options = {}) {return connectAndRun((pm2) => {return new Promise((resolve, reject) => {+ const script = options.script || 'npm';const startOptions = {name,- script: options.script || 'npm',+ script,args: options.args || 'run dev',cwd: options.cwd,env: options.env || {},watch: false,- autorestart: true+ autorestart: true,+ max_restarts: 10,+ min_uptime: '10s',+ restart_delay: 5000,+ windowsHide: IS_WIN};+ // On Windows, non-JS scripts (.cmd batch files) can't be fork'd by PM2+ if (IS_WIN && !isJsScript(script)) {+ startOptions.interpreter = 'none';+ }+pm2.start(startOptions, (err, proc) => {if (err) return reject(err);resolve({ success: true, process: proc });@@ -292,15 +314,26 @@ export async function startWithCommand(name, cwd, command) {return connectAndRun((pm2) => {return new Promise((resolve, reject) => {- pm2.start({+ const opts = {name,script,args: args.join(' '),cwd,watch: false,autorestart: true,- max_memory_restart: '500M'- }, (err, proc) => {+ max_restarts: 10,+ min_uptime: '10s',+ restart_delay: 5000,+ max_memory_restart: '500M',+ windowsHide: IS_WIN+ };++ // On Windows, non-JS scripts (.cmd batch files) can't be fork'd by PM2+ if (IS_WIN && !isJsScript(script)) {+ opts.interpreter = 'none';+ }++ pm2.start(opts, (err, proc) => {if (err) return reject(err);resolve({ success: true, process: proc });});@@ -309,21 +342,14 @@ export async function startWithCommand(name, cwd, command) {}/**- * Start app(s) using ecosystem.config.cjs/js file- * This properly uses all env vars, scripts, args defined in the config- * @param {string} cwd Working directory containing ecosystem config- * @param {string[]} processNames Optional: specific processes to start (--only flag)- * @param {string} pm2Home Optional custom PM2_HOME path+ * Spawn pm2 start with an ecosystem config file+ * @param {string} cwd Working directory+ * @param {string} ecosystemFile Config filename+ * @param {string[]} processNames Processes to start (--only flag)+ * @param {string} pm2Home Optional custom PM2_HOME*/-export async function startFromEcosystem(cwd, processNames = [], pm2Home = null) {+function spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home) {return new Promise((resolve, reject) => {- const ecosystemFile = ['ecosystem.config.cjs', 'ecosystem.config.js']- .find(f => existsSync(`${cwd}/${f}`));-- if (!ecosystemFile) {- return reject(new Error('No ecosystem.config.cjs or ecosystem.config.js found'));- }-const args = ['start', ecosystemFile];if (processNames.length > 0) {args.push('--only', processNames.join(','));@@ -356,3 +382,91 @@ export async function startFromEcosystem(cwd, processNames = [], pm2Home = null)child.on('error', reject);});}++/**+ * Start app(s) using ecosystem.config.cjs/js file+ * This properly uses all env vars, scripts, args defined in the config+ * @param {string} cwd Working directory containing ecosystem config+ * @param {string[]} processNames Optional: specific processes to start (--only flag)+ * @param {string} pm2Home Optional custom PM2_HOME path+ */+export async function startFromEcosystem(cwd, processNames = [], pm2Home = null) {+ const ecosystemFile = ['ecosystem.config.cjs', 'ecosystem.config.js']+ .find(f => existsSync(`${cwd}/${f}`));++ if (!ecosystemFile) {+ throw new Error('No ecosystem.config.cjs or ecosystem.config.js found');+ }++ // On Windows, PM2 fork mode can't execute .cmd batch files (npm, npx, etc.)+ // Load the config, patch non-JS scripts with interpreter:'none', write temp config+ if (IS_WIN) {+ return startFromEcosystemWindows(cwd, ecosystemFile, processNames, pm2Home);+ }++ return spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home);+}++/**+ * Windows-specific ecosystem start: loads config, patches non-JS scripts+ * with interpreter:'none' so PM2 spawns them instead of forking (which would+ * try to require() .cmd batch files as JavaScript).+ */+async function startFromEcosystemWindows(cwd, ecosystemFile, processNames, pm2Home) {+ const configPath = join(cwd, ecosystemFile);++ // Try to load and patch the config+ let config;+ try {+ const require = createRequire(configPath);+ // Clear module cache to get fresh config on repeated starts+ try { delete require.cache[require.resolve(configPath)]; } catch {}+ config = require(configPath);+ } catch (err) {+ // If we can't load the config (syntax error, missing deps, etc.),+ // fall back to unpatched start — PM2 may still handle it+ console.log(`⚠️ Could not load ${ecosystemFile} for Windows patching: ${err.message}`);+ return spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home);+ }++ const apps = config.apps || [];+ let needsPatch = false;++ for (const app of apps) {+ // Skip apps not in our target list+ if (processNames.length > 0 && !processNames.includes(app.name)) continue;++ // Patch non-JS scripts to use interpreter:'none' (spawn instead of fork)+ if (app.script && !isJsScript(app.script) && app.interpreter !== 'none') {+ app.interpreter = 'none';+ needsPatch = true;+ }++ // Ensure windowsHide and restart safety on all apps+ app.windowsHide = true;+ if (app.autorestart !== false && !app.max_restarts) {+ app.max_restarts = 10;+ }+ }++ if (!needsPatch) {+ // All scripts are .js files, no patching needed+ return spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home);+ }++ // Write patched config to a temp file+ // JSON.stringify works because require() already resolved all __dirname,+ // path.join(), process.env references to concrete values+ const tempFile = `_portos_pm2_${Date.now()}.config.cjs`;+ const tempPath = join(cwd, tempFile);++ try {+ const content = `module.exports = ${JSON.stringify({ apps }, null, 2)};\n`;+ await writeFile(tempPath, content);+ console.log(`🔧 Patched ${ecosystemFile} for Windows → ${tempFile}`);+ return await spawnPm2StartEcosystem(cwd, tempFile, processNames, pm2Home);+ } finally {+ // Clean up temp file (don't await, fire-and-forget)+ unlink(tempPath).catch(() => {});+ }+}diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex c52a3b79fd..377f5b2f0c 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -181,7 +181,8 @@ async function executeCliAnalysis(provider, prompt, cwd) {const child = spawn(provider.command, args, {cwd,env: process.env,- shell: false+ shell: false,+ windowsHide: true});child.stdout.on('data', (data) => {@@ -319,21 +320,21 @@ export async function createGitBackup(repoPath) {const branch = `portos-backup-${timestamp}`;// Check for uncommitted changes- const { stdout: status } = await execAsync('git status --porcelain', { cwd: repoPath });+ const { stdout: status } = await execAsync('git status --porcelain', { cwd: repoPath, windowsHide: true });const hasChanges = status.trim().length > 0;if (hasChanges) {// Stash changes- await execAsync('git stash push -m "PortOS standardization backup"', { cwd: repoPath })+ await execAsync('git stash push -m "PortOS standardization backup"', { cwd: repoPath, windowsHide: true }).catch(() => null); // Ignore if nothing to stash}// Create backup branch- await execAsync(`git branch ${branch}`, { cwd: repoPath });+ await execAsync(`git branch ${branch}`, { cwd: repoPath, windowsHide: true });if (hasChanges) {// Pop stash- await execAsync('git stash pop', { cwd: repoPath }).catch(() => null);+ await execAsync('git stash pop', { cwd: repoPath, windowsHide: true }).catch(() => null);}return { success: true, branch, hadChanges: hasChanges };diff --git a/server/services/socket.js b/server/services/socket.jsindex 4419c213ad..4673d12318 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -140,7 +140,8 @@ export function initSocket(io) {// Spawn pm2 logs with --raw flagconst logProcess = spawn('pm2', ['logs', processName, '--raw', '--lines', String(lines)], {- shell: process.platform === 'win32'+ shell: process.platform === 'win32',+ windowsHide: true});activeStreams.set(socket.id, { process: logProcess, processName });diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.jsindex 8481fc2558..4b8763ed3e 100644--- a/server/services/streamingDetect.js+++ b/server/services/streamingDetect.js@@ -511,7 +511,7 @@ export async function streamDetection(socket, dirPath) {// Use custom PM2_HOME if detected from ecosystem configconst pm2Env = result.pm2Home ? { ...process.env, PM2_HOME: result.pm2Home } : process.env;const pm2Cmd = 'pm2 jlist';- const { stdout } = await execAsync(pm2Cmd, { env: pm2Env }).catch(() => ({ stdout: '[]' }));+ const { stdout } = await execAsync(pm2Cmd, { env: pm2Env, windowsHide: true }).catch(() => ({ stdout: '[]' }));// pm2 jlist may output ANSI codes and warnings before JSONlet jsonStart = stdout.indexOf('[{');if (jsonStart < 0) {diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 130537ba66..4124c8772c 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -313,7 +313,7 @@ function checkForTaskCommit(taskId, workspacePath = ROOT_DIR) {try {const searchPattern = `[task-${taskId}]`;const result = execSync(`git log --all --oneline --grep="${searchPattern}" -1`, {- cwd: workspacePath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe']+ cwd: workspacePath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true}).trim();return result.length > 0;} catch {@@ -1389,7 +1389,7 @@ export async function spawnAgentForTask(task) {if (defaultBranch) {await git.checkout(workspacePath, defaultBranch).catch(() => {});// Fast-forward to latest origin- try { execSync(`git merge --ff-only origin/${defaultBranch}`, { cwd: workspacePath, stdio: 'ignore' }); } catch (err) { emitLog('warn', `Fast-forward merge of ${defaultBranch} failed: ${err.message}`, { taskId: task.id }); }+ try { execSync(`git merge --ff-only origin/${defaultBranch}`, { cwd: workspacePath, stdio: 'ignore', windowsHide: true }); } catch (err) { emitLog('warn', `Fast-forward merge of ${defaultBranch} failed: ${err.message}`, { taskId: task.id }); }}}@@ -1882,6 +1882,7 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providcwd,shell: false,stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,env: {...process.env,...provider.envVars@@ -2890,7 +2891,7 @@ export async function getAgentProcessStats(agentId) {const psCmd = process.platform === 'win32'? `tasklist /FI "PID eq ${agent.pid}" /FO CSV /NH`: `ps -p ${agent.pid} -o pid=,pcpu=,rss=,state=`;- const result = await execAsync(psCmd).catch(() => ({ stdout: '' }));+ const result = await execAsync(psCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));const line = result.stdout.trim();if (!line) {diff --git a/server/services/taskConflict.js b/server/services/taskConflict.jsindex b0a08bab33..603fc251d2 100644--- a/server/services/taskConflict.js+++ b/server/services/taskConflict.js@@ -15,7 +15,7 @@ import { join } from 'path';*/function execGit(args, cwd) {return new Promise((resolve, reject) => {- const child = spawn('git', args, { cwd, shell: false });+ const child = spawn('git', args, { cwd, shell: false, windowsHide: true });let stdout = '';let stderr = '';child.stdout.on('data', d => { stdout += d.toString(); });