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: close three busy-probe gaps found in review (#3342)
[._.]/ Adam Eivy39c6ae49246e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex eaea9b3b0f..ef1dae217a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -121,7 +121,7 @@- **[issue-3285] Every directory on the Data Manager now says what it holds and whether it is safe to remove.** Seven of the thirteen biggest rows — including the single largest one — were labelled "Unknown category", and because an unrecognised directory also fell back to "not archivable, not deletable", the cleanup page silently refused to act on the very things filling the disk. All ~65 directories PortOS creates under `data/` are now classified with a real description and honest archive/purge flags: LoRA training checkpoints and the managed Python virtualenv are purgeable and say what survives, while generated sprite art, training datasets and 3D meshes are explicitly protected as the only copy. A directory that genuinely has no classification now reads "Not classified — PortOS does not know if this is safe to remove" and explains that Archive and Purge are being withheld on purpose, and a new test fails the build if a future data directory ships without an entry.- **[issue-3327] Images, videos and LoRAs can no longer be wiped in one click.** All three were marked purgeable, so a single confirm ran a recursive delete over the whole directory — even though those bytes are the only copy, and trained LoRA adapters are excluded from backup snapshots and cost hours of GPU time to retrain. LoRAs are now protected outright, and Images and Videos trade the all-or-nothing Purge button for a per-entry delete in the expanded file list, so reclaiming space stays possible without betting the whole folder on one confirmation. A new `purgeScope` flag records the distinction explicitly rather than overloading "deletable", the purge endpoint refuses a category-wide wipe for item-scoped categories instead of trusting the UI to hide the button, and an unrecognised scope fails closed.-- **[issue-3342] Purging scratch no longer pulls the rug out from under a job that is still running.** Image Cleaner scratch, LoRA training runs and the self-update control files are all genuinely reproducible — which is why they stay purgeable — but "reproducible" only holds when nothing is using them: wiping them mid-flight kills the inputs a queued render is about to read, deletes checkpoints out from under a live trainer, or loses the handle on a running update. Each of those three now carries a liveness probe wired to state PortOS already tracks (the image sweep's own active-job predicate, the training queue, and the same detached-process check the updater uses to refuse a second update). While a job is in flight the row swaps the Purge button for the reason it is withheld, and the endpoint refuses the whole-directory wipe with a 409 rather than trusting the UI to have hidden the button. A probe that cannot answer counts as busy — the delete is irreversible, so "could not verify" must not read as "nothing is running". Per-entry deletes and every category without a probe are untouched.+- **[issue-3342] Purging scratch no longer pulls the rug out from under a job that is still running.** Image Cleaner scratch, LoRA training runs and the self-update control files are all genuinely reproducible — which is why they stay purgeable — but "reproducible" only holds when nothing is using them: wiping them mid-flight kills the inputs a queued render is about to read, deletes checkpoints out from under a live trainer, or loses the handle on a running update. Each of those three now carries a liveness probe wired to state PortOS already tracks (the image sweep's own active-job predicate, the training queue *plus* each run's detached-process handle so a trainer that outlived a restart still counts, and the same detached-process check the updater uses to refuse a second update). While a job is in flight the row swaps the Purge button for the reason it is withheld, and the endpoint refuses the whole-directory wipe with a 409 rather than trusting the UI to have hidden the button. A probe that cannot answer counts as busy — the delete is irreversible, so "could not verify" must not read as "nothing is running". Per-entry deletes and every category without a probe are untouched.## Appsdiff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsxindex 616420d937..4cb1f81e1d 100644--- a/client/src/pages/DataManager.jsx+++ b/client/src/pages/DataManager.jsx@@ -142,10 +142,13 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu// Some reproducible-scratch categories hold the working state of a job that is// running right now — the server refuses the whole-directory purge while that// is true (409 CATEGORY_BUSY). Say why in place of the button so the page- // explains itself instead of failing on click (#3342). Older servers omit- // `busy`; only an explicit true withholds the button.- const busy = cat.busy === true;- const busyReason = cat.busyReason || 'A job is using this directory right now — purge once it finishes.';+ // explains itself instead of failing on click (#3342). The detail fetch runs+ // the same probe on expand, so prefer it: a job that started after the+ // overview loaded would otherwise still be offered a Purge button. Older+ // servers omit `busy` from both — only an explicit true withholds the button.+ const busy = (detail?.busy ?? cat.busy) === true;+ const busyReason = detail?.busyReason || cat.busyReason+ || 'A job is using this directory right now — purge once it finishes.';const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();return (<div className="border border-port-border rounded-lg overflow-hidden">diff --git a/client/src/pages/DataManager.test.jsx b/client/src/pages/DataManager.test.jsxindex 8d061eac31..95752ed48b 100644--- a/client/src/pages/DataManager.test.jsx+++ b/client/src/pages/DataManager.test.jsx@@ -179,6 +179,23 @@ describe('DataManager busy categories (#3342)', () => {await waitFor(() => expect(screen.getByRole('button', { name: /Purge/ })).toBeInTheDocument());});+ // The detail fetch re-runs the probe on expand, so a job that started after+ // the overview loaded must still take the button away before the click.+ it('prefers the fresher busy state from the category detail', async () => {+ getDataOverview.mockResolvedValue({+ ...busyOverview,+ categories: [{ ...busyOverview.categories[0], busy: false, busyReason: null }],+ });+ getDataCategory.mockResolvedValue({ key: 'training-runs', items: [], busy: true, busyReason: BUSY_REASON });++ render(<DataManager />);+ await waitFor(() => expect(screen.getAllByText('LoRA Training Runs').length).toBeGreaterThan(0));++ expandRow('LoRA Training Runs');+ await waitFor(() => expect(screen.getByText(BUSY_REASON)).toBeInTheDocument());+ expect(screen.queryByRole('button', { name: /Purge/ })).not.toBeInTheDocument();+ });+// Older servers omit `busy` entirely — treating anything but an explicit true// as busy would strip the button from every category on an older peer.it('treats a missing busy flag as idle', async () => {diff --git a/server/services/dataManagerBusy.js b/server/services/dataManagerBusy.jsindex 9f8fb08d81..cac75f568f 100644--- a/server/services/dataManagerBusy.js+++ b/server/services/dataManagerBusy.js@@ -16,9 +16,16 @@* both the 409 `CATEGORY_BUSY` body and the text the Data Manager row shows in* place of the Purge button, so it must name what is running and imply when to* retry. Every probe takes its state as an optional argument so it is testable- * without standing up the real queue or a real detached process.+ * without standing up the real queue, a real detached process, or the real+ * `data/` tree.+ *+ * Directories are joined off `PATHS.data` inside each probe (the category key+ * IS the directory name) rather than read from the `PATHS.imageCleanTmp` /+ * `PATHS.trainingRuns` aliases — those are captured at module load, so a test+ * that redirects the data root would not be honored by them.*/+import { readdir } from 'fs/promises';import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';import { isDetachedRunning } from '../lib/detachedSpawn.js';@@ -31,50 +38,78 @@ const IDLE = { busy: false, reason: null };// canceled) has no claim on anything under `data/`.const IN_FLIGHT_STATUSES = new Set(['queued', 'running']);+const listDirNames = (dir) => readdir(dir, { withFileTypes: true }).catch(() => []);+/**- * `data/image-clean-tmp` — delegates to the SAME predicate the hourly GC sweep- * uses to spare an active job's files (`collectActiveCleanBasenames`), so a- * one-click purge can never be more permissive than the automatic sweep that- * deliberately leaves those files alone.+ * `data/image-clean-tmp` — the pinned set comes from the SAME predicate the+ * hourly GC sweep uses to spare an active job's files+ * (`collectActiveCleanBasenames`), so a one-click purge can never be more+ * permissive than the automatic sweep that deliberately leaves them alone.+ *+ * That predicate is intentionally broad: it pins `<jobId>-{mask,original}.png`+ * and friends for EVERY in-flight image job, because a job's clean side files+ * are keyed by job id. Left at that, an unrelated gallery render would report+ * the scratch dir busy. So the pinned names are intersected with what is+ * actually in the directory — the purge is only refused when a live job's file+ * is really sitting there to be destroyed.*- * @param {{ jobs?: Array }} [state] - injected job list; defaults to the live queue+ * @param {{ jobs?: Array, entries?: string[] }} [state] - injected job list / directory listing* @returns {Promise<{ busy: boolean, reason: string|null }>}*/-export async function imageCleanTmpBusy({ jobs = null } = {}) {+export async function imageCleanTmpBusy({ jobs = null, entries = null } = {}) {const pinned = collectActiveCleanBasenames(jobs || listJobs({ kind: 'image' }));if (pinned.size === 0) return IDLE;+ const present = entries+ || (await listDirNames(join(PATHS.data, 'image-clean-tmp'))).filter(e => e.isFile()).map(e => e.name);+ const atRisk = present.filter(name => pinned.has(name));+ if (atRisk.length === 0) return IDLE;return {busy: true,- reason: `An image job is queued or running and ${pinned.size} working file(s) here belong to it — purge once it finishes.`+ reason: `An image job is queued or running and ${atRisk.length} working file(s) here belong to it — purge once it finishes.`};}/**- * `data/training-runs` — LoRA training is routed through the media queue's GPU- * lane as `kind: 'training'`, which is the live registry of in-flight runs: the- * boot reconcile in `loraTraining/index.js` and the cancel path both key on it,- * and unlike the Postgres run record it costs no DB round-trip on the- * `GET /api/data` overview.+ * `data/training-runs`. Two sources, because neither alone covers a restart:*- * @param {{ jobs?: Array }} [state] - injected job list; defaults to the live queue+ * 1. The media queue's GPU lane, where training runs as `kind: 'training'` —+ * the live registry the cancel path and the boot reconcile both key on,+ * and cheaper than a Postgres round-trip on every `GET /api/data`.+ * 2. Each run's `.detached` control dir. A trainer is a detached child that+ * SURVIVES a pm2 restart, so between accepting requests and+ * `initLoraTraining()` finishing its reconcile there is a window where a+ * live trainer has no queue job. Asking the control dir answers "is a+ * process writing here right now" independent of any in-memory state.+ *+ * @param {{ jobs?: Array, runsDir?: string }} [state] - injected job list / runs root* @returns {Promise<{ busy: boolean, reason: string|null }>}*/-export async function trainingRunsBusy({ jobs = null } = {}) {+export async function trainingRunsBusy({ jobs = null, runsDir = null } = {}) {const all = jobs || listJobs({ kind: 'training' });const active = (Array.isArray(all) ? all : []).filter((job) => IN_FLIGHT_STATUSES.has(job?.status));- if (active.length === 0) return IDLE;+ if (active.length > 0) {+ return {+ busy: true,+ reason: `${active.length} LoRA training run(s) queued or running — purging now would delete checkpoints out from under a live trainer. Purge once training finishes.`+ };+ }++ const dir = runsDir || join(PATHS.data, 'training-runs');+ const runs = (await listDirNames(dir)).filter(e => e.isDirectory()).map(e => e.name);+ const surviving = await Promise.all(+ runs.map(name => isDetachedRunning(join(dir, name, '.detached')).catch(() => false))+ );+ if (!surviving.some(Boolean)) return IDLE;return {busy: true,- reason: `${active.length} LoRA training run(s) queued or running — purging now would delete checkpoints out from under a live trainer. Purge once training finishes.`+ reason: 'A LoRA trainer that outlived a restart is still writing here — purge once it finishes or is cancelled.'};}/*** `data/update-detached` — the same `isDetachedRunning` probe `updateExecutor.js`* uses to refuse a second concurrent update. The directory name is duplicated- * from that module's `controlDir`; keep the two in step. It is joined off- * `PATHS.data` inside the function (not hoisted to a module constant) so a test- * that redirects the data root is honored.+ * from that module's `controlDir`; keep the two in step.** @param {{ controlDir?: string }} [state] - injected control dir; defaults to the real one* @returns {Promise<{ busy: boolean, reason: string|null }>}diff --git a/server/services/dataManagerBusy.test.js b/server/services/dataManagerBusy.test.jsindex 6f332f61d4..c693580379 100644--- a/server/services/dataManagerBusy.test.js+++ b/server/services/dataManagerBusy.test.js@@ -25,61 +25,105 @@ const imageJob = (overrides = {}) => ({const trainingJob = (overrides = {}) => ({ id: 'job-0002', kind: 'training', status: 'running', ...overrides });+const INIT_NAME = 'init-00000000-0000-4000-8000-000000000000.png';+describe('imageCleanTmpBusy', () => {it('is idle when no image job is in flight', async () => {- await expect(imageCleanTmpBusy({ jobs: [] })).resolves.toEqual({ busy: false, reason: null });+ await expect(imageCleanTmpBusy({ jobs: [], entries: [INIT_NAME] })).resolves.toEqual({ busy: false, reason: null });});it('is idle when every image job has reached a terminal state', async () => {const jobs = [imageJob({ status: 'completed' }), imageJob({ id: 'job-0003', status: 'failed' })];- await expect(imageCleanTmpBusy({ jobs })).resolves.toEqual({ busy: false, reason: null });+ await expect(imageCleanTmpBusy({ jobs, entries: [INIT_NAME] })).resolves.toEqual({ busy: false, reason: null });});it('reports busy for a queued job whose init image has not been read yet', async () => {- const { busy, reason } = await imageCleanTmpBusy({ jobs: [imageJob({ status: 'queued' })] });+ const { busy, reason } = await imageCleanTmpBusy({ jobs: [imageJob({ status: 'queued' })], entries: [INIT_NAME] });expect(busy).toBe(true);expect(reason).toMatch(/queued or running/);});// The purge must never be more permissive than the GC sweep, which spares// exactly the basenames `collectActiveCleanBasenames` pins.- it('reports busy for a running job even with no initImagePath — its side files are still pinned', async () => {- const { busy } = await imageCleanTmpBusy({ jobs: [imageJob({ params: {} })] });+ it('reports busy on a pinned side file even when the job names no initImagePath', async () => {+ const { busy } = await imageCleanTmpBusy({ jobs: [imageJob({ params: {} })], entries: ['job-0001-mask.png'] });expect(busy).toBe(true);});+ // The pinned set covers every in-flight image job because clean side files are+ // keyed by job id — an unrelated gallery render must not lock the directory.+ it('is idle when nothing an in-flight job pins is actually in the directory', async () => {+ const { busy } = await imageCleanTmpBusy({+ jobs: [imageJob({ id: 'gallery-render', params: {} })],+ entries: ['init-11111111-1111-4111-8111-111111111111.png', 'stale-0002.png'],+ });+ expect(busy).toBe(false);+ });++ it('is idle when the directory is empty', async () => {+ await expect(imageCleanTmpBusy({ jobs: [imageJob()], entries: [] })).resolves.toEqual({ busy: false, reason: null });+ });+it('ignores jobs of other kinds', async () => {- await expect(imageCleanTmpBusy({ jobs: [trainingJob()] })).resolves.toEqual({ busy: false, reason: null });+ await expect(imageCleanTmpBusy({ jobs: [trainingJob()], entries: [INIT_NAME] })).resolves.toEqual({ busy: false, reason: null });});});+const controlDir = (...segments) => {+ const dir = join(TEST_ROOT, ...segments);+ mkdirSync(dir, { recursive: true });+ return dir;+};+describe('trainingRunsBusy', () => {+ const emptyRunsDir = () => controlDir('runs-empty');+it('is idle when no training job is in flight', async () => {- await expect(trainingRunsBusy({ jobs: [] })).resolves.toEqual({ busy: false, reason: null });+ await expect(trainingRunsBusy({ jobs: [], runsDir: emptyRunsDir() })).resolves.toEqual({ busy: false, reason: null });});it('is idle once every run has finished', async () => {const jobs = [trainingJob({ status: 'completed' }), trainingJob({ id: 'job-0004', status: 'canceled' })];- await expect(trainingRunsBusy({ jobs })).resolves.toEqual({ busy: false, reason: null });+ await expect(trainingRunsBusy({ jobs, runsDir: emptyRunsDir() })).resolves.toEqual({ busy: false, reason: null });});it.each(['queued', 'running'])('reports busy for a %s run and counts it', async (status) => {- const { busy, reason } = await trainingRunsBusy({ jobs: [trainingJob({ status })] });+ const { busy, reason } = await trainingRunsBusy({ jobs: [trainingJob({ status })], runsDir: emptyRunsDir() });expect(busy).toBe(true);expect(reason).toMatch(/^1 LoRA training run/);});it('survives a non-array job list instead of throwing into the fail-closed path', async () => {- await expect(trainingRunsBusy({ jobs: null })).resolves.toBeTruthy();+ await expect(trainingRunsBusy({ jobs: null, runsDir: emptyRunsDir() })).resolves.toBeTruthy();+ });++ it('is idle when a runs directory holds only finished runs', async () => {+ const runsDir = controlDir('runs-finished');+ const detached = controlDir('runs-finished', 'run-0001', '.detached');+ writeFileSync(join(detached, 'pid'), String(process.pid));+ writeFileSync(join(detached, 'exit'), '0');+ await expect(trainingRunsBusy({ jobs: [], runsDir })).resolves.toEqual({ busy: false, reason: null });+ });++ // A trainer is a detached child that outlives a pm2 restart, so between+ // accepting requests and the boot reconcile it has no queue job at all.+ it('reports busy for a trainer that outlived a restart and has no queue job', async () => {+ const runsDir = controlDir('runs-surviving');+ controlDir('runs-surviving', 'run-0001');+ const detached = controlDir('runs-surviving', 'run-0002', '.detached');+ writeFileSync(join(detached, 'pid'), String(process.pid));+ const { busy, reason } = await trainingRunsBusy({ jobs: [], runsDir });+ expect(busy).toBe(true);+ expect(reason).toMatch(/outlived a restart/);+ });++ it('is idle when the runs directory does not exist at all', async () => {+ await expect(trainingRunsBusy({ jobs: [], runsDir: join(TEST_ROOT, 'runs-missing') }))+ .resolves.toEqual({ busy: false, reason: null });});});describe('updateDetachedBusy', () => {- const controlDir = (name) => {- const dir = join(TEST_ROOT, name);- mkdirSync(dir, { recursive: true });- return dir;- };it('is idle when there is no control dir at all', async () => {await expect(updateDetachedBusy({ controlDir: join(TEST_ROOT, 'never-created') }))