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: bypass pm2.cmd on Windows to eliminate CMD window flashes

[._.]/ Adam Eivy255a9849f11e
diff --git a/.changelog/v1.6.x.md b/.changelog/v1.6.x.md
index 1bbc2ab2e0..223677be50 100644
--- a/.changelog/v1.6.x.md
+++ b/.changelog/v1.6.x.md
@@ -25,6 +25,7 @@ Folder picker improvements for Windows: drive selector, home directory quick-nav
- 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`.
+- 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.
### FolderPicker: Error state handling
- Directory load errors now display inline with a message and "Go to default directory" recovery button instead of silently failing
diff --git a/package-lock.json b/package-lock.json
index cb673a5ec5..2e0137981b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos",
- "version": "1.6.1",
+ "version": "1.6.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos",
- "version": "1.6.1",
+ "version": "1.6.2",
"license": "MIT",
"dependencies": {
"express": "^4.21.2",
diff --git a/package.json b/package.json
index d27a2ea849..1c183ca3ac 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "portos",
- "version": "1.6.1",
+ "version": "1.6.2",
"private": true,
"description": "Local dev machine App OS portal",
"author": "Adam Eivy (@antic|@atomantic)",
diff --git a/server/routes/detect.js b/server/routes/detect.js
index a10b71cf34..d54cd8eb8c 100644
--- a/server/routes/detect.js
+++ b/server/routes/detect.js
@@ -4,6 +4,7 @@ import { readFile, stat } from 'fs/promises';
import { join } from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
+import { execPm2 } from '../services/pm2.js';
import { detectAppWithAi } from '../services/aiDetect.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { safeJSONParse } from '../lib/fileUtils.js';
@@ -166,7 +167,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', { windowsHide: true }).catch(() => ({ stdout: '[]' }));
+ const { stdout } = await execPm2(['jlist']).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.js
index e276edd55b..5ebaeb7302 100644
--- a/server/routes/logs.js
+++ b/server/routes/logs.js
@@ -1,7 +1,7 @@
import { Router } from 'express';
-import { spawn } from 'child_process';
import * as appsService from '../services/apps.js';
import * as pm2Service from '../services/pm2.js';
+import { spawnPm2 } from '../services/pm2.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
@@ -58,10 +58,7 @@ 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 characters
- const logProcess = spawn('pm2', ['logs', safeProcessName, '--raw', '--lines', String(lines)], {
- shell: process.platform === 'win32',
- windowsHide: true
- });
+ const logProcess = spawnPm2(['logs', safeProcessName, '--raw', '--lines', String(lines)]);
let buffer = '';
diff --git a/server/services/cos.js b/server/services/cos.js
index a0f01ca9e0..aaf015cb15 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -10,6 +10,7 @@ import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { exec, execFile } from 'child_process';
+import { execPm2 } from './pm2.js';
import { promisify } from 'util';
import { v4 as uuidv4 } from 'uuid';
import { getActiveProvider } from './providers.js';
@@ -1981,7 +1982,7 @@ export async function runHealthCheck() {
};
// Check PM2 processes
- const pm2Result = await execAsync('pm2 jlist', { windowsHide: true }).catch(() => ({ stdout: '[]' }));
+ const pm2Result = await execPm2(['jlist']).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 [31m
const pm2Output = pm2Result.stdout || '[]';
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 1abc69bd90..e6d79bdbd1 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -2,12 +2,20 @@ 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 { join, dirname } from 'path';
import { createRequire } from 'module';
+import { fileURLToPath } from 'url';
import { extractJSONArray, safeJSONParse } from '../lib/fileUtils.js';
const IS_WIN = process.platform === 'win32';
+// Resolve PM2 CLI binary path from our local dependency.
+// On Windows, we run `node pm2/bin/pm2` directly to avoid pm2.cmd batch file
+// which creates visible CMD windows even with windowsHide:true
+// (cmd.exe → pm2.cmd → node is a chain where the middle .cmd flashes a window).
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const PM2_BIN = join(__dirname, '..', 'node_modules', 'pm2', 'bin', 'pm2');
+
/**
* 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
@@ -17,6 +25,46 @@ function isJsScript(script) {
return /\.(?:js|mjs|cjs|ts)$/.test(script);
}
+/**
+ * Spawn PM2 CLI directly via node, bypassing pm2.cmd on Windows.
+ * On Windows, `spawn('pm2', args, {shell:true})` runs cmd.exe → pm2.cmd → node,
+ * and the intermediate pm2.cmd batch file creates a visible CMD window even with
+ * windowsHide:true. Running `node pm2/bin/pm2` directly avoids the .cmd wrapper entirely.
+ * @param {string[]} pm2Args PM2 CLI arguments (e.g. ['jlist'], ['start', 'ecosystem.config.cjs'])
+ * @param {object} opts Spawn options (cwd, env, etc.)
+ * @returns {ChildProcess}
+ */
+export function spawnPm2(pm2Args, opts = {}) {
+ if (IS_WIN) {
+ // Run node with PM2's JS binary directly — no cmd.exe, no .cmd wrapper
+ return spawn(process.execPath, [PM2_BIN, ...pm2Args], {
+ windowsHide: true,
+ ...opts
+ });
+ }
+ // On non-Windows, pm2 is a JS file with shebang, runs fine directly
+ return spawn('pm2', pm2Args, { windowsHide: true, ...opts });
+}
+
+/**
+ * Execute a PM2 CLI command and return stdout/stderr as a promise.
+ * Drop-in replacement for execAsync('pm2 ...') that bypasses pm2.cmd on Windows.
+ * @param {string[]} pm2Args PM2 CLI arguments (e.g. ['jlist'])
+ * @param {object} opts Spawn options (env, cwd, etc.)
+ * @returns {Promise<{stdout: string, stderr: string}>}
+ */
+export function execPm2(pm2Args, opts = {}) {
+ return new Promise((resolve) => {
+ const child = spawnPm2(pm2Args, opts);
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (data) => { stdout += data.toString(); });
+ child.stderr.on('data', (data) => { stderr += data.toString(); });
+ child.on('close', () => resolve({ stdout, stderr }));
+ child.on('error', () => resolve({ stdout, stderr }));
+ });
+}
+
/**
* Build environment object with optional custom PM2_HOME
* @param {string} pm2Home Optional custom PM2_HOME path
@@ -42,10 +90,8 @@ function buildEnv(pm2Home) {
*/
function spawnPm2Cli(action, name, pm2Home) {
return new Promise((resolve, reject) => {
- const child = spawn('pm2', [action, name], {
- shell: IS_WIN,
- env: buildEnv(pm2Home),
- windowsHide: true
+ const child = spawnPm2([action, name], {
+ env: buildEnv(pm2Home)
});
let stderr = '';
child.stderr.on('data', (data) => { stderr += data.toString(); });
@@ -186,10 +232,8 @@ export async function deleteApp(name, pm2Home = null) {
*/
export async function getAppStatus(name, pm2Home = null) {
return new Promise((resolve) => {
- const child = spawn('pm2', ['jlist'], {
- shell: IS_WIN,
- env: buildEnv(pm2Home),
- windowsHide: true
+ const child = spawnPm2(['jlist'], {
+ env: buildEnv(pm2Home)
});
let stdout = '';
@@ -234,10 +278,8 @@ export async function getAppStatus(name, pm2Home = null) {
*/
export async function listProcesses(pm2Home = null) {
return new Promise((resolve) => {
- const child = spawn('pm2', ['jlist'], {
- shell: IS_WIN,
- env: buildEnv(pm2Home),
- windowsHide: true
+ const child = spawnPm2(['jlist'], {
+ env: buildEnv(pm2Home)
});
let stdout = '';
@@ -275,10 +317,8 @@ export async function listProcesses(pm2Home = null) {
export async function getLogs(name, lines = 100, pm2Home = null) {
return new Promise((resolve, reject) => {
const args = ['logs', name, '--lines', String(lines), '--nostream', '--raw'];
- const child = spawn('pm2', args, {
- shell: IS_WIN,
- env: buildEnv(pm2Home),
- windowsHide: true
+ const child = spawnPm2(args, {
+ env: buildEnv(pm2Home)
});
let stdout = '';
@@ -355,11 +395,9 @@ function spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home) {
args.push('--only', processNames.join(','));
}
- const child = spawn('pm2', args, {
+ const child = spawnPm2(args, {
cwd,
- shell: IS_WIN,
- env: buildEnv(pm2Home),
- windowsHide: true
+ env: buildEnv(pm2Home)
});
let stdout = '';
let stderr = '';
diff --git a/server/services/socket.js b/server/services/socket.js
index 4673d12318..78dc16fb8f 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,4 +1,4 @@
-import { spawn } from 'child_process';
+import { spawnPm2 } from './pm2.js';
import { streamDetection } from './streamingDetect.js';
import { cosEvents } from './cosEvents.js';
import { appsEvents } from './apps.js';
@@ -139,10 +139,7 @@ export function initSocket(io) {
console.log(`📜 Log stream started: ${processName} (${lines} lines)`);
// Spawn pm2 logs with --raw flag
- const logProcess = spawn('pm2', ['logs', processName, '--raw', '--lines', String(lines)], {
- shell: process.platform === 'win32',
- windowsHide: true
- });
+ const logProcess = spawnPm2(['logs', processName, '--raw', '--lines', String(lines)]);
activeStreams.set(socket.id, { process: logProcess, processName });
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index 4b8763ed3e..8e2752fa3d 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -2,12 +2,9 @@ import { readFile, readdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join, basename } from 'path';
import { homedir } from 'os';
-import { exec } from 'child_process';
-import { promisify } from 'util';
+import { execPm2 } from './pm2.js';
import { safeJSONParse } from '../lib/fileUtils.js';
-const execAsync = promisify(exec);
-
/**
* Parse ecosystem.config.js/cjs to extract all processes with their ports
* Uses regex parsing since we can't safely execute arbitrary JS
@@ -509,9 +506,8 @@ export async function streamDetection(socket, dirPath) {
// Step 5: Check PM2 status
emit('pm2', 'running', { message: 'Checking PM2 processes...' });
// Use custom PM2_HOME if detected from ecosystem config
- const pm2Env = result.pm2Home ? { ...process.env, PM2_HOME: result.pm2Home } : process.env;
- const pm2Cmd = 'pm2 jlist';
- const { stdout } = await execAsync(pm2Cmd, { env: pm2Env, windowsHide: true }).catch(() => ({ stdout: '[]' }));
+ const pm2Env = result.pm2Home ? { ...process.env, PM2_HOME: result.pm2Home } : undefined;
+ const { stdout } = await execPm2(['jlist'], pm2Env ? { env: pm2Env } : {}).catch(() => ({ stdout: '[]' }));
// pm2 jlist may output ANSI codes and warnings before JSON
let jsonStart = stdout.indexOf('[{');
if (jsonStart < 0) {