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

refactor([issue-1836]): extract standardize:start and app:deploy orchestration into services

[._.]/ Adam Eivya17fe01a3d78
diff --git a/server/services/appDeployer.js b/server/services/appDeployer.js
index 533e0aa713..c4899ffa0c 100644
--- a/server/services/appDeployer.js
+++ b/server/services/appDeployer.js
@@ -2,6 +2,7 @@ import { spawn } from 'child_process';
import { existsSync } from 'fs';
import { join } from 'path';
import { NON_PM2_TYPES } from './streamingDetect.js';
+import { getAppById } from './apps.js';
export const DEPLOY_FLAGS = ['--ios', '--macos', '--watch', '--all', '--skip-tests'];
const VALID_FLAGS = new Set(DEPLOY_FLAGS);
@@ -111,6 +112,45 @@ export function deployApp(app, flags, emit) {
});
}
+/**
+ * Resolve an app by id, validate it has a deploy script, and run the deploy —
+ * the orchestration the `app:deploy` socket handler used to do inline. Pulling
+ * it into the service makes it unit-testable and HTTP-callable; the caller only
+ * supplies a streaming-output callback and consumes the terminal outcome.
+ *
+ * Returns a discriminated outcome so the caller can map it to the right event:
+ * - `{ ok: false, error }` — the request was invalid (app not found, or no
+ * deploy.sh) and never started a deploy (caller emits `app:deploy:error`).
+ * - `{ ok: true, success, code }` — the deploy ran to completion (caller emits
+ * `app:deploy:complete`).
+ *
+ * @param {string} appId - Id of the app to deploy
+ * @param {string[]} flags - CLI flags forwarded to deploy.sh
+ * @param {object} [opts]
+ * @param {(type: string, payload: object) => void} [opts.onOutput] - Streaming
+ * deploy output/status/error frames (same `(type, data)` shape `deployApp` emits)
+ * @param {Function} [opts.resolveApp] - Injectable app lookup (defaults to getAppById);
+ * a test seam so the orchestration is unit-testable without a real app store.
+ * @param {Function} [opts.checkScript] - Injectable deploy-script check (defaults to hasDeployScript).
+ * @param {Function} [opts.runDeploy] - Injectable deploy runner (defaults to deployApp).
+ * @returns {Promise<{ok: false, error: string} | {ok: true, success: boolean, code: number}>}
+ */
+export async function runDeployFlow(
+ appId,
+ flags = [],
+ { onOutput, resolveApp = getAppById, checkScript = hasDeployScript, runDeploy = deployApp } = {}
+) {
+ const app = await resolveApp(appId);
+ if (!app) return { ok: false, error: 'App not found' };
+ if (!checkScript(app)) return { ok: false, error: 'No deploy.sh found for this app' };
+
+ console.log(`🚀 Deploy started for ${app.name} [${flags.join(', ') || 'default'}]`);
+ const result = await runDeploy(app, flags, onOutput || (() => {}));
+ console.log(`${result.success ? '✅' : '❌'} Deploy ${result.success ? 'complete' : 'failed'} for ${app.name}`);
+
+ return { ok: true, success: result.success, code: result.code };
+}
+
/**
* Check if an app is currently deploying
*/
diff --git a/server/services/appDeployer.test.js b/server/services/appDeployer.test.js
new file mode 100644
index 0000000000..9248b554ca
--- /dev/null
+++ b/server/services/appDeployer.test.js
@@ -0,0 +1,63 @@
+import { describe, it, expect, vi } from 'vitest';
+import { runDeployFlow } from './appDeployer.js';
+
+describe('runDeployFlow', () => {
+ const app = { id: 'app-1', name: 'MyApp', repoPath: '/repo', type: 'xcode' };
+
+ it('returns a not-found outcome when the app is missing (no deploy attempted)', async () => {
+ const runDeploy = vi.fn();
+ const outcome = await runDeployFlow('missing', [], {
+ resolveApp: vi.fn().mockResolvedValue(null),
+ checkScript: vi.fn(),
+ runDeploy
+ });
+ expect(outcome).toEqual({ ok: false, error: 'App not found' });
+ expect(runDeploy).not.toHaveBeenCalled();
+ });
+
+ it('returns a no-script outcome when the app has no deploy.sh', async () => {
+ const runDeploy = vi.fn();
+ const outcome = await runDeployFlow('app-1', [], {
+ resolveApp: vi.fn().mockResolvedValue(app),
+ checkScript: vi.fn().mockReturnValue(false),
+ runDeploy
+ });
+ expect(outcome).toEqual({ ok: false, error: 'No deploy.sh found for this app' });
+ expect(runDeploy).not.toHaveBeenCalled();
+ });
+
+ it('runs the deploy and surfaces success + exit code', async () => {
+ const runDeploy = vi.fn().mockResolvedValue({ success: true, code: 0 });
+ const onOutput = vi.fn();
+ const outcome = await runDeployFlow('app-1', ['--ios'], {
+ resolveApp: vi.fn().mockResolvedValue(app),
+ checkScript: vi.fn().mockReturnValue(true),
+ runDeploy,
+ onOutput
+ });
+ expect(runDeploy).toHaveBeenCalledWith(app, ['--ios'], onOutput);
+ expect(outcome).toEqual({ ok: true, success: true, code: 0 });
+ });
+
+ it('reports a failed deploy with its non-zero exit code', async () => {
+ const outcome = await runDeployFlow('app-1', [], {
+ resolveApp: vi.fn().mockResolvedValue(app),
+ checkScript: vi.fn().mockReturnValue(true),
+ runDeploy: vi.fn().mockResolvedValue({ success: false, code: 2 })
+ });
+ expect(outcome).toEqual({ ok: true, success: false, code: 2 });
+ });
+
+ it('passes a no-op output sink to the deploy runner when onOutput is omitted', async () => {
+ const runDeploy = vi.fn().mockResolvedValue({ success: true, code: 0 });
+ await runDeployFlow('app-1', [], {
+ resolveApp: vi.fn().mockResolvedValue(app),
+ checkScript: vi.fn().mockReturnValue(true),
+ runDeploy
+ });
+ const passedSink = runDeploy.mock.calls[0][2];
+ expect(typeof passedSink).toBe('function');
+ // The sink must be safely callable (the real deployApp invokes it).
+ expect(() => passedSink('status', { message: 'x' })).not.toThrow();
+ });
+});
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index f053d61847..0d86193345 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -590,6 +590,104 @@ export async function applyStandardization(repoPath, plan, { skipBackup = false
return results;
}
+/**
+ * Run the full PM2 standardization flow: analyze → git backup → apply.
+ *
+ * This is the orchestration the `standardize:start` socket handler used to do
+ * inline. Pulling it into the service makes it unit-testable and HTTP-callable —
+ * the caller only supplies progress callbacks and consumes the final result.
+ *
+ * Progress is reported through `onStep({ step, status, data })` (the same
+ * `step`/`status`/`data` triple the socket layer forwards as `standardize:step`)
+ * and `onAnalyzed({ plan })` once the analysis plan is ready. Both callbacks are
+ * optional, so the flow is callable headless.
+ *
+ * Resolves to the terminal outcome the caller should report as
+ * `standardize:complete`:
+ * - `{ success: false, error }` on any failed step
+ * - `{ success: true, result: { backupBranch, filesModified, processes } }`
+ *
+ * @param {string} repoPath - Absolute path to the repo being standardized
+ * @param {string|null} providerId - Optional AI provider id (else the active one)
+ * @param {object} [opts]
+ * @param {(evt: {step: string, status: string, data: object}) => void} [opts.onStep]
+ * @param {(evt: {plan: object}) => void} [opts.onAnalyzed]
+ * @param {Function} [opts.analyze] - Injectable step impl (defaults to analyzeApp);
+ * a test seam so the orchestration is unit-testable without real AI analysis.
+ * @param {Function} [opts.backup] - Injectable step impl (defaults to createGitBackup).
+ * @param {Function} [opts.apply] - Injectable step impl (defaults to applyStandardization).
+ * @returns {Promise<{success: boolean, error?: string, result?: object}>}
+ */
+export async function runStandardizeFlow(
+ repoPath,
+ providerId = null,
+ { onStep, onAnalyzed, analyze = analyzeApp, backup = createGitBackup, apply = applyStandardization } = {}
+) {
+ const emit = (step, status, data = {}) => onStep?.({ step, status, data });
+
+ // Step 1: Analyze
+ emit('analyze', 'running', { message: 'Analyzing project configuration...' });
+
+ const analysis = await analyze(repoPath, providerId)
+ .catch(err => ({ success: false, error: err.message }));
+
+ if (!analysis.success) {
+ emit('analyze', 'error', { message: analysis.error });
+ return { success: false, error: analysis.error };
+ }
+
+ emit('analyze', 'done', {
+ message: `Found ${analysis.proposedChanges.processes?.length || 0} processes`,
+ processes: analysis.proposedChanges.processes,
+ strayPorts: analysis.proposedChanges.strayPorts
+ });
+
+ onAnalyzed?.({ plan: analysis });
+
+ // Step 2: Backup
+ emit('backup', 'running', { message: 'Creating git backup...' });
+
+ const backupResult = await backup(repoPath)
+ .catch(err => ({ success: false, reason: err.message }));
+
+ if (backupResult.success) {
+ emit('backup', 'done', { message: `Backup branch: ${backupResult.branch}`, branch: backupResult.branch });
+ } else if (backupResult.code === 'DIRTY_WORKTREE') {
+ emit('backup', 'error', { message: backupResult.reason });
+ return { success: false, error: backupResult.reason };
+ } else {
+ emit('backup', 'skipped', { message: backupResult.reason || 'No git repository' });
+ }
+
+ // Step 3: Apply changes (backup already handled above)
+ emit('apply', 'running', { message: 'Writing ecosystem.config.cjs...' });
+
+ const result = await apply(repoPath, analysis, { skipBackup: true })
+ .catch(err => ({ success: false, errors: [err.message] }));
+
+ if (result.errors?.length > 0) {
+ emit('apply', 'error', { message: result.errors.join(', ') });
+ return { success: false, error: result.errors.join(', ') };
+ }
+
+ emit('apply', 'done', {
+ message: `Modified ${result.filesModified.length} files`,
+ filesModified: result.filesModified
+ });
+
+ console.log(`✅ Standardization complete: ${result.filesModified.length} files modified`);
+
+ return {
+ success: true,
+ result: {
+ // Use the backup branch from step 2 since step 3 skipped its own backup.
+ backupBranch: backupResult.branch || null,
+ filesModified: result.filesModified,
+ processes: analysis.proposedChanges.processes
+ }
+ };
+}
+
/**
* Get the standard PM2 template for reference
*/
diff --git a/server/services/pm2Standardizer.test.js b/server/services/pm2Standardizer.test.js
index 23a0b39c4a..a47ef240ee 100644
--- a/server/services/pm2Standardizer.test.js
+++ b/server/services/pm2Standardizer.test.js
@@ -1,5 +1,5 @@
-import { describe, it, expect } from 'vitest';
-import { reassignCollidingPorts } from './pm2Standardizer.js';
+import { describe, it, expect, vi } from 'vitest';
+import { reassignCollidingPorts, runStandardizeFlow } from './pm2Standardizer.js';
describe('reassignCollidingPorts', () => {
it('moves a process off a taken port and rewrites both env.PORT and --port args', () => {
@@ -100,3 +100,102 @@ describe('reassignCollidingPorts', () => {
expect(processes[0].env.RETRIES).toBe(5173); // not a port key
});
});
+
+describe('runStandardizeFlow', () => {
+ // A successful analysis plan shape (only the fields the flow reads).
+ const okAnalysis = {
+ success: true,
+ proposedChanges: { processes: [{ name: 'srv' }], strayPorts: [{ file: '.env' }] }
+ };
+
+ it('runs analyze → backup → apply and returns a success outcome with the backup branch', async () => {
+ const analyze = vi.fn().mockResolvedValue(okAnalysis);
+ const backup = vi.fn().mockResolvedValue({ success: true, branch: 'portos-backup-123' });
+ const apply = vi.fn().mockResolvedValue({ success: true, filesModified: ['ecosystem.config.cjs'], errors: [] });
+
+ const outcome = await runStandardizeFlow('/repo', 'prov-1', { analyze, backup, apply });
+
+ expect(analyze).toHaveBeenCalledWith('/repo', 'prov-1');
+ // Step 3 must skip its own backup since step 2 already made one.
+ expect(apply).toHaveBeenCalledWith('/repo', okAnalysis, { skipBackup: true });
+ expect(outcome).toEqual({
+ success: true,
+ result: {
+ backupBranch: 'portos-backup-123',
+ filesModified: ['ecosystem.config.cjs'],
+ processes: okAnalysis.proposedChanges.processes
+ }
+ });
+ });
+
+ it('emits ordered step + analyzed callbacks while it runs', async () => {
+ const steps = [];
+ const analyzed = vi.fn();
+ await runStandardizeFlow('/repo', null, {
+ onStep: ({ step, status }) => steps.push(`${step}:${status}`),
+ onAnalyzed: analyzed,
+ analyze: vi.fn().mockResolvedValue(okAnalysis),
+ backup: vi.fn().mockResolvedValue({ success: true, branch: 'b1' }),
+ apply: vi.fn().mockResolvedValue({ success: true, filesModified: [], errors: [] })
+ });
+
+ expect(steps).toEqual([
+ 'analyze:running', 'analyze:done',
+ 'backup:running', 'backup:done',
+ 'apply:running', 'apply:done'
+ ]);
+ expect(analyzed).toHaveBeenCalledWith({ plan: okAnalysis });
+ });
+
+ it('short-circuits with the analyze error and never backs up or applies', async () => {
+ const backup = vi.fn();
+ const apply = vi.fn();
+ const outcome = await runStandardizeFlow('/repo', null, {
+ analyze: vi.fn().mockResolvedValue({ success: false, error: 'No AI provider configured' }),
+ backup,
+ apply
+ });
+ expect(outcome).toEqual({ success: false, error: 'No AI provider configured' });
+ expect(backup).not.toHaveBeenCalled();
+ expect(apply).not.toHaveBeenCalled();
+ });
+
+ it('aborts on a dirty worktree (DIRTY_WORKTREE) before applying', async () => {
+ const apply = vi.fn();
+ const outcome = await runStandardizeFlow('/repo', null, {
+ analyze: vi.fn().mockResolvedValue(okAnalysis),
+ backup: vi.fn().mockResolvedValue({ success: false, code: 'DIRTY_WORKTREE', reason: 'uncommitted changes' }),
+ apply
+ });
+ expect(outcome).toEqual({ success: false, error: 'uncommitted changes' });
+ expect(apply).not.toHaveBeenCalled();
+ });
+
+ it('treats a non-git repo as a skipped backup and still applies (backupBranch null)', async () => {
+ const outcome = await runStandardizeFlow('/repo', null, {
+ analyze: vi.fn().mockResolvedValue(okAnalysis),
+ backup: vi.fn().mockResolvedValue({ success: false, reason: 'Not a git repository' }),
+ apply: vi.fn().mockResolvedValue({ success: true, filesModified: ['ecosystem.config.cjs'], errors: [] })
+ });
+ expect(outcome.success).toBe(true);
+ expect(outcome.result.backupBranch).toBeNull();
+ });
+
+ it('returns the joined apply errors when applying fails', async () => {
+ const outcome = await runStandardizeFlow('/repo', null, {
+ analyze: vi.fn().mockResolvedValue(okAnalysis),
+ backup: vi.fn().mockResolvedValue({ success: true, branch: 'b1' }),
+ apply: vi.fn().mockResolvedValue({ success: false, filesModified: [], errors: ['disk full', 'oops'] })
+ });
+ expect(outcome).toEqual({ success: false, error: 'disk full, oops' });
+ });
+
+ it('surfaces a thrown analyze rejection as a failed outcome', async () => {
+ const outcome = await runStandardizeFlow('/repo', null, {
+ analyze: vi.fn().mockRejectedValue(new Error('boom')),
+ backup: vi.fn(),
+ apply: vi.fn()
+ });
+ expect(outcome).toEqual({ success: false, error: 'boom' });
+ });
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index ea65ab1e26..38d85988df 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -177,7 +177,9 @@ export function initSocket(io) {
}
});
- // Handle PM2 standardization
+ // Handle PM2 standardization — the multi-step analyze→backup→apply flow
+ // lives in pm2Standardizer.runStandardizeFlow (testable + HTTP-callable);
+ // the socket handler only wires progress callbacks to socket events.
socket.on('standardize:start', async (rawData) => {
try {
const data = validateSocketData(standardizeStartSchema, rawData, socket, 'standardize:start');
@@ -185,74 +187,14 @@ export function initSocket(io) {
const { repoPath, providerId } = data;
console.log(`🔧 Starting PM2 standardization: ${repoPath}`);
- const emit = (step, status, data = {}) => {
- socket.emit('standardize:step', { step, status, data, timestamp: Date.now() });
- };
-
- // Step 1: Analyze
- emit('analyze', 'running', { message: 'Analyzing project configuration...' });
-
- const analysis = await pm2Standardizer.analyzeApp(repoPath, providerId)
- .catch(err => ({ success: false, error: err.message }));
-
- if (!analysis.success) {
- emit('analyze', 'error', { message: analysis.error });
- socket.emit('standardize:complete', { success: false, error: analysis.error });
- return;
- }
-
- emit('analyze', 'done', {
- message: `Found ${analysis.proposedChanges.processes?.length || 0} processes`,
- processes: analysis.proposedChanges.processes,
- strayPorts: analysis.proposedChanges.strayPorts
- });
-
- socket.emit('standardize:analyzed', { plan: analysis });
-
- // Step 2: Backup
- emit('backup', 'running', { message: 'Creating git backup...' });
-
- const backup = await pm2Standardizer.createGitBackup(repoPath)
- .catch(err => ({ success: false, reason: err.message }));
-
- if (backup.success) {
- emit('backup', 'done', { message: `Backup branch: ${backup.branch}`, branch: backup.branch });
- } else if (backup.code === 'DIRTY_WORKTREE') {
- emit('backup', 'error', { message: backup.reason });
- socket.emit('standardize:complete', { success: false, error: backup.reason });
- return;
- } else {
- emit('backup', 'skipped', { message: backup.reason || 'No git repository' });
- }
-
- // Step 3: Apply changes
- emit('apply', 'running', { message: 'Writing ecosystem.config.cjs...' });
-
- const result = await pm2Standardizer.applyStandardization(repoPath, analysis, { skipBackup: true })
- .catch(err => ({ success: false, errors: [err.message] }));
-
- if (result.errors?.length > 0) {
- emit('apply', 'error', { message: result.errors.join(', ') });
- socket.emit('standardize:complete', { success: false, error: result.errors.join(', ') });
- return;
- }
-
- emit('apply', 'done', {
- message: `Modified ${result.filesModified.length} files`,
- filesModified: result.filesModified
+ const outcome = await pm2Standardizer.runStandardizeFlow(repoPath, providerId, {
+ onStep: ({ step, status, data }) => {
+ socket.emit('standardize:step', { step, status, data, timestamp: Date.now() });
+ },
+ onAnalyzed: (payload) => socket.emit('standardize:analyzed', payload)
});
- // Complete — use backup branch from step 2 since step 3 skips backup
- socket.emit('standardize:complete', {
- success: true,
- result: {
- backupBranch: backup.branch || null,
- filesModified: result.filesModified,
- processes: analysis.proposedChanges.processes
- }
- });
-
- console.log(`✅ Standardization complete: ${result.filesModified.length} files modified`);
+ socket.emit('standardize:complete', outcome);
} catch (err) {
const message = err?.message ?? String(err);
console.error(`❌ Socket handler error [standardize:start]: ${message}`);
@@ -480,31 +422,25 @@ export function initSocket(io) {
}
});
- // App deploy handler — streams real-time output from deploy.sh
+ // App deploy handler — streams real-time output from deploy.sh. The
+ // app-lookup → deploy-script check → run orchestration lives in
+ // appDeployer.runDeployFlow (testable + HTTP-callable); the handler only
+ // forwards streamed frames and maps the terminal outcome to socket events.
socket.on('app:deploy', async (rawData) => {
try {
const data = validateSocketData(appDeploySchema, rawData, socket, 'app:deploy');
if (!data) return;
- const app = await appsService.getAppById(data.appId);
- if (!app) {
- socket.emit('app:deploy:error', { message: 'App not found' });
- return;
- }
-
- if (!appDeployer.hasDeployScript(app)) {
- socket.emit('app:deploy:error', { message: 'No deploy.sh found for this app' });
- return;
- }
-
- console.log(`🚀 Deploy started for ${app.name} [${data.flags.join(', ') || 'default'}]`);
- const emit = (type, payload) => {
+ const onOutput = (type, payload) => {
socket.emit(`app:deploy:${type}`, { ...payload, timestamp: Date.now() });
};
- const result = await appDeployer.deployApp(app, data.flags, emit);
- socket.emit('app:deploy:complete', { success: result.success, code: result.code });
- console.log(`${result.success ? '✅' : '❌'} Deploy ${result.success ? 'complete' : 'failed'} for ${app.name}`);
+ const outcome = await appDeployer.runDeployFlow(data.appId, data.flags, { onOutput });
+ if (!outcome.ok) {
+ socket.emit('app:deploy:error', { message: outcome.error });
+ return;
+ }
+ socket.emit('app:deploy:complete', { success: outcome.success, code: outcome.code });
} catch (err) {
const message = err?.message ?? String(err);
console.error(`❌ Socket handler error [app:deploy]: ${message}`);
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index ab2df75073..3e65b2b564 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -14,7 +14,7 @@ vi.mock('./cosEvents.js', () => ({ cosEvents: { on: vi.fn() }, emitLog: vi.fn()
vi.mock('./apps.js', () => ({ appsEvents: { on: vi.fn() }, getAppById: vi.fn(), updateApp: vi.fn() }));
vi.mock('../lib/errorHandler.js', () => ({ errorEvents: { on: vi.fn() } }));
vi.mock('./autoFixer.js', () => ({ handleErrorRecovery: vi.fn() }));
-vi.mock('./pm2Standardizer.js', () => ({ analyzeApp: vi.fn(), createGitBackup: vi.fn(), applyStandardization: vi.fn() }));
+vi.mock('./pm2Standardizer.js', () => ({ analyzeApp: vi.fn(), createGitBackup: vi.fn(), applyStandardization: vi.fn(), runStandardizeFlow: vi.fn() }));
vi.mock('./notifications.js', () => ({ notificationEvents: { on: vi.fn() } }));
vi.mock('./providerStatus.js', () => ({ providerStatusEvents: { on: vi.fn() } }));
vi.mock('./agentPersonalities.js', () => ({ agentPersonalityEvents: { on: vi.fn() } }));
@@ -55,7 +55,7 @@ vi.mock('../lib/socketValidation.js', () => ({
appDeploySchema: {}
}));
vi.mock('./appUpdater.js', () => ({ updateApp: vi.fn() }));
-vi.mock('./appDeployer.js', () => ({ hasDeployScript: vi.fn(), deployApp: vi.fn() }));
+vi.mock('./appDeployer.js', () => ({ hasDeployScript: vi.fn(), deployApp: vi.fn(), runDeployFlow: vi.fn() }));
vi.mock('../sockets/voice.js', () => ({ registerVoiceHandlers: vi.fn() }));
import { initSocket } from './socket.js';