A local-first multi-agent app development platform, built on PenguinHarness
feat(web): the reviewed cleanup on the Settings page
lmlihengf77d79e60dfa
diff --git a/packages/ui-gallery/src/app/main.tsx b/packages/ui-gallery/src/app/main.tsxindex bb19c214..bcbd141c 100644--- a/packages/ui-gallery/src/app/main.tsx+++ b/packages/ui-gallery/src/app/main.tsx@@ -33,6 +33,7 @@ const SETTINGS_PAGES = ["uploads","company","plugins",+ "storage","users",] as const satisfies readonly SettingsSectionKey[];diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.tsindex 08cffa61..c157f922 100644--- a/packages/ui-gallery/src/app/mock/fixtures.ts+++ b/packages/ui-gallery/src/app/mock/fixtures.ts@@ -31,7 +31,10 @@ import type {ProjectSummary,ProxyProbeTargetsResponse,ServerSettings,+ StoragePlanView,StorageReport,+ StorageSettings,+ StorageTrashEntry,SessionContextResponse,SessionInfo,SkillMetadataItem,@@ -64,6 +67,29 @@ const iso = (ms: number) => new Date(ms).toISOString();/** `yyyy-mm-dd` in UTC, which is also what the usage series buckets on. */export const dayKey = (ms: number) => new Date(ms).toISOString().slice(0, 10);+/**+ * The local stamp core's storage ids are made of, in the two shapes they take. Local, not UTC, and+ * by hand rather than through `toISOString`: these names are read by a person looking at the data+ * root (or at a bill's header) rather than parsed, and they are what makes a bill sort by time as+ * a string.+ */+function localStamp(ms: number): { dashed: string; compact: string } {+ const at = new Date(ms);+ const pad = (n: number): string => String(n).padStart(2, "0");+ const date = `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}`;+ const time = `${pad(at.getHours())}-${pad(at.getMinutes())}-${pad(at.getSeconds())}`;+ return {+ dashed: `${date}-${time}`,+ compact: `${date.replace(/-/g, "")}-${time.replace(/-/g, "")}`,+ };+}++/** A bill's id as core writes it (`2026-10-08-11-30-45-4f2a1c`): the stamp plus a short suffix. */+export const planId = (ms: number, suffix: string): string => `${localStamp(ms).dashed}-${suffix}`;++/** A trash entry's id as core writes it (`20261008-113045`): the moment of the run, compact. */+export const trashId = (ms: number): string => localStamp(ms).compact;+/** A small deterministic generator, so the numbers are stable between reloads and tests. */export function seeded(seed: number): () => number {let state = seed >>> 0;@@ -92,8 +118,17 @@ export interface DemoFixtures {me: Omit<MeResponse, "user">;prefs: UiPrefs;serverSettings: ServerSettings;- /** The storage ledger the Settings page renders; read-only, so the mock only ever answers it. */+ /** The storage ledger the Settings page renders; read-only, and what the page measures again. */storageReport: StorageReport;+ /**+ * The cleanup mode's settings. **Off**, which is what an untouched install has: the gallery+ * therefore opens on the read-only ledger, and the switch is what brings the rest into view.+ */+ storageSettings: StorageSettings;+ /** The bills the demo world has written, newest first — a scan prepends one. */+ storagePlans: StoragePlanView[];+ /** What a move put aside, and what restore and purge act on. */+ storageTrash: StorageTrashEntry[];project: ProjectSummary;members: MemberInfo[];agents: AgentSummary[];@@ -1430,6 +1465,12 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {},];+ // The cleanup mode's own clock: a bill written half an hour ago (its day still ahead of it), one+ // applied with the day before, and a trash entry that a two-week retention has run out on.+ const storagePlanWrittenMs = ago(0, 30);+ const storageAppliedPlanMs = ago(1, 90);+ const storageStaleTrashMs = ago(20);+return {lang,now,@@ -1485,7 +1526,7 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {files: 23_731,entries: 83,candidateEntries: 2,- candidateBytes: 1_448_000,+ candidateBytes: 2_360_000,},{class: "session_drafts",@@ -1539,6 +1580,17 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {referenced: false,rules: ["unreferenced"],},+ // The class's second candidate, so the two that the class summary above counts are both+ // listed — and so a scan of this world writes the same bill the cleanup fixtures hold.+ {+ path: `${IDS.project}/agents/${IDS.agents.docs}/workspaces/tmp-71c0be14`,+ class: "tmp_workspaces",+ bytes: 918_000,+ files: 7,+ lastModifiedAt: null,+ referenced: false,+ rules: ["empty", "unreferenced"],+ },{path: `${IDS.project}/agents/${IDS.agents.docs}/scratchpad/session-2026-09-30-10-00-00-1a2b3c4d`,class: "session_drafts",@@ -1563,6 +1615,131 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {disk: { freeBytes: 8_100_000_000, totalBytes: 52_700_000_000 },unreadable: [`${IDS.project}/agents/${IDS.agents.notes}/scratchpad/sealed`],},+ storageSettings: {+ enabled: false,+ trashTtlDays: 14,+ pins: [],+ },+ // Two bills, newest first, sharing the ledger's clock above. The newest is still open — nothing+ // applied it and its day has not passed — so a page that is reloaded adopts it rather than+ // showing nothing; the older one was applied and is spent, which is what the "a bill is good+ // for one run" sentence and the "nothing to review" branch are for.+ storagePlans: [+ {+ id: planId(storagePlanWrittenMs, "4f2a1c"),+ root: "/home/demo/.adelie/data",+ createdAt: iso(storagePlanWrittenMs),+ expiresAt: iso(storagePlanWrittenMs + DAY),+ fingerprint: "9f1c0b7ad4e25360c2a8b1f0d7e64a39",+ totalBytes: 1_442_000 + 918_000 + 3_460_000,+ entries: [+ {+ path: `${IDS.project}/agents/${IDS.agents.docs}/workspaces/tmp-8e8a3ace`,+ class: "tmp_workspaces",+ bytes: 1_442_000,+ files: 12,+ lastModifiedAt: iso(ago(2, 30)),+ rules: ["unreferenced"],+ fingerprint: "3b7d19c4028fe64a1c05d9b8e7f30215",+ executable: true,+ },+ // A second temporary Workspace, so "select all of this class" has more than one row to+ // take — and a candidate the ledger's own list does not show (that list is capped).+ {+ path: `${IDS.project}/agents/${IDS.agents.docs}/workspaces/tmp-71c0be14`,+ class: "tmp_workspaces",+ bytes: 918_000,+ files: 7,+ lastModifiedAt: null,+ rules: ["empty", "unreferenced"],+ fingerprint: "c4a0e1735bd9f28640e1a7b3cd920f58",+ executable: true,+ },+ // The class this version only reports: drawn with its price tag beside it, and with a+ // box that cannot be ticked, which is the state the page has to be able to show.+ {+ path: `${IDS.project}/agents/${IDS.agents.docs}/scratchpad/session-2026-09-30-10-00-00-1a2b3c4d`,+ class: "session_drafts",+ bytes: 3_460_000,+ files: 5,+ lastModifiedAt: iso(ago(9, 40)),+ rules: ["orphan"],+ fingerprint: "7e2b68d1f0c395a8be47120df6a3c8e9",+ executable: false,+ },+ ],+ excluded: [],+ executableClasses: ["tmp_workspaces"],+ appliedAt: null,+ appliedPaths: [],+ usable: true,+ expired: false,+ },+ {+ id: planId(storageAppliedPlanMs, "9d13e7"),+ root: "/home/demo/.adelie/data",+ createdAt: iso(storageAppliedPlanMs),+ expiresAt: iso(storageAppliedPlanMs + DAY),+ fingerprint: "1d6fa309c8b7e4250af13d9c6b28e740",+ totalBytes: 2_140_000,+ entries: [+ {+ path: `${IDS.project}/agents/${IDS.agents.docs}/workspaces/tmp-0c7f19aa`,+ class: "tmp_workspaces",+ bytes: 2_140_000,+ files: 33,+ lastModifiedAt: iso(ago(1, 200)),+ rules: ["unreferenced"],+ fingerprint: "a80c35e1b7d42f9603c8ae51d709b2f4",+ executable: true,+ },+ ],+ excluded: [],+ executableClasses: ["tmp_workspaces"],+ appliedAt: iso(storageAppliedPlanMs),+ appliedPaths: [`${IDS.project}/agents/${IDS.agents.docs}/workspaces/tmp-0c7f19aa`],+ usable: false,+ expired: true,+ },+ ],+ // What a move put aside. The first entry is the tree the applied bill above moved, and is+ // inside the retention; the second is past it, so both purge routes — this entry, and+ // everything past the retention — have something to act on. Restoring either puts its trees+ // back and takes the entry away, as the server does once the entry holds nothing.+ storageTrash: [+ {+ id: trashId(storageAppliedPlanMs),+ createdAt: iso(storageAppliedPlanMs),+ planId: planId(storageAppliedPlanMs, "9d13e7"),+ bytes: 2_140_000,+ files: 33,+ items: [+ {+ path: `${IDS.project}/agents/${IDS.agents.docs}/workspaces/tmp-0c7f19aa`,+ class: "tmp_workspaces",+ bytes: 2_140_000,+ files: 33,+ },+ ],+ expired: false,+ },+ {+ id: trashId(storageStaleTrashMs),+ createdAt: iso(storageStaleTrashMs),+ planId: planId(storageStaleTrashMs, "b71e35"),+ bytes: 620_000,+ files: 9,+ items: [+ {+ path: `${IDS.project}/agents/${IDS.agents.notes}/scratchpad/session-2026-09-18-15-58-00-5f0c7a91`,+ class: "session_drafts",+ bytes: 620_000,+ files: 9,+ },+ ],+ expired: true,+ },+ ],project,members: [{ userId: user.userId, role: "owner", createdAt: project.createdAt },diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex 5be6669e..016a00de 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -85,7 +85,16 @@ import type {SchedulesResponse,SemanticIdSuggestResponse,ServerSettingsResponse,+ StorageApplyResponse,+ StoragePlanEntryView,+ StoragePlanResponse,+ StoragePlansResponse,+ StoragePlanView,+ StoragePurgeResponse,StorageReportResponse,+ StorageRestoreResponse,+ StorageSettingsResponse,+ StorageTrashResponse,SessionCategory,SessionCategoryCounts,SessionContextResponse,@@ -121,8 +130,8 @@ import type {// The catalog decides which groups publish a balance, as it does on the server.import { providerInfo } from "../../../../core/dist/state/model-catalog.js";import { READ_ONLY } from "./errors";-import { dayKey } from "./fixtures";-import type { UsageDay } from "./fixtures";+import { dayKey, planId, trashId } from "./fixtures";+import type { DemoFixtures, UsageDay } from "./fixtures";import { IDS } from "./ids";import { empty, fail, json, raw, Router } from "./router";import type { RequestContext } from "./router";@@ -147,6 +156,98 @@ function notFound(what: string): never {return fail(404, "not_found", `${what} not found.`);}+/**+ * The classes the reviewed cleanup may actually move — core's `EXECUTABLE_STORAGE_CLASSES`, which+ * this file cannot import (that module reaches for `node:crypto`, and the gallery runs in a+ * browser). A class outside this list is on a bill to be read and not acted on, which is a state+ * the page draws, so the demo keeps the same one-class answer the server gives.+ */+const EXECUTABLE_CLASSES = ["tmp_workspaces"] as const;++/** The mode gates every storage write, as it does on the server: off means nothing may be planned. */+function assertStorageMode(store: DemoStore): void {+ if (!store.f.storageSettings.enabled) {+ fail(409, "storage_mode_off", "Cleanup mode is off, so this is not available.");+ }+}++/** One of the demo's bills by id, or the same 404 the server answers with. */+function findPlan(store: DemoStore, planId: string): StoragePlanView {+ const plan = store.f.storagePlans.find((candidate) => candidate.id === planId);+ if (plan === undefined) {+ fail(404, "plan_not_found", "No plan with that id. Scan again for a new bill.");+ }+ return plan;+}++/** Adds or removes one pin, keeping the list sorted the way the server's does. */+function changePin(store: DemoStore, path: string, pinned: boolean): void {+ const current = store.f.storageSettings.pins;+ store.f.storageSettings.pins = pinned+ ? [...new Set([...current, path])].sort()+ : current.filter((existing) => existing !== path);+}++/** A short deterministic digest, for the fingerprints a bill carries. Not a security boundary. */+function mockFingerprint(...parts: (string | number)[]): string {+ let hash = 0x811c9dc5;+ for (const char of parts.join("\n")) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return hash.toString(16).padStart(8, "0").repeat(4);+}++/** Bills scanned in this session, so two ids of the same second do not collide. */+let scans = 0;++/**+ * A scan, as the server writes one: the ledger's candidates, minus the paths somebody pinned. The+ * demo has no disk to walk, so the candidates ARE the scan — which is why a pinned path really does+ * disappear from the next bill here, exactly as it would there.+ */+function scanStoragePlan(f: DemoFixtures, nowMs: number): StoragePlanView {+ scans += 1;+ const pins = new Set(f.storageSettings.pins);+ const excluded: string[] = [];+ const entries: StoragePlanEntryView[] = [];+ for (const candidate of f.storageReport.candidates) {+ if (candidate.rules.length === 0) continue;+ if (pins.has(candidate.path)) {+ excluded.push(candidate.path);+ continue;+ }+ entries.push({+ path: candidate.path,+ class: candidate.class,+ bytes: candidate.bytes,+ files: candidate.files,+ lastModifiedAt: candidate.lastModifiedAt,+ rules: candidate.rules,+ fingerprint: mockFingerprint(candidate.path, candidate.bytes),+ executable: (EXECUTABLE_CLASSES as readonly string[]).includes(candidate.class),+ });+ }+ const suffix = ((scans * 0x9e3779b1) >>> 0).toString(16).padStart(6, "0").slice(-6);+ return {+ id: planId(nowMs, suffix),+ root: f.storageReport.root,+ createdAt: new Date(nowMs).toISOString(),+ // The same day the server gives a bill: it describes one instant, and a day is how long that+ // description is worth acting on.+ expiresAt: new Date(nowMs + 86_400_000).toISOString(),+ fingerprint: mockFingerprint(nowMs, entries.map((entry) => entry.fingerprint).join("\n")),+ totalBytes: entries.reduce((sum, entry) => sum + entry.bytes, 0),+ entries,+ excluded,+ executableClasses: [...EXECUTABLE_CLASSES],+ appliedAt: null,+ appliedPaths: [],+ usable: true,+ expired: false,+ };+}+/** The cost of a Token bucket at the demo's default rates (USD per million). */function costOf(day: Pick<UsageDay, "cacheRead" | "cacheWrite" | "output" | "provider">): number {const rate =@@ -224,11 +325,165 @@ router.get("/api/admin/settings", ({ store }): ServerSettingsResponse => ({settings: store.f.serverSettings,}))- // Read-only by contract: the gallery answers the ledger and nothing else, exactly as the- // server does — there is no route here a cleanup could ride on.+ // The storage ledger's page, and the human-reviewed cleanup that reads it. The mode gates every+ // write here exactly as it does on the server, so the gallery can be walked through both pages:+ // off (the ledger alone, which is the default an untouched install has) and on (a bill to review,+ // a move into the trash, and the one deletion in the demo — `purge`)..get("/api/admin/storage", ({ store }): StorageReportResponse => ({report: store.f.storageReport,}))+ .get("/api/admin/storage/settings", ({ store }): StorageSettingsResponse => ({+ settings: store.f.storageSettings,+ }))+ .put("/api/admin/storage/settings", ({ store, body }): StorageSettingsResponse => {+ const update = record(body);+ store.f.storageSettings = {+ enabled:+ typeof update.enabled === "boolean" ? update.enabled : store.f.storageSettings.enabled,+ trashTtlDays:+ typeof update.trashTtlDays === "number"+ ? update.trashTtlDays+ : store.f.storageSettings.trashTtlDays,+ pins: Array.isArray(update.pins)+ ? update.pins.filter((path): path is string => typeof path === "string")+ : store.f.storageSettings.pins,+ };+ return { settings: store.f.storageSettings };+ })+ .get("/api/admin/storage/plans", ({ store }): StoragePlansResponse => ({+ plans: store.f.storagePlans,+ }))+ .post("/api/admin/storage/plans", ({ store }): unknown => {+ assertStorageMode(store);+ const nowMs = Date.now();+ const plan = scanStoragePlan(store.f, nowMs);+ store.f.storagePlans.unshift(plan);+ return json({ plan } satisfies StoragePlanResponse, 201);+ })+ .get("/api/admin/storage/plans/:planId", ({ store, params }): StoragePlanResponse => ({+ plan: findPlan(store, str(params.planId)),+ }))+ .post(+ "/api/admin/storage/plans/:planId/pin",+ ({ store, params, body }): StorageSettingsResponse => {+ assertStorageMode(store);+ // The bill is read first, as the server reads it: pinning an entry of a bill that is gone is+ // told so rather than answered with a settings blob.+ findPlan(store, str(params.planId));+ const { path, pinned } = record(body);+ changePin(store, str(path), typeof pinned === "boolean" ? pinned : true);+ return { settings: store.f.storageSettings };+ },+ )+ .post("/api/admin/storage/apply", ({ store, body }): StorageApplyResponse => {+ assertStorageMode(store);+ const request = record(body);+ const plan = findPlan(store, str(request.planId));+ if (plan.appliedAt !== null) {+ fail(409, "plan_used", "This plan has already been applied. Scan again for a new bill.");+ }+ if (plan.expired) {+ fail(409, "plan_expired", "This plan is older than 24 hours. Scan again.");+ }+ if (str(request.fingerprint) !== plan.fingerprint) {+ fail(409, "plan_stale", "The fingerprint does not match this plan. Read the bill again.");+ }+ const paths = Array.isArray(request.paths)+ ? request.paths.filter((path): path is string => typeof path === "string")+ : [];+ if (paths.length === 0) {+ fail(400, "nothing_selected", "Nothing was selected. Approve at least one entry.");+ }+ // Checked as the server checks it — the whole batch, before anything moves — so a path the+ // demo would refuse is refused here too rather than silently taken.+ const entries = paths.map((path) => {+ const entry = plan.entries.find((row) => row.path === path);+ if (entry === undefined) fail(400, "unknown_path", `Not an entry of this plan: ${path}.`);+ if (!entry.executable) {+ fail(+ 409,+ "class_not_executable",+ `This version does not clean ${entry.class} entries: ${path}.`,+ );+ }+ if (store.f.storageSettings.pins.includes(path)) {+ fail(409, "pinned_path", `Pinned — it will never be cleaned: ${path}.`);+ }+ return entry;+ });+ const moved = entries.map((entry) => ({+ path: entry.path,+ bytes: entry.bytes,+ files: entry.files,+ }));+ const nowMs = Date.now();+ const id = moved.length === 0 ? null : trashId(nowMs);+ if (id !== null) {+ store.f.storageTrash.unshift({+ id,+ createdAt: new Date(nowMs).toISOString(),+ planId: plan.id,+ bytes: moved.reduce((sum, item) => sum + item.bytes, 0),+ files: moved.reduce((sum, item) => sum + item.files, 0),+ items: entries.map((entry) => ({+ path: entry.path,+ class: entry.class,+ bytes: entry.bytes,+ files: entry.files,+ })),+ expired: false,+ });+ }+ // Spent whatever moved: the demo's ledger is one fixed measurement rather than a walk of a+ // disk that has changed, so the report keeps showing the trees the trash now holds — the+ // server would re-measure, and the trash block is where this world shows the move.+ plan.appliedAt = new Date(nowMs).toISOString();+ plan.appliedPaths = moved.map((item) => item.path);+ plan.usable = false;+ return {+ planId: plan.id,+ trashId: id,+ moved,+ failed: [],+ freedBytes: moved.reduce((sum, item) => sum + item.bytes, 0),+ };+ })+ .get("/api/admin/storage/trash", ({ store }): StorageTrashResponse => ({+ entries: store.f.storageTrash,+ ttlDays: store.f.storageSettings.trashTtlDays,+ }))+ .post("/api/admin/storage/trash/restore", ({ store, body }): StorageRestoreResponse => {+ assertStorageMode(store);+ const id = str(record(body).id);+ const entry = store.f.storageTrash.find((candidate) => candidate.id === id);+ if (entry === undefined) fail(404, "trash_not_found", "No trash entry with that id.");+ // Everything is restored and nothing is skipped: the demo has no disk behind it, so the two+ // reasons the server skips an item (it is not there any more, something else took its path)+ // cannot arise here. The entry then holds nothing, which is when the server removes it.+ store.f.storageTrash = store.f.storageTrash.filter((candidate) => candidate.id !== id);+ return { id, restored: entry.items.map((item) => item.path), skipped: [], remaining: false };+ })+ .post("/api/admin/storage/trash/purge", ({ store, body }): StoragePurgeResponse => {+ assertStorageMode(store);+ const requested = record(body).id;+ const id = typeof requested === "string" ? requested : null;+ if (id !== null && !store.f.storageTrash.some((entry) => entry.id === id)) {+ fail(404, "trash_not_found", "No trash entry with that id.");+ }+ const targets =+ id === null+ ? store.f.storageTrash.filter((entry) => entry.expired)+ : store.f.storageTrash.filter((entry) => entry.id === id);+ const purged = targets.map((entry) => ({+ id: entry.id,+ bytes: entry.bytes,+ files: entry.files,+ }));+ store.f.storageTrash = store.f.storageTrash.filter(+ (entry) => !purged.some((gone) => gone.id === entry.id),+ );+ return { purged };+ }).put("/api/admin/settings", ({ store, body }): ServerSettingsResponse => {store.f.serverSettings = { ...store.f.serverSettings, ...record(body) };return { settings: store.f.serverSettings };diff --git a/packages/ui-gallery/test/storage-demo.test.ts b/packages/ui-gallery/test/storage-demo.test.tsnew file mode 100644index 00000000..1ebd8f80--- /dev/null+++ b/packages/ui-gallery/test/storage-demo.test.ts@@ -0,0 +1,109 @@+/**+ * The demo's storage cleanup, walked end to end through the app's own endpoint wrappers.+ *+ * The gallery's mock answers the same routes the server does, and on the storage page those+ * answers ARE the feature's state machine: the mode gates every write, a scan writes a bill out of+ * the ledger's candidates, a pin takes a path out of the next bill, and an approval is what fills+ * the trash. None of that can be checked by the wrapper sweep in `mock-api.test.ts` — that one+ * only proves a route exists — so the sequence is driven here, in the order a person would click+ * it, and each refusal is the code the page names.+ *+ * What the mock deliberately does not reproduce is the disk: there is no walk, no re-measure and no+ * rename, so the ledger keeps showing what the trash now holds and a restore skips nothing. The+ * server's own rules for those live in `packages/server/test/storage-cleanup.test.ts`; what is+ * protected here is the demo's, which is what the gallery is looked at through.+ */+import { describe, expect, it } from "vitest";+import * as api from "../../web/src/api/endpoints";+import { resetStore } from "../src/app/mock/store";++describe("the demo's reviewed cleanup", () => {+ it("gates on the mode, then scans, pins, applies, restores and purges", async () => {+ const store = resetStore({ lang: "en", signedIn: true });++ // Off by default: every write is refused with the code the page names.+ await expect(api.adminScanStorage()).rejects.toMatchObject({ code: "storage_mode_off" });+ await expect(api.adminPurgeStorageTrash()).rejects.toMatchObject({+ code: "storage_mode_off",+ });++ const on = await api.adminUpdateStorageSettings({ enabled: true });+ expect(on.settings.enabled).toBe(true);++ // A scan writes a bill out of the ledger's candidates.+ const scanned = await api.adminScanStorage();+ const movable = scanned.plan.entries.filter((entry) => entry.executable);+ expect(movable.length).toBe(2);+ expect(scanned.plan.entries.some((entry) => !entry.executable)).toBe(true);+ expect((await api.adminListStoragePlans()).plans[0]?.id).toBe(scanned.plan.id);+ expect((await api.adminGetStoragePlan(scanned.plan.id)).plan.id).toBe(scanned.plan.id);++ // Pinning takes a path out of the next bill and lands in the settings. On the bill that still+ // lists it, an apply is refused for the pin; on the next scan it is not on the bill at all.+ const pins = await api.adminPinStoragePath(scanned.plan.id, {+ path: movable[0]!.path,+ pinned: true,+ });+ expect(pins.settings.pins).toContain(movable[0]!.path);+ await expect(+ api.adminApplyStoragePlan({+ planId: scanned.plan.id,+ fingerprint: scanned.plan.fingerprint,+ paths: [movable[0]!.path],+ }),+ ).rejects.toMatchObject({ code: "pinned_path" });+ const afterPin = await api.adminScanStorage();+ expect(afterPin.plan.entries.some((entry) => entry.path === movable[0]!.path)).toBe(false);+ expect(afterPin.plan.excluded).toContain(movable[0]!.path);+ await expect(+ api.adminApplyStoragePlan({+ planId: afterPin.plan.id,+ fingerprint: afterPin.plan.fingerprint,+ paths: [movable[0]!.path],+ }),+ ).rejects.toMatchObject({ code: "unknown_path" });++ // A wrong fingerprint is refused; the bill's own one moves the selection.+ const targets = afterPin.plan.entries.filter((entry) => entry.executable);+ await expect(+ api.adminApplyStoragePlan({+ planId: afterPin.plan.id,+ fingerprint: "nope",+ paths: targets.map((entry) => entry.path),+ }),+ ).rejects.toMatchObject({ code: "plan_stale" });+ const applied = await api.adminApplyStoragePlan({+ planId: afterPin.plan.id,+ fingerprint: afterPin.plan.fingerprint,+ paths: targets.map((entry) => entry.path),+ });+ expect(applied.moved.length).toBe(targets.length);+ expect(applied.trashId).not.toBeNull();+ expect(applied.freedBytes).toBeGreaterThan(0);+ expect((await api.adminGetStoragePlan(afterPin.plan.id)).plan.usable).toBe(false);+ await expect(+ api.adminApplyStoragePlan({+ planId: afterPin.plan.id,+ fingerprint: afterPin.plan.fingerprint,+ paths: targets.map((entry) => entry.path),+ }),+ ).rejects.toMatchObject({ code: "plan_used" });++ // The move landed in the trash, where restore puts it back and purge deletes for good.+ const trash = await api.adminGetStorageTrash();+ expect(trash.entries[0]?.id).toBe(applied.trashId);+ expect(trash.ttlDays).toBe(14);+ const restored = await api.adminRestoreStorageTrash(applied.trashId!);+ expect(restored.restored.length).toBe(targets.length);+ expect(restored.remaining).toBe(false);+ expect((await api.adminGetStorageTrash()).entries.some((e) => e.id === applied.trashId)).toBe(+ false,+ );+ const expired = (await api.adminGetStorageTrash()).entries.find((entry) => entry.expired)!;+ const purged = await api.adminPurgeStorageTrash(expired.id);+ expect(purged.purged.map((entry) => entry.id)).toEqual([expired.id]);+ // Nothing but the entries past the retention goes without an id.+ expect((await api.adminPurgeStorageTrash()).purged).toEqual([]);+ expect(store.f.storageSettings.pins).toContain(movable[0]!.path);+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 97bcd519..3ce3641c 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -186,7 +186,17 @@ import type {SessionTracesResponse,SkillArchiveInstallRequest,SteerRequest,+ StorageApplyRequest,+ StorageApplyResponse,+ StoragePinRequest,+ StoragePlanResponse,+ StoragePlansResponse,+ StoragePurgeResponse,StorageReportResponse,+ StorageRestoreResponse,+ StorageSettingsResponse,+ StorageSettingsUpdateRequest,+ StorageTrashResponse,SubagentMessageResponse,TaskCreateRequest,TaskCreateResponse,@@ -352,6 +362,75 @@ export const adminProbeProxy = (provider: ProxyProbeProvider) =>*/export const adminGetStorageReport = () => apiFetch<StorageReportResponse>("/api/admin/storage");+/**+ * The cleanup mode, machine-wide like the root it describes: `enabled` is off until a person turns+ * it on, and every route that writes — scanning out a bill, pinning, moving, purging — is refused+ * with 409 `storage_mode_off` while it is off. `pins` are the paths a person decided to keep.+ */+export const adminGetStorageSettings = () =>+ apiFetch<StorageSettingsResponse>("/api/admin/storage/settings");++/** An omitted field keeps its stored value; the response is the mode as it now stands. */+export const adminUpdateStorageSettings = (body: StorageSettingsUpdateRequest) =>+ apiFetch<StorageSettingsResponse>("/api/admin/storage/settings", { method: "PUT", body });++/**+ * Writes a bill out of the ledger: a walk of the whole root, and a POST because it creates a file+ * (the plan), not because it moves anything. The bill is a snapshot of one instant, reviewed+ * before anything acts on it — nothing scans on a timer, so this is only ever somebody's click.+ */+export const adminScanStorage = () =>+ apiFetch<StoragePlanResponse>("/api/admin/storage/plans", { method: "POST", body: {} });++/** The recent bills, newest first — so a page reload can find the one the server still holds. */+export const adminListStoragePlans = () =>+ apiFetch<StoragePlansResponse>("/api/admin/storage/plans");++/** One bill, as it stands now (`usable` / `expired` are computed at read time, not stored). */+export const adminGetStoragePlan = (planId: string) =>+ apiFetch<StoragePlanResponse>(`/api/admin/storage/plans/${encodeURIComponent(planId)}`);++/**+ * Keeps one path out of every later bill, or lets it back in. The plan in the path is read first,+ * so pinning an entry of a bill that is gone is told so rather than answered with a settings blob.+ */+export const adminPinStoragePath = (planId: string, body: StoragePinRequest) =>+ apiFetch<StorageSettingsResponse>(`/api/admin/storage/plans/${encodeURIComponent(planId)}/pin`, {+ method: "POST",+ body,+ });++/**+ * Moves the approved entries into the trash — the only route that changes the data root, and it+ * needs a bill's id, **that bill's own fingerprint** and an explicit path list. A fingerprint the+ * server does not hold a bill for, a bill already spent, or one past its day is refused, so what+ * moves is exactly what somebody read and ticked.+ */+export const adminApplyStoragePlan = (body: StorageApplyRequest) =>+ apiFetch<StorageApplyResponse>("/api/admin/storage/apply", { method: "POST", body });++/** What moves have put aside: measured now, so a listing never lies about what is on disk. */+export const adminGetStorageTrash = () =>+ apiFetch<StorageTrashResponse>("/api/admin/storage/trash");++/** Puts one trash entry's trees back where they came from, refusing whatever is in the way. */+export const adminRestoreStorageTrash = (id: string) =>+ apiFetch<StorageRestoreResponse>("/api/admin/storage/trash/restore", {+ method: "POST",+ body: { id },+ });++/**+ * The one deletion in the API: with an id it removes that trash entry, without one only the+ * entries past the retention. It never reaches anything that is not already in the trash, and+ * nothing calls it on a timer.+ */+export const adminPurgeStorageTrash = (id?: string) =>+ apiFetch<StoragePurgeResponse>("/api/admin/storage/trash/purge", {+ method: "POST",+ body: id === undefined ? {} : { id },+ });+// Project & members --------------------------------------------------------------export const listProjects = () => apiFetch<ProjectsResponse>("/api/projects");diff --git a/packages/web/src/features/settings/storage-labels.ts b/packages/web/src/features/settings/storage-labels.tsindex b037aa1d..63d43584 100644--- a/packages/web/src/features/settings/storage-labels.ts+++ b/packages/web/src/features/settings/storage-labels.ts@@ -1,12 +1,14 @@/**- * The storage report's vocabulary in the reader's words (storage-section.tsx draws it).+ * The storage report's, and its bills', vocabulary in the reader's words (storage-section.tsx+ * draws it).** The ledger's classes and rules arrive as ids — `session_drafts`, `orphan` — because the API,- * the rules engine in `@lmliheng/penguin-core` (its `state/storage.ts` defines them) and a future- * cleanup plan all have to agree on them. A person reading the report has to recognise what- * `shared_env` or `budget` means, so every id is translated here, in one place, and both- * dictionaries carry the words (`S.settings`), so the labels follow the UI language like the- * rest of the app.+ * the rules engine in `@lmliheng/penguin-core` (its `state/storage.ts` defines them) and the+ * cleanup plan a scan writes all have to agree on them. A person reading the report has to+ * recognise what `shared_env` or `budget` means, so every id is translated here, in one place,+ * and both dictionaries carry the words (`S.settings`), so the labels follow the UI language like+ * the rest of the app. A bill's state and a trash entry's are the same kind of value and are+ * translated here too, though those two are derived (see {@link storagePlanState}).** Every map is keyed by the DTO's own union and read through it rather than being a partial list* with a fallback: a fallback would quietly render a class the engine added as "Other", which is@@ -21,6 +23,8 @@ import type {StorageCandidateRule,StorageClass,StorageEnvGroup,+ StoragePlanView,+ StorageTrashEntry,} from "@lmliheng/penguin-server/api";import { S } from "../../lib/strings";@@ -59,3 +63,46 @@ export function storageEnvGroupKindLabel(kind: StorageEnvGroup["kind"]): string? S.settings.storageEnvGroupKindName: S.settings.storageEnvGroupKindStructure;}++/** How a bill stands with the reviewer: open for approval, spent once, or past its day. */+export type StoragePlanState = "usable" | "applied" | "expired";++/**+ * The state of `plan`. `applied` is asked first because it is the stronger fact: a bill applied+ * yesterday is spent whether or not its day has also passed, and reading it as "expired" would+ * point a reviewer at the clock instead of at the scan they need.+ *+ * This is the sentence, not the permission — whether the server would still accept an approval is+ * its own `usable` flag, which the page obeys rather than recomputes.+ */+export function storagePlanState(plan: StoragePlanView): StoragePlanState {+ if (plan.appliedAt !== null) return "applied";+ return plan.expired ? "expired" : "usable";+}++/** What that state means, in one sentence (`usable` → it can still be approved). */+export function storagePlanStateText(state: StoragePlanState): string {+ return S.settings.storagePlanStateText[state];+}++/** How a trash entry stands: inside the retention, or past it. Nothing removes it on its own. */+export type StorageTrashState = "fresh" | "expired";++/** The entry's own state, from the flag the server computed against the current retention. */+export function storageTrashState(entry: StorageTrashEntry): StorageTrashState {+ return entry.expired ? "expired" : "fresh";+}++/** What that state means for the entry, under the listing's state column. */+export function storageTrashStateLabel(state: StorageTrashState): string {+ return S.settings.storageTrashStateNames[state];+}++/**+ * Whether this version may move a row of a bill at all. The other half of the answer — what the+ * row costs to clear — is the class's own line ({@link storageClassCost}), so a report-only row is+ * read with the same price tag beside it, plus the fact that nothing here will pay it.+ */+export function storageExecutableLabel(executable: boolean): string {+ return S.settings.storageExecutable[executable ? "yes" : "no"];+}diff --git a/packages/web/src/features/settings/storage-review.ts b/packages/web/src/features/settings/storage-review.tsnew file mode 100644index 00000000..7e35f009--- /dev/null+++ b/packages/web/src/features/settings/storage-review.ts@@ -0,0 +1,184 @@+/**+ * The bill's bookkeeping (storage-section.tsx draws it, storage-labels.ts names it).+ *+ * Everything here is a pure function of a bill, the pins and the ticked paths, so what a reviewer+ * is about to approve can be read off one value — and pinned by a test without a DOM (this+ * package's vitest runs in Node). Three rules are the whole flow:+ *+ * - **Nothing is selected until somebody selects it.** The default is "keep", so an empty+ * selection is the state the page opens in, and a selection is what a click on a class's own+ * button (or on one row) turns into — never something a bill arrives with.+ * - **A selection only ever names what may be moved.** Two things take a row out of reach, and+ * both are the server's rules rather than this module's guesses: the API's `executable` flag (a+ * bill lists entries this version can only report — see `StoragePlanEntryView.executable`) and+ * the pins (an apply containing a pinned path is refused as a whole, with 409 `pinned_path`).+ * - **A pin is read from the settings, not from the bill.** The bill was written before the pin+ * existed, so a page that decided reachability from `plan.excluded` alone would offer a row the+ * very next click could not move.+ *+ * The bill is a snapshot of one instant, so nothing here is derived from the disk or from an+ * earlier bill: the paths a selection holds are paths *this* bill recorded, and the fingerprint+ * sent back is the one this bill carries — which is what makes an approval say what was read.+ */+import type {+ StorageApplyRequest,+ StorageClass,+ StoragePlanEntryView,+ StoragePlanView,+} from "@lmliheng/penguin-server/api";++/** The paths ticked on a bill; a fresh constant, so the page's default never mutates. */+export const NO_SELECTION: ReadonlySet<string> = new Set<string>();++/** One class's slice of a bill, with what its entries come to. */+export interface StorageBillGroup {+ class: StorageClass;+ /** Summed here rather than read off the report: a bill's own rows are what a reviewer sees. */+ bytes: number;+ files: number;+ entries: StoragePlanEntryView[];+}++/**+ * The bill's rows grouped by class, largest class first and largest entry first inside it. Equal+ * sizes fall back to the id, so two bills that account for the same bytes never show their groups+ * in an order the reader cannot explain.+ */+export function storageBillGroups(plan: StoragePlanView): StorageBillGroup[] {+ const byClass = new Map<StorageClass, StoragePlanEntryView[]>();+ for (const entry of plan.entries) {+ const rows = byClass.get(entry.class);+ if (rows === undefined) byClass.set(entry.class, [entry]);+ else rows.push(entry);+ }+ const groups: StorageBillGroup[] = [];+ for (const [classKey, rows] of byClass) {+ const entries = [...rows].sort((a, b) => b.bytes - a.bytes || compareIds(a.path, b.path));+ groups.push({+ class: classKey,+ bytes: entries.reduce((sum, entry) => sum + entry.bytes, 0),+ files: entries.reduce((sum, entry) => sum + entry.files, 0),+ entries,+ });+ }+ return groups.sort((a, b) => b.bytes - a.bytes || compareIds(a.class, b.class));+}++/** The bill a fresh page should review: the newest one the server still lets be approved. */+export function storageOpenPlan(plans: readonly StoragePlanView[]): StoragePlanView | null {+ // `plans` arrives newest first. Only an approvable bill is adopted: a spent one cannot run+ // whatever is ticked on it, and dead boxes would read as an action the page does not have.+ return plans.find((plan) => plan.usable) ?? null;+}++/** The rows of the bill a reviewer may move: this version's classes, minus the pinned paths. */+export function storageMovableEntries(+ plan: StoragePlanView,+ pins: ReadonlySet<string>,+): StoragePlanEntryView[] {+ return plan.entries.filter((entry) => entry.executable && !pins.has(entry.path));+}++/** The rows of one class a reviewer may move; a class with none is on the bill to be read only. */+export function storageSelectablePaths(+ plan: StoragePlanView,+ classKey: StorageClass,+ pins: ReadonlySet<string>,+): string[] {+ return storageMovableEntries(plan, pins)+ .filter((entry) => entry.class === classKey)+ .map((entry) => entry.path);+}++/** Whether every movable row of a class is already ticked — what flips the class's own button. */+export function storageClassFullySelected(+ plan: StoragePlanView,+ selection: ReadonlySet<string>,+ classKey: StorageClass,+ pins: ReadonlySet<string>,+): boolean {+ const paths = storageSelectablePaths(plan, classKey, pins);+ return paths.length > 0 && paths.every((path) => selection.has(path));+}++/** "Select all of this class": adds its movable rows, and leaves every other class's ticks alone. */+export function storageSelectClass(+ plan: StoragePlanView,+ selection: ReadonlySet<string>,+ classKey: StorageClass,+ pins: ReadonlySet<string>,+): ReadonlySet<string> {+ return new Set([...selection, ...storageSelectablePaths(plan, classKey, pins)]);+}++/** The inverse of {@link storageSelectClass}: drops this class's rows, keeping the others' ticks. */+export function storageUnselectClass(+ plan: StoragePlanView,+ selection: ReadonlySet<string>,+ classKey: StorageClass,+ pins: ReadonlySet<string>,+): ReadonlySet<string> {+ const dropped = new Set(storageSelectablePaths(plan, classKey, pins));+ return new Set([...selection].filter((path) => !dropped.has(path)));+}++/**+ * One row's box. Ticking a path that is not a movable entry of this bill does nothing rather than+ * adding it: the only way a tick can be wrong is by not being movable, and a selection must never+ * hold a path an apply would be refused for.+ */+export function storageTogglePath(+ plan: StoragePlanView,+ selection: ReadonlySet<string>,+ path: string,+ pins: ReadonlySet<string>,+): ReadonlySet<string> {+ const next = new Set(selection);+ if (next.delete(path)) return next;+ if (storageMovableEntries(plan, pins).some((entry) => entry.path === path)) next.add(path);+ return next;+}++/** What the current selection comes to, for the line beside the apply button. */+export function storageSelectionTotals(+ plan: StoragePlanView,+ selection: ReadonlySet<string>,+ pins: ReadonlySet<string>,+): { entries: number; bytes: number } {+ const rows = storageMovableEntries(plan, pins).filter((entry) => selection.has(entry.path));+ return {+ entries: rows.length,+ bytes: rows.reduce((sum, entry) => sum + entry.bytes, 0),+ };+}++/**+ * The approval the ticked rows stand for: the bill's **own** fingerprint, as displayed, and+ * exactly those paths — in the bill's order rather than in the order they were clicked, so the+ * request is a function of the bill and the selection alone. Null when nothing is selected, which+ * is also the state the button that would send it is disabled in.+ *+ * The request is capped at what a reviewer can see themselves: a pinned path and a report-only one+ * are left out rather than sent and refused, because the server refuses the whole batch for one+ * bad path — losing the rest of a reviewed selection to a row the page should never have offered.+ *+ * Whether the bill may still be applied is not decided here: that is the server's `usable` flag,+ * and a request built from a spent bill is refused by the server rather than pre-empted here.+ */+export function storageApplyBody(+ plan: StoragePlanView,+ selection: ReadonlySet<string>,+ pins: ReadonlySet<string>,+): StorageApplyRequest | null {+ const paths = storageMovableEntries(plan, pins)+ .filter((entry) => selection.has(entry.path))+ .map((entry) => entry.path);+ if (paths.length === 0) return null;+ return { planId: plan.id, fingerprint: plan.fingerprint, paths };+}++/** Code-point order, so a sort of equal-sized rows does not depend on the viewer's locale. */+function compareIds(a: string, b: string): number {+ if (a === b) return 0;+ return a < b ? -1 : 1;+}diff --git a/packages/web/src/features/settings/storage-section.tsx b/packages/web/src/features/settings/storage-section.tsxindex 2b18175a..ca915a89 100644--- a/packages/web/src/features/settings/storage-section.tsx+++ b/packages/web/src/features/settings/storage-section.tsx@@ -1,10 +1,15 @@/**- * The storage ledger (admin only, server-global): what the data root holds, and what a person- * could clean up. **Read-only, and the page has to look it.** The app's default is that it keeps- * every byte, and there is no automatic cleanup anywhere: a future destructive step is a separate,- * human-reviewed one, so this page draws no delete button, no checkbox and no "clean now" — the- * sentences at the top say what the page is and that nothing here removes data, and the only- * control is measuring again.+ * The storage ledger (admin only, server-global): what the data root holds, what a person could+ * clean up, and the reviewed cleanup that reads it.+ *+ * Two halves, and the mode switch between them. The **ledger** measures — one walk of the whole+ * data root, class by class, with the entries that matched a cleanup rule — and the app keeps its+ * promise that it deletes nothing by itself: no scan and no move happens on a timer, and a page+ * left open measures once and then waits. The **cleanup** is the design's second step, and it can+ * only happen because somebody read a bill and ticked rows on it: a scan writes that bill, an+ * apply moves exactly the ticked entries into the trash, and the trash is where the one deletion+ * in the whole app lives. With the mode off — which is the default, and what an untouched install+ * has — none of that exists on screen, and the page is the read-only ledger it was.** The report is one measurement of one instant (`scannedAt`), so the page replaces it wholesale* rather than merging: a figure from an older walk beside a newer one cannot be told apart. It is@@ -12,21 +17,38 @@* rail already keeps them from opening it (settings-sections.ts), and this page adds no guard of* its own beyond the failure it reports.*- * A measurement walks the whole data root, so it is not free and not instant: the button says it- * is running and stays disabled while it does, and the first mount fires it exactly once.+ * A measurement walks the whole data root, so it is not free and not instant: the buttons say they+ * are running and stay disabled while they do, and the first mount fires exactly one measurement+ * and one read of the mode. A scan, an apply and every trash write are the reviewer's own clicks.** What the page will NOT do is round the report off. A class the scan could not read, a path it* could not enter, a candidate whose mtime is unknown — each is shown as such (see `unreadable`* and `StorageCandidate.lastModifiedAt`), because a report that hides its own gaps is the one- * thing a cleanup decision must not be based on.+ * thing a cleanup decision must not be based on. The same rule governs the bill: a row this+ * version cannot move is drawn rather than dropped, a refusal is reported with the server's own+ * reason instead of a summary, and the fingerprint an approval sends is the one the displayed bill+ * carries (storage-review.ts) — never one re-read from somewhere else.*/-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import type { ReactNode } from "react";-import type { StorageReport } from "@lmliheng/penguin-server/api";+import type {+ StorageApplyResponse,+ StorageClass,+ StoragePlanEntryView,+ StoragePlanView,+ StoragePurgeResponse,+ StorageReport,+ StorageRestoreResponse,+ StorageSettings,+ StorageTrashEntry,+} from "@lmliheng/penguin-server/api";import {Button,+ Checkbox,EmptyState,+ NoticeStrip,SettingsSection,+ Switch,Table,TableBody,TableCell,@@ -34,6 +56,7 @@ import {TableHeaderCell,TableRow,toastError,+ toastSuccess,} from "@lmliheng/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";@@ -43,8 +66,26 @@ import {storageClassCost,storageClassLabel,storageEnvGroupKindLabel,+ storageExecutableLabel,+ storagePlanState,+ storagePlanStateText,storageRulesLabel,+ storageTrashState,+ storageTrashStateLabel,} from "./storage-labels";+import {+ NO_SELECTION,+ storageApplyBody,+ storageBillGroups,+ storageClassFullySelected,+ storageMovableEntries,+ storageOpenPlan,+ storageSelectClass,+ storageSelectionTotals,+ storageTogglePath,+ storageUnselectClass,+} from "./storage-review";+import type { StorageBillGroup } from "./storage-review";/** A section of the page: its heading, an optional line saying what the heading's rows mean. */function Block({ title, hint, children }: { title: string; hint?: string; children: ReactNode }) {@@ -147,7 +188,7 @@ function CandidateTable({ report }: { report: StorageReport }) {<TableBody>{report.candidates.map((candidate) => (<TableRow key={candidate.path}>- {/* The recorded path is what a future plan and a pin name, so it is shown as+ {/* The recorded path is what a plan and a pin name, so it is shown asrecorded, monospaced and allowed to break. */}<TableCell className="max-w-[280px] font-mono text-xs break-all">{candidate.path}@@ -234,6 +275,411 @@ function Unreadable({ report }: { report: StorageReport }) {);}+/**+ * The mode switch, and the one sentence that says what its position means. Everything else on the+ * page that writes hangs off it, so it is drawn first and its sentence names what the other+ * position cannot do — that difference is the whole page, and a reader who scrolls past it should+ * still be told which page they are on.+ */+function ModeRow({+ settings,+ busy,+ failed,+ onChange,+}: {+ settings: StorageSettings | null;+ busy: boolean;+ /** The settings could not be read: the switch then shows the position the page acts on (off). */+ failed: boolean;+ onChange: (enabled: boolean) => void;+}) {+ const enabled = settings?.enabled === true;+ return (+ <Block title={S.settings.storageModeTitle}>+ <div className="flex items-center justify-between gap-3">+ <span className="text-xs text-gray-500 dark:text-gray-400">+ {S.settings.storageModeLabel}+ </span>+ <Switch+ aria-label={S.settings.storageModeLabel}+ checked={enabled}+ // Deliberately not disabled when the read failed: a switch that cannot be pressed leaves+ // no way back from a failed read, while a PUT that succeeds both turns the mode on and+ // replaces the guess with the answer the server holds.+ disabled={busy}+ onChange={onChange}+ />+ </div>+ <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">+ {failed+ ? S.settings.storageModeFailed+ : enabled+ ? S.settings.storageModeOn+ : S.settings.storageModeOff}+ </p>+ </Block>+ );+}++/** The bill's own header: which scan it is, and until when it can still be approved. */+function BillHeader({ plan }: { plan: StoragePlanView }) {+ return (+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs">+ <dt className="text-gray-500 dark:text-gray-400">{S.settings.storageBillId}</dt>+ <dd className="min-w-0 font-mono break-all">{plan.id}</dd>+ <dt className="text-gray-500 dark:text-gray-400">{S.settings.storageBillCreatedAt}</dt>+ <dd className="tabular-nums">{formatDateTime(plan.createdAt)}</dd>+ <dt className="text-gray-500 dark:text-gray-400">{S.settings.storageBillExpiresAt}</dt>+ <dd className="tabular-nums">{formatDateTime(plan.expiresAt)}</dd>+ <dt className="text-gray-500 dark:text-gray-400">{S.settings.storageBillTotal}</dt>+ <dd className="tabular-nums">+ {formatBytes(plan.totalBytes)} · {S.settings.storageBillEntries(plan.entries.length)}+ </dd>+ </dl>+ );+}++/**+ * One class of a bill: its name with what clearing one of its entries costs, the way to take or+ * drop its whole class at once, and its rows.+ *+ * The class's own button touches only the rows this page may move, so a report-only class offers+ * words instead of a button — a control that cannot do anything is worse than a sentence saying+ * so.+ */+function BillGroup({+ plan,+ group,+ pins,+ movable,+ selection,+ approvable,+ enabled,+ pinning,+ onToggleRow,+ onSelectClass,+ onUnselectClass,+ onPin,+}: {+ plan: StoragePlanView;+ group: StorageBillGroup;+ pins: ReadonlySet<string>;+ /** The paths this page may move right now, mode and bill state included. */+ movable: ReadonlySet<string>;+ selection: ReadonlySet<string>;+ /** Whether the bill may still be applied at all; with it false nothing here is operable. */+ approvable: boolean;+ /** Whether the cleanup mode is on — pins are refused while it is off, like every other write. */+ enabled: boolean;+ /** The path whose pin request is in flight, so one row's button is busy and no others are. */+ pinning: string | null;+ onToggleRow: (path: string) => void;+ onSelectClass: (classKey: StorageClass) => void;+ onUnselectClass: (classKey: StorageClass) => void;+ onPin: (path: string, pinned: boolean) => void;+}) {+ const selectable = group.entries.filter((entry) => movable.has(entry.path));+ const fullySelected = storageClassFullySelected(plan, selection, group.class, pins);+ return (+ <section className="mt-5">+ <div className="mb-2 flex items-center justify-between gap-3">+ <div className="min-w-0">+ <span className="text-sm font-medium">{storageClassLabel(group.class)}</span>+ {/* The class's price tag, the same line the ledger's class table shows: the reviewer is+ told what clearing one of these costs at the moment they can decide to. */}+ <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">+ {storageClassCost(group.class)}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-3">+ <span className="text-xs tabular-nums text-gray-500 dark:text-gray-400">+ {S.settings.storageBillGroupTotals(group.entries.length, formatBytes(group.bytes))}+ </span>+ {selectable.length === 0 ? (+ <span className="text-xs text-gray-500 dark:text-gray-400">+ {S.settings.storageSelectClassNothing}+ </span>+ ) : (+ <Button+ size="sm"+ disabled={!approvable}+ title={approvable ? undefined : S.settings.storageModeRequired}+ onClick={() =>+ fullySelected ? onUnselectClass(group.class) : onSelectClass(group.class)+ }+ >+ {fullySelected ? S.settings.storageUnselectClass : S.settings.storageSelectClass}+ </Button>+ )}+ </div>+ </div>+ <Table size="sm" tableClassName="min-w-[880px]">+ <TableHead>+ <TableHeaderCell>{S.settings.storageColSelect}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColPath}</TableHeaderCell>+ <TableHeaderCell align="right">{S.settings.storageColBytes}</TableHeaderCell>+ <TableHeaderCell align="right">{S.settings.storageColFiles}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColLastModified}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColRules}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColExecutable}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColPin}</TableHeaderCell>+ </TableHead>+ <TableBody>+ {group.entries.map((entry) => (+ <BillRow+ key={entry.path}+ entry={entry}+ pinned={pins.has(entry.path)}+ ticked={selection.has(entry.path)}+ movable={movable.has(entry.path)}+ enabled={enabled}+ pinning={pinning}+ onToggleRow={onToggleRow}+ onPin={onPin}+ />+ ))}+ </TableBody>+ </Table>+ </section>+ );+}++/** One row of a bill: the box, what the entry is, and the two things that can be done with it. */+function BillRow({+ entry,+ pinned,+ ticked,+ movable,+ enabled,+ pinning,+ onToggleRow,+ onPin,+}: {+ entry: StoragePlanEntryView;+ pinned: boolean;+ ticked: boolean;+ /** The box is inert for a row this page may not move — a report-only class, or a pinned path. */+ movable: boolean;+ enabled: boolean;+ pinning: string | null;+ onToggleRow: (path: string) => void;+ onPin: (path: string, pinned: boolean) => void;+}) {+ return (+ <TableRow>+ <TableCell>+ {/* Named by its path: the row's own words are in the cells beside it, and a bare box+ carries no name of its own. */}+ <Checkbox+ checked={ticked && movable}+ disabled={!movable}+ aria-label={entry.path}+ onChange={() => onToggleRow(entry.path)}+ />+ </TableCell>+ <TableCell className="max-w-[280px] font-mono text-xs break-all">{entry.path}</TableCell>+ <TableCell numeric>{formatBytes(entry.bytes)}</TableCell>+ <TableCell numeric>{entry.files}</TableCell>+ <TableCell className="whitespace-nowrap tabular-nums">+ {entry.lastModifiedAt === null+ ? S.settings.storageNeverModified+ : formatDateTime(entry.lastModifiedAt)}+ </TableCell>+ <TableCell className="whitespace-nowrap">{storageRulesLabel(entry.rules)}</TableCell>+ <TableCell className="whitespace-nowrap">+ {storageExecutableLabel(entry.executable)}+ </TableCell>+ <TableCell className="whitespace-nowrap">+ <Button+ size="sm"+ variant="ghost"+ disabled={!enabled || pinning !== null}+ aria-busy={pinning === entry.path}+ title={enabled ? undefined : S.settings.storageModeRequired}+ onClick={() => onPin(entry.path, !pinned)}+ >+ {pinned ? S.settings.storageUnpin : S.settings.storagePin}+ </Button>+ </TableCell>+ </TableRow>+ );+}++/** What an approval did: how much moved, where it went, and what refused to move. */+function ApplyResult({ result }: { result: StorageApplyResponse }) {+ return (+ <div className="mt-4 text-xs">+ <p className="font-medium">+ {result.moved.length === 0+ ? S.settings.storageApplyNothingMoved+ : S.settings.storageApplyResult(result.moved.length, formatBytes(result.freedBytes))}+ </p>+ {result.trashId !== null && (+ <p className="mt-1 font-mono break-all text-gray-500 dark:text-gray-400">+ {S.settings.storageApplyTrashId(result.trashId)}+ </p>+ )}+ {result.failed.length > 0 && (+ <>+ <p className="mt-2 font-medium">{S.settings.storageApplyFailedTitle}</p>+ {/* The server's own reason, as it sent it: two failures with the same path can differ+ (a rename refused, a target that came back), and a summarized reason would erase+ exactly the distinction the person has to act on. */}+ <ul className="mt-1 space-y-1">+ {result.failed.map((item) => (+ <li key={item.path} className="font-mono break-all text-gray-500 dark:text-gray-400">+ {S.settings.storageApplyFailedLine(item.path, item.reason)}+ </li>+ ))}+ </ul>+ </>+ )}+ </div>+ );+}++/** The trash: what a move put aside, entry by entry, with the two things a person may do with it. */+function TrashBlock({+ entries,+ ttlDays,+ enabled,+ busy,+ restored,+ purged,+ onRestore,+ onPurge,+}: {+ entries: StorageTrashEntry[];+ ttlDays: number | null;+ enabled: boolean;+ busy: string | null;+ restored: StorageRestoreResponse | null;+ purged: StoragePurgeResponse | null;+ onRestore: (id: string) => void;+ /** Without an id: only the entries past the retention. */+ onPurge: (id?: string) => void;+}) {+ return (+ <Block+ title={S.settings.storageTrashTitle}+ // The retention is the server's number, so the sentence is built from the answer to the+ // listing request rather than from a constant here; without it the line stays generic+ // instead of quoting a default that may not be the stored one.+ hint={ttlDays === null ? undefined : S.settings.storageTrashHint(ttlDays)}+ >+ {/* The one deletion there is, said once and in the danger tone, above the buttons that do it. */}+ <NoticeStrip tone="danger" as="p" className="rounded-md px-3 py-2 text-xs">+ {S.settings.storageTrashPurgeWarning}+ </NoticeStrip>+ {entries.length === 0 ? (+ <div className="mt-4">+ <EmptyState dashed title={S.settings.storageTrashEmpty} />+ </div>+ ) : (+ <Table size="sm" tableClassName="min-w-[720px]">+ <TableHead>+ <TableHeaderCell>{S.settings.storageColTrashId}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColTrashCreated}</TableHeaderCell>+ <TableHeaderCell align="right">{S.settings.storageColTrashItems}</TableHeaderCell>+ <TableHeaderCell align="right">{S.settings.storageColBytes}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColTrashState}</TableHeaderCell>+ <TableHeaderCell>{S.settings.storageColTrashActions}</TableHeaderCell>+ </TableHead>+ <TableBody>+ {entries.map((entry) => (+ <TableRow key={entry.id}>+ <TableCell className="font-mono break-all">{entry.id}</TableCell>+ <TableCell className="whitespace-nowrap tabular-nums">+ {formatDateTime(entry.createdAt)}+ </TableCell>+ <TableCell numeric>{entry.items.length}</TableCell>+ <TableCell numeric>{formatBytes(entry.bytes)}</TableCell>+ <TableCell className="whitespace-nowrap">+ {storageTrashStateLabel(storageTrashState(entry))}+ </TableCell>+ <TableCell className="whitespace-nowrap">+ <Button+ size="sm"+ disabled={!enabled || busy !== null}+ aria-busy={busy === `restore:${entry.id}`}+ title={enabled ? undefined : S.settings.storageModeRequired}+ onClick={() => onRestore(entry.id)}+ >+ {busy === `restore:${entry.id}`+ ? S.settings.storageTrashRestoring+ : S.settings.storageTrashRestore}+ </Button>+ {/* Labelled "delete for good" rather than "clean up": this button removes what+ the entry holds, and the word is the whole warning. */}+ <Button+ size="sm"+ variant="danger"+ className="ml-2"+ disabled={!enabled || busy !== null}+ aria-busy={busy === `purge:${entry.id}`}+ title={enabled ? undefined : S.settings.storageModeRequired}+ onClick={() => onPurge(entry.id)}+ >+ {S.settings.storageTrashPurge}+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ {entries.some((entry) => entry.expired) && (+ <div className="mt-3 flex justify-end">+ <Button+ size="sm"+ variant="danger"+ disabled={!enabled || busy !== null}+ aria-busy={busy === "purge:expired"}+ title={enabled ? undefined : S.settings.storageModeRequired}+ onClick={() => onPurge()}+ >+ {S.settings.storageTrashPurgeExpired}+ </Button>+ </div>+ )}+ {restored !== null && (+ <div className="mt-3 text-xs">+ <p className="font-medium">+ {S.settings.storageTrashRestored(restored.restored.length, restored.skipped.length)}+ </p>+ <p className="mt-1 text-gray-500 dark:text-gray-400">+ {restored.remaining+ ? S.settings.storageTrashRestoreRemaining.yes+ : S.settings.storageTrashRestoreRemaining.no}+ </p>+ {restored.skipped.length > 0 && (+ <ul className="mt-1 space-y-1">+ {restored.skipped.map((item) => (+ <li+ key={item.path}+ className="font-mono break-all text-gray-500 dark:text-gray-400"+ >+ {S.settings.storageTrashSkippedLine(item.path, item.reason)}+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ {purged !== null && (+ <p className="mt-3 text-xs font-medium">+ {purged.purged.length === 0+ ? S.settings.storageTrashPurgedNothing+ : S.settings.storageTrashPurged(+ purged.purged.length,+ formatBytes(purged.purged.reduce((sum, item) => sum + item.bytes, 0)),+ )}+ </p>+ )}+ </Block>+ );+}+export function StorageSection() {/** The last measurement (null until one lands) — replaced, never patched, by the next. */const [report, setReport] = useState<StorageReport | null>(null);@@ -241,6 +687,32 @@ export function StorageSection() {/** A measurement that failed: the page says so and offers to try again. */const [failed, setFailed] = useState(false);+ /** The cleanup mode, and with it the pins; null until the server has answered. */+ const [settings, setSettings] = useState<StorageSettings | null>(null);+ const [modeBusy, setModeBusy] = useState(false);+ /** The mode's settings could not be read, so the page behaves as if it were off. */+ const [modeFailed, setModeFailed] = useState(false);++ /** The bill under review, or null when there is none. */+ const [plan, setPlan] = useState<StoragePlanView | null>(null);+ const [scanning, setScanning] = useState(false);+ const [scanFailed, setScanFailed] = useState(false);++ /** The ticked paths — empty is the default a page and a fresh bill both open in. */+ const [selection, setSelection] = useState<ReadonlySet<string>>(NO_SELECTION);+ const [applying, setApplying] = useState(false);+ const [applyFailed, setApplyFailed] = useState<string | null>(null);+ const [applied, setApplied] = useState<StorageApplyResponse | null>(null);++ const [trash, setTrash] = useState<StorageTrashEntry[]>([]);+ const [ttlDays, setTtlDays] = useState<number | null>(null);+ /** Which trash action is in flight (`restore:<id>` / `purge:<id>` / `purge:expired`), or none. */+ const [trashBusy, setTrashBusy] = useState<string | null>(null);+ const [restored, setRestored] = useState<StorageRestoreResponse | null>(null);+ const [purged, setPurged] = useState<StoragePurgeResponse | null>(null);+ /** The path whose pin request is in flight, so one row's button is busy and no others are. */+ const [pinning, setPinning] = useState<string | null>(null);+const measure = useCallback(async () => {setBusy(true);setFailed(false);@@ -256,21 +728,200 @@ export function StorageSection() {}}, []);+ /**+ * The mode, the pins and the trash — the three reads that are not a walk of the root. A bill+ * the page is already showing is left alone: it is the one being reviewed, and a reload only+ * adopts the server's newest approvable bill so a page that is opened later is not empty.+ *+ * All three arrive together or the page says it could not read them: a mode known while the+ * trash is not (or the reverse) would draw a half-true page, and the one thing worse than a+ * disabled control is a control enabled by a stale answer.+ */+ const loadState = useCallback(async () => {+ try {+ const [settingsRes, trashRes, plansRes] = await Promise.all([+ api.adminGetStorageSettings(),+ api.adminGetStorageTrash(),+ api.adminListStoragePlans(),+ ]);+ setSettings(settingsRes.settings);+ setTrash(trashRes.entries);+ setTtlDays(trashRes.ttlDays);+ setPlan((current) => current ?? storageOpenPlan(plansRes.plans));+ setModeFailed(false);+ } catch (e) {+ setModeFailed(true);+ toastError(apiErrorText(e));+ }+ }, []);+useEffect(() => {void measure();- }, [measure]);+ void loadState();+ }, [measure, loadState]);++ const enabled = settings?.enabled === true;+ const pins = useMemo(() => new Set(settings?.pins ?? []), [settings]);++ /**+ * The rows this page may move right now: the bill's own movable entries, and only while the+ * mode is on and the bill may still be applied. One set, computed once, so every box on the+ * page and the apply button agree about what a click would do.+ */+ const movable = useMemo(() => {+ if (plan === null || !enabled || !plan.usable) return NO_SELECTION;+ return new Set(storageMovableEntries(plan, pins).map((entry) => entry.path));+ }, [plan, enabled, pins]);++ const saveMode = async (next: boolean) => {+ if (modeBusy) return;+ setModeBusy(true);+ try {+ setSettings((await api.adminUpdateStorageSettings({ enabled: next })).settings);+ toastSuccess(S.common.saved);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setModeBusy(false);+ }+ };++ const scan = async () => {+ if (scanning) return;+ setScanning(true);+ setScanFailed(false);+ setApplied(null);+ setApplyFailed(null);+ try {+ const fresh = await api.adminScanStorage();+ setPlan(fresh.plan);+ // A new bill replaces the old one wholesale, and a selection belongs to the bill that+ // offered it: keeping ticks across two bills would be approving rows nobody read.+ setSelection(NO_SELECTION);+ } catch (e) {+ // With the mode off the server refuses this with `storage_mode_off`; the page disables the+ // button instead, so reaching here means the mode changed elsewhere since it was read.+ setScanFailed(true);+ toastError(apiErrorText(e));+ } finally {+ setScanning(false);+ }+ };++ const apply = async () => {+ if (plan === null || applying) return;+ const body = storageApplyBody(plan, selection, pins);+ if (body === null) return;+ setApplying(true);+ setApplyFailed(null);+ try {+ const result = await api.adminApplyStoragePlan(body);+ setApplied(result);+ // The bill is spent by that run whatever moved, so the page drops it and goes back to+ // "scan again" rather than leaving boxes a second apply would be refused for; the ledger+ // and the trash are re-read because both just changed.+ setPlan(null);+ setSelection(NO_SELECTION);+ await Promise.all([measure(), loadState()]);+ } catch (e) {+ // A refusal here is the interesting case (a stale bill, an entry that came alive, the mode+ // turned off elsewhere): it is kept on the page, where the selection it refused still is.+ setApplyFailed(apiErrorText(e));+ toastError(apiErrorText(e));+ } finally {+ setApplying(false);+ }+ };++ const pin = async (path: string, pinned: boolean) => {+ if (plan === null || pinning !== null) return;+ setPinning(path);+ try {+ setSettings((await api.adminPinStoragePath(plan.id, { path, pinned })).settings);+ // A pinned path is refused by an apply, so it must not stay ticked: the refusal is+ // all-or-nothing, and it would name a row the page still drew as selected.+ if (pinned) {+ setSelection((current) => {+ const next = new Set(current);+ next.delete(path);+ return next;+ });+ }+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setPinning(null);+ }+ };++ const restore = async (id: string) => {+ if (trashBusy !== null) return;+ setTrashBusy(`restore:${id}`);+ setRestored(null);+ setPurged(null);+ try {+ setRestored(await api.adminRestoreStorageTrash(id));+ // Trees came back into the data root, so the ledger is a measurement of a moment that has+ // just passed; re-measuring is what keeps the two halves of the page telling one story.+ await Promise.all([measure(), loadState()]);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setTrashBusy(null);+ }+ };++ const purge = async (id?: string) => {+ if (trashBusy !== null) return;+ setTrashBusy(id === undefined ? "purge:expired" : `purge:${id}`);+ setRestored(null);+ setPurged(null);+ try {+ setPurged(await api.adminPurgeStorageTrash(id));+ // The trash is part of the ledger's own figures, so the report is re-read rather than left+ // showing the size of what has just been deleted.+ await Promise.all([measure(), loadState()]);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setTrashBusy(null);+ }+ };++ const approvable = plan !== null && plan.usable && enabled && !applying;+ const totals = plan === null ? null : storageSelectionTotals(plan, selection, pins);return (<SettingsSectionactions={- <Button size="sm" disabled={busy} aria-busy={busy} onClick={() => void measure()}>- {busy ? S.settings.storageRescanning : S.settings.storageRescan}- </Button>+ <>+ <Button size="sm" disabled={busy} aria-busy={busy} onClick={() => void measure()}>+ {busy ? S.settings.storageRescanning : S.settings.storageRescan}+ </Button>+ {/* Disabled rather than offered-and-refused while the mode is off: the scan is a write+ (it creates a bill), and the sentence under the switch says so. */}+ <Button+ size="sm"+ variant="primary"+ disabled={!enabled || scanning}+ aria-busy={scanning}+ title={enabled ? undefined : S.settings.storageModeRequired}+ onClick={() => void scan()}+ >+ {scanning ? S.settings.storageScanning : S.settings.storageScan}+ </Button>+ </>}>- {/* The page's first sentence is what it is not: a report. Everything below is a figure a- reader could otherwise mistake for an offer to free space. */}+ {/* The page's first sentence is what it promises, mode and all: everything below it is+ either a figure or an action a person has to take. */}<p className="text-xs text-gray-500 dark:text-gray-400">{S.settings.storageReportOnly}</p>+ <ModeRow+ settings={settings}+ busy={modeBusy}+ failed={modeFailed}+ onChange={(next) => void saveMode(next)}+ />{report === null && (<p className="text-sm text-gray-400">{failed ? S.settings.storageFailed : S.settings.storageLoading}@@ -292,6 +943,127 @@ export function StorageSection() {{report.unreadable.length > 0 && <Unreadable report={report} />}</>)}+ {enabled && (+ <Block title={S.settings.storageBillTitle}>+ {scanFailed && (+ <p className="mb-3 text-xs text-gray-500 dark:text-gray-400">+ {S.settings.storageScanFailed}+ </p>+ )}+ {plan === null ? (+ <EmptyState+ dashed+ title={S.settings.storageBillNone}+ description={S.settings.storageScanHint}+ />+ ) : (+ <>+ <BillHeader plan={plan} />+ {/* The bill's state in its own sentence, and what its stamps mean: a reviewer has to+ know whether the boxes below still mean anything before ticking one. */}+ <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">+ {storagePlanStateText(storagePlanState(plan))} {S.settings.storageBillHint}+ </p>+ <div className="mt-3 text-xs text-gray-500 dark:text-gray-400">+ <p className="font-medium text-gray-600 dark:text-gray-300">+ {plan.excluded.length === 0+ ? S.settings.storagePinsEmpty+ : S.settings.storageExcludedTitle(plan.excluded.length)}+ </p>+ <p className="mt-0.5">{S.settings.storagePinsHint}</p>+ <ul className="mt-1 space-y-1">+ {plan.excluded.map((path) => (+ <li key={path} className="font-mono break-all">+ {path}+ </li>+ ))}+ </ul>+ <p className="mt-1 font-medium text-gray-600 dark:text-gray-300">+ {S.settings.storagePinsTitle(settings?.pins.length ?? 0)}+ </p>+ <ul className="mt-1 space-y-1">+ {(settings?.pins ?? []).map((path) => (+ <li key={path} className="font-mono break-all">+ {path}+ </li>+ ))}+ </ul>+ </div>+ <section className="mt-6">+ <div className="mb-2 text-sm font-medium">{S.settings.storageBillClassesTitle}</div>+ {plan.entries.length === 0 ? (+ <EmptyState dashed title={S.settings.storageScanEmpty} />+ ) : (+ storageBillGroups(plan).map((group) => (+ <BillGroup+ key={group.class}+ plan={plan}+ group={group}+ pins={pins}+ movable={movable}+ selection={selection}+ approvable={approvable}+ enabled={enabled}+ pinning={pinning}+ onToggleRow={(path) =>+ setSelection((current) => storageTogglePath(plan, current, path, pins))+ }+ onSelectClass={(classKey) =>+ setSelection((current) => storageSelectClass(plan, current, classKey, pins))+ }+ onUnselectClass={(classKey) =>+ setSelection((current) =>+ storageUnselectClass(plan, current, classKey, pins),+ )+ }+ onPin={(path, next) => void pin(path, next)}+ />+ ))+ )}+ </section>+ <div className="mt-4 flex items-center justify-end gap-3">+ {/* The default is nothing selected, and the line says so rather than leaving the+ button's disabled state unexplained. */}+ <span className="text-xs tabular-nums text-gray-500 dark:text-gray-400">+ {totals === null || totals.entries === 0+ ? S.settings.storageSelectionNone+ : S.settings.storageSelectionSummary(totals.entries, formatBytes(totals.bytes))}+ </span>+ <Button+ variant="primary"+ disabled={!approvable || (totals?.entries ?? 0) === 0}+ loading={applying}+ title={enabled ? undefined : S.settings.storageModeRequired}+ onClick={() => void apply()}+ >+ {applying ? S.settings.storageApplying : S.settings.storageApply}+ </Button>+ </div>+ <p className="mt-1 text-right text-xs text-gray-500 dark:text-gray-400">+ {S.settings.storageApplyHint}+ </p>+ {applied !== null && <ApplyResult result={applied} />}+ </>+ )}+ {applyFailed !== null && (+ // Where the refusal is kept: the selection it refused to move is still below it, and a+ // toast would be gone by the time the person has read which rows were ticked.+ <NoticeStrip tone="danger" as="p" className="mt-3 rounded-md px-3 py-2 text-xs">+ {applyFailed}+ </NoticeStrip>+ )}+ </Block>+ )}+ <TrashBlock+ entries={trash}+ ttlDays={ttlDays}+ enabled={enabled}+ busy={trashBusy}+ restored={restored}+ purged={purged}+ onRestore={(id) => void restore(id)}+ onPurge={(id) => void purge(id)}+ /></SettingsSection>);}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex d66be05a..988343d9 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -458,16 +458,21 @@ export const en: Strings = {`Run "${action}" on ${machine ?? "this server"}? It runs on that machine right away; what it does is up to the plugin.`,/** Under a number field whose box does not parse; the save is not sent. */pluginFieldNotNumber: "Must be a number",- /** Admin-only sub-page (server-global): the data root's storage ledger. A report, and nothing else. */+ /**+ * Admin-only sub-page (server-global): the data root's storage ledger, and the human-reviewed+ * cleanup that reads it — a report on one side, a bill and its approval on the other.+ */storageTitle: "Storage ledger",/**- * The one line at the top of that page's own body: what the page is, and the promise it keeps.- * Deliberately visible rather than folded into the heading's "?" — it is what keeps every- * figure below from reading as an offer to clear something.+ * The one line at the top of that page's own body: what the page is, and the promise it keeps+ * now that it can also move something. Deliberately visible rather than folded into the+ * heading's "?" — it is what keeps the figures and the buttons below from reading as an offer+ * to free space automatically.*/storageReportOnly:- "This is a read-only report: it measures and lists what is on disk and deletes nothing. " +- "Cleanup will be a separate step, taken by a person after reading this — the page offers no such action.",+ "The default is to keep every byte: with the cleanup mode off, this page only measures and lists what is on disk. " ++ "Once the mode is on, a scan writes a bill and only the entries you tick are moved into the trash — where they can be restored. " ++ 'Nothing runs by itself, and the one deletion is "Delete for good" in the trash.',/** The page's "?" at the pane heading: what is measured, and what a candidate is (and is not). */storageInfo:"The subject is this machine's data root, measured in one walk: every byte lands in exactly one class by provenance, and the total is the root's own size. " +@@ -562,6 +567,115 @@ export const en: Strings = {storageUnreadableTitle: "Paths that could not be read",storageUnreadableHint:"Nothing under these paths entered the figures above, so those figures are a lower bound.",+ /**+ * The cleanup mode: the switch a person turns on, and what each position means. Each sentence+ * names what the OTHER position cannot do, because that difference is the whole page.+ */+ storageModeTitle: "Cleanup mode",+ storageModeLabel: "Allow cleanup after a human review",+ storageModeOn:+ "On: you can scan out a bill, move the entries you tick into the trash, and put what is in the trash back. " ++ 'The only deletion is "Delete for good", and it takes your click.',+ storageModeOff:+ "Off: this page only measures and lists what is on disk — no scan, pin, move or purge happens, and nothing is moved. " ++ "This is the default, and nothing changes it on its own.",+ /** The mode's settings could not be read: the page then behaves as if it were off. */+ storageModeFailed: "Could not read the cleanup mode's settings, so this page treats it as off.",+ /** The hint on every write control the mode gates, so a disabled button says why. */+ storageModeRequired: "Turn the cleanup mode on first",+ /** The bill's own state, one sentence each: the difference decides whether a selection may run. */+ storagePlanStateText: {+ usable: "Not applied yet, and still within its day: the entries you tick can be moved.",+ applied: "Already applied once. A bill is good for one run; scan again to clean more.",+ expired: "Past its day. Scan again so the bill describes the disk as it is now.",+ },+ /** The scan that writes a bill; the ledger's own button beside it only measures again. */+ storageScan: "Scan for a bill",+ storageScanning: "Scanning…",+ storageScanHint:+ "A scan walks the data root and writes out a bill; its entries are what this scan found. " ++ 'The bill moves nothing by itself: a move happens only after you tick entries and press "Clean up".',+ storageScanEmpty: "This scan found no candidates, so this bill has nothing that could move.",+ storageScanFailed: "The scan failed, so there is no bill to review.",+ /** The bill's own header. */+ storageBillTitle: "Bill",+ storageBillId: "Bill id",+ storageBillCreatedAt: "Written at",+ storageBillExpiresAt: "Good until",+ storageBillTotal: "Bill total",+ storageBillEntries: (count: number): string => `${count} entries`,+ storageBillHint:+ "A bill is a snapshot of the instant it was written. Before anything moves, the server checks every entry against the disk and live state as they are then, and refuses the ones that no longer match rather than moving them anyway.",+ /** Before any scan has produced one: the page says what to press rather than leaving a void. */+ storageBillNone: "There is no bill to review yet.",+ /** The bill's own columns: the box, the rule that put the row there, and what may be done with it. */+ storageColSelect: "Select",+ storageColExecutable: "Movable",+ storageColPin: "Pin",+ /** The review: one group per class, and the boxes that decide what may move. */+ storageBillClassesTitle: "Review by class",+ storageBillGroupTotals: (entries: number, bytes: string): string =>+ `${entries} entries · ${bytes}`,+ storageSelectClass: "Select the class",+ storageUnselectClass: "Clear the class",+ storageSelectClassNothing: "Nothing in this class can be moved",+ /** Whether this version may act on a row at all; the rest are on the bill to be read. */+ storageExecutable: {+ yes: "can be moved",+ no: "report only",+ },+ /** The selection: nothing is ticked until a person ticks it, and the page says so. */+ storageSelectionNone: "Nothing is ticked yet — the default is to keep every byte.",+ storageSelectionSummary: (entries: number, bytes: string): string =>+ `${entries} entries selected, ${bytes}`,+ /** The pins: what a person decided to keep, and what a bill therefore leaves out. */+ storagePinsTitle: (count: number): string => `${count} pinned paths`,+ storagePinsEmpty: "No path is pinned yet.",+ storagePinsHint: "A pinned path never appears on a later bill, until you unpin it.",+ storageExcludedTitle: (count: number): string => `This bill left out ${count} pinned paths`,+ storagePin: "Pin",+ storageUnpin: "Unpin",+ /** The one action that moves something, and what it does when it does it. */+ storageApply: "Clean up",+ storageApplying: "Cleaning up…",+ storageApplyHint:+ "Only the entries you ticked are moved, and they are moved into the trash: they can be restored. This is not a deletion.",+ storageApplyResult: (moved: number, bytes: string): string =>+ `Moved ${moved} entries, ${bytes}`,+ storageApplyNothingMoved: "No entry was moved.",+ storageApplyTrashId: (id: string): string => `Trash entry: ${id}`,+ storageApplyFailedTitle: "Entries that could not be moved",+ storageApplyFailedLine: (path: string, reason: string): string => `${path}: ${reason}`,+ /** The trash: what a move put aside, and the two things a person may do with it. */+ storageTrashTitle: "Trash",+ storageTrashHint: (days: number): string =>+ `What was moved in is kept for at least ${days} days. Nothing is deleted on its own during that time — a deletion always takes your click.`,+ storageTrashEmpty: "The trash is empty.",+ storageColTrashId: "Trash entry",+ storageColTrashCreated: "Moved in",+ storageColTrashItems: "Entries",+ storageColTrashState: "State",+ storageColTrashActions: "Actions",+ storageTrashStateNames: {+ fresh: "within retention",+ expired: "past retention",+ },+ storageTrashRestore: "Restore",+ storageTrashRestoring: "Restoring…",+ storageTrashPurge: "Delete for good",+ storageTrashPurgeExpired: "Delete what is past retention",+ storageTrashPurgeWarning:+ '"Delete for good" is the only deletion on this page: what is in the trash is gone, and cannot be recovered.',+ storageTrashPurgedNothing: "There was nothing to delete.",+ storageTrashPurged: (count: number, bytes: string): string =>+ `Deleted ${count} entries for good, ${bytes} in all`,+ storageTrashRestored: (restored: number, skipped: number): string =>+ `Restored ${restored} entries, skipped ${skipped}`,+ storageTrashRestoreRemaining: {+ yes: "The trash entry still holds something, so this restore did not finish it.",+ no: "The trash entry was empty afterwards and has been removed.",+ },+ storageTrashSkippedLine: (path: string, reason: string): string => `${path}: ${reason}`,uploadLimitsTitle: "Upload limits",/** Its two number fields, both in whole MB. */attachmentMaxMb: "Max attachment size (MB)",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 0c92b350..cf07a84e 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -523,16 +523,21 @@ export const zh = {`在${machine === null ? "本机" : ` ${machine} `}上执行「${action}」?它会立即在那台机器上运行,具体做什么由插件决定。`,/** Under a number field whose box does not parse; the save is not sent. */pluginFieldNotNumber: "必须是数字",- /** Admin-only sub-page (server-global): the data root's storage ledger. A report, and nothing else. */+ /**+ * Admin-only sub-page (server-global): the data root's storage ledger, and the human-reviewed+ * cleanup that reads it — a report on one side, a bill and its approval on the other.+ */storageTitle: "存储台账",/**- * The one line at the top of that page's own body: what the page is, and the promise it keeps.- * Deliberately visible rather than folded into the heading's "?" — it is what keeps every- * figure below from reading as an offer to clear something.+ * The one line at the top of that page's own body: what the page is, and the promise it keeps+ * now that it can also move something. Deliberately visible rather than folded into the+ * heading's "?" — it is what keeps the figures and the buttons below from reading as an offer+ * to free space automatically.*/storageReportOnly:- "这是一份只读报告:本页只测量并列出磁盘上的内容,不会删除任何数据。" +- "清理将是另一步,需要人看过之后自己决定——本页不提供这种操作。",+ "默认是一个字节都不动:清理模式关着的时候,本页只测量并列出磁盘上的内容。" ++ "开启之后,「重新扫描」写出一份账单,只有你勾选的条目才会被移入回收站——在那里可以恢复。" ++ "没有任何操作会自动运行,唯一的删除是回收站里的「彻底删除」。",/** The page's "?" at the pane heading: what is measured, and what a candidate is (and is not). */storageInfo:"测量的是本机的数据根目录,一次遍历得出:每个字节按来源归入一个类别,各类别互不重叠,合计即根目录本身的大小。" +@@ -623,6 +628,114 @@ export const zh = {storageUnreadableTitle: "无法读取的路径",storageUnreadableHint:"这些位置在测量时没有读到,其中的内容没有进入上面的统计,所以上面的数字是下限。",+ /**+ * The cleanup mode: the switch a person turns on, and what each position means. Each sentence+ * names what the OTHER position cannot do, because that difference is the whole page.+ */+ storageModeTitle: "清理模式",+ storageModeLabel: "允许人工审核后的清理",+ storageModeOn:+ "已开启:可以扫描出一份账单、把勾选的条目移入回收站,也可以把回收站里的内容恢复回去。" ++ "删除只发生在「彻底删除」这一步,而且要你自己按下按钮。",+ storageModeOff:+ "已关闭:本页只测量并列出磁盘上的内容,扫描、固定、移动和清空都不会发生,没有任何东西会被挪动。" ++ "这是默认状态,也不会自己改变。",+ /** The mode's settings could not be read: the page then behaves as if it were off. */+ storageModeFailed: "无法读取清理模式设置,因此按「已关闭」处理。",+ /** The hint on every write control the mode gates, so a disabled button says why. */+ storageModeRequired: "需要先开启清理模式",+ /** The bill's own state, one sentence each: the difference decides whether a selection may run. */+ storagePlanStateText: {+ usable: "尚未执行,且仍在有效期内:勾选的条目可以被移动。",+ applied: "已经执行过一次。一份账单只对一次执行有效,要再清理请重新扫描。",+ expired: "已超过有效期。请重新扫描,让账单描述的是现在的磁盘。",+ },+ /** The scan that writes a bill; the ledger's own button beside it only measures again. */+ storageScan: "重新扫描",+ storageScanning: "扫描中…",+ storageScanHint:+ "「重新扫描」会遍历数据根目录并写出一份账单,列出的条目是这次扫描的候选。" ++ "账单本身不移动任何东西:移动只发生在你勾选条目并按下「执行清理」之后。",+ storageScanEmpty: "这次扫描没有找到候选条目,因此这份账单里没有可以移动的东西。",+ storageScanFailed: "扫描失败,没有可以审阅的账单。",+ /** The bill's own header. */+ storageBillTitle: "账单",+ storageBillId: "账单编号",+ storageBillCreatedAt: "生成时间",+ storageBillExpiresAt: "有效期至",+ storageBillTotal: "账单合计",+ storageBillEntries: (count: number): string => `${count} 个条目`,+ storageBillHint:+ "账单是扫描那一刻的快照。执行之前服务器会按现在的情况复核一遍,对不上的条目会被拒绝,而不是照旧被移动。",+ /** Before any scan has produced one: the page says what to press rather than leaving a void. */+ storageBillNone: "还没有可审阅的账单。",+ /** The bill's own columns: the box, the rule that put the row there, and what may be done with it. */+ storageColSelect: "选中",+ storageColExecutable: "能否移动",+ storageColPin: "固定",+ /** The review: one group per class, and the boxes that decide what may move. */+ storageBillClassesTitle: "按类别审阅",+ storageBillGroupTotals: (entries: number, bytes: string): string =>+ `${entries} 个条目 · ${bytes}`,+ storageSelectClass: "全选本类",+ storageUnselectClass: "取消本类",+ storageSelectClassNothing: "本类没有可移动的条目",+ /** Whether this version may act on a row at all; the rest are on the bill to be read. */+ storageExecutable: {+ yes: "可以移动",+ no: "仅供查看",+ },+ /** The selection: nothing is ticked until a person ticks it, and the page says so. */+ storageSelectionNone: "尚未勾选任何条目——默认是一个字节都不动。",+ storageSelectionSummary: (entries: number, bytes: string): string =>+ `已勾选 ${entries} 个条目,合计 ${bytes}`,+ /** The pins: what a person decided to keep, and what a bill therefore leaves out. */+ storagePinsTitle: (count: number): string => `已固定 ${count} 条路径`,+ storagePinsEmpty: "还没有固定任何路径。",+ storagePinsHint: "固定的路径不会再出现在之后的任何账单里,直到你取消固定。",+ storageExcludedTitle: (count: number): string => `这份账单排除了 ${count} 条已固定路径`,+ storagePin: "固定",+ storageUnpin: "取消固定",+ /** The one action that moves something, and what it does when it does it. */+ storageApply: "执行清理",+ storageApplying: "清理中…",+ storageApplyHint: "只移动勾选的条目,而且是移入回收站:可以再恢复,这不是删除。",+ storageApplyResult: (moved: number, bytes: string): string =>+ `已移动 ${moved} 个条目,回收 ${bytes}`,+ storageApplyNothingMoved: "没有条目被移动。",+ storageApplyTrashId: (id: string): string => `回收站条目:${id}`,+ storageApplyFailedTitle: "未能移动的条目",+ storageApplyFailedLine: (path: string, reason: string): string => `${path}:${reason}`,+ /** The trash: what a move put aside, and the two things a person may do with it. */+ storageTrashTitle: "回收站",+ storageTrashHint: (days: number): string =>+ `移入的条目至少保留 ${days} 天。保留期内没有任何东西会自动删除——删除永远需要你按下按钮。`,+ storageTrashEmpty: "回收站是空的。",+ storageColTrashId: "回收站条目",+ storageColTrashCreated: "移入时间",+ storageColTrashItems: "条目",+ storageColTrashState: "状态",+ storageColTrashActions: "操作",+ storageTrashStateNames: {+ fresh: "保留中",+ expired: "已过保留期",+ },+ storageTrashRestore: "恢复",+ storageTrashRestoring: "恢复中…",+ storageTrashPurge: "彻底删除",+ storageTrashPurgeExpired: "彻底删除已过保留期的",+ storageTrashPurgeWarning:+ "「彻底删除」是本页唯一的删除操作:回收站里的内容会就此消失,无法恢复。",+ storageTrashPurgedNothing: "没有可删除的内容。",+ storageTrashPurged: (count: number, bytes: string): string =>+ `已彻底删除 ${count} 项,共 ${bytes}`,+ storageTrashRestored: (restored: number, skipped: number): string =>+ `已恢复 ${restored} 个条目,跳过 ${skipped} 个`,+ storageTrashRestoreRemaining: {+ yes: "回收站条目里还有内容,这次没有全部恢复。",+ no: "回收站条目已经空了,随之被移除。",+ },+ storageTrashSkippedLine: (path: string, reason: string): string => `${path}:${reason}`,uploadLimitsTitle: "上传限制",/** Its two number fields, both in whole MB. */attachmentMaxMb: "单个附件上限(MB)",diff --git a/packages/web/test/storage-labels.test.ts b/packages/web/test/storage-labels.test.tsindex 90879d33..8e6ee45b 100644--- a/packages/web/test/storage-labels.test.ts+++ b/packages/web/test/storage-labels.test.ts@@ -1,5 +1,6 @@/**- * The storage report's vocabulary (features/settings/storage-labels.ts), pinned by value.+ * The storage report's and its bills' vocabulary (features/settings/storage-labels.ts), pinned by+ * value.** The report's reader decides nothing from this page, but they do read it: a class or a rule* rendered as its raw id (`session_drafts`, `orphan`) is a word this audience cannot act on, and a@@ -10,7 +11,12 @@* classes that never become a candidate, which say that rather than inventing a price;* - each rule has a name of its own;* - a candidate's rules render joined, and an empty list renders words rather than nothing;- * - a look-alike environment group says what matched it (the name, or what it holds).+ * - a look-alike environment group says what matched it (the name, or what it holds);+ * - a bill's state and a trash entry's are read off what the server sent, and each has its own+ * sentence — the state decides whether the boxes on a bill mean anything, so it cannot be the+ * same words for two of them;+ * - a bill row says whether this version may move it, which is the one thing a reviewer cannot+ * learn from its size.** The lists below are written out rather than derived from a union, so a value the engine adds* fails this test (as it fails the type check in storage-labels.ts) instead of passing quietly.@@ -20,11 +26,22 @@ import {storageClassCost,storageClassLabel,storageEnvGroupKindLabel,+ storageExecutableLabel,+ storagePlanState,+ storagePlanStateText,storageRulesLabel,+ storageTrashState,+ storageTrashStateLabel,} from "../src/features/settings/storage-labels";+import type { StoragePlanState, StorageTrashState } from "../src/features/settings/storage-labels";import { setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";-import type { StorageCandidateRule, StorageClass } from "@lmliheng/penguin-server/api";+import type {+ StorageCandidateRule,+ StorageClass,+ StoragePlanView,+ StorageTrashEntry,+} from "@lmliheng/penguin-server/api";/** Every class the ledger accounts for (core's STORAGE_CLASSES, the API's StorageClass). */const CLASSES: StorageClass[] = [@@ -41,6 +58,33 @@ const CLASSES: StorageClass[] = [/** Every rule a candidate can carry. */const RULES: StorageCandidateRule[] = ["empty", "unreferenced", "orphan", "idle", "budget"];+/** Every state a bill can be read as, and every state a trash entry can. */+const PLAN_STATES: StoragePlanState[] = ["usable", "applied", "expired"];+const TRASH_STATES: StorageTrashState[] = ["fresh", "expired"];++/** The two answers a bill row gives about whether this version may move it. */+const EXECUTABLE = [true, false];++/** A bill carrying only what decides its state. */+function plan(over: Partial<StoragePlanView>): StoragePlanView {+ return {+ id: "2026-10-10-09-12-00-4f2a1c",+ root: "/home/demo/.adelie/data",+ createdAt: "2026-10-10T09:12:00.000Z",+ expiresAt: "2026-10-11T09:12:00.000Z",+ fingerprint: "fp",+ totalBytes: 0,+ entries: [],+ excluded: [],+ executableClasses: ["tmp_workspaces"],+ appliedAt: null,+ appliedPaths: [],+ usable: true,+ expired: false,+ ...over,+ };+}+afterEach(() => setActiveStrings(zh));describe("storageClassLabel / storageClassCost", () => {@@ -126,3 +170,83 @@ describe("storageEnvGroupKindLabel", () => {}});});++describe("storagePlanState / storagePlanStateText", () => {+ it("reads the state off what the bill carries, with 'applied' stronger than 'expired'", () => {+ expect(storagePlanState(plan({}))).toBe("usable");+ expect(storagePlanState(plan({ expired: true, usable: false }))).toBe("expired");+ expect(storagePlanState(plan({ appliedAt: "2026-10-10T10:00:00.000Z", usable: false }))).toBe(+ "applied",+ );+ // A bill applied yesterday is spent whatever its day says: reading it as "expired" would point+ // the reviewer at the clock instead of at the scan they need.+ expect(+ storagePlanState(+ plan({ appliedAt: "2026-10-09T10:00:00.000Z", expired: true, usable: false }),+ ),+ ).toBe("applied");+ });++ it("has its own sentence for each state, in both locales", () => {+ for (const dict of [zh, en]) {+ setActiveStrings(dict);+ const sentences = PLAN_STATES.map((state) => storagePlanStateText(state));+ for (const state of PLAN_STATES) {+ expect(storagePlanStateText(state), state).toBe(dict.settings.storagePlanStateText[state]);+ expect(storagePlanStateText(state).trim(), state).not.toBe("");+ // A state that read as another state's words would tell a reviewer to wait for a bill that+ // is already spent, or to approve one whose boxes no longer mean anything.+ expect(storagePlanStateText(state), state).not.toBe(state);+ }+ expect(new Set(sentences).size, "one sentence per state").toBe(PLAN_STATES.length);+ }+ });+});++describe("storageTrashState / storageTrashStateLabel", () => {+ const entry = (over: Partial<StorageTrashEntry>): StorageTrashEntry => ({+ id: "20261010-130522",+ createdAt: "2026-10-10T13:05:22.000Z",+ planId: "2026-10-10-13-05-00-4f2a1c",+ bytes: 1_000,+ files: 3,+ items: [],+ expired: false,+ ...over,+ });++ it("takes the flag the server computed against the retention", () => {+ expect(storageTrashState(entry({}))).toBe("fresh");+ expect(storageTrashState(entry({ expired: true }))).toBe("expired");+ });++ it("says what each state means for the entry, in both locales", () => {+ for (const dict of [zh, en]) {+ setActiveStrings(dict);+ for (const state of TRASH_STATES) {+ expect(storageTrashStateLabel(state), state).toBe(+ dict.settings.storageTrashStateNames[state],+ );+ expect(storageTrashStateLabel(state), state).not.toBe(state);+ }+ expect(storageTrashStateLabel("fresh")).not.toBe(storageTrashStateLabel("expired"));+ }+ });+});++describe("storageExecutableLabel", () => {+ it("says whether this version may move a row, in both locales, once per answer", () => {+ for (const dict of [zh, en]) {+ setActiveStrings(dict);+ for (const flag of EXECUTABLE) {+ expect(storageExecutableLabel(flag), String(flag)).toBe(+ dict.settings.storageExecutable[flag ? "yes" : "no"],+ );+ expect(storageExecutableLabel(flag).trim(), String(flag)).not.toBe("");+ }+ // "Can be moved" and "report only" must not be the same words: that difference is the whole+ // reason a row is drawn with a dead box.+ expect(storageExecutableLabel(true)).not.toBe(storageExecutableLabel(false));+ }+ });+});diff --git a/packages/web/test/storage-review.test.ts b/packages/web/test/storage-review.test.tsnew file mode 100644index 00000000..47b2143b--- /dev/null+++ b/packages/web/test/storage-review.test.ts@@ -0,0 +1,264 @@+/**+ * The bill's bookkeeping (features/settings/storage-review.ts), pinned by value.+ *+ * The page's whole safety argument is that a click cannot widen what moves, so the three things+ * that decide it are checked here rather than trusted to the component's rendering:+ *+ * - **the default is nothing.** A bill arrives with an empty selection, and an empty selection+ * cannot become a request at all (the apply body is null rather than "everything");+ * - **"select all of this class" takes only what may move.** The rows this version can only+ * report stay out of it, and so do the pinned ones — the server refuses an apply containing a+ * pinned path as a whole, so a button that took one would lose the rest of the click;+ * - **the request says what was read.** The fingerprint sent back is the bill's own, and the+ * paths are the bill's rows in the bill's order, so two builds of the same selection are the+ * same request whatever order the boxes were ticked in.+ *+ * The rows are written out rather than derived, so a row or a class the API adds shows up here as+ * a failing expectation instead of passing quietly.+ */+import { describe, expect, it } from "vitest";+import {+ NO_SELECTION,+ storageApplyBody,+ storageBillGroups,+ storageClassFullySelected,+ storageMovableEntries,+ storageOpenPlan,+ storageSelectClass,+ storageSelectionTotals,+ storageTogglePath,+ storageUnselectClass,+} from "../src/features/settings/storage-review";+import type { StoragePlanEntryView, StoragePlanView } from "@lmliheng/penguin-server/api";++const tmp1 = "proj/agents/docs/workspaces/tmp-11111111";+const tmp2 = "proj/agents/docs/workspaces/tmp-22222222";+const drafts = "proj/agents/docs/scratchpad/session-2026-10-01-10-00-00-aaaaaaaa";+const trace = "proj/agents/docs/traces/session-2026-10-01-10-00-00-aaaaaaaa";++/** One bill row, with only the fields a test cares about spelled out. */+function row(over: Partial<StoragePlanEntryView> & { path: string }): StoragePlanEntryView {+ return {+ class: "tmp_workspaces",+ bytes: 1_000,+ files: 3,+ lastModifiedAt: "2026-10-01T10:00:00.000Z",+ rules: ["unreferenced"],+ fingerprint: "fp-row",+ executable: true,+ ...over,+ };+}++/** A bill of two movable temporary Workspaces, one draft row and one trace row (both report-only). */+function bill(over: Partial<StoragePlanView> = {}): StoragePlanView {+ return {+ id: "2026-10-10-09-12-00-4f2a1c",+ root: "/home/demo/.adelie/data",+ createdAt: "2026-10-10T09:12:00.000Z",+ expiresAt: "2026-10-11T09:12:00.000Z",+ fingerprint: "fp-bill",+ totalBytes: 2_000 + 700 + 500 + 100,+ entries: [+ row({ path: tmp1, bytes: 2_000, files: 4 }),+ row({ path: tmp2, bytes: 700, files: 2 }),+ row({+ path: drafts,+ class: "session_drafts",+ bytes: 500,+ files: 1,+ rules: ["orphan"],+ executable: false,+ }),+ row({+ path: trace,+ class: "traces",+ bytes: 100,+ files: 1,+ rules: ["idle"],+ executable: false,+ }),+ ],+ excluded: [],+ executableClasses: ["tmp_workspaces"],+ appliedAt: null,+ appliedPaths: [],+ usable: true,+ expired: false,+ ...over,+ };+}++const EMPTY_PINS: ReadonlySet<string> = new Set<string>();++describe("storageBillGroups", () => {+ it("groups the bill by class, biggest class first and biggest row first inside it", () => {+ const groups = storageBillGroups(bill());+ expect(groups.map((group) => group.class)).toEqual([+ "tmp_workspaces",+ "session_drafts",+ "traces",+ ]);+ expect(groups[0]!.entries.map((entry) => entry.path)).toEqual([tmp1, tmp2]);+ expect(groups[0]!.bytes).toBe(2_700);+ expect(groups[0]!.files).toBe(6);+ // A class's figure is its own rows summed, never the report's number for the class: a bill+ // accounts for part of a class, and a group claiming the class total would overstate it.+ expect(groups.reduce((sum, group) => sum + group.bytes, 0)).toBeLessThanOrEqual(+ bill().totalBytes,+ );+ });++ it("orders two classes that account for the same size by id, not by the order they arrived", () => {+ const plan = bill({+ entries: [+ row({ path: trace, class: "traces", bytes: 400, executable: false }),+ row({ path: tmp1, bytes: 400 }),+ ],+ });+ expect(storageBillGroups(plan).map((group) => group.class)).toEqual([+ "tmp_workspaces",+ "traces",+ ]);+ const reversed = bill({+ entries: [+ row({ path: tmp1, bytes: 400 }),+ row({ path: trace, class: "traces", bytes: 400, executable: false }),+ ],+ });+ expect(storageBillGroups(reversed).map((group) => group.class)).toEqual([+ "tmp_workspaces",+ "traces",+ ]);+ });++ it("says nothing at all for a bill that found nothing", () => {+ expect(storageBillGroups(bill({ entries: [] }))).toEqual([]);+ });+});++describe("the selection", () => {+ it("starts empty, and copying it never mutates the shared default", () => {+ expect(NO_SELECTION.size).toBe(0);+ const next = storageTogglePath(bill(), NO_SELECTION, tmp1, EMPTY_PINS);+ expect([...next]).toEqual([tmp1]);+ expect(NO_SELECTION.size).toBe(0);+ });++ it("takes a row, and gives it back when the box is clicked again", () => {+ const plan = bill();+ const ticked = storageTogglePath(plan, NO_SELECTION, tmp1, EMPTY_PINS);+ expect(storageSelectionTotals(plan, ticked, EMPTY_PINS)).toEqual({ entries: 1, bytes: 2_000 });+ expect(storageTogglePath(plan, ticked, tmp1, EMPTY_PINS).size).toBe(0);+ });++ it("refuses a row this version can only report, and one that is pinned", () => {+ const plan = bill();+ const pins = new Set([tmp1]);+ expect([...storageTogglePath(plan, NO_SELECTION, drafts, EMPTY_PINS)]).toEqual([]);+ expect([...storageTogglePath(plan, NO_SELECTION, tmp1, pins)]).toEqual([]);+ // A path that is not on this bill at all is not a selection either: the apply would be+ // refused for naming something the bill never recorded.+ expect([...storageTogglePath(plan, NO_SELECTION, "proj/elsewhere", EMPTY_PINS)]).toEqual([]);+ });++ it("takes a whole class's movable rows and nothing else", () => {+ const plan = bill();+ const selected = storageSelectClass(plan, NO_SELECTION, "tmp_workspaces", EMPTY_PINS);+ expect([...selected].sort()).toEqual([tmp2, tmp1].sort());+ expect(storageClassFullySelected(plan, selected, "tmp_workspaces", EMPTY_PINS)).toBe(true);+ // A class with nothing movable can never read as fully selected: the button it drives would+ // otherwise offer to "clear" a selection that was never possible.+ expect(storageClassFullySelected(plan, selected, "session_drafts", EMPTY_PINS)).toBe(false);+ });++ it("leaves a pinned row out of its class, and out of what is already ticked", () => {+ const plan = bill();+ const pins = new Set([tmp1]);+ const selected = storageSelectClass(plan, NO_SELECTION, "tmp_workspaces", pins);+ expect([...selected]).toEqual([tmp2]);+ expect(storageMovableEntries(plan, pins).map((entry) => entry.path)).toEqual([tmp2]);+ expect(storageSelectionTotals(plan, new Set([tmp1, tmp2]), pins)).toEqual({+ entries: 1,+ bytes: 700,+ });+ });++ it("drops one class without touching another class's ticks", () => {+ const plan = bill();+ const both = storageSelectClass(+ plan,+ storageSelectClass(plan, NO_SELECTION, "tmp_workspaces", EMPTY_PINS),+ "tmp_workspaces",+ EMPTY_PINS,+ );+ expect(both.size).toBe(2);+ const cleared = storageUnselectClass(plan, both, "traces", EMPTY_PINS);+ expect(cleared.size).toBe(2);+ expect(storageUnselectClass(plan, both, "tmp_workspaces", EMPTY_PINS).size).toBe(0);+ });+});++describe("storageApplyBody", () => {+ it("is null while nothing is selected — an empty selection is not 'everything'", () => {+ expect(storageApplyBody(bill(), NO_SELECTION, EMPTY_PINS)).toBeNull();+ expect(storageApplyBody(bill(), new Set([drafts]), EMPTY_PINS)).toBeNull();+ });++ it("carries the displayed bill's own fingerprint and exactly the ticked paths", () => {+ const plan = bill();+ const selection = storageSelectClass(plan, NO_SELECTION, "tmp_workspaces", EMPTY_PINS);+ expect(storageApplyBody(plan, selection, EMPTY_PINS)).toEqual({+ planId: plan.id,+ fingerprint: "fp-bill",+ paths: [tmp1, tmp2],+ });+ });++ it("sends the paths in the bill's order, whatever order they were ticked in", () => {+ const plan = bill();+ const backwards = storageTogglePath(+ plan,+ storageTogglePath(plan, NO_SELECTION, tmp2, EMPTY_PINS),+ tmp1,+ EMPTY_PINS,+ );+ expect(storageApplyBody(plan, backwards, EMPTY_PINS)?.paths).toEqual([tmp1, tmp2]);+ });++ it("never sends a report-only or a pinned path, whatever the selection holds", () => {+ const plan = bill();+ const pins = new Set([tmp2]);+ const selection = new Set([tmp1, tmp2, drafts, trace]);+ expect(storageApplyBody(plan, selection, pins)).toEqual({+ planId: plan.id,+ fingerprint: "fp-bill",+ paths: [tmp1],+ });+ });+});++describe("storageOpenPlan", () => {+ it("adopts the newest bill the server still lets be approved", () => {+ // The list arrives newest first, so the spent one at the head is skipped rather than shown:+ // its boxes could not run, and the bill below it is the one a reviewer can still approve.+ const open = bill({ id: "newer" });+ expect(+ storageOpenPlan([+ bill({ id: "applied", appliedAt: "2026-10-10T10:00:00.000Z", usable: false }),+ open,+ bill({ id: "older" }),+ ]),+ ).toBe(open);+ });++ it("adopts nothing when every recent bill is spent, expired, or absent", () => {+ expect(+ storageOpenPlan([+ bill({ id: "applied", appliedAt: "2026-10-10T10:00:00.000Z", usable: false }),+ bill({ id: "expired", expired: true, usable: false }),+ ]),+ ).toBeNull();+ expect(storageOpenPlan([])).toBeNull();+ });+});