Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(sandbox-drive): analyze drive space and clean it up, from the drive and from the agent (#22883)

Rdmclin2028b058be99e
diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts
index 67497dd57c8..a1ec2ffa4be 100644
--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts
@@ -37,10 +37,12 @@ const STORAGE_KEY = `ws-org-${workspaceId}`;
const personalKey = (userId: string) => `ws-mem-${workspaceId}-${userId}`;
const plane = vi.hoisted(() => ({
+ analyzeStorage: vi.fn(),
copyInstance: vi.fn(),
createDirectory: vi.fn(),
deleteFile: vi.fn(),
deleteInstance: vi.fn(),
+ deletePaths: vi.fn(),
exportFile: vi.fn(),
getStorage: vi.fn(),
listFiles: vi.fn(),
@@ -151,6 +153,14 @@ beforeEach(async () => {
plane.createDirectory.mockReset().mockImplementation(async ({ path }) => ({ path }));
plane.deleteFile.mockReset().mockImplementation(async ({ path }) => ({ path }));
plane.deleteInstance.mockReset().mockResolvedValue(undefined);
+ plane.analyzeStorage.mockReset();
+ plane.deletePaths.mockReset().mockImplementation(async ({ paths }) => ({
+ deleted: paths,
+ done: true,
+ freedBytes: 0,
+ missing: [],
+ pending: [],
+ }));
// A storage service that cannot export, so a download packs in a sandbox
// unless a case says otherwise.
plane.exportFile
@@ -575,6 +585,107 @@ describe('the public drive', () => {
});
});
+describe('analyzing and cleaning up the drive', () => {
+ const analysis = {
+ result: {
+ categories: [{ bytes: 300, category: 'other', items: 3 }],
+ items: [
+ {
+ bytes: 100,
+ category: 'other',
+ isDirectory: false,
+ path: 'projA/a.bin',
+ regenerable: false,
+ },
+ {
+ bytes: 100,
+ category: 'other',
+ isDirectory: false,
+ path: 'secret/key',
+ regenerable: false,
+ },
+ {
+ bytes: 150,
+ category: 'dependencies',
+ isDirectory: true,
+ path: 'projects',
+ regenerable: true,
+ },
+ ],
+ largestDirectories: [
+ { bytes: 200, path: 'projects' },
+ { bytes: 100, path: 'projects/secret' },
+ { bytes: 100, path: 'projA' },
+ ],
+ largestFiles: [
+ { bytes: 100, category: 'other', path: 'secret/key' },
+ { bytes: 100, category: 'other', path: 'projA/a.bin' },
+ ],
+ totalBytes: 300,
+ },
+ scannedBytes: 300,
+ status: 'done',
+ };
+
+ it('names nothing inside a hidden directory, nor the folder holding one, but keeps the totals', async () => {
+ await legacyPrivateFolder(ownerId, 'secret');
+ await legacyPrivateFolder(ownerId, 'projects/secret');
+ plane.analyzeStorage.mockResolvedValue(analysis);
+
+ const seen = await drive(memberId).analyzeStorage({ restart: true });
+
+ expect(plane.analyzeStorage).toHaveBeenCalledWith(expect.objectContaining({ restart: true }));
+ expect(seen.result?.totalBytes).toBe(300);
+ expect(seen.result?.items.map((item) => item.path)).toEqual(['projA/a.bin']);
+ expect(seen.result?.largestFiles.map((entry) => entry.path)).toEqual(['projA/a.bin']);
+ expect(seen.result?.largestDirectories.map((entry) => entry.path)).toEqual(['projA']);
+ });
+
+ it('shows the owner of a personal drive everything', async () => {
+ plane.analyzeStorage.mockResolvedValue(analysis);
+
+ const seen = await drive(ownerId).analyzeStorage({ drive: 'personal' });
+
+ expect(reached).toEqual([personalKey(ownerId)]);
+ expect(seen.result?.items).toHaveLength(3);
+ });
+
+ it('deletes a batch once, with duplicates collapsed and the flag passed on', async () => {
+ const result = await drive(memberId).deleteFiles({
+ paths: ['projA/node_modules', 'projA/node_modules', 'b.zip'],
+ regenerableOnly: true,
+ });
+
+ expect(plane.deletePaths).toHaveBeenCalledWith(
+ expect.objectContaining({ paths: ['projA/node_modules', 'b.zip'], regenerableOnly: true }),
+ );
+ expect(result.done).toBe(true);
+ });
+
+ it('refuses a batch that reaches a hidden directory, deleting nothing', async () => {
+ await legacyPrivateFolder(ownerId, 'projects/secret');
+
+ await expect(
+ drive(memberId).deleteFiles({ paths: ['projA/a.bin', 'projects'] }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'PATH_HOLDS_HIDDEN' });
+ await expect(
+ drive(memberId).deleteFiles({ paths: ['projects/secret/key'] }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(drive(memberId).deleteFiles({ paths: ['.sandbox/envs'] })).rejects.toThrow();
+ expect(plane.deletePaths).not.toHaveBeenCalled();
+ });
+
+ it('passes a refusal of non-regenerable paths through as its code', async () => {
+ plane.deletePaths.mockRejectedValue(
+ new SandboxStorageFilesError('not regenerable', 400, 'storage_paths_not_regenerable'),
+ );
+
+ await expect(
+ drive(memberId).deleteFiles({ paths: ['notes.md'], regenerableOnly: true }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: 'storage_paths_not_regenerable' });
+ });
+});
+
describe('drive usage', () => {
it("shows an admin each member's personal drive usage and nothing else of it", async () => {
await serverDB.insert(workspaceMembers).values([
diff --git a/apps/server/src/routers/lambda/sandboxStorage/cleanup.ts b/apps/server/src/routers/lambda/sandboxStorage/cleanup.ts
new file mode 100644
index 00000000000..efb5072290f
--- /dev/null
+++ b/apps/server/src/routers/lambda/sandboxStorage/cleanup.ts
@@ -0,0 +1,108 @@
+import debug from 'debug';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+import { forgetDriveFolders } from '@/server/services/sandbox';
+import type {
+ SandboxStorageAnalysis,
+ SandboxStorageAnalysisResult,
+} from '@/server/services/sandbox/storageFiles';
+
+import {
+ assertWritablePath,
+ type DriveScope,
+ holdsHidden,
+ isHidden,
+ resolveDriveScope,
+} from './driveScope';
+import { instanceProcedure, mapStorageError } from './procedures';
+import { driveSchema, relativePathSchema, topicIdSchema } from './schemas';
+
+const log = debug('lobe-server:sandbox:drive-cleanup');
+
+/** One batch, matching the storage service's own ceiling. */
+export const MAX_DELETE_PATHS = 100;
+
+/**
+ * The analysis as this member may see it. The figures stay whole — the drive's
+ * total is what its quota is judged on, hidden folders included — but no path
+ * inside a hidden folder is named, exactly as a listing leaves them out.
+ */
+export const visibleAnalysis = (
+ analysis: SandboxStorageAnalysis,
+ scope: Pick<DriveScope, 'hidden'>,
+): SandboxStorageAnalysis => {
+ if (!analysis.result || scope.hidden.length === 0) return analysis;
+
+ // Neither a path inside a hidden folder, nor one holding it: the latter's
+ // size would say how big the hidden one is, and deleting it is refused.
+ const visible = (path: string) =>
+ !isHidden(path, scope as DriveScope) && !holdsHidden(path, scope);
+ const result: SandboxStorageAnalysisResult = {
+ ...analysis.result,
+ items: analysis.result.items.filter((item) => visible(item.path)),
+ largestDirectories: analysis.result.largestDirectories.filter((entry) => visible(entry.path)),
+ largestFiles: analysis.result.largestFiles.filter((entry) => visible(entry.path)),
+ };
+
+ return { ...analysis, result };
+};
+
+export const cleanupRouter = router({
+ /**
+ * One step of the drive's space analysis. A large drive takes several:
+ * the client calls again while `status` is not `done`. Not quota gated —
+ * this is how a drive over its limit is emptied.
+ */
+ analyzeStorage: instanceProcedure
+ .input(
+ z.object({
+ drive: driveSchema,
+ restart: z.boolean().optional(),
+ top: z.number().int().min(1).max(200).optional(),
+ topicId: topicIdSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input: { drive: _drive, ...input } }) => {
+ const scope = await resolveDriveScope(ctx);
+ const analysis = await scope.client.analyzeStorage(input).catch(mapStorageError);
+
+ return visibleAnalysis(analysis, scope);
+ }),
+
+ /**
+ * Delete several files or folders for good. The confirmation is the
+ * client's to ask for; this layer only refuses what the member may not
+ * touch: a hidden folder, or one that holds one.
+ */
+ deleteFiles: instanceProcedure
+ .input(
+ z.object({
+ drive: driveSchema,
+ paths: z.array(relativePathSchema).min(1).max(MAX_DELETE_PATHS),
+ regenerableOnly: z.boolean().optional(),
+ topicId: topicIdSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input: { drive: _drive, ...input } }) => {
+ const scope = await resolveDriveScope(ctx);
+ for (const path of input.paths) assertWritablePath(path, scope);
+
+ const paths = [...new Set(input.paths)];
+ const result = await scope.client.deletePaths({ ...input, paths }).catch(mapStorageError);
+ forgetDriveFolders(ctx.claim.key);
+ // Deleting cannot be undone, so each one leaves a line saying who and how much.
+ log(
+ 'user %s deleted from %s: %d paths, regenerableOnly=%s, freed %d bytes, %d pending, %d failed',
+ ctx.userId,
+ ctx.claim.key,
+ paths.length,
+ !!input.regenerableOnly,
+ result.freedBytes,
+ result.pending.length,
+ result.failed?.length ?? 0,
+ );
+
+ return result;
+ }),
+});
diff --git a/apps/server/src/routers/lambda/sandboxStorage/driveScope.ts b/apps/server/src/routers/lambda/sandboxStorage/driveScope.ts
index 3ccb3ce5f70..5fc9daff923 100644
--- a/apps/server/src/routers/lambda/sandboxStorage/driveScope.ts
+++ b/apps/server/src/routers/lambda/sandboxStorage/driveScope.ts
@@ -165,14 +165,23 @@ export const resolveWritableScope = async (
if (instanceId) throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_READ_ONLY' });
const scope = await resolveDriveScope(ctx);
+ assertWritablePath(path, scope);
+
+ return scope;
+};
+
+/** Whether `path` is a folder that holds a hidden one, which a write would carry into the open. */
+export const holdsHidden = (path: string, scope: Pick<DriveScope, 'hidden'>) =>
+ scope.hidden.some((directory) => isPathWithin(directory, path));
+
+/** Refuses a write to `path`: outside the scope, hidden, or holding something hidden. */
+export const assertWritablePath = (path: string, scope: DriveScope) => {
assertReadable(path, scope);
// Refused without naming what is inside: the caller can see this folder,
// so "not found" would be false, and the hidden one stays unnamed.
- if (scope.hidden.some((directory) => isPathWithin(directory, path))) {
+ if (holdsHidden(path, scope)) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_HOLDS_HIDDEN' });
}
-
- return scope;
};
/** Names the instance a file route works in; see {@link resolveDriveScope}. */
diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts
index befcd60c4fc..eb116e42ee1 100644
--- a/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts
@@ -30,11 +30,13 @@ function expected(): Array<
[name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]
> {
return [
+ ['analyzeStorage', 'mutation', 15],
['copyInstance', 'mutation', 15],
['createDirectory', 'mutation', 15],
['createEnvironment', 'mutation', 15],
['createInstance', 'mutation', 15],
['createInstanceForEnvironment', 'mutation', 15],
+ ['deleteFiles', 'mutation', 15],
['getDriveUsage', 'query', 12],
['getEntitlement', 'query', 11],
['getInstance', 'query', 15],
diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.ts b/apps/server/src/routers/lambda/sandboxStorage/index.ts
index f6b52285ae4..0df57f4e34b 100644
--- a/apps/server/src/routers/lambda/sandboxStorage/index.ts
+++ b/apps/server/src/routers/lambda/sandboxStorage/index.ts
@@ -1,5 +1,6 @@
import { mergeRouters } from '@/libs/trpc/lambda';
+import { cleanupRouter } from './cleanup';
import { downloadRouter } from './download';
import { filesRouter } from './files';
import { instanceBuildRouter } from './instanceBuild';
@@ -24,6 +25,7 @@ import { storageRouter } from './storage';
*/
export const sandboxStorageRouter = mergeRouters(
filesRouter,
+ cleanupRouter,
downloadRouter,
storageRouter,
instancesRouter,
diff --git a/apps/server/src/services/sandbox/storageFiles.ts b/apps/server/src/services/sandbox/storageFiles.ts
index 252dd211401..8d057b2d50f 100644
--- a/apps/server/src/services/sandbox/storageFiles.ts
+++ b/apps/server/src/services/sandbox/storageFiles.ts
@@ -26,6 +26,67 @@ export interface SandboxStorageFileEntry {
size?: number;
}
+/**
+ * What a drive's space goes to, in the categories the storage analysis sorts
+ * it into. `dependencies` and `cache` (caches and build output) can be
+ * regenerated; the rest cannot, and `environments` is the runtime's own
+ * snapshot store, deleted through the environment, never as files.
+ */
+export const SANDBOX_STORAGE_CATEGORIES = [
+ 'dependencies',
+ 'cache',
+ 'archives',
+ 'media',
+ 'git',
+ 'environments',
+ 'other',
+] as const;
+
+export type SandboxStorageCategory = (typeof SANDBOX_STORAGE_CATEGORIES)[number];
+
+export interface SandboxStorageAnalysisItem {
+ bytes: number;
+ category: SandboxStorageCategory;
+ /** `environments` only: the stored environment (instance id) this is. */
+ environment?: string;
+ isDirectory: boolean;
+ /** Relative to the drive's root. */
+ path: string;
+ /** Deletable without asking: a dependency directory, a cache or build output. */
+ regenerable: boolean;
+}
+
+export interface SandboxStorageAnalysisResult {
+ categories: { bytes: number; category: SandboxStorageCategory; items: number }[];
+ items: SandboxStorageAnalysisItem[];
+ largestDirectories: { bytes: number; path: string }[];
+ largestFiles: { bytes: number; category: SandboxStorageCategory; path: string }[];
+ /** A delete since the scan could not be subtracted exactly; scan again for exact figures. */
+ stale?: boolean;
+ totalBytes: number;
+}
+
+export interface SandboxStorageAnalysis {
+ finishedAt?: string;
+ /** Snapshot so far while scanning; the final figures once `done`. */
+ result?: SandboxStorageAnalysisResult;
+ scannedBytes: number;
+ startedAt?: string;
+ /** `scanning`: this call advanced the scan; `running`: another call is advancing it. */
+ status: 'done' | 'running' | 'scanning';
+}
+
+export interface SandboxStorageDeleteResult {
+ deleted: string[];
+ /** Everything requested is gone or failed; otherwise call again with `pending`. */
+ done: boolean;
+ /** Paths the volume refused to remove (permissions, busy); the rest of the batch still ran. */
+ failed?: { message: string; path: string }[];
+ freedBytes: number;
+ missing: string[];
+ pending: string[];
+}
+
export interface SandboxStorageExportResult {
contentType: string;
kind: 'directory' | 'file';
@@ -305,6 +366,41 @@ export const createSandboxStorageClient = ({ baseURL, headers }: SandboxStorageC
});
},
+ /**
+ * One step of the drive's space analysis: what takes the space, by
+ * category, with the largest files and folders. A large drive takes
+ * several steps — call again while `status` is not `done`. A finished
+ * analysis is reused for a while unless `restart`. Not quota gated, and
+ * no sandbox session: it is how an over-quota drive is emptied.
+ */
+ analyzeStorage: async (
+ params: RequestContext & { restart?: boolean; top?: number } = {},
+ ): Promise<SandboxStorageAnalysis> =>
+ request(`${CURRENT_STORAGE}/analysis`, {
+ body: JSON.stringify({ restart: params.restart, top: params.top, topicId: params.topicId }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ }),
+
+ /**
+ * Delete several files or folders at once, for good. Not quota gated.
+ * With `regenerableOnly` the storage service refuses the whole call
+ * (`storage_paths_not_regenerable`) unless every path is a dependency
+ * directory, a cache or build output, or inside one.
+ */
+ deletePaths: async (
+ params: RequestContext & { paths: string[]; regenerableOnly?: boolean },
+ ): Promise<SandboxStorageDeleteResult> =>
+ request(`${CURRENT_STORAGE}/files/delete`, {
+ body: JSON.stringify({
+ paths: params.paths,
+ regenerableOnly: params.regenerableOnly,
+ topicId: params.topicId,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ }),
+
deleteFile: async (
params: RequestContext & { path: string; recursive?: boolean },
): Promise<{ path: string }> => {
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 97209d38ed5..718c041f793 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -315,6 +315,8 @@
"builtins.lobe-claude-code.worktree.remove.failed": "Failed to remove worktree",
"builtins.lobe-claude-code.worktree.remove.idle": "Remove worktree",
"builtins.lobe-claude-code.worktree.remove.loading": "Removing worktree",
+ "builtins.lobe-cloud-sandbox.apiName.analyzeStorage": "Analyze drive space",
+ "builtins.lobe-cloud-sandbox.apiName.deleteFiles": "Delete files",
"builtins.lobe-cloud-sandbox.apiName.editFile": "Edit file",
"builtins.lobe-cloud-sandbox.apiName.editLocalFile": "Edit file",
"builtins.lobe-cloud-sandbox.apiName.executeCode": "Execute code",
@@ -336,6 +338,8 @@
"builtins.lobe-cloud-sandbox.apiName.searchLocalFiles": "Search files",
"builtins.lobe-cloud-sandbox.apiName.writeFile": "Write file",
"builtins.lobe-cloud-sandbox.apiName.writeLocalFile": "Write file",
+ "builtins.lobe-cloud-sandbox.deleteFiles.irreversible": "Deleted files can’t be recovered. The drive has no trash.",
+ "builtins.lobe-cloud-sandbox.deleteFiles.title": "Permanently delete {{count}} items from the drive:",
"builtins.lobe-cloud-sandbox.inspector.noResults": "No results",
"builtins.lobe-cloud-sandbox.title": "Cloud Sandbox",
"builtins.lobe-computer-use.apiName.runCommand": "Use computer",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 7dda75a5458..4dc5690af2f 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -619,6 +619,59 @@
"devices.visibilityTabs.private": "Private",
"devices.visibilityTabs.workspace": "Workspace",
"devices.workingDirectory": "Working dir: {{path}}",
+ "drive.cleanup.back": "Back to files",
+ "drive.cleanup.category.archives": "Archives",
+ "drive.cleanup.category.cache": "Caches and build output",
+ "drive.cleanup.category.dependencies": "Dependencies",
+ "drive.cleanup.category.environments": "Environment snapshots",
+ "drive.cleanup.category.git": "Git repositories",
+ "drive.cleanup.category.media": "Media",
+ "drive.cleanup.category.other": "Other files",
+ "drive.cleanup.categoryHint.archives": ".zip, .tar.gz and other archives",
+ "drive.cleanup.categoryHint.cache": "Caches and build output. The next run or build recreates them.",
+ "drive.cleanup.categoryHint.dependencies": "node_modules, .venv and other installed packages. Reinstalling restores them.",
+ "drive.cleanup.categoryHint.environments": "Saved code environments",
+ "drive.cleanup.categoryHint.git": ".git history. Deleting it removes local commits that were never pushed.",
+ "drive.cleanup.categoryHint.media": "Images, video and audio",
+ "drive.cleanup.categoryHint.other": "Everything else",
+ "drive.cleanup.collapse": "Hide items",
+ "drive.cleanup.confirm.acknowledge": "I understand these files can’t be recovered",
+ "drive.cleanup.confirm.irreversible": "Deleted files can’t be recovered",
+ "drive.cleanup.confirm.irreversibleHint": "The drive has no trash. Download anything you want to keep first.",
+ "drive.cleanup.confirm.ok": "Delete {{count}} items",
+ "drive.cleanup.confirm.regenerableHint": "These are dependencies, caches or build output. Reinstall or rebuild to get them back.",
+ "drive.cleanup.confirm.summary": "{{count}} items, {{size}} in total, will be deleted from the drive.",
+ "drive.cleanup.confirm.title": "Delete {{count}} items?",
+ "drive.cleanup.delete": "Delete selected",
+ "drive.cleanup.deleteFailed": "Couldn’t delete the selected items. Try again.",
+ "drive.cleanup.description": "See what takes up the drive and delete what you no longer need.",
+ "drive.cleanup.empty": "Nothing on this drive takes up space yet.",
+ "drive.cleanup.entry": "Analyze space",
+ "drive.cleanup.environmentsHint": "Environment snapshots are deleted together with their environment, on the Environments page.",
+ "drive.cleanup.expand": "Show items",
+ "drive.cleanup.failed": "Couldn’t analyze the drive. Try again.",
+ "drive.cleanup.failedAndPending": "{{failed}} items couldn’t be deleted and {{pending}} are still being deleted. Delete again to finish.",
+ "drive.cleanup.freed": "Deleted. {{size}} freed.",
+ "drive.cleanup.holdsHidden": "This folder holds a private environment directory and can’t be deleted here.",
+ "drive.cleanup.incomplete": "Scan stopped · {{size}} counted, figures are incomplete",
+ "drive.cleanup.moreItems": "{{count}} smaller items not listed",
+ "drive.cleanup.notRegenerable": "Some of these files can’t be regenerated, so deleting them needs your confirmation.",
+ "drive.cleanup.open": "Analyze and free up space",
+ "drive.cleanup.overQuota": "This drive is {{size}} over its quota",
+ "drive.cleanup.overQuotaHint": "Saving files and running terminal commands are blocked until you free up space.",
+ "drive.cleanup.partial": "{{count}} items are still being deleted. Delete them again to finish.",
+ "drive.cleanup.regenerable": "Regenerable",
+ "drive.cleanup.rescan": "Scan again",
+ "drive.cleanup.scanning": "Scanning · {{size}} counted so far",
+ "drive.cleanup.scanningFirst": "Scanning the drive. A large drive takes a few minutes.",
+ "drive.cleanup.scopeChanged": "The workspace changed, so nothing was deleted. Choose again in this workspace.",
+ "drive.cleanup.selectHint": "Select items, or a whole category, to delete",
+ "drive.cleanup.selected": "{{count}} selected · {{size}}",
+ "drive.cleanup.someFailed": "{{count}} items couldn’t be deleted. The rest were deleted.",
+ "drive.cleanup.stale": "Some figures are estimates after the last cleanup. Scan again for exact figures.",
+ "drive.cleanup.summary": "{{size}} in total",
+ "drive.cleanup.title": "Space analysis and cleanup",
+ "drive.cleanup.unavailable": "Space analysis isn’t available on this deployment yet.",
"drive.explorer.columns.kind": "Kind",
"drive.explorer.columns.modified": "Date modified",
"drive.explorer.columns.name": "Name",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 3936edbb4f2..561590d3a76 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -315,6 +315,8 @@
"builtins.lobe-claude-code.worktree.remove.failed": "删除工作树失败",
"builtins.lobe-claude-code.worktree.remove.idle": "删除工作树",
"builtins.lobe-claude-code.worktree.remove.loading": "正在删除工作树",
+ "builtins.lobe-cloud-sandbox.apiName.analyzeStorage": "分析网盘空间",
+ "builtins.lobe-cloud-sandbox.apiName.deleteFiles": "删除文件",
"builtins.lobe-cloud-sandbox.apiName.editFile": "编辑文件",
"builtins.lobe-cloud-sandbox.apiName.editLocalFile": "编辑文件",
"builtins.lobe-cloud-sandbox.apiName.executeCode": "执行代码",
@@ -336,6 +338,8 @@
"builtins.lobe-cloud-sandbox.apiName.searchLocalFiles": "搜索文件",
"builtins.lobe-cloud-sandbox.apiName.writeFile": "写入文件",
"builtins.lobe-cloud-sandbox.apiName.writeLocalFile": "写入文件",
+ "builtins.lobe-cloud-sandbox.deleteFiles.irreversible": "删除后无法找回,网盘没有回收站。",
+ "builtins.lobe-cloud-sandbox.deleteFiles.title": "从网盘永久删除以下 {{count}} 个项目:",
"builtins.lobe-cloud-sandbox.inspector.noResults": "无结果",
"builtins.lobe-cloud-sandbox.title": "云端沙盒",
"builtins.lobe-computer-use.apiName.runCommand": "操作电脑",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index e583058fc4e..3026a90e4e5 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -619,6 +619,59 @@
"devices.visibilityTabs.private": "私人",
"devices.visibilityTabs.workspace": "工作区",
"devices.workingDirectory": "工作目录:{{path}}",
+ "drive.cleanup.back": "返回文件",
+ "drive.cleanup.category.archives": "压缩包",
+ "drive.cleanup.category.cache": "缓存与构建产物",
+ "drive.cleanup.category.dependencies": "依赖",
+ "drive.cleanup.category.environments": "环境快照",
+ "drive.cleanup.category.git": "Git 仓库",
+ "drive.cleanup.category.media": "媒体",
+ "drive.cleanup.category.other": "其他文件",
+ "drive.cleanup.categoryHint.archives": ".zip、.tar.gz 等压缩包",
+ "drive.cleanup.categoryHint.cache": "缓存和构建产物,下次运行或构建时会重新生成。",
+ "drive.cleanup.categoryHint.dependencies": "node_modules、.venv 等已安装的包,重新安装即可恢复。",
+ "drive.cleanup.categoryHint.environments": "保存的代码环境",
+ "drive.cleanup.categoryHint.git": ".git 历史。删除后,没推送的本地提交会一起丢失。",
+ "drive.cleanup.categoryHint.media": "图片、视频和音频",
+ "drive.cleanup.categoryHint.other": "其余所有文件",
+ "drive.cleanup.collapse": "收起",
+ "drive.cleanup.confirm.acknowledge": "我知道这些文件删除后无法找回",
+ "drive.cleanup.confirm.irreversible": "删除后无法找回",
+ "drive.cleanup.confirm.irreversibleHint": "网盘没有回收站,需要保留的文件请先下载。",
+ "drive.cleanup.confirm.ok": "删除 {{count}} 个项目",
+ "drive.cleanup.confirm.regenerableHint": "这些是依赖、缓存或构建产物,重新安装或构建即可恢复。",
+ "drive.cleanup.confirm.summary": "将从网盘删除 {{count}} 个项目,共 {{size}}。",
+ "drive.cleanup.confirm.title": "删除 {{count}} 个项目?",
+ "drive.cleanup.delete": "删除所选",
+ "drive.cleanup.deleteFailed": "无法删除所选项目,请重试。",
+ "drive.cleanup.description": "查看网盘空间被什么占用,删掉不再需要的内容。",
+ "drive.cleanup.empty": "这个网盘还没有占用空间的内容。",
+ "drive.cleanup.entry": "空间分析",
+ "drive.cleanup.environmentsHint": "环境快照会随环境一起删除,请在「环境」页面操作。",
+ "drive.cleanup.expand": "展开",
+ "drive.cleanup.failed": "无法分析网盘,请重试。",
+ "drive.cleanup.failedAndPending": "有 {{failed}} 个项目无法删除,还有 {{pending}} 个没删完,再删除一次即可完成。",
+ "drive.cleanup.freed": "已删除,释放了 {{size}}。",
+ "drive.cleanup.holdsHidden": "这个文件夹里有私有环境目录,不能在这里删除。",
+ "drive.cleanup.incomplete": "扫描中断 · 已统计 {{size}},数字不完整",
+ "drive.cleanup.moreItems": "还有 {{count}} 个较小的项目未列出",
+ "drive.cleanup.notRegenerable": "其中有无法重新生成的文件,删除需要你确认。",
+ "drive.cleanup.open": "分析并清理空间",
+ "drive.cleanup.overQuota": "网盘已超出配额 {{size}}",
+ "drive.cleanup.overQuotaHint": "腾出空间之前,保存文件和运行终端命令都会被拦截。",
+ "drive.cleanup.partial": "还有 {{count}} 个项目没删完,再删除一次即可完成。",
+ "drive.cleanup.regenerable": "可再生",
+ "drive.cleanup.rescan": "重新扫描",
+ "drive.cleanup.scanning": "正在扫描 · 已统计 {{size}}",
+ "drive.cleanup.scanningFirst": "正在扫描网盘,较大的网盘需要几分钟。",
+ "drive.cleanup.scopeChanged": "工作区已切换,没有删除任何内容。请在当前工作区重新选择。",
+ "drive.cleanup.selectHint": "勾选要删除的项目,或整个类别",
+ "drive.cleanup.selected": "已选 {{count}} 项 · {{size}}",
+ "drive.cleanup.someFailed": "有 {{count}} 个项目无法删除,其余已删除。",
+ "drive.cleanup.stale": "清理后部分数字是估算值,重新扫描可得到准确数字。",
+ "drive.cleanup.summary": "共 {{size}}",
+ "drive.cleanup.title": "空间分析与清理",
+ "drive.cleanup.unavailable": "当前部署暂不支持空间分析。",
"drive.explorer.columns.kind": "种类",
"drive.explorer.columns.modified": "修改日期",
"drive.explorer.columns.name": "名称",
diff --git a/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts b/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts
index 9be6e373f70..8b166193b01 100644
--- a/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/ExecutionRuntime/index.ts
@@ -3,6 +3,8 @@ import { ComputerRuntime } from '@lobechat/tool-runtime';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import type {
+ AnalyzeStorageParams,
+ DeleteFilesParams,
ExecuteCodeParams,
ExecuteCodeState,
ExportFileParams,
@@ -11,6 +13,9 @@ import type {
SandboxCallToolResult,
} from '../types';
+const stringify = (value: unknown) =>
+ typeof value === 'string' ? value : JSON.stringify(value ?? null);
+
/**
* Cloud Sandbox Execution Runtime
*
@@ -88,6 +93,58 @@ export class CloudSandboxExecutionRuntime extends ComputerRuntime {
}
}
+ // ==================== Cloud-Specific: Drive Space ====================
+
+ /**
+ * What takes up the persistent drive, by category, with the largest items.
+ * Answered by the storage service off the volume — no command runs — so it
+ * works on a drive over its quota, where every shell command is refused.
+ */
+ async analyzeStorage(args: AnalyzeStorageParams = {}): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ // Capped so the listing stays a reasonable share of the model's context.
+ const top = typeof args.top === 'number' ? Math.min(Math.max(1, args.top), 50) : undefined;
+ const result = await this.callService('analyzeStorage', { top });
+ if (!result.success) return this.serviceFailure(result, 'Failed to analyze the drive', true);
+
+ return { content: stringify(result.result), state: result.result, success: true };
+ } catch (error) {
+ return this.handleError(error, true);
+ }
+ }
+
+ /**
+ * Delete files or folders on the persistent drive for good, past the quota.
+ * Whether the user is asked first is the manifest's dynamic audit; the
+ * storage service enforces `regenerableOnly` on the volume itself.
+ */
+ async deleteFiles(args: DeleteFilesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.callService('deleteFiles', {
+ paths: args.paths,
+ regenerableOnly: args.regenerableOnly === true,
+ });
+ if (!result.success) return this.serviceFailure(result, 'Failed to delete the files');
+
+ return { content: stringify(result.result), state: result.result, success: true };
+ } catch (error) {
+ return this.handleError(error);
+ }
+ }
+
+ private serviceFailure(
+ result: SandboxCallToolResult,
+ fallback: string,
+ retrySafe = false,
+ ): BuiltinServerRuntimeOutput {
+ const message = result.error?.message || fallback;
+ return {
+ content: message,
+ error: { ...result.error, kind: retrySafe ? undefined : 'stop', message },
+ success: false,
+ };
+ }
+
// ==================== Cloud-Specific: File Export ====================
/**
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Intervention/DeleteFiles/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Intervention/DeleteFiles/index.tsx
new file mode 100644
index 00000000000..b8356d822a0
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Intervention/DeleteFiles/index.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import type { BuiltinInterventionProps } from '@lobechat/types';
+import { Alert, Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DeleteFilesParams } from '../../../types';
+
+/**
+ * Approval for a permanent delete on the drive: every path, and — before the
+ * user approves — that what goes cannot be brought back. The drive has no
+ * trash, so this card is the last chance to say no.
+ */
+const DeleteFiles = memo<BuiltinInterventionProps<DeleteFilesParams>>(({ args }) => {
+ const { t } = useTranslation('plugin');
+ const paths = Array.isArray(args?.paths) ? [...new Set(args.paths)] : [];
+
+ return (
+ <Flexbox gap={8}>
+ <Alert
+ showIcon
+ title={t('builtins.lobe-cloud-sandbox.deleteFiles.irreversible')}
+ type={'error'}
+ variant={'soft'}
+ />
+ <Text>{t('builtins.lobe-cloud-sandbox.deleteFiles.title', { count: paths.length })}</Text>
+ <Flexbox gap={4}>
+ {paths.map((path) => (
+ <Text code ellipsis as={'span'} fontSize={12} key={path}>
+ {path}
+ </Text>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+DeleteFiles.displayName = 'CloudSandboxDeleteFilesIntervention';
+
+export default DeleteFiles;
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Intervention/index.ts b/packages/builtin-tool-cloud-sandbox/src/client/Intervention/index.ts
index d532e014891..95a747ef24a 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Intervention/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Intervention/index.ts
@@ -1,4 +1,5 @@
import { CloudSandboxApiName } from '../../types';
+import DeleteFiles from './DeleteFiles';
import EditLocalFile from './EditLocalFile';
import ExecuteCode from './ExecuteCode';
import MoveLocalFiles from './MoveLocalFiles';
@@ -12,6 +13,7 @@ import WriteFile from './WriteFile';
* messages with apiName like 'editLocalFile' still resolve after the rename.
*/
export const CloudSandboxInterventions = {
+ [CloudSandboxApiName.deleteFiles]: DeleteFiles,
[CloudSandboxApiName.editFile]: EditLocalFile,
[CloudSandboxApiName.executeCode]: ExecuteCode,
[CloudSandboxApiName.moveFiles]: MoveLocalFiles,
diff --git a/packages/builtin-tool-cloud-sandbox/src/executor/index.ts b/packages/builtin-tool-cloud-sandbox/src/executor/index.ts
index e613f78b65c..c4e755995ad 100644
--- a/packages/builtin-tool-cloud-sandbox/src/executor/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/executor/index.ts
@@ -8,6 +8,8 @@ import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
import { CloudSandboxExecutionRuntime } from '../ExecutionRuntime';
import { CloudSandboxIdentifier } from '../manifest';
import type {
+ AnalyzeStorageParams,
+ DeleteFilesParams,
EditLocalFileParams,
ExecuteCodeParams,
ExportFileParams,
@@ -140,6 +142,24 @@ class CloudSandboxExecutor extends BaseExecutor<typeof CloudSandboxApiName> {
// ==================== Code Execution ====================
+ analyzeStorage = async (
+ params: AnalyzeStorageParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const runtime = this.getRuntime(ctx);
+ const result = await runtime.analyzeStorage(params);
+ return this.toBuiltinResult(result);
+ };
+
+ deleteFiles = async (
+ params: DeleteFilesParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const runtime = this.getRuntime(ctx);
+ const result = await runtime.deleteFiles(params);
+ return this.toBuiltinResult(result);
+ };
+
executeCode = async (
params: ExecuteCodeParams,
ctx: BuiltinToolContext,
diff --git a/packages/builtin-tool-cloud-sandbox/src/index.ts b/packages/builtin-tool-cloud-sandbox/src/index.ts
index 79adef26f0f..fcde1ee640d 100644
--- a/packages/builtin-tool-cloud-sandbox/src/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/index.ts
@@ -1,3 +1,4 @@
+export * from './interventionAudit';
export * from './manifest';
export * from './projectCheckout';
export * from './systemRole';
diff --git a/packages/builtin-tool-cloud-sandbox/src/interventionAudit.ts b/packages/builtin-tool-cloud-sandbox/src/interventionAudit.ts
new file mode 100644
index 00000000000..ecacb3de090
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/interventionAudit.ts
@@ -0,0 +1,16 @@
+import type { DynamicInterventionResolver } from '@lobechat/types';
+
+/** Registry key of the `deleteFiles` approval audit (see `dynamicInterventionAudits`). */
+export const CLOUD_SANDBOX_DELETE_AUDIT = 'cloudSandboxDeleteAudit';
+
+/**
+ * Deleting from the drive is permanent, so a `deleteFiles` call asks the user
+ * first — unless it is flagged `regenerableOnly`. That flag is not taken on
+ * trust: the storage service refuses the whole call when any path is not a
+ * dependency directory, a cache or build output (checked on the volume, not
+ * by name alone), so what runs unattended is only what an install or build
+ * puts back. Anything else, a missing flag included, asks — with the
+ * manifest's `always` policy, so auto-run mode cannot skip it either.
+ */
+export const deleteFilesAudit: DynamicInterventionResolver = async (toolArgs) =>
+ toolArgs?.regenerableOnly !== true;
diff --git a/packages/builtin-tool-cloud-sandbox/src/manifest.ts b/packages/builtin-tool-cloud-sandbox/src/manifest.ts
index 4fb1dd1f8d5..d4e9e7ecb82 100644
--- a/packages/builtin-tool-cloud-sandbox/src/manifest.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/manifest.ts
@@ -1,5 +1,6 @@
import type { BuiltinToolManifest } from '@lobechat/types';
+import { CLOUD_SANDBOX_DELETE_AUDIT } from './interventionAudit';
import { systemPrompt } from './systemRole';
import { CloudSandboxApiName } from './types';
@@ -308,6 +309,45 @@ export const CloudSandboxManifest: BuiltinToolManifest = {
type: 'object',
},
},
+ {
+ description:
+ 'Analyze what takes up space on the persistent drive: totals by category (dependencies, caches and build output, archives, media, git, environment snapshots, other), the largest items of each with their absolute paths and whether they are regenerable, and the largest files and folders. Works when the drive is over its quota. A large drive may need several calls: when the result says it is not done, call again to continue.',
+ name: CloudSandboxApiName.analyzeStorage,
+ parameters: {
+ properties: {
+ top: {
+ description: 'How many of the largest items to list per category (default 20, max 50).',
+ type: 'number',
+ },
+ },
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Permanently delete files or folders on the persistent drive, to free space. Works when the drive is over its quota, when shell commands are refused. Deleted files cannot be recovered. Set regenerableOnly to true when every path is a dependency directory, a cache or build output (the "regenerable" items from analyzeStorage): such a call runs without asking the user, and is refused as a whole if any path is not regenerable. Any other deletion always asks the user to confirm first, even in auto-run mode, so tell the user what you are deleting and why.',
+ humanIntervention: {
+ dynamic: { default: 'never', policy: 'always', type: CLOUD_SANDBOX_DELETE_AUDIT },
+ },
+ name: CloudSandboxApiName.deleteFiles,
+ parameters: {
+ properties: {
+ paths: {
+ description:
+ 'Absolute paths, or paths relative to the working directory, of the files or folders to delete (at most 100).',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ regenerableOnly: {
+ description:
+ 'True only when every path is a dependency directory, cache or build output. Lets the deletion run without the user confirming.',
+ type: 'boolean',
+ },
+ },
+ required: ['paths'],
+ type: 'object',
+ },
+ },
],
identifier: CloudSandboxIdentifier,
meta: {
diff --git a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
index 6e1f2ce7294..064ed80fdf6 100644
--- a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
@@ -98,6 +98,12 @@ You have access to the following tools for interacting with the cloud sandbox:
11. **searchFiles**: Search for files based on keywords and criteria.
12. **grepContent**: Search for content within files using regex patterns.
13. **globFiles**: Find files matching glob patterns (e.g., "**/*.js").
+
+**Drive Space (persistent drive only):**
+14. **analyzeStorage**: Shows what takes up the drive, by category, with the largest items, their absolute paths and whether they are regenerable. Call again while it reports it is not done.
+15. **deleteFiles**: Permanently deletes files or folders. Both work when the drive is over its quota.
+
+When a command or write is refused because the drive is over its storage quota, shell commands (including \`rm\`) stay blocked until usage is back under the limit — do not retry them. Instead: call **analyzeStorage**; delete regenerable items (dependency directories, caches, build output) with **deleteFiles** and \`regenerableOnly: true\`, which runs without asking; for anything else, explain to the user what you want to delete and why, then call **deleteFiles** without the flag, which asks the user to confirm. Deleted files cannot be recovered. Never move files to \`/tmp\` to get around the quota: they are lost when the session ends.
</core_capabilities>
diff --git a/packages/builtin-tool-cloud-sandbox/src/types/api.ts b/packages/builtin-tool-cloud-sandbox/src/types/api.ts
index e1631a6e973..e23e527ba8b 100644
--- a/packages/builtin-tool-cloud-sandbox/src/types/api.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/types/api.ts
@@ -2,6 +2,8 @@
* API names for Cloud Sandbox tool
*/
export const CloudSandboxApiName = {
+ analyzeStorage: 'analyzeStorage',
+ deleteFiles: 'deleteFiles',
editFile: 'editFile',
executeCode: 'executeCode',
exportFile: 'exportFile',
diff --git a/packages/builtin-tool-cloud-sandbox/src/types/params.ts b/packages/builtin-tool-cloud-sandbox/src/types/params.ts
index b29de23ad7b..a831fab9dfb 100644
--- a/packages/builtin-tool-cloud-sandbox/src/types/params.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/types/params.ts
@@ -83,3 +83,14 @@ export interface GrepContentParams {
pattern: string;
recursive?: boolean;
}
+
+// ==================== Drive Space Params ====================
+
+export interface AnalyzeStorageParams {
+ top?: number;
+}
+
+export interface DeleteFilesParams {
+ paths: string[];
+ regenerableOnly?: boolean;
+}
diff --git a/packages/builtin-tools/src/dynamicInterventionAudits.test.ts b/packages/builtin-tools/src/dynamicInterventionAudits.test.ts
index 612acc5cce4..f940d13cacc 100644
--- a/packages/builtin-tools/src/dynamicInterventionAudits.test.ts
+++ b/packages/builtin-tools/src/dynamicInterventionAudits.test.ts
@@ -1,3 +1,7 @@
+import {
+ CLOUD_SANDBOX_DELETE_AUDIT,
+ CloudSandboxManifest,
+} from '@lobechat/builtin-tool-cloud-sandbox';
import { DASHBOARD_DRY_RUN_AUDIT, DashboardManifest } from '@lobechat/builtin-tool-dashboard';
import { describe, expect, it } from 'vitest';
@@ -5,7 +9,7 @@ import { dynamicInterventionAudits } from './dynamicInterventionAudits';
describe('dynamicInterventionAudits', () => {
it('registers every dynamic audit a builtin manifest references', () => {
- const referenced = DashboardManifest.api
+ const referenced = [...DashboardManifest.api, ...CloudSandboxManifest.api]
.map((api) => api.humanIntervention)
.filter((config): config is { dynamic: { type: string } } =>
Boolean(config && typeof config === 'object' && 'dynamic' in config),
@@ -13,6 +17,7 @@ describe('dynamicInterventionAudits', () => {
.map((config) => config.dynamic.type);
expect(referenced).toContain(DASHBOARD_DRY_RUN_AUDIT);
+ expect(referenced).toContain(CLOUD_SANDBOX_DELETE_AUDIT);
for (const type of referenced) expect(dynamicInterventionAudits).toHaveProperty(type);
});
@@ -22,4 +27,23 @@ describe('dynamicInterventionAudits', () => {
dynamicInterventionAudits[DASHBOARD_DRY_RUN_AUDIT]({ versionId: 'v1', widgetId: 'w1' }),
).resolves.toBe(true);
});
+
+ it('asks before a sandbox delete unless every path is claimed regenerable', async () => {
+ const audit = dynamicInterventionAudits[CLOUD_SANDBOX_DELETE_AUDIT];
+ // `always`: auto-run mode cannot skip a permanent delete of irreplaceable files.
+ expect(
+ CloudSandboxManifest.api.find((api) => api.name === 'deleteFiles')?.humanIntervention,
+ ).toEqual({
+ dynamic: { default: 'never', policy: 'always', type: CLOUD_SANDBOX_DELETE_AUDIT },
+ });
+
+ await expect(audit({ paths: ['/workspace/notes.md'] })).resolves.toBe(true);
+ await expect(audit({ paths: ['/workspace/a'], regenerableOnly: false })).resolves.toBe(true);
+ // A truthy non-boolean is not the flag the storage service enforces.
+ await expect(audit({ paths: ['/workspace/a'], regenerableOnly: 'true' })).resolves.toBe(true);
+ await expect(audit({})).resolves.toBe(true);
+ await expect(
+ audit({ paths: ['/workspace/app/node_modules'], regenerableOnly: true }),
+ ).resolves.toBe(false);
+ });
});
diff --git a/packages/builtin-tools/src/dynamicInterventionAudits.ts b/packages/builtin-tools/src/dynamicInterventionAudits.ts
index bdbde686094..2bcfe47fcaa 100644
--- a/packages/builtin-tools/src/dynamicInterventionAudits.ts
+++ b/packages/builtin-tools/src/dynamicInterventionAudits.ts
@@ -2,6 +2,7 @@ import {
AGENT_ACCOUNT_OUTBOUND_AUDIT,
agentAccountOutboundAudit,
} from '@lobechat/builtin-tool-agent-account';
+import { CLOUD_SANDBOX_DELETE_AUDIT, deleteFilesAudit } from '@lobechat/builtin-tool-cloud-sandbox';
import { createDryRunAudit, DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
import { pathScopeAudit } from '@lobechat/builtin-tool-local-system';
import { type DynamicInterventionResolver } from '@lobechat/types';
@@ -12,5 +13,8 @@ export const dynamicInterventionAudits: Record<string, DynamicInterventionResolv
// register a loader-backed audit under the same key.
[DASHBOARD_DRY_RUN_AUDIT]: createDryRunAudit(),
[AGENT_ACCOUNT_OUTBOUND_AUDIT]: agentAccountOutboundAudit,
+ // Permanent deletion asks, unless the storage service will itself refuse
+ // anything that is not a dependency, cache or build output.
+ [CLOUD_SANDBOX_DELETE_AUDIT]: deleteFilesAudit,
pathScopeAudit,
};
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 900fa2e7ab2..af9974c5dd2 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -270,6 +270,8 @@ export default {
'builtins.github.render.updatedAt': 'Updated {{time}}',
'builtins.linear.render.empty': 'No {{collection}} found',
'builtins.linear.render.updatedAt': 'Updated {{time}}',
+ 'builtins.lobe-cloud-sandbox.apiName.analyzeStorage': 'Analyze drive space',
+ 'builtins.lobe-cloud-sandbox.apiName.deleteFiles': 'Delete files',
'builtins.lobe-cloud-sandbox.apiName.editFile': 'Edit file',
'builtins.lobe-cloud-sandbox.apiName.executeCode': 'Execute code',
'builtins.lobe-cloud-sandbox.apiName.exportFile': 'Export file',
@@ -292,6 +294,10 @@ export default {
'builtins.lobe-cloud-sandbox.apiName.renameLocalFile': 'Rename',
'builtins.lobe-cloud-sandbox.apiName.searchLocalFiles': 'Search files',
'builtins.lobe-cloud-sandbox.apiName.writeLocalFile': 'Write file',
+ 'builtins.lobe-cloud-sandbox.deleteFiles.irreversible':
+ 'Deleted files can’t be recovered. The drive has no trash.',
+ 'builtins.lobe-cloud-sandbox.deleteFiles.title':
+ 'Permanently delete {{count}} items from the drive:',
'builtins.lobe-cloud-sandbox.inspector.noResults': 'No results',
'builtins.lobe-cloud-sandbox.title': 'Cloud Sandbox',
'builtins.lobe-group-agent-builder.apiName.batchCreateAgents': 'Batch create agents',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index e87ffa68581..e644742ecd8 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4884,6 +4884,72 @@ When I am ___, I need ___
'drive.retained.deleteConfirm.desc': 'Everything on it is deleted and cannot be recovered.',
'drive.retained.deleted': 'Drive deleted',
'drive.usage.manage': 'Manage in Sandbox Storage',
+ 'drive.cleanup.entry': 'Analyze space',
+ 'drive.cleanup.open': 'Analyze and free up space',
+ 'drive.cleanup.title': 'Space analysis and cleanup',
+ 'drive.cleanup.description': 'See what takes up the drive and delete what you no longer need.',
+ 'drive.cleanup.back': 'Back to files',
+ 'drive.cleanup.rescan': 'Scan again',
+ 'drive.cleanup.scanning': 'Scanning · {{size}} counted so far',
+ 'drive.cleanup.scanningFirst': 'Scanning the drive. A large drive takes a few minutes.',
+ 'drive.cleanup.summary': '{{size}} in total',
+ 'drive.cleanup.stale':
+ 'Some figures are estimates after the last cleanup. Scan again for exact figures.',
+ 'drive.cleanup.empty': 'Nothing on this drive takes up space yet.',
+ 'drive.cleanup.failed': 'Couldn’t analyze the drive. Try again.',
+ 'drive.cleanup.unavailable': 'Space analysis isn’t available on this deployment yet.',
+ 'drive.cleanup.holdsHidden':
+ 'This folder holds a private environment directory and can’t be deleted here.',
+ 'drive.cleanup.notRegenerable':
+ 'Some of these files can’t be regenerated, so deleting them needs your confirmation.',
+ 'drive.cleanup.regenerable': 'Regenerable',
+ 'drive.cleanup.expand': 'Show items',
+ 'drive.cleanup.collapse': 'Hide items',
+ 'drive.cleanup.moreItems': '{{count}} smaller items not listed',
+ 'drive.cleanup.environmentsHint':
+ 'Environment snapshots are deleted together with their environment, on the Environments page.',
+ 'drive.cleanup.selected': '{{count}} selected · {{size}}',
+ 'drive.cleanup.selectHint': 'Select items, or a whole category, to delete',
+ 'drive.cleanup.delete': 'Delete selected',
+ 'drive.cleanup.deleteFailed': 'Couldn’t delete the selected items. Try again.',
+ 'drive.cleanup.freed': 'Deleted. {{size}} freed.',
+ 'drive.cleanup.someFailed': '{{count}} items couldn’t be deleted. The rest were deleted.',
+ 'drive.cleanup.scopeChanged':
+ 'The workspace changed, so nothing was deleted. Choose again in this workspace.',
+ 'drive.cleanup.incomplete': 'Scan stopped · {{size}} counted, figures are incomplete',
+ 'drive.cleanup.failedAndPending':
+ '{{failed}} items couldn’t be deleted and {{pending}} are still being deleted. Delete again to finish.',
+ 'drive.cleanup.partial': '{{count}} items are still being deleted. Delete them again to finish.',
+ 'drive.cleanup.overQuota': 'This drive is {{size}} over its quota',
+ 'drive.cleanup.overQuotaHint':
+ 'Saving files and running terminal commands are blocked until you free up space.',
+ 'drive.cleanup.category.dependencies': 'Dependencies',
+ 'drive.cleanup.category.cache': 'Caches and build output',
+ 'drive.cleanup.category.archives': 'Archives',
+ 'drive.cleanup.category.media': 'Media',
+ 'drive.cleanup.category.git': 'Git repositories',
+ 'drive.cleanup.category.environments': 'Environment snapshots',
+ 'drive.cleanup.category.other': 'Other files',
+ 'drive.cleanup.categoryHint.dependencies':
+ 'node_modules, .venv and other installed packages. Reinstalling restores them.',
+ 'drive.cleanup.categoryHint.cache':
+ 'Caches and build output. The next run or build recreates them.',
+ 'drive.cleanup.categoryHint.archives': '.zip, .tar.gz and other archives',
+ 'drive.cleanup.categoryHint.media': 'Images, video and audio',
+ 'drive.cleanup.categoryHint.git':
+ '.git history. Deleting it removes local commits that were never pushed.',
+ 'drive.cleanup.categoryHint.environments': 'Saved code environments',
+ 'drive.cleanup.categoryHint.other': 'Everything else',
+ 'drive.cleanup.confirm.title': 'Delete {{count}} items?',
+ 'drive.cleanup.confirm.summary':
+ '{{count}} items, {{size}} in total, will be deleted from the drive.',
+ 'drive.cleanup.confirm.irreversible': 'Deleted files can’t be recovered',
+ 'drive.cleanup.confirm.irreversibleHint':
+ 'The drive has no trash. Download anything you want to keep first.',
+ 'drive.cleanup.confirm.regenerableHint':
+ 'These are dependencies, caches or build output. Reinstall or rebuild to get them back.',
+ 'drive.cleanup.confirm.acknowledge': 'I understand these files can’t be recovered',
+ 'drive.cleanup.confirm.ok': 'Delete {{count}} items',
'drive.explorer.newFolder': 'New folder',
'drive.explorer.columns.name': 'Name',
'drive.explorer.columns.modified': 'Date modified',
diff --git a/src/features/EnvironmentManager/errorMessage.ts b/src/features/EnvironmentManager/errorMessage.ts
index b7c3bc55703..756e786461e 100644
--- a/src/features/EnvironmentManager/errorMessage.ts
+++ b/src/features/EnvironmentManager/errorMessage.ts
@@ -34,11 +34,17 @@ const CODE_KEYS: Record<string, string> = {
INSTANCE_REBUILD_REQUIRED: 'environments.instances.rebuildPersonalRequired',
INSTANCE_STARTING: 'environments.instances.stopStarting',
INSTANCE_STOP_FAILED: 'environments.instances.stopRefused',
+ // Deleting a folder that holds a private environment directory left on the public drive.
+ PATH_HOLDS_HIDDEN: 'drive.cleanup.holdsHidden',
PATH_NOT_FOUND: 'environments.files.notFound',
PATH_OUTSIDE_INSTANCE: 'environments.files.invalidPath',
// Retryable on purpose: the run is still packing its snapshot, and the
// execution plane would rather leave it running than cut the save off.
SNAPSHOT_IN_PROGRESS: 'environments.instances.stopSnapshotPending',
+ // A storage service deployed before the drive could be analyzed.
+ storage_analysis_unavailable: 'drive.cleanup.unavailable',
+ // `regenerableOnly` asked for, and some path is not a dependency, cache or build output.
+ storage_paths_not_regenerable: 'drive.cleanup.notRegenerable',
};
/**
diff --git a/src/features/ResourceHome/paths.ts b/src/features/ResourceHome/paths.ts
index b8ad9906150..875791a6857 100644
--- a/src/features/ResourceHome/paths.ts
+++ b/src/features/ResourceHome/paths.ts
@@ -12,6 +12,11 @@ export const RESOURCE_HOME_PATH = '/resource';
export const DRIVE_PATH = '/resource/drive';
/** The cloud sandbox's drives (public / personal) and their usage. */
export const SANDBOX_STORAGE_PATH = '/resource/sandbox-storage';
+/**
+ * The sandbox storage page opened on its space analysis and cleanup, for a
+ * drive over its quota: where every refusal of a write points.
+ */
+export const SANDBOX_STORAGE_CLEANUP_PATH = `${SANDBOX_STORAGE_PATH}?view=cleanup`;
export const LIBRARY_INDEX_PATH = '/resource/library';
export const WORKS_PATH = '/resource/works';
diff --git a/src/features/SandboxDrive/Cleanup/CategorySection.tsx b/src/features/SandboxDrive/Cleanup/CategorySection.tsx
new file mode 100644
index 00000000000..b68b6cd4559
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/CategorySection.tsx
@@ -0,0 +1,162 @@
+'use client';
+
+import { ActionIcon, Checkbox, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatSize } from '@/utils/format';
+
+import { isDeletableItem, type StorageAnalysisItem, type StorageCategory } from './analysis';
+import { CATEGORY_COLORS, CATEGORY_ICONS } from './categoryMeta';
+
+const styles = stylex.create({
+ item: {
+ borderRadius: cssVar.borderRadius,
+ paddingBlock: 6,
+ paddingInline: 8,
+ },
+ itemHover: {
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ },
+ path: {
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ minWidth: 0,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ section: {
+ borderTopColor: cssVar.colorBorderSecondary,
+ borderTopStyle: 'solid',
+ borderTopWidth: 1,
+ paddingBlock: 12,
+ },
+ size: {
+ flex: 'none',
+ fontVariantNumeric: 'tabular-nums',
+ textAlign: 'end',
+ width: 88,
+ },
+ swatch: {
+ borderRadius: 2,
+ flex: 'none',
+ height: 10,
+ width: 10,
+ },
+ swatchColor: (color: string) => ({ backgroundColor: color }),
+});
+
+interface CategorySectionProps {
+ bytes: number;
+ category: StorageCategory;
+ /** How many items the category holds in all; the list shows the largest. */
+ itemCount: number;
+ items: StorageAnalysisItem[];
+ onToggle: (items: StorageAnalysisItem[], selected: boolean) => void;
+ selected: Set<string>;
+}
+
+/**
+ * One category of the analysis: what it is, what it occupies, and its largest
+ * items to tick one by one — or all at once from the category's own box.
+ * Environment snapshots are listed for what they occupy and nothing more:
+ * they go with their environment, on the environments page.
+ */
+const CategorySection = memo<CategorySectionProps>(
+ ({ bytes, category, itemCount, items, onToggle, selected }) => {
+ const { t } = useTranslation('setting');
+ const [open, setOpen] = useState(category === 'dependencies' || category === 'cache');
+ const deletable = items.filter(isDeletableItem);
+ const selectedCount = deletable.filter((item) => selected.has(item.path)).length;
+ const all = deletable.length > 0 && selectedCount === deletable.length;
+
+ return (
+ <Flexbox gap={8} {...stylex.props(styles.section)}>
+ <Flexbox horizontal align={'center'} gap={10}>
+ {deletable.length > 0 ? (
+ <Checkbox
+ checked={all}
+ indeterminate={selectedCount > 0 && !all}
+ onChange={(checked) => onToggle(deletable, checked)}
+ />
+ ) : (
+ <span style={{ flex: 'none', width: 16 }} />
+ )}
+ <span {...stylex.props(styles.swatch, styles.swatchColor(CATEGORY_COLORS[category]))} />
+ <Icon icon={CATEGORY_ICONS[category]} size={16} />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text weight={500}>{t(`drive.cleanup.category.${category}`)}</Text>
+ {(category === 'dependencies' || category === 'cache') && (
+ <Tag color={'success'} size={'small'}>
+ {t('drive.cleanup.regenerable')}
+ </Tag>
+ )}
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {t(`drive.cleanup.categoryHint.${category}`)}
+ </Text>
+ </Flexbox>
+ <Text {...stylex.props(styles.size)} weight={500}>
+ {formatSize(bytes)}
+ </Text>
+ <ActionIcon
+ disabled={items.length === 0}
+ icon={open ? ChevronDownIcon : ChevronRightIcon}
+ size={'small'}
+ title={t(open ? 'drive.cleanup.collapse' : 'drive.cleanup.expand')}
+ onClick={() => setOpen(!open)}
+ />
+ </Flexbox>
+ {open && items.length > 0 && (
+ <Flexbox gap={2} style={{ paddingInlineStart: 26 }}>
+ {items.map((item) => {
+ const canDelete = isDeletableItem(item);
+ const checked = selected.has(item.path);
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={10}
+ key={item.path}
+ {...stylex.props(styles.item, canDelete && styles.itemHover)}
+ >
+ {canDelete ? (
+ <Checkbox checked={checked} onChange={(next) => onToggle([item], next)} />
+ ) : (
+ <span style={{ flex: 'none', width: 16 }} />
+ )}
+ <Text {...stylex.props(styles.path)} title={item.path} type={'secondary'}>
+ {item.path}
+ </Text>
+ <span style={{ flex: 1 }} />
+ <Text {...stylex.props(styles.size)} fontSize={12} type={'secondary'}>
+ {formatSize(item.bytes)}
+ </Text>
+ </Flexbox>
+ );
+ })}
+ {itemCount > items.length && (
+ <Text fontSize={12} style={{ paddingInline: 8 }} type={'secondary'}>
+ {t('drive.cleanup.moreItems', { count: itemCount - items.length })}
+ </Text>
+ )}
+ {category === 'environments' && (
+ <Text fontSize={12} style={{ paddingInline: 8 }} type={'secondary'}>
+ {t('drive.cleanup.environmentsHint')}
+ </Text>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+CategorySection.displayName = 'StorageCleanupCategorySection';
+
+export default CategorySection;
diff --git a/src/features/SandboxDrive/Cleanup/CleanupEntryButton.tsx b/src/features/SandboxDrive/Cleanup/CleanupEntryButton.tsx
new file mode 100644
index 00000000000..6c35d8031e5
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/CleanupEntryButton.tsx
@@ -0,0 +1,49 @@
+'use client';
+
+import { Button, type ButtonProps, Icon } from '@lobehub/ui';
+import { ChartPieIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { SANDBOX_STORAGE_CLEANUP_PATH, SANDBOX_STORAGE_PATH } from '@/features/ResourceHome/paths';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+/**
+ * On the storage page itself, the drive tab being viewed is the one to
+ * clean up; anywhere else the page picks its default drive.
+ */
+const cleanupPathFromHere = () => {
+ const { pathname, search } = window.location;
+ const drive = pathname.includes(SANDBOX_STORAGE_PATH)
+ ? new URLSearchParams(search).get('drive')
+ : null;
+ return drive
+ ? `${SANDBOX_STORAGE_CLEANUP_PATH}&drive=${encodeURIComponent(drive)}`
+ : SANDBOX_STORAGE_CLEANUP_PATH;
+};
+
+/**
+ * The way out of a full drive, wherever its refusal is shown: the storage
+ * page, opened on its space analysis and cleanup.
+ */
+const CleanupEntryButton = memo<Pick<ButtonProps, 'size' | 'type'>>(
+ ({ size = 'small', type = 'primary' }) => {
+ const { t } = useTranslation('setting');
+ const navigate = useWorkspaceAwareNavigate();
+
+ return (
+ <Button
+ icon={<Icon icon={ChartPieIcon} />}
+ size={size}
+ type={type}
+ onClick={() => navigate(cleanupPathFromHere())}
+ >
+ {t('drive.cleanup.open')}
+ </Button>
+ );
+ },
+);
+
+CleanupEntryButton.displayName = 'SandboxDriveCleanupEntryButton';
+
+export default CleanupEntryButton;
diff --git a/src/features/SandboxDrive/Cleanup/analysis.test.ts b/src/features/SandboxDrive/Cleanup/analysis.test.ts
new file mode 100644
index 00000000000..ae22ee81deb
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/analysis.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from 'vitest';
+
+import { type StorageAnalysisResult, withoutDeleted } from './analysis';
+
+const result: StorageAnalysisResult = {
+ categories: [
+ { bytes: 700, category: 'dependencies', items: 2 },
+ { bytes: 300, category: 'other', items: 1 },
+ ],
+ items: [
+ {
+ bytes: 500,
+ category: 'dependencies',
+ isDirectory: true,
+ path: 'app/node_modules',
+ regenerable: true,
+ },
+ {
+ bytes: 200,
+ category: 'dependencies',
+ isDirectory: true,
+ path: 'tool/.venv',
+ regenerable: true,
+ },
+ { bytes: 300, category: 'other', isDirectory: false, path: 'app/data.bin', regenerable: false },
+ ],
+ largestDirectories: [
+ { bytes: 800, path: 'app' },
+ { bytes: 500, path: 'app/node_modules' },
+ { bytes: 200, path: 'tool' },
+ ],
+ largestFiles: [
+ { bytes: 300, category: 'other', path: 'app/data.bin' },
+ { bytes: 100, category: 'dependencies', path: 'app/node_modules/x/big.js' },
+ ],
+ totalBytes: 1000,
+};
+
+describe('withoutDeleted', () => {
+ it('should take deleted items out and their bytes off every figure', () => {
+ const next = withoutDeleted(result, [result.items[0]]);
+
+ expect(next.totalBytes).toBe(500);
+ expect(next.categories).toEqual([
+ { bytes: 200, category: 'dependencies', items: 1 },
+ { bytes: 300, category: 'other', items: 1 },
+ ]);
+ expect(next.items.map((item) => item.path)).toEqual(['tool/.venv', 'app/data.bin']);
+ // Files inside a deleted folder go with it; the folder holding it shrinks.
+ expect(next.largestFiles.map((entry) => entry.path)).toEqual(['app/data.bin']);
+ expect(next.largestDirectories).toEqual([
+ { bytes: 300, path: 'app' },
+ { bytes: 200, path: 'tool' },
+ ]);
+ });
+
+ it('should not treat a sibling with the same prefix as inside a deleted folder', () => {
+ const sibling = {
+ ...result,
+ items: [
+ ...result.items,
+ {
+ bytes: 1,
+ category: 'other' as const,
+ isDirectory: false,
+ path: 'app/node_modules2',
+ regenerable: false,
+ },
+ ],
+ };
+
+ const next = withoutDeleted(sibling, [result.items[0]]);
+
+ expect(next.items.map((item) => item.path)).toContain('app/node_modules2');
+ });
+
+ it('should leave the result as it was when nothing was deleted', () => {
+ expect(withoutDeleted(result, [])).toBe(result);
+ });
+});
diff --git a/src/features/SandboxDrive/Cleanup/analysis.ts b/src/features/SandboxDrive/Cleanup/analysis.ts
new file mode 100644
index 00000000000..4e779982747
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/analysis.ts
@@ -0,0 +1,80 @@
+import type { sandboxStorageService } from '@/services/sandboxStorage';
+
+export type StorageAnalysis = Awaited<ReturnType<typeof sandboxStorageService.analyzeStorage>>;
+export type StorageAnalysisResult = NonNullable<StorageAnalysis['result']>;
+export type StorageAnalysisItem = StorageAnalysisResult['items'][number];
+export type StorageCategory = StorageAnalysisItem['category'];
+
+/**
+ * The categories in the order the view lists them: what can go without a
+ * second thought first, the runtime's own snapshots last.
+ */
+export const STORAGE_CATEGORIES: StorageCategory[] = [
+ 'dependencies',
+ 'cache',
+ 'archives',
+ 'media',
+ 'git',
+ 'other',
+ 'environments',
+];
+
+/** Dependencies, caches and build output: rebuilt by the next install or build. */
+export const isRegenerableCategory = (category: StorageCategory) =>
+ category === 'dependencies' || category === 'cache';
+
+/**
+ * Environment snapshots are the runtime's own store. They are removed with
+ * the environment they belong to, never as files.
+ */
+export const isDeletableItem = (item: Pick<StorageAnalysisItem, 'category'>) =>
+ item.category !== 'environments';
+
+const isWithin = (path: string, directory: string) =>
+ path === directory || path.startsWith(`${directory}/`);
+
+/**
+ * The analysis with what was just deleted taken out, so the view reflects a
+ * cleanup at once instead of waiting for a new scan. Exact for the items
+ * themselves; a folder in the largest-folders list shrinks by the deleted
+ * items it held.
+ */
+export const withoutDeleted = (
+ result: StorageAnalysisResult,
+ deleted: StorageAnalysisItem[],
+): StorageAnalysisResult => {
+ if (deleted.length === 0) return result;
+
+ const gone = (path: string) => deleted.some((item) => isWithin(path, item.path));
+ const freedBy = (category: StorageCategory) =>
+ deleted.filter((item) => item.category === category).reduce((sum, item) => sum + item.bytes, 0);
+ const freed = deleted.reduce((sum, item) => sum + item.bytes, 0);
+
+ return {
+ ...result,
+ categories: result.categories.map((entry) => ({
+ ...entry,
+ bytes: Math.max(0, entry.bytes - freedBy(entry.category)),
+ items: Math.max(
+ 0,
+ entry.items - deleted.filter((item) => item.category === entry.category).length,
+ ),
+ })),
+ items: result.items.filter((item) => !gone(item.path)),
+ largestDirectories: result.largestDirectories
+ .filter((entry) => !gone(entry.path))
+ .map((entry) => ({
+ ...entry,
+ bytes: Math.max(
+ 0,
+ entry.bytes -
+ deleted
+ .filter((item) => isWithin(item.path, entry.path))
+ .reduce((sum, item) => sum + item.bytes, 0),
+ ),
+ }))
+ .sort((a, b) => b.bytes - a.bytes),
+ largestFiles: result.largestFiles.filter((entry) => !gone(entry.path)),
+ totalBytes: Math.max(0, result.totalBytes - freed),
+ };
+};
diff --git a/src/features/SandboxDrive/Cleanup/categoryMeta.ts b/src/features/SandboxDrive/Cleanup/categoryMeta.ts
new file mode 100644
index 00000000000..21ea59736ce
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/categoryMeta.ts
@@ -0,0 +1,38 @@
+import { cssVar } from '@lobehub/ui';
+import {
+ ArchiveIcon,
+ BoxIcon,
+ DatabaseIcon,
+ FileIcon,
+ GitBranchIcon,
+ ImageIcon,
+ type LucideIcon,
+ RecycleIcon,
+} from 'lucide-react';
+
+import type { StorageCategory } from './analysis';
+
+export const CATEGORY_ICONS: Record<StorageCategory, LucideIcon> = {
+ archives: ArchiveIcon,
+ cache: RecycleIcon,
+ dependencies: BoxIcon,
+ environments: DatabaseIcon,
+ git: GitBranchIcon,
+ media: ImageIcon,
+ other: FileIcon,
+};
+
+/**
+ * The bar's segment colours, one per category, from the theme's semantic
+ * palette so they follow light and dark. Regenerable categories take the
+ * calm ones; the rest are told apart by hue, not by alarm.
+ */
+export const CATEGORY_COLORS: Record<StorageCategory, string> = {
+ archives: cssVar.colorWarning,
+ cache: cssVar.colorSuccess,
+ dependencies: cssVar.colorPrimary,
+ environments: cssVar.colorTextQuaternary,
+ git: cssVar.purple,
+ media: cssVar.geekblue,
+ other: cssVar.colorTextTertiary,
+};
diff --git a/src/features/SandboxDrive/Cleanup/confirmDelete.tsx b/src/features/SandboxDrive/Cleanup/confirmDelete.tsx
new file mode 100644
index 00000000000..71fb9f43401
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/confirmDelete.tsx
@@ -0,0 +1,99 @@
+'use client';
+
+import {
+ Alert,
+ Button,
+ Checkbox,
+ createModal,
+ Flexbox,
+ type ModalInstance,
+ Text,
+ useModalContext,
+} from '@lobehub/ui';
+import { t } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatSize } from '@/utils/format';
+
+interface ConfirmDeleteContentProps {
+ bytes: number;
+ count: number;
+ onConfirm: () => Promise<void>;
+ /** Every selected item is a dependency directory, cache or build output. */
+ regenerable: boolean;
+}
+
+/**
+ * The second confirmation a cleanup asks for. Deleting from the drive cannot
+ * be undone — there is no trash on the volume — so the dialog says so in as
+ * many words and keeps the delete button disabled until that sentence has
+ * been acknowledged. Choosing what to delete was the first step.
+ */
+export const ConfirmDeleteContent = memo<ConfirmDeleteContentProps>(
+ ({ bytes, count, onConfirm, regenerable }) => {
+ const { t: translate } = useTranslation(['setting', 'common']);
+ const { close } = useModalContext();
+ const [acknowledged, setAcknowledged] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+
+ const confirm = async () => {
+ setDeleting(true);
+ try {
+ await onConfirm();
+ close();
+ } catch {
+ // `onConfirm` reports the failure; the dialog stays for a retry.
+ } finally {
+ setDeleting(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Text>
+ {translate('drive.cleanup.confirm.summary', { count, size: formatSize(bytes) })}
+ </Text>
+ <Alert
+ showIcon
+ title={translate('drive.cleanup.confirm.irreversible')}
+ type={'error'}
+ description={translate(
+ regenerable
+ ? 'drive.cleanup.confirm.regenerableHint'
+ : 'drive.cleanup.confirm.irreversibleHint',
+ )}
+ />
+ <Checkbox checked={acknowledged} onChange={setAcknowledged}>
+ {translate('drive.cleanup.confirm.acknowledge')}
+ </Checkbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={deleting} onClick={close}>
+ {translate('cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ danger
+ disabled={!acknowledged}
+ loading={deleting}
+ type={'primary'}
+ onClick={confirm}
+ >
+ {translate('drive.cleanup.confirm.ok', { count })}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+ConfirmDeleteContent.displayName = 'StorageCleanupConfirmDelete';
+
+export const confirmStorageDelete = (props: ConfirmDeleteContentProps): ModalInstance =>
+ createModal({
+ content: <ConfirmDeleteContent {...props} />,
+ footer: null,
+ maskClosable: false,
+ styles: { header: { borderBottom: 'none' } },
+ title: t('drive.cleanup.confirm.title', { count: props.count, ns: 'setting' }),
+ width: 'min(90vw, 480px)',
+ });
diff --git a/src/features/SandboxDrive/Cleanup/index.tsx b/src/features/SandboxDrive/Cleanup/index.tsx
new file mode 100644
index 00000000000..8f0cf617464
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/index.tsx
@@ -0,0 +1,238 @@
+'use client';
+
+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';
+import { ActionIcon, Alert, Button, Center, Flexbox, Icon, Spin, Text, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ArrowLeftIcon, RefreshCwIcon, Trash2Icon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { describeError } from '@/features/EnvironmentManager/errorMessage';
+import { formatSize } from '@/utils/format';
+
+import { STORAGE_CATEGORIES } from './analysis';
+import { CATEGORY_COLORS } from './categoryMeta';
+import CategorySection from './CategorySection';
+import { confirmStorageDelete } from './confirmDelete';
+import { useCleanupSelection } from './useCleanupSelection';
+import { useStorageAnalysis } from './useStorageAnalysis';
+
+const styles = stylex.create({
+ actionBar: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderTopColor: cssVar.colorBorderSecondary,
+ borderTopStyle: 'solid',
+ borderTopWidth: 1,
+ bottom: 0,
+ paddingBlock: 12,
+ position: 'sticky',
+ },
+ bar: {
+ backgroundColor: cssVar.colorFillSecondary,
+ borderRadius: 4,
+ display: 'flex',
+ height: 8,
+ overflow: 'hidden',
+ width: '100%',
+ },
+ segment: (color: string, width: string) => ({ backgroundColor: color, height: '100%', width }),
+});
+
+interface StorageCleanupProps {
+ drive: SandboxDrive;
+ onBack: () => void;
+}
+
+/**
+ * What a drive's space goes to, and a way to give it back.
+ *
+ * The analysis sorts the drive into categories — dependencies and caches,
+ * which the next install or build recreates, and archives, media, git
+ * history and everything else, which nothing recreates — with the largest
+ * items of each to tick. Deleting is permanent, so it always ends in a
+ * second confirmation that says so. None of this is held back by the quota:
+ * a drive over its limit is precisely the one that needs it.
+ */
+const StorageCleanup = memo<StorageCleanupProps>(({ drive, onBack }) => {
+ const { t } = useTranslation(['setting', 'common']);
+ const { analysis, error, remove, rescan, scanning } = useStorageAnalysis(drive);
+ const result = analysis?.result;
+ const selection = useCleanupSelection(result);
+ const { chosen, selected, toggle } = selection;
+ const chosenBytes = selection.bytes;
+
+ const deleteChosen = () => {
+ const items = chosen;
+ // What was chosen belongs to this workspace's drive; a confirmation that
+ // outlives a workspace switch must not delete in the next one.
+ const workspace = getActiveWorkspaceId();
+ confirmStorageDelete({
+ bytes: chosenBytes,
+ count: items.length,
+ onConfirm: async () => {
+ if (getActiveWorkspaceId() !== workspace) {
+ toast.error(t('drive.cleanup.scopeChanged'));
+ return;
+ }
+ try {
+ const outcome = await remove(items);
+ selection.clear();
+ if (outcome.failed.length > 0 && outcome.pending.length > 0) {
+ toast.warning(
+ t('drive.cleanup.failedAndPending', {
+ failed: outcome.failed.length,
+ pending: outcome.pending.length,
+ }),
+ );
+ } else if (outcome.failed.length > 0) {
+ toast.warning(t('drive.cleanup.someFailed', { count: outcome.failed.length }));
+ } else if (outcome.pending.length > 0) {
+ toast.warning(t('drive.cleanup.partial', { count: outcome.pending.length }));
+ } else {
+ toast.success(t('drive.cleanup.freed', { size: formatSize(outcome.freedBytes) }));
+ }
+ } catch (caught) {
+ toast.error(describeError(caught, t, t('drive.cleanup.deleteFailed')));
+ throw caught;
+ }
+ },
+ regenerable: selection.regenerable,
+ });
+ };
+
+ const total = result?.totalBytes ?? 0;
+ const categories = STORAGE_CATEGORIES.map((category) => {
+ const summary = result?.categories.find((entry) => entry.category === category);
+ return {
+ bytes: summary?.bytes ?? 0,
+ category,
+ itemCount: summary?.items ?? 0,
+ items: (result?.items ?? []).filter((item) => item.category === category),
+ };
+ }).filter((entry) => entry.bytes > 0);
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <ActionIcon icon={ArrowLeftIcon} title={t('drive.cleanup.back')} onClick={onBack} />
+ <Flexbox flex={1} gap={2}>
+ <Text as={'h2'} fontSize={16} style={{ margin: 0 }} weight={600}>
+ {t('drive.cleanup.title')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {scanning
+ ? t('drive.cleanup.scanning', { size: formatSize(analysis?.scannedBytes ?? 0) })
+ : error && result
+ ? t('drive.cleanup.incomplete', { size: formatSize(analysis?.scannedBytes ?? 0) })
+ : result
+ ? t('drive.cleanup.summary', { size: formatSize(total) })
+ : t('drive.cleanup.description')}
+ </Text>
+ </Flexbox>
+ <ActionIcon
+ disabled={scanning}
+ icon={RefreshCwIcon}
+ loading={scanning}
+ title={t('drive.cleanup.rescan')}
+ onClick={() => void rescan()}
+ />
+ </Flexbox>
+
+ {error && !result ? (
+ <Center gap={12} style={{ minHeight: 240 }}>
+ <Text type={'secondary'}>{describeError(error, t, t('drive.cleanup.failed'))}</Text>
+ <Button onClick={() => void rescan()}>{t('retry', { ns: 'common' })}</Button>
+ </Center>
+ ) : !result ? (
+ <Center gap={12} style={{ minHeight: 240 }}>
+ <Spin />
+ <Text type={'secondary'}>{t('drive.cleanup.scanningFirst')}</Text>
+ </Center>
+ ) : (
+ <>
+ <div {...stylex.props(styles.bar)} role={'presentation'}>
+ {categories.map((entry) => (
+ <span
+ key={entry.category}
+ title={t(`drive.cleanup.category.${entry.category}`)}
+ {...stylex.props(
+ styles.segment(
+ CATEGORY_COLORS[entry.category],
+ `${total > 0 ? (entry.bytes / total) * 100 : 0}%`,
+ ),
+ )}
+ />
+ ))}
+ </div>
+ {error && (
+ <Alert
+ showIcon
+ title={describeError(error, t, t('drive.cleanup.failed'))}
+ type={'warning'}
+ action={
+ <Button size={'small'} onClick={() => void rescan()}>
+ {t('retry', { ns: 'common' })}
+ </Button>
+ }
+ />
+ )}
+ {result.stale && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('drive.cleanup.stale')}
+ </Text>
+ )}
+ {categories.length === 0 ? (
+ <Center style={{ minHeight: 160 }}>
+ <Text type={'secondary'}>{t('drive.cleanup.empty')}</Text>
+ </Center>
+ ) : (
+ <Flexbox>
+ {categories.map((entry) => (
+ <CategorySection
+ bytes={entry.bytes}
+ category={entry.category}
+ itemCount={entry.itemCount}
+ items={entry.items}
+ key={entry.category}
+ selected={selected}
+ onToggle={toggle}
+ />
+ ))}
+ </Flexbox>
+ )}
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ justify={'space-between'}
+ {...stylex.props(styles.actionBar)}
+ >
+ <Text type={'secondary'}>
+ {chosen.length > 0
+ ? t('drive.cleanup.selected', {
+ count: chosen.length,
+ size: formatSize(chosenBytes),
+ })
+ : t('drive.cleanup.selectHint')}
+ </Text>
+ <Button
+ danger
+ disabled={chosen.length === 0}
+ icon={<Icon icon={Trash2Icon} />}
+ type={'primary'}
+ onClick={deleteChosen}
+ >
+ {t('drive.cleanup.delete')}
+ </Button>
+ </Flexbox>
+ </>
+ )}
+ </Flexbox>
+ );
+});
+
+StorageCleanup.displayName = 'StorageCleanup';
+
+export default StorageCleanup;
diff --git a/src/features/SandboxDrive/Cleanup/useCleanupSelection.test.ts b/src/features/SandboxDrive/Cleanup/useCleanupSelection.test.ts
new file mode 100644
index 00000000000..fd82f130368
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/useCleanupSelection.test.ts
@@ -0,0 +1,75 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import type { StorageAnalysisResult } from './analysis';
+import { useCleanupSelection } from './useCleanupSelection';
+
+const result: StorageAnalysisResult = {
+ categories: [],
+ items: [
+ {
+ bytes: 500,
+ category: 'dependencies',
+ isDirectory: true,
+ path: 'app/node_modules',
+ regenerable: true,
+ },
+ { bytes: 200, category: 'cache', isDirectory: true, path: 'app/.next', regenerable: true },
+ { bytes: 300, category: 'other', isDirectory: false, path: 'app/data.bin', regenerable: false },
+ {
+ bytes: 50,
+ category: 'environments',
+ environment: 'e1',
+ isDirectory: true,
+ path: '.sandbox/envs/e1',
+ regenerable: false,
+ },
+ ],
+ largestDirectories: [],
+ largestFiles: [],
+ totalBytes: 1050,
+};
+
+describe('useCleanupSelection', () => {
+ it('should select a whole category and add up what it frees', () => {
+ const { result: hook } = renderHook(() => useCleanupSelection(result));
+
+ act(() => hook.current.toggle(result.items.slice(0, 2), true));
+
+ expect(hook.current.chosen.map((item) => item.path)).toEqual(['app/node_modules', 'app/.next']);
+ expect(hook.current.bytes).toBe(700);
+ expect(hook.current.regenerable).toBe(true);
+ });
+
+ it('should say a selection with anything irreplaceable is not regenerable', () => {
+ const { result: hook } = renderHook(() => useCleanupSelection(result));
+
+ act(() => hook.current.toggle([result.items[0], result.items[2]], true));
+
+ expect(hook.current.regenerable).toBe(false);
+ });
+
+ it('should never select an environment snapshot as files', () => {
+ const { result: hook } = renderHook(() => useCleanupSelection(result));
+
+ act(() => hook.current.toggle(result.items, true));
+
+ expect(hook.current.chosen.map((item) => item.category)).not.toContain('environments');
+ expect(hook.current.bytes).toBe(1000);
+ });
+
+ it('should drop an item the analysis no longer lists, and unselect on toggle off', () => {
+ const { rerender, result: hook } = renderHook(({ value }) => useCleanupSelection(value), {
+ initialProps: { value: result },
+ });
+ act(() => hook.current.toggle(result.items.slice(0, 3), true));
+ act(() => hook.current.toggle([result.items[1]], false));
+ expect(hook.current.chosen).toHaveLength(2);
+
+ rerender({ value: { ...result, items: result.items.slice(1) } });
+
+ expect(hook.current.chosen.map((item) => item.path)).toEqual(['app/data.bin']);
+ act(() => hook.current.clear());
+ expect(hook.current.chosen).toEqual([]);
+ });
+});
diff --git a/src/features/SandboxDrive/Cleanup/useCleanupSelection.ts b/src/features/SandboxDrive/Cleanup/useCleanupSelection.ts
new file mode 100644
index 00000000000..3496c804f9c
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/useCleanupSelection.ts
@@ -0,0 +1,55 @@
+import { useCallback, useMemo, useState } from 'react';
+
+import {
+ isDeletableItem,
+ isRegenerableCategory,
+ type StorageAnalysisItem,
+ type StorageAnalysisResult,
+} from './analysis';
+
+/**
+ * What the user has ticked for deletion, by path. Only items the current
+ * analysis still lists count — one a cleanup already removed drops out — and
+ * environment snapshots never do, since they are not deleted as files.
+ */
+export const useCleanupSelection = (result: StorageAnalysisResult | undefined) => {
+ const [selected, setSelected] = useState<Set<string>>(() => new Set());
+
+ const itemsByPath = useMemo(
+ () => new Map((result?.items ?? []).map((item) => [item.path, item])),
+ [result],
+ );
+ const chosen = useMemo(
+ () =>
+ [...selected]
+ .map((path) => itemsByPath.get(path))
+ .filter((item): item is StorageAnalysisItem => !!item && isDeletableItem(item)),
+ [itemsByPath, selected],
+ );
+
+ const toggle = useCallback(
+ (items: StorageAnalysisItem[], on: boolean) =>
+ setSelected((current) => {
+ const next = new Set(current);
+ for (const item of items) {
+ if (!isDeletableItem(item)) continue;
+ if (on) next.add(item.path);
+ else next.delete(item.path);
+ }
+ return next;
+ }),
+ [],
+ );
+
+ const clear = useCallback(() => setSelected(new Set()), []);
+
+ return {
+ bytes: chosen.reduce((sum, item) => sum + item.bytes, 0),
+ chosen,
+ clear,
+ /** Every chosen item is a dependency directory, cache or build output. */
+ regenerable: chosen.length > 0 && chosen.every((item) => isRegenerableCategory(item.category)),
+ selected,
+ toggle,
+ };
+};
diff --git a/src/features/SandboxDrive/Cleanup/useStorageAnalysis.test.ts b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.test.ts
new file mode 100644
index 00000000000..7462f1dff1f
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.test.ts
@@ -0,0 +1,275 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useStorageAnalysis } from './useStorageAnalysis';
+
+const service = vi.hoisted(() => ({ analyzeStorage: vi.fn(), deleteFiles: vi.fn() }));
+const refreshDrive = vi.hoisted(() => vi.fn());
+
+vi.mock('@/services/sandboxStorage', () => ({ sandboxStorageService: service }));
+vi.mock('../useDriveData', () => ({ useRefreshDrive: () => refreshDrive }));
+
+const items = [
+ {
+ bytes: 500,
+ category: 'dependencies',
+ isDirectory: true,
+ path: 'app/node_modules',
+ regenerable: true,
+ },
+ { bytes: 300, category: 'other', isDirectory: false, path: 'app/data.bin', regenerable: false },
+] as const;
+
+const done = {
+ result: {
+ categories: [
+ { bytes: 500, category: 'dependencies', items: 1 },
+ { bytes: 300, category: 'other', items: 1 },
+ ],
+ items: [...items],
+ largestDirectories: [],
+ largestFiles: [],
+ totalBytes: 800,
+ },
+ scannedBytes: 800,
+ status: 'done',
+};
+
+beforeEach(() => {
+ service.analyzeStorage.mockReset();
+ service.deleteFiles.mockReset();
+ refreshDrive.mockReset().mockResolvedValue(undefined);
+});
+
+describe('useStorageAnalysis', () => {
+ it('should step a large drive until the scan is done, showing progress meanwhile', async () => {
+ service.analyzeStorage
+ .mockResolvedValueOnce({ ...done, scannedBytes: 100, status: 'scanning' })
+ .mockResolvedValueOnce(done);
+
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+ expect(service.analyzeStorage).toHaveBeenCalledTimes(2);
+ expect(service.analyzeStorage.mock.calls[0][0]).toEqual({
+ drive: 'personal',
+ restart: false,
+ top: 50,
+ });
+ expect(result.current.analysis?.status).toBe('done');
+ });
+
+ it('should restart only the first call of a rescan', async () => {
+ service.analyzeStorage.mockResolvedValue(done);
+ const { result } = renderHook(() => useStorageAnalysis('public'));
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+
+ service.analyzeStorage
+ .mockReset()
+ .mockResolvedValueOnce({ ...done, status: 'scanning' })
+ .mockResolvedValueOnce(done);
+ await act(() => result.current.rescan());
+
+ expect(service.analyzeStorage.mock.calls.map((call) => call[0].restart)).toEqual([true, false]);
+ });
+
+ it('should keep the error of a scan that failed', async () => {
+ service.analyzeStorage.mockRejectedValue(new Error('storage_analysis_unavailable'));
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+
+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));
+ expect(result.current.scanning).toBe(false);
+ });
+
+ it('should keep deleting what ran out of time, then take it off the figures', async () => {
+ service.analyzeStorage.mockResolvedValue(done);
+ service.deleteFiles
+ .mockResolvedValueOnce({
+ deleted: ['app/node_modules'],
+ done: false,
+ freedBytes: 100,
+ missing: [],
+ pending: ['app/data.bin'],
+ })
+ .mockResolvedValueOnce({
+ deleted: ['app/data.bin'],
+ done: true,
+ freedBytes: 200,
+ missing: [],
+ pending: [],
+ });
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+
+ let outcome: Awaited<ReturnType<typeof result.current.remove>> | undefined;
+ await act(async () => {
+ outcome = await result.current.remove([...items]);
+ });
+
+ expect(service.deleteFiles.mock.calls.map((call) => call[0].paths)).toEqual([
+ ['app/node_modules', 'app/data.bin'],
+ ['app/data.bin'],
+ ]);
+ expect(outcome).toEqual({ failed: [], freedBytes: 300, pending: [] });
+ expect(result.current.analysis?.result?.items).toEqual([]);
+ expect(result.current.analysis?.result?.totalBytes).toBe(0);
+ // The usage figure and listings reload to show the space coming back.
+ expect(refreshDrive).toHaveBeenCalled();
+ });
+
+ it('should leave in the figures what could not be deleted in time', async () => {
+ service.analyzeStorage.mockResolvedValue(done);
+ service.deleteFiles.mockResolvedValue({
+ deleted: [],
+ done: false,
+ freedBytes: 0,
+ missing: [],
+ pending: ['app/data.bin'],
+ });
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+
+ let outcome: Awaited<ReturnType<typeof result.current.remove>> | undefined;
+ await act(async () => {
+ outcome = await result.current.remove([items[1]]);
+ });
+
+ expect(outcome?.pending).toEqual(['app/data.bin']);
+ expect(result.current.analysis?.result?.items.map((item) => item.path)).toContain(
+ 'app/data.bin',
+ );
+ });
+});
+
+describe('useStorageAnalysis failures', () => {
+ it('should keep in the figures what the volume refused to remove', async () => {
+ service.analyzeStorage.mockResolvedValue(done);
+ service.deleteFiles.mockResolvedValue({
+ deleted: ['app/node_modules'],
+ done: true,
+ failed: [{ message: 'busy', path: 'app/data.bin' }],
+ freedBytes: 500,
+ missing: [],
+ pending: [],
+ });
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+
+ let outcome: Awaited<ReturnType<typeof result.current.remove>> | undefined;
+ await act(async () => {
+ outcome = await result.current.remove([...items]);
+ });
+
+ expect(outcome?.failed).toEqual(['app/data.bin']);
+ expect(result.current.analysis?.result?.items.map((item) => item.path)).toEqual([
+ 'app/data.bin',
+ ]);
+ });
+
+ it('should keep the figures on screen while another call advances the scan', async () => {
+ service.analyzeStorage
+ .mockResolvedValueOnce({ ...done, scannedBytes: 400, status: 'scanning' })
+ .mockResolvedValueOnce({ scannedBytes: 0, status: 'running' })
+ .mockResolvedValueOnce(done);
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+
+ await waitFor(() => expect(result.current.analysis?.status).toBe('running'));
+ expect(result.current.analysis?.result).toBeDefined();
+ expect(result.current.analysis?.scannedBytes).toBe(400);
+ await waitFor(() => expect(result.current.scanning).toBe(false), { timeout: 5000 });
+ });
+});
+
+describe('useStorageAnalysis large selections', () => {
+ it('should send a selection over the server ceiling in batches of 100', async () => {
+ const many = Array.from({ length: 230 }, (_, index) => ({
+ bytes: 1,
+ category: 'other' as const,
+ isDirectory: false,
+ path: `f/${index}.bin`,
+ regenerable: false,
+ }));
+ service.analyzeStorage.mockResolvedValue({
+ ...done,
+ result: { ...done.result, items: many, totalBytes: 230 },
+ });
+ service.deleteFiles.mockImplementation(async ({ paths }: { paths: string[] }) => ({
+ deleted: paths,
+ done: true,
+ failed: [],
+ freedBytes: paths.length,
+ missing: [],
+ pending: [],
+ }));
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+
+ let outcome: Awaited<ReturnType<typeof result.current.remove>> | undefined;
+ await act(async () => {
+ outcome = await result.current.remove(many);
+ });
+
+ expect(service.deleteFiles.mock.calls.map((call) => call[0].paths.length)).toEqual([
+ 100, 100, 30,
+ ]);
+ expect(outcome).toEqual({ failed: [], freedBytes: 230, pending: [] });
+ expect(result.current.analysis?.result?.items).toEqual([]);
+ });
+});
+
+describe('useStorageAnalysis partial failure', () => {
+ it('should reconcile what earlier batches deleted when a later batch fails', async () => {
+ const many = Array.from({ length: 150 }, (_, index) => ({
+ bytes: 1,
+ category: 'other' as const,
+ isDirectory: false,
+ path: `f/${index}.bin`,
+ regenerable: false,
+ }));
+ service.analyzeStorage.mockResolvedValue({
+ ...done,
+ result: { ...done.result, items: many, totalBytes: 150 },
+ });
+ service.deleteFiles
+ .mockImplementationOnce(async ({ paths }: { paths: string[] }) => ({
+ deleted: paths,
+ done: true,
+ failed: [],
+ freedBytes: paths.length,
+ missing: [],
+ pending: [],
+ }))
+ .mockRejectedValueOnce(new Error('BAD_GATEWAY'));
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+
+ await act(async () => {
+ await expect(result.current.remove(many)).rejects.toThrow('BAD_GATEWAY');
+ });
+
+ expect(result.current.analysis?.result?.items).toHaveLength(50);
+ expect(refreshDrive).toHaveBeenCalled();
+ });
+});
+
+describe('useStorageAnalysis estimates', () => {
+ it('should mark the figures an estimate when the freed bytes differ from the scan', async () => {
+ service.analyzeStorage.mockResolvedValue(done);
+ service.deleteFiles.mockResolvedValue({
+ deleted: ['app/data.bin'],
+ done: true,
+ failed: [],
+ freedBytes: 999,
+ missing: [],
+ pending: [],
+ });
+ const { result } = renderHook(() => useStorageAnalysis('personal'));
+ await waitFor(() => expect(result.current.scanning).toBe(false));
+
+ await act(async () => {
+ await result.current.remove([items[1]]);
+ });
+
+ expect(result.current.analysis?.result?.stale).toBe(true);
+ });
+});
diff --git a/src/features/SandboxDrive/Cleanup/useStorageAnalysis.ts b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.ts
new file mode 100644
index 00000000000..1d92217ac04
--- /dev/null
+++ b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.ts
@@ -0,0 +1,143 @@
+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { sandboxStorageService } from '@/services/sandboxStorage';
+
+import { useRefreshDrive } from '../useDriveData';
+import {
+ type StorageAnalysis,
+ type StorageAnalysisItem,
+ type StorageAnalysisResult,
+ withoutDeleted,
+} from './analysis';
+
+/** Items asked for per category: enough that "select the category" covers nearly all of it. */
+export const ANALYSIS_TOP = 50;
+
+/** Pause before asking again while another call is advancing the same scan. */
+const RUNNING_RETRY_MS = 2000;
+
+/** Most paths one delete call takes: the server's own ceiling. */
+export const DELETE_BATCH_SIZE = 100;
+
+/** A delete that keeps running out of time this often is reported, not retried forever. */
+const MAX_DELETE_ROUNDS = 20;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+export interface DeleteOutcome {
+ /** Paths the volume refused to remove; the rest were deleted. */
+ failed: string[];
+ freedBytes: number;
+ /** Paths still there: the storage service ran out of rounds. */
+ pending: string[];
+}
+
+/**
+ * The drive's space analysis, scanned on mount and stepped until it is done —
+ * a large drive takes several calls, and the figures counted so far are
+ * shown meanwhile. `remove` deletes for good and takes the deleted items out
+ * of the figures at once.
+ */
+export const useStorageAnalysis = (drive: SandboxDrive) => {
+ const [analysis, setAnalysis] = useState<StorageAnalysis>();
+ const [error, setError] = useState<unknown>();
+ const [scanning, setScanning] = useState(false);
+ const generation = useRef(0);
+ const refreshDrive = useRefreshDrive();
+
+ const scan = useCallback(
+ async (restart = false) => {
+ const run = ++generation.current;
+ setScanning(true);
+ setError(undefined);
+ try {
+ let first = true;
+ for (;;) {
+ const step = await sandboxStorageService.analyzeStorage({
+ drive,
+ restart: first && restart,
+ top: ANALYSIS_TOP,
+ });
+ first = false;
+ if (run !== generation.current) return;
+ // A call answered by another scan in progress may carry no figures
+ // of its own; the ones already on screen stay until it has some.
+ setAnalysis((previous) =>
+ step.result || !previous
+ ? step
+ : {
+ ...step,
+ result: previous.result,
+ scannedBytes: Math.max(step.scannedBytes, previous.scannedBytes),
+ },
+ );
+ if (step.status === 'done') break;
+ if (step.status === 'running') await sleep(RUNNING_RETRY_MS);
+ if (run !== generation.current) return;
+ }
+ } catch (caught) {
+ if (run === generation.current) setError(caught);
+ } finally {
+ if (run === generation.current) setScanning(false);
+ }
+ },
+ [drive],
+ );
+
+ useEffect(() => {
+ void scan();
+ return () => {
+ // A scan that outlives the view answers nobody.
+ generation.current++;
+ };
+ }, [scan]);
+
+ const remove = useCallback(
+ async (items: StorageAnalysisItem[], options: { regenerableOnly?: boolean } = {}) => {
+ // Sent in batches the server accepts; what a batch could not finish in
+ // time goes back to the front of the queue.
+ let pending = [...new Set(items.map((item) => item.path))];
+ let freedBytes = 0;
+ const failed: string[] = [];
+ // Gone from the drive: deleted now, or already missing.
+ const gone = new Set<string>();
+ const rounds = MAX_DELETE_ROUNDS + Math.ceil(pending.length / DELETE_BATCH_SIZE);
+ try {
+ for (let round = 0; round < rounds && pending.length > 0; round++) {
+ const batch = pending.slice(0, DELETE_BATCH_SIZE);
+ const result = await sandboxStorageService.deleteFiles({
+ drive,
+ paths: batch,
+ regenerableOnly: options.regenerableOnly,
+ });
+ freedBytes += result.freedBytes;
+ failed.push(...(result.failed ?? []).map((entry) => entry.path));
+ for (const path of [...result.deleted, ...result.missing]) gone.add(path);
+ pending = [...(result.done ? [] : result.pending), ...pending.slice(batch.length)];
+ }
+ } finally {
+ // Also when a later batch failed: what earlier ones removed is gone
+ // for good, and the figures and the meter must say so.
+ const removed = items.filter((item) => gone.has(item.path));
+ // Sizes are the scan's; if the files changed since, what was actually
+ // freed differs and the adjusted figures are only an estimate.
+ const estimated = removed.reduce((sum, item) => sum + item.bytes, 0) !== freedBytes;
+ setAnalysis((current) => {
+ if (!current?.result) return current;
+ const result = withoutDeleted(current.result as StorageAnalysisResult, removed);
+ return {
+ ...current,
+ result: estimated && removed.length > 0 ? { ...result, stale: true } : result,
+ };
+ });
+ await refreshDrive();
+ }
+
+ return { failed, freedBytes, pending } satisfies DeleteOutcome;
+ },
+ [drive, refreshDrive],
+ );
+
+ return { analysis, error, remove, rescan: () => scan(true), scanning };
+};
diff --git a/src/features/SandboxDrive/OverQuotaBanner.tsx b/src/features/SandboxDrive/OverQuotaBanner.tsx
new file mode 100644
index 00000000000..6bc82d4bd11
--- /dev/null
+++ b/src/features/SandboxDrive/OverQuotaBanner.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { Alert, Button } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatSize } from '@/utils/format';
+
+import { useDriveUsage } from './useDriveData';
+
+/**
+ * Said at the top of the drive while it is over a quota the plan does not
+ * bill past: then every write, terminal commands included, is refused, and
+ * the way out — the space analysis and cleanup — is one click away instead
+ * of something to go looking for.
+ */
+const OverQuotaBanner = memo<{ onCleanup: () => void }>(({ onCleanup }) => {
+ const { t } = useTranslation('setting');
+ const { data } = useDriveUsage();
+ if (!data || data.totalUsageBytes === null || data.overageAllowed) return null;
+ if (data.totalUsageBytes <= data.quotaBytes) return null;
+
+ return (
+ <Alert
+ showIcon
+ description={t('drive.cleanup.overQuotaHint')}
+ type={'error'}
+ action={
+ <Button size={'small'} type={'primary'} onClick={onCleanup}>
+ {t('drive.cleanup.open')}
+ </Button>
+ }
+ title={t('drive.cleanup.overQuota', {
+ size: formatSize(data.totalUsageBytes - data.quotaBytes),
+ })}
+ />
+ );
+});
+
+OverQuotaBanner.displayName = 'DriveOverQuotaBanner';
+
+export default OverQuotaBanner;
diff --git a/src/features/SandboxDrive/UsageBreakdown.test.tsx b/src/features/SandboxDrive/UsageBreakdown.test.tsx
index 5ee35dd37d1..df2788f39b0 100644
--- a/src/features/SandboxDrive/UsageBreakdown.test.tsx
+++ b/src/features/SandboxDrive/UsageBreakdown.test.tsx
@@ -7,6 +7,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { UsageBreakdown } from './UsageBreakdown';
vi.mock('@/business/client/features/RetainedMemberDrives', () => ({ default: () => null }));
+const navigate = vi.hoisted(() => vi.fn());
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => navigate,
+}));
const workspace = vi.hoisted(() => ({ id: 'ws-a' as string | null }));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => workspace.id,
@@ -41,6 +45,11 @@ const overQuota = (overageAllowed: boolean) =>
}) as any;
describe('UsageBreakdown', () => {
+ // A toast from one case must not answer for the next one's assertion.
+ beforeEach(() => {
+ vi.mocked(toast.error).mockClear();
+ });
+
it('should say saves are refused over a quota the plan does not bill past', () => {
render(<UsageBreakdown data={overQuota(false)} onRefresh={vi.fn()} />);
@@ -48,6 +57,32 @@ describe('UsageBreakdown', () => {
expect(screen.queryByText('drive.usage.overBilled')).not.toBeInTheDocument();
});
+ it('should offer the space cleanup while saves are refused', () => {
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={vi.fn()} />);
+
+ fireEvent.click(screen.getByText('drive.cleanup.open'));
+
+ expect(navigate).toHaveBeenCalledWith('/resource/sandbox-storage?view=cleanup');
+ });
+
+ it('should keep the drive tab being viewed when opened from the storage page', () => {
+ window.history.pushState({}, '', '/resource/sandbox-storage?drive=personal');
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={vi.fn()} />);
+
+ fireEvent.click(screen.getByText('drive.cleanup.open'));
+
+ expect(navigate).toHaveBeenLastCalledWith(
+ '/resource/sandbox-storage?view=cleanup&drive=personal',
+ );
+ window.history.pushState({}, '', '/');
+ });
+
+ it('should not push a cleanup when the overage is billed', () => {
+ render(<UsageBreakdown data={overQuota(true)} onRefresh={vi.fn()} />);
+
+ expect(screen.queryByText('drive.cleanup.open')).not.toBeInTheDocument();
+ });
+
it('should say the overage is billed when the plan allows it', () => {
// Pay-as-you-go keeps writes going; "free up space before saving" would
// be untrue there.
diff --git a/src/features/SandboxDrive/UsageBreakdown.tsx b/src/features/SandboxDrive/UsageBreakdown.tsx
index 3f0cc4b6134..fec7d77318c 100644
--- a/src/features/SandboxDrive/UsageBreakdown.tsx
+++ b/src/features/SandboxDrive/UsageBreakdown.tsx
@@ -15,6 +15,7 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import UserAvatar from '@/components/UserAvatar';
import { formatSize } from '@/utils/format';
+import CleanupEntryButton from './Cleanup/CleanupEntryButton';
import type { DriveUsageRefreshResult, useDriveUsage } from './useDriveData';
/** The market's code for a usage refresh whose walk did not finish. */
@@ -479,8 +480,14 @@ export const UsageBreakdown = memo<{
{t(refused ? 'drive.usage.over' : 'drive.usage.overBilled')}
</Text>
)}
- {/* While writes are refused, the way to keep saving — not only the fact. */}
- {refused && <SandboxStorageOverQuotaAction />}
+ {/* While writes are refused, the ways to keep saving — not only the fact:
+ free up space, or let the plan take more. */}
+ {refused && (
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <CleanupEntryButton />
+ <SandboxStorageOverQuotaAction />
+ </Flexbox>
+ )}
</Flexbox>
);
});
diff --git a/src/features/SandboxDrive/index.tsx b/src/features/SandboxDrive/index.tsx
index 1ec785e7e72..e531c04d9d1 100644
--- a/src/features/SandboxDrive/index.tsx
+++ b/src/features/SandboxDrive/index.tsx
@@ -2,7 +2,7 @@
import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';
import { Button, Center, Flexbox, Icon, Spin, Tabs, Text } from '@lobehub/ui';
-import { LockIcon, UsersIcon } from 'lucide-react';
+import { ChartPieIcon, LockIcon, UsersIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,9 +11,11 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import { MAX_WIDTH } from '@/const/layoutTokens';
import { useSandboxDriveEntitlement } from '@/hooks/useSandboxDriveEntitlement';
+import StorageCleanup from './Cleanup';
import DriveExplorer from './DriveExplorer';
import DriveUsage from './DriveUsage';
-import { useDriveTab } from './useDriveTab';
+import OverQuotaBanner from './OverQuotaBanner';
+import { useDriveTab, useDriveView } from './useDriveTab';
/**
* The cloud sandbox's drives: what is on them, how much they hold, and — for
@@ -32,6 +34,7 @@ const DriveSettings = memo(() => {
const { entitled, error, retry } = useSandboxDriveEntitlement();
const drives: SandboxDrive[] = isWorkspace ? ['public', 'personal'] : ['personal'];
const [active, setActive] = useDriveTab(drives);
+ const [view, setView] = useDriveView();
// Whether the plan has a drive could not be read: say so and offer it
// again, rather than a spinner that never resolves.
@@ -80,13 +83,33 @@ const DriveSettings = memo(() => {
<DriveUsage />
</Flexbox>
)}
+ {view === 'files' && <OverQuotaBanner onCleanup={() => setView('cleanup')} />}
{/* Keyed on the drive, so a path browsed on one never carries to the other. */}
- <DriveExplorer
- drive={active}
- isWorkspace={isWorkspace}
- key={active}
- toolbarExtra={isWorkspace ? undefined : <DriveUsage />}
- />
+ {view === 'cleanup' ? (
+ <StorageCleanup
+ drive={active}
+ key={`${workspaceId ?? 'personal'}:${active}`}
+ onBack={() => setView('files')}
+ />
+ ) : (
+ <DriveExplorer
+ drive={active}
+ isWorkspace={isWorkspace}
+ key={`${workspaceId ?? 'personal'}:${active}`}
+ toolbarExtra={
+ <>
+ {!isWorkspace && <DriveUsage />}
+ <Button
+ icon={<Icon icon={ChartPieIcon} />}
+ size={'small'}
+ onClick={() => setView('cleanup')}
+ >
+ {t('drive.cleanup.entry')}
+ </Button>
+ </>
+ }
+ />
+ )}
</Flexbox>
);
});
diff --git a/src/features/SandboxDrive/useDriveTab.ts b/src/features/SandboxDrive/useDriveTab.ts
index 6100884f422..3a0d3795500 100644
--- a/src/features/SandboxDrive/useDriveTab.ts
+++ b/src/features/SandboxDrive/useDriveTab.ts
@@ -27,3 +27,31 @@ export const useDriveTab = (drives: SandboxDrive[]) => {
return [active, setActive] as const;
};
+
+export type DriveView = 'cleanup' | 'files';
+
+/**
+ * Which view of the drive is open — its files, or the space analysis and
+ * cleanup — kept in `?view=cleanup` so a quota refusal elsewhere can link
+ * straight to it.
+ */
+export const useDriveView = () => {
+ const [params, setParams] = useSearchParams();
+ const view: DriveView = params.get('view') === 'cleanup' ? 'cleanup' : 'files';
+
+ const setView = useCallback(
+ (next: DriveView) =>
+ setParams(
+ (prev) => {
+ const updated = new URLSearchParams(prev);
+ if (next === 'cleanup') updated.set('view', 'cleanup');
+ else updated.delete('view');
+ return updated;
+ },
+ { replace: true },
+ ),
+ [setParams],
+ );
+
+ return [view, setView] as const;
+};
diff --git a/src/services/sandboxStorage.ts b/src/services/sandboxStorage.ts
index ac673a93acf..2368bc20f1d 100644
--- a/src/services/sandboxStorage.ts
+++ b/src/services/sandboxStorage.ts
@@ -216,6 +216,23 @@ class SandboxStorageService {
recursive?: boolean;
topicId?: string;
}) => lambdaClient.sandboxStorage.removeFile.mutate(params);
+
+ /**
+ * One step of the drive's space analysis; call again while `status` is not
+ * `done`. Works on a drive over its quota, which is what it is for.
+ */
+ analyzeStorage = async (params: { drive?: SandboxDrive; restart?: boolean; top?: number } = {}) =>
+ lambdaClient.sandboxStorage.analyzeStorage.mutate(params);
+
+ /**
+ * Delete several files or folders for good, past the quota. `done: false`
+ * means time ran out: call again with `pending`.
+ */
+ deleteFiles = async (params: {
+ drive?: SandboxDrive;
+ paths: string[];
+ regenerableOnly?: boolean;
+ }) => lambdaClient.sandboxStorage.deleteFiles.mutate(params);
}
export const sandboxStorageService = new SandboxStorageService();
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.test.ts b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.test.ts
new file mode 100644
index 00000000000..87cad0b7cb9
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.test.ts
@@ -0,0 +1,28 @@
+import { CLOUD_SANDBOX_DELETE_AUDIT } from '@lobechat/builtin-tool-cloud-sandbox';
+import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
+import { describe, expect, it, vi } from 'vitest';
+
+import { clientInterventionAudits } from './interventionAudits';
+
+vi.mock('@/services/dashboard', () => ({ dashboardService: {} }));
+vi.mock('@/services/electron/localFileService', () => ({ localFileService: {} }));
+vi.mock('@/store/user/store', () => ({ getUserStoreState: () => ({ settings: {} }) }));
+
+describe('clientInterventionAudits', () => {
+ // A dynamic audit missing here falls back to the manifest's default on
+ // client-driven runs, which for a permanent delete means running unasked.
+ it('registers every audit the server registers', () => {
+ for (const type of Object.keys(dynamicInterventionAudits)) {
+ expect(clientInterventionAudits).toHaveProperty(type);
+ }
+ });
+
+ it('asks before a sandbox delete unless it is regenerable only', async () => {
+ const audit = clientInterventionAudits[CLOUD_SANDBOX_DELETE_AUDIT];
+
+ await expect(audit({ paths: ['/workspace/notes.md'] })).resolves.toBe(true);
+ await expect(
+ audit({ paths: ['/workspace/a/node_modules'], regenerableOnly: true }),
+ ).resolves.toBe(false);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts
index 8ef45216709..33c6ca9a521 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts
@@ -2,6 +2,7 @@ import {
AGENT_ACCOUNT_OUTBOUND_AUDIT,
agentAccountOutboundAudit,
} from '@lobechat/builtin-tool-agent-account';
+import { CLOUD_SANDBOX_DELETE_AUDIT, deleteFilesAudit } from '@lobechat/builtin-tool-cloud-sandbox';
import { createDryRunAudit, DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';
import { isDesktop } from '@lobechat/const';
@@ -21,6 +22,9 @@ export const clientInterventionAudits = {
loadVersion: (widgetId, versionId) => dashboardService.getVersion(widgetId, versionId),
}),
[AGENT_ACCOUNT_OUTBOUND_AUDIT]: agentAccountOutboundAudit,
+ // Without it a client-driven run falls back to the manifest's `never` and
+ // a permanent delete would run unasked.
+ [CLOUD_SANDBOX_DELETE_AUDIT]: deleteFilesAudit,
pathScopeAudit: createPathScopeAudit({
areAllPathsSafe: async ({ paths, resolveAgainstScope }) => {
if (!isDesktop) return false;