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

feat(pm2): support custom PM2_HOME for isolated app instances

Adam Eivya29c8f05db27
diff --git a/.changelog/v0.13.x.md b/.changelog/v0.13.x.md
index 62b07a4f7b..77a0ac7bee 100644
--- a/.changelog/v0.13.x.md
+++ b/.changelog/v0.13.x.md
@@ -108,6 +108,12 @@ This release expands the genome dashboard with comprehensive cancer predispositi
- **Service function `getUpcomingTasks()`** in taskSchedule.js calculates eligibility, formats timing, and respects learning-based interval adjustments
- Addresses user preference for "quick visual summaries" and helps understand CoS behavior
+### Custom PM2_HOME Support for Isolated App Instances
+- **Per-app PM2_HOME configuration** — apps can now specify a custom `pm2Home` path to manage processes in a separate PM2 daemon instance, useful for apps that ship with their own PM2 setup (e.g., apps with embedded PM2 ecosystems)
+- **Smart process grouping** — the apps list route now groups apps by their PM2_HOME and queries each PM2 instance separately, so process statuses are correctly fetched from the right daemon
+- **All PM2 operations support custom home** — start, stop, restart, delete, status, and logs all pass the custom PM2_HOME via environment variable when specified
+- **Backwards compatible** — apps without `pm2Home` continue using the default shared PM2 daemon
+
### Digital Twin — Aesthetic Taste Prompting Spec (brain idea 608dc733)
- **Promoted brain idea 608dc733** ("Prompting Aesthetic Taste Docs via Digital Twin") from dormant idea to concrete P2.5 spec in PLAN.md under M42: Unified Digital Twin Identity System
- **Defined 7 aesthetic domains** for taste capture: movies, music, visual art, architecture, food, plus 2 new domains (fashion/texture and digital/interface aesthetics)
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 81995c2fee..c0e56ae90b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -165,7 +165,8 @@ export const appSchema = z.object({
icon: z.string().nullable().optional(),
editorCommand: z.string().optional(),
description: z.string().optional(),
- archived: z.boolean().optional().default(false)
+ archived: z.boolean().optional().default(false),
+ pm2Home: z.string().optional() // Custom PM2_HOME path for apps that run in their own PM2 instance
});
// Partial schema for updates
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 91ab819ea3..bc06fdfb94 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -15,12 +15,28 @@ const router = Router();
router.get('/', asyncHandler(async (req, res) => {
const apps = await appsService.getAllApps();
- // Get all PM2 processes once
- const allPm2 = await pm2Service.listProcesses().catch(() => []);
- const pm2Map = new Map(allPm2.map(p => [p.name, p]));
+ // Group apps by their PM2_HOME (null = default)
+ const pm2HomeGroups = new Map();
+ for (const app of apps) {
+ const home = app.pm2Home || null;
+ if (!pm2HomeGroups.has(home)) {
+ pm2HomeGroups.set(home, []);
+ }
+ pm2HomeGroups.get(home).push(app);
+ }
+
+ // Fetch PM2 processes for each unique PM2_HOME
+ const pm2Maps = new Map();
+ for (const pm2Home of pm2HomeGroups.keys()) {
+ const processes = await pm2Service.listProcesses(pm2Home).catch(() => []);
+ pm2Maps.set(pm2Home, new Map(processes.map(p => [p.name, p])));
+ }
// Enrich with PM2 status and auto-populate processes if needed
const enriched = await Promise.all(apps.map(async (app) => {
+ const pm2Home = app.pm2Home || null;
+ const pm2Map = pm2Maps.get(pm2Home) || new Map();
+
const statuses = {};
for (const processName of app.pm2ProcessNames || []) {
const pm2Proc = pm2Map.get(processName);
@@ -63,10 +79,10 @@ router.get('/:id', asyncHandler(async (req, res, next) => {
throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
}
- // Get PM2 status for each process
+ // Get PM2 status for each process (using app's custom PM2_HOME if set)
const statuses = {};
for (const processName of app.pm2ProcessNames || []) {
- const status = await pm2Service.getAppStatus(processName).catch(() => ({ status: 'unknown' }));
+ const status = await pm2Service.getAppStatus(processName, app.pm2Home).catch(() => ({ status: 'unknown' }));
statuses[processName] = status;
}
@@ -165,7 +181,8 @@ router.post('/:id/start', asyncHandler(async (req, res, next) => {
if (hasEcosystem) {
// Use ecosystem config for proper env/port configuration
- const result = await pm2Service.startFromEcosystem(app.repoPath, processNames)
+ // Pass custom PM2_HOME if the app has one
+ const result = await pm2Service.startFromEcosystem(app.repoPath, processNames, app.pm2Home)
.catch(err => ({ success: false, error: err.message }));
// Map result to each process name for consistent response format
for (const name of processNames) {
@@ -201,7 +218,7 @@ router.post('/:id/stop', asyncHandler(async (req, res, next) => {
const results = {};
for (const name of app.pm2ProcessNames || []) {
- const result = await pm2Service.stopApp(name)
+ const result = await pm2Service.stopApp(name, app.pm2Home)
.catch(err => ({ success: false, error: err.message }));
results[name] = result;
}
@@ -224,7 +241,7 @@ router.post('/:id/restart', asyncHandler(async (req, res, next) => {
const results = {};
for (const name of app.pm2ProcessNames || []) {
- const result = await pm2Service.restartApp(name)
+ const result = await pm2Service.restartApp(name, app.pm2Home)
.catch(err => ({ success: false, error: err.message }));
results[name] = result;
}
@@ -247,7 +264,7 @@ router.get('/:id/status', asyncHandler(async (req, res, next) => {
const statuses = {};
for (const name of app.pm2ProcessNames || []) {
- const status = await pm2Service.getAppStatus(name)
+ const status = await pm2Service.getAppStatus(name, app.pm2Home)
.catch(err => ({ status: 'error', error: err.message }));
statuses[name] = status;
}
@@ -270,7 +287,7 @@ router.get('/:id/logs', asyncHandler(async (req, res, next) => {
throw new ServerError('No process name specified', { status: 400, code: 'MISSING_PROCESS' });
}
- const logs = await pm2Service.getLogs(processName, lines)
+ const logs = await pm2Service.getLogs(processName, lines, app.pm2Home)
.catch(err => `Error retrieving logs: ${err.message}`);
res.json({ processName, lines, logs });
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 65951ff055..bb050246da 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -2,8 +2,25 @@ import pm2 from 'pm2';
import { spawn } from 'child_process';
import { existsSync } from 'fs';
+/**
+ * Build environment object with optional custom PM2_HOME
+ * @param {string} pm2Home Optional custom PM2_HOME path
+ * @returns {object} Environment variables
+ */
+function buildEnv(pm2Home) {
+ const env = { ...process.env };
+ if (pm2Home) {
+ env.PM2_HOME = pm2Home;
+ }
+ // Strip PortOS env vars to avoid conflicts
+ delete env.PORT;
+ delete env.HOST;
+ return env;
+}
+
/**
* Connect to PM2 daemon and run an action
+ * Note: This uses the default PM2_HOME. For custom PM2_HOME, use CLI commands.
*/
function connectAndRun(action) {
return new Promise((resolve, reject) => {
@@ -53,8 +70,26 @@ export async function startApp(name, options = {}) {
/**
* Stop an app
* @param {string} name PM2 process name
+ * @param {string} pm2Home Optional custom PM2_HOME path
*/
-export async function stopApp(name) {
+export async function stopApp(name, pm2Home = null) {
+ // Use CLI for custom PM2_HOME
+ if (pm2Home) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('pm2', ['stop', name], {
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
+ let stderr = '';
+ child.stderr.on('data', (data) => { stderr += data.toString(); });
+ child.on('close', (code) => {
+ if (code !== 0) return reject(new Error(stderr || `pm2 stop exited with code ${code}`));
+ resolve({ success: true });
+ });
+ child.on('error', reject);
+ });
+ }
+
return connectAndRun((pm2) => {
return new Promise((resolve, reject) => {
pm2.stop(name, (err) => {
@@ -68,8 +103,26 @@ export async function stopApp(name) {
/**
* Restart an app
* @param {string} name PM2 process name
+ * @param {string} pm2Home Optional custom PM2_HOME path
*/
-export async function restartApp(name) {
+export async function restartApp(name, pm2Home = null) {
+ // Use CLI for custom PM2_HOME
+ if (pm2Home) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('pm2', ['restart', name], {
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
+ let stderr = '';
+ child.stderr.on('data', (data) => { stderr += data.toString(); });
+ child.on('close', (code) => {
+ if (code !== 0) return reject(new Error(stderr || `pm2 restart exited with code ${code}`));
+ resolve({ success: true });
+ });
+ child.on('error', reject);
+ });
+ }
+
return connectAndRun((pm2) => {
return new Promise((resolve, reject) => {
pm2.restart(name, (err) => {
@@ -83,8 +136,26 @@ export async function restartApp(name) {
/**
* Delete an app from PM2
* @param {string} name PM2 process name
+ * @param {string} pm2Home Optional custom PM2_HOME path
*/
-export async function deleteApp(name) {
+export async function deleteApp(name, pm2Home = null) {
+ // Use CLI for custom PM2_HOME
+ if (pm2Home) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('pm2', ['delete', name], {
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
+ let stderr = '';
+ child.stderr.on('data', (data) => { stderr += data.toString(); });
+ child.on('close', (code) => {
+ if (code !== 0) return reject(new Error(stderr || `pm2 delete exited with code ${code}`));
+ resolve({ success: true });
+ });
+ child.on('error', reject);
+ });
+ }
+
return connectAndRun((pm2) => {
return new Promise((resolve, reject) => {
pm2.delete(name, (err) => {
@@ -98,10 +169,14 @@ export async function deleteApp(name) {
/**
* Get status of a specific process using CLI (avoids connection deadlocks)
* @param {string} name PM2 process name
+ * @param {string} pm2Home Optional custom PM2_HOME path
*/
-export async function getAppStatus(name) {
+export async function getAppStatus(name, pm2Home = null) {
return new Promise((resolve) => {
- const child = spawn('pm2', ['jlist'], { shell: false });
+ const child = spawn('pm2', ['jlist'], {
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
let stdout = '';
child.stdout.on('data', (data) => {
@@ -109,7 +184,14 @@ export async function getAppStatus(name) {
});
child.on('close', () => {
- const processes = JSON.parse(stdout || '[]');
+ // pm2 jlist may output ANSI codes and warnings before JSON
+ let jsonStart = stdout.indexOf('[{');
+ if (jsonStart < 0) {
+ const emptyMatch = stdout.match(/\[\](?![0-9])/);
+ jsonStart = emptyMatch ? stdout.indexOf(emptyMatch[0]) : -1;
+ }
+ const pm2Json = jsonStart >= 0 ? stdout.slice(jsonStart) : '[]';
+ const processes = JSON.parse(pm2Json);
const proc = processes.find(p => p.name === name);
if (!proc) {
@@ -141,10 +223,14 @@ export async function getAppStatus(name) {
/**
* List all PM2 processes using CLI (avoids connection deadlocks)
+ * @param {string} pm2Home Optional custom PM2_HOME path
*/
-export async function listProcesses() {
+export async function listProcesses(pm2Home = null) {
return new Promise((resolve) => {
- const child = spawn('pm2', ['jlist'], { shell: false });
+ const child = spawn('pm2', ['jlist'], {
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
let stdout = '';
child.stdout.on('data', (data) => {
@@ -184,11 +270,15 @@ export async function listProcesses() {
* Get logs for a process using pm2 CLI (more reliable for log retrieval)
* @param {string} name PM2 process name
* @param {number} lines Number of lines to retrieve
+ * @param {string} pm2Home Optional custom PM2_HOME path
*/
-export async function getLogs(name, lines = 100) {
+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: false });
+ const child = spawn('pm2', args, {
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
let stdout = '';
let stderr = '';
@@ -244,8 +334,9 @@ export async function startWithCommand(name, cwd, command) {
* 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 = []) {
+export async function startFromEcosystem(cwd, processNames = [], pm2Home = null) {
return new Promise((resolve, reject) => {
const ecosystemFile = ['ecosystem.config.cjs', 'ecosystem.config.js']
.find(f => existsSync(`${cwd}/${f}`));
@@ -259,13 +350,11 @@ export async function startFromEcosystem(cwd, processNames = []) {
args.push('--only', processNames.join(','));
}
- // Strip PortOS env vars so child ecosystem configs don't inherit them
- // e.g., process.env.PORT || 4420 would resolve to PortOS's 5554 otherwise
- const cleanEnv = { ...process.env };
- delete cleanEnv.PORT;
- delete cleanEnv.HOST;
-
- const child = spawn('pm2', args, { cwd, shell: false, env: cleanEnv });
+ const child = spawn('pm2', args, {
+ cwd,
+ shell: false,
+ env: buildEnv(pm2Home)
+ });
let stdout = '';
let stderr = '';