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-documents): fix delete 404, context menu, icons and server-runtime list refresh (#16694)

Arvin Xuca3a774c3762
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 4be58bef894..8f3172876d6 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -385,3 +385,23 @@
`SPA_PORT||9876`; Next proxies `VITE_DEV_PORT||9876`. Pass `SPA_PORT=9877` to
`init-dev-env.sh dev` (it exports `VITE_DEV_PORT=$SPA_PORT`) so both agree and
you don't fight a worktree already on 9876.
+
+### E3. ✅ WORKS — deep-link to an authed SPA route bounces to /signin; load `/` then soft-nav
+
+- **Situation**: after `setup-auth.sh web-seed`, `agent-browser open <app>/` lands
+ authed, but a hard `open <app>/agent/<id>/docs` (or any deep authed route)
+ redirects to `/signin?callbackUrl=...` — the deep-route hard-load runs an
+ SSR/middleware auth check the seeded cookie doesn't satisfy, even though `/`
+ is authed and the agent is owned by the seeded user.
+- **Doesn't work**: hard-loading the deep route directly; repeated deep hard-loads
+ can also drop the seeded cookie so even `/` starts bouncing (re-run `web-seed`).
+- **Works**: hard-load `/` (authed), confirm by screenshot (not the app-probe auth
+ JSON — it false-negatives here, returns `isSignedIn:false` on an authed page),
+ then **client-side soft-nav** with no server round-trip:
+ ```bash
+ agent-browser eval "history.pushState({},'','/agent/<id>/docs'); window.dispatchEvent(new PopStateEvent('popstate')); 'nav'" --session lobehub-dev
+ ```
+ react-router picks up the popstate and renders the route in-context with the
+ already-hydrated auth. Right-panels that render at a _layout_ level do NOT see a
+ child route's `:param` via `useParams()` — read it from `location.pathname` if
+ you need it.
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index deadaecb72a..5c929a9b22f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -25,6 +25,8 @@
"agentDefaultMessageWithSystemRole": "Hi, I’m **{{name}}**. One sentence is enough—you're in control.",
"agentDefaultMessageWithoutEdit": "Hi, I’m **{{name}}**. One sentence is enough—you're in control.",
"agentDocument.backToChat": "Back to chat",
+ "agentDocument.emptyDescription": "Pick a document from the panel on the right, or create a new one to get started.",
+ "agentDocument.emptyTitle": "No document open",
"agentDocument.linkCopied": "Link copied",
"agentDocument.openAsPage": "Open as full page",
"agentProfile.files_one": "{{count}} file",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 882cfdffa2d..dd45085c91e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -25,6 +25,8 @@
"agentDefaultMessageWithSystemRole": "你好,我是 **{{name}}**。从一句话开始就行——决定权在你",
"agentDefaultMessageWithoutEdit": "你好,我是 **{{name}}**。从一句话开始就行——决定权在你",
"agentDocument.backToChat": "返回对话",
+ "agentDocument.emptyDescription": "从右侧面板选择一个文档,或新建一个开始编辑。",
+ "agentDocument.emptyTitle": "未打开任何文档",
"agentDocument.linkCopied": "链接已复制",
"agentDocument.openAsPage": "打开整页",
"agentProfile.files_one": "{{count}} 个文件",
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index 88c49ba3858..f26b4a41528 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -151,6 +151,14 @@ export interface AgentDocumentsRuntimeOptions {
agentId: string;
documentId: string;
}) => MaybePromise<string | undefined>;
+ /**
+ * Fired after a document-mutating tool call finishes (create / remove /
+ * rename / copy) so the host can invalidate client-side caches. This is the
+ * only refresh signal for the server-runtime path — where the tool executes
+ * on the gateway and the client service layer (which normally invalidates)
+ * never runs. Invoked from the executor's `onAfterCall` lifecycle hook.
+ */
+ onDocumentsMutated?: () => MaybePromise<void>;
}
export class AgentDocumentsExecutionRuntime {
@@ -159,6 +167,17 @@ export class AgentDocumentsExecutionRuntime {
private options: AgentDocumentsRuntimeOptions = {},
) {}
+ /**
+ * Notify the host that the document set changed so it can refresh client
+ * state (e.g. the agent documents list). Invoked from the executor's
+ * `onAfterCall` hook, which fires on `tool_end` regardless of whether the
+ * mutation ran client- or server-side — covering the server-runtime path the
+ * inline client service invalidation can't reach.
+ */
+ notifyMutated(): Promise<void> {
+ return Promise.resolve(this.options.onDocumentsMutated?.());
+ }
+
private resolveAgentId(context?: AgentDocumentOperationContext) {
if (!context?.agentId) return;
return context.agentId;
diff --git a/packages/builtin-tool-agent-documents/src/executor/index.test.ts b/packages/builtin-tool-agent-documents/src/executor/index.test.ts
new file mode 100644
index 00000000000..0201c463afb
--- /dev/null
+++ b/packages/builtin-tool-agent-documents/src/executor/index.test.ts
@@ -0,0 +1,65 @@
+import type { ToolAfterCallContext } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AgentDocumentsExecutionRuntime } from '../ExecutionRuntime';
+import { AgentDocumentsApiName } from '../types';
+import { AgentDocumentsExecutor } from './index';
+
+const makeExecutor = (onDocumentsMutated: () => void) => {
+ // onAfterCall only reaches runtime.notifyMutated → options.onDocumentsMutated,
+ // so the service methods are never touched here.
+ const runtime = new AgentDocumentsExecutionRuntime({} as never, { onDocumentsMutated });
+ return new AgentDocumentsExecutor(runtime);
+};
+
+const ctx = (apiName: string, success: boolean): ToolAfterCallContext =>
+ ({
+ apiName,
+ identifier: 'lobe-agent-documents',
+ params: {},
+ result: { success },
+ toolCallId: 'call_1',
+ }) as ToolAfterCallContext;
+
+describe('AgentDocumentsExecutor.onAfterCall', () => {
+ it('notifies the host after a successful list-mutating call', async () => {
+ const onDocumentsMutated = vi.fn();
+ const executor = makeExecutor(onDocumentsMutated);
+
+ await executor.onAfterCall(ctx(AgentDocumentsApiName.createDocument, true));
+
+ expect(onDocumentsMutated).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ AgentDocumentsApiName.removeDocument,
+ AgentDocumentsApiName.renameDocument,
+ AgentDocumentsApiName.copyDocument,
+ ])('notifies for the %s mutation', async (apiName) => {
+ const onDocumentsMutated = vi.fn();
+ const executor = makeExecutor(onDocumentsMutated);
+
+ await executor.onAfterCall(ctx(apiName, true));
+
+ expect(onDocumentsMutated).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips notification when the call failed', async () => {
+ const onDocumentsMutated = vi.fn();
+ const executor = makeExecutor(onDocumentsMutated);
+
+ await executor.onAfterCall(ctx(AgentDocumentsApiName.createDocument, false));
+
+ expect(onDocumentsMutated).not.toHaveBeenCalled();
+ });
+
+ it('skips notification for read-only / content-only calls that leave the list unchanged', async () => {
+ const onDocumentsMutated = vi.fn();
+ const executor = makeExecutor(onDocumentsMutated);
+
+ await executor.onAfterCall(ctx(AgentDocumentsApiName.listDocuments, true));
+ await executor.onAfterCall(ctx(AgentDocumentsApiName.replaceDocumentContent, true));
+
+ expect(onDocumentsMutated).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/builtin-tool-agent-documents/src/executor/index.ts b/packages/builtin-tool-agent-documents/src/executor/index.ts
index cec0a050fe6..11ecf5aa3ee 100644
--- a/packages/builtin-tool-agent-documents/src/executor/index.ts
+++ b/packages/builtin-tool-agent-documents/src/executor/index.ts
@@ -1,4 +1,9 @@
-import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
+import {
+ BaseExecutor,
+ type BuiltinToolContext,
+ type BuiltinToolResult,
+ type ToolAfterCallContext,
+} from '@lobechat/types';
import { AgentDocumentsExecutionRuntime } from '../ExecutionRuntime';
import {
@@ -15,6 +20,17 @@ import {
type UpdateLoadRuleArgs,
} from '../types';
+// APIs that change the document set the client list renders (membership or
+// visible title). Content-only edits (replaceDocumentContent / modifyNodes) and
+// read-only calls are excluded — they don't alter the list. Used by
+// `onAfterCall` to decide when to refresh the client-side documents list.
+const LIST_MUTATING_APIS = new Set<string>([
+ AgentDocumentsApiName.createDocument,
+ AgentDocumentsApiName.removeDocument,
+ AgentDocumentsApiName.renameDocument,
+ AgentDocumentsApiName.copyDocument,
+]);
+
export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsApiName> {
readonly identifier = AgentDocumentsIdentifier;
protected readonly apiEnum = AgentDocumentsApiName;
@@ -26,6 +42,15 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
this.runtime = runtime;
}
+ // Refresh the client documents list after the agent mutates it. Fires on
+ // `tool_end` regardless of whether the tool ran client- or server-side — the
+ // server-runtime path never touches the client store otherwise, so a created
+ // doc wouldn't appear until a manual refresh.
+ onAfterCall = async ({ apiName, result }: ToolAfterCallContext): Promise<void> => {
+ if (!LIST_MUTATING_APIS.has(apiName) || !result.success) return;
+ await this.runtime.notifyMutated();
+ };
+
listDocuments = async (
params: ListDocumentsArgs,
ctx: BuiltinToolContext,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index f047638ad37..87b049bde87 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -31,6 +31,9 @@ export default {
'agentDefaultMessageWithoutEdit':
"Hi, I’m **{{name}}**. One sentence is enough—you're in control.",
'agentDocument.backToChat': 'Back to chat',
+ 'agentDocument.emptyDescription':
+ 'Pick a document from the panel on the right, or create a new one to get started.',
+ 'agentDocument.emptyTitle': 'No document open',
'agentDocument.linkCopied': 'Link copied',
'agentDocument.openAsPage': 'Open as full page',
'agentProfile.files_one': '{{count}} file',
diff --git a/src/features/AgentDocumentPage/DocumentsEmpty/index.tsx b/src/features/AgentDocumentPage/DocumentsEmpty/index.tsx
new file mode 100644
index 00000000000..fa4594851ea
--- /dev/null
+++ b/src/features/AgentDocumentPage/DocumentsEmpty/index.tsx
@@ -0,0 +1,76 @@
+'use client';
+
+import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { App } from 'antd';
+import { FileTextIcon, PlusIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { agentDocumentService } from '@/services/agentDocument';
+
+import { buildAgentDocumentPath } from '../navigation';
+
+/**
+ * Center landing for `/agent/:aid/docs` when no document is open — e.g. after
+ * deleting the doc that was being viewed. The right panel keeps showing the full
+ * document tree, so this is guidance + a create shortcut, not a second list.
+ */
+const AgentDocumentsEmpty = memo(() => {
+ const { t } = useTranslation('chat');
+ const { aid } = useParams<{ aid: string }>();
+ const agentId = aid ?? '';
+ const navigate = useWorkspaceAwareNavigate();
+ const { message } = App.useApp();
+ const [creating, setCreating] = useState(false);
+
+ const handleCreate = async () => {
+ if (!agentId || creating) return;
+ setCreating(true);
+ try {
+ const created = await agentDocumentService.createDocument({
+ agentId,
+ content: '',
+ title: t('workingPanel.resources.tree.untitledDocument'),
+ });
+ const documentId = (created as { documentId?: string })?.documentId;
+ // Fall back to staying on the index: the service already revalidated the
+ // list, so the new doc shows up in the right panel for the user to open.
+ if (documentId) navigate(buildAgentDocumentPath(agentId, documentId));
+ } catch (error) {
+ message.error(
+ error instanceof Error
+ ? `${t('workingPanel.resources.tree.createError')}: ${error.message}`
+ : t('workingPanel.resources.tree.createError'),
+ );
+ } finally {
+ setCreating(false);
+ }
+ };
+
+ return (
+ <Center flex={1} height={'100%'} padding={24} width={'100%'}>
+ <Flexbox align={'center'} gap={16}>
+ <Empty
+ description={t('agentDocument.emptyDescription')}
+ icon={FileTextIcon}
+ title={t('agentDocument.emptyTitle')}
+ />
+ <Button
+ icon={<Icon icon={PlusIcon} />}
+ loading={creating}
+ type={'primary'}
+ onClick={handleCreate}
+ >
+ {t('workingPanel.resources.tree.newDocument')}
+ </Button>
+ </Flexbox>
+ </Center>
+ );
+});
+
+AgentDocumentsEmpty.displayName = 'AgentDocumentsEmpty';
+
+export default AgentDocumentsEmpty;
diff --git a/src/features/AgentDocumentPage/index.test.tsx b/src/features/AgentDocumentPage/index.test.tsx
index 1f66cba64cb..1edb6e9238e 100644
--- a/src/features/AgentDocumentPage/index.test.tsx
+++ b/src/features/AgentDocumentPage/index.test.tsx
@@ -17,10 +17,6 @@ vi.mock('@lobehub/ui', () => ({
),
}));
-vi.mock('@/components/404', () => ({
- default: () => <div data-testid="not-found" />,
-}));
-
vi.mock('@/features/PageEditor', () => ({
PageEditor: ({ pageId, header }: { header?: ReactNode; pageId?: string }) => (
<div data-page-id={pageId} data-testid="page-editor">
@@ -60,8 +56,9 @@ vi.mock('./useAgentDocumentItem', () => ({
useAgentDocumentItem: () => agentDocumentItemState.current,
}));
+const navigateMock = vi.hoisted(() => vi.fn());
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
- useWorkspaceAwareNavigate: () => vi.fn(),
+ useWorkspaceAwareNavigate: () => navigateMock,
}));
const docChatTopicState = vi.hoisted(() => ({
@@ -119,6 +116,7 @@ describe('AgentDocumentPage', () => {
};
headerProps.current = undefined;
panelProps.current = undefined;
+ navigateMock.mockClear();
});
afterEach(() => {
@@ -132,12 +130,14 @@ describe('AgentDocumentPage', () => {
expect(screen.getByTestId('header').dataset.documentId).toBe('docs_abc');
});
- it('renders the not-found module (no header/editor) when the doc is genuinely absent', () => {
+ it('redirects to the docs index (no header/editor) when the doc is genuinely absent', () => {
agentDocumentItemState.current = { ...agentDocumentItemState.current, isNotFound: true };
render(<AgentDocumentPage documentId="docs_missing" />);
- expect(screen.getByTestId('not-found')).toBeInTheDocument();
+ // A deleted/absent doc must not strand the user on a 404 — it redirects to
+ // the docs index empty state.
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agent-from-url/docs', { replace: true });
expect(screen.queryByTestId('page-editor')).toBeNull();
expect(screen.queryByTestId('header')).toBeNull();
});
diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsx
index 3f4dfd9945a..4f876023ca1 100644
--- a/src/features/AgentDocumentPage/index.tsx
+++ b/src/features/AgentDocumentPage/index.tsx
@@ -1,10 +1,9 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { memo, useCallback, useMemo } from 'react';
+import { memo, useCallback, useEffect, useMemo } from 'react';
import { useParams } from 'react-router';
-import NotFound from '@/components/404';
import FloatingChatPanel from '@/features/FloatingChatPanel';
import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';
import { PageEditor } from '@/features/PageEditor';
@@ -14,6 +13,7 @@ import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
import Header from './Header';
+import { buildAgentDocumentsPath } from './navigation';
import { useAgentDocumentItem } from './useAgentDocumentItem';
interface AgentDocumentPageProps {
@@ -57,6 +57,23 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
[agentId, navigate],
);
+ // Deleting the open document lands on the docs index (empty-state guidance +
+ // the persistent document tree) rather than the deleted doc's now-404 route.
+ const backToDocs = useCallback(
+ () => navigate(agentId ? buildAgentDocumentsPath(agentId) : '/agent'),
+ [agentId, navigate],
+ );
+
+ // The doc backing this route can vanish while the page is open — most often
+ // deleted from the working-sidebar tree (which optimistically drops the row
+ // from the same list this reads). Redirect to the docs index rather than
+ // stranding the user on a 404 for a doc they just removed. `isNotFound` is
+ // precise (list resolved, doc genuinely absent — not a load error), so a bad
+ // deep link also lands on the index instead of a dead end.
+ useEffect(() => {
+ if (isNotFound && agentId) navigate(buildAgentDocumentsPath(agentId), { replace: true });
+ }, [isNotFound, agentId, navigate]);
+
// A skill index doc is stored as `SKILL.md`; show the skill name (bundle title) instead.
const isSkillIndex = !!skillBundle;
const title = skillBundle
@@ -73,22 +90,16 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
title={title}
updatedAt={item?.updatedAt}
onBack={backToChat}
- onDeleted={backToChat}
+ onDeleted={backToDocs}
/>
),
- [agentId, backToChat, documentId, item?.id, item?.updatedAt, itemError, title],
+ [agentId, backToChat, backToDocs, documentId, item?.id, item?.updatedAt, itemError, title],
);
- // Genuinely-absent doc: show the not-found state for the whole content module
- // rather than a breadcrumb with a placeholder "无标题" title + a title skeleton
- // sitting above a 404 body.
- if (isNotFound) {
- return (
- <Flexbox flex={1} height={'100%'} style={{ minHeight: 0 }} width={'100%'}>
- <NotFound />
- </Flexbox>
- );
- }
+ // Genuinely-absent doc (deleted or bad deep link): render nothing while the
+ // redirect effect above sends the user to the docs index, instead of flashing
+ // a 404 for a doc that simply moved to the empty-state landing.
+ if (isNotFound) return null;
return (
<Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }} width={'100%'}>
diff --git a/src/features/AgentDocumentPage/navigation.ts b/src/features/AgentDocumentPage/navigation.ts
index 1f661b7a357..435ac22253e 100644
--- a/src/features/AgentDocumentPage/navigation.ts
+++ b/src/features/AgentDocumentPage/navigation.ts
@@ -10,3 +10,12 @@ import { standardizeIdentifier } from '@/utils/identifier';
*/
export const buildAgentDocumentPath = (agentId: string, documentId: string): string =>
`/agent/${agentId}/docs/${standardizeIdentifier(documentId)}`;
+
+/**
+ * In-app router path for the agent documents index (`/agent/:aid/docs`) — the
+ * no-document-selected landing that renders empty-state guidance in the center
+ * while the right panel keeps showing the full document tree.
+ *
+ * @param agentId - Owning agent id, e.g. `agt_9GOn6nUgGw35`
+ */
+export const buildAgentDocumentsPath = (agentId: string): string => `/agent/${agentId}/docs`;
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
index 31512c1e769..e8d0f8a5a0a 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
@@ -29,9 +29,14 @@ vi.mock('@lobehub/ui', () => ({
</button>
),
Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ Icon: () => <span />,
Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
}));
+vi.mock('@lobehub/ui/icons', () => ({
+ SkillsIcon: () => null,
+}));
+
vi.mock('@lobehub/ui/base-ui', () => ({
confirmModal: modalConfirm,
}));
@@ -134,6 +139,7 @@ vi.mock('@/features/ExplorerTree', () => {
};
return {
+ DISABLE_ROW_TEXT_SELECTION_CSS: '',
DOCUMENT_TREE_ICON_CSS: '',
ExplorerTree,
FOLDER_ICON_CSS: '',
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
index b8a861c5cee..075b1e1225b 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
@@ -1,8 +1,9 @@
import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';
-import { Center, Empty, Flexbox } from '@lobehub/ui';
+import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';
+import { SkillsIcon } from '@lobehub/ui/icons';
import type { MenuProps } from 'antd';
import { createStaticStyles } from 'antd-style';
-import { FileTextIcon, Maximize2Icon, Trash2Icon } from 'lucide-react';
+import { FileTextIcon, Maximize2Icon, PenLineIcon, Trash2Icon } from 'lucide-react';
import type { CSSProperties } from 'react';
import { memo, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,6 +16,7 @@ import type {
ExplorerTreeNode,
} from '@/features/ExplorerTree';
import {
+ DISABLE_ROW_TEXT_SELECTION_CSS,
DOCUMENT_TREE_ICON_CSS,
ExplorerTree,
getExplorerTreeStyleVars,
@@ -33,7 +35,7 @@ import { canDropDocument } from './utils/canDrop';
const SKILL_INDEX_FILENAME = 'SKILL.md';
const FILE_TREE_HOST_TAG = 'file-tree-container';
const RENAME_INPUT_SELECTOR = 'input[data-item-rename-input]';
-const DOCUMENT_TREE_UNSAFE_CSS = `${DOCUMENT_TREE_ICON_CSS}\n${HIDE_POINTER_FOCUS_RING_CSS}`;
+const DOCUMENT_TREE_UNSAFE_CSS = `${DOCUMENT_TREE_ICON_CSS}\n${HIDE_POINTER_FOCUS_RING_CSS}\n${DISABLE_ROW_TEXT_SELECTION_CSS}`;
// pierre/trees auto-selects the full value when the rename input mounts. For
// files with extensions (e.g. `Untitled document.md`), narrow the selection to
@@ -314,6 +316,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
if (!isSkill && !isMulti) {
items.push({
+ icon: <PenLineIcon size={14} />,
key: 'rename',
label: t('workingPanel.resources.tree.rename'),
onClick: () => startInlineRename(node.id),
@@ -337,6 +340,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
!isFolder && !isSkill && node.data?.category === AGENT_DOCUMENT_CATEGORY;
if (isConvertibleToSkill && !isMulti) {
items.push({
+ icon: <Icon icon={SkillsIcon} size={14} />,
key: 'convert-to-skill',
label: t('workingPanel.resources.tree.convertToSkill'),
onClick: () => handleConvertToSkill(node.data!),
diff --git a/src/features/ExplorerTree/folderIconStyle.ts b/src/features/ExplorerTree/folderIconStyle.ts
index 2758a48cebf..97a5301c9ee 100644
--- a/src/features/ExplorerTree/folderIconStyle.ts
+++ b/src/features/ExplorerTree/folderIconStyle.ts
@@ -287,6 +287,20 @@ ${getFolderIconCSS(MATERIAL_FILE_ICON_ASSETS_URL)}
${DOCUMENT_FILE_ICON_CSS}
`;
+// Tree rows are pointer targets, not prose: allowing text selection lets a
+// drag-select swallow the row so a subsequent right-click hits the browser's
+// native selection menu instead of our context menu. Disable selection on rows
+// while keeping the rename input editable.
+export const DISABLE_ROW_TEXT_SELECTION_CSS = `
+ [data-type='item'] {
+ user-select: none;
+ }
+
+ [data-type='item'] input {
+ user-select: text;
+ }
+`;
+
// pierre/trees marks the clicked row as model-focused, which otherwise paints
// a pointer-only ring.
// Keep the native :focus-visible ring for keyboard navigation.
diff --git a/src/features/ExplorerTree/index.tsx b/src/features/ExplorerTree/index.tsx
index 1dbe9cdc832..858e557819b 100644
--- a/src/features/ExplorerTree/index.tsx
+++ b/src/features/ExplorerTree/index.tsx
@@ -1,4 +1,5 @@
export {
+ DISABLE_ROW_TEXT_SELECTION_CSS,
DOCUMENT_TREE_ICON_CSS,
FOLDER_ICON_CSS,
getExplorerTreeStyleVars,
diff --git a/src/routes/(main)/agent/docs/index.tsx b/src/routes/(main)/agent/docs/index.tsx
new file mode 100644
index 00000000000..9fcec9db6d7
--- /dev/null
+++ b/src/routes/(main)/agent/docs/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { default } from '@/features/AgentDocumentPage/DocumentsEmpty';
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 7fbb5e76f9f..7da826383c0 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -53,6 +53,7 @@ import AgentPage from '@/routes/(main)/agent';
import DesktopChatLayout from '@/routes/(main)/agent/_layout';
import DesktopAgentChatLayout from '@/routes/(main)/agent/(chat)/_layout';
import AgentChannelPage from '@/routes/(main)/agent/channel';
+import AgentDocumentsIndexRoute from '@/routes/(main)/agent/docs';
import AgentDocumentLayout from '@/routes/(main)/agent/docs/_layout';
import AgentDocumentRoute from '@/routes/(main)/agent/docs/[docId]';
import { agentRouteMeta, topicsRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
@@ -166,6 +167,10 @@ export const sharedMainAreaChildren: RouteObject[] = [
},
{
children: [
+ {
+ element: <AgentDocumentsIndexRoute />,
+ index: true,
+ },
{
element: <AgentDocumentRoute />,
handle: { meta: agentDocumentRouteMeta },
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index e98b06bd7a5..665099f4517 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -74,6 +74,13 @@ export const sharedMainAreaChildren: RouteObject[] = [
},
{
children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/docs'),
+ 'Desktop > Chat > DocumentsIndex',
+ ),
+ index: true,
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/agent/docs/[docId]'),
diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
index bae814a36bb..cd8b7417d14 100644
--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
@@ -6,6 +6,8 @@ import { isDesktop } from '@lobechat/const';
import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { agentDocumentService } from '@/services/agentDocument';
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
+import { useAgentStore } from '@/store/agent';
import { useElectronStore } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
@@ -107,6 +109,15 @@ const runtime = new AgentDocumentsExecutionRuntime(
buildAgentDocumentUrl(getAppOrigin(), agentId, documentId, {
workspaceSlug: getActiveWorkspaceSlug(),
}),
+ // Revalidate the documents list after the agent mutates it. `onAfterCall`
+ // carries no agentId, so resolve the active chat agent — the one whose run
+ // just produced the tool call. Covers the server-runtime path where the
+ // client service layer never invalidates.
+ onDocumentsMutated: async () => {
+ const agentId = useAgentStore.getState().activeAgentId;
+ if (!agentId) return;
+ await invalidateDocumentMutation({ agentId, cause: 'agent-document' });
+ },
},
);