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: expire shell image drops and stale task screenshots in data/screenshots (#8461)

[._.]/ Adam Eivy5f649040fb2c
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index b27ee68035..bd88e51d0b 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -115,6 +115,7 @@ import { startImageCleanTmpGc } from './imageCleanTmpGc.js';
import { startOrphanedPartialGc } from './orphanedPartialGc.js';
import { startBeeperAttachmentGc } from './beeperAttachmentGc.js';
import { startTribePurge } from './tribePurge.js';
+import { startScreenshotsGc } from './screenshotsGc.js';
import { initBridge as initBrainMemoryBridge } from './brainMemoryBridge.js';
import { initDrillCache } from './meatspacePostDrillCache.js';
import { registerPostReminderSchedule } from './meatspacePostReminder.js';
@@ -569,6 +570,10 @@ const startBackgroundServices = ({ spawnerReady, io }) => {
// identities, memory links and audit snapshots — and expire older tribe audit
// snapshots (#8459). Deleting a contact must eventually erase a third party's data.
startTribePurge();
+ // Periodically expire images handed to agents via data/screenshots: shell
+ // image drops after 7 days, other screenshots after 30 unless a live CoS task
+ // still references them (issue #8461). Fails closed on an unreadable task store.
+ startScreenshotsGc();
// Warm the catalog user-type registry from the user-type store (Postgres as of
// #1001; the settings.json slice under the escape hatch) before any catalog
// request can land, so user-defined types validate + mint ids immediately on
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 10f98fb406..80255c9557 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -154,7 +154,7 @@ export const CATEGORIES = {
'review': { label: 'Review', description: 'Review hub items', archivable: true, deletable: true, purgeScope: 'category' },
'rigging': { label: 'Rigging Clip Library', description: 'User-dropped animation-bearing GLB source files for retargeting — the only copy of assets you supplied', archivable: false, deletable: false },
'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' },
+ 'screenshots': { label: 'Screenshots', description: 'Task screenshots and images dropped into shell sessions — shell drops auto-delete after 7 days, others after 30 days unless an open task still uses them', 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 },
diff --git a/server/services/screenshotsGc.js b/server/services/screenshotsGc.js
new file mode 100644
index 0000000000..d30d755b72
--- /dev/null
+++ b/server/services/screenshotsGc.js
@@ -0,0 +1,123 @@
+/**
+ * Retention sweep for `data/screenshots` (issue #8461).
+ *
+ * The bucket is the hand-off point for images an AI reads from disk: shell
+ * image drops (`shell-<id>-<name>`, pasted into a PTY once and never read
+ * again), CoS task screenshots (`POST /api/screenshots`, referenced from a
+ * task's `metadata.screenshots[]`), and vision-test / universe-describe inputs.
+ * Nothing else ever deletes them, so a photo handed to an agent once stayed on
+ * disk, in every backup, indefinitely.
+ *
+ * Rules:
+ * - `shell-*` files older than 7 days are removed — single-use PTY hand-offs.
+ * - Every other file older than 30 days is removed unless a CoS task that is
+ * neither completed nor failed still lists it in `metadata.screenshots[]`.
+ *
+ * Fail closed: if the task store can't be read, the sweep deletes nothing —
+ * "couldn't read the references" must never collapse into "no references".
+ *
+ * Runs outside the request lifecycle, so the handler owns its rejections.
+ */
+
+import { readdir, stat } from 'fs/promises';
+import { join, basename } from 'path';
+import { PATHS, unlinkGuarded } from '../lib/fileUtils.js';
+import { createSweepScheduler } from './sweepScheduler.js';
+import { getAllTasks } from './cosTaskStore.js';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const SHELL_DROP_MAX_AGE_MS = 7 * DAY_MS;
+const SCREENSHOT_MAX_AGE_MS = 30 * DAY_MS;
+const SHELL_DROP_PREFIX = 'shell-';
+const TERMINAL_TASK_STATUSES = new Set(['completed', 'failed']);
+
+const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
+const INITIAL_DELAY_MS = 10 * 60 * 1000;
+
+// A task reference is either the API URL (`/api/screenshots/<encoded name>`)
+// the upload route hands back, or a filesystem path from an older client.
+const referenceBasename = (ref) => {
+ const name = basename(ref);
+ try { return decodeURIComponent(name); } catch { return name; }
+};
+
+/**
+ * Basenames of screenshots still listed by a live (not completed/failed) task.
+ * Throws when the task store is unreadable — callers must treat that as
+ * "unknown", not "empty".
+ */
+async function collectReferencedScreenshots(readTasks = getAllTasks) {
+ const { user, cos } = await readTasks();
+ const referenced = new Set();
+ for (const task of [...(user?.tasks ?? []), ...(cos?.tasks ?? [])]) {
+ if (TERMINAL_TASK_STATUSES.has(task?.status)) continue;
+ const refs = task?.metadata?.screenshots;
+ if (!Array.isArray(refs)) continue;
+ for (const ref of refs) {
+ if (typeof ref === 'string' && ref) referenced.add(referenceBasename(ref));
+ }
+ }
+ return referenced;
+}
+
+/**
+ * One GC pass (underscore: exported as a test hook). Returns counts, or `{ skipped: true }` when the task store was
+ * unreadable and nothing was touched.
+ */
+export async function _sweepScreenshots({
+ now = Date.now(),
+ dir = PATHS.screenshots,
+ readTasks = getAllTasks,
+} = {}) {
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
+ const files = entries.filter((e) => e.isFile()).map((e) => e.name);
+ const result = { deleted: 0, keptReferenced: 0, keptYoung: 0 };
+ if (files.length === 0) return result;
+
+ let referenced;
+ try {
+ referenced = await collectReferencedScreenshots(readTasks);
+ } catch (err) {
+ console.error(`❌ Screenshots GC skipped: task store unreadable: ${err.message}`);
+ return { ...result, skipped: true };
+ }
+
+ for (const name of files) {
+ const isShellDrop = name.startsWith(SHELL_DROP_PREFIX);
+ const maxAgeMs = isShellDrop ? SHELL_DROP_MAX_AGE_MS : SCREENSHOT_MAX_AGE_MS;
+ const info = await stat(join(dir, name)).catch(() => null);
+ if (!info) continue;
+ if (now - info.mtimeMs < maxAgeMs) {
+ result.keptYoung += 1;
+ continue;
+ }
+ if (!isShellDrop && referenced.has(name)) {
+ result.keptReferenced += 1;
+ continue;
+ }
+ const removed = await unlinkGuarded(join(dir, name)).then(() => true).catch(() => false);
+ if (removed) result.deleted += 1;
+ }
+ return result;
+}
+
+const runSweep = async () => {
+ const result = await _sweepScreenshots().catch((err) => {
+ console.error(`❌ Screenshots GC failed: ${err.message}`);
+ return null;
+ });
+ if (result?.deleted > 0) {
+ console.log(`🧹 Screenshots GC: removed ${result.deleted}, kept ${result.keptReferenced} referenced, ${result.keptYoung} recent`);
+ }
+};
+
+export const {
+ start: startScreenshotsGc,
+ stop: stopScreenshotsGc,
+} = createSweepScheduler({
+ id: 'screenshots-gc',
+ intervalMs: SWEEP_INTERVAL_MS,
+ initialDelayMs: INITIAL_DELAY_MS,
+ handler: runSweep,
+ source: 'screenshotsGc',
+});
diff --git a/server/services/screenshotsGc.test.js b/server/services/screenshotsGc.test.js
new file mode 100644
index 0000000000..4ee6cf4b8e
--- /dev/null
+++ b/server/services/screenshotsGc.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdir, writeFile, rm, utimes } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { _sweepScreenshots } from './screenshotsGc.js';
+
+const DAY = 24 * 60 * 60 * 1000;
+const NOW = Date.parse('2026-09-25T00:00:00Z');
+
+let dir;
+
+async function put(name, ageDays) {
+ const p = join(dir, name);
+ await writeFile(p, 'x');
+ const secs = (NOW - ageDays * DAY) / 1000;
+ await utimes(p, secs, secs);
+}
+
+const tasks = (list) => async () => ({ user: { tasks: list }, cos: { tasks: [] } });
+
+beforeEach(async () => {
+ dir = join(tmpdir(), `portos-screenshotsgc-${process.pid}-${Math.random().toString(36).slice(2)}`);
+ await mkdir(dir, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+});
+
+describe('_sweepScreenshots', () => {
+ it('expires shell drops after 7 days, even when a task names them', async () => {
+ await put('shell-aaaa1111-old.png', 8);
+ await put('shell-bbbb2222-new.png', 6);
+ const result = await _sweepScreenshots({
+ now: NOW,
+ dir,
+ readTasks: tasks([{ status: 'pending', metadata: { screenshots: ['/api/screenshots/shell-aaaa1111-old.png'] } }]),
+ });
+ expect(existsSync(join(dir, 'shell-aaaa1111-old.png'))).toBe(false);
+ expect(existsSync(join(dir, 'shell-bbbb2222-new.png'))).toBe(true);
+ expect(result).toEqual({ deleted: 1, keptReferenced: 0, keptYoung: 1 });
+ });
+
+ it('keeps a 40-day-old screenshot a live task references and removes unreferenced ones', async () => {
+ await put('my shot.png', 40);
+ await put('orphan.png', 40);
+ await put('done-task.png', 40);
+ await put('recent.png', 20);
+ const result = await _sweepScreenshots({
+ now: NOW,
+ dir,
+ readTasks: tasks([
+ { status: 'pending', metadata: { screenshots: [`/api/screenshots/${encodeURIComponent('my shot.png')}`] } },
+ { status: 'completed', metadata: { screenshots: ['/api/screenshots/done-task.png'] } },
+ ]),
+ });
+ expect(existsSync(join(dir, 'my shot.png'))).toBe(true);
+ expect(existsSync(join(dir, 'orphan.png'))).toBe(false);
+ expect(existsSync(join(dir, 'done-task.png'))).toBe(false);
+ expect(existsSync(join(dir, 'recent.png'))).toBe(true);
+ expect(result).toEqual({ deleted: 2, keptReferenced: 1, keptYoung: 1 });
+ });
+
+ it('deletes nothing and logs an error when the task store read throws', async () => {
+ await put('shell-cccc3333-old.png', 30);
+ await put('old.png', 90);
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const result = await _sweepScreenshots({
+ now: NOW,
+ dir,
+ readTasks: async () => { throw new Error('TASKS.md unreadable'); },
+ });
+ expect(result.skipped).toBe(true);
+ expect(existsSync(join(dir, 'shell-cccc3333-old.png'))).toBe(true);
+ expect(existsSync(join(dir, 'old.png'))).toBe(true);
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('TASKS.md unreadable'));
+ });
+});