Skip to content

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

🐛 fix(work): let users remove orphaned document works from the card (#19275)

YuTengjing812b39fa8eed
diff --git a/apps/server/src/routers/lambda/__tests__/work.test.ts b/apps/server/src/routers/lambda/__tests__/work.test.ts
index 172ba3b153e..94795f016ae 100644
--- a/apps/server/src/routers/lambda/__tests__/work.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/work.test.ts
@@ -19,6 +19,7 @@ vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
}));
const mockDeleteTaskWork = vi.fn();
+const mockDeleteWork = vi.fn();
const mockRegisterTask = vi.fn();
const mockRegisterDocument = vi.fn();
const mockHandleSkillToolResult = vi.fn();
@@ -27,6 +28,7 @@ const mockListByConversation = vi.fn();
vi.mock('@/database/models/work', () => ({
WorkModel: vi.fn(() => ({
deleteTaskWork: mockDeleteTaskWork,
+ deleteWork: mockDeleteWork,
handleSkillToolResult: mockHandleSkillToolResult,
listByConversation: mockListByConversation,
registerDocument: mockRegisterDocument,
@@ -83,6 +85,11 @@ describe('workRouter — per-procedure write permission gates', () => {
expect(mockHandleSkillToolResult).not.toHaveBeenCalled();
});
+ it('deleteWork gates on agent:update (workspace write, like other Work mutations)', async () => {
+ await expect(createCaller().deleteWork({ id: 'work-1' })).rejects.toThrow('GATE:agent:update');
+ expect(mockDeleteWork).not.toHaveBeenCalled();
+ });
+
it('read-only list procedures stay ungated', async () => {
mockListByConversation.mockResolvedValue([]);
await expect(createCaller().listByConversation({})).resolves.toEqual([]);
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
index b229305c764..3d0673d1f36 100644
--- a/apps/server/src/routers/lambda/work.ts
+++ b/apps/server/src/routers/lambda/work.ts
@@ -174,6 +174,15 @@ export const workRouter = router({
.input(z.object({ taskId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => ctx.workModel.deleteTaskWork(input)),
+ // User-initiated removal of an orphaned Work card. The Work is polymorphic,
+ // so this takes the general `agent:update` workspace-write gate (the same one
+ // Work, project and goal mutations use) rather than a per-resource gate; the
+ // model further restricts the delete to the caller's own rows whose backing
+ // task / document is already gone, so a live Work cannot be removed here.
+ deleteWork: skillWorkProcedureWrite
+ .input(z.object({ id: z.string().min(1) }))
+ .mutation(async ({ ctx, input }) => ctx.workModel.deleteWork(input)),
+
registerTask: taskWorkProcedureWrite
.input(registerTaskSchema)
.mutation(async ({ ctx, input }) => ctx.workModel.registerTask(input)),
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4f3c0c876a9..4fb31c12d0c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2612,10 +2612,15 @@
"workingPanel.title": "Working Panel",
"workingPanel.works.changeType.created": "Created",
"workingPanel.works.changeType.updated": "Updated",
+ "workingPanel.works.documentDeleted": "This document has been deleted",
"workingPanel.works.empty": "No works in this conversation yet",
"workingPanel.works.emptyVersions": "No versions yet",
"workingPanel.works.error": "Failed to load works",
- "workingPanel.works.taskDeleted": "Task deleted",
+ "workingPanel.works.remove": "Remove work",
+ "workingPanel.works.removeConfirm": "Remove this work card? Its version history, project pins and goal evidence links will be removed as well. This cannot be undone.",
+ "workingPanel.works.resourceDeleted": "This resource has been deleted",
+ "workingPanel.works.resourceDeletedRemoveConfirm": "It can no longer be opened. Remove this work card? Its version history, project pins and goal evidence links will be removed as well. This cannot be undone.",
+ "workingPanel.works.taskDeleted": "This task has been deleted",
"workingPanel.works.title": "Works",
"workingPanel.works.totalCost": "Total cost: {{cost}}",
"workingPanel.works.versionCost": "Version cost: {{cost}}",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index b57169138b8..091e5c6ec51 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2612,10 +2612,15 @@
"workingPanel.title": "工作面板",
"workingPanel.works.changeType.created": "已创建",
"workingPanel.works.changeType.updated": "已编辑",
+ "workingPanel.works.documentDeleted": "文档已被删除",
"workingPanel.works.empty": "当前会话暂无产物",
"workingPanel.works.emptyVersions": "暂无版本",
"workingPanel.works.error": "产物加载失败",
- "workingPanel.works.taskDeleted": "任务已删除",
+ "workingPanel.works.remove": "移除产物",
+ "workingPanel.works.removeConfirm": "确认移除该产物卡片吗?其版本历史、项目置顶和目标证据关联将一并移除,且无法恢复。",
+ "workingPanel.works.resourceDeleted": "资源已被删除",
+ "workingPanel.works.resourceDeletedRemoveConfirm": "已无法打开。要移除这张产物卡片吗?其版本记录、项目关联和目标证据链接会一并删除,且无法恢复。",
+ "workingPanel.works.taskDeleted": "任务已被删除",
"workingPanel.works.title": "产物",
"workingPanel.works.totalCost": "总成本:{{cost}}",
"workingPanel.works.versionCost": "本版本成本:{{cost}}",
diff --git a/packages/database/src/models/work/__tests__/document.test.ts b/packages/database/src/models/work/__tests__/document.test.ts
index d6d8771654f..5b6d838ae67 100644
--- a/packages/database/src/models/work/__tests__/document.test.ts
+++ b/packages/database/src/models/work/__tests__/document.test.ts
@@ -373,7 +373,80 @@ describe('WorkModel · workspace document visibility', () => {
// registrant keeps the orphan card.
await serverDB.delete(documents).where(eq(documents.id, doc.documentId));
- expect(await ownerWorks.listByConversation({ topicId })).toHaveLength(1);
+ const ownerView = await ownerWorks.listByConversation({ topicId });
+ expect(ownerView).toHaveLength(1);
+ // The orphan surfaces flagged `resourceDeleted` (documents LEFT JOIN miss)
+ // so the UI renders "document deleted" + a remove action instead of a live
+ // card that 404s on open.
+ expect(ownerView[0].resourceDeleted).toBe(true);
+ const { items } = await ownerWorks.listByWorkspace({});
+ expect(items).toHaveLength(1);
+ expect(items[0].resourceDeleted).toBe(true);
expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
});
+
+ it('reports resourceDeleted=false while the backing document is live', async () => {
+ await seedWorkspace();
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ await registerWorkspaceDocument('public');
+
+ const [conversation] = await ownerWorks.listByConversation({ topicId });
+ expect(conversation.resourceDeleted).toBe(false);
+ const { items } = await ownerWorks.listByWorkspace({});
+ expect(items[0].resourceDeleted).toBe(false);
+ });
+
+ describe('deleteWork', () => {
+ it('removes the caller-owned Work and cascades its versions', async () => {
+ await seedWorkspace();
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const { doc } = await registerWorkspaceDocument('public');
+ await serverDB.delete(documents).where(eq(documents.id, doc.documentId));
+
+ const [orphan] = await ownerWorks.listByConversation({ topicId });
+ await ownerWorks.deleteWork({ id: orphan.id });
+
+ expect(await serverDB.select().from(works).where(eq(works.id, orphan.id))).toHaveLength(0);
+ expect(
+ await serverDB.select().from(workVersions).where(eq(workVersions.workId, orphan.id)),
+ ).toHaveLength(0);
+ });
+
+ it('refuses to delete a Work whose backing document is still live', async () => {
+ await seedWorkspace();
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ await registerWorkspaceDocument('public');
+
+ const [live] = await ownerWorks.listByConversation({ topicId });
+ expect(live.resourceDeleted).toBe(false);
+ // The UI only offers removal on orphan cards; the model enforces the same
+ // invariant so a hand-crafted request cannot wipe a live Work's history.
+ await ownerWorks.deleteWork({ id: live.id });
+
+ expect(await serverDB.select().from(works).where(eq(works.id, live.id))).toHaveLength(1);
+ });
+
+ it('does not let another member delete a Work they did not register', async () => {
+ await seedWorkspace();
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ const memberWorks = new WorkModel(serverDB, userId2, workspaceId);
+ const { doc } = await registerWorkspaceDocument('public');
+ await serverDB.delete(documents).where(eq(documents.id, doc.documentId));
+
+ const [work] = await ownerWorks.listByConversation({ topicId });
+ // Even with the row id in hand, only the registrant may remove an orphan.
+ await memberWorks.deleteWork({ id: work.id });
+
+ expect(await serverDB.select().from(works).where(eq(works.id, work.id))).toHaveLength(1);
+ });
+
+ it('is a no-op for an unknown id', async () => {
+ await seedWorkspace();
+ const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
+ await registerWorkspaceDocument('public');
+
+ await expect(ownerWorks.deleteWork({ id: 'work_missing' })).resolves.toBeUndefined();
+ expect(await ownerWorks.listByConversation({ topicId })).toHaveLength(1);
+ });
+ });
});
diff --git a/packages/database/src/models/work/__tests__/task.test.ts b/packages/database/src/models/work/__tests__/task.test.ts
index d5f7c72bf2d..61645163a3a 100644
--- a/packages/database/src/models/work/__tests__/task.test.ts
+++ b/packages/database/src/models/work/__tests__/task.test.ts
@@ -100,7 +100,7 @@ describe('WorkModel · task', () => {
expect(worksInConversation[0]).toMatchObject({
id: work?.id,
task: { name: 'Work MVP plan', priority: 2, status: 'backlog' },
- taskDeleted: false,
+ resourceDeleted: false,
});
const byOperation = await workModel.listByRootOperation({ rootOperationId: 'op-root' });
@@ -752,14 +752,14 @@ describe('WorkModel · task', () => {
expect(workRows).toHaveLength(1);
expect(versionRows.length).toBeGreaterThan(0);
// The task-joined lists now surface the orphan via LEFT JOIN, rendered from
- // its version snapshot and flagged `taskDeleted` so the UI shows "task
+ // its version snapshot and flagged `resourceDeleted` so the UI shows "task
// deleted" instead of dropping the card entirely.
const orphaned = await workModel.listByConversation({ threadId, topicId });
expect(orphaned).toHaveLength(1);
expect(orphaned[0]).toMatchObject({
id: work!.id,
task: expect.objectContaining({ name: 'Keep my Work' }),
- taskDeleted: true,
+ resourceDeleted: true,
});
});
@@ -984,7 +984,7 @@ describe('WorkModel · workspace task visibility', () => {
const ownerView = await ownerWorks.listByConversation({ topicId });
expect(ownerView).toHaveLength(1);
- expect(expectTaskListItem(ownerView[0]).taskDeleted).toBe(true);
+ expect(expectTaskListItem(ownerView[0]).resourceDeleted).toBe(true);
expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);
});
diff --git a/packages/database/src/models/work/__tests__/workspace.test.ts b/packages/database/src/models/work/__tests__/workspace.test.ts
index 7bd6e036156..956f689442a 100644
--- a/packages/database/src/models/work/__tests__/workspace.test.ts
+++ b/packages/database/src/models/work/__tests__/workspace.test.ts
@@ -297,13 +297,13 @@ describe('WorkModel · listByWorkspace', () => {
});
// UI/CLI delete (no tool dispatch) leaves the Work orphaned; the LEFT JOIN
- // miss must render as `taskDeleted` from the version snapshot, not drop it.
+ // miss must render as `resourceDeleted` from the version snapshot, not drop it.
await taskModel.delete(task.id);
const { items } = await workModel.listByWorkspace({});
expect(items).toHaveLength(1);
const summary = expectTaskSummaryItem(items[0]);
expect(summary.task.name).toBe('Orphan task');
- expect(summary.taskDeleted).toBe(true);
+ expect(summary.resourceDeleted).toBe(true);
});
});
diff --git a/packages/database/src/models/work/displayWork.ts b/packages/database/src/models/work/displayWork.ts
index e3d3be42a05..46c26a8a366 100644
--- a/packages/database/src/models/work/displayWork.ts
+++ b/packages/database/src/models/work/displayWork.ts
@@ -1,18 +1,22 @@
import type {
RegisterExternalWorkParams,
- WorkListBaseItem,
+ WorkItem,
WorkListItem,
WorkSummaryItem,
WorkVersionEventItem,
} from '@lobechat/types';
import { and, desc, eq } from 'drizzle-orm';
+import { documents } from '../../schemas/file';
import { works, workVersions } from '../../schemas/work';
import { type WorkContext, workOwnership } from './context';
import {
currentWorkListFields,
type DisplayWorkType,
+ documentDeletedField,
+ documentSummaryJoin,
listDisplayVersionEventRows,
+ resourceNeverDeletedField,
type WorkDisplayColumns,
type WorkTypeAdapter,
} from './internal';
@@ -57,17 +61,26 @@ export const registerExternalWork = async (
* list/summary payloads.
*/
export const createDisplayWorkAdapter = (config: { type: DisplayWorkType }): WorkTypeAdapter => {
- const toListItem = (work: WorkListBaseItem): WorkListItem => work as WorkListItem;
+ const toListItem = (work: WorkItem, resourceDeleted: boolean): WorkListItem =>
+ ({ ...work, resourceDeleted }) as WorkListItem;
+ // `document` is the only display-backed type with a local backing row, so it
+ // is the only one that LEFT JOINs to derive `resourceDeleted`; the others
+ // answer with a constant `false`.
+ const isDocument = config.type === 'document';
return {
listConversationRows: async (ctx, params) => {
- const rows = await ctx.db
+ const query = ctx.db
.select({
eventCreatedAt: workVersions.createdAt,
+ resourceDeleted: isDocument ? documentDeletedField : resourceNeverDeletedField,
work: currentWorkListFields,
})
.from(workVersions)
.innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .$dynamic();
+
+ const rows = await (isDocument ? query.leftJoin(documents, documentSummaryJoin) : query)
.where(
and(
eq(workVersions.topicId, params.topicId),
@@ -80,7 +93,7 @@ export const createDisplayWorkAdapter = (config: { type: DisplayWorkType }): Wor
return rows.map((row) => ({
eventCreatedAt: row.eventCreatedAt,
- item: toListItem(row.work),
+ item: toListItem(row.work, row.resourceDeleted),
}));
},
@@ -90,7 +103,7 @@ export const createDisplayWorkAdapter = (config: { type: DisplayWorkType }): Wor
return rows.map(
(row) =>
({
- ...toListItem(row.work),
+ ...toListItem(row.work, row.resourceDeleted),
version: row.version,
}) as WorkVersionEventItem,
);
@@ -98,7 +111,7 @@ export const createDisplayWorkAdapter = (config: { type: DisplayWorkType }): Wor
mapCurrentRow: (row, totalCost) =>
({
- ...toListItem(row.work),
+ ...toListItem(row.work, row.resourceDeleted),
event: row.event,
totalCost,
version: row.version,
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index 95512ac1919..43c7cc2b9d3 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -1,6 +1,7 @@
import {
type DeleteDocumentWorkParams,
type DeleteTaskWorkParams,
+ type DeleteWorkParams,
isWorkSkillProvider,
type RegisterDocumentWorkParams,
type RegisterExternalWorkParams,
@@ -115,6 +116,8 @@ export class WorkModel {
deleteTaskWork = (params: DeleteTaskWorkParams): Promise<void> =>
writes.deleteTaskWork(this.ctx, params);
+ deleteWork = (params: DeleteWorkParams): Promise<void> => writes.deleteWork(this.ctx, params);
+
listByRootOperation = (params: {
includeFileWorks?: boolean;
limit?: number;
diff --git a/packages/database/src/models/work/internal.ts b/packages/database/src/models/work/internal.ts
index a25666b91d7..04c22964b72 100644
--- a/packages/database/src/models/work/internal.ts
+++ b/packages/database/src/models/work/internal.ts
@@ -3,6 +3,7 @@ import type {
TaskWorkListItem,
TaskWorkSummaryItem,
WorkDisplayField,
+ WorkItem,
WorkListBaseItem,
WorkListItem,
WorkSummaryItem,
@@ -14,6 +15,7 @@ import type { SQL } from 'drizzle-orm';
import { and, desc, eq, sql } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
+import { documents } from '../../schemas/file';
import { tasks } from '../../schemas/task';
import { works, workVersions } from '../../schemas/work';
import { taskOwnership, type WorkContext, workOwnership } from './context';
@@ -172,10 +174,12 @@ export const eventWorkListFields = {
export interface TaskWorkSummaryQueryRow {
event: WorkSummaryVersionPreview;
- /** Live-coalesced task columns; `deleted` flags a missing live row. */
- task: TaskWorkListItem['task'] & { deleted: TaskWorkListItem['taskDeleted'] };
+ /** See {@link WorkListBaseItem.resourceDeleted}; derived by the query, not a column. */
+ resourceDeleted: boolean;
+ /** Live-coalesced task columns, falling back to the snapshot on a LEFT JOIN miss. */
+ task: TaskWorkListItem['task'];
version: TaskWorkSummaryItem['version'];
- work: WorkListBaseItem;
+ work: WorkItem;
}
/**
@@ -184,19 +188,21 @@ export interface TaskWorkSummaryQueryRow {
*/
export type DisplayWorkType = 'document' | 'external' | 'file';
-/** Version-event row for display-backed types (each mutation event, no live join). */
+/** Version-event row for display-backed types (each mutation event). */
export interface DisplayVersionEventRow {
+ /** See {@link WorkListBaseItem.resourceDeleted}; constant `false` for external / file. */
+ resourceDeleted: boolean;
version: WorkVersionPreview;
- work: WorkListBaseItem;
+ work: WorkItem;
}
/**
* Current-card task projection. Live task columns take priority; a LEFT JOIN
- * miss falls back to the Work's current-version cache/snapshot.
+ * miss falls back to the Work's current-version cache/snapshot and is reported
+ * separately through {@link taskDeletedField}.
*/
export const currentTaskSummaryFields = {
task: {
- deleted: sql<boolean>`${tasks.id} is null`,
identifier: sql<string | null>`coalesce(${tasks.identifier}, ${works.identifier})`,
instruction: sql<string | null>`coalesce(${tasks.instruction}, ${works.description})`,
name: sql<string | null>`coalesce(${tasks.name}, ${works.title})`,
@@ -208,7 +214,6 @@ export const currentTaskSummaryFields = {
/** Historical task-event projection with fallback to that event's immutable snapshot. */
export const eventTaskSummaryFields = {
task: {
- deleted: sql<boolean>`${tasks.id} is null`,
identifier: sql<string | null>`coalesce(${tasks.identifier}, ${workVersions.identifier})`,
instruction: sql<string | null>`coalesce(${tasks.instruction}, ${workVersions.description})`,
name: sql<string | null>`coalesce(${tasks.name}, ${workVersions.title})`,
@@ -226,6 +231,39 @@ export const eventTaskSummaryFields = {
export const taskSummaryJoin = (ctx: WorkContext) =>
and(eq(works.resourceType, 'task'), eq(works.resourceId, tasks.id), taskOwnership(ctx));
+/**
+ * LEFT JOIN condition pairing a Work row to its live `documents` row (document
+ * type only). Existence-only, and deliberately WITHOUT the ownership predicate
+ * {@link taskSummaryJoin} carries: the single thing read through this join is
+ * `documents.id is null`, and which Work rows are visible at all is already
+ * decided by `workOwnership`'s `documentVisibilityGuard`. Filtering by owner
+ * here would instead make another member's live, public document look deleted.
+ */
+export const documentSummaryJoin = and(
+ eq(works.resourceType, 'document'),
+ eq(works.resourceId, documents.id),
+);
+
+/** `resourceDeleted` for a task-only query (the `tasks` LEFT JOIN missed). */
+export const taskDeletedField = sql<boolean>`${tasks.id} is null`;
+
+/** `resourceDeleted` for a document-only query (the `documents` LEFT JOIN missed). */
+export const documentDeletedField = sql<boolean>`${documents.id} is null`;
+
+/**
+ * `resourceDeleted` for the Work types with no local backing row (`external`,
+ * `file`): there is nothing to join, so the flag is a constant `false`.
+ */
+export const resourceNeverDeletedField = sql<boolean>`false`;
+
+/**
+ * `resourceDeleted` for the cross-type queries that LEFT JOIN BOTH backing
+ * tables (workspace gallery, root-operation summaries). Switching on
+ * `works.resourceType` keeps each type reading only its own join, and short-
+ * circuits `external` / `file` to `false` instead of misreading a NULL join.
+ */
+export const resourceDeletedField = sql<boolean>`case ${works.resourceType} when 'task' then ${tasks.id} is null when 'document' then ${documents.id} is null else false end`;
+
/**
* Shared version-event query for display-backed work types; `task` keeps its
* own variant because it additionally joins the tasks table.
@@ -235,17 +273,26 @@ export const listDisplayVersionEventRows = (
type: DisplayWorkType,
filters: SQL[],
limit: number,
-): Promise<DisplayVersionEventRow[]> =>
- ctx.db
+): Promise<DisplayVersionEventRow[]> => {
+ const query = ctx.db
.select({
+ resourceDeleted: type === 'document' ? documentDeletedField : resourceNeverDeletedField,
version: versionEventSelection,
work: eventWorkListFields,
})
.from(workVersions)
.innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .$dynamic();
+
+ // `document` is the only display-backed type with a local backing row, so it
+ // is the only one that pays for the join; the others answer with a constant.
+ const joined = type === 'document' ? query.leftJoin(documents, documentSummaryJoin) : query;
+
+ return joined
.where(and(...filters, eq(works.type, type)))
.orderBy(desc(workVersions.createdAt))
.limit(limit);
+};
/**
* One current-version row surfaced by the conversation-scoped list query,
@@ -269,9 +316,11 @@ export interface WorkConversationRowParams {
*/
export interface WorkspaceSummaryQueryRow {
event: WorkSummaryVersionPreview;
+ /** See {@link WorkListBaseItem.resourceDeleted}; derived by {@link resourceDeletedField}. */
+ resourceDeleted: boolean;
task: TaskWorkSummaryQueryRow['task'];
version: TaskWorkSummaryItem['version'];
- work: WorkListBaseItem;
+ work: WorkItem;
}
/**
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
index ae8e0fd2183..66949c62b2d 100644
--- a/packages/database/src/models/work/queries.ts
+++ b/packages/database/src/models/work/queries.ts
@@ -14,6 +14,7 @@ import {
import type { SQL } from 'drizzle-orm';
import { and, desc, eq, inArray, isNull, lt, or } from 'drizzle-orm';
+import { documents } from '../../schemas/file';
import { tasks } from '../../schemas/task';
import { topics } from '../../schemas/topic';
import { works, workVersions } from '../../schemas/work';
@@ -24,6 +25,8 @@ import {
currentVersionEventSelection,
currentVersions,
currentWorkListFields,
+ documentSummaryJoin,
+ resourceDeletedField,
taskSummaryJoin,
} from './internal';
import {
@@ -164,6 +167,7 @@ export const listSummariesByRootOperations = async (
.select({
event: currentVersionEventSelection,
...currentTaskSummaryFields,
+ resourceDeleted: resourceDeletedField,
version: {
createdAt: currentVersions.createdAt,
id: currentVersions.id,
@@ -174,6 +178,11 @@ export const listSummariesByRootOperations = async (
.from(works)
.innerJoin(currentVersions, eq(works.currentVersionId, currentVersions.id))
.leftJoin(tasks, taskSummaryJoin(ctx))
+ // LEFT JOIN, like the tasks one: an orphaned document Work (backing row
+ // hard-deleted outside the tool path) must still surface, so the UI can
+ // render it as "document deleted" and offer removal instead of showing a
+ // live-looking card that 404s on click.
+ .leftJoin(documents, documentSummaryJoin)
.where(and(workOwnership(ctx), inArray(works.id, Array.from(anchorByWorkId.keys()))))
.orderBy(desc(works.updatedAt), desc(works.id));
@@ -353,6 +362,7 @@ export const listByWorkspace = async (
// Joined for the gallery's group-by-conversation headers; null once the
// origin topic is deleted (originTopicId is set-null on topic deletion).
originTopicTitle: topics.title,
+ resourceDeleted: resourceDeletedField,
version: {
createdAt: currentVersions.createdAt,
id: currentVersions.id,
@@ -363,6 +373,11 @@ export const listByWorkspace = async (
.from(works)
.innerJoin(currentVersions, eq(works.currentVersionId, currentVersions.id))
.leftJoin(tasks, taskSummaryJoin(ctx))
+ // LEFT JOIN, like the tasks one: an orphaned document Work (backing row
+ // hard-deleted outside the tool path) must still surface, so the UI can
+ // render it as "document deleted" and offer removal instead of showing a
+ // live-looking card that 404s on click.
+ .leftJoin(documents, documentSummaryJoin)
.leftJoin(topics, eq(works.originTopicId, topics.id))
.where(and(...filters))
.orderBy(desc(works.updatedAt), desc(works.id))
diff --git a/packages/database/src/models/work/task.ts b/packages/database/src/models/work/task.ts
index 9da5a9f4a6e..1016803a17f 100644
--- a/packages/database/src/models/work/task.ts
+++ b/packages/database/src/models/work/task.ts
@@ -15,6 +15,7 @@ import {
currentWorkListFields,
eventTaskSummaryFields,
eventWorkListFields,
+ taskDeletedField,
taskSummaryJoin,
type TaskWorkSummaryQueryRow,
truncateSummaryText,
@@ -94,16 +95,16 @@ export const registerTaskWork = async (ctx: WorkContext, params: RegisterTaskWor
/** Card-facing task fields from a live-coalesced task projection. */
const toTaskCardFields = (
- task: TaskWorkSummaryQueryRow['task'],
-): Pick<TaskWorkListItem, 'task' | 'taskDeleted'> => ({
+ row: Pick<TaskWorkSummaryQueryRow, 'resourceDeleted' | 'task'>,
+): Pick<TaskWorkListItem, 'resourceDeleted' | 'task'> => ({
+ resourceDeleted: row.resourceDeleted,
task: {
- identifier: task.identifier,
- instruction: truncateSummaryText(task.instruction),
- name: task.name,
- priority: task.priority,
- status: task.status,
+ identifier: row.task.identifier,
+ instruction: truncateSummaryText(row.task.instruction),
+ name: row.task.name,
+ priority: row.task.priority,
+ status: row.task.status,
},
- taskDeleted: task.deleted,
});
/**
@@ -118,6 +119,7 @@ export const taskWorkAdapter: WorkTypeAdapter = {
.select({
eventCreatedAt: workVersions.createdAt,
...currentTaskSummaryFields,
+ resourceDeleted: taskDeletedField,
work: currentWorkListFields,
})
.from(workVersions)
@@ -133,7 +135,7 @@ export const taskWorkAdapter: WorkTypeAdapter = {
eventCreatedAt: row.eventCreatedAt,
item: {
...row.work,
- ...toTaskCardFields(row.task),
+ ...toTaskCardFields(row),
resourceType: 'task' as const,
type: 'task' as const,
} satisfies TaskWorkListItem,
@@ -144,6 +146,7 @@ export const taskWorkAdapter: WorkTypeAdapter = {
const rows = await ctx.db
.select({
...eventTaskSummaryFields,
+ resourceDeleted: taskDeletedField,
version: versionEventSelection,
work: eventWorkListFields,
})
@@ -156,7 +159,7 @@ export const taskWorkAdapter: WorkTypeAdapter = {
return rows.map((row) => ({
...row.work,
- ...toTaskCardFields(row.task),
+ ...toTaskCardFields(row),
resourceType: 'task' as const,
type: 'task' as const,
version: row.version,
@@ -165,7 +168,7 @@ export const taskWorkAdapter: WorkTypeAdapter = {
mapCurrentRow: (row, totalCost): TaskWorkSummaryItem => ({
...row.work,
- ...toTaskCardFields(row.task),
+ ...toTaskCardFields(row),
event: row.event,
resourceType: 'task' as const,
totalCost,
diff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.ts
index 091eb288719..76abdc1aeb1 100644
--- a/packages/database/src/models/work/writes.ts
+++ b/packages/database/src/models/work/writes.ts
@@ -1,6 +1,7 @@
import type {
DeleteDocumentWorkParams,
DeleteTaskWorkParams,
+ DeleteWorkParams,
WorkDisplayField,
WorkItem,
WorkResourceType,
@@ -10,6 +11,7 @@ import type {
import { and, eq, sql } from 'drizzle-orm';
import { documents } from '../../schemas/file';
+import { tasks } from '../../schemas/task';
import { works, workVersions } from '../../schemas/work';
import type { LobeChatDatabase } from '../../type';
import { documentOwnership, type WorkContext, workOwnership } from './context';
@@ -314,3 +316,35 @@ export const deleteTaskWork = async (
and(workOwnership(ctx), eq(works.resourceType, 'task'), eq(works.resourceId, params.taskId)),
);
};
+
+/**
+ * User-initiated removal of one Work card by its own id. Meant for orphaned
+ * Works (the backing task / document is gone — see `resourceDeleted`), where
+ * deleting the resource itself is no longer possible, so this is the only way
+ * the user can clear the card.
+ *
+ * Restricted to the Work's own `userId` (the resource owner stamped at
+ * registration), not every member who can see the row, and to rows whose
+ * backing task / document is actually gone: the endpoint has no scoped RBAC
+ * gate, so without this a caller could wipe a live Work's version history by
+ * id alone. `external` / `file` Works have no backing row and are always
+ * eligible. Cascades `work_versions`, `project_works` and
+ * `goal_node_work_versions` via FK.
+ */
+export const deleteWork = async (ctx: WorkContext, params: DeleteWorkParams): Promise<void> => {
+ const backingResourceGone = sql<boolean>`case ${works.resourceType}
+ when 'task' then not exists (select 1 from ${tasks} where ${tasks.id} = ${works.resourceId})
+ when 'document' then not exists (select 1 from ${documents} where ${documents.id} = ${works.resourceId})
+ else true end`;
+
+ await ctx.db
+ .delete(works)
+ .where(
+ and(
+ workOwnership(ctx),
+ eq(works.id, params.id),
+ eq(works.userId, ctx.userId),
+ backingResourceGone,
+ ),
+ );
+};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 537573640ad..03bc7336ad1 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2692,7 +2692,14 @@ export default {
'workingPanel.works.error': 'Failed to load works',
'workingPanel.works.changeType.created': 'Created',
'workingPanel.works.changeType.updated': 'Updated',
- 'workingPanel.works.taskDeleted': 'Task deleted',
+ 'workingPanel.works.documentDeleted': 'This document has been deleted',
+ 'workingPanel.works.remove': 'Remove work',
+ 'workingPanel.works.removeConfirm':
+ 'Remove this work card? Its version history, project pins and goal evidence links will be removed as well. This cannot be undone.',
+ 'workingPanel.works.resourceDeleted': 'This resource has been deleted',
+ 'workingPanel.works.resourceDeletedRemoveConfirm':
+ 'It can no longer be opened. Remove this work card? Its version history, project pins and goal evidence links will be removed as well. This cannot be undone.',
+ 'workingPanel.works.taskDeleted': 'This task has been deleted',
'workingPanel.works.title': 'Works',
'workingPanel.works.versionError': 'Failed to load versions',
'workingPanel.works.viewMode.history': 'Version history',
diff --git a/packages/types/src/work.ts b/packages/types/src/work.ts
index dd7131d05c4..055766cb02e 100644
--- a/packages/types/src/work.ts
+++ b/packages/types/src/work.ts
@@ -93,6 +93,18 @@ export type WorkListBaseItem = WorkItem & {
* origin topic was deleted (originTopicId is set-null) or never stamped.
*/
originTopicTitle?: string | null;
+ /**
+ * The live resource row backing this Work (the task / the document) no longer
+ * exists. It was deleted outside the tool-dispatch path, which deliberately
+ * orphans the Work rather than removing it (see `models/work/context.ts`), so
+ * the card renders from its version snapshot and opening it would 404 — the
+ * UI shows a "resource deleted" badge and offers removal instead.
+ *
+ * Derived per query from a LEFT JOIN miss on the backing table, never
+ * persisted. Always `false` for `external` and `file` Works: they have no
+ * local backing row that could go missing.
+ */
+ resourceDeleted: boolean;
};
export interface WorkVersionItem {
@@ -160,14 +172,6 @@ export interface TaskWorkListItem extends WorkListBaseItem {
priority: number | null;
status: TaskStatus | string | null;
};
- /**
- * The live task row backing this Work no longer exists (deleted outside the
- * tool-dispatch path, which deliberately orphans the Work). When true, the
- * `task` fields fall back to the version snapshot and the UI renders the card
- * as "task deleted". Derived from a `tasks` LEFT JOIN missing its row, not a
- * persisted flag.
- */
- taskDeleted: boolean;
type: 'task';
}
@@ -318,6 +322,17 @@ export interface DeleteTaskWorkParams {
taskId: string;
}
+/**
+ * User-initiated removal of one Work card, addressed by the Work's own id
+ * rather than a backing resource — the resource is typically already gone (see
+ * {@link WorkListBaseItem.resourceDeleted}), which is exactly why the user has
+ * no other way to clear the card.
+ */
+export interface DeleteWorkParams {
+ /** `works.id` of the card to remove. */
+ id: string;
+}
+
export interface RegisterExternalWorkParams {
agentId?: string | null;
changeType: WorkVersionChangeType;
diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
index e25a2d6e3c3..efa21a0a92a 100644
--- a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
+++ b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
@@ -1,14 +1,14 @@
import type { TaskStatus, WorkListItem } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import { Tag, Text } from '@lobehub/ui/base-ui';
+import { Text } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import { ChevronDownIcon, ChevronRightIcon, Trash2Icon } from 'lucide-react';
+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
import TaskPriorityTag from '@/features/AgentTasks/features/TaskPriorityTag';
import TaskStatusTag from '@/features/AgentTasks/features/TaskStatusTag';
import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
+import { useResourceDeletedPrompt } from '@/features/Work/useResourceDeletedPrompt';
import { useChatStore } from '@/store/chat';
import VersionList from './VersionList';
@@ -58,7 +58,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
- const { t } = useTranslation('chat');
const [expanded, setExpanded] = useState(false);
const [openDocument, openFilePreview, openTaskDetail] = useChatStore((s) => [
s.openDocument,
@@ -66,9 +65,11 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
s.openTaskDetail,
]);
const ToggleIcon = expanded ? ChevronDownIcon : ChevronRightIcon;
- // The underlying task was deleted outside the tool path — the Work survives as
- // an orphan rendered from its snapshot, and opening the (gone) task detail 404s.
- const taskDeleted = work.type === 'task' && work.taskDeleted;
+ const promptResourceDeleted = useResourceDeletedPrompt();
+ // The underlying resource (task / document) was deleted outside the tool path
+ // — the Work survives as an orphan rendered from its snapshot, and opening the
+ // gone resource 404s, so a title click explains that and offers removal.
+ const resourceDeleted = work.resourceDeleted;
const descriptor = getWorkTypeDescriptor(work);
const label = descriptor.getIdentifier(work) ?? work.resourceId;
@@ -83,7 +84,9 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
if (!openTarget) return undefined;
switch (openTarget.kind) {
case 'document': {
- return () => openDocument(openTarget.documentId);
+ return resourceDeleted
+ ? () => promptResourceDeleted(work)
+ : () => openDocument(openTarget.documentId);
}
case 'external': {
// Defense in depth: only ever hand http(s) to shell.openExternal.
@@ -95,7 +98,9 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
return () => openFilePreview({ fileId: openTarget.fileId });
}
case 'task': {
- return taskDeleted ? undefined : () => openTaskDetail(openTarget.identifier);
+ return resourceDeleted
+ ? () => promptResourceDeleted(work)
+ : () => openTaskDetail(openTarget.identifier);
}
}
})();
@@ -121,11 +126,6 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
<Text className={styles.context} style={{ flexShrink: 0 }}>
{label}
</Text>
- {taskDeleted && (
- <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
- {t('workingPanel.works.taskDeleted')}
- </Tag>
- )}
{title && (
<Text
ellipsis
diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsx
index 8bb2335a97f..8bec0b66df5 100644
--- a/src/features/Work/WorkSummaryCard.tsx
+++ b/src/features/Work/WorkSummaryCard.tsx
@@ -3,9 +3,9 @@
import type { WorkSummaryItem } from '@lobechat/types';
import { formatUsageValue } from '@lobechat/utils';
import { Center, Flexbox, Icon as LobeIcon } from '@lobehub/ui';
-import { Tag, Text } from '@lobehub/ui/base-ui';
+import { Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cx } from 'antd-style';
-import { CircleDollarSignIcon, CoinsIcon, Trash2Icon } from 'lucide-react';
+import { CircleDollarSignIcon, CoinsIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,6 +14,7 @@ import { getWorkVersionTotalTokens } from '@/utils/workCumulativeUsage';
import { formatWorkVersionCost } from '@/utils/workVersionCost';
import { getWorkTypeDescriptor, isSafeExternalUrl } from './descriptors';
+import { useResourceDeletedPrompt } from './useResourceDeletedPrompt';
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
@@ -116,8 +117,9 @@ interface WorkSummaryCardProps {
* Override the click target. The default opens the chat portal (task detail /
* document), which only renders inside the conversation UI; surfaces without
* that portal (e.g. the resource page's 产物 gallery) pass their own
- * navigation here. Only ever receives a clickable item — the card still gates
- * clickability on external-url presence and task-deleted state.
+ * navigation here. Only ever receives a clickable, non-orphaned item — the
+ * card still gates clickability on external-url presence and routes
+ * resource-deleted items to the deleted notice before reaching this.
*/
onOpen?: (item: WorkSummaryItem) => void;
/**
@@ -135,6 +137,7 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
const openDocument = useChatStore((s) => s.openDocument);
const openFilePreview = useChatStore((s) => s.openFilePreview);
const openTaskDetail = useChatStore((s) => s.openTaskDetail);
+ const promptResourceDeleted = useResourceDeletedPrompt();
const cost = formatWorkVersionCost(item.totalCost);
const totalTokens = getWorkVersionTotalTokens(item.event.cumulativeUsage);
const usage = cost
@@ -162,13 +165,18 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
const showIdentifier = !!identifier && identifier !== title;
const description = descriptor.getDescription(item);
const openTarget = descriptor.getOpenTarget(item);
- // The backing task was deleted outside the tool path: the Work lingers as an
- // orphan rendered from its snapshot, and opening the gone task detail 404s, so
- // strip the click affordance and surface a "task deleted" badge.
- const taskDeleted = item.resourceType === 'task' && item.taskDeleted;
- const clickable = !!openTarget && !taskDeleted;
+ // The backing resource (task / document) was deleted outside the tool path:
+ // the Work lingers as an orphan rendered from its snapshot, and opening the
+ // gone resource 404s. The card keeps its normal look and a click explains
+ // that the resource is gone and offers to remove the card.
+ const resourceDeleted = item.resourceDeleted;
+ const clickable = !!openTarget;
const handleOpen = () => {
+ if (resourceDeleted) {
+ promptResourceDeleted(item);
+ return;
+ }
if (onOpen) {
onOpen(item);
return;
@@ -212,11 +220,6 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
{title}
</Text>
{showIdentifier && <span className={styles.inlineIdentifier}>{identifier}</span>}
- {taskDeleted && (
- <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
- {t('workingPanel.works.taskDeleted')}
- </Tag>
- )}
</Flexbox>
{description && (
<Text ellipsis className={styles.inlineDescription}>
@@ -256,11 +259,6 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
{identifier}
</Text>
)}
- {taskDeleted && (
- <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
- {t('workingPanel.works.taskDeleted')}
- </Tag>
- )}
</Flexbox>
{usage && (
<Center horizontal className={styles.cost} gap={2} title={usageTitle}>
diff --git a/src/features/Work/useRemoveWork.ts b/src/features/Work/useRemoveWork.ts
new file mode 100644
index 00000000000..8bbf325918e
--- /dev/null
+++ b/src/features/Work/useRemoveWork.ts
@@ -0,0 +1,62 @@
+import type { WorkListBaseItem } from '@lobechat/types';
+import { confirmModal, toast } from '@lobehub/ui/base-ui';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { workService } from '@/services/work';
+
+/**
+ * User-initiated removal of a Work card. Intended for orphaned Works (the
+ * backing task / document is gone, so the user cannot clear the card by
+ * deleting the resource itself — see LOBE-13917). Confirms first because the
+ * delete cascades the Work's version history and any project pins.
+ */
+export interface UseRemoveWorkOptions {
+ /**
+ * Called after the Work is deleted and the global Work caches are refreshed.
+ * Lists backed by `useSWRInfinite` (e.g. the resource-page gallery) need
+ * this: SWR's filter-form `mutate` skips their `$inf$` cache keys, so the
+ * global refresh below never reaches them and the card would linger until a
+ * reload — the owner passes its bound `mutate` here instead.
+ */
+ onRemoved?: () => void | Promise<void>;
+}
+
+/**
+ * Per-call copy for the confirm dialog. The default asks a plain "remove this
+ * card?"; an entry point that already knows *why* the card is being removed
+ * (e.g. the user just tried to open an orphan) leads with that instead.
+ */
+interface RemoveWorkPrompt {
+ content: string;
+ title: string;
+}
+
+export const useRemoveWork = ({ onRemoved }: UseRemoveWorkOptions = {}) => {
+ const { t } = useTranslation(['chat', 'common']);
+
+ return useCallback(
+ (item: Pick<WorkListBaseItem, 'id'>, prompt?: RemoveWorkPrompt) => {
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: prompt?.content ?? t('workingPanel.works.removeConfirm', { ns: 'chat' }),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await workService.deleteWork(item.id);
+ // The orphan may be surfaced in the gallery, the sidebar and any
+ // message it was registered from, so refresh every Work view.
+ await workService.refreshAllConversations();
+ await onRemoved?.();
+ } catch (error) {
+ console.error('[useRemoveWork] failed to delete work', error);
+ toast.error(t('operationFailed', { ns: 'common' }));
+ }
+ },
+ title: prompt?.title ?? t('workingPanel.works.remove', { ns: 'chat' }),
+ });
+ },
+ [onRemoved, t],
+ );
+};
diff --git a/src/features/Work/useResourceDeletedPrompt.ts b/src/features/Work/useResourceDeletedPrompt.ts
new file mode 100644
index 00000000000..019b9c54cff
--- /dev/null
+++ b/src/features/Work/useResourceDeletedPrompt.ts
@@ -0,0 +1,52 @@
+import type { WorkListBaseItem } from '@lobechat/types';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useRemoveWork, type UseRemoveWorkOptions } from './useRemoveWork';
+
+/**
+ * i18n key for the "resource deleted" title, worded per Work type so the user
+ * learns *what* is gone (the task / the document), not just that the card is
+ * an orphan.
+ */
+const resourceDeletedKey = (item: Pick<WorkListBaseItem, 'type'>) => {
+ switch (item.type) {
+ case 'document': {
+ return 'workingPanel.works.documentDeleted';
+ }
+ case 'task': {
+ return 'workingPanel.works.taskDeleted';
+ }
+ default: {
+ return 'workingPanel.works.resourceDeleted';
+ }
+ }
+};
+
+/**
+ * Click handler for an orphaned Work: the backing resource was deleted outside
+ * the tool path, so the card renders from its snapshot and opening it would
+ * 404. The card deliberately looks like any other card — a persistent badge
+ * taxed every surface for a rare state — and only explains itself when the
+ * user actually tries to open it.
+ *
+ * The explanation is the removal confirm itself, not a toast: the one thing a
+ * user can still do with a card that no longer opens is clear it, and a
+ * corner toast is both far from where they clicked and gone before they can
+ * act on it. Cancel keeps the card. Callers gate on `item.resourceDeleted` and
+ * call this instead of their open handler.
+ */
+export const useResourceDeletedPrompt = (options: UseRemoveWorkOptions = {}) => {
+ const { t } = useTranslation('chat');
+ const removeWork = useRemoveWork(options);
+
+ return useCallback(
+ (item: Pick<WorkListBaseItem, 'id' | 'type'>) => {
+ removeWork(item, {
+ content: t('workingPanel.works.resourceDeletedRemoveConfirm'),
+ title: t(resourceDeletedKey(item)),
+ });
+ },
+ [removeWork, t],
+ );
+};
diff --git a/src/features/WorkGallery/WorkPreview.tsx b/src/features/WorkGallery/WorkPreview.tsx
index 21328fb3094..b28cfcd5319 100644
--- a/src/features/WorkGallery/WorkPreview.tsx
+++ b/src/features/WorkGallery/WorkPreview.tsx
@@ -230,7 +230,10 @@ const WorkPreview = memo<WorkPreviewProps>(({ item, title }) => {
<DescriptorIcon size={17} />
)}
</div>
- {!isLinear && !isGithub && status && (
+ {/* An orphan's status is the last snapshot of a resource that no longer
+ exists, and the badge shares the top-right corner with the card's
+ hover Remove action, so drop it once the resource is gone. */}
+ {!isLinear && !isGithub && status && !item.resourceDeleted && (
<Tag className={styles.status} color={getStatusColor(status)} size={'small'}>
{status}
</Tag>
diff --git a/src/features/WorkGallery/WorkPreviewCard.tsx b/src/features/WorkGallery/WorkPreviewCard.tsx
index 76437ff30f4..6b27bba702a 100644
--- a/src/features/WorkGallery/WorkPreviewCard.tsx
+++ b/src/features/WorkGallery/WorkPreviewCard.tsx
@@ -3,7 +3,7 @@
import type { WorkSummaryItem } from '@lobechat/types';
import { formatTokenNumber } from '@lobechat/utils/format';
import { Flexbox } from '@lobehub/ui';
-import { Avatar, Tag } from '@lobehub/ui/base-ui';
+import { ActionIcon, Avatar, Tag } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { Trash2Icon } from 'lucide-react';
import { memo } from 'react';
@@ -12,6 +12,8 @@ import { useTranslation } from 'react-i18next';
import { formatTaskItemDate } from '@/features/AgentTasks/features/formatTaskItemDate';
import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';
import { getWorkTypeDescriptor } from '@/features/Work/descriptors';
+import { useRemoveWork } from '@/features/Work/useRemoveWork';
+import { useResourceDeletedPrompt } from '@/features/Work/useResourceDeletedPrompt';
import { getWorkVersionTotalTokens } from '@/utils/workCumulativeUsage';
import { formatWorkVersionCost } from '@/utils/workVersionCost';
@@ -59,6 +61,26 @@ const styles = createStaticStyles(({ css }) => ({
border-color: ${cssVar.colorBorder};
}
`,
+ removeAction: css`
+ position: absolute;
+ z-index: 1;
+ inset-block-start: 12px;
+ inset-inline-end: 12px;
+
+ opacity: 0;
+
+ transition: opacity ${cssVar.motionDurationFast};
+
+ &:focus-visible,
+ .work-preview-card:hover & {
+ opacity: 1;
+ }
+
+ /* Touch devices have no hover to reveal it; keep the only removal control visible. */
+ @media (hover: none) {
+ opacity: 1;
+ }
+ `,
footer: css`
overflow: hidden;
margin-block-start: 8px;
@@ -124,6 +146,8 @@ const styles = createStaticStyles(({ css }) => ({
interface WorkPreviewCardProps {
item: WorkSummaryItem;
onOpen: (item: WorkSummaryItem) => void;
+ /** Refresh the owning (infinite) list after an orphan card is removed; see `useRemoveWork`. */
+ onRemoved?: () => void | Promise<void>;
}
const workTypeKey = (item: WorkSummaryItem) => {
@@ -152,9 +176,11 @@ const workTypeKey = (item: WorkSummaryItem) => {
}
};
-const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen }) => {
+const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen, onRemoved }) => {
const { t, i18n } = useTranslation(['chat', 'common', 'file']);
const agent = useAgentDisplayMeta(item.originAgentId);
+ const removeWork = useRemoveWork({ onRemoved });
+ const promptResourceDeleted = useResourceDeletedPrompt({ onRemoved });
const descriptor = getWorkTypeDescriptor(item);
const title =
descriptor.getTitle(item)?.trim() ||
@@ -166,10 +192,15 @@ const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen }) => {
item.resourceType.startsWith('github_') && identifier?.includes('#')
? `#${identifier.split('#').at(-1)}`
: identifier;
- const taskDeleted = item.resourceType === 'task' && item.taskDeleted;
+ // The backing resource was deleted outside the tool path: the Work lingers as
+ // an orphan rendered from its snapshot and opening it would 404. The card
+ // keeps its normal look; a click explains that the resource is gone and
+ // offers removal in the same dialog — the only way the user can clear the
+ // card, since the resource it points at is already gone. The hover trash
+ // action reaches the same confirm for users who already know.
+ const resourceDeleted = item.resourceDeleted;
const openTarget = descriptor.getOpenTarget(item);
- const actionable = !!openTarget && (openTarget.kind !== 'filePreview' || !!openTarget.url);
- const clickable = actionable && !taskDeleted;
+ const clickable = !!openTarget && (openTarget.kind !== 'filePreview' || !!openTarget.url);
const eventDate = item.event.changeType === 'created' ? item.createdAt : item.updatedAt;
const eventAt = formatTaskItemDate(eventDate, {
formatOtherYear: t('time.formatOtherYear', { ns: 'common' }),
@@ -185,9 +216,25 @@ const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen }) => {
return (
<Flexbox
- className={cx(styles.card, clickable && styles.clickable)}
- onClick={clickable ? () => onOpen(item) : undefined}
+ className={cx('work-preview-card', styles.card, clickable && styles.clickable)}
+ onClick={
+ clickable ? () => (resourceDeleted ? promptResourceDeleted(item) : onOpen(item)) : undefined
+ }
>
+ {resourceDeleted && (
+ <ActionIcon
+ danger
+ className={styles.removeAction}
+ icon={Trash2Icon}
+ size={'small'}
+ title={t('workingPanel.works.remove', { ns: 'chat' })}
+ variant={'filled'}
+ onClick={(event) => {
+ event.stopPropagation();
+ removeWork(item);
+ }}
+ />
+ )}
<WorkPreview item={item} title={title} />
<div className={styles.cardInfo}>
<Flexbox horizontal align={'center'} className={styles.metaRow} gap={6}>
@@ -205,11 +252,6 @@ const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen }) => {
{item.status}
</Tag>
)}
- {taskDeleted && (
- <Tag color={'warning'} icon={<Trash2Icon size={12} />} size={'small'}>
- {t('workingPanel.works.taskDeleted', { ns: 'chat' })}
- </Tag>
- )}
</Flexbox>
<div className={styles.title}>{title}</div>
<Flexbox horizontal align={'baseline'} className={styles.footer} gap={7}>
diff --git a/src/features/WorkGallery/index.tsx b/src/features/WorkGallery/index.tsx
index 09733a0ae40..871994b0363 100644
--- a/src/features/WorkGallery/index.tsx
+++ b/src/features/WorkGallery/index.tsx
@@ -284,7 +284,12 @@ const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {
</div>
<div className={styles.cardList}>
{group.items.map((item) => (
- <WorkPreviewCard item={item} key={item.id} onOpen={handleOpen} />
+ <WorkPreviewCard
+ item={item}
+ key={item.id}
+ onOpen={handleOpen}
+ onRemoved={reload}
+ />
))}
</div>
</section>
diff --git a/src/services/work.test.ts b/src/services/work.test.ts
index e5c1d2923dd..e37bf0d55ad 100644
--- a/src/services/work.test.ts
+++ b/src/services/work.test.ts
@@ -10,8 +10,12 @@ vi.mock('@/libs/swr', () => ({
// work.ts imports the lambda client at module load; stub it so the service
// module resolves without a real tRPC client.
+const deleteWorkMutate = vi.fn();
+
vi.mock('@/libs/trpc/client', () => ({
- lambdaClient: { work: {} },
+ lambdaClient: {
+ work: { deleteWork: { mutate: (...args: unknown[]) => deleteWorkMutate(...args) } },
+ },
}));
// Imported after the mocks so the service binds to the stubbed `mutate`.
@@ -85,6 +89,14 @@ describe('didToolMutateWorkView', () => {
});
});
+describe('workService.deleteWork', () => {
+ it('calls the deleteWork mutation with the work id', async () => {
+ deleteWorkMutate.mockResolvedValue(undefined);
+ await workService.deleteWork('work-1');
+ expect(deleteWorkMutate).toHaveBeenCalledWith({ id: 'work-1' });
+ });
+});
+
describe('workService.refreshConversation', () => {
it('refreshes messages, history, and mounted version timelines once per operation', async () => {
await workService.refreshConversation('t1', 'th1');
diff --git a/src/services/work.ts b/src/services/work.ts
index 188bba0d5e6..61ebcd9d57e 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -103,6 +103,9 @@ class WorkService {
deleteTaskWork = async (params: { taskId: string }): Promise<void> =>
lambdaClient.work.deleteTaskWork.mutate(params);
+ /** Remove one Work card by id (see `useRemoveWork`); server-side restricted to the caller's own rows. */
+ deleteWork = async (id: string): Promise<void> => lambdaClient.work.deleteWork.mutate({ id });
+
handleSkillToolResult = async (
params: RegisterSkillToolResultWorkParams,
): Promise<WorkItem | null> => lambdaClient.work.handleSkillToolResult.mutate(params);