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: refuse a Data Manager category purge while a job is still using the directory (#3342)

[._.]/ Adam Eivy728fd5ceebb7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fc99a07ad4..eaea9b3b0f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -121,6 +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.
## Apps
diff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsx
index 62197a8bcb..616420d937 100644
--- a/client/src/pages/DataManager.jsx
+++ b/client/src/pages/DataManager.jsx
@@ -139,6 +139,13 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
// legacy category-wide behavior rather than silently dropping the button.
const itemScoped = cat.deletable && cat.purgeScope === 'items';
const categoryPurgeable = cat.deletable && !itemScoped;
+ // 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.';
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
return (
<div className="border border-port-border rounded-lg overflow-hidden">
@@ -165,7 +172,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
{expanded && (
<div className="border-t border-port-border bg-port-bg/50">
{/* Actions */}
- {confirmingPurge ? (
+ {confirmingPurge && !busy ? (
<InlineConfirmRow
variant="separator"
question={`Purge all ${cat.fileCount.toLocaleString()} files (${formatBytes(cat.size)}) in ${cat.label}? This permanently deletes the data and cannot be undone.`}
@@ -187,7 +194,9 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
{archiving ? 'Archiving...' : 'Archive'}
</button>
)}
- {categoryPurgeable && (
+ {categoryPurgeable && (busy ? (
+ <span className="text-xs text-port-warning">{busyReason}</span>
+ ) : (
<button
onClick={() => onPurge(cat.key)}
disabled={purging}
@@ -196,7 +205,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
<Trash2 size={12} />
{purging ? 'Purging...' : 'Purge'}
</button>
- )}
+ ))}
{itemScoped && (
<span className="text-xs text-gray-500">
These files are the only copy, so there is no whole-category purge — delete individual entries from the list below.
diff --git a/client/src/pages/DataManager.test.jsx b/client/src/pages/DataManager.test.jsx
index 0d7c617c20..8d061eac31 100644
--- a/client/src/pages/DataManager.test.jsx
+++ b/client/src/pages/DataManager.test.jsx
@@ -139,3 +139,57 @@ describe('DataManager per-item purge (#3327)', () => {
await waitFor(() => expect(screen.getByRole('button', { name: /Purge/ })).toBeInTheDocument());
});
});
+
+// A reproducible-scratch category whose files a running job still needs: the
+// server refuses the whole-directory purge, and the row says why instead of
+// offering a button that fails on click (#3342).
+const BUSY_REASON = '1 LoRA training run(s) queued or running — purging now would delete checkpoints out from under a live trainer.';
+
+const busyOverview = {
+ totalSize: 3000,
+ dataDir: 'data',
+ categories: [
+ { key: 'training-runs', path: 'data/training-runs', label: 'LoRA Training Runs', description: 'Training checkpoints', archivable: false, deletable: true, purgeScope: 'category', classified: true, busy: true, busyReason: BUSY_REASON, size: 2000, fileCount: 9 },
+ { key: 'messages', path: 'data/messages', label: 'Messages', description: 'Email and messaging data', archivable: true, deletable: true, purgeScope: 'category', classified: true, busy: false, busyReason: null, size: 1000, fileCount: 5 },
+ ],
+};
+
+describe('DataManager busy categories (#3342)', () => {
+ beforeEach(() => {
+ getDataOverview.mockReset().mockResolvedValue(busyOverview);
+ getDataCategory.mockReset().mockResolvedValue({ key: 'training-runs', items: [] });
+ purgeDataCategory.mockReset();
+ });
+
+ it('replaces the Purge button with the server reason while the category is busy', async () => {
+ 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();
+ expect(purgeDataCategory).not.toHaveBeenCalled();
+ });
+
+ it('keeps the Purge button for an idle category in the same list', async () => {
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getByText('Messages')).toBeInTheDocument());
+
+ expandRow('Messages');
+ await waitFor(() => expect(screen.getByRole('button', { name: /Purge/ })).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 () => {
+ getDataOverview.mockResolvedValue({
+ ...busyOverview,
+ categories: [{ ...busyOverview.categories[0], busy: undefined, busyReason: undefined }],
+ });
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getAllByText('LoRA Training Runs').length).toBeGreaterThan(0));
+
+ expandRow('LoRA Training Runs');
+ await waitFor(() => expect(screen.getByRole('button', { name: /Purge/ })).toBeInTheDocument());
+ });
+});
diff --git a/server/routes/dataManager.test.js b/server/routes/dataManager.test.js
index 3702cdd837..c3e9ba5c43 100644
--- a/server/routes/dataManager.test.js
+++ b/server/routes/dataManager.test.js
@@ -68,4 +68,16 @@ describe('DELETE /api/data/:category', () => {
expect(res.status).toBe(400);
expect(res.body.error?.code ?? res.body.code).toBe('CATEGORY_ITEM_PURGE_ONLY');
});
+
+ // The disabled button is a hint; this is the backstop. The reason has to reach
+ // the client verbatim — it is the only thing that tells the user what to wait
+ // for (#3342).
+ it('surfaces a busy-category refusal as 409 with the reason intact', async () => {
+ const reason = '1 LoRA training run(s) queued or running — purge once training finishes.';
+ purgeCategory.mockRejectedValue(new ServerError(reason, { status: 409, code: 'CATEGORY_BUSY' }));
+ const res = await request(makeApp()).delete('/api/data/training-runs').send({});
+ expect(res.status).toBe(409);
+ expect(res.body.error?.code ?? res.body.code).toBe('CATEGORY_BUSY');
+ expect(JSON.stringify(res.body)).toContain(reason);
+ });
});
diff --git a/server/services/dataManager.busy.test.js b/server/services/dataManager.busy.test.js
new file mode 100644
index 0000000000..dcaedad8e9
--- /dev/null
+++ b/server/services/dataManager.busy.test.js
@@ -0,0 +1,132 @@
+/**
+ * The CATEGORY_BUSY gate on a whole-directory purge (issue #3342).
+ *
+ * Everything here runs against a throwaway temp root — `PATHS.data` is
+ * redirected before `dataManager.js` captures it, so no case can reach the
+ * install's real `data/`. The busy probes themselves are stubbed: this suite
+ * covers the gate, not the probes (`dataManagerBusy.test.js` covers those).
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'datamanager-busy-gate-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: TEST_DATA_ROOT });
+});
+
+const idle = () => Promise.resolve({ busy: false, reason: null });
+
+vi.mock('./dataManagerBusy.js', () => ({
+ imageCleanTmpBusy: vi.fn(idle),
+ trainingRunsBusy: vi.fn(idle),
+ updateDetachedBusy: vi.fn(idle),
+}));
+
+const { imageCleanTmpBusy, trainingRunsBusy, updateDetachedBusy } = await import('./dataManagerBusy.js');
+const { purgeCategory, getDataOverview, getCategoryDetail, CATEGORIES } = await import('./dataManager.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+const dataPath = (...parts) => join(TEST_DATA_ROOT, ...parts);
+
+const seed = (category, file = 'work.tmp') => {
+ mkdirSync(dataPath(category), { recursive: true });
+ writeFileSync(dataPath(category, file), 'x');
+};
+
+beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ seed('image-clean-tmp', 'init-0000.png');
+ seed('training-runs', 'run-0001');
+ seed('update-detached', 'pid');
+ seed('messages', 'index.json');
+ imageCleanTmpBusy.mockReset().mockImplementation(idle);
+ trainingRunsBusy.mockReset().mockImplementation(idle);
+ updateDetachedBusy.mockReset().mockImplementation(idle);
+});
+
+const busyWith = (reason) => () => Promise.resolve({ busy: true, reason });
+
+describe('purgeCategory — CATEGORY_BUSY refusal', () => {
+ const cases = [
+ ['image-clean-tmp', () => imageCleanTmpBusy, 'init-0000.png', 'an image render is in flight'],
+ ['training-runs', () => trainingRunsBusy, 'run-0001', 'a trainer is running'],
+ ['update-detached', () => updateDetachedBusy, 'pid', 'an update is running'],
+ ];
+
+ it.each(cases)('refuses the whole-category purge for %s while its probe reports busy', async (key, probe, file, reason) => {
+ probe().mockImplementation(busyWith(reason));
+ await expect(purgeCategory(key)).rejects.toMatchObject({ status: 409, code: 'CATEGORY_BUSY', message: reason });
+ expect(existsSync(dataPath(key, file))).toBe(true);
+ });
+
+ it.each(cases)('purges %s normally once its probe goes idle', async (key, _probe, file) => {
+ const result = await purgeCategory(key);
+ expect(result).toEqual({ category: key, subPath: null });
+ expect(existsSync(dataPath(key, file))).toBe(false);
+ expect(existsSync(dataPath(key))).toBe(true);
+ });
+
+ // A per-item purge names the one entry the user picked, so it stays available
+ // while the category is busy — the refusal is about the all-at-once wipe.
+ it('still allows a per-item purge while the category is busy', async () => {
+ trainingRunsBusy.mockImplementation(busyWith('a trainer is running'));
+ await purgeCategory('training-runs', { subPath: 'run-0001' });
+ expect(existsSync(dataPath('training-runs', 'run-0001'))).toBe(false);
+ expect(trainingRunsBusy).not.toHaveBeenCalled();
+ });
+
+ it('leaves a category with no busyCheck completely unaffected', async () => {
+ expect(CATEGORIES.messages.busyCheck).toBeUndefined();
+ await purgeCategory('messages');
+ expect(existsSync(dataPath('messages', 'index.json'))).toBe(false);
+ });
+
+ // "Could not verify" and "nothing is running" must not collapse into the same
+ // answer — the purge is irreversible.
+ it('fails closed when the probe throws', async () => {
+ trainingRunsBusy.mockImplementation(() => Promise.reject(new Error('queue unavailable')));
+ await expect(purgeCategory('training-runs')).rejects.toMatchObject({ status: 409, code: 'CATEGORY_BUSY' });
+ expect(existsSync(dataPath('training-runs', 'run-0001'))).toBe(true);
+ });
+
+ it('fails closed when the probe returns a shape it cannot read', async () => {
+ trainingRunsBusy.mockImplementation(() => Promise.resolve({ reason: 'no busy flag' }));
+ await expect(purgeCategory('training-runs')).rejects.toMatchObject({ code: 'CATEGORY_BUSY' });
+ expect(existsSync(dataPath('training-runs', 'run-0001'))).toBe(true);
+ });
+
+ it('supplies a fallback reason when a busy probe names none', async () => {
+ trainingRunsBusy.mockImplementation(() => Promise.resolve({ busy: true }));
+ await expect(purgeCategory('training-runs')).rejects.toThrow(/Something is using data\/training-runs/);
+ });
+});
+
+describe('busy state on the read paths', () => {
+ it('ships busy + busyReason on the overview so the button can go before the click', async () => {
+ trainingRunsBusy.mockImplementation(busyWith('2 LoRA training run(s) queued or running'));
+ const { categories } = await getDataOverview();
+ const training = categories.find(c => c.key === 'training-runs');
+ expect(training).toMatchObject({ busy: true, busyReason: '2 LoRA training run(s) queued or running' });
+ expect(categories.find(c => c.key === 'messages')).toMatchObject({ busy: false, busyReason: null });
+ });
+
+ it('never leaks the busyCheck function into the payload', async () => {
+ const { categories } = await getDataOverview();
+ expect(categories.every(c => !('busyCheck' in c))).toBe(true);
+ const detail = await getCategoryDetail('training-runs');
+ expect('busyCheck' in detail).toBe(false);
+ });
+
+ it('reports the same busy state on the category detail', async () => {
+ updateDetachedBusy.mockImplementation(busyWith('a self-update is running'));
+ const detail = await getCategoryDetail('update-detached');
+ expect(detail).toMatchObject({ busy: true, busyReason: 'a self-update is running' });
+ });
+});
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 3d1f974e4b..81f1511a13 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -5,6 +5,7 @@ import { execFile } from 'child_process';
import { promisify } from 'util';
import { PATHS, ensureDir, isTopLevelEntryName } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
+import { imageCleanTmpBusy, trainingRunsBusy, updateDetachedBusy } from './dataManagerBusy.js';
const execFileAsync = promisify(execFile);
const DATA_DIR = PATHS.data;
@@ -33,6 +34,14 @@ const DATA_DIR = PATHS.data;
// `purgeCategory` fails closed: anything other than an explicit 'category'
// refuses the directory-wide purge, so a missing or misspelled scope can
// never widen a delete.
+// busyCheck — optional `() => Promise<{ busy, reason }>`. Some directories are
+// genuinely reproducible scratch, yet only while nothing is USING them: a
+// category-wide purge mid-job destroys the working state of a render, a
+// trainer, or a self-update. A category carrying a `busyCheck` refuses the
+// directory-wide purge with 409 CATEGORY_BUSY while its probe says busy;
+// per-item purges (the user named one entry) and categories with no
+// `busyCheck` are unaffected (issue #3342). Probes live in
+// `dataManagerBusy.js`.
export const CATEGORIES = {
'agents': { label: 'Agents', description: 'Agent personality data', archivable: false, deletable: false },
'ask-conversations': { label: 'Ask Conversations', description: 'Saved Ask chat transcripts', archivable: true, deletable: false },
@@ -56,7 +65,7 @@ export const CATEGORIES = {
'digital-twin': { label: 'Digital Twin', description: 'Identity, goals, character data', archivable: true, deletable: false },
'games': { label: 'Games', description: 'Game project records and assets', archivable: true, deletable: false },
'health': { label: 'Apple Health', description: 'Daily health JSON snapshots', archivable: true, deletable: false },
- 'image-clean-tmp': { label: 'Image Cleaner Scratch', description: 'Ephemeral working files for Image Cleaner renders — swept automatically, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
+ 'image-clean-tmp': { label: 'Image Cleaner Scratch', description: 'Ephemeral working files for Image Cleaner renders — swept automatically, safe to purge when no render is in flight', archivable: false, deletable: true, purgeScope: 'category', busyCheck: imageCleanTmpBusy },
'image-refs': { label: 'Image References', description: 'Reference images uploaded for multi-reference edits — still served to existing renders', archivable: true, deletable: false },
'image-to-3d': { label: 'Image to 3D', description: 'Generated GLB meshes — the only copy; records live in Postgres', archivable: false, deletable: false },
'images': { label: 'Images', description: 'Uploaded and generated images — delete individually; gallery, pipeline, and collection records point at these files', archivable: true, deletable: true, purgeScope: 'items' },
@@ -97,9 +106,9 @@ export const CATEGORIES = {
'telegram': { label: 'Telegram', description: 'Telegram bot data', archivable: true, deletable: true, purgeScope: 'category' },
'templates': { label: 'Visual Templates', description: 'Shipped layout assets used as render anchors', archivable: false, deletable: false },
'tools': { label: 'Tools', description: 'Tool execution data', archivable: true, deletable: true, purgeScope: 'category' },
- 'training-runs': { label: 'LoRA Training Runs', description: 'Training checkpoints, caches, and sample previews — the finished adapters live in LoRAs and survive a purge; run history in Postgres will point at missing artifacts', archivable: false, deletable: true, purgeScope: 'category' },
+ 'training-runs': { label: 'LoRA Training Runs', description: 'Training checkpoints, caches, and sample previews — the finished adapters live in LoRAs and survive a purge; run history in Postgres will point at missing artifacts', archivable: false, deletable: true, purgeScope: 'category', busyCheck: trainingRunsBusy },
'universes': { label: 'Universes', description: 'Universe Builder records — bibles, canon, and style references', archivable: true, deletable: false },
- 'update-detached': { label: 'Update Control', description: 'Control files for a detached self-update run — safe to purge when no update is running', archivable: false, deletable: true, purgeScope: 'category' },
+ 'update-detached': { label: 'Update Control', description: 'Control files for a detached self-update run — safe to purge when no update is running', archivable: false, deletable: true, purgeScope: 'category', busyCheck: updateDetachedBusy },
'uploads': { label: 'Uploads', description: 'Files uploaded through the UI and referenced by records', archivable: true, deletable: false },
'video-thumbnails': { label: 'Video Thumbnails', description: 'JPEG thumbnails for generated videos', archivable: false, deletable: true, purgeScope: 'category' },
'videos': { label: 'Videos', description: 'Locally generated videos — delete individually; the render is the only copy and re-rendering costs provider spend', archivable: true, deletable: true, purgeScope: 'items' },
@@ -119,13 +128,40 @@ export const UNKNOWN_CATEGORY_DESCRIPTION = "Not classified — PortOS doesn't k
* the row as "deliberately unactionable" instead of guessing from the copy.
* `purgeScope` is always present in the payload (null on protected categories)
* so the client never has to distinguish "absent" from "not purgeable".
+ * `busyCheck` is stripped — it is server-side behavior, not payload.
*/
function categoryMeta(name) {
const known = CATEGORIES[name];
- if (known) return { purgeScope: null, ...known, classified: true };
+ if (known) {
+ const { busyCheck: _busyCheck, ...serializable } = known;
+ return { purgeScope: null, ...serializable, classified: true };
+ }
return { label: name, description: UNKNOWN_CATEGORY_DESCRIPTION, archivable: false, deletable: false, purgeScope: null, classified: false };
}
+/**
+ * Run a category's `busyCheck`, if it has one, and shape the answer for both
+ * the API payload (`busy` / `busyReason`) and the purge gate (issue #3342).
+ * A category with no probe is always `{ busy: false }` — today's behavior.
+ *
+ * Fails CLOSED. A probe that throws, or hands back a shape we can't read,
+ * reports busy: "we could not verify" and "nothing is running" must not
+ * collapse into the same answer on a page whose buttons are irreversible.
+ */
+export async function resolveCategoryBusy(categoryKey) {
+ const check = CATEGORIES[categoryKey]?.busyCheck;
+ if (typeof check !== 'function') return { busy: false, busyReason: null };
+ const result = await check().catch((err) => {
+ console.error(`❌ Busy check failed for data/${categoryKey}: ${err.message}`);
+ return null;
+ });
+ if (typeof result?.busy !== 'boolean') {
+ return { busy: true, busyReason: `PortOS could not confirm whether anything is using data/${categoryKey} right now, so the purge is withheld.` };
+ }
+ if (!result.busy) return { busy: false, busyReason: null };
+ return { busy: true, busyReason: result.reason || `Something is using data/${categoryKey} right now — purge once it finishes.` };
+}
+
// Validate category key contains only safe characters
const SAFE_NAME = /^[a-z0-9_-]+$/;
@@ -154,15 +190,18 @@ export async function getDataOverview() {
...dirs.map(d => getDirSizeAndCount(join(DATA_DIR, d.name)))
]);
- const categories = dirs.map((d, i) => {
- const meta = categoryMeta(d.name);
- return {
- key: d.name,
- path: `data/${d.name}`,
- ...meta,
- ...dirResults[i]
- };
- });
+ // Busy state ships with the overview so the Data Manager can drop the Purge
+ // button before the user commits, rather than failing on click (#3342). Only
+ // the handful of categories carrying a `busyCheck` cost anything here.
+ const busyStates = await Promise.all(dirs.map(d => resolveCategoryBusy(d.name)));
+
+ const categories = dirs.map((d, i) => ({
+ key: d.name,
+ path: `data/${d.name}`,
+ ...categoryMeta(d.name),
+ ...busyStates[i],
+ ...dirResults[i]
+ }));
categories.sort((a, b) => b.size - a.size);
@@ -200,9 +239,9 @@ export async function getCategoryDetail(categoryKey) {
items.sort((a, b) => b.size - a.size);
const totalSize = items.reduce((sum, item) => sum + item.size, 0);
- const meta = categoryMeta(categoryKey);
+ const busy = await resolveCategoryBusy(categoryKey);
- return { key: categoryKey, ...meta, totalSize, items };
+ return { key: categoryKey, ...categoryMeta(categoryKey), ...busy, totalSize, items };
}
export async function archiveCategory(categoryKey, options = {}) {
@@ -293,6 +332,18 @@ export async function purgeCategory(categoryKey, options = {}) {
throw new ServerError(`Category directory not found: ${categoryKey}`, { status: 404, code: 'NOT_FOUND' });
}
+ // A category-wide purge empties the directory in one action, so a job that is
+ // mid-flight loses its working state with no warning. Refuse outright while a
+ // category's `busyCheck` reports live work, rather than filtering "the busy
+ // files" out of the wipe — a partial purge is harder to reason about, and the
+ // user can retry in seconds once the job finishes (#3342). A per-item purge
+ // is exempt: the user named the one entry they meant. This runs before any
+ // `rm` below.
+ if (!wantsItem) {
+ const { busy, busyReason } = await resolveCategoryBusy(categoryKey);
+ if (busy) throw new ServerError(busyReason, { status: 409, code: 'CATEGORY_BUSY' });
+ }
+
if (wantsItem) {
const resolvedRoot = resolve(dirPath);
const resolvedTarget = resolve(join(dirPath, options.subPath));
diff --git a/server/services/dataManagerBusy.js b/server/services/dataManagerBusy.js
new file mode 100644
index 0000000000..9f8fb08d81
--- /dev/null
+++ b/server/services/dataManagerBusy.js
@@ -0,0 +1,90 @@
+/**
+ * Live-work probes for Data Manager category purges (issue #3342).
+ *
+ * A category-wide purge empties the whole directory in one action. Three
+ * categories are correctly classified as reproducible scratch — the bytes do
+ * come back — but only once nothing is USING them:
+ *
+ * image-clean-tmp — the init/mask/original inputs a queued or running Image
+ * Cleaner render is about to read.
+ * training-runs — the checkpoints, caches, and sample previews a LoRA
+ * trainer is writing right now (hours of GPU time).
+ * update-detached — the control files the detached self-update script is
+ * being polled through.
+ *
+ * Each probe resolves `{ busy, reason }`. `reason` is user-facing copy: it is
+ * 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.
+ */
+
+import { join } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
+import { isDetachedRunning } from '../lib/detachedSpawn.js';
+import { listJobs } from './mediaJobQueue/index.js';
+import { collectActiveCleanBasenames } from './imageCleanTmpGc.js';
+
+const IDLE = { busy: false, reason: null };
+
+// Jobs the media queue still owes work to. A terminal job (completed / failed /
+// canceled) has no claim on anything under `data/`.
+const IN_FLIGHT_STATUSES = new Set(['queued', 'running']);
+
+/**
+ * `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.
+ *
+ * @param {{ jobs?: Array }} [state] - injected job list; defaults to the live queue
+ * @returns {Promise<{ busy: boolean, reason: string|null }>}
+ */
+export async function imageCleanTmpBusy({ jobs = null } = {}) {
+ const pinned = collectActiveCleanBasenames(jobs || listJobs({ kind: 'image' }));
+ if (pinned.size === 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.`
+ };
+}
+
+/**
+ * `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.
+ *
+ * @param {{ jobs?: Array }} [state] - injected job list; defaults to the live queue
+ * @returns {Promise<{ busy: boolean, reason: string|null }>}
+ */
+export async function trainingRunsBusy({ jobs = 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;
+ 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.`
+ };
+}
+
+/**
+ * `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.
+ *
+ * @param {{ controlDir?: string }} [state] - injected control dir; defaults to the real one
+ * @returns {Promise<{ busy: boolean, reason: string|null }>}
+ */
+export async function updateDetachedBusy({ controlDir = null } = {}) {
+ const dir = controlDir || join(PATHS.data, 'update-detached');
+ const running = await isDetachedRunning(dir);
+ if (!running) return IDLE;
+ return {
+ busy: true,
+ reason: 'A self-update is running and PortOS polls its control files here — purging now loses the handle on it. Purge once the update finishes.'
+ };
+}
diff --git a/server/services/dataManagerBusy.test.js b/server/services/dataManagerBusy.test.js
new file mode 100644
index 0000000000..6f332f61d4
--- /dev/null
+++ b/server/services/dataManagerBusy.test.js
@@ -0,0 +1,103 @@
+/**
+ * Live-work probes behind the Data Manager's CATEGORY_BUSY refusal (#3342).
+ *
+ * Every case injects its state — a job list, or a control dir under a throwaway
+ * temp root — so nothing here reads the live media-job queue or the install's
+ * real `data/` directory.
+ */
+
+import { describe, it, expect, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { imageCleanTmpBusy, trainingRunsBusy, updateDetachedBusy } from './dataManagerBusy.js';
+
+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'datamanager-busy-test-'));
+afterAll(() => rmSync(TEST_ROOT, { recursive: true, force: true }));
+
+const imageJob = (overrides = {}) => ({
+ id: 'job-0001',
+ kind: 'image',
+ status: 'running',
+ params: { initImagePath: 'image-clean-tmp/init-00000000-0000-4000-8000-000000000000.png' },
+ ...overrides,
+});
+
+const trainingJob = (overrides = {}) => ({ id: 'job-0002', kind: 'training', status: 'running', ...overrides });
+
+describe('imageCleanTmpBusy', () => {
+ it('is idle when no image job is in flight', async () => {
+ await expect(imageCleanTmpBusy({ jobs: [] })).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 });
+ });
+
+ 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' })] });
+ 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: {} })] });
+ expect(busy).toBe(true);
+ });
+
+ it('ignores jobs of other kinds', async () => {
+ await expect(imageCleanTmpBusy({ jobs: [trainingJob()] })).resolves.toEqual({ busy: false, reason: null });
+ });
+});
+
+describe('trainingRunsBusy', () => {
+ it('is idle when no training job is in flight', async () => {
+ await expect(trainingRunsBusy({ jobs: [] })).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 });
+ });
+
+ it.each(['queued', 'running'])('reports busy for a %s run and counts it', async (status) => {
+ const { busy, reason } = await trainingRunsBusy({ jobs: [trainingJob({ status })] });
+ 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();
+ });
+});
+
+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') }))
+ .resolves.toEqual({ busy: false, reason: null });
+ });
+
+ it('is idle once the script has written its exit status', async () => {
+ const dir = controlDir('finished');
+ writeFileSync(join(dir, 'pid'), String(process.pid));
+ writeFileSync(join(dir, 'exit'), '0');
+ await expect(updateDetachedBusy({ controlDir: dir })).resolves.toEqual({ busy: false, reason: null });
+ });
+
+ it('reports busy while a live pid has not exited', async () => {
+ const dir = controlDir('running');
+ writeFileSync(join(dir, 'pid'), String(process.pid));
+ const { busy, reason } = await updateDetachedBusy({ controlDir: dir });
+ expect(busy).toBe(true);
+ expect(reason).toMatch(/self-update is running/);
+ });
+});