🤯 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(agent-documents): harden document explorer tree and skill index titles (#15998)
Arvin Xu68ef8a1cc691
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b4e6f75414c..cd5d0bd2020 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1043,6 +1043,7 @@"workingPanel.resources.deleteTitle": "Delete document?","workingPanel.resources.deleteTitleMulti": "Delete {{count}} items?","workingPanel.resources.empty": "No webpages. Webpages crawled in this agent will show up here.",+ "workingPanel.resources.emptyDocuments": "No documents yet. Create one with the + above.","workingPanel.resources.error": "Failed to load resources","workingPanel.resources.filter.documents": "Documents","workingPanel.resources.filter.skills": "Skills",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 96f6c48b918..a6a49355d5d 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1043,6 +1043,7 @@"workingPanel.resources.deleteTitle": "删除该文档?","workingPanel.resources.deleteTitleMulti": "删除 {{count}} 项?","workingPanel.resources.empty": "暂无网页。本智能体抓取的网页将显示在这里。",+ "workingPanel.resources.emptyDocuments": "暂无文档,点击上方 + 新建文档。","workingPanel.resources.error": "资源加载失败","workingPanel.resources.filter.documents": "文档","workingPanel.resources.filter.skills": "技能",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 900d9a3aebb..da7cee81ce0 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1108,6 +1108,7 @@ export default {'workingPanel.resources.deleteTitle': 'Delete document?','workingPanel.resources.deleteTitleMulti': 'Delete {{count}} items?','workingPanel.resources.empty': 'No webpages. Webpages crawled in this agent will show up here.',+ 'workingPanel.resources.emptyDocuments': 'No documents yet. Create one with the + above.','workingPanel.resources.error': 'Failed to load resources','workingPanel.resources.filter.documents': 'Documents','workingPanel.resources.filter.skills': 'Skills',diff --git a/src/features/AgentDocumentPage/RightPanel/index.tsx b/src/features/AgentDocumentPage/RightPanel/index.tsxindex 853546bd5aa..1ce0426ed89 100644--- a/src/features/AgentDocumentPage/RightPanel/index.tsx+++ b/src/features/AgentDocumentPage/RightPanel/index.tsx@@ -1,9 +1,10 @@'use client';+import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';import { ActionIcon, Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { PanelRightCloseIcon } from 'lucide-react';-import { memo, useState } from 'react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';@@ -11,7 +12,9 @@ import { isDesktop } from '@/const/version';import RightPanel from '@/features/RightPanel';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';+import { useClientDataSWR } from '@/libs/swr';import AgentDocumentsGroup from '@/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup';+import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { useGlobalStore } from '@/store/global';@@ -66,7 +69,8 @@ const TABS = [const AgentDocumentRightPanel = memo(() => {const { t } = useTranslation('chat');- const [activeTab, setActiveTab] = useState<AgentDocumentPanelTab>('documents');+ // null = not yet picked by the user → follow the auto default below.+ const [pickedTab, setPickedTab] = useState<AgentDocumentPanelTab | null>(null);const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);const activeAgentId = useAgentStore((s) => s.activeAgentId);const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);@@ -83,6 +87,20 @@ const AgentDocumentRightPanel = memo(() => {? agencyConfig.boundDeviceId: undefined;+ // Deduped against AgentDocumentsGroup's own fetch (same SWR key). When the+ // agent has no plain documents (e.g. only skills) we default to the Skills+ // tab so the panel doesn't open on an empty Documents view.+ const { data: documentList = [], isLoading: isDocumentListLoading } = useClientDataSWR(+ activeAgentId ? agentDocumentSWRKeys.documentsList(activeAgentId) : null,+ () => agentDocumentService.listDocuments({ agentId: activeAgentId! }),+ );+ const hasDocuments = useMemo(+ () => documentList.some((doc) => doc.category === AGENT_DOCUMENT_CATEGORY),+ [documentList],+ );+ const activeTab: AgentDocumentPanelTab =+ pickedTab ?? (!isDocumentListLoading && !hasDocuments ? 'skills' : 'documents');+return (<RightPanel stableLayout defaultWidth={360} maxWidth={720} minWidth={300}><Flexbox height={'100%'} width={'100%'}>@@ -100,7 +118,7 @@ const AgentDocumentRightPanel = memo(() => {className={`${styles.tab} ${activeTab === tab.key ? styles.tabActive : ''}`}key={tab.key}type="button"- onClick={() => setActiveTab(tab.key)}+ onClick={() => setPickedTab(tab.key)}>{t(tab.labelKey)}</button>diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsxindex 41fd292a63e..cbc44f1a1b7 100644--- a/src/features/AgentDocumentPage/index.tsx+++ b/src/features/AgentDocumentPage/index.tsx@@ -25,14 +25,18 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {const { aid } = useParams<{ aid: string }>();const agentId = aid ?? '';const navigate = useWorkspaceAwareNavigate();- const { item, mutate } = useAgentDocumentItem(agentId, documentId);+ const { item, mutate, skillBundle } = useAgentDocumentItem(agentId, documentId);const backToChat = useCallback(() => navigate(agentId ? `/agent/${agentId}` : '/agent'),[agentId, navigate],);- const title = item?.title || item?.filename;+ // A skill index doc is stored as `SKILL.md`; show the skill name (bundle title) instead.+ const isSkillIndex = !!skillBundle;+ const title = skillBundle+ ? skillBundle.title || skillBundle.filename || item?.title || item?.filename+ : item?.title || item?.filename;const header = useMemo(() => (@@ -54,12 +58,17 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {fullWidthHeaderheader={header}key={documentId}+ // A skill index's visible name is the bundle title; renaming must go+ // through the skill APIs, so lock the page title/emoji here. A plain+ // title save would overwrite the `SKILL.md` filename and desync the+ // bundle (and the bundle rename API rejects managed skill docs anyway).+ metaReadOnly={isSkillIndex}pageId={documentId}rightPanel={false}syncPageAgentActiveState={false}title={title}- // Persisted via the shared document save; refresh the list so the- // breadcrumb and working-sidebar entry pick up the new title.+ // Refresh the list so the breadcrumb and working-sidebar entry pick up+ // the new title after the shared page save persists it.onTitleChange={() => mutate()}/>);diff --git a/src/features/AgentDocumentPage/useAgentDocumentItem.ts b/src/features/AgentDocumentPage/useAgentDocumentItem.tsindex 2890bff2a9b..206497fdac9 100644--- a/src/features/AgentDocumentPage/useAgentDocumentItem.ts+++ b/src/features/AgentDocumentPage/useAgentDocumentItem.ts@@ -10,6 +10,11 @@ import {* the working-sidebar's documents list (same SWR key), so it adds no extra* request — it surfaces the agentDocument row id (needed for delete/rename) plus* title / updatedAt for the page header.+ *+ * For a skill's `SKILL.md` index document the row title is the canonical+ * `SKILL.md` filename, so we also resolve the parent skill bundle — the page+ * shows the skill name (bundle title) instead and routes title edits to a+ * bundle rename.*/export const useAgentDocumentItem = (agentId: string | undefined, documentId: string) => {const { data, mutate } = useClientDataSWR(@@ -19,5 +24,10 @@ export const useAgentDocumentItem = (agentId: string | undefined, documentId: stconst item: AgentDocumentListItem | undefined = data?.find((d) => d.documentId === documentId);- return { item, mutate };+ const skillBundle: AgentDocumentListItem | undefined =+ item?.isSkillIndex && item.parentId+ ? data?.find((d) => d.documentId === item.parentId)+ : undefined;++ return { item, mutate, skillBundle };};diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex 3527cef1994..e0c00ab6022 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -1,7 +1,8 @@import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';+import { Center, Empty, Flexbox } from '@lobehub/ui';import type { MenuProps } from 'antd';import { createStaticStyles } from 'antd-style';-import { Maximize2Icon, Trash2Icon } from 'lucide-react';+import { FileTextIcon, Maximize2Icon, Trash2Icon } from 'lucide-react';import type { CSSProperties } from 'react';import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -105,16 +106,35 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen[rowIdByDocumentId],);+ const resolveNodeName = useCallback(+ (doc: AgentDocumentItem): string => {+ if (doc.isSkillIndex) return SKILL_INDEX_FILENAME;+ // Never let an empty name through: a blank segment collides with its+ // parent's path inside the tree's path store and crashes the whole panel+ // (see ExplorerTree/adapter/normalize.ts). Fall back to a localized label.+ return (+ doc.title ||+ doc.filename ||+ t(+ doc.isFolder+ ? 'workingPanel.resources.tree.untitledFolder'+ : 'workingPanel.resources.tree.untitledDocument',+ )+ );+ },+ [t],+ );+const nodes = useMemo<ExplorerTreeNode<AgentDocumentItem>[]>(() =>documents.map((doc) => ({data: doc,id: doc.id,isFolder: doc.isFolder,- name: doc.isSkillIndex ? SKILL_INDEX_FILENAME : doc.title || doc.filename || '',+ name: resolveNodeName(doc),parentId: resolveParentRowId(doc.parentId),})),- [documents, resolveParentRowId],+ [documents, resolveNodeName, resolveParentRowId],);const defaultExpandedIds = useMemo(() => nodes.filter((node) => node.isFolder && node.parentId == null).map((node) => node.id),@@ -289,30 +309,42 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen],);+ const toolbar = (+ <DocumentExplorerToolbar+ onCreateDocument={() => handleCreateDocument(null)}+ onCreateFolder={() => handleCreateFolder(null)}+ />+ );+return (<div className={styles.tree} ref={containerRef} style={{ ...style, ...treeStyleVars }}>- <ExplorerTree<AgentDocumentItem>- iconsColored- canDrag={canDrag}- canDrop={canDrop}- canRename={canRename}- defaultExpandedIds={defaultExpandedIds}- getContextMenuItems={getContextMenuItems}- iconSet="complete"- nodes={nodes}- ref={treeRef}- style={{ height: '100%' }}- unsafeCSS={DOCUMENT_TREE_UNSAFE_CSS}- header={- <DocumentExplorerToolbar- onCreateDocument={() => handleCreateDocument(null)}- onCreateFolder={() => handleCreateFolder(null)}- />- }- onCommitRename={handleCommitRename}- onMove={handleMove}- onNodeClick={handleNodeClick}- />+ {nodes.length === 0 ? (+ // Keep the toolbar reachable (new folder / new doc) above the placeholder.+ <Flexbox height={'100%'}>+ {toolbar}+ <Center flex={1} paddingBlock={24}>+ <Empty description={t('workingPanel.resources.emptyDocuments')} icon={FileTextIcon} />+ </Center>+ </Flexbox>+ ) : (+ <ExplorerTree<AgentDocumentItem>+ iconsColored+ canDrag={canDrag}+ canDrop={canDrop}+ canRename={canRename}+ defaultExpandedIds={defaultExpandedIds}+ getContextMenuItems={getContextMenuItems}+ header={toolbar}+ iconSet="complete"+ nodes={nodes}+ ref={treeRef}+ style={{ height: '100%' }}+ unsafeCSS={DOCUMENT_TREE_UNSAFE_CSS}+ onCommitRename={handleCommitRename}+ onMove={handleMove}+ onNodeClick={handleNodeClick}+ />+ )}</div>);});diff --git a/src/features/ExplorerTree/adapter/normalize.test.ts b/src/features/ExplorerTree/adapter/normalize.test.tsindex 23fc7691708..855aaa9c688 100644--- a/src/features/ExplorerTree/adapter/normalize.test.ts+++ b/src/features/ExplorerTree/adapter/normalize.test.ts@@ -21,6 +21,42 @@ describe('normalizeTree', () => {).toEqual(['folder-b', 'file-a']);});+ it('disambiguates a folder and a file that share a name', () => {+ // @pierre/trees keys nodes by bare name within a parent, so `foo/` and+ // `foo` would collide into one ambiguous node without a directory index+ // (the "Unknown directory child index" crash). They must stay distinct.+ const nodes: ExplorerTreeNode[] = [+ { id: 'folder', isFolder: true, name: 'foo', parentId: null },+ { id: 'file', name: 'foo', parentId: null },+ ];++ const tree = normalizeTree(nodes);++ expect(tree.pathById.get('folder')).toBe('foo/');+ expect(tree.pathById.get('file')).toBe('foo (2)');+ // no two nodes share a bare path segment+ expect(new Set(tree.paths.map((p) => (p.endsWith('/') ? p.slice(0, -1) : p))).size).toBe(+ tree.paths.length,+ );+ });++ it('replaces empty names with a fallback instead of emitting a blank segment', () => {+ // A blank segment makes a child path equal to its parent's path, which the+ // path store cannot represent and crashes the panel.+ const nodes: ExplorerTreeNode[] = [+ { id: 'blank-folder', isFolder: true, name: '', parentId: null },+ { id: 'blank-file', name: ' ', parentId: null },+ { id: 'child', name: 'a.md', parentId: 'blank-folder' },+ ];++ const tree = normalizeTree(nodes);++ expect(tree.pathById.get('blank-folder')).toBe('Untitled/');+ expect(tree.pathById.get('blank-file')).toBe('Untitled (2)');+ expect(tree.pathById.get('child')).toBe('Untitled/a.md');+ expect(tree.paths.every((p) => p.replaceAll('/', '') !== '')).toBe(true);+ });+it('detects descendants by parent id mapping', () => {const tree = normalizeTree([{diff --git a/src/features/ExplorerTree/adapter/normalize.ts b/src/features/ExplorerTree/adapter/normalize.tsindex 48d53a680d4..8b59bb00690 100644--- a/src/features/ExplorerTree/adapter/normalize.ts+++ b/src/features/ExplorerTree/adapter/normalize.ts@@ -9,10 +9,23 @@ export interface NormalizedTree<TData> {paths: string[];}-const dedupeName = (taken: Set<string>, baseName: string, isFolder: boolean): string => {- const segment = buildSegment(baseName, isFolder);- if (!taken.has(segment)) {- taken.add(segment);+// Last-resort label when a node has no usable name. Callers should supply a+// localized fallback, but an empty segment must never reach the path store+// (see below), so we guard here too.+const UNNAMED_FALLBACK = 'Untitled';++// The underlying path store (@pierre/trees) keys a node by its *bare* name+// within its parent, ignoring the folder trailing slash. So a folder `foo/`+// and a file `foo` are the SAME node to it — an ambiguous dir/file with no+// directory index, which throws "Unknown directory child index" and takes down+// the whole panel. Dedupe on the bare name (type-agnostic) so siblings stay+// distinct regardless of folder-ness, and never emit an empty segment.+const bareKey = (name: string): string => buildSegment(name, false);++const dedupeName = (taken: Set<string>, rawName: string, isFolder: boolean): string => {+ const baseName = rawName.trim() === '' ? UNNAMED_FALLBACK : rawName;+ if (!taken.has(bareKey(baseName))) {+ taken.add(bareKey(baseName));return baseName;}// split name / ext for nicer suffixes on files@@ -21,14 +34,13 @@ const dedupeName = (taken: Set<string>, baseName: string, isFolder: boolean): stconst ext = dotIndex > 0 ? baseName.slice(dotIndex) : '';for (let i = 2; i < 10_000; i += 1) {const candidate = `${stem} (${i})${ext}`;- const seg = buildSegment(candidate, isFolder);- if (!taken.has(seg)) {- taken.add(seg);+ if (!taken.has(bareKey(candidate))) {+ taken.add(bareKey(candidate));return candidate;}}const fallback = `${stem}-${Math.random().toString(36).slice(2, 8)}${ext}`;- taken.add(buildSegment(fallback, isFolder));+ taken.add(bareKey(fallback));return fallback;};diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex 45142a28f9a..edc5ffae5b6 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -108,6 +108,12 @@ interface PageEditorProps {fullWidthHeader?: boolean;header?: PageEditorHeader;knowledgeBaseId?: string;+ /**+ * Make the page title/emoji read-only while keeping the body editable. Set for+ * managed docs whose identity lives elsewhere (e.g. a skill's `SKILL.md`+ * index — see {@link PublicState.metaReadOnly}).+ */+ metaReadOnly?: boolean;onBack?: () => void;onDelete?: () => void;onDocumentIdChange?: (newId: string) => void;@@ -347,6 +353,7 @@ export const PageEditor: FC<PageEditorProps> = ({header,fullWidthHeader,knowledgeBaseId,+ metaReadOnly,onDocumentIdChange,onEmojiChange,onSave,@@ -366,6 +373,7 @@ export const PageEditor: FC<PageEditorProps> = ({<PageEditorProvideremoji={emoji}knowledgeBaseId={knowledgeBaseId}+ metaReadOnly={metaReadOnly}pageId={pageId}title={title}onBack={onBack}diff --git a/src/features/PageEditor/PageEditorProvider.tsx b/src/features/PageEditor/PageEditorProvider.tsxindex cb2cc90f081..66145332313 100644--- a/src/features/PageEditor/PageEditorProvider.tsx+++ b/src/features/PageEditor/PageEditorProvider.tsx@@ -20,6 +20,7 @@ export const PageEditorProvider = memo<PageEditorProviderProps>(children,pageId,knowledgeBaseId,+ metaReadOnly,onDocumentIdChange,onEmojiChange,onSave,@@ -40,6 +41,7 @@ export const PageEditorProvider = memo<PageEditorProviderProps>(editor,emoji,knowledgeBaseId,+ metaReadOnly,onBack,onDelete,onDocumentIdChange,@@ -54,6 +56,7 @@ export const PageEditorProvider = memo<PageEditorProviderProps>(<StoreUpdateremoji={emoji}knowledgeBaseId={knowledgeBaseId}+ metaReadOnly={metaReadOnly}pageId={pageId}parentId={parentId}title={title}diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex 3115f52f6ff..936a264c97d 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -31,6 +31,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(({pageId,knowledgeBaseId,+ metaReadOnly,onDocumentIdChange,onEmojiChange,onSave,@@ -65,6 +66,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(useStoreUpdater('documentId', pageId);useStoreUpdater('isWorkspacePage', isWorkspacePage);useStoreUpdater('knowledgeBaseId', knowledgeBaseId);+ useStoreUpdater('metaReadOnly', metaReadOnly);useStoreUpdater('onDocumentIdChange', onDocumentIdChange);useStoreUpdater('onEmojiChange', onEmojiChange);useStoreUpdater('onSave', onSave);diff --git a/src/features/PageEditor/TitleSection.tsx b/src/features/PageEditor/TitleSection.tsxindex d8cdc9516a6..ad2ecab39f2 100644--- a/src/features/PageEditor/TitleSection.tsx+++ b/src/features/PageEditor/TitleSection.tsx@@ -24,7 +24,11 @@ const TitleSection = memo(() => {// Gate the title/emoji on the same state as the body editor: edit permission// AND not locked by another member (nor pending / save-blocked). The lock makes// the whole page read-only, so metadata must not stay editable behind it.- const canEdit = usePageEditable();+ // `metaReadOnly` additionally locks just the meta (title + emoji) while leaving+ // the body editable — used for managed docs like a skill's `SKILL.md` index,+ // whose identity is renamed through skill APIs, never a plain title save.+ const isMetaReadOnly = usePageEditorStore((s) => s.metaReadOnly);+ const canEdit = usePageEditable() && !isMetaReadOnly;const emoji = usePageEditorStore((s) => s.emoji);const title = usePageEditorStore((s) => s.title);const setEmoji = usePageEditorStore((s) => s.setEmoji);diff --git a/src/features/PageEditor/store/initialState.ts b/src/features/PageEditor/store/initialState.tsindex ff976d46ece..15c76a3a368 100644--- a/src/features/PageEditor/store/initialState.ts+++ b/src/features/PageEditor/store/initialState.ts@@ -9,6 +9,14 @@ export interface PublicState {autoSave?: boolean;emoji?: string;knowledgeBaseId?: string;+ /**+ * Make the page meta (title + emoji) read-only even when the body is editable.+ * Used for managed docs whose identity is owned elsewhere — e.g. a skill's+ * `SKILL.md` index, where the visible name is the bundle title and renaming+ * must go through the skill APIs, never a plain document title save (which+ * would overwrite the index filename and desync the bundle).+ */+ metaReadOnly?: boolean;onBack?: () => void;onDelete?: () => void;onDocumentIdChange?: (newId: string) => void;