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(agent): display managed skill folders and align delete confirms (#14553)

AmAzing-af319af93622
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
new file mode 100644
index 00000000000..e8f4509a2a3
--- /dev/null
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
@@ -0,0 +1,296 @@
+import { fireEvent, render, screen, within } from '@testing-library/react';
+import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ExplorerTreeNode } from '@/features/ExplorerTree';
+
+import DocumentExplorerTree from './DocumentExplorerTree';
+import type { AgentDocumentItem } from './types';
+import {
+ AGENT_SKILL_TEMPLATE_ID,
+ FOLDER_FILE_TYPE,
+ SKILL_BUNDLE_FILE_TYPE,
+ SKILL_INDEX_FILE_TYPE,
+} from './types';
+
+const { navigate, openDocument, useMatchMock } = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ openDocument: vi.fn(),
+ useMatchMock: vi.fn(),
+}));
+const messageError = vi.hoisted(() => vi.fn());
+const messageSuccess = vi.hoisted(() => vi.fn());
+const messageWarning = vi.hoisted(() => vi.fn());
+const modalConfirm = vi.hoisted(() => vi.fn());
+const removeDocumentMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
+ <button aria-label={title} onClick={onClick}>
+ {title}
+ </button>
+ ),
+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: { error: messageError, success: messageSuccess, warning: messageWarning },
+ modal: { confirm: modalConfirm },
+ }),
+ },
+}));
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: {
+ removeDocument: removeDocumentMock,
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useMatch: () => useMatchMock(),
+ useNavigate: () => navigate,
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ openDocument }),
+}));
+
+vi.mock('@/features/ExplorerTree', () => {
+ interface MockExplorerTreeProps {
+ canDrag?: (node: ExplorerTreeNode<unknown>) => boolean;
+ getContextMenuItems?: (node: ExplorerTreeNode<unknown>) => unknown[] | undefined;
+ header?: ReactNode;
+ nodes: ExplorerTreeNode<unknown>[];
+ onNodeClick?: (node: ExplorerTreeNode<unknown>, event: ReactMouseEvent<HTMLElement>) => void;
+ }
+
+ interface MockMenuItem {
+ key?: number | string;
+ onClick?: () => void;
+ type?: string;
+ }
+
+ const ExplorerTree = ({
+ canDrag,
+ getContextMenuItems,
+ header,
+ nodes,
+ onNodeClick,
+ }: MockExplorerTreeProps) => {
+ const renderNodes = (parentId: string | null): ReactNode =>
+ nodes
+ .filter((node) => (node.parentId ?? null) === parentId)
+ .map((node) => {
+ const menuItems = (getContextMenuItems?.(node) ?? []) as MockMenuItem[];
+ return (
+ <div
+ data-can-drag={String(canDrag?.(node) ?? true)}
+ data-folder={String(!!node.isFolder)}
+ data-menu-count={String(menuItems.length)}
+ data-testid={`tree-node-${node.id}`}
+ key={node.id}
+ >
+ <button
+ data-testid={`tree-node-button-${node.id}`}
+ onClick={(event) => onNodeClick?.(node, event)}
+ >
+ {node.name}
+ </button>
+ {node.isFolder && (
+ <div data-testid={`tree-node-children-${node.id}`}>{renderNodes(node.id)}</div>
+ )}
+ {menuItems
+ .filter((item) => item.type !== 'divider' && item.key !== undefined)
+ .map((item) => (
+ <button
+ data-testid={`tree-menu-${node.id}-${String(item.key)}`}
+ key={item.key}
+ onClick={() => item.onClick?.()}
+ >
+ {item.key}
+ </button>
+ ))}
+ </div>
+ );
+ });
+
+ return (
+ <div data-testid="explorer-tree">
+ {header}
+ {renderNodes(null)}
+ </div>
+ );
+ };
+
+ return { ExplorerTree };
+});
+
+const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentItem =>
+ ({
+ accessPublic: 0,
+ accessSelf: 0,
+ accessShared: 0,
+ agentId: 'agent-1',
+ content: '',
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ deletedAt: null,
+ deletedByAgentId: null,
+ deletedByUserId: null,
+ deleteReason: null,
+ description: null,
+ documentId: 'doc-1',
+ editorData: null,
+ filename: 'document.md',
+ fileType: 'custom/document',
+ id: 'agent-doc-1',
+ loadRules: {},
+ metadata: null,
+ parentId: null,
+ policy: null,
+ policyLoad: 'disabled',
+ policyLoadFormat: 'raw',
+ policyLoadPosition: 'before-first-user',
+ policyLoadRule: 'always',
+ source: null,
+ sourceType: 'file',
+ templateId: null,
+ title: 'Document',
+ updatedAt: new Date('2026-05-09T00:00:00Z'),
+ userId: 'user-1',
+ ...overrides,
+ }) as AgentDocumentItem;
+
+describe('DocumentExplorerTree', () => {
+ beforeEach(() => {
+ navigate.mockReset();
+ messageError.mockReset();
+ messageSuccess.mockReset();
+ messageWarning.mockReset();
+ modalConfirm.mockReset();
+ openDocument.mockReset();
+ removeDocumentMock.mockReset();
+ removeDocumentMock.mockResolvedValue({ deleted: true, id: 'skill-bundle-row' });
+ useMatchMock.mockReset();
+ useMatchMock.mockReturnValue(null);
+ });
+
+ it('renders managed skill bundle as a folder with SKILL.md underneath', () => {
+ const data = [
+ createDocument({
+ documentId: 'skill-bundle-doc',
+ fileType: SKILL_BUNDLE_FILE_TYPE,
+ filename: 'youtube-comment-retrieval-workflow',
+ id: 'skill-bundle-row',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ title: 'YouTube Comment Retrieval Workflow',
+ }),
+ createDocument({
+ documentId: 'skill-index-doc',
+ fileType: SKILL_INDEX_FILE_TYPE,
+ filename: 'SKILL.md',
+ id: 'skill-index-row',
+ parentId: 'skill-bundle-doc',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ title: 'Generated workflow title',
+ }),
+ createDocument({
+ documentId: 'folder-doc',
+ fileType: FOLDER_FILE_TYPE,
+ filename: 'Notes',
+ id: 'folder-row',
+ title: 'Notes',
+ }),
+ ];
+
+ render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />);
+
+ const bundleNode = screen.getByTestId('tree-node-skill-bundle-row');
+ expect(bundleNode).toHaveAttribute('data-folder', 'true');
+ expect(bundleNode).toHaveAttribute('data-can-drag', 'false');
+ expect(bundleNode).toHaveAttribute('data-menu-count', '0');
+ expect(within(bundleNode).getByText('SKILL.md')).toBeInTheDocument();
+
+ const skillIndexNode = screen.getByTestId('tree-node-skill-index-row');
+ expect(skillIndexNode).toHaveAttribute('data-folder', 'false');
+ expect(skillIndexNode).toHaveAttribute('data-can-drag', 'false');
+ expect(skillIndexNode).toHaveAttribute('data-menu-count', '0');
+ });
+
+ it('opens SKILL.md but does not open the empty skill bundle', () => {
+ const data = [
+ createDocument({
+ documentId: 'skill-bundle-doc',
+ fileType: SKILL_BUNDLE_FILE_TYPE,
+ filename: 'youtube-comment-retrieval-workflow',
+ id: 'skill-bundle-row',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ title: 'YouTube Comment Retrieval Workflow',
+ }),
+ createDocument({
+ documentId: 'skill-index-doc',
+ fileType: SKILL_INDEX_FILE_TYPE,
+ filename: 'SKILL.md',
+ id: 'skill-index-row',
+ parentId: 'skill-bundle-doc',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ title: 'SKILL.md',
+ }),
+ ];
+
+ render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />);
+
+ fireEvent.click(screen.getByTestId('tree-node-button-skill-bundle-row'));
+ expect(openDocument).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByTestId('tree-node-button-skill-index-row'));
+ expect(openDocument).toHaveBeenCalledWith('skill-index-doc');
+ });
+
+ it('shows delete recovery action for a managed skill bundle without SKILL.md', async () => {
+ const mutate = vi.fn().mockResolvedValue(undefined);
+ const data = [
+ createDocument({
+ documentId: 'skill-bundle-doc',
+ fileType: SKILL_BUNDLE_FILE_TYPE,
+ filename: 'youtube-comment-retrieval-workflow',
+ id: 'skill-bundle-row',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ title: 'YouTube Comment Retrieval Workflow',
+ }),
+ ];
+
+ render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={mutate} />);
+
+ const bundleNode = screen.getByTestId('tree-node-skill-bundle-row');
+ expect(bundleNode).toHaveAttribute('data-folder', 'true');
+ expect(bundleNode).toHaveAttribute('data-can-drag', 'false');
+ expect(bundleNode).toHaveAttribute('data-menu-count', '1');
+ expect(screen.queryByTestId('tree-menu-skill-bundle-row-rename')).not.toBeInTheDocument();
+ expect(screen.getByTestId('tree-menu-skill-bundle-row-delete')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByTestId('tree-menu-skill-bundle-row-delete'));
+
+ const [firstConfirmCall] = modalConfirm.mock.calls;
+ const [{ onOk }] = firstConfirmCall;
+ await onOk();
+
+ expect(removeDocumentMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ documentId: 'skill-bundle-doc',
+ id: 'skill-bundle-row',
+ topicId: undefined,
+ });
+ expect(mutate).toHaveBeenCalled();
+ expect(messageSuccess).toHaveBeenCalledWith('workingPanel.resources.deleteSuccess');
+ });
+});
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
index 1c3f1d5d745..5af5b6dcfe4 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
@@ -1,25 +1,33 @@
import type { MenuProps } from 'antd';
import { createStaticStyles } from 'antd-style';
import { Trash2Icon } from 'lucide-react';
-import { type CSSProperties, memo, useCallback, useMemo, useRef } from 'react';
+import type { CSSProperties } from 'react';
+import { memo, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useMatch, useNavigate } from 'react-router-dom';
import type { KeyedMutator } from 'swr';
-import {
- ExplorerTree,
- type ExplorerTreeCanDropCtx,
- type ExplorerTreeHandle,
- type ExplorerTreeNode,
+import type {
+ ExplorerTreeCanDropCtx,
+ ExplorerTreeHandle,
+ ExplorerTreeNode,
} from '@/features/ExplorerTree';
+import { ExplorerTree } from '@/features/ExplorerTree';
import { useChatStore } from '@/store/chat';
import DocumentExplorerToolbar from './DocumentExplorerToolbar';
import { useDocumentTreeOps } from './hooks/useDocumentTreeOps';
-import { type AgentDocumentItem, isFolderItem } from './types';
+import type { AgentDocumentItem } from './types';
+import {
+ isFolderItem,
+ isManagedSkillItem,
+ isOrphanSkillBundleItem,
+ isSkillIndexItem,
+} from './types';
import { canDropDocument } from './utils/canDrop';
const PAGE_ROUTE_PATTERN = '/agent/:aid/:topicId/page/:docId?';
+const SKILL_INDEX_FILENAME = 'SKILL.md';
const styles = createStaticStyles(({ css, cssVar }) => ({
tree: css`
@@ -86,7 +94,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
data: doc,
id: doc.id,
isFolder: isFolderItem(doc),
- name: doc.title || doc.filename || '',
+ name: isSkillIndexItem(doc) ? SKILL_INDEX_FILENAME : doc.title || doc.filename || '',
parentId: resolveParentRowId(doc.parentId),
})),
[documents, resolveParentRowId],
@@ -98,6 +106,11 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
return map;
}, [documents, resolveParentRowId]);
+ const isRecoverableSkillBundle = useCallback(
+ (doc: AgentDocumentItem) => isOrphanSkillBundleItem(doc, documents),
+ [documents],
+ );
+
const handleCreateFolder = useCallback(
(parentId: string | null) => ops.createFolder(parentId),
[ops],
@@ -145,12 +158,14 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
);
const canDrag = useCallback(
- (node: ExplorerTreeNode<AgentDocumentItem>) => node.data?.sourceType !== 'web',
+ (node: ExplorerTreeNode<AgentDocumentItem>) =>
+ !!node.data && node.data.sourceType !== 'web' && !isManagedSkillItem(node.data),
[],
);
const canRename = useCallback(
- (node: ExplorerTreeNode<AgentDocumentItem>) => node.data?.sourceType !== 'web',
+ (node: ExplorerTreeNode<AgentDocumentItem>) =>
+ !!node.data && node.data.sourceType !== 'web' && !isManagedSkillItem(node.data),
[],
);
@@ -161,12 +176,16 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
const getContextMenuItems = useCallback(
(node: ExplorerTreeNode<AgentDocumentItem>): MenuProps['items'] => {
+ if (node.data && isManagedSkillItem(node.data) && !isRecoverableSkillBundle(node.data)) {
+ return [];
+ }
+
const isFolder = !!node.isFolder;
const targetParentId = isFolder ? node.id : (node.parentId ?? null);
const items: NonNullable<MenuProps['items']> = [];
- if (isFolder) {
+ if (isFolder && (!node.data || !isManagedSkillItem(node.data))) {
items.push(
{
key: 'new-folder',
@@ -182,24 +201,25 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
);
}
- items.push(
- {
+ if (!node.data || !isManagedSkillItem(node.data)) {
+ items.push({
key: 'rename',
label: t('workingPanel.resources.tree.rename'),
onClick: () => startInlineRename(node.id),
- },
- {
- danger: true,
- icon: <Trash2Icon size={14} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: () => ops.deleteDocument(node.id),
- },
- );
+ });
+ }
+
+ items.push({
+ danger: true,
+ icon: <Trash2Icon size={14} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: () => ops.deleteDocument(node.id),
+ });
return items;
},
- [handleCreateDocument, handleCreateFolder, ops, startInlineRename, t],
+ [handleCreateDocument, handleCreateFolder, isRecoverableSkillBundle, ops, startInlineRename, t],
);
return (
diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
index 528a3bdd5a1..f8c50f5d010 100644
--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
@@ -1,4 +1,3 @@
-import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -6,7 +5,13 @@ import type { KeyedMutator } from 'swr';
import { agentDocumentService } from '@/services/agentDocument';
-import { type AgentDocumentItem, FOLDER_FILE_TYPE } from '../types';
+import type { AgentDocumentItem } from '../types';
+import {
+ FOLDER_FILE_TYPE,
+ isManagedSkillItem,
+ isProtectedManagedSkillItem,
+ isSkillBundleItem,
+} from '../types';
interface UseDocumentTreeOpsArgs {
agentId: string;
@@ -39,7 +44,7 @@ export const useDocumentTreeOps = ({
topicId,
}: UseDocumentTreeOpsArgs): DocumentTreeOps => {
const { t } = useTranslation(['chat', 'common']);
- const { message } = App.useApp();
+ const { message, modal } = App.useApp();
const dataRef = useRef(data);
dataRef.current = data;
@@ -77,6 +82,7 @@ export const useDocumentTreeOps = ({
if (parentRowId === null) return ROOT_PATH;
const parent = byRowId.get(parentRowId);
if (!parent) return null;
+ if (isManagedSkillItem(parent)) return null;
return buildItemPath(parent);
},
[byRowId, buildItemPath],
@@ -171,6 +177,7 @@ export const useDocumentTreeOps = ({
async (id: string, newName: string) => {
const target = dataRef.current.find((doc) => doc.id === id);
if (!target) return;
+ if (isManagedSkillItem(target)) return;
const trimmed = newName.trim();
if (!trimmed) {
@@ -218,12 +225,15 @@ export const useDocumentTreeOps = ({
}
const targetItem = targetId ? byRowId.get(targetId) : null;
+ if (targetItem && isSkillBundleItem(targetItem)) return;
+
const targetParentDocId = targetItem ? targetItem.documentId : null;
const moves: Array<{ fromPath: string; id: string; toPath: string }> = [];
for (const id of sourceIds) {
const node = sourceNodes.find((n) => n.data?.id === id)?.data;
if (!node) continue;
+ if (isManagedSkillItem(node)) return;
const fromPath = buildItemPath(node);
if (!fromPath) continue;
const toPath = joinPath(targetParentPath, node.filename);
@@ -270,10 +280,13 @@ export const useDocumentTreeOps = ({
(id: string) => {
const target = dataRef.current.find((doc) => doc.id === id);
if (!target) return;
+ if (isProtectedManagedSkillItem(target, dataRef.current)) return;
- confirmModal({
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ centered: true,
content: t('workingPanel.resources.deleteConfirm'),
- okButtonProps: { danger: true },
+ okButtonProps: { danger: true, type: 'primary' },
okText: t('delete', { ns: 'common' }),
onOk: async () => {
try {
@@ -307,7 +320,7 @@ export const useDocumentTreeOps = ({
title: t('workingPanel.resources.deleteTitle'),
});
},
- [agentId, buildItemPath, message, mutate, t, topicId],
+ [agentId, buildItemPath, message, modal, mutate, t, topicId],
);
return useMemo(
diff --git a/src/features/AgentDocumentsExplorer/index.ts b/src/features/AgentDocumentsExplorer/index.ts
index 085be76d122..843305b99fb 100644
--- a/src/features/AgentDocumentsExplorer/index.ts
+++ b/src/features/AgentDocumentsExplorer/index.ts
@@ -1,2 +1,15 @@
export { default as DocumentExplorerTree } from './DocumentExplorerTree';
export type { AgentDocumentItem } from './types';
+export {
+ AGENT_SKILL_TEMPLATE_ID,
+ FOLDER_FILE_TYPE,
+ hasSkillIndexChild,
+ isFolderItem,
+ isManagedSkillItem,
+ isOrphanSkillBundleItem,
+ isProtectedManagedSkillItem,
+ isSkillBundleItem,
+ isSkillIndexItem,
+ SKILL_BUNDLE_FILE_TYPE,
+ SKILL_INDEX_FILE_TYPE,
+} from './types';
diff --git a/src/features/AgentDocumentsExplorer/types.test.ts b/src/features/AgentDocumentsExplorer/types.test.ts
new file mode 100644
index 00000000000..d234ca24158
--- /dev/null
+++ b/src/features/AgentDocumentsExplorer/types.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import type { AgentDocumentItem } from './types';
+import {
+ AGENT_SKILL_TEMPLATE_ID,
+ FOLDER_FILE_TYPE,
+ hasSkillIndexChild,
+ isFolderItem,
+ isManagedSkillItem,
+ isOrphanSkillBundleItem,
+ isProtectedManagedSkillItem,
+ isSkillBundleItem,
+ isSkillIndexItem,
+ SKILL_BUNDLE_FILE_TYPE,
+ SKILL_INDEX_FILE_TYPE,
+} from './types';
+
+const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentItem =>
+ ({
+ accessPublic: 0,
+ accessSelf: 0,
+ accessShared: 0,
+ agentId: 'agent-1',
+ content: '',
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ deletedAt: null,
+ deletedByAgentId: null,
+ deletedByUserId: null,
+ deleteReason: null,
+ description: null,
+ documentId: 'doc-1',
+ editorData: null,
+ filename: 'document.md',
+ fileType: 'custom/document',
+ id: 'agent-doc-1',
+ loadRules: {},
+ metadata: null,
+ parentId: null,
+ policy: null,
+ policyLoad: 'disabled',
+ policyLoadFormat: 'raw',
+ policyLoadPosition: 'before-first-user',
+ policyLoadRule: 'always',
+ source: null,
+ sourceType: 'file',
+ templateId: null,
+ title: 'Document',
+ updatedAt: new Date('2026-05-09T00:00:00Z'),
+ userId: 'user-1',
+ ...overrides,
+ }) as AgentDocumentItem;
+
+describe('AgentDocumentsExplorer types', () => {
+ it('treats managed skill bundles as folders', () => {
+ const bundle = createDocument({
+ fileType: SKILL_BUNDLE_FILE_TYPE,
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ });
+ const index = createDocument({
+ fileType: SKILL_INDEX_FILE_TYPE,
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ });
+ const folder = createDocument({ fileType: FOLDER_FILE_TYPE });
+
+ expect(isSkillBundleItem(bundle)).toBe(true);
+ expect(isFolderItem(bundle)).toBe(true);
+ expect(isSkillIndexItem(index)).toBe(true);
+ expect(isFolderItem(index)).toBe(false);
+ expect(isFolderItem(folder)).toBe(true);
+ });
+
+ it('detects managed skill items by template id or file type', () => {
+ expect(isManagedSkillItem(createDocument({ templateId: AGENT_SKILL_TEMPLATE_ID }))).toBe(true);
+ expect(isManagedSkillItem(createDocument({ fileType: SKILL_INDEX_FILE_TYPE }))).toBe(true);
+ expect(isManagedSkillItem(createDocument({ fileType: 'custom/document' }))).toBe(false);
+ });
+
+ it('treats skill bundles without SKILL.md as recoverable orphan bundles', () => {
+ const bundle = createDocument({
+ documentId: 'bundle-doc',
+ fileType: SKILL_BUNDLE_FILE_TYPE,
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ });
+ const index = createDocument({
+ documentId: 'index-doc',
+ fileType: SKILL_INDEX_FILE_TYPE,
+ parentId: 'bundle-doc',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ });
+
+ expect(hasSkillIndexChild([bundle, index], bundle)).toBe(true);
+ expect(isOrphanSkillBundleItem(bundle, [bundle, index])).toBe(false);
+ expect(isProtectedManagedSkillItem(bundle, [bundle, index])).toBe(true);
+
+ expect(hasSkillIndexChild([bundle], bundle)).toBe(false);
+ expect(isOrphanSkillBundleItem(bundle, [bundle])).toBe(true);
+ expect(isProtectedManagedSkillItem(bundle, [bundle])).toBe(false);
+ });
+});
diff --git a/src/features/AgentDocumentsExplorer/types.ts b/src/features/AgentDocumentsExplorer/types.ts
index cc787fa3c28..7d4314ec91d 100644
--- a/src/features/AgentDocumentsExplorer/types.ts
+++ b/src/features/AgentDocumentsExplorer/types.ts
@@ -9,5 +9,37 @@ export const PENDING_ID_PREFIX = 'pending:';
export const isPendingId = (id: string): boolean => id.startsWith(PENDING_ID_PREFIX);
export const FOLDER_FILE_TYPE = 'custom/folder';
+export const SKILL_BUNDLE_FILE_TYPE = 'skills/bundle';
+export const SKILL_INDEX_FILE_TYPE = 'skills/index';
+export const AGENT_SKILL_TEMPLATE_ID = 'agent-skill';
-export const isFolderItem = (doc: AgentDocumentItem): boolean => doc.fileType === FOLDER_FILE_TYPE;
+type AgentDocumentKindFields = Pick<AgentDocumentItem, 'fileType' | 'templateId'>;
+type AgentDocumentSkillBundleFields = Pick<AgentDocumentItem, 'documentId' | 'fileType'>;
+type AgentDocumentSkillChildFields = Pick<AgentDocumentItem, 'fileType' | 'parentId'>;
+
+export const isSkillBundleItem = (doc: Pick<AgentDocumentItem, 'fileType'>): boolean =>
+ doc.fileType === SKILL_BUNDLE_FILE_TYPE;
+
+export const isSkillIndexItem = (doc: Pick<AgentDocumentItem, 'fileType'>): boolean =>
+ doc.fileType === SKILL_INDEX_FILE_TYPE;
+
+export const isManagedSkillItem = (doc: AgentDocumentKindFields): boolean =>
+ doc.templateId === AGENT_SKILL_TEMPLATE_ID || !!doc.fileType?.startsWith('skills/');
+
+export const hasSkillIndexChild = (
+ documents: AgentDocumentSkillChildFields[],
+ bundle: Pick<AgentDocumentItem, 'documentId'>,
+): boolean => documents.some((doc) => isSkillIndexItem(doc) && doc.parentId === bundle.documentId);
+
+export const isOrphanSkillBundleItem = (
+ doc: AgentDocumentSkillBundleFields,
+ documents: AgentDocumentSkillChildFields[],
+): boolean => isSkillBundleItem(doc) && !hasSkillIndexChild(documents, doc);
+
+export const isProtectedManagedSkillItem = (
+ doc: AgentDocumentKindFields & Pick<AgentDocumentItem, 'documentId'>,
+ documents: AgentDocumentSkillChildFields[],
+): boolean => isManagedSkillItem(doc) && !isOrphanSkillBundleItem(doc, documents);
+
+export const isFolderItem = (doc: AgentDocumentItem): boolean =>
+ doc.fileType === FOLDER_FILE_TYPE || isSkillBundleItem(doc);
diff --git a/src/features/AgentDocumentsExplorer/utils/canDrop.test.ts b/src/features/AgentDocumentsExplorer/utils/canDrop.test.ts
new file mode 100644
index 00000000000..b5db23c7e00
--- /dev/null
+++ b/src/features/AgentDocumentsExplorer/utils/canDrop.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ExplorerTreeCanDropCtx, ExplorerTreeNode } from '@/features/ExplorerTree';
+
+import type { AgentDocumentItem } from '../types';
+import {
+ AGENT_SKILL_TEMPLATE_ID,
+ FOLDER_FILE_TYPE,
+ SKILL_BUNDLE_FILE_TYPE,
+ SKILL_INDEX_FILE_TYPE,
+} from '../types';
+import { canDropDocument } from './canDrop';
+
+const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentItem =>
+ ({
+ accessPublic: 0,
+ accessSelf: 0,
+ accessShared: 0,
+ agentId: 'agent-1',
+ content: '',
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ deletedAt: null,
+ deletedByAgentId: null,
+ deletedByUserId: null,
+ deleteReason: null,
+ description: null,
+ documentId: 'doc-1',
+ editorData: null,
+ filename: 'document.md',
+ fileType: 'custom/document',
+ id: 'agent-doc-1',
+ loadRules: {},
+ metadata: null,
+ parentId: null,
+ policy: null,
+ policyLoad: 'disabled',
+ policyLoadFormat: 'raw',
+ policyLoadPosition: 'before-first-user',
+ policyLoadRule: 'always',
+ source: null,
+ sourceType: 'file',
+ templateId: null,
+ title: 'Document',
+ updatedAt: new Date('2026-05-09T00:00:00Z'),
+ userId: 'user-1',
+ ...overrides,
+ }) as AgentDocumentItem;
+
+const createNode = (
+ id: string,
+ data: AgentDocumentItem,
+ options?: Pick<ExplorerTreeNode<AgentDocumentItem>, 'isFolder' | 'parentId'>,
+): ExplorerTreeNode<AgentDocumentItem> => ({
+ data,
+ id,
+ isFolder: options?.isFolder,
+ name: data.title,
+ parentId: options?.parentId ?? null,
+});
+
+const createContext = (
+ sourceNode: ExplorerTreeNode<AgentDocumentItem>,
+ targetNode: ExplorerTreeNode<AgentDocumentItem> | null,
+): ExplorerTreeCanDropCtx<AgentDocumentItem> => ({
+ sourceIds: [sourceNode.id],
+ sourceNodes: [sourceNode],
+ targetId: targetNode?.id ?? null,
+ targetNode,
+});
+
+describe('canDropDocument', () => {
+ it('allows ordinary documents to move into ordinary folders', () => {
+ const source = createNode('doc-row', createDocument({ id: 'doc-row' }));
+ const target = createNode(
+ 'folder-row',
+ createDocument({ fileType: FOLDER_FILE_TYPE, id: 'folder-row', title: 'Folder' }),
+ { isFolder: true },
+ );
+
+ expect(canDropDocument({ ctx: createContext(source, target), parentMap: new Map() })).toBe(
+ true,
+ );
+ });
+
+ it('rejects drops into managed skill bundles', () => {
+ const source = createNode('doc-row', createDocument({ id: 'doc-row' }));
+ const target = createNode(
+ 'skill-row',
+ createDocument({
+ documentId: 'skill-bundle-doc',
+ fileType: SKILL_BUNDLE_FILE_TYPE,
+ id: 'skill-row',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ title: 'Research Skill',
+ }),
+ { isFolder: true },
+ );
+
+ expect(canDropDocument({ ctx: createContext(source, target), parentMap: new Map() })).toBe(
+ false,
+ );
+ });
+
+ it('rejects dragging managed skill nodes', () => {
+ const source = createNode(
+ 'skill-index-row',
+ createDocument({
+ fileType: SKILL_INDEX_FILE_TYPE,
+ id: 'skill-index-row',
+ templateId: AGENT_SKILL_TEMPLATE_ID,
+ title: 'SKILL.md',
+ }),
+ );
+ const target = createNode(
+ 'folder-row',
+ createDocument({ fileType: FOLDER_FILE_TYPE, id: 'folder-row', title: 'Folder' }),
+ { isFolder: true },
+ );
+
+ expect(canDropDocument({ ctx: createContext(source, target), parentMap: new Map() })).toBe(
+ false,
+ );
+ });
+});
diff --git a/src/features/AgentDocumentsExplorer/utils/canDrop.ts b/src/features/AgentDocumentsExplorer/utils/canDrop.ts
index e1dc41e3554..ff21c6d357f 100644
--- a/src/features/AgentDocumentsExplorer/utils/canDrop.ts
+++ b/src/features/AgentDocumentsExplorer/utils/canDrop.ts
@@ -1,6 +1,7 @@
import type { ExplorerTreeCanDropCtx } from '@/features/ExplorerTree';
-import { type AgentDocumentItem, isPendingId } from '../types';
+import type { AgentDocumentItem } from '../types';
+import { isManagedSkillItem, isPendingId, isSkillBundleItem } from '../types';
interface CanDropArgs {
ctx: ExplorerTreeCanDropCtx<AgentDocumentItem>;
@@ -26,6 +27,7 @@ export const canDropDocument = ({ ctx, parentMap }: CanDropArgs): boolean => {
// Drop target must be a folder or root
if (targetNode && !targetNode.isFolder) return false;
+ if (targetNode?.data && isSkillBundleItem(targetNode.data)) return false;
// Pending targets have no server-side row yet — refuse the drop instead of
// surfacing an error after the fact.
@@ -48,6 +50,7 @@ export const canDropDocument = ({ ctx, parentMap }: CanDropArgs): boolean => {
// Web docs cannot move (not part of tree management)
const data = node.data;
if (data && data.sourceType === 'web') return false;
+ if (data && isManagedSkillItem(data)) return false;
}
return true;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
index 313566549de..c59f2805ed2 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
@@ -159,6 +159,231 @@ describe('AgentDocumentsGroup', () => {
expect(openDocument).toHaveBeenCalledWith('doc-content-1');
});
+ it('opens a managed skill bundle card through its SKILL.md document and hides the duplicate file', () => {
+ useClientDataSWR.mockReturnValue({
+ data: [
+ {
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ description: 'Use for YouTube comments',
+ documentId: 'skill-bundle-doc',
+ fileType: 'skills/bundle',
+ filename: 'youtube-comment-retrieval-workflow',
+ id: 'skill-bundle-row',
+ parentId: null,
+ sourceType: 'agent-signal',
+ templateId: 'agent-skill',
+ title: 'YouTube Comment Retrieval Workflow',
+ updatedAt: new Date(),
+ },
+ {
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ description: 'Use for YouTube comments',
+ documentId: 'skill-index-doc',
+ fileType: 'skills/index',
+ filename: 'SKILL.md',
+ id: 'skill-index-row',
+ parentId: 'skill-bundle-doc',
+ sourceType: 'agent-signal',
+ templateId: 'agent-skill',
+ title: 'SKILL.md',
+ updatedAt: new Date(),
+ },
+ ],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ const bundle = screen.getByText('YouTube Comment Retrieval Workflow');
+ expect(bundle).toBeInTheDocument();
+ expect(screen.queryByText('SKILL.md')).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('delete')).not.toBeInTheDocument();
+
+ fireEvent.click(bundle);
+
+ expect(openDocument).toHaveBeenCalledWith('skill-index-doc');
+ expect(openDocument).not.toHaveBeenCalledWith('skill-bundle-doc');
+ });
+
+ it('renders the empty state when only hidden managed skill index documents are available', () => {
+ useClientDataSWR.mockReturnValue({
+ data: [
+ {
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ description: 'Use for YouTube comments',
+ documentId: 'skill-index-doc',
+ fileType: 'skills/index',
+ filename: 'SKILL.md',
+ id: 'skill-index-row',
+ parentId: 'missing-skill-bundle-doc',
+ sourceType: 'agent-signal',
+ templateId: 'agent-skill',
+ title: 'SKILL.md',
+ updatedAt: new Date(),
+ },
+ ],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ expect(screen.getByText('No agent documents yet')).toBeInTheDocument();
+ expect(screen.queryByText('SKILL.md')).not.toBeInTheDocument();
+ });
+
+ it('navigates to the page route when opening from a topic page', () => {
+ useMatchMock.mockReturnValue({
+ params: { aid: 'agent-1', topicId: 'topic-1' },
+ });
+ useClientDataSWR.mockReturnValue({
+ data: [
+ {
+ createdAt: new Date('2026-04-16T00:00:00Z'),
+ description: 'File doc',
+ documentId: 'doc-content-1',
+ filename: 'brief.md',
+ id: 'doc-1',
+ sourceType: 'file',
+ templateId: 'claw',
+ title: 'Brief',
+ updatedAt: null,
+ },
+ ],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ fireEvent.click(screen.getByText('Brief'));
+
+ expect(useNavigateMock).toHaveBeenCalledWith('/agent/agent-1/topic-1/page/doc-content-1');
+ expect(openDocument).not.toHaveBeenCalled();
+ });
+
+ it('allows opening and deleting an orphan managed skill bundle as a recovery path', async () => {
+ const mutate = vi.fn().mockResolvedValue(undefined);
+ useClientDataSWR.mockReturnValue({
+ data: [
+ {
+ createdAt: new Date('2026-05-09T00:00:00Z'),
+ description: 'Missing SKILL.md',
+ documentId: 'skill-bundle-doc',
+ fileType: 'skills/bundle',
+ filename: 'youtube-comment-retrieval-workflow',
+ id: 'skill-bundle-row',
+ parentId: null,
+ sourceType: 'agent-signal',
+ templateId: 'agent-skill',
+ title: 'YouTube Comment Retrieval Workflow',
+ updatedAt: new Date(),
+ },
+ ],
+ error: undefined,
+ isLoading: false,
+ mutate,
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ const bundle = screen.getByText('YouTube Comment Retrieval Workflow');
+ expect(screen.getByLabelText('delete')).toBeInTheDocument();
+
+ fireEvent.click(bundle);
+ expect(openDocument).toHaveBeenCalledWith('skill-bundle-doc');
+
+ fireEvent.click(screen.getByLabelText('delete'));
+
+ const [firstConfirmCall] = modalConfirm.mock.calls;
+ const [{ onOk }] = firstConfirmCall;
+ await onOk();
+
+ expect(removeDocumentMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ documentId: 'skill-bundle-doc',
+ id: 'skill-bundle-row',
+ topicId: undefined,
+ });
+ expect(mutate).toHaveBeenCalled();
+ });
+
+ it('shows an error message when deleting a document fails', async () => {
+ useClientDataSWR.mockReturnValue({
+ data: [
+ {
+ createdAt: new Date('2026-04-16T00:00:00Z'),
+ description: 'File doc',
+ documentId: 'doc-content-1',
+ filename: 'brief.md',
+ id: 'doc-1',
+ sourceType: 'file',
+ templateId: 'claw',
+ title: 'Brief',
+ updatedAt: new Date(),
+ },
+ ],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+ removeDocumentMock.mockRejectedValue(new Error('delete failed'));
+
+ render(<AgentDocumentsGroup />);
+
+ fireEvent.click(screen.getByLabelText('delete'));
+
+ const [firstConfirmCall] = modalConfirm.mock.calls;
+ const [{ onOk }] = firstConfirmCall;
+ await onOk();
+
+ expect(messageError).toHaveBeenCalledWith('delete failed');
+ });
+
+ it('renders grouped cards in tree view mode', () => {
+ useClientDataSWR.mockReturnValue({
+ data: [
+ {
+ createdAt: new Date('2026-04-16T00:00:00Z'),
+ description: 'File doc',
+ documentId: 'doc-content-1',
+ filename: 'brief.md',
+ id: 'doc-1',
+ sourceType: 'file',
+ templateId: 'claw',
+ title: 'Brief',
+ updatedAt: new Date(),
+ },
+ {
+ createdAt: new Date('2026-04-16T00:00:00Z'),
+ description: 'Crawled page',
+ documentId: 'doc-content-2',
+ filename: 'example.com',
+ id: 'doc-2',
+ sourceType: 'web',
+ templateId: null,
+ title: 'Example',
+ updatedAt: null,
+ },
+ ],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup viewMode="tree" />);
+
+ expect(screen.getByText('Documents')).toBeInTheDocument();
+ expect(screen.getByText('Web')).toBeInTheDocument();
+ expect(screen.getByText('Brief')).toBeInTheDocument();
+ expect(screen.getByText('Example')).toBeInTheDocument();
+ expect(screen.queryByTestId('document-explorer-tree')).not.toBeInTheDocument();
+ });
+
it('filters documents by source type via segmented tabs', () => {
useClientDataSWR.mockReturnValue({
data: [
@@ -239,6 +464,16 @@ describe('AgentDocumentsGroup', () => {
fireEvent.click(screen.getByLabelText('delete'));
+ expect(modalConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelText: 'cancel',
+ centered: true,
+ okButtonProps: { danger: true, type: 'primary' },
+ okText: 'delete',
+ title: 'workingPanel.resources.deleteTitle',
+ }),
+ );
+
const [firstConfirmCall] = modalConfirm.mock.calls;
const [{ onOk }] = firstConfirmCall;
await onOk();
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index cad7314cf39..4f372a8d1cc 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -3,12 +3,20 @@ import { App, Spin } from 'antd';
import { createStaticStyles, cx } from 'antd-style';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
-import { FileTextIcon, GlobeIcon, type LucideIcon, Trash2Icon } from 'lucide-react';
-import { type CSSProperties, memo, type MouseEvent, useMemo, useState } from 'react';
+import type { LucideIcon } from 'lucide-react';
+import { FileTextIcon, FolderIcon, GlobeIcon, Trash2Icon } from 'lucide-react';
+import type { CSSProperties, MouseEvent } from 'react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useMatch, useNavigate } from 'react-router-dom';
import { DocumentExplorerTree } from '@/features/AgentDocumentsExplorer';
+import {
+ isManagedSkillItem,
+ isOrphanSkillBundleItem,
+ isSkillBundleItem,
+ isSkillIndexItem,
+} from '@/features/AgentDocumentsExplorer/types';
import { useClientDataSWR } from '@/libs/swr';
import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
import { useAgentStore } from '@/store/agent';
@@ -100,107 +108,120 @@ type AgentDocumentListItem = Awaited<ReturnType<typeof agentDocumentService.getD
interface DocumentItemProps {
agentId: string;
document: AgentDocumentListItem;
+ hideDelete?: boolean;
mutate: () => Promise<unknown>;
+ openDocumentId?: string;
}
-const DocumentItem = memo<DocumentItemProps>(({ agentId, document, mutate }) => {
- const { t } = useTranslation(['chat', 'common']);
- const { message, modal } = App.useApp();
- const [deleting, setDeleting] = useState(false);
- const openDocument = useChatStore((s) => s.openDocument);
- const closeDocument = useChatStore((s) => s.closeDocument);
- const portalDocumentId = useChatStore(chatPortalSelectors.portalDocumentId);
- const navigate = useNavigate();
- const pageMatch = useMatch(PAGE_ROUTE_PATTERN);
-
- const title = document.title || document.filename || '';
- const description = document.description ?? undefined;
- const isWeb = document.sourceType === 'web';
- const IconComponent: LucideIcon = isWeb ? GlobeIcon : FileTextIcon;
- const updatedAtLabel = document.updatedAt
- ? t('workingPanel.resources.updatedAt', {
- ns: 'chat',
- time: dayjs(document.updatedAt).fromNow(),
- })
- : null;
-
- const activeDocumentId = pageMatch ? pageMatch.params.docId : portalDocumentId;
- const isActive = activeDocumentId === document.documentId;
-
- const handleOpen = () => {
- if (!document.documentId) return;
- if (pageMatch?.params.aid && pageMatch.params.topicId) {
- navigate(
- `/agent/${pageMatch.params.aid}/${pageMatch.params.topicId}/page/${document.documentId}`,
- );
- return;
- }
- openDocument(document.documentId);
- };
-
- const handleDelete = (e: MouseEvent) => {
- e.stopPropagation();
- modal.confirm({
- centered: true,
- okButtonProps: { danger: true },
- onOk: async () => {
- setDeleting(true);
- try {
- if (isActive) closeDocument();
- await agentDocumentService.removeDocument({
- agentId,
- documentId: document.documentId,
- id: document.id,
- topicId: pageMatch?.params.topicId,
- });
- await mutate();
- message.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));
- } catch (error) {
- message.error(
- error instanceof Error
- ? error.message
- : t('workingPanel.resources.deleteError', { ns: 'chat' }),
- );
- } finally {
- setDeleting(false);
- }
- },
- title: t('workingPanel.resources.deleteTitle', { ns: 'chat' }),
- });
- };
+const DocumentItem = memo<DocumentItemProps>(
+ ({ agentId, document, hideDelete = false, mutate, openDocumentId }) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const { message, modal } = App.useApp();
+ const [deleting, setDeleting] = useState(false);
+ const openDocument = useChatStore((s) => s.openDocument);
+ const closeDocument = useChatStore((s) => s.closeDocument);
+ const portalDocumentId = useChatStore(chatPortalSelectors.portalDocumentId);
+ const navigate = useNavigate();
+ const pageMatch = useMatch(PAGE_ROUTE_PATTERN);
+
+ const title = document.title || document.filename || '';
+ const description = document.description ?? undefined;
+ const isWeb = document.sourceType === 'web';
+ const isSkillBundle = isSkillBundleItem(document);
+ const targetDocumentId = isSkillBundle
+ ? (openDocumentId ?? document.documentId)
+ : document.documentId;
+ const IconComponent: LucideIcon = isWeb ? GlobeIcon : isSkillBundle ? FolderIcon : FileTextIcon;
+ const updatedAtLabel = document.updatedAt
+ ? t('workingPanel.resources.updatedAt', {
+ ns: 'chat',
+ time: dayjs(document.updatedAt).fromNow(),
+ })
+ : null;
+
+ const activeDocumentId = pageMatch ? pageMatch.params.docId : portalDocumentId;
+ const isActive = activeDocumentId === targetDocumentId;
+
+ const handleOpen = () => {
+ if (!targetDocumentId) return;
+ if (pageMatch?.params.aid && pageMatch.params.topicId) {
+ navigate(
+ `/agent/${pageMatch.params.aid}/${pageMatch.params.topicId}/page/${targetDocumentId}`,
+ );
+ return;
+ }
+ openDocument(targetDocumentId);
+ };
+
+ const handleDelete = (e: MouseEvent) => {
+ e.stopPropagation();
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ centered: true,
+ content: t('workingPanel.resources.deleteConfirm', { ns: 'chat' }),
+ okButtonProps: { danger: true, type: 'primary' },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ setDeleting(true);
+ try {
+ if (isActive) closeDocument();
+ await agentDocumentService.removeDocument({
+ agentId,
+ documentId: document.documentId,
+ id: document.id,
+ topicId: pageMatch?.params.topicId,
+ });
+ await mutate();
+ message.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));
+ } catch (error) {
+ message.error(
+ error instanceof Error
+ ? error.message
+ : t('workingPanel.resources.deleteError', { ns: 'chat' }),
+ );
+ } finally {
+ setDeleting(false);
+ }
+ },
+ title: t('workingPanel.resources.deleteTitle', { ns: 'chat' }),
+ });
+ };
- return (
- <Flexbox
- horizontal
- align={'flex-start'}
- className={`${styles.container} ${isActive ? styles.containerActive : ''}`}
- gap={8}
- onClick={handleOpen}
- >
- <IconComponent size={16} style={{ flexShrink: 0, marginTop: 2 }} />
- <Flexbox gap={4} style={{ flex: 1, minWidth: 0 }}>
- <Flexbox horizontal align={'center'} distribution={'space-between'}>
- <Text ellipsis className={styles.title}>
- {title}
- </Text>
- <ActionIcon
- icon={Trash2Icon}
- loading={deleting}
- size={'small'}
- title={t('delete', { ns: 'common' })}
- onClick={handleDelete}
- />
+ return (
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={`${styles.container} ${isActive ? styles.containerActive : ''}`}
+ gap={8}
+ onClick={handleOpen}
+ >
+ <IconComponent size={16} style={{ flexShrink: 0, marginTop: 2 }} />
+ <Flexbox gap={4} style={{ flex: 1, minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} distribution={'space-between'}>
+ <Text ellipsis className={styles.title}>
+ {title}
+ </Text>
+ {!hideDelete && (
+ <ActionIcon
+ icon={Trash2Icon}
+ loading={deleting}
+ size={'small'}
+ title={t('delete', { ns: 'common' })}
+ onClick={handleDelete}
+ />
+ )}
+ </Flexbox>
+ {description && (
+ <Text className={styles.description} ellipsis={{ rows: 2 }}>
+ {description}
+ </Text>
+ )}
+ {updatedAtLabel && <Text className={styles.meta}>{updatedAtLabel}</Text>}
</Flexbox>
- {description && (
- <Text className={styles.description} ellipsis={{ rows: 2 }}>
- {description}
- </Text>
- )}
- {updatedAtLabel && <Text className={styles.meta}>{updatedAtLabel}</Text>}
</Flexbox>
- </Flexbox>
- );
-});
+ );
+ },
+);
DocumentItem.displayName = 'AgentDocumentsGroupItem';
@@ -229,8 +250,31 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, viewMode =
return data;
}, [data, filter]);
+ const visibleFlatData = useMemo(
+ () => filteredData.filter((doc) => !isSkillIndexItem(doc)),
+ [filteredData],
+ );
+
+ const skillIndexDocumentIdByBundleDocumentId = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const doc of data) {
+ if (isSkillIndexItem(doc) && doc.parentId) {
+ map.set(doc.parentId, doc.documentId);
+ }
+ }
+ return map;
+ }, [data]);
+
+ const getOpenDocumentId = (document: AgentDocumentListItem): string | undefined =>
+ isSkillBundleItem(document)
+ ? (skillIndexDocumentIdByBundleDocumentId.get(document.documentId) ?? document.documentId)
+ : document.documentId;
+
+ const shouldHideDelete = (document: AgentDocumentListItem): boolean =>
+ isManagedSkillItem(document) && !isOrphanSkillBundleItem(document, data);
+
const treeGroups = useMemo(() => {
- const docs = data.filter((doc) => doc.sourceType !== 'web');
+ const docs = data.filter((doc) => doc.sourceType !== 'web' && !isSkillIndexItem(doc));
const webs = data.filter((doc) => doc.sourceType === 'web');
return (
[
@@ -278,7 +322,14 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, viewMode =
</Text>
<Flexbox gap={8}>
{group.items.map((doc) => (
- <DocumentItem agentId={agentId} document={doc} key={doc.id} mutate={mutate} />
+ <DocumentItem
+ agentId={agentId}
+ document={doc}
+ hideDelete={shouldHideDelete(doc)}
+ key={doc.id}
+ mutate={mutate}
+ openDocumentId={getOpenDocumentId(doc)}
+ />
))}
</Flexbox>
</Flexbox>
@@ -314,7 +365,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, viewMode =
style={{ height: '100%' }}
/>
</Flexbox>
- ) : filteredData.length === 0 ? (
+ ) : visibleFlatData.length === 0 ? (
<Center flex={1} gap={8} paddingBlock={24}>
<Empty
description={t('workingPanel.resources.empty')}
@@ -323,8 +374,15 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, viewMode =
</Center>
) : (
<Flexbox gap={8}>
- {filteredData.map((doc) => (
- <DocumentItem agentId={agentId} document={doc} key={doc.id} mutate={mutate} />
+ {visibleFlatData.map((doc) => (
+ <DocumentItem
+ agentId={agentId}
+ document={doc}
+ hideDelete={shouldHideDelete(doc)}
+ key={doc.id}
+ mutate={mutate}
+ openDocumentId={getOpenDocumentId(doc)}
+ />
))}
</Flexbox>
)}
diff --git a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts
index b6ac4b713d8..422c6a6ec70 100644
--- a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts
+++ b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts
@@ -9,6 +9,8 @@ import { uuid } from '@/utils/uuid';
import { resolveClientRuntimeCompleteFeedbackSource } from '../clientRuntimeComplete';
+const DB_HYDRATION_TEST_TIMEOUT = 10_000;
+
const createCompleteSource = (
payload: Partial<
AgentSignalSourceEvent<typeof AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete>['payload']
@@ -34,63 +36,67 @@ describe('resolveClientRuntimeCompleteFeedbackSource', () => {
* @example
* client.runtime.complete({ assistantMessageId }) hydrates a trusted parent user source with an assistant context boundary.
*/
- it('hydrates an assistant completion into the parent agent user message source', async () => {
- const db = await getTestDB();
- const userId = `user_${uuid()}`;
- const topicId = `topic_${uuid()}`;
- const parentMessageId = `msg_${uuid()}`;
- const assistantMessageId = `msg_${uuid()}`;
-
- await db.insert(users).values({ id: userId });
- await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });
- await db.insert(messages).values({
- content: 'Please remember this workflow.',
- id: parentMessageId,
- role: 'user',
- topicId,
- userId,
- });
- await db.insert(messages).values({
- content: 'I can remember that.',
- id: assistantMessageId,
- parentId: parentMessageId,
- role: 'assistant',
- topicId,
- userId,
- });
+ it(
+ 'hydrates an assistant completion into the parent agent user message source',
+ async () => {
+ const db = await getTestDB();
+ const userId = `user_${uuid()}`;
+ const topicId = `topic_${uuid()}`;
+ const parentMessageId = `msg_${uuid()}`;
+ const assistantMessageId = `msg_${uuid()}`;
+
+ await db.insert(users).values({ id: userId });
+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });
+ await db.insert(messages).values({
+ content: 'Please remember this workflow.',
+ id: parentMessageId,
+ role: 'user',
+ topicId,
+ userId,
+ });
+ await db.insert(messages).values({
+ content: 'I can remember that.',
+ id: assistantMessageId,
+ parentId: parentMessageId,
+ role: 'assistant',
+ topicId,
+ userId,
+ });
- const result = await resolveClientRuntimeCompleteFeedbackSource(
- createCompleteSource({
- assistantMessageId,
- operationId: 'op-success',
- serializedContext: 'client context must not be trusted',
- topicId: 'client-topic',
- }),
- { db, userId },
- );
+ const result = await resolveClientRuntimeCompleteFeedbackSource(
+ createCompleteSource({
+ assistantMessageId,
+ operationId: 'op-success',
+ serializedContext: 'client context must not be trusted',
+ topicId: 'client-topic',
+ }),
+ { db, userId },
+ );
- expect(result.diagnostic).toEqual({
- kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
- status: 'resolved',
- });
- expect(result.contextBoundaryMessageId).toBe(assistantMessageId);
- expect(result.contextEndAt).toBeInstanceOf(Date);
- expect(result.source).toEqual({
- payload: {
- agentId: 'client-agent',
- message: 'Please remember this workflow.',
- messageId: parentMessageId,
- threadId: 'client-thread',
- topicId,
- trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
- },
- scopeKey: `topic:${topicId}`,
- sourceId: `${assistantMessageId}:completion:${parentMessageId}`,
- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,
- timestamp: 123,
- });
- expect(result.source?.payload.serializedContext).toBeUndefined();
- });
+ expect(result.diagnostic).toEqual({
+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
+ status: 'resolved',
+ });
+ expect(result.contextBoundaryMessageId).toBe(assistantMessageId);
+ expect(result.contextEndAt).toBeInstanceOf(Date);
+ expect(result.source).toEqual({
+ payload: {
+ agentId: 'client-agent',
+ message: 'Please remember this workflow.',
+ messageId: parentMessageId,
+ threadId: 'client-thread',
+ topicId,
+ trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
+ },
+ scopeKey: `topic:${topicId}`,
+ sourceId: `${assistantMessageId}:completion:${parentMessageId}`,
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,
+ timestamp: 123,
+ });
+ expect(result.source?.payload.serializedContext).toBeUndefined();
+ },
+ DB_HYDRATION_TEST_TIMEOUT,
+ );
/**
* @example