Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud home: a signed, read-only diagnose read for the Admin (GET /api/cloud/diagnose) (#7544)
Milind Sonib4a5b15e999f
diff --git a/server/cloud-diagnose.test.ts b/server/cloud-diagnose.test.tsnew file mode 100644index 0000000000..7211056370--- /dev/null+++ b/server/cloud-diagnose.test.ts@@ -0,0 +1,177 @@+import type { IncomingMessage, ServerResponse } from "node:http";+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";+import { afterEach, describe, expect, it } from "vitest";++import { CLOUD_DIAGNOSE_PATH, createCloudDiagnose, DIAGNOSE_REUSE_MS } from "./cloud-diagnose.ts";+import { createCloudHealth } from "./cloud-health.ts";+import { cloudRequestSignature } from "./cloud-home.ts";+import { diagnoseWalk, YIELD_EVERY, type DiagnoseFs, type DiagnoseStat } from "./perf/diagnose-walk.ts";+import type { StorageReport } from "./perf/disk-usage.ts";+import { createStorageHistory } from "./perf/storage-history.ts";+import { createCloudSignedRoutes } from "./routes/cloud-signed.ts";+import { SessionRegistry } from "./sessions.ts";++const secret = "S".repeat(43);+const T0 = 1_800_000_000_000, DAY = 86_400_000;+const folders: string[] = [];+afterEach(() => { for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true }); });+const tempDir = () => { const dir = mkdtempSync(join(tmpdir(), "omb-diagnose-")); folders.push(dir); return dir; };++// Names a customer could have made: an email, a path with spaces, quotes, emoji, a secret-looking string, newlines.+const AWKWARD = ["[email protected]", "Tax return 2026 (final).pdf", "my \"secret\" plan.txt", "🦄 notes", "sk-live-ABCDEF1234567890", "line\nbreak", "..hidden", "Downloads"];++function homeFixture() {+ const home = tempDir(), data = join(home, ".openmausbot");+ for (const [folder, file] of [["workspaces/bot-abc/Project Jane", AWKWARD[1]!], ["task-workspaces/t1/node_modules/left-pad", "index.js"], ["Downloads", AWKWARD[0]!], [AWKWARD[3]!, AWKWARD[2]!]] as const) {+ const parent = folder.startsWith("workspaces") || folder.startsWith("task-workspaces") ? join(data, folder) : join(home, folder);+ mkdirSync(parent, { recursive: true });+ writeFileSync(join(parent, file), "x".repeat(2048));+ }+ mkdirSync(join(data, "events"), { recursive: true });+ writeFileSync(join(data, "events", AWKWARD[5]!), "{}");+ writeFileSync(join(home, AWKWARD[4]!), "secret");+ utimesSync(join(home, "Downloads", AWKWARD[0]!), new Date(T0 - 3 * DAY), new Date(T0 - 3 * DAY));+ return { home, data };+}++function health(dataDir: string, now: () => number) {+ return createCloudHealth({+ store: { onChange: () => () => {}, botByThread: () => null, bots: [] }, bus: { subscribe: () => () => {} },+ engines: () => [{ instanceId: "i1", driverKind: "claude", snapshot: undefined }], dataDir, eventsDir: dataDir, version: "0.1.181", image: undefined,+ connectors: () => null, browser: () => ({ available: true, installing: false, interrupted: 0 }), now,+ });+}++const storageReport = (at: number, bytes: Record<string, number>): StorageReport => ({+ v: 1, at, ageS: 60, tookS: 30, running: false, progress: null, volume: { totalBytes: 100e9, freeBytes: 4e9, usedBytes: 96e9 }, walkedBytes: 90e9, unwalkedBytes: 6e9,+ categories: Object.entries(bytes).map(([name, value]) => ({ name: name as StorageReport["categories"][number]["name"], class: "work" as const, bytes: value, files: 10 })),+ bots: [{ id: "bot-abc", bytes: 1, files: 1 }], botsRest: { bytes: 0, files: 0, count: 0 }, other: null, skipped: null, linksCapped: false, linksUncheckedBytes: 0, resumes: 0, failed: false,+});++describe("the diagnose read", () => {+ it("carries no name from the customer's folders: categories, fixed buckets, counts, sizes and ages only", async () => {+ const { home, data } = homeFixture();+ let clock = T0;+ const now = () => clock;+ const diagnose = createCloudDiagnose({ health: health(data, now), storage: () => storageReport(T0 - 1000, { bot_files: 5e9, other: 1e9 }), history: createStorageHistory({ file: null }),+ dataDir: data, home, now, uptimeS: () => ({ process: 10, machine: 20 }) });+ const report = await diagnose.read();+ const text = JSON.stringify(report);+ for (const name of [...AWKWARD.filter((name) => name !== "Downloads"), "Project Jane", "left-pad", "index.js", home]) expect(text).not.toContain(JSON.stringify(name).slice(1, -1));+ const buckets = Object.fromEntries(report.disk.detail!.buckets.map((row) => [row.name, row]));+ expect(buckets.downloads).toMatchObject({ files: 1, oldestAt: T0 - 3 * DAY });+ expect(buckets.node_modules?.files).toBe(1);+ expect(buckets.bot_files?.files).toBe(1);+ expect(buckets.conversations?.files).toBe(1);+ expect(report.disk.detail!.incomplete).toBe(false);+ expect(report.disk.categories.map((row) => row.name)).toEqual(["bot_files", "other"]);+ expect(report.uptimeS).toEqual({ process: 10, machine: 20 });+ expect(report.engines).toEqual([{ kind: "claude", used: false, available: null, authenticated: null, version: null }]);+ clock += 1000;+ expect((await diagnose.read()).reused).toBe(true);+ clock += DIAGNOSE_REUSE_MS;+ expect((await diagnose.read()).reused).toBe(false);+ });++ it("says what grew in the last day and week once the history reaches back that far, and unknown before", () => {+ const history = createStorageHistory({ file: null });+ history.note(storageReport(T0, { bot_files: 1e9, logs: 1e8 }));+ expect(history.growth(DAY)).toBeNull();+ history.note(storageReport(T0 + DAY, { bot_files: 3e9, logs: 1e8, temp: 5e8 }));+ history.note(storageReport(T0 + DAY, { bot_files: 9e9 }));+ expect(history.growth(DAY)).toEqual({ since: T0, rows: [{ name: "bot_files", bytes: 2e9 }, { name: "temp", bytes: 5e8 }] });+ expect(history.growth(7 * DAY)).toBeNull();+ history.note({ ...storageReport(T0 + 2 * DAY, { bot_files: 1 }), failed: true });+ expect(history.points()).toHaveLength(2);+ });+});++describe("the diagnose walk's budget", () => {+ // A fake tree of 10 folders of 100,000 files each: far more than the budget allows.+ const huge = (): { fs: DiagnoseFs; calls: () => number } => {+ let calls = 0;+ const stat = (directory: boolean): DiagnoseStat => ({ dev: 1, size: 4096, mtimeMs: T0, isDirectory: () => directory, isSymbolicLink: () => false });+ const fs: DiagnoseFs = {+ lstat: async (path) => { calls++; return stat(!/f\d+$/.test(path)); },+ opendir: async (path) => {+ calls++;+ const depth = path.split("/").length, names = depth <= 3 ? Array.from({ length: 10 }, (_, i) => `d${i}`) : Array.from({ length: 100_000 }, (_, i) => `f${i}`);+ let index = 0;+ return { read: async () => (index < names.length ? { name: names[index++]! } : null), close: async () => {} };+ },+ };+ return { fs, calls: () => calls };+ };++ it("stops at its entry budget and says the figures are partial", async () => {+ const tree = huge();+ let yields = 0;+ const result = await diagnoseWalk([{ path: "/data", scope: "home" }], { fs: tree.fs, maxEntries: 5_000, yieldNow: async () => { yields++; } });+ expect(result).toMatchObject({ incomplete: true, stoppedBy: "entries", entries: 5_000 });+ expect(yields).toBe(Math.floor(4_999 / YIELD_EVERY));+ expect(tree.calls()).toBeLessThan(5_100);+ });++ it("stops at its time budget, checked at each yield, on its own clock", async () => {+ const tree = huge();+ let clock = 0;+ const result = await diagnoseWalk([{ path: "/data", scope: "home" }], { fs: tree.fs, now: () => clock, maxMs: 1_000, yieldNow: async () => { clock += 100; } });+ expect(result).toMatchObject({ incomplete: true, stoppedBy: "time", entries: 10 * YIELD_EVERY, tookMs: 1_000 });+ });++ it("never goes deeper than its depth limit", async () => {+ let opened = 0;+ const fs: DiagnoseFs = {+ lstat: async () => ({ dev: 1, size: 1, mtimeMs: T0, isDirectory: () => true, isSymbolicLink: () => false }),+ opendir: async () => { opened++; let given = false; return { read: async () => (given ? null : (given = true, { name: "deeper" })), close: async () => {} }; },+ };+ const result = await diagnoseWalk([{ path: "/data", scope: "home" }], { fs, maxDepth: 6 });+ expect(result).toMatchObject({ incomplete: false, tooDeep: 1 });+ expect(opened).toBe(6);+ });+});++describe("GET /api/cloud/diagnose", () => {+ function routes() {+ const { home, data } = homeFixture();+ let counter = 0;+ const now = () => T0;+ const diagnose = createCloudDiagnose({ health: health(data, now), storage: () => null, dataDir: data, home, now, uptimeS: () => ({ process: 1, machine: 2 }) });+ const handle = createCloudSignedRoutes({ secret, sessions: new SessionRegistry({ file: join(data, "sessions.json"), now }), health: health(data, now), diagnose, now });+ const sign = (method = "GET", key = secret) => {+ const timestamp = String(Math.floor(now() / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;+ return { "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudRequestSignature(key, timestamp, nonce, method, CLOUD_DIAGNOSE_PATH, "")}` };+ };+ const send = async (method: string, headers: Record<string, string>) => {+ const req = Object.assign(new PassThrough(), { method, url: CLOUD_DIAGNOSE_PATH, headers, socket: { remoteAddress: "127.0.0.1" } }) as unknown as IncomingMessage;+ let status = 0, text = "";+ const res = { setHeader() {}, writeHead(code: number) { status = code; }, end(body: string) { text = body; } } as unknown as ServerResponse;+ const url = new URL(CLOUD_DIAGNOSE_PATH, "http://localhost");+ const answered = handle({ req, res, url, path: url.pathname, method });+ (req as unknown as PassThrough).end("");+ return { answered: await answered, status, body: text ? JSON.parse(text) : null };+ };+ return { sign, send };+ }++ it("answers only the Admin's signed GET", async () => {+ const { sign, send } = routes();+ const ok = await send("GET", sign());+ expect(ok).toMatchObject({ answered: true, status: 200 });+ expect(ok.body).toMatchObject({ v: 1, version: "0.1.181", disk: { pass: null } });+ expect((await send("GET", sign("GET", "W".repeat(43)))).status).toBe(401);+ expect((await send("GET", {})).status).toBe(401);+ expect((await send("POST", sign("POST"))).status).toBe(405);+ });++ it("is not a route on a server with no diagnose", async () => {+ const data = tempDir();+ const handle = createCloudSignedRoutes({ secret, sessions: new SessionRegistry({ file: join(data, "sessions.json") }), health: health(data, Date.now) });+ const req = Object.assign(new PassThrough(), { method: "GET", url: CLOUD_DIAGNOSE_PATH, headers: {}, socket: { remoteAddress: "127.0.0.1" } }) as unknown as IncomingMessage;+ const url = new URL(CLOUD_DIAGNOSE_PATH, "http://localhost");+ expect(await handle({ req, res: {} as ServerResponse, url, path: url.pathname, method: "GET" })).toBe(false);+ });+});diff --git a/server/cloud-diagnose.ts b/server/cloud-diagnose.tsnew file mode 100644index 0000000000..b130693c7c--- /dev/null+++ b/server/cloud-diagnose.ts@@ -0,0 +1,140 @@+// The Admin's diagnose read of a Cloud home (`GET /api/cloud/diagnose`, signed like the health read; routes/cloud-signed.ts):+// what fills the disk and what grew, what runs and how much memory and CPU it takes, how the event loop and the machine are+// coping, and the last turn failures, for an operator who cannot open a shell on the Cloud. Read-only.+//+// Cost: the storage figures are the last storage pass (perf/disk-usage.ts, never a new pass here); the only walk is+// perf/diagnose-walk.ts under its own hard budget, which returns partial figures marked `incomplete` rather than run long.+// A read within DIAGNOSE_REUSE_MS of the last one is answered with that one (`reused`), so a burst of reads walks once.+//+// Privacy invariant: category and bucket names from fixed lists, process kinds (server, engine:<kind>, browser, ...) never their+// arguments, failure codes from the health ledger, numbers and times. Never a file name, a path, a bot's name, a title, content+// or an engine's account.+import { uptime as machineUptime } from "node:os";+import { dirname } from "node:path";++import type { CloudHealth } from "./cloud-health.ts";+import { diagnoseWalk, type DiagnoseFs, type DiagnoseWalkResult } from "./perf/diagnose-walk.ts";+import type { StorageReport } from "./perf/disk-usage.ts";+import { DIAGNOSE_GROWTH_WINDOWS, type Growth, type StorageHistory } from "./perf/storage-history.ts";++export const CLOUD_DIAGNOSE_PATH = "/api/cloud/diagnose";+export const DIAGNOSE_VERSION = 1;+/** A read this soon after the last is answered with the last one. */+export const DIAGNOSE_REUSE_MS = 3 * 60_000;+/** The newest turn failures listed, by code. */+export const DIAGNOSE_FAILURES = 20;+const CODE = /^[a-z0-9][a-z0-9_.:-]{0,79}$/i;++export interface DiagnoseDeps {+ health: Pick<CloudHealth, "report" | "ledger">;+ /** The last storage pass, untrimmed; null where none is measured. */+ storage?: () => StorageReport | null;+ history?: StorageHistory | null;+ dataDir: string;+ /** The volume's root (HOME on a Cloud home, /data); defaults to the data folder's parent. */+ home?: string;+ fs?: DiagnoseFs;+ walk?: { maxEntries?: number; maxMs?: number; maxDepth?: number; yieldNow?: () => Promise<void> };+ uptimeS?: () => { process: number; machine: number };+ now?: () => number;+}++const code = (value: string | null | undefined) => (typeof value === "string" && CODE.test(value) ? value : null);+const growthOf = (growth: Growth | null | undefined) => (growth ? { since: growth.since, rows: growth.rows.slice(0, 10) } : null);++export function createCloudDiagnose(deps: DiagnoseDeps) {+ const now = deps.now ?? Date.now;+ let last: { at: number; report: DiagnoseReport } | null = null, running: Promise<DiagnoseReport> | null = null;++ const build = async (): Promise<DiagnoseReport> => {+ const started = now();+ const health = deps.health.report(null);+ let storage: StorageReport | null = null;+ try { storage = deps.storage?.() ?? null; } catch { storage = null; }+ try { deps.history?.note(storage); } catch { /* history is best effort */ }+ const home = deps.home ?? dirname(deps.dataDir);+ let walk: DiagnoseWalkResult | null = null;+ try {+ walk = await diagnoseWalk([{ path: home, scope: "home" }, { path: deps.dataDir, scope: "data" }], { ...deps.walk, ...(deps.fs ? { fs: deps.fs } : {}), now });+ } catch { walk = null; }+ const failures = [...deps.health.ledger.read(null).incidents].sort((a, b) => b.lastAt - a.lastAt).slice(0, DIAGNOSE_FAILURES)+ .flatMap((row) => (code(row.code) ? [{ kind: row.kind, code: row.code, engine: code(row.engine), count: row.count, firstAt: row.firstAt, lastAt: row.lastAt }] : []));+ const perf = health.perf;+ const uptime = deps.uptimeS?.() ?? { process: Math.round(process.uptime()), machine: Math.round(machineUptime()) };+ const report: DiagnoseReport = {+ v: DIAGNOSE_VERSION, at: now(), version: health.version, bootedAt: health.bootedAt, uptimeS: uptime,+ incomplete: Boolean(walk?.incomplete) || walk === null || Boolean(storage?.running && storage.at === null), tookMs: 0, reused: false,+ disk: {+ volume: health.system.disk,+ pass: storage ? { at: storage.at, ageS: storage.ageS, tookS: storage.tookS, running: storage.running, failed: storage.failed, progress: storage.progress } : null,+ categories: storage?.categories ?? [],+ unwalkedBytes: storage?.unwalkedBytes ?? null,+ bots: storage ? { shown: storage.bots.slice(0, 5), rest: storage.botsRest, gone: storage.botsGone ?? null } : null,+ caches: storage?.caches ?? null,+ growth: { h24: growthOf(deps.history?.growth(DIAGNOSE_GROWTH_WINDOWS.h24)), d7: growthOf(deps.history?.growth(DIAGNOSE_GROWTH_WINDOWS.d7)) },+ detail: walk,+ },+ processes: perf?.process ? { at: perf.process.at, scope: perf.process.scope, browsers: perf.process.browsers, unseen60mS: perf.process.unseen60mS, loop: perf.process.loop,+ kinds: perf.process.buckets.map((bucket) => ({ kind: bucket.bucket, procs: bucket.procs, rssMB: bucket.rssMB, cpu5mS: bucket.cpu5mS, cpu60mS: bucket.cpu60mS, peakPct: bucket.peakPct })) } : null,+ limits: perf?.processes ?? null,+ memory: { totalBytes: health.system.totalBytes, availableBytes: health.system.availableBytes, serverRssBytes: health.system.rssBytes, load1: health.system.load1, cpus: health.system.cpus,+ psi: health.speed.psi, steal: health.speed.steal, room: health.room },+ stalls: perf?.stalls ?? null,+ speed: { bootMs: health.speed.bootMs, wakeMs: health.speed.wakeMs },+ turns: health.turns,+ failures,+ engines: health.engines,+ browser: health.browser,+ box: health.box,+ doctor: health.doctor,+ };+ report.tookMs = Math.max(0, now() - started);+ return report;+ };++ return {+ /** The report, or the last one when it is younger than DIAGNOSE_REUSE_MS; concurrent reads share one build. */+ async read(): Promise<DiagnoseReport> {+ if (last && now() - last.at < DIAGNOSE_REUSE_MS) return { ...last.report, reused: true };+ if (running) return running;+ running = build().then((report) => { last = { at: now(), report }; return report; }).finally(() => { running = null; });+ return running;+ },+ };+}+export type CloudDiagnose = ReturnType<typeof createCloudDiagnose>;++type Health = ReturnType<CloudHealth["report"]>;+export interface DiagnoseReport {+ v: typeof DIAGNOSE_VERSION;+ at: number;+ version: string;+ bootedAt: number;+ uptimeS: { process: number; machine: number };+ /** Some part could not be read in full within its budget: the figures are partial. */+ incomplete: boolean;+ tookMs: number;+ /** The last read's report, answered again (DIAGNOSE_REUSE_MS). */+ reused: boolean;+ disk: {+ volume: Health["system"]["disk"];+ pass: { at: number | null; ageS: number | null; tookS: number | null; running: boolean; failed: boolean; progress: StorageReport["progress"] } | null;+ categories: StorageReport["categories"];+ unwalkedBytes: number | null;+ bots: { shown: StorageReport["bots"]; rest: StorageReport["botsRest"]; gone: StorageReport["botsGone"] | null } | null;+ caches: StorageReport["caches"] | null;+ growth: { h24: Growth | null; d7: Growth | null };+ detail: DiagnoseWalkResult | null;+ };+ processes: { at: number | null; scope: string; browsers: number; unseen60mS: number | null; loop: unknown; kinds: Array<{ kind: string; procs: number; rssMB: number; cpu5mS: number; cpu60mS: number; peakPct: number }> } | null;+ limits: unknown;+ memory: { totalBytes: number; availableBytes: number; serverRssBytes: number; load1: number; cpus: number; psi: Health["speed"]["psi"]; steal: number | null; room: Health["room"] };+ stalls: unknown;+ speed: { bootMs: number | null; wakeMs: number | null };+ turns: Health["turns"];+ failures: Array<{ kind: string; code: string; engine: string | null; count: number; firstAt: number; lastAt: number }>;+ engines: Health["engines"];+ browser: Health["browser"];+ box: Health["box"];+ doctor: Health["doctor"];+}diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.tsindex ec166fbe43..9a10769744 100644--- a/server/host/cloud-signed-host.ts+++ b/server/host/cloud-signed-host.ts@@ -2,9 +2,11 @@// bootstrap secret. Null on any server that is not a Cloud home. The bot box's report rides both the health report and// its own route, `GET /api/cloud/box`.import type { BoxReport } from "../bot-box/box.ts";+import { createCloudDiagnose } from "../cloud-diagnose.ts";import { createCloudHealth, type CloudHealth, type CloudHealthDeps } from "../cloud-health.ts";import type { CloudHomeConfig } from "../cloud-home.ts";import type { CloudPower } from "../cloud-power.ts";+import { createStorageHistory } from "../perf/storage-history.ts";import { createCloudSignedRoutes } from "../routes/cloud-signed.ts";import type { TeamAdminSummary } from "../cloud-team-admin.ts";import type { SessionRegistry } from "../sessions.ts";@@ -33,11 +35,16 @@ export interface CloudSignedHostDeps {}export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth: CloudHealth | null; cloudSigned: ReturnType<typeof createCloudSignedRoutes> | null } {- const cloudHealth = deps.cloudHome ? createCloudHealth({ ...deps.health, box: deps.box }) : null;+ // Each completed storage pass the health read sees is kept for the diagnose read's growth figures (perf/storage-history.ts).+ const history = deps.cloudHome ? createStorageHistory({ dataDir: deps.health.dataDir }) : null;+ const storage = deps.health.storage;+ const health = storage && history ? { ...deps.health, storage: () => { const report = storage(); try { history.note(report); } catch {} return report; } } : deps.health;+ const cloudHealth = deps.cloudHome ? createCloudHealth({ ...health, box: deps.box }) : null;+ const diagnose = cloudHealth ? createCloudDiagnose({ health: cloudHealth, storage: storage ?? (() => null), history, dataDir: deps.health.dataDir, ...(process.env.HOME ? { home: process.env.HOME } : {}) }) : null;const cloudSigned = deps.cloudHome && cloudHealth? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box,...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}), ...(deps.cloudHome.team && deps.invited ? { invited: deps.invited } : {}), ...(deps.cloudHome.team && deps.memberBrowserOff ? { memberBrowserOff: deps.memberBrowserOff } : {}),- ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}), ...(deps.planTier ? { planTier: deps.planTier } : {}) })+ ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}), ...(deps.planTier ? { planTier: deps.planTier } : {}), diagnose }): null;return { cloudHealth, cloudSigned };}diff --git a/server/perf/diagnose-walk.ts b/server/perf/diagnose-walk.tsnew file mode 100644index 0000000000..af35c84700--- /dev/null+++ b/server/perf/diagnose-walk.ts@@ -0,0 +1,128 @@+// The diagnose read's own look at the volume (server/cloud-diagnose.ts): how many files each kind of folder holds and how old+// its newest and oldest file are, which the storage pass (disk-usage.ts) does not keep. It runs only when the Admin asks, under+// a hard budget: at most `maxEntries` entries, `maxMs` of its own clock and `maxDepth` levels, one file-system call at a time,+// yielding to the event loop every YIELD_EVERY entries, and it stops early (`incomplete`) rather than run long on a nearly+// full, busy Cloud. lstat only: never a link followed, never a file opened, never past the root's filesystem.+// Privacy invariant: it returns category names, fixed bucket names, counts, bytes and times. No name read from the disk.+import { lstat, opendir } from "node:fs/promises";+import { join } from "node:path";++import { placeChild, placeStoragePath, type Placement, type StorageCategory, type StorageScope } from "./disk-categories.ts";++export interface DiagnoseStat { dev: number; size: number; blocks?: number; mtimeMs: number; isDirectory(): boolean; isSymbolicLink(): boolean }+export interface DiagnoseDir { read(): Promise<{ name: string } | null>; close(): Promise<void> }+export interface DiagnoseFs { lstat(path: string): Promise<DiagnoseStat>; opendir(path: string): Promise<DiagnoseDir> }+export const nodeDiagnoseFs: DiagnoseFs = { lstat: (path) => lstat(path), opendir: (path) => opendir(path, { bufferSize: 32 }) };++export const DIAGNOSE_WALK_MAX_ENTRIES = 250_000;+export const DIAGNOSE_WALK_MAX_MS = 8_000;+export const DIAGNOSE_WALK_MAX_DEPTH = 24;+/** Entries between two yields to the event loop. */+export const YIELD_EVERY = 256;++/** Finer kinds than the storage categories, matched by fixed folder names only: never a name from the disk in the output. */+export type DiagnoseBucket = StorageCategory | "node_modules" | "task_workspaces" | "downloads";+const DOWNLOADS = new Set(["Downloads", "downloads"]);++export interface BucketTally { bytes: number; files: number; newestAt: number | null; oldestAt: number | null }+export interface DiagnoseWalkResult {+ /** Stopped at a budget before it saw everything. */+ incomplete: boolean;+ /** Which budget stopped it, when one did. */+ stoppedBy: "entries" | "time" | null;+ entries: number;+ tookMs: number;+ /** Folders deeper than maxDepth, counted as one entry each and not entered. */+ tooDeep: number;+ unreadable: number;+ buckets: Array<{ name: DiagnoseBucket } & BucketTally>;+}++export interface DiagnoseWalkOptions {+ fs?: DiagnoseFs;+ now?: () => number;+ maxEntries?: number;+ maxMs?: number;+ maxDepth?: number;+ /** Awaited every YIELD_EVERY entries; a test counts these. */+ yieldNow?: () => Promise<void>;+}++const tally = (): BucketTally => ({ bytes: 0, files: 0, newestAt: null, oldestAt: null });+const bytesOf = (stat: DiagnoseStat) => (typeof stat.blocks === "number" ? stat.blocks * 512 : stat.size);+const fine = (scope: StorageScope, segments: readonly string[], placement: Placement): DiagnoseBucket => {+ if (segments.includes("node_modules")) return "node_modules";+ if (scope === "data" && segments[0] === "task-workspaces") return "task_workspaces";+ if (segments.some((part) => DOWNLOADS.has(part))) return "downloads";+ return placement.category;+};++interface Frame { path: string; segments: string[]; placement: Placement; scope: StorageScope; dev: number; dir: DiagnoseDir | null }++/** Walks `roots` (a root inside another root is walked once, as itself) within the budget. */+export async function diagnoseWalk(roots: ReadonlyArray<{ path: string; scope: StorageScope }>, options: DiagnoseWalkOptions = {}): Promise<DiagnoseWalkResult> {+ const fs = options.fs ?? nodeDiagnoseFs, now = options.now ?? Date.now;+ const maxEntries = options.maxEntries ?? DIAGNOSE_WALK_MAX_ENTRIES, maxMs = options.maxMs ?? DIAGNOSE_WALK_MAX_MS, maxDepth = options.maxDepth ?? DIAGNOSE_WALK_MAX_DEPTH;+ const yieldNow = options.yieldNow ?? (() => new Promise<void>((resolve) => setImmediate(resolve)));+ const started = now(), rootPaths = new Set(roots.map((root) => root.path));+ const buckets = new Map<DiagnoseBucket, BucketTally>();+ let entries = 0, tooDeep = 0, unreadable = 0, stoppedBy: DiagnoseWalkResult["stoppedBy"] = null;+ const add = (bucket: DiagnoseBucket, stat: DiagnoseStat, file: boolean) => {+ const row = buckets.get(bucket) ?? buckets.set(bucket, tally()).get(bucket)!;+ row.bytes += bytesOf(stat);+ if (!file) return;+ row.files += 1;+ if (Number.isFinite(stat.mtimeMs)) {+ row.newestAt = row.newestAt === null ? stat.mtimeMs : Math.max(row.newestAt, stat.mtimeMs);+ row.oldestAt = row.oldestAt === null ? stat.mtimeMs : Math.min(row.oldestAt, stat.mtimeMs);+ }+ };+ /** One more entry: false once a budget is spent. */+ const spend = async () => {+ entries += 1;+ if (entries >= maxEntries) { stoppedBy = "entries"; return false; }+ if (entries % YIELD_EVERY === 0) {+ await yieldNow();+ if (now() - started >= maxMs) { stoppedBy = "time"; return false; }+ }+ return true;+ };+ const stack: Frame[] = [];+ const close = async (frame: Frame | undefined) => { if (frame?.dir) { try { await frame.dir.close(); } catch {} frame.dir = null; } };+ try {+ walk: for (const root of roots) {+ let stat: DiagnoseStat;+ try { stat = await fs.lstat(root.path); } catch { unreadable += 1; continue; }+ if (!stat.isDirectory()) continue;+ stack.push({ path: root.path, segments: [], placement: { category: root.scope === "data" ? "settings" : "other", final: false }, scope: root.scope, dev: stat.dev, dir: null });+ while (stack.length) {+ const frame = stack.at(-1)!;+ if (!frame.dir) {+ try { frame.dir = await fs.opendir(frame.path); } catch { unreadable += 1; stack.pop(); continue; }+ }+ let next: { name: string } | null;+ try { next = await frame.dir.read(); } catch { unreadable += 1; next = null; }+ if (!next) { await close(stack.pop()); continue; }+ const path = join(frame.path, next.name);+ if (rootPaths.has(path)) continue;+ const segments = [...frame.segments, next.name];+ let child: DiagnoseStat;+ try { child = await fs.lstat(path); } catch { unreadable += 1; if (!(await spend())) break walk; continue; }+ const directory = child.isDirectory() && !child.isSymbolicLink();+ const placement = frame.segments.length === 0 ? placeStoragePath(frame.scope, segments, directory) : placeChild(frame.placement, frame.scope, segments, directory);+ const bucket = fine(frame.scope, segments, placement);+ add(bucket, child, !directory);+ if (!(await spend())) break walk;+ if (!directory || child.dev !== frame.dev) continue;+ if (segments.length >= maxDepth) { tooDeep += 1; continue; }+ stack.push({ path, segments, placement, scope: frame.scope, dev: frame.dev, dir: null });+ }+ }+ } finally {+ while (stack.length) await close(stack.pop());+ }+ return {+ incomplete: stoppedBy !== null, stoppedBy, entries, tookMs: Math.max(0, now() - started), tooDeep, unreadable,+ buckets: [...buckets.entries()].map(([name, row]) => ({ name, ...row })).filter((row) => row.bytes > 0 || row.files > 0).sort((a, b) => b.bytes - a.bytes),+ };+}diff --git a/server/perf/storage-history.ts b/server/perf/storage-history.tsnew file mode 100644index 0000000000..210218cb34--- /dev/null+++ b/server/perf/storage-history.ts@@ -0,0 +1,67 @@+// Each completed storage pass's bytes per category (disk-usage.ts), kept so the diagnose read (server/cloud-diagnose.ts) can+// say what grew in the last day and week. A pass ends about every 6 hours, so HISTORY_CAP passes span about two weeks. Saved+// to <data>/cache/storage-history.json (rebuildable: losing it only means "unknown" for a while). Category names and numbers only.+import { mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { writeFileAtomic } from "../atomic.ts";+import { STORAGE_CATEGORIES, type StorageCategory } from "./disk-categories.ts";+import type { StorageReport } from "./disk-usage.ts";++export const STORAGE_HISTORY_FILE = join("cache", "storage-history.json");+export const HISTORY_CAP = 60;+const DAY_MS = 86_400_000;++export interface HistoryPoint { at: number; bytes: Partial<Record<StorageCategory, number>> }+export interface Growth { since: number; rows: Array<{ name: StorageCategory; bytes: number }> }++const known = (name: string): name is StorageCategory => Object.hasOwn(STORAGE_CATEGORIES, name);+const pointsFrom = (value: unknown): HistoryPoint[] => {+ if (!Array.isArray(value)) return [];+ return value.flatMap((row) => {+ const at = (row as { at?: unknown })?.at, bytes = (row as { bytes?: unknown })?.bytes;+ if (typeof at !== "number" || !Number.isFinite(at) || !bytes || typeof bytes !== "object") return [];+ const kept: HistoryPoint["bytes"] = {};+ for (const [name, value] of Object.entries(bytes)) if (known(name) && typeof value === "number" && Number.isFinite(value) && value >= 0) kept[name] = value;+ return [{ at, bytes: kept }];+ }).sort((a, b) => a.at - b.at).slice(-HISTORY_CAP);+};++export function createStorageHistory(options: { dataDir: string } | { file: null }) {+ const file = "dataDir" in options ? join(options.dataDir, STORAGE_HISTORY_FILE) : null;+ let points: HistoryPoint[] | null = null;+ const load = (): HistoryPoint[] => {+ if (points) return points;+ try { points = file ? pointsFrom(JSON.parse(readFileSync(file, "utf8"))) : []; } catch { points = []; }+ return points;+ };+ return {+ /** Records a pass not seen yet (by its end time). A failed pass's figures are the one before's: not recorded again. */+ note(report: StorageReport | null | undefined) {+ if (!report || report.at === null || report.failed) return;+ const list = load();+ if (list.some((point) => point.at === report.at)) return;+ const bytes: HistoryPoint["bytes"] = {};+ for (const row of report.categories) bytes[row.name] = row.bytes;+ list.push({ at: report.at, bytes });+ list.sort((a, b) => a.at - b.at);+ while (list.length > HISTORY_CAP) list.shift();+ if (!file) return;+ try { mkdirSync(dirname(file), { recursive: true }); writeFileAtomic(file, JSON.stringify(list)); } catch { /* the next pass tries again */ }+ },+ points: (): readonly HistoryPoint[] => load(),+ /** Growth over the last `windowMs` (24 h, 7 days) from the newest pass back to the newest one at least that old; null until+ * the history reaches that far. Largest growth first; only categories that grew. */+ growth(windowMs: number): Growth | null {+ const list = load(), last = list.at(-1);+ if (!last) return null;+ const base = [...list].reverse().find((point) => point.at <= last.at - windowMs);+ if (!base) return null;+ const names = new Set([...Object.keys(last.bytes), ...Object.keys(base.bytes)].filter(known));+ const rows = [...names].map((name) => ({ name, bytes: (last.bytes[name] ?? 0) - (base.bytes[name] ?? 0) })).filter((row) => row.bytes > 0).sort((a, b) => b.bytes - a.bytes);+ return { since: base.at, rows };+ },+ };+}+export type StorageHistory = ReturnType<typeof createStorageHistory>;+export const DIAGNOSE_GROWTH_WINDOWS = { h24: DAY_MS, d7: 7 * DAY_MS } as const;diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.tsindex 071bcf4f0d..d444015213 100644--- a/server/routes/cloud-signed.ts+++ b/server/routes/cloud-signed.ts@@ -6,6 +6,7 @@ import { CLOUD_TIER } from "../host/cloud-plan-tier.ts";import type { IncomingMessage, ServerResponse } from "node:http";import type { BoxReport } from "../bot-box/box.ts";import { boxSummary } from "../cloud-health.ts";+import { CLOUD_DIAGNOSE_PATH, type CloudDiagnose } from "../cloud-diagnose.ts";import { CLOUD_HEALTH_PATH, CLOUD_PAIRING_PATH, createCloudPairing, createCloudRequestVerifier, readSignedBody } from "../cloud-home.ts";import { teamMemberEmail, type CloudTeam } from "../cloud-team.ts";import { CLOUD_TEAM_ADMIN_PATH, type TeamAdminSummary } from "../cloud-team-admin.ts";@@ -53,6 +54,8 @@ export function createCloudSignedRoutes(deps: {plan?: ((cancelled: boolean) => void) | null;/** Which plan this Cloud is on now; absent on a server that is not a Cloud home. */planTier?: ((tier: string) => void) | null;+ /** The diagnose read (cloud-diagnose.ts); absent on a server that is not a Cloud home. */+ diagnose?: Pick<CloudDiagnose, "read"> | null;now?: () => number;}) {const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, ...(deps.invited ? { invited: deps.invited } : {}), ...(deps.memberBrowserOff ? { memberBrowserOff: deps.memberBrowserOff } : {}), now: deps.now });@@ -64,6 +67,7 @@ export function createCloudSignedRoutes(deps: {const memberLeftRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });const planRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });const policyNudges = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });+ const diagnoseReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });/** True when the request was one of these and has been answered. */return async ({ req, res, url, path, method }: CloudSignedRequest): Promise<boolean> => {const power = path === CLOUD_POWER_PATH || path === CLOUD_POWER_SLEEP_PATH ? deps.power?.() ?? null : null;@@ -71,7 +75,8 @@ export function createCloudSignedRoutes(deps: {const memberLeft = path === CLOUD_TEAM_MEMBER_LEFT_PATH && deps.team ? deps.memberLeft ?? null : null;const plan = path === CLOUD_PLAN_PATH && (deps.plan || deps.planTier) ? true : null;const policyChanged = path === CLOUD_TEAM_POLICY_CHANGED_PATH && deps.team ? deps.policyChanged ?? null : null;- if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft && !plan && !policyChanged) return false;+ const diagnose = path === CLOUD_DIAGNOSE_PATH ? deps.diagnose ?? null : null;+ if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft && !plan && !policyChanged && !diagnose) return false;res.setHeader("cache-control", "no-store");const source = requestSource(req);const header = (name: string) => { const value = req.headers[name]; return typeof value === "string" ? value : undefined; };@@ -143,6 +148,13 @@ export function createCloudSignedRoutes(deps: {json(res, 200, { ok: true });return true;}+ if (diagnose) {+ if (method !== "GET") { json(res, 405, { error: "method_not_allowed" }); return true; }+ const verdict = diagnoseReads.verify({ ...signed, method, target: `${path}${url.search}`, body: "" });+ if (!verdict.ok) { console.warn(`cloud diagnose read refused from ${source}: ${verdict.error}`); json(res, verdict.status, { error: verdict.error }); return true; }+ json(res, 200, await diagnose.read());+ return true;+ }if (path === CLOUD_BOX_PATH) {if (method !== "GET") { json(res, 405, { error: "method_not_allowed" }); return true; }const verdict = boxReads.verify({ ...signed, method, target: `${path}${url.search}`, body: "" });