Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Settings: show how full the attachments store is and let the owner clear it (#4221)

Aditya Umale95d61be6556e
diff --git a/server/attachments.test.ts b/server/attachments.test.ts
index 93624728e4..4ed207137f 100644
--- a/server/attachments.test.ts
+++ b/server/attachments.test.ts
@@ -43,12 +43,17 @@ process.env.OMB_DATA_DIR = join(DATA_ROOT, "data");
const {
ATTACHMENTS_DIR,
ATTACHMENTS_MAX_BYTES,
+ ATTACHMENT_CLEAR_MIN_AGE_MS,
ATTACHMENT_PARTIAL_MAX_AGE_MS,
DEFAULT_ATTACHMENTS_MAX_BYTES,
FILE_MAX_BYTES,
IMAGE_MAX_BYTES,
__resetAttachmentAccountingForTests,
+ attachmentStorageUsage,
attachmentsMaxBytes,
+ clearAttachments,
+ keptAttachmentNames,
+ offerAttachmentClear,
cleanupStaleAttachmentPartials,
deleteAttachment,
extensionForFileMime,
@@ -257,7 +262,7 @@ describe("aggregate attachment storage", () => {
throw new Error("expected quota rejection");
} catch (error) {
expect(error).toMatchObject({ status: 507 });
- expect(error).toHaveProperty("message", "attachments storage is full (512 MB limit)");
+ expect(error).toHaveProperty("message", "attachments storage is full (512 MB limit). Clear old attachments in Settings → General.");
}
expect(existsSync(referenced.path)).toBe(true);
expect(statSync(referenced.path).size).toBe(ATTACHMENTS_MAX_BYTES);
@@ -638,3 +643,81 @@ describe("shared files", () => {
expect(readdirSync(ATTACHMENTS_DIR)).toEqual([`${UPLOAD_A}.pdf`]);
});
});
+
+describe("clearing attachments from Settings", () => {
+ beforeEach(() => {
+ resetDir();
+ });
+ afterEach(() => {
+ resetDir();
+ });
+
+ const nameOf = (path: string) => path.split(/[\\/]/).pop()!;
+
+ it("keeps pictures by their url and files by their path, on any platform", () => {
+ const kept = keptAttachmentNames(
+ ["/api/attachments/bot.png", null, undefined, "https://example.com/face.png"],
+ ["banner.webp", "C:\\Users\\me\\data\\attachments\\routine.pdf", "/home/me/data/attachments/run.png", undefined],
+ );
+ expect([...kept].sort()).toEqual(["banner.webp", "bot.png", "routine.pdf", "run.png"]);
+ });
+
+ const age = (path: string, ms: number) => {
+ const at = new Date(Date.now() - ms);
+ utimesSync(path, at, at);
+ };
+
+ it("frees a full store so the next upload works, keeping pictures, routine files and fresh uploads", () => {
+ const old = saveImage(Buffer.from("old"), "image/png");
+ const picture = saveImage(Buffer.from("avatar"), "image/png");
+ const fresh = saveImage(Buffer.from("fresh"), "image/png");
+ truncateSync(old.path, ATTACHMENTS_MAX_BYTES - 64);
+ age(old.path, ATTACHMENT_CLEAR_MIN_AGE_MS + 1_000);
+ age(picture.path, ATTACHMENT_CLEAR_MIN_AGE_MS + 1_000);
+ __resetAttachmentAccountingForTests();
+ expect(() => saveImage(Buffer.from("x".repeat(100)), "image/png")).toThrow(/storage is full.*Settings/);
+
+ const cleared = clearAttachments(new Set([nameOf(picture.path)]));
+
+ expect(cleared).toEqual({ removed: 1, freedBytes: ATTACHMENTS_MAX_BYTES - 64, failed: 0 });
+ expect(existsSync(old.path)).toBe(false);
+ expect(existsSync(picture.path)).toBe(true);
+ expect(existsSync(fresh.path)).toBe(true);
+ expect(attachmentStorageUsage()).toEqual({ usedBytes: "avatar".length + "fresh".length, maxBytes: ATTACHMENTS_MAX_BYTES });
+ expect(() => saveImage(Buffer.from("x".repeat(100)), "image/png")).not.toThrow();
+ });
+
+ it("does not point a Team Cloud, which has no clear, to Settings", () => {
+ const full = saveImage(Buffer.from("x"), "image/png");
+ truncateSync(full.path, ATTACHMENTS_MAX_BYTES);
+ __resetAttachmentAccountingForTests();
+ offerAttachmentClear(false);
+ try {
+ expect(() => saveImage(Buffer.from("y"), "image/png")).toThrow(/^attachments storage is full \(512 MB limit\)$/);
+ } finally {
+ offerAttachmentClear(true);
+ }
+ });
+
+ it("counts files it could not remove instead of hiding them", () => {
+ const busy = saveImage(Buffer.from("busy"), "image/png");
+ const gone = saveImage(Buffer.from("gone"), "image/png");
+ age(busy.path, ATTACHMENT_CLEAR_MIN_AGE_MS + 1_000);
+ age(gone.path, ATTACHMENT_CLEAR_MIN_AGE_MS + 1_000);
+ vi.mocked(unlinkSync).mockImplementation((path) => {
+ throw Object.assign(new Error("failed"), { code: String(path) === busy.path ? "EBUSY" : "ENOENT" });
+ });
+
+ expect(clearAttachments(new Set())).toEqual({ removed: 0, freedBytes: 0, failed: 1 });
+ });
+
+ it("leaves upload partials to their own cleanup", () => {
+ mkdirSync(ATTACHMENTS_DIR, { recursive: true });
+ const partial = join(ATTACHMENTS_DIR, `.openmaus-upload-${UPLOAD_A}-${UPLOAD_B}.partial`);
+ writeFileSync(partial, "part");
+ age(partial, ATTACHMENT_CLEAR_MIN_AGE_MS + 1_000);
+
+ expect(clearAttachments(new Set())).toEqual({ removed: 0, freedBytes: 0, failed: 0 });
+ expect(existsSync(partial)).toBe(true);
+ });
+});
diff --git a/server/attachments.ts b/server/attachments.ts
index 3e52b45730..eba2100026 100644
--- a/server/attachments.ts
+++ b/server/attachments.ts
@@ -181,6 +181,58 @@ export function deleteAttachment(path: string): void {
}
}
+/** Settings → General: what the store holds against its ceiling, rescanned so files removed outside the app count. */
+export function attachmentStorageUsage(): { usedBytes: number; maxBytes: number } {
+ invalidateAttachmentAccounting();
+ return { usedBytes: committedBytes(), maxBytes: ATTACHMENTS_MAX_BYTES };
+}
+
+/** What a Settings clear leaves, as stored names: pictures given by their /api/attachments/ url (bot and profile
+ * pictures), and files given by their path or bare name (the banner, routines' files). */
+export function keptAttachmentNames(urls: ReadonlyArray<string | null | undefined>, paths: ReadonlyArray<string | undefined>): Set<string> {
+ const kept = new Set<string>();
+ for (const url of urls) if (url?.startsWith("/api/attachments/")) kept.add(url.slice("/api/attachments/".length));
+ for (const path of paths) {
+ const name = path?.replaceAll("\\", "/").split("/").pop();
+ if (name) kept.add(name);
+ }
+ return kept;
+}
+
+let clearOffered = true;
+/** A Team Cloud has no Settings clear, so its full-store error must not point there. */
+export function offerAttachmentClear(offered: boolean): void {
+ clearOffered = offered;
+}
+
+/** A file this new may still be on its way into a message or a turn, so a clear leaves it. */
+export const ATTACHMENT_CLEAR_MIN_AGE_MS = 10 * 60 * 1000;
+
+/** The person's Clear in Settings: every stored file older than a few minutes goes, except the ones `kept` holds
+ * (pictures, routine files). A message that showed a removed file shows it missing. */
+export function clearAttachments(kept: ReadonlySet<string>, now = Date.now()): { removed: number; freedBytes: number; failed: number } {
+ ensureAttachmentsDir();
+ let removed = 0;
+ let freedBytes = 0;
+ let failed = 0;
+ for (const entry of readdirSync(ATTACHMENTS_DIR, { withFileTypes: true })) {
+ if (!entry.isFile() || PARTIAL_NAME.test(entry.name) || kept.has(entry.name)) continue;
+ const path = join(ATTACHMENTS_DIR, entry.name);
+ try {
+ const { mtimeMs, size } = statSync(path);
+ if (now - mtimeMs < ATTACHMENT_CLEAR_MIN_AGE_MS) continue;
+ unlinkSync(path);
+ removed += 1;
+ freedBytes += size;
+ } catch (error) {
+ // Gone already is fine; anything else (permissions, a busy file on Windows) the person is told about.
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") failed += 1;
+ }
+ }
+ invalidateAttachmentAccounting();
+ return { removed, freedBytes, failed };
+}
+
export function __resetAttachmentAccountingForTests(): void {
invalidateAttachmentAccounting();
}
@@ -223,7 +275,7 @@ class AttachmentReservation {
if (available < required) {
throw statusError(
507,
- `attachments storage is full (${formatStoreLimit(ATTACHMENTS_MAX_BYTES)} limit)`,
+ `attachments storage is full (${formatStoreLimit(ATTACHMENTS_MAX_BYTES)} limit)${clearOffered ? ". Clear old attachments in Settings → General." : ""}`,
);
}
const granted = Math.min(preferred, available);
diff --git a/server/index.ts b/server/index.ts
index 68376be824..600a0becaa 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -62,13 +62,7 @@ import { commandReceipt } from "./commands.ts";
import { buildTurnDigest, coverageForDriver, digestPromptLine, renderDigest, toolEvidence } from "./digest.ts";
import { appendDecision, bindDecisionRetention, decisionRetentionDays, flushDecisionLog, pruneDecisions, withDecisionActor, type DecisionActor, type DecisionVia } from "./decision-log.ts";
import { folderToFollow, inMyFolderCwd, validateBotCwd } from "./bot-cwd.ts";
-import {
- ATTACHMENTS_DIR,
- attachmentExists,
- deleteAttachment,
- saveAudio,
- saveImage,
-} from "./attachments.ts";
+import { ATTACHMENTS_DIR, attachmentExists, deleteAttachment, keptAttachmentNames, offerAttachmentClear, saveAudio, saveImage } from "./attachments.ts";
import {
messageAttachmentName,
messageFileRoots,
@@ -576,7 +570,7 @@ import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./h
import { holdBodyDeadline } from "./body-deadline.ts";
import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";
-import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerSummary } from "./routes/workspace-banner.ts";
+import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerStore, workspaceBannerSummary } from "./routes/workspace-banner.ts";
import { createBotMemoryRoutes } from "./routes/bot-memory.ts";
import { createBotCreateRoutes } from "./routes/bots-create.ts";
import { createTeamOwnerRoutes } from "./routes/team-owners.ts";
@@ -12275,7 +12269,9 @@ ROUTES.push(createThreadRoutes({
botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo, coordinator, groupThreadIsWorking, memberDefaultBot: CLOUD_TEAM ? (email) => ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM.name }) : undefined,
uploads: uploadsFor(createUploadOwners(DATA_DIR), Boolean(CLOUD_TEAM)),
attachmentInUse: (name) => threadsReferencing(name).length > 0 || store.bots.some((bot) => bot.avatarUrl === `/api/attachments/${name}`),
-}));
+ keptAttachments: CLOUD_TEAM ? undefined : () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles,
+ ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; },
+})); offerAttachmentClear(!CLOUD_TEAM);
ROUTES.push(createBotCreateRoutes({
store, cfg, presetStore, orgInstallStatuses,
hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED,
diff --git a/server/request-auth.test.ts b/server/request-auth.test.ts
index 0e100f324d..780b213646 100644
--- a/server/request-auth.test.ts
+++ b/server/request-auth.test.ts
@@ -105,6 +105,11 @@ describe("scopes", () => {
] as const) expect(requiredScope(method, path), `${method} ${path}`).toBe("admin");
});
+ it("keeps the attachments clear to the owner: a client may read one file, never empty the store", () => {
+ for (const method of ["GET", "POST"]) expect(requiredScope(method, "/api/attachment-storage"), method).toBe("admin");
+ expect(requiredScope("GET", "/api/attachments/a1b2.png")).toBe("client");
+ });
+
it("allows clients to list and read notifications with exactly the feed's methods and paths", () => {
for (const [method, path] of [
["GET", "/api/notifications"],
diff --git a/server/routes/threads-attachment-clear.test.ts b/server/routes/threads-attachment-clear.test.ts
new file mode 100644
index 0000000000..8faf97dfeb
--- /dev/null
+++ b/server/routes/threads-attachment-clear.test.ts
@@ -0,0 +1,54 @@
+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { ATTACHMENTS_DIR } from "../attachments.ts";
+import { DATA_DIR } from "../config.ts";
+import type { ModelSelection } from "../contracts.ts";
+import { json, readBody } from "../harness/http.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { Store } from "../store.ts";
+import { dispatchRoutes } from "./table.ts";
+import { createThreadRoutes, type ThreadRouteDeps } from "./threads.ts";
+
+const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };
+const servers: Server[] = [];
+
+beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
+});
+
+async function serve(keptAttachments: () => ReadonlySet<string> | null): Promise<string> {
+ const deps = { store: new Store(() => sonnet), viewerFor: () => ({}), visibleTo: () => ({ bot: () => true, group: () => true }), workspaceAccess: () => null, desktopMutationToken: () => undefined, companionMutationToken: () => undefined, cliOwnerToken: () => undefined, userName: () => "Milind", keptAttachments } as unknown as ThreadRouteDeps;
+ const routes = [createThreadRoutes(deps)];
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;
+ try {
+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, {});
+ } catch (error) {
+ json(res, 500, { error: String(error) });
+ }
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}
+
+describe("POST /api/attachment-storage", () => {
+ // routines.attachmentPaths() is null while routines.json is unreadable or a saved row's attachments are malformed.
+ it("deletes nothing while the files to keep are unknown", async () => {
+ mkdirSync(ATTACHMENTS_DIR, { recursive: true });
+ const file = join(ATTACHMENTS_DIR, "brief.pdf");
+ writeFileSync(file, "brief");
+ const base = await serve(() => null);
+
+ const cleared = await fetch(`${base}/api/attachment-storage`, { method: "POST" });
+
+ expect([cleared.status, await cleared.text()]).toEqual([503, JSON.stringify({ error: "Routines are still loading. Try again in a moment." })]);
+ expect(existsSync(file)).toBe(true);
+ });
+});
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 78a108ff4f..6795770e9c 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -2,8 +2,8 @@ import { basename, join } from "node:path";
import type { WireBot, WireGroup } from "../../shared/wire.ts";
import {
- ATTACHMENTS_DIR, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES, parseAudioRange, readAttachment,
- saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,
+ ATTACHMENTS_DIR, attachmentStorageUsage, clearAttachments, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES,
+ parseAudioRange, readAttachment, saveFile, saveImageUpload, validateAttachmentUploadId, type SavedAttachment,
} from "../attachments.ts";
import { deliveredCopy } from "../bot-attachment.ts";
import { memberBot, memberGroup, type Viewer, type VisibleSet } from "../bot-visibility.ts";
@@ -63,6 +63,8 @@ export interface ThreadRouteDeps {
/** Who uploaded each file: only its uploader discards it, and only while nothing uses it. */
uploads: { note(auth: RequestAuth, name: string): void; owns(auth: RequestAuth, name: string): boolean };
attachmentInUse(name: string): boolean;
+ /** The stored files a Settings clear must leave (pictures, banner, routine and calendar-call files), null until those load; absent on a Team Cloud, which has no clear. */
+ keptAttachments?(): ReadonlySet<string> | null;
}
export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
@@ -379,6 +381,17 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
}
}
+ // Not under /api/attachments/: that GET is open to clients. This path keeps the default admin scope.
+ if (path === "/api/attachment-storage" && deps.keptAttachments) {
+ if (method === "GET") return json(res, 200, attachmentStorageUsage());
+ if (method === "POST") {
+ // Until routines load their files are unknown, and a clear could take them.
+ const kept = deps.keptAttachments();
+ if (!kept) return json(res, 503, { error: "Routines are still loading. Try again in a moment." });
+ return json(res, 200, { ...clearAttachments(kept), ...attachmentStorageUsage() });
+ }
+ }
+
// Name-locked to the attachments dir: readAttachment refuses anything but a bare generated filename.
m = path.match(/^\/api\/attachments\/([\w.-]+)$/);
if (m && method === "DELETE") {
diff --git a/server/routine-attachments.ts b/server/routine-attachments.ts
index 476591d4db..a308985954 100644
--- a/server/routine-attachments.ts
+++ b/server/routine-attachments.ts
@@ -28,6 +28,28 @@ export function cleanAttachments(value: unknown): RoutineContextAttachment[] {
});
}
+/** The file paths the owners' attachments name; null when any saved list is malformed, so a clear that relies on it refuses. */
+export function attachmentPathsOf(owners: ReadonlyArray<{ attachments?: unknown }>): string[] | null {
+ const paths: string[] = [];
+ for (const { attachments } of owners) {
+ if (attachments === undefined) continue;
+ if (!Array.isArray(attachments)) return null;
+ for (const file of attachments as unknown[]) {
+ const path = file && typeof file === "object" ? (file as { path?: unknown }).path : undefined;
+ if (typeof path !== "string") return null;
+ paths.push(path);
+ }
+ }
+ return paths;
+}
+
+/** True when any saved list would not load as it is: loading drops such a list, so its files are no longer named. */
+export function attachmentsMalformed(owners: ReadonlyArray<{ attachments?: unknown }>): boolean {
+ return owners.some(({ attachments }) => {
+ try { cleanAttachments(attachments); return false; } catch { return true; }
+ });
+}
+
export function cleanTimeoutMinutes(value: unknown): number | undefined {
if (value == null) return undefined;
if (typeof value !== "number" || !Number.isInteger(value) || value < 5 || value > 240) {
diff --git a/server/routines.test.ts b/server/routines.test.ts
index 7c9364debf..df32ef4d9c 100644
--- a/server/routines.test.ts
+++ b/server/routines.test.ts
@@ -1194,6 +1194,64 @@ describe("RoutineManager", () => {
expect(readFileSync(file, "utf8")).toBe(corrupt);
});
+ it("names the files of unloaded routines and runs for an attachments clear, and none while the file is unreadable", () => {
+ const h = harness();
+ const file = h.options.file as string;
+ const routine = h.manager.create({
+ name: "Review attachment",
+ prompt: "Review the supplied context",
+ botId: "maus-1",
+ schedule: { type: "daily", time: "09:00", weekdays: [1] },
+ attachments: [{ id: "file-1", kind: "file", name: "brief.pdf", path: "/tmp/brief.pdf", size: 4_096 }],
+ });
+ h.manager.runNow(routine.id);
+ expect(h.manager.attachmentPaths()).toEqual(["/tmp/brief.pdf", "/tmp/brief.pdf"]);
+
+ const disk = JSON.parse(readFileSync(file, "utf8")) as { routines: Array<{ schedule: unknown }>; runs: Array<{ attachments?: unknown }> };
+ disk.routines[0]!.schedule = { type: "never" };
+ delete disk.runs[0]!.attachments;
+ writeFileSync(file, JSON.stringify(disk));
+ const unloaded = new RoutineManager(h.options);
+ expect(unloaded.listRoutines()).toEqual([]);
+ expect(unloaded.attachmentPaths()).toEqual(["/tmp/brief.pdf"]);
+
+ writeFileSync(file, "{ not json");
+ expect(new RoutineManager(h.options).attachmentPaths()).toBeNull();
+ });
+
+ it("names no files for a clear when an unloaded routine's attachments are malformed", () => {
+ for (const attachments of [{ path: "/tmp/brief.pdf" }, [null], [{ id: "file-1" }], "brief.pdf"]) {
+ const h = harness();
+ const file = h.options.file as string;
+ h.manager.create({ name: "Review", prompt: "Review it", botId: "maus-1", schedule: { type: "daily", time: "09:00", weekdays: [1] } });
+ const disk = JSON.parse(readFileSync(file, "utf8")) as { routines: Array<{ schedule: unknown; attachments?: unknown }> };
+ disk.routines[0]!.schedule = { type: "never" };
+ disk.routines[0]!.attachments = attachments;
+ writeFileSync(file, JSON.stringify(disk));
+ const unloaded = new RoutineManager(h.options);
+ expect(unloaded.listRoutines()).toEqual([]);
+ expect(unloaded.attachmentPaths()).toBeNull();
+ }
+ });
+
+ it("names no files for a clear when a loaded routine's or run's attachment list holds a bad entry", () => {
+ for (const owner of ["routines", "runs"] as const) {
+ const h = harness();
+ const file = h.options.file as string;
+ const routine = h.manager.create({
+ name: "Review", prompt: "Review it", botId: "maus-1", schedule: { type: "daily", time: "09:00", weekdays: [1] },
+ attachments: [{ id: "file-1", kind: "file", name: "brief.pdf", path: "/tmp/brief.pdf", size: 4_096 }],
+ });
+ h.manager.runNow(routine.id);
+ const disk = JSON.parse(readFileSync(file, "utf8")) as Record<typeof owner, Array<{ attachments?: unknown[] }>>;
+ disk[owner][0]!.attachments!.push(null);
+ writeFileSync(file, JSON.stringify(disk));
+ const reloaded = new RoutineManager(h.options);
+ expect(reloaded.listRoutines()).toHaveLength(1);
+ expect(reloaded.attachmentPaths()).toBeNull();
+ }
+ });
+
it("treats a routines file with a damaged top-level shape as unreadable", () => {
const h = harness();
const file = h.options.file as string;
diff --git a/server/routines.ts b/server/routines.ts
index fcaa15850c..af8eee0fda 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -28,7 +28,7 @@ import {
import { activeMs, askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waits.ts";
import { failsLikeLastOutcome, outcomesNewestFirst } from "./routine-outcomes.ts";
import { EVENT_RETRY_WINDOW_MS, loadEventReceipts, MAX_EVENT_RECEIPTS, type EventRunReceipt } from "./routine-event-receipts.ts";
-import { cloneAttachments } from "./routine-attachments.ts";
+import { attachmentPathsOf, attachmentsMalformed, cloneAttachments } from "./routine-attachments.ts";
import { loadInstalledPackage, loadRequestReceipts, loadRoutine, loadRun } from "./routine-load.ts";
import { applyHolds, holdCauses, type AppliedHolds } from "./routine-holds.ts";
import { sanitizeInput } from "./routine-input.ts";
@@ -312,8 +312,8 @@ export class RoutineManager {
/** Why routines are held now (routine-holds.ts): a change between two of these pauses or frees routines. */
private holds: RoutineHoldCause[] = [];
private readonly failureFacts = new Map<string, RoutineFailureFacts>();
- /** Saves are refused while set, so an empty state never overwrites an unreadable file. */
- private unreadable = false;
+ /** Saves are refused while unreadable, so an empty state never overwrites the file; malformedAttachments: a saved list failed to load, so no clear may trust attachmentPaths(). */
+ private unreadable = false; private malformedAttachments = false;
private frozenPending = false;
private readonly bootedAt: number;
private readonly checking = new Set<string>();
@@ -337,7 +337,7 @@ export class RoutineManager {
}
return loaded ? [loaded] : [];
}) : [];
- this.runs = Array.isArray(disk.runs) ? disk.runs.map(loadRun) : [];
+ this.runs = Array.isArray(disk.runs) ? disk.runs.map(loadRun) : []; this.malformedAttachments = attachmentsMalformed([...(disk.routines ?? []), ...(disk.runs ?? [])]);
this.routineRequestReceipts = loadRequestReceipts(disk.routineRequestReceipts);
this.webhookRunReceipts = loadEventReceipts(disk.webhookRunReceipts, this.runs, this.now());
this.frozenPending = disk.frozenResultsCleared !== true;
@@ -345,11 +345,7 @@ export class RoutineManager {
this.holds = holdCauses(disk.holds);
if (typeof disk.startupLaunchId === "string") this.startupLaunchId = disk.startupLaunchId;
} catch (error) {
- this.routines = [];
- this.unloadedRoutines = [];
- this.runs = [];
- this.routineRequestReceipts = [];
- this.webhookRunReceipts = [];
+ this.routines = []; this.unloadedRoutines = []; this.runs = []; this.routineRequestReceipts = []; this.webhookRunReceipts = [];
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
this.unreadable = true;
// JSON.parse errors can echo a fragment of the input, so they never reach the log.
@@ -379,6 +375,9 @@ export class RoutineManager {
}
}
+ /** Files every saved routine and run names, unloaded rows too; null while routines.json is unreadable or a row's attachments are malformed, so nothing can clear them. */
+ attachmentPaths(): string[] | null { return this.unreadable || this.malformedAttachments ? null : attachmentPathsOf([...this.routines, ...this.unloadedRoutines, ...this.runs]); }
+
listRoutines(): Routine[] {
return this.routines.map(routine => this.routineWithHealth(routine));
}
diff --git a/src/components/AttachmentStorageSettings.tsx b/src/components/AttachmentStorageSettings.tsx
new file mode 100644
index 0000000000..2f687f7084
--- /dev/null
+++ b/src/components/AttachmentStorageSettings.tsx
@@ -0,0 +1,68 @@
+import { useEffect, useState } from "react";
+
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { api } from "@/state/store";
+import { SettingRow } from "./SettingsPrimitives";
+
+interface Usage { usedBytes: number; maxBytes: number }
+interface Cleared extends Usage { removed: number; freedBytes: number; failed: number }
+
+/** Whole MB, or KB below one MB so a small store or a small clear never reads as "0 MB". */
+const size = (bytes: number) => bytes === 0 || bytes >= 1024 * 1024 ? `${Math.round(bytes / (1024 * 1024))} MB` : `${Math.ceil(bytes / 1024)} KB`;
+
+/** Settings → General: how full the attachments store is, and a clear for when it is. Absent where the server has none
+ * (a Team Cloud, or a session that is not the owner's). */
+export function AttachmentStorageSettings() {
+ const [usage, setUsage] = useState<Usage | null>(null);
+ const [confirming, setConfirming] = useState(false);
+ const [clearing, setClearing] = useState(false);
+ const [result, setResult] = useState<{ kind: "success" | "error"; message: string } | null>(null);
+
+ useEffect(() => {
+ let live = true;
+ api("/api/attachment-storage").then((body) => { if (live) setUsage(body as Usage); }).catch(() => {});
+ return () => { live = false; };
+ }, []);
+ if (!usage) return null;
+
+ const clear = async () => {
+ setClearing(true);
+ setResult(null);
+ try {
+ const body = await api("/api/attachment-storage", { method: "POST" }) as Cleared;
+ setUsage(body);
+ const cleared = t("settings.attachments.cleared", { count: body.removed, freed: size(body.freedBytes) });
+ setResult(body.failed > 0
+ ? { kind: "error", message: `${cleared} ${t("settings.attachments.failed", { count: body.failed })}` }
+ : { kind: "success", message: cleared });
+ } catch (error) {
+ setResult({ kind: "error", message: error instanceof Error ? error.message : String(error) });
+ } finally {
+ setClearing(false);
+ setConfirming(false);
+ }
+ };
+
+ return (
+ <SettingRow
+ title={t("settings.attachments.title")}
+ subtitle={<>
+ <span data-attachments-used className="block">{t("settings.attachments.used", { used: size(usage.usedBytes), max: size(usage.maxBytes) })}</span>
+ <span className="block">{t(confirming ? "settings.attachments.confirmText" : "settings.attachments.help")}</span>
+ </>}
+ message={result && <p role={result.kind === "error" ? "alert" : "status"} className={cn(result.kind === "error" ? "text-danger" : "text-success")}>
+ {result.message}
+ </p>}
+ >
+ <div className="flex flex-wrap gap-2">
+ {confirming ? <>
+ <button type="button" onClick={() => setConfirming(false)} disabled={clearing} className="ui-button">{t("settings.attachments.cancel")}</button>
+ <button type="button" onClick={() => void clear()} disabled={clearing} className="ui-button text-danger">
+ {clearing ? t("settings.attachments.clearing") : t("settings.attachments.confirm")}
+ </button>
+ </> : <button type="button" onClick={() => { setResult(null); setConfirming(true); }} className="ui-button">{t("settings.attachments.clear")}</button>}
+ </div>
+ </SettingRow>
+ );
+}
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index d76900b7d5..730dfc94c6 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -13,6 +13,7 @@ import { UpdatesConsentRow } from "./UpdatesConsent";
import { OpenAtLoginRow } from "./OpenAtLoginRow";
import { DefaultBotSidebarRow } from "./DefaultBotControls";
import { TalkShortcutRow, talkShortcutKeywords } from "./TalkShortcutRow";
+import { AttachmentStorageSettings } from "./AttachmentStorageSettings";
import { DiagnosticsRow } from "./DiagnosticsRow";
import { DecisionModelSettings } from "./DecisionModelSettings";
import { EnginesSettings } from "./EnginesSettings";
@@ -85,7 +86,7 @@ export const SECTIONS: Array<{
icon: typeof User;
keywords: string[];
}> = [
- { id: "general", group: "you", labelKey: "settings.section.general", icon: User, keywords: ["profile", "pinned panels", "web panel", "dashboard", "pin a page", "name", "email", "about me", "about", "suggestions", "suggested", "memory", "analytics", "updates", "product updates", "newsletter", "email updates", "effort", "new bots", "reasoning", "threads", "parallel", "concurrency", "cleanup", "retention", "event log", "event-log", "log size", "automatic recovery", "backup model", "fallback", "routines", "conversation", "schedule", "usage", "limit", "plan", "upgrade", "cloud desktop hours", "storage", "saved steps", "repeat", "replay", "computer tasks", "without ai", "forget", ...talkShortcutKeywords()] },
+ { id: "general", group: "you", labelKey: "settings.section.general", icon: User, keywords: ["profile", "pinned panels", "web panel", "dashboard", "pin a page", "name", "email", "about me", "about", "suggestions", "suggested", "memory", "analytics", "updates", "product updates", "newsletter", "email updates", "effort", "new bots", "reasoning", "threads", "parallel", "concurrency", "cleanup", "retention", "attachments", "clear attachments", "event log", "event-log", "log size", "automatic recovery", "backup model", "fallback", "routines", "conversation", "schedule", "usage", "limit", "plan", "upgrade", "cloud desktop hours", "storage", "saved steps", "repeat", "replay", "computer tasks", "without ai", "forget", ...talkShortcutKeywords()] },
{ id: "appearance", group: "you", labelKey: "settings.section.appearance", icon: Palette, keywords: ["skin", "theme", "appearance", "chat width", "width", "wide", "full width", "bubble", "bubbles", "tools", "tool calls", "threads", "show threads", "hide threads", "sidebar", "display", "run", "this run", "run card", "commands", "notifications", "sound", "sounds", "mute", "silent", "chime", "pinned", "circles", "universal", "groups", "top", "send", "enter", "return", "shift+enter", "ctrl+enter", "cmd+enter", "⌘+enter", "new line", "keyboard", "ime", "japanese", "message color", "my messages", "toolbar", "tools layout", "footer", "routines", "triggers", "team map", "color", "colour", "cloud color", "server color", "tint", "sidebar color", "sidebar picture", "picture", "image", "banner", "background", "computers", "your computers", "rail", "strip", "frame", "window frame", "title bar"] },
{ id: "companion", group: "you", labelKey: "settings.section.companion", icon: TabletSmartphone, keywords: ["companion", "device", "phone", "desktop", "client", "host", "pair", "pairing", "mobile", "https", "secure", "tailscale", "wifi", "remote", "advanced", "domain", "dns", "self-hosted", "server", "caddy"] },
{ id: "engines", group: "ai", labelKey: "settings.section.engines", icon: Terminal, keywords: ["models", "model providers", "engines", "claude", "codex", "grok", "providers", "cli", "sign in", "subscription"] },
@@ -362,6 +363,7 @@ export function SettingsModal() {
<AutomaticRecoverySettings />
<ThreadCleanupSettings />
+ <AttachmentStorageSettings />
<PinnedPanelsSettings />
{!remoteActive && <ReplayTourRow />}
diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsx
index a16d785d3d..6bf810d1cf 100644
--- a/src/components/SettingsSimplePages.tsx
+++ b/src/components/SettingsSimplePages.tsx
@@ -9,6 +9,7 @@ import { UpdatesConsentRow } from "./UpdatesConsent";
import { OpenAtLoginRow } from "./OpenAtLoginRow";
import { DefaultBotSidebarRow } from "./DefaultBotControls";
import { TalkShortcutRow } from "./TalkShortcutRow";
+import { AttachmentStorageSettings } from "./AttachmentStorageSettings";
import { DiagnosticsRow } from "./DiagnosticsRow";
import { EnginesSettings } from "./EnginesSettings";
import { LocalComputerSection } from "./LocalComputerSection";
@@ -86,6 +87,7 @@ export function SimpleGeneralPage({ has, peopleOpen, onLooks }: { has: Has; peop
<OpenAtLoginRow simple />
<DefaultBotSidebarRow simple />
<TalkShortcutRow />
+ <AttachmentStorageSettings />
<AnalyticsRow simple />
</SettingsRows>
</SettingsGroup>
diff --git a/src/locales/en.json b/src/locales/en.json
index ba0e708772..3f32acb9e0 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2708,6 +2708,16 @@
"settings.threadCleanup.invalidCap": "Enter a size between 0.25 and 4096 MiB.",
"settings.threadCleanup.saving": "Saving…",
"settings.threadCleanup.error": "Could not save event log settings. Please try again.",
+ "settings.attachments.title": "Attachments",
+ "settings.attachments.used": "{used} of {max} used",
+ "settings.attachments.help": "Pictures and files added to chats are kept here. Clearing removes the ones older than 10 minutes; bot and profile pictures, the sidebar banner and files your routines use stay.",
+ "settings.attachments.confirmText": "Older messages will no longer show the files they had. This can't be undone.",
+ "settings.attachments.clear": "Clear attachments",
+ "settings.attachments.confirm": "Clear now",
+ "settings.attachments.cancel": "Cancel",
+ "settings.attachments.clearing": "Clearing…",
+ "settings.attachments.cleared": "Done. Files removed: {count} ({freed} freed).",
+ "settings.attachments.failed": "{count} could not be removed (in use or read-only). Try again later.",
"composer.queued.deleteAria": "Delete queued message {index} of {count}",
"composer.queued.deleteTitle": "Delete this queued message",
"composer.queued.editAria": "Edit queued message {index} of {count}",