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: harden Persistent Mind attachment cleanup (#5169)

Adam Eivy03a35ae61728
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.js
index bee4855e63..8af8df0757 100644
--- a/server/lib/agentRunEvents.js
+++ b/server/lib/agentRunEvents.js
@@ -143,6 +143,10 @@ const DROPPED_KEY_PATTERNS = [
/** Bounds. A ledger line must stay a diagnostic, not become a record copy. */
export const RUN_EVENT_LIMITS = Object.freeze({
maxStringChars: 200,
+ // Persistent Mind image references are server-owned API-relative paths, not
+ // free-form text. Their bounded stored filename can be longer than the
+ // ordinary diagnostic string cap without exposing a filesystem path.
+ maxSafeImagePathChars: 512,
// Explicitly display-safe mind text is allowed to be useful context while
// still bounded. Prompt/result/body keys never take this path.
maxDisplayChars: 4_000,
@@ -165,6 +169,12 @@ export const RUN_EVENT_READ_LIMITS = Object.freeze({
});
const isDroppedKey = (key) => DROPPED_KEY_PATTERNS.some((re) => re.test(key));
+const isSafeImagePath = (key, value) => (
+ key === 'path'
+ && typeof value === 'string'
+ && value.length <= RUN_EVENT_LIMITS.maxSafeImagePathChars
+ && /^\/api\/screenshots\/[A-Za-z0-9][A-Za-z0-9._-]*\.(?:png|jpg|jpeg|gif|webp)$/i.test(value)
+);
/**
* Replace the user's home directory prefix with `~` anywhere in a string.
@@ -252,6 +262,8 @@ function redactValue(value, depth) {
// payload that was already safe.
if (isDroppedKey(key) && (typeof raw === 'string' || (raw !== null && typeof raw === 'object'))) {
out[key] = { redacted: 'content', chars: typeof raw === 'string' ? raw.length : null };
+ } else if (isSafeImagePath(key, raw)) {
+ out[key] = raw;
} else if ((key === 'displayText' || key === 'summaryText') && typeof raw === 'string') {
out[key] = scrubString(raw, RUN_EVENT_LIMITS.maxDisplayChars);
} else {
diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.js
index 00051ca591..175f20febe 100644
--- a/server/lib/agentRunEvents.test.js
+++ b/server/lib/agentRunEvents.test.js
@@ -199,6 +199,16 @@ describe('redactRunEventData — privacy', () => {
expect(data.detail.length).toBe(RUN_EVENT_LIMITS.maxStringChars + 1); // + the ellipsis
});
+ it('preserves bounded API-relative Persistent Mind image paths', () => {
+ const path = `/api/screenshots/${'a'.repeat(230)}.png`;
+ const data = redactRunEventData({ images: [{ path }] });
+ expect(data.images[0].path).toBe(path);
+ expect(data.images[0].path.length).toBeGreaterThan(RUN_EVENT_LIMITS.maxStringChars);
+
+ const ordinaryPath = redactRunEventData({ path: `/tmp/${'x'.repeat(230)}.png` });
+ expect(ordinaryPath.path.length).toBe(RUN_EVENT_LIMITS.maxStringChars + 1);
+ });
+
it('caps array length, key count, and nesting depth', () => {
const wide = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`k${i}`, i]));
const capped = redactRunEventData(wide);
diff --git a/server/services/persistentMindSupervisor.attachments.test.js b/server/services/persistentMindSupervisor.attachments.test.js
index dc8cf814e1..33ae8db2d3 100644
--- a/server/services/persistentMindSupervisor.attachments.test.js
+++ b/server/services/persistentMindSupervisor.attachments.test.js
@@ -195,6 +195,18 @@ describe('persistent mind image attachment lifecycle', () => {
expect(mocks.appendMindEvent).toHaveBeenCalledTimes(2);
});
+ it('removes the pending marker when image persistence rejects', async () => {
+ mocks.saveImageUpload.mockRejectedValue(new Error('Invalid image file'));
+
+ await expect(supervisor.createPersistentMindAttachment({ filename: 'diagram.png', data: 'encoded-image' }))
+ .rejects.toThrow('Invalid image file');
+
+ const markerPath = mocks.writeFile.mock.calls[0][0];
+ expect(markerPath).toMatch(/\.mind-pending-[A-Za-z0-9_-]+$/);
+ expect(mocks.unlink).toHaveBeenCalledWith(markerPath);
+ expect(mocks.root.persistentMind.pendingAttachments).toEqual([]);
+ });
+
it('deletes only unclaimed files and leaves claimed historical assets alone', async () => {
mocks.root.persistentMind.pendingAttachments = [uploadRecord()];
await expect(supervisor.deletePersistentMindAttachment('attachment-1')).resolves.toEqual({
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index da70c93671..5489244b1e 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -241,6 +241,16 @@ const removeUploadAfterStateFailure = async (filePath, attachmentId) => unlink(f
},
);
+// A validation/write rejection happens before `saveImageUpload` can return its
+// stored path. Remove every file with this upload's generated prefix as well as
+// the marker, so a partial write cannot survive without the marker-based crash
+// recovery path.
+const removeRejectedUpload = async (attachmentId) => {
+ const entries = await screenshotEntries();
+ if (entries) await removePendingAttachmentFiles(attachmentId, entries);
+ await removePendingAttachmentMarker(attachmentId);
+};
+
const resolveMessageAttachments = async (mind, attachmentIds, messageId) => {
const byId = new Map(mind.pendingAttachments.map((attachment) => [attachment.attachmentId, attachment]));
const attachments = [];
@@ -321,7 +331,13 @@ export async function createPersistentMindAttachment({ filename, data } = {}) {
const saved = await saveImageUpload(PATHS.screenshots, {
filename: `mind-${attachmentId}-${originalName}`,
data,
- }, { maxBytes: PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_BYTES });
+ }, { maxBytes: PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_BYTES }).then(
+ (value) => value,
+ async (error) => {
+ await removeRejectedUpload(attachmentId);
+ throw error;
+ },
+ );
const uploadedAt = nowIso();
const attachment = normalizePersistentMindAttachment({
attachmentId,