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
refactor: split apps router into domain-focused sub-routers (#2375)
Adam Eivy1ad1927a4f58
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d50873b61a..59414d419c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -81,3 +81,4 @@- **Rounds and Music Video can now turn a reference audio file into MIDI locally via MuScriptor.** MuScriptor (github.com/muscriptor/muscriptor) is a multi-instrument audio → MIDI transcription model that runs in an opt-in venv (`INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh`, weights auto-download from HuggingFace on first use; small/medium/large tiers). A new shared service (`server/services/audioMidiTranscription.js` + the `scripts/transcribe_muscriptor.py` sidecar, same STAGE:/RESULT: wire protocol as the music-gen sidecars) exposes the kickoff/SSE/cancel job shape in both features: a Rounds reference with attached audio gains a **Transcribe MIDI** control (the resulting `.mid` lands as `references[].midiFilename` on Save, cleared with the audio like segments), and a Music Video project gains a **MIDI** toolbar button + download link (`project.midiTranscription` is persisted server-side on completion and invalidated when the audio source changes, exactly like `audioAnalysis`). When the venv isn't provisioned the kickoff 503s with the install hint instead of a bare spawn error.- **[issue-2386] ffmpeg render errors are now separated into pre-spawn and post-spawn, so a failed kill can no longer let a replacement render overlap the live process.** The music-video and timeline renderers both routed every `'error'` event through the same immediate finalizer — which released the per-project render mutex and dropped process ownership. But `'error'` fires for two very different cases: a genuine pre-spawn failure (ENOENT — the child never started, no `'close'` follows) and a *later* child-process error such as a failed kill while ffmpeg is still running. Releasing the mutex on the latter let a re-render spawn and overlap the still-live ffmpeg. Both services now track spawn state (a `'spawn'` listener sets a flag) and finalize immediately only for pre-spawn errors; a post-spawn error is recorded but retains process + project-mutex ownership until the pending `'close'` runs the sole terminal finalization. A shared `terminal` guard makes terminal handling exactly-once across the error and close paths, and both handlers wrap their body per the child-process-callback convention. Covered by new error-to-close sequence tests before and after spawn in both services.+- **[issue-2375] Split the ~1,380-line `server/routes/apps.js` into domain-focused sub-routers.** The single apps router (24+ endpoints spanning CRUD/status enrichment, PM2 lifecycle, config repair, Xcode provisioning, icon serving, task-type overrides, document git-commits, editor/folder launch, and agent history) is now assembled from nine mountable sub-routers under `server/routes/apps/` (`crud`, `lifecycle`, `viteTls`, `xcode`, `icons`, `taskTypes`, `launch`, `documents`, `agents`), mirroring the pipeline sub-router pattern. Shared plumbing (`loadApp` middleware, `pathExists`, and the port/overall-status derivation helpers previously duplicated between the list and detail endpoints) lives in one `apps/shared.js`, and the ~130-line ecosystem-config port-rewrite orchestration moved out of the PUT handler into a `server/services/appPortConfig.js` service. The `/api/apps` route contract is byte-for-byte identical (all 35 path+method pairs verified) and the oversized route test file is split along the same domain boundaries. No behavior change.diff --git a/server/index.js b/server/index.jsindex 033a499a3f..69ba0da4d5 100644--- a/server/index.js+++ b/server/index.js@@ -17,7 +17,7 @@ import appleHealthRoutes from './routes/appleHealth.js';import avatarRoutes from './routes/avatar.js';import systemHealthRoutes from './routes/systemHealth.js';import capabilitiesRoutes from './routes/capabilities.js';-import appsRoutes from './routes/apps.js';+import appsRoutes from './routes/apps/index.js';import workspaceContextsRoutes from './routes/workspaceContexts.js';import referenceReposRoutes from './routes/referenceRepos.js';import portsRoutes from './routes/ports.js';diff --git a/server/routes/apps.js b/server/routes/apps.jsdeleted file mode 100644index 282951ffb6..0000000000--- a/server/routes/apps.js+++ /dev/null@@ -1,1381 +0,0 @@-import { Router } from 'express';-import { spawn } from 'child_process';-import { readFile, writeFile, stat, access, mkdir } from 'fs/promises';-import { join, resolve, extname } from 'path';-import { PATHS, tryReadFile, readJSONFile, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';-import * as appsService from '../services/apps.js';-import { notifyAppsChanged, PORTOS_APP_ID } from '../services/apps.js';-import * as pm2Service from '../services/pm2.js';-import * as appUpdater from '../services/appUpdater.js';-import * as appBuilder from '../services/appBuilder.js';-import * as cos from '../services/cos.js';-import { logAction } from '../services/history.js';-import { z } from 'zod';-import { validateRequest, appSchema, appUpdateSchema, sanitizeTaskMetadata, documentUpdateSchema } from '../lib/validation.js';-import * as git from '../services/git.js';-import { parseCronToNextRun } from '../services/eventScheduler.js';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { parseEcosystemFromPath, usesPm2, writeEcosystemPortEdits } from '../services/streamingDetect.js';-import { checkViteHost, findViteConfig, rewriteAllowedHosts } from '../lib/viteAllowedHosts.js';-import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';-import { hasDeployScript } from '../services/appDeployer.js';-import { checkScripts, installScripts, XCODE_SCRIPT_NAMES } from '../services/xcodeScripts.js';-import { SELF_IMPROVEMENT_TASK_TYPES } from '../services/taskSchedule.js';-import { certPaths } from '../../lib/certPaths.js';--const router = Router();--// Delay before restarting PortOS itself so the JSON response reaches the client-const SELF_RESTART_RESPONSE_DELAY_MS = 500;--/** Async equivalent of existsSync — returns true if the path is accessible */-const pathExists = (p) => access(p).then(() => true).catch(() => false);--/**- * Derive uiPort from apiPort when app has dev UI but no dedicated prod UI port- * (prod UI is served by the API server in these cases).- */-function deriveUiPort(uiPort, apiPort, devUiPort) {- if (!uiPort && apiPort && devUiPort) return apiPort;- return uiPort;-}--/**- * Middleware to load app by :id param and attach to req.loadedApp- * Throws 404 if not found, eliminating repeated null checks across routes- */-const loadApp = asyncHandler(async (req, res, next) => {- const app = await appsService.getAppById(req.params.id);- if (!app) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }- req.loadedApp = app;- next();-});--// GET /api/apps - List all apps-router.get('/', asyncHandler(async (req, res) => {- const apps = await appsService.getAllApps();-- // 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.- // listProcessesStrict returns `null` on a failed read (vs `[]` for a- // successful read with no processes) — track those homes so we report- // `unknown` (status unavailable) instead of `not_started` (confidently not- // running) for their apps. See getAppStatuses() in the service for the same- // absent-vs-empty distinction.- const pm2Maps = new Map();- const failedHomes = new Set();- for (const pm2Home of pm2HomeGroups.keys()) {- const processes = await pm2Service.listProcessesStrict(pm2Home);- if (processes === null) {- failedHomes.add(pm2Home);- pm2Maps.set(pm2Home, new Map());- } else {- 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) => {- // Non-PM2 apps skip PM2 enrichment entirely- if (!usesPm2(app.type)) {- return { ...app, pm2Status: {}, overallStatus: 'n/a', hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) };- }-- const pm2Home = app.pm2Home || null;- const pm2Map = pm2Maps.get(pm2Home) || new Map();- const homeFailed = failedHomes.has(pm2Home);-- const statuses = {};- for (const processName of app.pm2ProcessNames || []) {- const pm2Proc = pm2Map.get(processName);- // A failed PM2 read leaves status genuinely unknown — don't claim- // `not_found` (which the UI reads as "registered but never launched").- statuses[processName] = pm2Proc- ?? { name: processName, status: homeFailed ? 'unknown' : 'not_found', pm2_env: null };- }-- // Compute overall status. A failed PM2 home short-circuits to `unknown`- // with a `degraded` flag rather than collapsing to `not_started`.- const statusValues = Object.values(statuses);- let overallStatus = 'unknown';- if (homeFailed) {- overallStatus = 'unknown';- } else if (statusValues.some(s => s.status === 'online')) {- overallStatus = 'online';- } else if (statusValues.some(s => s.status === 'stopped')) {- overallStatus = 'stopped';- } else if (statusValues.every(s => s.status === 'not_found')) {- overallStatus = 'not_started';- }-- // Auto-populate processes from ecosystem config if not already set- let processes = app.processes;- if ((!processes || processes.length === 0) && await pathExists(app.repoPath)) {- const parsed = await parseEcosystemFromPath(app.repoPath).catch(() => ({ processes: [] }));- processes = parsed.processes;- }-- // Auto-derive uiPort/apiPort/devUiPort from processes when not explicitly set- let { uiPort, apiPort, devUiPort } = app;- if (!uiPort && processes?.length) {- const uiProc = processes.find(p => p.ports?.ui);- if (uiProc) uiPort = uiProc.ports.ui;- }- if (!apiPort && processes?.length) {- const apiProc = processes.find(p => p.ports?.api);- if (apiProc) apiPort = apiProc.ports.api;- }- if (!devUiPort && processes?.length) {- const devUiProc = processes.find(p => p.ports?.devUi);- if (devUiProc) devUiPort = devUiProc.ports.devUi;- }- uiPort = deriveUiPort(uiPort, apiPort, devUiPort);-- return {- ...app,- processes,- uiPort,- devUiPort,- apiPort,- pm2Status: statuses,- overallStatus,- degraded: homeFailed,- hasDeployScript: hasDeployScript(app),- xcodeScripts: checkScripts(app)- };- }));-- res.json(enriched);-}));--// GET /api/apps/:id - Get single app-router.get('/:id', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- // Non-PM2 apps skip PM2 status- let statuses = {};- let overallStatus = 'n/a';-- let degraded = false;- if (usesPm2(app.type)) {- // getAppStatusStrict returns `null` when the PM2 read failed (vs a real- // status object). A failed read is genuinely unknown, not "not running" —- // mark `degraded` so the detail UI can offer refresh-to-retry rather than a- // misleading Start. Mirrors the list endpoint's `degraded`.- // Read each process's PM2 status in parallel — a detail view of a- // multi-process app would otherwise serialize one IPC round-trip per process.- const reads = await Promise.all(- (app.pm2ProcessNames || []).map(async (processName) => ({- processName,- status: await pm2Service.getAppStatusStrict(processName, app.pm2Home),- })),- );- for (const { processName, status } of reads) {- if (status === null) {- degraded = true;- statuses[processName] = { name: processName, status: 'unknown', pm2_env: null };- } else {- statuses[processName] = status;- }- }-- // Compute overall status (same logic as list endpoint). A degraded read- // short-circuits to `unknown` rather than collapsing to `not_started`.- const statusValues = Object.values(statuses);- overallStatus = 'unknown';- if (degraded) {- overallStatus = 'unknown';- } else if (statusValues.some(s => s.status === 'online')) {- overallStatus = 'online';- } else if (statusValues.some(s => s.status === 'stopped')) {- overallStatus = 'stopped';- } else if (statusValues.every(s => s.status === 'not_found')) {- overallStatus = 'not_started';- }- }-- // Auto-derive uiPort/apiPort/devUiPort from processes when not explicitly set- let { uiPort, apiPort, devUiPort } = app;- const processes = app.processes || [];- if (!uiPort && processes.length) {- const uiProc = processes.find(p => p.ports?.ui);- if (uiProc) uiPort = uiProc.ports.ui;- }- if (!apiPort && processes.length) {- const apiProc = processes.find(p => p.ports?.api);- if (apiProc) apiPort = apiProc.ports.api;- }- if (!devUiPort && processes.length) {- const devUiProc = processes.find(p => p.ports?.devUi);- if (devUiProc) devUiPort = devUiProc.ports.devUi;- }- uiPort = deriveUiPort(uiPort, apiPort, devUiPort);-- // Read version from app's package.json if available- let appVersion = null;- if (app.repoPath) {- const pkg = await readJSONFile(join(app.repoPath, 'package.json'), null, { logError: false });- appVersion = pkg?.version || null;- }-- res.json({ ...app, uiPort, devUiPort, apiPort, overallStatus, degraded, pm2Status: statuses, appVersion, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });-}));--// POST /api/apps/:id/xcode-scripts/install - Install missing management scripts-// Restrict the request payload to the known, fixed set of script names so that-// arbitrary or oversized arrays are rejected at the validation layer.-const installScriptsSchema = z.object({- scripts: z.array(z.enum(XCODE_SCRIPT_NAMES)).min(1).max(XCODE_SCRIPT_NAMES.length)-});-router.post('/:id/xcode-scripts/install', loadApp, asyncHandler(async (req, res) => {- const { scripts } = validateRequest(installScriptsSchema, req.body);- if (!req.loadedApp.repoPath || !await pathExists(req.loadedApp.repoPath)) {- throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });- }- const result = await installScripts(req.loadedApp, scripts);- if (result.errors.length && !result.installed.length) {- throw new ServerError(result.errors.join(', '), { status: 400, code: 'INSTALL_FAILED' });- }- res.json(result);-}));--// POST /api/apps/:id/upgrade-tls - Copy the tailscale-https helper into the target app's-// repo and record tlsPort in apps.json so the Launch button prefers HTTPS. The app still-// needs to be edited manually to call createTailscaleServers() — we return an example-// snippet in the response so the frontend can surface it. Refuse to overwrite an existing-// helper unless `force: true` is set; this way a user who has customized their copy keeps it.-const upgradeTlsSchema = z.object({- tlsPort: z.number().int().min(1).max(65535),- force: z.boolean().optional()-});-router.post('/:id/upgrade-tls', loadApp, asyncHandler(async (req, res) => {- const { tlsPort, force } = validateRequest(upgradeTlsSchema, req.body);- const app = req.loadedApp;- if (app.id === PORTOS_APP_ID) {- throw new ServerError('PortOS itself already uses the helper — nothing to upgrade', {- status: 400, code: 'ALREADY_UPGRADED'- });- }- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });- }- const sourcePath = join(PATHS.root, 'lib', 'tailscale-https.js');- const targetDir = join(app.repoPath, 'lib');- const targetPath = join(targetDir, 'tailscale-https.js');-- const alreadyExists = await pathExists(targetPath);- if (alreadyExists && !force) {- throw new ServerError(- 'A tailscale-https.js already exists in the target app. Pass force:true to overwrite.',- { status: 409, code: 'ALREADY_EXISTS' }- );- }-- const helperSource = await readFile(sourcePath, 'utf-8');- await atomicWrite(targetPath, helperSource);-- await appsService.updateApp(app.id, { tlsPort });-- const snippet = [- `// In your server entry, replace the direct http.createServer(app).listen(...) with:`,- `import { createTailscaleServers, watchCertReload } from './lib/tailscale-https.js';`,- ``,- `const CERT_DIR = process.env.CERT_DIR || '/path/to/data/certs'; // shared with PortOS`,- `const { server, mirror, httpsEnabled } = createTailscaleServers(app, { certDir: CERT_DIR });`,- `// io.attach(server); if (mirror) io.attach(mirror); // when using Socket.IO`,- `server.listen(${tlsPort}, '0.0.0.0');`,- `// Optional: bind the HTTP mirror on a port of your choosing (127.0.0.1 only).`,- `// if (mirror) mirror.listen(<your-mirror-port>, '127.0.0.1');`,- `if (httpsEnabled) watchCertReload(server, CERT_DIR);`- ].join('\n');-- res.json({- ok: true,- helperPath: targetPath,- overwrote: alreadyExists,- tlsPort,- snippet,- certDirHint: certPaths(PATHS.data).dir,- note: 'Point your app at the PortOS cert dir (or symlink it) so apps share the single Tailscale cert.'- });-}));--// GET /api/apps/:id/vite-host-check?host=<hostname> - Report whether the app's-// Vite dev server would accept requests for `host` (the Tailscale MagicDNS / IP-// name PortOS is served under). Vite ≥5 blocks unknown hosts, so launching an-// app's Dev UI over Tailscale fails until that host is allow-listed. This drives-// the Dev-UI launch guard and the remediation UI in the app detail view.-router.get('/:id/vite-host-check', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const host = typeof req.query.host === 'string' ? req.query.host.trim() : '';- const extraDirs = (app.processes || []).map((p) => p.cwd).filter(Boolean);- const status = await checkViteHost(app.repoPath, host, { extraDirs });- res.json({ host, ...status });-}));--// POST /api/apps/:id/fix-vite-hosts - Remediate the Vite allowedHosts block.-// mode 'allow-all' (default): deterministically rewrite the app's vite.config-// to `server.allowedHosts: true`. Safe for a private Tailscale network and-// the most reliable fix; bails (422) when the config shape is too unusual to-// edit without risking corruption, steering the user to the AI path.-// mode 'ai': spawn a CoS agent that edits the app's vite.config in its OWN-// repo (honoring the Scope Boundary) — handles arbitrary config shapes and-// can create a vite.config when none exists.-const fixViteHostsSchema = z.object({- mode: z.enum(['allow-all', 'ai']).default('allow-all'),- host: z.string().trim().optional()-});-router.post('/:id/fix-vite-hosts', loadApp, asyncHandler(async (req, res) => {- const { mode, host } = validateRequest(fixViteHostsSchema, req.body);- const app = req.loadedApp;- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });- }- const extraDirs = (app.processes || []).map((p) => p.cwd).filter(Boolean);- const config = await findViteConfig(app.repoPath, { extraDirs });-- if (mode === 'ai') {- if (!cos.isRunning()) {- throw new ServerError(- 'CoS is not running — start it to use AI remediation, or use the automatic fix.',- { status: 409, code: 'COS_NOT_RUNNING' }- );- }- const where = config ? config.path : `${app.repoPath} (no vite.config found — create one)`;- const task = await cos.addTask({- description: `Allow the Tailscale host in ${app.name}'s Vite config so its Dev UI loads`,- priority: 'MEDIUM',- app: app.id,- approvalRequired: true,- context: [- `The app "${app.name}" is launched through PortOS over a Tailscale MagicDNS hostname` +- (host ? ` ("${host}")` : '') + '.',- 'Launching its Vite Dev UI fails with: "Blocked request. This host is not allowed."',- `Fix: edit ${where} so the dev server's \`server.allowedHosts\` accepts that host.`,- 'Prefer `server.allowedHosts: true` (allow all — this app runs only on a private Tailscale network),',- 'or add the specific host plus a leading-dot `.ts.net` suffix entry. Leave the rest of the config intact.',- 'If no vite config exists, create a minimal vite.config.js that sets server.allowedHosts.'- ].join('\n')- }, 'internal');- return res.json({ ok: true, mode: 'ai', taskId: task.id, configPath: config?.path || null });- }-- // mode === 'allow-all': deterministic rewrite.- if (!config) {- throw new ServerError(- 'No vite.config found to edit automatically — use AI remediation, which can create one.',- { status: 422, code: 'NO_VITE_CONFIG' }- );- }- const rewrite = rewriteAllowedHosts(config.content);- if (!rewrite.ok) {- throw new ServerError(- `Could not safely auto-edit ${config.filename}: ${rewrite.reason}. Use AI remediation instead.`,- { status: 422, code: 'AUTO_FIX_UNSAFE' }- );- }- await atomicWrite(config.path, rewrite.content);- res.json({- ok: true,- mode: 'allow-all',- configPath: config.path,- filename: config.filename,- strategy: rewrite.strategy,- note: 'Restart the app (or its Vite dev server) for the change to take effect.'- });-}));--// GET /api/apps/:id/icon - Serve the app's detected icon image-router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- // Use stored appIconPath, or detect on-the-fly. Stored SVGs that embed an- // external <image href="..."> render blank under the route's `default-src- // 'none'` CSP, so re-detect when the cached path is an unusable SVG (e.g.- // PortOS's own favicon.svg, which wraps a /portos-logo.png reference) —- // otherwise installs that resolved an icon BEFORE the detector learned to- // skip these stay broken until the user manually re-detects.- let iconPath = app.appIconPath;- const stale =- !iconPath ||- !await pathExists(iconPath) ||- (extname(iconPath).toLowerCase() === '.svg' && !await isUsableSvg(iconPath));- if (stale) {- iconPath = await detectAppIcon(app.repoPath, app.type);- if (iconPath && iconPath !== app.appIconPath) {- await appsService.updateApp(app.id, { appIconPath: iconPath });- }- }-- if (!iconPath || !await pathExists(iconPath)) {- throw new ServerError('No app icon found', { status: 404 });- }-- const contentType = getIconContentType(iconPath);- const iconStat = await stat(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));- if (!iconStat) throw new ServerError('No app icon found', { status: 404 });- const etag = `W/"${iconStat.mtimeMs.toString(36)}-${iconStat.size.toString(36)}"`;-- res.set('Content-Type', contentType);- res.set('Cache-Control', 'public, max-age=3600');- res.set('ETag', etag);- res.set('X-Content-Type-Options', 'nosniff');- if (contentType === 'image/svg+xml') {- res.set('Content-Disposition', 'inline; filename="icon.svg"');- res.set('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'");- }-- const ifNoneMatch = req.headers['if-none-match'];- if (ifNoneMatch) {- const tags = ifNoneMatch.split(',').map(v => v.trim());- if (tags.includes('*') || tags.includes(etag)) {- return res.status(304).end();- }- }-- const iconData = await readFile(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));- if (!iconData) throw new ServerError('No app icon found', { status: 404 });- res.send(iconData);-}));--// POST /api/apps - Create new app-router.post('/', asyncHandler(async (req, res, next) => {- const data = validateRequest(appSchema, req.body);-- // Detect app icon before creation to avoid a double write- if (data.repoPath) {- const detectedIcon = await detectAppIcon(data.repoPath, data.type);- if (detectedIcon) data.appIconPath = detectedIcon;- }-- const app = await appsService.createApp(data);- res.status(201).json(app);-}));--// PUT /api/apps/:id - Update app-router.put('/:id', asyncHandler(async (req, res, next) => {- const data = validateRequest(appUpdateSchema, req.body);-- // Only port edits need the canonical-config write-back below; snapshot the- // pre-update ports just for those so ordinary updates (rename, archive,- // jira/datadog) don't pay the extra read + fs stat. tlsPort is omitted: it's- // synthetic (derived from cert presence / upgradeAppTls), never a literal in- // ecosystem.config.cjs, so there's nothing to rewrite for it.- const PORT_KEYS = ['apiPort', 'uiPort', 'devUiPort'];- const hasPortUpdate = PORT_KEYS.some(key => key in data);- const existing = hasPortUpdate ? await appsService.getAppById(req.params.id) : null;-- // Port fields in apps.json are *derived* from ecosystem.config.cjs (the- // source of truth PM2 reads). Persist the change to the canonical config- // FIRST, before the derived registry: an unreadable/unwritable config then- // surfaces as a failed request instead of a 200 that leaves apps.json and- // PM2 disagreeing (the write throws and bubbles to the error middleware).- if (existing && usesPm2(existing.type) && await pathExists(existing.repoPath)) {- // Diff the submitted ports against the ACTUAL config values (not apps.json,- // whose top-level fields may be stale or absent for derived ports). This- // is the single source of truth for both "did it change" and "what's the- // old literal to rewrite": EditAppModal submits every field even on a- // rename, so a value equal to the config's current port is a no-op echo,- // and a value that differs is a genuine edit to persist.- const { processes: cfgProcs } = await parseEcosystemFromPath(existing.repoPath);- const LABEL_BY_KEY = { apiPort: 'api', uiPort: 'ui', devUiPort: 'devUi' };- const currentPort = {};- const procNameByKey = {}; // which process block owns each label (for targeted rewrites)- for (const proc of cfgProcs || []) {- for (const [key, label] of Object.entries(LABEL_BY_KEY)) {- if (currentPort[key] === undefined && Number.isInteger(proc.ports?.[label])) {- currentPort[key] = proc.ports[label];- procNameByKey[key] = proc.name;- }- }- }- // Count current values so a value-keyed rewrite never fires on a number- // shared by another port field (e.g. uiPort derived from apiPort, both- // 6000) — that would rewrite every occurrence and clobber the field the- // user didn't touch. Such a value can't be split by value alone; it falls- // through to the per-process-label-targeted rewrite below.- const valueCounts = new Map();- for (const key of PORT_KEYS) {- const v = currentPort[key];- if (Number.isInteger(v)) valueCounts.set(v, (valueCounts.get(v) || 0) + 1);- }- // A port is "changed" when the submitted value differs from the config's- // current value for that label. A field the config doesn't define has no- // literal to rewrite, so it isn't treated as a config edit here.- const changedKeys = PORT_KEYS.filter(key =>- Number.isInteger(currentPort[key]) && Number.isInteger(data[key]) && data[key] !== currentPort[key]);-- // Served-by-API detection. When an app has an API process plus a Vite dev- // UI but no literal `ports.ui`, the prod UI is served by the API server, so- // the `uiPort` is *derived* (= apiPort) and CANNOT be set independently —- // there's no separate UI port literal in the config to rewrite. The edit- // drawer always submits every port field and never syncs the UI field to a- // changed API field, so an API-only edit arrives as `{ apiPort: <new>,- // uiPort: <old derived> }`. We can't distinguish that stale echo from a- // deliberate (impossible) independent UI change, so the only coherent- // behavior is to IGNORE the submitted uiPort entirely and pin the stored- // value to the derived port (= the post-edit API port). That tracks the API- // port on every save, never reverts, and never spuriously 422s the common- // API-edit path. The user changes this UI port by changing the API port.- const effectiveApiPort = Number.isInteger(data.apiPort) ? data.apiPort : currentPort.apiPort;- const derivedUiPort = deriveUiPort(undefined, effectiveApiPort, currentPort.devUiPort);- const uiIsDerived = currentPort.uiPort === undefined && Number.isInteger(derivedUiPort);- const remap = [];- const targetedEdits = []; // shared-value keys: rewritten by process + label- for (const key of changedKeys) {- const oldPort = currentPort[key]; // guaranteed integer by the filter above- // Value shared with another field (can't disambiguate by value): target- // the specific process block + label so the edit lands on exactly the- // port the user touched, not every occurrence of the shared literal.- if (valueCounts.get(oldPort) > 1 && procNameByKey[key]) {- targetedEdits.push({ processName: procNameByKey[key], label: LABEL_BY_KEY[key], oldPort, newPort: data[key] });- continue;- }- remap.push([oldPort, data[key]]);- }-- // Pin the stored uiPort to the derived value for served-by-API apps (see- // above). This both overwrites the drawer's echoed/stale UI field and keeps- // the stored value tracking apiPort — deleting `data.uiPort` would NOT be- // enough, since updateApp merges omitted fields over the existing record, so- // a stale explicit `uiPort` from an earlier refresh would survive (truthy)- // and block re-derivation (after API 6000→7000 the GET path would keep- // returning 6000). Writing the derived value self-corrects on every save.- // (uiIsDerived is computed from the parsed CONFIG, not apps.json, so it's- // true even when apps.json already holds a stale explicit value.)- if (uiIsDerived) {- data.uiPort = derivedUiPort;- }-- // Persist the value-keyed remap (distinct ports) and the targeted edits- // (shared-value ports) in ONE atomic write. Doing them as two separate- // writes would let the value-keyed pass land on disk before a later- // unpersistable targeted edit forces the 422 below — leaving config- // partially changed for a rejected request. writeEcosystemPortEdits- // computes both rewrites in memory and writes only when nothing is- // unpersistable.- const result = changedKeys.length > 0- ? await writeEcosystemPortEdits(existing.repoPath, remap, targetedEdits)- : { changed: false, remapApplied: false, applied: [], unapplied: [] };- if (result.changed) {- const remapMsg = result.remapApplied ? remap.map(([o, n]) => `${o}→${n}`).join(', ') : '';- const tgtMsg = targetedEdits.map(e => `${e.label} ${e.oldPort}→${e.newPort}`).join(', ');- console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${[remapMsg, tgtMsg].filter(Boolean).join(', ')} (restart the app to apply)`);- }-- // Honesty gate: if the user changed a port we could NOT write to the- // source-of-truth config, reject the whole update rather than persist a- // registry value PM2 will contradict (and the next refresh will revert).- // `remap.length && !remapApplied` catches value-keyed pairs whose literal- // wasn't found; `unapplied` catches process/label edits that didn't match.- // On any unpersistable targeted edit the writer persists nothing, so this- // reject leaves the config untouched.- const valueKeyedFailed = remap.length > 0 && !result.remapApplied;- const targetedFailed = (result.unapplied || []).length > 0;- if (changedKeys.length > 0 && (valueKeyedFailed || targetedFailed)) {- throw new ServerError(- `Could not persist port change to ${existing.name}'s ecosystem config — the port is derived from process config or is not a literal value. Edit the ecosystem.config.cjs directly to change this port.`,- { status: 422, code: 'PORT_NOT_PERSISTABLE' }- );- }- }-- // layeredIntelligence must go through the dedicated merge helper — the generic- // updateApp shallow-REPLACES the nested object, so a partial patch like- // { layeredIntelligence: { enabled: true } } would wipe stored sources /- // allowedScopes / providerId / lastRunAt. Pull it out, apply the rest, then- // merge-apply the config so untouched fields are preserved.- const { layeredIntelligence: liUpdate, ...rest } = data;- const app = await appsService.updateApp(req.params.id, rest);-- if (!app) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }-- if (liUpdate !== undefined) {- const merged = await appsService.updateAppLayeredIntelligence(req.params.id, liUpdate);- res.json(merged || app);- return;- }-- res.json(app);-}));--// DELETE /api/apps/:id - Delete app (PortOS baseline cannot be deleted)-router.delete('/:id', asyncHandler(async (req, res, next) => {- if (req.params.id === PORTOS_APP_ID) {- throw new ServerError('PortOS baseline app cannot be deleted', { status: 403, code: 'PROTECTED' });- }-- const deleted = await appsService.deleteApp(req.params.id);-- if (!deleted) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }-- res.status(204).send();-}));--// POST /api/apps/:id/archive - Archive app (exclude from COS tasks)-router.post('/:id/archive', asyncHandler(async (req, res) => {- if (req.params.id === PORTOS_APP_ID) {- throw new ServerError('PortOS baseline app cannot be archived', { status: 403, code: 'PROTECTED' });- }-- const app = await appsService.archiveApp(req.params.id);-- if (!app) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }-- console.log(`📦 Archived app: ${app.name}`);- notifyAppsChanged('archive');- res.json(app);-}));--// POST /api/apps/:id/unarchive - Unarchive app (include in COS tasks)-router.post('/:id/unarchive', asyncHandler(async (req, res) => {- const app = await appsService.unarchiveApp(req.params.id);-- if (!app) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }-- console.log(`📤 Unarchived app: ${app.name}`);- notifyAppsChanged('unarchive');- res.json(app);-}));--// PUT /api/apps/bulk-task-type/:taskType - Enable/disable a task type for all active apps-router.put('/bulk-task-type/:taskType', asyncHandler(async (req, res) => {- const { enabled } = req.body;- if (typeof enabled !== 'boolean') {- throw new ServerError('enabled (boolean) is required', { status: 400, code: 'VALIDATION_ERROR' });- }- if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {- throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });- }-- const result = await appsService.bulkUpdateAppTaskTypeOverride(req.params.taskType, { enabled });- console.log(`📋 Bulk ${enabled ? 'enabled' : 'disabled'} task type ${req.params.taskType} for ${result.count} apps`);- res.json({ success: true, taskType: req.params.taskType, enabled, appsUpdated: result.count });-}));--// POST /api/apps/detect-icons - Detect and persist app icons for all apps-router.post('/detect-icons', asyncHandler(async (req, res) => {- const apps = await appsService.getAllApps();- let detected = 0;-- for (const app of apps) {- if (!app.repoPath || !await pathExists(app.repoPath)) continue;- // Skip apps that already have a valid icon path- if (app.appIconPath && await pathExists(app.appIconPath)) continue;-- const iconPath = await detectAppIcon(app.repoPath, app.type);- if (iconPath) {- await appsService.updateApp(app.id, { appIconPath: iconPath });- detected++;- console.log(`🎨 Detected icon for ${app.name}: ${iconPath.split('/').pop()}`);- }- }-- if (detected > 0) notifyAppsChanged('detect-icons');- console.log(`🎨 Icon detection complete: ${detected}/${apps.length} apps`);- res.json({ success: true, detected, total: apps.length });-}));--// POST /api/apps/:id/detect-icon - Detect and persist app icon for a single app-router.post('/:id/detect-icon', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repoPath is missing or inaccessible', { status: 400, code: 'INVALID_REPO_PATH' });- }-- const iconPath = await detectAppIcon(app.repoPath, app.type);- if (!iconPath) {- console.log(`🎨 No icon detected for ${app.name}`);- res.json({ success: true, detected: false, appIconPath: null });- return;- }-- await appsService.updateApp(app.id, { appIconPath: iconPath });- notifyAppsChanged('detect-icon');- console.log(`🎨 Detected icon for ${app.name}: ${iconPath.split('/').pop()}`);- res.json({ success: true, detected: true, appIconPath: iconPath });-}));--// GET /api/apps/:id/task-types - Get per-app task type overrides-router.get('/:id/task-types', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const overrides = await appsService.getAppTaskTypeOverrides(app.id);- res.json({ appId: app.id, appName: app.name, taskTypeOverrides: overrides });-}));--// GET /api/apps/:id/work-tracker - Resolve where this app's autonomous work-// items live (PLAN.md / GitHub / GitLab / JIRA). 'auto' resolves from the git-// origin host; see server/lib/workTracker.js. Read-only — the value itself is-// saved through the generic PUT /api/apps/:id (appUpdateSchema.workTracker).-router.get('/:id/work-tracker', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const info = await appsService.getAppWorkTracker(app.id);- res.json({ appId: app.id, appName: app.name, ...info });-}));--// GET /api/apps/:id/layered-intelligence - Effective Layered Intelligence config-// for this app (the self-improvement loop). Merges the app's stored partial-// config over the shipped defaults so the UI always renders a complete, safe-// config — including the isPortos-derived scope set. Read-only; the value is-// saved through PUT /api/apps/:id (layeredIntelligence goes via the dedicated-// merge helper there). See server/services/layeredIntelligence.js.-router.get('/:id/layered-intelligence', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const config = await appsService.getAppLayeredIntelligenceConfig(app.id);- res.json({ appId: app.id, appName: app.name, isPortos: app.id === PORTOS_APP_ID, config });-}));--// PUT /api/apps/:id/task-types/all - Toggle all task types for an app-router.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {- const { enabled } = req.body;- if (typeof enabled !== 'boolean') {- throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });- }- const result = await appsService.toggleAllAppTaskTypes(req.params.id, enabled);- if (!result) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }- console.log(`📋 ${enabled ? 'Enabled' : 'Disabled'} all task types for ${result.name}`);- res.json({ success: true, appId: result.id, taskTypeOverrides: result.taskTypeOverrides || {} });-}));--// PUT /api/apps/:id/task-types/:taskType - Update a task type override for an app-router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {- const { enabled, interval, intervalMs, providerId, model, taskMetadata } = req.body;- if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {- throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });- }- if (enabled !== undefined && typeof enabled !== 'boolean') {- throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });- }- if (typeof enabled !== 'boolean' && interval === undefined && intervalMs === undefined &&- providerId === undefined && model === undefined && taskMetadata === undefined) {- throw new ServerError('enabled (boolean), interval (string|null), intervalMs (number|null), providerId (string|null), model (string|null), or taskMetadata (object|null) required', { status: 400, code: 'VALIDATION_ERROR' });- }-- // Per-app scheduling fields for handler-backed tasks (layered-intelligence).- // `null`/'' clears back to inherit; a numeric intervalMs must be a positive- // finite number (a sub-daily cadence the string interval enum can't express).- if (intervalMs !== undefined && intervalMs !== null) {- if (typeof intervalMs !== 'number' || !Number.isFinite(intervalMs) || intervalMs <= 0) {- throw new ServerError('intervalMs must be a positive number or null', { status: 400, code: 'VALIDATION_ERROR' });- }- }- if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {- throw new ServerError('providerId must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });- }- if (model !== undefined && model !== null && typeof model !== 'string') {- throw new ServerError('model must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });- }-- // Validate and sanitize taskMetadata to allowed agent-option keys only- let sanitizedTaskMetadata;- if (taskMetadata === undefined) {- sanitizedTaskMetadata = undefined;- } else if (taskMetadata === null) {- sanitizedTaskMetadata = null;- } else {- if (typeof taskMetadata !== 'object' || Array.isArray(taskMetadata)) {- throw new ServerError('taskMetadata must be an object or null', { status: 400, code: 'VALIDATION_ERROR' });- }- sanitizedTaskMetadata = sanitizeTaskMetadata(taskMetadata);- if (sanitizedTaskMetadata === null) {- throw new ServerError('Invalid taskMetadata: unrecognized keys or values', { status: 400, code: 'VALIDATION_ERROR' });- }- }-- // Validate interval against allowed values (also accepts 5-field cron expressions)- if (interval !== undefined) {- // 'custom' pairs with a numeric intervalMs (handler-backed tasks with a- // sub-daily per-app cadence); the scheduler's CUSTOM branch reads intervalMs.- const allowedIntervals = ['rotation', 'daily', 'weekly', 'once', 'on-demand', 'custom'];- if (interval !== null && typeof interval === 'string') {- const isCron = interval.trim().split(/\s+/).length === 5;- if (!isCron && !allowedIntervals.includes(interval)) {- throw new ServerError('interval must be one of rotation|daily|weekly|once|on-demand|custom, a cron expression, or null', { status: 400, code: 'VALIDATION_ERROR' });- }- if (isCron) {- // Validate syntax and field ranges (parseCronToNextRun throws on invalid expressions)- // Note: null return means no match within search window (e.g. leap day) -- not invalid- parseCronToNextRun(interval, new Date(), 'UTC');- }- } else if (interval !== null) {- throw new ServerError('interval must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });- }- }-- const result = await appsService.updateAppTaskTypeOverride(req.params.id, req.params.taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata: sanitizedTaskMetadata });- if (!result) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }-- const action = typeof enabled === 'boolean' ? (enabled ? 'Enabled' : 'Disabled') : 'Updated interval for';- console.log(`📋 ${action} task type ${req.params.taskType} for ${result.name}`);- res.json({ success: true, appId: result.id, taskType: req.params.taskType, enabled, interval, taskTypeOverrides: result.taskTypeOverrides || {} });-}));--// POST /api/apps/:id/start - Start app via PM2-router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!usesPm2(app.type)) {- throw new ServerError(`${app.type} apps cannot be started via PM2`, { status: 400, code: 'NOT_PM2_APP' });- }-- const processNames = app.pm2ProcessNames || [app.name.toLowerCase().replace(/\s+/g, '-')];-- // Check if ecosystem config exists - prefer using it for proper env var handling- const ecosystemChecks = await Promise.all(- ['ecosystem.config.cjs', 'ecosystem.config.js'].map(f => pathExists(`${app.repoPath}/${f}`))- );- const hasEcosystem = ecosystemChecks.some(Boolean);-- let results = {};-- if (hasEcosystem) {- // Use ecosystem config for proper env/port configuration- // 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) {- results[name] = result;- }- } else {- // Fallback to command-based start for apps without ecosystem config- const commands = app.startCommands || ['npm run dev'];- for (let i = 0; i < processNames.length; i++) {- const name = processNames[i];- const command = commands[i] || commands[0];- const result = await pm2Service.startWithCommand(name, app.repoPath, command)- .catch(err => ({ success: false, error: err.message }));- results[name] = result;- }- }-- const allSuccess = Object.values(results).every(r => r.success !== false);- await logAction('start', app.id, app.name, { processNames }, allSuccess);- notifyAppsChanged('start');-- res.json({ success: true, results });-}));--// POST /api/apps/:id/stop - Stop app-router.post('/:id/stop', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!usesPm2(app.type)) {- throw new ServerError(`${app.type} apps cannot be stopped via PM2`, { status: 400, code: 'NOT_PM2_APP' });- }-- const results = {};-- for (const name of app.pm2ProcessNames || []) {- const result = await pm2Service.stopApp(name, app.pm2Home)- .catch(err => ({ success: false, error: err.message }));- results[name] = result;- }-- const allSuccess = Object.values(results).every(r => r.success !== false);- await logAction('stop', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);- notifyAppsChanged('stop');-- res.json({ success: true, results });-}));--// POST /api/apps/:id/restart - Restart app-router.post('/:id/restart', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!usesPm2(app.type)) {- throw new ServerError(`${app.type} apps cannot be restarted via PM2`, { status: 400, code: 'NOT_PM2_APP' });- }-- // Self-restart: respond first, then restart after a delay so the response reaches the client- if (app.id === PORTOS_APP_ID) {- await logAction('restart', app.id, app.name, { processNames: app.pm2ProcessNames }, true);- notifyAppsChanged('restart');- res.json({ success: true, selfRestart: true });- setTimeout(async () => {- console.log('🔄 Self-restart: restarting PortOS processes');- for (const name of app.pm2ProcessNames || []) {- await pm2Service.restartApp(name, app.pm2Home)- .catch(err => console.error(`❌ Self-restart failed for ${name}: ${err.message}`));- }- }, SELF_RESTART_RESPONSE_DELAY_MS);- return;- }-- const results = {};-- for (const name of app.pm2ProcessNames || []) {- const result = await pm2Service.restartApp(name, app.pm2Home)- .catch(err => ({ success: false, error: err.message }));- results[name] = result;- }-- const allSuccess = Object.values(results).every(r => r.success !== false);- await logAction('restart', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);- notifyAppsChanged('restart');-- res.json({ success: true, results });-}));--// POST /api/apps/:id/update - Pull, install deps, setup, restart-router.post('/:id/update', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- console.log(`⬇️ Starting update for ${app.name}`);- const progressSteps = [];- const emit = (step, status, message) => {- progressSteps.push({ step, status, message, timestamp: Date.now() });- };-- const result = await appUpdater.updateApp(app, emit);- const success = result.success;- await logAction('update', app.id, app.name, { steps: result.steps }, success);- notifyAppsChanged('update');- console.log(`${success ? '✅' : '❌'} Update ${success ? 'complete' : 'failed'} for ${app.name}`);-- res.json({ success, steps: result.steps, progress: progressSteps });-}));--// POST /api/apps/:id/build - Build production UI-router.post('/:id/build', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!await pathExists(app.repoPath)) {- throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- const result = await appBuilder.buildApp(app);-- if (result.failure === 'validation') {- throw new ServerError(result.message, { status: 400, code: result.code });- }-- if (result.failure === 'install') {- await logAction('build', app.id, app.name, { buildCommand: result.buildCommand, step: `npm install (${result.label})` }, false);- throw new ServerError(`npm install failed (${result.label}) exit=${result.exitCode}: ${result.output}`, { status: 500, code: 'INSTALL_FAILED' });- }-- await logAction('build', app.id, app.name, { buildCommand: result.buildCommand }, result.success);-- if (!result.success) {- const detail = result.signal ? `killed by ${result.signal}` : result.output || `exit code ${result.code}`;- throw new ServerError(`Build failed: ${detail}`, { status: 500, code: 'BUILD_FAILED' });- }-- res.json({ success: true, output: result.output });-}));--// GET /api/apps/:id/status - Get PM2 status-router.get('/:id/status', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!usesPm2(app.type)) {- return res.json({});- }-- const statuses = {};-- for (const name of app.pm2ProcessNames || []) {- const status = await pm2Service.getAppStatus(name, app.pm2Home)- .catch(err => ({ status: 'error', error: err.message }));- statuses[name] = status;- }-- res.json(statuses);-}));--// GET /api/apps/:id/logs - Get logs-router.get('/:id/logs', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const lines = parseInt(req.query.lines, 10) || 100;- const processName = req.query.process || app.pm2ProcessNames?.[0];-- if (!processName) {- throw new ServerError('No process name specified', { status: 400, code: 'MISSING_PROCESS' });- }-- const logs = await pm2Service.getLogs(processName, lines, app.pm2Home)- .catch(err => `Error retrieving logs: ${err.message}`);-- res.json({ processName, lines, logs });-}));--// Allowlist of safe editor commands-// Security: Only allow known-safe editor commands to prevent arbitrary code execution-const ALLOWED_EDITORS = new Set([- 'code', // VS Code- 'cursor', // Cursor- 'zed', // Zed- 'subl', // Sublime Text- 'atom', // Atom- 'vim', // Vim- 'nvim', // Neovim- 'nano', // Nano- 'emacs', // Emacs- 'idea', // IntelliJ IDEA- 'pycharm', // PyCharm- 'webstorm', // WebStorm- 'phpstorm', // PhpStorm- 'rubymine', // RubyMine- 'goland', // GoLand- 'clion', // CLion- 'rider', // Rider- 'studio', // Android Studio- 'xed' // Xcode-]);--// POST /api/apps/:id/open-editor - Open app in editor-router.post('/:id/open-editor', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!await pathExists(app.repoPath)) {- throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- const editorCommand = app.editorCommand || 'code .';- const [cmd, ...args] = editorCommand.split(/\s+/);-- // Security: Validate that the editor command is in our allowlist- // This prevents arbitrary command execution via malicious editorCommand values- if (!ALLOWED_EDITORS.has(cmd)) {- throw new ServerError(`Editor '${cmd}' is not in the allowed editors list`, {- status: 400,- code: 'INVALID_EDITOR',- context: { allowedEditors: Array.from(ALLOWED_EDITORS) }- });- }-- // Security: Validate args don't contain shell metacharacters- const DANGEROUS_CHARS = /[;|&`$(){}[\]<>\\!#*?~]/;- for (const arg of args) {- if (DANGEROUS_CHARS.test(arg)) {- throw new ServerError('Editor arguments contain disallowed characters', {- status: 400,- code: 'INVALID_EDITOR_ARGS'- });- }- }-- // Spawn the editor process detached so it doesn't block.- // On Windows, editor binaries are typically `.cmd`/`.bat` shims (e.g. `code.cmd`,- // `cursor.cmd`) which Node refuses to spawn without a shell since 20.12.2 — so we- // opt into the shell on win32. Args are pre-sanitized for shell metacharacters- // above, and the command is allowlisted.- const child = spawn(cmd, args, {- cwd: app.repoPath,- detached: true,- stdio: 'ignore',- shell: process.platform === 'win32',- windowsHide: true- });- child.unref();-- res.json({ success: true, command: editorCommand, path: app.repoPath });-}));--// POST /api/apps/:id/open-claude - Open Claude Code in app directory-router.post('/:id/open-claude', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!await pathExists(app.repoPath)) {- throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- // shell:true on Windows so `claude.cmd` resolves (see open-editor above for the- // Node 20.12.2 rationale). No user args reach the command line here.- const child = spawn('claude', [], {- cwd: app.repoPath,- detached: true,- stdio: 'ignore',- shell: process.platform === 'win32',- windowsHide: true- });- child.unref();-- console.log(`🤖 Opened Claude Code in ${app.name}`);- res.json({ success: true, path: app.repoPath });-}));--// POST /api/apps/:id/open-folder - Open app folder in file manager-router.post('/:id/open-folder', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!await pathExists(app.repoPath)) {- throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- // Cross-platform folder open command- const platform = process.platform;- let cmd, args;-- if (platform === 'darwin') {- cmd = 'open';- args = [app.repoPath];- } else if (platform === 'win32') {- cmd = 'explorer';- args = [app.repoPath];- } else {- cmd = 'xdg-open';- args = [app.repoPath];- }-- const child = spawn(cmd, args, {- detached: true,- stdio: 'ignore',- windowsHide: true- });- child.unref();-- res.json({ success: true, path: app.repoPath });-}));--// POST /api/apps/:id/refresh-config - Re-parse ecosystem config for PM2 processes-router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!usesPm2(app.type)) {- return res.json({ success: true, updated: false, app, processes: [] });- }-- if (!await pathExists(app.repoPath)) {- throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- // Parse ecosystem config from the app's repo path- const { processes, pm2Home } = await parseEcosystemFromPath(app.repoPath);-- // Update app with new process data- const updates = {};-- // Detect buildCommand from package.json if not already set- if (!app.buildCommand) {- const pkgPath = join(app.repoPath, 'package.json');- const pkgContent = await tryReadFile(pkgPath);- if (pkgContent) {- const pkg = safeJSONParse(pkgContent);- if (pkg?.scripts?.build) updates.buildCommand = 'npm run build';- }- }-- // Update pm2Home if detected and different from current- if (pm2Home && pm2Home !== app.pm2Home) {- updates.pm2Home = pm2Home;- }-- if (processes.length > 0) {- updates.processes = processes;- updates.pm2ProcessNames = processes.map(p => p.name);-- // Derive ports from parsed process labels (same logic as streamDetection)- const apiProc = processes.find(p => p.ports?.api);- if (apiProc) updates.apiPort = apiProc.ports.api;-- const uiProc = processes.find(p => p.ports?.ui);- if (uiProc) updates.uiPort = uiProc.ports.ui;-- const devUiProc = processes.find(p => p.ports?.devUi);- if (devUiProc) updates.devUiPort = devUiProc.ports.devUi;-- updates.uiPort = deriveUiPort(updates.uiPort, updates.apiPort, updates.devUiPort || app.devUiPort);- }-- // Detect app icon if not already set, missing on disk, or stored as an- // unusable external-image SVG (won't render under the icon route's CSP).- const iconStale =- !app.appIconPath ||- !await pathExists(app.appIconPath) ||- (extname(app.appIconPath).toLowerCase() === '.svg' && !await isUsableSvg(app.appIconPath));- if (iconStale) {- const detectedIcon = await detectAppIcon(app.repoPath, app.type);- if (detectedIcon) updates.appIconPath = detectedIcon;- }-- // Only update if we have changes- if (Object.keys(updates).length > 0) {- const updatedApp = await appsService.updateApp(req.params.id, updates);- console.log(`🔄 Refreshed config for ${app.name}: ${processes.length} processes found`);- res.json({ success: true, updated: true, app: updatedApp, processes });- } else {- console.log(`🔄 No config changes for ${app.name}`);- res.json({ success: true, updated: false, app, processes: app.processes || [] });- }-}));--// ============================================================-// Document Endpoints-// ============================================================--const ALLOWED_DOCUMENTS = ['PLAN.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];--// GET /api/apps/:id/documents - List which documents exist-router.get('/:id/documents', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;-- if (!app.repoPath || !await pathExists(app.repoPath)) {- return res.json({ documents: [], hasPlanning: false });- }-- const documents = await Promise.all(ALLOWED_DOCUMENTS.map(async filename => ({- filename,- exists: await pathExists(join(app.repoPath, filename))- })));-- const planningDir = join(app.repoPath, '.planning');- const hasPlanning = await pathExists(planningDir);-- // GSD status: detect which GSD artifacts exist- const gsd = {- hasCodebaseMap: await pathExists(join(planningDir, 'codebase')),- hasProject: await pathExists(join(planningDir, 'PROJECT.md')),- hasRoadmap: await pathExists(join(planningDir, 'ROADMAP.md')),- hasState: await pathExists(join(planningDir, 'STATE.md')),- hasConcerns: await pathExists(join(planningDir, 'CONCERNS.md')),- };-- res.json({ documents, hasPlanning, gsd });-}));--// GET /api/apps/:id/documents/:filename - Read a single document-router.get('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const { filename } = req.params;-- if (!ALLOWED_DOCUMENTS.includes(filename)) {- throw new ServerError('Document not in allowlist', { status: 400, code: 'INVALID_DOCUMENT' });- }-- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- const filePath = join(app.repoPath, filename);- const resolved = resolve(filePath);-- // Path traversal guard- if (!resolved.startsWith(resolve(app.repoPath))) {- throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });- }-- if (!await pathExists(resolved)) {- throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });- }-- const content = await readFile(resolved, 'utf-8');- res.json({ filename, content });-}));--// PUT /api/apps/:id/documents/:filename - Update a document and git commit-router.put('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const { filename } = req.params;-- if (!ALLOWED_DOCUMENTS.includes(filename)) {- throw new ServerError('Document not in allowlist', { status: 400, code: 'INVALID_DOCUMENT' });- }-- if (!app.repoPath || !await pathExists(app.repoPath)) {- throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });- }-- const filePath = join(app.repoPath, filename);- const resolved = resolve(filePath);-- if (!resolved.startsWith(resolve(app.repoPath))) {- throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });- }-- const { content, commitMessage } = documentUpdateSchema.parse(req.body);- const created = !await pathExists(resolved);-- await atomicWrite(resolved, content);- await git.stageFiles(app.repoPath, [filename]);-- const status = await git.getStatus(app.repoPath);- if (status.clean) {- return res.json({ success: true, noChanges: true });- }-- const message = commitMessage || `docs: update ${filename} via PortOS`;- const result = await git.commit(app.repoPath, message);- console.log(`📝 ${created ? 'Created' : 'Updated'} ${filename} in ${app.name} (${result.hash})`);-- res.json({ success: true, hash: result.hash, created });-}));--// ============================================================-// Agent History Endpoints-// ============================================================--// GET /api/apps/:id/agents - Recent CoS agents for this app-router.get('/:id/agents', loadApp, asyncHandler(async (req, res) => {- const app = req.loadedApp;- const limit = parseInt(req.query.limit, 10) || 50;-- // Get running agents filtered by this app- const runningAgents = await cos.getAgents().catch(() => []);- const appRunning = runningAgents.filter(a =>- a.metadata?.app === app.id || a.metadata?.taskApp === app.id- );-- // Scan last 14 days of agent history for this app- const dates = await cos.getAgentDates().catch(() => []);- const recentDates = dates.slice(0, 14);- const historyAgents = [];-- for (const { date } of recentDates) {- if (historyAgents.length >= limit) break;- const dayAgents = await cos.getAgentsByDate(date).catch(() => []);- const appAgents = dayAgents.filter(a =>- a.metadata?.app === app.id || a.metadata?.taskApp === app.id- );- historyAgents.push(...appAgents);- }-- // Combine running + history, deduplicate by id, limit- const seenIds = new Set();- const combined = [];- for (const agent of [...appRunning, ...historyAgents]) {- if (seenIds.has(agent.id)) continue;- seenIds.add(agent.id);- combined.push(agent);- if (combined.length >= limit) break;- }-- const running = combined.filter(a => a.status === 'running' || a.status === 'spawning').length;- const succeeded = combined.filter(a => a.status === 'completed').length;- const failed = combined.filter(a => a.status === 'failed' || a.status === 'error').length;-- res.json({- agents: combined,- summary: { total: combined.length, running, succeeded, failed }- });-}));--export default router;diff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsdeleted file mode 100644index cd7d47459c..0000000000--- a/server/routes/apps.test.js+++ /dev/null@@ -1,1256 +0,0 @@-import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';-import express from 'express';-import { request } from '../lib/testHelper.js';-import appsRoutes from './apps.js';--// Mock the services-vi.mock('../services/apps.js', () => ({- getAllApps: vi.fn(),- getActiveApps: vi.fn(),- getAppById: vi.fn(),- createApp: vi.fn(),- updateApp: vi.fn(),- deleteApp: vi.fn(),- archiveApp: vi.fn(),- updateAppTaskTypeOverride: vi.fn(),- getAppTaskTypeOverrides: vi.fn(),- getAppLayeredIntelligenceConfig: vi.fn(),- updateAppLayeredIntelligence: vi.fn(),- toggleAllAppTaskTypes: vi.fn(),- notifyAppsChanged: vi.fn(),- PORTOS_APP_ID: 'portos-default'-}));--vi.mock('../services/pm2.js', () => ({- listProcesses: vi.fn(),- listProcessesStrict: vi.fn(),- getAppStatus: vi.fn(),- getAppStatusStrict: vi.fn(),- startWithCommand: vi.fn(),- stopApp: vi.fn(),- restartApp: vi.fn(),- getLogs: vi.fn()-}));--vi.mock('../services/history.js', () => ({- logAction: vi.fn()-}));--vi.mock('../services/streamingDetect.js', () => ({- parseEcosystemFromPath: vi.fn(),- writeEcosystemPortEdits: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true, remapApplied: true, applied: [], unapplied: [] }),- usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),- NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift'])-}));--vi.mock('../services/appUpdater.js', () => ({- updateApp: vi.fn()-}));--vi.mock('../services/appIconDetect.js', () => ({- detectAppIcon: vi.fn(),- getIconContentType: vi.fn(),- isUsableSvg: vi.fn().mockResolvedValue(true)-}));--vi.mock('../services/cos.js', () => ({- getAgents: vi.fn().mockResolvedValue([]),- getAgentDates: vi.fn().mockResolvedValue([]),- getAgentsByDate: vi.fn().mockResolvedValue([]),- isRunning: vi.fn().mockReturnValue(true),- addTask: vi.fn().mockResolvedValue({ id: 'task-vite-1' })-}));--vi.mock('../services/git.js', () => ({- stageFiles: vi.fn(),- getStatus: vi.fn(),- commit: vi.fn()-}));--vi.mock('../services/xcodeScripts.js', () => ({- checkScripts: vi.fn().mockReturnValue({ missing: [], present: [] }),- installScripts: vi.fn(),- XCODE_TEAM_ID: 'TEST_TEAM',- XCODE_BUNDLE_PREFIX: 'net.test',- XCODE_SCRIPT_NAMES: ['deploy.sh', 'take_screenshots.sh', 'take_screenshots_macos.sh'],- toBundleId: vi.fn(),- toTargetName: vi.fn(),- generateDeployScript: vi.fn(),- generateScreenshotScript: vi.fn(),- generateMacScreenshotScript: vi.fn()-}));--// Import mocked modules-import * as appsService from '../services/apps.js';-import * as pm2Service from '../services/pm2.js';-import * as history from '../services/history.js';-import * as streamingDetect from '../services/streamingDetect.js';-import * as cos from '../services/cos.js';-import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';-import { installScripts } from '../services/xcodeScripts.js';-import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'fs';-import { join } from 'path';-import { tmpdir } from 'os';--describe('Apps Routes', () => {- let app;-- beforeEach(() => {- app = express();- app.use(express.json());- app.use('/api/apps', appsRoutes);-- // Reset all mocks- vi.clearAllMocks();- });-- describe('GET /api/apps', () => {- it('should return list of apps with PM2 status', async () => {- const mockApps = [- { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }- ];- const mockPm2Processes = [- { name: 'test-app', status: 'online' }- ];-- appsService.getAllApps.mockResolvedValue(mockApps);- pm2Service.listProcessesStrict.mockResolvedValue(mockPm2Processes);- streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);-- const response = await request(app).get('/api/apps');-- expect(response.status).toBe(200);- expect(response.body).toHaveLength(1);- expect(response.body[0].overallStatus).toBe('online');- });-- it('should handle apps with no PM2 processes', async () => {- const mockApps = [- { id: 'app-001', name: 'Test App', pm2ProcessNames: [], repoPath: '/tmp/test' }- ];-- appsService.getAllApps.mockResolvedValue(mockApps);- pm2Service.listProcessesStrict.mockResolvedValue([]);- streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);-- const response = await request(app).get('/api/apps');-- expect(response.status).toBe(200);- expect(response.body[0].overallStatus).toBe('not_started');- });-- it('reports unknown + degraded (not not_started) when the PM2 read fails', async () => {- const mockApps = [- { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }- ];-- appsService.getAllApps.mockResolvedValue(mockApps);- // Strict read returns null on a failed PM2 read — must not collapse into- // a confident "not started."- pm2Service.listProcessesStrict.mockResolvedValue(null);- streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);-- const response = await request(app).get('/api/apps');-- expect(response.status).toBe(200);- expect(response.body[0].overallStatus).toBe('unknown');- expect(response.body[0].degraded).toBe(true);- expect(response.body[0].pm2Status['test-app'].status).toBe('unknown');- });-- it('should return empty array when no apps exist', async () => {- appsService.getAllApps.mockResolvedValue([]);- pm2Service.listProcessesStrict.mockResolvedValue([]);-- const response = await request(app).get('/api/apps');-- expect(response.status).toBe(200);- expect(response.body).toHaveLength(0);- });- });-- describe('GET /api/apps/:id', () => {- it('should return app by ID', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);- pm2Service.getAppStatusStrict.mockResolvedValue({ name: 'test-app', status: 'online' });-- const response = await request(app).get('/api/apps/app-001');-- expect(response.status).toBe(200);- expect(response.body.id).toBe('app-001');- expect(response.body.pm2Status).toBeDefined();- });-- it('returns degraded + unknown when the PM2 status read fails', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);- // Detail endpoint reads per-process status via the strict variant, which- // returns null on a failed read — must surface as degraded, not collapse- // into a confident not_started.- pm2Service.getAppStatusStrict.mockResolvedValue(null);-- const response = await request(app).get('/api/apps/app-001');-- expect(response.status).toBe(200);- expect(response.body.overallStatus).toBe('unknown');- expect(response.body.degraded).toBe(true);- });-- it('should return 404 if app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app).get('/api/apps/app-999');-- expect(response.status).toBe(404);- });- });-- describe('POST /api/apps', () => {- it('should create a new app', async () => {- const newApp = {- name: 'New App',- repoPath: '/path/to/repo'- };- appsService.createApp.mockResolvedValue({ id: 'app-001', ...newApp });-- const response = await request(app)- .post('/api/apps')- .send(newApp);-- expect(response.status).toBe(201);- expect(response.body.id).toBe('app-001');- expect(appsService.createApp).toHaveBeenCalledWith(expect.objectContaining({ name: 'New App' }));- });-- it('should return 400 if validation fails', async () => {- // Missing required fields- const response = await request(app)- .post('/api/apps')- .send({});-- expect(response.status).toBe(400);- });- });-- describe('PUT /api/apps/:id', () => {- it('should update an app', async () => {- const updates = { name: 'Updated Name' };- appsService.updateApp.mockResolvedValue({ id: 'app-001', name: 'Updated Name' });-- const response = await request(app)- .put('/api/apps/app-001')- .send(updates);-- expect(response.status).toBe(200);- expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.objectContaining({ name: 'Updated Name' }));- });-- it('should return 404 if app not found', async () => {- appsService.updateApp.mockResolvedValue(null);-- const response = await request(app)- .put('/api/apps/app-999')- .send({ name: 'Test' });-- expect(response.status).toBe(404);- });-- it('routes a layeredIntelligence update through the dedicated merge helper (not the shallow updateApp)', async () => {- appsService.updateApp.mockResolvedValue({ id: 'app-001', name: 'App' });- appsService.updateAppLayeredIntelligence.mockResolvedValue({ id: 'app-001', layeredIntelligence: { enabled: true, sources: { goals: true } } });-- const response = await request(app)- .put('/api/apps/app-001')- .send({ layeredIntelligence: { enabled: true } });-- expect(response.status).toBe(200);- // The nested config must NOT be passed to the shallow updateApp (which would wipe it)…- expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.not.objectContaining({ layeredIntelligence: expect.anything() }));- // …it goes through the preserving merge helper instead.- expect(appsService.updateAppLayeredIntelligence).toHaveBeenCalledWith('app-001', { enabled: true });- expect(response.body.layeredIntelligence.enabled).toBe(true);- });-- it('GET /:id/layered-intelligence returns the effective config + isPortos flag', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'App' });- appsService.getAppLayeredIntelligenceConfig.mockResolvedValue({- enabled: false, intervalMs: 86400000, sources: { goals: true }, allowedScopes: ['app-improvement']- });-- const response = await request(app).get('/api/apps/app-001/layered-intelligence');-- expect(response.status).toBe(200);- expect(response.body.appId).toBe('app-001');- expect(response.body.isPortos).toBe(false);- expect(response.body.config.allowedScopes).toEqual(['app-improvement']);- expect(appsService.getAppLayeredIntelligenceConfig).toHaveBeenCalledWith('app-001');- });-- it('GET /:id/layered-intelligence flags the PortOS baseline app', async () => {- appsService.getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS' });- appsService.getAppLayeredIntelligenceConfig.mockResolvedValue({ enabled: false, allowedScopes: ['app-improvement', 'loop-meta'] });-- const response = await request(app).get('/api/apps/portos-default/layered-intelligence');-- expect(response.status).toBe(200);- expect(response.body.isPortos).toBe(true);- });-- it('GET /:id/layered-intelligence returns 404 for an unknown app', async () => {- appsService.getAppById.mockResolvedValue(null);- const response = await request(app).get('/api/apps/app-999/layered-intelligence');- expect(response.status).toBe(404);- });-- it('writes changed ports back to the ecosystem config (source of truth)', async () => {- // repoPath must exist on disk so the pathExists guard passes.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173, uiPort: 5174 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173, ui: 5174 } }] });- appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 6000, uiPort: 6001 });-- const response = await request(app)- .put('/api/apps/app-001')- .send({ apiPort: 6000, uiPort: 6001 });-- expect(response.status).toBe(200);- expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(- process.cwd(),- expect.arrayContaining([[5173, 6000], [5174, 6001]]),- []- );- });-- it('does not write to the ecosystem config when no port changed', async () => {- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };- appsService.getAppById.mockResolvedValue(mockApp);- appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });-- await request(app).put('/api/apps/app-001').send({ name: 'Renamed' });-- expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();- });-- it('persists a shared-value port change via the per-process-targeted rewrite', async () => {- // uiPort and apiPort both 6000 in the same process block. A value-keyed- // rewrite can't split them, so the route routes it to the targeted edits- // (process + label) instead — the edit now persists rather than 422.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'srv', ports: { api: 6000, ui: 6000 } }] });- appsService.updateApp.mockResolvedValue({ ...mockApp, uiPort: 7000 });-- const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });-- expect(response.status).toBe(200);- // Empty value-keyed remap (shared value), one targeted edit.- expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(- process.cwd(),- [],- [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]- );- expect(appsService.updateApp).toHaveBeenCalled();- });-- it('persists a request mixing a distinct port (value-keyed) and a shared port (targeted) in one PUT', async () => {- // devUiPort is distinct (5556) so it goes through the value-keyed remap;- // apiPort/uiPort share 6000 so the uiPort edit goes through the targeted- // edits. Both are handed to the single atomic writer in one call.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({- processes: [- { name: 'srv', ports: { api: 6000, ui: 6000 } },- { name: 'srv-ui', ports: { devUi: 5556 } }- ]- });- appsService.updateApp.mockResolvedValue({ ...mockApp, uiPort: 7000, devUiPort: 7001 });-- const response = await request(app)- .put('/api/apps/app-001')- .send({ uiPort: 7000, devUiPort: 7001 });-- expect(response.status).toBe(200);- // One atomic write: devUiPort (distinct) in remap; uiPort (shared) targeted.- expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(- process.cwd(),- [[5556, 7001]],- [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]- );- expect(appsService.updateApp).toHaveBeenCalled();- });-- it('rejects (422) a shared-value port change the targeted rewrite cannot apply', async () => {- // Shared value, but the targeted rewrite finds no matching literal to- // change (e.g. derived from a const outside the block) → unapplied → 422.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'srv', ports: { api: 6000, ui: 6000 } }] });- streamingDetect.writeEcosystemPortEdits.mockResolvedValueOnce({- file: 'ecosystem.config.cjs', changed: false, remapApplied: false, applied: [],- unapplied: [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]- });-- const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });-- expect(response.status).toBe(422);- expect(appsService.updateApp).not.toHaveBeenCalled();- });-- it('ignores a submitted uiPort on a derived (served-by-API) app and pins it to the derived value', async () => {- // App has an API process + Vite dev UI but no literal ports.ui, so the- // displayed uiPort is derived (= apiPort). The drawer submits all fields- // and never syncs the UI field to a changed API field, so a stale/echoed- // or even hand-typed uiPort can't be distinguished from a deliberate- // (impossible) independent UI change. The route ignores the submitted- // value: no config write for the UI port, no 422, and the stored uiPort is- // pinned to the derived value so it keeps tracking the API port.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };- appsService.getAppById.mockResolvedValue(mockApp);- // Parser yields api + devUi only; ui is derived from api (served-by-API).- streamingDetect.parseEcosystemFromPath.mockResolvedValue({- processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]- });- appsService.updateApp.mockResolvedValue({ ...mockApp });-- const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });-- expect(response.status).toBe(200);- // No API port change → no config rewrite for the (ignored) UI port.- expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();- // Stored uiPort pinned to the derived value (= unchanged apiPort 6000),- // NOT the submitted 7000.- const updateArg = appsService.updateApp.mock.calls[0][1];- expect(updateArg.uiPort).toBe(6000);- });-- it('strips the echoed derived uiPort so it is never persisted as an explicit field', async () => {- // Same served-by-API shape; the modal echoes the derived uiPort (6000)- // unchanged on a rename. That must NOT 422, but it also must NOT be stored- // as a STALE explicit uiPort — the route pins it to the current derived- // value so it keeps tracking apiPort instead of freezing.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({- processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]- });- appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });-- const response = await request(app)- .put('/api/apps/app-001')- .send({ name: 'Renamed', uiPort: 6000 });-- expect(response.status).toBe(200);- expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();- // uiPort pinned to the derived value (= unchanged apiPort 6000) so a stale- // stored value can't survive the merge.- const updateArg = appsService.updateApp.mock.calls[0][1];- expect(updateArg.uiPort).toBe(6000);- expect(updateArg.name).toBe('Renamed');- });-- it('changing apiPort on a served-by-API app (UI following the new API port) persists the API port and pins uiPort to the new derived value', async () => {- // Valid combined save: API 6000→7000 with the UI following to 7000 (the- // derived port tracks the new API port). The apiPort edit persists via the- // value-keyed rewrite; the stored uiPort is overwritten with the NEW- // derived value (7000) so a stale 6000 can't survive the updateApp merge- // and block re-derivation.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({- processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]- });- appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 7000, uiPort: 7000 });-- const response = await request(app)- .put('/api/apps/app-001')- .send({ apiPort: 7000, uiPort: 7000 });-- expect(response.status).toBe(200);- // apiPort (distinct, value-keyed) persisted; uiPort follows → not in remap.- expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(- process.cwd(),- [[6000, 7000]],- []- );- const updateArg = appsService.updateApp.mock.calls[0][1];- expect(updateArg.uiPort).toBe(7000); // pinned to new derived value- expect(updateArg.apiPort).toBe(7000);- });-- it('accepts the common API-only edit (drawer echoes the stale derived uiPort) and pins uiPort to the new API port', async () => {- // The drawer submits all fields and does NOT sync the UI field when the- // API field changes, so a normal API-only edit arrives as- // { apiPort: 7000, uiPort: 6000 (old derived) }. That stale echo must NOT- // 422 — the API port persists via the value-keyed rewrite and the stored- // uiPort is pinned to the NEW derived value (7000), not the echoed 6000.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({- processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]- });- appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 7000, uiPort: 7000 });-- const response = await request(app)- .put('/api/apps/app-001')- .send({ apiPort: 7000, uiPort: 6000 });-- expect(response.status).toBe(200);- // API port persisted; the stale echoed UI port is ignored, not remapped.- expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(- process.cwd(),- [[6000, 7000]],- []- );- const updateArg = appsService.updateApp.mock.calls[0][1];- expect(updateArg.uiPort).toBe(7000); // pinned to NEW derived value, not echoed 6000- expect(updateArg.apiPort).toBe(7000);- });-- it('does not reject a non-port edit on an app whose top-level ports are not stored (derived)', async () => {- // apps.json has no apiPort/uiPort (derived from processes); a rename- // submits the echoed display values. Those must not read as port changes.- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd() };- appsService.getAppById.mockResolvedValue(mockApp);- // Config currently serves these derived ports; the modal echoes them back.- streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5555, ui: 5556 } }] });- appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });-- const response = await request(app)- .put('/api/apps/app-001')- .send({ name: 'Renamed', apiPort: 5555, uiPort: 5556 });-- expect(response.status).toBe(200);- expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();- expect(appsService.updateApp).toHaveBeenCalled();- });-- it('rejects (422) when the port literal is not found in the config (changed:false)', async () => {- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173 } }] });- streamingDetect.writeEcosystemPortEdits.mockResolvedValueOnce({ file: 'ecosystem.config.cjs', changed: false, remapApplied: false, applied: [], unapplied: [] });-- const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });-- expect(response.status).toBe(422);- expect(appsService.updateApp).not.toHaveBeenCalled();- });-- it('fails the request (and does not update the registry) when the config write throws', async () => {- const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };- appsService.getAppById.mockResolvedValue(mockApp);- streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173 } }] });- streamingDetect.writeEcosystemPortEdits.mockRejectedValueOnce(new Error('EACCES'));-- const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });-- expect(response.status).toBeGreaterThanOrEqual(500);- // Registry write must not happen after a failed canonical-config write.- expect(appsService.updateApp).not.toHaveBeenCalled();- });- });-- describe('DELETE /api/apps/:id', () => {- it('should delete an app', async () => {- appsService.deleteApp.mockResolvedValue(true);-- const response = await request(app).delete('/api/apps/app-001');-- expect(response.status).toBe(204);- expect(appsService.deleteApp).toHaveBeenCalledWith('app-001');- });-- it('should return 404 if app not found', async () => {- appsService.deleteApp.mockResolvedValue(false);-- const response = await request(app).delete('/api/apps/app-999');-- expect(response.status).toBe(404);- });-- it('should return 403 when deleting PortOS baseline app', async () => {- const response = await request(app).delete('/api/apps/portos-default');-- expect(response.status).toBe(403);- expect(appsService.deleteApp).not.toHaveBeenCalled();- });- });-- describe('POST /api/apps/:id/archive', () => {- it('should return 403 when archiving PortOS baseline app', async () => {- const response = await request(app).post('/api/apps/portos-default/archive');-- expect(response.status).toBe(403);- expect(appsService.archiveApp).not.toHaveBeenCalled();- });- });-- describe('POST /api/apps/:id/start', () => {- it('should start an app', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- repoPath: '/path/to/repo',- pm2ProcessNames: ['test-app'],- startCommands: ['npm run dev']- };- appsService.getAppById.mockResolvedValue(mockApp);- pm2Service.startWithCommand.mockResolvedValue({ success: true });- history.logAction.mockResolvedValue();-- const response = await request(app).post('/api/apps/app-001/start');-- expect(response.status).toBe(200);- expect(response.body.success).toBe(true);- expect(pm2Service.startWithCommand).toHaveBeenCalled();- expect(history.logAction).toHaveBeenCalledWith('start', 'app-001', 'Test App', expect.any(Object), true);- });-- it('should return 404 if app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app).post('/api/apps/app-999/start');-- expect(response.status).toBe(404);- });- });-- describe('POST /api/apps/:id/stop', () => {- it('should stop an app', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);- pm2Service.stopApp.mockResolvedValue({ success: true });- history.logAction.mockResolvedValue();-- const response = await request(app).post('/api/apps/app-001/stop');-- expect(response.status).toBe(200);- expect(response.body.success).toBe(true);- expect(pm2Service.stopApp).toHaveBeenCalledWith('test-app', undefined);- });-- it('should return 404 if app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app).post('/api/apps/app-999/stop');-- expect(response.status).toBe(404);- });- });-- describe('POST /api/apps/:id/restart', () => {- it('should restart an app', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);- pm2Service.restartApp.mockResolvedValue({ success: true });- history.logAction.mockResolvedValue();-- const response = await request(app).post('/api/apps/app-001/restart');-- expect(response.status).toBe(200);- expect(response.body.success).toBe(true);- expect(pm2Service.restartApp).toHaveBeenCalledWith('test-app', undefined);- });-- it('should return 404 if app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app).post('/api/apps/app-999/restart');-- expect(response.status).toBe(404);- });- });-- describe('GET /api/apps - devUiPort enrichment', () => {- it('should include devUiPort derived from process ports.devUi', async () => {- const mockApps = [{- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-app'],- repoPath: '/tmp/test',- processes: [{ name: 'test-app', ports: { devUi: 5554 } }]- }];- appsService.getAllApps.mockResolvedValue(mockApps);- pm2Service.listProcessesStrict.mockResolvedValue([]);-- const response = await request(app).get('/api/apps');-- expect(response.status).toBe(200);- expect(response.body[0].devUiPort).toBe(5554);- });-- it('should derive uiPort from apiPort when app has devUi but no ui process', async () => {- const mockApps = [{- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-api', 'test-ui'],- repoPath: '/tmp/test',- processes: [- { name: 'test-api', ports: { api: 5551 } },- { name: 'test-ui', ports: { devUi: 5550 } }- ]- }];- appsService.getAllApps.mockResolvedValue(mockApps);- pm2Service.listProcessesStrict.mockResolvedValue([]);-- const response = await request(app).get('/api/apps');-- expect(response.status).toBe(200);- expect(response.body[0].uiPort).toBe(5551);- expect(response.body[0].devUiPort).toBe(5550);- expect(response.body[0].apiPort).toBe(5551);- });-- it('should use explicit devUiPort over derived value', async () => {- const mockApps = [{- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-app'],- repoPath: '/tmp/test',- devUiPort: 4444,- processes: [{ name: 'test-app', ports: { devUi: 5554 } }]- }];- appsService.getAllApps.mockResolvedValue(mockApps);- pm2Service.listProcessesStrict.mockResolvedValue([]);-- const response = await request(app).get('/api/apps');-- expect(response.status).toBe(200);- expect(response.body[0].devUiPort).toBe(4444);- });- });-- describe('POST /api/apps/:id/build', () => {- it('should return 404 if app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app).post('/api/apps/app-999/build');-- expect(response.status).toBe(404);- });-- it.skipIf(process.platform !== 'win32')('should reject build command args containing shell-unsafe metacharacters', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- repoPath: process.cwd(), // real path so pathExists check passes- buildCommand: 'npm run build&whoami',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);-- const response = await request(app).post('/api/apps/app-001/build');-- expect(response.status).toBe(400);- expect(response.body.code).toBe('INVALID_BUILD_COMMAND');- });-- it('should reject build commands not starting with npm or npx', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- repoPath: '/tmp',- buildCommand: 'rm -rf /',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);-- const response = await request(app).post('/api/apps/app-001/build');-- expect(response.status).toBe(400);- expect(response.body.code).toBe('INVALID_BUILD_COMMAND');- });-- it('should return 400 if repo path does not exist', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- repoPath: '/nonexistent/path/that/does/not/exist',- buildCommand: 'npm run build',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);-- const response = await request(app).post('/api/apps/app-001/build');-- expect(response.status).toBe(400);- expect(response.body.code).toBe('PATH_NOT_FOUND');- });- });-- describe('GET /api/apps/:id/status', () => {- it('should return PM2 status for app processes', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-api', 'test-worker']- };- appsService.getAppById.mockResolvedValue(mockApp);- pm2Service.getAppStatus- .mockResolvedValueOnce({ status: 'online', cpu: 2.5 })- .mockResolvedValueOnce({ status: 'stopped' });-- const response = await request(app).get('/api/apps/app-001/status');-- expect(response.status).toBe(200);- expect(response.body['test-api']).toEqual({ status: 'online', cpu: 2.5 });- expect(response.body['test-worker']).toEqual({ status: 'stopped' });- });-- it('should return 404 if app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app).get('/api/apps/app-999/status');-- expect(response.status).toBe(404);- });- });-- describe('GET /api/apps/:id/logs', () => {- it('should return logs for app process', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- pm2ProcessNames: ['test-app']- };- appsService.getAppById.mockResolvedValue(mockApp);- pm2Service.getLogs.mockResolvedValue('Log line 1\nLog line 2');-- const response = await request(app).get('/api/apps/app-001/logs?lines=50');-- expect(response.status).toBe(200);- expect(response.body.processName).toBe('test-app');- expect(response.body.lines).toBe(50);- expect(response.body.logs).toBe('Log line 1\nLog line 2');- });-- it('should return 404 if app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app).get('/api/apps/app-999/logs');-- expect(response.status).toBe(404);- });-- it('should return 400 if no process name available', async () => {- const mockApp = {- id: 'app-001',- name: 'Test App',- pm2ProcessNames: []- };- appsService.getAppById.mockResolvedValue(mockApp);-- const response = await request(app).get('/api/apps/app-001/logs');-- expect(response.status).toBe(400);- });- });-- describe('PUT /api/apps/:id/task-types/:taskType', () => {- it('should accept valid taskMetadata with allowed boolean keys', async () => {- appsService.updateAppTaskTypeOverride.mockResolvedValue({- id: 'app-001',- name: 'Test App',- taskTypeOverrides: { 'feature-ideas': { taskMetadata: { useWorktree: true } } }- });-- const response = await request(app)- .put('/api/apps/app-001/task-types/feature-ideas')- .send({ taskMetadata: { useWorktree: true, simplify: false } });-- expect(response.status).toBe(200);- expect(response.body.success).toBe(true);- });-- it('should accept taskMetadata: null to clear metadata', async () => {- appsService.updateAppTaskTypeOverride.mockResolvedValue({- id: 'app-001',- name: 'Test App',- taskTypeOverrides: {}- });-- const response = await request(app)- .put('/api/apps/app-001/task-types/feature-ideas')- .send({ taskMetadata: null });-- expect(response.status).toBe(200);- });-- it('should reject taskMetadata that is an array', async () => {- const response = await request(app)- .put('/api/apps/app-001/task-types/feature-ideas')- .send({ taskMetadata: [1, 2, 3] });-- expect(response.status).toBe(400);- });-- it('should reject taskMetadata with only unknown keys', async () => {- const response = await request(app)- .put('/api/apps/app-001/task-types/feature-ideas')- .send({ taskMetadata: { unknownKey: true } });-- expect(response.status).toBe(400);- expect(response.body.error).toContain('unrecognized');- });-- it('should reject taskMetadata with non-boolean values for allowed keys', async () => {- const response = await request(app)- .put('/api/apps/app-001/task-types/feature-ideas')- .send({ taskMetadata: { useWorktree: 'yes' } });-- expect(response.status).toBe(400);- });-- it('should return 400 when no valid fields provided', async () => {- const response = await request(app)- .put('/api/apps/app-001/task-types/feature-ideas')- .send({});-- expect(response.status).toBe(400);- });-- it('should reject an unknown taskType in the URL', async () => {- const response = await request(app)- .put('/api/apps/app-001/task-types/not-a-real-task-type')- .send({ enabled: true });-- expect(response.status).toBe(400);- expect(response.body.code).toBe('INVALID_TASK_TYPE');- });- });-- describe('PUT /api/apps/bulk-task-type/:taskType', () => {- it('should reject an unknown taskType in the URL', async () => {- const response = await request(app)- .put('/api/apps/bulk-task-type/not-a-real-task-type')- .send({ enabled: true });-- expect(response.status).toBe(400);- expect(response.body.code).toBe('INVALID_TASK_TYPE');- });- });-- describe('GET /api/apps/:id/icon', () => {- const iconDir = join(tmpdir(), 'portos-test-icon');- const iconPath = join(iconDir, 'icon.png');- const mockApp = { id: 'app-001', name: 'Test App', appIconPath: iconPath, repoPath: '/tmp/test', pm2ProcessNames: [] };-- beforeEach(() => {- mkdirSync(iconDir, { recursive: true });- writeFileSync(iconPath, 'fake-png-data');- appsService.getAppById.mockResolvedValue(mockApp);- getIconContentType.mockReturnValue('image/png');- });-- afterAll(() => {- rmSync(iconDir, { recursive: true, force: true });- });-- it('should return icon with ETag header', async () => {- const response = await request(app).get('/api/apps/app-001/icon');-- expect(response.status).toBe(200);- expect(response.headers['etag']).toBeDefined();- expect(response.headers['etag']).toMatch(/^W\//);- expect(response.headers['cache-control']).toBe('public, max-age=3600');- });-- it('should return 304 when If-None-Match matches ETag', async () => {- const first = await request(app).get('/api/apps/app-001/icon');- const etag = first.headers['etag'];-- const second = await request(app)- .get('/api/apps/app-001/icon')- .set('If-None-Match', etag);-- expect(second.status).toBe(304);- });-- it('should return 304 when If-None-Match contains multiple ETags including match', async () => {- const first = await request(app).get('/api/apps/app-001/icon');- const etag = first.headers['etag'];-- const second = await request(app)- .get('/api/apps/app-001/icon')- .set('If-None-Match', `W/"other-etag", ${etag}, W/"another"`);-- expect(second.status).toBe(304);- });-- it('redetects when stored path is an unusable SVG (external <image href>) so PortOS-style icons recover', async () => {- // Simulate the bad-state PortOS install: appIconPath stored as an SVG- // that exists on disk but embeds <image href="/portos-logo.png"> — CSP- // blocks the embed, so it renders blank. The route must re-detect.- const badSvgPath = join(iconDir, 'favicon.svg');- const goodPngPath = join(iconDir, 'redetected.png');- writeFileSync(badSvgPath, '<svg><image href="/logo.png"/></svg>');- writeFileSync(goodPngPath, 'fake-png-data');- appsService.getAppById.mockResolvedValue({- ...mockApp,- appIconPath: badSvgPath,- });- isUsableSvg.mockResolvedValueOnce(false);- detectAppIcon.mockResolvedValueOnce(goodPngPath);-- const response = await request(app).get('/api/apps/app-001/icon');-- expect(response.status).toBe(200);- expect(detectAppIcon).toHaveBeenCalledWith('/tmp/test', undefined);- expect(appsService.updateApp).toHaveBeenCalledWith('app-001', { appIconPath: goodPngPath });- });- });-- describe('PUT /api/apps/:id/task-types/all', () => {- it('should toggle all task types for an app', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App' });- appsService.toggleAllAppTaskTypes.mockResolvedValue({ id: 'app-001', name: 'Test App', taskTypeOverrides: { security: { enabled: true } } });-- const response = await request(app)- .put('/api/apps/app-001/task-types/all')- .send({ enabled: true });-- expect(response.status).toBe(200);- expect(response.body.success).toBe(true);- expect(response.body.appId).toBe('app-001');- expect(appsService.toggleAllAppTaskTypes).toHaveBeenCalledWith('app-001', true);- });-- it('should return 400 when enabled is not a boolean', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App' });-- const response = await request(app)- .put('/api/apps/app-001/task-types/all')- .send({ enabled: 'yes' });-- expect(response.status).toBe(400);- expect(response.body.code).toBe('VALIDATION_ERROR');- });-- it('should return 404 when app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app)- .put('/api/apps/app-999/task-types/all')- .send({ enabled: true });-- expect(response.status).toBe(404);- });- });-- describe('POST /api/apps/:id/xcode-scripts/install', () => {- it('should install requested scripts successfully', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });- installScripts.mockResolvedValue({ installed: ['deploy.sh'], skipped: [], errors: [] });-- const response = await request(app)- .post('/api/apps/app-001/xcode-scripts/install')- .send({ scripts: ['deploy.sh'] });-- expect(response.status).toBe(200);- expect(response.body.installed).toEqual(['deploy.sh']);- });-- it('should return 400 when all scripts fail', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });- installScripts.mockResolvedValue({ installed: [], skipped: [], errors: ['some failure'] });-- const response = await request(app)- .post('/api/apps/app-001/xcode-scripts/install')- .send({ scripts: ['deploy.sh'] });-- expect(response.status).toBe(400);- expect(response.body.code).toBe('INSTALL_FAILED');- });-- it('should return 400 when scripts array contains an unknown name', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });-- const response = await request(app)- .post('/api/apps/app-001/xcode-scripts/install')- .send({ scripts: ['bad.sh'] });-- // Unknown script names are now rejected by the Zod enum validator- expect(response.status).toBe(400);- });-- it('should return 400 when scripts array is empty', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });-- const response = await request(app)- .post('/api/apps/app-001/xcode-scripts/install')- .send({ scripts: [] });-- expect(response.status).toBe(400);- });-- it('should return 404 when app not found', async () => {- appsService.getAppById.mockResolvedValue(null);-- const response = await request(app)- .post('/api/apps/app-999/xcode-scripts/install')- .send({ scripts: ['deploy.sh'] });-- expect(response.status).toBe(404);- });-- it('should return partial success with errors', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });- installScripts.mockResolvedValue({- installed: ['deploy.sh'],- skipped: [],- errors: ['Script take_screenshots_macos.sh does not apply to ios-native apps']- });-- const response = await request(app)- .post('/api/apps/app-001/xcode-scripts/install')- .send({ scripts: ['deploy.sh', 'take_screenshots_macos.sh'] });-- expect(response.status).toBe(200);- expect(response.body.installed).toEqual(['deploy.sh']);- expect(response.body.errors).toHaveLength(1);- });-- it('should return 400 when repoPath does not exist', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/nonexistent/path' });-- const response = await request(app)- .post('/api/apps/app-001/xcode-scripts/install')- .send({ scripts: ['deploy.sh'] });-- expect(response.status).toBe(400);- expect(response.body.code).toBe('PATH_NOT_FOUND');- });- });-- describe('Vite Dev-UI host guard', () => {- let repoDir;-- beforeEach(() => {- repoDir = join(tmpdir(), `vite-host-${Math.random().toString(36).slice(2)}`);- mkdirSync(repoDir, { recursive: true });- });-- afterAll(() => {- // best-effort cleanup of any straggler temp dirs is handled per-test below- });-- const writeViteConfig = (content) =>- writeFileSync(join(repoDir, 'vite.config.js'), content);-- describe('GET /:id/vite-host-check', () => {- it('reports hostAllowed=false + canAutoFix for a Vite app missing the host', async () => {- writeViteConfig("export default { server: { port: 5173 } };");- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });-- const response = await request(app)- .get('/api/apps/app-001/vite-host-check?host=null.taile8179.ts.net');-- expect(response.status).toBe(200);- expect(response.body.hasViteConfig).toBe(true);- expect(response.body.hostAllowed).toBe(false);- expect(response.body.canAutoFix).toBe(true);- rmSync(repoDir, { recursive: true, force: true });- });-- it('reports hostAllowed=true when the config already allows the tailnet', async () => {- writeViteConfig("export default { server: { allowedHosts: ['.ts.net'] } };");- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });-- const response = await request(app)- .get('/api/apps/app-001/vite-host-check?host=box.taile8179.ts.net');-- expect(response.status).toBe(200);- expect(response.body.hostAllowed).toBe(true);- rmSync(repoDir, { recursive: true, force: true });- });-- it('reports hasViteConfig=false when the app has no vite config', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });-- const response = await request(app)- .get('/api/apps/app-001/vite-host-check?host=box.taile8179.ts.net');-- expect(response.status).toBe(200);- expect(response.body.hasViteConfig).toBe(false);- rmSync(repoDir, { recursive: true, force: true });- });- });-- describe('POST /:id/fix-vite-hosts', () => {- it('allow-all rewrites the config to allowedHosts: true', async () => {- writeViteConfig("export default { server: { port: 5173 } };");- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });-- const response = await request(app)- .post('/api/apps/app-001/fix-vite-hosts')- .send({ mode: 'allow-all', host: 'null.taile8179.ts.net' });-- expect(response.status).toBe(200);- expect(response.body.strategy).toBe('inject-into-server');- const written = readFileSync(join(repoDir, 'vite.config.js'), 'utf-8');- expect(written).toContain('allowedHosts: true');- rmSync(repoDir, { recursive: true, force: true });- });-- it('allow-all returns 422 when no vite config exists', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });-- const response = await request(app)- .post('/api/apps/app-001/fix-vite-hosts')- .send({ mode: 'allow-all' });-- expect(response.status).toBe(422);- expect(response.body.code).toBe('NO_VITE_CONFIG');- rmSync(repoDir, { recursive: true, force: true });- });-- it('ai mode queues a CoS task targeting the app', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });- cos.isRunning.mockReturnValue(true);-- const response = await request(app)- .post('/api/apps/app-001/fix-vite-hosts')- .send({ mode: 'ai', host: 'null.taile8179.ts.net' });-- expect(response.status).toBe(200);- expect(response.body.taskId).toBe('task-vite-1');- expect(cos.addTask).toHaveBeenCalledWith(- expect.objectContaining({ app: 'app-001', approvalRequired: true }),- 'internal'- );- rmSync(repoDir, { recursive: true, force: true });- });-- it('ai mode returns 409 when CoS is not running', async () => {- appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });- cos.isRunning.mockReturnValue(false);-- const response = await request(app)- .post('/api/apps/app-001/fix-vite-hosts')- .send({ mode: 'ai' });-- expect(response.status).toBe(409);- expect(response.body.code).toBe('COS_NOT_RUNNING');- rmSync(repoDir, { recursive: true, force: true });- });- });- });-});diff --git a/server/routes/apps/agents.js b/server/routes/apps/agents.jsnew file mode 100644index 0000000000..9192ec82d8--- /dev/null+++ b/server/routes/apps/agents.js@@ -0,0 +1,59 @@+/**+ * Recent CoS agent history for an app (running + last-14-days history, deduped).+ *+ * GET /:id/agents → { agents, summary }+ */++import { Router } from 'express';+import * as cos from '../../services/cos.js';+import { asyncHandler } from '../../lib/errorHandler.js';+import { loadApp } from './shared.js';++const router = Router();++// GET /api/apps/:id/agents - Recent CoS agents for this app+router.get('/:id/agents', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const limit = parseInt(req.query.limit, 10) || 50;++ // Get running agents filtered by this app+ const runningAgents = await cos.getAgents().catch(() => []);+ const appRunning = runningAgents.filter(a =>+ a.metadata?.app === app.id || a.metadata?.taskApp === app.id+ );++ // Scan last 14 days of agent history for this app+ const dates = await cos.getAgentDates().catch(() => []);+ const recentDates = dates.slice(0, 14);+ const historyAgents = [];++ for (const { date } of recentDates) {+ if (historyAgents.length >= limit) break;+ const dayAgents = await cos.getAgentsByDate(date).catch(() => []);+ const appAgents = dayAgents.filter(a =>+ a.metadata?.app === app.id || a.metadata?.taskApp === app.id+ );+ historyAgents.push(...appAgents);+ }++ // Combine running + history, deduplicate by id, limit+ const seenIds = new Set();+ const combined = [];+ for (const agent of [...appRunning, ...historyAgents]) {+ if (seenIds.has(agent.id)) continue;+ seenIds.add(agent.id);+ combined.push(agent);+ if (combined.length >= limit) break;+ }++ const running = combined.filter(a => a.status === 'running' || a.status === 'spawning').length;+ const succeeded = combined.filter(a => a.status === 'completed').length;+ const failed = combined.filter(a => a.status === 'failed' || a.status === 'error').length;++ res.json({+ agents: combined,+ summary: { total: combined.length, running, succeeded, failed }+ });+}));++export default router;diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.jsnew file mode 100644index 0000000000..1ac43da386--- /dev/null+++ b/server/routes/apps/crud.js@@ -0,0 +1,284 @@+/**+ * App CRUD + status enrichment + archive lifecycle.+ *+ * GET / → App[] (PM2-status-enriched)+ * GET /:id → App (PM2-status-enriched, + appVersion)+ * POST / → App+ * PUT /:id → App (ports written back to ecosystem config)+ * DELETE /:id → 204+ * POST /:id/archive → App+ * POST /:id/unarchive → App+ */++import { Router } from 'express';+import { join } from 'path';+import { readJSONFile } from '../../lib/fileUtils.js';+import * as appsService from '../../services/apps.js';+import { notifyAppsChanged, PORTOS_APP_ID } from '../../services/apps.js';+import * as pm2Service from '../../services/pm2.js';+import { validateRequest, appSchema, appUpdateSchema } from '../../lib/validation.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { parseEcosystemFromPath, usesPm2 } from '../../services/streamingDetect.js';+import { detectAppIcon } from '../../services/appIconDetect.js';+import { hasDeployScript } from '../../services/appDeployer.js';+import { checkScripts } from '../../services/xcodeScripts.js';+import { applyEcosystemPortEdits } from '../../services/appPortConfig.js';+import { loadApp, pathExists, deriveAppPorts, computeOverallStatus } from './shared.js';++const router = Router();++// GET /api/apps - List all apps+router.get('/', asyncHandler(async (req, res) => {+ const apps = await appsService.getAllApps();++ // 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.+ // listProcessesStrict returns `null` on a failed read (vs `[]` for a+ // successful read with no processes) — track those homes so we report+ // `unknown` (status unavailable) instead of `not_started` (confidently not+ // running) for their apps. See getAppStatuses() in the service for the same+ // absent-vs-empty distinction.+ const pm2Maps = new Map();+ const failedHomes = new Set();+ for (const pm2Home of pm2HomeGroups.keys()) {+ const processes = await pm2Service.listProcessesStrict(pm2Home);+ if (processes === null) {+ failedHomes.add(pm2Home);+ pm2Maps.set(pm2Home, new Map());+ } else {+ 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) => {+ // Non-PM2 apps skip PM2 enrichment entirely+ if (!usesPm2(app.type)) {+ return { ...app, pm2Status: {}, overallStatus: 'n/a', hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) };+ }++ const pm2Home = app.pm2Home || null;+ const pm2Map = pm2Maps.get(pm2Home) || new Map();+ const homeFailed = failedHomes.has(pm2Home);++ const statuses = {};+ for (const processName of app.pm2ProcessNames || []) {+ const pm2Proc = pm2Map.get(processName);+ // A failed PM2 read leaves status genuinely unknown — don't claim+ // `not_found` (which the UI reads as "registered but never launched").+ statuses[processName] = pm2Proc+ ?? { name: processName, status: homeFailed ? 'unknown' : 'not_found', pm2_env: null };+ }++ // Compute overall status. A failed PM2 home short-circuits to `unknown`+ // with a `degraded` flag rather than collapsing to `not_started`.+ const overallStatus = computeOverallStatus(Object.values(statuses), homeFailed);++ // Auto-populate processes from ecosystem config if not already set+ let processes = app.processes;+ if ((!processes || processes.length === 0) && await pathExists(app.repoPath)) {+ const parsed = await parseEcosystemFromPath(app.repoPath).catch(() => ({ processes: [] }));+ processes = parsed.processes;+ }++ // Auto-derive uiPort/apiPort/devUiPort from processes when not explicitly set+ const { uiPort, apiPort, devUiPort } = deriveAppPorts(app, processes);++ return {+ ...app,+ processes,+ uiPort,+ devUiPort,+ apiPort,+ pm2Status: statuses,+ overallStatus,+ degraded: homeFailed,+ hasDeployScript: hasDeployScript(app),+ xcodeScripts: checkScripts(app)+ };+ }));++ res.json(enriched);+}));++// GET /api/apps/:id - Get single app+router.get('/:id', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ // Non-PM2 apps skip PM2 status+ let statuses = {};+ let overallStatus = 'n/a';++ let degraded = false;+ if (usesPm2(app.type)) {+ // getAppStatusStrict returns `null` when the PM2 read failed (vs a real+ // status object). A failed read is genuinely unknown, not "not running" —+ // mark `degraded` so the detail UI can offer refresh-to-retry rather than a+ // misleading Start. Mirrors the list endpoint's `degraded`.+ // Read each process's PM2 status in parallel — a detail view of a+ // multi-process app would otherwise serialize one IPC round-trip per process.+ const reads = await Promise.all(+ (app.pm2ProcessNames || []).map(async (processName) => ({+ processName,+ status: await pm2Service.getAppStatusStrict(processName, app.pm2Home),+ })),+ );+ for (const { processName, status } of reads) {+ if (status === null) {+ degraded = true;+ statuses[processName] = { name: processName, status: 'unknown', pm2_env: null };+ } else {+ statuses[processName] = status;+ }+ }++ // Compute overall status (same logic as list endpoint). A degraded read+ // short-circuits to `unknown` rather than collapsing to `not_started`.+ overallStatus = computeOverallStatus(Object.values(statuses), degraded);+ }++ // Auto-derive uiPort/apiPort/devUiPort from processes when not explicitly set+ const { uiPort, apiPort, devUiPort } = deriveAppPorts(app, app.processes || []);++ // Read version from app's package.json if available+ let appVersion = null;+ if (app.repoPath) {+ const pkg = await readJSONFile(join(app.repoPath, 'package.json'), null, { logError: false });+ appVersion = pkg?.version || null;+ }++ res.json({ ...app, uiPort, devUiPort, apiPort, overallStatus, degraded, pm2Status: statuses, appVersion, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });+}));++// POST /api/apps - Create new app+router.post('/', asyncHandler(async (req, res, next) => {+ const data = validateRequest(appSchema, req.body);++ // Detect app icon before creation to avoid a double write+ if (data.repoPath) {+ const detectedIcon = await detectAppIcon(data.repoPath, data.type);+ if (detectedIcon) data.appIconPath = detectedIcon;+ }++ const app = await appsService.createApp(data);+ res.status(201).json(app);+}));++// PUT /api/apps/:id - Update app+router.put('/:id', asyncHandler(async (req, res, next) => {+ const data = validateRequest(appUpdateSchema, req.body);++ // Only port edits need the canonical-config write-back; snapshot the+ // pre-update app just for those so ordinary updates (rename, archive,+ // jira/datadog) don't pay the extra read + fs stat. tlsPort is omitted: it's+ // synthetic (derived from cert presence / upgradeAppTls), never a literal in+ // ecosystem.config.cjs, so there's nothing to rewrite for it.+ const PORT_KEYS = ['apiPort', 'uiPort', 'devUiPort'];+ const hasPortUpdate = PORT_KEYS.some(key => key in data);+ const existing = hasPortUpdate ? await appsService.getAppById(req.params.id) : null;++ // Port fields in apps.json are *derived* from ecosystem.config.cjs (the source+ // of truth PM2 reads). Persist the change to the canonical config FIRST,+ // before the derived registry: an unreadable/unwritable config then surfaces+ // as a failed request instead of a 200 that leaves apps.json and PM2+ // disagreeing (the write throws and bubbles to the error middleware).+ if (existing && usesPm2(existing.type) && await pathExists(existing.repoPath)) {+ const { persistFailed, uiPortOverride } = await applyEcosystemPortEdits(existing, data);++ // Pin the stored uiPort to the derived value for served-by-API apps. This+ // both overwrites the drawer's echoed/stale UI field and keeps the stored+ // value tracking apiPort — deleting `data.uiPort` would NOT be enough, since+ // updateApp merges omitted fields over the existing record, so a stale+ // explicit `uiPort` would survive (truthy) and block re-derivation. Writing+ // the derived value self-corrects on every save.+ if (uiPortOverride !== undefined) {+ data.uiPort = uiPortOverride;+ }++ // Honesty gate: if the user changed a port we could NOT write to the+ // source-of-truth config, reject the whole update rather than persist a+ // registry value PM2 will contradict (and the next refresh will revert).+ if (persistFailed) {+ throw new ServerError(+ `Could not persist port change to ${existing.name}'s ecosystem config — the port is derived from process config or is not a literal value. Edit the ecosystem.config.cjs directly to change this port.`,+ { status: 422, code: 'PORT_NOT_PERSISTABLE' }+ );+ }+ }++ // layeredIntelligence must go through the dedicated merge helper — the generic+ // updateApp shallow-REPLACES the nested object, so a partial patch like+ // { layeredIntelligence: { enabled: true } } would wipe stored sources /+ // allowedScopes / providerId / lastRunAt. Pull it out, apply the rest, then+ // merge-apply the config so untouched fields are preserved.+ const { layeredIntelligence: liUpdate, ...rest } = data;+ const app = await appsService.updateApp(req.params.id, rest);++ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (liUpdate !== undefined) {+ const merged = await appsService.updateAppLayeredIntelligence(req.params.id, liUpdate);+ res.json(merged || app);+ return;+ }++ res.json(app);+}));++// DELETE /api/apps/:id - Delete app (PortOS baseline cannot be deleted)+router.delete('/:id', asyncHandler(async (req, res, next) => {+ if (req.params.id === PORTOS_APP_ID) {+ throw new ServerError('PortOS baseline app cannot be deleted', { status: 403, code: 'PROTECTED' });+ }++ const deleted = await appsService.deleteApp(req.params.id);++ if (!deleted) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }++ res.status(204).send();+}));++// POST /api/apps/:id/archive - Archive app (exclude from COS tasks)+router.post('/:id/archive', asyncHandler(async (req, res) => {+ if (req.params.id === PORTOS_APP_ID) {+ throw new ServerError('PortOS baseline app cannot be archived', { status: 403, code: 'PROTECTED' });+ }++ const app = await appsService.archiveApp(req.params.id);++ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }++ console.log(`📦 Archived app: ${app.name}`);+ notifyAppsChanged('archive');+ res.json(app);+}));++// POST /api/apps/:id/unarchive - Unarchive app (include in COS tasks)+router.post('/:id/unarchive', asyncHandler(async (req, res) => {+ const app = await appsService.unarchiveApp(req.params.id);++ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }++ console.log(`📤 Unarchived app: ${app.name}`);+ notifyAppsChanged('unarchive');+ res.json(app);+}));++export default router;diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.jsnew file mode 100644index 0000000000..1a48b7191e--- /dev/null+++ b/server/routes/apps/crud.test.js@@ -0,0 +1,575 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import crudRoutes from './crud.js';++// Mock the services this router (and its port-config service) touch.+vi.mock('../../services/apps.js', () => ({+ getAllApps: vi.fn(),+ getAppById: vi.fn(),+ createApp: vi.fn(),+ updateApp: vi.fn(),+ deleteApp: vi.fn(),+ archiveApp: vi.fn(),+ unarchiveApp: vi.fn(),+ updateAppLayeredIntelligence: vi.fn(),+ notifyAppsChanged: vi.fn(),+ PORTOS_APP_ID: 'portos-default'+}));++vi.mock('../../services/pm2.js', () => ({+ listProcessesStrict: vi.fn(),+ getAppStatusStrict: vi.fn()+}));++vi.mock('../../services/streamingDetect.js', () => ({+ parseEcosystemFromPath: vi.fn(),+ writeEcosystemPortEdits: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true, remapApplied: true, applied: [], unapplied: [] }),+ usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),+ NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift'])+}));++vi.mock('../../services/appIconDetect.js', () => ({+ detectAppIcon: vi.fn(),+ getIconContentType: vi.fn(),+ isUsableSvg: vi.fn().mockResolvedValue(true)+}));++vi.mock('../../services/xcodeScripts.js', () => ({+ checkScripts: vi.fn().mockReturnValue({ missing: [], present: [] }),+ XCODE_SCRIPT_NAMES: ['deploy.sh', 'take_screenshots.sh', 'take_screenshots_macos.sh']+}));++import * as appsService from '../../services/apps.js';+import * as pm2Service from '../../services/pm2.js';+import * as streamingDetect from '../../services/streamingDetect.js';++describe('Apps CRUD Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', crudRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/apps', () => {+ it('should return list of apps with PM2 status', async () => {+ const mockApps = [+ { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }+ ];+ const mockPm2Processes = [+ { name: 'test-app', status: 'online' }+ ];++ appsService.getAllApps.mockResolvedValue(mockApps);+ pm2Service.listProcessesStrict.mockResolvedValue(mockPm2Processes);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(1);+ expect(response.body[0].overallStatus).toBe('online');+ });++ it('should handle apps with no PM2 processes', async () => {+ const mockApps = [+ { id: 'app-001', name: 'Test App', pm2ProcessNames: [], repoPath: '/tmp/test' }+ ];++ appsService.getAllApps.mockResolvedValue(mockApps);+ pm2Service.listProcessesStrict.mockResolvedValue([]);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body[0].overallStatus).toBe('not_started');+ });++ it('reports unknown + degraded (not not_started) when the PM2 read fails', async () => {+ const mockApps = [+ { id: 'app-001', name: 'Test App', pm2ProcessNames: ['test-app'], repoPath: '/tmp/test' }+ ];++ appsService.getAllApps.mockResolvedValue(mockApps);+ // Strict read returns null on a failed PM2 read — must not collapse into+ // a confident "not started."+ pm2Service.listProcessesStrict.mockResolvedValue(null);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body[0].overallStatus).toBe('unknown');+ expect(response.body[0].degraded).toBe(true);+ expect(response.body[0].pm2Status['test-app'].status).toBe('unknown');+ });++ it('should return empty array when no apps exist', async () => {+ appsService.getAllApps.mockResolvedValue([]);+ pm2Service.listProcessesStrict.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body).toHaveLength(0);+ });+ });++ describe('GET /api/apps/:id', () => {+ it('should return app by ID', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.getAppStatusStrict.mockResolvedValue({ name: 'test-app', status: 'online' });++ const response = await request(app).get('/api/apps/app-001');++ expect(response.status).toBe(200);+ expect(response.body.id).toBe('app-001');+ expect(response.body.pm2Status).toBeDefined();+ });++ it('returns degraded + unknown when the PM2 status read fails', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ // Detail endpoint reads per-process status via the strict variant, which+ // returns null on a failed read — must surface as degraded, not collapse+ // into a confident not_started.+ pm2Service.getAppStatusStrict.mockResolvedValue(null);++ const response = await request(app).get('/api/apps/app-001');++ expect(response.status).toBe(200);+ expect(response.body.overallStatus).toBe('unknown');+ expect(response.body.degraded).toBe(true);+ });++ it('should return 404 if app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).get('/api/apps/app-999');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/apps', () => {+ it('should create a new app', async () => {+ const newApp = {+ name: 'New App',+ repoPath: '/path/to/repo'+ };+ appsService.createApp.mockResolvedValue({ id: 'app-001', ...newApp });++ const response = await request(app)+ .post('/api/apps')+ .send(newApp);++ expect(response.status).toBe(201);+ expect(response.body.id).toBe('app-001');+ expect(appsService.createApp).toHaveBeenCalledWith(expect.objectContaining({ name: 'New App' }));+ });++ it('should return 400 if validation fails', async () => {+ // Missing required fields+ const response = await request(app)+ .post('/api/apps')+ .send({});++ expect(response.status).toBe(400);+ });+ });++ describe('PUT /api/apps/:id', () => {+ it('should update an app', async () => {+ const updates = { name: 'Updated Name' };+ appsService.updateApp.mockResolvedValue({ id: 'app-001', name: 'Updated Name' });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send(updates);++ expect(response.status).toBe(200);+ expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.objectContaining({ name: 'Updated Name' }));+ });++ it('should return 404 if app not found', async () => {+ appsService.updateApp.mockResolvedValue(null);++ const response = await request(app)+ .put('/api/apps/app-999')+ .send({ name: 'Test' });++ expect(response.status).toBe(404);+ });++ it('routes a layeredIntelligence update through the dedicated merge helper (not the shallow updateApp)', async () => {+ appsService.updateApp.mockResolvedValue({ id: 'app-001', name: 'App' });+ appsService.updateAppLayeredIntelligence.mockResolvedValue({ id: 'app-001', layeredIntelligence: { enabled: true, sources: { goals: true } } });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ layeredIntelligence: { enabled: true } });++ expect(response.status).toBe(200);+ // The nested config must NOT be passed to the shallow updateApp (which would wipe it)…+ expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.not.objectContaining({ layeredIntelligence: expect.anything() }));+ // …it goes through the preserving merge helper instead.+ expect(appsService.updateAppLayeredIntelligence).toHaveBeenCalledWith('app-001', { enabled: true });+ expect(response.body.layeredIntelligence.enabled).toBe(true);+ });++ it('writes changed ports back to the ecosystem config (source of truth)', async () => {+ // repoPath must exist on disk so the pathExists guard passes.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173, uiPort: 5174 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173, ui: 5174 } }] });+ appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 6000, uiPort: 6001 });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ apiPort: 6000, uiPort: 6001 });++ expect(response.status).toBe(200);+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(+ process.cwd(),+ expect.arrayContaining([[5173, 6000], [5174, 6001]]),+ []+ );+ });++ it('does not write to the ecosystem config when no port changed', async () => {+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };+ appsService.getAppById.mockResolvedValue(mockApp);+ appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });++ await request(app).put('/api/apps/app-001').send({ name: 'Renamed' });++ expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();+ });++ it('persists a shared-value port change via the per-process-targeted rewrite', async () => {+ // uiPort and apiPort both 6000 in the same process block. A value-keyed+ // rewrite can't split them, so the route routes it to the targeted edits+ // (process + label) instead — the edit now persists rather than 422.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'srv', ports: { api: 6000, ui: 6000 } }] });+ appsService.updateApp.mockResolvedValue({ ...mockApp, uiPort: 7000 });++ const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });++ expect(response.status).toBe(200);+ // Empty value-keyed remap (shared value), one targeted edit.+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(+ process.cwd(),+ [],+ [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]+ );+ expect(appsService.updateApp).toHaveBeenCalled();+ });++ it('persists a request mixing a distinct port (value-keyed) and a shared port (targeted) in one PUT', async () => {+ // devUiPort is distinct (5556) so it goes through the value-keyed remap;+ // apiPort/uiPort share 6000 so the uiPort edit goes through the targeted+ // edits. Both are handed to the single atomic writer in one call.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({+ processes: [+ { name: 'srv', ports: { api: 6000, ui: 6000 } },+ { name: 'srv-ui', ports: { devUi: 5556 } }+ ]+ });+ appsService.updateApp.mockResolvedValue({ ...mockApp, uiPort: 7000, devUiPort: 7001 });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ uiPort: 7000, devUiPort: 7001 });++ expect(response.status).toBe(200);+ // One atomic write: devUiPort (distinct) in remap; uiPort (shared) targeted.+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(+ process.cwd(),+ [[5556, 7001]],+ [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]+ );+ expect(appsService.updateApp).toHaveBeenCalled();+ });++ it('rejects (422) a shared-value port change the targeted rewrite cannot apply', async () => {+ // Shared value, but the targeted rewrite finds no matching literal to+ // change (e.g. derived from a const outside the block) → unapplied → 422.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'srv', ports: { api: 6000, ui: 6000 } }] });+ streamingDetect.writeEcosystemPortEdits.mockResolvedValueOnce({+ file: 'ecosystem.config.cjs', changed: false, remapApplied: false, applied: [],+ unapplied: [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]+ });++ const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });++ expect(response.status).toBe(422);+ expect(appsService.updateApp).not.toHaveBeenCalled();+ });++ it('ignores a submitted uiPort on a derived (served-by-API) app and pins it to the derived value', async () => {+ // App has an API process + Vite dev UI but no literal ports.ui, so the+ // displayed uiPort is derived (= apiPort). The drawer submits all fields+ // and never syncs the UI field to a changed API field, so a stale/echoed+ // or even hand-typed uiPort can't be distinguished from a deliberate+ // (impossible) independent UI change. The route ignores the submitted+ // value: no config write for the UI port, no 422, and the stored uiPort is+ // pinned to the derived value so it keeps tracking the API port.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };+ appsService.getAppById.mockResolvedValue(mockApp);+ // Parser yields api + devUi only; ui is derived from api (served-by-API).+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({+ processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]+ });+ appsService.updateApp.mockResolvedValue({ ...mockApp });++ const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });++ expect(response.status).toBe(200);+ // No API port change → no config rewrite for the (ignored) UI port.+ expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();+ // Stored uiPort pinned to the derived value (= unchanged apiPort 6000),+ // NOT the submitted 7000.+ const updateArg = appsService.updateApp.mock.calls[0][1];+ expect(updateArg.uiPort).toBe(6000);+ });++ it('strips the echoed derived uiPort so it is never persisted as an explicit field', async () => {+ // Same served-by-API shape; the modal echoes the derived uiPort (6000)+ // unchanged on a rename. That must NOT 422, but it also must NOT be stored+ // as a STALE explicit uiPort — the route pins it to the current derived+ // value so it keeps tracking apiPort instead of freezing.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({+ processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]+ });+ appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ name: 'Renamed', uiPort: 6000 });++ expect(response.status).toBe(200);+ expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();+ // uiPort pinned to the derived value (= unchanged apiPort 6000) so a stale+ // stored value can't survive the merge.+ const updateArg = appsService.updateApp.mock.calls[0][1];+ expect(updateArg.uiPort).toBe(6000);+ expect(updateArg.name).toBe('Renamed');+ });++ it('changing apiPort on a served-by-API app (UI following the new API port) persists the API port and pins uiPort to the new derived value', async () => {+ // Valid combined save: API 6000→7000 with the UI following to 7000 (the+ // derived port tracks the new API port). The apiPort edit persists via the+ // value-keyed rewrite; the stored uiPort is overwritten with the NEW+ // derived value (7000) so a stale 6000 can't survive the updateApp merge+ // and block re-derivation.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({+ processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]+ });+ appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 7000, uiPort: 7000 });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ apiPort: 7000, uiPort: 7000 });++ expect(response.status).toBe(200);+ // apiPort (distinct, value-keyed) persisted; uiPort follows → not in remap.+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(+ process.cwd(),+ [[6000, 7000]],+ []+ );+ const updateArg = appsService.updateApp.mock.calls[0][1];+ expect(updateArg.uiPort).toBe(7000); // pinned to new derived value+ expect(updateArg.apiPort).toBe(7000);+ });++ it('accepts the common API-only edit (drawer echoes the stale derived uiPort) and pins uiPort to the new API port', async () => {+ // The drawer submits all fields and does NOT sync the UI field when the+ // API field changes, so a normal API-only edit arrives as+ // { apiPort: 7000, uiPort: 6000 (old derived) }. That stale echo must NOT+ // 422 — the API port persists via the value-keyed rewrite and the stored+ // uiPort is pinned to the NEW derived value (7000), not the echoed 6000.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({+ processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]+ });+ appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 7000, uiPort: 7000 });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ apiPort: 7000, uiPort: 6000 });++ expect(response.status).toBe(200);+ // API port persisted; the stale echoed UI port is ignored, not remapped.+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(+ process.cwd(),+ [[6000, 7000]],+ []+ );+ const updateArg = appsService.updateApp.mock.calls[0][1];+ expect(updateArg.uiPort).toBe(7000); // pinned to NEW derived value, not echoed 6000+ expect(updateArg.apiPort).toBe(7000);+ });++ it('does not reject a non-port edit on an app whose top-level ports are not stored (derived)', async () => {+ // apps.json has no apiPort/uiPort (derived from processes); a rename+ // submits the echoed display values. Those must not read as port changes.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd() };+ appsService.getAppById.mockResolvedValue(mockApp);+ // Config currently serves these derived ports; the modal echoes them back.+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5555, ui: 5556 } }] });+ appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ name: 'Renamed', apiPort: 5555, uiPort: 5556 });++ expect(response.status).toBe(200);+ expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();+ expect(appsService.updateApp).toHaveBeenCalled();+ });++ it('rejects (422) when the port literal is not found in the config (changed:false)', async () => {+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173 } }] });+ streamingDetect.writeEcosystemPortEdits.mockResolvedValueOnce({ file: 'ecosystem.config.cjs', changed: false, remapApplied: false, applied: [], unapplied: [] });++ const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });++ expect(response.status).toBe(422);+ expect(appsService.updateApp).not.toHaveBeenCalled();+ });++ it('fails the request (and does not update the registry) when the config write throws', async () => {+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173 } }] });+ streamingDetect.writeEcosystemPortEdits.mockRejectedValueOnce(new Error('EACCES'));++ const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });++ expect(response.status).toBeGreaterThanOrEqual(500);+ // Registry write must not happen after a failed canonical-config write.+ expect(appsService.updateApp).not.toHaveBeenCalled();+ });+ });++ describe('DELETE /api/apps/:id', () => {+ it('should delete an app', async () => {+ appsService.deleteApp.mockResolvedValue(true);++ const response = await request(app).delete('/api/apps/app-001');++ expect(response.status).toBe(204);+ expect(appsService.deleteApp).toHaveBeenCalledWith('app-001');+ });++ it('should return 404 if app not found', async () => {+ appsService.deleteApp.mockResolvedValue(false);++ const response = await request(app).delete('/api/apps/app-999');++ expect(response.status).toBe(404);+ });++ it('should return 403 when deleting PortOS baseline app', async () => {+ const response = await request(app).delete('/api/apps/portos-default');++ expect(response.status).toBe(403);+ expect(appsService.deleteApp).not.toHaveBeenCalled();+ });+ });++ describe('POST /api/apps/:id/archive', () => {+ it('should return 403 when archiving PortOS baseline app', async () => {+ const response = await request(app).post('/api/apps/portos-default/archive');++ expect(response.status).toBe(403);+ expect(appsService.archiveApp).not.toHaveBeenCalled();+ });+ });++ describe('GET /api/apps - devUiPort enrichment', () => {+ it('should include devUiPort derived from process ports.devUi', async () => {+ const mockApps = [{+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-app'],+ repoPath: '/tmp/test',+ processes: [{ name: 'test-app', ports: { devUi: 5554 } }]+ }];+ appsService.getAllApps.mockResolvedValue(mockApps);+ pm2Service.listProcessesStrict.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body[0].devUiPort).toBe(5554);+ });++ it('should derive uiPort from apiPort when app has devUi but no ui process', async () => {+ const mockApps = [{+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-api', 'test-ui'],+ repoPath: '/tmp/test',+ processes: [+ { name: 'test-api', ports: { api: 5551 } },+ { name: 'test-ui', ports: { devUi: 5550 } }+ ]+ }];+ appsService.getAllApps.mockResolvedValue(mockApps);+ pm2Service.listProcessesStrict.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body[0].uiPort).toBe(5551);+ expect(response.body[0].devUiPort).toBe(5550);+ expect(response.body[0].apiPort).toBe(5551);+ });++ it('should use explicit devUiPort over derived value', async () => {+ const mockApps = [{+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-app'],+ repoPath: '/tmp/test',+ devUiPort: 4444,+ processes: [{ name: 'test-app', ports: { devUi: 5554 } }]+ }];+ appsService.getAllApps.mockResolvedValue(mockApps);+ pm2Service.listProcessesStrict.mockResolvedValue([]);++ const response = await request(app).get('/api/apps');++ expect(response.status).toBe(200);+ expect(response.body[0].devUiPort).toBe(4444);+ });+ });+});diff --git a/server/routes/apps/documents.js b/server/routes/apps/documents.jsnew file mode 100644index 0000000000..24ec34ff7f--- /dev/null+++ b/server/routes/apps/documents.js@@ -0,0 +1,118 @@+/**+ * App document endpoints — read/list a fixed allowlist of planning docs and+ * write-with-git-commit updates.+ *+ * GET /:id/documents → { documents, hasPlanning, gsd }+ * GET /:id/documents/:filename → { filename, content }+ * PUT /:id/documents/:filename → { success, hash?, created } (git commit)+ */++import { Router } from 'express';+import { readFile } from 'fs/promises';+import { join, resolve } from 'path';+import { atomicWrite } from '../../lib/fileUtils.js';+import { documentUpdateSchema } from '../../lib/validation.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import * as git from '../../services/git.js';+import { loadApp, pathExists } from './shared.js';++const router = Router();++const ALLOWED_DOCUMENTS = ['PLAN.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];++// GET /api/apps/:id/documents - List which documents exist+router.get('/:id/documents', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!app.repoPath || !await pathExists(app.repoPath)) {+ return res.json({ documents: [], hasPlanning: false });+ }++ const documents = await Promise.all(ALLOWED_DOCUMENTS.map(async filename => ({+ filename,+ exists: await pathExists(join(app.repoPath, filename))+ })));++ const planningDir = join(app.repoPath, '.planning');+ const hasPlanning = await pathExists(planningDir);++ // GSD status: detect which GSD artifacts exist+ const gsd = {+ hasCodebaseMap: await pathExists(join(planningDir, 'codebase')),+ hasProject: await pathExists(join(planningDir, 'PROJECT.md')),+ hasRoadmap: await pathExists(join(planningDir, 'ROADMAP.md')),+ hasState: await pathExists(join(planningDir, 'STATE.md')),+ hasConcerns: await pathExists(join(planningDir, 'CONCERNS.md')),+ };++ res.json({ documents, hasPlanning, gsd });+}));++// GET /api/apps/:id/documents/:filename - Read a single document+router.get('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const { filename } = req.params;++ if (!ALLOWED_DOCUMENTS.includes(filename)) {+ throw new ServerError('Document not in allowlist', { status: 400, code: 'INVALID_DOCUMENT' });+ }++ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ const filePath = join(app.repoPath, filename);+ const resolved = resolve(filePath);++ // Path traversal guard+ if (!resolved.startsWith(resolve(app.repoPath))) {+ throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });+ }++ if (!await pathExists(resolved)) {+ throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });+ }++ const content = await readFile(resolved, 'utf-8');+ res.json({ filename, content });+}));++// PUT /api/apps/:id/documents/:filename - Update a document and git commit+router.put('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const { filename } = req.params;++ if (!ALLOWED_DOCUMENTS.includes(filename)) {+ throw new ServerError('Document not in allowlist', { status: 400, code: 'INVALID_DOCUMENT' });+ }++ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ const filePath = join(app.repoPath, filename);+ const resolved = resolve(filePath);++ if (!resolved.startsWith(resolve(app.repoPath))) {+ throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });+ }++ const { content, commitMessage } = documentUpdateSchema.parse(req.body);+ const created = !await pathExists(resolved);++ await atomicWrite(resolved, content);+ await git.stageFiles(app.repoPath, [filename]);++ const status = await git.getStatus(app.repoPath);+ if (status.clean) {+ return res.json({ success: true, noChanges: true });+ }++ const message = commitMessage || `docs: update ${filename} via PortOS`;+ const result = await git.commit(app.repoPath, message);+ console.log(`📝 ${created ? 'Created' : 'Updated'} ${filename} in ${app.name} (${result.hash})`);++ res.json({ success: true, hash: result.hash, created });+}));++export default router;diff --git a/server/routes/apps/icons.js b/server/routes/apps/icons.jsnew file mode 100644index 0000000000..cc132a6533--- /dev/null+++ b/server/routes/apps/icons.js@@ -0,0 +1,116 @@+/**+ * App icon serving + detection.+ *+ * GET /:id/icon → image bytes (ETag / CSP-guarded SVG)+ * POST /detect-icons → { success, detected, total } (all apps)+ * POST /:id/detect-icon → { success, detected, appIconPath } (single app)+ */++import { Router } from 'express';+import { readFile, stat } from 'fs/promises';+import { extname } from 'path';+import * as appsService from '../../services/apps.js';+import { notifyAppsChanged } from '../../services/apps.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { detectAppIcon, getIconContentType, isUsableSvg } from '../../services/appIconDetect.js';+import { loadApp, pathExists } from './shared.js';++const router = Router();++// GET /api/apps/:id/icon - Serve the app's detected icon image+router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ // Use stored appIconPath, or detect on-the-fly. Stored SVGs that embed an+ // external <image href="..."> render blank under the route's `default-src+ // 'none'` CSP, so re-detect when the cached path is an unusable SVG (e.g.+ // PortOS's own favicon.svg, which wraps a /portos-logo.png reference) —+ // otherwise installs that resolved an icon BEFORE the detector learned to+ // skip these stay broken until the user manually re-detects.+ let iconPath = app.appIconPath;+ const stale =+ !iconPath ||+ !await pathExists(iconPath) ||+ (extname(iconPath).toLowerCase() === '.svg' && !await isUsableSvg(iconPath));+ if (stale) {+ iconPath = await detectAppIcon(app.repoPath, app.type);+ if (iconPath && iconPath !== app.appIconPath) {+ await appsService.updateApp(app.id, { appIconPath: iconPath });+ }+ }++ if (!iconPath || !await pathExists(iconPath)) {+ throw new ServerError('No app icon found', { status: 404 });+ }++ const contentType = getIconContentType(iconPath);+ const iconStat = await stat(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));+ if (!iconStat) throw new ServerError('No app icon found', { status: 404 });+ const etag = `W/"${iconStat.mtimeMs.toString(36)}-${iconStat.size.toString(36)}"`;++ res.set('Content-Type', contentType);+ res.set('Cache-Control', 'public, max-age=3600');+ res.set('ETag', etag);+ res.set('X-Content-Type-Options', 'nosniff');+ if (contentType === 'image/svg+xml') {+ res.set('Content-Disposition', 'inline; filename="icon.svg"');+ res.set('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'");+ }++ const ifNoneMatch = req.headers['if-none-match'];+ if (ifNoneMatch) {+ const tags = ifNoneMatch.split(',').map(v => v.trim());+ if (tags.includes('*') || tags.includes(etag)) {+ return res.status(304).end();+ }+ }++ const iconData = await readFile(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));+ if (!iconData) throw new ServerError('No app icon found', { status: 404 });+ res.send(iconData);+}));++// POST /api/apps/detect-icons - Detect and persist app icons for all apps+router.post('/detect-icons', asyncHandler(async (req, res) => {+ const apps = await appsService.getAllApps();+ let detected = 0;++ for (const app of apps) {+ if (!app.repoPath || !await pathExists(app.repoPath)) continue;+ // Skip apps that already have a valid icon path+ if (app.appIconPath && await pathExists(app.appIconPath)) continue;++ const iconPath = await detectAppIcon(app.repoPath, app.type);+ if (iconPath) {+ await appsService.updateApp(app.id, { appIconPath: iconPath });+ detected++;+ console.log(`🎨 Detected icon for ${app.name}: ${iconPath.split('/').pop()}`);+ }+ }++ if (detected > 0) notifyAppsChanged('detect-icons');+ console.log(`🎨 Icon detection complete: ${detected}/${apps.length} apps`);+ res.json({ success: true, detected, total: apps.length });+}));++// POST /api/apps/:id/detect-icon - Detect and persist app icon for a single app+router.post('/:id/detect-icon', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repoPath is missing or inaccessible', { status: 400, code: 'INVALID_REPO_PATH' });+ }++ const iconPath = await detectAppIcon(app.repoPath, app.type);+ if (!iconPath) {+ console.log(`🎨 No icon detected for ${app.name}`);+ res.json({ success: true, detected: false, appIconPath: null });+ return;+ }++ await appsService.updateApp(app.id, { appIconPath: iconPath });+ notifyAppsChanged('detect-icon');+ console.log(`🎨 Detected icon for ${app.name}: ${iconPath.split('/').pop()}`);+ res.json({ success: true, detected: true, appIconPath: iconPath });+}));++export default router;diff --git a/server/routes/apps/icons.test.js b/server/routes/apps/icons.test.jsnew file mode 100644index 0000000000..d235d80e2e--- /dev/null+++ b/server/routes/apps/icons.test.js@@ -0,0 +1,105 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import iconRoutes from './icons.js';++vi.mock('../../services/apps.js', () => ({+ getAllApps: vi.fn(),+ getAppById: vi.fn(),+ updateApp: vi.fn(),+ notifyAppsChanged: vi.fn(),+ PORTOS_APP_ID: 'portos-default'+}));++vi.mock('../../services/appIconDetect.js', () => ({+ detectAppIcon: vi.fn(),+ getIconContentType: vi.fn(),+ isUsableSvg: vi.fn().mockResolvedValue(true)+}));++import * as appsService from '../../services/apps.js';+import { detectAppIcon, getIconContentType, isUsableSvg } from '../../services/appIconDetect.js';+import { writeFileSync, mkdirSync, rmSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';++describe('Apps Icon Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', iconRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/apps/:id/icon', () => {+ const iconDir = join(tmpdir(), 'portos-test-icon');+ const iconPath = join(iconDir, 'icon.png');+ const mockApp = { id: 'app-001', name: 'Test App', appIconPath: iconPath, repoPath: '/tmp/test', pm2ProcessNames: [] };++ beforeEach(() => {+ mkdirSync(iconDir, { recursive: true });+ writeFileSync(iconPath, 'fake-png-data');+ appsService.getAppById.mockResolvedValue(mockApp);+ getIconContentType.mockReturnValue('image/png');+ });++ afterAll(() => {+ rmSync(iconDir, { recursive: true, force: true });+ });++ it('should return icon with ETag header', async () => {+ const response = await request(app).get('/api/apps/app-001/icon');++ expect(response.status).toBe(200);+ expect(response.headers['etag']).toBeDefined();+ expect(response.headers['etag']).toMatch(/^W\//);+ expect(response.headers['cache-control']).toBe('public, max-age=3600');+ });++ it('should return 304 when If-None-Match matches ETag', async () => {+ const first = await request(app).get('/api/apps/app-001/icon');+ const etag = first.headers['etag'];++ const second = await request(app)+ .get('/api/apps/app-001/icon')+ .set('If-None-Match', etag);++ expect(second.status).toBe(304);+ });++ it('should return 304 when If-None-Match contains multiple ETags including match', async () => {+ const first = await request(app).get('/api/apps/app-001/icon');+ const etag = first.headers['etag'];++ const second = await request(app)+ .get('/api/apps/app-001/icon')+ .set('If-None-Match', `W/"other-etag", ${etag}, W/"another"`);++ expect(second.status).toBe(304);+ });++ it('redetects when stored path is an unusable SVG (external <image href>) so PortOS-style icons recover', async () => {+ // Simulate the bad-state PortOS install: appIconPath stored as an SVG+ // that exists on disk but embeds <image href="/portos-logo.png"> — CSP+ // blocks the embed, so it renders blank. The route must re-detect.+ const badSvgPath = join(iconDir, 'favicon.svg');+ const goodPngPath = join(iconDir, 'redetected.png');+ writeFileSync(badSvgPath, '<svg><image href="/logo.png"/></svg>');+ writeFileSync(goodPngPath, 'fake-png-data');+ appsService.getAppById.mockResolvedValue({+ ...mockApp,+ appIconPath: badSvgPath,+ });+ isUsableSvg.mockResolvedValueOnce(false);+ detectAppIcon.mockResolvedValueOnce(goodPngPath);++ const response = await request(app).get('/api/apps/app-001/icon');++ expect(response.status).toBe(200);+ expect(detectAppIcon).toHaveBeenCalledWith('/tmp/test', undefined);+ expect(appsService.updateApp).toHaveBeenCalledWith('app-001', { appIconPath: goodPngPath });+ });+ });+});diff --git a/server/routes/apps/index.js b/server/routes/apps/index.jsnew file mode 100644index 0000000000..414fd0f005--- /dev/null+++ b/server/routes/apps/index.js@@ -0,0 +1,49 @@+/**+ * Apps Routes — assembled from domain-focused sub-routers, all mounted at the+ * same `/api/apps` base (mirrors the pipeline sub-router pattern). Splitting the+ * former ~1,380-line single file into these domains preserves the exact+ * `/api/apps` contract, the shared `loadApp` middleware, and the centralized+ * error behavior (every handler still throws `ServerError` to the middleware).+ *+ * crud — GET/POST/PUT/DELETE /, /:id, archive/unarchive, status enrichment+ * lifecycle — PM2 start/stop/restart, update, build, status, logs, refresh-config+ * viteTls — upgrade-tls, vite-host-check, fix-vite-hosts (config repair)+ * xcode — xcode-scripts/install+ * icons — icon serving + detection+ * taskTypes — per-app task-type overrides, work-tracker, layered-intelligence+ * launch — open-editor, open-claude, open-folder+ * documents — planning-doc read/list/commit+ * agents — recent CoS agent history+ *+ * Route ordering is safe across sub-routers: every param route is either the+ * single-segment `/:id` or a deeper `/:id/...`, and the static routes+ * (`/detect-icons`, `/bulk-task-type/:taskType`) differ from `/:id` by method or+ * segment count, so no sub-router can shadow another's routes. The only+ * order-sensitive pair (`/:id/task-types/all` before `/:id/task-types/:taskType`)+ * lives entirely inside `taskTypes.js`.+ */++import { Router } from 'express';+import crudRoutes from './crud.js';+import lifecycleRoutes from './lifecycle.js';+import viteTlsRoutes from './viteTls.js';+import xcodeRoutes from './xcode.js';+import iconRoutes from './icons.js';+import taskTypeRoutes from './taskTypes.js';+import launchRoutes from './launch.js';+import documentRoutes from './documents.js';+import agentRoutes from './agents.js';++const router = Router();++router.use(crudRoutes);+router.use(lifecycleRoutes);+router.use(viteTlsRoutes);+router.use(xcodeRoutes);+router.use(iconRoutes);+router.use(taskTypeRoutes);+router.use(launchRoutes);+router.use(documentRoutes);+router.use(agentRoutes);++export default router;diff --git a/server/routes/apps/launch.js b/server/routes/apps/launch.jsnew file mode 100644index 0000000000..99c1675336--- /dev/null+++ b/server/routes/apps/launch.js@@ -0,0 +1,146 @@+/**+ * Local launch helpers: open the app in an editor, in Claude Code, or in the+ * OS file manager. Each spawns a detached child process.+ *+ * POST /:id/open-editor → { success, command, path }+ * POST /:id/open-claude → { success, path }+ * POST /:id/open-folder → { success, path }+ */++import { Router } from 'express';+import { spawn } from 'child_process';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { loadApp, pathExists } from './shared.js';++const router = Router();++// Allowlist of safe editor commands+// Security: Only allow known-safe editor commands to prevent arbitrary code execution+const ALLOWED_EDITORS = new Set([+ 'code', // VS Code+ 'cursor', // Cursor+ 'zed', // Zed+ 'subl', // Sublime Text+ 'atom', // Atom+ 'vim', // Vim+ 'nvim', // Neovim+ 'nano', // Nano+ 'emacs', // Emacs+ 'idea', // IntelliJ IDEA+ 'pycharm', // PyCharm+ 'webstorm', // WebStorm+ 'phpstorm', // PhpStorm+ 'rubymine', // RubyMine+ 'goland', // GoLand+ 'clion', // CLion+ 'rider', // Rider+ 'studio', // Android Studio+ 'xed' // Xcode+]);++// POST /api/apps/:id/open-editor - Open app in editor+router.post('/:id/open-editor', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!await pathExists(app.repoPath)) {+ throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ const editorCommand = app.editorCommand || 'code .';+ const [cmd, ...args] = editorCommand.split(/\s+/);++ // Security: Validate that the editor command is in our allowlist+ // This prevents arbitrary command execution via malicious editorCommand values+ if (!ALLOWED_EDITORS.has(cmd)) {+ throw new ServerError(`Editor '${cmd}' is not in the allowed editors list`, {+ status: 400,+ code: 'INVALID_EDITOR',+ context: { allowedEditors: Array.from(ALLOWED_EDITORS) }+ });+ }++ // Security: Validate args don't contain shell metacharacters+ const DANGEROUS_CHARS = /[;|&`$(){}[\]<>\\!#*?~]/;+ for (const arg of args) {+ if (DANGEROUS_CHARS.test(arg)) {+ throw new ServerError('Editor arguments contain disallowed characters', {+ status: 400,+ code: 'INVALID_EDITOR_ARGS'+ });+ }+ }++ // Spawn the editor process detached so it doesn't block.+ // On Windows, editor binaries are typically `.cmd`/`.bat` shims (e.g. `code.cmd`,+ // `cursor.cmd`) which Node refuses to spawn without a shell since 20.12.2 — so we+ // opt into the shell on win32. Args are pre-sanitized for shell metacharacters+ // above, and the command is allowlisted.+ const child = spawn(cmd, args, {+ cwd: app.repoPath,+ detached: true,+ stdio: 'ignore',+ shell: process.platform === 'win32',+ windowsHide: true+ });+ child.unref();++ res.json({ success: true, command: editorCommand, path: app.repoPath });+}));++// POST /api/apps/:id/open-claude - Open Claude Code in app directory+router.post('/:id/open-claude', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!await pathExists(app.repoPath)) {+ throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ // shell:true on Windows so `claude.cmd` resolves (see open-editor above for the+ // Node 20.12.2 rationale). No user args reach the command line here.+ const child = spawn('claude', [], {+ cwd: app.repoPath,+ detached: true,+ stdio: 'ignore',+ shell: process.platform === 'win32',+ windowsHide: true+ });+ child.unref();++ console.log(`🤖 Opened Claude Code in ${app.name}`);+ res.json({ success: true, path: app.repoPath });+}));++// POST /api/apps/:id/open-folder - Open app folder in file manager+router.post('/:id/open-folder', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!await pathExists(app.repoPath)) {+ throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ // Cross-platform folder open command+ const platform = process.platform;+ let cmd, args;++ if (platform === 'darwin') {+ cmd = 'open';+ args = [app.repoPath];+ } else if (platform === 'win32') {+ cmd = 'explorer';+ args = [app.repoPath];+ } else {+ cmd = 'xdg-open';+ args = [app.repoPath];+ }++ const child = spawn(cmd, args, {+ detached: true,+ stdio: 'ignore',+ windowsHide: true+ });+ child.unref();++ res.json({ success: true, path: app.repoPath });+}));++export default router;diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.jsnew file mode 100644index 0000000000..045cf6da6d--- /dev/null+++ b/server/routes/apps/lifecycle.js@@ -0,0 +1,300 @@+/**+ * App runtime lifecycle: PM2 start/stop/restart, update, build, status, logs,+ * and ecosystem-config refresh.+ *+ * POST /:id/start → { success, results }+ * POST /:id/stop → { success, results }+ * POST /:id/restart → { success, results } (self-restart for PortOS)+ * POST /:id/update → { success, steps, progress }+ * POST /:id/build → { success, output }+ * GET /:id/status → { [process]: status }+ * GET /:id/logs → { processName, lines, logs }+ * POST /:id/refresh-config → { success, updated, app, processes }+ */++import { Router } from 'express';+import { join, extname } from 'path';+import { tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';+import * as appsService from '../../services/apps.js';+import { notifyAppsChanged, PORTOS_APP_ID } from '../../services/apps.js';+import * as pm2Service from '../../services/pm2.js';+import * as appUpdater from '../../services/appUpdater.js';+import * as appBuilder from '../../services/appBuilder.js';+import { logAction } from '../../services/history.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { parseEcosystemFromPath, usesPm2 } from '../../services/streamingDetect.js';+import { detectAppIcon, isUsableSvg } from '../../services/appIconDetect.js';+import { loadApp, pathExists, deriveUiPort } from './shared.js';++const router = Router();++// Delay before restarting PortOS itself so the JSON response reaches the client+const SELF_RESTART_RESPONSE_DELAY_MS = 500;++// POST /api/apps/:id/start - Start app via PM2+router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!usesPm2(app.type)) {+ throw new ServerError(`${app.type} apps cannot be started via PM2`, { status: 400, code: 'NOT_PM2_APP' });+ }++ const processNames = app.pm2ProcessNames || [app.name.toLowerCase().replace(/\s+/g, '-')];++ // Check if ecosystem config exists - prefer using it for proper env var handling+ const ecosystemChecks = await Promise.all(+ ['ecosystem.config.cjs', 'ecosystem.config.js'].map(f => pathExists(`${app.repoPath}/${f}`))+ );+ const hasEcosystem = ecosystemChecks.some(Boolean);++ let results = {};++ if (hasEcosystem) {+ // Use ecosystem config for proper env/port configuration+ // 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) {+ results[name] = result;+ }+ } else {+ // Fallback to command-based start for apps without ecosystem config+ const commands = app.startCommands || ['npm run dev'];+ for (let i = 0; i < processNames.length; i++) {+ const name = processNames[i];+ const command = commands[i] || commands[0];+ const result = await pm2Service.startWithCommand(name, app.repoPath, command)+ .catch(err => ({ success: false, error: err.message }));+ results[name] = result;+ }+ }++ const allSuccess = Object.values(results).every(r => r.success !== false);+ await logAction('start', app.id, app.name, { processNames }, allSuccess);+ notifyAppsChanged('start');++ res.json({ success: true, results });+}));++// POST /api/apps/:id/stop - Stop app+router.post('/:id/stop', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!usesPm2(app.type)) {+ throw new ServerError(`${app.type} apps cannot be stopped via PM2`, { status: 400, code: 'NOT_PM2_APP' });+ }++ const results = {};++ for (const name of app.pm2ProcessNames || []) {+ const result = await pm2Service.stopApp(name, app.pm2Home)+ .catch(err => ({ success: false, error: err.message }));+ results[name] = result;+ }++ const allSuccess = Object.values(results).every(r => r.success !== false);+ await logAction('stop', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);+ notifyAppsChanged('stop');++ res.json({ success: true, results });+}));++// POST /api/apps/:id/restart - Restart app+router.post('/:id/restart', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!usesPm2(app.type)) {+ throw new ServerError(`${app.type} apps cannot be restarted via PM2`, { status: 400, code: 'NOT_PM2_APP' });+ }++ // Self-restart: respond first, then restart after a delay so the response reaches the client+ if (app.id === PORTOS_APP_ID) {+ await logAction('restart', app.id, app.name, { processNames: app.pm2ProcessNames }, true);+ notifyAppsChanged('restart');+ res.json({ success: true, selfRestart: true });+ setTimeout(async () => {+ console.log('🔄 Self-restart: restarting PortOS processes');+ for (const name of app.pm2ProcessNames || []) {+ await pm2Service.restartApp(name, app.pm2Home)+ .catch(err => console.error(`❌ Self-restart failed for ${name}: ${err.message}`));+ }+ }, SELF_RESTART_RESPONSE_DELAY_MS);+ return;+ }++ const results = {};++ for (const name of app.pm2ProcessNames || []) {+ const result = await pm2Service.restartApp(name, app.pm2Home)+ .catch(err => ({ success: false, error: err.message }));+ results[name] = result;+ }++ const allSuccess = Object.values(results).every(r => r.success !== false);+ await logAction('restart', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);+ notifyAppsChanged('restart');++ res.json({ success: true, results });+}));++// POST /api/apps/:id/update - Pull, install deps, setup, restart+router.post('/:id/update', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ console.log(`⬇️ Starting update for ${app.name}`);+ const progressSteps = [];+ const emit = (step, status, message) => {+ progressSteps.push({ step, status, message, timestamp: Date.now() });+ };++ const result = await appUpdater.updateApp(app, emit);+ const success = result.success;+ await logAction('update', app.id, app.name, { steps: result.steps }, success);+ notifyAppsChanged('update');+ console.log(`${success ? '✅' : '❌'} Update ${success ? 'complete' : 'failed'} for ${app.name}`);++ res.json({ success, steps: result.steps, progress: progressSteps });+}));++// POST /api/apps/:id/build - Build production UI+router.post('/:id/build', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!await pathExists(app.repoPath)) {+ throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ const result = await appBuilder.buildApp(app);++ if (result.failure === 'validation') {+ throw new ServerError(result.message, { status: 400, code: result.code });+ }++ if (result.failure === 'install') {+ await logAction('build', app.id, app.name, { buildCommand: result.buildCommand, step: `npm install (${result.label})` }, false);+ throw new ServerError(`npm install failed (${result.label}) exit=${result.exitCode}: ${result.output}`, { status: 500, code: 'INSTALL_FAILED' });+ }++ await logAction('build', app.id, app.name, { buildCommand: result.buildCommand }, result.success);++ if (!result.success) {+ const detail = result.signal ? `killed by ${result.signal}` : result.output || `exit code ${result.code}`;+ throw new ServerError(`Build failed: ${detail}`, { status: 500, code: 'BUILD_FAILED' });+ }++ res.json({ success: true, output: result.output });+}));++// GET /api/apps/:id/status - Get PM2 status+router.get('/:id/status', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!usesPm2(app.type)) {+ return res.json({});+ }++ const statuses = {};++ for (const name of app.pm2ProcessNames || []) {+ const status = await pm2Service.getAppStatus(name, app.pm2Home)+ .catch(err => ({ status: 'error', error: err.message }));+ statuses[name] = status;+ }++ res.json(statuses);+}));++// GET /api/apps/:id/logs - Get logs+router.get('/:id/logs', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const lines = parseInt(req.query.lines, 10) || 100;+ const processName = req.query.process || app.pm2ProcessNames?.[0];++ if (!processName) {+ throw new ServerError('No process name specified', { status: 400, code: 'MISSING_PROCESS' });+ }++ const logs = await pm2Service.getLogs(processName, lines, app.pm2Home)+ .catch(err => `Error retrieving logs: ${err.message}`);++ res.json({ processName, lines, logs });+}));++// POST /api/apps/:id/refresh-config - Re-parse ecosystem config for PM2 processes+router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;++ if (!usesPm2(app.type)) {+ return res.json({ success: true, updated: false, app, processes: [] });+ }++ if (!await pathExists(app.repoPath)) {+ throw new ServerError('App path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });+ }++ // Parse ecosystem config from the app's repo path+ const { processes, pm2Home } = await parseEcosystemFromPath(app.repoPath);++ // Update app with new process data+ const updates = {};++ // Detect buildCommand from package.json if not already set+ if (!app.buildCommand) {+ const pkgPath = join(app.repoPath, 'package.json');+ const pkgContent = await tryReadFile(pkgPath);+ if (pkgContent) {+ const pkg = safeJSONParse(pkgContent);+ if (pkg?.scripts?.build) updates.buildCommand = 'npm run build';+ }+ }++ // Update pm2Home if detected and different from current+ if (pm2Home && pm2Home !== app.pm2Home) {+ updates.pm2Home = pm2Home;+ }++ if (processes.length > 0) {+ updates.processes = processes;+ updates.pm2ProcessNames = processes.map(p => p.name);++ // Derive ports from parsed process labels (same logic as streamDetection)+ const apiProc = processes.find(p => p.ports?.api);+ if (apiProc) updates.apiPort = apiProc.ports.api;++ const uiProc = processes.find(p => p.ports?.ui);+ if (uiProc) updates.uiPort = uiProc.ports.ui;++ const devUiProc = processes.find(p => p.ports?.devUi);+ if (devUiProc) updates.devUiPort = devUiProc.ports.devUi;++ updates.uiPort = deriveUiPort(updates.uiPort, updates.apiPort, updates.devUiPort || app.devUiPort);+ }++ // Detect app icon if not already set, missing on disk, or stored as an+ // unusable external-image SVG (won't render under the icon route's CSP).+ const iconStale =+ !app.appIconPath ||+ !await pathExists(app.appIconPath) ||+ (extname(app.appIconPath).toLowerCase() === '.svg' && !await isUsableSvg(app.appIconPath));+ if (iconStale) {+ const detectedIcon = await detectAppIcon(app.repoPath, app.type);+ if (detectedIcon) updates.appIconPath = detectedIcon;+ }++ // Only update if we have changes+ if (Object.keys(updates).length > 0) {+ const updatedApp = await appsService.updateApp(req.params.id, updates);+ console.log(`🔄 Refreshed config for ${app.name}: ${processes.length} processes found`);+ res.json({ success: true, updated: true, app: updatedApp, processes });+ } else {+ console.log(`🔄 No config changes for ${app.name}`);+ res.json({ success: true, updated: false, app, processes: app.processes || [] });+ }+}));++export default router;diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.jsnew file mode 100644index 0000000000..2883cd6f99--- /dev/null+++ b/server/routes/apps/lifecycle.test.js@@ -0,0 +1,266 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import lifecycleRoutes from './lifecycle.js';++// Mock the services this router touches. appBuilder is intentionally NOT mocked+// so the build-command validation branch (INVALID_BUILD_COMMAND) runs for real.+vi.mock('../../services/apps.js', () => ({+ getAppById: vi.fn(),+ updateApp: vi.fn(),+ notifyAppsChanged: vi.fn(),+ PORTOS_APP_ID: 'portos-default'+}));++vi.mock('../../services/pm2.js', () => ({+ getAppStatus: vi.fn(),+ startFromEcosystem: vi.fn(),+ startWithCommand: vi.fn(),+ stopApp: vi.fn(),+ restartApp: vi.fn(),+ getLogs: vi.fn()+}));++vi.mock('../../services/history.js', () => ({+ logAction: vi.fn()+}));++vi.mock('../../services/streamingDetect.js', () => ({+ parseEcosystemFromPath: vi.fn(),+ usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),+ NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift'])+}));++vi.mock('../../services/appUpdater.js', () => ({+ updateApp: vi.fn()+}));++vi.mock('../../services/appIconDetect.js', () => ({+ detectAppIcon: vi.fn(),+ isUsableSvg: vi.fn().mockResolvedValue(true)+}));++import * as appsService from '../../services/apps.js';+import * as pm2Service from '../../services/pm2.js';+import * as history from '../../services/history.js';++describe('Apps Lifecycle Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', lifecycleRoutes);+ vi.clearAllMocks();+ });++ describe('POST /api/apps/:id/start', () => {+ it('should start an app', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ repoPath: '/path/to/repo',+ pm2ProcessNames: ['test-app'],+ startCommands: ['npm run dev']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.startWithCommand.mockResolvedValue({ success: true });+ history.logAction.mockResolvedValue();++ const response = await request(app).post('/api/apps/app-001/start');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(pm2Service.startWithCommand).toHaveBeenCalled();+ expect(history.logAction).toHaveBeenCalledWith('start', 'app-001', 'Test App', expect.any(Object), true);+ });++ it('should return 404 if app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).post('/api/apps/app-999/start');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/apps/:id/stop', () => {+ it('should stop an app', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.stopApp.mockResolvedValue({ success: true });+ history.logAction.mockResolvedValue();++ const response = await request(app).post('/api/apps/app-001/stop');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(pm2Service.stopApp).toHaveBeenCalledWith('test-app', undefined);+ });++ it('should return 404 if app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).post('/api/apps/app-999/stop');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/apps/:id/restart', () => {+ it('should restart an app', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.restartApp.mockResolvedValue({ success: true });+ history.logAction.mockResolvedValue();++ const response = await request(app).post('/api/apps/app-001/restart');++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(pm2Service.restartApp).toHaveBeenCalledWith('test-app', undefined);+ });++ it('should return 404 if app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).post('/api/apps/app-999/restart');++ expect(response.status).toBe(404);+ });+ });++ describe('POST /api/apps/:id/build', () => {+ it('should return 404 if app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).post('/api/apps/app-999/build');++ expect(response.status).toBe(404);+ });++ it.skipIf(process.platform !== 'win32')('should reject build command args containing shell-unsafe metacharacters', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ repoPath: process.cwd(), // real path so pathExists check passes+ buildCommand: 'npm run build&whoami',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);++ const response = await request(app).post('/api/apps/app-001/build');++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('INVALID_BUILD_COMMAND');+ });++ it('should reject build commands not starting with npm or npx', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ repoPath: '/tmp',+ buildCommand: 'rm -rf /',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);++ const response = await request(app).post('/api/apps/app-001/build');++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('INVALID_BUILD_COMMAND');+ });++ it('should return 400 if repo path does not exist', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ repoPath: '/nonexistent/path/that/does/not/exist',+ buildCommand: 'npm run build',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);++ const response = await request(app).post('/api/apps/app-001/build');++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('PATH_NOT_FOUND');+ });+ });++ describe('GET /api/apps/:id/status', () => {+ it('should return PM2 status for app processes', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-api', 'test-worker']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.getAppStatus+ .mockResolvedValueOnce({ status: 'online', cpu: 2.5 })+ .mockResolvedValueOnce({ status: 'stopped' });++ const response = await request(app).get('/api/apps/app-001/status');++ expect(response.status).toBe(200);+ expect(response.body['test-api']).toEqual({ status: 'online', cpu: 2.5 });+ expect(response.body['test-worker']).toEqual({ status: 'stopped' });+ });++ it('should return 404 if app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).get('/api/apps/app-999/status');++ expect(response.status).toBe(404);+ });+ });++ describe('GET /api/apps/:id/logs', () => {+ it('should return logs for app process', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: ['test-app']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.getLogs.mockResolvedValue('Log line 1\nLog line 2');++ const response = await request(app).get('/api/apps/app-001/logs?lines=50');++ expect(response.status).toBe(200);+ expect(response.body.processName).toBe('test-app');+ expect(response.body.lines).toBe(50);+ expect(response.body.logs).toBe('Log line 1\nLog line 2');+ });++ it('should return 404 if app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app).get('/api/apps/app-999/logs');++ expect(response.status).toBe(404);+ });++ it('should return 400 if no process name available', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Test App',+ pm2ProcessNames: []+ };+ appsService.getAppById.mockResolvedValue(mockApp);++ const response = await request(app).get('/api/apps/app-001/logs');++ expect(response.status).toBe(400);+ });+ });+});diff --git a/server/routes/apps/shared.js b/server/routes/apps/shared.jsnew file mode 100644index 0000000000..8a98e3d511--- /dev/null+++ b/server/routes/apps/shared.js@@ -0,0 +1,79 @@+/**+ * Shared plumbing for the apps sub-routers: the `loadApp` param middleware,+ * the async `pathExists` guard, and the pure port/status-derivation helpers+ * used by both the list (`GET /`) and detail (`GET /:id`) endpoints.+ *+ * Mirrors the pipeline sub-router `shared.js` pattern — one small module of+ * common plumbing that every domain router imports, so the split preserves a+ * single `loadApp` / error / enrichment behavior across all of `/api/apps`.+ */++import { access } from 'fs/promises';+import * as appsService from '../../services/apps.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';++/** Async equivalent of existsSync — returns true if the path is accessible */+export const pathExists = (p) => access(p).then(() => true).catch(() => false);++/**+ * Derive uiPort from apiPort when app has dev UI but no dedicated prod UI port+ * (prod UI is served by the API server in these cases).+ */+export function deriveUiPort(uiPort, apiPort, devUiPort) {+ if (!uiPort && apiPort && devUiPort) return apiPort;+ return uiPort;+}++/**+ * Middleware to load app by :id param and attach to req.loadedApp.+ * Throws 404 if not found, eliminating repeated null checks across routes.+ */+export const loadApp = asyncHandler(async (req, res, next) => {+ const app = await appsService.getAppById(req.params.id);+ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }+ req.loadedApp = app;+ next();+});++/**+ * Derive uiPort/apiPort/devUiPort from an app's process list when not+ * explicitly set on the app record. Shared by the list and detail endpoints so+ * the two never diverge. Returns the resolved trio (uiPort passed through+ * deriveUiPort for the served-by-API case).+ */+export function deriveAppPorts(app, processes) {+ let { uiPort, apiPort, devUiPort } = app;+ const procs = processes || [];+ if (!uiPort && procs.length) {+ const uiProc = procs.find(p => p.ports?.ui);+ if (uiProc) uiPort = uiProc.ports.ui;+ }+ if (!apiPort && procs.length) {+ const apiProc = procs.find(p => p.ports?.api);+ if (apiProc) apiPort = apiProc.ports.api;+ }+ if (!devUiPort && procs.length) {+ const devUiProc = procs.find(p => p.ports?.devUi);+ if (devUiProc) devUiPort = devUiProc.ports.devUi;+ }+ uiPort = deriveUiPort(uiPort, apiPort, devUiPort);+ return { uiPort, apiPort, devUiPort };+}++/**+ * Compute the overall status from a set of per-process PM2 statuses. A degraded+ * (failed-read) home short-circuits to `unknown` rather than collapsing to a+ * confident `not_started`. Shared by the list and detail endpoints.+ */+export function computeOverallStatus(statusValues, degraded) {+ // Mirrors the original inline logic exactly: an empty status set (an app with+ // no PM2 process names) satisfies the vacuous `every(...)` and resolves to+ // `not_started`, NOT `unknown`.+ if (degraded) return 'unknown';+ if (statusValues.some(s => s.status === 'online')) return 'online';+ if (statusValues.some(s => s.status === 'stopped')) return 'stopped';+ if (statusValues.every(s => s.status === 'not_found')) return 'not_started';+ return 'unknown';+}diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.jsnew file mode 100644index 0000000000..f450f2f833--- /dev/null+++ b/server/routes/apps/taskTypes.js@@ -0,0 +1,160 @@+/**+ * Per-app task-type overrides + read-only work-tracker / layered-intelligence+ * config resolution.+ *+ * PUT /bulk-task-type/:taskType → { success, appsUpdated } (all active apps)+ * GET /:id/task-types → { taskTypeOverrides }+ * GET /:id/work-tracker → { tracker info }+ * GET /:id/layered-intelligence → { config, isPortos }+ * PUT /:id/task-types/all → { success, taskTypeOverrides }+ * PUT /:id/task-types/:taskType → { success, taskTypeOverrides }+ *+ * ORDER-SENSITIVE: `/:id/task-types/all` MUST be registered before+ * `/:id/task-types/:taskType`, otherwise `all` is captured as a taskType param.+ */++import { Router } from 'express';+import * as appsService from '../../services/apps.js';+import { PORTOS_APP_ID } from '../../services/apps.js';+import { sanitizeTaskMetadata } from '../../lib/validation.js';+import { parseCronToNextRun } from '../../services/eventScheduler.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { SELF_IMPROVEMENT_TASK_TYPES } from '../../services/taskSchedule.js';+import { loadApp } from './shared.js';++const router = Router();++// PUT /api/apps/bulk-task-type/:taskType - Enable/disable a task type for all active apps+router.put('/bulk-task-type/:taskType', asyncHandler(async (req, res) => {+ const { enabled } = req.body;+ if (typeof enabled !== 'boolean') {+ throw new ServerError('enabled (boolean) is required', { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {+ throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });+ }++ const result = await appsService.bulkUpdateAppTaskTypeOverride(req.params.taskType, { enabled });+ console.log(`📋 Bulk ${enabled ? 'enabled' : 'disabled'} task type ${req.params.taskType} for ${result.count} apps`);+ res.json({ success: true, taskType: req.params.taskType, enabled, appsUpdated: result.count });+}));++// GET /api/apps/:id/task-types - Get per-app task type overrides+router.get('/:id/task-types', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const overrides = await appsService.getAppTaskTypeOverrides(app.id);+ res.json({ appId: app.id, appName: app.name, taskTypeOverrides: overrides });+}));++// GET /api/apps/:id/work-tracker - Resolve where this app's autonomous work+// items live (PLAN.md / GitHub / GitLab / JIRA). 'auto' resolves from the git+// origin host; see server/lib/workTracker.js. Read-only — the value itself is+// saved through the generic PUT /api/apps/:id (appUpdateSchema.workTracker).+router.get('/:id/work-tracker', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const info = await appsService.getAppWorkTracker(app.id);+ res.json({ appId: app.id, appName: app.name, ...info });+}));++// GET /api/apps/:id/layered-intelligence - Effective Layered Intelligence config+// for this app (the self-improvement loop). Merges the app's stored partial+// config over the shipped defaults so the UI always renders a complete, safe+// config — including the isPortos-derived scope set. Read-only; the value is+// saved through PUT /api/apps/:id (layeredIntelligence goes via the dedicated+// merge helper there). See server/services/layeredIntelligence.js.+router.get('/:id/layered-intelligence', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const config = await appsService.getAppLayeredIntelligenceConfig(app.id);+ res.json({ appId: app.id, appName: app.name, isPortos: app.id === PORTOS_APP_ID, config });+}));++// PUT /api/apps/:id/task-types/all - Toggle all task types for an app+router.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {+ const { enabled } = req.body;+ if (typeof enabled !== 'boolean') {+ throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const result = await appsService.toggleAllAppTaskTypes(req.params.id, enabled);+ if (!result) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }+ console.log(`📋 ${enabled ? 'Enabled' : 'Disabled'} all task types for ${result.name}`);+ res.json({ success: true, appId: result.id, taskTypeOverrides: result.taskTypeOverrides || {} });+}));++// PUT /api/apps/:id/task-types/:taskType - Update a task type override for an app+router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {+ const { enabled, interval, intervalMs, providerId, model, taskMetadata } = req.body;+ if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {+ throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });+ }+ if (enabled !== undefined && typeof enabled !== 'boolean') {+ throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (typeof enabled !== 'boolean' && interval === undefined && intervalMs === undefined &&+ providerId === undefined && model === undefined && taskMetadata === undefined) {+ throw new ServerError('enabled (boolean), interval (string|null), intervalMs (number|null), providerId (string|null), model (string|null), or taskMetadata (object|null) required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ // Per-app scheduling fields for handler-backed tasks (layered-intelligence).+ // `null`/'' clears back to inherit; a numeric intervalMs must be a positive+ // finite number (a sub-daily cadence the string interval enum can't express).+ if (intervalMs !== undefined && intervalMs !== null) {+ if (typeof intervalMs !== 'number' || !Number.isFinite(intervalMs) || intervalMs <= 0) {+ throw new ServerError('intervalMs must be a positive number or null', { status: 400, code: 'VALIDATION_ERROR' });+ }+ }+ if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {+ throw new ServerError('providerId must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (model !== undefined && model !== null && typeof model !== 'string') {+ throw new ServerError('model must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });+ }++ // Validate and sanitize taskMetadata to allowed agent-option keys only+ let sanitizedTaskMetadata;+ if (taskMetadata === undefined) {+ sanitizedTaskMetadata = undefined;+ } else if (taskMetadata === null) {+ sanitizedTaskMetadata = null;+ } else {+ if (typeof taskMetadata !== 'object' || Array.isArray(taskMetadata)) {+ throw new ServerError('taskMetadata must be an object or null', { status: 400, code: 'VALIDATION_ERROR' });+ }+ sanitizedTaskMetadata = sanitizeTaskMetadata(taskMetadata);+ if (sanitizedTaskMetadata === null) {+ throw new ServerError('Invalid taskMetadata: unrecognized keys or values', { status: 400, code: 'VALIDATION_ERROR' });+ }+ }++ // Validate interval against allowed values (also accepts 5-field cron expressions)+ if (interval !== undefined) {+ // 'custom' pairs with a numeric intervalMs (handler-backed tasks with a+ // sub-daily per-app cadence); the scheduler's CUSTOM branch reads intervalMs.+ const allowedIntervals = ['rotation', 'daily', 'weekly', 'once', 'on-demand', 'custom'];+ if (interval !== null && typeof interval === 'string') {+ const isCron = interval.trim().split(/\s+/).length === 5;+ if (!isCron && !allowedIntervals.includes(interval)) {+ throw new ServerError('interval must be one of rotation|daily|weekly|once|on-demand|custom, a cron expression, or null', { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (isCron) {+ // Validate syntax and field ranges (parseCronToNextRun throws on invalid expressions)+ // Note: null return means no match within search window (e.g. leap day) -- not invalid+ parseCronToNextRun(interval, new Date(), 'UTC');+ }+ } else if (interval !== null) {+ throw new ServerError('interval must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });+ }+ }++ const result = await appsService.updateAppTaskTypeOverride(req.params.id, req.params.taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata: sanitizedTaskMetadata });+ if (!result) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }++ const action = typeof enabled === 'boolean' ? (enabled ? 'Enabled' : 'Disabled') : 'Updated interval for';+ console.log(`📋 ${action} task type ${req.params.taskType} for ${result.name}`);+ res.json({ success: true, appId: result.id, taskType: req.params.taskType, enabled, interval, taskTypeOverrides: result.taskTypeOverrides || {} });+}));++export default router;diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.jsnew file mode 100644index 0000000000..27d70f61cd--- /dev/null+++ b/server/routes/apps/taskTypes.test.js@@ -0,0 +1,185 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import taskTypeRoutes from './taskTypes.js';++// Only the apps service is mocked; SELF_IMPROVEMENT_TASK_TYPES (taskSchedule) and+// parseCronToNextRun (eventScheduler) run for real, as do the sanitizeTaskMetadata+// validators.+vi.mock('../../services/apps.js', () => ({+ getAppById: vi.fn(),+ updateAppTaskTypeOverride: vi.fn(),+ getAppTaskTypeOverrides: vi.fn(),+ getAppWorkTracker: vi.fn(),+ getAppLayeredIntelligenceConfig: vi.fn(),+ toggleAllAppTaskTypes: vi.fn(),+ bulkUpdateAppTaskTypeOverride: vi.fn(),+ PORTOS_APP_ID: 'portos-default'+}));++import * as appsService from '../../services/apps.js';++describe('Apps Task-Type Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', taskTypeRoutes);+ vi.clearAllMocks();+ });++ describe('GET /api/apps/:id/layered-intelligence', () => {+ it('returns the effective config + isPortos flag', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'App' });+ appsService.getAppLayeredIntelligenceConfig.mockResolvedValue({+ enabled: false, intervalMs: 86400000, sources: { goals: true }, allowedScopes: ['app-improvement']+ });++ const response = await request(app).get('/api/apps/app-001/layered-intelligence');++ expect(response.status).toBe(200);+ expect(response.body.appId).toBe('app-001');+ expect(response.body.isPortos).toBe(false);+ expect(response.body.config.allowedScopes).toEqual(['app-improvement']);+ expect(appsService.getAppLayeredIntelligenceConfig).toHaveBeenCalledWith('app-001');+ });++ it('flags the PortOS baseline app', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS' });+ appsService.getAppLayeredIntelligenceConfig.mockResolvedValue({ enabled: false, allowedScopes: ['app-improvement', 'loop-meta'] });++ const response = await request(app).get('/api/apps/portos-default/layered-intelligence');++ expect(response.status).toBe(200);+ expect(response.body.isPortos).toBe(true);+ });++ it('returns 404 for an unknown app', async () => {+ appsService.getAppById.mockResolvedValue(null);+ const response = await request(app).get('/api/apps/app-999/layered-intelligence');+ expect(response.status).toBe(404);+ });+ });++ describe('PUT /api/apps/:id/task-types/:taskType', () => {+ it('should accept valid taskMetadata with allowed boolean keys', async () => {+ appsService.updateAppTaskTypeOverride.mockResolvedValue({+ id: 'app-001',+ name: 'Test App',+ taskTypeOverrides: { 'feature-ideas': { taskMetadata: { useWorktree: true } } }+ });++ const response = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ taskMetadata: { useWorktree: true, simplify: false } });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ });++ it('should accept taskMetadata: null to clear metadata', async () => {+ appsService.updateAppTaskTypeOverride.mockResolvedValue({+ id: 'app-001',+ name: 'Test App',+ taskTypeOverrides: {}+ });++ const response = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ taskMetadata: null });++ expect(response.status).toBe(200);+ });++ it('should reject taskMetadata that is an array', async () => {+ const response = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ taskMetadata: [1, 2, 3] });++ expect(response.status).toBe(400);+ });++ it('should reject taskMetadata with only unknown keys', async () => {+ const response = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ taskMetadata: { unknownKey: true } });++ expect(response.status).toBe(400);+ expect(response.body.error).toContain('unrecognized');+ });++ it('should reject taskMetadata with non-boolean values for allowed keys', async () => {+ const response = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({ taskMetadata: { useWorktree: 'yes' } });++ expect(response.status).toBe(400);+ });++ it('should return 400 when no valid fields provided', async () => {+ const response = await request(app)+ .put('/api/apps/app-001/task-types/feature-ideas')+ .send({});++ expect(response.status).toBe(400);+ });++ it('should reject an unknown taskType in the URL', async () => {+ const response = await request(app)+ .put('/api/apps/app-001/task-types/not-a-real-task-type')+ .send({ enabled: true });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('INVALID_TASK_TYPE');+ });+ });++ describe('PUT /api/apps/bulk-task-type/:taskType', () => {+ it('should reject an unknown taskType in the URL', async () => {+ const response = await request(app)+ .put('/api/apps/bulk-task-type/not-a-real-task-type')+ .send({ enabled: true });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('INVALID_TASK_TYPE');+ });+ });++ describe('PUT /api/apps/:id/task-types/all', () => {+ it('should toggle all task types for an app', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App' });+ appsService.toggleAllAppTaskTypes.mockResolvedValue({ id: 'app-001', name: 'Test App', taskTypeOverrides: { security: { enabled: true } } });++ const response = await request(app)+ .put('/api/apps/app-001/task-types/all')+ .send({ enabled: true });++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);+ expect(response.body.appId).toBe('app-001');+ expect(appsService.toggleAllAppTaskTypes).toHaveBeenCalledWith('app-001', true);+ });++ it('should return 400 when enabled is not a boolean', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App' });++ const response = await request(app)+ .put('/api/apps/app-001/task-types/all')+ .send({ enabled: 'yes' });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('VALIDATION_ERROR');+ });++ it('should return 404 when app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app)+ .put('/api/apps/app-999/task-types/all')+ .send({ enabled: true });++ expect(response.status).toBe(404);+ });+ });+});diff --git a/server/routes/apps/viteTls.js b/server/routes/apps/viteTls.jsnew file mode 100644index 0000000000..0464d84ff8--- /dev/null+++ b/server/routes/apps/viteTls.js@@ -0,0 +1,171 @@+/**+ * App config repair: Tailscale TLS upgrade + Vite allowed-hosts guard/remediation.+ *+ * POST /:id/upgrade-tls → { ok, helperPath, ... }+ * GET /:id/vite-host-check → { host, hasViteConfig, hostAllowed, canAutoFix }+ * POST /:id/fix-vite-hosts → { ok, mode, ... } (allow-all rewrite or AI CoS task)+ */++import { Router } from 'express';+import { readFile } from 'fs/promises';+import { join } from 'path';+import { PATHS, atomicWrite } from '../../lib/fileUtils.js';+import * as appsService from '../../services/apps.js';+import { PORTOS_APP_ID } from '../../services/apps.js';+import * as cos from '../../services/cos.js';+import { z } from 'zod';+import { validateRequest } from '../../lib/validation.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { checkViteHost, findViteConfig, rewriteAllowedHosts } from '../../lib/viteAllowedHosts.js';+import { certPaths } from '../../../lib/certPaths.js';+import { loadApp, pathExists } from './shared.js';++const router = Router();++// POST /api/apps/:id/upgrade-tls - Copy the tailscale-https helper into the target app's+// repo and record tlsPort in apps.json so the Launch button prefers HTTPS. The app still+// needs to be edited manually to call createTailscaleServers() — we return an example+// snippet in the response so the frontend can surface it. Refuse to overwrite an existing+// helper unless `force: true` is set; this way a user who has customized their copy keeps it.+const upgradeTlsSchema = z.object({+ tlsPort: z.number().int().min(1).max(65535),+ force: z.boolean().optional()+});+router.post('/:id/upgrade-tls', loadApp, asyncHandler(async (req, res) => {+ const { tlsPort, force } = validateRequest(upgradeTlsSchema, req.body);+ const app = req.loadedApp;+ if (app.id === PORTOS_APP_ID) {+ throw new ServerError('PortOS itself already uses the helper — nothing to upgrade', {+ status: 400, code: 'ALREADY_UPGRADED'+ });+ }+ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });+ }+ const sourcePath = join(PATHS.root, 'lib', 'tailscale-https.js');+ const targetDir = join(app.repoPath, 'lib');+ const targetPath = join(targetDir, 'tailscale-https.js');++ const alreadyExists = await pathExists(targetPath);+ if (alreadyExists && !force) {+ throw new ServerError(+ 'A tailscale-https.js already exists in the target app. Pass force:true to overwrite.',+ { status: 409, code: 'ALREADY_EXISTS' }+ );+ }++ const helperSource = await readFile(sourcePath, 'utf-8');+ await atomicWrite(targetPath, helperSource);++ await appsService.updateApp(app.id, { tlsPort });++ const snippet = [+ `// In your server entry, replace the direct http.createServer(app).listen(...) with:`,+ `import { createTailscaleServers, watchCertReload } from './lib/tailscale-https.js';`,+ ``,+ `const CERT_DIR = process.env.CERT_DIR || '/path/to/data/certs'; // shared with PortOS`,+ `const { server, mirror, httpsEnabled } = createTailscaleServers(app, { certDir: CERT_DIR });`,+ `// io.attach(server); if (mirror) io.attach(mirror); // when using Socket.IO`,+ `server.listen(${tlsPort}, '0.0.0.0');`,+ `// Optional: bind the HTTP mirror on a port of your choosing (127.0.0.1 only).`,+ `// if (mirror) mirror.listen(<your-mirror-port>, '127.0.0.1');`,+ `if (httpsEnabled) watchCertReload(server, CERT_DIR);`+ ].join('\n');++ res.json({+ ok: true,+ helperPath: targetPath,+ overwrote: alreadyExists,+ tlsPort,+ snippet,+ certDirHint: certPaths(PATHS.data).dir,+ note: 'Point your app at the PortOS cert dir (or symlink it) so apps share the single Tailscale cert.'+ });+}));++// GET /api/apps/:id/vite-host-check?host=<hostname> - Report whether the app's+// Vite dev server would accept requests for `host` (the Tailscale MagicDNS / IP+// name PortOS is served under). Vite ≥5 blocks unknown hosts, so launching an+// app's Dev UI over Tailscale fails until that host is allow-listed. This drives+// the Dev-UI launch guard and the remediation UI in the app detail view.+router.get('/:id/vite-host-check', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const host = typeof req.query.host === 'string' ? req.query.host.trim() : '';+ const extraDirs = (app.processes || []).map((p) => p.cwd).filter(Boolean);+ const status = await checkViteHost(app.repoPath, host, { extraDirs });+ res.json({ host, ...status });+}));++// POST /api/apps/:id/fix-vite-hosts - Remediate the Vite allowedHosts block.+// mode 'allow-all' (default): deterministically rewrite the app's vite.config+// to `server.allowedHosts: true`. Safe for a private Tailscale network and+// the most reliable fix; bails (422) when the config shape is too unusual to+// edit without risking corruption, steering the user to the AI path.+// mode 'ai': spawn a CoS agent that edits the app's vite.config in its OWN+// repo (honoring the Scope Boundary) — handles arbitrary config shapes and+// can create a vite.config when none exists.+const fixViteHostsSchema = z.object({+ mode: z.enum(['allow-all', 'ai']).default('allow-all'),+ host: z.string().trim().optional()+});+router.post('/:id/fix-vite-hosts', loadApp, asyncHandler(async (req, res) => {+ const { mode, host } = validateRequest(fixViteHostsSchema, req.body);+ const app = req.loadedApp;+ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });+ }+ const extraDirs = (app.processes || []).map((p) => p.cwd).filter(Boolean);+ const config = await findViteConfig(app.repoPath, { extraDirs });++ if (mode === 'ai') {+ if (!cos.isRunning()) {+ throw new ServerError(+ 'CoS is not running — start it to use AI remediation, or use the automatic fix.',+ { status: 409, code: 'COS_NOT_RUNNING' }+ );+ }+ const where = config ? config.path : `${app.repoPath} (no vite.config found — create one)`;+ const task = await cos.addTask({+ description: `Allow the Tailscale host in ${app.name}'s Vite config so its Dev UI loads`,+ priority: 'MEDIUM',+ app: app.id,+ approvalRequired: true,+ context: [+ `The app "${app.name}" is launched through PortOS over a Tailscale MagicDNS hostname` ++ (host ? ` ("${host}")` : '') + '.',+ 'Launching its Vite Dev UI fails with: "Blocked request. This host is not allowed."',+ `Fix: edit ${where} so the dev server's \`server.allowedHosts\` accepts that host.`,+ 'Prefer `server.allowedHosts: true` (allow all — this app runs only on a private Tailscale network),',+ 'or add the specific host plus a leading-dot `.ts.net` suffix entry. Leave the rest of the config intact.',+ 'If no vite config exists, create a minimal vite.config.js that sets server.allowedHosts.'+ ].join('\n')+ }, 'internal');+ return res.json({ ok: true, mode: 'ai', taskId: task.id, configPath: config?.path || null });+ }++ // mode === 'allow-all': deterministic rewrite.+ if (!config) {+ throw new ServerError(+ 'No vite.config found to edit automatically — use AI remediation, which can create one.',+ { status: 422, code: 'NO_VITE_CONFIG' }+ );+ }+ const rewrite = rewriteAllowedHosts(config.content);+ if (!rewrite.ok) {+ throw new ServerError(+ `Could not safely auto-edit ${config.filename}: ${rewrite.reason}. Use AI remediation instead.`,+ { status: 422, code: 'AUTO_FIX_UNSAFE' }+ );+ }+ await atomicWrite(config.path, rewrite.content);+ res.json({+ ok: true,+ mode: 'allow-all',+ configPath: config.path,+ filename: config.filename,+ strategy: rewrite.strategy,+ note: 'Restart the app (or its Vite dev server) for the change to take effect.'+ });+}));++export default router;diff --git a/server/routes/apps/viteTls.test.js b/server/routes/apps/viteTls.test.jsnew file mode 100644index 0000000000..70b8786a28--- /dev/null+++ b/server/routes/apps/viteTls.test.js@@ -0,0 +1,140 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import viteTlsRoutes from './viteTls.js';++// Real viteAllowedHosts / fileUtils / certPaths run against temp dirs; only the+// apps registry and the CoS task queue are mocked.+vi.mock('../../services/apps.js', () => ({+ getAppById: vi.fn(),+ updateApp: vi.fn(),+ PORTOS_APP_ID: 'portos-default'+}));++vi.mock('../../services/cos.js', () => ({+ isRunning: vi.fn().mockReturnValue(true),+ addTask: vi.fn().mockResolvedValue({ id: 'task-vite-1' })+}));++import * as appsService from '../../services/apps.js';+import * as cos from '../../services/cos.js';+import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';++describe('Apps Vite Dev-UI host guard', () => {+ let app;+ let repoDir;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', viteTlsRoutes);+ vi.clearAllMocks();+ cos.isRunning.mockReturnValue(true);+ cos.addTask.mockResolvedValue({ id: 'task-vite-1' });+ repoDir = join(tmpdir(), `vite-host-${Math.random().toString(36).slice(2)}`);+ mkdirSync(repoDir, { recursive: true });+ });++ const writeViteConfig = (content) =>+ writeFileSync(join(repoDir, 'vite.config.js'), content);++ describe('GET /:id/vite-host-check', () => {+ it('reports hostAllowed=false + canAutoFix for a Vite app missing the host', async () => {+ writeViteConfig("export default { server: { port: 5173 } };");+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .get('/api/apps/app-001/vite-host-check?host=null.taile8179.ts.net');++ expect(response.status).toBe(200);+ expect(response.body.hasViteConfig).toBe(true);+ expect(response.body.hostAllowed).toBe(false);+ expect(response.body.canAutoFix).toBe(true);+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('reports hostAllowed=true when the config already allows the tailnet', async () => {+ writeViteConfig("export default { server: { allowedHosts: ['.ts.net'] } };");+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .get('/api/apps/app-001/vite-host-check?host=box.taile8179.ts.net');++ expect(response.status).toBe(200);+ expect(response.body.hostAllowed).toBe(true);+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('reports hasViteConfig=false when the app has no vite config', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .get('/api/apps/app-001/vite-host-check?host=box.taile8179.ts.net');++ expect(response.status).toBe(200);+ expect(response.body.hasViteConfig).toBe(false);+ rmSync(repoDir, { recursive: true, force: true });+ });+ });++ describe('POST /:id/fix-vite-hosts', () => {+ it('allow-all rewrites the config to allowedHosts: true', async () => {+ writeViteConfig("export default { server: { port: 5173 } };");+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'allow-all', host: 'null.taile8179.ts.net' });++ expect(response.status).toBe(200);+ expect(response.body.strategy).toBe('inject-into-server');+ const written = readFileSync(join(repoDir, 'vite.config.js'), 'utf-8');+ expect(written).toContain('allowedHosts: true');+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('allow-all returns 422 when no vite config exists', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'allow-all' });++ expect(response.status).toBe(422);+ expect(response.body.code).toBe('NO_VITE_CONFIG');+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('ai mode queues a CoS task targeting the app', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });+ cos.isRunning.mockReturnValue(true);++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'ai', host: 'null.taile8179.ts.net' });++ expect(response.status).toBe(200);+ expect(response.body.taskId).toBe('task-vite-1');+ expect(cos.addTask).toHaveBeenCalledWith(+ expect.objectContaining({ app: 'app-001', approvalRequired: true }),+ 'internal'+ );+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('ai mode returns 409 when CoS is not running', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });+ cos.isRunning.mockReturnValue(false);++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'ai' });++ expect(response.status).toBe(409);+ expect(response.body.code).toBe('COS_NOT_RUNNING');+ rmSync(repoDir, { recursive: true, force: true });+ });+ });+});diff --git a/server/routes/apps/xcode.js b/server/routes/apps/xcode.jsnew file mode 100644index 0000000000..abb4f9cca7--- /dev/null+++ b/server/routes/apps/xcode.js@@ -0,0 +1,34 @@+/**+ * Xcode management-script provisioning.+ *+ * POST /:id/xcode-scripts/install → { installed, skipped, errors }+ */++import { Router } from 'express';+import { z } from 'zod';+import { validateRequest } from '../../lib/validation.js';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { installScripts, XCODE_SCRIPT_NAMES } from '../../services/xcodeScripts.js';+import { loadApp, pathExists } from './shared.js';++const router = Router();++// POST /api/apps/:id/xcode-scripts/install - Install missing management scripts+// Restrict the request payload to the known, fixed set of script names so that+// arbitrary or oversized arrays are rejected at the validation layer.+const installScriptsSchema = z.object({+ scripts: z.array(z.enum(XCODE_SCRIPT_NAMES)).min(1).max(XCODE_SCRIPT_NAMES.length)+});+router.post('/:id/xcode-scripts/install', loadApp, asyncHandler(async (req, res) => {+ const { scripts } = validateRequest(installScriptsSchema, req.body);+ if (!req.loadedApp.repoPath || !await pathExists(req.loadedApp.repoPath)) {+ throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });+ }+ const result = await installScripts(req.loadedApp, scripts);+ if (result.errors.length && !result.installed.length) {+ throw new ServerError(result.errors.join(', '), { status: 400, code: 'INSTALL_FAILED' });+ }+ res.json(result);+}));++export default router;diff --git a/server/routes/apps/xcode.test.js b/server/routes/apps/xcode.test.jsnew file mode 100644index 0000000000..d42c48c4a4--- /dev/null+++ b/server/routes/apps/xcode.test.js@@ -0,0 +1,113 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import xcodeRoutes from './xcode.js';++vi.mock('../../services/apps.js', () => ({+ getAppById: vi.fn(),+ PORTOS_APP_ID: 'portos-default'+}));++vi.mock('../../services/xcodeScripts.js', () => ({+ installScripts: vi.fn(),+ XCODE_SCRIPT_NAMES: ['deploy.sh', 'take_screenshots.sh', 'take_screenshots_macos.sh']+}));++import * as appsService from '../../services/apps.js';+import { installScripts } from '../../services/xcodeScripts.js';++describe('Apps Xcode Routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', xcodeRoutes);+ vi.clearAllMocks();+ });++ describe('POST /api/apps/:id/xcode-scripts/install', () => {+ it('should install requested scripts successfully', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });+ installScripts.mockResolvedValue({ installed: ['deploy.sh'], skipped: [], errors: [] });++ const response = await request(app)+ .post('/api/apps/app-001/xcode-scripts/install')+ .send({ scripts: ['deploy.sh'] });++ expect(response.status).toBe(200);+ expect(response.body.installed).toEqual(['deploy.sh']);+ });++ it('should return 400 when all scripts fail', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });+ installScripts.mockResolvedValue({ installed: [], skipped: [], errors: ['some failure'] });++ const response = await request(app)+ .post('/api/apps/app-001/xcode-scripts/install')+ .send({ scripts: ['deploy.sh'] });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('INSTALL_FAILED');+ });++ it('should return 400 when scripts array contains an unknown name', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });++ const response = await request(app)+ .post('/api/apps/app-001/xcode-scripts/install')+ .send({ scripts: ['bad.sh'] });++ // Unknown script names are now rejected by the Zod enum validator+ expect(response.status).toBe(400);+ });++ it('should return 400 when scripts array is empty', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });++ const response = await request(app)+ .post('/api/apps/app-001/xcode-scripts/install')+ .send({ scripts: [] });++ expect(response.status).toBe(400);+ });++ it('should return 404 when app not found', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await request(app)+ .post('/api/apps/app-999/xcode-scripts/install')+ .send({ scripts: ['deploy.sh'] });++ expect(response.status).toBe(404);+ });++ it('should return partial success with errors', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/tmp' });+ installScripts.mockResolvedValue({+ installed: ['deploy.sh'],+ skipped: [],+ errors: ['Script take_screenshots_macos.sh does not apply to ios-native apps']+ });++ const response = await request(app)+ .post('/api/apps/app-001/xcode-scripts/install')+ .send({ scripts: ['deploy.sh', 'take_screenshots_macos.sh'] });++ expect(response.status).toBe(200);+ expect(response.body.installed).toEqual(['deploy.sh']);+ expect(response.body.errors).toHaveLength(1);+ });++ it('should return 400 when repoPath does not exist', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Test App', type: 'xcode', repoPath: '/nonexistent/path' });++ const response = await request(app)+ .post('/api/apps/app-001/xcode-scripts/install')+ .send({ scripts: ['deploy.sh'] });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('PATH_NOT_FOUND');+ });+ });+});diff --git a/server/services/appPortConfig.js b/server/services/appPortConfig.jsnew file mode 100644index 0000000000..4439eb0c0d--- /dev/null+++ b/server/services/appPortConfig.js@@ -0,0 +1,126 @@+/**+ * App port-config orchestration.+ *+ * Port fields in apps.json are *derived* from ecosystem.config.cjs (the source+ * of truth PM2 reads). This module diffs a submitted port update against the+ * ACTUAL config literals and persists the change back to the ecosystem config+ * (value-keyed remap for distinct ports; per-process/label targeted rewrite for+ * shared-value ports) in ONE atomic write. Extracted verbatim from the+ * `PUT /api/apps/:id` route so the route handler stays HTTP-thin — the caller+ * still owns the precondition guard (`usesPm2` + path exists) and the HTTP+ * error/response mapping.+ *+ * Returns `{ persistFailed, uiPortOverride, changedKeys }`:+ * - persistFailed — true when the user changed a port we could NOT write to+ * the source-of-truth config (caller should reject 422).+ * - uiPortOverride — the derived uiPort to pin for served-by-API apps+ * (undefined when the app's ui port is a real literal).+ * - changedKeys — port keys that differed from the config (for context).+ */++import { parseEcosystemFromPath, writeEcosystemPortEdits } from './streamingDetect.js';+import { deriveUiPort } from '../routes/apps/shared.js';++const PORT_KEYS = ['apiPort', 'uiPort', 'devUiPort'];+const LABEL_BY_KEY = { apiPort: 'api', uiPort: 'ui', devUiPort: 'devUi' };++/**+ * Persist submitted port edits for `existing` to its ecosystem config.+ * @param {object} existing the current app record (must have repoPath)+ * @param {object} data the validated PUT body (mutated? no — read-only here)+ */+export async function applyEcosystemPortEdits(existing, data) {+ // Diff the submitted ports against the ACTUAL config values (not apps.json,+ // whose top-level fields may be stale or absent for derived ports). This is+ // the single source of truth for both "did it change" and "what's the old+ // literal to rewrite": EditAppModal submits every field even on a rename, so+ // a value equal to the config's current port is a no-op echo, and a value+ // that differs is a genuine edit to persist.+ const { processes: cfgProcs } = await parseEcosystemFromPath(existing.repoPath);+ const currentPort = {};+ const procNameByKey = {}; // which process block owns each label (for targeted rewrites)+ for (const proc of cfgProcs || []) {+ for (const [key, label] of Object.entries(LABEL_BY_KEY)) {+ if (currentPort[key] === undefined && Number.isInteger(proc.ports?.[label])) {+ currentPort[key] = proc.ports[label];+ procNameByKey[key] = proc.name;+ }+ }+ }+ // Count current values so a value-keyed rewrite never fires on a number shared+ // by another port field (e.g. uiPort derived from apiPort, both 6000) — that+ // would rewrite every occurrence and clobber the field the user didn't touch.+ // Such a value can't be split by value alone; it falls through to the+ // per-process-label-targeted rewrite below.+ const valueCounts = new Map();+ for (const key of PORT_KEYS) {+ const v = currentPort[key];+ if (Number.isInteger(v)) valueCounts.set(v, (valueCounts.get(v) || 0) + 1);+ }+ // A port is "changed" when the submitted value differs from the config's+ // current value for that label. A field the config doesn't define has no+ // literal to rewrite, so it isn't treated as a config edit here.+ const changedKeys = PORT_KEYS.filter(key =>+ Number.isInteger(currentPort[key]) && Number.isInteger(data[key]) && data[key] !== currentPort[key]);++ // Served-by-API detection. When an app has an API process plus a Vite dev UI+ // but no literal `ports.ui`, the prod UI is served by the API server, so the+ // `uiPort` is *derived* (= apiPort) and CANNOT be set independently — there's+ // no separate UI port literal in the config to rewrite. The edit drawer always+ // submits every port field and never syncs the UI field to a changed API+ // field, so an API-only edit arrives as `{ apiPort: <new>, uiPort: <old+ // derived> }`. We can't distinguish that stale echo from a deliberate+ // (impossible) independent UI change, so the only coherent behavior is to+ // IGNORE the submitted uiPort entirely and pin the stored value to the derived+ // port (= the post-edit API port). That tracks the API port on every save,+ // never reverts, and never spuriously 422s the common API-edit path. The user+ // changes this UI port by changing the API port.+ const effectiveApiPort = Number.isInteger(data.apiPort) ? data.apiPort : currentPort.apiPort;+ const derivedUiPort = deriveUiPort(undefined, effectiveApiPort, currentPort.devUiPort);+ const uiIsDerived = currentPort.uiPort === undefined && Number.isInteger(derivedUiPort);+ const remap = [];+ const targetedEdits = []; // shared-value keys: rewritten by process + label+ for (const key of changedKeys) {+ const oldPort = currentPort[key]; // guaranteed integer by the filter above+ // Value shared with another field (can't disambiguate by value): target the+ // specific process block + label so the edit lands on exactly the port the+ // user touched, not every occurrence of the shared literal.+ if (valueCounts.get(oldPort) > 1 && procNameByKey[key]) {+ targetedEdits.push({ processName: procNameByKey[key], label: LABEL_BY_KEY[key], oldPort, newPort: data[key] });+ continue;+ }+ remap.push([oldPort, data[key]]);+ }++ // Persist the value-keyed remap (distinct ports) and the targeted edits+ // (shared-value ports) in ONE atomic write. Doing them as two separate writes+ // would let the value-keyed pass land on disk before a later unpersistable+ // targeted edit forces the reject below — leaving config partially changed for+ // a rejected request. writeEcosystemPortEdits computes both rewrites in memory+ // and writes only when nothing is unpersistable.+ const result = changedKeys.length > 0+ ? await writeEcosystemPortEdits(existing.repoPath, remap, targetedEdits)+ : { changed: false, remapApplied: false, applied: [], unapplied: [] };+ if (result.changed) {+ const remapMsg = result.remapApplied ? remap.map(([o, n]) => `${o}→${n}`).join(', ') : '';+ const tgtMsg = targetedEdits.map(e => `${e.label} ${e.oldPort}→${e.newPort}`).join(', ');+ console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${[remapMsg, tgtMsg].filter(Boolean).join(', ')} (restart the app to apply)`);+ }++ // Honesty gate: if the user changed a port we could NOT write to the+ // source-of-truth config, signal a reject rather than persist a registry value+ // PM2 will contradict (and the next refresh will revert). `remap.length &&+ // !remapApplied` catches value-keyed pairs whose literal wasn't found;+ // `unapplied` catches process/label edits that didn't match. On any+ // unpersistable targeted edit the writer persists nothing, so this leaves the+ // config untouched.+ const valueKeyedFailed = remap.length > 0 && !result.remapApplied;+ const targetedFailed = (result.unapplied || []).length > 0;+ const persistFailed = changedKeys.length > 0 && (valueKeyedFailed || targetedFailed);++ return {+ persistFailed,+ uiPortOverride: uiIsDerived ? derivedUiPort : undefined,+ changedKeys,+ };+}diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex 9963b90d02..6a4bd06c9b 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -110,7 +110,7 @@ function pinAgainstEviction(path) {// detached + unref so a long-running `brctl download` (large evicted file,// slow network) can't keep the Node process alive on shutdown. Matches the- // repo's fire-and-forget spawn pattern in server/routes/apps.js ++ // repo's fire-and-forget spawn pattern in server/routes/apps/launch.js +// server/routes/brain.js.const child = spawn('brctl', ['download', path], { detached: true, stdio: 'ignore' });child.unref();