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: stop the Data Manager from wiping images, videos, and LoRAs in one purge (#3327)

[._.]/ Adam Eivy26290be362f0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a5202572f8..97d91b281d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -118,6 +118,8 @@
## Data Manager
- **[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.
+
## Apps
- **[issue-3286] Delete is no longer the loudest button on an app row.** Every app card rendered `Archive`, `Manage` and a red-tinted `Delete` as three equal-weight buttons, so the most destructive and rarest action was the highest-contrast control on the page — sixteen permanently-armed Delete buttons stacked down the list, sitting a thumb's width from `Manage` once the row wrapped on a phone. `Archive` and `Delete` now live behind a per-row "…" menu (arrow keys, Escape, and 40px touch targets included), `Manage` is the row's single filled primary, the app name reads as an actual link, and deleting asks for an inline confirmation naming the app before anything is removed.
diff --git a/client/src/pages/DataManager.jsx b/client/src/pages/DataManager.jsx
index 5e8bef6256..e54488a380 100644
--- a/client/src/pages/DataManager.jsx
+++ b/client/src/pages/DataManager.jsx
@@ -127,12 +127,19 @@ function SizeBar({ size, maxSize }) {
);
}
-function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPurge, onConfirmPurge, onCancelPurge, confirmingPurge, archiving, purging }) {
+function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPurge, onConfirmPurge, onCancelPurge, onDeleteItem, deletingItem, confirmingPurge, archiving, purging }) {
// Directories with no CATEGORIES entry come back with `classified: false` and
// no Archive/Purge flags. Say why the buttons are missing in outcome terms so
// the row reads as a deliberate safety stance, not a broken row (#3285).
// Older servers omit `classified`; treat only an explicit false as unknown.
const unclassified = cat.classified === false;
+ // `purgeScope: 'items'` categories hold the only copy of each file, so the
+ // whole-directory Purge button is replaced by a per-row delete in the detail
+ // table (#3327). Older servers omit `purgeScope` entirely — treat that as the
+ // legacy category-wide behavior rather than silently dropping the button.
+ const itemScoped = cat.deletable && cat.purgeScope === 'items';
+ const categoryPurgeable = cat.deletable && !itemScoped;
+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
return (
<div className="border border-port-border rounded-lg overflow-hidden">
<button
@@ -180,7 +187,7 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
{archiving ? 'Archiving...' : 'Archive'}
</button>
)}
- {cat.deletable && (
+ {categoryPurgeable && (
<button
onClick={() => onPurge(cat.key)}
disabled={purging}
@@ -190,6 +197,11 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
{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.
+ </span>
+ )}
{!cat.archivable && !cat.deletable && (
<span className="text-xs text-gray-500">
{unclassified
@@ -206,12 +218,13 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
{detail.items.length === 0 ? (
<div className="p-3 text-xs text-gray-500">Empty</div>
) : (
- <table className="w-full text-xs">
+ <table className={`w-full text-xs ${itemScoped ? 'min-w-[420px]' : ''}`}>
<thead>
<tr className="text-gray-500 border-b border-port-border/30">
<th className="text-left p-2 pl-3 font-medium">Name</th>
<th className="text-right p-2 font-medium">Size</th>
<th className="text-right p-2 pr-3 font-medium">Files</th>
+ {itemScoped && <th className="text-right p-2 pr-3 font-medium"><span className="sr-only">Delete</span></th>}
</tr>
</thead>
<tbody>
@@ -223,6 +236,29 @@ function CategoryRow({ cat, maxSize, onExpand, expanded, detail, onArchive, onPu
</td>
<td className="p-2 text-right text-gray-400 font-mono">{formatBytes(item.size)}</td>
<td className="p-2 pr-3 text-right text-gray-500">{item.type === 'directory' ? item.fileCount?.toLocaleString() : '—'}</td>
+ {itemScoped && (
+ <td className="p-2 pr-3 text-right">
+ {isConfirming(item.name) ? (
+ <ConfirmButtonPair
+ className="justify-end"
+ prompt="Delete?"
+ onConfirm={() => confirmDelete(() => onDeleteItem(cat.key, item.name))}
+ onCancel={cancelDelete}
+ ariaLabel={`Confirm delete ${item.name} from ${cat.label}`}
+ />
+ ) : (
+ <button
+ onClick={() => requestDelete(item.name)}
+ disabled={deletingItem === item.name}
+ className="text-gray-500 hover:text-port-error transition-colors disabled:opacity-50"
+ title={`Delete ${item.name}`}
+ aria-label={`Delete ${item.name} from ${cat.label}`}
+ >
+ <Trash2 size={12} />
+ </button>
+ )}
+ </td>
+ )}
</tr>
))}
</tbody>
@@ -308,6 +344,7 @@ export default function DataManager() {
const [archiving, setArchiving] = useState(null);
const [purging, setPurging] = useState(null);
const [confirmPurge, setConfirmPurge] = useState(null);
+ const [deletingItem, setDeletingItem] = useState(null);
const fetchOverview = useCallback(async () => {
const [data, bk] = await Promise.all([
@@ -353,6 +390,18 @@ export default function DataManager() {
refreshAfterAction(key);
};
+ // Per-item purge for `purgeScope: 'items'` categories — the only delete those
+ // categories offer (#3327). Drops the row locally for immediate feedback and
+ // refetches the overview so the size bars and totals catch up.
+ const handleDeleteItem = async (key, name) => {
+ setDeletingItem(name);
+ const result = await api.purgeDataCategory(key, { subPath: name }).catch(() => null);
+ setDeletingItem(null);
+ if (!result) return;
+ setDetail(prev => (prev?.key === key ? { ...prev, items: prev.items.filter(i => i.name !== name) } : prev));
+ fetchOverview();
+ };
+
const handleDeleteBackup = async (filename) => {
await api.deleteDataBackup(filename).catch(() => null);
setBackups(prev => prev.filter(b => b.name !== filename));
@@ -447,6 +496,8 @@ export default function DataManager() {
onPurge={setConfirmPurge}
onConfirmPurge={executePurge}
onCancelPurge={() => setConfirmPurge(null)}
+ onDeleteItem={handleDeleteItem}
+ deletingItem={expandedCat === cat.key ? deletingItem : null}
confirmingPurge={confirmPurge === cat.key}
archiving={archiving === cat.key}
purging={purging === cat.key}
diff --git a/client/src/pages/DataManager.test.jsx b/client/src/pages/DataManager.test.jsx
index 22aa79c0d2..a6b39f4cce 100644
--- a/client/src/pages/DataManager.test.jsx
+++ b/client/src/pages/DataManager.test.jsx
@@ -7,13 +7,14 @@ import DataManager from './DataManager';
// missing instead of leaving a dead end on the cleanup page (#3285).
const getDataOverview = vi.fn();
const getDataCategory = vi.fn();
+const purgeDataCategory = vi.fn();
vi.mock('../services/api', () => ({
getDataOverview: (...a) => getDataOverview(...a),
getDataBackups: vi.fn(() => Promise.resolve([])),
getDataCategory: (...a) => getDataCategory(...a),
archiveDataCategory: vi.fn(),
- purgeDataCategory: vi.fn(),
+ purgeDataCategory: (...a) => purgeDataCategory(...a),
deleteDataBackup: vi.fn(),
getTombstoneSweepStatus: vi.fn(() => Promise.resolve({ refused: [] })),
sweepTombstonesNow: vi.fn(),
@@ -62,3 +63,63 @@ describe('DataManager unclassified rows (#3285)', () => {
await waitFor(() => expect(screen.getByText(/This category is protected/)).toBeInTheDocument());
});
});
+
+// `purgeScope: 'items'` categories hold the only copy of each file, so the row
+// trades the whole-category Purge button for a per-entry delete (#3327).
+const scopedOverview = {
+ totalSize: 3000,
+ dataDir: 'data',
+ categories: [
+ { key: 'images', path: 'data/images', label: 'Images', description: 'Uploaded and generated images', archivable: true, deletable: true, purgeScope: 'items', classified: true, size: 2000, fileCount: 2 },
+ { key: 'messages', path: 'data/messages', label: 'Messages', description: 'Email and messaging data', archivable: true, deletable: true, purgeScope: 'category', classified: true, size: 1000, fileCount: 5 },
+ { key: 'legacy', path: 'data/legacy', label: 'Legacy', description: 'From a server that predates purgeScope', archivable: false, deletable: true, classified: true, size: 500, fileCount: 1 },
+ ],
+};
+
+describe('DataManager per-item purge (#3327)', () => {
+ beforeEach(() => {
+ getDataOverview.mockReset().mockResolvedValue(scopedOverview);
+ getDataCategory.mockReset().mockResolvedValue({
+ key: 'images',
+ items: [{ name: 'render-0001.png', type: 'file', size: 1200 }],
+ });
+ purgeDataCategory.mockReset().mockResolvedValue({ category: 'images', subPath: 'render-0001.png' });
+ });
+
+ it('hides the whole-category Purge button and explains why', async () => {
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getAllByText('Images').length).toBeGreaterThan(0));
+
+ expandRow('Images');
+ await waitFor(() => expect(screen.getByText(/no whole-category purge/)).toBeInTheDocument());
+ expect(screen.queryByRole('button', { name: 'Purge' })).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Archive/ })).toBeInTheDocument();
+ });
+
+ it('deletes a single entry through the subPath purge', async () => {
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getAllByText('Images').length).toBeGreaterThan(0));
+
+ expandRow('Images');
+ const trash = await screen.findByRole('button', { name: 'Delete render-0001.png from Images' });
+ fireEvent.click(trash);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
+ await waitFor(() => expect(purgeDataCategory).toHaveBeenCalledWith('images', { subPath: 'render-0001.png' }));
+ // Reactive removal — the row leaves the table without a detail refetch.
+ await waitFor(() => expect(screen.queryByText('render-0001.png')).not.toBeInTheDocument());
+ });
+
+ it('keeps the category-wide Purge button for category-scoped and legacy rows', async () => {
+ render(<DataManager />);
+ await waitFor(() => expect(screen.getByText('Messages')).toBeInTheDocument());
+
+ expandRow('Messages');
+ await waitFor(() => expect(screen.getByRole('button', { name: /Purge/ })).toBeInTheDocument());
+
+ // A server that predates purgeScope omits the field — the button must not
+ // vanish for every deletable category on an older peer.
+ expandRow('Legacy');
+ await waitFor(() => expect(screen.getByRole('button', { name: /Purge/ })).toBeInTheDocument());
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f7ab59fa14..b673e7afbd 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -820,6 +820,20 @@ export const portsAllocateSchema = z.object({
)
});
+// =============================================================================
+// DATA MANAGER
+// =============================================================================
+
+// DELETE /api/data/:category — purge a category, or one entry inside it.
+// `subPath` names a single top-level entry of the category directory; omitting
+// it asks for the whole-directory wipe, which `purgeCategory` only honors for
+// `purgeScope: 'category'` entries (#3327). Traversal is still rejected in the
+// service by a path.relative containment check — this schema just refuses the
+// obviously-wrong shapes (non-string, empty, absurdly long) before that.
+export const dataPurgeSchema = z.object({
+ subPath: z.string().min(1).max(1024).optional()
+});
+
// =============================================================================
// DATABASE
// =============================================================================
diff --git a/server/routes/dataManager.js b/server/routes/dataManager.js
index 318d47b018..82c630e0b6 100644
--- a/server/routes/dataManager.js
+++ b/server/routes/dataManager.js
@@ -1,5 +1,6 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest, dataPurgeSchema } from '../lib/validation.js';
import {
getDataOverview,
getCategoryDetail,
@@ -47,9 +48,12 @@ router.delete('/backups/:filename', asyncHandler(async (req, res) => {
res.json(result);
}));
-// DELETE /api/data/:category — purge a category's contents
+// DELETE /api/data/:category — purge a category's contents, or a single entry
+// when `subPath` is given. Categories flagged `purgeScope: 'items'` reject the
+// bodiless (whole-directory) form in `purgeCategory` — hiding the button in the
+// UI is not enough, the endpoint has to refuse it too (#3327).
router.delete('/:category', asyncHandler(async (req, res) => {
- const { subPath } = req.body || {};
+ const { subPath } = validateRequest(dataPurgeSchema, req.body || {});
const result = await purgeCategory(req.params.category, { subPath });
res.json(result);
}));
diff --git a/server/routes/dataManager.test.js b/server/routes/dataManager.test.js
new file mode 100644
index 0000000000..d924dd85e2
--- /dev/null
+++ b/server/routes/dataManager.test.js
@@ -0,0 +1,62 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware, ServerError } from '../lib/errorHandler.js';
+
+// The whole service is stubbed — nothing in this suite may reach the real
+// `data/` directory, which holds the user's only copy of these files (#3327).
+vi.mock('../services/dataManager.js', () => ({
+ getDataOverview: vi.fn(),
+ getCategoryDetail: vi.fn(),
+ archiveCategory: vi.fn(),
+ purgeCategory: vi.fn(),
+ getBackups: vi.fn(),
+ deleteBackup: vi.fn(),
+}));
+
+const { purgeCategory } = await import('../services/dataManager.js');
+const { default: dataRoutes } = await import('./dataManager.js');
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/data', dataRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+describe('DELETE /api/data/:category', () => {
+ beforeEach(() => {
+ purgeCategory.mockReset().mockResolvedValue({ category: 'images', subPath: null });
+ });
+
+ it('forwards a per-item purge target to the service', async () => {
+ const res = await request(makeApp()).delete('/api/data/images').send({ subPath: 'render-0001.png' });
+ expect(res.status).toBe(200);
+ expect(purgeCategory).toHaveBeenCalledWith('images', { subPath: 'render-0001.png' });
+ });
+
+ it('treats a bodiless request as a whole-category purge', async () => {
+ const res = await request(makeApp()).delete('/api/data/messages').send({});
+ expect(res.status).toBe(200);
+ expect(purgeCategory).toHaveBeenCalledWith('messages', { subPath: undefined });
+ });
+
+ it('rejects a malformed subPath before the service is reached', async () => {
+ const res = await request(makeApp()).delete('/api/data/images').send({ subPath: 42 });
+ expect(res.status).toBe(400);
+ expect(purgeCategory).not.toHaveBeenCalled();
+ });
+
+ // The endpoint stays reachable even when the UI hides the button, so the
+ // service's refusal has to surface as a 4xx rather than an opaque 500.
+ it('surfaces the service refusal of a category-wide purge on an item-scoped category', async () => {
+ purgeCategory.mockRejectedValue(new ServerError('Category "images" only supports per-item purge — pass a subPath', {
+ status: 400,
+ code: 'CATEGORY_ITEM_PURGE_ONLY',
+ }));
+ const res = await request(makeApp()).delete('/api/data/images').send({});
+ expect(res.status).toBe(400);
+ expect(res.body.error?.code ?? res.body.code).toBe('CATEGORY_ITEM_PURGE_ONLY');
+ });
+});
diff --git a/server/services/dataManager.categories.test.js b/server/services/dataManager.categories.test.js
index 61d6226fae..02899b3860 100644
--- a/server/services/dataManager.categories.test.js
+++ b/server/services/dataManager.categories.test.js
@@ -25,7 +25,7 @@ import { readdirSync, readFileSync } from 'fs';
import { join, relative, sep } from 'path';
import { PATHS } from '../lib/fileUtils.js';
import { DEFAULT_EXCLUDES } from './backup.js';
-import { CATEGORIES, UNKNOWN_CATEGORY_DESCRIPTION } from './dataManager.js';
+import { CATEGORIES, UNKNOWN_CATEGORY_DESCRIPTION, purgeCategory } from './dataManager.js';
// A path segment that is a file, not a directory (`settings.json`, `TASKS.md`).
const isFileSegment = (segment) => segment.includes('.');
@@ -121,3 +121,43 @@ describe('dataManager CATEGORIES coverage (#3285)', () => {
}
});
});
+
+describe('dataManager purge scope (#3327)', () => {
+ it('gives every purgeable category an explicit purgeScope and none to the protected ones', () => {
+ for (const [key, meta] of Object.entries(CATEGORIES)) {
+ if (meta.deletable) {
+ expect(['items', 'category'], `${key} purgeScope`).toContain(meta.purgeScope);
+ } else {
+ expect(meta.purgeScope, `${key} is protected and must not carry a purgeScope`).toBeUndefined();
+ }
+ }
+ });
+
+ it('keeps the irreplaceable media categories out of the all-or-nothing purge', () => {
+ // LoRA adapters are excluded from backup snapshots and cost hours of GPU
+ // time to retrain — no purge affordance at all.
+ expect(CATEGORIES.loras.deletable).toBe(false);
+ // Uploads and renders that other records point at: reclaimable one at a time.
+ expect(CATEGORIES.images.purgeScope).toBe('items');
+ expect(CATEGORIES.videos.purgeScope).toBe('items');
+ // Drafts live in Postgres; screenshots are task scratch — still wipeable whole.
+ expect(CATEGORIES.messages.purgeScope).toBe('category');
+ expect(CATEGORIES.screenshots.purgeScope).toBe('category');
+ });
+
+ // These only exercise the refusal paths, which all return before purgeCategory
+ // touches the filesystem — no test here may reach `rm` against the real data/.
+ it('refuses a category-wide purge for item-scoped and protected categories', async () => {
+ await expect(purgeCategory('images')).rejects.toThrow(/only supports per-item purge/);
+ await expect(purgeCategory('videos')).rejects.toThrow(/only supports per-item purge/);
+ await expect(purgeCategory('loras')).rejects.toThrow(/is not purgeable/);
+ await expect(purgeCategory('loras', { subPath: 'anything' })).rejects.toThrow(/is not purgeable/);
+ });
+
+ it('fails closed when a deletable category has no recognized purgeScope', async () => {
+ const original = CATEGORIES.messages.purgeScope;
+ CATEGORIES.messages.purgeScope = 'typo';
+ await expect(purgeCategory('messages')).rejects.toThrow(/only supports per-item purge/);
+ CATEGORIES.messages.purgeScope = original;
+ });
+});
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index aa574bd791..d4c2c0a011 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -4,6 +4,7 @@ import { existsSync } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
const execFileAsync = promisify(execFile);
const DATA_DIR = PATHS.data;
@@ -22,42 +23,52 @@ const DATA_DIR = PATHS.data;
// deletable — the bytes are genuinely reproducible (caches, ephemeral working
// dirs, re-downloadable assets) or are already duplicated elsewhere. False
// whenever purging would destroy the only copy of generated or uploaded work.
+// purgeScope — how much a purge may take at once. Only meaningful when
+// `deletable`; omit it (it resolves to null) on protected categories.
+// 'category' — the whole directory can go in one action.
+// 'items' — only a per-item delete (`subPath`) is offered; the
+// category-wide wipe is refused server-side. For a mixed directory of
+// uploads and renders that other records point at, "reclaim space" is a
+// legitimate need but an all-or-nothing wipe is not (issue #3327).
+// `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.
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 },
'audio': { label: 'Audio', description: 'Rendered voice-over lines referenced by pipeline issues', archivable: true, deletable: false },
- 'autofixer': { label: 'Autofixer', description: 'Autofixer run data', archivable: true, deletable: true },
+ 'autofixer': { label: 'Autofixer', description: 'Autofixer run data', archivable: true, deletable: true, purgeScope: 'category' },
'avatar': { label: 'Avatar', description: 'Uploaded avatar images', archivable: true, deletable: false },
- 'backup': { label: 'Backups', description: 'Data backup archives', archivable: false, deletable: true },
+ 'backup': { label: 'Backups', description: 'Data backup archives', archivable: false, deletable: true, purgeScope: 'category' },
'brain': { label: 'Brain', description: 'Brain items and sync log', archivable: true, deletable: false },
// Legacy location — current installs download to ~/Downloads (PATHS.browserDownloads),
// but installs that predate that move still carry the dir, and backup still excludes it.
- 'browser-downloads': { label: 'Browser Downloads', description: 'Files the agent browser downloaded — re-downloadable, safe to purge', archivable: false, deletable: true },
- 'browser-profile': { label: 'Browser Profile', description: 'Chrome/Chromium browser data', archivable: false, deletable: true },
+ 'browser-downloads': { label: 'Browser Downloads', description: 'Files the agent browser downloaded — re-downloadable, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
+ 'browser-profile': { label: 'Browser Profile', description: 'Chrome/Chromium browser data', archivable: false, deletable: true, purgeScope: 'category' },
'calendar': { label: 'Calendar', description: 'Calendar sync data', archivable: true, deletable: false },
'certs': { label: 'TLS Certificates', description: 'HTTPS certificate and private key — purging drops the install back to HTTP', archivable: false, deletable: false },
'commission-feedback': { label: 'Commission Feedback', description: 'Reactions on creative commissions (file mirror of the Postgres store)', archivable: true, deletable: false },
- 'conflict-journal': { label: 'Conflict Journal', description: 'Peer-sync conflict history — diagnostics only, safe to purge', archivable: true, deletable: true },
+ 'conflict-journal': { label: 'Conflict Journal', description: 'Peer-sync conflict history — diagnostics only, safe to purge', archivable: true, deletable: true, purgeScope: 'category' },
'cos': { label: 'Chief of Staff', description: 'Agent data, reports, memories', archivable: true, deletable: false },
'creative': { label: 'Creative Ledger', description: 'Append-only ledger of creative generation runs', archivable: true, deletable: false },
'creative-commissions': { label: 'Creative Commissions', description: 'Commission records (file mirror of the Postgres store)', archivable: true, deletable: false },
- 'db-dumps': { label: 'DB Dumps', description: 'PostgreSQL database backups', archivable: true, deletable: true },
+ 'db-dumps': { label: 'DB Dumps', description: 'PostgreSQL database backups', archivable: true, deletable: true, purgeScope: 'category' },
'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 },
+ '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-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', archivable: true, deletable: true },
- 'insights': { label: 'Insights', description: 'Derived goal scorecards and insights — rebuilt on the next insights run', archivable: true, deletable: true },
- 'jira-reports': { label: 'Jira Reports', description: 'Generated Jira reports — regenerable from Jira', archivable: true, deletable: true },
+ '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' },
+ 'insights': { label: 'Insights', description: 'Derived goal scorecards and insights — rebuilt on the next insights run', archivable: true, deletable: true, purgeScope: 'category' },
+ 'jira-reports': { label: 'Jira Reports', description: 'Generated Jira reports — regenerable from Jira', archivable: true, deletable: true, purgeScope: 'category' },
'loops': { label: 'Loops', description: 'Output history from scheduled loop runs', archivable: true, deletable: false },
'lora-datasets': { label: 'LoRA Datasets', description: 'Training images and captions for LoRA runs — uploaded source material, not regenerable', archivable: false, deletable: false },
- 'loras': { label: 'LoRAs', description: 'LoRA adapter files for image generation', archivable: false, deletable: true },
+ 'loras': { label: 'LoRAs', description: 'Trained LoRA adapters — excluded from backups and not regenerable without hours of GPU retraining', archivable: false, deletable: false },
'meatspace': { label: 'MeatSpace', description: 'Body metrics, blood tests, eyes', archivable: true, deletable: false },
'media-collections': { label: 'Media Collections', description: 'Media collection records', archivable: true, deletable: false },
'media-sketches': { label: 'Media Sketches', description: 'Saved sketch canvases used as render inputs', archivable: true, deletable: false },
- 'messages': { label: 'Messages', description: 'Email and messaging data', archivable: true, deletable: true },
+ 'messages': { label: 'Messages', description: 'Email and messaging data', archivable: true, deletable: true, purgeScope: 'category' },
'model-personality': { label: 'Model Personality', description: 'Model personality probe results and settings', archivable: true, deletable: false },
'music': { label: 'Music', description: 'Uploaded and generated background tracks', archivable: true, deletable: false },
'openclaw': { label: 'OpenClaw', description: 'OpenClaw integration config', archivable: true, deletable: false },
@@ -73,25 +84,25 @@ export const CATEGORIES = {
'pipeline-series-review': { label: 'Series Review', description: 'Cached series reviews — re-running them costs LLM calls', archivable: true, deletable: false },
'privacy': { label: 'Privacy', description: 'Data-broker opt-out records and request history', archivable: true, deletable: false },
'prompts': { label: 'Prompts', description: 'AI prompt templates', archivable: false, deletable: false },
- 'python': { label: 'Python Runtime', description: 'Managed virtualenv for local ML tooling — rebuilt on the next Python-backed run (re-downloads several GB of wheels)', archivable: false, deletable: true },
- 'repos': { label: 'Cloned Repos', description: 'Git repositories cloned by agents', archivable: false, deletable: true },
- 'review': { label: 'Review', description: 'Review hub items', archivable: true, deletable: true },
- 'runs': { label: 'AI Runs', description: 'Agent run logs and outputs', archivable: true, deletable: true },
- 'screenshots': { label: 'Screenshots', description: 'Task-related screenshots', archivable: true, deletable: true },
+ 'python': { label: 'Python Runtime', description: 'Managed virtualenv for local ML tooling — rebuilt on the next Python-backed run (re-downloads several GB of wheels)', archivable: false, deletable: true, purgeScope: 'category' },
+ 'repos': { label: 'Cloned Repos', description: 'Git repositories cloned by agents', archivable: false, deletable: true, purgeScope: 'category' },
+ 'review': { label: 'Review', description: 'Review hub items', archivable: true, deletable: true, purgeScope: 'category' },
+ 'runs': { label: 'AI Runs', description: 'Agent run logs and outputs', archivable: true, deletable: true, purgeScope: 'category' },
+ 'screenshots': { label: 'Screenshots', description: 'Task-related screenshots', archivable: true, deletable: true, purgeScope: 'category' },
'settings': { label: 'Settings', description: 'Per-feature settings files', archivable: true, deletable: false },
'sharing': { label: 'Peer Sync State', description: 'Peer-sync bookkeeping — purging forces a full resync and can resurrect deleted records', archivable: true, deletable: false },
'spotify': { label: 'Spotify Sync', description: 'Machine-local Spotify sync cursor and cache — purging resets the cursor and can leave a gap in imported history', archivable: true, deletable: false },
'sprites': { label: 'Sprites', description: 'Sprite reference art, walk frames, and runtime atlases — the only copy of the generated art; records live in Postgres', archivable: false, deletable: false },
'story-builder': { label: 'Story Builder', description: 'Story Builder project records', archivable: true, deletable: false },
- 'telegram': { label: 'Telegram', description: 'Telegram bot data', archivable: true, deletable: true },
+ '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 },
- '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 },
+ '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' },
'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 },
+ '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' },
'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 },
- 'videos': { label: 'Videos', description: 'Locally generated videos', archivable: true, deletable: true },
+ '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' },
'writers-room': { label: 'Writers Room', description: 'Writers Room works and story bibles', archivable: true, deletable: false },
'youtube': { label: 'YouTube Sync', description: 'Machine-local YouTube sync state — purging resets the cursor and can leave a gap in imported history', archivable: true, deletable: false }
};
@@ -106,11 +117,13 @@ export const UNKNOWN_CATEGORY_DESCRIPTION = "Not classified — PortOS doesn't k
* Resolve the display/permission metadata for a `data/` directory name.
* Adds `classified: false` for the unknown fallback so the client can style
* 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".
*/
function categoryMeta(name) {
const known = CATEGORIES[name];
- if (known) return { ...known, classified: true };
- return { label: name, description: UNKNOWN_CATEGORY_DESCRIPTION, archivable: false, deletable: false, classified: false };
+ if (known) return { purgeScope: null, ...known, classified: true };
+ return { label: name, description: UNKNOWN_CATEGORY_DESCRIPTION, archivable: false, deletable: false, purgeScope: null, classified: false };
}
// Validate category key contains only safe characters
@@ -193,12 +206,16 @@ export async function getCategoryDetail(categoryKey) {
}
export async function archiveCategory(categoryKey, options = {}) {
- if (!SAFE_NAME.test(categoryKey)) throw new Error('Invalid category name');
+ if (!SAFE_NAME.test(categoryKey)) throw new ServerError('Invalid category name', { status: 400, code: 'VALIDATION_ERROR' });
const meta = CATEGORIES[categoryKey];
- if (!meta?.archivable) throw new Error(`Category "${categoryKey}" is not archivable`);
+ if (!meta?.archivable) {
+ throw new ServerError(`Category "${categoryKey}" is not archivable`, { status: 403, code: 'CATEGORY_NOT_ARCHIVABLE' });
+ }
const dirPath = join(DATA_DIR, categoryKey);
- if (!existsSync(dirPath)) throw new Error(`Category directory not found: ${categoryKey}`);
+ if (!existsSync(dirPath)) {
+ throw new ServerError(`Category directory not found: ${categoryKey}`, { status: 404, code: 'NOT_FOUND' });
+ }
const backupDir = join(DATA_DIR, 'backup');
await ensureDir(backupDir);
@@ -244,12 +261,25 @@ export async function archiveCategory(categoryKey, options = {}) {
}
export async function purgeCategory(categoryKey, options = {}) {
- if (!SAFE_NAME.test(categoryKey)) throw new Error('Invalid category name');
+ if (!SAFE_NAME.test(categoryKey)) throw new ServerError('Invalid category name', { status: 400, code: 'VALIDATION_ERROR' });
const meta = CATEGORIES[categoryKey];
- if (!meta?.deletable) throw new Error(`Category "${categoryKey}" is not purgeable`);
+ if (!meta?.deletable) {
+ throw new ServerError(`Category "${categoryKey}" is not purgeable`, { status: 403, code: 'CATEGORY_NOT_PURGEABLE' });
+ }
+ // Item-scoped categories only ever lose one entry at a time. Written as
+ // "must be exactly 'category'" so an absent or misspelled scope refuses the
+ // wipe instead of inheriting the old all-or-nothing behavior (#3327).
+ if (!options.subPath && meta.purgeScope !== 'category') {
+ throw new ServerError(
+ `Category "${categoryKey}" only supports per-item purge — pass a subPath`,
+ { status: 400, code: 'CATEGORY_ITEM_PURGE_ONLY' }
+ );
+ }
const dirPath = join(DATA_DIR, categoryKey);
- if (!existsSync(dirPath)) throw new Error(`Category directory not found: ${categoryKey}`);
+ if (!existsSync(dirPath)) {
+ throw new ServerError(`Category directory not found: ${categoryKey}`, { status: 404, code: 'NOT_FOUND' });
+ }
if (options.subPath) {
const resolvedRoot = resolve(dirPath);
@@ -257,11 +287,15 @@ export async function purgeCategory(categoryKey, options = {}) {
// Boundary-aware containment check: use path.relative so a prefix like
// `/data/cat` cannot satisfy containment for `/data/cat2`.
const rel = relative(resolvedRoot, resolvedTarget);
- if (!rel || rel.startsWith('..') || isAbsolute(rel)) throw new Error('Invalid subPath');
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) {
+ throw new ServerError('Invalid subPath', { status: 400, code: 'VALIDATION_ERROR' });
+ }
await rm(resolvedTarget, { recursive: true, force: true });
+ console.log(`🗑️ Purged item from data/${categoryKey}`);
} else {
const entries = await readdir(dirPath).catch(() => []);
await Promise.all(entries.map(entry => rm(join(dirPath, entry), { recursive: true, force: true })));
+ console.log(`🗑️ Purged all ${entries.length} entries from data/${categoryKey}`);
}
return { category: categoryKey, subPath: options.subPath || null };
@@ -298,11 +332,13 @@ const SAFE_FILENAME = /^[a-z0-9._-]+$/i;
export async function deleteBackup(filename) {
if (!SAFE_FILENAME.test(filename) || filename === '.' || filename === '..') {
- throw new Error('Invalid filename');
+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
}
const backupDir = join(DATA_DIR, 'backup');
const fullPath = join(backupDir, filename);
- if (!fullPath.startsWith(backupDir)) throw new Error('Path traversal not allowed');
+ if (!fullPath.startsWith(backupDir)) {
+ throw new ServerError('Path traversal not allowed', { status: 400, code: 'VALIDATION_ERROR' });
+ }
await rm(fullPath);
return { deleted: filename };
}