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(settings): export data in the background and notify when ready (#23125)

YuTengjingaf52449fe24f
diff --git a/apps/server/src/modules/S3/index.test.ts b/apps/server/src/modules/S3/index.test.ts
index a4eb8eb6d79..596f22103fc 100644
--- a/apps/server/src/modules/S3/index.test.ts
+++ b/apps/server/src/modules/S3/index.test.ts
@@ -771,6 +771,20 @@ describe('FileS3', () => {
expect(mockS3ClientSend).toHaveBeenCalled();
});
+ it('keeps a private upload private even when uploads are public by default', async () => {
+ const s3 = new FileS3();
+ mockS3ClientSend.mockResolvedValue({});
+
+ const buffer = Buffer.from('{}');
+ await s3.uploadBuffer('exports/u/t.json', buffer, 'application/json', undefined, {
+ private: true,
+ });
+
+ expect(PutObjectCommand).toHaveBeenCalledWith(
+ expect.objectContaining({ ACL: undefined, Key: 'exports/u/t.json' }),
+ );
+ });
+
it('should upload buffer without content type', async () => {
const s3 = new FileS3();
mockS3ClientSend.mockResolvedValue({});
diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.ts
index af5aeb0c5af..04eede773da 100644
--- a/apps/server/src/modules/S3/index.ts
+++ b/apps/server/src/modules/S3/index.ts
@@ -363,10 +363,15 @@ export class S3 {
* having that ETag, so a caller holding a cached copy cannot overwrite a
* newer one; the store answers 412 instead.
*/
- options?: { abortSignal?: AbortSignal; ifMatch?: string },
+ options?: {
+ abortSignal?: AbortSignal;
+ ifMatch?: string;
+ /** Never grant public read, even when S3_SET_ACL makes uploads public (e.g. data exports). */
+ private?: boolean;
+ },
) {
const command = new PutObjectCommand({
- ACL: this.setAcl ? 'public-read' : undefined,
+ ACL: this.setAcl && !options?.private ? 'public-read' : undefined,
Body: buffer,
Bucket: this.bucket,
CacheControl: cacheControl,
diff --git a/apps/server/src/routers/async/dataExport.ts b/apps/server/src/routers/async/dataExport.ts
new file mode 100644
index 00000000000..f7fcca83e92
--- /dev/null
+++ b/apps/server/src/routers/async/dataExport.ts
@@ -0,0 +1,14 @@
+import { z } from 'zod';
+
+import { asyncAuthedProcedure, asyncRouter as router } from '@/libs/trpc/async';
+import { DataExportService } from '@/server/services/dataExport';
+
+/** Background data exports, queued by the lambda `exporter` router. */
+export const dataExportRouter = router({
+ run: asyncAuthedProcedure
+ .input(z.object({ taskId: z.string().uuid(), workspaceId: z.string().optional() }))
+ .mutation(async ({ ctx, input }) => {
+ await new DataExportService(ctx.serverDB, ctx.userId, input.workspaceId).run(input.taskId);
+ return { ok: true };
+ }),
+});
diff --git a/apps/server/src/routers/async/index.ts b/apps/server/src/routers/async/index.ts
index 225b22a4208..45d10d30cf7 100644
--- a/apps/server/src/routers/async/index.ts
+++ b/apps/server/src/routers/async/index.ts
@@ -1,5 +1,6 @@
import { asyncRouter as router, publicProcedure } from '@/libs/trpc/async';
+import { dataExportRouter } from './dataExport';
import { documentRouter } from './document';
import { fileRouter } from './file';
import { imageRouter } from './image';
@@ -9,6 +10,7 @@ import { ragEvalRouter } from './ragEval';
import { videoRouter } from './video';
export const asyncRouter = router({
+ dataExport: dataExportRouter,
document: documentRouter,
file: fileRouter,
healthcheck: publicProcedure.query(() => "i'm live!"),
diff --git a/apps/server/src/routers/lambda/exporter.ts b/apps/server/src/routers/lambda/exporter.ts
index 27ff55f4f48..b32de34cdc6 100644
--- a/apps/server/src/routers/lambda/exporter.ts
+++ b/apps/server/src/routers/lambda/exporter.ts
@@ -10,6 +10,8 @@ import { SessionModel } from '@/database/models/session';
import { DataExporterRepos } from '@/database/repositories/dataExporter';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { DataExportService } from '@/server/services/dataExport';
+import { startDataExport } from '@/server/services/dataExport/start';
import { type ExportDatabaseData } from '@/types/export';
const exportProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
@@ -173,6 +175,28 @@ const generatePdfFromMarkdown = async (
};
export const exporterRouter = router({
+ /** Download link for a finished background export; the link expires after a few minutes. */
+ getExportDownloadUrl: workspaceExportProcedure
+ .input(z.object({ id: z.string().uuid() }))
+ .mutation(async ({ ctx, input }) =>
+ new DataExportService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined).getDownloadUrl(
+ input.id,
+ ),
+ ),
+
+ getLatestExport: workspaceExportProcedure.query(async ({ ctx }) =>
+ new DataExportService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined).getLatest(),
+ ),
+
+ /** Queue a full data export in the background, or return the one already running. */
+ startExport: workspaceExportProcedure.mutation(async ({ ctx }) =>
+ startDataExport(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
+ ),
+
+ /**
+ * Synchronous export kept for clients released before background exports;
+ * it holds the request open until every table is read.
+ */
exportData: workspaceExportProcedure.mutation(async ({ ctx }): Promise<ExportDatabaseData> => {
const data = await ctx.dataExporterRepos.export(5);
const schemaHash = await ctx.drizzleMigration.getLatestMigrationHash();
diff --git a/apps/server/src/services/dataExport/index.test.ts b/apps/server/src/services/dataExport/index.test.ts
new file mode 100644
index 00000000000..1c2a2537719
--- /dev/null
+++ b/apps/server/src/services/dataExport/index.test.ts
@@ -0,0 +1,257 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { asyncTasks, users } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ DATA_EXPORT_RUN_DEADLINE_MS,
+ DATA_EXPORT_STALE_AFTER_MS,
+ DataExportService,
+} from './index';
+import { startDataExport } from './start';
+
+const mocks = vi.hoisted(() => ({
+ after: vi.fn(),
+ createDownloadUrl: vi.fn(),
+ deleteFile: vi.fn(),
+ exportTables: vi.fn(),
+ notify: vi.fn(),
+ uploadBuffer: vi.fn(),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ createDownloadUrl: mocks.createDownloadUrl,
+ deleteFile: mocks.deleteFile,
+ uploadBuffer: mocks.uploadBuffer,
+ };
+ }),
+}));
+
+vi.mock('@/database/repositories/dataExporter', () => ({
+ DataExporterRepos: vi.fn().mockImplementation(function () {
+ return { export: mocks.exportTables };
+ }),
+}));
+
+vi.mock('@/database/models/drizzleMigration', () => ({
+ DrizzleMigrationModel: vi.fn().mockImplementation(function () {
+ return { getLatestMigrationHash: vi.fn().mockResolvedValue('schema-hash') };
+ }),
+}));
+
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: mocks.after }));
+
+vi.mock('@/server/routers/async', () => ({ createAsyncCaller: vi.fn() }));
+
+vi.mock('@/business/server/data-export/notifyDataExportResult', () => ({
+ notifyDataExportResult: mocks.notify,
+}));
+
+const db: LobeChatDatabase = await getTestDB();
+const userId = 'data-export-service-user';
+
+const getTask = async (id: string) =>
+ (await db.select().from(asyncTasks).where(eq(asyncTasks.id, id)))[0];
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await db.delete(users).where(eq(users.id, userId));
+ await db.insert(users).values({ id: userId });
+ mocks.exportTables.mockResolvedValue({ topics: [{ id: 't1' }] });
+ mocks.uploadBuffer.mockResolvedValue({ key: 'stored' });
+});
+
+afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+});
+
+describe('DataExportService', () => {
+ it('stores the export file, marks it ready and notifies the user', async () => {
+ const service = new DataExportService(db, userId);
+ const taskId = await service.createTask();
+
+ await service.run(taskId);
+
+ const [key, buffer, contentType, options] = mocks.uploadBuffer.mock.calls[0];
+ expect(key).toBe(`exports/${userId}/${taskId}.json`);
+ expect(contentType).toBe('application/json');
+ expect(options).toMatchObject({ private: true });
+ expect(JSON.parse(buffer.toString())).toEqual({
+ data: { topics: [{ id: 't1' }] },
+ mode: 'postgres',
+ schemaHash: 'schema-hash',
+ });
+
+ expect(await service.getLatest()).toMatchObject({
+ fileSize: buffer.byteLength,
+ id: taskId,
+ status: 'success',
+ });
+ expect(mocks.notify).toHaveBeenCalledWith({ status: 'success', taskId, userId });
+ });
+
+ it('runs a task only once even when handed off twice', async () => {
+ const service = new DataExportService(db, userId);
+ const taskId = await service.createTask();
+
+ await Promise.all([service.run(taskId), service.run(taskId)]);
+
+ expect(mocks.exportTables).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks the export failed and notifies the user when building it fails', async () => {
+ mocks.exportTables.mockRejectedValue(new Error('db timeout'));
+ const service = new DataExportService(db, userId);
+ const taskId = await service.createTask();
+
+ await service.run(taskId);
+
+ expect((await getTask(taskId)).status).toBe(AsyncTaskStatus.Error);
+ expect(await service.getLatest()).toMatchObject({ id: taskId, status: 'error' });
+ expect(mocks.notify).toHaveBeenCalledWith({ status: 'error', taskId, userId });
+ });
+
+ it('keeps only the newest export file', async () => {
+ const service = new DataExportService(db, userId);
+ const firstId = await service.createTask();
+ await service.run(firstId);
+ await db
+ .update(asyncTasks)
+ .set({ createdAt: new Date(Date.now() - 60_000) })
+ .where(eq(asyncTasks.id, firstId));
+
+ const secondId = await service.createTask();
+ await service.run(secondId);
+
+ expect(mocks.deleteFile).toHaveBeenCalledWith(`exports/${userId}/${firstId}.json`);
+ expect(await getTask(firstId)).toBeUndefined();
+ expect((await service.getLatest())?.id).toBe(secondId);
+ });
+
+ it('shows an export that never finished as failed and lets a new one start', async () => {
+ const service = new DataExportService(db, userId);
+ const [lost] = await db
+ .insert(asyncTasks)
+ .values({
+ createdAt: new Date(Date.now() - DATA_EXPORT_STALE_AFTER_MS - 1000),
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.DataExport,
+ userId,
+ })
+ .returning();
+
+ expect(await service.getLatest()).toMatchObject({ id: lost.id, status: 'error' });
+ expect(await service.findRunning()).toBeUndefined();
+ });
+
+ it('fails a hand-off that never started, but leaves a claimed run alone', async () => {
+ const service = new DataExportService(db, userId);
+ const unclaimedId = await service.createTask();
+ const claimedId = await service.createTask();
+ await db
+ .update(asyncTasks)
+ .set({ status: AsyncTaskStatus.Processing })
+ .where(eq(asyncTasks.id, claimedId));
+
+ await service.failUnclaimed(unclaimedId, 'hand-off failed');
+ await service.failUnclaimed(claimedId, 'hand-off failed');
+
+ expect((await getTask(unclaimedId)).status).toBe(AsyncTaskStatus.Error);
+ expect((await getTask(claimedId)).status).toBe(AsyncTaskStatus.Processing);
+ });
+
+ it('only signs download links for a finished export', async () => {
+ mocks.createDownloadUrl.mockResolvedValue('https://s3/signed');
+ const service = new DataExportService(db, userId);
+ const pendingId = await service.createTask();
+
+ await expect(service.getDownloadUrl(pendingId)).rejects.toThrow('Data export not found');
+
+ await service.run(pendingId);
+ const result = await service.getDownloadUrl(pendingId);
+
+ expect(result.url).toBe('https://s3/signed');
+ expect(result.fileName).toMatch(/^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}_LobeHub-data\.json$/);
+ expect(mocks.createDownloadUrl).toHaveBeenCalledWith(
+ `exports/${userId}/${pendingId}.json`,
+ result.fileName,
+ 600,
+ );
+ });
+
+ it('does not expose another user’s export', async () => {
+ const service = new DataExportService(db, userId);
+ const taskId = await service.createTask();
+ await service.run(taskId);
+
+ await db.insert(users).values({ id: 'data-export-other-user' }).onConflictDoNothing();
+ const other = new DataExportService(db, 'data-export-other-user');
+
+ expect(await other.getLatest()).toBeNull();
+ await expect(other.getDownloadUrl(taskId)).rejects.toThrow('Data export not found');
+ await db.delete(users).where(eq(users.id, 'data-export-other-user'));
+ });
+
+ it('does not store an export that finishes after its deadline', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ let finishExport!: (data: object) => void;
+ mocks.exportTables.mockReturnValue(
+ new Promise((resolve) => {
+ finishExport = resolve;
+ }),
+ );
+ const service = new DataExportService(db, userId);
+ const taskId = await service.createTask();
+
+ const run = service.run(taskId);
+ await vi.advanceTimersByTimeAsync(DATA_EXPORT_RUN_DEADLINE_MS + 1);
+ await run;
+ finishExport({ topics: [] });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(mocks.uploadBuffer).not.toHaveBeenCalled();
+ expect((await getTask(taskId)).status).toBe(AsyncTaskStatus.Error);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reports a run that would outlive the host time limit as failed', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ mocks.exportTables.mockReturnValue(new Promise(() => {}));
+ const service = new DataExportService(db, userId);
+ const taskId = await service.createTask();
+
+ const run = service.run(taskId);
+ await vi.advanceTimersByTimeAsync(DATA_EXPORT_RUN_DEADLINE_MS + 1);
+ await run;
+
+ expect((await getTask(taskId)).status).toBe(AsyncTaskStatus.Error);
+ expect(mocks.notify).toHaveBeenCalledWith({ status: 'error', taskId, userId });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('startDataExport', () => {
+ it('queues one export when two starts arrive at once', async () => {
+ const [first, second] = await Promise.all([
+ startDataExport(db, userId, undefined),
+ startDataExport(db, userId, undefined),
+ ]);
+
+ expect(first.id).toBe(second.id);
+ expect(first.status).toBe('processing');
+ expect(mocks.after).toHaveBeenCalledTimes(1);
+ expect(await db.select().from(asyncTasks).where(eq(asyncTasks.userId, userId))).toHaveLength(1);
+ });
+});
diff --git a/apps/server/src/services/dataExport/index.ts b/apps/server/src/services/dataExport/index.ts
new file mode 100644
index 00000000000..8951273e775
--- /dev/null
+++ b/apps/server/src/services/dataExport/index.ts
@@ -0,0 +1,260 @@
+import { BRANDING_NAME } from '@lobechat/business-const';
+import type {
+ DataExportTaskMetadata,
+ DataExportView,
+ ImportPgDataStructure,
+} from '@lobechat/types';
+import {
+ AsyncTaskError,
+ AsyncTaskErrorType,
+ AsyncTaskStatus,
+ AsyncTaskType,
+} from '@lobechat/types';
+import dayjs from 'dayjs';
+
+import { notifyDataExportResult } from '@/business/server/data-export/notifyDataExportResult';
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { DrizzleMigrationModel } from '@/database/models/drizzleMigration';
+import { DataExporterRepos } from '@/database/repositories/dataExporter';
+import type { AsyncTaskSelectItem } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { FileService } from '@/server/services/file';
+
+/**
+ * An export still queued or running after this long is shown as failed. The
+ * background run is capped by the host's function timeout well below this, so
+ * such a task was lost (crashed instance, dropped hand-off) and will never end.
+ */
+export const DATA_EXPORT_STALE_AFTER_MS = 30 * 60 * 1000;
+
+/**
+ * A run gives up, and reports the failure, before the async route's 800s
+ * function limit would kill it silently and leave the user without a result.
+ */
+export const DATA_EXPORT_RUN_DEADLINE_MS = 12 * 60 * 1000;
+
+/**
+ * Run `work` until it settles or `ms` passes. On the deadline the signal
+ * aborts, so work still going stops instead of finishing after its task was
+ * already reported as failed.
+ */
+const withDeadline = async <T>(
+ work: (signal: AbortSignal) => Promise<T>,
+ ms: number,
+): Promise<T> => {
+ const controller = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ const error = new Error(`Data export did not finish within ${ms}ms`);
+ controller.abort(error);
+ reject(error);
+ }, ms);
+ });
+ try {
+ return await Promise.race([work(controller.signal), deadline]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+/** Rows exported per table query, matching the former synchronous export. */
+const EXPORT_PAGE_CONCURRENCY = 5;
+
+/** How long a download link stays valid; the page asks for a new one per click. */
+const DOWNLOAD_URL_EXPIRES_IN_SECONDS = 10 * 60;
+
+const isStale = (task: AsyncTaskSelectItem, now = Date.now()) =>
+ now - task.createdAt.getTime() > DATA_EXPORT_STALE_AFTER_MS;
+
+export const toDataExportView = (task: AsyncTaskSelectItem): DataExportView => {
+ const metadata = (task.metadata ?? {}) as DataExportTaskMetadata;
+ const base = { createdAt: task.createdAt, id: task.id };
+
+ if (task.status === AsyncTaskStatus.Success && metadata.fileKey) {
+ return {
+ ...base,
+ completedAt: task.updatedAt,
+ fileSize: metadata.fileSize,
+ status: 'success',
+ };
+ }
+
+ if (task.status === AsyncTaskStatus.Pending || task.status === AsyncTaskStatus.Processing) {
+ return { ...base, status: isStale(task) ? 'error' : 'processing' };
+ }
+
+ return { ...base, status: 'error' };
+};
+
+/** Same name the browser download used before exports moved to the background. */
+export const getDataExportFileName = (createdAt: Date) =>
+ `${dayjs(createdAt).format('YYYY-MM-DD-HH-mm')}_${BRANDING_NAME}-data.json`;
+
+/**
+ * Builds a full data export into a stored file, so a large account no longer
+ * has to keep a browser request open until every table is read.
+ *
+ * Only the newest export is kept: once a new file is stored, older export
+ * files and their tasks are removed.
+ */
+export class DataExportService {
+ private db: LobeChatDatabase;
+ private taskModel: AsyncTaskModel;
+ private userId: string;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ this.taskModel = new AsyncTaskModel(db, userId, workspaceId);
+ }
+
+ getLatest = async (): Promise<DataExportView | null> => {
+ const [latest] = await this.taskModel.findAllByType(AsyncTaskType.DataExport);
+ return latest ? toDataExportView(latest) : null;
+ };
+
+ /** The running export, if any; a stale one does not count. */
+ findRunning = async (): Promise<AsyncTaskSelectItem | undefined> => {
+ const tasks = await this.taskModel.findAllByType(AsyncTaskType.DataExport);
+ return tasks.find((task) => toDataExportView(task).status === 'processing');
+ };
+
+ createTask = async (): Promise<string> =>
+ this.taskModel.create({
+ metadata: {} satisfies DataExportTaskMetadata,
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.DataExport,
+ });
+
+ /** Mark a task that was never picked up as failed; a claimed one is left to its runner. */
+ failUnclaimed = async (taskId: string, reason: string) => {
+ const task = await this.taskModel.findById(taskId);
+ if (task?.status !== AsyncTaskStatus.Pending) return;
+
+ await this.taskModel.update(taskId, {
+ error: new AsyncTaskError(AsyncTaskErrorType.TaskTriggerError, reason),
+ status: AsyncTaskStatus.Error,
+ });
+ await this.notify(taskId, 'error');
+ };
+
+ /** Build the export file for a queued task. Runs at most once per task. */
+ run = async (taskId: string): Promise<void> => {
+ if (!(await this.taskModel.claimPending(taskId))) return;
+
+ const startedAt = Date.now();
+ const fileService = new FileService(this.db, this.userId, this.workspaceId);
+
+ try {
+ const { fileKey, fileSize } = await withDeadline(
+ (signal) => this.buildFile(taskId, fileService, signal),
+ DATA_EXPORT_RUN_DEADLINE_MS,
+ );
+
+ await this.taskModel.update(taskId, {
+ duration: Date.now() - startedAt,
+ metadata: { fileKey, fileSize } satisfies DataExportTaskMetadata,
+ status: AsyncTaskStatus.Success,
+ });
+ } catch (error) {
+ console.error('[data-export] export %s failed: %O', taskId, error);
+ await this.taskModel.update(taskId, {
+ duration: Date.now() - startedAt,
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.ServerError,
+ error instanceof Error ? error.message : String(error),
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+ await this.notify(taskId, 'error');
+ return;
+ }
+
+ await this.removeOlderExports(taskId, fileService);
+ await this.notify(taskId, 'success');
+ };
+
+ getDownloadUrl = async (taskId: string): Promise<{ fileName: string; url: string }> => {
+ const task = await this.taskModel.findById(taskId);
+ const fileKey = (task?.metadata as DataExportTaskMetadata | undefined)?.fileKey;
+
+ if (
+ !task ||
+ task.type !== AsyncTaskType.DataExport ||
+ task.status !== AsyncTaskStatus.Success ||
+ !fileKey
+ ) {
+ throw new Error('Data export not found');
+ }
+
+ const fileName = getDataExportFileName(task.createdAt);
+ const url = await new FileService(this.db, this.userId, this.workspaceId).createDownloadUrl(
+ fileKey,
+ fileName,
+ DOWNLOAD_URL_EXPIRES_IN_SECONDS,
+ );
+
+ return { fileName, url };
+ };
+
+ private buildFile = async (taskId: string, fileService: FileService, signal: AbortSignal) => {
+ const data = await new DataExporterRepos(this.db, this.userId, this.workspaceId).export(
+ EXPORT_PAGE_CONCURRENCY,
+ );
+ const schemaHash = await new DrizzleMigrationModel(this.db).getLatestMigrationHash();
+ signal.throwIfAborted();
+ const content: ImportPgDataStructure = { data, mode: 'postgres', schemaHash };
+ const buffer = Buffer.from(JSON.stringify(content));
+
+ const fileKey = `exports/${this.workspaceId ?? this.userId}/${taskId}.json`;
+ // A full account dump is only ever served through short-lived signed links.
+ await fileService.uploadBuffer(fileKey, buffer, 'application/json', {
+ abortSignal: signal,
+ private: true,
+ });
+ if (signal.aborted) {
+ // The upload landed after the task was failed; nothing references this file anymore.
+ await fileService.deleteFile(fileKey).catch(() => {});
+ signal.throwIfAborted();
+ }
+
+ return { fileKey, fileSize: buffer.byteLength };
+ };
+
+ private removeOlderExports = async (keepTaskId: string, fileService: FileService) => {
+ const tasks = await this.taskModel.findAllByType(AsyncTaskType.DataExport);
+ const keepIndex = tasks.findIndex((task) => task.id === keepTaskId);
+ // Only exports created before the kept one; a newer export started meanwhile owns its own cleanup.
+ const older = keepIndex === -1 ? [] : tasks.slice(keepIndex + 1);
+
+ for (const task of older) {
+ if (task.status === AsyncTaskStatus.Processing && !isStale(task)) continue;
+
+ const fileKey = (task.metadata as DataExportTaskMetadata | null)?.fileKey;
+ try {
+ if (fileKey) await fileService.deleteFile(fileKey);
+ await this.taskModel.delete(task.id);
+ } catch (error) {
+ // A leftover old file only costs storage; the new export is already usable.
+ console.error('[data-export] failed to remove old export %s: %O', task.id, error);
+ }
+ }
+ };
+
+ private notify = async (taskId: string, status: 'error' | 'success') => {
+ try {
+ await notifyDataExportResult({
+ status,
+ taskId,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ } catch (error) {
+ // The settings page still shows the result; a lost notification must not fail the export.
+ console.error('[data-export] notify %s failed: %O', taskId, error);
+ }
+ };
+}
diff --git a/apps/server/src/services/dataExport/start.ts b/apps/server/src/services/dataExport/start.ts
new file mode 100644
index 00000000000..e0c0423a8aa
--- /dev/null
+++ b/apps/server/src/services/dataExport/start.ts
@@ -0,0 +1,55 @@
+import type { DataExportView } from '@lobechat/types';
+import { sql } from 'drizzle-orm';
+
+import type { LobeChatDatabase } from '@/database/type';
+import { createAsyncCaller } from '@/server/routers/async';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+import { DataExportService, toDataExportView } from './index';
+
+/**
+ * Queue a data export and hand it to the async router, or return the export
+ * already running. Kept apart from `DataExportService` so the async router can
+ * import that service without importing itself back.
+ *
+ * The export runs in its own request because a large account can take
+ * minutes; the caller only waits for the task row.
+ */
+export const startDataExport = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | undefined,
+): Promise<DataExportView> => {
+ const service = new DataExportService(db, userId, workspaceId);
+
+ // The check and the insert run under one lock per scope, so two tabs (or two
+ // quick clicks) that start at once queue one export, not two.
+ const queued = await db.transaction(async (tx): Promise<DataExportView | string> => {
+ await tx.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext(${`dataExport:${workspaceId ?? userId}`})::bigint)`,
+ );
+ const scoped = new DataExportService(tx as unknown as LobeChatDatabase, userId, workspaceId);
+ const running = await scoped.findRunning();
+ return running ? toDataExportView(running) : scoped.createTask();
+ });
+ // An export already running is returned as is; only a new task is handed off.
+ if (typeof queued !== 'string') return queued;
+
+ const taskId = queued;
+
+ // Hand off after this response is sent, so the click returns at once.
+ after(async () => {
+ try {
+ const asyncCaller = await createAsyncCaller({ userId });
+ await asyncCaller.dataExport.run({ taskId, workspaceId });
+ } catch (error) {
+ // A run the async router already claimed owns its result (a proxy may
+ // drop a long response); only a hand-off that never started is failed here.
+ console.error('[data-export] hand-off of export %s failed: %O', taskId, error);
+ await service.failUnclaimed(taskId, 'Failed to start the data export');
+ }
+ });
+
+ const task = await service.getLatest();
+ return task ?? { createdAt: new Date(), id: taskId, status: 'processing' };
+};
diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.ts
index 9f4c91e792b..2822d6b61a9 100644
--- a/apps/server/src/services/file/__tests__/index.test.ts
+++ b/apps/server/src/services/file/__tests__/index.test.ts
@@ -505,6 +505,7 @@ describe('FileService', () => {
'files/test-user/abc/report.pdf',
content,
'application/pdf',
+ undefined,
);
});
diff --git a/apps/server/src/services/file/impls/s3.ts b/apps/server/src/services/file/impls/s3.ts
index a37a83befac..621c7939906 100644
--- a/apps/server/src/services/file/impls/s3.ts
+++ b/apps/server/src/services/file/impls/s3.ts
@@ -234,8 +234,13 @@ export class S3StaticFileImpl implements FileServiceImpl {
return { key };
}
- async uploadBuffer(key: string, buffer: Buffer, contentType: string): Promise<{ key: string }> {
- await this.s3.uploadBuffer(key, buffer, contentType);
+ async uploadBuffer(
+ key: string,
+ buffer: Buffer,
+ contentType: string,
+ options?: { abortSignal?: AbortSignal; private?: boolean },
+ ): Promise<{ key: string }> {
+ await this.s3.uploadBuffer(key, buffer, contentType, undefined, options);
return { key };
}
}
diff --git a/apps/server/src/services/file/impls/type.ts b/apps/server/src/services/file/impls/type.ts
index 2a183334723..9f190096e32 100644
--- a/apps/server/src/services/file/impls/type.ts
+++ b/apps/server/src/services/file/impls/type.ts
@@ -84,7 +84,12 @@ export interface FileServiceImpl {
/**
* Upload buffer with specified content type (for any file type)
*/
- uploadBuffer: (key: string, buffer: Buffer, contentType: string) => Promise<{ key: string }>;
+ uploadBuffer: (
+ key: string,
+ buffer: Buffer,
+ contentType: string,
+ options?: { abortSignal?: AbortSignal; private?: boolean },
+ ) => Promise<{ key: string }>;
/**
* Upload content
diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.ts
index 1bfdeec2a2f..f40d434ba43 100644
--- a/apps/server/src/services/file/index.ts
+++ b/apps/server/src/services/file/index.ts
@@ -226,8 +226,9 @@ export class FileService {
key: string,
buffer: Buffer,
contentType: string,
+ options?: { abortSignal?: AbortSignal; private?: boolean },
): Promise<{ key: string }> {
- return this.impl.uploadBuffer(key, buffer, contentType);
+ return this.impl.uploadBuffer(key, buffer, contentType, options);
}
private async isStoredFileAvailable(url: string): Promise<boolean> {
diff --git a/apps/server/src/services/skill/importer.test.ts b/apps/server/src/services/skill/importer.test.ts
index cdbfab18eb6..4712207054a 100644
--- a/apps/server/src/services/skill/importer.test.ts
+++ b/apps/server/src/services/skill/importer.test.ts
@@ -607,11 +607,11 @@ describe('SkillImporter', () => {
gitUrl: 'https://github.com/lobehub/skill-path-test',
});
- // Verify uploadBuffer was called with correct path
expect(mockUploadBuffer).toHaveBeenCalledWith(
`skills/zip/${zipHash}.zip`,
expect.any(Buffer),
'application/zip',
+ undefined,
);
});
@@ -668,11 +668,11 @@ describe('SkillImporter', () => {
gitUrl: 'https://github.com/lobehub/large-repo',
});
- // Verify uploadBuffer was called with skillZipBuffer, not the large repo ZIP
expect(mockUploadBuffer).toHaveBeenCalledWith(
expect.stringContaining('skills/zip/'),
smallSkillZip, // Should be the small repacked ZIP
'application/zip',
+ undefined,
);
});
diff --git a/locales/en-US/notification.json b/locales/en-US/notification.json
index f60b8d33442..68cf0f9dc73 100644
--- a/locales/en-US/notification.json
+++ b/locales/en-US/notification.json
@@ -56,6 +56,10 @@
"credit_balance_low": "Your balance is running low — about {{balance}} remaining. Turn on auto top-up so your balance refills automatically and your work is never interrupted.",
"credit_balance_low_action": "Set up auto top-up",
"credit_balance_low_title": "Your balance is running low",
+ "data_export_completed": "Your data export is ready. Open storage settings to download it.",
+ "data_export_completed_title": "Data export ready",
+ "data_export_failed": "Your data export failed. Please try again from storage settings.",
+ "data_export_failed_title": "Data export failed",
"document_comment_activity": "{{actorLabel}} commented on your document \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} replied to your comment in \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "New reply to your comment",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 42d00e18d17..c2f1ed60b62 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -2104,12 +2104,20 @@
"storage.actions.copyLobeAI.desc": "Keep the originals and create independent copies in another Workspace or your personal account. Topics and messages are optional.",
"storage.actions.copyLobeAI.title": "Copy Agents",
"storage.actions.export.button": "Export",
+ "storage.actions.export.download": "Download",
+ "storage.actions.export.downloadError": "Download failed. Please try again.",
"storage.actions.export.exportType.agent": "Export Agent Settings",
"storage.actions.export.exportType.agentWithMessage": "Export Agent and Messages",
"storage.actions.export.exportType.all": "Export Global Settings and All Agent Data",
"storage.actions.export.exportType.allAgent": "Export All Agent Settings",
"storage.actions.export.exportType.allAgentWithMessage": "Export All Agents and Messages",
"storage.actions.export.exportType.globalSetting": "Export Global Settings",
+ "storage.actions.export.exporting": "Exporting…",
+ "storage.actions.export.exportingDesc": "Preparing your data in the background. You can leave this page; we will notify you when it is ready.",
+ "storage.actions.export.failed": "The last export failed. Please try again.",
+ "storage.actions.export.ready": "Last export: {{time}} · {{size}}",
+ "storage.actions.export.rerun": "Export Again",
+ "storage.actions.export.startError": "Could not start the export. Please try again later.",
"storage.actions.export.title": "Export Data",
"storage.actions.import.button": "Import",
"storage.actions.import.title": "Import Data",
diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.json
index 7f570050cb5..169f96f73cb 100644
--- a/locales/zh-CN/notification.json
+++ b/locales/zh-CN/notification.json
@@ -56,6 +56,10 @@
"credit_balance_low": "你的余额即将用尽,当前约剩余 {{balance}}。建议开启自动充值,余额不足时自动续费,让你的工作不被中断。",
"credit_balance_low_action": "开启自动充值",
"credit_balance_low_title": "你的余额即将用尽",
+ "data_export_completed": "你的数据导出已完成,前往数据存储设置下载。",
+ "data_export_completed_title": "数据导出已完成",
+ "data_export_failed": "数据导出失败,请在数据存储设置中重试。",
+ "data_export_failed_title": "数据导出失败",
"document_comment_activity": "{{actorLabel}} 评论了你的文档「{{documentTitle}}」。",
"document_comment_activity_replied": "{{actorLabel}} 在「{{documentTitle}}」中回复了你的评论。",
"document_comment_activity_replied_title": "你的评论有新回复",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 09d09f00705..426b9e4b08c 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -2104,12 +2104,20 @@
"storage.actions.copyLobeAI.desc": "保留原助理,并在另一个工作区或个人账户中创建独立副本。话题和消息为可选项。",
"storage.actions.copyLobeAI.title": "复制助理",
"storage.actions.export.button": "导出",
+ "storage.actions.export.download": "下载",
+ "storage.actions.export.downloadError": "下载失败,请重试。",
"storage.actions.export.exportType.agent": "导出助理设定",
"storage.actions.export.exportType.agentWithMessage": "导出助理和消息",
"storage.actions.export.exportType.all": "导出全局设置和所有助理数据",
"storage.actions.export.exportType.allAgent": "导出所有助理设定",
"storage.actions.export.exportType.allAgentWithMessage": "导出所有助理和消息",
"storage.actions.export.exportType.globalSetting": "导出全局设置",
+ "storage.actions.export.exporting": "导出中…",
+ "storage.actions.export.exportingDesc": "正在后台准备数据,可以先离开此页面,完成后会通知你。",
+ "storage.actions.export.failed": "上次导出失败,请重试。",
+ "storage.actions.export.ready": "上次导出:{{time}} · {{size}}",
+ "storage.actions.export.rerun": "重新导出",
+ "storage.actions.export.startError": "无法开始导出,请稍后重试。",
"storage.actions.export.title": "导出数据",
"storage.actions.import.button": "导入",
"storage.actions.import.title": "导入数据",
diff --git a/packages/database/src/models/__tests__/asyncTask.test.ts b/packages/database/src/models/__tests__/asyncTask.test.ts
index 5342f5ef036..11875d438c7 100644
--- a/packages/database/src/models/__tests__/asyncTask.test.ts
+++ b/packages/database/src/models/__tests__/asyncTask.test.ts
@@ -230,6 +230,71 @@ describe('AsyncTaskModel', () => {
});
});
+ describe('claimPending', () => {
+ it('claims a pending task once and moves it to processing', async () => {
+ const taskId = await asyncTaskModel.create({
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.DataExport,
+ });
+
+ expect(await asyncTaskModel.claimPending(taskId)).toBe(true);
+ expect(await asyncTaskModel.claimPending(taskId)).toBe(false);
+
+ const task = await asyncTaskModel.findById(taskId);
+ expect(task?.status).toBe(AsyncTaskStatus.Processing);
+ });
+
+ it('does not claim a settled task or another user’s task', async () => {
+ const settledId = await asyncTaskModel.create({
+ status: AsyncTaskStatus.Error,
+ type: AsyncTaskType.DataExport,
+ });
+ const pendingId = await asyncTaskModel.create({
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.DataExport,
+ });
+ await serverDB.insert(users).values({ id: 'async-task-other-user' });
+ const otherModel = new AsyncTaskModel(serverDB, 'async-task-other-user');
+
+ expect(await asyncTaskModel.claimPending(settledId)).toBe(false);
+ expect(await otherModel.claimPending(pendingId)).toBe(false);
+ expect((await asyncTaskModel.findById(pendingId))?.status).toBe(AsyncTaskStatus.Pending);
+ });
+ });
+
+ describe('findAllByType', () => {
+ it('returns only the given type in the caller’s scope, newest first', async () => {
+ await serverDB.insert(users).values({ id: 'async-task-other-user' });
+ await serverDB.insert(asyncTasks).values([
+ {
+ createdAt: new Date('2026-01-01'),
+ status: AsyncTaskStatus.Success,
+ type: AsyncTaskType.DataExport,
+ userId,
+ },
+ {
+ createdAt: new Date('2026-02-01'),
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.DataExport,
+ userId,
+ },
+ { status: AsyncTaskStatus.Success, type: AsyncTaskType.Chunking, userId },
+ {
+ status: AsyncTaskStatus.Success,
+ type: AsyncTaskType.DataExport,
+ userId: 'async-task-other-user',
+ },
+ ]);
+
+ const tasks = await asyncTaskModel.findAllByType(AsyncTaskType.DataExport);
+
+ expect(tasks.map((task) => [task.status, task.createdAt.toISOString()])).toEqual([
+ [AsyncTaskStatus.Pending, '2026-02-01T00:00:00.000Z'],
+ [AsyncTaskStatus.Success, '2026-01-01T00:00:00.000Z'],
+ ]);
+ });
+ });
+
describe('findActiveByType', () => {
it('should find active tasks with Pending status', async () => {
await serverDB.insert(asyncTasks).values({
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index e01daf373c2..30ec30121ce 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -10,7 +10,7 @@ import {
AsyncTaskStatus,
AsyncTaskType,
} from '@lobechat/types';
-import { and, eq, inArray, lt, or, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, lt, or, sql } from 'drizzle-orm';
import type { AsyncTaskSelectItem, NewAsyncTaskItem } from '../schemas';
import { asyncTasks } from '../schemas';
@@ -121,6 +121,35 @@ export class AsyncTaskModel {
.where(and(eq(asyncTasks.id, taskId), this.ownership()));
}
+ /**
+ * Move a pending task to processing. Returns false when the task is gone or
+ * another runner already claimed or settled it, so one task runs at most once.
+ */
+ claimPending = async (taskId: string): Promise<boolean> => {
+ const [claimed] = await this.db
+ .update(asyncTasks)
+ .set({ status: AsyncTaskStatus.Processing, updatedAt: new Date() })
+ .where(
+ and(
+ eq(asyncTasks.id, taskId),
+ this.ownership(),
+ eq(asyncTasks.status, AsyncTaskStatus.Pending),
+ ),
+ )
+ .returning({ id: asyncTasks.id });
+
+ return Boolean(claimed);
+ };
+
+ /** All tasks of one type in the current scope, newest first. */
+ findAllByType = async (type: AsyncTaskType): Promise<AsyncTaskSelectItem[]> => {
+ return this.db
+ .select()
+ .from(asyncTasks)
+ .where(and(this.ownership(), eq(asyncTasks.type, type)))
+ .orderBy(desc(asyncTasks.createdAt));
+ };
+
findActiveByType = async (type: AsyncTaskType) => {
return this.db.query.asyncTasks.findFirst({
where: and(
diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.ts
index 59b2cc99964..ee7e8b5f4b0 100644
--- a/packages/locales/src/default/notification.ts
+++ b/packages/locales/src/default/notification.ts
@@ -65,6 +65,10 @@ export default {
'Your balance is running low — about {{balance}} remaining. Turn on auto top-up so your balance refills automatically and your work is never interrupted.',
'credit_balance_low_action': 'Set up auto top-up',
'credit_balance_low_title': 'Your balance is running low',
+ 'data_export_completed': 'Your data export is ready. Open storage settings to download it.',
+ 'data_export_completed_title': 'Data export ready',
+ 'data_export_failed': 'Your data export failed. Please try again from storage settings.',
+ 'data_export_failed_title': 'Data export failed',
'email.footer.contactSupport': 'Contact support',
'email.footer.joinDiscord': 'Join Discord',
'email.footer.manage': 'Manage notifications',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 1d8471a9c45..43977637f2e 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -2004,6 +2004,15 @@ When I am ___, I need ___
'Copy agent groups and their member agents into another workspace or personal account.',
'storage.actions.copyAgentGroups.title': 'Agent Groups Copy',
'storage.actions.export.button': 'Export',
+ 'storage.actions.export.download': 'Download',
+ 'storage.actions.export.downloadError': 'Download failed. Please try again.',
+ 'storage.actions.export.exporting': 'Exporting…',
+ 'storage.actions.export.exportingDesc':
+ 'Preparing your data in the background. You can leave this page; we will notify you when it is ready.',
+ 'storage.actions.export.failed': 'The last export failed. Please try again.',
+ 'storage.actions.export.ready': 'Last export: {{time}} · {{size}}',
+ 'storage.actions.export.rerun': 'Export Again',
+ 'storage.actions.export.startError': 'Could not start the export. Please try again later.',
'storage.actions.export.exportType.agent': 'Export Agent Settings',
'storage.actions.export.exportType.agentWithMessage': 'Export Agent and Messages',
'storage.actions.export.exportType.all': 'Export Global Settings and All Agent Data',
diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.ts
index 54306d86b13..a41a09ecada 100644
--- a/packages/types/src/asyncTask.ts
+++ b/packages/types/src/asyncTask.ts
@@ -2,6 +2,8 @@ import type { SpendOrigin } from './agentRuntime';
export enum AsyncTaskType {
Chunking = 'chunk',
+ /** Full account or workspace data export built in the background (`data_export`). */
+ DataExport = 'data_export',
Embedding = 'embedding',
ImageGeneration = 'image_generation',
/** One-way Linear issue → task sync run in the background (`linear_issue_sync`). */
diff --git a/packages/types/src/dataExport.ts b/packages/types/src/dataExport.ts
new file mode 100644
index 00000000000..4d0e2443677
--- /dev/null
+++ b/packages/types/src/dataExport.ts
@@ -0,0 +1,27 @@
+/**
+ * Stored in `async_tasks.metadata` of a `data_export` task once its file is ready.
+ */
+export interface DataExportTaskMetadata {
+ /** Storage key of the export file, e.g. `exports/<userId>/<taskId>.json`. */
+ fileKey?: string;
+ /** Size of the export file in bytes. */
+ fileSize?: number;
+}
+
+/**
+ * - `processing`: queued or being built
+ * - `success`: the file is ready to download
+ * - `error`: the export failed or never finished
+ */
+export type DataExportStatus = 'error' | 'processing' | 'success';
+
+/** The latest data export as shown on the storage settings page. */
+export interface DataExportView {
+ /** When the file finished building; only set on `success`. */
+ completedAt?: Date;
+ createdAt: Date;
+ /** Size of the export file in bytes; only set on `success`. */
+ fileSize?: number;
+ id: string;
+ status: DataExportStatus;
+}
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 9aedd4ae2a1..2a1019f5b44 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -21,6 +21,7 @@ export * from './contact';
export * from './conversation';
export * from './creds';
export * from './dashboard';
+export * from './dataExport';
export * from './dbMigration';
export * from './device';
export * from './deviceFilePreviewFailure';
diff --git a/src/business/server/data-export/notifyDataExportResult.ts b/src/business/server/data-export/notifyDataExportResult.ts
new file mode 100644
index 00000000000..ccdc8f360e3
--- /dev/null
+++ b/src/business/server/data-export/notifyDataExportResult.ts
@@ -0,0 +1,10 @@
+export interface DataExportResultParams {
+ status: 'error' | 'success';
+ taskId: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/** Tell the user who started a data export that it finished or failed. */
+export const notifyDataExportResult = (_params: DataExportResultParams): Promise<void> =>
+ Promise.resolve();
diff --git a/src/features/DataExporter/useDataExportItem.tsx b/src/features/DataExporter/useDataExportItem.tsx
new file mode 100644
index 00000000000..02bc8767c29
--- /dev/null
+++ b/src/features/DataExporter/useDataExportItem.tsx
@@ -0,0 +1,134 @@
+'use client';
+
+import { type DataExportView } from '@lobechat/types';
+import { Button, Flexbox, Icon, toast } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import { Download, HardDriveUpload } from 'lucide-react';
+import { type ReactNode, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { exportService } from '@/services/export';
+import { downloadFile } from '@/utils/client/downloadFile';
+import { formatSize } from '@/utils/format';
+
+/** How often the row re-reads a running export; the export itself takes seconds to minutes. */
+const PROCESSING_POLL_INTERVAL = 3000;
+
+const LATEST_EXPORT_KEY = 'dataExport:latest';
+
+interface DataExportItemOptions {
+ /** Shown instead of the export status when the user may not export. */
+ disabledReason?: ReactNode;
+ enabled?: boolean;
+}
+
+interface DataExportItem {
+ children: ReactNode;
+ desc?: ReactNode;
+}
+
+/**
+ * The "Export data" settings row. The export is built in the background and
+ * stored, so the user can leave the page; the row shows the running export,
+ * then the latest file to download, and the user is notified when it ends.
+ */
+export const useDataExportItem = ({
+ disabledReason,
+ enabled = true,
+}: DataExportItemOptions = {}): DataExportItem => {
+ const { t } = useTranslation('setting');
+ const [starting, setStarting] = useState(false);
+ const [downloading, setDownloading] = useState(false);
+
+ const { data: latest, mutate } = useClientDataSWR<DataExportView | null>(
+ enabled ? LATEST_EXPORT_KEY : null,
+ () => exportService.getLatestExport(),
+ {
+ refreshInterval: (data?: DataExportView | null) =>
+ data?.status === 'processing' ? PROCESSING_POLL_INTERVAL : 0,
+ },
+ );
+
+ const start = useCallback(async () => {
+ setStarting(true);
+ try {
+ await mutate(await exportService.startExport(), { revalidate: false });
+ } catch (error) {
+ console.error('[dataExport] start failed:', error);
+ toast.error(t('storage.actions.export.startError'));
+ } finally {
+ setStarting(false);
+ }
+ }, [mutate, t]);
+
+ const download = useCallback(async () => {
+ if (!latest) return;
+ setDownloading(true);
+ try {
+ const { fileName, url } = await exportService.getExportDownloadUrl(latest.id);
+ await downloadFile(url, fileName);
+ } catch (error) {
+ console.error('[dataExport] download failed:', error);
+ toast.error(t('storage.actions.export.downloadError'));
+ } finally {
+ setDownloading(false);
+ }
+ }, [latest, t]);
+
+ if (!enabled) {
+ return {
+ children: (
+ <Button disabled icon={<Icon icon={HardDriveUpload} />}>
+ {t('storage.actions.export.button')}
+ </Button>
+ ),
+ desc: disabledReason,
+ };
+ }
+
+ if (latest?.status === 'processing') {
+ return {
+ children: (
+ <Button loading icon={<Icon icon={HardDriveUpload} />}>
+ {t('storage.actions.export.exporting')}
+ </Button>
+ ),
+ desc: t('storage.actions.export.exportingDesc'),
+ };
+ }
+
+ const exportButton = (
+ <Button icon={<Icon icon={HardDriveUpload} />} loading={starting} onClick={start}>
+ {t(latest ? 'storage.actions.export.rerun' : 'storage.actions.export.button')}
+ </Button>
+ );
+
+ if (latest?.status === 'success') {
+ return {
+ children: (
+ <Flexbox horizontal gap={8}>
+ {exportButton}
+ <Button
+ icon={<Icon icon={Download} />}
+ loading={downloading}
+ type={'primary'}
+ onClick={download}
+ >
+ {t('storage.actions.export.download')}
+ </Button>
+ </Flexbox>
+ ),
+ desc: t('storage.actions.export.ready', {
+ size: latest.fileSize === undefined ? '-' : formatSize(latest.fileSize),
+ time: dayjs(latest.completedAt ?? latest.createdAt).format('YYYY-MM-DD HH:mm'),
+ }),
+ };
+ }
+
+ if (latest?.status === 'error') {
+ return { children: exportButton, desc: t('storage.actions.export.failed') };
+ }
+
+ return { children: exportButton };
+};
diff --git a/src/features/Settings/storage/features/Advanced.test.tsx b/src/features/Settings/storage/features/Advanced.test.tsx
index 651922086d7..0e4ea2a369d 100644
--- a/src/features/Settings/storage/features/Advanced.test.tsx
+++ b/src/features/Settings/storage/features/Advanced.test.tsx
@@ -1,10 +1,12 @@
-import { fireEvent, render, screen } from '@testing-library/react';
+import { act, fireEvent, render, screen } from '@testing-library/react';
import { type ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { mapFeatureFlagsEnvToState } from '@/config/featureFlags';
+import { exportService } from '@/services/export';
import { initServerConfigStore, Provider } from '@/store/serverConfig/store';
import { useUserStore } from '@/store/user';
+import { downloadFile } from '@/utils/client/downloadFile';
import AdvancedActions from './Advanced';
@@ -27,13 +29,17 @@ vi.mock('@/features/DataImporter', () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
-vi.mock('@/services/config', () => ({
- configService: {
- exportAll: vi.fn(),
+vi.mock('@/services/export', () => ({
+ exportService: {
+ getExportDownloadUrl: vi.fn(),
+ getLatestExport: vi.fn(),
+ startExport: vi.fn(),
},
}));
-const createWrapper = (hideDocs: boolean) => {
+vi.mock('@/utils/client/downloadFile', () => ({ downloadFile: vi.fn() }));
+
+const createWrapper = (hideDocs: boolean, enableBusinessFeatures = false) => {
const Wrapper = ({ children }: { children: ReactNode }) => (
<Provider
createStore={() =>
@@ -44,6 +50,7 @@ const createWrapper = (hideDocs: boolean) => {
}),
hideDocs,
},
+ serverConfig: { aiProvider: {}, enableBusinessFeatures, telemetry: {} },
})
}
>
@@ -85,4 +92,60 @@ describe('AdvancedActions', () => {
expect(updateGeneralConfig).toHaveBeenCalledWith({ telemetry: false });
});
+
+ it('starts a background export and shows it as running', async () => {
+ vi.mocked(exportService.getLatestExport).mockResolvedValue(null);
+ vi.mocked(exportService.startExport).mockResolvedValue({
+ createdAt: new Date(),
+ id: 'task-1',
+ status: 'processing',
+ });
+
+ render(<AdvancedActions />, { wrapper: createWrapper(false, true) });
+
+ fireEvent.click(await screen.findByText('storage.actions.export.button'));
+
+ expect(await screen.findByText('storage.actions.export.exporting')).toBeDefined();
+ expect(screen.getByText('storage.actions.export.exportingDesc')).toBeDefined();
+ expect(exportService.startExport).toHaveBeenCalledTimes(1);
+ });
+
+ it('offers the finished export for download', async () => {
+ vi.mocked(exportService.getLatestExport).mockResolvedValue({
+ completedAt: new Date('2026-11-16T08:30:00Z'),
+ createdAt: new Date('2026-11-16T08:29:00Z'),
+ fileSize: 2048,
+ id: 'task-1',
+ status: 'success',
+ });
+ vi.mocked(exportService.getExportDownloadUrl).mockResolvedValue({
+ fileName: 'export.json',
+ url: 'https://s3/signed',
+ });
+
+ render(<AdvancedActions />, { wrapper: createWrapper(false, true) });
+
+ expect(await screen.findByText('storage.actions.export.ready')).toBeDefined();
+ expect(screen.getByText('storage.actions.export.rerun')).toBeDefined();
+
+ await act(async () => {
+ fireEvent.click(screen.getByText('storage.actions.export.download'));
+ });
+
+ expect(exportService.getExportDownloadUrl).toHaveBeenCalledWith('task-1');
+ expect(downloadFile).toHaveBeenCalledWith('https://s3/signed', 'export.json');
+ });
+
+ it('tells the user when the last export failed', async () => {
+ vi.mocked(exportService.getLatestExport).mockResolvedValue({
+ createdAt: new Date(),
+ id: 'task-1',
+ status: 'error',
+ });
+
+ render(<AdvancedActions />, { wrapper: createWrapper(false, true) });
+
+ expect(await screen.findByText('storage.actions.export.failed')).toBeDefined();
+ expect(screen.getByText('storage.actions.export.rerun')).toBeDefined();
+ });
});
diff --git a/src/features/Settings/storage/features/Advanced.tsx b/src/features/Settings/storage/features/Advanced.tsx
index 9cab79f4058..14d6702ee80 100644
--- a/src/features/Settings/storage/features/Advanced.tsx
+++ b/src/features/Settings/storage/features/Advanced.tsx
@@ -3,16 +3,16 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { Button, confirmModal, Icon, Switch, toast } from '@lobehub/ui';
import { Form, type FormGroupItem, useForm } from '@lobehub/ui/form';
-import { HardDriveDownload, HardDriveUpload } from 'lucide-react';
+import { HardDriveDownload } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import AccountDeletion from '@/business/client/features/AccountDeletion';
import { useTransferAgentsFormItem } from '@/business/client/hooks/useTransferAgentsFormItem';
import { FORM_STYLE } from '@/const/layoutTokens';
+import { useDataExportItem } from '@/features/DataExporter/useDataExportItem';
import DataImporter from '@/features/DataImporter';
import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
-import { configService } from '@/services/config';
import { useServerConfigStore } from '@/store/serverConfig';
import { featureFlagsSelectors, serverConfigSelectors } from '@/store/serverConfig/selectors';
import { useUserStore } from '@/store/user';
@@ -28,6 +28,7 @@ const AdvancedActions = () => {
const resetSettings = useUserStore((s) => s.resetSettings);
const updateGeneralConfig = useUserStore((s) => s.updateGeneralConfig);
const form = useForm();
+ const exportItem = useDataExportItem({ enabled: enableBusinessFeatures });
const handleReset = useCallback(() => {
confirmModal({
@@ -45,16 +46,8 @@ const AdvancedActions = () => {
const renderExportButtonFormItem = () => {
return {
- children: (
- <Button
- icon={<Icon icon={HardDriveUpload} />}
- onClick={() => {
- configService.exportAll();
- }}
- >
- {t('storage.actions.export.button')}
- </Button>
- ),
+ children: exportItem.children,
+ desc: exportItem.desc,
label: (
<SettingsSearchAnchor id={'storage-export'}>
{t('storage.actions.export.title')}
diff --git a/src/features/User/__tests__/useMenu.test.tsx b/src/features/User/__tests__/useMenu.test.tsx
index f5ec3e6aeb0..2b612cc66c3 100644
--- a/src/features/User/__tests__/useMenu.test.tsx
+++ b/src/features/User/__tests__/useMenu.test.tsx
@@ -37,15 +37,6 @@ vi.mock('react-i18next', () => ({
})),
}));
-vi.mock('@/services/config', () => ({
- configService: {
- exportAgents: vi.fn(),
- exportAll: vi.fn(),
- exportSessions: vi.fn(),
- exportSettings: vi.fn(),
- },
-}));
-
vi.mock('./useNewVersion', () => ({
useNewVersion: vi.fn(() => false),
}));
diff --git a/src/services/config.ts b/src/services/config.ts
deleted file mode 100644
index b3d6a109872..00000000000
--- a/src/services/config.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { BRANDING_NAME } from '@lobechat/business-const';
-import { downloadFile, exportJSONFile } from '@lobechat/utils/client';
-import dayjs from 'dayjs';
-
-import { type ImportPgDataStructure } from '@/types/export';
-
-import { exportService } from './export';
-
-class ConfigService {
- exportAll = async () => {
- const { data, url, schemaHash } = await exportService.exportData();
- const filename = `${dayjs().format('YYYY-MM-DD-hh-mm')}_${BRANDING_NAME}-data.json`;
-
- // if url exists, means export data from server and upload the data to S3
- // just need to download the file
- if (url) {
- await downloadFile(url, filename);
- return;
- }
-
- const result: ImportPgDataStructure = { data, mode: 'postgres', schemaHash };
-
- exportJSONFile(result, filename);
- };
-}
-
-export const configService = new ConfigService();
diff --git a/src/services/export/index.ts b/src/services/export/index.ts
index 7e34fac22eb..6199671e992 100644
--- a/src/services/export/index.ts
+++ b/src/services/export/index.ts
@@ -1,10 +1,15 @@
+import { type DataExportView } from '@lobechat/types';
+
import { lambdaClient } from '@/libs/trpc/client';
-import { type ExportDatabaseData } from '@/types/export';
class ExportService {
- exportData = async (): Promise<ExportDatabaseData> => {
- return await lambdaClient.exporter.exportData.mutate();
- };
+ getExportDownloadUrl = async (id: string): Promise<{ fileName: string; url: string }> =>
+ lambdaClient.exporter.getExportDownloadUrl.mutate({ id });
+
+ getLatestExport = async (): Promise<DataExportView | null> =>
+ lambdaClient.exporter.getLatestExport.query();
+
+ startExport = async (): Promise<DataExportView> => lambdaClient.exporter.startExport.mutate();
}
export const exportService = new ExportService();