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: bypass pm2.cmd in autofixer and dev-start to eliminate remaining CMD windows
[._.]/ Adam Eivy0c9077df5ddb
diff --git a/.changelog/v1.6.x.md b/.changelog/v1.6.x.mdindex 451aebaac3..68e2fc1427 100644--- a/.changelog/v1.6.x.md+++ b/.changelog/v1.6.x.md@@ -27,6 +27,8 @@ Folder picker improvements for Windows: drive selector, home directory quick-nav- 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`.- Eliminated remaining CMD window flashes by bypassing `pm2.cmd` entirely: all PM2 CLI invocations (`jlist`, `logs`, `start`, `stop`, `restart`, `delete`) now run `node pm2/bin/pm2` directly instead of `spawn('pm2', {shell:true})` which created a `cmd.exe → pm2.cmd → node` chain where the intermediate `.cmd` batch file flashed a visible window. New `spawnPm2()` and `execPm2()` helpers in `pm2.js` are shared by logs, socket, detect, streamingDetect, and cos services.- Updated all `pm2:*` npm scripts in package.json to use `node ./node_modules/pm2/bin/pm2` instead of bare `pm2` command, avoiding `pm2.cmd` batch file wrapper on Windows+- Fixed `autofixer/server.js` and `autofixer/ui.js` still using bare `pm2` commands via `exec()` and `spawn('pm2', {shell:true})` — these were the last remaining CMD window sources, now bypassed with local `node pm2/bin/pm2` pattern+- Rewrote `scripts/dev-start.js` to use `execFileSync` instead of `execSync` (avoids cmd.exe) with local PM2 binary resolution### PM2 binary resolution fails when pm2 not globally installed- `spawnPm2()` on macOS/Linux fell back to `spawn('pm2', ...)` which requires a global pm2 install — now always uses `node pm2/bin/pm2` via the local binary on all platformsdiff --git a/autofixer/server.js b/autofixer/server.jsindex 8d4c9c574b..f0ddd9d972 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -2,14 +2,31 @@ import { spawn } from 'child_process';import { readFile, writeFile, mkdir, access } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { promisify } from 'util';-import { execFile as execFileCb } from 'child_process';+import { createRequire } from 'module';-const IS_WIN = process.platform === 'win32';-const execFileAsync = (cmd, args, opts = {}) => promisify(execFileCb)(cmd, args, { shell: IS_WIN, windowsHide: true, ...opts });const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Resolve PM2 binary to avoid pm2.cmd on Windows (creates visible CMD windows)+const require = createRequire(import.meta.url);+const PM2_BIN = join(dirname(require.resolve('pm2/package.json')), 'bin', 'pm2');++/** Execute a PM2 CLI command via node (bypasses pm2.cmd) */+function execPm2(pm2Args) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], { windowsHide: true });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (d) => { stdout += d.toString(); });+ child.stderr.on('data', (d) => { stderr += d.toString(); });+ child.on('close', (code) => {+ if (code !== 0 && stderr) return reject(new Error(stderr));+ resolve({ stdout, stderr });+ });+ child.on('error', reject);+ });+}+// Pathsconst DATA_DIR = join(__dirname, '../data');const APPS_FILE = join(DATA_DIR, 'apps.json');@@ -99,7 +116,7 @@ async function saveSession(sessionId, prompt, output, metadata) {// Get PM2 process listasync function getProcessList() {- const { stdout } = await execFileAsync('pm2', ['jlist']);+ const { stdout } = await execPm2(['jlist']);const stripped = stdout.replace(/\x1b\[[0-9;]*m/g, '');const jsonStart = stripped.indexOf('[{');const jsonEnd = stripped.lastIndexOf('}]');@@ -114,8 +131,8 @@ async function getProcessList() {// Get error logs for a processasync function getProcessLogs(processName) {- const { stdout: errLogs } = await execFileAsync('pm2', ['logs', processName, '--lines', '100', '--nostream', '--err']).catch(() => ({ stdout: '' }));- const { stdout: outLogs } = await execFileAsync('pm2', ['logs', processName, '--lines', '50', '--nostream', '--out']).catch(() => ({ stdout: '' }));+ const { stdout: errLogs } = await execPm2(['logs', processName, '--lines', '100', '--nostream', '--err']).catch(() => ({ stdout: '' }));+ const { stdout: outLogs } = await execPm2(['logs', processName, '--lines', '50', '--nostream', '--out']).catch(() => ({ stdout: '' }));return { errLogs, outLogs };}diff --git a/autofixer/ui.js b/autofixer/ui.jsindex 107ea3f39e..43eef6c367 100644--- a/autofixer/ui.js+++ b/autofixer/ui.js@@ -1,14 +1,33 @@import express from 'express';-import { spawn, exec as execCb } from 'child_process';+import { spawn } from 'child_process';import { readFile } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { promisify } from 'util';+import { createRequire } from 'module';-const exec = (cmd, opts) => promisify(execCb)(cmd, { windowsHide: true, ...opts });const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Resolve PM2 binary to avoid pm2.cmd on Windows (creates visible CMD windows)+const require = createRequire(import.meta.url);+const PM2_BIN = join(dirname(require.resolve('pm2/package.json')), 'bin', 'pm2');++/** Execute a PM2 CLI command via node (bypasses pm2.cmd) */+function execPm2(pm2Args) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], { windowsHide: true });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (d) => { stdout += d.toString(); });+ child.stderr.on('data', (d) => { stderr += d.toString(); });+ child.on('close', (code) => {+ if (code !== 0 && stderr) return reject(new Error(stderr));+ resolve({ stdout, stderr });+ });+ child.on('error', reject);+ });+}+const app = express();const PORT = process.env.PORT || 5560;@@ -45,7 +64,7 @@ app.get('/api/history', async (req, res) => {// API: Get PM2 statusapp.get('/api/status', async (req, res) => {- const { stdout } = await exec('pm2 jlist').catch(() => ({ stdout: '[]' }));+ const { stdout } = await execPm2(['jlist']).catch(() => ({ stdout: '[]' }));const stripped = stdout.replace(/\x1b\[[0-9;]*m/g, '');const jsonStart = stripped.indexOf('[');const jsonEnd = stripped.lastIndexOf(']');@@ -79,7 +98,7 @@ app.post('/api/restart/:process', async (req, res) => {return res.status(400).json({ success: false, error: 'Unknown process' });}console.log(`🔄 [Autofixer UI] Restarting process: ${processName}`);- const { stdout, stderr } = await exec(`pm2 restart ${processName}`).catch(err => ({+ const { stdout, stderr } = await execPm2(['restart', processName]).catch(err => ({stdout: '',stderr: err.message}));@@ -98,7 +117,7 @@ app.post('/api/stop/:process', async (req, res) => {return res.status(400).json({ success: false, error: 'Unknown process' });}console.log(`⏹️ [Autofixer UI] Stopping process: ${processName}`);- const { stdout, stderr } = await exec(`pm2 stop ${processName}`).catch(err => ({+ const { stdout, stderr } = await execPm2(['stop', processName]).catch(err => ({stdout: '',stderr: err.message}));@@ -865,14 +884,15 @@ app.get('/logs', async (req, res) => {req.on('close', cleanup);res.on('close', cleanup);- // Get initial logs- const initialLogsCmd = `pm2 logs ${processName} --lines 50 --nostream --raw`;-- execCb(initialLogsCmd, { windowsHide: true }, (error, stdout) => {+ // Get initial logs via node pm2/bin/pm2 (bypasses pm2.cmd on Windows)+ const initialChild = spawn(process.execPath, [PM2_BIN, 'logs', processName, '--lines', '50', '--nostream', '--raw'], { windowsHide: true });+ let initialStdout = '';+ initialChild.stdout.on('data', (d) => { initialStdout += d.toString(); });+ initialChild.on('close', () => {if (res.writableEnded) return;- if (!error && stdout) {- const lines = stdout.split('\n').filter(line => line.trim());+ if (initialStdout) {+ const lines = initialStdout.split('\n').filter(line => line.trim());lines.forEach(line => {const event = {type: 'log',@@ -884,8 +904,8 @@ app.get('/logs', async (req, res) => {});}- // Stream new logs- pm2Process = spawn('pm2', ['logs', processName, '--lines', '0', '--raw'], { shell: process.platform === 'win32', windowsHide: true });+ // Stream new logs via node pm2/bin/pm2 (bypasses pm2.cmd on Windows)+ pm2Process = spawn(process.execPath, [PM2_BIN, 'logs', processName, '--lines', '0', '--raw'], { windowsHide: true });pm2Process.stdout.on('data', (data) => {if (res.writableEnded) {diff --git a/package-lock.json b/package-lock.jsonindex 0ede278d37..aac0961d53 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "1.6.4",+ "version": "1.6.5","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "1.6.4",+ "version": "1.6.5","license": "MIT","dependencies": {"express": "^4.21.2",diff --git a/package.json b/package.jsonindex 1290fa894c..0b82461659 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.6.4",+ "version": "1.6.5","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/scripts/dev-start.js b/scripts/dev-start.jsindex 4b925248ee..8ff26d9b65 100644--- a/scripts/dev-start.js+++ b/scripts/dev-start.js@@ -1,26 +1,36 @@/*** Dev start script — cleanly (re)starts all PM2 processes.* Handles lingering processes, port conflicts, and fresh starts.+ *+ * Uses execFileSync (not execSync with string) to avoid cmd.exe on Windows,+ * which creates visible CMD windows even with windowsHide.*/-import { execSync, spawn } from 'child_process';+import { execFileSync, spawn } from 'child_process';import { dirname, join } from 'path';import { fileURLToPath } from 'url';+import { createRequire } from 'module';-const __dirname = dirname(fileURLToPath(import.meta.url));-const PM2 = join(__dirname, '..', 'node_modules', 'pm2', 'bin', 'pm2');+const require = createRequire(import.meta.url);+const PM2 = join(dirname(require.resolve('pm2/package.json')), 'bin', 'pm2');const ECO = 'ecosystem.config.cjs';-function pm2(args) {- execSync(`node "${PM2}" ${args}`, { stdio: 'inherit' });+function pm2(...args) {+ execFileSync(process.execPath, [PM2, ...args], {+ stdio: 'inherit',+ windowsHide: true+ });}// Stop and delete existing PortOS processes (ignore errors if none exist)-try { pm2(`stop ${ECO}`); } catch {}-try { pm2(`delete ${ECO}`); } catch {}+try { pm2('stop', ECO); } catch {}+try { pm2('delete', ECO); } catch {}// Brief pause for port releaseawait new Promise(r => setTimeout(r, 1500));// Start fresh and tail logs-pm2(`start ${ECO}`);-spawn(process.execPath, [PM2, 'logs'], { stdio: 'inherit' });+pm2('start', ECO);+spawn(process.execPath, [PM2, 'logs'], {+ stdio: 'inherit',+ windowsHide: true+});