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
fix: scope the app-operation guard to the checkout and stop a refused dispatch reading as failure (#3435)
[._.]/ Adam Eivye1b0c2eee246
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ff2e7f7fb3..9a330a5d70 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,7 +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.+- **[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. Operations are tracked per app id, so two apps operating from different tabs each get their own banner instead of one shadowing the other, and the app-detail Overview tab passes its own `appId` so it still reports only its own operation. The guard also matches on `repoPath`, since two app records can point at the same checkout; a refused dispatch is flagged `duplicate` so the client toasts it without marking the healthy run failed; and a completion carrying `success: false` now reads as a failure instead of "Operation complete".- **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.jsxindex 41d4582498..706d93155c 100644--- a/client/src/components/apps/AppOperationBanner.jsx+++ b/client/src/components/apps/AppOperationBanner.jsx@@ -24,7 +24,7 @@ export default function AppOperationBanner({ appName, type, steps, error, complereturn (<div- className={`sticky top-0 z-20 mb-4 rounded-xl border p-3 backdrop-blur ${tone}`}+ className={`rounded-xl border p-3 backdrop-blur ${tone}`}role="status"aria-live="polite"aria-label="App operation status"diff --git a/client/src/hooks/useAppOperation.js b/client/src/hooks/useAppOperation.jsindex 963d7e6509..17ad768d2a 100644--- a/client/src/hooks/useAppOperation.js+++ b/client/src/hooks/useAppOperation.js@@ -1,5 +1,6 @@import { useState, useCallback, useEffect, useRef } from 'react';import socket from '../services/socket';+import toast from '../components/ui/Toast';const CLEAR_DELAY_MS = 5000;@@ -12,6 +13,8 @@ const mergeStep = (prev, data) => {return next;};+const isLive = (op) => !!op && !op.completed && !op.error;+/*** Hook for socket-based app operations (update, standardize) with live step tracking.*@@ -19,94 +22,111 @@ const mergeStep = (prev, data) => {* 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).+ * operation (#3435). Operations are tracked per app id, so two apps updating+ * from different tabs are both represented rather than one shadowing the other.** `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.+ * operation; omit it on the multi-app list, which reports every operation.*/export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {- const [steps, setSteps] = useState([]);- const [operation, setOperation] = useState(null);- const [error, setError] = useState(null);- const [completed, setCompleted] = useState(false);- const clearTimerRef = useRef(null);+ const [operations, setOperations] = useState({});+ const clearTimersRef = useRef({});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 });useEffect(() => { onCompleteRef.current = onComplete; });- useEffect(() => () => clearTimeout(clearTimerRef.current), []);-- const track = useCallback((next) => {- clearTimeout(clearTimerRef.current);- trackedRef.current = { appId: next.appId, finished: false };- setOperation(next);- setError(null);- setCompleted(false);+ useEffect(() => () => {+ for (const timer of Object.values(clearTimersRef.current)) clearTimeout(timer);}, []);- const reset = useCallback(() => {- clearTimeout(clearTimerRef.current);- trackedRef.current = { appId: null, finished: false };- setSteps([]);- setOperation(null);- setError(null);- setCompleted(false);+ const drop = useCallback((appId) => {+ clearTimeout(clearTimersRef.current[appId]);+ delete clearTimersRef.current[appId];+ setOperations(prev => {+ if (!prev[appId]) return prev;+ const next = { ...prev };+ delete next[appId];+ return next;+ });}, []);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 inScope = (appId) => !scopeAppId || appId === scopeAppId;+ // Frames from an older server carry no appId; attribute them to the app we+ // are scoped to (or the only live operation) rather than dropping them.+ const resolveAppId = (data, current) => {+ if (data?.appId) return data.appId;+ if (scopeAppId) return scopeAppId;+ const live = Object.values(current).filter(isLive);+ return live.length === 1 ? live[0].appId : null;};- 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 patch = (data, updater) => setOperations(prev => {+ const appId = resolveAppId(data, prev);+ if (!appId || !inScope(appId)) return prev;+ const current = prev[appId] || { appId, appName: null, type: 'update', steps: [] };+ return { ...prev, [appId]: updater(current) };+ });++ const onActive = ({ operations: active = [] } = {}) => {+ setOperations(prev => {+ const next = {};+ for (const op of active) {+ if (!inScope(op.appId)) continue;+ const current = prev[op.appId];+ next[op.appId] = {+ appId: op.appId,+ appName: op.appName ?? current?.appName ?? null,+ type: op.type,+ steps: op.steps?.length ? op.steps : (current?.steps || []),+ error: null,+ completed: false+ };+ }+ // The server drops an operation from the set the moment it ends, so keep+ // entries that already reported a terminal outcome — they're mid-display+ // and their own clear timer removes them. Anything else we still believed+ // was running is genuinely gone (e.g. the server restarted).+ for (const [appId, op] of Object.entries(prev)) {+ if (!next[appId] && !isLive(op)) next[appId] = op;+ }+ return next;+ });};- const onStep = (data) => {- if (!isOurs(data)) return;- setSteps(prev => mergeStep(prev, data));- };+ const onStep = (data) => patch(data, current => ({ ...current, steps: mergeStep(current.steps, data) }));const onError = (data) => {- if (!isOurs(data)) return;- trackedRef.current.finished = true;- setError(data?.message || 'Operation failed');+ // A refused duplicate dispatch says nothing about the run already in+ // flight — surface it without marking that run failed.+ if (data?.duplicate) {+ toast.error(data.message || 'That operation is already running');+ // Re-sync so the optimistic entry this dispatch created is replaced by+ // the operation the server is actually running.+ socket.emit('app:operations:list');+ return;+ }+ patch(data, current => ({ ...current, error: data?.message || 'Operation failed' }));};const onDone = (data) => {- 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- )));+ patch(data, current => {+ const warning = data?.steps?.find(s => s.warning)?.warning;+ const steps = warning+ ? current.steps.map(s => (s.step === 'restart' && s.status === 'running' ? { ...s, status: 'warning', message: warning } : s))+ : current.steps;+ // `success: false` is a failed run, not a finished one — don't report it+ // as "complete" the way the pre-#3435 hook did.+ return data?.success === false+ ? { ...current, steps, error: 'Operation did not complete successfully' }+ : { ...current, steps, completed: true };+ });+ const appId = data?.appId || scopeAppId;+ if (appId) {+ clearTimeout(clearTimersRef.current[appId]);+ clearTimersRef.current[appId] = setTimeout(() => drop(appId), CLEAR_DELAY_MS);}- trackedRef.current.finished = true;- setCompleted(true);onCompleteRef.current?.();- clearTimeout(clearTimerRef.current);- clearTimerRef.current = setTimeout(reset, CLEAR_DELAY_MS);};const requestActive = () => socket.emit('app:operations:list');@@ -133,29 +153,35 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {socket.off('app:standardize:complete', onDone);socket.off('connect', requestActive);};- }, [track, reset, scopeAppId]);+ }, [scopeAppId, drop]);const start = useCallback((type, appId, appName) => {- track({ appId, appName, type });- setSteps([]);+ clearTimeout(clearTimersRef.current[appId]);+ delete clearTimersRef.current[appId];+ setOperations(prev => ({ ...prev, [appId]: { appId, appName, type, steps: [], error: null, completed: false } }));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]);+ const list = Object.values(operations);+ // Single-operation view, for surfaces scoped to one app (Overview tab).+ const primary = list.find(isLive) || list[0] || null;+return {- steps,+ operations: list,// 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,+ // let a finished operation keep every row's buttons disabled.+ isOperating: list.some(isLive),+ steps: primary?.steps || [],+ error: primary?.error ?? null,+ completed: primary?.completed ?? false,+ operatingAppId: primary?.appId ?? null,+ operatingAppName: primary?.appName ?? null,+ operationType: primary?.type ?? null,startUpdate,startStandardize,- dismiss: reset+ dismiss: drop};}diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsxindex ec6ac9f6c2..b52f546f22 100644--- a/client/src/pages/Apps.jsx+++ b/client/src/pages/Apps.jsx@@ -47,10 +47,7 @@ export default function Apps() {setLoading(false);}, []);- const {- steps, isOperating, operatingAppId, operatingAppName, operationType,- error, completed, startUpdate, startStandardize, dismiss- } = useAppOperation({ onComplete: fetchApps });+ const { operations, isOperating, startUpdate, startStandardize, dismiss } = useAppOperation({ onComplete: fetchApps });useEffect(() => {fetchApps();@@ -155,8 +152,8 @@ export default function Apps() {// 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;+ const operationName = (op) => op.appName || apps.find(app => app.id === op.appId)?.name;+ const liveOperation = operations.find(op => !op.completed && !op.error);// Filter apps based on archive statusconst activeApps = apps.filter(app => !app.archived);@@ -203,15 +200,20 @@ export default function Apps() {{/* In-flight update/standardize — page-level so it survives collapsingthe row and remounting the page. */}- {operatingAppId && (+ {operations.length > 0 && (+ <div className="sticky top-0 z-20 mb-4 space-y-2">+ {operations.map(op => (<AppOperationBanner- appName={operationLabel}- type={operationType}- steps={steps}- error={error}- completed={completed}- onDismiss={error || completed ? dismiss : null}+ key={op.appId}+ appName={operationName(op)}+ type={op.type}+ steps={op.steps}+ error={op.error}+ completed={op.completed}+ onDismiss={op.error || op.completed ? () => dismiss(op.appId) : null}/>+ ))}+ </div>)}{/* App List */}@@ -244,12 +246,13 @@ 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;+ // One update/standardize 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 rowOperation = operations.find(op => op.appId === app.id);+ const rowOperating = !!rowOperation && !rowOperation.completed && !rowOperation.error;const busyElsewhere = isOperating && !rowOperating;- const busyReason = `${operationLabel || 'Another app'} is ${operationType === 'standardize' ? 'being standardized' : 'updating'}`;+ const busyReason = `${(liveOperation && operationName(liveOperation)) || 'Another app'} is ${liveOperation?.type === 'standardize' ? 'being standardized' : 'updating'}`;return (<divkey={app.id}@@ -618,8 +621,8 @@ export default function Apps() {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={rowOperating && operationType === 'update' ? 'animate-bounce' : ''} />- {rowOperating && operationType === 'update'+ <Download size={14} aria-hidden="true" className={rowOperating && rowOperation.type === 'update' ? 'animate-bounce' : ''} />+ {rowOperating && rowOperation.type === 'update'? 'Updating...': busyElsewhere ? 'Update (busy)' : 'Update'}</button>@@ -654,8 +657,8 @@ export default function Apps() {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={rowOperating && operationType === 'standardize' ? 'animate-spin' : ''} />- {rowOperating && operationType === 'standardize'+ <Wrench size={14} aria-hidden="true" className={rowOperating && rowOperation.type === 'standardize' ? 'animate-spin' : ''} />+ {rowOperating && rowOperation.type === 'standardize'? 'Standardizing...': busyElsewhere ? 'Standardize PM2 (busy)' : 'Standardize PM2'}</button>diff --git a/client/src/pages/Apps.test.jsx b/client/src/pages/Apps.test.jsxindex 30ca34822b..1e663879a1 100644--- a/client/src/pages/Apps.test.jsx+++ b/client/src/pages/Apps.test.jsx@@ -283,3 +283,63 @@ describe('Apps in-flight operation banner (#3435)', () => {expect(screen.queryByRole('status', { name: 'App operation status' })).toBeNull();});});++describe('Apps concurrent operations and duplicate dispatch (#3435)', () => {+ const SECOND_APP = { ...APPS[0], id: 'app-beta', name: 'Second App' };++ beforeEach(() => {+ vi.clearAllMocks();+ api.getApps.mockResolvedValue([APPS[0], SECOND_APP]);+ });++ const emitSocket = async (event, payload) => {+ const [, handler] = socket.on.mock.calls.find(([evt]) => evt === event);+ await act(async () => { await handler(payload); });+ };++ const banners = () => screen.getAllByRole('status', { name: 'App operation status' });++ it('represents every running operation rather than shadowing one with the other', async () => {+ await renderApps();+ await emitSocket('app:operations:active', {+ operations: [+ { appId: 'app-alpha', appName: 'Example App', type: 'update', steps: [] },+ { appId: 'app-beta', appName: 'Second App', type: 'standardize', steps: [] }+ ]+ });+ await emitSocket('app:standardize:step', { appId: 'app-beta', step: 'analyze', status: 'running', message: 'Analyzing…' });++ const text = banners().map(b => b.textContent).join(' ');+ expect(text).toContain('Updating Example App');+ expect(text).toContain('Standardizing Second App');+ // The second app's steps land on the second app's banner, not the first's.+ expect(banners()[1].textContent).toContain('Analyzing…');+ });++ it('does not report a refused duplicate dispatch as the running operation failing', async () => {+ await renderApps();+ await emitSocket('app:operations:active', {+ operations: [{ appId: 'app-alpha', appName: 'Example App', type: 'update', steps: [] }]+ });++ await emitSocket('app:update:error', {+ appId: 'app-alpha',+ duplicate: true,+ message: 'An update is already running for Example App'+ });++ // Still shown as running — the rejection was about the second dispatch.+ expect(banners()[0].textContent).toContain('Updating Example App');+ expect(banners()[0].textContent).not.toContain('failed');+ });++ it('treats an unsuccessful completion as a failure instead of "complete"', async () => {+ await renderApps();+ await emitSocket('app:operations:active', {+ operations: [{ appId: 'app-alpha', appName: 'Example App', type: 'update', steps: [] }]+ });+ await emitSocket('app:update:complete', { appId: 'app-alpha', success: false, steps: [] });++ expect(banners()[0].textContent).toContain('Update failed for Example App');+ });+});diff --git a/server/services/socket.js b/server/services/socket.jsindex b7944467bf..ea3d790931 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -84,10 +84,19 @@ const bumpStreamGeneration = (key) => {// via `app:operations:active` instead of showing a clean slate.const activeAppOperations = new Map();-const activeOperationsPayload = () => ({ operations: [...activeAppOperations.values()] });+// repoPath stays server-side: the client only needs to name and render the run.+const activeOperationsPayload = () => ({+ operations: [...activeAppOperations.values()].map(({ repoPath: _repoPath, ...op }) => op)+});++// Two app records may point at the same checkout, so the app id alone doesn't+// identify the resource being mutated — match the repo path too, or a second+// record's Update would run `npm install` in a directory already being rebuilt.+const findConflictingOperation = (app) => activeAppOperations.get(app.id)+ || (app.repoPath ? [...activeAppOperations.values()].find(op => op.repoPath === app.repoPath) : undefined);const beginAppOperation = (io, app, type) => {- const operation = { appId: app.id, appName: app.name, type, steps: [], startedAt: Date.now() };+ const operation = { appId: app.id, appName: app.name, type, steps: [], startedAt: Date.now(), repoPath: app.repoPath };activeAppOperations.set(app.id, operation);io.emit('app:operations:active', activeOperationsPayload());return operation;@@ -432,11 +441,15 @@ export function initSocket(io) {return;}- const inFlight = activeAppOperations.get(app.id);+ const inFlight = findConflictingOperation(app);if (inFlight) {+ // `duplicate` marks this as "your dispatch was refused", not "the+ // running operation failed" — the client must not show a failure for+ // a run that is still healthy.socket.emit('app:update:error', {appId: app.id,- message: `An ${inFlight.type} is already running for ${app.name}`+ duplicate: true,+ message: `An ${inFlight.type} is already running for ${inFlight.appName}`});return;}@@ -486,11 +499,12 @@ export function initSocket(io) {return;}- const inFlight = activeAppOperations.get(app.id);+ const inFlight = findConflictingOperation(app);if (inFlight) {socket.emit('app:standardize:error', {appId: app.id,- message: `An ${inFlight.type} is already running for ${app.name}`+ duplicate: true,+ message: `An ${inFlight.type} is already running for ${inFlight.appName}`});return;}diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 410a937a60..c813b40582 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -589,7 +589,7 @@ describe('socket.js — initSocket', () => {// app:update — server-held in-flight set (#3435)// ===========================================================================describe('app operations in-flight set', () => {- const APP = { id: 'app-1', name: 'Example App' };+ const APP = { id: 'app-1', name: 'Example App', repoPath: '/srv/example-app' };const flush = () => new Promise(resolve => setTimeout(resolve, 0));beforeEach(() => {@@ -612,6 +612,8 @@ describe('socket.js — initSocket', () => {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);+ // Flagged as a refused dispatch, not a failure of the run in flight.+ expect(rejections[0][1].duplicate).toBe(true);// The first run is untouched — no second updateApp call.expect(vi.mocked(runAppUpdate)).toHaveBeenCalledTimes(1);@@ -631,6 +633,28 @@ describe('socket.js — initSocket', () => {expect(vi.mocked(runAppUpdate)).toHaveBeenCalledTimes(2);});+ it('blocks a second app record that points at the same checkout', async () => {+ const socket = makeSocket('app-op-alias');+ 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();++ // A different app id, same repoPath — the resource being rebuilt is shared.+ vi.mocked(getAppById).mockResolvedValueOnce({ id: 'app-2', name: 'Alias App', repoPath: APP.repoPath });+ await socket.handlers['app:standardize']({ appId: 'app-2' });++ expect(socket.emitted.some(([ev, payload]) => (+ ev === 'app:standardize:error' && payload.duplicate === true && payload.message.includes(APP.name)+ ))).toBe(true);++ finishUpdate({ success: true, steps: [] });+ await running;+ await flush();+ });+it('buffers steps so a client that connects mid-operation rehydrates the log', async () => {const socket = makeSocket('app-op-buffer');io.connect(socket);@@ -649,6 +673,8 @@ describe('socket.js — initSocket', () => {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' });+ // The wire payload names the run; the checkout path stays server-side.+ expect(pushed.operations[0].repoPath).toBeUndefined();expect(pushed.operations[0].steps).toEqual([expect.objectContaining({ appId: APP.id, step: 'pull', status: 'running' })]);