Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep an in-flight app Update visible page-wide and reject a duplicate dispatch (#3435)

[._.]/ Adam Eivy9ecef7f986d0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 492b38c5ad..ff2e7f7fb3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@
## Fixed
+- **[issue-3435] A running app Update no longer vanishes when you collapse the row or leave `/apps`, and can't be dispatched twice.** The Update / Standardize flow (git pull → npm install → setup → PM2 restart, minutes long) rendered its step log *inside* the expanded row, and the hook tracking it held `isOperating` / `steps` in page state whose unmount tore down the socket listeners — so collapsing the row or navigating away left a long-running operation with no indicator anywhere, and the second dispatch that invited ran a concurrent `npm install` against the same checkout. The server now owns the in-flight set: a module-level map keyed by app id rejects a second `app:update` / `app:standardize` for an app already operating (a re-entrancy guard, not a lock), buffers the steps emitted so far, and broadcasts progress with `io.emit` instead of replying only to the socket that dispatched. Clients rehydrate from `app:operations:active` — pushed on connect and on demand via `app:operations:list` — so a page that mounts mid-operation restores the whole log. `/apps` renders that state in a sticky page-level banner naming the app (`Updating <app>…`) above the list instead of inside the row, and a row blocked only by another app's operation now reads `Update (busy)` rather than being silently greyed out. The app-detail Overview tab passes its own `appId` so it still reports only its own operation.
- **A successful `branch-cleanup` run is no longer recorded as a failure.** The task deletes merged branches in the app's live checkout — its prompt `cd`s to the repo path and runs `git branch -d` / `git push --delete` — but it was the only git/gh coordinator type shipping with no `taskMetadata` at all, so `applyAppWorktreeDefault` filled `useWorktree`/`openPR` from the app's `defaultOpenPR: true`. Every run got a CoS-managed worktree it never touched (one that holds the very refs it was trying to delete) and a PR expectation it could never satisfy, and finalization scored the completed run `pr-missing`. The four non-committing coordinator types — `branch-cleanup`, `branch-reconcile`, `issue-reconcile`, `jira-status-report` — now share one documented `taskMetadata` posture: `useWorktree`/`openPR` explicitly `false` (not merely absent, which is what let the app defaults in) *and* locked via `MANAGED_AGENT_OPTIONS` so a per-app override can't re-attach them, plus `worktreeChangesExpected: false`, because a clean tree is the success shape for a branch deletion or a posted report and the TUI idle-complete gate must not read it as "the model produced no work". `jira-status-report` was hit by the same bug for a subtler reason: its `readOnly: true` skips worktree *creation* but the finalize-time PR-claim check reads `metadata.openPR` directly, so a posted report still scored `pr-missing`. A guard test now iterates `NON_COMMITTING_COORDINATOR_TASK_TYPES` — the set that already grants these types their commit-criterion exemption — so a future coordinator type can't be added to one list and not the other. Existing installs pick all of this up on the next schedule load: the taskMetadata deep-merge backfills the new keys and `enforceManagedAgentOptions` rewrites any stored `true`.
- **[issue-3396] CyberCity's ambient music no longer drifts under main-thread load.** The chord changes (every 2400ms) and the 16th-note arp plucks (every 150ms) rode two independent `setInterval`s that each read `ctx.currentTime` at fire time — so under load both drifted against the audio clock *and* against each other, the failure mode the sibling synth players adopted the shared lookahead scheduler to avoid. Both now come off one 16th-note step counter (16 steps per chord, so the arp is phase-locked to the chord changes by construction) and every event is written to the audio clock at an absolute grid time, `gridOrigin + step × 0.15s`, which cannot accumulate drift. The timing constants come from `SYNTH_TIMING` in `lib/lookaheadTransport.js` so the feel stays shared; the transport body itself is deliberately not reused, because it reads its clock from the shared `lib/audioContext.js` singleton while `cityAudioEngine` is a documented holdout that owns (and closes) its own `AudioContext` — scheduling this graph against a clock it doesn't run on would be worse than the drift. A backgrounded tab now re-anchors to the grid on return instead of dumping every missed step into one burst. Generative behavior (chord walk, mood sets, energy-driven arp gain) and the stop-ramp contract are unchanged.
- **A manually-triggered ("Run Now") perpetual claim drain no longer stalls after one item.** A `claim-issue` / `claim-work` schedule set to *perpetual* is meant to drain actionable work back-to-back. When the daemon's own scheduler drives it that works, but a manual "Run Now" (`RunTaskButton` → `POST /api/cos/schedule/trigger`) did not: the on-demand trigger only gates on the master Improve flag, so the first item ran, but `refillPerpetualForCompletedAgent` then gated the *continuation* on `canQueueImprovementTasks` — which additionally requires idle-review ON **and** CoS auto-run = `execute`. Those are exactly the postures in which a user reaches for "Run Now" (auto-run off/dry-run, or idle-review off), so the drain refused to spin up the next item even with a queue of claimable issues. The refill now routes a manual drain through `perpetualRefillPlan`'s `onDemand` lane: it re-issues an on-demand request for the same task type + app, gated only on the master Improve flag (matching what let the manual run START), and returns before the auto-run-gated queue lane — so a manual perpetual drain keeps draining, scoped to that one type+app (it can't leak unrelated rotation/idle autonomous work past the auto-run kill switch), until the work-detector parks. The on-demand spawn engines mark generated tasks `metadata.onDemand` (projected onto the agent as `taskOnDemand`) and forward the completion's `ignoreTaskId` to `addTask`, so the re-issued claim isn't rejected as a duplicate of the still-`in_progress` run that just triggered it. Scheduled perpetual drains are unchanged.
diff --git a/client/src/components/apps/AppOperationBanner.jsx b/client/src/components/apps/AppOperationBanner.jsx
new file mode 100644
index 0000000000..41d4582498
--- /dev/null
+++ b/client/src/components/apps/AppOperationBanner.jsx
@@ -0,0 +1,63 @@
+import { Check, X, AlertTriangle } from 'lucide-react';
+import BrailleSpinner from '../BrailleSpinner';
+import ActivityLog from './ActivityLog';
+
+const LABELS = {
+ update: { running: 'Updating', done: 'Updated', failed: 'Update failed for' },
+ standardize: { running: 'Standardizing', done: 'Standardized', failed: 'Standardize failed for' }
+};
+
+/**
+ * Page-level banner for an in-flight app update/standardize. It lives above the
+ * app list rather than inside the expanded row so collapsing the row — or
+ * returning to /apps mid-operation — still shows what is running (#3435).
+ */
+export default function AppOperationBanner({ appName, type, steps, error, completed, onDismiss }) {
+ const labels = LABELS[type] || LABELS.update;
+ const name = appName || 'app';
+ const heading = error ? `${labels.failed} ${name}` : completed ? `${labels.done} ${name}` : `${labels.running} ${name}…`;
+ const tone = error
+ ? 'border-port-error/40 bg-port-error/10'
+ : completed
+ ? 'border-port-success/40 bg-port-success/10'
+ : 'border-port-accent/40 bg-port-accent/10';
+
+ return (
+ <div
+ className={`sticky top-0 z-20 mb-4 rounded-xl border p-3 backdrop-blur ${tone}`}
+ role="status"
+ aria-live="polite"
+ aria-label="App operation status"
+ >
+ <div className="flex items-start gap-2">
+ <span className="shrink-0 mt-0.5">
+ {error
+ ? <AlertTriangle size={16} aria-hidden="true" className="text-port-error" />
+ : completed
+ ? <Check size={16} aria-hidden="true" className="text-port-success" />
+ : <BrailleSpinner text="" className="text-port-accent" />}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium text-white">{heading}</div>
+ <div className="text-xs text-gray-400">
+ {error
+ ? error
+ : completed
+ ? 'You can start another operation now.'
+ : 'This keeps running if you collapse the row or leave the page.'}
+ </div>
+ </div>
+ {onDismiss && (
+ <button
+ onClick={onDismiss}
+ className="shrink-0 p-1 rounded text-gray-400 hover:text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"
+ aria-label={`Dismiss ${name} operation status`}
+ >
+ <X size={16} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ <ActivityLog steps={steps} error={null} completed={false} />
+ </div>
+ );
+}
diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsx
index 81f02af7e8..0da5025b50 100644
--- a/client/src/components/apps/tabs/OverviewTab.jsx
+++ b/client/src/components/apps/tabs/OverviewTab.jsx
@@ -29,7 +29,9 @@ export default function OverviewTab({ app, onRefresh }) {
const [spriteBindings, setSpriteBindings] = useState([]);
const onComplete = useMemo(() => () => onRefresh(), [onRefresh]);
- const { steps, isOperating, operationType, error, completed, startUpdate, startStandardize } = useAppOperation({ onComplete });
+ // Scoped to this app: the shared hook otherwise reports whichever operation
+ // is running, which would stream another app's steps into this tab.
+ const { steps, isOperating, operationType, error, completed, startUpdate, startStandardize } = useAppOperation({ onComplete, appId: app?.id });
const updating = isOperating && operationType === 'update';
const standardizing = isOperating && operationType === 'standardize';
@@ -53,7 +55,7 @@ export default function OverviewTab({ app, onRefresh }) {
return () => { cancelled = true; };
}, [app?.id]);
- const handleUpdate = () => startUpdate(app.id);
+ const handleUpdate = () => startUpdate(app.id, app.name);
const handleRefreshConfig = async () => {
setRefreshingConfig(true);
@@ -62,7 +64,7 @@ export default function OverviewTab({ app, onRefresh }) {
onRefresh();
};
- const handleStandardize = () => startStandardize(app.id);
+ const handleStandardize = () => startStandardize(app.id, app.name);
const handleDetectIcon = async () => {
setDetectingIcon(true);
diff --git a/client/src/hooks/useAppOperation.js b/client/src/hooks/useAppOperation.js
index 0006110e96..963d7e6509 100644
--- a/client/src/hooks/useAppOperation.js
+++ b/client/src/hooks/useAppOperation.js
@@ -1,122 +1,161 @@
import { useState, useCallback, useEffect, useRef } from 'react';
import socket from '../services/socket';
+const CLEAR_DELAY_MS = 5000;
+
+const mergeStep = (prev, data) => {
+ const entry = { step: data.step, status: data.status, message: data.message, timestamp: data.timestamp };
+ const existing = prev.findIndex(s => s.step === data.step);
+ if (existing < 0) return [...prev, entry];
+ const next = [...prev];
+ next[existing] = entry;
+ return next;
+};
+
/**
* Hook for socket-based app operations (update, standardize) with live step tracking.
+ *
+ * The server owns the in-flight set (`app:operations:active`) because these
+ * operations run for minutes and outlive the page that started them. The hook
+ * subscribes for its whole lifetime and rehydrates on mount, so collapsing the
+ * row — or navigating away from /apps and back — never loses a running
+ * operation (#3435).
+ *
+ * `appId` scopes a single-app surface (an app's Overview tab) to its own
+ * operation; omit it on the multi-app list, which reports whichever operation
+ * is running.
*/
-export function useAppOperation({ onComplete } = {}) {
+export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {
const [steps, setSteps] = useState([]);
- const [isOperating, setIsOperating] = useState(false);
- const [operatingAppId, setOperatingAppId] = useState(null);
- const [operationType, setOperationType] = useState(null);
+ const [operation, setOperation] = useState(null);
const [error, setError] = useState(null);
const [completed, setCompleted] = useState(false);
const clearTimerRef = useRef(null);
- const cleanupRef = useRef(null);
+ const onCompleteRef = useRef(onComplete);
+ // Mirrors the state the socket handlers need to read without re-subscribing
+ // on every render: which app we're tracking, and whether that operation has
+ // already reported a terminal outcome — so the `operations: []` broadcast
+ // that follows a completion doesn't wipe the result off screen.
+ const trackedRef = useRef({ appId: null, finished: false });
- // Clear timer and remove socket listeners on unmount
- useEffect(() => () => {
- clearTimeout(clearTimerRef.current);
- cleanupRef.current?.();
- }, []);
+ useEffect(() => { onCompleteRef.current = onComplete; });
- const handleStep = useCallback((data) => {
- setSteps(prev => {
- const existing = prev.findIndex(s => s.step === data.step);
- const entry = { step: data.step, status: data.status, message: data.message, timestamp: data.timestamp };
- if (existing >= 0) {
- const next = [...prev];
- next[existing] = entry;
- return next;
- }
- return [...prev, entry];
- });
- }, []);
+ useEffect(() => () => clearTimeout(clearTimerRef.current), []);
- const finish = useCallback((_opType) => {
- setIsOperating(false);
- setCompleted(true);
- clearTimerRef.current = setTimeout(() => {
- setSteps([]);
- setCompleted(false);
- setOperatingAppId(null);
- setOperationType(null);
- setError(null);
- }, 5000);
+ const track = useCallback((next) => {
+ clearTimeout(clearTimerRef.current);
+ trackedRef.current = { appId: next.appId, finished: false };
+ setOperation(next);
+ setError(null);
+ setCompleted(false);
}, []);
- const startUpdate = useCallback((appId) => {
+ const reset = useCallback(() => {
clearTimeout(clearTimerRef.current);
+ trackedRef.current = { appId: null, finished: false };
setSteps([]);
+ setOperation(null);
setError(null);
setCompleted(false);
- setIsOperating(true);
- setOperatingAppId(appId);
- setOperationType('update');
+ }, []);
+
+ useEffect(() => {
+ // A frame is ours when it names the app we track (or the app this hook is
+ // scoped to), or when it carries no appId at all — an older server that
+ // predates the per-app broadcast.
+ const isOurs = (data) => {
+ if (!data?.appId) return true;
+ if (scopeAppId) return data.appId === scopeAppId;
+ return !trackedRef.current.appId || data.appId === trackedRef.current.appId;
+ };
+
+ const onActive = ({ operations = [] } = {}) => {
+ const inScope = scopeAppId ? operations.filter(op => op.appId === scopeAppId) : operations;
+ const active = inScope.find(op => op.appId === trackedRef.current.appId) || inScope[0];
+ if (active) {
+ track({ appId: active.appId, appName: active.appName, type: active.type });
+ setSteps(active.steps || []);
+ return;
+ }
+ // Nothing running server-side. Leave a just-finished result on screen and
+ // only clear when we still believe an operation is in flight (e.g. the
+ // server restarted mid-run, so the work is genuinely gone).
+ if (trackedRef.current.appId && !trackedRef.current.finished) reset();
+ };
+
+ const onStep = (data) => {
+ if (!isOurs(data)) return;
+ setSteps(prev => mergeStep(prev, data));
+ };
- const onStep = (data) => handleStep(data);
const onError = (data) => {
- setError(data.message);
- setIsOperating(false);
- cleanup();
+ if (!isOurs(data)) return;
+ trackedRef.current.finished = true;
+ setError(data?.message || 'Operation failed');
};
+
const onDone = (data) => {
- if (data.steps?.some(s => s.warning)) {
- setSteps(prev => prev.map(s => s.step === 'restart' && s.status === 'running' ? { ...s, status: 'warning', message: data.steps.find(ds => ds.warning)?.warning } : s));
+ if (!isOurs(data)) return;
+ const warning = data?.steps?.find(s => s.warning)?.warning;
+ if (warning) {
+ setSteps(prev => prev.map(s => (
+ s.step === 'restart' && s.status === 'running' ? { ...s, status: 'warning', message: warning } : s
+ )));
}
- finish('update');
- onComplete?.();
- cleanup();
- };
- const cleanup = () => {
- socket.off('app:update:step', onStep);
- socket.off('app:update:error', onError);
- socket.off('app:update:complete', onDone);
- cleanupRef.current = null;
+ trackedRef.current.finished = true;
+ setCompleted(true);
+ onCompleteRef.current?.();
+ clearTimeout(clearTimerRef.current);
+ clearTimerRef.current = setTimeout(reset, CLEAR_DELAY_MS);
};
- cleanupRef.current?.();
- cleanupRef.current = cleanup;
+ const requestActive = () => socket.emit('app:operations:list');
+
+ socket.on('app:operations:active', onActive);
socket.on('app:update:step', onStep);
socket.on('app:update:error', onError);
socket.on('app:update:complete', onDone);
- socket.emit('app:update', { appId });
- }, [handleStep, finish, onComplete]);
-
- const startStandardize = useCallback((appId) => {
- clearTimeout(clearTimerRef.current);
- setSteps([]);
- setError(null);
- setCompleted(false);
- setIsOperating(true);
- setOperatingAppId(appId);
- setOperationType('standardize');
+ socket.on('app:standardize:step', onStep);
+ socket.on('app:standardize:error', onError);
+ socket.on('app:standardize:complete', onDone);
+ socket.on('connect', requestActive);
+ // The socket is normally connected long before this page mounts, so the
+ // server's connect-time push already fired — ask for the set again.
+ requestActive();
- const onStep = (data) => handleStep(data);
- const onError = (data) => {
- setError(data.message);
- setIsOperating(false);
- cleanup();
- };
- const onDone = () => {
- finish('standardize');
- onComplete?.();
- cleanup();
- };
- const cleanup = () => {
+ return () => {
+ socket.off('app:operations:active', onActive);
+ socket.off('app:update:step', onStep);
+ socket.off('app:update:error', onError);
+ socket.off('app:update:complete', onDone);
socket.off('app:standardize:step', onStep);
socket.off('app:standardize:error', onError);
socket.off('app:standardize:complete', onDone);
- cleanupRef.current = null;
+ socket.off('connect', requestActive);
};
+ }, [track, reset, scopeAppId]);
- cleanupRef.current?.();
- cleanupRef.current = cleanup;
- socket.on('app:standardize:step', onStep);
- socket.on('app:standardize:error', onError);
- socket.on('app:standardize:complete', onDone);
- socket.emit('app:standardize', { appId });
- }, [handleStep, finish, onComplete]);
+ const start = useCallback((type, appId, appName) => {
+ track({ appId, appName, type });
+ setSteps([]);
+ socket.emit(type === 'update' ? 'app:update' : 'app:standardize', { appId });
+ }, [track]);
+
+ const startUpdate = useCallback((appId, appName) => start('update', appId, appName), [start]);
+ const startStandardize = useCallback((appId, appName) => start('standardize', appId, appName), [start]);
- return { steps, isOperating, operatingAppId, operationType, error, completed, startUpdate, startStandardize };
+ return {
+ steps,
+ // Derived, not a separate flag: a stale `isOperating` was how the old hook
+ // let a finished operation keep every other row's buttons disabled.
+ isOperating: !!operation && !completed && !error,
+ operatingAppId: operation?.appId ?? null,
+ operatingAppName: operation?.appName ?? null,
+ operationType: operation?.type ?? null,
+ error,
+ completed,
+ startUpdate,
+ startStandardize,
+ dismiss: reset
+ };
}
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index 71d8ea7d5d..ec6ac9f6c2 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -9,7 +9,7 @@ import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import KanbanBoard from '../components/KanbanBoard';
import StatusBadge from '../components/StatusBadge';
-import ActivityLog from '../components/apps/ActivityLog';
+import AppOperationBanner from '../components/apps/AppOperationBanner';
import { useAppOperation } from '../hooks/useAppOperation';
import useUrlParams from '../hooks/useUrlParams';
import * as api from '../services/api';
@@ -47,7 +47,10 @@ export default function Apps() {
setLoading(false);
}, []);
- const { steps, isOperating, operatingAppId, operationType, error, completed, startUpdate, startStandardize } = useAppOperation({ onComplete: fetchApps });
+ const {
+ steps, isOperating, operatingAppId, operatingAppName, operationType,
+ error, completed, startUpdate, startStandardize, dismiss
+ } = useAppOperation({ onComplete: fetchApps });
useEffect(() => {
fetchApps();
@@ -98,7 +101,7 @@ export default function Apps() {
if (result?.success) toast.success(`${app.nativeLaunch.label} is running`);
};
- const handleUpdate = (app) => startUpdate(app.id);
+ const handleUpdate = (app) => startUpdate(app.id, app.name);
const handleBuild = async (app) => {
setBuilding(prev => ({ ...prev, [app.id]: true }));
@@ -116,7 +119,7 @@ export default function Apps() {
fetchApps();
};
- const handleStandardize = (app) => startStandardize(app.id);
+ const handleStandardize = (app) => startStandardize(app.id, app.name);
const toggleExpand = async (id) => {
const newExpandedId = expandedId === id ? null : id;
@@ -150,6 +153,11 @@ export default function Apps() {
toast.success(`${app.name} unarchived - included in COS tasks`);
};
+ // The server names the app it is operating on (so a rehydrated operation is
+ // labelled even before the list loads); fall back to the loaded list.
+ const operatingApp = apps.find(app => app.id === operatingAppId);
+ const operationLabel = operatingAppName || operatingApp?.name;
+
// Filter apps based on archive status
const activeApps = apps.filter(app => !app.archived);
const archivedApps = apps.filter(app => app.archived);
@@ -193,6 +201,19 @@ export default function Apps() {
</div>
</div>
+ {/* In-flight update/standardize — page-level so it survives collapsing
+ the row and remounting the page. */}
+ {operatingAppId && (
+ <AppOperationBanner
+ appName={operationLabel}
+ type={operationType}
+ steps={steps}
+ error={error}
+ completed={completed}
+ onDismiss={error || completed ? dismiss : null}
+ />
+ )}
+
{/* App List */}
{displayedApps.length === 0 ? (
<div className="bg-port-card border border-port-border rounded-xl p-12 text-center">
@@ -223,6 +244,12 @@ export default function Apps() {
<div className="space-y-4">
{displayedApps.map(app => {
const isNonPm2 = NON_PM2_TYPES.has(app.type);
+ // Only one update/standardize runs at a time. Rows that aren't the
+ // one operating say so in the button label — a bare greyed control
+ // with a tooltip explains nothing on touch.
+ const rowOperating = operatingAppId === app.id;
+ const busyElsewhere = isOperating && !rowOperating;
+ const busyReason = `${operationLabel || 'Another app'} is ${operationType === 'standardize' ? 'being standardized' : 'updating'}`;
return (
<div
key={app.id}
@@ -587,11 +614,14 @@ export default function Apps() {
<button
onClick={() => handleUpdate(app)}
disabled={isOperating}
- className="px-3 py-1.5 min-h-[40px] sm:min-h-0 bg-port-success/20 text-port-success hover:bg-port-success/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
- aria-label="Pull latest code, install dependencies, run setup, and restart"
+ className="px-3 py-1.5 min-h-[40px] sm:min-h-0 bg-port-success/20 text-port-success enabled:hover:bg-port-success/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
+ aria-label={busyElsewhere ? `Update unavailable — ${busyReason}` : 'Pull latest code, install dependencies, run setup, and restart'}
+ title={busyElsewhere ? busyReason : undefined}
>
- <Download size={14} aria-hidden="true" className={operatingAppId === app.id && operationType === 'update' ? 'animate-bounce' : ''} />
- {operatingAppId === app.id && operationType === 'update' ? 'Updating...' : 'Update'}
+ <Download size={14} aria-hidden="true" className={rowOperating && operationType === 'update' ? 'animate-bounce' : ''} />
+ {rowOperating && operationType === 'update'
+ ? 'Updating...'
+ : busyElsewhere ? 'Update (busy)' : 'Update'}
</button>
{app.buildCommand && (
<button
@@ -620,11 +650,14 @@ export default function Apps() {
<button
onClick={() => handleStandardize(app)}
disabled={isOperating}
- className="px-3 py-1.5 min-h-[40px] sm:min-h-0 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
- aria-label="Standardize PM2 config: move all ports to ecosystem.config.cjs"
+ className="px-3 py-1.5 min-h-[40px] sm:min-h-0 bg-port-accent/20 text-port-accent enabled:hover:bg-port-accent/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
+ aria-label={busyElsewhere ? `Standardize PM2 unavailable — ${busyReason}` : 'Standardize PM2 config: move all ports to ecosystem.config.cjs'}
+ title={busyElsewhere ? busyReason : undefined}
>
- <Wrench size={14} aria-hidden="true" className={operatingAppId === app.id && operationType === 'standardize' ? 'animate-spin' : ''} />
- {operatingAppId === app.id && operationType === 'standardize' ? 'Standardizing...' : 'Standardize PM2'}
+ <Wrench size={14} aria-hidden="true" className={rowOperating && operationType === 'standardize' ? 'animate-spin' : ''} />
+ {rowOperating && operationType === 'standardize'
+ ? 'Standardizing...'
+ : busyElsewhere ? 'Standardize PM2 (busy)' : 'Standardize PM2'}
</button>
)}
</>
@@ -642,11 +675,6 @@ export default function Apps() {
</button>
)}
</div>
-
- {/* Activity Log */}
- {operatingAppId === app.id && (
- <ActivityLog steps={steps} error={error} completed={completed} />
- )}
</div>
</div>
)}
diff --git a/client/src/pages/Apps.test.jsx b/client/src/pages/Apps.test.jsx
index 814622e8cd..30ca34822b 100644
--- a/client/src/pages/Apps.test.jsx
+++ b/client/src/pages/Apps.test.jsx
@@ -205,3 +205,81 @@ describe('Apps archived filter', () => {
expect(screen.queryByText('No archived apps')).toBeNull();
});
});
+
+describe('Apps in-flight operation banner (#3435)', () => {
+ const SECOND_APP = { ...APPS[0], id: 'app-beta', name: 'Second App' };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getApps.mockResolvedValue([APPS[0], SECOND_APP]);
+ });
+
+ // Fire a socket event the page subscribed to, the way the server broadcasts it.
+ const emitSocket = async (event, payload) => {
+ const [, handler] = socket.on.mock.calls.find(([evt]) => evt === event);
+ await act(async () => { await handler(payload); });
+ };
+
+ const activeUpdate = (steps = []) => ({
+ operations: [{ appId: 'app-alpha', appName: 'Example App', type: 'update', steps }]
+ });
+
+ it('asks the server for in-flight operations on mount', async () => {
+ await renderApps();
+ expect(socket.emit).toHaveBeenCalledWith('app:operations:list');
+ });
+
+ it('shows an operation started elsewhere with every row collapsed', async () => {
+ await renderApps();
+ await emitSocket('app:operations:active', activeUpdate([
+ { appId: 'app-alpha', step: 'pull', status: 'running', message: 'Pulling latest…' }
+ ]));
+
+ // No row is expanded — the banner is the only place progress could show.
+ expect(screen.queryByText('Repository Path')).toBeNull();
+ const banner = screen.getByRole('status', { name: 'App operation status' });
+ expect(banner.textContent).toContain('Updating Example App');
+ expect(banner.textContent).toContain('Pulling latest…');
+ });
+
+ it('keeps streaming steps into the banner while the row stays collapsed', async () => {
+ await renderApps();
+ await emitSocket('app:operations:active', activeUpdate());
+ await emitSocket('app:update:step', { appId: 'app-alpha', step: 'install', status: 'running', message: 'Installing deps…' });
+
+ expect(screen.getByRole('status', { name: 'App operation status' }).textContent).toContain('Installing deps…');
+ });
+
+ it('states why another app’s Update is unavailable instead of silently greying it out', async () => {
+ await renderApps();
+ await emitSocket('app:operations:active', activeUpdate());
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'Expand Second App details' }).click();
+ });
+
+ const busy = screen.getByRole('button', { name: /Update unavailable/ });
+ expect(busy.textContent).toContain('Update (busy)');
+ expect(busy.disabled).toBe(true);
+ });
+
+ it('keeps the completion visible when the server reports nothing in flight', async () => {
+ await renderApps();
+ await emitSocket('app:operations:active', activeUpdate());
+ await emitSocket('app:update:complete', { appId: 'app-alpha', success: true, steps: [] });
+ // The server clears its in-flight set right after the completion broadcast.
+ await emitSocket('app:operations:active', { operations: [] });
+
+ expect(screen.getByRole('status', { name: 'App operation status' }).textContent).toContain('Updated Example App');
+ });
+
+ it('clears a stale banner when the server reports no operation and none finished', async () => {
+ await renderApps();
+ await emitSocket('app:operations:active', activeUpdate());
+ expect(screen.getByRole('status', { name: 'App operation status' })).toBeTruthy();
+
+ // e.g. the server restarted mid-operation — the work is genuinely gone.
+ await emitSocket('app:operations:active', { operations: [] });
+ expect(screen.queryByRole('status', { name: 'App operation status' })).toBeNull();
+ });
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index c26c328fd3..b7944467bf 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -71,6 +71,42 @@ const bumpStreamGeneration = (key) => {
streamGenerations.set(key, next);
return next;
};
+// In-flight app update/standardize operations, keyed by app id. These run for
+// minutes (git pull → npm install → setup → pm2 restart) and are dispatched from
+// a page the user can navigate away from, so the server — not the client — is
+// the only place that reliably knows one is still running. Two jobs of it:
+// 1. re-entrancy guard: a second `app:update` for an id already in the map is
+// rejected instead of interleaving a second npm install in the same
+// checkout (sanctioned by the Security Model — duplicate in-flight
+// operations, not competing humans);
+// 2. resumable progress: each entry buffers the steps emitted so far, so a
+// client that mounts (or remounts) mid-operation rehydrates the whole log
+// via `app:operations:active` instead of showing a clean slate.
+const activeAppOperations = new Map();
+
+const activeOperationsPayload = () => ({ operations: [...activeAppOperations.values()] });
+
+const beginAppOperation = (io, app, type) => {
+ const operation = { appId: app.id, appName: app.name, type, steps: [], startedAt: Date.now() };
+ activeAppOperations.set(app.id, operation);
+ io.emit('app:operations:active', activeOperationsPayload());
+ return operation;
+};
+
+const endAppOperation = (io, appId) => {
+ if (!activeAppOperations.delete(appId)) return;
+ io.emit('app:operations:active', activeOperationsPayload());
+};
+
+// Record a step into the operation's buffer using the same last-write-wins
+// per-step semantics the client renders with, so a rehydrated log matches a
+// live-streamed one.
+const recordOperationStep = (operation, frame) => {
+ const existing = operation.steps.findIndex(s => s.step === frame.step);
+ if (existing >= 0) operation.steps[existing] = frame;
+ else operation.steps.push(frame);
+};
+
// Store CoS subscribers
const cosSubscribers = new Set();
// Store error subscribers for auto-fix notifications
@@ -384,6 +420,8 @@ export function initSocket(io) {
// App update handler — streams progress via socket
socket.on('app:update', async (rawData) => {
+ // Tracked outside the try so every exit path releases the in-flight slot.
+ let operatingAppId = null;
try {
const data = validateSocketData(appUpdateSchema, rawData, socket, 'app:update');
if (!data) return;
@@ -394,30 +432,50 @@ export function initSocket(io) {
return;
}
+ const inFlight = activeAppOperations.get(app.id);
+ if (inFlight) {
+ socket.emit('app:update:error', {
+ appId: app.id,
+ message: `An ${inFlight.type} is already running for ${app.name}`
+ });
+ return;
+ }
+
console.log(`⬇️ Socket update started for ${app.name}`);
+ const operation = beginAppOperation(io, app, 'update');
+ operatingAppId = app.id;
+ // Broadcast (not socket.emit): the client that dispatched may have
+ // unmounted, and any other open tab should see the same progress.
const emit = (step, status, message) => {
- socket.emit('app:update:step', { step, status, message, timestamp: Date.now() });
+ const frame = { appId: app.id, step, status, message, timestamp: Date.now() };
+ recordOperationStep(operation, frame);
+ io.emit('app:update:step', frame);
};
const result = await appUpdater.updateApp(app, emit).catch(err => {
- socket.emit('app:update:error', { message: err.message });
+ io.emit('app:update:error', { appId: app.id, message: err.message });
return null;
});
if (result) {
- socket.emit('app:update:complete', { success: result.success, steps: result.steps });
+ io.emit('app:update:complete', { appId: app.id, success: result.success, steps: result.steps });
console.log(`✅ Socket update complete for ${app.name}`);
}
} catch (err) {
const message = err?.message ?? String(err);
console.error(`❌ Socket handler error [app:update]: ${message}`);
- socket.emit('app:update:error', { message });
- socket.emit('app:update:complete', { success: false, steps: [] });
+ io.emit('app:update:error', { appId: operatingAppId, message });
+ io.emit('app:update:complete', { appId: operatingAppId, success: false, steps: [] });
+ } finally {
+ if (operatingAppId) endAppOperation(io, operatingAppId);
}
});
// App standardize handler — streams progress via socket
socket.on('app:standardize', async (rawData) => {
+ // Tracked outside the try so every exit path (early return, thrown error)
+ // releases the in-flight slot in the finally below.
+ let operatingAppId = null;
try {
const data = validateSocketData(appStandardizeSchema, rawData, socket, 'app:standardize');
if (!data) return;
@@ -428,9 +486,22 @@ export function initSocket(io) {
return;
}
+ const inFlight = activeAppOperations.get(app.id);
+ if (inFlight) {
+ socket.emit('app:standardize:error', {
+ appId: app.id,
+ message: `An ${inFlight.type} is already running for ${app.name}`
+ });
+ return;
+ }
+
console.log(`🔧 Socket standardize started for ${app.name}`);
+ const operation = beginAppOperation(io, app, 'standardize');
+ operatingAppId = app.id;
const emit = (step, status, message) => {
- socket.emit('app:standardize:step', { step, status, message, timestamp: Date.now() });
+ const frame = { appId: app.id, step, status, message, timestamp: Date.now() };
+ recordOperationStep(operation, frame);
+ io.emit('app:standardize:step', frame);
};
// Step 1: Analyze
@@ -440,7 +511,7 @@ export function initSocket(io) {
if (!analysis.success) {
emit('analyze', 'error', analysis.error);
- socket.emit('app:standardize:error', { message: analysis.error });
+ io.emit('app:standardize:error', { appId: app.id, message: analysis.error });
return;
}
emit('analyze', 'done', `Found ${analysis.proposedChanges.processes?.length || 0} processes`);
@@ -464,7 +535,7 @@ export function initSocket(io) {
if (result.errors?.length > 0) {
emit('apply', 'error', result.errors.join(', '));
- socket.emit('app:standardize:error', { message: result.errors.join(', ') });
+ io.emit('app:standardize:error', { appId: app.id, message: result.errors.join(', ') });
return;
}
const preserved = result.filesPreserved || [];
@@ -478,7 +549,8 @@ export function initSocket(io) {
await appsService.updateApp(data.appId, { pm2ProcessNames });
}
- socket.emit('app:standardize:complete', {
+ io.emit('app:standardize:complete', {
+ appId: app.id,
success: true,
result: {
backupBranch: result.backupBranch,
@@ -491,10 +563,20 @@ export function initSocket(io) {
} catch (err) {
const message = err?.message ?? String(err);
console.error(`❌ Socket handler error [app:standardize]: ${message}`);
- socket.emit('app:standardize:error', { message });
+ io.emit('app:standardize:error', { appId: operatingAppId, message });
+ } finally {
+ if (operatingAppId) endAppOperation(io, operatingAppId);
}
});
+ // Current in-flight app operations — pushed on connect and on demand, so a
+ // client mounting mid-operation (or after a remount) restores the live
+ // progress instead of showing a clean slate.
+ socket.on('app:operations:list', () => {
+ socket.emit('app:operations:active', activeOperationsPayload());
+ });
+ socket.emit('app:operations:active', activeOperationsPayload());
+
// App deploy handler — streams real-time output from deploy.sh. The
// app-lookup → deploy-script check → run orchestration lives in
// appDeployer.runDeployFlow (testable + HTTP-callable); the handler only
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 5cf7e63712..410a937a60 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -70,6 +70,7 @@ import { mediaJobEvents } from './mediaJobQueue/index.js';
import { audioGenEvents } from './audioGen/events.js';
import { detachSocketSessions } from './shell.js';
import * as shellService from './shell.js';
+import { updateApp as runAppUpdate } from './appUpdater.js';
// Build a minimal fake socket with per-event handler capture
function makeSocket(id = 'sock-1') {
@@ -583,4 +584,83 @@ describe('socket.js — initSocket', () => {
expect(serverStream.kill).toHaveBeenCalledWith('SIGTERM');
});
});
+
+ // ===========================================================================
+ // app:update — server-held in-flight set (#3435)
+ // ===========================================================================
+ describe('app operations in-flight set', () => {
+ const APP = { id: 'app-1', name: 'Example App' };
+ const flush = () => new Promise(resolve => setTimeout(resolve, 0));
+
+ beforeEach(() => {
+ vi.mocked(getAppById).mockResolvedValue(APP);
+ });
+
+ it('rejects a second app:update for an app already updating, then frees the slot when it finishes', async () => {
+ const socket = makeSocket('app-op-guard');
+ io.connect(socket);
+
+ let finishUpdate;
+ vi.mocked(runAppUpdate).mockReturnValueOnce(new Promise(resolve => { finishUpdate = resolve; }));
+
+ const running = socket.handlers['app:update']({ appId: APP.id });
+ await flush();
+ expect(vi.mocked(runAppUpdate)).toHaveBeenCalledTimes(1);
+
+ // Second dispatch for the same app while the first is still running.
+ await socket.handlers['app:update']({ appId: APP.id });
+ const rejections = socket.emitted.filter(([ev, payload]) => ev === 'app:update:error' && /already running/.test(payload.message));
+ expect(rejections).toHaveLength(1);
+ expect(rejections[0][1].appId).toBe(APP.id);
+ // The first run is untouched — no second updateApp call.
+ expect(vi.mocked(runAppUpdate)).toHaveBeenCalledTimes(1);
+
+ finishUpdate({ success: true, steps: [] });
+ await running;
+ await flush();
+
+ // Slot released: the completion broadcast is followed by an empty set.
+ expect(io.emitted.some(([ev, payload]) => ev === 'app:update:complete' && payload.appId === APP.id)).toBe(true);
+ const activeBroadcasts = io.emitted.filter(([ev]) => ev === 'app:operations:active');
+ expect(activeBroadcasts.at(-1)[1].operations).toEqual([]);
+
+ // …and a fresh dispatch is accepted again.
+ vi.mocked(runAppUpdate).mockResolvedValueOnce({ success: true, steps: [] });
+ await socket.handlers['app:update']({ appId: APP.id });
+ await flush();
+ expect(vi.mocked(runAppUpdate)).toHaveBeenCalledTimes(2);
+ });
+
+ it('buffers steps so a client that connects mid-operation rehydrates the log', async () => {
+ const socket = makeSocket('app-op-buffer');
+ io.connect(socket);
+
+ let finishUpdate;
+ vi.mocked(runAppUpdate).mockImplementationOnce((_app, emit) => new Promise(resolve => {
+ emit('pull', 'running', 'Pulling latest…');
+ finishUpdate = resolve;
+ }));
+
+ const running = socket.handlers['app:update']({ appId: APP.id });
+ await flush();
+
+ const latecomer = makeSocket('app-op-latecomer');
+ io.connect(latecomer);
+ const pushed = latecomer.emitted.filter(([ev]) => ev === 'app:operations:active').at(-1)[1];
+ expect(pushed.operations).toHaveLength(1);
+ expect(pushed.operations[0]).toMatchObject({ appId: APP.id, appName: APP.name, type: 'update' });
+ expect(pushed.operations[0].steps).toEqual([
+ expect.objectContaining({ appId: APP.id, step: 'pull', status: 'running' })
+ ]);
+
+ // The same set is available on demand for a page that mounts later.
+ latecomer.emitted.length = 0;
+ latecomer.handlers['app:operations:list']();
+ expect(latecomer.emitted.at(-1)[1].operations).toHaveLength(1);
+
+ finishUpdate({ success: true, steps: [] });
+ await running;
+ await flush();
+ });
+ });
});