Skip to content

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

Cloud home storage report: what fills the volume, by category, in the health read (#7118)

Milind Sonicd5c2a0ec799
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 6054dae59c..b9132374d7 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1859,6 +1859,68 @@ run in place of the missed occurrence, which gets no record; and occurrences
that fall while a routine is held (its owner left) are not recorded, because a
held routine is off.
+**`storage`** says what fills the volume (`server/perf/disk-usage.ts`), from
+the last full pass of a slow walk over HOME (the volume) and the data folder
+inside it. It sits beside `perf` with its own budget of 4 KB, and the field is
+left out where nothing is measured or its read fails; the health read never
+starts a walk.
+
+```json
+"storage": { "v": 1, "at": 1790000000000, "ageS": 300, "tookS": 1500, "running": false, "progress": null,
+ "volume": { "totalBytes": 84000000000, "freeBytes": 3400000000, "usedBytes": 80600000000 },
+ "walkedBytes": 80100000000, "unwalkedBytes": 500000000,
+ "categories": [{ "name": "engine_state", "class": "precious", "bytes": 41000000000, "files": 210000 },
+ { "name": "bot_files", "class": "work", "bytes": 22000000000, "files": 90000 }],
+ "bots": [{ "id": "<uuid>", "bytes": 20000000000, "files": 80000 }], "botsRest": { "bytes": 2000000000, "files": 10000, "count": 3 },
+ "other": { "named": [{ "name": "lost+found", "bytes": 16384, "files": 0 }], "unlisted": { "bytes": 1200000, "files": 40, "entries": 2 } },
+ "skipped": { "unreadable": 0, "otherDevice": 0, "tooDeep": 0, "vanished": 12, "links": 340 },
+ "linksCapped": false, "linksUncheckedBytes": 0, "resumes": 1, "failed": false }
+```
+
+- **Categories** are fixed names, each with its class (`server/perf/disk-categories.ts`):
+ `precious` (only this home holds it: `conversations`, `settings`,
+ `engine_state`, `browser_profiles`), `work` (what bots and people made or
+ may still read: `bot_files`, `attachments`, `synced`, `backups`, `trash`,
+ `logs`, `other`) or `rebuildable` (made again when missing:
+ `browser_cache`, `browser_engines`, `engine_clis`, `packages`, `caches`,
+ `temp`). Only a name the code lists is ever rebuildable; anything unknown
+ is `other`. A `node_modules` folder inside a bot's or person's folder
+ counts as `packages`. Bytes are allocated blocks, so a sparse file counts
+ what it takes on disk.
+- **Hard links** count once, checked by inode for up to 500,000 linked
+ files. Past that, `linksCapped` is true and `linksUncheckedBytes` is the
+ most that may be counted twice.
+- **`bots`** are the ten bots with the most bytes in `workspaces/`,
+ `task-workspaces/` and `bots/`, by id, and only bots the store knows. Every
+ other bot folder is summed in `botsRest`.
+- **`other`** names a first-level folder only from a fixed list of names our
+ code or the filesystem makes (`lost+found` and a few shell history files).
+ Anything else is summed in `unlisted` with no name, so a person's folder
+ name never leaves the home.
+- **`unwalkedBytes`** is the space the volume reports used minus what the
+ walk counted. It is positive for what the walk cannot see, such as deleted
+ files a process still holds open and filesystem metadata. It is negative
+ when the walk counted too much, which only happens past the hard-link check
+ or in a pass resumed after a restart (`resumes`).
+- **The cost.** A pass reads names and sizes only (lstat): it never opens a
+ file, never follows a link and never leaves the volume's filesystem. Each
+ tick, every 2 seconds, reads at most 2,000 entries or 25 ms. No tick starts
+ while a turn runs, and a tick stops at its next entry once one starts.
+ `progress.waitedS` is how long the current pass has waited for turns, so a
+ home that is never idle shows as one whose pass does not finish. The first
+ pass starts 2 minutes after boot, and the next one 6 hours after each pass
+ ends. The last pass is kept in the data folder's
+ `cache/storage-report.json`, and the pass under way in
+ `cache/storage-progress.json`, saved at most once a minute between two
+ folders of the top four levels. Backups leave both out. A home that sleeps
+ by stopping keeps its report and picks the pass up where it left off.
+ Node has no per-call I/O priority, and lowering the server's own priority
+ would slow everything else, so the budget is the only throttle.
+
+The owner's own session can read the same report at
+`GET /api/diagnostics/storage` (admin scope; `{ "storage": null }` on
+anything but a Cloud home).
+
**What it never carries:** a failure's words, a bot's name, a thread's title,
a prompt, a URL, an email address, a token, or an engine's account
(`ProviderSnapshot.account`). Only fixed codes, counts, times, versions, engine
diff --git a/server/cloud-health.test.ts b/server/cloud-health.test.ts
index 9ca3adaf41..553b09920b 100644
--- a/server/cloud-health.test.ts
+++ b/server/cloud-health.test.ts
@@ -14,6 +14,7 @@ import { memoryStallText, memoryStopText } from "./engine-memory.ts";
import type { RuntimeEvent } from "./contracts.ts";
import { doctorAtStart } from "./doctor/start.ts";
import { toolFailureMessage } from "./drivers/tool-failure.ts";
+import { STORAGE_HEALTH_MAX_BYTES, type StorageReport } from "./perf/disk-usage.ts";
import { createCloudSignedRoutes } from "./routes/cloud-signed.ts";
import { SessionRegistry } from "./sessions.ts";
import { Store } from "./store.ts";
@@ -50,6 +51,28 @@ function world(overrides: Partial<CloudHealthDeps> = {}) {
const incidents = (w: ReturnType<typeof world>, after?: string) => w.health.report(after).incidents.map(({ kind, code, engine, count }) => ({ kind, code, engine, count }));
const place = (state: PlaceRow["state"]): PlaceRow => ({ state, params: { bot: "Tallyspoon Ops", cause: "Boat said: quota exceeded for [email protected]." }, source: "works-on" });
+describe("a Cloud home's storage in its health report", () => {
+ const report = (bots: number): StorageReport => ({
+ v: 1, at: START, ageS: 0, tookS: 60, running: false, progress: null, volume: { totalBytes: 84e9, freeBytes: 3e9, usedBytes: 81e9 }, walkedBytes: 80e9, unwalkedBytes: 1e9,
+ categories: [{ name: "engine_state", class: "precious", bytes: 50e9, files: 10 }], bots: Array.from({ length: bots }, (_, index) => ({ id: `${"b".repeat(60)}${index}`, bytes: 1e9, files: 1 })),
+ botsRest: { bytes: 0, files: 0, count: 0 }, other: null, skipped: null, linksCapped: false, linksUncheckedBytes: 0, resumes: 0, failed: false,
+ });
+
+ it("carries the last breakdown within its own budget, and leaves the field out where it is not measured or its read throws", () => {
+ expect(world({ storage: () => report(2) }).health.report(undefined)).toMatchObject({ storage: { v: 1, volume: { usedBytes: 81e9 }, categories: [{ name: "engine_state" }] } });
+ const big = world({ storage: () => report(200) }).health.report(undefined).storage!;
+ expect(JSON.stringify(big).length).toBeLessThanOrEqual(STORAGE_HEALTH_MAX_BYTES);
+ expect(big.botsRest.count).toBeGreaterThan(0);
+ expect(world().health.report(undefined)).not.toHaveProperty("storage");
+ expect(world({ storage: () => null }).health.report(undefined)).not.toHaveProperty("storage");
+ const warned: string[] = [];
+ const broken = world({ storage: () => { throw new RangeError("at /Users/ada/secret"); }, log: (line) => warned.push(line) });
+ expect(broken.health.report(undefined)).not.toHaveProperty("storage");
+ broken.health.report(undefined);
+ expect(warned).toEqual(["cloud health: storage left out: RangeError"]);
+ });
+});
+
describe("a Cloud home's memory pressure in its health report", () => {
it("carries the last day's counts where the home watches memory, and null where it does not", () => {
expect(world().health.report(undefined)).toMatchObject({ room: null });
diff --git a/server/cloud-health.ts b/server/cloud-health.ts
index 674ccc7939..264eb3616b 100644
--- a/server/cloud-health.ts
+++ b/server/cloud-health.ts
@@ -14,6 +14,7 @@ import type { ProviderSnapshot, RuntimeEvent } from "./contracts.ts";
import { createCloudSpeed, type CloudSpeed } from "./cloud-speed.ts";
import { doctorSummary } from "./doctor/start.ts";
import { classifyError } from "./drivers/retry.ts";
+import { storageHealth, type StorageReport } from "./perf/disk-usage.ts";
import type { PerfHealth } from "./perf/perf-report.ts";
import type { RoutineHealth } from "./routine-health.ts";
import type { ScheduleSection } from "./routine-schedule-report.ts";
@@ -254,6 +255,8 @@ export interface CloudHealthDeps {
/** Turn phase timings, usage-limit holds, process buckets and event-loop lag: at most PERF_HEALTH_MAX_BYTES. A throw
* reads as null: the Admin restarts a home whose health read fails, so this optional part never fails it. */
perf?: () => PerfHealth | null;
+ /** What fills the volume (perf/disk-usage.ts), at most STORAGE_HEALTH_MAX_BYTES; the field is left out on a throw or null. */
+ storage?: () => StorageReport | null;
log?: (line: string) => void;
now?: () => number;
}
@@ -288,12 +291,17 @@ export function createCloudHealth(deps: CloudHealthDeps) {
deps.bus.subscribe((event) => { ledger.noteEvent(event); speed.noteEvent(event); });
const connectors = backgroundLookup(deps.connectors, CONNECTORS_TTL_MS, now);
const version = match(VERSION, deps.version) ?? "unknown", image = match(IMAGE, deps.image);
- let perfWarnedAt = -Infinity;
+ const warnedAt = new Map<string, number>();
+ const leftOut = (part: string, error: unknown) => {
+ if (now() - (warnedAt.get(part) ?? -Infinity) < 60_000) return;
+ warnedAt.set(part, now());
+ (deps.log ?? console.warn)(`cloud health: ${part} left out: ${error instanceof Error ? error.name : "error"}`);
+ };
const perf = () => {
- try { return deps.perf?.() ?? null; } catch (error) {
- if (now() - perfWarnedAt >= 60_000) { perfWarnedAt = now(); (deps.log ?? console.warn)(`cloud health: perf left out: ${error instanceof Error ? error.name : "error"}`); }
- return null;
- }
+ try { return deps.perf?.() ?? null; } catch (error) { leftOut("perf", error); return null; }
+ };
+ const storage = (): { storage?: StorageReport } => {
+ try { const report = deps.storage?.(); return report ? { storage: storageHealth(report) } : {}; } catch (error) { leftOut("storage", error); return {}; }
};
const engines = () => {
@@ -323,7 +331,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {
engines: engines(), connectors: connectorState(),
browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },
box: boxSummary(deps.box?.()),
- firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(), perf: perf(),
+ firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(), perf: perf(), ...storage(),
// The data checks of this version's first start: check ids and counts (server/doctor/start.ts).
doctor: doctorHealth(),
system: { ...memory, rssBytes: process.memoryUsage.rss(), load1: loadavg()[0] ?? 0, cpus: availableParallelism(), disk: diskBytes(deps.dataDir), eventLogWritable: writable(deps.eventsDir) },
diff --git a/server/index.ts b/server/index.ts
index 072ff3fd7f..4dd680d681 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -636,7 +636,7 @@ import { createPersonReplies } from "./person-replies.ts";
import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey, relayedPersonKey } from "./person-key.ts"; import { ownWindowLine } from "./own-window-sends.ts";
import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";
import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";
-import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
+import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { cloudStorage, createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";
import { createThreadRoutes } from "./routes/threads.ts";
import { createWebhookRoutes } from "./routes/webhooks.ts"; import { createRemoteTeammateRoutes } from "./routes/remote-teammates.ts"; import { RemoteTeammates } from "./remote-teammates.ts"; import { createRemoteHandoff, isRemoteBotId } from "./host/remote-teammate-handoff.ts";
@@ -2762,7 +2762,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPers
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const refusedLending = createRefusedLending({ runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, lentDevice: () => { const lent = lentNow(); return lent ? deviceWord(lent.platform) : null; }, language: conversationLanguage }); const takeRefusedRun = (threadId: string) => refusedLending.ending(threadId, refusedHandoffs.take(threadId)); /** The computer the person lends My Cloud now, newest first: one source for the word every refusal names it by. */ function lentNow() { return sharedComputers.known(CLOUD_HOME_LENDER).find((one) => one.lent); } const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, watchStalls: !DESKTOP_MANAGED, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME), ...(DESKTOP_MANAGED ? { launches: { launchId: process.env.OMB_DESKTOP_LAUNCH_ID ?? null, server: launchServerPart, counts: () => ({ bots: store.bots.length, threads: store.bots.reduce((sum, bot) => sum + (bot.tasks?.length ?? 0), 0) }) } } : {}) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const refusedLending = createRefusedLending({ runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, lentDevice: () => { const lent = lentNow(); return lent ? deviceWord(lent.platform) : null; }, language: conversationLanguage }); const takeRefusedRun = (threadId: string) => refusedLending.ending(threadId, refusedHandoffs.take(threadId)); /** The computer the person lends My Cloud now, newest first: one source for the word every refusal names it by. */ function lentNow() { return sharedComputers.known(CLOUD_HOME_LENDER).find((one) => one.lent); } const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, watchStalls: !DESKTOP_MANAGED, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME), ...cloudStorage(CLOUD_HOME, homedir(), (id) => Boolean(store.bot(id))), ...(DESKTOP_MANAGED ? { launches: { launchId: process.env.OMB_DESKTOP_LAUNCH_ID ?? null, server: launchServerPart, counts: () => ({ bots: store.bots.length, threads: store.bots.reduce((sum, bot) => sum + (bot.tasks?.length ?? 0), 0) }) } } : {}) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
@@ -2780,7 +2780,7 @@ const phones = createPhones({
active: (turn) => internalCapabilityIsActive(turn as InternalCapability),
});
const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, routineThread: (botId, threadId) => { const run = activeRoutineRunForThread(threadId); return run?.botId === botId && run.target === "bot"; }, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); let starterRoutineWake: StarterRoutineWake | undefined; /* made beside tieAutomationsToBots, once the routines and triggers are */ const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.
-const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,
+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, storage: perf.storage, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,
engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),
connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),
browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });
@@ -9373,7 +9373,7 @@ const appTriggers = createAppTriggerHost({ store, webhooks, webhookBase: () => w
audit: (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, 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, 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-categories.test.ts b/server/perf/disk-categories.test.ts
new file mode 100644
index 0000000000..02817ea767
--- /dev/null
+++ b/server/perf/disk-categories.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from "vitest";
+
+import { placeChild, placeStoragePath, STORAGE_CATEGORIES, storageSegments, type Placement, type StorageScope } from "./disk-categories.ts";
+
+/** Places a path the way the walk does: each segment from its parent's placement. */
+function place(scope: StorageScope, path: string, directory = false): Placement {
+ const segments = storageSegments(path);
+ let placement: Placement = { category: scope === "data" ? "settings" : "other", final: false };
+ segments.forEach((_, index) => { placement = placeChild(placement, scope, segments.slice(0, index + 1), index < segments.length - 1 || directory); });
+ return placement;
+}
+const category = (scope: StorageScope, path: string, directory = false) => place(scope, path, directory).category;
+
+describe("storage categories", () => {
+ it("files every data-folder path class where its writer puts it", () => {
+ const cases: Array<[string, string]> = [
+ ["messages.db", "conversations"], ["messages.db-wal", "conversations"], ["runtime.db-shm", "conversations"], ["bursts.db", "conversations"],
+ ["events/thread-1.ndjson", "conversations"], ["native/thread-1.ndjson", "conversations"], ["checkpoints/a/b", "conversations"], ["memory-journal/bot.jsonl", "conversations"],
+ ["config.json", "settings"], ["bots.json", "settings"], ["routines.json", "settings"], ["sessions.json", "settings"], ["environment-id", "settings"],
+ ["logins.json.enc", "settings"], ["providers/claude/auth.json", "settings"], ["people/a/b.json", "settings"], ["skills/x/SKILL.md", "settings"],
+ ["engine-homes/team/.claude/projects/x.jsonl", "engine_state"], ["pi-sessions/local/k", "engine_state"],
+ ["workspaces/bot1/notes.md", "bot_files"], ["task-workspaces/bot1/thread1/out.csv", "bot_files"], ["bots/bot1/SOUL.md", "bot_files"],
+ ["bots/bot1/data.duckdb", "bot_files"], ["team-files/report.pdf", "bot_files"], ["vm-homes/abc/x", "bot_files"],
+ ["attachments/a.png", "attachments"], ["attachment-originals/a", "attachments"], ["box-uploads/b/t/f", "attachments"], ["browser-uploads/f", "attachments"],
+ ["tool-results/t/r.json", "attachments"], ["meetings/m/rec.wav", "attachments"], ["browser/downloads/abc/file.zip", "attachments"],
+ ["sync/lent/f", "synced"], ["sync/trash/123", "trash"], ["sync/uploads/part", "temp"], ["engine-homes/.held/old", "trash"],
+ [".backups/job/staged/data", "backups"], ["doctor-backups/2026/x", "backups"],
+ ["browser/profiles/abc/Default/Cookies", "browser_profiles"], ["browser/profiles/abc/Default/Login Data", "browser_profiles"],
+ ["browser/profiles/abc/Local State", "browser_profiles"], ["browser/workspace-id", "browser_profiles"], ["agent-browser-profiles/abc/Default/Cookies", "browser_profiles"],
+ ["browser/profiles/abc/Default/Cache/Cache_Data/f", "browser_cache"], ["browser/profiles/abc/Default/Code Cache/js/f", "browser_cache"],
+ ["browser/profiles/abc/GrShaderCache/f", "browser_cache"], ["browser/profiles/abc/Default/Service Worker/ScriptCache/f", "browser_cache"], ["browser/profiles/abc/Default/Service Worker/CacheStorage/f", "browser_cache"],
+ ["agent-browser-profiles/abc/Default/GPUCache/f", "browser_cache"], ["browser/temp/abc/Default/Cookies", "browser_cache"], ["browser/screenshots/abc/1.png", "attachments"],
+ ["browser/profiles/abc/Default/Service Worker/Database/x", "browser_profiles"], ["browser/profiles/abc/Default/IndexedDB/x", "browser_profiles"],
+ ["chrome-profile/Default/Cookies", "browser_profiles"], [".agent-browser/sessions/x", "browser_profiles"],
+ ["vm-homes/abc/.browser-profiles/p/Cookies", "browser_profiles"], ["vm-home/.browser-profiles/p", "browser_profiles"], ["vm-home/work/x", "bot_files"],
+ ["dist-native/cloudflared", "engine_clis"],
+ ["tools/chrome/153/linux64/chrome", "browser_engines"], ["tools/agent-browser/1.2/agent-browser", "browser_engines"],
+ ["tools/npm/lib/node_modules/@anthropic-ai/claude-code/cli.js", "engine_clis"], ["tools/standalone/x", "engine_clis"], ["tools/bitwarden/2026.1.0/bw", "engine_clis"],
+ ["tools/bitwarden/account/data.json", "settings"], ["tools/bitwarden/notes", "other"], ["tools/something-new/x", "other"], ["tools/npm-home/.npmrc", "settings"],
+ ["scrcpy/scrcpy-server-v3", "engine_clis"], ["tools/npm-home/cache/_cacache/x", "packages"],
+ ["logs/service.log", "logs"], ["evidence/thread/1.png", "attachments"], ["decisions.ndjson", "settings"], ["decisions.ndjson.1", "settings"], ["decisions/2026-11.ndjson", "settings"], ["decider-log/x", "logs"], ["engine-runs/tag/pid", "logs"], ["perf-timings.json", "logs"],
+ ["perf-stalls.json", "logs"], ["launch-timings.json", "logs"], ["server.log", "logs"],
+ ["cache/node-compile/x", "caches"], ["duckdb-extensions/v1/x", "caches"], ["org-library/blobs/abc", "caches"], ["org-library/catalog.json", "settings"],
+ ["tmp/omb-cline-mcp-1/x", "temp"], ["tunnel-runtime/x", "temp"], ["tools/.npm-staging-1/x", "temp"], ["tools/.npm-aside-1/x", "temp"],
+ ["bots/bot1/data-tmp/spill", "temp"], ["config.json.123.0f8fad5b-d9cb-469f-a165-70867728950e.tmp", "temp"], ["notes.tmp", "settings"],
+ ["browser/audiences.json", "browser_profiles"], ["browser/panes/abc", "browser_profiles"], ["browser/identity/x.json", "browser_cache"], ["browser/displays/1/x", "browser_cache"],
+ ["browser/something-new", "other"], [".cache/x", "other"],
+ ["something-new/x", "other"],
+ ];
+ for (const [path, expected] of cases) expect([path, category("data", path)]).toEqual([path, expected]);
+ });
+
+ it("files every HOME path class: engines, packages, caches, browser engines, synced folders, the rest other", () => {
+ const cases: Array<[string, string]> = [
+ [".claude/projects/-data/x.jsonl", "engine_state"], [".claude.json", "engine_state"], [".codex/sessions/x", "engine_state"], [".grok/auth.json", "engine_state"],
+ [".local/share/opencode/x", "engine_state"],
+ [".local/share/claude/versions/2.1.0", "engine_clis"], [".grok/bin/grok", "engine_clis"], [".grok/auth.json", "engine_state"],
+ [".local/bin/my-script", "other"], [".cargo/bin/tool", "other"], [".cargo/registry/cache/x", "packages"], ["go/pkg/mod/x", "packages"], ["go/src/app/main.go", "other"],
+ [".gradle/caches/x", "packages"], [".m2/settings.xml", "other"],
+ [".npm/_cacache/x", "packages"], [".cache/pip/x", "packages"], [".cache/uv/x", "packages"], [".local/share/pnpm/store/x", "packages"], [".cargo/registry/x", "packages"],
+ [".cache/ms-playwright/chromium-1/chrome", "browser_engines"], [".agent-browser/browsers/chrome/x", "browser_engines"],
+ [".agent-browser/sessions/s.json", "browser_profiles"],
+ [".cache/opencode/models.json", "caches"], [".cache/something", "other"], [".cache/huggingface/token", "other"],
+ [".local/share/pnpm/store/v3/x", "packages"], [".local/share/pnpm/global/5/x", "other"], [".local/state/claude/locks/x", "engine_clis"], [".local/share/uv/tools/x", "other"],
+ [".config/gh/hosts.yml", "settings"], [".omb-cloud-home.json", "settings"], [".omb-edge/caddy/x", "settings"],
+ ["Synced/Desktop/a.txt", "synced"], [".local/share/Trash/files/x", "trash"],
+ ["lost+found/x", "other"], ["acme-merger/plan.md", "other"], [".local/lib/x", "other"],
+ ];
+ for (const [path, expected] of cases) expect([path, category("home", path)]).toEqual([path, expected]);
+ });
+
+ it("counts node_modules in work folders as packages, still the bot's, and leaves tool installs alone", () => {
+ expect(place("data", "task-workspaces/bot1/thread1/app/node_modules/react/index.js")).toMatchObject({ category: "packages", botId: "bot1" });
+ expect(place("data", "workspaces/bot1/node_modules/x")).toMatchObject({ category: "packages", botId: "bot1" });
+ expect(category("home", "projects/node_modules/x")).toBe("packages");
+ expect(category("data", "tools/npm/lib/node_modules/x")).toBe("engine_clis");
+ expect(category("home", ".claude/local/node_modules/x")).toBe("engine_state");
+ });
+
+ it("names a bot folder's id only when it looks like an id, and names nothing else from the disk but OTHER_NAMES", () => {
+ expect(place("data", "workspaces/bot_1-a/f").botId).toBe("bot_1-a");
+ expect(place("data", "bots/bot1/data-tmp/x")).toMatchObject({ category: "temp", botId: "bot1" });
+ expect(place("data", "workspaces/Ada's plans/f").botId).toBeUndefined();
+ expect(place("data", "something-new/x").otherName).toBeUndefined();
+ expect(place("home", "lost+found/x")).toMatchObject({ category: "other", otherName: "lost+found" });
+ expect(place("home", "acme-merger/plan.md").otherName).toBeUndefined();
+ expect(place("home", ".bash_history")).toMatchObject({ category: "other", otherName: ".bash_history" });
+ });
+
+ it("reads a Windows relative path the same way", () => {
+ expect(storageSegments("task-workspaces\\bot1\\thread1\\a.txt")).toEqual(["task-workspaces", "bot1", "thread1", "a.txt"]);
+ expect(storageSegments("./browser//profiles/abc/")).toEqual(["browser", "profiles", "abc"]);
+ expect(category("data", "browser\\profiles\\abc\\Default\\Cache\\f")).toBe("browser_cache");
+ });
+
+ it("tells a first-level file from a folder of the same name", () => {
+ expect(placeStoragePath("data", ["logs"], false).category).toBe("settings");
+ expect(placeStoragePath("data", ["logs"], true).category).toBe("logs");
+ });
+
+ it("pins every category's class: only caches, downloads and scratch space are rebuildable", () => {
+ expect(STORAGE_CATEGORIES).toEqual({
+ conversations: "precious", settings: "precious", engine_state: "precious", browser_profiles: "precious",
+ bot_files: "work", attachments: "work", synced: "work", backups: "work", trash: "work", other: "work", logs: "work",
+ browser_cache: "rebuildable", browser_engines: "rebuildable", engine_clis: "rebuildable", packages: "rebuildable", caches: "rebuildable", temp: "rebuildable",
+ });
+ });
+});
diff --git a/server/perf/disk-categories.ts b/server/perf/disk-categories.ts
new file mode 100644
index 0000000000..1ec3442e64
--- /dev/null
+++ b/server/perf/disk-categories.ts
@@ -0,0 +1,301 @@
+// What each path on a Cloud home's volume is, by where the server, its engines and its browser write. The volume is HOME
+// (/data, Dockerfile), and the data folder (OMB_DATA_DIR, /data/.openmausbot) sits inside it; a path is read as segments
+// relative to one of the two. Privacy invariant: nothing here returns a name taken from the disk except a bot id (which the
+// report shows only for bots the store knows) and a name from OTHER_NAMES.
+
+/** `precious`: losing it loses something only this home holds. `work`: what bots and people made or may still read,
+ * which only doing the work again would bring back. `rebuildable`: the code named next to it makes it again when it is
+ * missing. Security invariant: only a name listed here as rebuildable is ever rebuildable; anything unknown is `other`. */
+export type StorageClass = "precious" | "work" | "rebuildable";
+
+export const STORAGE_CATEGORIES = {
+ conversations: "precious",
+ settings: "precious",
+ engine_state: "precious",
+ browser_profiles: "precious",
+ bot_files: "work",
+ attachments: "work",
+ synced: "work",
+ backups: "work",
+ trash: "work",
+ other: "work",
+ // Chrome rebuilds its own caches; temporary profiles are made per use (browser/chrome/profile.ts profileDir).
+ browser_cache: "rebuildable",
+ // tools/chrome: browser/chrome/install.ts; tools/agent-browser: browser-engine.ts; ~/.cache/ms-playwright: Playwright.
+ browser_engines: "rebuildable",
+ // tools/npm and its siblings: engine-install.ts and engine-npm-update.ts install them again on first use.
+ engine_clis: "rebuildable",
+ // npm, pnpm, pip, uv, cargo and bun fetch packages again; node_modules is rebuilt by its project's install.
+ packages: "rebuildable",
+ // History people may still read (service logs, the timings, what each run started): nothing makes it again.
+ logs: "work",
+ // Node's compile cache (cloud-home-start.ts NODE_COMPILE_CACHE), DuckDB's extensions (data/engine.ts) and tools' caches.
+ caches: "rebuildable",
+ // Scratch space a running step made for itself and removes when it ends.
+ temp: "rebuildable",
+} as const satisfies Record<string, StorageClass>;
+export type StorageCategory = keyof typeof STORAGE_CATEGORIES;
+
+export type StorageScope = "data" | "home";
+
+/** First-level names in `other` that our own code or the filesystem makes, so they may be named in the report. */
+export const OTHER_NAMES: ReadonlySet<string> = new Set(["lost+found", ".bash_history", ".lesshst", ".wget-hsts", ".python_history", ".node_repl_history"]);
+
+/** A folder of a bot that holds per-bot files, `<folder>/<bot id>/…`. */
+const BOT_FOLDERS: ReadonlySet<string> = new Set(["workspaces", "task-workspaces", "bots"]);
+const BOT_ID = /^[A-Za-z0-9_-]{1,64}$/;
+
+export interface Placement {
+ category: StorageCategory;
+ /** `workspaces/<id>`, `task-workspaces/<id>`, `bots/<id>`: a candidate bot id, shown only if the store knows it. */
+ botId?: string;
+ /** Only names in OTHER_NAMES. */
+ otherName?: string;
+ /** No deeper segment changes the category, except a `node_modules` under a work folder. */
+ final: boolean;
+}
+
+const at = (category: StorageCategory, final = true): Placement => ({ category, final });
+
+/** Data folder, first level, folders. */
+const DATA_FOLDERS: Readonly<Record<string, StorageCategory>> = {
+ // config.ts EVENTS_DIR and NATIVE_DIR: each conversation's event log; checkpoints.ts; memory-journal.ts.
+ events: "conversations", native: "conversations", checkpoints: "conversations", "memory-journal": "conversations",
+ // Sign-ins and settings: providers (provider logins), people and people-connections (team-connections.ts), caddy
+ // (caddy.ts), ssh (vps-ssh.ts), the skills folders (index.ts, skill-library.ts, imported-skills.ts), themes
+ // (themes/store.ts), org-library (org-library.ts), share (share.ts), usage (usage-ledger.ts), decisions and
+ // admin-activity (decision-log.ts, admin-activity.ts: the audit log readDecisions reads), prompt-split (drivers/prompt-split.ts),
+ // codex-instructions (drivers/codex-instructions.ts), local-vm-stops, skill-switch, hook-tokens (drivers/claude.ts),
+ // claude-user-skills (turn-settings.ts), box (bot-box/boot.ts).
+ providers: "settings", people: "settings", "people-connections": "settings", caddy: "settings", ssh: "settings",
+ skills: "settings", "skills-library": "settings", "imported-skills": "settings", "skill-state": "settings", "skill-switch": "settings",
+ themes: "settings", "org-library": "settings", share: "settings", usage: "settings", decisions: "settings", "admin-activity": "settings",
+ "prompt-split": "settings", "codex-instructions": "settings", "local-vm-stops": "settings", "hook-tokens": "settings",
+ "claude-user-skills": "settings", box: "settings",
+ // engine-homes/layout.ts (a Team Cloud's per-audience engine homes); drivers/pi-session.ts.
+ "engine-homes": "engine_state", "pi-sessions": "engine_state",
+ // host/team-files.ts (container-computer.ts's vm-home and vm-homes are placed in dataPlacement).
+ "team-files": "bot_files",
+ // attachments.ts, attachment-originals.ts, box-uploads (attachments.ts), host/browser.ts, tool-results
+ // (mcp-gate-config.ts), meetings/manager.ts, evidence (browser-evidence.ts: the browser steps' screenshots a
+ // conversation still shows).
+ attachments: "attachments", "attachment-originals": "attachments", "box-uploads": "attachments", "browser-uploads": "attachments",
+ "tool-results": "attachments", meetings: "attachments", evidence: "attachments",
+ // cloud-sync-store.ts: what a desktop lent this Cloud.
+ sync: "synced",
+ // workspace-backup.ts (backup and restore jobs, the restore's safety copy); doctor/backup.ts.
+ ".backups": "backups", "doctor-backups": "backups",
+ // cli.ts and service-unit.ts (service logs), decider/log.ts, engine-records.ts (what each server run started).
+ logs: "logs", "decider-log": "logs", "engine-runs": "logs",
+ // Made again on first use: phone-screen/scrcpy-server-file.ts downloads scrcpy; service-cli.ts installs the app copy;
+ // tunnel.ts prepares cloudflared in dist-native again when it is missing.
+ scrcpy: "engine_clis", app: "engine_clis", "dist-native": "engine_clis",
+ // excludedWorkspaceAuthPath (workspace-backup-policy.ts): login profiles of older browser engines.
+ "chrome-profile": "browser_profiles", ".agent-browser": "browser_profiles",
+ "duckdb-extensions": "caches", cache: "caches",
+ // cloud-send-files.ts and the MCP configs; tunnel.ts TUNNEL_RUNTIME_DIR.
+ tmp: "temp", ".tmp": "temp", "tunnel-runtime": "temp",
+};
+
+/** `tools/<name>` in the data folder (engine-roots.ts, browser/chrome/install.ts, browser-engine.ts ENGINE_DIR). */
+const TOOL_FOLDERS: Readonly<Record<string, StorageCategory>> = {
+ chrome: "browser_engines", "agent-browser": "browser_engines",
+ npm: "engine_clis", standalone: "engine_clis", "antigravity-acp": "engine_clis",
+};
+
+/** Data folder, first level, files: the rest of the first-level files are settings and state files. */
+const DATA_FILES: Readonly<Record<string, StorageCategory>> = {
+ "perf-timings.json": "logs", "perf-stalls.json": "logs", "launch-timings.json": "logs",
+};
+const CONVERSATION_DB = /^(?:messages|runtime|bursts)\.db(?:-wal|-shm|-journal)?$/;
+
+/** Folders Chrome downloads or computes again by itself inside a profile (`<profile>/Default/<name>` or `<profile>/<name>`). */
+const CHROME_CACHES: ReadonlySet<string> = new Set([
+ "Cache", "Code Cache", "GPUCache", "DawnCache", "DawnGraphiteCache", "DawnWebGPUCache", "GraphiteDawnCache", "GrShaderCache", "ShaderCache",
+ "component_crx_cache", "extensions_crx_cache", "optimization_guide_model_store", "Crashpad", "BrowserMetrics", "Safe Browsing",
+ "OnDeviceHeadSuggestModel", "screen_ai",
+]);
+/** `Service Worker/<name>`: only the fetched copies; the registrations beside them are the site's state. */
+const SERVICE_WORKER_CACHES: ReadonlySet<string> = new Set(["CacheStorage", "ScriptCache"]);
+
+/** A browser profile folder `<root>/<profile>/…`, `rest` being what is under the profile. */
+function profilePlacement(rest: readonly string[]): Placement {
+ const [first, second, third] = rest;
+ if (first === undefined) return at("browser_profiles", false);
+ if (CHROME_CACHES.has(first)) return at("browser_cache");
+ if (second === undefined) return at("browser_profiles", false);
+ if (CHROME_CACHES.has(second)) return at("browser_cache");
+ if (second !== "Service Worker") return at("browser_profiles");
+ if (third === undefined) return at("browser_profiles", false);
+ return at(SERVICE_WORKER_CACHES.has(third) ? "browser_cache" : "browser_profiles");
+}
+
+/** `browser/<name>` (browser/chrome/profile.ts browserRoot). */
+const BROWSER_ENTRIES: Readonly<Record<string, StorageCategory>> = {
+ // The bot's downloads (browser/service.ts downloadDir) and the screenshots it took (#saveScreenshot) are its work.
+ downloads: "attachments", screenshots: "attachments",
+ // workspace-id (profile.ts), the per-member profiles' record (host/browser.ts AudienceBrowsers, read to erase a deleted
+ // bot's profiles) and the panes each profile opened (pane/backend.ts marksDir).
+ "workspace-id": "browser_profiles", "audiences.json": "browser_profiles", panes: "browser_profiles",
+ // Temporary profiles, swept when unused (chrome/processes.ts); a display's runtime files (desktop/displays.ts); the
+ // calibrated identity, measured again when missing (chrome/calibrate.ts).
+ temp: "browser_cache", displays: "browser_cache", identity: "browser_cache",
+};
+
+function browserPlacement(rest: readonly string[]): Placement {
+ const [first] = rest;
+ if (first === undefined) return at("browser_profiles", false);
+ if (first === "profiles") return rest.length < 2 ? at("browser_profiles", false) : profilePlacement(rest.slice(2));
+ return at(BROWSER_ENTRIES[first] ?? "other");
+}
+
+function dataPlacement(segments: readonly string[], directory: boolean): Placement {
+ const [first, second, third] = segments;
+ if (first === undefined) return at("settings", false);
+ if (segments.length === 1 && !directory) {
+ if (CONVERSATION_DB.test(first)) return at("conversations");
+ if (DATA_FILES[first]) return at(DATA_FILES[first]);
+ // decision-log.ts keeps the audit log's older file beside the current one.
+ if (first === "decisions.ndjson" || first === "decisions.ndjson.1") return at("settings");
+ if (first.endsWith(".log")) return at("logs");
+ // atomic.ts writeWhole: `<file>.<pid>.<uuid>.tmp`, renamed over the file once written; one left is a crashed write.
+ if (/\.\d+\.[0-9a-f-]{36}\.tmp$/.test(first)) return at("temp");
+ return at("settings");
+ }
+ if (BOT_FOLDERS.has(first)) {
+ if (second === undefined) return at("bot_files", false);
+ const botId = BOT_ID.test(second) ? second : undefined;
+ // dataEngineSpillPath (workspace-backup-policy.ts): DuckDB's spill folder, emptied when the database closes.
+ if (first === "bots" && third === "data-tmp") return { category: "temp", final: true, ...(botId ? { botId } : {}) };
+ return { category: "bot_files", final: first !== "bots" || segments.length >= 3, ...(botId ? { botId } : {}) };
+ }
+ if (first === "browser") return browserPlacement(segments.slice(1));
+ // excludedWorkspaceAuthPath: a container computer's browser logins.
+ if ((first === "vm-home" && second === ".browser-profiles") || (first === "vm-homes" && third === ".browser-profiles")) return at("browser_profiles");
+ if (first === "vm-home" || first === "vm-homes") return { category: "bot_files", final: segments.length >= (first === "vm-home" ? 2 : 3) };
+ // browser-engine.ts browserProfilesRoot: agent-browser's own profiles.
+ if (first === "agent-browser-profiles") return segments.length < 2 ? at("browser_profiles", false) : profilePlacement(segments.slice(2));
+ if (first === "tools") {
+ if (second === undefined) return at("engine_clis", false);
+ // engine-npm-update.ts and engine-standalone.ts stage an update beside the copy it replaces.
+ if (second.startsWith(".npm-staging-") || second.startsWith(".npm-aside-") || second.startsWith(".staging-")) return at("temp");
+ // engine-install.ts npmServerHome: npm's own config files beside its download cache.
+ if (second === "npm-home") return third === undefined ? at("engine_clis", false) : at(third === "cache" ? "packages" : "settings");
+ // host/bitwarden-cli.ts puts the tool in tools/bitwarden/<version>; bitwarden-vault.ts keeps the signed-in account
+ // and its encrypted copy of the vault in tools/bitwarden/account.
+ if (second === "bitwarden") return third === undefined ? at("engine_clis", false) : at(third === "account" ? "settings" : /^\d[\w.-]*$/.test(third) ? "engine_clis" : "other");
+ return at(TOOL_FOLDERS[second] ?? "other");
+ }
+ if (first === "sync") {
+ if (second === undefined) return at("synced", false);
+ // cloud-sync-store.ts: deleted synced files wait in trash; uploads hold parts of a transfer still under way.
+ if (second === "trash") return at("trash");
+ if (second === "uploads") return at("temp");
+ return at("synced");
+ }
+ if (first === "engine-homes") {
+ if (second === undefined) return at("engine_state", false);
+ // engine-homes/layout.ts HELD_DIR: state from before the split, deleted after HELD_DAYS.
+ if (second === ".held") return at("trash");
+ return at("engine_state");
+ }
+ if (first === "org-library") {
+ if (second === undefined) return at("settings", false);
+ // redownloadedOrgLibraryPath (workspace-backup-policy.ts): the library's files come again from the Admin.
+ return second === "blobs" ? at("caches") : at("settings");
+ }
+ const known = DATA_FOLDERS[first];
+ return known ? at(known) : at("other");
+}
+
+/** HOME, first level: engine homes (engine-homes/layout.ts ENGINE_FOLDERS and the drivers), sign-ins and dotfiles. */
+const HOME_FOLDERS: Readonly<Record<string, StorageCategory>> = {
+ ".claude": "engine_state", ".codex": "engine_state", ".kimi-code": "engine_state", ".dsh": "engine_state",
+ ".hermes": "engine_state", ".qwen": "engine_state", ".factory": "engine_state", ".pi": "engine_state", ".gemini": "engine_state",
+ ".copilot": "engine_state", ".cline": "engine_state", ".cursor": "engine_state", ".opencode": "engine_state", ".mmx": "engine_state",
+ ".config": "settings", ".ssh": "settings", ".gnupg": "settings",
+ // cloud-home-start.ts edgeCertificateStorage: the edge's TLS certificates.
+ ".omb-edge": "settings",
+ // npm's and pnpm's own cache and store folders: nothing but downloaded packages.
+ ".npm": "packages", ".pnpm-store": "packages",
+ // cloud-sync-paths.ts syncRoot: the person's synced folders.
+ Synced: "synced",
+};
+/** HOME, first level, files. */
+const HOME_FILES: Readonly<Record<string, StorageCategory>> = {
+ ".claude.json": "engine_state", ".claude.json.backup": "engine_state",
+ // cloud-home.ts CLOUD_HOME_MARKER and the dotfiles a fresh volume may hold (cloud-home.ts ADOPTABLE).
+ ".omb-cloud-home.json": "settings", ".bashrc": "settings", ".profile": "settings", ".bash_logout": "settings", ".gitconfig": "settings",
+ ".npmrc": "settings",
+};
+/** Download caches inside tool folders that also hold what people installed or wrote: only these subfolders are packages. */
+const HOME_PACKAGE_CACHES: ReadonlyArray<readonly [string, string, string?]> = [
+ [".cargo", "registry"], [".cargo", "git"], ["go", "pkg", "mod"], [".m2", "repository"], [".gradle", "caches"], [".bun", "install", "cache"], [".yarn", "berry", "cache"],
+];
+
+/** `~/.cache/<name>`: browser engines, package stores and caches; any other name is `other` (a token may live there). */
+const HOME_CACHES: Readonly<Record<string, StorageCategory>> = {
+ "ms-playwright": "browser_engines", puppeteer: "browser_engines",
+ pip: "packages", uv: "packages", pnpm: "packages", yarn: "packages", "node-gyp": "packages", npm: "packages", bun: "packages",
+ "pypoetry": "packages", "go-build": "packages",
+ // model-catalog/catalog.ts: opencode's model list, fetched again.
+ opencode: "caches",
+};
+
+function homePlacement(segments: readonly string[], directory: boolean): Placement {
+ const [first, second, third] = segments;
+ if (first === undefined) return at("other", false);
+ if (segments.length === 1 && !directory) {
+ const known = HOME_FILES[first];
+ if (known) return at(known);
+ return OTHER_NAMES.has(first) ? { category: "other", otherName: first, final: true } : at("other");
+ }
+ if (first === ".cache") return second === undefined ? at("caches", false) : at(HOME_CACHES[second] ?? "other");
+ if (first === ".local") {
+ if (second === undefined) return at("other", false);
+ if (second !== "share" && second !== "state") return at("other");
+ if (third === undefined) return at("other", false);
+ // The Claude native installer keeps each version under ~/.local/share/claude (env-path.ts), and its locks under
+ // ~/.local/state/claude.
+ if (third === "claude") return at("engine_clis");
+ // pnpm's content-addressed store; its global installs beside it are not a cache.
+ if (third === "pnpm") return segments.length < 4 ? at("other", false) : at(segments[3] === "store" ? "packages" : "other");
+ if (third === "Trash") return at("trash");
+ if (third === "opencode") return at("engine_state");
+ return at("other");
+ }
+ // browser-engine.ts browserSessionsDirectory: agent-browser's saved sessions (sign-ins); its own browsers under it.
+ if (first === ".agent-browser") return second === undefined ? at("browser_profiles", false) : at(second === "browsers" ? "browser_engines" : "browser_profiles");
+ // The Grok installer puts its binary in ~/.grok/bin (Dockerfile); the rest of ~/.grok is its sign-in and sessions.
+ if (first === ".grok") return second === undefined ? at("engine_state", false) : at(second === "bin" ? "engine_clis" : "engine_state");
+ for (const cache of HOME_PACKAGE_CACHES) {
+ if (cache[0] !== first) continue;
+ if (segments.length < cache.length) return at("other", false);
+ return at(cache.every((part, index) => segments[index] === part) ? "packages" : "other");
+ }
+ const known = HOME_FOLDERS[first];
+ if (known) return at(known);
+ return OTHER_NAMES.has(first) ? { category: "other", otherName: first, final: true } : at("other");
+}
+
+/** Where a path is, from its segments relative to the scope's root (the data folder or HOME). */
+export function placeStoragePath(scope: StorageScope, segments: readonly string[], directory: boolean): Placement {
+ return scope === "data" ? dataPlacement(segments, directory) : homePlacement(segments, directory);
+}
+
+/** Folders whose `node_modules` is counted as packages: the ones holding what people and bots made. */
+const PACKAGE_HOSTS: ReadonlySet<StorageCategory> = new Set(["bot_files", "synced", "other", "attachments"]);
+
+/** A child's placement from its parent's: the classifier is asked only while the parent's is not final. */
+export function placeChild(parent: Placement, scope: StorageScope, segments: readonly string[], directory: boolean): Placement {
+ const name = segments.at(-1);
+ if (directory && name === "node_modules" && PACKAGE_HOSTS.has(parent.category)) return { category: "packages", final: true, ...(parent.botId ? { botId: parent.botId } : {}) };
+ if (parent.final) return parent;
+ const placed = placeStoragePath(scope, segments, directory);
+ return parent.botId && !placed.botId ? { ...placed, botId: parent.botId } : placed;
+}
+
+/** Path segments of `relative`, which may use either separator (a Windows data folder). */
+export function storageSegments(relative: string): string[] {
+ return relative.split(/[\\/]+/).filter((part) => part !== "" && part !== ".");
+}
diff --git a/server/perf/disk-usage.test.ts b/server/perf/disk-usage.test.ts
new file mode 100644
index 0000000000..c6a57a7d6b
--- /dev/null
+++ b/server/perf/disk-usage.test.ts
@@ -0,0 +1,339 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, 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_PATH } from "../routes/perf-diagnostics.ts";
+import type { RouteContext } from "../routes/table.ts";
+import { STORAGE_CATEGORIES } from "./disk-categories.ts";
+import { MAX_BOTS, nodeWalkFs, type WalkFs } from "./disk-walk.ts";
+import { cloudStorage, createPerfHost } from "./perf-host.ts";
+import { createDiskUsage, readSavedPass, readSavedProgress, STORAGE_HEALTH_MAX_BYTES, storageHealth, type DiskUsageOptions, type StorageReport } from "./disk-usage.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 }); });
+
+/** A Cloud home's volume: HOME with the data folder inside, and names that must never leave it. */
+function volume() {
+ const home = mkdtempSync(join(tmpdir(), "disk-usage-"));
+ dirs.push(home);
+ const data = join(home, ".openmausbot");
+ const write = (path: string, bytes = 1_000) => { mkdirSync(join(path, ".."), { recursive: true }); writeFileSync(path, Buffer.alloc(bytes, 7)); };
+ write(join(data, "messages.db"), 20_000);
+ write(join(data, "workspaces", "bot-known", "Acme merger plan.md"), 8_000);
+ write(join(data, "task-workspaces", "bot-known", "thread-1", "[email protected]"), 4_000);
+ write(join(data, "workspaces", "bot-gone", "old.txt"), 2_000);
+ write(join(data, "Tallyspoon-secrets", "token.txt"));
+ write(join(home, "acme-merger", "sk-ant-api03-PRIVATE.txt"));
+ write(join(home, "lost+found", "x"));
+ write(join(home, ".cache", "ms-playwright", "chromium-1", "chrome"), 6_000);
+ return { home, data };
+}
+
+function usage(overrides: Partial<DiskUsageOptions> = {}) {
+ const { home, data } = volume();
+ let clock = START, mono = 0, busy = false;
+ const disk = createDiskUsage({
+ roots: [{ path: home, scope: "home" }, { path: data, scope: "data" }], volume: home, timer: false,
+ now: () => clock, monotonic: () => mono, busy: () => busy, knownBot: (id) => id === "bot-known",
+ statfs: async () => ({ blocks: 1_000_000, bsize: 4096, bavail: 400_000, bfree: 450_000 }),
+ firstPassAfterMs: 60_000, passEveryMs: 3_600_000, tickMs: 2_000, ...overrides,
+ });
+ return { disk, home, data, advance: (ms: number) => { clock += ms; }, tickMono: (ms: number) => { mono += ms; }, setBusy: (value: boolean) => { busy = value; } };
+}
+
+async function untilDone(w: ReturnType<typeof usage>, max = 1_000) {
+ for (let index = 0; index < max && (w.disk.running() || w.disk.report().at === null); index++) { w.advance(2_000); await w.disk.tick(); }
+}
+
+describe("storage sampler", () => {
+ it("waits for its first pass after boot, then reports each category with its class, the volume and the bots the store knows", async () => {
+ const w = usage();
+ await w.disk.tick();
+ expect(w.disk.running()).toBe(false);
+ expect(w.disk.report()).toMatchObject({ v: 1, at: null, running: false, categories: [], bots: [], volume: null, other: null });
+ w.advance(60_000);
+ await untilDone(w);
+ const report = w.disk.report();
+ expect(report).toMatchObject({ v: 1, running: false, progress: null, failed: false, volume: { totalBytes: 4_096_000_000, freeBytes: 1_638_400_000, usedBytes: 2_252_800_000 } });
+ const names = report.categories.map((row) => row.name);
+ expect(names).toEqual(expect.arrayContaining(["conversations", "bot_files", "browser_engines", "other"]));
+ for (const row of report.categories) expect(row.class).toBe(STORAGE_CATEGORIES[row.name]);
+ const sizes = report.categories.map((row) => row.bytes);
+ expect(sizes).toEqual(sizes.toSorted((a, b) => b - a));
+ expect(report.bots.map((bot) => bot.id)).toEqual(["bot-known"]);
+ expect(report.bots[0]!.files).toBe(2);
+ expect(report.botsRest).toMatchObject({ count: 1, files: 1 });
+ expect(report.walkedBytes! + report.unwalkedBytes!).toBeGreaterThanOrEqual(report.walkedBytes!);
+ expect(report.other).toMatchObject({ named: [{ name: "lost+found", files: 1 }], unlisted: { files: 2, entries: 2 } });
+ w.advance(30_000);
+ expect(w.disk.report().ageS).toBe(30);
+ });
+
+ it("never names a file or folder outside its allow-list, nor a bot the store does not know", async () => {
+ const w = usage();
+ w.advance(60_000);
+ await untilDone(w);
+ const text = JSON.stringify(storageHealth(w.disk.report()));
+ for (const secret of ["Acme", "acme-merger", "[email protected]", "Tallyspoon", "sk-ant", "PRIVATE", "token.txt", "bot-gone", "plan.md", "ms-playwright", w.home]) expect(text).not.toContain(secret);
+ });
+
+ it("starts no step while a turn runs, stops a step under way when one starts, and reports how long it waited", async () => {
+ let calls = 0, busyAfter = Infinity;
+ const counting: WalkFs = { opendir: nodeWalkFs.opendir, lstat: async (path) => { calls += 1; return nodeWalkFs.lstat(path); } };
+ const w = usage({ fs: counting, busy: () => calls >= busyAfter });
+ w.advance(60_000);
+ busyAfter = 3;
+ await w.disk.tick();
+ expect(w.disk.running()).toBe(true);
+ const read = calls;
+ expect(read).toBe(3);
+ for (let index = 0; index < 5; index++) { w.advance(2_000); await w.disk.tick(); }
+ expect(calls).toBe(read);
+ expect(w.disk.report()).toMatchObject({ running: true, at: null, progress: { waitedS: 10 } });
+ busyAfter = Infinity;
+ await untilDone(w);
+ expect(w.disk.report()).toMatchObject({ running: false, progress: null });
+ expect(w.disk.report().at).not.toBeNull();
+ });
+
+ it("keeps each tick within its entry and time budget, and passes again only when due", async () => {
+ let mono = 0;
+ const slow: WalkFs = { opendir: nodeWalkFs.opendir, lstat: async (path) => { mono += 10; return nodeWalkFs.lstat(path); } };
+ const w = usage({ fs: slow, monotonic: () => mono, tickBudgetMs: 25, tickEntries: 1_000 });
+ w.advance(60_000);
+ await w.disk.tick();
+ expect(w.disk.report().progress!.entries).toBeLessThanOrEqual(3);
+ await untilDone(w);
+ const first = w.disk.report().at!;
+ w.advance(1_800_000);
+ await w.disk.tick();
+ expect(w.disk.running()).toBe(false);
+ w.advance(1_800_000);
+ await w.disk.tick();
+ expect(w.disk.running() || w.disk.report().at! > first).toBe(true);
+ });
+
+ it("counts what it cannot read and still finishes the pass", async () => {
+ let broken = false;
+ const flaky: WalkFs = { opendir: async (path) => { if (broken) throw Object.assign(new Error("EIO"), { code: "EIO" }); return nodeWalkFs.opendir(path); }, lstat: nodeWalkFs.lstat };
+ const w = usage({ fs: flaky });
+ w.advance(60_000);
+ await untilDone(w);
+ const before = w.disk.report();
+ broken = true;
+ w.disk.passNow();
+ for (let index = 0; index < 50 && (index === 0 || w.disk.running()); index++) { w.advance(2_000); await w.disk.tick(); }
+ const after = w.disk.report();
+ expect(after).toMatchObject({ failed: false, running: false });
+ expect(after.skipped!.unreadable).toBeGreaterThan(0);
+ expect(after.at).toBeGreaterThan(before.at!);
+ });
+
+ it("keeps the last figures and says so when a pass fails", async () => {
+ let broken = false;
+ const failing: WalkFs = {
+ opendir: nodeWalkFs.opendir,
+ lstat: async (path) => {
+ const stat = await nodeWalkFs.lstat(path);
+ return broken ? Object.assign(Object.create(Object.getPrototypeOf(stat)), stat, { isDirectory: () => { throw new TypeError("bad stat"); } }) : stat;
+ },
+ };
+ const w = usage({ fs: failing });
+ w.advance(60_000);
+ await untilDone(w);
+ const before = w.disk.report();
+ broken = true;
+ w.disk.passNow();
+ w.advance(2_000);
+ await w.disk.tick();
+ const after = w.disk.report();
+ expect(after).toMatchObject({ failed: true, running: false, at: before.at, categories: before.categories });
+ });
+
+ it("stops at once and closes what it holds", async () => {
+ const w = usage({ tickEntries: 2 });
+ w.advance(60_000);
+ await w.disk.tick();
+ expect(w.disk.running()).toBe(true);
+ await w.disk.stop();
+ expect(w.disk.running()).toBe(false);
+ w.advance(2_000);
+ await w.disk.tick();
+ expect(w.disk.running()).toBe(false);
+ });
+
+ it("keeps the last pass across a restart and waits until it is due again", async () => {
+ const file = join(mkdtempSync(join(tmpdir(), "disk-usage-saved-")), "cache", "storage-report.json");
+ dirs.push(join(file, "..", ".."));
+ const w = usage({ file });
+ w.advance(60_000);
+ await untilDone(w);
+ const before = w.disk.report();
+ let clock = before.at! + 60_000;
+ const again = createDiskUsage({ roots: [{ path: w.home, scope: "home" }], volume: w.home, timer: false, file, now: () => clock, knownBot: (id) => id === "bot-known",
+ firstPassAfterMs: 60_000, passEveryMs: 3_600_000 });
+ expect({ ...again.report(), ageS: before.ageS }).toEqual({ ...before, ageS: before.ageS });
+ clock += 120_000;
+ await again.tick();
+ expect(again.report().at).toBe(before.at);
+ clock = before.at! + 3_600_000;
+ await again.tick();
+ expect(again.running() || again.report().at! > before.at!).toBe(true);
+ await again.stop();
+ });
+
+ it("reads back a saved pass field by field: a name that is not a category, a known-shaped id or an allowed name is dropped", () => {
+ const saved = readSavedPass(JSON.stringify({ v: 1, at: START, tookMs: 5, volume: { totalBytes: 10, freeBytes: "x", usedBytes: -1 }, totals: {
+ categories: { conversations: { bytes: 5, files: 1 }, "acme-merger": { bytes: 9, files: 9 } }, bots: [["bot-known", { bytes: 3, files: 1 }], ["Ada's plans", { bytes: 1, files: 1 }]],
+ otherNamed: [["lost+found", { bytes: 1, files: 0 }], ["acme-merger", { bytes: 1, files: 1 }]], walkedBytes: 7, entries: 2 } }))!;
+ expect(saved.volume).toEqual({ totalBytes: 10, freeBytes: 0, usedBytes: 0 });
+ expect(saved.totals.categories.conversations).toEqual({ bytes: 5, files: 1 });
+ expect(Object.keys(saved.totals.categories)).not.toContain("acme-merger");
+ expect([...saved.totals.bots.keys()]).toEqual(["bot-known"]);
+ expect([...saved.totals.otherNamed.keys()]).toEqual(["lost+found"]);
+ expect(readSavedPass("{")).toBeNull();
+ expect(readSavedPass(JSON.stringify({ v: 2, at: START }))).toBeNull();
+ });
+
+ it("never records a pass cut short by stop as complete", async () => {
+ let w: ReturnType<typeof usage> | null = null;
+ const stopping: WalkFs = { opendir: nodeWalkFs.opendir, lstat: async (path) => { if (path.endsWith("messages.db")) void w!.disk.stop(); return nodeWalkFs.lstat(path); } };
+ w = usage({ fs: stopping });
+ w.advance(60_000);
+ for (let index = 0; index < 50; index++) { w.advance(2_000); await w.disk.tick(); }
+ expect(w.disk.report()).toMatchObject({ at: null, running: false, failed: false });
+ });
+
+ it("goes on after a restart from where the pass was saved, to the same figures as one pass", async () => {
+ const folder = mkdtempSync(join(tmpdir(), "disk-usage-progress-"));
+ dirs.push(folder);
+ const progressFile = join(folder, "cache", "storage-progress.json"), file = join(folder, "cache", "storage-report.json");
+ const whole = usage({ tickEntries: 1_000_000 });
+ whole.advance(60_000);
+ await untilDone(whole);
+ const expected = whole.disk.report();
+
+ const { home, data } = volume();
+ let clock = START;
+ const make = () => createDiskUsage({ roots: [{ path: home, scope: "home" }, { path: data, scope: "data" }], volume: home, timer: false, file, progressFile,
+ now: () => clock, knownBot: (id) => id === "bot-known", statfs: async () => ({ blocks: 1_000_000, bsize: 4096, bavail: 400_000, bfree: 450_000 }),
+ firstPassAfterMs: 60_000, passEveryMs: 3_600_000, tickEntries: 2 });
+ let disk = make();
+ clock += 60_000;
+ let restarts = 0;
+ for (let index = 0; index < 500 && disk.report().at === null; index++) {
+ clock += 61_000;
+ await disk.tick();
+ if (existsSync(progressFile) && index % 5 === 4) { await disk.stop(); disk = make(); restarts += 1; clock += 60_000; }
+ }
+ expect(restarts).toBeGreaterThan(0);
+ const report = disk.report();
+ expect(report.resumes).toBeGreaterThan(0);
+ const figures = (one: StorageReport) => ({ categories: one.categories, bots: one.bots, botsRest: one.botsRest, other: one.other, walkedBytes: one.walkedBytes });
+ expect(figures(report)).toEqual(figures(expected));
+ expect(existsSync(progressFile)).toBe(false);
+ });
+
+ it("starts again from nothing on a saved pass that is unreadable, too old or names a folder outside the roots", () => {
+ const { home } = volume();
+ const roots = [{ path: home, scope: "home" as const }];
+ const saved = (checkpoint: unknown, savedAt = START) => JSON.stringify({ v: 1, startedAt: START, waitedMs: 0, savedAt, checkpoint });
+ const totals = { categories: {}, bots: [] };
+ expect(readSavedProgress(saved({ totals, doneRoots: [], frames: [{ path: home, names: ["a"] }] }), roots, START)).not.toBeNull();
+ expect(readSavedProgress(saved({ totals, doneRoots: [], frames: [{ path: home, names: ["a"] }] }), roots, START + 8 * 24 * 3_600_000)).toBeNull();
+ expect(readSavedProgress(saved({ totals, doneRoots: [], frames: [{ path: "/etc", names: ["passwd"] }] }), roots, START)).toBeNull();
+ expect(readSavedProgress("{", roots, START)).toBeNull();
+ });
+
+ it("walks only on a Cloud home: the desktop app and a self-hosted server measure nothing", () => {
+ expect(cloudStorage(null, "/home/ada", () => true)).toEqual({});
+ expect(cloudStorage(undefined, "/home/ada", () => true)).toEqual({});
+ expect(cloudStorage({ adminOrigin: "https://admin.test" }, "/data", () => true).storage?.home).toBe("/data");
+ const store = { onChange: () => () => {}, botByThread: () => null };
+ const bus = { subscribe: () => () => {} };
+ const { home } = volume();
+ expect(createPerfHost({ dataDir: home, timer: false, wholeMachine: false, bus, store, ...cloudStorage(null, home, () => true) }).storage()).toBeNull();
+ expect(createPerfHost({ dataDir: home, timer: false, wholeMachine: true, bus, store, ...cloudStorage({}, home, () => true) }).storage()).toMatchObject({ v: 1, at: null });
+ const index = readFileSync(join(import.meta.dirname, "..", "index.ts"), "utf8");
+ expect(index.match(/\.\.\.cloudStorage\(CLOUD_HOME, homedir\(\), /g)).toHaveLength(1);
+ expect(index).not.toMatch(/storage: \{ home:/);
+ });
+
+ it("walks a data folder that is HOME itself once", async () => {
+ const { home } = volume();
+ const disk = createDiskUsage({ roots: [{ path: home, scope: "home" }, { path: home, scope: "data" }], volume: home, timer: false, firstPassAfterMs: 0, now: () => START });
+ for (let index = 0; index < 100 && (disk.running() || disk.report().at === null); index++) await disk.tick();
+ const files = disk.report().categories.reduce((sum, row) => sum + row.files, 0);
+ expect(files).toBe(8);
+ });
+});
+
+/** The largest report the sampler can make: every category, as many bots as it keeps, every allowed name, 16-digit numbers. */
+function worstCase(): StorageReport {
+ const big = 4_000_000_000_000_000;
+ const tally = { bytes: big, files: big };
+ return {
+ v: 1, at: big, ageS: big, tookS: big, running: true, progress: { entries: big, waitedS: big },
+ volume: { totalBytes: big, freeBytes: big, usedBytes: big }, walkedBytes: big, unwalkedBytes: big,
+ categories: Object.entries(STORAGE_CATEGORIES).map(([name, value]) => ({ name: name as keyof typeof STORAGE_CATEGORIES, class: value, ...tally })),
+ bots: Array.from({ length: Math.min(MAX_BOTS, 10) }, (_, index) => ({ id: `${"b".repeat(62)}${String(index).padStart(2, "0")}`, ...tally })),
+ botsRest: { ...tally, count: big },
+ other: { named: Array.from({ length: 5 }, (_, index) => ({ name: `lost+found${index}`, ...tally })), unlisted: { ...tally, entries: big } },
+ skipped: { unreadable: big, otherDevice: big, tooDeep: big, vanished: big, links: big }, linksCapped: true, linksUncheckedBytes: big, resumes: big, failed: true,
+ };
+}
+
+describe("storage in the health read", () => {
+ it("fits its own budget untrimmed at the largest the sampler makes", () => {
+ const report = worstCase();
+ expect(JSON.stringify(report).length).toBeLessThanOrEqual(STORAGE_HEALTH_MAX_BYTES);
+ expect(storageHealth(report)).toEqual(report);
+ });
+
+ it("drops bots into the rest before anything else when a report is over its budget", () => {
+ const report = worstCase();
+ report.bots = Array.from({ length: 40 }, (_, index) => ({ ...report.bots[0]!, id: `${"c".repeat(62)}${String(index).padStart(2, "0")}` }));
+ const trimmed = storageHealth(report);
+ expect(JSON.stringify(report).length).toBeGreaterThan(STORAGE_HEALTH_MAX_BYTES);
+ expect(JSON.stringify(trimmed).length).toBeLessThanOrEqual(STORAGE_HEALTH_MAX_BYTES);
+ expect(trimmed.categories).toHaveLength(Object.keys(STORAGE_CATEGORIES).length);
+ expect(trimmed.v).toBe(1);
+ expect(trimmed.bots.length).toBeLessThan(report.bots.length);
+ expect(trimmed.botsRest.count).toBe(report.botsRest.count + report.bots.length - trimmed.bots.length);
+ expect(trimmed.botsRest.bytes).toBeGreaterThan(report.botsRest.bytes);
+ });
+
+ it("leaves a small report as it is", async () => {
+ const w = usage();
+ w.advance(60_000);
+ await untilDone(w);
+ const report = w.disk.report();
+ expect(storageHealth(report)).toEqual(report);
+ });
+});
+
+describe("GET /api/diagnostics/storage", () => {
+ async function get(storage?: () => StorageReport | null) {
+ let answered: { status: number; body: unknown } | null = null;
+ const route = createPerfDiagnosticsRoutes({ text: () => "", ...(storage ? { storage } : {}) });
+ const result = await route({
+ req: {} as RouteContext["req"], res: { setHeader: () => undefined } as unknown as RouteContext["res"], url: new URL(`http://x${STORAGE_PATH}`), path: STORAGE_PATH, method: "GET",
+ 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 { result, answered: answered as { status: number; body: unknown } | null };
+ }
+
+ it("answers the owner with the report, or null where the home measures nothing", async () => {
+ const report = worstCase();
+ expect((await get(() => report)).answered).toEqual({ status: 200, body: { storage: report } });
+ expect((await get()).answered).toEqual({ status: 200, body: { storage: null } });
+ });
+
+ it("is admin scope: a Team Cloud member's session and a service caller never reach it", () => {
+ expect(requiredScope("GET", STORAGE_PATH)).toBe("admin");
+ expect(serviceAllowed("GET", STORAGE_PATH)).toBe(false);
+ });
+});
diff --git a/server/perf/disk-usage.ts b/server/perf/disk-usage.ts
new file mode 100644
index 0000000000..a2a3135e90
--- /dev/null
+++ b/server/perf/disk-usage.ts
@@ -0,0 +1,274 @@
+// What fills a Cloud home's volume, by category (disk-categories.ts), for the Admin's health read and the owner's
+// diagnostics. A pass walks the volume a little at a time (disk-walk.ts): at most TICK_ENTRIES entries or TICK_BUDGET_MS
+// every TICK_MS, nothing while a turn runs, one pass soon after boot and then one every PASS_EVERY_MS. A pass under way
+// is saved as it goes, so a home that sleeps by stopping goes on after each start rather than starting again. Node gives no
+// per-call I/O priority and re-nicing would slow the whole server, so the budget is the only throttle. Privacy invariant:
+// sizes, counts, fixed category names, ids of bots the store knows and names from OTHER_NAMES; never a file's contents.
+import { mkdirSync, readFileSync, rmSync } from "node:fs";
+import { statfs } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+import { performance } from "node:perf_hooks";
+
+import { writeFileAtomic } from "../atomic.ts";
+import { OTHER_NAMES, STORAGE_CATEGORIES, type StorageCategory, type StorageClass } from "./disk-categories.ts";
+import {
+ checkpointFrom, createDiskWalk, totalsFrom, totalsJson, type DiskWalk, type Tally, type WalkCheckpoint, type WalkFs, type WalkRoot, type WalkSkipped, type WalkTotals,
+} from "./disk-walk.ts";
+
+export const STORAGE_REPORT_VERSION = 1;
+/** The health report's `storage` field is at most this many bytes of JSON, apart from `perf`'s own budget. */
+export const STORAGE_HEALTH_MAX_BYTES = 4 * 1024;
+export const TICK_MS = 2_000;
+export const TICK_BUDGET_MS = 25;
+export const TICK_ENTRIES = 2_000;
+export const PASS_EVERY_MS = 6 * 3_600_000;
+export const FIRST_PASS_AFTER_MS = 2 * 60_000;
+const BOTS_SHOWN = 10, OTHER_SHOWN = 5;
+const ID = /^[A-Za-z0-9_-]{1,64}$/;
+
+export interface VolumeBytes { totalBytes: number; freeBytes: number; usedBytes: number }
+export interface StorageCategoryRow { name: StorageCategory; class: StorageClass; bytes: number; files: number }
+export interface StorageReport {
+ v: typeof STORAGE_REPORT_VERSION;
+ /** When the last full pass ended; null before the first. */
+ at: number | null;
+ ageS: number | null;
+ tookS: number | null;
+ /** A pass is under way now. */
+ running: boolean;
+ /** Entries the pass under way has read, and how long it has waited for turns to end. */
+ progress: { entries: number; waitedS: number } | null;
+ /** The volume when the last pass ended. */
+ volume: VolumeBytes | null;
+ walkedBytes: number | null;
+ /** Used on the volume minus walked: files held open after deletion and filesystem metadata when positive; negative when
+ * the walk over-counted (hard links past MAX_LINKS, see linksUncheckedBytes, or a pass resumed after a restart). */
+ unwalkedBytes: number | null;
+ /** The categories with anything in them, the largest first. */
+ categories: StorageCategoryRow[];
+ /** The bots the store knows, the most bytes first. */
+ 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 };
+ other: { named: Array<{ name: string } & Tally>; unlisted: Tally & { entries: number } } | null;
+ skipped: WalkSkipped | null;
+ linksCapped: boolean;
+ /** Bytes of hard-linked files past the check: at most this much may be counted twice. */
+ linksUncheckedBytes: number;
+ /** Times the last pass went on after a restart. */
+ resumes: number;
+ /** The last pass failed; the figures are from the one before, if any. */
+ failed: boolean;
+}
+
+export interface CompletedPass { at: number; tookMs: number; totals: WalkTotals; volume: VolumeBytes | null }
+
+export interface DiskUsageOptions {
+ roots: readonly WalkRoot[];
+ /** Any path on the volume, for its total and free bytes. */
+ volume: string;
+ /** True while a turn runs: no step starts, and a step under way stops at its next entry. */
+ busy?: () => boolean;
+ /** Whether a bot id is a bot the store knows now. */
+ knownBot?: (id: string) => boolean;
+ fs?: WalkFs;
+ statfs?: (path: string) => Promise<{ blocks: number; bsize: number; bavail: number; bfree: number }>;
+ now?: () => number;
+ monotonic?: () => number;
+ /** Tests: no timer; call `tick()`. */
+ timer?: false;
+ tickMs?: number;
+ tickBudgetMs?: number;
+ tickEntries?: number;
+ passEveryMs?: number;
+ firstPassAfterMs?: number;
+ maxDepth?: number;
+ /** Where the last completed pass is kept, so a restart (a home that sleeps by stopping) still has it. */
+ file?: string;
+ /** Where the pass under way is kept as it goes, so a restart goes on from it. */
+ progressFile?: string;
+}
+
+/** Bots kept in the saved pass: the report shows ten, and a bot the store learns of later is rare. */
+const SAVED_BOTS = 100;
+/** A pass under way is saved at most this often, at a folder boundary (disk-walk.ts WalkCheckpoint). */
+export const PROGRESS_EVERY_MS = 60_000;
+/** A saved pass under way older than this starts again from nothing. */
+const PROGRESS_MAX_AGE_MS = 7 * 24 * 3_600_000;
+
+const count = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);
+
+function savedText(completed: CompletedPass): string {
+ const bots = [...completed.totals.bots].sort(([, a], [, b]) => b.bytes - a.bytes);
+ const overflow = bots.slice(SAVED_BOTS).reduce((rest, [, tally]) => ({ bytes: rest.bytes + tally.bytes, files: rest.files + tally.files }), { ...completed.totals.botsOverflow });
+ return JSON.stringify({ v: STORAGE_REPORT_VERSION, at: completed.at, tookMs: completed.tookMs, volume: completed.volume,
+ totals: totalsJson({ ...completed.totals, bots: new Map(bots.slice(0, SAVED_BOTS)), botsOverflow: overflow }) });
+}
+
+/** A saved pass, every field checked: a name that is not a category, a bot-id-shaped id or an allowed name is dropped. */
+export function readSavedPass(text: string): CompletedPass | null {
+ let saved: Record<string, unknown>;
+ try { saved = JSON.parse(text) as Record<string, unknown>; } catch { return null; }
+ if (!saved || saved.v !== STORAGE_REPORT_VERSION || !count(saved.at)) return null;
+ const volume = saved.volume as Record<string, unknown> | null;
+ return {
+ at: count(saved.at), tookMs: count(saved.tookMs),
+ volume: volume && typeof volume === "object" ? { totalBytes: count(volume.totalBytes), freeBytes: count(volume.freeBytes), usedBytes: count(volume.usedBytes) } : null,
+ totals: totalsFrom(saved.totals),
+ };
+}
+
+interface SavedProgress { startedAt: number; waitedMs: number; savedAt: number; checkpoint: WalkCheckpoint }
+
+/** The pass under way as saved: its start, its wait for turns and where to go on from. */
+export function readSavedProgress(text: string, roots: readonly WalkRoot[], at: number): SavedProgress | null {
+ let saved: Record<string, unknown>;
+ try { saved = JSON.parse(text) as Record<string, unknown>; } catch { return null; }
+ if (!saved || saved.v !== STORAGE_REPORT_VERSION || !count(saved.startedAt) || at - count(saved.savedAt) > PROGRESS_MAX_AGE_MS) return null;
+ const checkpoint = checkpointFrom(saved.checkpoint, roots);
+ return checkpoint ? { startedAt: count(saved.startedAt), waitedMs: count(saved.waitedMs), savedAt: count(saved.savedAt), checkpoint } : null;
+}
+
+export function createDiskUsage(options: DiskUsageOptions) {
+ const now = options.now ?? Date.now, monotonic = options.monotonic ?? (() => performance.now());
+ const tickMs = options.tickMs ?? TICK_MS, budgetMs = options.tickBudgetMs ?? TICK_BUDGET_MS, entries = options.tickEntries ?? TICK_ENTRIES;
+ const everyMs = options.passEveryMs ?? PASS_EVERY_MS;
+ // A data folder that is HOME itself is walked once, as the data folder.
+ const roots = [...new Map(options.roots.map((root) => [resolve(root.path), { ...root, path: resolve(root.path) }])).values()];
+ const busy = () => { try { return options.busy?.() === true; } catch { return false; } };
+ const readVolume = async (): Promise<VolumeBytes | null> => {
+ try {
+ const stats = await (options.statfs ?? statfs)(options.volume);
+ return { totalBytes: stats.blocks * stats.bsize, freeBytes: stats.bavail * stats.bsize, usedBytes: (stats.blocks - stats.bfree) * stats.bsize };
+ } catch { return null; }
+ };
+ let last: CompletedPass | null = null;
+ if (options.file) { try { last = readSavedPass(readFileSync(options.file, "utf8")); } catch {} }
+ const firstAt = now() + (options.firstPassAfterMs ?? FIRST_PASS_AFTER_MS);
+ let dueAt = last && last.at <= now() ? Math.max(firstAt, last.at + everyMs) : firstAt;
+ let walk: DiskWalk | null = null, pass: { startedAt: number; waitedMs: number; lastTickAt: number } | null = null;
+ let failed = false, ticking = false, stopped = false, progressSavedAt = -Infinity;
+ let resumeFrom: SavedProgress | null = null;
+ if (options.progressFile) { try { resumeFrom = readSavedProgress(readFileSync(options.progressFile, "utf8"), roots, now()); } catch {} }
+ if (resumeFrom) dueAt = firstAt;
+ const write = (file: string | undefined, text: string) => {
+ if (!file) return;
+ try { mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); writeFileAtomic(file, text, { mode: 0o600 }); } catch {}
+ };
+ const saveProgress = (take: () => WalkCheckpoint | null) => {
+ if (!options.progressFile || !pass || now() - progressSavedAt < PROGRESS_EVERY_MS) return;
+ const checkpoint = take();
+ if (!checkpoint) return;
+ progressSavedAt = now();
+ write(options.progressFile, JSON.stringify({ v: STORAGE_REPORT_VERSION, startedAt: pass.startedAt, waitedMs: pass.waitedMs, savedAt: progressSavedAt,
+ checkpoint: { ...checkpoint, totals: totalsJson(checkpoint.totals) } }));
+ };
+ const forgetProgress = () => { if (options.progressFile) { try { rmSync(options.progressFile, { force: true }); } catch {} } };
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ const schedule = () => {
+ if (options.timer === false || stopped) return;
+ if (timer) clearTimeout(timer);
+ const wait = walk ? tickMs : Math.max(tickMs, dueAt - now());
+ timer = setTimeout(() => void tick(), wait);
+ timer.unref?.();
+ };
+
+ async function tick(): Promise<void> {
+ if (ticking || stopped) return;
+ ticking = true;
+ try {
+ const at = now();
+ if (!walk) {
+ if (at < dueAt) return;
+ walk = createDiskWalk(roots, { ...(options.fs ? { fs: options.fs } : {}), ...(options.maxDepth ? { maxDepth: options.maxDepth } : {}),
+ resume: resumeFrom?.checkpoint ?? null, onBoundary: saveProgress });
+ pass = { startedAt: resumeFrom?.startedAt ?? at, waitedMs: resumeFrom?.waitedMs ?? 0, lastTickAt: at };
+ resumeFrom = null;
+ progressSavedAt = now();
+ }
+ const current = pass!, walking = walk;
+ if (busy()) { current.waitedMs += at - current.lastTickAt; current.lastTickAt = at; return; }
+ current.lastTickAt = at;
+ const started = monotonic();
+ const ended = await walking.step({ entries, stop: () => stopped || monotonic() - started >= budgetMs || busy() });
+ if (ended && !stopped) {
+ last = { at: now(), tookMs: now() - current.startedAt, totals: walking.totals, volume: await readVolume() };
+ failed = false;
+ walk = null; pass = null;
+ dueAt = now() + everyMs;
+ write(options.file, savedText(last));
+ forgetProgress();
+ }
+ } catch {
+ await walk?.close().catch(() => {});
+ walk = null; pass = null; failed = true;
+ dueAt = now() + everyMs;
+ forgetProgress();
+ } finally {
+ ticking = false;
+ schedule();
+ }
+ }
+
+ return {
+ start() { if (options.timer !== false && !timer && !stopped) schedule(); },
+ async stop() { stopped = true; if (timer) clearTimeout(timer); timer = null; await walk?.close(); walk = null; pass = null; },
+ tick,
+ /** Starts a pass at the next tick, whatever the schedule says. */
+ passNow() { if (!walk) dueAt = now(); },
+ running: () => walk !== null,
+ report(): StorageReport {
+ const at = now();
+ const totals = last?.totals;
+ 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; }
+ if (totals) { rest.bytes += totals.botsOverflow.bytes; rest.files += totals.botsOverflow.files; }
+ const volume = last?.volume ?? null;
+ return {
+ v: STORAGE_REPORT_VERSION,
+ at: last?.at ?? null,
+ ageS: last ? Math.max(0, Math.round((at - last.at) / 1000)) : null,
+ tookS: last ? Math.round(last.tookMs / 1000) : null,
+ running: walk !== null,
+ progress: walk && pass ? { entries: walk.totals.entries, waitedS: Math.round(pass.waitedMs / 1000) } : null,
+ volume,
+ walkedBytes: totals?.walkedBytes ?? null,
+ unwalkedBytes: totals && volume ? volume.usedBytes - totals.walkedBytes : null,
+ categories: totals ? (Object.keys(STORAGE_CATEGORIES) as StorageCategory[])
+ .map((name) => ({ name, class: STORAGE_CATEGORIES[name], ...totals.categories[name] }))
+ .filter((row) => row.bytes > 0 || row.files > 0).sort((a, b) => b.bytes - a.bytes) : [],
+ bots: shown.map(([id, tally]) => ({ id, ...tally })),
+ botsRest: rest,
+ 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 },
+ } : null,
+ skipped: totals ? { ...totals.skipped } : null,
+ linksCapped: totals?.linksCapped ?? false,
+ linksUncheckedBytes: totals?.linksUncheckedBytes ?? 0,
+ resumes: totals?.resumes ?? 0,
+ failed,
+ };
+ },
+ };
+}
+export type DiskUsage = ReturnType<typeof createDiskUsage>;
+
+/** The report as the health read carries it: at most STORAGE_HEALTH_MAX_BYTES, bots and named others dropped first. */
+export function storageHealth(report: StorageReport): StorageReport {
+ const body = { ...report };
+ const size = () => JSON.stringify(body).length;
+ const keepBots = (count: number) => {
+ const dropped = body.bots.slice(count);
+ body.bots = body.bots.slice(0, count);
+ body.botsRest = dropped.reduce((rest, bot) => ({ bytes: rest.bytes + bot.bytes, files: rest.files + bot.files, count: rest.count + 1 }), body.botsRest);
+ };
+ if (size() > STORAGE_HEALTH_MAX_BYTES) keepBots(3);
+ if (size() > STORAGE_HEALTH_MAX_BYTES && body.other) body.other = { ...body.other, named: [] };
+ if (size() > STORAGE_HEALTH_MAX_BYTES) keepBots(0);
+ return body;
+}
diff --git a/server/perf/disk-walk.test.ts b/server/perf/disk-walk.test.ts
new file mode 100644
index 0000000000..4a215aaf9c
--- /dev/null
+++ b/server/perf/disk-walk.test.ts
@@ -0,0 +1,226 @@
+import { chmodSync, linkSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, truncateSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { allocatedBytes, checkpointFrom, createDiskWalk, nodeWalkFs, totalsJson, type WalkCheckpoint, type WalkFs, type WalkRoot, type WalkStat, type WalkTotals } from "./disk-walk.ts";
+
+const dirs: string[] = [];
+afterEach(() => {
+ for (const dir of dirs.splice(0)) {
+ try { chmodSync(join(dir, "data", "workspaces", "locked"), 0o700); } catch {}
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+function tree(): { home: string; data: string; roots: WalkRoot[] } {
+ const home = mkdtempSync(join(tmpdir(), "disk-walk-"));
+ dirs.push(home);
+ const data = join(home, "data");
+ const write = (path: string, bytes: number) => { mkdirSync(join(path, ".."), { recursive: true }); writeFileSync(path, Buffer.alloc(bytes, 1)); };
+ write(join(data, "messages.db"), 10_000);
+ write(join(data, "workspaces", "bot1", "notes.md"), 5_000);
+ write(join(data, "task-workspaces", "bot1", "t1", "out.csv"), 7_000);
+ write(join(data, "task-workspaces", "bot2", "t1", "app", "node_modules", "x", "index.js"), 3_000);
+ write(join(data, "browser", "profiles", "p1", "Default", "Cookies"), 2_000);
+ write(join(data, "browser", "profiles", "p1", "Default", "Cache", "Cache_Data", "f"), 9_000);
+ write(join(home, ".npm", "_cacache", "x"), 4_000);
+ write(join(home, "acme-merger", "plan.md"), 1_000);
+ return { home, data, roots: [{ path: home, scope: "home" }, { path: data, scope: "data" }] };
+}
+
+async function walkAll(roots: WalkRoot[], options: Parameters<typeof createDiskWalk>[1] = {}, entries = 1_000_000) {
+ const walk = createDiskWalk(roots, options);
+ let steps = 0;
+ while (!(await walk.step({ entries, stop: () => false }))) steps += 1;
+ return { totals: walk.totals, steps };
+}
+
+const fileCounts = (totals: Awaited<ReturnType<typeof walkAll>>["totals"]) =>
+ Object.fromEntries(Object.entries(totals.categories).filter(([, tally]) => tally.files).map(([name, tally]) => [name, tally.files]));
+
+describe("disk walk", () => {
+ it("counts each file once into its category and bot, walking the data folder as its own root", async () => {
+ const { roots } = tree();
+ const { totals } = await walkAll(roots);
+ expect(fileCounts(totals)).toEqual({ conversations: 1, bot_files: 2, packages: 2, browser_profiles: 1, browser_cache: 1, other: 1 });
+ expect(totals.bots.get("bot1")?.files).toBe(2);
+ expect(totals.bots.get("bot2")?.files).toBe(1);
+ expect(totals.otherUnlisted).toMatchObject({ files: 1, entries: 1 });
+ expect(totals.categories.conversations.bytes).toBeGreaterThanOrEqual(10_000);
+ expect(totals.walkedBytes).toBe(Object.values(totals.categories).reduce((sum, tally) => sum + tally.bytes, 0));
+ });
+
+ it("goes on where it stopped: one entry a step gives the same totals as one step", async () => {
+ const { roots } = tree();
+ const whole = await walkAll(roots);
+ const stepped = await walkAll(roots, {}, 1);
+ expect(stepped.steps).toBeGreaterThan(10);
+ expect(stepped.totals).toEqual(whole.totals);
+ });
+
+ it("stops before the next entry when told to, and reads nothing more", async () => {
+ const { roots } = tree();
+ const walk = createDiskWalk(roots);
+ let calls = 0;
+ expect(await walk.step({ entries: 1_000, stop: () => ++calls > 3 })).toBe(false);
+ expect(walk.totals.entries).toBeLessThanOrEqual(3);
+ const before = walk.totals.entries;
+ expect(await walk.step({ entries: 1_000, stop: () => true })).toBe(false);
+ expect(walk.totals.entries).toBe(before);
+ await walk.close();
+ expect(walk.done).toBe(true);
+ });
+
+ it.skipIf(process.platform === "win32")("never follows a symbolic link, to a folder or a file", async () => {
+ const { home, data, roots } = tree();
+ const outside = mkdtempSync(join(tmpdir(), "disk-walk-outside-"));
+ dirs.push(outside);
+ writeFileSync(join(outside, "big"), Buffer.alloc(200_000, 1));
+ const before = (await walkAll(roots)).totals.walkedBytes;
+ symlinkSync(outside, join(data, "workspaces", "bot1", "linked-folder"));
+ symlinkSync(join(outside, "big"), join(home, "linked-file"));
+ const { totals } = await walkAll(roots);
+ expect(totals.skipped.links).toBe(2);
+ expect(totals.walkedBytes - before).toBeLessThan(200_000);
+ expect(totals.categories.bot_files.files).toBe(3);
+ });
+
+ it.skipIf(process.platform === "win32")("counts a hard-linked file once", async () => {
+ const { data, roots } = tree();
+ linkSync(join(data, "messages.db"), join(data, "workspaces", "bot1", "copy.db"));
+ const { totals } = await walkAll(roots);
+ expect(totals.categories.conversations.files + totals.categories.bot_files.files).toBe(3);
+ });
+
+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)("skips a folder it cannot read and goes on", async () => {
+ const { data, roots } = tree();
+ mkdirSync(join(data, "workspaces", "locked"));
+ writeFileSync(join(data, "workspaces", "locked", "secret"), "x");
+ chmodSync(join(data, "workspaces", "locked"), 0o000);
+ const { totals } = await walkAll(roots);
+ expect(totals.skipped.unreadable).toBe(1);
+ expect(totals.categories.conversations.files).toBe(1);
+ expect(totals.categories.browser_cache.files).toBe(1);
+ });
+
+ it("does not cross into another filesystem", async () => {
+ const { data, roots } = tree();
+ const mounted = join(data, "workspaces", "bot1");
+ const fs: WalkFs = {
+ opendir: nodeWalkFs.opendir,
+ lstat: async (path) => {
+ const stat = await nodeWalkFs.lstat(path);
+ return path === mounted ? Object.assign(Object.create(Object.getPrototypeOf(stat)), stat, { dev: stat.dev + 1 }) as WalkStat : stat;
+ },
+ };
+ const { totals } = await walkAll(roots, { fs });
+ expect(totals.skipped.otherDevice).toBe(1);
+ expect(totals.bots.get("bot1")?.files).toBe(1);
+ });
+
+ it("takes files and folders deleted during the walk in its stride", async () => {
+ const { data, roots } = tree();
+ const fs: WalkFs = {
+ opendir: async (path) => {
+ if (path === join(data, "browser")) rmSync(join(data, "browser"), { recursive: true, force: true });
+ return nodeWalkFs.opendir(path);
+ },
+ lstat: async (path) => {
+ if (path === join(data, "messages.db")) rmSync(path);
+ return nodeWalkFs.lstat(path);
+ },
+ };
+ const { totals } = await walkAll(roots, { fs });
+ expect(totals.skipped.vanished).toBe(2);
+ expect(totals.categories.conversations.files).toBe(0);
+ expect(totals.categories.bot_files.files).toBe(2);
+ });
+
+ it("closes every open folder when closed mid-walk", async () => {
+ const { roots } = tree();
+ const open = new Set<object>();
+ const fs: WalkFs = {
+ lstat: nodeWalkFs.lstat,
+ opendir: async (path) => {
+ const dir = await nodeWalkFs.opendir(path);
+ const handle = { read: () => dir.read(), close: async () => { open.delete(handle); await dir.close(); } };
+ open.add(handle);
+ return handle;
+ },
+ };
+ const walk = createDiskWalk(roots, { fs });
+ await walk.step({ entries: 6, stop: () => false });
+ expect(open.size).toBeGreaterThan(0);
+ await walk.close();
+ expect(open.size).toBe(0);
+ });
+
+ it("stops at the depth limit and keeps bot tallies and hard links bounded", async () => {
+ const { data, roots } = tree();
+ for (let index = 0; index < 5; index++) writeFileSync(join(data, "workspaces", `extra${index}`), "x");
+ for (let index = 0; index < 4; index++) mkdirSync(join(data, "workspaces", `bot-more-${index}`));
+ const { totals } = await walkAll(roots, { maxBots: 2, maxDepth: 3 });
+ expect(totals.bots.size).toBe(2);
+ expect(totals.botsOverflow.bytes).toBeGreaterThan(0);
+ expect(totals.skipped.tooDeep).toBeGreaterThan(0);
+ });
+
+ it("measures allocated blocks where the platform has them, a sparse file's included, else the size", () => {
+ expect(allocatedBytes({ size: 10, blocks: 8 }, false)).toBe(4096);
+ expect(allocatedBytes({ size: 10_000_000, blocks: 8 }, false)).toBe(4096);
+ expect(allocatedBytes({ size: 2_147_483_648, blocks: 0 }, false)).toBe(0);
+ expect(allocatedBytes({ size: 0, blocks: 0 }, false)).toBe(0);
+ expect(allocatedBytes({ size: 10 })).toBe(10);
+ expect(allocatedBytes({ size: 10, blocks: 8 }, false)).toBe(4096);
+ expect(allocatedBytes({ size: 10, blocks: 0 }, true)).toBe(10);
+ });
+
+ it.skipIf(process.platform === "win32")("counts a sparse file by what it takes on disk", async () => {
+ const { data, roots } = tree();
+ const before = (await walkAll(roots)).totals.walkedBytes;
+ truncateSync(join(data, "workspaces", "bot1", "notes.md"), 2_147_483_648);
+ const { totals } = await walkAll(roots);
+ expect(totals.walkedBytes - before).toBeLessThan(1_000_000);
+ });
+
+ it.skipIf(process.platform === "win32")("says how many bytes of hard links went unchecked past the cap", async () => {
+ const { data, roots } = tree();
+ linkSync(join(data, "messages.db"), join(data, "workspaces", "bot1", "copy.db"));
+ const { totals } = await walkAll(roots, { maxLinks: 0 });
+ expect(totals.linksCapped).toBe(true);
+ expect(totals.linksUncheckedBytes).toBeGreaterThanOrEqual(2 * 10_000);
+ });
+
+ it("goes on from any checkpoint to the same totals as one walk, never counting anything twice", async () => {
+ const { data, roots } = tree();
+ for (let index = 0; index < 4; index++) {
+ mkdirSync(join(data, "task-workspaces", "bot1", `t${index + 2}`, "deep", "er"), { recursive: true });
+ writeFileSync(join(data, "task-workspaces", "bot1", `t${index + 2}`, "deep", "er", "f"), Buffer.alloc(3_000, 1));
+ writeFileSync(join(data, "task-workspaces", "bot1", `t${index + 2}`, "top"), Buffer.alloc(1_000, 1));
+ }
+ const whole = (await walkAll(roots)).totals;
+ const checkpoints: WalkCheckpoint[] = [];
+ const first = createDiskWalk(roots, { onBoundary: (take) => { const taken = take(); if (taken) checkpoints.push(JSON.parse(JSON.stringify({ ...taken, totals: totalsJson(taken.totals) }))); } });
+ while (!(await first.step({ entries: 1, stop: () => false })));
+ expect(checkpoints.length).toBeGreaterThan(5);
+ const comparable = (totals: WalkTotals) => ({ ...totalsJson(totals), entries: 0, resumes: 0 });
+ for (const saved of checkpoints) {
+ const checkpoint = checkpointFrom(saved, roots);
+ expect(checkpoint).not.toBeNull();
+ const { totals } = await walkAll(roots, { resume: checkpoint });
+ expect(totals.resumes).toBe(1);
+ expect(comparable(totals)).toEqual(comparable(whole));
+ }
+ });
+
+ it("refuses a saved checkpoint naming a folder outside the roots or a name with a separator", () => {
+ const { home, roots } = tree();
+ const totals = totalsJson(createDiskWalk(roots).totals);
+ expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: home, names: ["a"] }] }, roots)).not.toBeNull();
+ expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: "/etc", names: ["a"] }] }, roots)).toBeNull();
+ expect(checkpointFrom({ totals, doneRoots: [], frames: [{ path: home, names: ["../x"] }] }, roots)).toBeNull();
+ expect(checkpointFrom({ totals, doneRoots: ["/etc"], frames: [] }, roots)).toBeNull();
+ expect(checkpointFrom({ totals: { categories: { "acme-merger": { bytes: 1, files: 1 } }, bots: [["Ada's plans", { bytes: 1, files: 1 }]] }, doneRoots: [], frames: [] }, roots)?.totals.bots.size).toBe(0);
+ });
+});
diff --git a/server/perf/disk-walk.ts b/server/perf/disk-walk.ts
new file mode 100644
index 0000000000..83f9d482b1
--- /dev/null
+++ b/server/perf/disk-walk.ts
@@ -0,0 +1,285 @@
+// A walk over the volume that can stop after any entry and go on later: one directory handle per level held between
+// steps, one file-system call in flight at a time, lstat only (never a link followed, never a file opened), and never
+// past the root's filesystem. Memory: the open levels (at most MAX_DEPTH), the per-bot tallies (at most MAX_BOTS), the
+// hard links seen (at most MAX_LINKS inode numbers) and, for going on after a restart, the names already counted in
+// the open folders of the top RESUME_DEPTH levels (at most MAX_NAMES each).
+import { lstat, opendir } from "node:fs/promises";
+import { join, sep } from "node:path";
+
+import { OTHER_NAMES, placeChild, STORAGE_CATEGORIES, type Placement, type StorageCategory, type StorageScope } from "./disk-categories.ts";
+
+export interface WalkStat {
+ dev: number; ino: number; nlink: number; size: number; blocks?: number;
+ isDirectory(): boolean; isSymbolicLink(): boolean;
+}
+export interface WalkDir { read(): Promise<{ name: string } | null>; close(): Promise<void> }
+export interface WalkFs { lstat(path: string): Promise<WalkStat>; opendir(path: string): Promise<WalkDir> }
+
+export const nodeWalkFs: WalkFs = { lstat: (path) => lstat(path), opendir: (path) => opendir(path, { bufferSize: 32 }) };
+
+export interface WalkRoot { path: string; scope: StorageScope }
+export interface Tally { bytes: number; files: number }
+export interface WalkSkipped {
+ /** Folders and entries that could not be read (permissions, I/O errors). */
+ unreadable: number;
+ /** Folders on another filesystem (a mount): not walked. */
+ otherDevice: number;
+ /** Folders deeper than MAX_DEPTH: counted themselves, not walked. */
+ tooDeep: number;
+ /** Entries deleted between being listed and being read. */
+ vanished: number;
+ /** Symbolic links: their own size counted, never followed. */
+ links: number;
+}
+export interface WalkTotals {
+ categories: Record<StorageCategory, Tally>;
+ /** By candidate bot id (disk-categories.ts BOT_FOLDERS). */
+ bots: Map<string, Tally>;
+ /** Bot folders past MAX_BOTS. */
+ botsOverflow: Tally;
+ /** Other's first-level names from OTHER_NAMES. */
+ otherNamed: Map<string, Tally>;
+ /** Other's first-level entries whose names are never reported. */
+ otherUnlisted: Tally & { entries: number };
+ skipped: WalkSkipped;
+ walkedBytes: number;
+ entries: number;
+ /** More hard-linked files than MAX_LINKS: those past it were counted without the check. */
+ linksCapped: boolean;
+ /** Bytes of hard-linked files counted past MAX_LINKS, so possibly more than once: at most this much is over-counted. */
+ linksUncheckedBytes: number;
+ /** Times this pass went on after a restart; hard links are checked again from nothing after each. */
+ resumes: number;
+}
+
+/** What a pass needs to go on after a restart: the totals so far, the roots finished, and the names counted in each open
+ * folder. Taken only between two folders of the top RESUME_DEPTH levels, so nothing counted is outside those names. */
+export interface WalkCheckpoint {
+ totals: WalkTotals;
+ doneRoots: string[];
+ frames: Array<{ path: string; names: string[] }>;
+}
+
+export const MAX_DEPTH = 64;
+export const MAX_BOTS = 5_000;
+export const MAX_LINKS = 500_000;
+export const RESUME_DEPTH = 4;
+export const MAX_NAMES = 5_000;
+
+interface Frame {
+ path: string; segments: string[]; placement: Placement; scope: StorageScope; dev: number; dir: WalkDir | null;
+ /** Names counted directly in it so far, for a checkpoint; null past MAX_NAMES or below the top levels. */
+ names: string[] | null;
+ /** Names a resumed pass counted before the restart. */
+ skip: ReadonlySet<string> | null;
+}
+
+const emptyTally = (): Tally => ({ bytes: 0, files: 0 });
+
+export function emptyTotals(): WalkTotals {
+ return {
+ categories: Object.fromEntries(Object.keys(STORAGE_CATEGORIES).map((name) => [name, emptyTally()])) as Record<StorageCategory, Tally>,
+ bots: new Map(), botsOverflow: emptyTally(), otherNamed: new Map(), otherUnlisted: { ...emptyTally(), entries: 0 },
+ skipped: { unreadable: 0, otherDevice: 0, tooDeep: 0, vanished: 0, links: 0 }, walkedBytes: 0, entries: 0, linksCapped: false,
+ linksUncheckedBytes: 0, resumes: 0,
+ };
+}
+
+/** Bytes the entry takes on disk: its allocated blocks where the platform reports them (sparse and tiny files), else its
+ * size. Node on Windows reports `blocks` as 0 for every file, so there it is always the size. */
+export function allocatedBytes(stat: Pick<WalkStat, "size" | "blocks">, windows = process.platform === "win32"): number {
+ const blocks = stat.blocks;
+ return !windows && typeof blocks === "number" && Number.isFinite(blocks) && blocks >= 0 ? blocks * 512 : Math.max(0, stat.size);
+}
+
+const BOT_ID = /^[A-Za-z0-9_-]{1,64}$/;
+const count = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);
+const tallyOf = (value: unknown): Tally => ({ bytes: count((value as Tally | null)?.bytes), files: count((value as Tally | null)?.files) });
+
+/** Totals as JSON values (maps as pairs). */
+export function totalsJson(totals: WalkTotals): Record<string, unknown> {
+ return { ...totals, categories: structuredClone(totals.categories), bots: [...totals.bots].map(([id, tally]) => [id, { ...tally }]),
+ otherNamed: [...totals.otherNamed].map(([name, tally]) => [name, { ...tally }]), botsOverflow: { ...totals.botsOverflow },
+ otherUnlisted: { ...totals.otherUnlisted }, skipped: { ...totals.skipped } };
+}
+
+/** Totals read back field by field: a name that is not a category, a bot-id-shaped id or an allowed other name is dropped. */
+export function totalsFrom(value: unknown): WalkTotals {
+ const totals = (value ?? {}) as Record<string, unknown>;
+ const categories = (totals.categories ?? {}) as Record<string, unknown>;
+ const pairs = (list: unknown, keep: (name: string) => boolean) =>
+ new Map((Array.isArray(list) ? list : []).flatMap((pair) => (Array.isArray(pair) && typeof pair[0] === "string" && keep(pair[0]) ? [[pair[0], tallyOf(pair[1])] as const] : [])));
+ const skipped = (totals.skipped ?? {}) as Record<string, unknown>;
+ const unlisted = (totals.otherUnlisted ?? {}) as Record<string, unknown>;
+ return {
+ categories: Object.fromEntries((Object.keys(STORAGE_CATEGORIES) as StorageCategory[]).map((name) => [name, tallyOf(categories[name])])) as WalkTotals["categories"],
+ bots: pairs(totals.bots, (id) => BOT_ID.test(id)), botsOverflow: tallyOf(totals.botsOverflow),
+ otherNamed: pairs(totals.otherNamed, (name) => OTHER_NAMES.has(name)), otherUnlisted: { ...tallyOf(unlisted), entries: count(unlisted.entries) },
+ skipped: { unreadable: count(skipped.unreadable), otherDevice: count(skipped.otherDevice), tooDeep: count(skipped.tooDeep), vanished: count(skipped.vanished), links: count(skipped.links) },
+ walkedBytes: count(totals.walkedBytes), entries: count(totals.entries), linksCapped: totals.linksCapped === true,
+ linksUncheckedBytes: count(totals.linksUncheckedBytes), resumes: count(totals.resumes),
+ };
+}
+
+const NAME = (name: unknown): name is string => typeof name === "string" && name.length > 0 && name.length <= 1024 && !/[\\/\0]/.test(name) && name !== "." && name !== "..";
+
+/** A saved checkpoint, kept only where every path is a root or under one and every name is one folder entry. */
+export function checkpointFrom(value: unknown, roots: readonly WalkRoot[]): WalkCheckpoint | null {
+ const saved = value as { totals?: unknown; doneRoots?: unknown; frames?: unknown } | null;
+ if (!saved || typeof saved !== "object" || !Array.isArray(saved.frames) || !Array.isArray(saved.doneRoots)) return null;
+ const inRoots = (path: unknown): path is string => typeof path === "string" && roots.some((root) => path === root.path || path.startsWith(root.path + sep));
+ if (saved.frames.length > RESUME_DEPTH + 1 || !saved.doneRoots.every((path) => roots.some((root) => root.path === path))) return null;
+ const frames: WalkCheckpoint["frames"] = [];
+ for (const frame of saved.frames as Array<{ path?: unknown; names?: unknown }>) {
+ if (!inRoots(frame?.path) || !Array.isArray(frame.names) || frame.names.length > MAX_NAMES || !frame.names.every(NAME)) return null;
+ frames.push({ path: frame.path, names: [...frame.names] });
+ }
+ return { totals: totalsFrom(saved.totals), doneRoots: [...saved.doneRoots as string[]], frames };
+}
+
+const code = (error: unknown) => (error as NodeJS.ErrnoException | undefined)?.code;
+
+export interface DiskWalkOptions {
+ fs?: WalkFs; maxDepth?: number; maxBots?: number; maxLinks?: number;
+ /** Goes on from a checkpoint of an earlier walk over the same roots. */
+ resume?: WalkCheckpoint | null;
+ /** After each folder of the top RESUME_DEPTH levels ends: `take()` gives a checkpoint, or null when one is not possible now. */
+ onBoundary?: (take: () => WalkCheckpoint | null) => void;
+}
+
+export function createDiskWalk(roots: readonly WalkRoot[], options: DiskWalkOptions = {}) {
+ const fs = options.fs ?? nodeWalkFs, maxDepth = options.maxDepth ?? MAX_DEPTH, maxBots = options.maxBots ?? MAX_BOTS, maxLinks = options.maxLinks ?? MAX_LINKS;
+ const rootPaths = new Set(roots.map((root) => root.path));
+ const resume = options.resume ?? null;
+ const doneRoots = [...resume?.doneRoots ?? []];
+ const pending = roots.filter((root) => !doneRoots.includes(root.path));
+ const stack: Frame[] = [];
+ /** Inode numbers of hard-linked files seen, by device. */
+ const links = new Map<number, Set<number>>();
+ let linkCount = 0;
+ const totals: WalkTotals = resume ? { ...resume.totals, resumes: resume.totals.resumes + 1 } : emptyTotals();
+ /** Folders whose own blocks the pass counted before the restart, and the names it counted in each. */
+ const resumed = new Map((resume?.frames ?? []).map((frame) => [frame.path, new Set(frame.names)]));
+ let done = false;
+
+ const add = (placement: Placement, bytes: number, files: number) => {
+ totals.categories[placement.category].bytes += bytes;
+ totals.categories[placement.category].files += files;
+ totals.walkedBytes += bytes;
+ if (placement.botId !== undefined) {
+ let tally = totals.bots.get(placement.botId);
+ if (!tally && totals.bots.size < maxBots) totals.bots.set(placement.botId, tally = emptyTally());
+ tally ??= totals.botsOverflow;
+ tally.bytes += bytes;
+ tally.files += files;
+ }
+ if (placement.category === "other") {
+ const tally = placement.otherName === undefined ? totals.otherUnlisted
+ : totals.otherNamed.get(placement.otherName) ?? totals.otherNamed.set(placement.otherName, emptyTally()).get(placement.otherName)!;
+ tally.bytes += bytes;
+ tally.files += files;
+ }
+ };
+ const missed = (error: unknown) => { if (code(error) === "ENOENT" || code(error) === "ENOTDIR") totals.skipped.vanished += 1; else totals.skipped.unreadable += 1; };
+ const counted = (frame: Frame, name: string) => {
+ if (!frame.names) return;
+ frame.names.push(name);
+ if (frame.names.length > MAX_NAMES) frame.names = null;
+ };
+ const newFrame = (path: string, segments: string[], placement: Placement, scope: StorageScope, dev: number): Frame => {
+ const skip = resumed.get(path) ?? null;
+ return { path, segments, placement, scope, dev, dir: null, names: segments.length < RESUME_DEPTH ? [...skip ?? []] : null, skip };
+ };
+ const checkpoint = (): WalkCheckpoint | null => {
+ if (!stack.every((frame) => frame.names !== null)) return null;
+ return { totals: totalsFrom(totalsJson(totals)), doneRoots: [...doneRoots], frames: stack.map((frame) => ({ path: frame.path, names: [...frame.names!] })) };
+ };
+ const endFrame = async () => {
+ const frame = stack.pop();
+ if (!frame) return;
+ const dir = frame.dir;
+ frame.dir = null;
+ if (dir) { try { await dir.close(); } catch {} }
+ const parent = stack.at(-1);
+ if (frame.segments.length === 0) doneRoots.push(frame.path);
+ else if (parent) counted(parent, frame.segments.at(-1)!);
+ if (frame.segments.length <= RESUME_DEPTH && options.onBoundary) {
+ try { options.onBoundary(checkpoint); } catch {}
+ }
+ };
+
+ const startRoot = async (root: WalkRoot) => {
+ let stat: WalkStat;
+ try { stat = await fs.lstat(root.path); } catch (error) { missed(error); return; }
+ if (!stat.isDirectory()) return;
+ const placement: Placement = { category: root.scope === "data" ? "settings" : "other", final: false };
+ if (!resumed.has(root.path)) add(placement, allocatedBytes(stat), 0);
+ stack.push(newFrame(root.path, [], placement, root.scope, stat.dev));
+ };
+
+ const visit = async (frame: Frame, name: string) => {
+ const path = join(frame.path, name);
+ if (rootPaths.has(path)) return;
+ let stat: WalkStat;
+ try { stat = await fs.lstat(path); } catch (error) { missed(error); counted(frame, name); return; }
+ const segments = [...frame.segments, name];
+ const directory = stat.isDirectory();
+ const placement = placeChild(frame.placement, frame.scope, segments, directory);
+ const again = resumed.has(path);
+ if (segments.length === 1 && placement.category === "other" && placement.otherName === undefined && !again) totals.otherUnlisted.entries += 1;
+ if (directory) {
+ if (stat.dev !== frame.dev) { totals.skipped.otherDevice += 1; counted(frame, name); return; }
+ if (!again) add(placement, allocatedBytes(stat), 0);
+ if (segments.length >= maxDepth) { totals.skipped.tooDeep += 1; counted(frame, name); return; }
+ stack.push(newFrame(path, segments, placement, frame.scope, frame.dev));
+ return;
+ }
+ counted(frame, name);
+ const bytes = allocatedBytes(stat);
+ if (stat.isSymbolicLink()) totals.skipped.links += 1;
+ else if (stat.nlink > 1) {
+ const seen = links.get(stat.dev) ?? links.set(stat.dev, new Set()).get(stat.dev)!;
+ if (seen.has(stat.ino)) return;
+ if (linkCount < maxLinks) { seen.add(stat.ino); linkCount += 1; } else { totals.linksCapped = true; totals.linksUncheckedBytes += bytes; }
+ }
+ add(placement, bytes, 1);
+ };
+
+ return {
+ totals,
+ get done() { return done; },
+ /** Walks until `entries` entries are read, `stop()` says so (checked before each one) or the walk ends. True when it ended. */
+ async step(budget: { entries: number; stop: () => boolean }): Promise<boolean> {
+ let read = 0;
+ while (!done && read < budget.entries && !budget.stop()) {
+ const frame = stack.at(-1);
+ if (!frame) {
+ const root = pending.shift();
+ if (root) await startRoot(root); else done = true;
+ continue;
+ }
+ if (!frame.dir) {
+ try { frame.dir = await fs.opendir(frame.path); } catch (error) { missed(error); await endFrame(); continue; }
+ }
+ let entry: { name: string } | null;
+ try { entry = await frame.dir.read(); } catch (error) { missed(error); await endFrame(); continue; }
+ if (!entry) { await endFrame(); continue; }
+ if (frame.skip?.has(entry.name)) continue;
+ read += 1;
+ totals.entries += 1;
+ await visit(frame, entry.name);
+ }
+ return done;
+ },
+ /** Closes every open directory; the walk cannot go on after. */
+ async close() {
+ done = true;
+ pending.length = 0;
+ while (stack.length) {
+ const dir = stack.pop()!.dir;
+ if (dir) { try { await dir.close(); } catch {} }
+ }
+ },
+ };
+}
+export type DiskWalk = ReturnType<typeof createDiskWalk>;
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
index bfae3e85b6..9f4a1abaf6 100644
--- a/server/perf/perf-host.ts
+++ b/server/perf/perf-host.ts
@@ -8,6 +8,7 @@ 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 { 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";
@@ -18,6 +19,15 @@ import { createLaunchTimings, LAUNCH_FILE, type LaunchTimings } from "./launch-t
import { startStallWatch, stallReportLines, type StallWatch } from "./stall-watch.ts";
export const PERF_FILE = "perf-timings.json";
+/** The last storage pass and the one under way: under `cache`, which backups leave behind, since they describe this volume only. */
+export const STORAGE_FILE = join("cache", "storage-report.json");
+export const STORAGE_PROGRESS_FILE = join("cache", "storage-progress.json");
+
+/** The storage sampler's part of the perf host's options: only on a Cloud home, whose HOME is its volume, never on a
+ * person's own computer (the desktop app, a self-hosted server). */
+export function cloudStorage(cloudHome: unknown, home: string, knownBot: (id: string) => boolean): { storage?: NonNullable<PerfHostDeps["storage"]> } {
+ return cloudHome ? { storage: { home, knownBot } } : {};
+}
/** One line per kind of slow event at most this often; the ones held back are counted on the next. */
export const LOG_EVERY_MS = 60_000;
const RECENT_IN_REPORT = 10;
@@ -52,6 +62,10 @@ export interface PerfHostDeps {
watchStalls?: boolean;
/** The desktop app started this server: its launches are recorded (launch-timings.ts). */
launches?: Pick<NonNullable<Parameters<typeof createLaunchTimings>[0]>, "launchId" | "counts" | "server">;
+ /** A Cloud home, whose HOME is its volume: what fills it is measured (disk-usage.ts). Never a person's own computer. */
+ storage?: { home: string; knownBot: (id: string) => boolean };
+ /** Tests: the storage sampler. */
+ disk?: DiskUsage;
}
/** The health report shows this many bots, the ones using the most memory first; the admin's read shows every one. */
@@ -122,6 +136,10 @@ export function createPerfHost(deps: PerfHostDeps) {
const caught = () => guarded("stall-watch", () => stallReportLines(watch?.recent() ?? []), []);
/** Stall records right under the heading: a @devs report keeps only the first lines of this part. */
const stallsFirst = (lines: string[]) => { const stalls = caught(); return lines[0]?.startsWith("## ") ? [lines[0], ...stalls, ...lines.slice(1)] : [...stalls, ...lines]; };
+ const disk: DiskUsage | null = deps.disk ?? (deps.storage ? createDiskUsage({ roots: [{ path: deps.storage.home, scope: "home" }, { path: deps.dataDir, scope: "data" }], volume: deps.storage.home,
+ 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();
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(),
@@ -144,6 +162,8 @@ export function createPerfHost(deps: PerfHostDeps) {
/** Logs a usage-limit hold that started or ended since the last check; the sampler runs it after each sample. */
checkHolds: watchHolds,
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),
/** 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));
@@ -153,7 +173,7 @@ export function createPerfHost(deps: PerfHostDeps) {
return stallsFirst(guarded("text", () => perfLines(sources(), timings.recent({ limit: RECENT_IN_REPORT }), "Latest turns, newest last:"), PERF_UNAVAILABLE)).join("\n");
},
/** The graceful shutdown: no more samples, and the turns since the last save written now. */
- stop() { sampler.stop(); stalls.stop(); watch?.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },
+ stop() { sampler.stop(); stalls.stop(); watch?.stop(); void disk?.stop(); guarded("save", () => timings.flush(), undefined); if (launches) guarded("launch", () => launches.flush(), undefined); },
};
}
export type PerfHost = ReturnType<typeof createPerfHost>;
diff --git a/server/perf/perf-privacy.test.ts b/server/perf/perf-privacy.test.ts
index f02861514c..e6225f7562 100644
--- a/server/perf/perf-privacy.test.ts
+++ b/server/perf/perf-privacy.test.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -7,6 +7,7 @@ import { createCloudHealth } from "../cloud-health.ts";
import type { RuntimeEvent } from "../contracts.ts";
import { buildDevsReport } from "../devs-report.ts";
import type { StoreChange } from "../store.ts";
+import { createDiskUsage } from "./disk-usage.ts";
import { createPerfHost, PERF_FILE } from "./perf-host.ts";
import { createLaunchTimings, LAUNCH_CHILDREN, LAUNCH_FILE, LAUNCH_HOSTS, LAUNCH_MARKS, LAUNCH_SPANS } from "./launch-timings.ts";
import { PERF_HEALTH_MAX_BYTES, perfHealth } from "./perf-report.ts";
@@ -132,6 +133,37 @@ describe("performance diagnostics carry no content", () => {
});
});
+describe("the storage report carries no names from the disk", () => {
+ it("rides the signed health report as `storage` and the owner's route with no seeded secret, though every file and folder is named after one", async () => {
+ const home = mkdtempSync(join(tmpdir(), "perf-storage-"));
+ dirs.push(home);
+ const data = join(home, ".openmausbot");
+ const named = (secret: string) => secret.replace(/[/\\:?]/g, "_");
+ for (const secret of SECRETS) {
+ for (const parent of [home, data, join(data, "workspaces", "bot_ok"), join(data, "workspaces", named(secret)), join(data, "browser", "profiles", named(secret))]) {
+ mkdirSync(join(parent, named(secret)), { recursive: true });
+ writeFileSync(join(parent, named(secret), named(secret)), secret);
+ }
+ }
+ const store = { onChange: () => () => {}, botByThread: () => null, bots: [] };
+ const bus = { subscribe: () => () => {} };
+ const disk = createDiskUsage({ roots: [{ path: home, scope: "home" }, { path: data, scope: "data" }], volume: home, timer: false, firstPassAfterMs: 0, now: () => START,
+ knownBot: (id) => id === "bot_ok" });
+ const perf = createPerfHost({ dataDir: data, timer: false, now: () => START, wholeMachine: true, bus, store, disk });
+ expect(perf.storage()).toMatchObject({ v: 1, at: null });
+ for (let index = 0; index < 1_000 && (disk.running() || disk.report().at === null); index++) await disk.tick();
+ const cloud = { store, bus, engines: () => [], dataDir: data, eventsDir: data, version: "0.1.160", image: undefined, connectors: () => null,
+ browser: () => ({ available: true, installing: false, interrupted: 0 }), now: () => START };
+ const report = createCloudHealth({ ...cloud, storage: perf.storage }).report(undefined);
+ expect(report.storage).toMatchObject({ v: 1, at: START, bots: [{ id: "bot_ok" }] });
+ expect(report.storage!.categories.reduce((sum, row) => sum + row.files, 0)).toBe(SECRETS.length * 5);
+ expect(leaks(JSON.stringify(report.storage))).toEqual([]);
+ expect(leaks(JSON.stringify(perf.storage()))).toEqual([]);
+ expect(createCloudHealth(cloud).report(undefined)).not.toHaveProperty("storage");
+ perf.stop();
+ });
+});
+
describe("a tampered file read back", () => {
it("passes nothing but checked fields: every string a secret, every key a trap", () => {
const dir = mkdtempSync(join(tmpdir(), "perf-tampered-"));
diff --git a/server/perf/turn-timings.ts b/server/perf/turn-timings.ts
index da3cc6360d..2d953cdb47 100644
--- a/server/perf/turn-timings.ts
+++ b/server/perf/turn-timings.ts
@@ -318,6 +318,8 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
return { turns: turns.length, failed: turns.filter((turn) => !turn.ok).length, phases, setup: setupStatsOf(turns), slow, partial: ring.length >= RING_CAP && ring[0]!.endedAt > from };
},
day: (windowMs = DAY_HOURS * HOUR) => day.read(windowMs),
+ /** Whether any turn runs now: cheap enough to ask before each file the storage walk reads. */
+ running(): boolean { sweep(now()); return live.size > 0; },
live(): LiveTurnView[] {
const at = now();
sweep(at);
diff --git a/server/routes/perf-diagnostics.ts b/server/routes/perf-diagnostics.ts
index 07c8fb4ab2..479d209cea 100644
--- a/server/routes/perf-diagnostics.ts
+++ b/server/routes/perf-diagnostics.ts
@@ -1,27 +1,30 @@
// 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. 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. 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 { 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 LAUNCH_PATH = "/api/diagnostics/launch";
const LAUNCH_BODY_MAX = 16 * 1024;
-export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): BotFootprintReport | null; launch?(part: unknown): { ok: boolean; complete: boolean } | null }): RouteHandler {
+export function createPerfDiagnosticsRoutes(deps: { text(): string; bots?(): BotFootprintReport | null; storage?(): StorageReport | null; launch?(part: unknown): { ok: boolean; complete: boolean } | null }): RouteHandler {
return async ({ req, res, path, method, json, readBody }) => {
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;
return json(res, noted ? 200 : 404, noted ?? { ok: false, complete: false });
}
- if (method !== "GET" || (path !== PERF_DIAGNOSTICS_PATH && path !== BOT_FOOTPRINT_PATH)) return PASS;
+ if (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 });
return json(res, 200, { text: deps.text() });
};
}