🤯 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(acceptance): opt-in purge of evidence files when deleting (#19529)
Innei1918aaf433dd
diff --git a/apps/server/src/modules/S3/index.test.ts b/apps/server/src/modules/S3/index.test.tsindex 9da359840bf..a98e4753ad0 100644--- a/apps/server/src/modules/S3/index.test.ts+++ b/apps/server/src/modules/S3/index.test.ts@@ -238,6 +238,20 @@ describe('FileS3', () => {expect(mockS3ClientSend).toHaveBeenCalled();});+ it('should split more than 1000 keys into multiple requests', async () => {+ const s3 = new FileS3();+ mockS3ClientSend.mockResolvedValue({});++ const keys = Array.from({ length: 2001 }, (_, i) => `file${i}.txt`);+ await s3.deleteFiles(keys);++ expect(mockS3ClientSend).toHaveBeenCalledTimes(3);+ const sizes = vi+ .mocked(DeleteObjectsCommand)+ .mock.calls.map(([input]) => input.Delete!.Objects!.length);+ expect(sizes).toEqual([1000, 1000, 1]);+ });+it('should handle empty array', async () => {const s3 = new FileS3();mockS3ClientSend.mockResolvedValue({});diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.tsindex 0a121e31a18..5842f5df09d 100644--- a/apps/server/src/modules/S3/index.ts+++ b/apps/server/src/modules/S3/index.ts@@ -30,6 +30,8 @@ export type FileType = z.infer<typeof fileSchema>;const DEFAULT_S3_REGION = 'us-east-1';const PUBLIC_READ_ACL_HEADER = 'public-read';+// S3 DeleteObjects rejects more than 1000 keys per request.+const DELETE_OBJECTS_MAX_KEYS = 1000;const encodeContentDispositionFilename = (fileName: string) =>encodeURIComponent(fileName || 'download').replaceAll(@@ -91,12 +93,22 @@ export class S3 {}public async deleteFiles(keys: string[]) {- const command = new DeleteObjectsCommand({- Bucket: this.bucket,- Delete: { Objects: keys.map((key) => ({ Key: key })) },- });+ const batches = [];+ for (let i = 0; i < keys.length; i += DELETE_OBJECTS_MAX_KEYS) {+ batches.push(keys.slice(i, i + DELETE_OBJECTS_MAX_KEYS));+ }+ if (batches.length === 0) batches.push([]);- return this.client.send(command);+ const results = [];+ for (const batch of batches) {+ const command = new DeleteObjectsCommand({+ Bucket: this.bucket,+ Delete: { Objects: batch.map((key) => ({ Key: key })) },+ });+ results.push(await this.client.send(command));+ }++ return results.at(-1)!;}public async getFileContent(key: string, byteLength?: number): Promise<string> {diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.purge.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.purge.test.tsnew file mode 100644index 00000000000..76958d3f2e8--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/acceptance.purge.test.ts@@ -0,0 +1,231 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import { type LobeChatDatabase } from '@lobechat/database';+import { acceptances, verifyRuns, workspaceMembers, workspaces } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { acceptanceRouter } from '../acceptance';+import { cleanupTestUser, createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++const purgeMocks = vi.hoisted(() => ({+ previewAcceptancePurge: vi.fn(),+ purgeAcceptance: vi.fn(),+}));++vi.mock('@/server/services/verify/acceptancePurge', () => purgeMocks);++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return { deleteFiles: vi.fn() };+ }),+}));++describe('acceptanceRouter purge', () => {+ let serverDB: LobeChatDatabase;+ let ownerId: string;+ let strangerId: string;+ let workspaceOwnerId: string;+ let workspaceId: string;+ let personalId: string;+ let workspaceRowId: string;++ beforeEach(async () => {+ serverDB = await getTestDB();+ testDB = serverDB;+ vi.clearAllMocks();+ ownerId = await createTestUser(serverDB);+ strangerId = await createTestUser(serverDB);+ workspaceOwnerId = await createTestUser(serverDB);++ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: workspaceOwnerId, slug: `ws-${randomUUID()}` })+ .returning();+ workspaceId = workspace.id;+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId: workspaceOwnerId, workspaceId },+ { role: 'member', userId: ownerId, workspaceId },+ ]);++ const [personal, workspaceRow] = await serverDB+ .insert(acceptances)+ .values([+ {+ subjectId: randomUUID(),+ subjectType: 'standalone',+ userId: ownerId,+ visibility: 'private',+ },+ {+ subjectId: randomUUID(),+ subjectType: 'standalone',+ userId: ownerId,+ visibility: 'private',+ workspaceId,+ },+ ])+ .returning();+ personalId = personal.id;+ workspaceRowId = workspaceRow.id;+ });++ afterEach(async () => {+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await cleanupTestUser(serverDB, strangerId);+ await cleanupTestUser(serverDB, workspaceOwnerId);+ await cleanupTestUser(serverDB, ownerId);+ });++ const caller = (userId: string) =>+ acceptanceRouter.createCaller({ jwtPayload: { userId }, userId } as any);++ describe('purgePreview', () => {+ it('previews with the acceptance scope for a reader and hides a private one from strangers', async () => {+ purgeMocks.previewAcceptancePurge.mockResolvedValueOnce({+ bytes: 10,+ fileCount: 1,+ files: { images: 1, other: 0, videos: 0 },+ rounds: 2,+ });++ const res = await caller(ownerId).purgePreview({ ids: [workspaceRowId] });++ expect(res).toEqual({+ bytes: 10,+ fileCount: 1,+ files: { images: 1, other: 0, videos: 0 },+ rounds: 2,+ });+ expect(purgeMocks.previewAcceptancePurge).toHaveBeenCalledWith(+ expect.anything(),+ ownerId,+ workspaceId,+ [workspaceRowId],+ );++ await expect(caller(strangerId).purgePreview({ ids: [personalId] })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ it('sums one preview per scope across a batch and rejects when any id is unreadable', async () => {+ purgeMocks.previewAcceptancePurge+ .mockResolvedValueOnce({+ bytes: 10,+ fileCount: 1,+ files: { images: 1, other: 0, videos: 0 },+ rounds: 2,+ })+ .mockResolvedValueOnce({+ bytes: 5,+ fileCount: 2,+ files: { images: 0, other: 1, videos: 1 },+ rounds: 1,+ });++ const res = await caller(ownerId).purgePreview({ ids: [personalId, workspaceRowId] });++ expect(res).toEqual({+ bytes: 15,+ fileCount: 3,+ files: { images: 1, other: 1, videos: 1 },+ rounds: 3,+ });+ expect(purgeMocks.previewAcceptancePurge).toHaveBeenCalledTimes(2);+ expect(purgeMocks.previewAcceptancePurge).toHaveBeenCalledWith(+ expect.anything(),+ ownerId,+ undefined,+ [personalId],+ );+ expect(purgeMocks.previewAcceptancePurge).toHaveBeenCalledWith(+ expect.anything(),+ ownerId,+ workspaceId,+ [workspaceRowId],+ );++ await expect(+ caller(strangerId).purgePreview({ ids: [workspaceRowId, personalId] }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(+ caller(ownerId).purgePreview({ ids: [personalId, randomUUID()] }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+ });++ describe('remove', () => {+ it('detaches the rounds without purging by default', async () => {+ const [run] = await serverDB+ .insert(verifyRuns)+ .values({ acceptanceId: workspaceRowId, roundIndex: 1, userId: ownerId, workspaceId })+ .returning();++ await caller(ownerId).remove({ id: workspaceRowId });++ expect(purgeMocks.purgeAcceptance).not.toHaveBeenCalled();+ expect(+ await serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, workspaceRowId) }),+ ).toBeUndefined();+ expect(+ await serverDB.query.verifyRuns.findFirst({ where: eq(verifyRuns.id, run.id) }),+ ).toMatchObject({ acceptanceId: null });+ });++ it('purges through the acceptance scope when asked', async () => {+ await caller(ownerId).remove({ id: workspaceRowId, purge: true });++ expect(purgeMocks.purgeAcceptance).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ ownerId,+ workspaceId,+ workspaceRowId,+ );+ });++ it('detaches each manageable row in a batch by default and collects the rest', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const [foreign] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: strangerId })+ .returning();++ const res = await caller(ownerId).removeBatch({ ids: [personalId, foreign.id] });++ expect(res).toEqual({ deleted: 1, failedIds: [foreign.id] });+ expect(purgeMocks.purgeAcceptance).not.toHaveBeenCalled();+ expect(+ await serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, personalId) }),+ ).toBeUndefined();+ });++ it('purges each manageable row in a batch when asked', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const [foreign] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: strangerId })+ .returning();++ const res = await caller(ownerId).removeBatch({ ids: [personalId, foreign.id], purge: true });++ expect(res).toEqual({ deleted: 1, failedIds: [foreign.id] });+ expect(purgeMocks.purgeAcceptance).toHaveBeenCalledTimes(1);+ expect(purgeMocks.purgeAcceptance).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ ownerId,+ undefined,+ personalId,+ );+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.tsindex 43e33f0a771..058a18b1b53 100644--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts@@ -8,6 +8,7 @@ import type * as VerifyServiceModule from '@/server/services/verify';const modelMocks = vi.hoisted(() => ({createEvidence: vi.fn(),+ purgeVerifyRun: vi.fn(),createRun: vi.fn(),deleteResult: vi.fn(),deleteRun: vi.fn(),@@ -67,6 +68,10 @@ vi.mock('@/server/services/verify', async (importOriginal) => ({VerifyReporterService: class VerifyReporterService {},}));+vi.mock('@/server/services/verify/acceptancePurge', () => ({+ purgeVerifyRun: modelMocks.purgeVerifyRun,+}));+vi.mock('@/server/services/goal/criteriaGenerator', () => ({GoalCriteriaGeneratorService: class GoalCriteriaGeneratorService {generate = modelMocks.generateGoalCriteria;@@ -248,15 +253,26 @@ describe('verifyRouter', () => {);expect(modelMocks.findRunById).toHaveBeenCalledWith('other-user-run');- expect(modelMocks.deleteRun).not.toHaveBeenCalled();+ expect(modelMocks.purgeVerifyRun).not.toHaveBeenCalled();});- it('deletes a run the caller owns and returns its id', async () => {- modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });+ it('purges a run the caller owns in its own scope and returns its id', async () => {+ modelMocks.findRunById.mockResolvedValueOnce({+ id: 'run-1',+ userId: 'verify-router-test-user',+ workspaceId: 'ws-1',+ });const res = await createCaller().deleteRun({ verifyRunId: 'run-1' });- expect(modelMocks.deleteRun).toHaveBeenCalledWith('run-1');+ expect(modelMocks.purgeVerifyRun).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ 'verify-router-test-user',+ 'ws-1',+ 'run-1',+ );+ expect(modelMocks.deleteRun).not.toHaveBeenCalled();expect(res).toEqual({ id: 'run-1', success: true });});});diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex 9fb49989cb5..72fa3756830 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -29,6 +29,7 @@ import type { LobeChatDatabase } from '@/database/type';import { isUuid } from '@/database/utils/uuid';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { FileService } from '@/server/services/file';import {AcceptanceService,buildAcceptanceCheckUnion,@@ -36,6 +37,8 @@ import {createEvidenceFileResolver,isCurrentReviewPrediction,mapWithConcurrency,+ previewAcceptancePurge,+ purgeAcceptance,REVIEW_PREDICT_CONCURRENCY,REVIEW_PREDICT_MODEL_CONFIG,shouldSurfaceProposal,@@ -150,8 +153,26 @@ const resolveAcceptanceForWrite = async (};};+const canReadAcceptance = async (+ ctx: { serverDB: LobeChatDatabase; userId?: string | null },+ acceptance: AcceptanceItem,+) => {+ if (ctx.userId && ctx.userId === acceptance.userId) return true;+ if (acceptance.visibility === 'public') return true;+ if (!ctx.userId || !acceptance.workspaceId) return false;+ // Membership in the acceptance's OWN workspace — not the viewer's currently+ // active one, which may be a different workspace entirely.+ const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(+ acceptance.workspaceId,+ ctx.userId,+ );+ return Boolean(member);+};+/** Max rows one multi-select sweep may touch — the list itself is capped at 200. */const ACCEPTANCE_BATCH_LIMIT = 200;+const PURGE_BATCH_CONCURRENCY = 4;+const PURGE_PREVIEW_LIMIT = 20;const acceptanceStatusOverrideSchema = z.enum(['delivered', 'accepted', 'closed', 'rejected']);@@ -525,18 +546,7 @@ export const acceptanceRouter = router({}const isOwner = Boolean(ctx.userId) && ctx.userId === acceptance.userId;- // The viewer's membership in the acceptance's OWN workspace — not their- // currently-active one, which may be a different workspace entirely.- const member =- !isOwner && ctx.userId && acceptance.workspaceId- ? await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(- acceptance.workspaceId,- ctx.userId,- )- : undefined;-- const canRead = isOwner || acceptance.visibility === 'public' || Boolean(member);- if (!canRead) {+ if (!isOwner && !(await canReadAcceptance(ctx, acceptance))) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });}@@ -1375,17 +1385,68 @@ export const acceptanceRouter = router({return { failedIds, updated };}),+ purgePreview: acceptanceProcedure+ .input(z.object({ ids: z.array(z.string()).min(1).max(PURGE_PREVIEW_LIMIT) }))+ .query(async ({ ctx, input }) => {+ const ids = [...new Set(input.ids)];+ const rows = ids.every(isUuid)+ ? await ctx.serverDB.query.acceptances.findMany({ where: inArray(acceptances.id, ids) })+ : [];+ const readable = await Promise.all(rows.map((row) => canReadAcceptance(ctx, row)));+ if (rows.length !== ids.length || readable.includes(false)) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });+ }++ const scopes = new Map<string, { ids: string[]; userId: string; workspaceId?: string }>();+ for (const row of rows) {+ const workspaceId = row.workspaceId ?? undefined;+ const key = workspaceId ?? `user:${row.userId}`;+ const scope = scopes.get(key) ?? { ids: [], userId: row.userId, workspaceId };+ scope.ids.push(row.id);+ scopes.set(key, scope);+ }+ const previews = await Promise.all(+ [...scopes.values()].map((scope) =>+ previewAcceptancePurge(ctx.serverDB, scope.userId, scope.workspaceId, scope.ids),+ ),+ );+ return previews.reduce(+ (total, preview) => ({+ bytes: total.bytes + preview.bytes,+ fileCount: total.fileCount + preview.fileCount,+ files: {+ images: total.files.images + preview.files.images,+ other: total.files.other + preview.files.other,+ videos: total.files.videos + preview.files.videos,+ },+ rounds: total.rounds + preview.rounds,+ }),+ { bytes: 0, fileCount: 0, files: { images: 0, other: 0, videos: 0 }, rounds: 0 },+ );+ }),+/**- * Delete the acceptance aggregate. Its chained verify runs detach- * (acceptance_id → null via the FK's `set null`) rather than cascade-delete,- * so the individual round reports stay reachable; only the grouping goes.+ * Delete the acceptance aggregate. By default its chained verify runs detach+ * (acceptance_id → null via the FK's `set null`) so the individual round+ * reports stay reachable; `purge` also removes the rounds and the evidence+ * files only they referenced.*/remove: acceptanceWriteProcedure- .input(z.object({ id: z.string() }))+ .input(z.object({ id: z.string(), purge: z.boolean().optional() })).mutation(async ({ ctx, input }) => {const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- await service.acceptanceModel.delete(acceptance.id);+ if (input.purge) {+ await purgeAcceptance(+ ctx.serverDB,+ new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ acceptance.id,+ );+ } else {+ await service.acceptanceModel.delete(acceptance.id);+ }return { success: true };}),@@ -1395,21 +1456,37 @@ export const acceptanceRouter = router({* selection still goes.*/removeBatch: acceptanceWriteProcedure- .input(z.object({ ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT) }))+ .input(+ z.object({+ ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),+ purge: z.boolean().optional(),+ }),+ ).mutation(async ({ ctx, input }) => {const failedIds: string[] = [];let deleted = 0;+ const fileService = new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);- for (const id of new Set(input.ids)) {+ await mapWithConcurrency([...new Set(input.ids)], PURGE_BATCH_CONCURRENCY, async (id) => {try {const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);- await service.acceptanceModel.delete(acceptance.id);+ if (input.purge) {+ await purgeAcceptance(+ ctx.serverDB,+ fileService,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ acceptance.id,+ );+ } else {+ await service.acceptanceModel.delete(acceptance.id);+ }deleted += 1;} catch (error) {console.error('[acceptance] batch delete failed for %s', id, error);failedIds.push(id);}- }+ });return { deleted, failedIds };}),diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex ea7331b7ff6..f78e78ce4b5 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -41,11 +41,13 @@ import { isUuid } from '@/database/utils/uuid';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';+import { FileService } from '@/server/services/file';import { GoalCriteriaGeneratorService } from '@/server/services/goal/criteriaGenerator';import {AcceptanceService,createEvidenceFileResolver,finalizeVerifyRun,+ purgeVerifyRun,VerifyExecutorService,VerifyFeedbackService,VerifyPlanGeneratorService,@@ -823,14 +825,21 @@ export const verifyRouter = router({.query(async ({ ctx, input }) => ctx.runModel.findById(input.verifyRunId)),// Delete a whole verification session: the run row cascades to its check- // results (→ their evidence) and its report via the schema FKs, so one delete- // tears down the published bundle. Ownership-scoped: resolveVerifyRun 404s a- // run that isn't the caller's before we touch it.+ // results (→ their evidence) and its report via the schema FKs, and the+ // evidence files only this run referenced are purged from storage.+ // Ownership-scoped: resolveVerifyRun 404s a run that isn't the caller's+ // before we touch it.deleteRun: verifyWriteProcedure.input(verifyRunIdInputSchema).mutation(async ({ ctx, input }) => {const run = await resolveVerifyRun(ctx, input.verifyRunId);assertWorkspaceRowManageable(ctx, run.userId, 'verify run');- await ctx.runModel.delete(run.id);+ await purgeVerifyRun(+ ctx.serverDB,+ new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),+ run.userId,+ run.workspaceId ?? undefined,+ run.id,+ );return { id: run.id, success: true };}),diff --git a/apps/server/src/services/verify/__tests__/acceptancePurge.test.ts b/apps/server/src/services/verify/__tests__/acceptancePurge.test.tsnew file mode 100644index 00000000000..9b02337850d--- /dev/null+++ b/apps/server/src/services/verify/__tests__/acceptancePurge.test.ts@@ -0,0 +1,338 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import { type LobeChatDatabase } from '@lobechat/database';+import {+ acceptances,+ files,+ globalFiles,+ users,+ verifyCheckResults,+ verifyEvidence,+ verifyRuns,+} from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { FileSource } from '@lobechat/types';+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { FileService } from '@/server/services/file';++import { previewAcceptancePurge, purgeAcceptance, purgeVerifyRun } from '../acceptancePurge';++const envMock = vi.hoisted(() => ({ serverDBEnv: { REMOVE_GLOBAL_FILE: true } }));+vi.mock('@/config/db', () => envMock);++const createTestUser = async (db: LobeChatDatabase) => {+ const id = randomUUID();+ await db.insert(users).values({ id });+ return id;+};++const cleanupTestUser = async (db: LobeChatDatabase, id: string) => {+ await db.delete(users).where(eq(users.id, id));+};++describe('acceptancePurge', () => {+ let serverDB: LobeChatDatabase;+ let userId: string;+ let acceptanceId: string;+ let runIds: string[];+ let fileIds: string[];+ let keeperFileId: string;+ let SHARED_HASH: string;+ let SOLO_HASH: string;+ let PAIR_HASH: string;+ const fileService = { deleteFiles: vi.fn() } as unknown as FileService;++ const seedRound = async (targetAcceptanceId: string, roundIndex: number, fileIds: string[]) => {+ const [run] = await serverDB+ .insert(verifyRuns)+ .values({ acceptanceId: targetAcceptanceId, roundIndex, userId })+ .returning();+ const [result] = await serverDB+ .insert(verifyCheckResults)+ .values({ checkItemId: 'c1', userId, verifierType: 'agent', verifyRunId: run.id })+ .returning();+ await serverDB.insert(verifyEvidence).values(+ fileIds.map((fileId) => ({+ checkResultId: result.id,+ fileId,+ type: 'screenshot' as const,+ userId,+ })),+ );+ return run.id;+ };++ beforeEach(async () => {+ serverDB = await getTestDB();+ userId = await createTestUser(serverDB);+ vi.mocked(fileService.deleteFiles).mockReset();+ envMock.serverDBEnv.REMOVE_GLOBAL_FILE = true;+ SHARED_HASH = randomUUID().replaceAll('-', '');+ SOLO_HASH = randomUUID().replaceAll('-', '');+ PAIR_HASH = randomUUID().replaceAll('-', '');++ await serverDB.insert(globalFiles).values([+ { creator: userId, fileType: 'image/png', hashId: SHARED_HASH, size: 500, url: 'shared.png' },+ { creator: userId, fileType: 'video/mp4', hashId: SOLO_HASH, size: 900, url: 'solo.mp4' },+ ]);+ const inserted = await serverDB+ .insert(files)+ .values([+ {+ fileHash: SHARED_HASH,+ fileType: 'image/png',+ name: 'a.png',+ size: 500,+ source: FileSource.Acceptance,+ url: 'shared.png',+ userId,+ },+ {+ fileHash: SHARED_HASH,+ fileType: 'image/png',+ name: 'b.png',+ size: 500,+ source: FileSource.Acceptance,+ url: 'shared.png',+ userId,+ },+ {+ fileHash: SOLO_HASH,+ fileType: 'video/mp4',+ name: 'c.mp4',+ size: 900,+ source: FileSource.Acceptance,+ url: 'solo.mp4',+ userId,+ },+ {+ fileHash: SHARED_HASH,+ fileType: 'image/png',+ name: 'keeper.png',+ size: 500,+ url: 'shared.png',+ userId,+ },+ ])+ .returning({ id: files.id });+ fileIds = inserted.slice(0, 3).map((f) => f.id);+ keeperFileId = inserted[3].id;++ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId })+ .returning();+ acceptanceId = acceptance.id;+ runIds = [+ await seedRound(acceptanceId, 1, [fileIds[0], fileIds[1]]),+ await seedRound(acceptanceId, 2, [fileIds[2]]),+ ];+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, userId);+ await serverDB+ .delete(globalFiles)+ .where(inArray(globalFiles.hashId, [SHARED_HASH, SOLO_HASH, PAIR_HASH]));+ });++ const seedFile = async (values: Partial<typeof files.$inferInsert>) => {+ const [row] = await serverDB+ .insert(files)+ .values({+ fileType: 'text/plain',+ name: 'x.log',+ size: 100,+ source: FileSource.Acceptance,+ url: `${randomUUID()}.log`,+ userId,+ ...values,+ })+ .returning({ id: files.id });+ return row.id;+ };++ const seedAcceptance = async () => {+ const [row] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId })+ .returning();+ return row.id;+ };++ it('previews rounds and file counts, and only counts bytes of objects that will be freed', async () => {+ await expect(+ previewAcceptancePurge(serverDB, userId, undefined, [acceptanceId]),+ ).resolves.toEqual({+ bytes: 900,+ fileCount: 3,+ files: { images: 2, other: 0, videos: 1 },+ rounds: 2,+ });+ });++ it('previews a batch jointly so a hash shared only inside the batch is freed and counted once', async () => {+ await serverDB+ .insert(globalFiles)+ .values({ creator: userId, fileType: 'text/plain', hashId: PAIR_HASH, size: 300, url: 'p' });+ const d = await seedFile({ fileHash: PAIR_HASH, fileType: 'text/plain', size: 300 });+ const e = await seedFile({ fileHash: PAIR_HASH, fileType: 'text/plain', size: 300 });+ const hashless = await seedFile({ fileHash: null, size: 50 });+ const otherAcceptanceId = await seedAcceptance();+ await seedRound(otherAcceptanceId, 1, [d, hashless]);+ await seedRound(acceptanceId, 3, [e]);++ await expect(+ previewAcceptancePurge(serverDB, userId, undefined, [acceptanceId]),+ ).resolves.toMatchObject({ bytes: 900, fileCount: 4, rounds: 3 });++ await expect(+ previewAcceptancePurge(serverDB, userId, undefined, [acceptanceId, otherAcceptanceId]),+ ).resolves.toEqual({+ bytes: 1250,+ fileCount: 6,+ files: { images: 2, other: 3, videos: 1 },+ rounds: 4,+ });+ });++ it('purges files, runs and the acceptance, deleting only unreferenced objects from S3', async () => {+ await expect(+ purgeAcceptance(serverDB, fileService, userId, undefined, acceptanceId),+ ).resolves.toEqual({ deletedFiles: 3, deletedRuns: 2 });++ expect(fileService.deleteFiles).toHaveBeenCalledTimes(1);+ expect(fileService.deleteFiles).toHaveBeenCalledWith(['solo.mp4']);++ await expect(+ serverDB.query.files.findMany({ where: inArray(files.id, fileIds) }),+ ).resolves.toHaveLength(0);+ await expect(+ serverDB.query.files.findFirst({ where: eq(files.id, keeperFileId) }),+ ).resolves.toBeDefined();+ await expect(+ serverDB.query.verifyRuns.findMany({ where: inArray(verifyRuns.id, runIds) }),+ ).resolves.toHaveLength(0);+ await expect(+ serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, acceptanceId) }),+ ).resolves.toBeUndefined();+ });++ it('keeps files still referenced by another run or not owned by the report', async () => {+ const libraryFileId = await seedFile({ fileHash: null, source: null, url: 'library.pdf' });+ const otherAcceptanceId = await seedAcceptance();+ const otherRunId = await seedRound(otherAcceptanceId, 1, [fileIds[2]]);+ await serverDB.insert(verifyEvidence).values({+ checkResultId: (await serverDB.query.verifyCheckResults.findFirst({+ where: eq(verifyCheckResults.verifyRunId, runIds[0]),+ }))!.id,+ fileId: libraryFileId,+ type: 'screenshot',+ userId,+ });++ await expect(+ purgeAcceptance(serverDB, fileService, userId, undefined, acceptanceId),+ ).resolves.toEqual({ deletedFiles: 2, deletedRuns: 2 });++ expect(fileService.deleteFiles).not.toHaveBeenCalled();+ await expect(+ serverDB.query.files.findMany({ where: inArray(files.id, [fileIds[2], libraryFileId]) }),+ ).resolves.toHaveLength(2);+ const otherEvidence = await serverDB+ .select({ fileId: verifyEvidence.fileId })+ .from(verifyEvidence)+ .innerJoin(verifyCheckResults, eq(verifyCheckResults.id, verifyEvidence.checkResultId))+ .where(eq(verifyCheckResults.verifyRunId, otherRunId));+ expect(otherEvidence.map((row) => row.fileId)).toEqual([fileIds[2]]);+ });++ it('deletes rows but leaves storage alone when REMOVE_GLOBAL_FILE is off', async () => {+ envMock.serverDBEnv.REMOVE_GLOBAL_FILE = false;++ await expect(+ purgeAcceptance(serverDB, fileService, userId, undefined, acceptanceId),+ ).resolves.toEqual({ deletedFiles: 3, deletedRuns: 2 });++ expect(fileService.deleteFiles).not.toHaveBeenCalled();+ await expect(+ serverDB.query.files.findMany({ where: inArray(files.id, fileIds) }),+ ).resolves.toHaveLength(0);+ await expect(+ serverDB.query.globalFiles.findFirst({ where: eq(globalFiles.hashId, SOLO_HASH) }),+ ).resolves.toBeDefined();+ });++ it('removes hashless evidence objects from storage by url', async () => {+ const hashless = await seedFile({ fileHash: null, url: 'raw.log' });+ await seedRound(acceptanceId, 3, [hashless]);++ await expect(+ purgeAcceptance(serverDB, fileService, userId, undefined, acceptanceId),+ ).resolves.toEqual({ deletedFiles: 4, deletedRuns: 3 });++ expect(fileService.deleteFiles).toHaveBeenCalledTimes(1);+ expect(vi.mocked(fileService.deleteFiles).mock.calls[0][0].sort()).toEqual([+ 'raw.log',+ 'solo.mp4',+ ]);+ });++ it('still purges rows and rounds when the storage delete fails', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(fileService.deleteFiles).mockRejectedValueOnce(new Error('s3 down'));++ await expect(+ purgeAcceptance(serverDB, fileService, userId, undefined, acceptanceId),+ ).resolves.toEqual({ deletedFiles: 3, deletedRuns: 2 });++ await expect(+ serverDB.query.verifyRuns.findMany({ where: inArray(verifyRuns.id, runIds) }),+ ).resolves.toHaveLength(0);+ await expect(+ serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, acceptanceId) }),+ ).resolves.toBeUndefined();+ });++ it('removes storage objects before the rounds go away', async () => {+ let runsAtStorageDelete: unknown[] = [];+ vi.mocked(fileService.deleteFiles).mockImplementation(async () => {+ runsAtStorageDelete = await serverDB.query.verifyRuns.findMany({+ where: inArray(verifyRuns.id, runIds),+ });+ });++ await purgeAcceptance(serverDB, fileService, userId, undefined, acceptanceId);++ expect(runsAtStorageDelete).toHaveLength(2);+ });++ it('purges a single round and leaves the acceptance in place', async () => {+ await expect(+ purgeVerifyRun(serverDB, fileService, userId, undefined, runIds[1]),+ ).resolves.toEqual({ deletedFiles: 1 });++ expect(fileService.deleteFiles).toHaveBeenCalledWith(['solo.mp4']);+ await expect(+ serverDB.query.verifyRuns.findMany({ where: inArray(verifyRuns.id, runIds) }),+ ).resolves.toHaveLength(1);+ await expect(+ serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, acceptanceId) }),+ ).resolves.toBeDefined();+ });++ it("does not touch another user's acceptance", async () => {+ const strangerId = await createTestUser(serverDB);+ await expect(+ purgeAcceptance(serverDB, fileService, strangerId, undefined, acceptanceId),+ ).resolves.toEqual({ deletedFiles: 0, deletedRuns: 0 });+ expect(fileService.deleteFiles).not.toHaveBeenCalled();+ await expect(+ serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, acceptanceId) }),+ ).resolves.toBeDefined();+ await cleanupTestUser(serverDB, strangerId);+ });+});diff --git a/apps/server/src/services/verify/acceptancePurge.ts b/apps/server/src/services/verify/acceptancePurge.tsnew file mode 100644index 00000000000..b5b2a719187--- /dev/null+++ b/apps/server/src/services/verify/acceptancePurge.ts@@ -0,0 +1,213 @@+import { FileSource } from '@lobechat/types';+import { and, eq, inArray, isNotNull, notExists, notInArray } from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';++import { serverDBEnv } from '@/config/db';+import { AcceptanceModel } from '@/database/models/acceptance';+import { FileModel } from '@/database/models/file';+import { VerifyRunModel } from '@/database/models/verifyRun';+import { files } from '@/database/schemas/file';+import { verifyCheckResults, verifyEvidence, verifyRuns } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';+import { buildWorkspaceWhere } from '@/database/utils/workspace';+import type { FileService } from '@/server/services/file';++export interface PurgePreview {+ bytes: number;+ fileCount: number;+ files: { images: number; other: number; videos: number };+ rounds: number;+}++const listRunIds = async (+ db: LobeChatDatabase,+ userId: string,+ workspaceId: string | undefined,+ acceptanceIds: string[],+) => {+ if (acceptanceIds.length === 0) return [];+ const rows = await db+ .select({ id: verifyRuns.id })+ .from(verifyRuns)+ .where(+ and(+ inArray(verifyRuns.acceptanceId, acceptanceIds),+ buildWorkspaceWhere({ userId, workspaceId }, verifyRuns),+ ),+ );+ return rows.map((row) => row.id);+};++const listExclusiveEvidenceFileIds = async (db: LobeChatDatabase, runIds: string[]) => {+ if (runIds.length === 0) return [];+ const otherEvidence = alias(verifyEvidence, 'other_evidence');+ const otherResults = alias(verifyCheckResults, 'other_results');+ const rows = await db+ .selectDistinct({ fileId: verifyEvidence.fileId })+ .from(verifyEvidence)+ .innerJoin(verifyCheckResults, eq(verifyCheckResults.id, verifyEvidence.checkResultId))+ .innerJoin(files, eq(files.id, verifyEvidence.fileId))+ .where(+ and(+ inArray(verifyCheckResults.verifyRunId, runIds),+ isNotNull(verifyEvidence.fileId),+ eq(files.source, FileSource.Acceptance),+ notExists(+ db+ .select({ id: otherEvidence.id })+ .from(otherEvidence)+ .innerJoin(otherResults, eq(otherResults.id, otherEvidence.checkResultId))+ .where(+ and(+ eq(otherEvidence.fileId, verifyEvidence.fileId),+ notInArray(otherResults.verifyRunId, runIds),+ ),+ ),+ ),+ ),+ );+ return rows.map((row) => row.fileId!);+};++const listRetainedHashes = async (+ db: LobeChatDatabase,+ rows: { fileHash: string | null; id: string }[],+) => {+ const hashes = rows.map((row) => row.fileHash).filter((hash): hash is string => Boolean(hash));+ if (hashes.length === 0) return new Set<string | null>();+ const outside = await db+ .select({ fileHash: files.fileHash })+ .from(files)+ .where(+ and(+ inArray(files.fileHash, hashes),+ notInArray(+ files.id,+ rows.map((row) => row.id),+ ),+ ),+ );+ return new Set(outside.map((row) => row.fileHash));+};++const purgeFiles = async (+ db: LobeChatDatabase,+ fileService: FileService,+ userId: string,+ workspaceId: string | undefined,+ fileIds: string[],+) => {+ if (fileIds.length === 0) return 0;+ const owned = await db+ .select({ fileHash: files.fileHash, id: files.id, url: files.url })+ .from(files)+ .where(and(inArray(files.id, fileIds), buildWorkspaceWhere({ userId, workspaceId }, files)));+ if (owned.length === 0) return 0;++ const removeGlobalFile = serverDBEnv.REMOVE_GLOBAL_FILE;+ const unreferenced = await new FileModel(db, userId, workspaceId).deleteMany(+ owned.map((file) => file.id),+ removeGlobalFile,+ );+ if (!removeGlobalFile) return owned.length;++ const urls = new Set([+ ...unreferenced.map((file) => file.url),+ ...owned.filter((file) => !file.fileHash).map((file) => file.url),+ ]);+ if (urls.size > 0) {+ try {+ await fileService.deleteFiles([...urls]);+ } catch (error) {+ console.error('[acceptance:purge] storage delete failed', error);+ }+ }+ return owned.length;+};++export const previewAcceptancePurge = async (+ db: LobeChatDatabase,+ userId: string,+ workspaceId: string | undefined,+ acceptanceIds: string[],+): Promise<PurgePreview> => {+ const runIds = await listRunIds(db, userId, workspaceId, acceptanceIds);+ const fileIds = await listExclusiveEvidenceFileIds(db, runIds);+ const empty = { bytes: 0, fileCount: 0, files: { images: 0, other: 0, videos: 0 } };+ if (fileIds.length === 0) return { ...empty, rounds: runIds.length };++ const rows = await db+ .select({+ fileHash: files.fileHash,+ fileType: files.fileType,+ id: files.id,+ size: files.size,+ })+ .from(files)+ .where(and(inArray(files.id, fileIds), buildWorkspaceWhere({ userId, workspaceId }, files)));++ const retained = await listRetainedHashes(db, rows);+ const maxSizeByObject = new Map<string, number>();+ const counts = { ...empty.files };+ for (const row of rows) {+ if (row.fileType.startsWith('image/')) counts.images += 1;+ else if (row.fileType.startsWith('video/')) counts.videos += 1;+ else counts.other += 1;+ if (row.fileHash && retained.has(row.fileHash)) continue;+ const key = row.fileHash ?? row.id;+ maxSizeByObject.set(key, Math.max(maxSizeByObject.get(key) ?? 0, row.size));+ }++ return {+ bytes: [...maxSizeByObject.values()].reduce((sum, size) => sum + size, 0),+ fileCount: rows.length,+ files: counts,+ rounds: runIds.length,+ };+};++export const purgeAcceptance = async (+ db: LobeChatDatabase,+ fileService: FileService,+ userId: string,+ workspaceId: string | undefined,+ acceptanceId: string,+): Promise<{ deletedFiles: number; deletedRuns: number }> => {+ const runIds = await listRunIds(db, userId, workspaceId, [acceptanceId]);+ const fileIds = await listExclusiveEvidenceFileIds(db, runIds);+ const deletedFiles = await purgeFiles(db, fileService, userId, workspaceId, fileIds);++ await db.transaction(async (tx) => {+ if (runIds.length > 0) {+ await tx+ .delete(verifyRuns)+ .where(+ and(+ inArray(verifyRuns.id, runIds),+ buildWorkspaceWhere({ userId, workspaceId }, verifyRuns),+ ),+ );+ }+ await new AcceptanceModel(tx, userId, workspaceId).delete(acceptanceId);+ });++ return { deletedFiles, deletedRuns: runIds.length };+};++export const purgeVerifyRun = async (+ db: LobeChatDatabase,+ fileService: FileService,+ userId: string,+ workspaceId: string | undefined,+ verifyRunId: string,+): Promise<{ deletedFiles: number }> => {+ const runModel = new VerifyRunModel(db, userId, workspaceId);+ const run = await runModel.findById(verifyRunId);+ if (!run) return { deletedFiles: 0 };++ const fileIds = await listExclusiveEvidenceFileIds(db, [run.id]);+ const deletedFiles = await purgeFiles(db, fileService, userId, workspaceId, fileIds);+ await runModel.delete(run.id);++ return { deletedFiles };+};diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.tsindex 710030bd6a5..57acb3fc197 100644--- a/apps/server/src/services/verify/index.ts+++ b/apps/server/src/services/verify/index.ts@@ -4,6 +4,12 @@ export {mergeAcceptanceRounds,planCheckIdRemap,} from './acceptanceMerge';+export {+ previewAcceptancePurge,+ purgeAcceptance,+ type PurgePreview,+ purgeVerifyRun,+} from './acceptancePurge';export {type AcceptanceCheckHistoryEntry,type AcceptanceCheckReviewEvent,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex eb60b432421..375bf434318 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1639,6 +1639,7 @@"taskDetail.acceptance.retry": "Retry","taskDetail.acceptance.reviewError": "Could not save this review.","taskDetail.acceptance.title": "Acceptance",+ "taskDetail.acceptance.untitled": "this acceptance","taskDetail.acceptance.verifier": "Verification method","taskDetail.acceptanceState.accepted": "Accepted","taskDetail.acceptanceState.awaitingDecision": "Not passed — your call",diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex b3ef86ad9d9..f23844287e0 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -346,7 +346,7 @@"acceptance.workspace.batch.accept": "Accept","acceptance.workspace.batch.close": "Close","acceptance.workspace.batch.deleteConfirmDescription": "Delete the {{count}} selected acceptance(s)? Their verification rounds are kept — they detach into standalone reports.",- "acceptance.workspace.batch.deleteConfirmTitle": "Delete {{count}} acceptance(s)",+ "acceptance.workspace.batch.deleteConfirmTitle": "Delete {{count}} acceptance(s)?","acceptance.workspace.batch.deleteSuccess": "{{count}} acceptance(s) deleted","acceptance.workspace.batch.enter": "Select multiple","acceptance.workspace.batch.error": "The batch action failed. Try again.",@@ -359,8 +359,19 @@"acceptance.workspace.batch.selected": "{{count}} selected","acceptance.workspace.batch.statusSuccess": "{{count}} acceptance(s) updated","acceptance.workspace.checkCount": "{{count}} checks",+ "acceptance.workspace.deleteConfirm.files": "Evidence files",+ "acceptance.workspace.deleteConfirm.filesValue": "{{count}} (screenshots {{images}} · recordings {{videos}} · other {{other}})",+ "acceptance.workspace.deleteConfirm.ok": "Delete and free {{size}}",+ "acceptance.workspace.deleteConfirm.okBatch": "Delete {{count}} and free {{size}}",+ "acceptance.workspace.deleteConfirm.okBatchPlain": "Delete {{count}}",+ "acceptance.workspace.deleteConfirm.purgeOption": "Also permanently delete every round, report and evidence file ({{size}})",+ "acceptance.workspace.deleteConfirm.purgeOptionPlain": "Also permanently delete every round, report and evidence file",+ "acceptance.workspace.deleteConfirm.purgeWarning": "This permanently deletes every round, report and evidence file of this acceptance. It cannot be undone.",+ "acceptance.workspace.deleteConfirm.rounds": "Rounds",+ "acceptance.workspace.deleteConfirm.roundsValue": "{{count}} rounds",+ "acceptance.workspace.deleteConfirm.space": "Space freed","acceptance.workspace.deleteConfirmDescription": "Delete the acceptance “{{title}}”? Its verification rounds are kept — they detach into standalone reports.",- "acceptance.workspace.deleteConfirmTitle": "Delete acceptance",+ "acceptance.workspace.deleteConfirmTitle": "Delete “{{title}}”?","acceptance.workspace.deleteError": "Failed to delete acceptance","acceptance.workspace.deleteSuccess": "Acceptance deleted","acceptance.workspace.emptyDetail.description": "Open the Acceptance menu to pick a record and inspect its checks, rounds and evidence.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex eeba0a63c35..a04fc2c30c8 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1639,6 +1639,7 @@"taskDetail.acceptance.retry": "重试","taskDetail.acceptance.reviewError": "复核结果保存失败。","taskDetail.acceptance.title": "交付验收",+ "taskDetail.acceptance.untitled": "该验收","taskDetail.acceptance.verifier": "验证方式","taskDetail.acceptanceState.accepted": "已验收","taskDetail.acceptanceState.awaitingDecision": "未通过 · 待你定夺",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 2422da7b92a..1f6bba4c654 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -346,7 +346,7 @@"acceptance.workspace.batch.accept": "标记验收","acceptance.workspace.batch.close": "标记关闭","acceptance.workspace.batch.deleteConfirmDescription": "将删除选中的 {{count}} 项验收?其验证轮次会保留,脱离为独立报告。",- "acceptance.workspace.batch.deleteConfirmTitle": "删除 {{count}} 项验收",+ "acceptance.workspace.batch.deleteConfirmTitle": "删除 {{count}} 项验收?","acceptance.workspace.batch.deleteSuccess": "已删除 {{count}} 项验收","acceptance.workspace.batch.enter": "多选","acceptance.workspace.batch.error": "批量操作失败,请重试",@@ -359,8 +359,19 @@"acceptance.workspace.batch.selected": "已选 {{count}} 项","acceptance.workspace.batch.statusSuccess": "已更新 {{count}} 项验收","acceptance.workspace.checkCount": "{{count}} 项验收项",+ "acceptance.workspace.deleteConfirm.files": "证据文件",+ "acceptance.workspace.deleteConfirm.filesValue": "{{count}} 个(截图 {{images}} · 录屏 {{videos}} · 其他 {{other}})",+ "acceptance.workspace.deleteConfirm.ok": "删除并释放 {{size}}",+ "acceptance.workspace.deleteConfirm.okBatch": "删除 {{count}} 项并释放 {{size}}",+ "acceptance.workspace.deleteConfirm.okBatchPlain": "删除 {{count}} 项",+ "acceptance.workspace.deleteConfirm.purgeOption": "同时永久删除全部轮次、报告和证据文件,释放 {{size}}",+ "acceptance.workspace.deleteConfirm.purgeOptionPlain": "同时永久删除全部轮次、报告和证据文件",+ "acceptance.workspace.deleteConfirm.purgeWarning": "这会永久删除该验收的全部轮次、报告和证据文件,无法恢复。",+ "acceptance.workspace.deleteConfirm.rounds": "验收轮次",+ "acceptance.workspace.deleteConfirm.roundsValue": "{{count}} 轮",+ "acceptance.workspace.deleteConfirm.space": "释放空间","acceptance.workspace.deleteConfirmDescription": "确定删除验收「{{title}}」吗?各轮验证记录会保留,并拆分为独立的报告。",- "acceptance.workspace.deleteConfirmTitle": "删除验收",+ "acceptance.workspace.deleteConfirmTitle": "删除「{{title}}」?","acceptance.workspace.deleteError": "删除验收失败","acceptance.workspace.deleteSuccess": "验收已删除","acceptance.workspace.emptyDetail.description": "打开交付列表,选择一条验收记录,查看它的检查项、轮次与证据。",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex b9fac8294bf..0a6d413a226 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1553,6 +1553,7 @@ export default {'taskDetail.acceptance.multimodalLlm': 'Multimodal LLM','taskDetail.acceptance.openReport': 'Acceptance report','taskDetail.acceptance.remove': 'Remove acceptance',+ 'taskDetail.acceptance.untitled': 'this acceptance','taskDetail.acceptance.removeConfirm.content':"This removes the task's acceptance goal, checklist, and recorded acceptance results. Task artifacts are unaffected.",'taskDetail.acceptance.removeConfirm.ok': 'Remove',diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 0672d1748a0..8142dc1c405 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -476,7 +476,7 @@ export default {'acceptance.workspace.batch.close': 'Close','acceptance.workspace.batch.deleteConfirmDescription':'Delete the {{count}} selected acceptance(s)? Their verification rounds are kept — they detach into standalone reports.',- 'acceptance.workspace.batch.deleteConfirmTitle': 'Delete {{count}} acceptance(s)',+ 'acceptance.workspace.batch.deleteConfirmTitle': 'Delete {{count}} acceptance(s)?','acceptance.workspace.batch.deleteSuccess': '{{count}} acceptance(s) deleted','acceptance.workspace.batch.enter': 'Select multiple','acceptance.workspace.batch.error': 'The batch action failed. Try again.',@@ -490,9 +490,24 @@ export default {'acceptance.workspace.batch.selected': '{{count}} selected','acceptance.workspace.batch.statusSuccess': '{{count}} acceptance(s) updated','acceptance.workspace.checkCount': '{{count}} checks',+ 'acceptance.workspace.deleteConfirm.files': 'Evidence files',+ 'acceptance.workspace.deleteConfirm.filesValue':+ '{{count}} (screenshots {{images}} · recordings {{videos}} · other {{other}})',+ 'acceptance.workspace.deleteConfirm.ok': 'Delete and free {{size}}',+ 'acceptance.workspace.deleteConfirm.okBatch': 'Delete {{count}} and free {{size}}',+ 'acceptance.workspace.deleteConfirm.okBatchPlain': 'Delete {{count}}',+ 'acceptance.workspace.deleteConfirm.purgeOption':+ 'Also permanently delete every round, report and evidence file ({{size}})',+ 'acceptance.workspace.deleteConfirm.purgeOptionPlain':+ 'Also permanently delete every round, report and evidence file',+ 'acceptance.workspace.deleteConfirm.purgeWarning':+ 'This permanently deletes every round, report and evidence file of this acceptance. It cannot be undone.',+ 'acceptance.workspace.deleteConfirm.rounds': 'Rounds',+ 'acceptance.workspace.deleteConfirm.roundsValue': '{{count}} rounds',+ 'acceptance.workspace.deleteConfirm.space': 'Space freed','acceptance.workspace.deleteConfirmDescription':'Delete the acceptance “{{title}}”? Its verification rounds are kept — they detach into standalone reports.',- 'acceptance.workspace.deleteConfirmTitle': 'Delete acceptance',+ 'acceptance.workspace.deleteConfirmTitle': 'Delete “{{title}}”?','acceptance.workspace.deleteError': 'Failed to delete acceptance','acceptance.workspace.deleteSuccess': 'Acceptance deleted','acceptance.workspace.emptyDetail.description':diff --git a/src/features/Acceptance/Workspace/AcceptanceDeleteConfirm.tsx b/src/features/Acceptance/Workspace/AcceptanceDeleteConfirm.tsxnew file mode 100644index 00000000000..817359e5cff--- /dev/null+++ b/src/features/Acceptance/Workspace/AcceptanceDeleteConfirm.tsx@@ -0,0 +1,165 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import {+ Button,+ Checkbox,+ createModal,+ type ModalInstance,+ Text,+ toast,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { t } from 'i18next';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useClientDataSWR } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';+import { formatSize } from '@/utils/format';++import { frostedModalStyles } from '../Viewer/Review/modals';++const PREVIEW_BATCH_LIMIT = 20;++const styles = createStaticStyles(({ css }) => ({+ facts: css`+ display: grid;+ grid-template-columns: auto 1fr;+ gap: 4px 14px;++ margin: 0;+ padding-block: 10px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadiusLG};++ font-size: 13px;+ font-variant-numeric: tabular-nums;++ background: ${cssVar.colorFillQuaternary};++ dt {+ margin: 0;+ color: ${cssVar.colorTextTertiary};+ }++ dd {+ margin: 0;+ color: ${cssVar.colorText};+ }+ `,+}));++interface DeleteConfirmProps {+ description?: string;+ ids: string[];+ onDelete: (purge: boolean) => Promise<unknown>;+ title?: string;+}++const usePurgePreview = (ids: string[]) =>+ useClientDataSWR(+ ids.length > PREVIEW_BATCH_LIMIT ? null : verifyKeys.acceptancePurgePreview(ids.join(',')),+ () => verifyService.getAcceptancePurgePreview(ids),+ );++const DeleteConfirmContent = memo<DeleteConfirmProps>(({ description, ids, onDelete, title }) => {+ const { t: translate } = useTranslation('verify');+ const { close } = useModalContext();+ const [pending, setPending] = useState(false);+ const [purge, setPurge] = useState(false);+ const { data: preview } = usePurgePreview(ids);+ const batch = ids.length > 1;+ const size = preview ? formatSize(preview.bytes) : undefined;++ const run = async () => {+ setPending(true);+ try {+ await onDelete(purge);+ close();+ } catch (error) {+ console.error('[acceptance:deleteConfirm]', error);+ toast.error(translate('acceptance.workspace.deleteError'));+ } finally {+ setPending(false);+ }+ };++ const okLabel =+ !purge || !size+ ? batch+ ? translate('acceptance.workspace.deleteConfirm.okBatchPlain', { count: ids.length })+ : translate('actions.delete')+ : batch+ ? translate('acceptance.workspace.deleteConfirm.okBatch', { count: ids.length, size })+ : translate('acceptance.workspace.deleteConfirm.ok', { size });++ return (+ <Flexbox gap={12}>+ <Text fontSize={13} type={purge ? 'danger' : 'secondary'}>+ {purge+ ? translate('acceptance.workspace.deleteConfirm.purgeWarning')+ : batch+ ? translate('acceptance.workspace.batch.deleteConfirmDescription', {+ count: ids.length,+ })+ : translate('acceptance.workspace.deleteConfirmDescription', { title })}+ </Text>+ {description && (+ <Text fontSize={13} type={'secondary'}>+ {description}+ </Text>+ )}+ <Checkbox checked={purge} onChange={setPurge}>+ {size+ ? translate('acceptance.workspace.deleteConfirm.purgeOption', { size })+ : translate('acceptance.workspace.deleteConfirm.purgeOptionPlain')}+ </Checkbox>+ {purge && preview && (+ <dl className={styles.facts}>+ <dt>{translate('acceptance.workspace.deleteConfirm.rounds')}</dt>+ <dd>+ {translate('acceptance.workspace.deleteConfirm.roundsValue', { count: preview.rounds })}+ </dd>+ <dt>{translate('acceptance.workspace.deleteConfirm.files')}</dt>+ <dd>+ {translate('acceptance.workspace.deleteConfirm.filesValue', {+ count: preview.fileCount,+ ...preview.files,+ })}+ </dd>+ <dt>{translate('acceptance.workspace.deleteConfirm.space')}</dt>+ <dd>{formatSize(preview.bytes)}</dd>+ </dl>+ )}+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={pending} onClick={close}>+ {translate('actions.cancel')}+ </Button>+ <Button danger loading={pending} type={'primary'} onClick={() => void run()}>+ {okLabel}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++DeleteConfirmContent.displayName = 'AcceptanceDeleteConfirmContent';++export const openAcceptanceDeleteConfirm = (options: DeleteConfirmProps): ModalInstance =>+ createModal({+ content: <DeleteConfirmContent {...options} />,+ footer: null,+ maskClosable: true,+ styles: frostedModalStyles,+ title:+ options.ids.length > 1+ ? t('acceptance.workspace.batch.deleteConfirmTitle', {+ count: options.ids.length,+ ns: 'verify',+ })+ : t('acceptance.workspace.deleteConfirmTitle', { ns: 'verify', title: options.title }),+ width: 'min(90vw, 440px)',+ });diff --git a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsxindex 8f6abe0c1fb..e21275f8e27 100644--- a/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx+++ b/src/features/Acceptance/Workspace/AcceptanceListPanel.tsx@@ -6,7 +6,6 @@ import {ActionIcon,Button,Checkbox,- confirmModal,DraggablePanel,DraggablePanelContainer,DropdownMenu,@@ -47,6 +46,7 @@ import { useAcceptanceList, useAcceptanceListInfinite } from '../hooks';import { acceptanceHomePath } from '../Viewer/routes';import type { AcceptanceStatusAction } from '../Viewer/statusActions';import AcceptanceBatchBar from './AcceptanceBatchBar';+import { openAcceptanceDeleteConfirm } from './AcceptanceDeleteConfirm';import {acceptanceListEmptyVariant,type AcceptanceListFilter,@@ -535,15 +535,9 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(const targets = selectedVisible;if (targets.length === 0) return;- confirmModal({- cancelText: t('actions.cancel'),- content: t('acceptance.workspace.batch.deleteConfirmDescription', {- count: targets.length,- }),- okButtonProps: { danger: true },- okText: t('actions.delete'),- title: t('acceptance.workspace.batch.deleteConfirmTitle', { count: targets.length }),- onOk: async () => {+ openAcceptanceDeleteConfirm({+ ids: targets,+ onDelete: async (purge) => {setBatchPending(true);try {// `allSettled`, never `all`: a rejected chunk must not hide the ones@@ -552,9 +546,12 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(// chunk had just removed.const chunks = chunkAcceptanceBatch(targets);const settled = await Promise.allSettled(- chunks.map((chunk) => verifyService.deleteAcceptanceBatch(chunk)),+ chunks.map((chunk) => verifyService.deleteAcceptanceBatch(chunk, purge)),);+ if (settled.every((part): part is PromiseRejectedResult => part.status === 'rejected'))+ throw settled[0].reason;+let deleted = 0;const failedIds: string[] = [];settled.forEach((part, index) => {@@ -573,9 +570,6 @@ const AcceptanceListPanel = memo<AcceptanceListPanelProps>(navigate(acceptanceHomePath(), { replace: true });await settleBatch(targets, [], failedIds);reportBatch(deleted, targets.length, 'acceptance.workspace.batch.deleteSuccess');- } catch (cause) {- console.error('[acceptance:batchDelete]', cause);- toast.error(t('acceptance.workspace.batch.error'));} finally {setBatchPending(false);}diff --git a/src/features/Acceptance/Workspace/AcceptanceRow.tsx b/src/features/Acceptance/Workspace/AcceptanceRow.tsxindex e1a8a91045d..e14f9852a83 100644--- a/src/features/Acceptance/Workspace/AcceptanceRow.tsx+++ b/src/features/Acceptance/Workspace/AcceptanceRow.tsx@@ -3,7 +3,7 @@import type { AcceptanceStatus } from '@lobechat/types';import { Center, Flexbox, Icon } from '@lobehub/ui';import type { DropdownItem } from '@lobehub/ui/base-ui';-import { ActionIcon, Checkbox, confirmModal, DropdownMenu, toast } from '@lobehub/ui/base-ui';+import { ActionIcon, Checkbox, DropdownMenu, toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import dayjs from 'dayjs';import {@@ -33,6 +33,7 @@ import type { AcceptanceListItem } from '@/services/verify';import { verifyService } from '@/services/verify';import { getAcceptanceStatusActions } from '../Viewer/statusActions';+import { openAcceptanceDeleteConfirm } from './AcceptanceDeleteConfirm';import { openMergeAcceptanceModal } from './MergeAcceptanceModal';import { useAcceptanceProjectMenuItem } from './useAcceptanceProjectMenuItem';@@ -225,26 +226,20 @@ const AcceptanceRow = memo<{};const removeAcceptance = () => {- confirmModal({- cancelText: t('actions.cancel'),- content: t('acceptance.workspace.deleteConfirmDescription', { title }),- okButtonProps: { danger: true },- okText: t('actions.delete'),- onOk: async () => {+ openAcceptanceDeleteConfirm({+ ids: [item.id],+ title,+ onDelete: async (purge) => {setMutating(true);try {- await verifyService.deleteAcceptance(item.id);+ await verifyService.deleteAcceptance(item.id, purge);if (active) navigate('/acceptance', { replace: true });await onChanged();toast.success(t('acceptance.workspace.deleteSuccess'));- } catch (error) {- console.error('[acceptance:delete]', error);- toast.error(t('acceptance.workspace.deleteError'));} finally {setMutating(false);}},- title: t('acceptance.workspace.deleteConfirmTitle'),});};diff --git a/src/features/Acceptance/hooks.ts b/src/features/Acceptance/hooks.tsindex aeb771177f6..b1d5154602a 100644--- a/src/features/Acceptance/hooks.ts+++ b/src/features/Acceptance/hooks.ts@@ -121,6 +121,14 @@ export const useAcceptanceList = (},);+/** Rounds, evidence files and bytes a delete would purge. Pass null to skip. */+export const useAcceptancePurgePreview = (acceptanceId: string | null) =>+ useClientDataSWR(+ acceptanceId ? verifyKeys.acceptancePurgePreview(acceptanceId) : null,+ () => verifyService.getAcceptancePurgePreview([acceptanceId!]),+ VERIFY_REPORT_SWR_CONFIG,+ );+/*** The panel's scroll feed: keyset pages, newest first, with the in-progress /* completed split applied server-side (see `acceptance.listPage`).diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsxindex 7728d552c7e..db4b88298bc 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx@@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({isOwner: boolean;},currentPortalView: null as null | string,- confirmModal: vi.fn(),+ openDeleteConfirm: vi.fn(),deleteAcceptance: vi.fn(),mutateBundle: vi.fn(),mutateSubject: vi.fn(),@@ -49,7 +49,10 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({{title}</button>),- confirmModal: (opts: unknown) => mocks.confirmModal(opts),+}));++vi.mock('@/features/Acceptance/Workspace/AcceptanceDeleteConfirm', () => ({+ openAcceptanceDeleteConfirm: (opts: unknown) => mocks.openDeleteConfirm(opts),}));vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({@@ -130,7 +133,7 @@ vi.mock('@/features/Acceptance/Viewer/Review/AcceptanceDecision', () => ({vi.mock('@/services/verify', () => ({verifyService: {- deleteAcceptance: (id: string) => mocks.deleteAcceptance(id),+ deleteAcceptance: (id: string, purge?: boolean) => mocks.deleteAcceptance(id, purge),reviewChecks: vi.fn(),},}));@@ -355,13 +358,21 @@ describe('TaskAcceptance', () => {render(<TaskAcceptance />);fireEvent.click(screen.getByText('taskDetail.acceptance.remove'));- expect(mocks.confirmModal).toHaveBeenCalledTimes(1);+ expect(mocks.openDeleteConfirm).toHaveBeenCalledTimes(1);+ expect(mocks.openDeleteConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ description: 'taskDetail.acceptance.removeConfirm.content',+ ids: ['acceptance-1'],+ }),+ );expect(mocks.deleteAcceptance).not.toHaveBeenCalled();- const opts = mocks.confirmModal.mock.calls[0][0] as { onOk: () => Promise<void> };- await opts.onOk();+ const opts = mocks.openDeleteConfirm.mock.calls[0][0] as {+ onDelete: (purge: boolean) => Promise<void>;+ };+ await opts.onDelete(true);- expect(mocks.deleteAcceptance).toHaveBeenCalledWith('acceptance-1');+ expect(mocks.deleteAcceptance).toHaveBeenCalledWith('acceptance-1', true);expect(mocks.updateVerifyConfig).toHaveBeenCalledWith('T-231', {enabled: false,requirement: null,@@ -387,8 +398,10 @@ describe('TaskAcceptance', () => {render(<TaskAcceptance />);fireEvent.click(screen.getByText('taskDetail.acceptance.remove'));- const opts = mocks.confirmModal.mock.calls[0][0] as { onOk: () => Promise<void> };- await expect(opts.onOk()).rejects.toThrow('config write failed');+ const opts = mocks.openDeleteConfirm.mock.calls[0][0] as {+ onDelete: (purge: boolean) => Promise<void>;+ };+ await expect(opts.onDelete(false)).rejects.toThrow('config write failed');expect(mocks.deleteAcceptance).not.toHaveBeenCalled();expect(mocks.mutateSubject).not.toHaveBeenCalled();diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsxindex cf02c0b8a68..fe3be22a4aa 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx@@ -1,7 +1,7 @@'use client';import { Flexbox, Icon } from '@lobehub/ui';-import { ActionIcon, Button, confirmModal, Text } from '@lobehub/ui/base-ui';+import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import {ChevronRight,@@ -32,6 +32,7 @@ import {} from '@/features/Acceptance/Viewer/AcceptanceScope';import AcceptanceCheckInventory from '@/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory';import AcceptanceDecision from '@/features/Acceptance/Viewer/Review/AcceptanceDecision';+import { openAcceptanceDeleteConfirm } from '@/features/Acceptance/Workspace/AcceptanceDeleteConfirm';import { usePermission } from '@/hooks/usePermission';import { verifyService } from '@/services/verify';import { useChatStore } from '@/store/chat';@@ -128,6 +129,7 @@ const TaskAcceptance = memo<TaskAcceptanceProps>(({ variant = 'default' }) => {const { allowed: canEditTask } = usePermission('create_content');const taskId = useTaskStore(taskDetailSelectors.activeTaskId);const taskDatabaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);+ const taskName = useTaskStore(taskDetailSelectors.activeTaskName);const automationMode = useTaskStore(taskDetailSelectors.activeTaskAutomationMode);const verify = useTaskStore(taskDetailSelectors.activeTaskVerifyConfig);const [sectionExpanded, setSectionExpanded] = useState(true);@@ -197,20 +199,19 @@ const TaskAcceptance = memo<TaskAcceptanceProps>(({ variant = 'default' }) => {// to recreate it on the next run.const handleRemoveAcceptance = () => {if (!acceptanceSubject || !taskId) return;- confirmModal({- content: t('taskDetail.acceptance.removeConfirm.content'),- okButtonProps: { danger: true },- okText: t('taskDetail.acceptance.removeConfirm.ok'),- onOk: async () => {+ openAcceptanceDeleteConfirm({+ description: t('taskDetail.acceptance.removeConfirm.content'),+ ids: [acceptanceSubject.id],+ title: taskName || requirement || t('taskDetail.acceptance.untitled'),+ onDelete: async (purge) => {await useTaskStore.getState().updateVerifyConfig(taskId, {enabled: false,requirement: null,verifyCriteriaIds: null,});- await verifyService.deleteAcceptance(acceptanceSubject.id);+ await verifyService.deleteAcceptance(acceptanceSubject.id, purge);await mutateSubject();},- title: t('taskDetail.acceptance.removeConfirm.title'),});};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 88ec1397dce..a6fde08cf58 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -1094,6 +1094,10 @@ export const verifyKeys = {* One scroll page of the list panel. Keyed by workspace + the status split +* the cursor, mirroring `reportSummaries` — the sibling paged feed.*/+ acceptancePurgePreview: def('verify:acceptancePurgePreview', (acceptanceId: string) => [+ 'verify:acceptancePurgePreview',+ acceptanceId,+ ]),acceptancePage: def('verify:acceptancePage',(workspaceId: string | undefined, filter: string, projectId?: string, cursor?: string) => [diff --git a/src/services/verify.ts b/src/services/verify.tsindex 202ce642356..8919cd58f14 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -38,6 +38,10 @@ export type AcceptanceListItem = Awaited<export type AcceptanceListPage = Awaited<ReturnType<typeof lambdaClient.acceptance.listPage.query>>;+export type AcceptancePurgePreview = Awaited<+ ReturnType<typeof lambdaClient.acceptance.purgePreview.query>+>;+/** The list's status split, shared by the flat and paged reads. */export type AcceptanceListFilter = 'active' | 'all' | 'completed';@@ -343,11 +347,16 @@ export class VerifyService {mergeAcceptance = (sourceId: string, targetId: string) =>lambdaClient.acceptance.merge.mutate({ sourceId, targetId });- /** Delete the acceptance aggregate (its round reports detach, not delete). */- deleteAcceptance = (id: string) => lambdaClient.acceptance.remove.mutate({ id });+ getAcceptancePurgePreview = (ids: string[]) =>+ lambdaClient.acceptance.purgePreview.query({ ids });++ /** Delete the acceptance aggregate; its round reports detach unless `purge` removes them too. */+ deleteAcceptance = (id: string, purge?: boolean) =>+ lambdaClient.acceptance.remove.mutate({ id, purge });/** Batch twin of `deleteAcceptance` for the list's multi-selection. */- deleteAcceptanceBatch = (ids: string[]) => lambdaClient.acceptance.removeBatch.mutate({ ids });+ deleteAcceptanceBatch = (ids: string[], purge?: boolean) =>+ lambdaClient.acceptance.removeBatch.mutate({ ids, purge });// ---- per-run plan ----getVerifyState = (operationId: string): Promise<VerifyStateResponse | null> =>