🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(drive): download drive files, and folders as zip (#22095)
Rdmclin23ab3bc7a4378
diff --git a/apps/server/src/modules/S3/index.test.ts b/apps/server/src/modules/S3/index.test.tsindex dc98d43f51e..a4eb8eb6d79 100644--- a/apps/server/src/modules/S3/index.test.ts+++ b/apps/server/src/modules/S3/index.test.ts@@ -8,6 +8,7 @@ import {DeleteObjectsCommand,GetObjectCommand,HeadObjectCommand,+ ListObjectsV2Command,paginateListParts,PutObjectCommand,S3Client,@@ -269,6 +270,31 @@ describe('FileS3', () => {});});+ describe('listFileKeys', () => {+ it('lists one bounded page of keys under the prefix', async () => {+ const s3 = new FileS3();+ mockS3ClientSend.mockResolvedValue({+ Contents: [{ Key: 'downloads/2026-10-30/a' }, {}, { Key: 'downloads/2026-10-31/b' }],+ });++ await expect(s3.listFileKeys('downloads/', 50)).resolves.toEqual([+ 'downloads/2026-10-30/a',+ 'downloads/2026-10-31/b',+ ]);+ expect(ListObjectsV2Command).toHaveBeenCalledWith({+ Bucket: 'test-bucket',+ MaxKeys: 50,+ Prefix: 'downloads/',+ });+ });++ it('answers no keys for an empty prefix', async () => {+ mockS3ClientSend.mockResolvedValue({});++ await expect(new FileS3().listFileKeys('downloads/')).resolves.toEqual([]);+ });+ });+describe('deleteFiles', () => {it('should delete multiple files with correct parameters', async () => {const s3 = new FileS3();@@ -496,6 +522,21 @@ describe('FileS3', () => {url: 'https://presigned-url.example.com',});});++ it('signs a private upload without the public-read ACL even when the bucket sets one', async () => {+ const s3 = new FileS3();++ const result = await s3.createPreSignedUpload('private-copy.zip', undefined, {+ private: true,+ });++ expect(PutObjectCommand).toHaveBeenCalledWith({+ ACL: undefined,+ Bucket: 'test-bucket',+ Key: 'private-copy.zip',+ });+ expect(result).toEqual({ headers: undefined, url: 'https://presigned-url.example.com' });+ });});describe('multipart uploads', () => {diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.tsindex 2827db091ce..af5aeb0c5af 100644--- a/apps/server/src/modules/S3/index.ts+++ b/apps/server/src/modules/S3/index.ts@@ -6,6 +6,7 @@ import {DeleteObjectsCommand,GetObjectCommand,HeadObjectCommand,+ ListObjectsV2Command,paginateListParts,PutObjectCommand,S3Client,@@ -125,6 +126,18 @@ export class S3 {return results.at(-1)!;}+ /**+ * Up to `limit` keys under `prefix`, in the bucket's lexical order — one+ * page, never the whole listing, so a caller sweeping a prefix stays bounded.+ */+ public async listFileKeys(prefix: string, limit = 1000): Promise<string[]> {+ const response = await this.client.send(+ new ListObjectsV2Command({ Bucket: this.bucket, MaxKeys: limit, Prefix: prefix }),+ );++ return (response.Contents ?? []).flatMap((object) => (object.Key ? [object.Key] : []));+ }+public async getFileContent(key: string, byteLength?: number): Promise<string> {const boundedLength = byteLength ? Math.max(1, Math.floor(byteLength)) : undefined;const command = new GetObjectCommand({@@ -182,12 +195,19 @@ export class S3 {return upload.url;}+ /**+ * A presigned PUT for one object. `private` signs it without the public-read+ * ACL `S3_SET_ACL` otherwise applies — for a transient copy that must only be+ * reachable through a short-lived signed GET.+ */public async createPreSignedUpload(key: string,contentLength?: number,+ options?: { private?: boolean },): Promise<PreSignedUpload> {+ const publicRead = this.setAcl && !options?.private;const command = new PutObjectCommand({- ACL: this.setAcl ? PUBLIC_READ_ACL_HEADER : undefined,+ ACL: publicRead ? PUBLIC_READ_ACL_HEADER : undefined,Bucket: this.bucket,...(contentLength === undefined ? {} : { ContentLength: contentLength }),Key: key,@@ -196,7 +216,7 @@ export class S3 {const url = await getSignedUrl(this.presignClient, command, { expiresIn: 3600 });return {- headers: this.setAcl ? { 'x-amz-acl': PUBLIC_READ_ACL_HEADER } : undefined,+ headers: publicRead ? { 'x-amz-acl': PUBLIC_READ_ACL_HEADER } : undefined,url,};}diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.tsindex 902bbcbbcfc..8f0611b5c20 100644--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts@@ -50,6 +50,9 @@ const plane = vi.hoisted(() => ({const entitlement = vi.hoisted(() => ({ claim: vi.fn() }));+/** The sandbox a download runs its packing command in, and how it was addressed. */+const downloads = vi.hoisted(() => ({ callTool: vi.fn(), createSandboxService: vi.fn() }));+/** The storage key of every client the router made, in order: whose drive each call reached. */const reached = vi.hoisted(() => [] as (string | undefined)[]);@@ -72,6 +75,7 @@ vi.mock('@/server/services/sandbox', async () => {...binding,...(await vi.importActual<object>('@/server/services/sandbox/driveAccess')),...(await vi.importActual<object>('@/server/services/sandbox/driveUsage')),+ createSandboxService: downloads.createSandboxService,forgetDriveFolders: vi.fn(),resolveSandboxSessionConfig: vi.fn(),resolveSandboxStorageClaim: entitlement.claim,@@ -89,6 +93,19 @@ vi.mock('@/server/services/market', () => ({}),}));+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return {+ createDownloadUrl: async (key: string, name: string) => `https://files/${key}?as=${name}`,+ createPreSignedUrlForPreview: async (key: string) => `https://files/${key}?inline`,+ createPreSignedUpload: async (key: string) => ({ url: `https://upload/${key}` }),+ deleteFile: async () => undefined,+ deleteFiles: async () => undefined,+ listFileKeys: async () => [],+ };+ }),+}));+const asMember = (userId: string) => ({ serverDB, userId, workspaceId }) as any;const drive = (userId = ownerId) => sandboxStorageRouter.createCaller(asMember(userId));const definitions = (userId = ownerId) => environmentRouter.createCaller(asMember(userId));@@ -137,6 +154,11 @@ beforeEach(async () => {plane.readOccupancy.mockReset().mockResolvedValue({ held: [], unavailable: false });plane.renameFile.mockReset().mockImplementation(async ({ newPath }) => ({ path: newPath }));plane.writeFile.mockReset().mockImplementation(async ({ path }) => ({ path }));+ downloads.callTool.mockReset();+ downloads.createSandboxService.mockReset().mockImplementation(() => ({+ callTool: downloads.callTool,+ capabilities: { shell: true },+ }));});afterEach(reset);@@ -579,3 +601,90 @@ describe('drive usage', () => {expect(plane.listFiles).not.toHaveBeenCalled();});});++describe('downloading from the drive', () => {+ const answer = (result: object) =>+ downloads.callTool.mockResolvedValue({+ result: { exitCode: 0, stdout: `LOBE_DRIVE_DOWNLOAD_RESULT ${JSON.stringify(result)}\n` },+ success: true,+ });++ /** What the packing command was told to read, decoded from the command. */+ const packed = () => {+ const [, params] = downloads.callTool.mock.calls[0] as [string, { command: string }];+ const payload = /LOBE_DRIVE_DOWNLOAD='([^']+)'/.exec(params.command)![1];+ return JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));+ };++ it('zips a folder on the drive it names, leaving a hidden directory inside it out', async () => {+ await legacyPrivateFolder(ownerId, 'projects/secret');+ answer({ contentType: 'application/zip', kind: 'directory', ok: true, size: 7 });++ const result = await drive(memberId).prepareDownload({ drive: 'public', path: 'projects' });++ expect(result).toMatchObject({ fileName: 'projects.zip', kind: 'directory', size: 7 });+ expect(result.url).toMatch(/^https:\/\/files\/sandbox-drive-downloads\/.+\?as=projects\.zip$/);+ expect(downloads.createSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({+ sandboxMode: 'drive',+ topicId: `sandbox-drive-download:${STORAGE_KEY}`,+ userId: memberId,+ }),+ );+ expect(packed()).toMatchObject({ hidden: ['projects/secret'], path: 'projects' });+ });++ it("downloads from the caller's own personal drive", async () => {+ answer({ contentType: 'text/plain', kind: 'file', ok: true, size: 3 });++ await drive(memberId).prepareDownload({ drive: 'personal', path: 'notes.txt' });++ expect(downloads.createSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: `sandbox-drive-download:${personalKey(memberId)}` }),+ );+ expect(packed()).toMatchObject({ hidden: [], path: 'notes.txt' });+ });++ it('answers a hidden directory as if it were not there, without starting a sandbox', async () => {+ await legacyPrivateFolder(ownerId, 'secret');++ await expect(+ drive(ownerId).prepareDownload({ drive: 'public', path: 'secret/.env' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'PATH_NOT_FOUND' });+ expect(downloads.callTool).not.toHaveBeenCalled();+ });++ it('says a folder is too large in a code the client translates', async () => {+ answer({ code: 'TOO_LARGE', ok: false });++ await expect(drive(ownerId).prepareDownload({ path: 'big' })).rejects.toMatchObject({+ code: 'PAYLOAD_TOO_LARGE',+ message: 'DOWNLOAD_TOO_LARGE',+ });+ });++ it('previews a file inline, through the same read rules as a download', async () => {+ answer({ contentType: 'image/png', kind: 'file', ok: true, size: 5 });++ const result = await drive(memberId).preparePreview({ drive: 'public', path: 'shots/a.png' });++ expect(result).toMatchObject({ contentType: 'image/png', fileName: 'a.png', kind: 'file' });+ expect(result.url).toMatch(/^https:\/\/files\/sandbox-drive-downloads\/.+\?inline$/);+ expect(packed()).toMatchObject({ fileOnly: true, path: 'shots/a.png' });+ });++ it('refuses to preview a hidden directory, and a folder in a code the client translates', async () => {+ await legacyPrivateFolder(ownerId, 'secret');++ await expect(+ drive(ownerId).preparePreview({ drive: 'public', path: 'secret/a.txt' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'PATH_NOT_FOUND' });+ expect(downloads.callTool).not.toHaveBeenCalled();++ answer({ code: 'NOT_A_FILE', ok: false });+ await expect(drive(ownerId).preparePreview({ path: 'projects' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ message: 'PREVIEW_NOT_A_FILE',+ });+ });+});diff --git a/apps/server/src/routers/lambda/sandboxStorage/download.ts b/apps/server/src/routers/lambda/sandboxStorage/download.tsnew file mode 100644index 00000000000..f357edb92c9--- /dev/null+++ b/apps/server/src/routers/lambda/sandboxStorage/download.ts@@ -0,0 +1,83 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { router } from '@/libs/trpc/lambda';+import { FileService } from '@/server/services/file';+import { createSandboxService } from '@/server/services/sandbox';+import {+ type DriveCopyPurpose,+ DriveDownloadError,+ prepareDriveDownload,+} from '@/server/services/sandbox/driveDownload';++import { assertReadable, resolveDriveScope } from './driveScope';+import { instanceProcedure } from './procedures';+import { driveSchema, relativePathSchema } from './schemas';++const ERROR_CODES: Record<DriveDownloadError['code'], TRPCError['code']> = {+ DOWNLOAD_FAILED: 'BAD_GATEWAY',+ DOWNLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE',+ DOWNLOAD_UNAVAILABLE: 'NOT_IMPLEMENTED',+ PATH_NOT_FOUND: 'NOT_FOUND',+ PREVIEW_NOT_A_FILE: 'BAD_REQUEST',+};++/**+ * The topic the download sessions run under. Not a topic of ours — it is never+ * looked up — but the execution plane keys a session to one, and binds that+ * session to the drive its first call names. One per drive, so downloading+ * from the public drive and then the personal one does not tear down and+ * restart the same sandbox each time.+ */+export const driveDownloadTopicId = (storageKey: string) => `sandbox-drive-download:${storageKey}`;++/**+ * Copies one path of the drive to object storage from a sandbox session and+ * answers with a link to it. Read the way a listing is — a member reaches+ * whatever they can browse — and a hidden environment directory is refused+ * when named and left out of any folder that holds it.+ *+ * A mutation, not a query: it starts a sandbox session and writes an object+ * to storage, and a refetch-on-focus must never repeat that.+ */+const copyProcedure = (purpose: DriveCopyPurpose) =>+ instanceProcedure+ .input(z.object({ drive: driveSchema, path: relativePathSchema }))+ .mutation(async ({ ctx, input }) => {+ const scope = await resolveDriveScope(ctx);+ assertReadable(input.path, scope);++ const sandbox = createSandboxService({+ marketService: ctx.marketService,+ sandboxMode: 'drive',+ topicId: driveDownloadTopicId(ctx.claim.key),+ userId: ctx.userId,+ });++ try {+ return await prepareDriveDownload({+ fileService: new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),+ hidden: scope.hidden,+ path: input.path,+ purpose,+ sandbox,+ });+ } catch (error) {+ if (error instanceof DriveDownloadError) {+ throw new TRPCError({ cause: error, code: ERROR_CODES[error.code], message: error.code });+ }+ throw error;+ }+ });++export const downloadRouter = router({+ /** A link that downloads one file of the drive as it is, or one folder as a zip. */+ prepareDownload: copyProcedure('download'),++ /**+ * A link one file of the drive can be shown in the page from — answered+ * inline, with the type the file's name implies, so the viewer can render+ * it. A folder is refused; it has nothing to show but its listing.+ */+ preparePreview: copyProcedure('preview'),+});diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.tsindex 44250bd776a..befcd60c4fc 100644--- a/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts@@ -46,6 +46,8 @@ function expected(): Array<['listGithubRepositories', 'query', 11],['listInstanceSessions', 'query', 15],['listInstances', 'query', 15],+ ['prepareDownload', 'mutation', 15],+ ['preparePreview', 'mutation', 15],['readFile', 'query', 15],['refreshStorageUsage', 'mutation', 13],['removeEnvironment', 'mutation', 15],diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.ts b/apps/server/src/routers/lambda/sandboxStorage/index.tsindex d3b4ef0284e..f6b52285ae4 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 { downloadRouter } from './download';import { filesRouter } from './files';import { instanceBuildRouter } from './instanceBuild';import { instancesRouter } from './instances';@@ -23,6 +24,7 @@ import { storageRouter } from './storage';*/export const sandboxStorageRouter = mergeRouters(filesRouter,+ downloadRouter,storageRouter,instancesRouter,instanceBuildRouter,diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.tsindex b69df2f7268..d9154d62de9 100644--- a/apps/server/src/services/file/__tests__/index.test.ts+++ b/apps/server/src/services/file/__tests__/index.test.ts@@ -290,7 +290,7 @@ describe('FileService', () => {const result = await service.createPreSignedUpload(testKey);- expect(service['impl'].createPreSignedUpload).toHaveBeenCalledWith(testKey);+ expect(service['impl'].createPreSignedUpload).toHaveBeenCalledWith(testKey, undefined);expect(result).toBe(expectedUpload);});diff --git a/apps/server/src/services/file/impls/s3.ts b/apps/server/src/services/file/impls/s3.tsindex fa1ca7fb56e..a37a83befac 100644--- a/apps/server/src/services/file/impls/s3.ts+++ b/apps/server/src/services/file/impls/s3.ts@@ -52,6 +52,10 @@ export class S3StaticFileImpl implements FileServiceImpl {return this.s3.deleteFiles(keys);}+ async listFileKeys(prefix: string, limit?: number): Promise<string[]> {+ return this.s3.listFileKeys(prefix, limit);+ }+async getFileContent(key: string, byteLength?: number): Promise<string> {return byteLength === undefined? this.s3.getFileContent(key)@@ -66,8 +70,13 @@ export class S3StaticFileImpl implements FileServiceImpl {return this.s3.createPreSignedUrl(key);}- async createPreSignedUpload(key: string): Promise<PreSignedUpload> {- return this.s3.createPreSignedUpload(key);+ async createPreSignedUpload(+ key: string,+ options?: { private?: boolean },+ ): Promise<PreSignedUpload> {+ return options+ ? this.s3.createPreSignedUpload(key, undefined, options)+ : this.s3.createPreSignedUpload(key);}async getFileMetadata(key: string): Promise<{ contentLength: number; contentType?: string }> {diff --git a/apps/server/src/services/file/impls/type.ts b/apps/server/src/services/file/impls/type.tsindex d3b6c013055..2a183334723 100644--- a/apps/server/src/services/file/impls/type.ts+++ b/apps/server/src/services/file/impls/type.ts@@ -19,7 +19,7 @@ export interface FileServiceImpl {/*** Create pre-signed upload descriptor*/- createPreSignedUpload: (key: string) => Promise<PreSignedUpload>;+ createPreSignedUpload: (key: string, options?: { private?: boolean }) => Promise<PreSignedUpload>;/*** Create pre-signed upload URL@@ -76,6 +76,11 @@ export interface FileServiceImpl {*/getKeyFromFullUrl: (url: string) => Promise<string | null>;+ /**+ * Up to `limit` storage keys under a prefix, in lexical order+ */+ listFileKeys: (prefix: string, limit?: number) => Promise<string[]>;+/*** Upload buffer with specified content type (for any file type)*/diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex 2e668065492..b8cf812cf4f 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -83,6 +83,13 @@ export class FileService {return this.impl.deleteFiles(keys);}+ /**+ * Up to `limit` storage keys under a prefix, in lexical order+ */+ public async listFileKeys(prefix: string, limit?: number): Promise<string[]> {+ return this.impl.listFileKeys(prefix, limit);+ }+/*** Get file content*/@@ -109,8 +116,11 @@ export class FileService {/*** Create pre-signed upload descriptor*/- public async createPreSignedUpload(key: string): Promise<PreSignedUpload> {- return this.impl.createPreSignedUpload(key);+ public async createPreSignedUpload(+ key: string,+ options?: { private?: boolean },+ ): Promise<PreSignedUpload> {+ return this.impl.createPreSignedUpload(key, options);}/**diff --git a/apps/server/src/services/sandbox/__tests__/driveDownload.test.ts b/apps/server/src/services/sandbox/__tests__/driveDownload.test.tsnew file mode 100644index 00000000000..54d5f771cad--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/driveDownload.test.ts@@ -0,0 +1,428 @@+// @vitest-environment node+import { execFileSync, spawn, spawnSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { createServer, type Server } from 'node:http';+import type { AddressInfo } from 'node:net';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ buildDriveDownloadCommand,+ DRIVE_DOWNLOAD_MAX_BYTES,+ DRIVE_DOWNLOAD_URL_EXPIRES_IN,+ DRIVE_PREVIEW_URL_EXPIRES_IN,+ driveDownloadFileName,+ parseDriveDownloadOutput,+ prepareDriveDownload,+} from '../driveDownload';++const hasPython = spawnSync('python3', ['--version']).status === 0;++/**+ * The script the sandbox runs, run here for real: against a folder standing+ * in for the drive's root, uploading to a local server standing in for the+ * presigned URL.+ */+describe.skipIf(!hasPython)('the drive download script', () => {+ let server: Server;+ let uploadUrl: string;+ let received: { body: Buffer; headers: Record<string, unknown> }[];+ let root: string;+ let outside: string;++ beforeAll(async () => {+ server = createServer((request, response) => {+ const chunks: Buffer[] = [];+ request.on('data', (chunk) => chunks.push(chunk));+ request.on('end', () => {+ received.push({ body: Buffer.concat(chunks), headers: request.headers });+ response.writeHead(request.url?.includes('fail') ? 403 : 200);+ response.end();+ });+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ uploadUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/upload?sig=a'b"c`;+ });++ afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));++ beforeEach(() => {+ received = [];+ root = mkdtempSync(path.join(tmpdir(), 'drive-root-'));+ outside = mkdtempSync(path.join(tmpdir(), 'drive-outside-'));+ writeFileSync(path.join(outside, 'secret.txt'), 'not yours');++ mkdirSync(path.join(root, 'project/src'), { recursive: true });+ mkdirSync(path.join(root, 'project/empty'), { recursive: true });+ mkdirSync(path.join(root, 'project/private'), { recursive: true });+ writeFileSync(path.join(root, 'project/README.md'), '# hello');+ writeFileSync(path.join(root, 'project/src/index.ts'), 'export {};');+ writeFileSync(path.join(root, 'project/private/token'), 'hidden');+ symlinkSync(outside, path.join(root, 'project/escape'));+ symlinkSync(path.join(outside, 'secret.txt'), path.join(root, 'project/secret.txt'));+ writeFileSync(path.join(root, "report q3 'final'.bin"), Buffer.from([0, 1, 2, 255]));+ symlinkSync(outside, path.join(root, 'linked'));+ });++ afterEach(() => {+ rmSync(root, { force: true, recursive: true });+ rmSync(outside, { force: true, recursive: true });+ });++ const run = (+ target: string,+ options: {+ fileOnly?: boolean;+ hidden?: string[];+ maxBytes?: number;+ maxFiles?: number;+ url?: string;+ } = {},+ ) => {+ const command = buildDriveDownloadCommand({+ fileOnly: options.fileOnly,+ hidden: options.hidden ?? [],+ maxBytes: options.maxBytes ?? DRIVE_DOWNLOAD_MAX_BYTES,+ maxFiles: options.maxFiles ?? 100,+ path: target,+ uploadHeaders: { 'x-amz-acl': 'public-read' },+ uploadUrl: options.url ?? uploadUrl,+ });+ // Asynchronously, so the server in this process can answer the upload.+ return new Promise<ReturnType<typeof parseDriveDownloadOutput>>((resolve, reject) => {+ const child = spawn('sh', ['-c', command], { cwd: root });+ let stdout = '';+ child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString()));+ child.on('error', reject);+ child.on('close', () => resolve(parseDriveDownloadOutput(stdout)));+ });+ };++ const zipEntries = (body: Buffer) => {+ const file = path.join(outside, 'received.zip');+ writeFileSync(file, body);+ return execFileSync('python3', [+ '-c',+ 'import sys, zipfile; print("\\n".join(sorted(zipfile.ZipFile(sys.argv[1]).namelist())))',+ file,+ ])+ .toString()+ .trim()+ .split('\n');+ };++ it('uploads a file byte for byte, whatever its name holds', async () => {+ const outcome = await run("report q3 'final'.bin");++ expect(outcome).toEqual({+ contentType: 'application/octet-stream',+ kind: 'file',+ ok: true,+ size: 4,+ });+ expect(received).toHaveLength(1);+ expect([...received[0].body]).toEqual([0, 1, 2, 255]);+ expect(received[0].headers['x-amz-acl']).toBe('public-read');+ });++ it('zips a folder under its own name, leaving out links and hidden directories', async () => {+ const outcome = await run('project', { hidden: ['project/private'] });++ expect(outcome).toMatchObject({ contentType: 'application/zip', kind: 'directory', ok: true });+ expect(zipEntries(received[0].body)).toEqual([+ 'project/README.md',+ 'project/empty/',+ 'project/src/index.ts',+ ]);+ });++ it('refuses a path that leads out of the drive, a hidden one, and one that is not there', async () => {+ await expect(run('linked')).resolves.toEqual({ code: 'NOT_FOUND', ok: false });+ await expect(run('project/secret.txt')).resolves.toEqual({ code: 'NOT_FOUND', ok: false });+ await expect(run('project/private', { hidden: ['project/private'] })).resolves.toEqual({+ code: 'NOT_FOUND',+ ok: false,+ });+ await expect(run('missing')).resolves.toEqual({ code: 'NOT_FOUND', ok: false });+ expect(received).toHaveLength(0);+ });++ it('refuses a path that passes through a link, even to a real file', async () => {+ // `linked` points outside the drive; `linked/secret.txt` exists there.+ await expect(run('linked/secret.txt')).resolves.toEqual({ code: 'NOT_FOUND', ok: false });+ expect(received).toHaveLength(0);+ });++ it('packs what each file holds, read through the file itself', async () => {+ await run('project/src');++ const file = path.join(outside, 'src.zip');+ writeFileSync(file, received[0].body);+ const content = execFileSync('python3', [+ '-c',+ 'import sys, zipfile; sys.stdout.write(zipfile.ZipFile(sys.argv[1]).read("src/index.ts").decode())',+ file,+ ]).toString();+ expect(content).toBe('export {};');+ });++ // Root reads everything, so there is no unreadable file to make.+ it.skipIf(process.getuid?.() === 0)(+ 'fails rather than leaving out a file it cannot read',+ async () => {+ chmodSync(path.join(root, 'project/src/index.ts'), 0o000);++ await expect(run('project', { hidden: ['project/private'] })).resolves.toMatchObject({+ code: 'READ_FAILED',+ ok: false,+ path: 'project/src/index.ts',+ });+ expect(received).toHaveLength(0);+ },+ );++ it('counts directories toward the entry limit, so empty ones cannot run it unbounded', async () => {+ for (let index = 0; index < 5; index += 1)+ mkdirSync(path.join(root, `many/d${index}`), { recursive: true });++ await expect(run('many', { maxFiles: 3 })).resolves.toMatchObject({+ code: 'TOO_LARGE',+ ok: false,+ });+ expect(received).toHaveLength(0);+ });++ it('refuses to pack a folder for a preview, and still copies a file', async () => {+ await expect(run('project', { fileOnly: true })).resolves.toEqual({+ code: 'NOT_A_FILE',+ ok: false,+ });+ expect(received).toHaveLength(0);++ await expect(run('project/README.md', { fileOnly: true })).resolves.toMatchObject({+ contentType: 'text/markdown',+ kind: 'file',+ ok: true,+ });+ expect(received).toHaveLength(1);+ });++ it('refuses a folder over the size limit before packing it', async () => {+ await expect(run('project', { maxBytes: 5 })).resolves.toMatchObject({+ code: 'TOO_LARGE',+ ok: false,+ });+ expect(received).toHaveLength(0);+ });++ it('reports an upload the storage refused', async () => {+ await expect(run('project/README.md', { url: `${uploadUrl}&fail=1` })).resolves.toMatchObject({+ code: 'UPLOAD_FAILED',+ ok: false,+ status: 403,+ });+ });+});++describe('driveDownloadFileName', () => {+ it('names a folder after itself with .zip and a file as it is', () => {+ expect(driveDownloadFileName('a/b/project', 'directory')).toBe('project.zip');+ expect(driveDownloadFileName('a/report.pdf', 'file')).toBe('report.pdf');+ });+});++describe('prepareDriveDownload', () => {+ const fileService = {+ createDownloadUrl: vi.fn(async (key: string, name: string) => `https://cdn/${key}?as=${name}`),+ createPreSignedUrlForPreview: vi.fn(async (key: string) => `https://cdn/${key}?inline`),+ createPreSignedUpload: vi.fn(async (key: string) => ({+ headers: { 'x-amz-acl': 'public-read' },+ url: `https://upload/${key}`,+ })),+ deleteFile: vi.fn(async () => undefined),+ deleteFiles: vi.fn(async () => undefined),+ listFileKeys: vi.fn(async (): Promise<string[]> => []),+ };++ const sandboxAnswering = (stdout: string | undefined, shell = true) => ({+ callTool: vi.fn(async () => ({+ result: stdout === undefined ? null : { exitCode: 0, stdout },+ success: stdout !== undefined,+ })),+ capabilities: { shell } as any,+ });++ beforeEach(() => {+ fileService.createDownloadUrl.mockClear();+ fileService.createPreSignedUrlForPreview.mockClear();+ fileService.createPreSignedUpload.mockClear();+ fileService.deleteFile.mockClear();+ fileService.deleteFiles.mockClear();+ fileService.listFileKeys.mockReset().mockResolvedValue([]);+ });++ it('answers with an attachment link named after the folder', async () => {+ const sandbox = sandboxAnswering(+ 'noise\nLOBE_DRIVE_DOWNLOAD_RESULT {"ok":true,"kind":"directory","size":42,"contentType":"application/zip"}\n',+ );++ const result = await prepareDriveDownload({+ fileService,+ hidden: ['project/private'],+ path: 'project',+ sandbox,+ });++ const [key, uploadOptions] = fileService.createPreSignedUpload.mock.calls[0] as unknown as [+ string,+ unknown,+ ];+ expect(uploadOptions).toEqual({ private: true });+ expect(key).toMatch(/^sandbox-drive-downloads\/\d{4}-\d{2}-\d{2}\/[\da-f-]{36}$/);+ expect(fileService.createDownloadUrl).toHaveBeenCalledWith(+ key,+ 'project.zip',+ DRIVE_DOWNLOAD_URL_EXPIRES_IN,+ );+ expect(result).toEqual({+ contentType: 'application/zip',+ fileName: 'project.zip',+ kind: 'directory',+ size: 42,+ url: `https://cdn/${key}?as=project.zip`,+ });++ const [tool, params] = sandbox.callTool.mock.calls[0] as unknown as [string, any];+ expect(tool).toBe('runCommand');+ expect(params.command).not.toContain('https://upload');+ const payload = /LOBE_DRIVE_DOWNLOAD='([^']+)'/.exec(params.command)![1];+ expect(JSON.parse(Buffer.from(payload, 'base64').toString('utf8'))).toMatchObject({+ headers: { 'x-amz-acl': 'public-read' },+ hidden: ['project/private'],+ path: 'project',+ uploadUrl: `https://upload/${key}`,+ });+ });++ it('answers a preview with an inline link, and tells the script to refuse a folder', async () => {+ const sandbox = sandboxAnswering(+ 'LOBE_DRIVE_DOWNLOAD_RESULT {"ok":true,"kind":"file","size":9,"contentType":"application/pdf"}\n',+ );++ const result = await prepareDriveDownload({+ fileService,+ hidden: [],+ path: 'docs/report.pdf',+ purpose: 'preview',+ sandbox,+ });++ const [key] = fileService.createPreSignedUpload.mock.calls[0] as unknown as [string];+ expect(fileService.createPreSignedUrlForPreview).toHaveBeenCalledWith(+ key,+ DRIVE_PREVIEW_URL_EXPIRES_IN,+ );+ expect(fileService.createDownloadUrl).not.toHaveBeenCalled();+ expect(result).toEqual({+ contentType: 'application/pdf',+ fileName: 'report.pdf',+ kind: 'file',+ size: 9,+ url: `https://cdn/${key}?inline`,+ });++ const [, params] = sandbox.callTool.mock.calls[0] as unknown as [string, any];+ const payload = /LOBE_DRIVE_DOWNLOAD='([^']+)'/.exec(params.command)![1];+ expect(JSON.parse(Buffer.from(payload, 'base64').toString('utf8'))).toMatchObject({+ fileOnly: true,+ path: 'docs/report.pdf',+ });+ });++ it.each([+ ['NOT_A_FILE', 'PREVIEW_NOT_A_FILE'],+ ['NOT_FOUND', 'PATH_NOT_FOUND'],+ ['TOO_LARGE', 'DOWNLOAD_TOO_LARGE'],+ ['UPLOAD_FAILED', 'DOWNLOAD_FAILED'],+ ])('turns the script refusing with %s into %s', async (code, expected) => {+ const sandbox = sandboxAnswering(`LOBE_DRIVE_DOWNLOAD_RESULT {"ok":false,"code":"${code}"}`);++ await expect(+ prepareDriveDownload({ fileService, hidden: [], path: 'a', sandbox }),+ ).rejects.toMatchObject({ code: expected });+ expect(fileService.createDownloadUrl).not.toHaveBeenCalled();+ });++ it('deletes the copy a failed download may have left, and keeps the failure', async () => {+ const sandbox = sandboxAnswering(+ 'LOBE_DRIVE_DOWNLOAD_RESULT {"ok":false,"code":"UPLOAD_FAILED"}',+ );++ await expect(+ prepareDriveDownload({ fileService, hidden: [], path: 'a', sandbox }),+ ).rejects.toMatchObject({ code: 'DOWNLOAD_FAILED' });+ expect(fileService.deleteFile).toHaveBeenCalledWith(+ fileService.createPreSignedUpload.mock.calls[0][0],+ );+ });++ it('sweeps copies from before yesterday, and keeps the download when the sweep fails', async () => {+ const now = new Date('2026-11-02T00:30:00Z');+ fileService.listFileKeys.mockResolvedValue([+ 'sandbox-drive-downloads/2026-10-30/a',+ 'sandbox-drive-downloads/2026-10-31/b',+ 'sandbox-drive-downloads/2026-11-01/c',+ 'sandbox-drive-downloads/2026-11-02/d',+ ]);+ const answer =+ 'LOBE_DRIVE_DOWNLOAD_RESULT {"ok":true,"kind":"file","size":1,"contentType":"text/plain"}';++ await prepareDriveDownload({+ fileService,+ hidden: [],+ now,+ path: 'a',+ sandbox: sandboxAnswering(answer),+ });++ expect(fileService.listFileKeys).toHaveBeenCalledWith('sandbox-drive-downloads/');+ expect(fileService.deleteFiles).toHaveBeenCalledWith([+ 'sandbox-drive-downloads/2026-10-30/a',+ 'sandbox-drive-downloads/2026-10-31/b',+ ]);+ expect(fileService.deleteFile).not.toHaveBeenCalled();++ fileService.listFileKeys.mockRejectedValue(new Error('AccessDenied'));+ await expect(+ prepareDriveDownload({+ fileService,+ hidden: [],+ now,+ path: 'a',+ sandbox: sandboxAnswering(answer),+ }),+ ).resolves.toMatchObject({ fileName: 'a' });+ });++ it('fails when the command never answered', async () => {+ await expect(+ prepareDriveDownload({+ fileService,+ hidden: [],+ path: 'a',+ sandbox: sandboxAnswering(undefined),+ }),+ ).rejects.toMatchObject({ code: 'DOWNLOAD_FAILED' });+ });++ it('is unavailable on a sandbox without a shell', async () => {+ const sandbox = sandboxAnswering('', false);++ await expect(+ prepareDriveDownload({ fileService, hidden: [], path: 'a', sandbox }),+ ).rejects.toMatchObject({ code: 'DOWNLOAD_UNAVAILABLE' });+ expect(sandbox.callTool).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/sandbox/driveDownload.ts b/apps/server/src/services/sandbox/driveDownload.tsnew file mode 100644index 00000000000..1ebc53baf49--- /dev/null+++ b/apps/server/src/services/sandbox/driveDownload.ts@@ -0,0 +1,503 @@+import { randomUUID } from 'node:crypto';++import debug from 'debug';++import type { PreSignedUpload } from '@/server/modules/S3';++import type { SandboxService } from './types';++const log = debug('lobe-server:sandbox:drive-download');++/**+ * Ceiling on what one download packs or carries: the bytes of the files it+ * reads, before compression. Large enough for any folder a person keeps work+ * in, small enough that packing it and uploading it fit in one request rather+ * than outliving it. A checkout with its dependencies installed can pass it;+ * the refusal says so instead of timing out.+ */+export const DRIVE_DOWNLOAD_MAX_BYTES = 1024 * 1024 * 1024;++/** The same idea for the number of files: walking a million costs more than reading them. */+export const DRIVE_DOWNLOAD_MAX_FILES = 50_000;++/** How long the sandbox may spend packing and uploading. */+export const DRIVE_DOWNLOAD_TIMEOUT_MS = 180_000;++/** How long the link the browser follows stays valid. */+export const DRIVE_DOWNLOAD_URL_EXPIRES_IN = 15 * 60;++/**+ * How long a preview link stays valid: longer than a download's, since a+ * video or PDF keeps fetching ranges for as long as it stays open. Still well+ * inside the day the sweep keeps every copy for.+ */+export const DRIVE_PREVIEW_URL_EXPIRES_IN = 60 * 60;++/**+ * What the copy is for: `download` saves it — a folder packed as a zip —+ * and `preview` shows one file in the page, so a folder is refused.+ */+export type DriveCopyPurpose = 'download' | 'preview';++/**+ * Where the transient copies go, one folder per UTC day+ * (`sandbox-drive-downloads/2026-11-01/<uuid>`), which is what lets them be+ * swept by date without a record of each one.+ */+export const DRIVE_DOWNLOAD_PREFIX = 'sandbox-drive-downloads/';++/** Marks the one line of the command's output that is its answer. */+const RESULT_MARKER = 'LOBE_DRIVE_DOWNLOAD_RESULT ';++/**+ * Packs (a folder) or takes as it is (a file) one path on the drive and PUTs it+ * to the upload URL, from inside a sandbox session the drive is mounted in.+ *+ * The working directory is the drive's root, which is what every relative+ * path here is resolved against. Other members and sandboxes may be changing+ * the drive while this runs, so nothing is checked by name and then read by+ * name: the target is opened one component at a time beneath the root with+ * `O_NOFOLLOW`, a folder is walked with `os.fwalk` (directory descriptors, no+ * links followed), and each file is read through the descriptor it was opened+ * as. A link anywhere is never followed — the target that is or passes through+ * one is refused, and one inside a folder is left out. The hidden directories+ * the caller names are skipped as if they were not there.+ *+ * Anything that cannot be read fails the download rather than leaving a hole+ * in an archive that claims to be complete. The archive is built in `/tmp`,+ * never on the drive, so it costs the drive no quota.+ *+ * It prints exactly one {@link RESULT_MARKER} line, success or not, and always+ * exits 0: a non-zero exit would read as "the command could not run" and lose+ * the reason.+ */+const SCRIPT = String.raw`+import base64, errno, json, mimetypes, os, posixpath, stat, sys, tempfile, time, urllib.error, urllib.request, zipfile++MARKER = ${JSON.stringify(RESULT_MARKER)}+NOFOLLOW = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK+NOT_THERE = (errno.ENOENT, errno.ENOTDIR, errno.ELOOP)++def done(**result):+ sys.stdout.write(MARKER + json.dumps(result) + "\n")+ sys.stdout.flush()+ sys.exit(0)++params = json.loads(base64.b64decode(os.environ["LOBE_DRIVE_DOWNLOAD"]).decode("utf-8"))+max_bytes = int(params["maxBytes"])+max_files = int(params["maxFiles"])++def within(path, parent):+ return path == parent or path.startswith(parent + "/")++hidden = [posixpath.normpath(entry) for entry in params.get("hidden", [])]++def is_hidden(rel):+ return any(within(rel, entry) for entry in hidden)++target = posixpath.normpath(params["path"])+if target in ("", ".") or target.startswith("/") or target == ".." or target.startswith("../") or is_hidden(target):+ done(ok=False, code="NOT_FOUND")++root_fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY)++def open_beneath(rel):+ """Opens a path under the root without following a link at any component."""+ parts = rel.split("/")+ fd = os.dup(root_fd)+ try:+ for part in parts[:-1]:+ child = os.open(part, NOFOLLOW | os.O_DIRECTORY, dir_fd=fd)+ os.close(fd)+ fd = child+ return os.open(parts[-1], NOFOLLOW, dir_fd=fd)+ finally:+ os.close(fd)++try:+ target_fd = open_beneath(target)+except OSError as error:+ done(ok=False, code="NOT_FOUND" if error.errno in NOT_THERE else "READ_FAILED")++def read_failed(rel, error):+ done(ok=False, code="READ_FAILED", path=rel, message=str(error)[:200])++def raise_error(error):+ raise error++def walk():+ """The folder's directories, each with its regular files' (name, stat), hidden ones left out."""+ for current, dirnames, filenames, dir_fd in os.fwalk(".", dir_fd=target_fd, follow_symlinks=False, onerror=raise_error):+ sub = posixpath.normpath(current)+ rel = target if sub == "." else posixpath.join(target, sub)+ dirnames[:] = sorted(name for name in dirnames if not is_hidden(posixpath.join(rel, name)))+ files = []+ for name in sorted(filenames):+ try:+ info = os.stat(name, dir_fd=dir_fd, follow_symlinks=False)+ except OSError as error:+ read_failed(posixpath.join(rel, name), error)+ # Links and special files are not content of the folder.+ if stat.S_ISREG(info.st_mode):+ files.append((name, info))+ yield rel, dirnames, files, dir_fd++def zip_info(name, info):+ entry = zipfile.ZipInfo(name, date_time=time.localtime(max(info.st_mtime, 315532800))[:6])+ entry.external_attr = (info.st_mode & 0xFFFF) << 16+ return entry++upload_fd = None+cleanup = None++try:+ info = os.fstat(target_fd)+ if stat.S_ISDIR(info.st_mode):+ if params.get("fileOnly"):+ done(ok=False, code="NOT_A_FILE")+ total = 0+ count = 0+ try:+ for _, _, files, _ in walk():+ # Every directory is an entry walked, and maybe one archived.+ count += len(files) + 1+ total += sum(entry.st_size for _, entry in files)+ if total > max_bytes or count > max_files:+ done(ok=False, code="TOO_LARGE", bytes=total, files=count)+ except OSError as error:+ read_failed(target, error)++ base = posixpath.dirname(target)+ handle, cleanup = tempfile.mkstemp(dir="/tmp" if os.path.isdir("/tmp") else None, suffix=".zip")+ os.close(handle)+ # The drive can change between the two walks, so the ceilings hold+ # again here, on what is actually read rather than on what was listed.+ packed_bytes = 0+ packed_entries = 0++ def over_limit():+ if packed_bytes > max_bytes or packed_entries > max_files:+ done(ok=False, code="TOO_LARGE", bytes=packed_bytes, files=packed_entries)++ with zipfile.ZipFile(cleanup, "w", zipfile.ZIP_DEFLATED, allowZip64=True, compresslevel=1) as archive:+ try:+ for rel, dirnames, files, dir_fd in walk():+ packed_entries += 1+ over_limit()+ name = posixpath.relpath(rel, base) if base else rel+ if not files and not dirnames:+ archive.writestr(zip_info(name + "/", os.fstat(dir_fd)), b"")+ for file_name, _ in files:+ path = posixpath.join(rel, file_name)+ try:+ fd = os.open(file_name, NOFOLLOW, dir_fd=dir_fd)+ except OSError as error:+ # Became a link since it was listed: still not followed.+ if error.errno == errno.ELOOP:+ continue+ read_failed(path, error)+ with os.fdopen(fd, "rb") as source:+ current = os.fstat(source.fileno())+ if not stat.S_ISREG(current.st_mode):+ continue+ packed_entries += 1+ over_limit()+ entry = zip_info(posixpath.join(name, file_name), current)+ entry.compress_type = zipfile.ZIP_DEFLATED+ with archive.open(entry, "w", force_zip64=True) as sink:+ while True:+ chunk = source.read(1024 * 1024)+ if not chunk:+ break+ packed_bytes += len(chunk)+ over_limit()+ sink.write(chunk)+ except OSError as error:+ read_failed(target, error)+ upload_fd = os.open(cleanup, os.O_RDONLY)+ content_type = "application/zip"+ kind = "directory"+ elif stat.S_ISREG(info.st_mode):+ if info.st_size > max_bytes:+ done(ok=False, code="TOO_LARGE", bytes=info.st_size, files=1)+ upload_fd = target_fd+ content_type = mimetypes.guess_type(target)[0] or "application/octet-stream"+ kind = "file"+ else:+ done(ok=False, code="NOT_FOUND")++ # Measured again right before sending: a file can grow after it was checked.+ size = os.fstat(upload_fd).st_size+ if size > max_bytes:+ done(ok=False, code="TOO_LARGE", bytes=size, files=1)++ class Capped:+ """The first size bytes and no more, whatever is appended meanwhile."""++ def __init__(self, source):+ self.source = source+ self.remaining = size++ def read(self, amount=-1):+ if self.remaining <= 0:+ return b""+ amount = self.remaining if amount is None or amount < 0 else min(amount, self.remaining)+ chunk = self.source.read(amount)+ self.remaining -= len(chunk)+ return chunk++ headers = dict(params.get("headers") or {})+ headers["Content-Length"] = str(size)+ headers["Content-Type"] = content_type+ with os.fdopen(upload_fd, "rb") as source:+ upload_fd = None+ body = Capped(source)+ request = urllib.request.Request(params["uploadUrl"], data=body, headers=headers, method="PUT")+ try:+ with urllib.request.urlopen(request, timeout=170) as response:+ response.read()+ except urllib.error.HTTPError as error:+ done(ok=False, code="UPLOAD_FAILED", status=error.code)+ except Exception as error:+ done(ok=False, code="UPLOAD_FAILED", message=str(error)[:200])+ done(ok=True, kind=kind, size=size, contentType=content_type)+finally:+ if cleanup:+ try:+ os.remove(cleanup)+ except OSError:+ pass+`;++export interface DriveDownloadCommandParams {+ /** Refuse a folder instead of packing it — a preview shows one file. */+ fileOnly?: boolean;+ /** Paths, relative to the drive's root, that must not end up in the download. */+ hidden: string[];+ maxBytes: number;+ maxFiles: number;+ /** Relative to the drive's root. */+ path: string;+ uploadHeaders?: Record<string, string>;+ uploadUrl: string;+}++/**+ * The shell command that runs {@link SCRIPT}. Its input travels as base64 in+ * an environment variable and the script as a quoted heredoc, so nothing a+ * path or a URL contains is ever parsed by the shell.+ */+export const buildDriveDownloadCommand = ({+ fileOnly,+ hidden,+ maxBytes,+ maxFiles,+ path,+ uploadHeaders,+ uploadUrl,+}: DriveDownloadCommandParams) => {+ const payload = Buffer.from(+ JSON.stringify({+ fileOnly: fileOnly || undefined,+ headers: uploadHeaders,+ hidden,+ maxBytes,+ maxFiles,+ path,+ uploadUrl,+ }),+ 'utf8',+ ).toString('base64');++ return `LOBE_DRIVE_DOWNLOAD='${payload}' python3 - <<'LOBE_DRIVE_DOWNLOAD_PY'\n${SCRIPT}\nLOBE_DRIVE_DOWNLOAD_PY`;+};++export type DriveDownloadOutcome =+ | { contentType: string; kind: 'directory' | 'file'; ok: true; size: number }+ | {+ bytes?: number;+ code: 'NOT_A_FILE' | 'NOT_FOUND' | 'READ_FAILED' | 'TOO_LARGE' | 'UPLOAD_FAILED';+ ok: false;+ };++/** The script's answer, or `undefined` when it never printed one (it did not run, or died). */+export const parseDriveDownloadOutput = (stdout: string): DriveDownloadOutcome | undefined => {+ const line = stdout+ .split('\n')+ .reverse()+ .find((entry) => entry.startsWith(RESULT_MARKER));+ if (!line) return;++ try {+ return JSON.parse(line.slice(RESULT_MARKER.length)) as DriveDownloadOutcome;+ } catch {+ return;+ }+};++/** Why a download could not be prepared, as the code the client translates. */+export class DriveDownloadError extends Error {+ readonly code:+ | 'DOWNLOAD_FAILED'+ | 'DOWNLOAD_TOO_LARGE'+ | 'DOWNLOAD_UNAVAILABLE'+ | 'PATH_NOT_FOUND'+ | 'PREVIEW_NOT_A_FILE';++ constructor(code: DriveDownloadError['code'], detail?: string) {+ super(detail ? `${code}: ${detail}` : code);+ this.name = 'DriveDownloadError';+ this.code = code;+ }+}++/** The name the browser saves it under: the file's own, or the folder's with `.zip`. */+export const driveDownloadFileName = (path: string, kind: 'directory' | 'file') => {+ const name = path.split('/').findLast(Boolean) || 'download';+ return kind === 'directory' ? `${name}.zip` : name;+};++export interface PrepareDriveDownloadParams {+ fileService: {+ createDownloadUrl: (url: string, fileName: string, expiresIn?: number) => Promise<string>;+ createPreSignedUrlForPreview: (key: string, expiresIn?: number) => Promise<string>;+ createPreSignedUpload: (+ key: string,+ options?: { private?: boolean },+ ) => Promise<PreSignedUpload>;+ deleteFile: (key: string) => Promise<unknown>;+ deleteFiles: (keys: string[]) => Promise<unknown>;+ listFileKeys: (prefix: string, limit?: number) => Promise<string[]>;+ };+ hidden: string[];+ now?: Date;+ path: string;+ /** Defaults to `download`. */+ purpose?: DriveCopyPurpose;+ sandbox: Pick<SandboxService, 'callTool' | 'capabilities'>;+}++const dayOf = (date: Date) => date.toISOString().slice(0, 10);++/**+ * The copies from before yesterday (UTC). Their links lasted+ * {@link DRIVE_DOWNLOAD_URL_EXPIRES_IN}, so nobody can still be fetching them;+ * keeping yesterday's too means a link handed out just before midnight is+ * never pulled out from under its download.+ */+export const expiredDriveDownloadKeys = (keys: string[], now: Date) => {+ const yesterday = new Date(now);+ yesterday.setUTCDate(yesterday.getUTCDate() - 1);+ const cutoff = dayOf(yesterday);++ return keys.filter((key) => {+ const day = key.slice(DRIVE_DOWNLOAD_PREFIX.length, DRIVE_DOWNLOAD_PREFIX.length + 10);+ return key.startsWith(DRIVE_DOWNLOAD_PREFIX) && /^\d{4}-\d{2}-\d{2}$/.test(day) && day < cutoff;+ });+};++/**+ * Deletes expired copies, a page at a time. Keys sort by day, so the oldest+ * come first and every download clears up to a page of what earlier ones+ * left. Best-effort: a bucket that refuses listing or deleting must not cost+ * the person their download. A storage lifecycle rule on the prefix does the+ * same job more cheaply where one is configured; this keeps a deployment+ * without one from growing without bound.+ */+const sweepExpiredDownloads = async (+ fileService: PrepareDriveDownloadParams['fileService'],+ now: Date,+) => {+ try {+ const expired = expiredDriveDownloadKeys(+ await fileService.listFileKeys(DRIVE_DOWNLOAD_PREFIX),+ now,+ );+ if (expired.length > 0) await fileService.deleteFiles(expired);+ } catch (error) {+ log('sweeping expired drive downloads failed: %O', error);+ }+};++/**+ * Puts one file or folder of the drive where the browser can fetch it, and+ * answers with the link.+ *+ * The drive is only mounted inside a sandbox, so the bytes are read there and+ * uploaded from there straight to object storage; nothing passes through this+ * server. The object is a transient copy, not a library file: no file record+ * is made, so a download never shows up among the user's resources. A copy+ * that never gets a link is deleted at once; the rest are swept once expired.+ */+export const prepareDriveDownload = async ({+ fileService,+ hidden,+ now = new Date(),+ path,+ purpose = 'download',+ sandbox,+}: PrepareDriveDownloadParams) => {+ if (!sandbox.capabilities.shell) throw new DriveDownloadError('DOWNLOAD_UNAVAILABLE');++ const key = `${DRIVE_DOWNLOAD_PREFIX}${dayOf(now)}/${randomUUID()}`;+ // Private whatever the bucket's default ACL: a copy of someone's drive is+ // reachable only through the short-lived link below.+ const upload = await fileService.createPreSignedUpload(key, { private: true });+ // Alongside the packing, which takes far longer.+ const sweep = sweepExpiredDownloads(fileService, now);++ try {+ const result = await sandbox.callTool('runCommand', {+ command: buildDriveDownloadCommand({+ fileOnly: purpose === 'preview',+ hidden,+ maxBytes: DRIVE_DOWNLOAD_MAX_BYTES,+ maxFiles: DRIVE_DOWNLOAD_MAX_FILES,+ path,+ uploadHeaders: upload.headers,+ uploadUrl: upload.url,+ }),+ timeout: DRIVE_DOWNLOAD_TIMEOUT_MS,+ });++ const stdout = (result.result as { stdout?: unknown } | null | undefined)?.stdout;+ const outcome = typeof stdout === 'string' ? parseDriveDownloadOutput(stdout) : undefined;++ if (!outcome) {+ log('drive download produced no result: %O', result.error ?? result.result);+ throw new DriveDownloadError('DOWNLOAD_FAILED', result.error?.message);+ }++ if (!outcome.ok) {+ log('drive download refused: %O', outcome);+ if (outcome.code === 'NOT_FOUND') throw new DriveDownloadError('PATH_NOT_FOUND');+ if (outcome.code === 'TOO_LARGE') throw new DriveDownloadError('DOWNLOAD_TOO_LARGE');+ if (outcome.code === 'NOT_A_FILE') throw new DriveDownloadError('PREVIEW_NOT_A_FILE');+ throw new DriveDownloadError('DOWNLOAD_FAILED', outcome.code);+ }++ const fileName = driveDownloadFileName(path, outcome.kind);+ // A preview is shown in the page, so its link answers inline; a download's+ // answers as an attachment the browser saves.+ const url =+ purpose === 'preview'+ ? await fileService.createPreSignedUrlForPreview(key, DRIVE_PREVIEW_URL_EXPIRES_IN)+ : await fileService.createDownloadUrl(key, fileName, DRIVE_DOWNLOAD_URL_EXPIRES_IN);++ return {+ contentType: outcome.contentType,+ fileName,+ kind: outcome.kind,+ size: outcome.size,+ url,+ };+ } catch (error) {+ // Whatever was uploaded before the failure is unreachable without a link.+ await fileService.deleteFile(key).catch((cause: unknown) => {+ log('deleting an unused drive download failed: %O', cause);+ });+ throw error;+ } finally {+ await sweep;+ }+};diff --git a/apps/server/src/services/sandbox/providers/market.test.ts b/apps/server/src/services/sandbox/providers/market.test.tsindex 820ba95d003..811eced95a3 100644--- a/apps/server/src/services/sandbox/providers/market.test.ts+++ b/apps/server/src/services/sandbox/providers/market.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import type { MarketService } from '@/server/services/market';+import { buildDriveDownloadCommand } from '../driveDownload';import { MarketSandboxProvider, redactSandboxParams } from './market';describe('MarketSandboxProvider', () => {@@ -211,6 +212,21 @@ describe('MarketSandboxProvider', () => {expect(redactSandboxParams(params).command).not.toContain('c2VjcmV0');});+ it("redacts a drive download's payload, which carries a presigned upload URL", () => {+ const command = buildDriveDownloadCommand({+ hidden: [],+ maxBytes: 1,+ maxFiles: 1,+ path: 'project',+ uploadUrl: 'https://bucket.example.com/key?X-Amz-Signature=secret',+ });+ const payload = /LOBE_DRIVE_DOWNLOAD='([^']+)'/.exec(command)![1];++ const redacted = redactSandboxParams({ command }).command as string;+ expect(redacted).not.toContain(payload);+ expect(redacted).toContain('LOBE_DRIVE_DOWNLOAD=[redacted] python3 -');+ });+it('fully redacts a command that writes into ~/.creds/env, regardless of the credential names it carries', () => {const params = {command:diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.tsindex b133df428ad..2bd9bc5cea7 100644--- a/apps/server/src/services/sandbox/providers/market.ts+++ b/apps/server/src/services/sandbox/providers/market.ts@@ -18,8 +18,10 @@ const log = debug('lobe-server:sandbox:market');const REDACTED_SANDBOX_PARAM = '[redacted]';// `GIT_CONFIG_VALUE_<n>` carries the clone credential an environment's// initializer exports for git; see `buildSandboxEnvironmentInitCommand`.+// `LOBE_DRIVE_DOWNLOAD` carries a drive download's presigned upload URL; see+// `buildDriveDownloadCommand`.const SANDBOX_AUTH_ENV_PATTERN =- /\b(LOBEHUB_JWT|GITHUB_TOKEN|GIT_CONFIG_VALUE_\d+)=("[^"]*"|'[^']*'|\S+)/g;+ /\b(LOBEHUB_JWT|GITHUB_TOKEN|GIT_CONFIG_VALUE_\d+|LOBE_DRIVE_DOWNLOAD)=("[^"]*"|'[^']*'|\S+)/g;/*** Any command that writes into `~/.creds/env` (the path documented to the* model as where `injectCredsToSandbox` places credentials) carriesdiff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 20c9cea086a..32759ba950b 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -599,6 +599,12 @@"drive.explorer.deleteFileContent": "The file is removed from the drive.","drive.explorer.deleteFolderContent": "The folder and everything in it are removed from the drive. Conversations working in it switch to a temporary sandbox.","drive.explorer.deleteTitle": "Delete “{{name}}”?",+ "drive.explorer.download": "Download",+ "drive.explorer.downloadFailed": "Couldn’t prepare the download. Try again.",+ "drive.explorer.downloadPreparing": "Preparing “{{name}}” for download…",+ "drive.explorer.downloadTooLarge": "Over 1 GB or 50,000 files — too large to download here.",+ "drive.explorer.downloadUnavailable": "Downloading from the drive isn’t available on this server.",+ "drive.explorer.downloadZip": "Download as ZIP","drive.explorer.empty": "This folder is empty","drive.explorer.emptyRoot.personal": "Your drive is empty. Create a folder, then pick it as a conversation’s working folder.","drive.explorer.emptyRoot.public": "No folders on the public drive yet. Create one to work in it with your team.",@@ -609,6 +615,9 @@"drive.explorer.loadFailed": "Could not load this folder.","drive.explorer.moreActions": "More actions","drive.explorer.newFolder": "New folder",+ "drive.explorer.preview": "Preview",+ "drive.explorer.previewFailed": "Couldn’t open the preview. Try again.",+ "drive.explorer.previewPreparing": "Preparing the preview…","drive.explorer.readOnly": "Environment directories are read-only","drive.explorer.readOnlyHint": "Only its own sandbox sessions write to an environment directory, so you can browse it here but not change it.","drive.explorer.rename": "Rename",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 6e6c328043e..88302fcc6a6 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -599,6 +599,12 @@"drive.explorer.deleteFileContent": "文件会从网盘删除。","drive.explorer.deleteFolderContent": "文件夹及其中所有内容都会从网盘删除,在其中工作的对话之后会改用临时沙箱。","drive.explorer.deleteTitle": "删除「{{name}}」?",+ "drive.explorer.download": "下载",+ "drive.explorer.downloadFailed": "无法准备下载,请重试。",+ "drive.explorer.downloadPreparing": "正在准备下载「{{name}}」…",+ "drive.explorer.downloadTooLarge": "内容超过 1 GB 或 5 万个文件,无法在这里下载。",+ "drive.explorer.downloadUnavailable": "当前服务不支持从网盘下载。",+ "drive.explorer.downloadZip": "打包为 ZIP 下载","drive.explorer.empty": "这个文件夹是空的","drive.explorer.emptyRoot.personal": "个人网盘还是空的。新建一个文件夹,就能在对话里把它选作工作目录。","drive.explorer.emptyRoot.public": "公共网盘还没有文件夹。新建一个,和成员一起在里面工作。",@@ -609,6 +615,9 @@"drive.explorer.loadFailed": "无法加载这个文件夹。","drive.explorer.moreActions": "更多操作","drive.explorer.newFolder": "新建文件夹",+ "drive.explorer.preview": "预览",+ "drive.explorer.previewFailed": "无法打开预览,请重试。",+ "drive.explorer.previewPreparing": "正在准备预览…","drive.explorer.readOnly": "环境目录只读","drive.explorer.readOnlyHint": "环境目录只由它自己的沙箱会话写入,这里可以浏览,但不能修改。","drive.explorer.rename": "重命名",diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 2d5befc7726..9376850ba34 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -4713,6 +4713,16 @@ When I am ___, I need ___'drive.explorer.delete': 'Delete','drive.explorer.moreActions': 'More actions','drive.explorer.deleteTitle': 'Delete “{{name}}”?',+ 'drive.explorer.download': 'Download',+ 'drive.explorer.downloadFailed': 'Couldn’t prepare the download. Try again.',+ 'drive.explorer.downloadPreparing': 'Preparing “{{name}}” for download…',+ 'drive.explorer.downloadTooLarge': 'Over 1 GB or 50,000 files — too large to download here.',+ 'drive.explorer.downloadUnavailable':+ 'Downloading from the drive isn’t available on this server.',+ 'drive.explorer.downloadZip': 'Download as ZIP',+ 'drive.explorer.preview': 'Preview',+ 'drive.explorer.previewFailed': 'Couldn’t open the preview. Try again.',+ 'drive.explorer.previewPreparing': 'Preparing the preview…','drive.explorer.deleteFolderContent':'The folder and everything in it are removed from the drive. Conversations working in it switch to a temporary sandbox.','drive.explorer.deleteFileContent': 'The file is removed from the drive.',diff --git a/src/features/EnvironmentManager/errorMessage.ts b/src/features/EnvironmentManager/errorMessage.tsindex 0666d718e96..b7c3bc55703 100644--- a/src/features/EnvironmentManager/errorMessage.ts+++ b/src/features/EnvironmentManager/errorMessage.ts@@ -12,6 +12,10 @@ import { isMachineErrorMessage } from '@/utils/machineErrorMessage';* sentence — falls back to the caller's generic line.*/const CODE_KEYS: Record<string, string> = {+ // A drive download over the size the sandbox packs in one request.+ DOWNLOAD_TOO_LARGE: 'drive.explorer.downloadTooLarge',+ // A deployment whose sandbox has no shell to pack a download with.+ DOWNLOAD_UNAVAILABLE: 'drive.explorer.downloadUnavailable',DUPLICATE_INSTANCE_DIRECTORY: 'environments.files.folderTaken',ENVIRONMENT_HAS_INSTANCES: 'environments.hasInstances',// The execution plane calls this an instance now too. The olddiff --git a/src/features/SandboxDrive/DriveExplorer.tsx b/src/features/SandboxDrive/DriveExplorer.tsxindex da3ba3138ed..803c0468559 100644--- a/src/features/SandboxDrive/DriveExplorer.tsx+++ b/src/features/SandboxDrive/DriveExplorer.tsx@@ -15,6 +15,8 @@ import {import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import {+ DownloadIcon,+ EyeIcon,FolderPlusIcon,HardDriveIcon,LockIcon,@@ -38,6 +40,7 @@ import {} from '@/features/WorkingDirectory';import { sandboxStorageService } from '@/services/sandboxStorage';+import { openDriveFilePreview } from './DriveFilePreview';import {entryKind,entryModified,@@ -46,6 +49,7 @@ import {sortDriveEntries,} from './entryColumns';import { useDriveFiles, useRefreshDrive } from './useDriveData';+import { useDriveDownload } from './useDriveDownload';/*** The columns after the name — size, kind, then date modified — fixed so@@ -130,7 +134,8 @@ interface DriveExplorerProps {/*** One drive, browsed like a desktop file manager's list view: a header, then* each folder and file with its icon, when it changed, its size and its kind;- * a new folder, rename and delete.+ * a new folder, rename, delete and download — a file as it is, a folder as a+ * zip. Opening a file previews it the way the resource library does.** Every folder is an ordinary one. A folder a code environment initialized is* a checkout like any other — environments are one-time initializers — so@@ -142,6 +147,7 @@ const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExtconst [creating, setCreating] = useState(false);const files = useDriveFiles(drive, path);const refreshDrive = useRefreshDrive();+ const download = useDriveDownload(drive);const tSetting = (key: string, options?: Record<string, unknown>) =>(t as (key: string, options?: Record<string, unknown>) => string)(key, {@@ -202,6 +208,9 @@ const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExtconst scope = drive === 'public' && isWorkspace ? 'public' : 'personal';+ const preview = (entry: { name: string; path: string }) =>+ openDriveFilePreview({ drive, entry, onDownload: () => void download(entry) });+const menuFor = (entry: { isDirectory: boolean; name: string; path: string }) => (<spanrole={'none'}@@ -211,6 +220,22 @@ const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExt<DropdownMenuplacement={'bottomRight'}items={[+ ...(entry.isDirectory+ ? []+ : [+ {+ icon: <Icon icon={EyeIcon} />,+ key: 'preview',+ label: t('drive.explorer.preview'),+ onClick: () => preview(entry),+ },+ ]),+ {+ icon: <Icon icon={DownloadIcon} />,+ key: 'download',+ label: t(entry.isDirectory ? 'drive.explorer.downloadZip' : 'drive.explorer.download'),+ onClick: () => void download(entry),+ },...(entry.isDirectory? [{@@ -360,29 +385,26 @@ const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExt</Flexbox>) : (entries.map((entry) => {- const open = entry.isDirectory ? () => setPath(entry.path) : undefined;+ // A folder opens in place; a file opens its preview.+ const open = entry.isDirectory ? () => setPath(entry.path) : () => preview(entry);return (<Flexboxhorizontalalign={'center'}- className={stylex.props(styles.row, open && styles.clickable).className}+ className={stylex.props(styles.row, styles.clickable).className}data-testid={'drive-entry'}gap={10}key={entry.path}- role={open ? 'button' : undefined}- tabIndex={open ? 0 : undefined}+ role={'button'}+ tabIndex={0}onClick={open}- onKeyDown={- open- ? (event) => {- if (event.key === 'Enter' || event.key === ' ') {- event.preventDefault();- open();- }- }- : undefined- }+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ open();+ }+ }}><span {...stylex.props(styles.entryIcon)}><FileIcondiff --git a/src/features/SandboxDrive/DriveFilePreview.test.tsx b/src/features/SandboxDrive/DriveFilePreview.test.tsxnew file mode 100644index 00000000000..8c7f5e3cfb6--- /dev/null+++ b/src/features/SandboxDrive/DriveFilePreview.test.tsx@@ -0,0 +1,62 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DriveFilePreviewContent } from './DriveFilePreview';++const service = vi.hoisted(() => ({ preparePreview: vi.fn() }));+const viewer = vi.hoisted(() => ({ props: vi.fn() }));++vi.mock('@/services/sandboxStorage', () => ({ sandboxStorageService: service }));+vi.mock('@/features/FileViewer', () => ({+ default: (props: Record<string, unknown>) => {+ viewer.props(props);+ return <div data-testid={'file-viewer'}>{String(props.url)}</div>;+ },+}));++const entry = { name: 'report.pdf', path: 'docs/report.pdf' };++describe('DriveFilePreviewContent', () => {+ beforeEach(() => {+ service.preparePreview.mockReset();+ viewer.props.mockReset();+ });++ it('copies the file out of the drive, then shows it in the resource library viewer', async () => {+ service.preparePreview.mockResolvedValue({+ contentType: 'application/pdf',+ fileName: 'report.pdf',+ kind: 'file',+ size: 9,+ url: 'https://cdn/copy?inline',+ });++ render(<DriveFilePreviewContent drive={'personal'} entry={entry} />);++ expect(screen.getByText('drive.explorer.previewPreparing')).toBeInTheDocument();+ expect(await screen.findByTestId('file-viewer')).toHaveTextContent('https://cdn/copy?inline');+ expect(service.preparePreview).toHaveBeenCalledWith({+ drive: 'personal',+ path: 'docs/report.pdf',+ });+ expect(viewer.props).toHaveBeenLastCalledWith(+ expect.objectContaining({ fileType: 'application/pdf', name: 'report.pdf', size: 9 }),+ );+ });++ it('says the preview failed and copies again on retry', async () => {+ service.preparePreview.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce({+ contentType: 'text/plain',+ fileName: 'report.pdf',+ kind: 'file',+ size: 1,+ url: 'https://cdn/second',+ });++ render(<DriveFilePreviewContent drive={'public'} entry={entry} />);++ fireEvent.click(await screen.findByText('retry'));+ expect(await screen.findByTestId('file-viewer')).toHaveTextContent('https://cdn/second');+ expect(service.preparePreview).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/features/SandboxDrive/DriveFilePreview.tsx b/src/features/SandboxDrive/DriveFilePreview.tsxnew file mode 100644index 00000000000..a9d47170fad--- /dev/null+++ b/src/features/SandboxDrive/DriveFilePreview.tsx@@ -0,0 +1,145 @@+'use client';++import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import { ActionIcon, Button, Center, createModal, Flexbox, Spin, Text } from '@lobehub/ui';+import { t as i18nT } from 'i18next';+import { DownloadIcon } from 'lucide-react';+import { memo, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { describeError } from '@/features/EnvironmentManager/errorMessage';+import FileViewer from '@/features/FileViewer';+import { sandboxStorageService } from '@/services/sandboxStorage';++export interface DriveFileEntry {+ name: string;+ path: string;+}++type PreviewState =+ | { status: 'loading' }+ | { error: unknown; status: 'error' }+ | {+ file: { contentType?: string; fileName: string; size: number; url: string };+ /** When the copy was made — the viewer's item carries a date, and this is the copy's. */+ preparedAt: Date;+ status: 'ready';+ };++interface DriveFilePreviewProps {+ drive: SandboxDrive;+ entry: DriveFileEntry;+}++/**+ * One file of the drive, shown the way the resource library shows a file: the+ * same viewer, so an image, PDF, video, Office document, Markdown, HTML or+ * any text renders as it does there, and a format it cannot show offers the+ * download instead.+ *+ * The drive is only mounted in a sandbox, so the file is first copied out to+ * object storage — seconds on a cold start — and the viewer reads that copy.+ * A fresh copy each time the preview opens: the link expires, and the file+ * may have changed since.+ */+export const DriveFilePreviewContent = memo<DriveFilePreviewProps>(({ drive, entry }) => {+ const { t } = useTranslation('setting');+ const [attempt, setAttempt] = useState(0);+ const [state, setState] = useState<PreviewState>({ status: 'loading' });++ useEffect(() => {+ let active = true;++ sandboxStorageService.preparePreview({ drive, path: entry.path }).then(+ (file) => {+ if (active) setState({ file, preparedAt: new Date(), status: 'ready' });+ },+ (error: unknown) => {+ if (active) setState({ error, status: 'error' });+ },+ );++ return () => {+ active = false;+ };+ }, [attempt, drive, entry.path]);++ if (state.status === 'loading')+ return (+ <Center gap={12} height={'100%'} width={'100%'}>+ <Spin size={'large'} />+ <Text type={'secondary'}>{t('drive.explorer.previewPreparing')}</Text>+ </Center>+ );++ if (state.status === 'error')+ return (+ <Center gap={12} height={'100%'} padding={24} width={'100%'}>+ <Text type={'secondary'}>+ {describeError(state.error, t, t('drive.explorer.previewFailed'))}+ </Text>+ <Button+ onClick={() => {+ setState({ status: 'loading' });+ setAttempt((value) => value + 1);+ }}+ >+ {t('retry', { ns: 'common' })}+ </Button>+ </Center>+ );++ const { file, preparedAt } = state;++ return (+ <FileViewer+ chunkCount={null}+ chunkingError={null}+ createdAt={preparedAt}+ embeddingError={null}+ fileType={file.contentType ?? ''}+ finishEmbedding={false}+ id={`drive:${drive}:${entry.path}`}+ name={file.fileName}+ size={file.size}+ sourceType={'file'}+ updatedAt={preparedAt}+ url={file.url}+ />+ );+});++DriveFilePreviewContent.displayName = 'DriveFilePreviewContent';++/**+ * Opens the preview of one drive file in a large modal, its name in the title+ * beside a download — the file as it is, through the same path the row's menu+ * downloads it by.+ */+export const openDriveFilePreview = ({+ drive,+ entry,+ onDownload,+}: DriveFilePreviewProps & { onDownload: () => void }) =>+ createModal({+ content: <DriveFilePreviewContent drive={drive} entry={entry} />,+ footer: null,+ maskClosable: true,+ styles: {+ content: { height: '80vh', minHeight: 0, overflow: 'auto', padding: 0 },+ },+ title: (+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0, paddingInlineEnd: 32 }}>+ <Text ellipsis strong style={{ minWidth: 0 }} title={entry.name}>+ {entry.name}+ </Text>+ <ActionIcon+ icon={DownloadIcon}+ size={'small'}+ title={i18nT('drive.explorer.download', { ns: 'setting' })}+ onClick={onDownload}+ />+ </Flexbox>+ ),+ width: 'min(90vw, 1024px)',+ });diff --git a/src/features/SandboxDrive/useDriveDownload.test.ts b/src/features/SandboxDrive/useDriveDownload.test.tsnew file mode 100644index 00000000000..857bb204e7e--- /dev/null+++ b/src/features/SandboxDrive/useDriveDownload.test.ts@@ -0,0 +1,99 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useDriveDownload } from './useDriveDownload';++const mocks = vi.hoisted(() => ({+ close: vi.fn(),+ error: vi.fn(),+ loading: vi.fn(),+ prepareDownload: vi.fn(),+}));++vi.mock('@lobehub/ui', () => ({ toast: { error: mocks.error, loading: mocks.loading } }));+vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: { prepareDownload: mocks.prepareDownload },+}));++describe('useDriveDownload', () => {+ let clicked: { download: string; href: string }[];++ beforeEach(() => {+ clicked = [];+ mocks.close.mockReset();+ mocks.error.mockReset();+ mocks.prepareDownload.mockReset();+ mocks.loading.mockReset().mockReturnValue({ close: mocks.close });+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (+ this: HTMLAnchorElement,+ ) {+ clicked.push({ download: this.download, href: this.href });+ });+ });++ afterEach(() => vi.restoreAllMocks());++ const download = (drive: 'personal' | 'public', entry: { name: string; path: string }) => {+ const { result } = renderHook(() => useDriveDownload(drive));+ return act(() => result.current(entry));+ };++ it('saves the link the server prepared, under its name, from the drive it is on', async () => {+ mocks.prepareDownload.mockResolvedValue({+ fileName: 'project.zip',+ kind: 'directory',+ url: 'https://files.example.com/project.zip?sig=1',+ });++ await download('public', { name: 'project', path: 'work/project' });++ expect(mocks.loading).toHaveBeenCalledWith('drive.explorer.downloadPreparing');+ expect(mocks.prepareDownload).toHaveBeenCalledWith({ drive: 'public', path: 'work/project' });+ expect(clicked).toEqual([+ { download: 'project.zip', href: 'https://files.example.com/project.zip?sig=1' },+ ]);+ expect(mocks.close).toHaveBeenCalledTimes(1);+ expect(mocks.error).not.toHaveBeenCalled();+ // The anchor is gone once followed.+ expect(document.querySelector('a[download]')).toBeNull();+ });++ it('says why a folder is too large, and saves nothing', async () => {+ mocks.prepareDownload.mockRejectedValue(new Error('DOWNLOAD_TOO_LARGE'));++ await download('personal', { name: 'project', path: 'project' });++ expect(mocks.error).toHaveBeenCalledWith('drive.explorer.downloadTooLarge');+ expect(mocks.close).toHaveBeenCalledTimes(1);+ expect(clicked).toEqual([]);+ });++ it('falls back to a generic line for a failure it has no sentence for', async () => {+ mocks.prepareDownload.mockRejectedValue(new Error('DOWNLOAD_FAILED'));++ await download('personal', { name: 'report.pdf', path: 'report.pdf' });++ expect(mocks.error).toHaveBeenCalledWith('drive.explorer.downloadFailed');+ });++ it('ignores a second click while the same entry is still being prepared', async () => {+ let finish!: (value: unknown) => void;+ mocks.prepareDownload.mockReturnValue(new Promise((resolve) => (finish = resolve)));+ const { result } = renderHook(() => useDriveDownload('public'));+ const entry = { name: 'project', path: 'project' };++ const first = result.current(entry);+ await result.current(entry);+ expect(mocks.prepareDownload).toHaveBeenCalledTimes(1);++ finish({ fileName: 'project.zip', kind: 'directory', url: 'https://files.example.com/p.zip' });+ await act(() => first);+ mocks.prepareDownload.mockResolvedValue({+ fileName: 'project.zip',+ kind: 'directory',+ url: 'https://files.example.com/p.zip',+ });+ await act(() => result.current(entry));+ expect(mocks.prepareDownload).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/features/SandboxDrive/useDriveDownload.ts b/src/features/SandboxDrive/useDriveDownload.tsnew file mode 100644index 00000000000..c545faf54e2--- /dev/null+++ b/src/features/SandboxDrive/useDriveDownload.ts@@ -0,0 +1,59 @@+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import { toast } from '@lobehub/ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { describeError } from '@/features/EnvironmentManager/errorMessage';+import { useSingleton } from '@/hooks/useSingleton';+import { sandboxStorageService } from '@/services/sandboxStorage';++/** Follows a link whose response is an attachment, which the browser saves. */+const saveFromUrl = (url: string, fileName: string) => {+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = fileName;+ anchor.rel = 'noopener';+ anchor.style.display = 'none';+ document.body.append(anchor);+ anchor.click();+ anchor.remove();+};++/**+ * Downloads one entry of a drive: a file as it is, a folder as a zip.+ *+ * The server packs it in a sandbox session — seconds on a cold start or a+ * large folder — and answers with a link that downloads as an attachment, so+ * following it saves the file; nothing is fetched into memory, which a large+ * archive would not survive. Progress shows until the link is ready, and a+ * refusal is said in a sentence, not a code.+ *+ * A second click on an entry still being prepared is ignored: each one starts+ * a sandbox command and an upload of up to a gigabyte.+ */+export const useDriveDownload = (drive: SandboxDrive) => {+ const { t } = useTranslation('setting');+ const inFlight = useSingleton(() => new Set<string>());++ return useCallback(+ async (entry: { name: string; path: string }) => {+ if (inFlight.has(entry.path)) return;+ inFlight.add(entry.path);++ const pending = toast.loading(t('drive.explorer.downloadPreparing', { name: entry.name }));+ try {+ const { fileName, url } = await sandboxStorageService.prepareDownload({+ drive,+ path: entry.path,+ });+ saveFromUrl(url, fileName);+ } catch (error) {+ toast.error(describeError(error, t, t('drive.explorer.downloadFailed')));+ } finally {+ inFlight.delete(entry.path);+ pending.close();+ }+ },+ [drive, inFlight, t],+ );+};diff --git a/src/services/sandboxStorage.ts b/src/services/sandboxStorage.tsindex 2adf4d1e050..ac673a93acf 100644--- a/src/services/sandboxStorage.ts+++ b/src/services/sandboxStorage.ts@@ -193,6 +193,22 @@ class SandboxStorageService {topicId?: string;}) => lambdaClient.sandboxStorage.readFile.query(params);+ /**+ * A link to download one file of the drive as it is, or one folder as a zip.+ * Packing happens in a sandbox session, so this can take a while on a cold+ * start or a large folder; callers show progress until it answers.+ */+ prepareDownload = async (params: { drive?: SandboxDrive; path: string }) =>+ lambdaClient.sandboxStorage.prepareDownload.mutate(params);++ /**+ * A link one file of the drive is shown from in the page, with the type its+ * name implies. Copied out through a sandbox session like a download, so it+ * takes as long; callers show progress until it answers.+ */+ preparePreview = async (params: { drive?: SandboxDrive; path: string }) =>+ lambdaClient.sandboxStorage.preparePreview.mutate(params);+removeFile = async (params: {drive?: SandboxDrive;instanceId?: string;