Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Settings → Storage: what fills a Cloud's disk, and a quiet line at 80% and 90% (#7141)
Milind Soni4250c53a3acb
diff --git a/docs/pr-screenshots/storage-view/before-sidebar-full-daylight.png b/docs/pr-screenshots/storage-view/before-sidebar-full-daylight.pngnew file mode 100644index 0000000000..f8643c0d2fBinary files /dev/null and b/docs/pr-screenshots/storage-view/before-sidebar-full-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/before-sidebar-full-midnight.png b/docs/pr-screenshots/storage-view/before-sidebar-full-midnight.pngnew file mode 100644index 0000000000..0a2d69ce7eBinary files /dev/null and b/docs/pr-screenshots/storage-view/before-sidebar-full-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/settings-list-1440-daylight.png b/docs/pr-screenshots/storage-view/settings-list-1440-daylight.pngnew file mode 100644index 0000000000..6eea5ab8dcBinary files /dev/null and b/docs/pr-screenshots/storage-view/settings-list-1440-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/settings-list-1440-midnight.png b/docs/pr-screenshots/storage-view/settings-list-1440-midnight.pngnew file mode 100644index 0000000000..3c21dca4c8Binary files /dev/null and b/docs/pr-screenshots/storage-view/settings-list-1440-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/sidebar-80-1440-daylight-crop.png b/docs/pr-screenshots/storage-view/sidebar-80-1440-daylight-crop.pngnew file mode 100644index 0000000000..fc68b15ed8Binary files /dev/null and b/docs/pr-screenshots/storage-view/sidebar-80-1440-daylight-crop.png differdiff --git a/docs/pr-screenshots/storage-view/sidebar-80-1440-midnight-crop.png b/docs/pr-screenshots/storage-view/sidebar-80-1440-midnight-crop.pngnew file mode 100644index 0000000000..6ef6942af6Binary files /dev/null and b/docs/pr-screenshots/storage-view/sidebar-80-1440-midnight-crop.png differdiff --git a/docs/pr-screenshots/storage-view/sidebar-90-1440-daylight-crop.png b/docs/pr-screenshots/storage-view/sidebar-90-1440-daylight-crop.pngnew file mode 100644index 0000000000..586c11c7bfBinary files /dev/null and b/docs/pr-screenshots/storage-view/sidebar-90-1440-daylight-crop.png differdiff --git a/docs/pr-screenshots/storage-view/sidebar-90-1440-midnight-crop.png b/docs/pr-screenshots/storage-view/sidebar-90-1440-midnight-crop.pngnew file mode 100644index 0000000000..d74a604380Binary files /dev/null and b/docs/pr-screenshots/storage-view/sidebar-90-1440-midnight-crop.png differdiff --git a/docs/pr-screenshots/storage-view/storage-80-1440-daylight.png b/docs/pr-screenshots/storage-view/storage-80-1440-daylight.pngnew file mode 100644index 0000000000..db1b6718ecBinary files /dev/null and b/docs/pr-screenshots/storage-view/storage-80-1440-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-80-1440-midnight.png b/docs/pr-screenshots/storage-view/storage-80-1440-midnight.pngnew file mode 100644index 0000000000..99d87747feBinary files /dev/null and b/docs/pr-screenshots/storage-view/storage-80-1440-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-80-390-daylight.png b/docs/pr-screenshots/storage-view/storage-80-390-daylight.pngnew file mode 100644index 0000000000..ccd82636dfBinary files /dev/null and b/docs/pr-screenshots/storage-view/storage-80-390-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-80-390-midnight.png b/docs/pr-screenshots/storage-view/storage-80-390-midnight.pngnew file mode 100644index 0000000000..2ad1bf1b94Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-80-390-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-80-de-1440-midnight.png b/docs/pr-screenshots/storage-view/storage-80-de-1440-midnight.pngnew file mode 100644index 0000000000..b067f6c7c8Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-80-de-1440-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-90-1440-daylight.png b/docs/pr-screenshots/storage-view/storage-90-1440-daylight.pngnew file mode 100644index 0000000000..04bf637a62Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-90-1440-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-90-1440-midnight.png b/docs/pr-screenshots/storage-view/storage-90-1440-midnight.pngnew file mode 100644index 0000000000..4933c6de52Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-90-1440-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-90-ja-768-midnight.png b/docs/pr-screenshots/storage-view/storage-90-ja-768-midnight.pngnew file mode 100644index 0000000000..2ae85162a1Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-90-ja-768-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-first-open-1440-daylight.png b/docs/pr-screenshots/storage-view/storage-first-open-1440-daylight.pngnew file mode 100644index 0000000000..98d839deb7Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-first-open-1440-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-first-open-1440-midnight.png b/docs/pr-screenshots/storage-view/storage-first-open-1440-midnight.pngnew file mode 100644index 0000000000..7504222177Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-first-open-1440-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-normal-1440-daylight.png b/docs/pr-screenshots/storage-view/storage-normal-1440-daylight.pngnew file mode 100644index 0000000000..e7366eab94Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-normal-1440-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-normal-1440-midnight.png b/docs/pr-screenshots/storage-view/storage-normal-1440-midnight.pngnew file mode 100644index 0000000000..be4540e27dBinary files /dev/null and b/docs/pr-screenshots/storage-view/storage-normal-1440-midnight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-team-cloud-1440-daylight.png b/docs/pr-screenshots/storage-view/storage-team-cloud-1440-daylight.pngnew file mode 100644index 0000000000..e5d2c51eb7Binary files /dev/null and b/docs/pr-screenshots/storage-view/storage-team-cloud-1440-daylight.png differdiff --git a/docs/pr-screenshots/storage-view/storage-team-cloud-1440-midnight.png b/docs/pr-screenshots/storage-view/storage-team-cloud-1440-midnight.pngnew file mode 100644index 0000000000..27d04ee08eBinary files /dev/null and b/docs/pr-screenshots/storage-view/storage-team-cloud-1440-midnight.png differdiff --git a/electron/preload.cjs b/electron/preload.cjsindex 746e1fa067..a8f2497aa0 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -50,7 +50,7 @@ ipcRenderer.on("desktop-notifications:open", (_event, target) => {// Only fixed actions are retained, never a destination supplied by a renderer.const FIXED_SETTINGS_ACTIONS = new Set(["organization", "cloud", "cloud-settings", "cloud-add", "cloud-add-howto",- "overview", "devices", "phone", "ai", "bots", "desktops", "vault", "usage", "transfer", "data", "people", "installations", "account", "plan", "app", "general", "appearance"]);+ "overview", "devices", "phone", "ai", "bots", "desktops", "vault", "usage", "transfer", "storage", "data", "people", "installations", "account", "plan", "app", "general", "appearance"]);let pendingSettingsAction = null;const appSettingsListeners = new Set();ipcRenderer.on("app:open-settings", (_event, section) => {diff --git a/server/index.ts b/server/index.tsindex 98961d20b1..c0eb9ac604 100644--- a/server/index.ts+++ b/server/index.ts@@ -9373,7 +9373,7 @@ const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => waudit: (row) => appendDecision(DATA_DIR, { ...row, decision: "auto-approved", source: "routine" }) });tieAutomationsToBots(store, { routines: routines!, webhooks, apps: appTriggers.manager, waits: botWaits }); starterRoutineWake = createStarterRoutineWake({ awake: starterAwake, store, held: (botId) => botHolds.held(botId), routines: () => routines!.listRoutines(), triggers: () => [...webhooks.list(), ...appTriggers.manager.list()], busy: workInFlight({ conversations: (botId) => store.tasks(botId).map((task) => task.threadId), turnActive: (botId) => botHasActiveTurn(botId) || routines?.activeBotRunForBot(botId) != null, conversationBusy: (botId, threadId) => threadBusy(botId, threadId) || queuedThreadPosition(botId, threadId) !== null, coordinator, checkBacks: (botId, threadId) => checkBacks.list(botId, threadId).length, waits: (botId) => botWaits.list(botId).length }) });ROUTES.push(appTriggers.routes); ROUTES.unshift(createMoveFreezeRoutes({ freeze: moveFreeze, automationsOff: () => switchAutomationsOff({ routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }), restart: () => { restartRequested = true; gracefulShutdown(); }, busy: createMoveWaits({ bots: () => store.bots, rooms: () => store.groups, answering: (id) => watchdog.answering(id), turn: botHasActiveTurn, runs: () => routines?.listRuns() ?? [], roomWorking: (id) => { const group = store.group(id); return Boolean(group && groupIsWorking(group)); }, handoffs: () => coordinator.active(), exists: (node) => !(!node.parentId && node.groupId ? roomRootProblem(node) : roomHandoffProblem(node)), signingIn: () => providerAuthSessions.active }) }));-ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots, storage: perf.storage, launch: perf.noteLaunch })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,+ROUTES.push(createPerfDiagnosticsRoutes({ text: perf.text, bots: perf.bots, storage: perf.storage, serverId: ENVIRONMENT_ID, storageNow: perf.storageNow, storageMeasureInS: perf.storageMeasureInS, measureStorage: perf.measureStorage, launch: perf.noteLaunch })); ROUTES.push(createLimitResetRoutes({ clock: limitClock, routines: routines!, requests: routineRequests, engineName, threadEngine: (botId, threadId) => turnSelection(botId, threadId)?.instanceId,threadTitle: (botId, threadId) => store.bot(botId) && !store.bot(botId)!.hidden ? store.taskByThread(botId, threadId)?.title ?? null : null,created: (id, auth) => cloudRoutineAuthors?.wrote(id, auth.kind === "session" ? actorKey(auth) : CLOUD_NOBODY_KEY) }));diff --git a/server/perf/disk-usage.ts b/server/perf/disk-usage.tsindex a90598184f..21b98b523a 100644--- a/server/perf/disk-usage.ts+++ b/server/perf/disk-usage.ts@@ -50,6 +50,8 @@ export interface StorageReport {bots: Array<{ id: string } & Tally>;/** The other bot folders: bots not shown, and folders of ids the store does not know. */botsRest: Tally & { count: number };+ /** The part of `botsRest` in folders of ids the store does not know now: bots deleted since, mostly. */+ botsGone?: Tally & { count: number };other: { named: Array<{ name: string } & Tally>; unlisted: Tally & { entries: number } } | null;skipped: WalkSkipped | null;linksCapped: boolean;@@ -239,8 +241,11 @@ export function createDiskUsage(options: DiskUsageOptions) {const known = (id: string) => ID.test(id) && (() => { try { return options.knownBot?.(id) === true; } catch { return false; } })();const bots = [...totals?.bots ?? []].filter(([id]) => known(id)).sort(([, a], [, b]) => b.bytes - a.bytes);const shown = bots.slice(0, BOTS_SHOWN);- const rest = { bytes: 0, files: 0, count: 0 };- for (const [id, tally] of totals?.bots ?? []) if (!shown.some(([shownId]) => shownId === id)) { rest.bytes += tally.bytes; rest.files += tally.files; rest.count += 1; }+ const rest = { bytes: 0, files: 0, count: 0 }, gone = { bytes: 0, files: 0, count: 0 };+ for (const [id, tally] of totals?.bots ?? []) if (!shown.some(([shownId]) => shownId === id)) {+ rest.bytes += tally.bytes; rest.files += tally.files; rest.count += 1;+ if (!known(id)) { gone.bytes += tally.bytes; gone.files += tally.files; gone.count += 1; }+ }if (totals) { rest.bytes += totals.botsOverflow.bytes; rest.files += totals.botsOverflow.files; }const volume = last?.volume ?? null;return {@@ -258,6 +263,7 @@ export function createDiskUsage(options: DiskUsageOptions) {.filter((row) => row.bytes > 0 || row.files > 0).sort((a, b) => b.bytes - a.bytes) : [],bots: shown.map(([id, tally]) => ({ id, ...tally })),botsRest: rest,+ botsGone: gone,other: totals ? {named: [...totals.otherNamed].filter(([name]) => OTHER_NAMES.has(name)).sort(([, a], [, b]) => b.bytes - a.bytes).slice(0, OTHER_SHOWN).map(([name, tally]) => ({ name, ...tally })),unlisted: { ...totals.otherUnlisted },diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.tsindex f9abb3ac52..e5fb36385f 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -8,7 +8,8 @@ import type { StoreChange } from "../store.ts";import { createLoopStalls, requestArrivedBefore, type LoopStalls } from "./loop-stalls.ts";import { createBotFootprints, type BotCapReport, type BotFootprintReport, type BotFootprints, type FootprintOwner } from "./bot-footprint.ts";import { duration, limitHolds, perfHealth, perfLines, turnLine, type PerfHealth } from "./perf-report.ts";-import { createDiskUsage, type DiskUsage, type StorageReport } from "./disk-usage.ts";+import { createDiskUsage, type DiskUsage, type StorageReport, type VolumeBytes } from "./disk-usage.ts";+import { createStorageMeasure, readVolumeNow, type MeasureAnswer } from "./storage-measure.ts";import { createProcessHealth, type ProcessHealthRecorder } from "./process-health.ts";import type { ProcessRow } from "./process-buckets.ts";import { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilization, OTHER_SAMPLE_MS, psProcessList, type ProcessSampler } from "./process-sampler.ts";@@ -141,6 +142,7 @@ export function createPerfHost(deps: PerfHostDeps) {busy: () => timings.running(), knownBot: deps.storage.knownBot, file: join(deps.dataDir, STORAGE_FILE),progressFile: join(deps.dataDir, STORAGE_PROGRESS_FILE), now }) : null);if (deps.timer !== false) disk?.start();+ const measure = disk ? createStorageMeasure({ passNow: disk.passNow, tick: disk.tick, running: disk.running, lastPassAt: () => disk.report().at, now }) : null;if (deps.timer !== false && linux) guarded("limits", () => (deps.log ?? ((line: string) => console.warn(line)))(processes.startLine()), undefined);const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null), processes: processes.report(),@@ -165,6 +167,11 @@ export function createPerfHost(deps: PerfHostDeps) {health: (): PerfHealth | null => guarded("health", () => perfHealth(sources()), null),/** What fills the volume, from the last full pass; null where it is not measured or the report failed. */storage: (): StorageReport | null => guarded("storage", () => disk?.report() ?? null, null),+ /** The measured volume as it is now, for Settings → Storage; null where nothing is measured. */+ storageNow: (): Promise<VolumeBytes | null> => (deps.storage ? readVolumeNow(deps.storage.home) : Promise.resolve(null)),+ /** Seconds until the owner may ask for a pass; null where nothing is measured. */+ storageMeasureInS: (): number | null => guarded("storage", () => measure?.inS() ?? null, null),+ measureStorage: (): MeasureAnswer | null => guarded("storage", () => measure?.measure() ?? null, null),/** For a @devs report: these conversations' and bots' latest turns, then everything else. */lines(filter: { threadIds: readonly string[]; botIds: readonly string[] }): string[] {return stallsFirst(guarded("lines", () => perfLines(sources(), timings.recent({ ...filter, limit: RECENT_IN_REPORT }), "Latest turns in this conversation or of its bots, newest last:"), PERF_UNAVAILABLE));diff --git a/server/perf/storage-measure.test.ts b/server/perf/storage-measure.test.tsnew file mode 100644index 0000000000..7e2f29bdb2--- /dev/null+++ b/server/perf/storage-measure.test.ts@@ -0,0 +1,130 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { requiredScope, serviceAllowed } from "../request-auth.ts";+import { createPerfDiagnosticsRoutes, STORAGE_MEASURE_PATH, STORAGE_PATH } from "../routes/perf-diagnostics.ts";+import type { RouteContext } from "../routes/table.ts";+import type { StorageReport } from "./disk-usage.ts";+import { cloudStorage, createPerfHost } from "./perf-host.ts";+import { createStorageMeasure, MEASURE_GAP_MS, readVolumeNow } from "./storage-measure.ts";++const START = 1_800_000_000_000;+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function sampler() {+ let clock = START, running = false, lastPassAt: number | null = START - 3_600_000;+ const calls = { passNow: 0, tick: 0 };+ const measure = createStorageMeasure({+ passNow: () => { calls.passNow += 1; }, tick: async () => { calls.tick += 1; running = true; },+ running: () => running, lastPassAt: () => lastPassAt, now: () => clock,+ });+ return {+ measure, calls,+ advance: (ms: number) => { clock += ms; },+ finish: () => { running = false; lastPassAt = clock; },+ setLast: (at: number | null) => { lastPassAt = at; },+ };+}++describe("Measure again", () => {+ it("starts a pass at once, by asking for one and running the sampler's tick so a sleeping schedule wakes", () => {+ const s = sampler();+ expect(s.measure.inS()).toBe(0);+ expect(s.measure.measure()).toEqual({ started: true, running: true, inS: MEASURE_GAP_MS / 1000 });+ expect(s.calls).toEqual({ passNow: 1, tick: 1 });+ });++ it("never while a pass runs, and not again within the gap of the last pass's end or the last start asked for", () => {+ const s = sampler();+ s.measure.measure();+ expect(s.measure.measure()).toMatchObject({ started: false, running: true });+ s.advance(60_000);+ s.finish();+ expect(s.measure.measure()).toEqual({ started: false, running: false, inS: MEASURE_GAP_MS / 1000 });+ s.advance(MEASURE_GAP_MS - 1_000);+ expect(s.measure.inS()).toBe(1);+ s.advance(1_000);+ expect(s.measure.measure().started).toBe(true);+ expect(s.calls.passNow).toBe(2);+ });++ it("counts from the last start asked for when the pass it asked for has not ended yet", () => {+ const s = sampler();+ s.setLast(null);+ s.measure.measure();+ s.finish();+ s.setLast(null);+ s.advance(MEASURE_GAP_MS / 2);+ expect(s.measure.inS()).toBe(MEASURE_GAP_MS / 2000);+ });+});++describe("the volume now", () => {+ it("reads used and free as the report does, and null when the filesystem can't be read", async () => {+ expect(await readVolumeNow("/data", async () => ({ blocks: 1_000, bsize: 4096, bavail: 300, bfree: 350 })))+ .toEqual({ totalBytes: 4_096_000, freeBytes: 1_228_800, usedBytes: 2_662_400 });+ expect(await readVolumeNow("/data", async () => { throw new Error("EIO"); })).toBeNull();+ });+});++describe("the storage routes", () => {+ const report = { v: 1, at: START, running: false } as unknown as StorageReport;+ async function call(method: "GET" | "POST", path: string, deps: Parameters<typeof createPerfDiagnosticsRoutes>[0]) {+ let answered: { status: number; body: unknown } | null = null;+ await createPerfDiagnosticsRoutes(deps)({+ req: {} as RouteContext["req"], res: { setHeader: () => undefined } as unknown as RouteContext["res"], url: new URL(`http://x${path}`), path, method,+ auth: {} as RouteContext["auth"], json: ((_res: unknown, status: number, body: unknown) => { answered = { status, body }; }) as unknown as RouteContext["json"],+ readBody: (async () => null) as unknown as RouteContext["readBody"],+ });+ return answered as { status: number; body: unknown } | null;+ }+ const volume = { totalBytes: 100, freeBytes: 10, usedBytes: 90 };++ it("GET carries the volume now and when a pass may be asked for beside the report, only where there is a report", async () => {+ const deps = { text: () => "", storage: () => report, storageNow: async () => volume, storageMeasureInS: () => 0 };+ expect(await call("GET", STORAGE_PATH, deps)).toEqual({ status: 200, body: { storage: report, now: volume, measureInS: 0 } });+ expect(await call("GET", STORAGE_PATH, { ...deps, storage: () => null })).toEqual({ status: 200, body: { storage: null } });+ expect(await call("GET", STORAGE_PATH, { ...deps, storageNow: async () => { throw new Error("EIO"); } })).toEqual({ status: 200, body: { storage: report, now: null, measureInS: 0 } });+ expect(await call("GET", STORAGE_PATH, { ...deps, serverId: "env-a" })).toEqual({ status: 200, body: { storage: report, now: volume, measureInS: 0, server: "env-a" } });+ });++ it("POST asks for a pass, and is 404 where nothing is measured", async () => {+ const answer = { started: true, running: true, inS: 600 };+ expect(await call("POST", STORAGE_MEASURE_PATH, { text: () => "", measureStorage: () => answer })).toEqual({ status: 200, body: answer });+ expect((await call("POST", STORAGE_MEASURE_PATH, { text: () => "" }))?.status).toBe(404);+ });++ it("is admin scope: a Team Cloud member's session and a service caller never reach either", () => {+ expect(requiredScope("POST", STORAGE_MEASURE_PATH)).toBe("admin");+ expect(serviceAllowed("POST", STORAGE_MEASURE_PATH)).toBe(false);+ expect(requiredScope("GET", STORAGE_PATH)).toBe("admin");+ });+});++describe("on a Cloud home's perf host", () => {+ it("Measure again runs a pass now, and the report keeps a deleted bot's leftovers apart from the bots it lists", async () => {+ const home = mkdtempSync(join(tmpdir(), "storage-measure-"));+ dirs.push(home);+ const data = join(home, ".openmausbot");+ const write = (path: string, bytes: number) => { mkdirSync(join(path, ".."), { recursive: true }); writeFileSync(path, Buffer.alloc(bytes, 7)); };+ write(join(data, "workspaces", "bot-known", "notes.md"), 8_000);+ write(join(data, "workspaces", "bot-gone", "old.txt"), 3_000);+ const host = createPerfHost({ dataDir: data, timer: false, wholeMachine: true, bus: { subscribe: () => () => {} }, store: { onChange: () => () => {}, botByThread: () => null },+ now: () => START, ...cloudStorage({}, home, (id) => id === "bot-known") });+ expect(host.storage()).toMatchObject({ at: null, running: false });+ expect(host.storageMeasureInS()).toBe(0);+ expect(host.measureStorage()).toMatchObject({ started: true });+ for (let index = 0; index < 2_000 && host.storage()?.at === null; index++) await new Promise((resolve) => setTimeout(resolve, 10));+ const report = host.storage()!;+ expect(report.at).toBe(START);+ expect(report.bots.map((bot) => bot.id)).toEqual(["bot-known"]);+ expect(report.botsGone).toMatchObject({ count: 1, files: 1 });+ expect(report.botsGone!.bytes).toBeGreaterThanOrEqual(3_000);+ expect(host.measureStorage()).toMatchObject({ started: false, inS: MEASURE_GAP_MS / 1000 });+ expect(await host.storageNow()).toMatchObject({ totalBytes: expect.any(Number), freeBytes: expect.any(Number) });+ host.stop();+ });+});diff --git a/server/perf/storage-measure.ts b/server/perf/storage-measure.tsnew file mode 100644index 0000000000..db0f80be0b--- /dev/null+++ b/server/perf/storage-measure.ts@@ -0,0 +1,58 @@+// What Settings → Storage reads beside the storage report: the volume as it is now (the report's figures are from the end of+// the last pass, up to PASS_EVERY_MS old), and "Measure again", a pass started on the owner's word at most once per+// MEASURE_GAP_MS, counted from the last pass's end or the last start asked for, whichever is later.+import { statfs as nodeStatfs } from "node:fs/promises";++import type { VolumeBytes } from "./disk-usage.ts";++export const MEASURE_GAP_MS = 10 * 60_000;++type Statfs = (path: string) => Promise<{ blocks: number; bsize: number; bavail: number; bfree: number }>;++/** The volume holding `path` now; null when the filesystem can't be read. */+export async function readVolumeNow(path: string, statfs: Statfs = nodeStatfs): Promise<VolumeBytes | null> {+ try {+ const stats = await statfs(path);+ return { totalBytes: stats.blocks * stats.bsize, freeBytes: stats.bavail * stats.bsize, usedBytes: (stats.blocks - stats.bfree) * stats.bsize };+ } catch {+ return null;+ }+}++export interface StorageMeasureDeps {+ /** The sampler's own: a pass is due at its next tick. */+ passNow(): void;+ /** Runs that tick now, so a sampler sleeping until its next scheduled pass starts this one. */+ tick(): Promise<void>;+ running(): boolean;+ /** When the last full pass ended; null before the first. */+ lastPassAt(): number | null;+ now?: () => number;+ gapMs?: number;+}++export interface MeasureAnswer { started: boolean; running: boolean; inS: number }++export function createStorageMeasure(deps: StorageMeasureDeps) {+ const now = deps.now ?? Date.now;+ const gapMs = deps.gapMs ?? MEASURE_GAP_MS;+ let askedAt: number | null = null;+ /** Seconds until a pass may be asked for: 0 now, never while one runs (its end restarts the wait). */+ const inS = (): number => {+ if (deps.running()) return Math.ceil(gapMs / 1000);+ const since = Math.max(deps.lastPassAt() ?? -Infinity, askedAt ?? -Infinity);+ return Math.max(0, Math.ceil((since + gapMs - now()) / 1000));+ };+ return {+ inS,+ measure(): MeasureAnswer {+ const wait = inS();+ if (wait > 0) return { started: false, running: deps.running(), inS: wait };+ askedAt = now();+ deps.passNow();+ void deps.tick().catch(() => {});+ return { started: true, running: true, inS: Math.ceil(gapMs / 1000) };+ },+ };+}+export type StorageMeasure = ReturnType<typeof createStorageMeasure>;diff --git a/server/routes/perf-diagnostics.ts b/server/routes/perf-diagnostics.tsindex 479d209cea..72ffdad03f 100644--- a/server/routes/perf-diagnostics.ts+++ b/server/routes/perf-diagnostics.ts@@ -1,21 +1,38 @@// GET /api/diagnostics/performance: the performance recorder's plain lines for the desktop's diagnostics export.// GET /api/diagnostics/bots: every bot's processes, threads, memory and CPU at the last sample (perf/bot-footprint.ts), bot-// ids and numbers only. GET /api/diagnostics/storage: what fills a Cloud home's volume (perf/disk-usage.ts), null elsewhere. POST /api/diagnostics/launch: the desktop app's main process and its page each hand in their part+// ids and numbers only. GET /api/diagnostics/storage: what fills a Cloud home's volume (perf/disk-usage.ts), null elsewhere, with the+// volume as it is now and when the owner may ask for a pass; POST /api/diagnostics/storage/measure asks for one. POST /api/diagnostics/launch: the desktop app's main process and its page each hand in their part// of the launch record (perf/launch-timings.ts), which keeps only checked numbers and fixed codes. All admin scope (request-auth's default), so on a Cloud home a bot's shell, a service-trust// loopback caller, never reaches them.import type { BotFootprintReport } from "../perf/bot-footprint.ts";-import type { StorageReport } from "../perf/disk-usage.ts";+import type { StorageReport, VolumeBytes } from "../perf/disk-usage.ts";+import type { MeasureAnswer } from "../perf/storage-measure.ts";import { PASS, type RouteHandler } from "./table.ts";export const PERF_DIAGNOSTICS_PATH = "/api/diagnostics/performance";export const BOT_FOOTPRINT_PATH = "/api/diagnostics/bots";export const STORAGE_PATH = "/api/diagnostics/storage";+export const STORAGE_MEASURE_PATH = "/api/diagnostics/storage/measure";export const LAUNCH_PATH = "/api/diagnostics/launch";const LAUNCH_BODY_MAX = 16 * 1024;-export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): BotFootprintReport | null; storage?(): StorageReport | null; launch?(part: unknown): { ok: boolean; complete: boolean } | null }): RouteHandler {+export interface StorageViewDeps {+ /** This server's environment id (already public at /.well-known/openmausbot/environment): the app keys what it remembers+ * of a storage answer by it, so two Clouds never share a "seen" mark or numbers. */+ serverId?: string;+ storageNow?(): Promise<VolumeBytes | null>;+ storageMeasureInS?(): number | null;+ measureStorage?(): MeasureAnswer | null;+}++export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): BotFootprintReport | null; storage?(): StorageReport | null; launch?(part: unknown): { ok: boolean; complete: boolean } | null } & StorageViewDeps): RouteHandler {return async ({ req, res, path, method, json, readBody }) => {+ if (method === "POST" && path === STORAGE_MEASURE_PATH) {+ res.setHeader("cache-control", "no-store");+ const answer = deps.measureStorage?.() ?? null;+ return json(res, answer ? 200 : 404, answer ?? { started: false, running: false, inS: 0 });+ }if (method === "POST" && path === LAUNCH_PATH) {res.setHeader("cache-control", "no-store");const noted = deps.launch ? deps.launch(await readBody(req, LAUNCH_BODY_MAX).catch(() => null)) : null;@@ -24,7 +41,13 @@ export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): Botif (method !== "GET" || (path !== PERF_DIAGNOSTICS_PATH && path !== BOT_FOOTPRINT_PATH && path !== STORAGE_PATH)) return PASS;res.setHeader("cache-control", "no-store");if (path === BOT_FOOTPRINT_PATH) return json(res, 200, { bots: deps.bots?.() ?? null });- if (path === STORAGE_PATH) return json(res, 200, { storage: deps.storage?.() ?? null });+ if (path === STORAGE_PATH) return json(res, 200, await storageBody(deps));return json(res, 200, { text: deps.text() });};}++async function storageBody(deps: { storage?(): StorageReport | null } & StorageViewDeps) {+ const storage = deps.storage?.() ?? null;+ if (!storage || !deps.storageNow) return { storage };+ return { storage, now: await deps.storageNow().catch(() => null), measureInS: deps.storageMeasureInS?.() ?? null, ...(deps.serverId ? { server: deps.serverId } : {}) };+}diff --git a/shared/settings-places.ts b/shared/settings-places.tsindex 4c649500eb..92898978c0 100644--- a/shared/settings-places.ts+++ b/shared/settings-places.ts@@ -23,6 +23,7 @@ export const SETTINGS_PLACES = [{"id":"page:vault","path":"Settings → Vault","words":["vault","password","passwords","login","logins","secrets","1password","2fa"]},{"id":"page:usage","path":"Settings → Spending","words":["spending","usage","cost","costs","tokens","money","runs","export csv"]},{"id":"page:transfer","path":"Settings → Import & export","words":["import","export","backup","backups","restore","grok","grok bot","move from","bring"]},+ {"id":"page:storage","path":"Settings → Storage","words":["storage","disk","disk space","space","full","free space","volume","what uses space","cache","downloads"],"only":"a MausBot Cloud's Settings, for its owner or admins"},{"id":"page:data","path":"Settings → Data","words":["data","storage","attachments","activity","audit"],"advanced":true},{"id":"page:people","path":"Settings → People","words":["people","members","invite","roles","bot access","sharing","team"],"only":"a team's or a self-hosted server's Settings, for admins"},{"id":"page:installations","path":"Settings → Installations","words":["installations","fleet","clients","tenants"],"only":"a server that manages installations"},diff --git a/src/components/SidebarFooter.tsx b/src/components/SidebarFooter.tsxindex 4f6290377f..63fdf4acb9 100644--- a/src/components/SidebarFooter.tsx+++ b/src/components/SidebarFooter.tsx@@ -11,6 +11,7 @@ import { endCloudHowTo, useWorkspacePlace, type WorkspacePlace } from "./Desktopimport { SidebarConnectApps } from "./SidebarConnectApps";import { SidebarBottomButtons, SidebarFooterNav } from "./SidebarFooterNav";import { phoneSettingsAction, SidebarPhoneButton } from "./SidebarPhoneButton";+import { StorageNotice } from "./StorageNotice";import { SidebarProfileMenu, useSimpleAccount, type ArchivedBots } from "./SidebarProfileMenu";import { UpdateIndicator } from "./UpdateIndicator";@@ -38,6 +39,7 @@ function SimpleSidebarFooter({ owner, archived }: { owner: string | null; archiv<CloudRoomCard /><CloudUsageCard /><SidebarPlaceStatus place={place} className="mb-2 px-1" />+ <StorageNotice className="mb-2 px-1" /><AccountMoveStatus kind={move.kind} place={move.place} retry={move.retry} onOpen={openAccount} className="ps-1" /><div className="flex items-center gap-2 not-first:mt-2"><SidebarProfileMenu simple={account} />@@ -73,6 +75,7 @@ export function SidebarFooter({ density, simple = false, owner = null, archived,<><CloudRoomCard /><CloudUsageCard />+ <StorageNotice className="px-2" /><div className="flex items-center gap-1 not-first:mt-3"><div className="min-w-0 flex-1"><SidebarProfileMenu />diff --git a/src/components/StorageNotice.dom.test.ts b/src/components/StorageNotice.dom.test.tsnew file mode 100644index 0000000000..e0d7f63a07--- /dev/null+++ b/src/components/StorageNotice.dom.test.ts@@ -0,0 +1,190 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({+ admin: true as boolean | null,+ usedGb: 50,+ room: null as null | { id: string; cause: { kind: "disk" | "memory" } },+ dispatch: (() => {}) as (action: unknown) => void,+ reads: [] as Array<{ path: string; background?: boolean }>,+ server: "env-a",+ gate: null as Promise<void> | null,+}));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));+vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => fixture.dispatch }));+vi.mock("./CloudRoomCard", () => ({ useCloudRoom: () => ({ snapshot: fixture.room ? { status: "paid", room: fixture.room } : null, bridge: undefined, teamHome: false }) }));+vi.mock("@/state/api", () => ({+ api: async (path: string, init?: { background?: boolean }) => {+ fixture.reads.push({ path, background: init?.background });+ if (fixture.gate) await fixture.gate;+ const { storageReport, GB } = await import("@/lib/storage-report-fixture");+ return { storage: storageReport(), now: { totalBytes: 100 * GB, freeBytes: (100 - fixture.usedGb) * GB, usedBytes: fixture.usedGb * GB }, measureInS: 0, server: fixture.server };+ },+}));++import { setLocale } from "@/lib/i18n";+import { readStorageSeen } from "@/lib/storage-report";+import { forgetStorageReport, rememberStorageSeen } from "@/lib/use-storage-report";+import { StorageNotice } from "./StorageNotice";++let container: HTMLDivElement, root: Root;+beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ setLocale("en");+ localStorage.clear();+ forgetStorageReport();+ Object.assign(fixture, { admin: true, usedGb: 50, room: null, reads: [], dispatch: vi.fn(), server: "env-a", gate: null });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.useRealTimers(); vi.unstubAllGlobals(); });++/** A launch: the sidebar mounts, waits its few seconds, reads once. */+async function launch() {+ await act(async () => { root.render(createElement(StorageNotice)); });+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });+ await answered();+}+/** The read's answer reaches the page. */+async function answered() {+ await act(async () => { await vi.dynamicImportSettled(); });+ for (let i = 0; i < 5; i++) await act(async () => { await Promise.resolve(); });+}+/** The half-hourly read, with usage at `usedGb`. */+async function later(usedGb: number) {+ fixture.usedGb = usedGb;+ await act(async () => { await vi.advanceTimersByTimeAsync(30 * 60_000); });+ await answered();+}+async function relaunch() {+ await act(async () => root.unmount());+ forgetStorageReport();+ root = createRoot(container);+ await launch();+}+const line = () => container.querySelector<HTMLElement>("[data-storage-notice]");+const A = "server:env-a";++describe("the sidebar's storage line", () => {+ it("says nothing under 80%, reading in the background a few seconds after launch and never before", async () => {+ await act(async () => { root.render(createElement(StorageNotice)); });+ expect(fixture.reads).toEqual([]);+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });+ expect(fixture.reads).toEqual([{ path: "/api/diagnostics/storage", background: true }]);+ expect(line()).toBeNull();+ });++ it("at 80% is one quiet line that takes no focus, and opens Settings → Storage only when clicked", async () => {+ fixture.usedGb = 82;+ const before = document.activeElement;+ await launch();+ expect(line()?.dataset.storageNotice).toBe("near");+ expect(line()?.getAttribute("role")).toBe("status");+ expect(line()?.textContent).toBe("Storage 82% full");+ expect(document.activeElement).toBe(before);+ expect(document.querySelector('[role="dialog"], [role="alertdialog"], [role="alert"]')).toBeNull();+ expect(fixture.dispatch).not.toHaveBeenCalled();+ line()!.querySelector("button")!.click();+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "toggleAppSettings", open: true, section: "storage" });+ });++ it("shown for one launch is seen: never on the launches after, though nobody clicked it", async () => {+ fixture.usedGb = 83;+ await launch();+ expect(line()?.dataset.storageNotice).toBe("near");+ await later(85);+ expect(line(), "stays through the launch it appeared in").not.toBeNull();+ await relaunch();+ expect(line()).toBeNull();+ await relaunch();+ expect(line()).toBeNull();+ });++ it("once seen at a line, stays away on every launch after, comes back at 90%, and once more only after usage falls well under", async () => {+ fixture.usedGb = 83;+ await launch();+ expect(line()).not.toBeNull();+ // Opening Settings → Storage sees it at once.+ await act(async () => { rememberStorageSeen(A, "near"); });+ expect(line()).toBeNull();+ await relaunch();+ expect(line()).toBeNull();+ await later(88);+ expect(line()).toBeNull();+ await later(91);+ expect(line()?.dataset.storageNotice).toBe("full");+ await relaunch();+ expect(line()).toBeNull();+ await later(78);+ expect(line()).toBeNull();+ expect(readStorageSeen(A)).toBe("near");+ await later(81);+ expect(line()).toBeNull();+ await later(70);+ expect(readStorageSeen(A)).toBeNull();+ await later(80);+ expect(line()?.dataset.storageNotice).toBe("near");+ });++ it("keeps each Cloud's seen mark apart: one Cloud's line seen never hides another's, on the same page origin", async () => {+ fixture.usedGb = 84;+ await launch();+ expect(line()?.dataset.storageNotice).toBe("near");+ await relaunch();+ expect(line(), "seen on this Cloud").toBeNull();+ fixture.server = "env-b";+ await relaunch();+ expect(line()?.dataset.storageNotice, "the other Cloud says it once too").toBe("near");+ expect(readStorageSeen(A)).toBe("near");+ expect(readStorageSeen("server:env-b")).toBe("near");+ fixture.server = "env-a";+ await relaunch();+ expect(line()).toBeNull();+ });++ it("an answer to a read from before the page forgot what it knew (another server) never shows", async () => {+ fixture.usedGb = 92;+ let release!: () => void;+ fixture.gate = new Promise((resolve) => { release = resolve; });+ await act(async () => { root.render(createElement(StorageNotice)); });+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });+ expect(fixture.reads).toHaveLength(1);+ await act(async () => { forgetStorageReport(); release(); });+ await answered();+ expect(line()).toBeNull();+ });++ it("clears when usage drops under 80%", async () => {+ fixture.usedGb = 85;+ await launch();+ expect(line()).not.toBeNull();+ await later(60);+ expect(line()).toBeNull();+ });++ it("keeps out of the way of the Admin's own disk card, and shows once that card was put away", async () => {+ fixture.usedGb = 92;+ fixture.room = { id: "offer-9", cause: { kind: "disk" } };+ await launch();+ expect(line()).toBeNull();+ localStorage.setItem("openmausbot.roomCard.hidden.v1", "offer-9");+ await relaunch();+ expect(line()?.dataset.storageNotice).toBe("full");+ // Amber, not red, even at 90%: the avatar's red dot sits right under this line.+ expect(line()!.querySelector("button")!.className).toContain("text-warning");+ expect(line()!.querySelector("button")!.className).not.toContain("text-danger");+ });++ it("a team member who is not an admin sends nothing and sees nothing", async () => {+ fixture.admin = false;+ fixture.usedGb = 95;+ await launch();+ await later(95);+ expect(fixture.reads).toEqual([]);+ expect(line()).toBeNull();+ });+});diff --git a/src/components/StorageNotice.tsx b/src/components/StorageNotice.tsxnew file mode 100644index 0000000000..dd20ad1daa--- /dev/null+++ b/src/components/StorageNotice.tsx@@ -0,0 +1,69 @@+import { useEffect } from "react";+import { HardDrive } from "lucide-react";++import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { readRoomCardHidden } from "@/lib/room-card";+import { settleSeen, storageBand, storageFullness, storageNotice, storageScope } from "@/lib/storage-report";+import { markStorageNoticeShown, rememberStorageSeen, storageNoticeShownThisLaunch, useStorageReport, useStorageSeen } from "@/lib/use-storage-report";+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";+import { useStoreDispatch } from "@/state/store-select";+import { useCloudRoom } from "./CloudRoomCard";++/** The sidebar reads the report a little after launch, then this often: the report itself changes every few hours. */+const FIRST_READ_MS = 5_000;+const READ_EVERY_MS = 30 * 60_000;++/** One quiet line where the sidebar's foot already says how this place is doing: never a card, a pop-up or a sound. Amber at+ * both lines (90% and over in medium weight): the avatar's red dot sits right under it, and two reds would stack. Settings →+ * Storage keeps red for 90% and over. */+export function StorageNoticeLine({ band, percent, onOpen, className }: { band: "near" | "full"; percent: number; onOpen: () => void; className?: string }) {+ const words = t("storageNotice.line", { percent: String(percent) });+ return (+ <div role="status" data-storage-notice={band} className={cn("flex min-w-0", className)}>+ <button type="button" onClick={onOpen} title={t("storageNotice.open")}+ className={cn("flex min-w-0 items-center gap-1.5 rounded-md text-start text-[12px] leading-4 focus-visible:outline-2 focus-visible:outline-focus",+ "text-warning hover:underline", band === "full" && "font-medium")}>+ <HardDrive size={13} aria-hidden="true" className="shrink-0" />+ <span className="truncate">{words}</span>+ </button>+ </div>+ );+}++/** The Admin's own disk card (with its Upgrade) says the same thing: while it is up, this line keeps out of its way. */+function useRoomCardOnDisk(): boolean {+ const { snapshot } = useCloudRoom();+ const room = snapshot?.status === "paid" ? snapshot.room : null;+ return Boolean(room && room.cause.kind === "disk" && readRoomCardHidden() !== room.id);+}++function Shown({ scope, band, percent, className }: { scope: string; band: "near" | "full"; percent: number; className?: string }) {+ const dispatch = useStoreDispatch();+ const yielded = useRoomCardOnDisk();+ useEffect(() => { if (!yielded) markStorageNoticeShown(scope, band); }, [yielded, scope, band]);+ if (yielded) return null;+ return <StorageNoticeLine band={band} percent={percent} className={className} onOpen={() => dispatch({ type: "toggleAppSettings", open: true, section: "storage" })} />;+}++/** At 80% and again at 90% full, once per crossing: shown for one launch (or until Settings → Storage is opened), and back only+ * after usage falls well under the line and crosses it again. Only an owner or admin, never a paired client, reads the report. */+export function StorageNotice({ className }: { className?: string }) {+ const admin = useOwnerOrAdmin() === true;+ const client = typeof window !== "undefined" && window.ogb?.remoteClient?.active === true;+ const read = useStorageReport({ enabled: admin && !client, delayMs: FIRST_READ_MS, everyMs: READ_EVERY_MS, background: true });+ const answer = read.status === "ready" ? read.answer : null;+ const scope = answer ? storageScope(answer) : null;+ const seen = useStorageSeen(scope);+ const percent = answer ? storageFullness(answer)?.percent ?? null : null;+ useEffect(() => {+ if (percent === null || scope === null) return;+ const settled = settleSeen(seen, percent);+ if (settled !== seen) rememberStorageSeen(scope, settled);+ }, [percent, seen, scope]);+ const fresh = storageNotice(percent, seen);+ const kept = scope === null ? null : storageNoticeShownThisLaunch(scope);+ const band = fresh ?? (percent !== null && kept !== null && kept !== "ok" && storageBand(percent) === kept ? kept : null);+ if (!band || percent === null || scope === null) return null;+ return <Shown scope={scope} band={band} percent={percent} className={className} />;+}diff --git a/src/components/settings/SettingsNav.tsx b/src/components/settings/SettingsNav.tsxindex b569a74ecc..56714ff197 100644--- a/src/components/settings/SettingsNav.tsx+++ b/src/components/settings/SettingsNav.tsx@@ -320,13 +320,13 @@ function HitRow({ ctx, place, hit, query, onHit }: { ctx: SettingsContext; place}const PAGE_OWNER: Record<SettingsPageId, SettingsOwner> = {- overview: "place", devices: "place", phone: "place", ai: "place", bots: "place", desktops: "place", vault: "place", usage: "place", transfer: "place", data: "place",- people: "place", installations: "place", account: "account", plan: "account", app: "app", general: "app", appearance: "app",+ overview: "place", devices: "place", phone: "place", ai: "place", bots: "place", desktops: "place", vault: "place", usage: "place", transfer: "place", storage: "place",+ data: "place", people: "place", installations: "place", account: "account", plan: "account", app: "app", general: "app", appearance: "app",};const PAGE_KEY: Partial<Record<SettingsPageId, Parameters<typeof t>[0]>> = {devices: "settings.page.devices", phone: "settings.section.phoneDevices", ai: "settings.group.ai", bots: "settings.page.bots", desktops: "settings.page.desktops",- vault: "settings.section.vault", usage: "settings.page.spending", transfer: "settings.page.importExport", data: "settings.page.data", people: "settings.section.people",+ vault: "settings.section.vault", usage: "settings.page.spending", transfer: "settings.page.importExport", storage: "settings.page.storage", data: "settings.page.data", people: "settings.section.people",installations: "settings.section.workspaces", plan: "settings.page.plan", general: "settings.section.general", appearance: "settings.section.appearance",};diff --git a/src/components/settings/StoragePage.dom.test.ts b/src/components/settings/StoragePage.dom.test.tsnew file mode 100644index 0000000000..b5cabf55d8--- /dev/null+++ b/src/components/settings/StoragePage.dom.test.ts@@ -0,0 +1,129 @@+// @vitest-environment happy-dom+// The real provider and the real Settings window in a browser tab, against a server that answers the storage route as a+// Cloud home, a person's own computer, an older Cloud or a refusal would: who gets a Storage page, and who never asks.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";++import { GB, storageReport } from "@/lib/storage-report-fixture";++class FixtureEventSource {+ static opened: FixtureEventSource[] = [];+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }+ close() {}+ send(frame: object) { this.onmessage?.({ data: JSON.stringify(frame) }); }+}++const STORAGE = "/api/diagnostics/storage";+const CONFIG = {+ composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" },+ rooms: { turnTimeoutMinutes: 10 }, localVm: { mode: "shared", maxInstances: 1 },+ profile: { name: "Ada", email: "[email protected]" }, features: { savedSteps: false },+ onboarding: { completedAt: "2026-01-01", version: 1, reelSeen: true, hintsSeen: [] },+ edition: { edition: "community", features: [] }, browserProfiles: [], managedPolicy: null,+ signIn: { admins: [], members: [] }, membership: { authority: "local", pairingCodes: true }, cloudHome: true,+};+const session = (scopes: string[]) => ({ kind: "session", id: "s1", label: "Chrome on Mac", email: "[email protected]", scopes, expiresAt: 0 });+const ADMIN = session(["admin", "client"]);+const REPORT = { storage: storageReport(), now: { totalBytes: 100 * GB, freeBytes: 15 * GB, usedBytes: 85 * GB }, measureInS: 0, server: "env-a" };++let root: Root | null = null;+const requests: string[] = [];+const task = () => new Promise((resolve) => setTimeout(resolve, 0));+const settle = async () => { for (let i = 0; i < 25; i++) await task(); };++afterEach(() => {+ root?.unmount();+ root = null;+ document.body.innerHTML = "";+ localStorage.clear();+ vi.unstubAllGlobals();+});++/** Settings opened on `section`, with the server answering `storage` (a status code for a refusal) to the storage route. */+async function openSettings({ storage, sessionAnswer = ADMIN, config = CONFIG, section = "overview", bots = [{ id: "chief", name: "Chief", threadId: "t1" }] }: {+ storage: unknown; sessionAnswer?: object; config?: object; section?: string; bots?: object[];+}) {+ vi.resetModules();+ requests.length = 0;+ FixtureEventSource.opened = [];+ const answers: Record<string, unknown> = {+ "/api/instances": { instances: [] }, "/api/config": config, "/api/auth/session": sessionAnswer,+ "/api/auth/sessions": { sessions: [{ id: "s1" }], current: "s1" }, "/api/routines": { routines: [], runs: [] },+ "/api/webhooks": { webhooks: [], attempts: [] }, "/api/bots": { bots, groups: [] },+ };+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", (input: string | URL | Request, init?: RequestInit) => {+ const path = String(input instanceof Request ? input.url : input).replace(/^https?:\/\/[^/]+/, "").replace(/\?.*$/, "");+ requests.push(`${init?.method ?? "GET"} ${path}`);+ if (path === STORAGE && typeof storage === "number") return Promise.resolve(new Response(JSON.stringify({ error: "no" }), { status: storage }));+ return Promise.resolve(new Response(JSON.stringify(path === STORAGE ? storage : answers[path] ?? {})));+ });+ const { StoreProvider, useStore } = await import("@/state/store");+ const { SettingsModal } = await import("../SettingsModal");+ let dispatch!: (action: never) => void;+ function Probe() {+ const store = useStore();+ dispatch = store.dispatch as never;+ return store.state.appSettingsOpen ? createElement(SettingsModal) : null;+ }+ const container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root!.render(createElement(StoreProvider, null, createElement(Probe))));+ await settle();+ FixtureEventSource.opened[0]?.send({ kind: "hello", resumed: false, cursor: "run:0" });+ await settle();+ flushSync(() => dispatch({ type: "toggleAppSettings", open: true, section } as never));+ await settle();+}+const storageInNav = () => document.querySelector("button[data-settings-page='storage']");+const storageReads = () => requests.filter((request) => request === `GET ${STORAGE}`).length;++describe("who gets Settings → Storage", () => {+ it("an owner or admin of a Cloud home: Storage is in the list, and opens on how full it is and its largest bots", async () => {+ await openSettings({ storage: REPORT, section: "storage" });+ expect(storageInNav()?.textContent).toContain("Storage");+ expect(document.querySelector("[data-settings-page-body='storage']")).not.toBeNull();+ expect(document.querySelector("[data-storage-summary]")?.getAttribute("data-band")).toBe("near");+ expect(document.querySelector("[data-storage-bot]")?.textContent).toBe("Chief7 GB");+ // Seeing it here is what keeps the sidebar's line for this band away.+ expect(localStorage.getItem("openmausbot.storageNotice.seen.v1:server:env-a")).toBe("near");+ expect(localStorage.getItem("openmausbot.storageNotice.seen.v1")).toBeNull();+ });++ it("opening Storage reads the report and never starts a measurement", async () => {+ await openSettings({ storage: REPORT, section: "storage" });+ expect(storageReads()).toBeGreaterThan(0);+ expect(requests.filter((request) => request.startsWith("POST /api/diagnostics/storage"))).toEqual([]);+ });++ it("a Team Cloud's admin: their own MausBot keeps its name, and a bot the app isn't shown reads as a private bot", async () => {+ const answers = { ...REPORT, storage: storageReport({ bots: [{ id: "mine", bytes: 7 * GB, files: 1 }, { id: "theirs", bytes: 3 * GB, files: 1 }] }) };+ await openSettings({ storage: answers, section: "storage", config: { ...CONFIG, team: { id: "team-1", name: "Studio" } },+ bots: [{ id: "mine", name: "MausBot", threadId: "t1", defaultBot: { person: "[email protected]" } }] });+ expect([...document.querySelectorAll("[data-storage-bot]")].map((row) => row.textContent)).toEqual(["MausBot7 GB", "Private bot3 GB", "Deleted bots1.5 GB", "Other bots512 MB"]);+ });++ it("a team member who is not an admin: no Storage page, and the route is never asked", async () => {+ await openSettings({ storage: REPORT, sessionAnswer: session(["client"]), config: { ...CONFIG, team: { id: "team-1", name: "Acme" } } });+ expect(document.querySelector("[data-settings-page-body]")).not.toBeNull();+ expect(storageInNav()).toBeNull();+ expect(storageReads()).toBe(0);+ });++ it.each([+ ["a person's own computer (no report)", { storage: null }],+ ["an older Cloud without the route", 404],+ ["a refusal", 403],+ ])("%s: no Storage page", async (_name, storage) => {+ await openSettings({ storage, section: "storage" });+ expect(storageReads()).toBe(1);+ expect(storageInNav()).toBeNull();+ expect(document.querySelector("[data-settings-page-body='storage']")).toBeNull();+ });+});diff --git a/src/components/settings/StorageView.dom.test.ts b/src/components/settings/StorageView.dom.test.tsnew file mode 100644index 0000000000..0a6b76b713--- /dev/null+++ b/src/components/settings/StorageView.dom.test.ts@@ -0,0 +1,107 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { setLocale } from "@/lib/i18n";+import type { StorageAnswer } from "@/lib/storage-report";+import { GB, storageReport } from "@/lib/storage-report-fixture";+import { StorageView, type StorageViewProps } from "./StorageView";++const NOW = 1_800_000_000_000 + 3_600_000;+const NAMES: Record<string, string> = { chief: "Chief" };+let container: HTMLDivElement, root: Root;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ setLocale("en");+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); });++async function show(answer: StorageAnswer | null, over: Partial<StorageViewProps> = {}) {+ await act(async () => {+ root.render(createElement(StorageView, { answer, fetchedAt: NOW, now: NOW, nameOf: (id: string) => NAMES[id], measuring: false, onMeasure: () => {}, ...over }));+ });+}+const used = (usedGb: number) => ({ totalBytes: 100 * GB, freeBytes: (100 - usedGb) * GB, usedBytes: usedGb * GB });+const summary = () => container.querySelector<HTMLElement>("[data-storage-summary]");+const footnote = () => container.querySelector('[data-settings-block="storage-used"] > p:last-child')?.textContent ?? "";+const button = (label: string) => [...container.querySelectorAll("button")].find((item) => item.textContent === label);++describe("Settings → Storage", () => {+ it("holds its place with skeleton rows until the answer comes", async () => {+ await show(null);+ expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();+ expect(summary()).toBeNull();+ });++ it("while the first pass runs: how full it is now, a calm line, and no breakdown or bots yet", async () => {+ await show({ storage: storageReport({ at: null, ageS: null, running: true, volume: null, categories: [], bots: [] }), now: used(40), measureInS: 600 });+ expect(summary()?.dataset.band).toBe("ok");+ expect(summary()?.textContent).toContain("40%full");+ expect(container.textContent).toContain("Measuring what uses this space. This can take a while on a large Cloud.");+ expect(container.querySelector("[data-storage-group]")).toBeNull();+ expect(container.querySelector("[data-storage-bot]")).toBeNull();+ expect(container.textContent).toContain("Measuring…");+ expect(button("Measure again")).toBeUndefined();+ });++ it("normal: the used of total, the three plain groups with Other and the unmeasured rest, the age and Measure again", async () => {+ const measure = vi.fn();+ await show({ storage: storageReport(), now: used(50), measureInS: 0 }, { onMeasure: measure });+ expect(summary()?.dataset.band).toBe("ok");+ expect(summary()?.querySelector("p")?.textContent).toBe("50 GB of 100 GB used");+ expect([...container.querySelectorAll("[data-storage-group]")].map((row) => row.textContent)).toEqual([+ "Your bots' files13 GB", "Conversations and settings6 GB", "Cache and downloads8 GB", "Other2 GB", "Not measured21 GB",+ ]);+ expect(container.querySelector('[role="progressbar"]')?.getAttribute("aria-valuenow")).toBe("50");+ expect(footnote()).toContain("Measured 1 hour ago.");+ expect(footnote()).toContain("Not measured is the system's own space");+ button("Measure again")!.click();+ expect(measure).toHaveBeenCalledTimes(1);+ });++ it("offers no Measure again while the server would refuse one, and no clearing at all", async () => {+ await show({ storage: storageReport(), now: used(30), measureInS: 240 });+ expect(button("Measure again")).toBeUndefined();+ expect([...container.querySelectorAll("button")].map((item) => item.textContent)).toEqual([]);+ });++ it.each([[80, "near", "text-warning"], [91, "full", "text-danger"]] as const)("at %i%% says so in the status colour", async (percent, band, ink) => {+ await show({ storage: storageReport(), now: used(percent), measureInS: 0 });+ expect(summary()?.dataset.band).toBe(band);+ expect(summary()?.querySelector(`.${ink}`)?.textContent).toBe(`${percent}%`);+ });++ it("says an over-count plainly, and a failed pass's figures are the one before", async () => {+ const report = storageReport({ failed: true, categories: [{ name: "bot_files", class: "work", bytes: 40 * GB, files: 1 }] });+ await show({ storage: report, now: used(30), measureInS: 0 });+ expect(footnote()).toContain("Some files may be counted twice, so the parts add up to 10 GB more than is used.");+ expect(footnote()).toContain("The last measurement didn't finish, so these figures are from the one before.");+ });++ it("lists the largest bots by name, an unnamed bot as such, deleted bots apart, and says a bot's size counts its cache too", async () => {+ await show({ storage: storageReport(), now: used(30), measureInS: 0 });+ expect([...container.querySelectorAll("[data-storage-bot]")].map((row) => row.textContent)).toEqual([+ "Chief7 GB", "Unnamed bot3 GB", "Deleted bots1.5 GB", "Other bots512 MB",+ ]);+ expect(container.querySelector('[data-settings-block="storage-bots"] > p:last-child')?.textContent)+ .toBe("A bot's size includes its own cache and downloads, also counted under Cache and downloads.");+ });++ it("on a Team Cloud a bot this person isn't shown is a private bot, never its name", async () => {+ await show({ storage: storageReport(), now: used(30), measureInS: 0 }, { team: true });+ expect([...container.querySelectorAll("[data-storage-bot]")].map((row) => row.textContent)).toEqual([+ "Chief7 GB", "Private bot3 GB", "Deleted bots1.5 GB", "Other bots512 MB",+ ]);+ });++ it("the faint groups' legend dots carry a ring, so they read on a dark skin", async () => {+ await show({ storage: storageReport(), now: used(50), measureInS: 0 });+ const dot = (key: string) => container.querySelector(`[data-storage-group="${key}"] > span`)?.className ?? "";+ expect(dot("other")).toContain("var(--color-ink-tertiary)");+ expect(dot("unmeasured")).toContain("var(--color-ink-tertiary)");+ });+});diff --git a/src/components/settings/StorageView.tsx b/src/components/settings/StorageView.tsxnew file mode 100644index 0000000000..9323373335--- /dev/null+++ b/src/components/settings/StorageView.tsx@@ -0,0 +1,118 @@+import { Loader2, RefreshCw } from "lucide-react";++import { cn } from "@/lib/cn";+import { activeLocale, t } from "@/lib/i18n";+import { localizedRelativeTime } from "@/lib/relative-time";+import {+ storageBand, storageBots, storageFullness, storageSize, storageSummary, type StorageAnswer, type StorageBand, type StorageBotRow, type StorageGroupKey,+} from "@/lib/storage-report";+import type { LocaleKey } from "@/locales";+import { SettingsEmptyRow, SettingsGroup, SettingsRows, SIMPLE_CARD } from "../SettingsPrimitives";+import { SettingsSkeletonRows } from "./SettingsStates";++const GROUP_LABEL: Record<StorageGroupKey, LocaleKey> = {+ work: "settings.storage.group.work", precious: "settings.storage.group.precious", rebuildable: "settings.storage.group.rebuildable",+ other: "settings.storage.group.other", unmeasured: "settings.storage.group.unmeasured",+};+const GROUP_FILL: Record<StorageGroupKey, string> = {+ work: "bg-ink", precious: "bg-ink/60", rebuildable: "bg-ink/35", other: "bg-ink/20", unmeasured: "bg-ink/[0.12]",+};+/** The legend's dots: the bar's fills, but the two faintest get a ring in the tertiary ink so they read on dark skins too. */+const GROUP_DOT: Record<StorageGroupKey, string> = {+ ...GROUP_FILL, other: "bg-ink/20 shadow-[inset_0_0_0_1px_var(--color-ink-tertiary)]", unmeasured: "shadow-[inset_0_0_0_1px_var(--color-ink-tertiary)]",+};+/** The unmeasured part is explained once it is at least this share of what is used. */+const UNMEASURED_NOTED = 0.05;+const PERCENT_INK: Record<StorageBand, string> = { ok: "text-ink", near: "text-warning", full: "text-danger" };++export interface StorageViewProps {+ answer: StorageAnswer | null;+ /** When the answer was read, on this computer's clock (the report's age counts from it). */+ fetchedAt: number;+ now: number;+ nameOf: (id: string) => string | null | undefined;+ /** A Team Cloud: a bot the app has no name for is a teammate's own, shown as a private bot. */+ team?: boolean;+ measuring: boolean;+ /** "Measure again", when the server takes one now. */+ onMeasure?: () => void;+}++/** Settings → Storage: how full this place's disk is, by plain group, its largest bots, and when it was measured. */+export function StorageView({ answer, fetchedAt, now, nameOf, team = false, measuring, onMeasure }: StorageViewProps) {+ const report = answer?.storage ?? null;+ if (!report) return <SettingsGroup label={t("settings.storage.section")} block="storage-used"><SettingsRows><SettingsSkeletonRows /></SettingsRows></SettingsGroup>;+ const running = report.running || measuring;+ const canMeasure = Boolean(onMeasure) && !running && answer?.measureInS === 0;+ const action = running+ ? <span role="status" className="flex items-center gap-1.5 text-[13px] leading-[18px] text-ink-secondary"><Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />{t("settings.storage.measuring")}</span>+ : canMeasure ? <button type="button" onClick={onMeasure} className="settings-quiet flex cursor-pointer items-center gap-1.5"><RefreshCw size={14} aria-hidden="true" />{t("settings.storage.measureAgain")}</button>+ : undefined;+ const summary = storageSummary(answer);+ const full = storageFullness(answer);+ const measuredAt = report.ageS === null ? null : fetchedAt - report.ageS * 1000;+ const notes = [+ measuredAt !== null && t("settings.storage.measured", { when: localizedRelativeTime(measuredAt, activeLocale(), now) }),+ report.failed && (report.at === null ? t("settings.storage.failedFirst") : t("settings.storage.failed")),+ summary && summary.overcountBytes > 0 && t("settings.storage.overcount", { size: storageSize(summary.overcountBytes) }),+ summary?.groups.some((group) => group.key === "unmeasured" && group.bytes >= summary.usedBytes * UNMEASURED_NOTED) && t("settings.storage.unmeasuredNote"),+ ].filter(Boolean).join(" ");+ const bots = report.at === null ? [] : storageBots(report, nameOf, undefined, team);+ return <>+ <SettingsGroup label={t("settings.storage.section")} block="storage-used" actions={action} footnote={notes || undefined}>+ {full ? <StorageSummaryCard full={full} groups={summary?.groups ?? null} waiting={report.at === null && !report.failed} />+ : <SettingsRows><SettingsEmptyRow>{t("settings.storage.firstPass")}</SettingsEmptyRow></SettingsRows>}+ </SettingsGroup>+ {bots.length > 0 && (+ <SettingsGroup label={t("settings.storage.bots")} block="storage-bots" footnote={t("settings.storage.botsNote")}>+ <SettingsRows>{bots.map((row) => <BotRow key={row.key} row={row} />)}</SettingsRows>+ </SettingsGroup>+ )}+ </>;+}++function StorageSummaryCard({ full, groups, waiting }: {+ full: { usedBytes: number; sizeBytes: number; percent: number }; groups: Array<{ key: StorageGroupKey; bytes: number }> | null; waiting: boolean;+}) {+ const band = storageBand(full.percent);+ const label = t("settings.storage.summary", { percent: String(full.percent) });+ const parts = groups ?? [{ key: "unmeasured" as const, bytes: full.usedBytes }];+ return (+ <section data-storage-summary="" data-band={band} aria-label={label} className={cn(SIMPLE_CARD, "px-4 py-3.5")}>+ <p className="text-[13px] leading-[18px] text-ink">{t("settings.storage.used", { used: storageSize(full.usedBytes), size: storageSize(full.sizeBytes) })}</p>+ <p className="mt-2 flex items-baseline gap-1.5">+ <span className={cn("text-[22px] font-medium leading-7 tracking-[-0.012em] tabular-nums", PERCENT_INK[band])}>{full.percent}%</span>+ <span className="text-[13px] text-ink-secondary">{t("settings.storage.full")}</span>+ </p>+ <div role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={100} aria-valuenow={full.percent}+ aria-valuetext={t("settings.storage.used", { used: storageSize(full.usedBytes), size: storageSize(full.sizeBytes) })}+ className="mt-2 flex h-1.5 w-full gap-px overflow-hidden rounded-full bg-ink/[0.06]">+ {parts.map((part) => <div key={part.key} data-storage-part={part.key} className={cn("h-full", GROUP_FILL[part.key])}+ style={{ width: `${Math.max((part.bytes / full.sizeBytes) * 100, part.bytes > 0 ? 0.5 : 0)}%` }} />)}+ </div>+ {waiting && <p role="status" className="mt-2 text-[12px] leading-4 text-ink-secondary">{t("settings.storage.firstPass")}</p>}+ {groups && (+ <ul className="mt-3 flex flex-col gap-1.5" aria-label={t("settings.storage.breakdown")}>+ {groups.map((group) => (+ <li key={group.key} data-storage-group={group.key} className="flex min-w-0 items-center gap-2 text-[13px] leading-[18px]">+ <span aria-hidden="true" className={cn("size-2 shrink-0 rounded-full", GROUP_DOT[group.key])} />+ <span className="min-w-0 flex-1 truncate text-ink">{t(GROUP_LABEL[group.key])}</span>+ <span className="shrink-0 tabular-nums text-ink-secondary">{storageSize(group.bytes)}</span>+ </li>+ ))}+ </ul>+ )}+ </section>+ );+}++function BotRow({ row }: { row: StorageBotRow }) {+ const name = row.kind === "gone" ? t("settings.storage.deletedBots") : row.kind === "rest" ? t("settings.storage.otherBots")+ : row.kind === "private" ? t("settings.storage.privateBot") : row.name ?? t("settings.storage.unnamedBot");+ return (+ <div data-storage-bot={row.kind} className="flex min-h-11 items-center gap-3 px-4 py-3">+ <span title={name} className={cn("min-w-0 flex-1 truncate text-[14px] leading-5", row.kind === "bot" && row.name ? "text-ink" : "text-ink-secondary")}>{name}</span>+ <span className="shrink-0 text-[13px] leading-[18px] tabular-nums text-ink-secondary">{storageSize(row.bytes)}</span>+ </div>+ );+}diff --git a/src/components/settings/pages/SettingsPageBody.tsx b/src/components/settings/pages/SettingsPageBody.tsxindex a8af16360c..fab0d340b1 100644--- a/src/components/settings/pages/SettingsPageBody.tsx+++ b/src/components/settings/pages/SettingsPageBody.tsx@@ -5,6 +5,7 @@ import { DataPage, ImportExportPage, InstallationsPage, PeoplePage, SpendingPageimport { DevicesPage } from "./DevicesPage";import { PhonePage } from "./PhonePage";import { AiPage, BotsPage, DesktopsPage, OverviewPage } from "./PlacePages";+import { StoragePage } from "./StoragePage";const PAGES: Record<SettingsPageId, () => React.ReactNode> = {overview: OverviewPage,@@ -16,6 +17,7 @@ const PAGES: Record<SettingsPageId, () => React.ReactNode> = {vault: VaultPage,usage: SpendingPage,transfer: ImportExportPage,+ storage: StoragePage,data: DataPage,people: PeoplePage,installations: InstallationsPage,diff --git a/src/components/settings/pages/StoragePage.tsx b/src/components/settings/pages/StoragePage.tsxnew file mode 100644index 0000000000..861f2d7e95--- /dev/null+++ b/src/components/settings/pages/StoragePage.tsx@@ -0,0 +1,41 @@+import { useEffect, useMemo, useState } from "react";++import { settleSeen, storageBand, storageBotNames, storageFullness, storageScope } from "@/lib/storage-report";+import { measureStorage, rememberStorageSeen, useStorageReport, useStorageSeen } from "@/lib/use-storage-report";+import { useStoreSelector } from "@/state/store-select";+import { useTeamPeople } from "@/state/team-people";+import { StorageView } from "../StorageView";+import { useSettingsShell } from "../settings-shell";++/** Read again this often while a pass runs and the page is open. */+const WHILE_RUNNING_MS = 10_000;++export function StoragePage() {+ const { ctx } = useSettingsShell();+ const read = useStorageReport({ enabled: ctx.admin && !ctx.client, everyMs: WHILE_RUNNING_MS, whileRunning: true });+ const bots = useStoreSelector((state) => state.bots);+ const teamPeople = useTeamPeople();+ const me = teamPeople?.me?.email ?? null;+ const names = useMemo(() => storageBotNames(bots, ctx.team ? { me } : null), [bots, ctx.team, me]);+ const [measuring, setMeasuring] = useState(false);+ const [now, setNow] = useState(Date.now);+ const answer = read.status === "ready" ? read.answer : null;+ const scope = answer ? storageScope(answer) : null;+ const seen = useStorageSeen(scope);+ const percent = storageFullness(answer)?.percent ?? null;+ useEffect(() => { setNow(Date.now()); }, [answer]);+ // Opening Storage is seeing it: this Cloud's sidebar line for this band (or a lower one) stays away until usage falls well+ // under it.+ useEffect(() => {+ if (percent === null || scope === null) return;+ const band = storageBand(percent), settled = settleSeen(seen, percent);+ const next = band === "full" || settled === "full" ? "full" : band === "near" || settled === "near" ? "near" : null;+ if (next !== seen) rememberStorageSeen(scope, next);+ }, [percent, seen, scope]);+ const measure = () => {+ setMeasuring(true);+ void measureStorage().finally(() => setMeasuring(false));+ };+ return <StorageView answer={answer} fetchedAt={read.status === "ready" ? read.fetchedAt : now} now={now} nameOf={(id) => names.get(id)}+ team={ctx.team} measuring={measuring} onMeasure={measure} />;+}diff --git a/src/components/settings/settings-context.ts b/src/components/settings/settings-context.tsindex 68fc4f5c20..db1226f1f3 100644--- a/src/components/settings/settings-context.ts+++ b/src/components/settings/settings-context.ts@@ -7,6 +7,7 @@ export { useSettingsPlace, type PlaceKind, type SettingsPlace } from "./settingsimport { useAdvancedMode } from "@/lib/interface-mode";import { railShown, usePlaces, type RailPlace } from "@/lib/places";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";+import { useStorageReport } from "@/lib/use-storage-report";import { useStoreSelector } from "@/state/store-select";import { workspacesAvailable } from "../WorkspacesSection";import type { SettingsContext } from "./settings-index";@@ -30,8 +31,9 @@ export function useSettingsContext(): SettingsContext {const environments = Boolean(ogb?.environments);const installations = workspacesAvailable(config);const skills = skillsLibraryEnabled(config);- return useMemo(() => ({ desktop, here, home, cloud, team, client, admin, places: placesShown, plan, organization, environments, installations, skills, advanced }),- [desktop, here, home, cloud, team, client, admin, placesShown, plan, organization, environments, installations, skills, advanced]);+ const storage = useStorageReport({ enabled: admin && !client }).status === "ready";+ return useMemo(() => ({ desktop, here, home, cloud, team, client, admin, places: placesShown, plan, organization, environments, installations, skills, advanced, storage }),+ [desktop, here, home, cloud, team, client, admin, placesShown, plan, organization, environments, installations, skills, advanced, storage]);}/** How many places this app knows (a hidden rail's included), from main's environments list. */diff --git a/src/components/settings/settings-index.ts b/src/components/settings/settings-index.tsindex 9856fc783d..5f46429e4d 100644--- a/src/components/settings/settings-index.ts+++ b/src/components/settings/settings-index.ts@@ -1,5 +1,5 @@import {- Archive, ArrowLeftRight, Bot, Coins, CreditCard, LockKeyhole, Monitor, Network, Palette, Server, SlidersHorizontal, Smartphone, Sparkles, Users,+ Archive, ArrowLeftRight, Bot, Coins, CreditCard, HardDrive, LockKeyhole, Monitor, Network, Palette, Server, SlidersHorizontal, Smartphone, Sparkles, Users,type LucideIcon,} from "lucide-react";import type { LocaleKey } from "@/locales";@@ -32,6 +32,8 @@ export interface SettingsContext {installations: boolean;skills: boolean;advanced: boolean;+ /** this place's server answers with a storage report (a Cloud home), read only by an owner or admin */+ storage?: boolean;}export interface SettingsPage {@@ -49,8 +51,9 @@ const notClient = (ctx: SettingsContext) => !ctx.client;const adminPage = (ctx: SettingsContext) => !ctx.client && !(ctx.team && !ctx.admin);/** A page Simple mode leaves out: its everyday rows show elsewhere in Simple (Overview, This app, Plan & billing). */const advancedOnly = (when: (ctx: SettingsContext) => boolean) => (ctx: SettingsContext) => ctx.advanced && when(ctx);-/** Simple mode's eleven entries: the place (Overview, Devices, Phone & devices, AI, Vault, Spending, Import & export), Your account- * (Plan & billing) and This app (Appearance). Advanced adds You and your bots, Desktops & browser, Data and General. */+/** Simple mode's eleven entries: the place (Overview, Devices, Phone & devices, AI, Vault, Spending, Import & export, and Storage+ * on a Cloud), Your account (Plan & billing) and This app (Appearance). Advanced adds You and your bots, Desktops & browser,+ * Data and General. */export const ADVANCED_PAGES: readonly SettingsPageId[] = ["bots", "desktops", "data", "general"];export const SETTINGS_PAGES: readonly SettingsPage[] = [@@ -71,6 +74,8 @@ export const SETTINGS_PAGES: readonly SettingsPage[] = [synonyms: ["spending", "usage", "cost", "costs", "tokens", "money", "runs", "export csv"] },{ id: "transfer", owner: "place", labelKey: "settings.page.importExport", icon: ArrowLeftRight, when: adminPage,synonyms: ["import", "export", "backup", "backups", "restore", "grok", "grok bot", "move from", "bring"] },+ { id: "storage", owner: "place", labelKey: "settings.page.storage", icon: HardDrive, when: (ctx) => ctx.storage === true && adminPage(ctx),+ synonyms: ["storage", "disk", "disk space", "space", "full", "free space", "volume", "what uses space", "cache", "downloads"] },{ id: "data", owner: "place", labelKey: "settings.page.data", icon: Archive, when: advancedOnly(adminPage),synonyms: ["data", "storage", "attachments", "activity", "audit"] },{ id: "people", owner: "place", labelKey: "settings.section.people", icon: Users,diff --git a/src/components/settings/settings-places.ts b/src/components/settings/settings-places.tsindex 2b5a781781..89a1b9c8d1 100644--- a/src/components/settings/settings-places.ts+++ b/src/components/settings/settings-places.ts@@ -27,6 +27,7 @@ const KINDS: ReadonlyArray<{ only: string; ctx: Partial<SettingsContext> }> = [{ only: "a company's managed MausBot", ctx: { organization: true } },{ only: "a place with the skills library on", ctx: { skills: true } },{ only: "a server that manages installations", ctx: { installations: true } },+ { only: "a MausBot Cloud's Settings, for its owner or admins", ctx: { cloud: true, storage: true } },];function onlyOn(shows: (ctx: SettingsContext) => boolean): string | undefined {diff --git a/src/lib/storage-report-fixture.ts b/src/lib/storage-report-fixture.tsnew file mode 100644index 0000000000..3883b467af--- /dev/null+++ b/src/lib/storage-report-fixture.ts@@ -0,0 +1,22 @@+// A storage report as a Cloud home's server sends it, for tests and the Storage preview.+import type { StorageReportWire } from "./storage-report";++export const GB = 1024 ** 3;++/** A report as the server sends it: 60 GB volume, 30 GB used, measured an hour ago. */+export function storageReport(over: Partial<StorageReportWire> = {}): StorageReportWire {+ return {+ at: 1_800_000_000_000, ageS: 3_600, running: false, failed: false,+ volume: { totalBytes: 60 * GB, freeBytes: 30 * GB, usedBytes: 30 * GB }, walkedBytes: 29 * GB, unwalkedBytes: 1 * GB,+ categories: [+ { name: "bot_files", class: "work", bytes: 12 * GB, files: 1_000 },+ { name: "conversations", class: "precious", bytes: 6 * GB, files: 10 },+ { name: "packages", class: "rebuildable", bytes: 8 * GB, files: 90_000 },+ { name: "other", class: "work", bytes: 2 * GB, files: 40 },+ { name: "attachments", class: "work", bytes: 1 * GB, files: 300 },+ ],+ bots: [{ id: "chief", bytes: 7 * GB, files: 600 }, { id: "research", bytes: 3 * GB, files: 300 }],+ botsRest: { bytes: 2 * GB, files: 100, count: 2 }, botsGone: { bytes: 1.5 * GB, files: 60, count: 1 },+ ...over,+ };+}diff --git a/src/lib/storage-report.test.ts b/src/lib/storage-report.test.tsnew file mode 100644index 0000000000..2854324db9--- /dev/null+++ b/src/lib/storage-report.test.ts@@ -0,0 +1,137 @@+// @vitest-environment happy-dom+import { describe, expect, it } from "vitest";++import { GB, storageReport } from "./storage-report-fixture";+import {+ readStorageSeen, settleSeen, storageBand, storageBotNames, storageBots, storageFullness, storageNotice, storageScope, storageSeenKey, storageSize, storageSummary,+ writeStorageSeen, type StorageAnswer, type StorageReportWire,+} from "./storage-report";++const answer = (report: StorageReportWire | null, over: Partial<StorageAnswer> = {}): StorageAnswer => ({ storage: report, ...over });+const bytesOf = (summary: ReturnType<typeof storageSummary>) => Object.fromEntries(summary!.groups.map((group) => [group.key, group.bytes]));++describe("storage fullness", () => {+ it("is used of used plus free, as df counts it, from the live reading when there is one", () => {+ expect(storageFullness(answer(storageReport()))).toEqual({ usedBytes: 30 * GB, sizeBytes: 60 * GB, percent: 50 });+ expect(storageFullness(answer(storageReport(), { now: { totalBytes: 60 * GB, freeBytes: 6 * GB, usedBytes: 51 * GB } }))?.percent).toBe(89);+ expect(storageFullness(answer(storageReport({ volume: null })))).toBeNull();+ expect(storageFullness(null)).toBeNull();+ });++ it("bands at 80 and 90", () => {+ expect([79, 80, 89, 90, 100].map(storageBand)).toEqual(["ok", "near", "near", "full", "full"]);+ });+});++describe("the bar's groups", () => {+ it("groups by the class the server gives, takes `other` out by name, and names what the pass couldn't see", () => {+ expect(bytesOf(storageSummary(answer(storageReport())))).toEqual({ work: 13 * GB, precious: 6 * GB, rebuildable: 8 * GB, other: 2 * GB, unmeasured: 1 * GB });+ });++ it("puts a class this app doesn't know under Other, never under cache", () => {+ const report = storageReport({ categories: [{ name: "future_thing", class: "fresh-class", bytes: 4 * GB, files: 1 }] });+ expect(bytesOf(storageSummary(answer(report)))).toEqual({ other: 4 * GB, unmeasured: 26 * GB });+ });++ it("scales an over-count down to what is used and says by how much", () => {+ const report = storageReport({ categories: [{ name: "bot_files", class: "work", bytes: 30 * GB, files: 1 }, { name: "caches", class: "rebuildable", bytes: 10 * GB, files: 1 }] });+ const summary = storageSummary(answer(report))!;+ expect(summary.overcountBytes).toBe(10 * GB);+ expect(bytesOf(summary)).toEqual({ work: 22.5 * GB, rebuildable: 7.5 * GB });+ });++ it("counts what was written since the pass as unmeasured, and shrinks the groups when the volume shrank", () => {+ const grown = storageSummary(answer(storageReport(), { now: { totalBytes: 60 * GB, freeBytes: 20 * GB, usedBytes: 40 * GB } }))!;+ expect(bytesOf(grown).unmeasured).toBe(11 * GB);+ const shrunk = storageSummary(answer(storageReport(), { now: { totalBytes: 60 * GB, freeBytes: 45 * GB, usedBytes: 15 * GB } }))!;+ expect(shrunk.groups.reduce((sum, group) => sum + group.bytes, 0)).toBe(15 * GB);+ });++ it("is nothing before the first pass", () => {+ expect(storageSummary(answer(storageReport({ at: null, ageS: null, categories: [] })))).toBeNull();+ });+});++describe("the sidebar's line", () => {+ it("shows once per crossing: seen at 80 stays away until 90, and seen at 90 stays away", () => {+ expect(storageNotice(79, null)).toBeNull();+ expect(storageNotice(80, null)).toBe("near");+ expect(storageNotice(86, "near")).toBeNull();+ expect(storageNotice(90, "near")).toBe("full");+ expect(storageNotice(95, "full")).toBeNull();+ expect(storageNotice(null, null)).toBeNull();+ });++ it("re-arms only after usage falls five points under a line, so a volume that grows itself near 80% says it once", () => {+ expect(settleSeen("near", 77)).toBe("near");+ expect(storageNotice(81, settleSeen("near", 77))).toBeNull();+ expect(settleSeen("near", 74)).toBeNull();+ expect(storageNotice(80, settleSeen("near", 74))).toBe("near");+ expect(settleSeen("full", 86)).toBe("full");+ expect(settleSeen("full", 84)).toBe("near");+ expect(storageNotice(91, settleSeen("full", 84))).toBe("full");+ expect(settleSeen("full", 10)).toBeNull();+ });+});++describe("the bots list", () => {+ it("names the largest bots by the app's own names, says Unnamed for a bot with none, and keeps deleted bots apart", () => {+ const names: Record<string, string> = { chief: "Chief", research: " " };+ expect(storageBots(storageReport(), (id) => names[id])).toEqual([+ { key: "chief", name: "Chief", bytes: 7 * GB, kind: "bot" },+ { key: "research", name: null, bytes: 3 * GB, kind: "bot" },+ { key: "gone", name: null, bytes: 1.5 * GB, kind: "gone" },+ { key: "rest", name: null, bytes: 0.5 * GB, kind: "rest" },+ ]);+ });++ it("folds bots past the first few into Other bots, and an older server without the split into Other bots too", () => {+ const report = storageReport({ bots: [1, 2, 3, 4, 5, 6, 7].map((n) => ({ id: `b${n}`, bytes: n * GB, files: 1 })), botsGone: undefined });+ const rows = storageBots(report, () => "Bot");+ expect(rows.map((row) => row.kind)).toEqual(["bot", "bot", "bot", "bot", "bot", "rest"]);+ expect(rows.at(-1)!.bytes).toBe(2 * GB + 3 * GB);+ });+});++describe("on a Team Cloud", () => {+ it("names only the bots this person may see, never a teammate's own MausBot, and counts an unnamed one as a private bot", () => {+ const names = storageBotNames([+ { id: "chief", name: "Chief" }, { id: "research", name: "Research", defaultBot: { person: "[email protected]" } },+ { id: "theirs", name: "Bo's MausBot", defaultBot: { person: "[email protected]" } },+ ], { me: "[email protected]" });+ expect([...names]).toEqual([["chief", "Chief"], ["research", "Research"]]);+ expect([...storageBotNames([{ id: "mine", name: "MausBot", defaultBot: { person: "[email protected]" } }], { me: null })]).toEqual([["mine", "MausBot"]]);+ expect(storageBots(storageReport(), (id) => names.get(id), undefined, true).map((row) => [row.key, row.kind, row.name])).toEqual([+ ["chief", "bot", "Chief"], ["research", "bot", "Research"], ["gone", "gone", null], ["rest", "rest", null],+ ]);+ expect(storageBots(storageReport(), (id) => (id === "chief" ? "Chief" : undefined), undefined, true).map((row) => row.kind)).toEqual(["bot", "private", "gone", "rest"]);+ });++ it("off a team every bot keeps its name, and one without a name is unnamed, not private", () => {+ expect([...storageBotNames([{ id: "theirs", name: "Bo's MausBot", defaultBot: { person: "[email protected]" } }], null)]).toEqual([["theirs", "Bo's MausBot"]]);+ expect(storageBots(storageReport(), () => undefined).map((row) => row.kind)).toEqual(["bot", "bot", "gone", "rest"]);+ });+});++describe("what is remembered, per Cloud", () => {+ it("keys the seen mark by the server's own id, or the page's origin for a server that sends none", () => {+ expect(storageScope({ server: "env-a" })).toBe("server:env-a");+ expect(storageScope({})).toBe(`origin:${location.origin}`);+ localStorage.clear();+ writeStorageSeen(storageScope({ server: "env-a" }), "full");+ expect(readStorageSeen("server:env-a")).toBe("full");+ expect(readStorageSeen("server:env-b")).toBeNull();+ expect(localStorage.getItem(storageSeenKey("server:env-a"))).toBe("full");+ writeStorageSeen("server:env-a", null);+ expect(readStorageSeen("server:env-a")).toBeNull();+ });+});++describe("sizes", () => {+ it("reads in the person's own number format", () => {+ expect(storageSize(12.34 * GB, "en")).toBe("12.3 GB");+ expect(storageSize(512 * GB, "en")).toBe("512 GB");+ expect(storageSize(3.5 * 1024 ** 2, "de")).toBe("3,5 MB");+ expect(storageSize(900, "en")).toBe("1 kB");+ });+});diff --git a/src/lib/storage-report.ts b/src/lib/storage-report.tsnew file mode 100644index 0000000000..cada0b98db--- /dev/null+++ b/src/lib/storage-report.ts@@ -0,0 +1,165 @@+// Settings → Storage and the sidebar's quiet storage line read one answer: GET /api/diagnostics/storage, the Cloud home's+// storage report beside the volume as it is now. Display only; nothing here deletes or clears anything.+import { activeLocale } from "@/lib/i18n";++export type StorageClass = "precious" | "work" | "rebuildable";+interface Tally { bytes: number; files: number }+interface Volume { totalBytes: number; freeBytes: number; usedBytes: number }++/** The fields of the server's storage report this view reads. */+export interface StorageReportWire {+ at: number | null;+ ageS: number | null;+ running: boolean;+ volume: Volume | null;+ walkedBytes: number | null;+ unwalkedBytes: number | null;+ categories: Array<{ name: string; class: string; bytes: number; files: number }>;+ bots: Array<{ id: string } & Tally>;+ botsRest: Tally & { count: number };+ botsGone?: Tally & { count: number };+ linksUncheckedBytes?: number;+ failed: boolean;+}++export interface StorageAnswer {+ storage: StorageReportWire | null;+ now?: Volume | null;+ measureInS?: number | null;+ /** The server's environment id: what the app remembers of this answer is kept under it. */+ server?: string;+}++/** Whose answer this is: the server's own id, or (an older server without one) this page's origin. What the app remembers+ * of a storage answer (the "seen" mark) is kept per scope, so switching Clouds never hides another Cloud's line. */+export function storageScope(answer: Pick<StorageAnswer, "server"> | null | undefined): string {+ const server = typeof answer?.server === "string" ? answer.server.trim() : "";+ if (server) return `server:${server}`;+ try { return `origin:${globalThis.location?.origin ?? ""}`; } catch { return "origin:"; }+}++export type StorageGroupKey = "work" | "precious" | "rebuildable" | "other" | "unmeasured";+/** The bar's order: what people made, what they said and set, what comes back by itself, the rest. */+export const STORAGE_GROUPS: readonly StorageGroupKey[] = ["work", "precious", "rebuildable", "other", "unmeasured"];++export interface StorageSummary {+ usedBytes: number;+ /** Used plus what is still free to write: what a percentage of "full" is of. */+ sizeBytes: number;+ percent: number;+ groups: Array<{ key: StorageGroupKey; bytes: number }>;+ /** The measured files add up to this much more than the volume says it uses (hard links, a pass that resumed). */+ overcountBytes: number;+}++const GROUP_OF: Readonly<Record<string, Exclude<StorageGroupKey, "other" | "unmeasured">>> = { work: "work", precious: "precious", rebuildable: "rebuildable" };++/** The volume's fullness, as `df` puts it (used of used plus available), from the freshest reading there is. */+export function storageFullness(answer: StorageAnswer | null): { usedBytes: number; sizeBytes: number; percent: number } | null {+ const volume = answer?.now ?? answer?.storage?.volume ?? null;+ if (!volume) return null;+ const sizeBytes = volume.usedBytes + volume.freeBytes;+ if (sizeBytes <= 0) return null;+ return { usedBytes: volume.usedBytes, sizeBytes, percent: Math.min(100, Math.max(0, Math.round((volume.usedBytes / sizeBytes) * 100))) };+}++/** The bar: each category in its plain group by the class the server gave it, `other` (and any class this app doesn't know)+ * under Other, and what the pass couldn't see as the unmeasured rest. When the measured files add up to more than the+ * volume uses, the groups are scaled down to it and the difference is said instead. */+export function storageSummary(answer: StorageAnswer | null): StorageSummary | null {+ const report = answer?.storage;+ const full = storageFullness(answer);+ if (!report || !full || report.at === null || !report.volume) return null;+ const sums: Record<StorageGroupKey, number> = { work: 0, precious: 0, rebuildable: 0, other: 0, unmeasured: 0 };+ for (const row of report.categories) sums[row.name === "other" ? "other" : GROUP_OF[row.class] ?? "other"] += Math.max(0, row.bytes);+ const measured = sums.work + sums.precious + sums.rebuildable + sums.other;+ const usedAtPass = report.volume.usedBytes;+ const overcountBytes = Math.max(0, measured - usedAtPass);+ const scale = measured > 0 && overcountBytes > 0 ? usedAtPass / measured : 1;+ // The groups are the last pass's. What was written since counts as unmeasured; if the volume shrank since, they shrink with it.+ const shrink = usedAtPass > 0 ? Math.min(1, full.usedBytes / usedAtPass) : 1;+ const groups: Array<{ key: StorageGroupKey; bytes: number }> = STORAGE_GROUPS.filter((key) => key !== "unmeasured").map((key) => ({ key, bytes: Math.round(sums[key] * scale * shrink) }));+ const shown = groups.reduce((sum, group) => sum + group.bytes, 0);+ groups.push({ key: "unmeasured", bytes: Math.max(0, full.usedBytes - shown) });+ return { ...full, groups: groups.filter((group) => group.bytes > 0), overcountBytes };+}++export type StorageBand = "ok" | "near" | "full";+export const NEAR_PERCENT = 80, FULL_PERCENT = 90;+/** How far under a line usage has to fall before crossing it again counts as new: a volume that grows by itself as it+ * fills sits near a line for a while, and each grow is not a new crossing. */+export const REARM_POINTS = 5;++export const storageBand = (percent: number): StorageBand => (percent >= FULL_PERCENT ? "full" : percent >= NEAR_PERCENT ? "near" : "ok");+const RANK: Record<StorageBand, number> = { ok: 0, near: 1, full: 2 };++/** What has been seen, once usage moved: a band seen stays seen until usage falls REARM_POINTS under its line. */+export function settleSeen(seen: StorageBand | null, percent: number): StorageBand | null {+ let settled = seen === "ok" ? null : seen;+ if (settled === "full" && percent < FULL_PERCENT - REARM_POINTS) settled = "near";+ if (settled === "near" && percent < NEAR_PERCENT - REARM_POINTS) settled = null;+ return settled;+}++/** The band the sidebar's line shows, or null: under 80%, or this band (or a fuller one) already seen. */+export function storageNotice(percent: number | null, seen: StorageBand | null): Exclude<StorageBand, "ok"> | null {+ if (percent === null) return null;+ const band = storageBand(percent);+ if (band === "ok") return null;+ return RANK[band] > RANK[settleSeen(seen, percent) ?? "ok"] ? band : null;+}++const SEEN_KEY = "openmausbot.storageNotice.seen.v1";+/** The "seen" mark of one Cloud (storageScope). */+export const storageSeenKey = (scope: string): string => `${SEEN_KEY}:${scope}`;+export function readStorageSeen(scope: string): StorageBand | null {+ try {+ const value = globalThis.localStorage?.getItem(storageSeenKey(scope));+ return value === "near" || value === "full" ? value : null;+ } catch { return null; }+}+export function writeStorageSeen(scope: string, seen: StorageBand | null): void {+ try {+ if (seen === null || seen === "ok") globalThis.localStorage?.removeItem(storageSeenKey(scope));+ else globalThis.localStorage?.setItem(storageSeenKey(scope), seen);+ } catch { /* storage may be blocked: the line shows again next launch */ }+}++const GIB = 1024 ** 3, MIB = 1024 ** 2, KIB = 1024;+/** A size in the person's own number format, in binary units as the plans count them. */+export function storageSize(bytes: number, locale = activeLocale()): string {+ const [value, unit] = bytes >= GIB ? [bytes / GIB, "gigabyte"] : bytes >= MIB ? [bytes / MIB, "megabyte"] : [Math.ceil(Math.max(0, bytes) / KIB), "kilobyte"];+ const digits = value >= 100 || unit === "kilobyte" ? 0 : 1;+ return new Intl.NumberFormat(locale, { style: "unit", unit, unitDisplay: "short", maximumFractionDigits: digits }).format(value);+}++export const BOTS_SHOWN = 5;+/** `private`: on a Team Cloud, a bot this person is not shown (a teammate's own MausBot): counted, never named. */+export interface StorageBotRow { key: string; name: string | null; bytes: number; kind: "bot" | "private" | "gone" | "rest" }++/** The names Storage may show: on a Team Cloud never another person's own MausBot (the server keeps it from an admin too;+ * this holds should one still reach the list), which then reads as a private bot. While who this person is isn't known yet+ * (`me` null) the server's list is taken as it is, so their own MausBot never reads as private. */+export function storageBotNames(bots: ReadonlyArray<{ id: string; name: string; defaultBot?: { person?: string } }>, team: { me: string | null } | null): Map<string, string> {+ const me = team?.me?.trim().toLowerCase() ?? "";+ return new Map(bots.filter((bot) => {+ const person = bot.defaultBot?.person?.trim().toLowerCase();+ return !team || !person || !me || person === me;+ }).map((bot) => [bot.id, bot.name]));+}++/** The largest bots first, named by the app (null when it has no name for the id; on a Team Cloud such a bot is a private+ * one, someone else's), then deleted bots' leftovers and any other bot folders together. */+export function storageBots(report: StorageReportWire, nameOf: (id: string) => string | null | undefined, shown = BOTS_SHOWN, team = false): StorageBotRow[] {+ const listed = report.bots.filter((bot) => bot.bytes > 0).sort((a, b) => b.bytes - a.bytes);+ const rows: StorageBotRow[] = listed.slice(0, shown).map((bot) => {+ const name = nameOf(bot.id)?.trim() || null;+ return { key: bot.id, name, bytes: bot.bytes, kind: team && name === null ? "private" : "bot" };+ });+ const gone = report.botsGone?.bytes ?? 0;+ const folded = listed.slice(shown).reduce((sum, bot) => sum + bot.bytes, 0);+ const rest = Math.max(0, report.botsRest.bytes - gone) + folded;+ if (gone > 0) rows.push({ key: "gone", name: null, bytes: gone, kind: "gone" });+ if (rest > 0) rows.push({ key: "rest", name: null, bytes: rest, kind: "rest" });+ return rows;+}diff --git a/src/lib/use-storage-report.ts b/src/lib/use-storage-report.tsnew file mode 100644index 0000000000..a562f323b7--- /dev/null+++ b/src/lib/use-storage-report.ts@@ -0,0 +1,140 @@+// One copy of the storage answer for the page, shared by Settings → Storage and the sidebar's line. Only an owner or admin+// asks (the route is admin scope: a team's member gets nothing and sends nothing). A page whose server has no report (a+// person's own computer, an older Cloud, a refusal) is "none" and shows no Storage at all.+import { useEffect, useState } from "react";++import { api } from "@/state/api";+import { readStorageSeen, writeStorageSeen, type StorageAnswer, type StorageBand } from "./storage-report";++/** The page this answer was read for: a page talks to one server, and an answer read for another origin is never shown. */+const pageOrigin = (): string => { try { return globalThis.location?.origin ?? ""; } catch { return ""; } };++export const STORAGE_PATH = "/api/diagnostics/storage";+export const STORAGE_MEASURE_PATH = "/api/diagnostics/storage/measure";++export type StorageState =+ | { status: "unknown" }+ | { status: "none" }+ | { status: "ready"; answer: StorageAnswer; fetchedAt: number };++let state: StorageState = { status: "unknown" };+/** The origin `state` was read on. */+let stateOrigin = pageOrigin();+let loading: Promise<void> | null = null;+/** Bumped by forgetStorageReport: an answer to a read from before it is dropped. */+let generation = 0;+const listeners = new Set<(next: StorageState) => void>();++function set(next: StorageState): void {+ state = next;+ for (const listener of listeners) listener(next);+}++function statusOf(error: unknown): number | null {+ return typeof error === "object" && error !== null && typeof (error as { status?: unknown }).status === "number" ? (error as { status: number }).status : null;+}++/** Reads the answer again. `background`: a poll nobody asked for, which never wakes a sleeping Cloud. */+export function loadStorage(background: boolean): Promise<void> {+ if (loading) return loading;+ const asked = generation, origin = pageOrigin();+ const current = () => asked === generation && origin === pageOrigin();+ const settle = (next: StorageState) => { if (!current()) return; stateOrigin = origin; set(next); };+ const read: Promise<void> = api<StorageAnswer>(STORAGE_PATH, { background })+ .then((answer) => settle(answer?.storage ? { status: "ready", answer, fetchedAt: Date.now() } : { status: "none" }))+ .catch((error: unknown) => {+ const status = statusOf(error);+ // Refused, or a server without the route: there is no report here. Anything else (asleep, offline) keeps what was known.+ if (status === 403 || status === 404 || status === 401) settle({ status: "none" });+ })+ .finally(() => { if (loading === read) loading = null; });+ loading = read;+ return read;+}++/** The shared answer, unless it was read for another page's server. */+const known = (): StorageState => (stateOrigin === pageOrigin() ? state : { status: "unknown" });++/** "Measure again": true when the server started a pass. */+export async function measureStorage(): Promise<boolean> {+ try {+ const answer = await api<{ started: boolean }>(STORAGE_MEASURE_PATH, { method: "POST" });+ await loadStorage(false);+ return answer.started === true;+ } catch {+ return false;+ }+}++export interface StorageReadOptions {+ /** Only an owner or admin, never a paired client: false sends nothing and reads "none". */+ enabled: boolean;+ /** Wait this long before the first read (the sidebar, so the launch isn't held up). */+ delayMs?: number;+ /** Read again this often while mounted; `whileRunning` only while a pass runs. */+ everyMs?: number;+ whileRunning?: boolean;+ background?: boolean;+}++export function useStorageReport(options: StorageReadOptions): StorageState {+ const { enabled, delayMs = 0, everyMs, whileRunning = false, background = false } = options;+ const [seen, setSeen] = useState<StorageState>(known);+ const running = seen.status === "ready" && seen.answer.storage?.running === true;+ useEffect(() => {+ if (!enabled) return;+ listeners.add(setSeen);+ setSeen(known());+ const first = window.setTimeout(() => { if (delayMs === 0 || known().status === "unknown") void loadStorage(background); }, delayMs);+ return () => { listeners.delete(setSeen); window.clearTimeout(first); };+ }, [enabled, delayMs, background]);+ useEffect(() => {+ if (!enabled || !everyMs || (whileRunning && !running)) return;+ const timer = window.setInterval(() => { if (state.status !== "none") void loadStorage(background); }, everyMs);+ return () => window.clearInterval(timer);+ }, [enabled, everyMs, whileRunning, running, background]);+ return enabled ? seen : { status: "none" };+}++const seenListeners = new Set<(scope: string, seen: StorageBand | null) => void>();++/** The fullest band the person has seen Storage at on this Cloud (`scope`, storageScope; opening Settings → Storage while+ * there), kept on this device. Null scope (no answer yet): nothing seen. */+export function useStorageSeen(scope: string | null): StorageBand | null {+ const [seen, setSeen] = useState<{ scope: string | null; seen: StorageBand | null }>(() => ({ scope, seen: scope === null ? null : readStorageSeen(scope) }));+ useEffect(() => {+ setSeen({ scope, seen: scope === null ? null : readStorageSeen(scope) });+ if (scope === null) return;+ const listener = (changed: string, next: StorageBand | null) => { if (changed === scope) setSeen({ scope, seen: next }); };+ seenListeners.add(listener);+ return () => { seenListeners.delete(listener); };+ }, [scope]);+ return seen.scope === scope ? seen.seen : scope === null ? null : readStorageSeen(scope);+}++let shownThisLaunch: { scope: string; band: StorageBand } | null = null;++/** The sidebar showed its line for `band` on this Cloud: from the next launch on that counts as seen, and this launch+ * keeps showing it until Storage is opened. */+export function markStorageNoticeShown(scope: string, band: StorageBand): void {+ if (shownThisLaunch?.scope === scope && shownThisLaunch.band === band) return;+ shownThisLaunch = { scope, band };+ writeStorageSeen(scope, band);+}+export const storageNoticeShownThisLaunch = (scope: string): StorageBand | null => (shownThisLaunch?.scope === scope ? shownThisLaunch.band : null);++export function rememberStorageSeen(scope: string, seen: StorageBand | null): void {+ if (shownThisLaunch?.scope === scope) shownThisLaunch = null;+ writeStorageSeen(scope, seen);+ for (const listener of seenListeners) listener(scope, seen === "ok" ? null : seen);+}++/** Forget the shared answer and what this launch showed, as a new launch would. Tests use it; the app needs no call: a switch+ * to another Cloud loads a new page, and the seen mark is kept per server either way. */+export function forgetStorageReport(): void {+ stateOrigin = pageOrigin();+ loading = null;+ generation += 1;+ shownThisLaunch = null;+ set({ status: "unknown" });+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex ce3ae04f26..9377523af9 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -3690,6 +3690,33 @@"settings.page.overview": "Übersicht","settings.page.plan": "Tarif & Abrechnung","settings.page.spending": "Ausgaben",+ "settings.page.storage": "Speicher",+ "settings.storage.section": "Belegter Speicher",+ "settings.storage.used": "{used} von {size} belegt",+ "settings.storage.full": "voll",+ "settings.storage.summary": "Speicher zu {percent} % voll",+ "settings.storage.breakdown": "Was den Platz belegt",+ "settings.storage.group.work": "Dateien deiner Bots",+ "settings.storage.group.precious": "Unterhaltungen und Einstellungen",+ "settings.storage.group.rebuildable": "Cache und Downloads",+ "settings.storage.group.other": "Sonstiges",+ "settings.storage.group.unmeasured": "Nicht gemessen",+ "settings.storage.unmeasuredNote": "„Nicht gemessen“ ist der Platz des Systems und alles, was seit der letzten Messung geschrieben wurde.",+ "settings.storage.measured": "Gemessen {when}.",+ "settings.storage.measureAgain": "Erneut messen",+ "settings.storage.measuring": "Wird gemessen…",+ "settings.storage.firstPass": "Es wird gemessen, was diesen Platz belegt. Auf einer großen Cloud kann das eine Weile dauern.",+ "settings.storage.failed": "Die letzte Messung wurde nicht abgeschlossen, daher stammen diese Zahlen von der vorherigen.",+ "settings.storage.failedFirst": "Der belegte Platz konnte noch nicht gemessen werden. Es wird automatisch erneut versucht.",+ "settings.storage.overcount": "Manche Dateien werden womöglich doppelt gezählt, daher ergeben die Teile {size} mehr als belegt.",+ "settings.storage.bots": "Größte Bots",+ "settings.storage.botsNote": "Die Größe eines Bots enthält seinen eigenen Cache und seine Downloads, die auch unter Cache und Downloads zählen.",+ "settings.storage.unnamedBot": "Unbenannter Bot",+ "settings.storage.privateBot": "Privater Bot",+ "settings.storage.deletedBots": "Gelöschte Bots",+ "settings.storage.otherBots": "Weitere Bots",+ "storageNotice.line": "Speicher zu {percent} % voll",+ "storageNotice.open": "Speicher in den Einstellungen öffnen","settings.page.devices": "Geräte","devicesPage.add": "Gerät hinzufügen","devicesPage.mapLabel": "Deine Geräte und wie sie verbunden sind",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 6aa0a90885..53c6f09130 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -11063,6 +11063,33 @@"settings.page.overview": "Overview","settings.page.plan": "Plan & billing","settings.page.spending": "Spending",+ "settings.page.storage": "Storage",+ "settings.storage.section": "Space used",+ "settings.storage.used": "{used} of {size} used",+ "settings.storage.full": "full",+ "settings.storage.summary": "Storage is {percent}% full",+ "settings.storage.breakdown": "What uses the space",+ "settings.storage.group.work": "Your bots' files",+ "settings.storage.group.precious": "Conversations and settings",+ "settings.storage.group.rebuildable": "Cache and downloads",+ "settings.storage.group.other": "Other",+ "settings.storage.group.unmeasured": "Not measured",+ "settings.storage.unmeasuredNote": "Not measured is the system's own space and anything written since the last measurement.",+ "settings.storage.measured": "Measured {when}.",+ "settings.storage.measureAgain": "Measure again",+ "settings.storage.measuring": "Measuring…",+ "settings.storage.firstPass": "Measuring what uses this space. This can take a while on a large Cloud.",+ "settings.storage.failed": "The last measurement didn't finish, so these figures are from the one before.",+ "settings.storage.failedFirst": "Couldn't measure what uses this space yet. It tries again on its own.",+ "settings.storage.overcount": "Some files may be counted twice, so the parts add up to {size} more than is used.",+ "settings.storage.bots": "Largest bots",+ "settings.storage.botsNote": "A bot's size includes its own cache and downloads, also counted under Cache and downloads.",+ "settings.storage.unnamedBot": "Unnamed bot",+ "settings.storage.privateBot": "Private bot",+ "settings.storage.deletedBots": "Deleted bots",+ "settings.storage.otherBots": "Other bots",+ "storageNotice.line": "Storage {percent}% full",+ "storageNotice.open": "Open Storage in Settings","devicesPage.add": "Add a device","devicesPage.mapLabel": "Your devices and how they connect","devicesPage.empty": "Nothing else is connected yet. Add a phone, a computer or your own server.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex db017a958d..9d2af96824 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -6083,6 +6083,33 @@"settings.page.overview": "Resumen","settings.page.plan": "Plan y facturación","settings.page.spending": "Gastos",+ "settings.page.storage": "Almacenamiento",+ "settings.storage.section": "Espacio usado",+ "settings.storage.used": "{used} de {size} usados",+ "settings.storage.full": "lleno",+ "settings.storage.summary": "El almacenamiento está al {percent} %",+ "settings.storage.breakdown": "Qué ocupa el espacio",+ "settings.storage.group.work": "Archivos de tus bots",+ "settings.storage.group.precious": "Conversaciones y ajustes",+ "settings.storage.group.rebuildable": "Caché y descargas",+ "settings.storage.group.other": "Otros",+ "settings.storage.group.unmeasured": "Sin medir",+ "settings.storage.unmeasuredNote": "«Sin medir» es el espacio del sistema y todo lo escrito desde la última medición.",+ "settings.storage.measured": "Medido {when}.",+ "settings.storage.measureAgain": "Volver a medir",+ "settings.storage.measuring": "Midiendo…",+ "settings.storage.firstPass": "Midiendo qué ocupa este espacio. En una Cloud grande puede tardar un buen rato.",+ "settings.storage.failed": "La última medición no terminó, así que estas cifras son de la anterior.",+ "settings.storage.failedFirst": "Aún no se pudo medir qué ocupa este espacio. Se volverá a intentar automáticamente.",+ "settings.storage.overcount": "Puede que algunos archivos se cuenten dos veces, así que las partes suman {size} más de lo usado.",+ "settings.storage.bots": "Bots más grandes",+ "settings.storage.botsNote": "El tamaño de un bot incluye su propia caché y sus descargas, que también cuentan en Caché y descargas.",+ "settings.storage.unnamedBot": "Bot sin nombre",+ "settings.storage.privateBot": "Bot privado",+ "settings.storage.deletedBots": "Bots eliminados",+ "settings.storage.otherBots": "Otros bots",+ "storageNotice.line": "Almacenamiento al {percent} %",+ "storageNotice.open": "Abrir Almacenamiento en Ajustes","settings.page.devices": "Dispositivos","devicesPage.add": "Añadir un dispositivo","devicesPage.mapLabel": "Tus dispositivos y cómo se conectan",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex c97ae7382d..634b11a100 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3427,6 +3427,33 @@"settings.page.overview": "Vue d'ensemble","settings.page.plan": "Forfait et facturation","settings.page.spending": "Dépenses",+ "settings.page.storage": "Stockage",+ "settings.storage.section": "Espace utilisé",+ "settings.storage.used": "{used} utilisés sur {size}",+ "settings.storage.full": "plein",+ "settings.storage.summary": "Stockage plein à {percent} %",+ "settings.storage.breakdown": "Ce qui occupe l'espace",+ "settings.storage.group.work": "Fichiers de vos bots",+ "settings.storage.group.precious": "Conversations et paramètres",+ "settings.storage.group.rebuildable": "Cache et téléchargements",+ "settings.storage.group.other": "Autre",+ "settings.storage.group.unmeasured": "Non mesuré",+ "settings.storage.unmeasuredNote": "« Non mesuré » correspond à l'espace du système et à tout ce qui a été écrit depuis la dernière mesure.",+ "settings.storage.measured": "Mesuré {when}.",+ "settings.storage.measureAgain": "Mesurer à nouveau",+ "settings.storage.measuring": "Mesure en cours…",+ "settings.storage.firstPass": "Mesure de ce qui occupe cet espace. Sur une grande Cloud, cela peut prendre un moment.",+ "settings.storage.failed": "La dernière mesure n'a pas abouti : ces chiffres viennent de la précédente.",+ "settings.storage.failedFirst": "Impossible de mesurer cet espace pour l'instant. Une nouvelle tentative aura lieu automatiquement.",+ "settings.storage.overcount": "Certains fichiers sont peut-être comptés deux fois : les parties dépassent de {size} l'espace utilisé.",+ "settings.storage.bots": "Bots les plus volumineux",+ "settings.storage.botsNote": "La taille d’un bot inclut son propre cache et ses téléchargements, aussi comptés dans Cache et téléchargements.",+ "settings.storage.unnamedBot": "Bot sans nom",+ "settings.storage.privateBot": "Bot privé",+ "settings.storage.deletedBots": "Bots supprimés",+ "settings.storage.otherBots": "Autres bots",+ "storageNotice.line": "Stockage plein à {percent} %",+ "storageNotice.open": "Ouvrir Stockage dans les paramètres","settings.page.devices": "Appareils","devicesPage.add": "Ajouter un appareil","devicesPage.mapLabel": "Vos appareils et leurs connexions",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex d62e11c6c1..d49980e3ba 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -3278,6 +3278,33 @@"settings.page.overview": "झलक","settings.page.plan": "प्लान और बिलिंग","settings.page.spending": "खर्च",+ "settings.page.storage": "स्टोरेज",+ "settings.storage.section": "इस्तेमाल हुई जगह",+ "settings.storage.used": "{size} में से {used} इस्तेमाल हुआ",+ "settings.storage.full": "भरा",+ "settings.storage.summary": "स्टोरेज {percent}% भरा है",+ "settings.storage.breakdown": "जगह किसमें लगी है",+ "settings.storage.group.work": "आपके बॉट की फ़ाइलें",+ "settings.storage.group.precious": "बातचीत और सेटिंग्स",+ "settings.storage.group.rebuildable": "कैश और डाउनलोड",+ "settings.storage.group.other": "अन्य",+ "settings.storage.group.unmeasured": "नहीं मापा गया",+ "settings.storage.unmeasuredNote": "“नहीं मापा गया” में सिस्टम की अपनी जगह और पिछली माप के बाद लिखा गया सब कुछ शामिल है।",+ "settings.storage.measured": "{when} मापा गया।",+ "settings.storage.measureAgain": "फिर से मापें",+ "settings.storage.measuring": "माप रहे हैं…",+ "settings.storage.firstPass": "यह मापा जा रहा है कि यह जगह किसने घेरी है। बड़े Cloud पर इसमें काफ़ी समय लग सकता है।",+ "settings.storage.failed": "पिछला माप पूरा नहीं हुआ, इसलिए ये आँकड़े उससे पहले वाले माप के हैं।",+ "settings.storage.failedFirst": "अभी तक यह नहीं मापा जा सका कि जगह किसमें लगी है। यह अपने आप फिर कोशिश करेगा।",+ "settings.storage.overcount": "कुछ फ़ाइलें शायद दो बार गिनी गई हैं, इसलिए हिस्सों का जोड़ इस्तेमाल हुई जगह से {size} ज़्यादा है।",+ "settings.storage.bots": "सबसे बड़े बॉट",+ "settings.storage.botsNote": "किसी बॉट के आकार में उसका अपना कैश और डाउनलोड शामिल हैं, जो कैश और डाउनलोड में भी गिने जाते हैं।",+ "settings.storage.unnamedBot": "बिना नाम का बॉट",+ "settings.storage.privateBot": "निजी बॉट",+ "settings.storage.deletedBots": "हटाए गए बॉट",+ "settings.storage.otherBots": "अन्य बॉट",+ "storageNotice.line": "स्टोरेज {percent}% भरा",+ "storageNotice.open": "सेटिंग्स में स्टोरेज खोलें","settings.page.devices": "डिवाइस","devicesPage.add": "डिवाइस जोड़ें","devicesPage.mapLabel": "आपके डिवाइस और वे कैसे जुड़ते हैं",diff --git a/src/locales/it.json b/src/locales/it.jsonindex d00b83fe09..57947a6fae 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -10868,6 +10868,33 @@"settings.page.overview": "Panoramica","settings.page.plan": "Piano e fatturazione","settings.page.spending": "Spese",+ "settings.page.storage": "Spazio",+ "settings.storage.section": "Spazio usato",+ "settings.storage.used": "{used} di {size} usati",+ "settings.storage.full": "pieno",+ "settings.storage.summary": "Spazio pieno al {percent}%",+ "settings.storage.breakdown": "Cosa occupa lo spazio",+ "settings.storage.group.work": "File dei tuoi bot",+ "settings.storage.group.precious": "Conversazioni e impostazioni",+ "settings.storage.group.rebuildable": "Cache e download",+ "settings.storage.group.other": "Altro",+ "settings.storage.group.unmeasured": "Non misurato",+ "settings.storage.unmeasuredNote": "«Non misurato» è lo spazio del sistema e tutto ciò che è stato scritto dall'ultima misurazione.",+ "settings.storage.measured": "Misurato {when}.",+ "settings.storage.measureAgain": "Misura di nuovo",+ "settings.storage.measuring": "Misurazione…",+ "settings.storage.firstPass": "Misurazione di cosa occupa questo spazio. Su una Cloud grande può richiedere un po’ di tempo.",+ "settings.storage.failed": "L'ultima misurazione non è terminata, quindi questi dati sono della precedente.",+ "settings.storage.failedFirst": "Non è stato ancora possibile misurare cosa occupa questo spazio. Si riproverà automaticamente.",+ "settings.storage.overcount": "Alcuni file potrebbero essere contati due volte, quindi le parti superano di {size} lo spazio usato.",+ "settings.storage.bots": "Bot più grandi",+ "settings.storage.botsNote": "La dimensione di un bot include la sua cache e i suoi download, contati anche in Cache e download.",+ "settings.storage.unnamedBot": "Bot senza nome",+ "settings.storage.privateBot": "Bot privato",+ "settings.storage.deletedBots": "Bot eliminati",+ "settings.storage.otherBots": "Altri bot",+ "storageNotice.line": "Spazio pieno al {percent}%",+ "storageNotice.open": "Apri Spazio nelle impostazioni","settings.page.devices": "Dispositivi","devicesPage.add": "Aggiungi un dispositivo","devicesPage.mapLabel": "I tuoi dispositivi e come si collegano",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 1fc760a83f..11e8570fd5 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -7682,6 +7682,33 @@"settings.page.overview": "概要","settings.page.plan": "プランと請求","settings.page.spending": "支出",+ "settings.page.storage": "ストレージ",+ "settings.storage.section": "使用中の容量",+ "settings.storage.used": "{size} 中 {used} を使用",+ "settings.storage.full": "使用済み",+ "settings.storage.summary": "ストレージの {percent}% を使用中",+ "settings.storage.breakdown": "容量の内訳",+ "settings.storage.group.work": "ボットのファイル",+ "settings.storage.group.precious": "会話と設定",+ "settings.storage.group.rebuildable": "キャッシュとダウンロード",+ "settings.storage.group.other": "その他",+ "settings.storage.group.unmeasured": "未計測",+ "settings.storage.unmeasuredNote": "「未計測」は、システムが使う容量と、前回の計測以降に書き込まれたものです。",+ "settings.storage.measured": "{when}に計測しました。",+ "settings.storage.measureAgain": "再計測",+ "settings.storage.measuring": "計測中…",+ "settings.storage.firstPass": "この容量を何が使っているか測定しています。大きな Cloud ではしばらく時間がかかることがあります。",+ "settings.storage.failed": "前回の計測が完了しなかったため、この数値はその前の計測のものです。",+ "settings.storage.failedFirst": "まだ容量の内訳を計測できていません。自動で再試行します。",+ "settings.storage.overcount": "一部のファイルが二重に数えられている可能性があり、内訳の合計が使用量より {size} 多くなっています。",+ "settings.storage.bots": "容量の大きいボット",+ "settings.storage.botsNote": "ボットのサイズには、そのボット自身のキャッシュとダウンロードが含まれ、それらは「キャッシュとダウンロード」にも数えられます。",+ "settings.storage.unnamedBot": "名前のないボット",+ "settings.storage.privateBot": "非公開のボット",+ "settings.storage.deletedBots": "削除したボット",+ "settings.storage.otherBots": "その他のボット",+ "storageNotice.line": "ストレージ {percent}% 使用中",+ "storageNotice.open": "設定でストレージを開く","settings.page.devices": "デバイス","devicesPage.add": "デバイスを追加","devicesPage.mapLabel": "お使いのデバイスと接続方法",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 2ae4934feb..07fbee90de 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7355,6 +7355,33 @@"settings.page.overview": "개요","settings.page.plan": "요금제 및 결제","settings.page.spending": "지출",+ "settings.page.storage": "저장 공간",+ "settings.storage.section": "사용 중인 공간",+ "settings.storage.used": "{size} 중 {used} 사용",+ "settings.storage.full": "사용 중",+ "settings.storage.summary": "저장 공간 {percent}% 사용 중",+ "settings.storage.breakdown": "공간을 차지하는 항목",+ "settings.storage.group.work": "봇 파일",+ "settings.storage.group.precious": "대화 및 설정",+ "settings.storage.group.rebuildable": "캐시 및 다운로드",+ "settings.storage.group.other": "기타",+ "settings.storage.group.unmeasured": "측정되지 않음",+ "settings.storage.unmeasuredNote": "'측정되지 않음'은 시스템이 쓰는 공간과 마지막 측정 이후 기록된 내용입니다.",+ "settings.storage.measured": "{when} 측정함.",+ "settings.storage.measureAgain": "다시 측정",+ "settings.storage.measuring": "측정 중…",+ "settings.storage.firstPass": "이 공간을 무엇이 차지하는지 측정하고 있습니다. 큰 Cloud에서는 시간이 꽤 걸릴 수 있습니다.",+ "settings.storage.failed": "마지막 측정이 끝나지 않아 이 수치는 그 이전 측정의 결과입니다.",+ "settings.storage.failedFirst": "아직 공간 사용 내역을 측정하지 못했습니다. 자동으로 다시 시도합니다.",+ "settings.storage.overcount": "일부 파일이 두 번 집계되었을 수 있어 항목의 합이 사용량보다 {size} 많습니다.",+ "settings.storage.bots": "용량이 큰 봇",+ "settings.storage.botsNote": "봇의 크기에는 봇 자체의 캐시와 다운로드가 포함되며, 이는 캐시 및 다운로드에도 집계됩니다.",+ "settings.storage.unnamedBot": "이름 없는 봇",+ "settings.storage.privateBot": "비공개 봇",+ "settings.storage.deletedBots": "삭제된 봇",+ "settings.storage.otherBots": "기타 봇",+ "storageNotice.line": "저장 공간 {percent}% 사용 중",+ "storageNotice.open": "설정에서 저장 공간 열기","settings.page.devices": "기기","devicesPage.add": "기기 추가","devicesPage.mapLabel": "내 기기와 연결 방식",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex f0f2dd87bf..55d00e8e76 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -6777,6 +6777,33 @@"settings.page.overview": "Przegląd","settings.page.plan": "Plan i płatności","settings.page.spending": "Wydatki",+ "settings.page.storage": "Miejsce na dane",+ "settings.storage.section": "Zajęte miejsce",+ "settings.storage.used": "Zajęte {used} z {size}",+ "settings.storage.full": "zajęte",+ "settings.storage.summary": "Miejsce na dane zajęte w {percent}%",+ "settings.storage.breakdown": "Co zajmuje miejsce",+ "settings.storage.group.work": "Pliki Twoich botów",+ "settings.storage.group.precious": "Rozmowy i ustawienia",+ "settings.storage.group.rebuildable": "Pamięć podręczna i pobrane pliki",+ "settings.storage.group.other": "Inne",+ "settings.storage.group.unmeasured": "Niezmierzone",+ "settings.storage.unmeasuredNote": "„Niezmierzone” to miejsce zajmowane przez system i wszystko, co zapisano od ostatniego pomiaru.",+ "settings.storage.measured": "Zmierzono {when}.",+ "settings.storage.measureAgain": "Zmierz ponownie",+ "settings.storage.measuring": "Trwa pomiar…",+ "settings.storage.firstPass": "Mierzenie, co zajmuje to miejsce. W dużej Cloud może to chwilę potrwać.",+ "settings.storage.failed": "Ostatni pomiar się nie zakończył, więc te dane pochodzą z poprzedniego.",+ "settings.storage.failedFirst": "Nie udało się jeszcze zmierzyć, co zajmuje to miejsce. Kolejna próba nastąpi automatycznie.",+ "settings.storage.overcount": "Niektóre pliki mogły zostać policzone dwa razy, więc części sumują się do {size} więcej, niż jest zajęte.",+ "settings.storage.bots": "Największe boty",+ "settings.storage.botsNote": "Rozmiar bota obejmuje jego własną pamięć podręczną i pobrane pliki, liczone też w grupie Pamięć podręczna i pobrane pliki.",+ "settings.storage.unnamedBot": "Bot bez nazwy",+ "settings.storage.privateBot": "Prywatny bot",+ "settings.storage.deletedBots": "Usunięte boty",+ "settings.storage.otherBots": "Inne boty",+ "storageNotice.line": "Miejsce na dane zajęte w {percent}%",+ "storageNotice.open": "Otwórz Miejsce na dane w ustawieniach","settings.page.devices": "Urządzenia","devicesPage.add": "Dodaj urządzenie","devicesPage.mapLabel": "Twoje urządzenia i sposób ich połączenia",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 0f07eaefb9..19001496d3 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10988,6 +10988,33 @@"settings.page.overview": "Visão geral","settings.page.plan": "Plano e cobrança","settings.page.spending": "Gastos",+ "settings.page.storage": "Armazenamento",+ "settings.storage.section": "Espaço usado",+ "settings.storage.used": "{used} de {size} usados",+ "settings.storage.full": "cheio",+ "settings.storage.summary": "Armazenamento {percent}% cheio",+ "settings.storage.breakdown": "O que ocupa o espaço",+ "settings.storage.group.work": "Arquivos dos seus bots",+ "settings.storage.group.precious": "Conversas e configurações",+ "settings.storage.group.rebuildable": "Cache e downloads",+ "settings.storage.group.other": "Outros",+ "settings.storage.group.unmeasured": "Não medido",+ "settings.storage.unmeasuredNote": "“Não medido” é o espaço do próprio sistema e tudo o que foi gravado desde a última medição.",+ "settings.storage.measured": "Medido {when}.",+ "settings.storage.measureAgain": "Medir de novo",+ "settings.storage.measuring": "Medindo…",+ "settings.storage.firstPass": "Medindo o que usa este espaço. Em uma Cloud grande, isso pode demorar um bom tempo.",+ "settings.storage.failed": "A última medição não terminou, então estes números são da anterior.",+ "settings.storage.failedFirst": "Ainda não foi possível medir o que ocupa este espaço. Uma nova tentativa será feita automaticamente.",+ "settings.storage.overcount": "Alguns arquivos podem ter sido contados duas vezes, então as partes somam {size} a mais do que o usado.",+ "settings.storage.bots": "Maiores bots",+ "settings.storage.botsNote": "O tamanho de um bot inclui o próprio cache e downloads, que também contam em Cache e downloads.",+ "settings.storage.unnamedBot": "Bot sem nome",+ "settings.storage.privateBot": "Bot privado",+ "settings.storage.deletedBots": "Bots excluídos",+ "settings.storage.otherBots": "Outros bots",+ "storageNotice.line": "Armazenamento {percent}% cheio",+ "storageNotice.open": "Abrir Armazenamento nas Configurações","settings.page.devices": "Dispositivos","devicesPage.add": "Adicionar um dispositivo","devicesPage.mapLabel": "Seus dispositivos e como eles se conectam",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 4a11a3e38d..bb056a7442 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -6838,6 +6838,33 @@"settings.page.overview": "Обзор","settings.page.plan": "Тариф и оплата","settings.page.spending": "Расходы",+ "settings.page.storage": "Хранилище",+ "settings.storage.section": "Занятое место",+ "settings.storage.used": "Занято {used} из {size}",+ "settings.storage.full": "занято",+ "settings.storage.summary": "Хранилище заполнено на {percent}%",+ "settings.storage.breakdown": "Что занимает место",+ "settings.storage.group.work": "Файлы ваших ботов",+ "settings.storage.group.precious": "Разговоры и настройки",+ "settings.storage.group.rebuildable": "Кеш и загрузки",+ "settings.storage.group.other": "Другое",+ "settings.storage.group.unmeasured": "Не измерено",+ "settings.storage.unmeasuredNote": "«Не измерено» — это место, которое занимает сама система, и всё, что записано после последнего измерения.",+ "settings.storage.measured": "Измерено {when}.",+ "settings.storage.measureAgain": "Измерить снова",+ "settings.storage.measuring": "Идёт измерение…",+ "settings.storage.firstPass": "Измеряем, что занимает это место. На большом Cloud это может занять немало времени.",+ "settings.storage.failed": "Последнее измерение не завершилось, поэтому цифры взяты из предыдущего.",+ "settings.storage.failedFirst": "Пока не удалось измерить, что занимает это место. Попытка повторится автоматически.",+ "settings.storage.overcount": "Некоторые файлы могли быть посчитаны дважды, поэтому сумма частей на {size} больше занятого места.",+ "settings.storage.bots": "Самые большие боты",+ "settings.storage.botsNote": "Размер бота включает его собственный кеш и загрузки, которые также учитываются в разделе «Кеш и загрузки».",+ "settings.storage.unnamedBot": "Бот без имени",+ "settings.storage.privateBot": "Личный бот",+ "settings.storage.deletedBots": "Удалённые боты",+ "settings.storage.otherBots": "Другие боты",+ "storageNotice.line": "Хранилище заполнено на {percent}%",+ "storageNotice.open": "Открыть «Хранилище» в настройках","settings.page.devices": "Устройства","devicesPage.add": "Добавить устройство","devicesPage.mapLabel": "Ваши устройства и их подключения",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 777db051e1..9d8ee4fda3 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -5575,6 +5575,33 @@"settings.page.overview": "Genel bakış","settings.page.plan": "Plan ve faturalandırma","settings.page.spending": "Harcamalar",+ "settings.page.storage": "Depolama",+ "settings.storage.section": "Kullanılan alan",+ "settings.storage.used": "{size} alanın {used} kadarı kullanılıyor",+ "settings.storage.full": "dolu",+ "settings.storage.summary": "Depolama %{percent} dolu",+ "settings.storage.breakdown": "Alanı ne kullanıyor",+ "settings.storage.group.work": "Botlarınızın dosyaları",+ "settings.storage.group.precious": "Konuşmalar ve ayarlar",+ "settings.storage.group.rebuildable": "Önbellek ve indirmeler",+ "settings.storage.group.other": "Diğer",+ "settings.storage.group.unmeasured": "Ölçülmedi",+ "settings.storage.unmeasuredNote": "\"Ölçülmedi\", sistemin kendi kullandığı alanı ve son ölçümden bu yana yazılan her şeyi kapsar.",+ "settings.storage.measured": "{when} ölçüldü.",+ "settings.storage.measureAgain": "Yeniden ölç",+ "settings.storage.measuring": "Ölçülüyor…",+ "settings.storage.firstPass": "Bu alanı neyin kullandığı ölçülüyor. Büyük bir Cloud’da bu biraz zaman alabilir.",+ "settings.storage.failed": "Son ölçüm tamamlanmadı, bu yüzden bu rakamlar bir önceki ölçümden.",+ "settings.storage.failedFirst": "Bu alanı neyin kullandığı henüz ölçülemedi. Kendiliğinden yeniden denenecek.",+ "settings.storage.overcount": "Bazı dosyalar iki kez sayılmış olabilir, bu yüzden parçaların toplamı kullanılandan {size} fazla.",+ "settings.storage.bots": "En büyük botlar",+ "settings.storage.botsNote": "Bir botun boyutu kendi önbelleğini ve indirmelerini içerir; bunlar Önbellek ve indirmeler altında da sayılır.",+ "settings.storage.unnamedBot": "Adsız bot",+ "settings.storage.privateBot": "Özel bot",+ "settings.storage.deletedBots": "Silinen botlar",+ "settings.storage.otherBots": "Diğer botlar",+ "storageNotice.line": "Depolama %{percent} dolu",+ "storageNotice.open": "Ayarlar'da Depolama'yı aç","settings.page.devices": "Cihazlar","devicesPage.add": "Cihaz ekle","devicesPage.mapLabel": "Cihazlarınız ve nasıl bağlandıkları",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex e237814604..e90a4d2479 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -3713,6 +3713,33 @@"settings.page.overview": "Огляд","settings.page.plan": "План і оплата","settings.page.spending": "Витрати",+ "settings.page.storage": "Сховище",+ "settings.storage.section": "Зайняте місце",+ "settings.storage.used": "Зайнято {used} з {size}",+ "settings.storage.full": "зайнято",+ "settings.storage.summary": "Сховище заповнене на {percent}%",+ "settings.storage.breakdown": "Що займає місце",+ "settings.storage.group.work": "Файли ваших ботів",+ "settings.storage.group.precious": "Розмови й налаштування",+ "settings.storage.group.rebuildable": "Кеш і завантаження",+ "settings.storage.group.other": "Інше",+ "settings.storage.group.unmeasured": "Не виміряно",+ "settings.storage.unmeasuredNote": "«Не виміряно» — це місце, яке займає сама система, і все, що записано після останнього вимірювання.",+ "settings.storage.measured": "Виміряно {when}.",+ "settings.storage.measureAgain": "Виміряти знову",+ "settings.storage.measuring": "Триває вимірювання…",+ "settings.storage.firstPass": "Вимірюємо, що займає це місце. На великому Cloud це може тривати чимало часу.",+ "settings.storage.failed": "Останнє вимірювання не завершилося, тому ці цифри з попереднього.",+ "settings.storage.failedFirst": "Поки не вдалося виміряти, що займає це місце. Спроба повториться автоматично.",+ "settings.storage.overcount": "Деякі файли могли бути пораховані двічі, тому сума частин на {size} більша за зайняте місце.",+ "settings.storage.bots": "Найбільші боти",+ "settings.storage.botsNote": "Розмір бота містить його власний кеш і завантаження, які також враховано в розділі «Кеш і завантаження».",+ "settings.storage.unnamedBot": "Бот без назви",+ "settings.storage.privateBot": "Особистий бот",+ "settings.storage.deletedBots": "Видалені боти",+ "settings.storage.otherBots": "Інші боти",+ "storageNotice.line": "Сховище заповнене на {percent}%",+ "storageNotice.open": "Відкрити «Сховище» в налаштуваннях","settings.page.devices": "Пристрої","devicesPage.add": "Додати пристрій","devicesPage.mapLabel": "Ваші пристрої та їхні з'єднання",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 16b2b78992..36fc406abc 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -5575,6 +5575,33 @@"settings.page.overview": "Tổng quan","settings.page.plan": "Gói và thanh toán","settings.page.spending": "Chi tiêu",+ "settings.page.storage": "Dung lượng lưu trữ",+ "settings.storage.section": "Dung lượng đã dùng",+ "settings.storage.used": "Đã dùng {used} / {size}",+ "settings.storage.full": "đã dùng",+ "settings.storage.summary": "Đã dùng {percent}% dung lượng lưu trữ",+ "settings.storage.breakdown": "Những gì chiếm dung lượng",+ "settings.storage.group.work": "Tệp của bot",+ "settings.storage.group.precious": "Cuộc trò chuyện và cài đặt",+ "settings.storage.group.rebuildable": "Bộ nhớ đệm và tệp tải xuống",+ "settings.storage.group.other": "Khác",+ "settings.storage.group.unmeasured": "Chưa đo",+ "settings.storage.unmeasuredNote": "“Chưa đo” là dung lượng của chính hệ thống và mọi thứ được ghi từ lần đo gần nhất.",+ "settings.storage.measured": "Đã đo {when}.",+ "settings.storage.measureAgain": "Đo lại",+ "settings.storage.measuring": "Đang đo…",+ "settings.storage.firstPass": "Đang đo những gì chiếm dung lượng này. Trên một Cloud lớn, việc này có thể mất khá lâu.",+ "settings.storage.failed": "Lần đo gần nhất chưa hoàn tất nên các số liệu này là của lần trước đó.",+ "settings.storage.failedFirst": "Chưa đo được những gì chiếm dung lượng này. Hệ thống sẽ tự thử lại.",+ "settings.storage.overcount": "Một số tệp có thể bị tính hai lần nên tổng các phần nhiều hơn dung lượng đã dùng {size}.",+ "settings.storage.bots": "Bot lớn nhất",+ "settings.storage.botsNote": "Kích thước của một bot gồm cả bộ nhớ đệm và tệp tải xuống của chính nó, cũng được tính trong Bộ nhớ đệm và tệp tải xuống.",+ "settings.storage.unnamedBot": "Bot chưa đặt tên",+ "settings.storage.privateBot": "Bot riêng tư",+ "settings.storage.deletedBots": "Bot đã xóa",+ "settings.storage.otherBots": "Bot khác",+ "storageNotice.line": "Dung lượng lưu trữ đã dùng {percent}%",+ "storageNotice.open": "Mở Dung lượng lưu trữ trong Cài đặt","settings.page.devices": "Thiết bị","devicesPage.add": "Thêm thiết bị","devicesPage.mapLabel": "Các thiết bị của bạn và cách chúng kết nối",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 76976e722d..1813d53e9a 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -9920,6 +9920,33 @@"settings.page.overview": "總覽","settings.page.plan": "方案和帳單","settings.page.spending": "花費",+ "settings.page.storage": "儲存空間",+ "settings.storage.section": "已用空間",+ "settings.storage.used": "已使用 {used},共 {size}",+ "settings.storage.full": "已用",+ "settings.storage.summary": "儲存空間已用 {percent}%",+ "settings.storage.breakdown": "空間使用情形",+ "settings.storage.group.work": "機器人的檔案",+ "settings.storage.group.precious": "對話和設定",+ "settings.storage.group.rebuildable": "快取和下載",+ "settings.storage.group.other": "其他",+ "settings.storage.group.unmeasured": "未測量",+ "settings.storage.unmeasuredNote": "「未測量」是系統本身使用的空間,以及上次測量後寫入的內容。",+ "settings.storage.measured": "{when}測量。",+ "settings.storage.measureAgain": "重新測量",+ "settings.storage.measuring": "正在測量…",+ "settings.storage.firstPass": "正在測量佔用此空間的內容。在大型 Cloud 上可能需要一段時間。",+ "settings.storage.failed": "上次測量未完成,因此這些數字來自更早的一次測量。",+ "settings.storage.failedFirst": "暫時無法測量空間使用情形,稍後會自動重試。",+ "settings.storage.overcount": "部分檔案可能被重複計算,因此各項合計比已用空間多 {size}。",+ "settings.storage.bots": "占用最多的機器人",+ "settings.storage.botsNote": "機器人的大小包含它自己的快取和下載內容,這些也計入「快取和下載」。",+ "settings.storage.unnamedBot": "未命名的機器人",+ "settings.storage.privateBot": "私人機器人",+ "settings.storage.deletedBots": "已刪除的機器人",+ "settings.storage.otherBots": "其他機器人",+ "storageNotice.line": "儲存空間已用 {percent}%",+ "storageNotice.open": "在設定中開啟儲存空間","settings.page.devices": "裝置","devicesPage.add": "新增裝置","devicesPage.mapLabel": "你的裝置及其連線方式",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 56ed4d0bfc..19cf80bdd7 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -8223,6 +8223,33 @@"settings.page.overview": "总览","settings.page.plan": "方案和账单","settings.page.spending": "花费",+ "settings.page.storage": "存储空间",+ "settings.storage.section": "已用空间",+ "settings.storage.used": "已使用 {used},共 {size}",+ "settings.storage.full": "已用",+ "settings.storage.summary": "存储空间已用 {percent}%",+ "settings.storage.breakdown": "空间占用情况",+ "settings.storage.group.work": "机器人的文件",+ "settings.storage.group.precious": "对话和设置",+ "settings.storage.group.rebuildable": "缓存和下载",+ "settings.storage.group.other": "其他",+ "settings.storage.group.unmeasured": "未测量",+ "settings.storage.unmeasuredNote": "“未测量”是系统自身占用的空间,以及上次测量后写入的内容。",+ "settings.storage.measured": "{when}测量。",+ "settings.storage.measureAgain": "重新测量",+ "settings.storage.measuring": "正在测量…",+ "settings.storage.firstPass": "正在测量占用此空间的内容。在大型 Cloud 上可能需要较长时间。",+ "settings.storage.failed": "上次测量未完成,因此这些数字来自更早的一次测量。",+ "settings.storage.failedFirst": "暂时无法测量空间占用情况,稍后会自动重试。",+ "settings.storage.overcount": "部分文件可能被重复计算,因此各项合计比已用空间多 {size}。",+ "settings.storage.bots": "占用最多的机器人",+ "settings.storage.botsNote": "机器人的大小包括它自己的缓存和下载内容,这些也计入“缓存和下载”。",+ "settings.storage.unnamedBot": "未命名的机器人",+ "settings.storage.privateBot": "私人机器人",+ "settings.storage.deletedBots": "已删除的机器人",+ "settings.storage.otherBots": "其他机器人",+ "storageNotice.line": "存储空间已用 {percent}%",+ "storageNotice.open": "在设置中打开存储空间","settings.page.devices": "设备","devicesPage.add": "添加设备","devicesPage.mapLabel": "你的设备及其连接方式",diff --git a/src/state/store.tsx b/src/state/store.tsxindex f1660cdd70..4c67fef9c2 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -469,7 +469,7 @@ export type AppSettingsSection = SettingsPageId| "desktopWorkspaces" | "organization" | "cloudAccount" | "experimental" | "connections" | "decisionModel" | "imageGeneration"| "engines" | "companion" | "remote" | "computer" | "logins" | "botAccess" | "activity" | "backups" | "workspaces"| "skills" | "import" | "updates";-export type SettingsPageId = "overview" | "devices" | "phone" | "ai" | "bots" | "desktops" | "vault" | "usage" | "transfer" | "data" | "people"+export type SettingsPageId = "overview" | "devices" | "phone" | "ai" | "bots" | "desktops" | "vault" | "usage" | "transfer" | "storage" | "data" | "people"| "installations" | "account" | "plan" | "app" | "general" | "appearance";export type BotSettingsSection =diff --git a/src/storage-preview.tsx b/src/storage-preview.tsxnew file mode 100644index 0000000000..db2642c2d3--- /dev/null+++ b/src/storage-preview.tsx@@ -0,0 +1,97 @@+// Dev-only: the real Settings window and the real sidebar foot against a Cloud home's answers, served at+// /storage-preview.html; not in the packaged app. Every request is answered here, so it needs no server.+// ?view=settings|sidebar&page=storage|overview&state=none|first|normal|near|full&skin=midnight|daylight&lang=de&team=1+import { StrictMode, useEffect } from "react";+import { createRoot } from "react-dom/client";+import "./styles.css";++const GB = 1024 ** 3;+const params = new URLSearchParams(location.search);+const view = params.get("view") ?? "settings";+const page = params.get("page") ?? "storage";+const state = params.get("state") ?? "normal";+const USED: Record<string, number> = { first: 41, normal: 50, near: 84, full: 93 };+const used = USED[state] ?? 50;+/** A Team Cloud's admin: "bot-x7" is a teammate's own MausBot, which the app never lists for anyone else. */+const team = params.get("team") === "1";++const report = state === "first"+ ? { at: null, ageS: null, tookS: null, running: true, progress: { entries: 21_000, waitedS: 0 }, volume: null, walkedBytes: null, unwalkedBytes: null,+ categories: [], bots: [], botsRest: { bytes: 0, files: 0, count: 0 }, botsGone: { bytes: 0, files: 0, count: 0 }, other: null, skipped: null,+ linksCapped: false, linksUncheckedBytes: 0, resumes: 0, failed: false }+ : { at: Date.now() - 2 * 3_600_000, ageS: 2 * 3_600, tookS: 540, running: false, progress: null,+ volume: { totalBytes: 100 * GB, freeBytes: (100 - used) * GB, usedBytes: used * GB }, walkedBytes: (used - 1.6) * GB, unwalkedBytes: 1.6 * GB,+ categories: [+ { name: "bot_files", class: "work", bytes: used * 0.38 * GB, files: 41_000 },+ { name: "packages", class: "rebuildable", bytes: used * 0.22 * GB, files: 380_000 },+ { name: "conversations", class: "precious", bytes: used * 0.14 * GB, files: 2_400 },+ { name: "browser_cache", class: "rebuildable", bytes: used * 0.07 * GB, files: 9_000 },+ { name: "attachments", class: "work", bytes: used * 0.06 * GB, files: 1_200 },+ { name: "engine_state", class: "precious", bytes: used * 0.04 * GB, files: 800 },+ { name: "other", class: "work", bytes: (used * 0.09 - 1.6) * GB, files: 300 },+ ],+ bots: [{ id: "chief", bytes: used * 0.19 * GB, files: 20_000 }, { id: "research", bytes: used * 0.11 * GB, files: 9_000 },+ { id: "bot-x7", bytes: used * 0.04 * GB, files: 2_000 }, { id: "inbox", bytes: used * 0.02 * GB, files: 900 }],+ botsRest: { bytes: used * 0.03 * GB, files: 1_000, count: 2 }, botsGone: { bytes: used * 0.025 * GB, files: 800, count: 1 }, other: null, skipped: null,+ linksCapped: false, linksUncheckedBytes: 0, resumes: 0, failed: false };+const storage = state === "none" ? { storage: null } : { storage: report, now: { totalBytes: 100 * GB, freeBytes: (100 - used) * GB, usedBytes: used * GB }, measureInS: 0,+ server: "5d0c6f2e-9c1a-4c57-8f0e-2b7a1d3e4f50" };++const CONFIG = {+ composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" },+ rooms: { turnTimeoutMinutes: 10 }, localVm: { mode: "shared", maxInstances: 1 },+ profile: { name: "Maya Shah", email: "[email protected]" }, features: { savedSteps: false },+ onboarding: { completedAt: "2026-01-01", version: 1, reelSeen: true, hintsSeen: [] },+ edition: { edition: "community", features: [] }, browserProfiles: [], managedPolicy: null,+ signIn: { admins: [], members: [] }, membership: { authority: "local", pairingCodes: true }, cloudHome: true,+ ...(team ? { team: { id: "team-1", name: "Studio" } } : {}),+};+const ANSWERS: Record<string, unknown> = {+ "/api/instances": { instances: [] }, "/api/config": CONFIG,+ "/api/auth/session": { kind: "session", id: "s1", label: "Chrome on Mac", email: "[email protected]", scopes: ["admin", "client"], expiresAt: 0 },+ "/api/auth/sessions": { sessions: [{ id: "s1" }], current: "s1" }, "/api/routines": { routines: [], runs: [] }, "/api/webhooks": { webhooks: [], attempts: [] },+ "/api/bots": { bots: [{ id: "chief", name: "Chief", threadId: "t-chief" }, { id: "research", name: "Research", threadId: "t-research" }, { id: "inbox", name: "Inbox", threadId: "t-inbox" }], groups: [] },+ "/api/diagnostics/storage": storage,+};+const realFetch = window.fetch.bind(window);+window.fetch = (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input instanceof Request ? input.url : input), location.href);+ if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return realFetch(input, init);+ return Promise.resolve(new Response(JSON.stringify(ANSWERS[url.pathname] ?? {}), { headers: { "content-type": "application/json" } }));+};+class QuietEventSource {+ onopen: (() => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string }) => void) | null = null;+ readyState = 1;+ constructor(readonly url: string) { setTimeout(() => this.onmessage?.({ data: JSON.stringify({ kind: "hello", resumed: false, cursor: "run:0" }) }), 50); }+ addEventListener() {} removeEventListener() {} close() {}+}+Object.assign(window, { EventSource: QuietEventSource });+try {+ for (const key of Object.keys(localStorage)) if (key.startsWith("openmausbot.storageNotice.seen.v1")) localStorage.removeItem(key);+ // Simple mode, the default for a new install, unless ?mode=advanced.+ localStorage.setItem("omb-advanced-mode", params.get("mode") === "advanced" ? "1" : "0");+} catch { /* blocked storage */ }++const [{ StoreProvider }, { useStoreDispatch, useStoreSelector }, { SettingsModal }, { SidebarFooter }, { applySkin, readSkin, SKIN_IDS }, { loadLocale }] = await Promise.all([+ import("@/state/store"), import("@/state/store-select"), import("@/components/SettingsModal"), import("@/components/SidebarFooter"), import("@/lib/skins"), import("@/lib/i18n"),+]);++function SettingsView() {+ const loaded = useStoreSelector((app) => app.config !== null), open = useStoreSelector((app) => app.appSettingsOpen), dispatch = useStoreDispatch();+ useEffect(() => { if (loaded) dispatch({ type: "toggleAppSettings", open: true, section: page as never }); }, [loaded, dispatch]);+ return open ? <SettingsModal /> : null;+}++function SidebarView() {+ return <div className="flex h-screen bg-app text-ink">+ <aside className="flex w-[280px] shrink-0 flex-col justify-end border-e border-hairline/40 bg-panel">+ <SidebarFooter density="comfortable" simple toolsCollapsed={false} />+ </aside>+ <main className="flex-1" />+ </div>;+}++const asked = params.get("skin");+applySkin((SKIN_IDS as readonly string[]).includes(asked ?? "") ? asked as Parameters<typeof applySkin>[0] : readSkin());+await loadLocale(params.get("lang") ?? "en");+createRoot(document.getElementById("root")!).render(<StrictMode><StoreProvider>{view === "sidebar" ? <SidebarView /> : <SettingsView />}</StoreProvider></StrictMode>);diff --git a/storage-preview.html b/storage-preview.htmlnew file mode 100644index 0000000000..98be017312--- /dev/null+++ b/storage-preview.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Storage Preview</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/storage-preview.tsx"></script>+ </body>+</html>