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: block the unattended updater while an LLM run or backup is in flight (#7467)

[._.]/ Adam Eivy0e9d7f8a032a
diff --git a/client/src/components/apps/tabs/AutoUpdatePanel.jsx b/client/src/components/apps/tabs/AutoUpdatePanel.jsx
index d9c38bd657..111d8d3266 100644
--- a/client/src/components/apps/tabs/AutoUpdatePanel.jsx
+++ b/client/src/components/apps/tabs/AutoUpdatePanel.jsx
@@ -95,7 +95,7 @@ export default function AutoUpdatePanel() {
</div>
<div className="text-xs text-gray-400 mt-1">
Runs the update for you — but only once the install is completely idle: no render running or queued,
- no CoS agent, no Persistent Mind turn, no app operation.
+ no LLM or pipeline run, no CoS agent, no Persistent Mind turn, no app operation, no backup in progress.
</div>
</div>
<label className="flex items-center gap-2 text-xs text-gray-300 shrink-0" htmlFor="auto-update-enabled">
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 377b1f7c57..2859285fef 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -1022,6 +1022,17 @@ export function createRunnerService(config = {}) {
async isRunActive(runId) {
return externalRuns.has(runId) || activeRuns.has(runId);
+ },
+
+ /**
+ * How many runs this instance is tracking right now — API-based
+ * (`activeRuns`) and host-spawned CLI/TUI (`externalRuns`) alike. A count
+ * only: no run's prompt or output crosses this surface, so a host can
+ * safely fold it into an activity/idle gate (PortOS's `systemIdle.js`
+ * does exactly that) without leaking record content.
+ */
+ async getActiveRunCount() {
+ return activeRuns.size + externalRuns.size;
}
};
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index d426908a9f..83574eb3c1 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -727,6 +727,20 @@ describe('AI Toolkit runner — declared extension points', () => {
expect(await runner.stopRun('x')).toBe(false);
});
+ // getActiveRunCount is the surface the host's system-idle gate reads — it
+ // must count BOTH tracking maps (API runs and host-spawned CLI/TUI runs),
+ // since a host runner never populates the other one for the same run.
+ it('getActiveRunCount sums external and internally-tracked runs', async () => {
+ const runner = createRunnerService({ dataDir: './data' });
+ expect(await runner.getActiveRunCount()).toBe(0);
+
+ runner.registerExternalRun('external-1', externalChild());
+ expect(await runner.getActiveRunCount()).toBe(1);
+
+ await runner.stopRun('external-1');
+ expect(await runner.getActiveRunCount()).toBe(0);
+ });
+
// registerExternalRun also holds node-pty sessions (the host's TUI runs). On
// Windows node-pty throws "Signals not supported on windows." for any signal,
// so a signalled kill there stopped nothing and threw past stopRun, leaving
diff --git a/server/lib/systemIdle.js b/server/lib/systemIdle.js
index 4adc0b0b80..ed104f5e03 100644
--- a/server/lib/systemIdle.js
+++ b/server/lib/systemIdle.js
@@ -103,6 +103,17 @@ export function summarizeSystemActivity(snapshot) {
if (queuedMessages > 0) add('mind-queued', `${pluralize(queuedMessages, 'Persistent Mind message')} queued`, queuedMessages);
}
+ // Same contract as the agent and mind slices: an unreadable run count is not
+ // a zero one, and zero in-flight runs is exactly the value that unlocks a
+ // restart. A prompt/stage run (promptRunner, stageRunner, loops, sprite
+ // workflows) is the most common form of live work on this install — this
+ // is deliberately separate from `agents-running` above, which is a CoS
+ // agent spawned through an entirely different path.
+ const llmState = snapshot?.llm;
+ if (llmState?.trusted === false) add('llm-unreadable', 'In-flight LLM run state unreadable', 1);
+ const activeLlmRuns = Number(llmState?.active) || 0;
+ if (activeLlmRuns > 0) add('llm-running', `${pluralize(activeLlmRuns, 'LLM run')} running`, activeLlmRuns);
+
const appOperations = Array.isArray(snapshot?.appOperations) ? snapshot.appOperations : [];
if (appOperations.length > 0) {
add('app-operations', `${pluralize(appOperations.length, 'app operation')} running`, appOperations.length);
@@ -110,8 +121,14 @@ export function summarizeSystemActivity(snapshot) {
if (snapshot?.update?.inProgress) add('update-in-progress', 'An update is already running', 1);
+ // Milder than the others: a killed backup wastes a snapshot rather than
+ // losing work, but restarting still kills the rsync/pg_dump mid-write.
+ const backupActive = snapshot?.backup?.inProgress ? 1 : 0;
+ if (backupActive) add('backup-running', 'A backup snapshot is running', 1);
+
const activeCount = jobs.filter((job) => job?.status === 'running').length
- + imageTo3d + activeAgents + (mind?.thinking ? 1 : 0) + appOperations.length;
+ + imageTo3d + activeAgents + activeLlmRuns + (mind?.thinking ? 1 : 0) + appOperations.length
+ + backupActive;
const queuedCount = jobs.filter((job) => job?.status === 'queued').length
+ queuedAgents + (Number(mind?.queued) || 0);
diff --git a/server/lib/systemIdle.test.js b/server/lib/systemIdle.test.js
index 7989aaa135..22634f440d 100644
--- a/server/lib/systemIdle.test.js
+++ b/server/lib/systemIdle.test.js
@@ -6,8 +6,10 @@ const snapshot = (overrides = {}) => ({
extras: { imageTo3d: [] },
agents: { trusted: true, active: 0, queued: 0 },
mind: { trusted: true, thinking: false, queued: 0, status: 'idle' },
+ llm: { trusted: true, active: 0 },
appOperations: [],
update: { inProgress: false },
+ backup: { inProgress: false },
...overrides,
});
@@ -86,6 +88,31 @@ describe('system idle verdict', () => {
expect(summarizeSystemActivity(snapshot({ update: { inProgress: true } })).idle).toBe(false);
});
+ // The gap this module shipped without: a prompt/stage run holds a provider
+ // connection or a CLI/TUI child process the updater would kill mid-run.
+ it('counts an in-flight LLM/pipeline run as activity', () => {
+ const verdict = summarizeSystemActivity(snapshot({ llm: { trusted: true, active: 2 } }));
+ expect(verdict.idle).toBe(false);
+ expect(verdict.blockers).toEqual([{ kind: 'llm-running', label: '2 LLM runs running', count: 2 }]);
+ expect(verdict.activeCount).toBe(2);
+ });
+
+ // Bypass probe: a failed read of the run count must not read as "nothing
+ // running" — that zero is exactly the value that unlocks the restart.
+ it('refuses to read an unreadable LLM run count as an idle one', () => {
+ const verdict = summarizeSystemActivity(snapshot({ llm: { trusted: false } }));
+ expect(verdict.idle).toBe(false);
+ expect(verdict.blockers).toEqual([{ kind: 'llm-unreadable', label: 'In-flight LLM run state unreadable', count: 1 }]);
+ });
+
+ // Milder than the others (a wasted snapshot, not lost work), but a running
+ // backup still gets killed mid-rsync by an unattended restart.
+ it('counts a running backup snapshot as activity', () => {
+ const verdict = summarizeSystemActivity(snapshot({ backup: { inProgress: true } }));
+ expect(verdict.idle).toBe(false);
+ expect(verdict.blockers).toEqual([{ kind: 'backup-running', label: 'A backup snapshot is running', count: 1 }]);
+ });
+
// A degraded snapshot (a slice that failed to load) must still produce a
// usable verdict rather than throwing inside the scheduler's tick.
it('reads missing slices as absent rather than throwing', () => {
diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.js
index 0073348250..08afb17a61 100644
--- a/server/services/activeProcessing.js
+++ b/server/services/activeProcessing.js
@@ -9,6 +9,15 @@ import { readPersistentMindStateForSafetyCheck } from './cosState.js';
import { isUpdateInProgress } from './updateChecker.js';
import * as cos from './cos.js';
+// Lazy — NOT a static top-level import. `services/runner.js` and
+// `services/backup.js` both drag heavy subtrees (provider CLI spawning;
+// `socket.js` → `instances.js` respectively) that this module's own callers
+// (`routes/systemHealth.js`, the dashboard) must not eagerly reach just to
+// read a count/flag. `routes/update.js` already defers this whole module the
+// same way for the same reason — see "Import scoping" in server/AGENTS.md.
+const importRunner = () => import('./runner.js');
+const importBackup = () => import('./backup.js');
+
const LIVE_STATUSES = new Set(['queued', 'running']);
/**
@@ -38,6 +47,18 @@ function summarizeMind(snapshot) {
};
}
+/**
+ * In-flight LLM/pipeline run count, off the toolkit's own `activeRuns` +
+ * `externalRuns` tracking (`getActiveRunCount` in `services/runner.js`).
+ * Counts and lifecycle only — no prompt or response content ever reaches this
+ * slice. `trusted: false` (the count could not be read) is NOT collapsed into
+ * "idle", the same contract the agent and Persistent Mind slices keep: a
+ * failed read must never manufacture the zero that unlocks a restart.
+ */
+function llmRunState(count) {
+ return count === null ? { trusted: false, active: 0 } : { trusted: true, active: count };
+}
+
/**
* Active vs queued CoS agents, from ONE read of the agent list.
*
@@ -83,7 +104,7 @@ function agentCounts(agents, cosStatus, pendingTaskIds) {
* when the daemon is wedged. Neither feeds the verdict.
*/
export async function getSystemActivity() {
- const [jobs, models, pendingTaskIds, agents, mindState] = await Promise.all([
+ const [jobs, models, pendingTaskIds, agents, mindState, activeRunCount, backupInProgress] = await Promise.all([
Promise.resolve(listJobs()).then((items) => items.filter((job) => LIVE_STATUSES.has(job.status))),
// `null` = the read FAILED, distinct from `[]` = read fine, nothing
// building. Both of these degrade to the value that unlocks a restart, so
@@ -96,6 +117,13 @@ export async function getSystemActivity() {
// Same contract one layer down: the reader reports `trusted: false` rather
// than an empty mind, so an unreadable state cannot read as an idle one.
readPersistentMindStateForSafetyCheck().catch(() => ({ trusted: false, persistentMind: null })),
+ // Same contract again: a failed read degrades to `null`, not 0.
+ importRunner().then((m) => m.getActiveRunCount()).catch(() => null),
+ // The only way this rejects is the lazy import itself failing (the module
+ // is otherwise a synchronous, no-I/O flag read) — an anomaly rare enough
+ // that it is itself reason to refuse rather than read as "no backup
+ // running", the same fail-closed direction every other slice here takes.
+ importBackup().then((m) => m.isBackupInProgress()).catch(() => true),
]);
const cosStatus = agents === null ? await cos.getStatus().catch(() => null) : null;
const slices = {
@@ -105,11 +133,18 @@ export async function getSystemActivity() {
extras: { imageTo3d: models === null ? null : models.map((model) => ({ id: model.id, name: model.name || model.id })) },
agents: agentCounts(agents, cosStatus, pendingTaskIds),
mind: summarizeMind(mindState),
+ // A prompt/stage run holds a provider connection or a CLI/TUI child
+ // process — activity in exactly the sense the updater must not restart
+ // through, and distinct from a CoS agent (its own slice above, spawned
+ // through a different path entirely).
+ llm: llmRunState(activeRunCount),
// An App Management update/standardize holds a checkout and restarts PM2
// processes — activity in exactly the sense that matters to a caller
// deciding whether it may restart the install.
appOperations: listActiveAppOperations(),
update: { inProgress: isUpdateInProgress() },
+ // No trusted contract needed: an in-process flag with no I/O once loaded.
+ backup: { inProgress: backupInProgress },
};
return { ...slices, activity: summarizeSystemActivity(slices) };
}
diff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.js
index c7e32155b4..449977ebd9 100644
--- a/server/services/activeProcessing.test.js
+++ b/server/services/activeProcessing.test.js
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const deps = vi.hoisted(() => ({
capability: vi.fn(), utilization: vi.fn(), jobs: vi.fn(), running: vi.fn(), models: vi.fn(), loaded: vi.fn(), tasks: vi.fn(), status: vi.fn(), agents: vi.fn(),
- mind: vi.fn(), operations: vi.fn(), updating: vi.fn(),
+ mind: vi.fn(), operations: vi.fn(), updating: vi.fn(), runCount: vi.fn(), backupRunning: vi.fn(),
}));
vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: deps.capability, getCudaUtilization: deps.utilization }));
vi.mock('./mediaJobQueue/index.js', () => ({ listJobs: deps.jobs, getRunningJob: deps.running }));
@@ -13,6 +13,8 @@ vi.mock('./cos.js', () => ({ getPendingTaskIds: deps.tasks, getStatus: deps.stat
vi.mock('./cosState.js', () => ({ readPersistentMindStateForSafetyCheck: deps.mind }));
vi.mock('./appOperations.js', () => ({ listActiveAppOperations: deps.operations }));
vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: deps.updating }));
+vi.mock('./runner.js', () => ({ getActiveRunCount: deps.runCount }));
+vi.mock('./backup.js', () => ({ isBackupInProgress: deps.backupRunning }));
const { getActiveProcessing } = await import('./activeProcessing.js');
@@ -22,6 +24,8 @@ describe('active processing snapshot', () => {
deps.mind.mockResolvedValue({ trusted: true, persistentMind: { enabled: true, started: true, status: 'idle', queuedMessages: [], activeTurn: null } });
deps.operations.mockReturnValue([]);
deps.updating.mockReturnValue(false);
+ deps.runCount.mockResolvedValue(0);
+ deps.backupRunning.mockReturnValue(false);
});
it('reports sanitized audio work, GPU utilization, and non-media extras', async () => {
@@ -88,6 +92,8 @@ describe('persistent mind and idle verdict', () => {
deps.tasks.mockResolvedValue([]);
deps.agents.mockResolvedValue([]);
deps.status.mockResolvedValue({ activeAgents: 0 });
+ deps.runCount.mockResolvedValue(0);
+ deps.backupRunning.mockReturnValue(false);
});
it('reports an active turn as thinking, carrying counts but no message content', async () => {
@@ -148,6 +154,8 @@ describe('queued agent count', () => {
deps.models.mockResolvedValue([]);
deps.loaded.mockResolvedValue([]);
deps.status.mockResolvedValue({ activeAgents: 0 });
+ deps.runCount.mockResolvedValue(0);
+ deps.backupRunning.mockReturnValue(false);
});
it('does not count a pending task a running agent already holds', async () => {
@@ -212,3 +220,64 @@ describe('queued agent count', () => {
expect(snapshot.activity.blockers.map(b => b.kind)).toContain('agents-unreadable');
});
});
+
+// The gap this module shipped without: a promptRunner/stageRunner run holds a
+// provider connection or a CLI/TUI child process — the most common form of
+// live work on this install, and none of the other slices ever saw it.
+describe('LLM run and backup snapshot activity', () => {
+ beforeEach(() => {
+ Object.values(deps).forEach((mock) => mock.mockReset());
+ deps.mind.mockResolvedValue({ trusted: true, persistentMind: { enabled: true, started: true, status: 'idle', queuedMessages: [], activeTurn: null } });
+ deps.operations.mockReturnValue([]);
+ deps.updating.mockReturnValue(false);
+ deps.capability.mockResolvedValue({ status: 'absent', gpus: [] });
+ deps.jobs.mockReturnValue([]);
+ deps.running.mockReturnValue(null);
+ deps.models.mockResolvedValue([]);
+ deps.loaded.mockResolvedValue([]);
+ deps.tasks.mockResolvedValue([]);
+ deps.agents.mockResolvedValue([]);
+ deps.status.mockResolvedValue({ activeAgents: 0 });
+ });
+
+ // Contract test: a live run blocks the gate.
+ it('blocks idle while an LLM/pipeline run is in flight', async () => {
+ deps.runCount.mockResolvedValue(1);
+ deps.backupRunning.mockReturnValue(false);
+ const snapshot = await getActiveProcessing();
+ expect(snapshot.llm).toEqual({ trusted: true, active: 1 });
+ expect(snapshot.activity.idle).toBe(false);
+ expect(snapshot.activity.blockers.map(b => b.kind)).toContain('llm-running');
+ });
+
+ // Bypass probe: a FAILED read of the run count must not collapse into "zero
+ // running" — that is exactly the value that would unlock the restart. This
+ // guard is worthless unless it also fails without the fix in place.
+ it('refuses to read a failed run-count read as an idle one', async () => {
+ deps.runCount.mockRejectedValue(new Error('toolkit unavailable'));
+ deps.backupRunning.mockReturnValue(false);
+ const snapshot = await getActiveProcessing();
+ expect(snapshot.llm).toEqual({ trusted: false, active: 0 });
+ expect(snapshot.activity.idle).toBe(false);
+ expect(snapshot.activity.blockers.map(b => b.kind)).toContain('llm-unreadable');
+ });
+
+ it('reports zero active runs and idle when nothing is tracked', async () => {
+ deps.runCount.mockResolvedValue(0);
+ deps.backupRunning.mockReturnValue(false);
+ const snapshot = await getActiveProcessing();
+ expect(snapshot.llm).toEqual({ trusted: true, active: 0 });
+ expect(snapshot.activity.idle).toBe(true);
+ });
+
+ // Milder than the others: a killed backup wastes a snapshot rather than
+ // losing work, but it still belongs in the same gate.
+ it('blocks idle while a backup snapshot is running', async () => {
+ deps.runCount.mockResolvedValue(0);
+ deps.backupRunning.mockReturnValue(true);
+ const snapshot = await getActiveProcessing();
+ expect(snapshot.backup).toEqual({ inProgress: true });
+ expect(snapshot.activity.idle).toBe(false);
+ expect(snapshot.activity.blockers.map(b => b.kind)).toContain('backup-running');
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index c8bd252411..8eb70fe25a 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1471,3 +1471,20 @@ export function getNextRunTime() {
const event = getEvent('backup-daily');
return event?.nextRunAt ? new Date(event.nextRunAt).toISOString() : null;
}
+
+/**
+ * Whether THIS process has a backup snapshot in flight right now, for the
+ * system-idle gate. Deliberately reads the in-process `isRunning` flag rather
+ * than scanning for an on-disk `.in-progress` marker: that marker is designed
+ * to OUTLIVE a crash/PM2 restart so a restore never mistakes a partial
+ * snapshot for a complete one, but nothing ever clears an orphaned one on its
+ * own (the next run writes a fresh snapshot id) — gating the updater on its
+ * mere existence would block it forever after a single interrupted backup on
+ * a drive that might not even be mounted. The gate only needs to know whether
+ * restarting would kill a live rsync/pg_dump in this server instance, and
+ * `isRunning` answers exactly that, with no I/O and nothing that can fail to
+ * read.
+ */
+export function isBackupInProgress() {
+ return isRunning;
+}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index f16023da60..c7efc43641 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -2326,6 +2326,7 @@ describe('runBackup lifecycle', () => {
let destRoot;
let prevMemoryBackend;
let runBackup;
+ let isBackupInProgress;
let dataRoot;
// Real fs bound once, bypassing the module-level fs/promises mock, so the
@@ -2377,7 +2378,7 @@ describe('runBackup lifecycle', () => {
// Fresh module per test: `isRunning` is module-level state, so the lock
// tests must not inherit a previous test's value.
vi.resetModules();
- ({ runBackup } = await import('./backup.js'));
+ ({ runBackup, isBackupInProgress } = await import('./backup.js'));
({ PATHS: { data: dataRoot } } = await import('../lib/fileUtils.js'));
});
@@ -2596,6 +2597,25 @@ describe('runBackup lifecycle', () => {
await first;
});
+ // Feeds the system-idle gate (server/lib/systemIdle.js): a live snapshot
+ // must not read as an idle install, or the unattended updater would kill
+ // rsync mid-write. `isBackupInProgress` is the signal that gate reads.
+ it('isBackupInProgress reflects the in-process run, false before and after', async () => {
+ expect(isBackupInProgress()).toBe(false);
+
+ const io = { emit: vi.fn() };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+
+ const pending = runBackup(destRoot, io);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ expect(isBackupInProgress()).toBe(true);
+
+ proc.emit('close', 0);
+ await pending;
+ expect(isBackupInProgress()).toBe(false);
+ });
+
// A snapshot mid-assembly would tar/rsync as a truncated tree that looks like
// a complete backup. Driven through the real runBackup rather than a stubbed
// marker so the guard is tested against the state that actually gates it.
diff --git a/server/services/runner.js b/server/services/runner.js
index e91773ff36..6698ced111 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -689,3 +689,15 @@ export async function deleteFailedRuns() {
export async function isRunActive(runId) {
return requireToolkit().services.runner.isRunActive(runId);
}
+
+/**
+ * Count of in-flight LLM/pipeline runs the toolkit is tracking right now —
+ * counts and lifecycle only, never a prompt or a response. Feeds the
+ * system-idle gate (`server/lib/systemIdle.js`) so a live run blocks the
+ * unattended updater the same way a CoS agent or a Persistent Mind turn does.
+ * `null` (not 0) when the toolkit isn't loaded to read from — a boot-race
+ * absence must not manufacture the zero that unlocks a restart.
+ */
+export async function getActiveRunCount() {
+ return getAIToolkitInstance()?.services?.runner?.getActiveRunCount?.() ?? null;
+}