🤯 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
🐛 fix(artboard): take a trashed task's shares offline and count board files toward storage (#23558)
Inneif2027f536547
diff --git a/apps/server/src/services/artboard/__tests__/storageUsage.integration.test.ts b/apps/server/src/services/artboard/__tests__/storageUsage.integration.test.tsnew file mode 100644index 00000000000..6c51db63559--- /dev/null+++ b/apps/server/src/services/artboard/__tests__/storageUsage.integration.test.ts@@ -0,0 +1,116 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import { FileSource } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { FileModel } from '@/database/models/file';+import { TaskModel } from '@/database/models/task';+import { files, projects, tasks, users } from '@/database/schemas';++import { ArtboardService } from '../index';+import { memoryStore } from './files.integration.test';++const userId = 'artboard-storage-usage-user';+const projectId = 'prj_artboard_storage_usage';++const db: LobeChatDatabase = await getTestDB();++let memory: ReturnType<typeof memoryStore>;++const service = () =>+ new ArtboardService(db, userId, undefined, {+ context: { agentId: null },+ fileStore: memory.store,+ sources: { imageBytes: async () => undefined, importPage: async () => undefined },+ });++const artboardRows = () =>+ db+ .select({ metadata: files.metadata, name: files.name, size: files.size, url: files.url })+ .from(files)+ .where(and(eq(files.userId, userId), eq(files.source, FileSource.Artboard)));++const createBoard = async () => {+ const task = await new TaskModel(db, userId).create({ instruction: 'Onboarding', projectId });+ const { artboard } = await service().create(+ {+ files: {+ writes: [+ { content: '<html>home</html>', path: 'pages/home.html' },+ { content: 'body{}', path: 'pages/base.css' },+ ],+ },+ taskId: task.identifier,+ title: 'Onboarding',+ },+ {},+ );+ return artboard;+};++beforeEach(async () => {+ memory = memoryStore();+ await db.delete(users).where(eq(users.id, userId));+ await db.insert(users).values({ id: userId });+ await db.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+});++afterEach(async () => {+ await db.delete(tasks).where(eq(tasks.createdByUserId, userId));+ await db.delete(users).where(eq(users.id, userId));+});++describe('artboard files in storage usage', () => {+ it("counts every stored file toward the owner's storage usage", async () => {+ const artboard = await createBoard();++ expect((await artboardRows()).sort((a, b) => a.name.localeCompare(b.name))).toEqual([+ {+ metadata: { artboardId: artboard.id, path: 'pages/base.css' },+ name: 'base.css',+ size: 6,+ url: `artboards/${artboard.id}/files/pages/base.css`,+ },+ {+ metadata: { artboardId: artboard.id, path: 'pages/home.html' },+ name: 'home.html',+ size: 17,+ url: `artboards/${artboard.id}/files/pages/home.html`,+ },+ ]);+ expect(await new FileModel(db, userId).countUsage()).toBe(23);+ });++ it('counts a file uploaded through a signed URL at its stored size', async () => {+ const artboard = await createBoard();+ await memory.store.write(+ `artboards/${artboard.id}/files/shots/home.png`,+ new Uint8Array(4096),+ 'image/png',+ );++ await service().writeFiles(artboard.id, {+ writes: [{ path: 'shots/home.png', uploaded: true }],+ });++ expect(await artboardRows()).toContainEqual(+ expect.objectContaining({ name: 'home.png', size: 4096 }),+ );+ });++ it('follows an overwrite and a delete', async () => {+ const artboard = await createBoard();++ await service().writeFiles(artboard.id, {+ deletes: ['pages/base.css'],+ writes: [{ content: '<html>welcome home</html>', path: 'pages/home.html' }],+ });++ expect(await artboardRows()).toEqual([+ expect.objectContaining({ name: 'home.html', size: 25 }),+ ]);+ expect(await new FileModel(db, userId).countUsage()).toBe(25);+ });+});diff --git a/apps/server/src/services/artboard/files.ts b/apps/server/src/services/artboard/files.tsindex defe3d121b3..42036192de6 100644--- a/apps/server/src/services/artboard/files.ts+++ b/apps/server/src/services/artboard/files.ts@@ -7,6 +7,7 @@ import {} from '@lobechat/types';import pMap from 'p-map';+import type { ArtboardFileModel, ArtboardStoredFile } from '@/database/models/artboardFile';import type { FileService } from '@/server/services/file';import { ArtboardServiceError } from './errors';@@ -121,11 +122,23 @@ interface ArtboardFileServiceDeps {*/resolveImport: (source: ArtboardImportSource) => Promise<ArtboardImportedPage | undefined>;store: ArtboardBlobStore;+ usage?: ArtboardFileUsage;}+export interface ArtboardFileUsage {+ record: (artboardId: string, stored: ArtboardStoredFile[], deleted: string[]) => Promise<void>;+ removeAll: (artboardId: string) => Promise<void>;+}++export const artboardFileUsage = (model: ArtboardFileModel): ArtboardFileUsage => ({+ record: (artboardId, stored, deleted) => model.record(artboardId, stored, deleted),+ removeAll: (artboardId) => model.deleteByArtboards([artboardId]),+});+/** What a set of changes will write and delete, checked against the limits but not yet stored. */export interface ArtboardFilePlan {deletes: string[];+ sizes: Map<string, number>;/** Paths already uploaded through a signed URL. */uploaded: string[];writes: Map<string, Uint8Array>;@@ -138,9 +151,15 @@ const invalid = (message: string): never => {throw new ArtboardServiceError('invalid', message);};-const artboardPrefix = (artboardId: string) => `artboards/${artboardId}/`;+const artboardStoragePrefix = (artboardId: string) => `artboards/${artboardId}/`;-export const artboardFilesPrefix = (artboardId: string) => `${artboardPrefix(artboardId)}files/`;+export const removeArtboardFiles = async (store: ArtboardBlobStore, artboardId: string) => {+ const objects = await store.list(artboardStoragePrefix(artboardId));+ if (objects.length) await store.delete(objects.map((object) => object.key));+};++export const artboardFilesPrefix = (artboardId: string) =>+ `${artboardStoragePrefix(artboardId)}files/`;export const artboardFileKey = (artboardId: string, path: string) =>`${artboardFilesPrefix(artboardId)}${path}`;@@ -303,7 +322,7 @@ export class ArtboardFileService {`The artboard's files would total ${total} bytes; the limit is ${ARTBOARD_FILE_LIMITS.maxTotalBytes}.`,);- return { deletes, uploaded, writes };+ return { deletes, sizes, uploaded, writes };}/** Every path a plan changes or deletes. */@@ -326,7 +345,18 @@ export class ArtboardFileService {);if (plan.deletes.length)await this.deps.store.delete(plan.deletes.map((path) => artboardFileKey(artboardId, path)));- return [...plan.writes.keys(), ...plan.uploaded];+ const stored = [...plan.writes.keys(), ...plan.uploaded];+ await this.deps.usage?.record(+ artboardId,+ stored.map((path) => ({+ contentType: artboardFileContentType(path)!,+ key: artboardFileKey(artboardId, path),+ path,+ size: plan.sizes.get(path) ?? 0,+ })),+ plan.deletes,+ );+ return stored;}async applyChanges(artboardId: string, changes: ArtboardFileChanges) {@@ -355,7 +385,7 @@ export class ArtboardFileService {}async removeAll(artboardId: string) {- const objects = await this.deps.store.list(artboardPrefix(artboardId));- if (objects.length) await this.deps.store.delete(objects.map((object) => object.key));+ await removeArtboardFiles(this.deps.store, artboardId);+ await this.deps.usage?.removeAll(artboardId);}}diff --git a/apps/server/src/services/artboard/index.ts b/apps/server/src/services/artboard/index.tsindex ccba6a0dfc2..14c314a5ff7 100644--- a/apps/server/src/services/artboard/index.ts+++ b/apps/server/src/services/artboard/index.ts@@ -10,6 +10,7 @@ import { AcceptanceFlowModel } from '@/database/models/acceptanceFlow';import { ArtboardModel, type ArtboardRow } from '@/database/models/artboard';import { ArtboardCommentModel } from '@/database/models/artboard/comment';import { ArtboardStructureModel } from '@/database/models/artboard/structure';+import { ArtboardFileModel } from '@/database/models/artboardFile';import { TaskModel } from '@/database/models/task';import { TopicModel } from '@/database/models/topic';import { WorkModel } from '@/database/models/work';@@ -30,6 +31,7 @@ import {type ArtboardFilePlan,ArtboardFileService,type ArtboardFileUploadRequest,+ artboardFileUsage,createFileServiceArtboardBlobStore,} from './files';import { buildJourneyFlow } from './finalize';@@ -132,6 +134,7 @@ export class ArtboardService {store:options.fileStore ??createFileServiceArtboardBlobStore(() => new FileService(db, userId, workspaceId)),+ usage: artboardFileUsage(new ArtboardFileModel(db, userId, workspaceId)),});}diff --git a/apps/server/src/services/artboard/taskCleanup.ts b/apps/server/src/services/artboard/taskCleanup.tsnew file mode 100644index 00000000000..1e7daf59624--- /dev/null+++ b/apps/server/src/services/artboard/taskCleanup.ts@@ -0,0 +1,89 @@+import { ArtboardModel } from '@/database/models/artboard';+import { ArtboardFileModel } from '@/database/models/artboardFile';+import { WorkModel } from '@/database/models/work';+import type { ArtboardWork } from '@/database/models/work/artboard';+import { FileService } from '@/server/services/file';++import {+ type ArtboardBlobStore,+ createFileServiceArtboardBlobStore,+ removeArtboardFiles,+} from './files';+import { type ArtboardShareOwner, unpublishArtboardWork } from './publish/offline';++export interface TaskArtboards {+ artboardIds: string[];+ works: ArtboardWork[];+}++const unpublishShared = async (owner: ArtboardShareOwner, works: ArtboardWork[]) => {+ const offline: string[] = [];+ for (const work of works) {+ if (!work.metadata?.artboardPublish || !work.resourceId) continue;+ try {+ await unpublishArtboardWork(owner, work);+ offline.push(work.resourceId);+ } catch (error) {+ console.error('[artboard:task-cleanup] share teardown failed', work.resourceId, error);+ }+ }+ return offline;+};++export const collectTaskArtboards = async (+ owner: ArtboardShareOwner,+ taskIds: string[],+): Promise<TaskArtboards> => {+ const rows = await new ArtboardModel(+ owner.db,+ owner.userId,+ owner.workspaceId,+ ).listByTrashedTaskIds(taskIds);+ const artboardIds = rows.map((row) => row.id);+ const works = await new WorkModel(+ owner.db,+ owner.userId,+ owner.workspaceId,+ ).findArtboardWorksForTrash(artboardIds);+ return { artboardIds, works };+};++export const takeTaskArtboardsOffline = async (owner: ArtboardShareOwner, taskIds: string[]) => {+ const { works } = await collectTaskArtboards(owner, taskIds);+ const offline = await unpublishShared(owner, works);+ await new WorkModel(owner.db, owner.userId, owner.workspaceId).clearArtboardPublishForTrash(+ offline,+ );+};++export const deleteTaskArtboardRecords = async (+ owner: ArtboardShareOwner,+ { artboardIds }: TaskArtboards,+) => {+ await new WorkModel(owner.db, owner.userId, owner.workspaceId).deleteArtboardWorksForTrash(+ artboardIds,+ );+ await new ArtboardFileModel(owner.db, owner.userId, owner.workspaceId).deleteByArtboards(+ artboardIds,+ );+ await new ArtboardModel(owner.db, owner.userId, owner.workspaceId).deleteForTrashPurge(+ artboardIds,+ );+};++export const releaseTaskArtboards = async (+ owner: ArtboardShareOwner,+ { artboardIds, works }: TaskArtboards,+ store: ArtboardBlobStore = createFileServiceArtboardBlobStore(+ () => new FileService(owner.db, owner.userId, owner.workspaceId),+ ),+) => {+ await unpublishShared(owner, works);+ for (const artboardId of artboardIds) {+ try {+ await removeArtboardFiles(store, artboardId);+ } catch (error) {+ console.error('[artboard:task-cleanup] file removal failed', artboardId, error);+ }+ }+};diff --git a/apps/server/src/services/task/batch.integration.test.ts b/apps/server/src/services/task/batch.integration.test.tsindex d121624515f..46f8ba8cee5 100644--- a/apps/server/src/services/task/batch.integration.test.ts+++ b/apps/server/src/services/task/batch.integration.test.ts@@ -9,16 +9,29 @@ import {import { and, eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ArtboardModel } from '@/database/models/artboard';import { GoalModel } from '@/database/models/goal';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';-import { agents, taskActivities, tasks, users, workspaces } from '@/database/schemas';+import { WorkModel } from '@/database/models/work';+import {+ agents,+ artboards,+ projects,+ taskActivities,+ tasks,+ users,+ workspaces,+} from '@/database/schemas';import { TaskRunnerService } from '@/server/services/taskRunner';import { TaskBatchService } from './batch';vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));+const { unpublishCanvasSite } = vi.hoisted(() => ({ unpublishCanvasSite: vi.fn() }));+vi.mock('@/business/server/canvasPublish', () => ({ unpublishCanvasSite }));+const userId = 'task-batch-integration-user';const otherUserId = 'task-batch-integration-other';@@ -376,6 +389,94 @@ describe('TaskBatchService (real PostgreSQL)', () => {expect(await teammate.findById(hidden.id)).not.toBeNull();});+ it("takes a deleted task's shared artboard offline and keeps the board for a restore", async () => {+ unpublishCanvasSite.mockReset();+ const projectId = 'prj_task_batch_artboard';+ await db.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ const [task] = await createTasks(1, { projectId });+ const artboard = await new ArtboardModel(db, userId).create({+ projectId,+ taskId: task.id,+ title: 'Onboarding board',+ });+ const workModel = new WorkModel(db, userId);+ await workModel.registerArtboard({+ artboardId: artboard.id,+ changeType: 'created',+ projectId,+ title: artboard.title,+ toolIdentifier: 'lobe-artboard',+ toolName: 'createArtboard',+ });+ await workModel.recordArtboardPublish(artboard.id, {+ deploymentId: 'dep_task_batch',+ publishedRevision: 1,+ publisherUserId: userId,+ snapshotHash: 'hash',+ url: 'https://onboarding.lobe.page',+ });++ await service.delete([task.id]);++ expect(unpublishCanvasSite).toHaveBeenCalledWith(+ expect.objectContaining({ deploymentId: 'dep_task_batch', userId }),+ );+ const work = await workModel.findArtboardWork(artboard.id);+ expect(work?.url).toBeNull();+ expect(work?.metadata?.artboardPublish).toBeUndefined();+ expect(await db.select().from(artboards).where(eq(artboards.id, artboard.id))).toHaveLength(+ 1,+ );+ });++ it("takes a teammate's share down with a workspace task someone else deletes", async () => {+ unpublishCanvasSite.mockReset();+ const workspaceId = 'task-batch-artboard-ws';+ await db.insert(workspaces).values({+ id: workspaceId,+ name: 'Workspace',+ primaryOwnerId: otherUserId,+ slug: workspaceId,+ });+ const projectId = 'prj_task_batch_ws_artboard';+ await db+ .insert(projects)+ .values({ id: projectId, name: 'Shared', userId: otherUserId, workspaceId });+ const task = await new TaskModel(db, otherUserId, workspaceId).create({+ instruction: 'Shared task',+ projectId,+ visibility: 'public',+ });+ const artboard = await new ArtboardModel(db, otherUserId, workspaceId).create({+ projectId,+ taskId: task.id,+ title: 'Shared board',+ });+ const teammateWorks = new WorkModel(db, otherUserId, workspaceId);+ await teammateWorks.registerArtboard({+ artboardId: artboard.id,+ changeType: 'created',+ projectId,+ title: artboard.title,+ toolIdentifier: 'lobe-artboard',+ toolName: 'createArtboard',+ });+ await teammateWorks.recordArtboardPublish(artboard.id, {+ deploymentId: 'dep_task_batch_ws',+ publishedRevision: 1,+ publisherUserId: otherUserId,+ snapshotHash: 'hash',+ url: 'https://shared.lobe.page',+ });++ await new TaskBatchService(db, userId, workspaceId).delete([task.id]);++ expect(unpublishCanvasSite).toHaveBeenCalledWith(+ expect.objectContaining({ deploymentId: 'dep_task_batch_ws', userId: otherUserId }),+ );+ expect((await teammateWorks.findArtboardWork(artboard.id))?.url).toBeNull();+ });+it('deletes idle tasks in one pass and reports missing ones', async () => {const [a, b] = await createTasks(2);const keep = (await createTasks(1))[0];diff --git a/apps/server/src/services/task/batch.ts b/apps/server/src/services/task/batch.tsindex 831076c5874..e1b33c2a48e 100644--- a/apps/server/src/services/task/batch.ts+++ b/apps/server/src/services/task/batch.ts@@ -8,6 +8,7 @@ import { withStaleReposCleared } from '@/database/models/task/utils';import { TaskArchiveModel } from '@/database/models/taskArchive';import { TaskTopicModel } from '@/database/models/taskTopic';import type { LobeChatDatabase } from '@/database/type';+import { takeTaskArtboardsOffline } from '@/server/services/artboard/taskCleanup';import { EditLockService } from '@/server/services/editLock';import { AiAgentService } from '../aiAgent';@@ -647,6 +648,16 @@ export class TaskBatchService {return deleted;});result.updated.push(...deletedIdle);+ if (deletedIdle.length > 0) {+ try {+ await takeTaskArtboardsOffline(+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },+ deletedIdle,+ );+ } catch (error) {+ console.error('[task:batchDelete] Artboard share teardown failed', error);+ }+ }if (removedTopicIds.length > 0) {try {await removeByTopics(this.db, { userId: this.userId, workspaceId: this.workspaceId }, [diff --git a/apps/server/src/services/task/index.deleteTask.test.ts b/apps/server/src/services/task/index.deleteTask.test.tsindex acefc2de622..a5ff5dae0be 100644--- a/apps/server/src/services/task/index.deleteTask.test.ts+++ b/apps/server/src/services/task/index.deleteTask.test.ts@@ -21,6 +21,11 @@ const { cancelScheduled, scheduleNextTopic, trashTasksInTransaction } = vi.hoistvi.mock('../trash', () => ({ trashTasksInTransaction }));vi.mock('../inboundWebhook/lifecycle', () => ({ removeByTopics: vi.fn() }));+const { takeTaskArtboardsOffline } = vi.hoisted(() => ({+ takeTaskArtboardsOffline: vi.fn(),+}));+vi.mock('@/server/services/artboard/taskCleanup', () => ({ takeTaskArtboardsOffline }));+vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(),}));@@ -210,6 +215,36 @@ describe('TaskService.deleteTask', () => {mockTaskTopicModel.findByTaskId.mockResolvedValue([]);});+ it("takes the trashed task's artboard shares offline after the delete commits", async () => {+ mockTaskModel.findById.mockResolvedValue({+ id: 'task-idle',+ identifier: 'T-3',+ status: 'todo',+ });++ await new TaskService(db, userId).deleteTask('T-3');++ expect(takeTaskArtboardsOffline).toHaveBeenCalledWith(+ { db, userId, workspaceId: undefined },+ ['task-idle'],+ );+ expect(trashTasksInTransaction.mock.invocationCallOrder[0]).toBeLessThan(+ takeTaskArtboardsOffline.mock.invocationCallOrder[0],+ );+ });++ it('leaves artboard shares alone when the delete loses to a run that moved the task on', async () => {+ mockTaskModel.findById.mockResolvedValue({+ id: 'task-idle',+ identifier: 'T-3',+ status: 'todo',+ });+ trashTasksInTransaction.mockResolvedValueOnce([]);++ await expect(new TaskService(db, userId).deleteTask('T-3')).rejects.toThrow();+ expect(takeTaskArtboardsOffline).not.toHaveBeenCalled();+ });+it('interrupts a running execution before trashing the task', async () => {mockTaskModel.findById.mockResolvedValue({id: 'task-live',diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex b361de085b4..ca3e1d4302c 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -11,6 +11,7 @@ import { TaskTopicModel } from '@/database/models/taskTopic';import { TopicModel } from '@/database/models/topic';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import type { LobeChatDatabase } from '@/database/type';+import { takeTaskArtboardsOffline } from '@/server/services/artboard/taskCleanup';import { AiAgentService } from '../aiAgent';import { removeByTopics } from '../inboundWebhook/lifecycle';@@ -443,6 +444,16 @@ export class TaskService {'The task changed while it was being deleted (it may have just started). Try again.',});}+ if (outcome === 'deleted') {+ try {+ await takeTaskArtboardsOffline(+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },+ [task.id],+ );+ } catch (error) {+ console.error('[task:delete] Artboard share teardown failed', error);+ }+ }// Remote teardown follows commit: conflicts and rollbacks preserve the live endpoints.if (outcome === 'deleted' && removedTopicIds.length > 0) {try {diff --git a/apps/server/src/services/trash/__tests__/taskArtboard.test.ts b/apps/server/src/services/trash/__tests__/taskArtboard.test.tsnew file mode 100644index 00000000000..4a59e333164--- /dev/null+++ b/apps/server/src/services/trash/__tests__/taskArtboard.test.ts@@ -0,0 +1,128 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { FileSource } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ArtboardModel } from '@/database/models/artboard';+import { TaskModel } from '@/database/models/task';+import { WorkModel } from '@/database/models/work';+import { artboards, files, projects, tasks, users, works } from '@/database/schemas';++import { TrashService, trashTasksInTransaction } from '../index';++const { blobs, unpublishCanvasSite } = vi.hoisted(() => ({+ blobs: new Map<string, number>(),+ unpublishCanvasSite: vi.fn(),+}));++vi.mock('@/business/server/canvasPublish', () => ({ unpublishCanvasSite }));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return {+ deleteFiles: async (keys: string[]) => {+ for (const key of keys) blobs.delete(key);+ },+ listFileObjects: async (prefix: string) =>+ [...blobs]+ .filter(([key]) => key.startsWith(prefix))+ .map(([key, size]) => ({ etag: key, key, size })),+ };+ }),+}));++const db = await getTestDB();+const userId = 'trash-task-artboard-user';+const projectId = 'prj_trash_task_artboard';++const shareArtboard = async () => {+ const task = await new TaskModel(db, userId).create({ instruction: 'Onboarding', projectId });+ const artboard = await new ArtboardModel(db, userId).create({+ projectId,+ taskId: task.id,+ title: 'Onboarding board',+ });+ const workModel = new WorkModel(db, userId);+ await workModel.registerArtboard({+ artboardId: artboard.id,+ changeType: 'created',+ projectId,+ title: artboard.title,+ toolIdentifier: 'lobe-artboard',+ toolName: 'createArtboard',+ });+ await workModel.recordArtboardPublish(artboard.id, {+ deploymentId: 'dep_trash_task',+ publishedRevision: 1,+ publisherUserId: userId,+ snapshotHash: 'hash',+ url: 'https://onboarding.lobe.page',+ });+ blobs.set(`artboards/${artboard.id}/files/pages/home.html`, 120);+ await db.insert(files).values({+ fileType: 'text/html; charset=utf-8',+ metadata: { artboardId: artboard.id, path: 'pages/home.html' },+ name: 'home.html',+ size: 120,+ source: FileSource.Artboard,+ url: `artboards/${artboard.id}/files/pages/home.html`,+ userId,+ });+ blobs.set(`artboards/${artboard.id}/files/shots/home.png`, 4096);+ return { artboard, task };+};++const trashTask = (task: { id: string; status: string }) =>+ db.transaction((tx) =>+ trashTasksInTransaction(tx as unknown as typeof db, { userId }, [+ { status: task.status, taskId: task.id, topicIds: [] },+ ]),+ );++beforeEach(async () => {+ await db.delete(users).where(eq(users.id, userId));+ await db.insert(users).values({ id: userId });+ await db.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ blobs.clear();+ blobs.set('artboards/art_someone_else/files/pages/home.html', 64);+ unpublishCanvasSite.mockReset();+});++afterEach(async () => {+ await db.delete(tasks).where(eq(tasks.createdByUserId, userId));+ await db.delete(users).where(eq(users.id, userId));+});++describe('Task trash handler and artboards', () => {+ it('purging a trashed task deletes its artboard, the Work, the stored files and the share', async () => {+ const { artboard, task } = await shareArtboard();+ await trashTask(task);+ const service = new TrashService(db, userId);+ const { items } = await service.list({ resourceType: 'task' });++ await service.purge(items.map((item) => item.id));++ expect(await db.select().from(artboards).where(eq(artboards.id, artboard.id))).toEqual([]);+ expect(await db.select().from(works).where(eq(works.resourceId, artboard.id))).toEqual([]);+ expect([...blobs.keys()]).toEqual(['artboards/art_someone_else/files/pages/home.html']);+ expect(await db.select().from(files).where(eq(files.userId, userId))).toEqual([]);+ expect(unpublishCanvasSite).toHaveBeenCalledWith(+ expect.objectContaining({ deploymentId: 'dep_trash_task', userId }),+ );+ });++ it('restoring a trashed task keeps its artboard and files', async () => {+ const { artboard, task } = await shareArtboard();+ await trashTask(task);+ const service = new TrashService(db, userId);+ const { items } = await service.list({ resourceType: 'task' });++ await service.restore(items.map((item) => item.id));++ expect(await new ArtboardModel(db, userId).findById(artboard.id)).toMatchObject({+ id: artboard.id,+ });+ expect(blobs.has(`artboards/${artboard.id}/files/pages/home.html`)).toBe(true);+ });+});diff --git a/apps/server/src/services/trash/handlers/task.ts b/apps/server/src/services/trash/handlers/task.tsindex d805d9e122a..51a40bfbab1 100644--- a/apps/server/src/services/trash/handlers/task.ts+++ b/apps/server/src/services/trash/handlers/task.ts@@ -4,6 +4,12 @@ import { TaskModel } from '@/database/models/task';import { TopicModel } from '@/database/models/topic';import type { TrashRegisterEntry } from '@/database/models/trash';import type { SoftDeleteOptions } from '@/database/utils/softDelete';+import { createFileServiceArtboardBlobStore } from '@/server/services/artboard/files';+import {+ collectTaskArtboards,+ deleteTaskArtboardRecords,+ releaseTaskArtboards,+} from '@/server/services/artboard/taskCleanup';import { hasWaitingWorktreeCleanup, topicEntry, WORKTREE_CLEANUP_WAITING_MESSAGE } from './topic';import {@@ -90,12 +96,20 @@ export const taskHandler: TrashHandler = {if (hasWaitingWorktreeCleanup(childTopics))throw new TrashPurgeBlockedError(WORKTREE_CLEANUP_WAITING_MESSAGE);+ // Read before the purge: the task delete sets `artboards.task_id` to NULL.+ const artboards = await collectTaskArtboards(ctx, [root.resourceId]);+ let taskPurged = false;await ctx.db.transaction(async (tx) => {const db = tx as unknown as typeof ctx.db;// FK cascades take dependencies, comments, documents and `task_topics`;// subtasks get `parent_task_id = NULL`, as the hard delete always did.const purged = await new TaskModel(db, ctx.userId, ctx.workspaceId).purge([root.resourceId]);if (purged.length === 0) return;+ taskPurged = true;+ await deleteTaskArtboardRecords(+ { db, userId: ctx.userId, workspaceId: ctx.workspaceId },+ artboards,+ );const topicIds = children.filter((child) => child.resourceType === 'topic')@@ -104,6 +118,12 @@ export const taskHandler: TrashHandler = {await new TopicModel(db, ctx.userId, ctx.workspaceId).batchDeleteIncludingTrashed(topicIds);}});+ if (taskPurged)+ await releaseTaskArtboards(+ ctx,+ artboards,+ createFileServiceArtboardBlobStore(() => ctx.fileService),+ );},restore: async (ctx, root, children) => {const taskModel = new TaskModel(ctx.db, ctx.userId, ctx.workspaceId);diff --git a/packages/database/src/models/artboard/index.ts b/packages/database/src/models/artboard/index.tsindex a35df2b2f01..0d5485f4a05 100644--- a/packages/database/src/models/artboard/index.ts+++ b/packages/database/src/models/artboard/index.ts@@ -1,5 +1,5 @@import { ARTBOARD_DEFAULT_PAGE_NAME, type ArtboardPhase } from '@lobechat/types';-import { and, desc, eq, exists, isNull, or, sql } from 'drizzle-orm';+import { and, desc, eq, exists, inArray, isNull, or, sql } from 'drizzle-orm';import { artboardPages, artboards } from '../../schemas/artboard';import { tasks } from '../../schemas/task';@@ -139,6 +139,26 @@ export class ArtboardModel {await this.db.delete(artboards).where(and(eq(artboards.id, id), this.scope()));};+ // Recycle-bin internals only: the parent task is trashed, so `scope()` no longer sees these rows.+ private ownedRows = () =>+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: artboards.userId, workspaceId: artboards.workspaceId },+ );++ listByTrashedTaskIds = async (taskIds: string[]): Promise<ArtboardRow[]> => {+ if (taskIds.length === 0) return [];+ return this.db+ .select()+ .from(artboards)+ .where(and(inArray(artboards.taskId, taskIds), this.ownedRows()));+ };++ deleteForTrashPurge = async (ids: string[]): Promise<void> => {+ if (ids.length === 0) return;+ await this.db.delete(artboards).where(and(inArray(artboards.id, ids), this.ownedRows()));+ };+/** The structure revision and the row's updatedAt, which file-only writes also move. */getRevision = async (id: string): Promise<{ revision: number; updatedAt: Date } | undefined> => {const [row] = await this.dbdiff --git a/packages/database/src/models/artboardFile.ts b/packages/database/src/models/artboardFile.tsnew file mode 100644index 00000000000..2d1aa4284a2--- /dev/null+++ b/packages/database/src/models/artboardFile.ts@@ -0,0 +1,65 @@+import { FileSource } from '@lobechat/types';+import { and, eq, inArray, sql } from 'drizzle-orm';++import { files } from '../schemas';+import type { LobeChatDatabase, Transaction } from '../type';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';++export interface ArtboardStoredFile {+ contentType: string;+ key: string;+ path: string;+ size: number;+}++const artboardIdField = sql<string | null>`${files.metadata} ->> 'artboardId'`;+const pathField = sql<string | null>`${files.metadata} ->> 'path'`;++export class ArtboardFileModel {+ constructor(+ private db: LobeChatDatabase | Transaction,+ private userId: string,+ private workspaceId?: string,+ ) {}++ // Any member may write a workspace board, so a row is matched by board, not by writer.+ private boardRows = (artboardIds: string[]) =>+ and(+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: files.userId, workspaceId: files.workspaceId },+ ),+ eq(files.source, FileSource.Artboard),+ inArray(artboardIdField, artboardIds),+ );++ record = async (artboardId: string, stored: ArtboardStoredFile[], deleted: string[]) => {+ const paths = [...stored.map((file) => file.path), ...deleted];+ if (paths.length === 0) return;++ await this.db.transaction(async (tx) => {+ await tx.delete(files).where(and(this.boardRows([artboardId]), inArray(pathField, paths)));+ if (stored.length === 0) return;+ await tx.insert(files).values(+ stored.map((file) =>+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ fileType: file.contentType,+ metadata: { artboardId, path: file.path },+ name: file.path.slice(file.path.lastIndexOf('/') + 1),+ size: file.size,+ source: FileSource.Artboard,+ url: file.key,+ },+ ),+ ),+ );+ });+ };++ deleteByArtboards = async (artboardIds: string[]) => {+ if (artboardIds.length === 0) return;+ await this.db.delete(files).where(this.boardRows(artboardIds));+ };+}diff --git a/packages/database/src/models/work/artboard.ts b/packages/database/src/models/work/artboard.tsindex 669f9c78cad..cf8a1bc002a 100644--- a/packages/database/src/models/work/artboard.ts+++ b/packages/database/src/models/work/artboard.ts@@ -8,6 +8,7 @@ import { and, eq, inArray, sql } from 'drizzle-orm';import { projectWorks } from '../../schemas/projectWork';import { works } from '../../schemas/work';+import { buildWorkspaceWhere } from '../../utils/workspace';import { type WorkContext, workOwnership } from './context';import { createDisplayWorkAdapter } from './displayWork';import { registerWorkVersion } from './writes';@@ -19,6 +20,48 @@ const artboardResource = (ctx: WorkContext, artboardId: string) =>export type ArtboardWork = WorkItem & { metadata: WorkMetadata | null };+// Recycle-bin cleanup only: a teammate's private Work still has to come down with the task.+const artboardWorksInScope = (ctx: WorkContext, artboardIds: string[]) =>+ and(+ buildWorkspaceWhere(+ { userId: ctx.userId, workspaceId: ctx.workspaceId },+ { userId: works.userId, workspaceId: works.workspaceId },+ ),+ eq(works.resourceType, 'artboard'),+ inArray(works.resourceId, artboardIds),+ );++export const findArtboardWorksForTrash = async (+ ctx: WorkContext,+ artboardIds: string[],+): Promise<ArtboardWork[]> => {+ if (artboardIds.length === 0) return [];+ const rows = await ctx.db.select().from(works).where(artboardWorksInScope(ctx, artboardIds));+ return rows as ArtboardWork[];+};++export const clearArtboardPublishForTrash = async (+ ctx: WorkContext,+ artboardIds: string[],+): Promise<void> => {+ if (artboardIds.length === 0) return;+ await ctx.db+ .update(works)+ .set({+ metadata: sql`coalesce(${works.metadata}, '{}'::jsonb) - 'artboardPublish'`,+ url: null,+ })+ .where(artboardWorksInScope(ctx, artboardIds));+};++export const deleteArtboardWorksForTrash = async (+ ctx: WorkContext,+ artboardIds: string[],+): Promise<void> => {+ if (artboardIds.length === 0) return;+ await ctx.db.delete(works).where(artboardWorksInScope(ctx, artboardIds));+};+export const registerArtboardWork = async (ctx: WorkContext,params: RegisterArtboardWorkParams,diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex a110574f733..1e503265214 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -1,6 +1,6 @@import {- type ArtboardWorkPublishMetadata,type AgentWorkRunContext,+ type ArtboardWorkPublishMetadata,type CanvasWorkPublishMetadata,type CreateAgentWorkInput,type DeleteDocumentWorkParams,@@ -28,9 +28,12 @@ import { ScmChangeRequestModel } from '../scm';import { createAgentWork, deleteAgentWork, fillAgentWorkCost, updateAgentWork } from './agentWork';import {clearArtboardPublish,+ clearArtboardPublishForTrash,+ deleteArtboardWorksForTrash,findArtboardIdsByDeploymentIds,findArtboardWork,findArtboardWorkByWorkId,+ findArtboardWorksForTrash,recordArtboardPublish,registerArtboardWork,} from './artboard';@@ -156,6 +159,15 @@ export class WorkModel {findArtboardIdsByDeploymentIds = (deploymentIds: string[]) =>findArtboardIdsByDeploymentIds(this.ctx, deploymentIds);+ findArtboardWorksForTrash = (artboardIds: string[]) =>+ findArtboardWorksForTrash(this.ctx, artboardIds);++ clearArtboardPublishForTrash = (artboardIds: string[]) =>+ clearArtboardPublishForTrash(this.ctx, artboardIds);++ deleteArtboardWorksForTrash = (artboardIds: string[]) =>+ deleteArtboardWorksForTrash(this.ctx, artboardIds);+registerCanvas = (params: RegisterCanvasWorkParams): Promise<WorkItem> =>registerCanvasWork(this.ctx, params);diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex 764912c792c..4484c2bfd74 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -23,6 +23,8 @@ export enum FileSource {Acceptance = 'acceptance',/** Original upload owned by an agent's document tree rather than the resource library. */AgentDocument = 'agent-document',+ /** A file in an artboard's folder; counted toward storage, owned by the artboard. */+ Artboard = 'artboard',Canvas = 'canvas',/** Attachment sent in a public agent's conversation; shared with the conversation, not the library. */ChatAttachment = 'chat-attachment',@@ -60,6 +62,7 @@ export enum FileSource {export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [FileSource.Acceptance,FileSource.AgentDocument,+ FileSource.Artboard,FileSource.Canvas,FileSource.Meeting,FileSource.ToolResult,