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: auto-start the Eidoverse runtime at boot and on feature enable

Adam Eivy81cb2bb72519
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index bbce8e1bd4..2343c11b0a 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -92,8 +92,16 @@ installed during setup:
<bun> --env-file=.env.portos server/server.ts
```
-Installation does not start the server. Start, stop, logs, updates, and launch
-links remain visible on the normal managed-app screen. Plain-HTTP managed apps
+Once installed and enabled, PortOS starts the runtime automatically at server
+boot and when the feature is enabled. It waits for readiness, opens the host
+bridge, reconnects the resident CoS presence when that presence is enabled, and
+reconciles pending world-design updates. This startup never installs missing
+dependencies, downloads assets, or calls an AI provider. A disabled feature does
+not auto-start the runtime; manual app controls remain available. Start, stop,
+logs, updates, and launch links remain visible on the normal managed-app screen.
+Command-based Eidoverse launches use a 2 GB PM2 memory restart limit so the
+loaded world and asset runtime can exceed the generic app limit of 500 MB.
+Plain-HTTP managed apps
keep an `http://` launch URL even when PortOS itself is open over HTTPS, so the
Apps launch action works from a Tailscale MagicDNS session. Managed updates pull
both the selected Worlds checkout and its companion video runtime before using
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index b242809e53..49e79d3990 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -65,7 +65,7 @@
* persistent-mind setup, agent-benchmark and JEV policy/head mutations
* require operator authority. Head training reads git/forge history;
* adoption/discard changes the classifier admitting agent work.
- * - settings: feature toggles and the Eidoverse host bridge (they arm
+ * - settings: other feature toggles and the Eidoverse host bridge (they arm
* PortOS's own integrations or open a listener), orchestration profiles,
* AI assignments and credentials (they choose among configured providers
* or store a key). The `PUT /api/settings` and `PUT /api/cos/config`
@@ -528,8 +528,11 @@ const bodyKeys = (body) => (body && typeof body === 'object' && !Array.isArray(b
// `hostControlBodyGate` in services/authGate.js applies these after the body
// parser, since `hostControlRouteGate` runs before it.
const COMPILED_BODY_ROUTES = [
+ // Enabling this feature now launches its registered host executable.
+ ['PUT /api/settings/features/eidoverse', (body) => bodyKeys(body)],
['POST /api/local-llm/capability-tests/run', (body) => body?.testId === 'sandbox-repair' ? ['testId'] : []],
- ['PUT /api/settings', (body) => bodyKeys(body).filter((key) => HOST_CONTROL_SETTINGS_SLICES.includes(key))],
+ ['PUT /api/settings', (body) => bodyKeys(body).filter((key) => HOST_CONTROL_SETTINGS_SLICES.includes(key)
+ || (key === 'instanceFeatures' && body.instanceFeatures?.eidoverse !== undefined))],
['PUT /api/cos/config', (body) => bodyKeys(body).filter((key) => !HOST_CONTROL_OPEN_COS_CONFIG_KEYS.includes(key))],
].map(([route, pick]) => ({ ...compileRoute(route), pick }));
diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.js
index 70110bcac2..56a75dfbe0 100644
--- a/server/routes/apps/lifecycle.js
+++ b/server/routes/apps/lifecycle.js
@@ -28,6 +28,7 @@ import { parseEcosystemFromPath } from '../../services/streamingDetect.js';
import { usesPm2, isDesktopType } from '../../services/appProcessTypes.js';
import { detectAppIcon, isUsableSvg } from '../../services/appIconDetect.js';
import { loadApp, pathExists, deriveUiPort } from './shared.js';
+import { EIDOVERSE_PROCESS_NAME, EIDOVERSE_MAX_MEMORY_RESTART } from '../../services/eidoverse.js';
const router = Router();
@@ -161,7 +162,8 @@ router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {
}
const result = await pm2Service.startWithCommand(name, app.repoPath, command, {
pm2Home: app.pm2Home,
- port: singleProcessPort
+ port: singleProcessPort,
+ ...(name === EIDOVERSE_PROCESS_NAME ? { maxMemoryRestart: EIDOVERSE_MAX_MEMORY_RESTART } : {}),
})
.catch(err => ({ success: false, error: err.message }));
results[name] = result;
diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.js
index 059cee639a..c9ff6a2c39 100644
--- a/server/routes/apps/lifecycle.test.js
+++ b/server/routes/apps/lifecycle.test.js
@@ -245,7 +245,7 @@ describe('Apps Lifecycle Routes', () => {
repoPath: '/path/to/repo',
uiPort: 8940,
apiPort: 8940,
- pm2ProcessNames: ['worlds'],
+ pm2ProcessNames: ['eidoverse-worlds'],
startCommands: ['bun --env-file=.env.portos server/server.ts']
};
appsService.getAppById.mockResolvedValue(mockApp);
@@ -256,8 +256,8 @@ describe('Apps Lifecycle Routes', () => {
expect(response.status).toBe(200);
expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
- 'worlds', '/path/to/repo', 'bun --env-file=.env.portos server/server.ts',
- expect.objectContaining({ port: 8940 })
+ 'eidoverse-worlds', '/path/to/repo', 'bun --env-file=.env.portos server/server.ts',
+ expect.objectContaining({ port: 8940, maxMemoryRestart: '2G' })
);
});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 8299071aaa..c45d0d4dc1 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -679,6 +679,11 @@ router.put('/', asyncHandler(async (req, res) => {
current,
);
}, { actor: 'user' });
+ if (settingsPatch.instanceFeatures?.eidoverse !== undefined) {
+ const { reconcileEidoverseRuntime } = await import('../services/eidoverseRuntime.js');
+ await reconcileEidoverseRuntime()
+ .catch((err) => console.error(`⚠️ Eidoverse startup deferred: ${err.message}`));
+ }
// A beeper save that flips `enabled` never armed the scheduler until a
// restart. `startBeeperScheduler()` is the only thing that registers the
// sweep, and it's reached exclusively through `reconcileBeeperArming` —
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 113e3e4771..73c805c241 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -2,6 +2,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
+const reconcileEidoverseRuntime = vi.hoisted(() => vi.fn(async () => ({ running: true })));
+vi.mock('../services/eidoverseRuntime.js', () => ({ reconcileEidoverseRuntime }));
+
// In-memory settings store backing the mocked service.
let store = {};
@@ -308,6 +311,14 @@ describe('Settings routes — instance feature participation', () => {
expect(reconcileBeeperIngestion).not.toHaveBeenCalled();
});
+ it('reconciles Eidoverse when the general settings save changes its feature gate', async () => {
+ const res = await request(buildApp()).put('/api/settings')
+ .send({ instanceFeatures: { eidoverse: { enabled: true } } });
+ expect(res.status).toBe(200);
+ expect(store.instanceFeatures.eidoverse.enabled).toBe(true);
+ expect(reconcileEidoverseRuntime).toHaveBeenCalledOnce();
+ });
+
// Fork issue #1, final live pass: the Beeper sweep + realtime transport arm on
// the instance feature plus a token, and that gate was read at boot only — so
// turning the feature on left both down until the next restart.
diff --git a/server/services/authGate.test.js b/server/services/authGate.test.js
index d3227e6084..396197f9f2 100644
--- a/server/services/authGate.test.js
+++ b/server/services/authGate.test.js
@@ -699,6 +699,10 @@ describe('mounted host-control trailing slashes (#8950)', () => {
res.json({ saved: true });
});
app.use('/api/settings', settings);
+ app.put('/api/settings/features/:featureId', (req, res) => {
+ persist(req.body);
+ res.json({ saved: true });
+ });
return { app, runner, persist };
};
const runBody = { providerId: 'example-cli', prompt: 'Example prompt' };
@@ -727,6 +731,18 @@ describe('mounted host-control trailing slashes (#8950)', () => {
expect(persist).toHaveBeenCalledExactlyOnceWith({ location: {} });
});
+ it('requires operator authority to arm Eidoverse through either settings path', async () => {
+ const remote = await buildApp();
+ const body = { instanceFeatures: { eidoverse: { enabled: true } } };
+ expect((await request(remote.app).put('/api/settings').send(body)).status).toBe(403);
+ expect((await request(remote.app).put('/api/settings/features/eidoverse').send({ enabled: true })).status).toBe(403);
+ expect(remote.persist).not.toHaveBeenCalled();
+ const local = await buildApp('127.0.0.1');
+ expect((await request(local.app).put('/api/settings').send(body)).status).toBe(200);
+ expect((await request(local.app).put('/api/settings/features/eidoverse').send({ enabled: true })).status).toBe(200);
+ expect(local.persist).toHaveBeenCalledTimes(2);
+ });
+
it.each(['local', 'session', 'basic'])('preserves %s authority through mounted root handlers', async (authority) => {
let header = ['X-Example', 'local'];
if (authority !== 'local') {
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index c865974433..888c982424 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -404,16 +404,15 @@ const startBackgroundServices = ({ spawnerReady, io }) => {
// in bootstrapSequence.js.
initCosAfterSpawner({ spawnerReady, initCos: () => cos.init() });
- // World Design migrations are offline and leave a pending checkpoint. If the
- // separately-managed Eidoverse process is already online, reconcile it now;
- // otherwise leave the checkpoint for direct remediation in the Eidoverse UI.
- // This is deterministic local projection only — never an AI provider call.
- import('./eidoverseWorld.js')
- .then(({ reconcilePendingEidoverseWorld }) => reconcilePendingEidoverseWorld())
+ // Restore only an installed, opted-in world, then its bridge, resident
+ // presence, and pending design. No install, download, or AI provider call.
+ // startBackgroundServices is disabled during smoke boot.
+ import('./eidoverseRuntime.js')
+ .then(({ reconcileEidoverseRuntime }) => reconcileEidoverseRuntime())
.then((result) => {
- if (result.reconciled) console.log('🌐 Reconciled pending Eidoverse World Design update');
+ if (result.running) console.log('🌐 Eidoverse runtime and resident presence restored');
})
- .catch(err => logBootstrapFailure('⚠️ Eidoverse World Design reconciliation deferred', err));
+ .catch(err => logBootstrapFailure('⚠️ Eidoverse startup deferred', err));
// Initialize agent automation scheduler and action executor
automationScheduler.init().catch(err => logBootstrapFailure('❌ Agent scheduler init failed', err));
diff --git a/server/services/eidoverse.js b/server/services/eidoverse.js
index fbeedb259d..f2b545be2c 100644
--- a/server/services/eidoverse.js
+++ b/server/services/eidoverse.js
@@ -15,6 +15,8 @@ export const DEFAULT_EIDOVERSE_WORLDS_REPO = 'https://github.com/atomantic/eidov
export const EIDOVERSE_VIDEO_REPO = 'https://github.com/anima-research/eidoverse-video';
export { EIDOVERSE_PORT };
export const EIDOVERSE_PROCESS_NAME = 'eidoverse-worlds';
+// The loaded world and asset runtime exceeds the generic command-app 500M cap.
+export const EIDOVERSE_MAX_MEMORY_RESTART = '2G';
const BUN_INSTALL_URL = 'https://bun.com/install';
const BUN_INSTALL_PS1_URL = 'https://bun.com/install.ps1';
diff --git a/server/services/eidoverseRuntime.js b/server/services/eidoverseRuntime.js
new file mode 100644
index 0000000000..e9855c8283
--- /dev/null
+++ b/server/services/eidoverseRuntime.js
@@ -0,0 +1,54 @@
+/** Restore the opted-in, installed world at boot without installing or inferring. */
+import { createSingleFlight } from '../lib/singleFlight.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+const startup = createSingleFlight();
+
+export function reconcileEidoverseRuntime() {
+ return startup.run('runtime', async () => {
+ const { isInstanceFeatureEnabled, assertConfiguredEidoverseInstalled } = await import('./instanceFeatures.js');
+ if (!await isInstanceFeatureEnabled('eidoverse')) return { running: false, reason: 'feature-disabled' };
+
+ // Strict configured-install check: never download, recreate a registry, or
+ // start an unknown process because a readiness probe failed.
+ const setup = await assertConfiguredEidoverseInstalled();
+ if (!['online', 'launching', 'not_started', 'stopped', 'errored'].includes(setup.runtimeStatus)) {
+ throw new ServerError('Eidoverse runtime status is unavailable; startup was deferred.', {
+ status: 503, code: 'EIDOVERSE_RUNTIME_UNKNOWN',
+ });
+ }
+ let started = false;
+ if (!['online', 'launching'].includes(setup.runtimeStatus)) {
+ const { getAppById, notifyAppsChanged } = await import('./apps.js');
+ const { EIDOVERSE_PROCESS_NAME, EIDOVERSE_PORT, EIDOVERSE_MAX_MEMORY_RESTART } = await import('./eidoverse.js');
+ const app = await getAppById(setup.appId);
+ if (app?.archived || !app?.repoPath || !app?.startCommands?.[0]
+ || app.pm2ProcessNames?.length !== 1 || app.pm2ProcessNames[0] !== EIDOVERSE_PROCESS_NAME) {
+ throw new ServerError('The registered Eidoverse launch configuration is unavailable.', {
+ status: 409, code: 'EIDOVERSE_LAUNCH_UNAVAILABLE',
+ });
+ }
+ // Recheck after async registry reads in case the operator disabled it.
+ if (!await isInstanceFeatureEnabled('eidoverse')) return { running: false, reason: 'feature-disabled' };
+ const { startWithCommand } = await import('./pm2.js');
+ const result = await startWithCommand(EIDOVERSE_PROCESS_NAME, app.repoPath, app.startCommands[0], {
+ pm2Home: app.pm2Home, port: EIDOVERSE_PORT, maxMemoryRestart: EIDOVERSE_MAX_MEMORY_RESTART,
+ });
+ if (result?.success !== true) {
+ throw new ServerError('Eidoverse runtime could not start.', { status: 503, code: 'EIDOVERSE_START_FAILED' });
+ }
+ started = true;
+ notifyAppsChanged('start', app.id);
+ }
+
+ if (!await isInstanceFeatureEnabled('eidoverse')) return { running: true, started, reason: 'feature-disabled' };
+ const { ensureEidoverseHost } = await import('./eidoverseHost.js');
+ await ensureEidoverseHost(); // Wait for HTTP readiness before the world socket.
+ const { ensureEidoverseWorldConfig, ensureEidoverseWorldPresence, reconcilePendingEidoverseWorld } = await import('./eidoverseWorld.js');
+ const config = await ensureEidoverseWorldConfig();
+ if (!await isInstanceFeatureEnabled('eidoverse')) return { running: true, started, reason: 'feature-disabled' };
+ if (config.cos.enabled) await ensureEidoverseWorldPresence();
+ await reconcilePendingEidoverseWorld();
+ return { running: true, started, presenceEnabled: config.cos.enabled };
+ });
+}
diff --git a/server/services/eidoverseRuntime.test.js b/server/services/eidoverseRuntime.test.js
new file mode 100644
index 0000000000..b73e45cb45
--- /dev/null
+++ b/server/services/eidoverseRuntime.test.js
@@ -0,0 +1,101 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mock = vi.hoisted(() => ({
+ enabled: true,
+ setup: { installed: true, appId: 'example-world', runtimeStatus: 'not_started' },
+ cosEnabled: true,
+ start: vi.fn(),
+ ready: vi.fn(),
+ presence: vi.fn(),
+ design: vi.fn(),
+ assertInstalled: vi.fn(),
+}));
+vi.mock('./instanceFeatures.js', () => ({
+ isInstanceFeatureEnabled: async () => mock.enabled,
+ assertConfiguredEidoverseInstalled: mock.assertInstalled,
+}));
+vi.mock('./apps.js', () => ({
+ getAppById: async () => ({ id: 'example-world', repoPath: '/example/worlds', pm2Home: '/example/pm2',
+ pm2ProcessNames: ['eidoverse-worlds'], startCommands: ['bun --env-file=.env.portos server/server.ts'] }),
+ notifyAppsChanged: vi.fn(),
+}));
+vi.mock('./eidoverse.js', () => ({ EIDOVERSE_PROCESS_NAME: 'eidoverse-worlds', EIDOVERSE_PORT: 8940, EIDOVERSE_MAX_MEMORY_RESTART: '2G' }));
+vi.mock('./pm2.js', () => ({ startWithCommand: mock.start }));
+vi.mock('./eidoverseHost.js', () => ({ ensureEidoverseHost: mock.ready }));
+vi.mock('./eidoverseWorld.js', () => ({
+ ensureEidoverseWorldConfig: async () => ({ cos: { enabled: mock.cosEnabled } }),
+ ensureEidoverseWorldPresence: mock.presence,
+ reconcilePendingEidoverseWorld: mock.design,
+}));
+import { reconcileEidoverseRuntime } from './eidoverseRuntime.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mock.enabled = true;
+ mock.cosEnabled = true;
+ mock.setup = { installed: true, appId: 'example-world', runtimeStatus: 'not_started' };
+ mock.assertInstalled.mockReset().mockImplementation(async () => mock.setup);
+ mock.start.mockReset().mockResolvedValue({ success: true });
+ mock.ready.mockReset().mockResolvedValue({ running: true });
+});
+
+describe('installed Eidoverse startup workflow', () => {
+ it('starts once, waits for readiness, then reconnects and reconciles the world', async () => {
+ let release;
+ mock.ready.mockImplementation(() => new Promise(resolve => { release = resolve; }));
+ const first = reconcileEidoverseRuntime();
+ const second = reconcileEidoverseRuntime();
+ expect(second).toBe(first);
+ await vi.waitFor(() => expect(mock.ready).toHaveBeenCalledOnce());
+ expect(mock.start).toHaveBeenCalledWith('eidoverse-worlds', '/example/worlds',
+ 'bun --env-file=.env.portos server/server.ts', { pm2Home: '/example/pm2', port: 8940, maxMemoryRestart: '2G' });
+ expect(mock.presence).not.toHaveBeenCalled();
+ release();
+ await expect(first).resolves.toMatchObject({ running: true, started: true });
+ expect(mock.presence).toHaveBeenCalledOnce();
+ expect(mock.design).toHaveBeenCalledOnce();
+ expect(mock.presence.mock.invocationCallOrder[0]).toBeLessThan(mock.design.mock.invocationCallOrder[0]);
+ });
+
+ it('does nothing while the optional feature is disabled', async () => {
+ mock.enabled = false;
+ await expect(reconcileEidoverseRuntime()).resolves.toMatchObject({ reason: 'feature-disabled' });
+ expect(mock.assertInstalled).not.toHaveBeenCalled();
+ expect(mock.start).not.toHaveBeenCalled();
+ expect(mock.ready).not.toHaveBeenCalled();
+ });
+
+ it('does not install an absent runtime or launch one with unknown status', async () => {
+ mock.assertInstalled.mockRejectedValueOnce(new Error('Install required'));
+ await expect(reconcileEidoverseRuntime()).rejects.toThrow('Install required');
+ mock.setup.runtimeStatus = 'unknown';
+ await expect(reconcileEidoverseRuntime()).rejects.toMatchObject({ code: 'EIDOVERSE_RUNTIME_UNKNOWN' });
+ expect(mock.start).not.toHaveBeenCalled();
+ });
+
+ it('reuses an online runtime and respects disabled CoS presence', async () => {
+ mock.setup.runtimeStatus = 'online';
+ mock.cosEnabled = false;
+ await expect(reconcileEidoverseRuntime()).resolves.toMatchObject({ running: true, started: false, presenceEnabled: false });
+ expect(mock.start).not.toHaveBeenCalled();
+ expect(mock.presence).not.toHaveBeenCalled();
+ expect(mock.design).toHaveBeenCalledOnce();
+ });
+
+ it('stops at failed launch/readiness and permits a later explicit retry', async () => {
+ mock.start.mockResolvedValueOnce({ success: false });
+ await expect(reconcileEidoverseRuntime()).rejects.toMatchObject({ code: 'EIDOVERSE_START_FAILED' });
+ expect(mock.ready).not.toHaveBeenCalled();
+ mock.ready.mockRejectedValueOnce(new Error('Readiness timed out'));
+ await expect(reconcileEidoverseRuntime()).rejects.toThrow('Readiness timed out');
+ expect(mock.presence).not.toHaveBeenCalled();
+ await expect(reconcileEidoverseRuntime()).resolves.toMatchObject({ running: true });
+ });
+
+ it('does not start after the feature is disabled during the install probe', async () => {
+ mock.assertInstalled.mockImplementation(async () => { mock.enabled = false; return mock.setup; });
+ await expect(reconcileEidoverseRuntime()).resolves.toMatchObject({ reason: 'feature-disabled' });
+ expect(mock.start).not.toHaveBeenCalled();
+ expect(mock.presence).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.js
index 6bc92327a9..8b124112d1 100644
--- a/server/services/instanceFeatures.js
+++ b/server/services/instanceFeatures.js
@@ -322,6 +322,14 @@ export async function updateInstanceFeature(featureId, enabled) {
await recordFeatureToggle(featureId, enabled);
+ if (featureId === 'eidoverse') {
+ // Use the same admission/readiness path as boot. A saved toggle remains
+ // saved even if the external runtime needs repair; never install here.
+ const { reconcileEidoverseRuntime } = await import('./eidoverseRuntime.js');
+ await reconcileEidoverseRuntime()
+ .catch((error) => console.error(`⚠️ Eidoverse startup deferred: ${error.message}`));
+ }
+
const detected = await detectFeatureConfiguration();
return {
features: await attachSetupStatus(resolveInstanceFeatures(settings, { detected }), settings),
diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.js
index 0f1233f084..2e28bd3188 100644
--- a/server/services/instanceFeatures.test.js
+++ b/server/services/instanceFeatures.test.js
@@ -13,9 +13,11 @@ const mock = vi.hoisted(() => ({
setEidoverseWorldsOrigin: vi.fn(),
riggingReady: false,
riggingThrows: false,
+ reconcileEidoverseRuntime: vi.fn(async () => ({ running: true })),
}));
const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('./eidoverseRuntime.js', () => ({ reconcileEidoverseRuntime: mock.reconcileEidoverseRuntime }));
vi.mock('./userActions.js', () => ({ recordUserAction }));
vi.mock('./settings.js', () => ({
@@ -95,6 +97,7 @@ describe('instance features', () => {
mock.assertEidoverseInstalled.mockReset().mockResolvedValue({ installed: true });
mock.setEidoverseWorldsOrigin.mockReset().mockResolvedValue({ appId: 'app-eidoverse' });
mock.updateSettingsWith.mockReset();
+ mock.reconcileEidoverseRuntime.mockReset().mockResolvedValue({ running: true });
mock.updateSettingsWith.mockImplementation(async (mutate) => {
mock.settings = await mutate(structuredClone(mock.settings));
return structuredClone(mock.settings);
@@ -172,6 +175,23 @@ describe('instance features', () => {
});
});
+ it('reconciles after saving Eidoverse toggles and retains an enable when launch fails', async () => {
+ mock.reconcileEidoverseRuntime.mockImplementation(async () => {
+ expect(mock.settings.instanceFeatures.eidoverse.enabled).toBe(true);
+ throw new Error('Example runtime unavailable');
+ });
+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const result = await updateInstanceFeature('eidoverse', true);
+ expect(byId(result.features, 'eidoverse').enabled).toBe(true);
+ mock.reconcileEidoverseRuntime.mockImplementation(async () => {
+ expect(mock.settings.instanceFeatures.eidoverse.enabled).toBe(false);
+ return { running: false };
+ });
+ await updateInstanceFeature('eidoverse', false);
+ expect(mock.reconcileEidoverseRuntime).toHaveBeenCalledTimes(2);
+ errorLog.mockRestore();
+ });
+
it('fails closed for malformed persisted feature flags', async () => {
const settings = { instanceFeatures: { post: { enabled: 'false' } } };
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 22ba0b53c3..bfe27cdad8 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -649,14 +649,14 @@ export async function getLogs(name, lines = 100, pm2Home = null) {
* one start call) — see the EADDRINUSE note at the env assignment below.
*/
export async function startWithCommand(name, cwd, command, options = {}) {
- const { autorestart = true, maxRestarts = 10, pm2Home = null, port = null } = options;
+ const { autorestart = true, maxRestarts = 10, maxMemoryRestart = '500M', pm2Home = null, port = null } = options;
// Parse with quote-awareness so `node --opt "arg with spaces"` survives;
// a bare split(' ') would shred quoted segments. PM2 accepts `args` as an
// array, which avoids re-joining and re-splitting on the way through.
const [script, ...args] = parseCommandArgs(command);
if (pm2Home) {
- return spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home, port });
+ return spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, maxMemoryRestart, pm2Home, port });
}
return connectAndRun((pm2) => {
@@ -675,7 +675,7 @@ export async function startWithCommand(name, cwd, command, options = {}) {
// desktop app (a game window routinely exceeds it) would kill and
// respawn the live window — exactly the relaunch loop this avoids.
...(autorestart
- ? { max_restarts: maxRestarts, min_uptime: '10s', restart_delay: 5000, max_memory_restart: '500M' }
+ ? { max_restarts: maxRestarts, min_uptime: '10s', restart_delay: 5000, max_memory_restart: maxMemoryRestart }
: {}),
// PM2 snapshots the launching process's environment into the child, so
// PortOS's own PORT would otherwise reach a managed app and win: both
@@ -712,12 +712,12 @@ export async function startWithCommand(name, cwd, command, options = {}) {
* tunes the autorestart=true nursing behavior, which no current caller uses
* together with a custom pm2Home.
*/
-function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home, port = null }) {
+function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, maxMemoryRestart, pm2Home, port = null }) {
return new Promise((resolve, reject) => {
const cliArgs = ['start', script, '--name', name, '--cwd', cwd];
if (!isJsScript(script)) cliArgs.push('--interpreter', 'none');
if (autorestart) {
- cliArgs.push('--max-restarts', String(maxRestarts), '--restart-delay', '5000', '--max-memory-restart', '500M');
+ cliArgs.push('--max-restarts', String(maxRestarts), '--restart-delay', '5000', '--max-memory-restart', String(maxMemoryRestart));
} else {
cliArgs.push('--no-autorestart');
}
diff --git a/server/services/pm2.launch.test.js b/server/services/pm2.launch.test.js
index 58c63f087e..0a840314ce 100644
--- a/server/services/pm2.launch.test.js
+++ b/server/services/pm2.launch.test.js
@@ -58,6 +58,15 @@ describe('PM2 command launch interpreters', () => {
expect(options).not.toHaveProperty('interpreter');
});
+ it('honors a runtime memory limit on both command launch paths', async () => {
+ await startWithCommand('example-world', '/repo/worlds', 'bun server/server.ts', { maxMemoryRestart: '2G' });
+ expect(mockPm2.start.mock.calls[0][0].max_memory_restart).toBe('2G');
+ await startWithCommand('example-world', '/repo/worlds', 'bun server/server.ts', {
+ maxMemoryRestart: '2G', pm2Home: '/tmp/example-pm2',
+ });
+ expect(mockSpawn.mock.calls[0][1]).toEqual(expect.arrayContaining(['--max-memory-restart', '2G']));
+ });
+
it('applies the same direct-execution rule to configured app scripts', async () => {
await startApp('tooling-app', { script: 'npm', args: 'run dev' });