🤯 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(work): hide orphaned Works on the resource page (#20717)
YuTengjing7e8a6118c5ce
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.mdindex 049cd712123..80b88863eb4 100644--- a/.agents/skills/agent-work/SKILL.md+++ b/.agents/skills/agent-work/SKILL.md@@ -33,6 +33,13 @@ A share visitor's run executes as the creator, so owner scope alone cannot separ- The resource unique indexes include the visitor topic id, so the creator and each visitor topic keep separate rows for the same external resource.- Visitor read payloads drop the creator's `userId` / `workspaceId` and gate spend on `showModelInfo` (`toVisitorMessage`).+## Orphaned Works (backing resource deleted)++`works.resourceId` has no FK, and deleting a document, task, or file never cascades into its Work (LOBE-13917). Deleting the Work would also drop its version history and its project and goal references. Each read surface handles orphans itself:++- **Resource-page galleries hide orphans.** These are `listByWorkspace` surfaces: `/resource`, `/resource/works`, and the project dashboard. They filter orphans out with `resourceLiveFilter` (`packages/database/src/models/work/internal.ts`). A task or document must still exist and not be trashed. A file Work's current-version `fileId` must point to a `files` row that exists and is not trashed. Restoring the resource brings the card back. Any new gallery-style Work list must apply the same filter.+- **Conversation surfaces keep the card.** These are `listByConversation` and the cards under messages; the conversation did produce the Work. `resourceDeleted` drives a click-time prompt (`useResourceDeletedPrompt`) that lets the user remove it.+## Registration write pathsFour write paths, two timing classes:diff --git a/packages/database/src/models/work/__tests__/document.test.ts b/packages/database/src/models/work/__tests__/document.test.tsindex ef11abcc76d..2355548c7ea 100644--- a/packages/database/src/models/work/__tests__/document.test.ts+++ b/packages/database/src/models/work/__tests__/document.test.ts@@ -475,9 +475,9 @@ describe('WorkModel · workspace document visibility', () => {// so the UI renders "document deleted" + a remove action instead of a live// card that 404s on open.expect(ownerView[0].resourceDeleted).toBe(true);+ // The resource-page gallery hides the orphan instead (resourceLiveFilter).const { items } = await ownerWorks.listByWorkspace({});- expect(items).toHaveLength(1);- expect(items[0].resourceDeleted).toBe(true);+ expect(items).toHaveLength(0);expect(await memberWorks.listByConversation({ topicId })).toHaveLength(0);});diff --git a/packages/database/src/models/work/__tests__/queries.test.ts b/packages/database/src/models/work/__tests__/queries.test.tsindex 6ff708fa177..1f21d129266 100644--- a/packages/database/src/models/work/__tests__/queries.test.ts+++ b/packages/database/src/models/work/__tests__/queries.test.ts@@ -2,7 +2,7 @@import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { topics, works } from '../../../schemas';+import { files, topics, works } from '../../../schemas';import { AgentDocumentModel } from '../../agentDocuments';import { TaskModel } from '../../task';import { WorkModel } from '..';@@ -401,6 +401,16 @@ describe('WorkModel · queries', () => {toolName: 'createTask',topicId,});+ // The workspace gallery hides file Works whose persisted file is gone, so+ // back this one with a live `files` row.+ await serverDB.insert(files).values({+ fileType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ id: 'file-gate',+ name: 'report.pptx',+ size: 1024,+ url: 'files/file-gate.pptx',+ userId,+ });// No threadId: the version's threadId stays null so the default (no-thread)// conversation query surfaces it alongside the task work.await workModel.registerFile({diff --git a/packages/database/src/models/work/__tests__/workspace.test.ts b/packages/database/src/models/work/__tests__/workspace.test.tsindex 956f689442a..d83f39d1437 100644--- a/packages/database/src/models/work/__tests__/workspace.test.ts+++ b/packages/database/src/models/work/__tests__/workspace.test.ts@@ -2,7 +2,7 @@import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { topics, works, workspaces } from '../../../schemas';+import { documents, files, topics, works, workspaces } from '../../../schemas';import { AgentDocumentModel } from '../../agentDocuments';import { TaskModel } from '../../task';import { WorkModel } from '..';@@ -281,7 +281,7 @@ describe('WorkModel · listByWorkspace', () => {expect(publicOnly.items.map((item) => item.id)).toEqual([publicWork!.id]);});- it('flags an orphaned task work whose task was deleted without the tool', async () => {+ it('hides an orphaned task work whose task was deleted without the tool', async () => {const taskModel = new TaskModel(serverDB, userId);const workModel = new WorkModel(serverDB, userId);const task = await taskModel.create({ instruction: 'Orphan', name: 'Orphan task' });@@ -296,14 +296,121 @@ describe('WorkModel · listByWorkspace', () => {topicId,});- // UI/CLI delete (no tool dispatch) leaves the Work orphaned; the LEFT JOIN- // miss must render as `resourceDeleted` from the version snapshot, not drop it.+ // UI/CLI delete (no tool dispatch) leaves the Work row orphaned; the+ // gallery drops it instead of rendering a dead card.await taskModel.delete(task.id);const { items } = await workModel.listByWorkspace({});+ expect(items).toHaveLength(0);+ expect(await serverDB.select().from(works)).toHaveLength(1);+ });+});++describe('WorkModel · listByWorkspace orphan filtering', () => {+ const registerDocumentWork = async (workModel: WorkModel) => {+ const doc = await new AgentDocumentModel(serverDB, userId).create(+ agentId,+ 'orphan.md',+ 'Orphan body',+ { title: 'Orphan doc' },+ );+ await workModel.registerDocument({+ agentDocumentId: doc.id,+ agentId,+ changeType: 'created',+ documentId: doc.documentId,+ rootOperationId: 'op-orphan-doc',+ toolCallId: 'tool-call-orphan-doc',+ toolIdentifier: 'lobe-agent-documents',+ toolName: 'createDocument',+ topicId,+ });+ return doc.documentId;+ };++ const registerFileWork = (workModel: WorkModel, fileId?: string) =>+ workModel.registerFile({+ agentId,+ filePath: '/mnt/data/deck.pptx',+ metadata: { filePath: '/mnt/data/deck.pptx', ...(fileId ? { fileId } : {}) },+ rootOperationId: 'op-orphan-file',+ title: 'deck.pptx',+ toolCallId: 'op:op-orphan-file',+ toolIdentifier: 'lobe-cloud-sandbox',+ toolName: 'writeFile',+ topicId,+ userId,+ });++ const insertFile = (id: string) =>+ serverDB.insert(files).values({+ fileType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ id,+ name: 'deck.pptx',+ size: 2048,+ url: `files/${id}.pptx`,+ userId,+ });++ it('hides a document work whose document was hard-deleted', async () => {+ const workModel = new WorkModel(serverDB, userId);+ const documentId = await registerDocumentWork(workModel);+ expect((await workModel.listByWorkspace({})).items).toHaveLength(1);++ await serverDB.delete(documents).where(eq(documents.id, documentId));++ expect((await workModel.listByWorkspace({})).items).toHaveLength(0);+ // Hidden, not deleted: the Work row and its history survive.+ expect(await serverDB.select().from(works)).toHaveLength(1);+ });++ it('hides a document work while its document is in the recycle bin and restores it after', async () => {+ const workModel = new WorkModel(serverDB, userId);+ const documentId = await registerDocumentWork(workModel);++ await serverDB+ .update(documents)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(documents.id, documentId));+ expect((await workModel.listByWorkspace({})).items).toHaveLength(0);++ await serverDB+ .update(documents)+ .set({ deletedAt: null, isDeleted: null })+ .where(eq(documents.id, documentId));+ expect((await workModel.listByWorkspace({})).items).toHaveLength(1);+ });++ it('keeps a file work whose persisted file is live', async () => {+ const workModel = new WorkModel(serverDB, userId);+ await insertFile('work-test-live-file');+ await registerFileWork(workModel, 'work-test-live-file');++ const { items } = await workModel.listByWorkspace({ includeFileWorks: true });expect(items).toHaveLength(1);- const summary = expectTaskSummaryItem(items[0]);- expect(summary.task.name).toBe('Orphan task');- expect(summary.resourceDeleted).toBe(true);+ expect(items[0]).toMatchObject({ title: 'deck.pptx', type: 'file' });+ });++ it('hides a file work whose persisted file was deleted or trashed', async () => {+ const workModel = new WorkModel(serverDB, userId);+ await insertFile('work-test-gone-file');+ await registerFileWork(workModel, 'work-test-gone-file');++ await serverDB+ .update(files)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(files.id, 'work-test-gone-file'));+ expect((await workModel.listByWorkspace({ includeFileWorks: true })).items).toHaveLength(0);++ await serverDB.delete(files).where(eq(files.id, 'work-test-gone-file'));+ expect((await workModel.listByWorkspace({ includeFileWorks: true })).items).toHaveLength(0);+ expect(await serverDB.select().from(works)).toHaveLength(1);+ });++ it('keeps a file work that was never uploaded (no fileId to check)', async () => {+ const workModel = new WorkModel(serverDB, userId);+ await registerFileWork(workModel);++ expect((await workModel.listByWorkspace({ includeFileWorks: true })).items).toHaveLength(1);});});diff --git a/packages/database/src/models/work/internal.ts b/packages/database/src/models/work/internal.tsindex 04c22964b72..4a197264290 100644--- a/packages/database/src/models/work/internal.ts+++ b/packages/database/src/models/work/internal.ts@@ -15,7 +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 { documents, files } from '../../schemas/file';import { tasks } from '../../schemas/task';import { works, workVersions } from '../../schemas/work';import { taskOwnership, type WorkContext, workOwnership } from './context';@@ -264,6 +264,32 @@ export const resourceNeverDeletedField = sql<boolean>`false`;*/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`;+/**+ * Row filter that keeps only Works whose backing resource is still live, for+ * the resource-page galleries. Those surfaces hide orphans instead of rendering+ * them as full-size cards that only a click reveals as gone; the Work row and+ * its version history stay untouched (removing them would also drop project+ * and goal references), so a restored resource brings its card back.+ *+ * Requires the same LEFT JOINs as {@link resourceDeletedField} plus the+ * {@link currentVersions} join:+ * - `task`: the owner-scoped join already misses trashed tasks.+ * - `document`: missing or in the recycle bin.+ * - `file`: the current version's persisted `fileId` is missing or trashed. A+ * version without `fileId` was never uploaded, so there is nothing to check.+ * The null test is COALESCEd because a bare `->> IS NULL` crashes pg_search+ * planning (see jsonbNullTest.test.ts).+ * - `external`: remote state is unknown locally, so it is always kept.+ */+export const resourceLiveFilter = sql<boolean>`case ${works.resourceType}+ when 'task' then ${tasks.id} is not null+ when 'document' then ${documents.id} is not null and ${documents.isDeleted} is not true+ when 'file' then coalesce(${currentVersions.metadata} ->> 'fileId', '') = '' or exists (+ select 1 from ${files}+ where ${files.id} = ${currentVersions.metadata} ->> 'fileId' and ${files.isDeleted} is not true+ )+ else true end`;+/*** Shared version-event query for display-backed work types; `task` keeps its* own variant because it additionally joins the tasks table.diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.tsindex 66949c62b2d..fcc6a5ad753 100644--- a/packages/database/src/models/work/queries.ts+++ b/packages/database/src/models/work/queries.ts@@ -27,6 +27,7 @@ import {currentWorkListFields,documentSummaryJoin,resourceDeletedField,+ resourceLiveFilter,taskSummaryJoin,} from './internal';import {@@ -328,6 +329,9 @@ export const listByWorkspace = async (// Row-level gate: un-opted-in requests never see `file` works, even in the// combined (no `type`) view (see resolveAllowedWorkTypes).inArray(works.type, resolveAllowedWorkTypes(params.includeFileWorks)),+ // Orphaned Works (backing resource deleted or trashed) are hidden here+ // rather than shown as dead cards; see resourceLiveFilter.+ resourceLiveFilter,];if (params.type) filters.push(eq(works.type, params.type));if (params.originAgentId) filters.push(eq(works.originAgentId, params.originAgentId));@@ -372,11 +376,9 @@ export const listByWorkspace = async (}).from(works).innerJoin(currentVersions, eq(works.currentVersionId, currentVersions.id))+ // LEFT JOINs feed resourceLiveFilter, which drops rows whose backing+ // task / document is gone instead of surfacing them as orphans..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))diff --git a/src/features/ResourceHome/Home/RecentWorks.test.tsx b/src/features/ResourceHome/Home/RecentWorks.test.tsxindex 985e47f7b6a..5c313bfe2df 100644--- a/src/features/ResourceHome/Home/RecentWorks.test.tsx+++ b/src/features/ResourceHome/Home/RecentWorks.test.tsx@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*/-import { fireEvent, render, screen } from '@testing-library/react';+import { render, screen } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';import RecentWorks from './RecentWorks';@@ -29,11 +29,7 @@ vi.mock('@/features/WorkGallery/useOpenWork', () => ({}));vi.mock('@/features/WorkGallery/WorkPreviewCard', () => ({- default: ({ item, onRemoved }: { item: { id: string }; onRemoved?: () => void }) => (- <button data-testid={`card-${item.id}`} type="button" onClick={() => onRemoved?.()}>- {item.id}- </button>- ),+ default: ({ item }: { item: { id: string } }) => <div data-testid={`card-${item.id}`} />,}));vi.mock('./SectionTitle', () => ({@@ -41,15 +37,11 @@ vi.mock('./SectionTitle', () => ({}));describe('RecentWorks', () => {- it('refreshes its own infinite list after a card is removed', () => {+ it('shows only the freshest three works', () => {render(<RecentWorks />);- // Only the freshest three are shown on the dashboard.+ expect(screen.getByTestId('card-wk_1')).toBeTruthy();+ expect(screen.getByTestId('card-wk_3')).toBeTruthy();expect(screen.queryByTestId('card-wk_4')).toBeNull();-- // The global Work refresh in `useRemoveWork` skips `useSWRInfinite` keys,- // so the card has to be handed this list's own `reload`.- fireEvent.click(screen.getByTestId('card-wk_1'));- expect(mocks.reload).toHaveBeenCalledTimes(1);});});diff --git a/src/features/ResourceHome/Home/RecentWorks.tsx b/src/features/ResourceHome/Home/RecentWorks.tsxindex 018abea8038..1f451c6d033 100644--- a/src/features/ResourceHome/Home/RecentWorks.tsx+++ b/src/features/ResourceHome/Home/RecentWorks.tsx@@ -46,10 +46,7 @@ const RecentWorks = memo(() => {) : (<div className={styles.grid}>{recent.map((item) => (- // `onRemoved` is required here: this list is `useSWRInfinite`-backed,- // and `useRemoveWork`'s global refresh skips `$inf$` keys, so without- // it a removed orphan card lingers until a page reload.- <WorkPreviewCard item={item} key={item.id} onOpen={openWork} onRemoved={reload} />+ <WorkPreviewCard item={item} key={item.id} onOpen={openWork} />))}</div>)}diff --git a/src/features/WorkGallery/WorkPreview.tsx b/src/features/WorkGallery/WorkPreview.tsxindex b28cfcd5319..21328fb3094 100644--- a/src/features/WorkGallery/WorkPreview.tsx+++ b/src/features/WorkGallery/WorkPreview.tsx@@ -230,10 +230,7 @@ const WorkPreview = memo<WorkPreviewProps>(({ item, title }) => {<DescriptorIcon size={17} />)}</div>- {/* 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 && (+ {!isLinear && !isGithub && status && (<Tag className={styles.status} color={getStatusColor(status)} size={'small'}>{status}</Tag>diff --git a/src/features/WorkGallery/WorkPreviewCard.tsx b/src/features/WorkGallery/WorkPreviewCard.tsxindex 6b27bba702a..6094bd6710c 100644--- a/src/features/WorkGallery/WorkPreviewCard.tsx+++ b/src/features/WorkGallery/WorkPreviewCard.tsx@@ -3,17 +3,14 @@import type { WorkSummaryItem } from '@lobechat/types';import { formatTokenNumber } from '@lobechat/utils/format';import { Flexbox } from '@lobehub/ui';-import { ActionIcon, Avatar, Tag } from '@lobehub/ui/base-ui';+import { Avatar, Tag } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';-import { Trash2Icon } from 'lucide-react';import { memo } from 'react';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';@@ -61,26 +58,6 @@ 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;@@ -146,8 +123,6 @@ 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) => {@@ -176,11 +151,14 @@ const workTypeKey = (item: WorkSummaryItem) => {}};-const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen, onRemoved }) => {+/**+ * Gallery card for a live Work. Orphans (backing resource deleted or trashed)+ * never reach it: `listByWorkspace` filters them out server-side, so the card+ * has no "resource deleted" state.+ */+const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen }) => {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() ||@@ -192,13 +170,6 @@ const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen, onRemoved })item.resourceType.startsWith('github_') && identifier?.includes('#')? `#${identifier.split('#').at(-1)}`: identifier;- // 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 clickable = !!openTarget && (openTarget.kind !== 'filePreview' || !!openTarget.url);const eventDate = item.event.changeType === 'created' ? item.createdAt : item.updatedAt;@@ -217,24 +188,8 @@ const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen, onRemoved })return (<FlexboxclassName={cx('work-preview-card', styles.card, clickable && styles.clickable)}- onClick={- clickable ? () => (resourceDeleted ? promptResourceDeleted(item) : onOpen(item)) : undefined- }+ onClick={clickable ? () => 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}>diff --git a/src/features/WorkGallery/index.tsx b/src/features/WorkGallery/index.tsxindex 871994b0363..09733a0ae40 100644--- a/src/features/WorkGallery/index.tsx+++ b/src/features/WorkGallery/index.tsx@@ -284,12 +284,7 @@ const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {</div><div className={styles.cardList}>{group.items.map((item) => (- <WorkPreviewCard- item={item}- key={item.id}- onOpen={handleOpen}- onRemoved={reload}- />+ <WorkPreviewCard item={item} key={item.id} onOpen={handleOpen} />))}</div></section>