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.

✨ feat(agent): improve connector, document, and fleet workflows (#15936)

Arvin Xu3f8203393971
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
index e94e671f988..6c906f355af 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
@@ -2,6 +2,7 @@ import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-doc
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { TaskModel } from '@/database/models/task';
+import { WorkspaceModel } from '@/database/models/workspace';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { agentDocumentsRuntime } from '../agentDocuments';
@@ -12,7 +13,11 @@ const agentDocumentToolOutcomeMocks = vi.hoisted(() => ({
vi.mock('@/server/services/agentDocuments');
vi.mock('@/database/models/task');
+vi.mock('@/database/models/workspace');
vi.mock('@/server/services/agentDocuments/toolOutcome', () => agentDocumentToolOutcomeMocks);
+vi.mock('@/envs/app', () => ({
+ appEnv: { APP_URL: 'https://app.example.com' },
+}));
describe('agentDocumentsRuntime', () => {
it('should have correct identifier', () => {
@@ -48,6 +53,7 @@ describe('agentDocumentsRuntime auto-pin to task', () => {
renameDocumentById: ReturnType<typeof vi.fn>;
};
let pinDocument: ReturnType<typeof vi.fn>;
+ let findWorkspaceById: ReturnType<typeof vi.fn>;
beforeEach(() => {
agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely.mockClear();
@@ -59,12 +65,14 @@ describe('agentDocumentsRuntime auto-pin to task', () => {
renameDocumentById: vi.fn().mockResolvedValue(newDoc),
};
pinDocument = vi.fn().mockResolvedValue(undefined);
+ findWorkspaceById = vi.fn().mockResolvedValue({ slug: 'lobe-team' });
vi.mocked(AgentDocumentsService).mockImplementation(() => serviceImpl as any);
vi.mocked(TaskModel).mockImplementation(() => ({ pinDocument }) as any);
+ vi.mocked(WorkspaceModel).mockImplementation(() => ({ findById: findWorkspaceById }) as any);
});
- const buildContext = (taskId?: string) => {
+ const buildContext = (taskId?: string, workspaceId?: string) => {
// Mock the workspace lookup chain that `pinToTask` runs against the task
// row. Returning `workspaceId: null` reproduces personal-mode behavior.
const limit = vi.fn().mockResolvedValue([{ workspaceId: null }]);
@@ -76,6 +84,7 @@ describe('agentDocumentsRuntime auto-pin to task', () => {
taskId,
toolManifestMap: {},
userId: 'user-1',
+ workspaceId,
};
};
@@ -187,6 +196,32 @@ describe('agentDocumentsRuntime auto-pin to task', () => {
expect(pinDocument).not.toHaveBeenCalled();
});
+
+ it('includes the workspace slug in generated document URLs', async () => {
+ const runtime = agentDocumentsRuntime.factory(buildContext(undefined, 'workspace-1'));
+
+ const result = await runtime.createDocument(
+ { content: 'body', title: 'Daily Brief' },
+ { agentId: 'agent-1' },
+ );
+
+ expect(findWorkspaceById).toHaveBeenCalledWith('workspace-1');
+ expect(result.content).toContain(
+ 'https://app.example.com/lobe-team/agent/agent-1/docs/documents-row-id',
+ );
+ });
+
+ it('omits document URLs for workspace-scoped runs when the workspace slug cannot be resolved', async () => {
+ findWorkspaceById.mockResolvedValueOnce(undefined);
+ const runtime = agentDocumentsRuntime.factory(buildContext(undefined, 'workspace-1'));
+
+ const result = await runtime.createDocument(
+ { content: 'body', title: 'Daily Brief' },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.content).toBe('Created document "Daily Brief" (agent-doc-assoc-id).');
+ });
});
describe('AgentDocumentsExecutionRuntime.createDocument', () => {
@@ -226,6 +261,31 @@ describe('AgentDocumentsExecutionRuntime.createDocument', () => {
});
});
+ it('includes a document URL when a URL builder is configured', async () => {
+ const stub = makeStub();
+ stub.createDocument.mockResolvedValue({
+ documentId: 'docs_document-row-id',
+ filename: 'daily-brief',
+ id: 'agent-doc-assoc-id',
+ title: 'Daily Brief',
+ });
+
+ const runtime = new AgentDocumentsExecutionRuntime(stub, {
+ getDocumentUrl: ({ agentId, documentId }) =>
+ `https://app.example.com/agent/${agentId}/docs/${documentId}`,
+ });
+ const result = await runtime.createDocument(
+ { content: 'body', title: 'Daily Brief' },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain(
+ 'https://app.example.com/agent/agent-1/docs/docs_document-row-id',
+ );
+ expect(result.content).toContain('Use id agent-doc-assoc-id for further edits');
+ });
+
it('refuses to run without agentId', async () => {
const stub = makeStub();
const runtime = new AgentDocumentsExecutionRuntime(stub);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
index 86c25336123..97bd5e0b533 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts
@@ -1,15 +1,28 @@
import type { DocumentLoadRule } from '@lobechat/agent-templates';
-import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
+import {
+ AgentDocumentsIdentifier,
+ buildAgentDocumentUrl,
+} from '@lobechat/builtin-tool-agent-documents';
import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';
import { eq } from 'drizzle-orm';
import { TaskModel } from '@/database/models/task';
+import { WorkspaceModel } from '@/database/models/workspace';
import { tasks } from '@/database/schemas';
+import { appEnv } from '@/envs/app';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';
import { type ServerRuntimeRegistration } from './types';
+const getAgentDocumentAppUrl = (): string | undefined => {
+ try {
+ return appEnv.APP_URL;
+ } catch {
+ return process.env.APP_URL;
+ }
+};
+
export const agentDocumentsRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId || !context.serverDB) {
@@ -20,6 +33,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
const userId = context.userId;
const service = new AgentDocumentsService(db, userId, context.workspaceId);
const { taskId } = context;
+ let workspaceSlugPromise: Promise<string | undefined> | undefined;
const emitDocumentOutcome = async (input: {
agentId?: string;
agentDocumentId?: string;
@@ -109,142 +123,168 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
return doc;
};
- return new AgentDocumentsExecutionRuntime({
- copyDocument: async ({ agentId, id, newTitle }) =>
- pinToTask(
- await withDocumentOutcome(
+ const resolveWorkspaceSlugForUrl = async (): Promise<string | undefined> => {
+ if (!context.workspaceId) return undefined;
+
+ workspaceSlugPromise ??= new WorkspaceModel(db, userId)
+ .findById(context.workspaceId)
+ .then((workspace) => workspace?.slug)
+ .catch((error) => {
+ console.error('[agentDocumentsRuntime] Failed to resolve workspace slug:', error);
+ return undefined;
+ });
+
+ return workspaceSlugPromise;
+ };
+
+ return new AgentDocumentsExecutionRuntime(
+ {
+ copyDocument: async ({ agentId, id, newTitle }) =>
+ pinToTask(
+ await withDocumentOutcome(
+ {
+ agentId,
+ apiName: 'copyDocument',
+ getAgentDocumentId: (result) => result?.id,
+ relation: 'created',
+ summary: 'Agent documents copied a document.',
+ toolAction: 'copy',
+ },
+ () => service.copyDocumentById(id, newTitle, agentId),
+ ),
+ ),
+ createDocument: async ({ agentId, content, hintIsSkill, title }) =>
+ pinToTask(
+ await withDocumentOutcome(
+ {
+ agentId,
+ apiName: 'createDocument',
+ getAgentDocumentId: (result) => result?.id,
+ hintIsSkill,
+ relation: 'created',
+ summary: 'Agent documents created a document.',
+ toolAction: 'create',
+ },
+ () => service.createDocument(agentId, title, content, { hintIsSkill }),
+ ),
+ ),
+ createTopicDocument: async ({ agentId, content, hintIsSkill, title, topicId }) =>
+ pinToTask(
+ await withDocumentOutcome(
+ {
+ agentId,
+ apiName: 'createTopicDocument',
+ getAgentDocumentId: (result) => result?.id,
+ hintIsSkill,
+ relation: 'created',
+ summary: 'Agent documents created a topic document.',
+ toolAction: 'create',
+ },
+ () => service.createForTopic(agentId, title, content, topicId, { hintIsSkill }),
+ ),
+ ),
+ listDocuments: async ({ agentId, sourceType }) => {
+ // Agents discover archived tool results via this path (see
+ // `excludeArchivedToolResults`), so keep the `.tool-results` archive visible.
+ const docs = await service.listDocuments(agentId, sourceType, {
+ includeArchivedToolResults: true,
+ });
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
+ },
+ listTopicDocuments: async ({ agentId, sourceType, topicId }) => {
+ const docs = await service.listDocumentsForTopic(agentId, topicId, sourceType, {
+ includeArchivedToolResults: true,
+ });
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
+ },
+ modifyNodes: ({ agentId, id, operations }) =>
+ withDocumentOutcome(
{
agentId,
- apiName: 'copyDocument',
- getAgentDocumentId: (result) => result?.id,
- relation: 'created',
- summary: 'Agent documents copied a document.',
- toolAction: 'copy',
+ apiName: 'modifyNodes',
+ getAgentDocumentId: () => id,
+ relation: 'updated',
+ summary: 'Agent documents modified document nodes.',
+ toolAction: 'edit',
},
- () => service.copyDocumentById(id, newTitle, agentId),
+ () => service.modifyDocumentNodesById(id, operations, agentId),
),
- ),
- createDocument: async ({ agentId, content, hintIsSkill, title }) =>
- pinToTask(
- await withDocumentOutcome(
+ readDocument: ({ agentId, id }) => service.getDocumentSnapshotById(id, agentId),
+ removeDocument: ({ agentId, id }) =>
+ withDocumentOutcome(
{
agentId,
- apiName: 'createDocument',
- getAgentDocumentId: (result) => result?.id,
- hintIsSkill,
- relation: 'created',
- summary: 'Agent documents created a document.',
- toolAction: 'create',
+ apiName: 'removeDocument',
+ getAgentDocumentId: () => id,
+ relation: 'removed',
+ summary: 'Agent documents removed a document.',
+ toolAction: 'remove',
},
- () => service.createDocument(agentId, title, content, { hintIsSkill }),
+ () => service.removeDocumentById(id, agentId),
),
- ),
- createTopicDocument: async ({ agentId, content, hintIsSkill, title, topicId }) =>
- pinToTask(
- await withDocumentOutcome(
+ renameDocument: ({ agentId, id, newTitle }) =>
+ withDocumentOutcome(
{
agentId,
- apiName: 'createTopicDocument',
- getAgentDocumentId: (result) => result?.id,
- hintIsSkill,
- relation: 'created',
- summary: 'Agent documents created a topic document.',
- toolAction: 'create',
+ apiName: 'renameDocument',
+ getAgentDocumentId: () => id,
+ relation: 'updated',
+ summary: 'Agent documents renamed a document.',
+ toolAction: 'rename',
},
- () => service.createForTopic(agentId, title, content, topicId, { hintIsSkill }),
+ () => service.renameDocumentById(id, newTitle, agentId),
+ ),
+ replaceDocumentContent: ({ agentId, content, id }) =>
+ withDocumentOutcome(
+ {
+ agentId,
+ apiName: 'replaceDocumentContent',
+ getAgentDocumentId: () => id,
+ relation: 'updated',
+ summary: 'Agent documents replaced document content.',
+ toolAction: 'replace',
+ },
+ () => service.replaceDocumentContentById(id, content, agentId),
+ ),
+ updateLoadRule: ({ agentId, id, rule }) =>
+ withDocumentOutcome(
+ {
+ agentId,
+ apiName: 'updateLoadRule',
+ getAgentDocumentId: () => id,
+ relation: 'updated',
+ summary: 'Agent documents updated a load rule.',
+ toolAction: 'update',
+ },
+ () =>
+ service.updateLoadRuleById(
+ id,
+ { ...rule, rule: rule.rule as DocumentLoadRule | undefined },
+ agentId,
+ ),
),
- ),
- listDocuments: async ({ agentId, sourceType }) => {
- // Agents discover archived tool results via this path (see
- // `excludeArchivedToolResults`), so keep the `.tool-results` archive visible.
- const docs = await service.listDocuments(agentId, sourceType, {
- includeArchivedToolResults: true,
- });
- return docs.map((d) => ({
- documentId: d.documentId,
- filename: d.filename,
- id: d.id,
- title: d.title,
- }));
},
- listTopicDocuments: async ({ agentId, sourceType, topicId }) => {
- const docs = await service.listDocumentsForTopic(agentId, topicId, sourceType, {
- includeArchivedToolResults: true,
- });
- return docs.map((d) => ({
- documentId: d.documentId,
- filename: d.filename,
- id: d.id,
- title: d.title,
- }));
+ {
+ getDocumentUrl: async ({ agentId, documentId }) => {
+ const workspaceSlug = await resolveWorkspaceSlugForUrl();
+ if (context.workspaceId && !workspaceSlug) return undefined;
+
+ return buildAgentDocumentUrl(getAgentDocumentAppUrl(), agentId, documentId, {
+ workspaceSlug,
+ });
+ },
},
- modifyNodes: ({ agentId, id, operations }) =>
- withDocumentOutcome(
- {
- agentId,
- apiName: 'modifyNodes',
- getAgentDocumentId: () => id,
- relation: 'updated',
- summary: 'Agent documents modified document nodes.',
- toolAction: 'edit',
- },
- () => service.modifyDocumentNodesById(id, operations, agentId),
- ),
- readDocument: ({ agentId, id }) => service.getDocumentSnapshotById(id, agentId),
- removeDocument: ({ agentId, id }) =>
- withDocumentOutcome(
- {
- agentId,
- apiName: 'removeDocument',
- getAgentDocumentId: () => id,
- relation: 'removed',
- summary: 'Agent documents removed a document.',
- toolAction: 'remove',
- },
- () => service.removeDocumentById(id, agentId),
- ),
- renameDocument: ({ agentId, id, newTitle }) =>
- withDocumentOutcome(
- {
- agentId,
- apiName: 'renameDocument',
- getAgentDocumentId: () => id,
- relation: 'updated',
- summary: 'Agent documents renamed a document.',
- toolAction: 'rename',
- },
- () => service.renameDocumentById(id, newTitle, agentId),
- ),
- replaceDocumentContent: ({ agentId, content, id }) =>
- withDocumentOutcome(
- {
- agentId,
- apiName: 'replaceDocumentContent',
- getAgentDocumentId: () => id,
- relation: 'updated',
- summary: 'Agent documents replaced document content.',
- toolAction: 'replace',
- },
- () => service.replaceDocumentContentById(id, content, agentId),
- ),
- updateLoadRule: ({ agentId, id, rule }) =>
- withDocumentOutcome(
- {
- agentId,
- apiName: 'updateLoadRule',
- getAgentDocumentId: () => id,
- relation: 'updated',
- summary: 'Agent documents updated a load rule.',
- toolAction: 'update',
- },
- () =>
- service.updateLoadRuleById(
- id,
- { ...rule, rule: rule.rule as DocumentLoadRule | undefined },
- agentId,
- ),
- ),
- });
+ );
},
identifier: AgentDocumentsIdentifier,
};
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 8d0c546c176..a7842e7e893 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -20,6 +20,9 @@
"agentDefaultMessage": "Hi, I’m **{{name}}**. One sentence is enough.\n\nWant me to match your workflow better? Go to [Agent Settings]({{url}}) and fill in the Agent Profile (you can edit it anytime).",
"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.linkCopied": "Link copied",
+ "agentDocument.openAsPage": "Open as full page",
"agentProfile.files_one": "{{count}} file",
"agentProfile.files_other": "{{count}} files",
"agentProfile.knowledgeBases_one": "{{count}} knowledge base",
@@ -165,7 +168,9 @@
"extendParams.urlContext.title": "Extract Webpage Link Content",
"followUpPlaceholder": "Follow up.",
"followUpPlaceholderHeterogeneous": "Follow up.",
- "gatewayMode.title": "Gateway Mode",
+ "gatewayMode.beta": "Beta",
+ "gatewayMode.desc": "Run agents in the cloud through LobeHub's Agent Gateway. Tasks keep running even after you close the page.",
+ "gatewayMode.title": "Agent Gateway Mode",
"group.desc": "Move a task forward with multiple Agents in one shared space.",
"group.memberTooltip": "There are {{count}} members in the group",
"group.orchestratorThinking": "Orchestrator is thinking...",
@@ -877,6 +882,7 @@
"toolAuth.authorize": "Authorize",
"toolAuth.authorizing": "Authorizing...",
"toolAuth.hint": "When Skills aren't authorized or configured, the related Skills won't work and the Agent's capabilities may be limited or run into errors.",
+ "toolAuth.remove": "Remove",
"toolAuth.signIn": "Sign In",
"toolAuth.title": "Authorize Skills for this Agent",
"topic.checkOpenNewTopic": "Start a new topic?",
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 0a4aab9d9e7..9e7b8dec769 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -3,6 +3,8 @@
"fleet.allShown": "All running tasks are shown",
"fleet.backToHome": "Back to home",
"fleet.closeColumn": "Close column",
+ "fleet.closeIdleColumns": "Close idle columns",
+ "fleet.closeIdleColumnsCount": "Close {{count}} idle columns",
"fleet.collapseReply": "Collapse",
"fleet.createTask": "Create task",
"fleet.dragHint": "Drag to reorder",
@@ -36,6 +38,7 @@
"navigation.discoverMcp": "Discover MCP",
"navigation.discoverModels": "Discover Models",
"navigation.discoverProviders": "Discover Providers",
+ "navigation.document": "Document",
"navigation.group": "Group",
"navigation.groupChat": "Group Chat",
"navigation.home": "Home",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 8d26b9f1c8d..e70d5c05408 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -20,6 +20,9 @@
"agentDefaultMessage": "你好,我是 **{{name}}**。从一句话开始就行。\n\n想让我更贴近你的工作方式:去 [助理设置]({{url}}) 补充助理档案(随时可改)",
"agentDefaultMessageWithSystemRole": "你好,我是 **{{name}}**。从一句话开始就行——决定权在你",
"agentDefaultMessageWithoutEdit": "你好,我是 **{{name}}**。从一句话开始就行——决定权在你",
+ "agentDocument.backToChat": "返回对话",
+ "agentDocument.linkCopied": "链接已复制",
+ "agentDocument.openAsPage": "打开整页",
"agentProfile.files_one": "{{count}} 个文件",
"agentProfile.files_other": "{{count}} 个文件",
"agentProfile.knowledgeBases_one": "{{count}} 个知识库",
@@ -165,7 +168,9 @@
"extendParams.urlContext.title": "提取网页链接内容",
"followUpPlaceholder": "继续跟进。",
"followUpPlaceholderHeterogeneous": "继续跟进。",
- "gatewayMode.title": "Gateway 模式",
+ "gatewayMode.beta": "Beta",
+ "gatewayMode.desc": "通过 LobeHub 的 Agent Gateway 在云端执行 Agent,即使关闭网页,任务也会继续运行。",
+ "gatewayMode.title": "Agent Gateway 模式",
"group.desc": "在同一对话空间,让多个助理一起推进任务",
"group.memberTooltip": "群组内有 {{count}} 名成员",
"group.orchestratorThinking": "主持人思考中…",
@@ -877,6 +882,7 @@
"toolAuth.authorize": "授权",
"toolAuth.authorizing": "授权中…",
"toolAuth.hint": "技能未授权或未配置时,相关技能无法使用,可能导致助理能力受限或报错",
+ "toolAuth.remove": "移除",
"toolAuth.signIn": "登录",
"toolAuth.title": "为助理完成技能授权",
"topic.checkOpenNewTopic": "要开启新话题吗?",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 530daf4b02b..f17438e5342 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -3,6 +3,8 @@
"fleet.allShown": "所有运行中的任务都已展示",
"fleet.backToHome": "返回首页",
"fleet.closeColumn": "关闭此列",
+ "fleet.closeIdleColumns": "关闭空闲看板",
+ "fleet.closeIdleColumnsCount": "关闭 {{count}} 个空闲看板",
"fleet.collapseReply": "收起",
"fleet.createTask": "创建任务",
"fleet.dragHint": "拖动以调整位置",
@@ -36,6 +38,7 @@
"navigation.discoverMcp": "发现 MCP",
"navigation.discoverModels": "发现模型",
"navigation.discoverProviders": "发现模型服务商",
+ "navigation.document": "文档",
"navigation.group": "群组",
"navigation.groupChat": "群组对话",
"navigation.home": "首页",
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
index 63f7776c7dd..347c2e841a4 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
@@ -48,6 +48,45 @@ describe('AgentDocumentsExecutionRuntime', () => {
});
});
+ it('awaits an async document URL builder', async () => {
+ const createDocument = vi.fn().mockResolvedValue({
+ documentId: 'docs_backing-doc-1',
+ id: 'agent-doc-1',
+ title: 'Research Notes',
+ });
+ const runtime = new AgentDocumentsExecutionRuntime(
+ {
+ copyDocument: vi.fn(),
+ createDocument,
+ createTopicDocument: vi.fn(),
+ listDocuments: vi.fn(),
+ listTopicDocuments: vi.fn(),
+ modifyNodes: vi.fn(),
+ readDocument: vi.fn(),
+ removeDocument: vi.fn(),
+ renameDocument: vi.fn(),
+ replaceDocumentContent: vi.fn(),
+ updateLoadRule: vi.fn(),
+ },
+ {
+ getDocumentUrl: async ({ agentId, documentId }) =>
+ `https://app.example.com/acme/agent/${agentId}/docs/${documentId}`,
+ },
+ );
+
+ const result = await runtime.createDocument(
+ {
+ content: 'notes',
+ title: 'Research Notes',
+ },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.content).toContain(
+ 'https://app.example.com/acme/agent/agent-1/docs/docs_backing-doc-1',
+ );
+ });
+
it('forwards tool trigger metadata when creating documents with same-turn tool context', async () => {
const createDocument = vi.fn().mockResolvedValue({
documentId: 'backing-doc-1',
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index 75ca81e26cf..1c9226374f8 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -70,6 +70,8 @@ interface AgentDocumentToolTriggerInput {
const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_CODE = 'CURRENT_PAGE_DOCUMENT_WRITE_FORBIDDEN';
const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_TYPE = 'CurrentPageDocumentWriteForbidden';
+type MaybePromise<T> = T | Promise<T>;
+
export interface AgentDocumentsRuntimeService {
copyDocument: (
params: CopyDocumentArgs & {
@@ -130,8 +132,23 @@ export interface AgentDocumentsRuntimeService {
) => Promise<AgentDocumentRecord | undefined>;
}
+export interface AgentDocumentsRuntimeOptions {
+ /**
+ * Build a shareable URL that opens a document in the standalone document
+ * route. When provided and it returns a URL, the create result surfaces the
+ * link so the agent can relay it to the user (e.g. in an IM channel).
+ */
+ getDocumentUrl?: (params: {
+ agentId: string;
+ documentId: string;
+ }) => MaybePromise<string | undefined>;
+}
+
export class AgentDocumentsExecutionRuntime {
- constructor(private service: AgentDocumentsRuntimeService) {}
+ constructor(
+ private service: AgentDocumentsRuntimeService,
+ private options: AgentDocumentsRuntimeOptions = {},
+ ) {}
private resolveAgentId(context?: AgentDocumentOperationContext) {
if (!context?.agentId) return;
@@ -282,8 +299,18 @@ export class AgentDocumentsExecutionRuntime {
: await this.service.createDocument({ ...args, ...toolTriggerInput, agentId });
if (!created) return { content: 'Failed to create agent document.', success: false };
+ const title = created.title || args.title;
+ // The document route is keyed by the `documents` id; the URL lets the agent
+ // hand the user a clickable link. `created.id` (the agentDocuments row id)
+ // is kept separately because subsequent edit/read/remove calls key off it.
+ const url = created.documentId
+ ? await this.options.getDocumentUrl?.({ agentId, documentId: created.documentId })
+ : undefined;
+
return {
- content: `Created document "${created.title || args.title}" (${created.id}).`,
+ content: url
+ ? `Created document "${title}" (${url}). Use id ${created.id} for further edits.`
+ : `Created document "${title}" (${created.id}).`,
state: { agentDocumentId: created.id, documentId: created.documentId },
success: true,
};
diff --git a/packages/builtin-tool-agent-documents/src/index.ts b/packages/builtin-tool-agent-documents/src/index.ts
index c0bb22ad407..8ad6b713bdc 100644
--- a/packages/builtin-tool-agent-documents/src/index.ts
+++ b/packages/builtin-tool-agent-documents/src/index.ts
@@ -24,3 +24,4 @@ export {
type UpdateLoadRuleArgs,
type UpdateLoadRuleState,
} from './types';
+export { buildAgentDocumentUrl, type BuildAgentDocumentUrlOptions } from './url';
diff --git a/packages/builtin-tool-agent-documents/src/url.test.ts b/packages/builtin-tool-agent-documents/src/url.test.ts
new file mode 100644
index 00000000000..c13885d8da3
--- /dev/null
+++ b/packages/builtin-tool-agent-documents/src/url.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildAgentDocumentUrl } from './url';
+
+describe('buildAgentDocumentUrl', () => {
+ it('strips the docs_ prefix to match the route param', () => {
+ expect(
+ buildAgentDocumentUrl('https://app.lobehub.com', 'agt_9GOn6nUgGw35', 'docs_MWkYMvbvzssoyWZ9'),
+ ).toBe('https://app.lobehub.com/agent/agt_9GOn6nUgGw35/docs/MWkYMvbvzssoyWZ9');
+ });
+
+ it('keeps ids that have no prefix as-is', () => {
+ expect(buildAgentDocumentUrl('https://app.lobehub.com', 'agt_x', 'MWkYMvbvzssoyWZ9')).toBe(
+ 'https://app.lobehub.com/agent/agt_x/docs/MWkYMvbvzssoyWZ9',
+ );
+ });
+
+ it('trims a trailing slash from the origin', () => {
+ expect(buildAgentDocumentUrl('https://app.lobehub.com/', 'agt_x', 'docs_y')).toBe(
+ 'https://app.lobehub.com/agent/agt_x/docs/y',
+ );
+ });
+
+ it('trims multiple trailing slashes from the origin without a regexp', () => {
+ expect(buildAgentDocumentUrl('https://app.lobehub.com///', 'agt_x', 'docs_y')).toBe(
+ 'https://app.lobehub.com/agent/agt_x/docs/y',
+ );
+ });
+
+ it('prefixes the standalone route with a workspace slug when provided', () => {
+ expect(
+ buildAgentDocumentUrl('https://app.lobehub.com', 'agt_x', 'docs_y', {
+ workspaceSlug: 'lobe-team',
+ }),
+ ).toBe('https://app.lobehub.com/lobe-team/agent/agt_x/docs/y');
+ });
+
+ it('returns undefined when no origin is available', () => {
+ expect(buildAgentDocumentUrl(undefined, 'agt_x', 'docs_y')).toBeUndefined();
+ expect(buildAgentDocumentUrl('', 'agt_x', 'docs_y')).toBeUndefined();
+ expect(buildAgentDocumentUrl('/', 'agt_x', 'docs_y')).toBeUndefined();
+ });
+});
diff --git a/packages/builtin-tool-agent-documents/src/url.ts b/packages/builtin-tool-agent-documents/src/url.ts
new file mode 100644
index 00000000000..94ae68798cd
--- /dev/null
+++ b/packages/builtin-tool-agent-documents/src/url.ts
@@ -0,0 +1,41 @@
+/**
+ * Strip the `docs_` (or any `<prefix>_`) prefix from a documents-table id.
+ * Mirrors the SPA `standardizeIdentifier` convention used by the
+ * `/agent/:agentId/docs/:docId` route param, which carries the bare nanoid.
+ */
+const stripDocumentPrefix = (documentId: string): string =>
+ documentId.includes('_') ? documentId.split('_')[1] : documentId;
+
+const trimTrailingSlashes = (value: string): string => {
+ let end = value.length;
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
+ return value.slice(0, end);
+};
+
+export interface BuildAgentDocumentUrlOptions {
+ workspaceSlug?: string | null;
+}
+
+/**
+ * Build a shareable URL that opens an agent document in the standalone
+ * document route (`/:workspaceSlug?/agent/:agentId/docs/:docId`). Returns
+ * `undefined` when no origin is available so callers can fall back to the bare
+ * id.
+ *
+ * @param origin - App origin, e.g. `https://app.lobehub.com` (no trailing slash required)
+ * @param agentId - Owning agent id, e.g. `agt_9GOn6nUgGw35`
+ * @param documentId - The `documents` table id, e.g. `docs_MWkYMvbvzssoyWZ9`
+ */
+export const buildAgentDocumentUrl = (
+ origin: string | undefined,
+ agentId: string,
+ documentId: string,
+ options?: BuildAgentDocumentUrlOptions,
+): string | undefined => {
+ if (!origin) return undefined;
+ const base = trimTrailingSlashes(origin);
+ if (!base) return undefined;
+
+ const workspacePrefix = options?.workspaceSlug ? `/${options.workspaceSlug}` : '';
+ return `${base}${workspacePrefix}/agent/${agentId}/docs/${stripDocumentPrefix(documentId)}`;
+};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 4952967c538..fcd042c287a 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -28,6 +28,9 @@ export default {
"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.linkCopied': 'Link copied',
+ 'agentDocument.openAsPage': 'Open as full page',
'agentProfile.files_one': '{{count}} file',
'agentProfile.files_other': '{{count}} files',
'agentProfile.knowledgeBases_one': '{{count}} knowledge base',
@@ -487,7 +490,10 @@ export default {
'memory.on.desc': 'Allow AI to actively search and manage your memories during conversation.',
'memory.on.title': 'Enable Memory Tool',
'memory.title': 'Memory',
- 'gatewayMode.title': 'Gateway Mode',
+ 'gatewayMode.beta': 'Beta',
+ 'gatewayMode.desc':
+ "Run agents in the cloud through LobeHub's Agent Gateway. Tasks keep running even after you close the page.",
+ 'gatewayMode.title': 'Agent Gateway Mode',
'search.grounding.imageSearchQueries': 'Image Search Keywords',
'search.grounding.imageTitle': 'Found {{count}} images',
'chatMode.agent': 'Agent',
@@ -966,6 +972,7 @@ export default {
'toolAuth.hint':
"When Skills aren't authorized or configured, the related Skills won't work and the Agent's capabilities may be limited or run into errors.",
'task.title': 'Tasks',
+ 'toolAuth.remove': 'Remove',
'toolAuth.signIn': 'Sign In',
'toolAuth.title': 'Authorize Skills for this Agent',
'topic.checkOpenNewTopic': 'Start a new topic?',
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 695586f8a83..5f9122e97be 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -15,6 +15,7 @@ export default {
'navigation.memoryContexts': 'Memory - Contexts',
'navigation.memoryExperiences': 'Memory - Experiences',
'navigation.memoryIdentities': 'Memory - Identities',
+ 'navigation.document': 'Document',
'navigation.memoryPreferences': 'Memory - Preferences',
'navigation.noPages': 'No pages yet',
'navigation.observation': 'Observation Mode',
@@ -36,6 +37,8 @@ export default {
'fleet.allShown': 'All running tasks are shown',
'fleet.backToHome': 'Back to home',
'fleet.closeColumn': 'Close column',
+ 'fleet.closeIdleColumns': 'Close idle columns',
+ 'fleet.closeIdleColumnsCount': 'Close {{count}} idle columns',
'fleet.collapseReply': 'Collapse',
'fleet.dragHint': 'Drag to reorder',
'fleet.empty': 'No tasks open',
diff --git a/public/images/agent_gateway_dark.webp b/public/images/agent_gateway_dark.webp
new file mode 100644
index 00000000000..05619d1153e
Binary files /dev/null and b/public/images/agent_gateway_dark.webp differ
diff --git a/public/images/agent_gateway_light.webp b/public/images/agent_gateway_light.webp
new file mode 100644
index 00000000000..787b54cae4b
Binary files /dev/null and b/public/images/agent_gateway_light.webp differ
diff --git a/src/features/AgentDocumentPage/Header/index.tsx b/src/features/AgentDocumentPage/Header/index.tsx
new file mode 100644
index 00000000000..7e34f1976f5
--- /dev/null
+++ b/src/features/AgentDocumentPage/Header/index.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
+import { DropdownMenu } from '@lobehub/ui/base-ui';
+import { cssVar, cx } from 'antd-style';
+import { MoreHorizontal } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ShareButton from '@/business/client/features/PageShare/ShareButton';
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { AutoSaveHint } from '@/features/EditorCanvas';
+import NavHeader from '@/features/NavHeader';
+import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { oneLineEllipsis } from '@/styles';
+
+import { useMenu } from './useMenu';
+
+interface HeaderProps {
+ agentDocumentId?: string;
+ agentId: string;
+ documentId: string;
+ onBack: () => void;
+ onDeleted: () => void;
+ title?: string;
+ updatedAt?: Date | string | null;
+}
+
+const Header = memo<HeaderProps>(
+ ({ agentId, agentDocumentId, documentId, onBack, onDeleted, title, updatedAt }) => {
+ const { t } = useTranslation(['file', 'chat']);
+ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));
+ const { menuItems } = useMenu({
+ agentDocumentId,
+ agentId,
+ documentId,
+ onDeleted,
+ title,
+ updatedAt,
+ });
+
+ return (
+ <NavHeader
+ left={
+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0 }}>
+ {/* Breadcrumb: agent → document. The agent label returns to chat. */}
+ <Flexbox
+ horizontal
+ align={'center'}
+ style={{ cursor: 'pointer', flexShrink: 0 }}
+ onClick={onBack}
+ >
+ <Text style={{ color: cssVar.colorTextSecondary }}>
+ {meta.title || t('untitledAgent', { ns: 'chat' })}
+ </Text>
+ </Flexbox>
+ <Text style={{ color: cssVar.colorTextQuaternary, flexShrink: 0 }}>/</Text>
+ <Text className={cx(oneLineEllipsis)} style={{ minWidth: 0 }} weight={500}>
+ {title || t('pageEditor.titlePlaceholder')}
+ </Text>
+ </Flexbox>
+ }
+ right={
+ <Flexbox horizontal align={'center'} gap={4}>
+ {documentId && <AutoSaveHint documentId={documentId} />}
+ {documentId && <ShareButton documentId={documentId} />}
+ <ToggleRightPanelButton hideWhenExpanded />
+ <DropdownMenu
+ iconSpaceMode={'group'}
+ items={menuItems}
+ placement={'bottomRight'}
+ popupProps={{ style: { minWidth: 200 } }}
+ >
+ <ActionIcon icon={MoreHorizontal} size={DESKTOP_HEADER_ICON_SMALL_SIZE} />
+ </DropdownMenu>
+ </Flexbox>
+ }
+ />
+ );
+ },
+);
+
+Header.displayName = 'AgentDocumentPageHeader';
+
+export default Header;
diff --git a/src/features/AgentDocumentPage/Header/useMenu.tsx b/src/features/AgentDocumentPage/Header/useMenu.tsx
new file mode 100644
index 00000000000..c49f9ff3a2a
--- /dev/null
+++ b/src/features/AgentDocumentPage/Header/useMenu.tsx
@@ -0,0 +1,191 @@
+import { buildAgentDocumentUrl } from '@lobechat/builtin-tool-agent-documents';
+import { isDesktop } from '@lobechat/const';
+import { useEditor } from '@lobehub/editor/react';
+import { Icon } from '@lobehub/ui';
+import type { DropdownItem } from '@lobehub/ui/base-ui';
+import { confirmModal } from '@lobehub/ui/base-ui';
+import { App } from 'antd';
+import { cssVar, useResponsive } from 'antd-style';
+import dayjs from 'dayjs';
+import { Download, Link2, Maximize2, Trash2 } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { agentDocumentService } from '@/services/agentDocument';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+interface UseMenuParams {
+ agentDocumentId?: string;
+ agentId: string;
+ documentId: string;
+ onDeleted: () => void;
+ title?: string;
+ updatedAt?: Date | string | null;
+}
+
+/**
+ * Action menu for the standalone agent-document page — mirrors the Pages
+ * document menu (full-width toggle, copy link, export, delete, info) but acts on
+ * the agent-document service.
+ */
+export const useMenu = ({
+ agentDocumentId,
+ agentId,
+ documentId,
+ onDeleted,
+ title,
+ updatedAt,
+}: UseMenuParams): { menuItems: DropdownItem[] } => {
+ const { t } = useTranslation(['file', 'common', 'chat']);
+ const { message } = App.useApp();
+ const { lg = true } = useResponsive();
+ const editor = useEditor();
+ const appOrigin = useAppOrigin();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+
+ const [wideScreen, toggleWideScreen] = useGlobalStore((s) => [
+ systemStatusSelectors.wideScreen(s),
+ s.toggleWideScreen,
+ ]);
+
+ const menuItems = useMemo<DropdownItem[]>(() => {
+ const handleCopyLink = async () => {
+ const url = buildAgentDocumentUrl(appOrigin, agentId, documentId, {
+ workspaceSlug: activeWorkspaceSlug,
+ });
+ if (!url) return;
+ await navigator.clipboard.writeText(url);
+ message.success(t('agentDocument.linkCopied', { ns: 'chat' }));
+ };
+
+ const handleExportMarkdown = async () => {
+ if (!editor) return;
+ const markdown = (editor.getDocument('markdown') as unknown as string) || '';
+ const fileName = `${title || 'Untitled'}.md`;
+ try {
+ if (isDesktop) {
+ const { desktopExportService } = await import('@/services/electron/desktopExportService');
+ await desktopExportService.exportMarkdown({ content: markdown, fileName });
+ } else {
+ const blob = new Blob([markdown], { type: 'text/markdown' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = fileName;
+ document.body.append(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ message.success(t('pageEditor.exportSuccess'));
+ }
+ } catch {
+ message.error(t('pageEditor.exportError'));
+ }
+ };
+
+ const handleDelete = () => {
+ if (!agentDocumentId) return;
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('workingPanel.resources.deleteConfirm', { ns: 'chat' }),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ try {
+ await agentDocumentService.removeDocument({ agentId, documentId, id: agentDocumentId });
+ message.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));
+ onDeleted();
+ } catch (error) {
+ message.error(
+ error instanceof Error
+ ? error.message
+ : t('workingPanel.resources.deleteError', { ns: 'chat' }),
+ );
+ }
+ },
+ title: t('workingPanel.resources.deleteTitle', { ns: 'chat' }),
+ });
+ };
+
+ const items: DropdownItem[] = [
+ ...(lg
+ ? [
+ {
+ checked: wideScreen,
+ icon: <Icon icon={Maximize2} />,
+ key: 'full-width',
+ label: t('viewMode.fullWidth', { ns: 'chat' }),
+ onCheckedChange: toggleWideScreen,
+ type: 'switch' as const,
+ },
+ { type: 'divider' as const },
+ ]
+ : []),
+ {
+ icon: <Icon icon={Link2} />,
+ key: 'copy-link',
+ label: t('pageEditor.menu.copyLink'),
+ onClick: handleCopyLink,
+ },
+ {
+ children: [
+ {
+ key: 'export-markdown',
+ label: t('pageEditor.menu.export.markdown'),
+ onClick: handleExportMarkdown,
+ },
+ ],
+ icon: <Icon icon={Download} />,
+ key: 'export',
+ label: t('pageEditor.menu.export'),
+ },
+ {
+ danger: true,
+ disabled: !agentDocumentId,
+ icon: <Icon icon={Trash2} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: handleDelete,
+ },
+ ];
+
+ if (updatedAt) {
+ items.push(
+ { type: 'divider' as const },
+ {
+ disabled: true,
+ key: 'doc-info',
+ label: (
+ <span style={{ color: cssVar.colorTextTertiary, fontSize: 12, lineHeight: 1.6 }}>
+ {t('pageEditor.editedAt', {
+ time: dayjs(updatedAt).format('MMMM D, YYYY [at] h:mm A'),
+ })}
+ </span>
+ ),
+ },
+ );
+ }
+
+ return items;
+ }, [
+ activeWorkspaceSlug,
+ agentDocumentId,
+ agentId,
+ appOrigin,
+ documentId,
+ editor,
+ lg,
+ message,
+ onDeleted,
+ t,
+ title,
+ toggleWideScreen,
+ updatedAt,
+ wideScreen,
+ ]);
+
+ return { menuItems };
+};
diff --git a/src/features/AgentDocumentPage/Layout/index.tsx b/src/features/AgentDocumentPage/Layout/index.tsx
new file mode 100644
index 00000000000..a9c0235f9db
--- /dev/null
+++ b/src/features/AgentDocumentPage/Layout/index.tsx
@@ -0,0 +1,26 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+import { Outlet } from 'react-router-dom';
+
+import AgentDocumentRightPanel from '../RightPanel';
+
+const AgentDocumentLayout = memo(() => (
+ <Flexbox
+ horizontal
+ flex={1}
+ height={'100%'}
+ style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
+ width={'100%'}
+ >
+ <Flexbox flex={1} style={{ minHeight: 0, minWidth: 0 }}>
+ <Outlet />
+ </Flexbox>
+ <AgentDocumentRightPanel />
+ </Flexbox>
+));
+
+AgentDocumentLayout.displayName = 'AgentDocumentLayout';
+
+export default AgentDocumentLayout;
diff --git a/src/features/AgentDocumentPage/RightPanel/index.tsx b/src/features/AgentDocumentPage/RightPanel/index.tsx
new file mode 100644
index 00000000000..853546bd5aa
--- /dev/null
+++ b/src/features/AgentDocumentPage/RightPanel/index.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { ActionIcon, Flexbox } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { PanelRightCloseIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { isDesktop } from '@/const/version';
+import RightPanel from '@/features/RightPanel';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
+import AgentDocumentsGroup from '@/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
+import { useGlobalStore } from '@/store/global';
+
+type AgentDocumentPanelTab = 'documents' | 'skills';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ body: css`
+ overflow-y: auto;
+ flex: 1;
+ min-height: 0;
+ `,
+ header: css`
+ flex-shrink: 0;
+ `,
+ tab: css`
+ cursor: pointer;
+
+ padding-block: 4px;
+ padding-inline: 10px;
+ border: none;
+ border-radius: 6px;
+
+ font-size: 13px;
+ color: ${cssVar.colorTextTertiary};
+
+ background: transparent;
+
+ transition:
+ color 0.15s,
+ background 0.15s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+ tabActive: css`
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ `,
+ tabs: css`
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ `,
+}));
+
+const TABS = [
+ { key: 'documents', labelKey: 'workingPanel.resources.filter.documents' },
+ { key: 'skills', labelKey: 'workingPanel.skills.title' },
+] as const satisfies readonly { key: AgentDocumentPanelTab; labelKey: string }[];
+
+const AgentDocumentRightPanel = memo(() => {
+ const { t } = useTranslation('chat');
+ const [activeTab, setActiveTab] = useState<AgentDocumentPanelTab>('documents');
+ const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
+ const workingDirectory = useEffectiveWorkingDirectory(activeAgentId);
+ const agencyConfig = useAgentStore((s) =>
+ activeAgentId ? agentByIdSelectors.getAgencyConfigById(activeAgentId)(s) : undefined,
+ );
+ const effectiveTarget = resolveExecutionTarget(agencyConfig, {
+ isDesktop,
+ isHetero,
+ });
+ const remoteDeviceId =
+ effectiveTarget === 'device' && agencyConfig?.boundDeviceId
+ ? agencyConfig.boundDeviceId
+ : undefined;
+
+ return (
+ <RightPanel stableLayout defaultWidth={360} maxWidth={720} minWidth={300}>
+ <Flexbox height={'100%'} width={'100%'}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.header}
+ height={44}
+ justify={'space-between'}
+ paddingInline={4}
+ >
+ <div className={styles.tabs}>
+ {TABS.map((tab) => (
+ <button
+ className={`${styles.tab} ${activeTab === tab.key ? styles.tabActive : ''}`}
+ key={tab.key}
+ type="button"
+ onClick={() => setActiveTab(tab.key)}
+ >
+ {t(tab.labelKey)}
+ </button>
+ ))}
+ </div>
+ <ActionIcon
+ icon={PanelRightCloseIcon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ onClick={() => toggleRightPanel(false)}
+ />
+ </Flexbox>
+ <Flexbox className={styles.body} width={'100%'}>
+ <AgentDocumentsGroup
+ activeFilter={activeTab}
+ deviceId={remoteDeviceId}
+ openMode="route"
+ showFilterTabs={false}
+ showLocalProjectSkills={isDesktop}
+ style={{ flex: 1, minHeight: 0 }}
+ workingDirectory={workingDirectory}
+ />
+ </Flexbox>
+ </Flexbox>
+ </RightPanel>
+ );
+});
+
+AgentDocumentRightPanel.displayName = 'AgentDocumentRightPanel';
+
+export default AgentDocumentRightPanel;
diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsx
new file mode 100644
index 00000000000..41fd292a63e
--- /dev/null
+++ b/src/features/AgentDocumentPage/index.tsx
@@ -0,0 +1,70 @@
+'use client';
+
+import { memo, useCallback, useMemo } from 'react';
+import { useParams } from 'react-router-dom';
+
+import { PageEditor } from '@/features/PageEditor';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+import Header from './Header';
+import { useAgentDocumentItem } from './useAgentDocumentItem';
+
+interface AgentDocumentPageProps {
+ /** Full `documents` table id, e.g. `docs_MWkYMvbvzssoyWZ9`. */
+ documentId: string;
+}
+
+/**
+ * Standalone document view at `/agent/:aid/docs/:docId`. Reuses the shared
+ * `PageEditor` (big title, Ask AI / slash items, width control, autosave) — an
+ * agent document is a row in the same `documents` table as a page — but swaps in
+ * an agent breadcrumb header and drops the page copilot panel so the outer
+ * document layout owns the page-mode right panel.
+ */
+const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
+ const { aid } = useParams<{ aid: string }>();
+ const agentId = aid ?? '';
+ const navigate = useWorkspaceAwareNavigate();
+ const { item, mutate } = useAgentDocumentItem(agentId, documentId);
+
+ const backToChat = useCallback(
+ () => navigate(agentId ? `/agent/${agentId}` : '/agent'),
+ [agentId, navigate],
+ );
+
+ const title = item?.title || item?.filename;
+
+ const header = useMemo(
+ () => (
+ <Header
+ agentDocumentId={item?.id}
+ agentId={agentId}
+ documentId={documentId}
+ title={title}
+ updatedAt={item?.updatedAt}
+ onBack={backToChat}
+ onDeleted={backToChat}
+ />
+ ),
+ [agentId, backToChat, documentId, item?.id, item?.updatedAt, title],
+ );
+
+ return (
+ <PageEditor
+ fullWidthHeader
+ header={header}
+ key={documentId}
+ 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.
+ onTitleChange={() => mutate()}
+ />
+ );
+});
+
+AgentDocumentPage.displayName = 'AgentDocumentPage';
+
+export default AgentDocumentPage;
diff --git a/src/features/AgentDocumentPage/navigation.ts b/src/features/AgentDocumentPage/navigation.ts
new file mode 100644
index 00000000000..1f661b7a357
--- /dev/null
+++ b/src/features/AgentDocumentPage/navigation.ts
@@ -0,0 +1,12 @@
+import { standardizeIdentifier } from '@/utils/identifier';
+
+/**
+ * In-app router path for the standalone document view
+ * (`/agent/:aid/docs/:docId`). The `:docId` segment carries the bare nanoid,
+ * matching the route param (reconstructed via `getIdFromIdentifier`).
+ *
+ * @param agentId - Owning agent id, e.g. `agt_9GOn6nUgGw35`
+ * @param documentId - The `documents` table id, e.g. `docs_MWkYMvbvzssoyWZ9`
+ */
+export const buildAgentDocumentPath = (agentId: string, documentId: string): string =>
+ `/agent/${agentId}/docs/${standardizeIdentifier(documentId)}`;
diff --git a/src/features/AgentDocumentPage/routeMeta.ts b/src/features/AgentDocumentPage/routeMeta.ts
new file mode 100644
index 00000000000..422bb3b7092
--- /dev/null
+++ b/src/features/AgentDocumentPage/routeMeta.ts
@@ -0,0 +1,23 @@
+import { FileTextIcon } from 'lucide-react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { portalKeys } from '@/libs/swr/keys';
+import { documentService } from '@/services/document';
+import { type DynamicRouteMeta, routeMeta } from '@/spa/router/routeMeta';
+import { getIdFromIdentifier } from '@/utils/identifier';
+
+export const agentDocumentRouteMeta = routeMeta({
+ icon: FileTextIcon,
+ titleKey: 'navigation.document',
+ useDynamicMeta: (params): DynamicRouteMeta => {
+ const documentId = params.docId ? getIdFromIdentifier(params.docId, 'docs') : '';
+ // Deduped against the Document Header's SWR fetch (same key), so this adds
+ // no extra request — it just surfaces the title into the breadcrumb.
+ const { data } = useClientDataSWR(
+ documentId ? portalKeys.documentHeader(documentId) : null,
+ () => documentService.getDocumentById(documentId),
+ );
+
+ return { title: data?.filename || data?.title || undefined };
+ },
+});
diff --git a/src/features/AgentDocumentPage/useAgentDocumentItem.ts b/src/features/AgentDocumentPage/useAgentDocumentItem.ts
new file mode 100644
index 00000000000..2890bff2a9b
--- /dev/null
+++ b/src/features/AgentDocumentPage/useAgentDocumentItem.ts
@@ -0,0 +1,23 @@
+import { useClientDataSWR } from '@/libs/swr';
+import {
+ type AgentDocumentListItem,
+ agentDocumentService,
+ agentDocumentSWRKeys,
+} from '@/services/agentDocument';
+
+/**
+ * Resolve the agent-document list row for a documents-table id. Deduped against
+ * 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.
+ */
+export const useAgentDocumentItem = (agentId: string | undefined, documentId: string) => {
+ const { data, mutate } = useClientDataSWR(
+ agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,
+ () => agentDocumentService.listDocuments({ agentId: agentId! }),
+ );
+
+ const item: AgentDocumentListItem | undefined = data?.find((d) => d.documentId === documentId);
+
+ return { item, mutate };
+};
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
index e94ed107d4a..31afd41e2cb 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
@@ -6,6 +6,7 @@ import {
} from '@lobechat/const';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react';
+import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ExplorerTreeNode } from '@/features/ExplorerTree';
@@ -13,13 +14,12 @@ import type { ExplorerTreeNode } from '@/features/ExplorerTree';
import DocumentExplorerTree from './DocumentExplorerTree';
import type { AgentDocumentItem } from './types';
-const { openDocument } = vi.hoisted(() => ({
- openDocument: vi.fn(),
-}));
+const navigateMock = vi.hoisted(() => 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 openDocumentMock = vi.hoisted(() => vi.fn());
const removeDocumentMock = vi.hoisted(() => vi.fn());
vi.mock('@lobehub/ui', () => ({
@@ -51,17 +51,16 @@ vi.mock('@/services/agentDocument', () => ({
},
}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => navigateMock,
+}));
+
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
}),
}));
-vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({ openDocument }),
-}));
-
vi.mock('@/features/ExplorerTree', () => {
interface MockExplorerTreeProps {
canDrag?: (node: ExplorerTreeNode<unknown>) => boolean;
@@ -182,7 +181,8 @@ describe('DocumentExplorerTree', () => {
messageSuccess.mockReset();
messageWarning.mockReset();
modalConfirm.mockReset();
- openDocument.mockReset();
+ navigateMock.mockReset();
+ openDocumentMock.mockReset();
removeDocumentMock.mockReset();
removeDocumentMock.mockResolvedValue({ deleted: true, id: 'skill-bundle-row' });
});
@@ -221,7 +221,9 @@ describe('DocumentExplorerTree', () => {
}),
];
- render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />);
+ render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />, {
+ wrapper: MemoryRouter,
+ });
const bundleNode = screen.getByTestId('tree-node-skill-bundle-row');
expect(bundleNode).toHaveAttribute('data-folder', 'true');
@@ -235,7 +237,7 @@ describe('DocumentExplorerTree', () => {
expect(skillIndexNode).toHaveAttribute('data-menu-count', '0');
});
- it('opens SKILL.md but does not open the empty skill bundle', () => {
+ it('opens SKILL.md in the document page but does not open the empty skill bundle', () => {
const data = [
createDocument({
category: AGENT_DOCUMENT_SKILL_CATEGORY,
@@ -261,13 +263,42 @@ describe('DocumentExplorerTree', () => {
}),
];
- render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />);
+ render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />, {
+ wrapper: MemoryRouter,
+ });
fireEvent.click(screen.getByTestId('tree-node-button-skill-bundle-row'));
- expect(openDocument).not.toHaveBeenCalled();
+ expect(navigateMock).not.toHaveBeenCalled();
fireEvent.click(screen.getByTestId('tree-node-button-skill-index-row'));
- expect(openDocument).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agent-1/docs/skill-index-doc');
+ });
+
+ it('delegates document opening to the caller when provided', () => {
+ const data = [
+ createDocument({
+ documentId: 'doc-content-1',
+ id: 'agent-doc-row-1',
+ title: 'Brief',
+ }),
+ ];
+
+ render(
+ <DocumentExplorerTree
+ agentId="agent-1"
+ data={data}
+ mutate={vi.fn()}
+ onOpenDocument={openDocumentMock}
+ />,
+ {
+ wrapper: MemoryRouter,
+ },
+ );
+
+ fireEvent.click(screen.getByTestId('tree-node-button-agent-doc-row-1'));
+
+ expect(openDocumentMock).toHaveBeenCalledWith('doc-content-1', 'agent-doc-row-1');
+ expect(navigateMock).not.toHaveBeenCalled();
});
it('shows delete recovery action for a managed skill bundle without SKILL.md', async () => {
@@ -286,7 +317,9 @@ describe('DocumentExplorerTree', () => {
}),
];
- render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={mutate} />);
+ render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={mutate} />, {
+ wrapper: MemoryRouter,
+ });
const bundleNode = screen.getByTestId('tree-node-skill-bundle-row');
expect(bundleNode).toHaveAttribute('data-folder', 'true');
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
index 34ac51c8747..3527cef1994 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
@@ -1,12 +1,13 @@
import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';
import type { MenuProps } from 'antd';
import { createStaticStyles } from 'antd-style';
-import { Trash2Icon } from 'lucide-react';
+import { Maximize2Icon, Trash2Icon } from 'lucide-react';
import type { CSSProperties } from 'react';
import { memo, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { KeyedMutator } from 'swr';
+import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';
import type {
ExplorerTreeCanDropCtx,
ExplorerTreeHandle,
@@ -18,7 +19,7 @@ import {
getExplorerTreeStyleVars,
HIDE_POINTER_FOCUS_RING_CSS,
} from '@/features/ExplorerTree';
-import { useChatStore } from '@/store/chat';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import DocumentExplorerToolbar from './DocumentExplorerToolbar';
import { useDocumentTreeOps } from './hooks/useDocumentTreeOps';
@@ -66,12 +67,13 @@ interface Props {
agentId: string;
data: AgentDocumentItem[];
mutate: KeyedMutator<AgentDocumentItem[]>;
+ onOpenDocument?: (documentId: string, agentDocumentId?: string) => void;
style?: CSSProperties;
}
-const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
+const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocument, style }) => {
const { t } = useTranslation(['chat', 'common']);
- const openDocument = useChatStore((s) => s.openDocument);
+ const navigate = useWorkspaceAwareNavigate();
const treeRef = useRef<ExplorerTreeHandle | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
@@ -160,9 +162,13 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
(node: ExplorerTreeNode<AgentDocumentItem>) => {
const doc = node.data;
if (!doc || node.isFolder) return;
- openDocument(doc.documentId, doc.id);
+ if (onOpenDocument) {
+ onOpenDocument(doc.documentId, doc.id);
+ return;
+ }
+ navigate(buildAgentDocumentPath(agentId, doc.documentId));
},
- [openDocument],
+ [agentId, navigate, onOpenDocument],
);
const handleCommitRename = useCallback(
@@ -248,6 +254,17 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
});
}
+ // A document file (not a folder, skill, or multi-select) can be expanded
+ // into the full-page document route — the standalone view agent links open.
+ if (!isFolder && !isSkill && !isMulti && node.data?.documentId) {
+ items.push({
+ icon: <Maximize2Icon size={14} />,
+ key: 'open-as-page',
+ label: t('agentDocument.openAsPage'),
+ onClick: () => navigate(buildAgentDocumentPath(agentId, node.data!.documentId)),
+ });
+ }
+
items.push({
danger: true,
icon: <Trash2Icon size={14} />,
@@ -260,7 +277,16 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
return items;
},
- [handleCreateDocument, handleCreateFolder, isRecoverableSkillBundle, ops, startInlineRename, t],
+ [
+ agentId,
+ handleCreateDocument,
+ handleCreateFolder,
+ isRecoverableSkillBundle,
+ navigate,
+ ops,
+ startInlineRename,
+ t,
+ ],
);
return (
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 86d27826559..b58aac0e8b2 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -2,7 +2,7 @@
import { validateVideoFileSize } from '@lobechat/utils/client';
import type { IconProps } from '@lobehub/ui';
-import { Icon, Popover } from '@lobehub/ui';
+import { Icon, Popover, Tag } from '@lobehub/ui';
import { GlobeOffIcon, SkillsIcon } from '@lobehub/ui/icons';
import { Upload } from 'antd';
import { css, cssVar, cx } from 'antd-style';
@@ -26,6 +26,7 @@ import { useTranslation } from 'react-i18next';
import { message } from '@/components/AntdStaticMethods';
import { openAttachKnowledgeModal } from '@/features/LibraryModal';
+import { useIsDark } from '@/hooks/useIsDark';
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';
import { useAgentStore } from '@/store/agent';
@@ -82,29 +83,6 @@ const activeLabel = css`
}
`;
-const optionLabel = css`
- display: flex;
- gap: 12px;
- align-items: center;
- justify-content: space-between;
-
- width: 100%;
- min-width: 220px;
-
- .title {
- line-height: 1.25;
- }
-
- .desc {
- margin-block-start: 3px;
-
- font-size: 12px;
- line-height: 1.35;
- color: ${cssVar.colorTextDescription};
- white-space: normal;
- }
-`;
-
const searchOptionRow = css`
display: flex;
gap: 10px;
@@ -166,6 +144,53 @@ const countChip = css`
background: ${cssVar.colorFillSecondary};
`;
+const gatewayModeLabel = css`
+ display: inline-flex;
+ gap: 8px;
+ align-items: center;
+ min-width: 0;
+
+ .title {
+ overflow: hidden;
+ min-width: 0;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+`;
+
+const gatewayModeInfoCard = css`
+ overflow: hidden;
+ width: 280px;
+ border-radius: 8px;
+
+ .cover {
+ display: block;
+
+ width: 100%;
+ height: 148px;
+
+ object-fit: cover;
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ .body {
+ padding: 12px;
+ }
+
+ .title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 1.35;
+ }
+
+ .desc {
+ margin-block-start: 6px;
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextSecondary};
+ }
+`;
+
const activeIcon = (icon: IconProps['icon'], active?: boolean): IconProps['icon'] =>
active ? <Icon color={cssVar.colorInfo} icon={icon} size={16} /> : icon;
@@ -179,9 +204,13 @@ const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
interface PopoverLabelProps {
label: ReactNode;
popoverContent: ReactNode;
+ // Distance from the label cell's right edge. Switch-type rows reserve a
+ // trailing toggle, so bump this to push the popover clear of the toggle and
+ // out to the right of the whole menu instead of overlapping it.
+ sideOffset?: number;
}
-const PopoverLabel = memo<PopoverLabelProps>(({ label, popoverContent }) => {
+const PopoverLabel = memo<PopoverLabelProps>(({ label, popoverContent, sideOffset = 10 }) => {
const [open, setOpen] = useState(false);
const suppressUntilRef = useRef(0);
@@ -208,7 +237,7 @@ const PopoverLabel = memo<PopoverLabelProps>(({ label, popoverContent }) => {
mouseEnterDelay={0.25}
open={open}
placement={'rightTop'}
- positionerProps={{ sideOffset: 10 }}
+ positionerProps={{ sideOffset }}
styles={{ content: { padding: 0 } }}
onOpenChange={handleOpenChange}
>
@@ -258,6 +287,7 @@ const PlusAction = memo(() => {
const { t } = useTranslation('chat');
const { t: tEditor } = useTranslation('editor');
const { t: tSetting } = useTranslation('setting');
+ const isDark = useIsDark();
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
const [dropdownOpen, setDropdownOpen] = useState(false);
@@ -378,16 +408,6 @@ const PlusAction = memo(() => {
label
);
- const renderOption = (title: string, description: string, active: boolean) => (
- <div className={cx(optionLabel)}>
- <div>
- <div className="title">{title}</div>
- {description && <div className="desc">{description}</div>}
- </div>
- {active && <Icon icon={CheckIcon} size={14} />}
- </div>
- );
-
const renderSearchOption = (
icon: ReactNode,
title: string,
@@ -414,6 +434,29 @@ const PlusAction = memo(() => {
label
);
+ const renderGatewayModeLabel = () => (
+ <span className={cx(gatewayModeLabel)}>
+ <span className="title">{t('gatewayMode.title')}</span>
+ <Tag color={'info'} size={'small'} variant={'filled'}>
+ {t('gatewayMode.beta')}
+ </Tag>
+ </span>
+ );
+
+ const gatewayModeInfo = (
+ <div className={cx(gatewayModeInfoCard)}>
+ <img
+ alt=""
+ className="cover"
+ src={isDark ? '/images/agent_gateway_dark.webp' : '/images/agent_gateway_light.webp'}
+ />
+ <div className="body">
+ <div className="title">{t('gatewayMode.title')}</div>
+ <div className="desc">{t('gatewayMode.desc')}</div>
+ </div>
+ </div>
+ );
+
const skillMenuItems = stripPopoverContent(skillItems as ActionDropdownMenuItems);
const uploadItems: ActionDropdownMenuItems = [
@@ -559,9 +602,16 @@ const PlusAction = memo(() => {
? [
{
checked: isGatewayModeEnabled,
- icon: activeIcon(Cloud, isGatewayModeEnabled),
+ icon: Cloud,
key: 'gateway-mode',
- label: t('gatewayMode.title'),
+ label: (
+ <PopoverLabel
+ label={renderGatewayModeLabel()}
+ popoverContent={gatewayModeInfo}
+ // Clear the trailing toggle so the card sits to the right of the whole menu.
+ sideOffset={64}
+ />
+ ),
onCheckedChange: handleToggleGatewayMode,
type: 'switch',
} as ActionDropdownMenuItems[number],
@@ -619,12 +669,12 @@ const PlusAction = memo(() => {
enableFC,
enableGatewayMode,
enableKnowledgeBase,
- defaultDisableGatewayMode,
handleSelectSearch,
handleToggleGatewayMode,
handleToggleMemory,
handleToggleParams,
isAgentModeEnabled,
+ isDark,
isGatewayModeEnabled,
isMemoryEnabled,
isParamsPanelActive,
diff --git a/src/features/Conversation/ChatInput/OpStatusTray.tsx b/src/features/Conversation/ChatInput/OpStatusTray.tsx
index 6792dfe1101..535e7a6056f 100644
--- a/src/features/Conversation/ChatInput/OpStatusTray.tsx
+++ b/src/features/Conversation/ChatInput/OpStatusTray.tsx
@@ -42,6 +42,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
border-start-start-radius: 0;
border-start-end-radius: 0;
`,
+ containerSeamless: css`
+ border: none;
+
+ /* keep a hairline divider on top so the tray still reads as separated from
+ the conversation above, even without the full card chrome */
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 0;
+ background: transparent;
+ `,
divider: css`
width: 1px;
height: 12px;
@@ -207,6 +216,11 @@ const normalizeStepCount = (stepCount: unknown) => {
};
interface OpStatusTrayProps {
+ /**
+ * Drop the card chrome (background, border, rounded corners) so the status
+ * reads as a plain inline row — used when nothing is flush below it to attach to.
+ */
+ seamless?: boolean;
/**
* Square the top corners when another panel sits flush above this one.
*/
@@ -221,7 +235,7 @@ interface MetricItem {
value: string;
}
-const OpStatusTray = memo<OpStatusTrayProps>(({ topAttached }) => {
+const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {
const { t } = useTranslation(['chat', 'opStatusTray']);
const context = useConversationStore(contextSelectors.context);
const dbMessages = useConversationStore(dataSelectors.dbMessages);
@@ -378,8 +392,12 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ topAttached }) => {
<Flexbox
horizontal
align="center"
- className={cx(styles.container, topAttached && styles.containerTopAttached)}
justify="space-between"
+ className={cx(
+ styles.container,
+ topAttached && styles.containerTopAttached,
+ seamless && styles.containerSeamless,
+ )}
>
<span className={cx(styles.metric, styles.statusMetric)}>
<ActivityGlyph />
diff --git a/src/features/Fleet/AddColumnButton.tsx b/src/features/Fleet/AddColumnButton.tsx
index 1e054b0a0df..6f5273861d0 100644
--- a/src/features/Fleet/AddColumnButton.tsx
+++ b/src/features/Fleet/AddColumnButton.tsx
@@ -7,7 +7,6 @@ import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import AssigneeAgentSelector from '@/features/AgentTasks/features/AssigneeAgentSelector';
-import { topicService } from '@/services/topic';
import { useFleetStore } from './store';
import { fleetColumnKey } from './types';
@@ -43,27 +42,41 @@ interface AddColumnButtonProps {
/**
* Trailing "+" at the end of a band. Opens an agent picker; selecting an agent
- * creates a fresh topic for it and opens it as a new column ready to receive
- * messages. In multi-band mode each band carries its own, adding into that row.
+ * opens that agent's main conversation (its existing default topic) as a column.
+ * Re-selecting an already-open agent just focuses/scrolls to its column instead
+ * of spawning a duplicate (the column key dedupes on `agentId::default`).
+ * In multi-band mode each band carries its own, adding into that row.
*/
const AddColumnButton = memo<AddColumnButtonProps>(({ insertAfterKey, row }) => {
const { t } = useTranslation(['electron', 'topic']);
const addColumn = useFleetStore((s) => s.addColumn);
const handleSelectAgent = useCallback(
- async (agentId: string) => {
- const title = t('defaultTitle', { ns: 'topic' });
- const topicId = await topicService.createTopic({ messages: [], sessionId: agentId, title });
- const key = fleetColumnKey(agentId, topicId);
+ (agentId: string) => {
+ // Open the agent's main conversation (topicId: null) as a fresh chat —
+ // "pick an agent" here means "start a new conversation with this agent",
+ // not "mint an empty throwaway topic". Instant (no server round-trip that
+ // could silently fail) and dedupes so re-picking just focuses the column.
+ const key = fleetColumnKey(agentId, null);
addColumn(
- { agentId, fallbackTitle: title, key, threadId: null, topicId },
+ {
+ agentId,
+ fallbackTitle: t('defaultTitle', { ns: 'topic' }),
+ key,
+ threadId: null,
+ topicId: null,
+ },
insertAfterKey,
row,
);
+ // Scroll after the column commits to the DOM. Double rAF so the query runs
+ // post-render (a single frame can fire before React paints the new column).
requestAnimationFrame(() => {
- document
- .querySelector(`[data-fleet-col="${CSS.escape(key)}"]`)
- ?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
+ requestAnimationFrame(() => {
+ document
+ .querySelector(`[data-fleet-col="${CSS.escape(key)}"]`)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
+ });
});
},
[addColumn, insertAfterKey, row, t],
diff --git a/src/features/Fleet/AgentColumn.tsx b/src/features/Fleet/AgentColumn.tsx
index 36669bfecf8..71f6b7291a9 100644
--- a/src/features/Fleet/AgentColumn.tsx
+++ b/src/features/Fleet/AgentColumn.tsx
@@ -21,7 +21,13 @@ import { useTranslation } from 'react-i18next';
import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';
import StatusDot from '@/features/AgentTopicManager/StatusDot';
-import { ChatInput, ChatList, ConversationProvider } from '@/features/Conversation';
+import {
+ ChatInput,
+ ChatList,
+ ConversationProvider,
+ conversationSelectors,
+ useConversationStore,
+} from '@/features/Conversation';
import OpStatusTray from '@/features/Conversation/ChatInput/OpStatusTray';
import { useOperationState } from '@/hooks/useOperationState';
import { useChatStore } from '@/store/chat';
@@ -92,6 +98,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
padding-inline: 8px 6px;
border-block-end: 1px solid ${cssVar.colorBorderSecondary};
`,
+ list: css`
+ /* Owns the flexible space so the seamless tray + reply bar below keep their
+ natural height instead of being squeezed (and clipped) by the list. */
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ `,
replyBar: css`
flex: none;
padding-block: 8px;
@@ -115,6 +128,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
/* opaque chip so the conversation behind never bleeds through the button */
background: ${cssVar.colorBgContainer};
+ /* lifted above the floating status tray (translateY set inline) so it never
+ overlaps and cuts into the tray's top border */
+ transition: transform 0.2s ${cssVar.motionEaseInOut};
+
button {
pointer-events: auto;
}
@@ -189,6 +206,91 @@ const WorkingDirRow = memo<{ workingDirectory: string }>(({ workingDirectory })
WorkingDirRow.displayName = 'FleetWorkingDirRow';
+/**
+ * Expanded reply input. The running-op status tray is owned by ChatInput's own
+ * floating overlay (so it carries proper card chrome + top border), so we don't
+ * render a second tray here. The collapse button is lifted above that overlay by
+ * its measured height, keeping it clear of the tray's top edge.
+ *
+ * `onCollapse` is omitted for a brand-new (empty) conversation — there's nothing
+ * to collapse back to yet, so the input just stays open until the first message.
+ */
+const ReplyPanel = memo<{ onCollapse?: () => void }>(({ onCollapse }) => {
+ const { t } = useTranslation('electron');
+ const overlayHeight = useConversationStore(conversationSelectors.chatInputOverlayHeight);
+
+ return (
+ <Flexbox className={styles.replyOpen}>
+ {onCollapse && (
+ <Flexbox
+ horizontal
+ className={styles.replyClose}
+ style={{ transform: overlayHeight ? `translateY(-${overlayHeight}px)` : undefined }}
+ >
+ <Button icon={ChevronDownIcon} size={'small'} type={'text'} onClick={onCollapse}>
+ {t('fleet.collapseReply')}
+ </Button>
+ </Flexbox>
+ )}
+ <ChatInput isConfigLoading={false} />
+ </Flexbox>
+ );
+});
+
+ReplyPanel.displayName = 'FleetReplyPanel';
+
+/**
+ * Bottom reply affordance for a column. Lives inside ConversationProvider so it
+ * reads the conversation's *real* loaded state — never the raw dbMessagesMap
+ * (where `undefined` means "still loading", not "empty"), which would blank the
+ * area out during load.
+ *
+ * - Empty/new conversation → input shown directly (type immediately), no collapse.
+ * - Has messages → "回复" button; expanding shows the input with a collapse button.
+ * - Still loading an existing conversation → keep the "回复" button as a stable
+ * placeholder so the reply area never disappears.
+ */
+const ReplyArea = memo(() => {
+ const { t } = useTranslation('electron');
+ const [replyOpen, setReplyOpen] = useState(false);
+
+ // `messagesInit` mirrors ChatList's own "loaded" gate; a topic-less column is
+ // treated as ready-and-empty immediately (nothing to fetch).
+ const isNewConversation = useConversationStore((s) => !s.context.topicId);
+ const messagesInit = useConversationStore(conversationSelectors.messagesInit);
+ const messageCount = useConversationStore(
+ (s) => conversationSelectors.displayMessageIds(s).length,
+ );
+
+ const isReady = isNewConversation || messagesInit;
+ const isEmptyConversation = isReady && messageCount === 0;
+ const inputExpanded = replyOpen || isEmptyConversation;
+
+ return (
+ <>
+ {/* Seamless inline tray only when collapsed — when expanded, ChatInput's
+ own overlay hosts the tray, so a second one here would duplicate it. */}
+ {!inputExpanded && <OpStatusTray seamless />}
+ {inputExpanded ? (
+ <ReplyPanel onCollapse={isEmptyConversation ? undefined : () => setReplyOpen(false)} />
+ ) : (
+ <Flexbox className={styles.replyBar}>
+ <Button
+ block
+ icon={MessageCirclePlus}
+ variant={'filled'}
+ onClick={() => setReplyOpen(true)}
+ >
+ {t('fleet.reply')}
+ </Button>
+ </Flexbox>
+ )}
+ </>
+ );
+});
+
+ReplyArea.displayName = 'FleetReplyArea';
+
/**
* Lightweight drag visual rendered into the DragOverlay portal — the column
* header on a lifted card with a centered "moving" hint instead of the live
@@ -257,7 +359,6 @@ const AgentColumn = memo<AgentColumnProps>(({ column, status }) => {
const togglePin = useFleetStore((s) => s.togglePin);
const isPinned = useFleetStore((s) => s.pinnedKeys.includes(column.key));
const [dragWidth, setDragWidth] = useState<number | null>(null);
- const [replyOpen, setReplyOpen] = useState(false);
const width = dragWidth ?? storedWidth ?? DEFAULT_COLUMN_WIDTH;
const chatKey = useMemo(() => messageMapKey(context), [context]);
@@ -372,34 +473,10 @@ const AgentColumn = memo<AgentColumnProps>(({ column, status }) => {
replaceMessages(next, { context: ctx });
}}
>
- <ChatList disableActionsBar />
- <OpStatusTray />
- {messages === undefined ? null : replyOpen ? (
- <Flexbox className={styles.replyOpen}>
- <Flexbox horizontal className={styles.replyClose}>
- <Button
- icon={ChevronDownIcon}
- size={'small'}
- type={'text'}
- onClick={() => setReplyOpen(false)}
- >
- {t('fleet.collapseReply')}
- </Button>
- </Flexbox>
- <ChatInput isConfigLoading={false} />
- </Flexbox>
- ) : (
- <Flexbox className={styles.replyBar}>
- <Button
- block
- icon={MessageCirclePlus}
- variant={'filled'}
- onClick={() => setReplyOpen(true)}
- >
- {t('fleet.reply')}
- </Button>
- </Flexbox>
- )}
+ <Flexbox className={styles.list}>
+ <ChatList disableActionsBar />
+ </Flexbox>
+ <ReplyArea />
</ConversationProvider>
</Flexbox>
diff --git a/src/features/Fleet/FleetPanelCollapseSync.tsx b/src/features/Fleet/FleetPanelCollapseSync.tsx
new file mode 100644
index 00000000000..baa74546983
--- /dev/null
+++ b/src/features/Fleet/FleetPanelCollapseSync.tsx
@@ -0,0 +1,54 @@
+'use client';
+
+import { memo, useEffect } from 'react';
+
+import { useGlobalStore } from '@/store/global';
+
+/**
+ * Gives Observation Mode (Fleet) its own persisted nav-panel collapse state.
+ *
+ * The nav panel is a single shared `DraggablePanel` driven by the global
+ * `showLeftPanel` flag, so without this the running-task list inherits whatever
+ * collapse state the chat rail was left in — e.g. collapse the chat sidebar, open
+ * Fleet, and the task list is collapsed too. We keep `showLeftPanel` as the live
+ * runtime source of truth (titlebar toggle / hotkey / layout all keep reading it)
+ * and instead swap it in/out around the Fleet view:
+ *
+ * - on enter: remember the chat rail's state, then apply Fleet's own (`showFleetPanel`)
+ * - while active: mirror collapse changes into `showFleetPanel` so they survive reloads
+ * - on exit: restore the chat rail's remembered state
+ *
+ * Mirrors the save/restore approach used by the agent page's PortalAutoCollapse.
+ */
+const FleetPanelCollapseSync = memo(() => {
+ useEffect(() => {
+ const store = useGlobalStore;
+ // Raw flag (not the zenMode-masked selector) — we persist the user's intent.
+ const savedShowLeftPanel = !!store.getState().status.showLeftPanel;
+
+ // Fleet defaults to expanded the first time it's opened.
+ const fleetExpand = store.getState().status.showFleetPanel ?? true;
+ if (savedShowLeftPanel !== fleetExpand) store.getState().toggleLeftPanel(fleetExpand);
+
+ // Persist Fleet's collapse state as the user toggles it (titlebar / hotkey),
+ // so it's restored next time Observation Mode opens.
+ const unsubscribe = store.subscribe((state, prev) => {
+ if (state.status.showLeftPanel !== prev.status.showLeftPanel) {
+ store.getState().updateSystemStatus({ showFleetPanel: !!state.status.showLeftPanel });
+ }
+ });
+
+ return () => {
+ unsubscribe();
+ if (!!store.getState().status.showLeftPanel !== savedShowLeftPanel) {
+ store.getState().toggleLeftPanel(savedShowLeftPanel);
+ }
+ };
+ }, []);
+
+ return null;
+});
+
+FleetPanelCollapseSync.displayName = 'FleetPanelCollapseSync';
+
+export default FleetPanelCollapseSync;
diff --git a/src/features/Fleet/RunningTaskSidebar.tsx b/src/features/Fleet/RunningTaskSidebar.tsx
index 9451bd6585d..fecb7ba9f23 100644
--- a/src/features/Fleet/RunningTaskSidebar.tsx
+++ b/src/features/Fleet/RunningTaskSidebar.tsx
@@ -1,10 +1,10 @@
'use client';
import { formatElapsedClockTime } from '@lobechat/utils';
-import { Avatar, Button, Flexbox, Tag, Text } from '@lobehub/ui';
+import { ActionIcon, Avatar, Button, Flexbox, Skeleton, Tag, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar, useTheme } from 'antd-style';
-import { PlusIcon } from 'lucide-react';
-import { memo, useCallback, useEffect, useState } from 'react';
+import { ListXIcon, PlusIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import RingLoadingIcon from '@/components/RingLoading';
@@ -18,6 +18,7 @@ import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { type ChatTopicStatus } from '@/types/topic';
+import { getIdleColumnKeys } from './idleColumns';
import RowsSwitcher from './RowsSwitcher';
import { useFleetStore } from './store';
import { type FleetColumn } from './types';
@@ -143,8 +144,70 @@ const SidebarTaskItem = memo<SidebarTaskItemProps>(({ column, status, onActivate
SidebarTaskItem.displayName = 'FleetSidebarTaskItem';
+/** Placeholder row matching `SidebarTaskItem`'s layout while the list loads. */
+const SidebarTaskSkeleton = memo(() => (
+ <Flexbox horizontal align={'center'} gap={10} paddingBlock={8} paddingInline={10}>
+ <Skeleton.Avatar active shape={'square'} size={28} />
+ <Flexbox flex={1} gap={6} style={{ overflow: 'hidden' }}>
+ <Skeleton.Button active style={{ height: 13, minWidth: 0, width: '70%' }} />
+ <Skeleton.Button active style={{ height: 12, minWidth: 0, width: '45%' }} />
+ </Flexbox>
+ </Flexbox>
+));
+
+SidebarTaskSkeleton.displayName = 'FleetSidebarTaskSkeleton';
+
+interface CloseIdleColumnsButtonProps {
+ isStatusLoading?: boolean;
+ statusByColumnKey: Record<string, ChatTopicStatus | undefined>;
+}
+
+/**
+ * Board-level action: close every open column that isn't actively running in one
+ * click. Idle is derived from the board's own columns (store) against the live
+ * running set, so columns whose task finished/paused get cleared while running
+ * ones stay. Disabled while the running-status query loads because an empty
+ * status map would otherwise make every persisted column look idle.
+ */
+const CloseIdleColumnsButton = memo<CloseIdleColumnsButtonProps>(
+ ({ isStatusLoading, statusByColumnKey }) => {
+ const { t } = useTranslation('electron');
+ const boardColumns = useFleetStore((s) => s.columns);
+ const removeColumns = useFleetStore((s) => s.removeColumns);
+
+ const idleKeys = useMemo(
+ () =>
+ getIdleColumnKeys({
+ columns: boardColumns,
+ isStatusLoading,
+ statusByColumnKey,
+ }),
+ [boardColumns, isStatusLoading, statusByColumnKey],
+ );
+
+ if (boardColumns.length === 0) return null;
+
+ return (
+ <ActionIcon
+ disabled={idleKeys.length === 0}
+ icon={ListXIcon}
+ size={'small'}
+ title={
+ idleKeys.length > 0
+ ? t('fleet.closeIdleColumnsCount', { count: idleKeys.length })
+ : t('fleet.closeIdleColumns')
+ }
+ onClick={() => removeColumns(idleKeys)}
+ />
+ );
+ },
+);
+
+CloseIdleColumnsButton.displayName = 'FleetCloseIdleColumnsButton';
+
interface RunningTaskSidebarProps {
columns: FleetColumn[];
+ isLoading?: boolean;
statusByColumnKey: Record<string, ChatTopicStatus | undefined>;
}
@@ -155,66 +218,82 @@ interface RunningTaskSidebarProps {
* count; the body leads with a "create task" action above the running-topic
* list. Clicking an item opens (or re-opens) its column.
*/
-const RunningTaskSidebar = memo<RunningTaskSidebarProps>(({ columns, statusByColumnKey }) => {
- const { t } = useTranslation('electron');
- const addColumn = useFleetStore((s) => s.addColumn);
-
- const handleActivate = useCallback(
- (column: FleetColumn) => {
- addColumn(column);
- requestAnimationFrame(() => {
- document
- .querySelector(`[data-fleet-col="${CSS.escape(column.key)}"]`)
- ?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
- });
- },
- [addColumn],
- );
+const RunningTaskSidebar = memo<RunningTaskSidebarProps>(
+ ({ columns, isLoading, statusByColumnKey }) => {
+ const { t } = useTranslation('electron');
+ const addColumn = useFleetStore((s) => s.addColumn);
- const handleCreateTask = useCallback(() => {
- createTaskModal({ showInlineToggle: false });
- }, []);
-
- const header = (
- <SideBarHeaderLayout
- backTo={'/'}
- right={<RowsSwitcher />}
- showTogglePanelButton={false}
- left={
- <Flexbox horizontal align={'center'} gap={8}>
- {t('fleet.runningBoard')}
- {columns.length > 0 && <Tag style={{ margin: 0 }}>{columns.length}</Tag>}
- </Flexbox>
- }
- />
- );
+ const handleActivate = useCallback(
+ (column: FleetColumn) => {
+ addColumn(column);
+ // Double rAF so the query runs after React paints the (re-)added column —
+ // a single frame can fire before the commit and find nothing to scroll to.
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ document
+ .querySelector(`[data-fleet-col="${CSS.escape(column.key)}"]`)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
+ });
+ });
+ },
+ [addColumn],
+ );
- const body = (
- <Flexbox gap={2} paddingBlock={'8px 12px'} paddingInline={8}>
- <Button block icon={PlusIcon} onClick={handleCreateTask}>
- {t('fleet.createTask')}
- </Button>
- {columns.length === 0 ? (
- <div className={styles.empty}>{t('fleet.noRunningTasks')}</div>
- ) : (
- columns.map((column) => (
- <SidebarTaskItem
- column={column}
- key={column.key}
- status={statusByColumnKey[column.key]}
- onActivate={handleActivate}
- />
- ))
- )}
- </Flexbox>
- );
+ const handleCreateTask = useCallback(() => {
+ createTaskModal({ showInlineToggle: false });
+ }, []);
- return (
- <NavPanelPortal navKey={'fleet'}>
- <SideBarLayout body={body} header={header} />
- </NavPanelPortal>
- );
-});
+ const header = (
+ <SideBarHeaderLayout
+ backTo={'/'}
+ showTogglePanelButton={false}
+ left={
+ <Flexbox horizontal align={'center'} gap={8}>
+ {t('fleet.runningBoard')}
+ {columns.length > 0 && <Tag style={{ margin: 0 }}>{columns.length}</Tag>}
+ </Flexbox>
+ }
+ right={
+ <Flexbox horizontal align={'center'} gap={4}>
+ <CloseIdleColumnsButton
+ isStatusLoading={isLoading}
+ statusByColumnKey={statusByColumnKey}
+ />
+ <RowsSwitcher />
+ </Flexbox>
+ }
+ />
+ );
+
+ const body = (
+ <Flexbox gap={2} paddingBlock={'8px 12px'} paddingInline={8}>
+ <Button block icon={PlusIcon} onClick={handleCreateTask}>
+ {t('fleet.createTask')}
+ </Button>
+ {isLoading && columns.length === 0 ? (
+ Array.from({ length: 3 }).map((_, index) => <SidebarTaskSkeleton key={index} />)
+ ) : columns.length === 0 ? (
+ <div className={styles.empty}>{t('fleet.noRunningTasks')}</div>
+ ) : (
+ columns.map((column) => (
+ <SidebarTaskItem
+ column={column}
+ key={column.key}
+ status={statusByColumnKey[column.key]}
+ onActivate={handleActivate}
+ />
+ ))
+ )}
+ </Flexbox>
+ );
+
+ return (
+ <NavPanelPortal navKey={'fleet'}>
+ <SideBarLayout body={body} header={header} />
+ </NavPanelPortal>
+ );
+ },
+);
RunningTaskSidebar.displayName = 'FleetRunningTaskSidebar';
diff --git a/src/features/Fleet/idleColumns.test.ts b/src/features/Fleet/idleColumns.test.ts
new file mode 100644
index 00000000000..15686b3882a
--- /dev/null
+++ b/src/features/Fleet/idleColumns.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { getIdleColumnKeys } from './idleColumns';
+import type { FleetColumn } from './types';
+
+const column = (key: string): FleetColumn => ({
+ agentId: 'agent-1',
+ fallbackTitle: key,
+ key,
+ threadId: null,
+ topicId: key,
+});
+
+describe('getIdleColumnKeys', () => {
+ it('does not classify persisted columns as idle while statuses are loading', () => {
+ expect(
+ getIdleColumnKeys({
+ columns: [column('running-column')],
+ isStatusLoading: true,
+ statusByColumnKey: {},
+ }),
+ ).toEqual([]);
+ });
+
+ it('returns non-running columns after statuses have loaded', () => {
+ expect(
+ getIdleColumnKeys({
+ columns: [column('running-column'), column('idle-column')],
+ statusByColumnKey: { 'running-column': 'running' },
+ }),
+ ).toEqual(['idle-column']);
+ });
+});
diff --git a/src/features/Fleet/idleColumns.ts b/src/features/Fleet/idleColumns.ts
new file mode 100644
index 00000000000..09f2e094cec
--- /dev/null
+++ b/src/features/Fleet/idleColumns.ts
@@ -0,0 +1,19 @@
+import type { ChatTopicStatus } from '@/types/topic';
+
+import type { FleetColumn } from './types';
+
+interface GetIdleColumnKeysParams {
+ columns: FleetColumn[];
+ isStatusLoading?: boolean;
+ statusByColumnKey: Record<string, ChatTopicStatus | undefined>;
+}
+
+export const getIdleColumnKeys = ({
+ columns,
+ isStatusLoading,
+ statusByColumnKey,
+}: GetIdleColumnKeysParams): string[] => {
+ if (isStatusLoading) return [];
+
+ return columns.filter((column) => statusByColumnKey[column.key] !== 'running').map((c) => c.key);
+};
diff --git a/src/features/Fleet/index.tsx b/src/features/Fleet/index.tsx
index da3d3de2df3..b774fb7e118 100644
--- a/src/features/Fleet/index.tsx
+++ b/src/features/Fleet/index.tsx
@@ -6,6 +6,7 @@ import { memo, useEffect } from 'react';
import { useFetchAgentList } from '@/hooks/useFetchAgentList';
import ColumnsBoard from './ColumnsBoard';
+import FleetPanelCollapseSync from './FleetPanelCollapseSync';
import RunningTaskSidebar from './RunningTaskSidebar';
import { useFleetStore } from './store';
import { useRunningTopics } from './useRunningTopics';
@@ -35,7 +36,12 @@ const FleetView = memo(() => {
return (
<Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>
- <RunningTaskSidebar columns={columns} statusByColumnKey={statusByColumnKey} />
+ <FleetPanelCollapseSync />
+ <RunningTaskSidebar
+ columns={columns}
+ isLoading={!isInit}
+ statusByColumnKey={statusByColumnKey}
+ />
<ColumnsBoard statusByColumnKey={statusByColumnKey} />
</Flexbox>
);
diff --git a/src/features/Fleet/store.test.ts b/src/features/Fleet/store.test.ts
index 83aef489b39..71738a422a1 100644
--- a/src/features/Fleet/store.test.ts
+++ b/src/features/Fleet/store.test.ts
@@ -37,6 +37,25 @@ describe('fleet store', () => {
expect(useFleetStore.getState().dismissedKeys).toEqual(['a']);
});
+ it('removeColumns drops every given key in one update and dismisses them', () => {
+ useFleetStore.setState({
+ columns: [col('a'), col('b'), col('c')],
+ pinnedKeys: ['b'],
+ rowByKey: { a: 0, b: 0, c: 0 },
+ });
+ useFleetStore.getState().removeColumns(['a', 'c']);
+ const s = useFleetStore.getState();
+ expect(s.columns.map((c) => c.key)).toEqual(['b']);
+ expect(s.dismissedKeys).toEqual(['a', 'c']);
+ expect(s.rowByKey).toEqual({ b: 0 });
+ });
+
+ it('removeColumns is a no-op for an empty list', () => {
+ useFleetStore.setState({ columns: [col('a')] });
+ useFleetStore.getState().removeColumns([]);
+ expect(useFleetStore.getState().columns.map((c) => c.key)).toEqual(['a']);
+ });
+
it('addColumn clears a prior dismissal so a re-pinned column sticks', () => {
useFleetStore.setState({ columns: [], dismissedKeys: ['a'] });
useFleetStore.getState().addColumn(col('a'));
diff --git a/src/features/Fleet/store.ts b/src/features/Fleet/store.ts
index 5b0846729ab..494e6448a64 100644
--- a/src/features/Fleet/store.ts
+++ b/src/features/Fleet/store.ts
@@ -47,6 +47,12 @@ interface FleetState {
/** Keys the user explicitly pinned — a deliberate "keep this column" marker. */
pinnedKeys: string[];
removeColumn: (key: string) => void;
+ /**
+ * Close a batch of columns at once (e.g. "close all idle columns"). Mirrors
+ * removeColumn for each key in a single update so the board doesn't reflow
+ * once per column.
+ */
+ removeColumns: (keys: string[]) => void;
/** Reorder columns to match the given key order (from single-row drag). */
reorderColumns: (orderedKeys: string[]) => void;
/**
@@ -122,6 +128,21 @@ export const useFleetStore = create<FleetState>()(
rowByKey,
};
}),
+ removeColumns: (keys) =>
+ set((s) => {
+ if (keys.length === 0) return {};
+ const remove = new Set(keys);
+ const rowByKey = { ...s.rowByKey };
+ for (const key of remove) delete rowByKey[key];
+ const dismissedKeys = [...s.dismissedKeys];
+ for (const key of remove) if (!dismissedKeys.includes(key)) dismissedKeys.push(key);
+ return {
+ columns: s.columns.filter((c) => !remove.has(c.key)),
+ dismissedKeys,
+ pinnedKeys: s.pinnedKeys.filter((k) => !remove.has(k)),
+ rowByKey,
+ };
+ }),
reorderColumns: (orderedKeys) =>
set((s) => {
const byKey = new Map(s.columns.map((c) => [c.key, c]));
diff --git a/src/features/PageEditor/PageAgentProvider.test.tsx b/src/features/PageEditor/PageAgentProvider.test.tsx
index f85fa3d54b4..3a1917323b0 100644
--- a/src/features/PageEditor/PageAgentProvider.test.tsx
+++ b/src/features/PageEditor/PageAgentProvider.test.tsx
@@ -185,6 +185,33 @@ describe('PageAgentProvider', () => {
expect(context.agentId).toBe('page-agent');
});
+ it('can avoid syncing the page agent into global agent state', async () => {
+ agentState.activeAgentId = 'claude-code';
+ agentState.heterogeneousAgentIds = ['claude-code'];
+ chatState.activeAgentId = 'claude-code';
+ chatState.activeTopicId = 'topic-1';
+
+ render(
+ <PageAgentProvider pageId="doc-1" syncActiveAgent={false}>
+ <div>child</div>
+ </PageAgentProvider>,
+ );
+
+ await waitFor(() => {
+ expect(conversationProviderSpy).toHaveBeenCalled();
+ });
+
+ const { context } = conversationProviderSpy.mock.calls.at(-1)![0];
+ expect(context.agentId).toBe('page-agent');
+ expect(context.documentId).toBe('doc-1');
+ expect(context.topicId).toBeNull();
+ expect(agentState.activeAgentId).toBe('claude-code');
+ expect(agentState.setActiveAgentId).not.toHaveBeenCalled();
+ expect(chatState.activeAgentId).toBe('claude-code');
+ expect(chatState.activeTopicId).toBe('topic-1');
+ expect(chatState.switchTopic).not.toHaveBeenCalled();
+ });
+
it('injects the open document id into the conversation context', async () => {
render(
<PageAgentProvider pageId="doc-1">
diff --git a/src/features/PageEditor/PageAgentProvider.tsx b/src/features/PageEditor/PageAgentProvider.tsx
index 665705b53b3..53e7a8111f5 100644
--- a/src/features/PageEditor/PageAgentProvider.tsx
+++ b/src/features/PageEditor/PageAgentProvider.tsx
@@ -22,92 +22,100 @@ interface PageAgentProviderProps {
* gets cleared/overwritten when switching tabs.
*/
pageId?: string;
+ /**
+ * Keep legacy page-editor behavior: sync the selected page copilot agent into
+ * the global agent/chat stores. Disable when PageEditor is embedded inside an
+ * existing agent layout that must keep its own active agent and working panel.
+ */
+ syncActiveAgent?: boolean;
}
-export const PageAgentProvider = memo<PageAgentProviderProps>(({ children, pageId }) => {
- const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
- const pageAgentId = useAgentStore(builtinAgentSelectors.pageAgentId);
- const activeTopicId = useChatStore((s) => s.activeTopicId);
- const activeAgentId = useAgentStore((s) => s.activeAgentId);
- const isActiveAgentHeterogeneous = useAgentStore((s) =>
- activeAgentId ? agentByIdSelectors.isAgentHeterogeneousById(activeAgentId)(s) : false,
- );
- const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);
- const syncedAgentIdRef = useRef<string | undefined>(undefined);
-
- useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.pageAgent);
-
- // Build conversation context for page agent.
- // Fall back to the page agent when the global active agent cannot drive a page
- // copilot: empty, a chat-group id, or a heterogeneous agent (e.g. Claude Code
- // / Codex). Heterogeneous agents run on external runtimes and must not leak
- // into the page-scoped conversation when navigating from their tab.
- const selectedAgentId =
- !activeAgentId || isChatGroupSessionId(activeAgentId) || isActiveAgentHeterogeneous
- ? pageAgentId
- : activeAgentId;
-
- useEffect(() => {
- if (!selectedAgentId) return;
-
- if (useAgentStore.getState().activeAgentId !== selectedAgentId) {
- setActiveAgentId(selectedAgentId);
- }
-
- const chatState = useChatStore.getState();
- const shouldResetTopic =
- chatState.activeAgentId !== selectedAgentId || !!chatState.activeTopicId;
-
- if (chatState.activeAgentId !== selectedAgentId) {
- useChatStore.setState(
- { activeAgentId: selectedAgentId },
- false,
- 'PageEditor/PageAgentProvider/syncActiveAgentId',
- );
- }
-
- if (syncedAgentIdRef.current === selectedAgentId) return;
- syncedAgentIdRef.current = selectedAgentId;
-
- if (shouldResetTopic) {
- void chatState.switchTopic(null, { scope: 'page', skipRefreshMessage: true });
- }
- }, [selectedAgentId, setActiveAgentId]);
-
- const context = useMemo<ConversationContext>(
- () => ({
- agentId: selectedAgentId,
- // Bind the conversation to the open document directly so page-scoped tool
- // calls don't depend on the `pageAgentRuntime` singleton, which can't
- // represent multiple tabs/documents and is cleared on tab switch.
- documentId: pageId,
- scope: 'page',
- topicId: activeTopicId, // No topic initially, can be extended later
- }),
- [selectedAgentId, activeTopicId, pageId],
- );
-
- // Get messages from ChatStore based on context
- const chatKey = useMemo(() => messageMapKey(context), [context]);
- const replaceMessages = useChatStore((s) => s.replaceMessages);
- const messages = useChatStore((s) => (chatKey ? s.dbMessagesMap[chatKey] : undefined));
-
- // Get operation state for reactive updates
- const operationState = useOperationState(context);
-
- if (!pageAgentId) return <Loading debugId="PageAgentProvider" />;
-
- return (
- <ConversationProvider
- context={context}
- hasInitMessages={!!messages}
- messages={messages}
- operationState={operationState}
- onMessagesChange={(msgs, ctx) => {
- replaceMessages(msgs, { context: ctx });
- }}
- >
- {children}
- </ConversationProvider>
- );
-});
+export const PageAgentProvider = memo<PageAgentProviderProps>(
+ ({ children, pageId, syncActiveAgent = true }) => {
+ const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
+ const pageAgentId = useAgentStore(builtinAgentSelectors.pageAgentId);
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const isActiveAgentHeterogeneous = useAgentStore((s) =>
+ activeAgentId ? agentByIdSelectors.isAgentHeterogeneousById(activeAgentId)(s) : false,
+ );
+ const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);
+ const syncedAgentIdRef = useRef<string | undefined>(undefined);
+
+ useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.pageAgent);
+
+ // Build conversation context for page agent.
+ // Fall back to the page agent when the global active agent cannot drive a page
+ // copilot: empty, a chat-group id, or a heterogeneous agent (e.g. Claude Code
+ // / Codex). Heterogeneous agents run on external runtimes and must not leak
+ // into the page-scoped conversation when navigating from their tab.
+ const selectedAgentId =
+ !activeAgentId || isChatGroupSessionId(activeAgentId) || isActiveAgentHeterogeneous
+ ? pageAgentId
+ : activeAgentId;
+
+ useEffect(() => {
+ if (!selectedAgentId || !syncActiveAgent) return;
+
+ if (useAgentStore.getState().activeAgentId !== selectedAgentId) {
+ setActiveAgentId(selectedAgentId);
+ }
+
+ const chatState = useChatStore.getState();
+ const shouldResetTopic =
+ chatState.activeAgentId !== selectedAgentId || !!chatState.activeTopicId;
+
+ if (chatState.activeAgentId !== selectedAgentId) {
+ useChatStore.setState(
+ { activeAgentId: selectedAgentId },
+ false,
+ 'PageEditor/PageAgentProvider/syncActiveAgentId',
+ );
+ }
+
+ if (syncedAgentIdRef.current === selectedAgentId) return;
+ syncedAgentIdRef.current = selectedAgentId;
+
+ if (shouldResetTopic) {
+ void chatState.switchTopic(null, { scope: 'page', skipRefreshMessage: true });
+ }
+ }, [selectedAgentId, setActiveAgentId, syncActiveAgent]);
+
+ const context = useMemo<ConversationContext>(
+ () => ({
+ agentId: selectedAgentId,
+ // Bind the conversation to the open document directly so page-scoped tool
+ // calls don't depend on the `pageAgentRuntime` singleton, which can't
+ // represent multiple tabs/documents and is cleared on tab switch.
+ documentId: pageId,
+ scope: 'page',
+ topicId: syncActiveAgent ? activeTopicId : null,
+ }),
+ [selectedAgentId, activeTopicId, pageId, syncActiveAgent],
+ );
+
+ // Get messages from ChatStore based on context
+ const chatKey = useMemo(() => messageMapKey(context), [context]);
+ const replaceMessages = useChatStore((s) => s.replaceMessages);
+ const messages = useChatStore((s) => (chatKey ? s.dbMessagesMap[chatKey] : undefined));
+
+ // Get operation state for reactive updates
+ const operationState = useOperationState(context);
+
+ if (!pageAgentId) return <Loading debugId="PageAgentProvider" />;
+
+ return (
+ <ConversationProvider
+ context={context}
+ hasInitMessages={!!messages}
+ messages={messages}
+ operationState={operationState}
+ onMessagesChange={(msgs, ctx) => {
+ replaceMessages(msgs, { context: ctx });
+ }}
+ >
+ {children}
+ </ConversationProvider>
+ );
+ },
+);
diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsx
index 2363f8a8009..45142a28f9a 100644
--- a/src/features/PageEditor/PageEditor.tsx
+++ b/src/features/PageEditor/PageEditor.tsx
@@ -115,15 +115,30 @@ interface PageEditorProps {
onSave?: () => void;
onTitleChange?: (title: string) => void;
pageId?: string;
+ /**
+ * Render the built-in right panel (page copilot / history). Defaults to true.
+ * Set false when an outer layout supplies its own right panel (e.g. the
+ * agent-document route keeps the agent working sidebar instead).
+ */
+ rightPanel?: boolean;
+ /**
+ * Whether PageEditor should sync its page-copilot agent into the global
+ * agent/chat stores. Defaults to true for normal Pages. Set false when the
+ * editor is embedded under an existing agent layout that must preserve its
+ * own active agent and topic state.
+ */
+ syncPageAgentActiveState?: boolean;
title?: string;
}
interface PageEditorCanvasProps {
fullWidthHeader?: boolean;
header?: PageEditorHeader;
+ rightPanel?: boolean;
}
-const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader }) => {
+const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader, rightPanel }) => {
+ const showRightPanel = rightPanel !== false;
const editable = usePageEditable();
const editor = usePageEditorStore((s) => s.editor);
const documentId = usePageEditorStore((s) => s.documentId);
@@ -303,7 +318,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader
{headerSlot}
<Flexbox horizontal flex={1} style={{ minHeight: 0 }} width={'100%'}>
{editorPane}
- <RightPanel />
+ {showRightPanel && <RightPanel />}
</Flexbox>
</Flexbox>
);
@@ -317,7 +332,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader
width={'100%'}
>
{editorPane}
- <RightPanel />
+ {showRightPanel && <RightPanel />}
</Flexbox>
);
});
@@ -339,12 +354,14 @@ export const PageEditor: FC<PageEditorProps> = ({
onBack,
title,
emoji,
+ rightPanel,
+ syncPageAgentActiveState,
}) => {
const { allowed: canEdit } = usePermission('edit_own_content');
const deletePage = usePageStore((s) => s.deletePage);
return (
- <PageAgentProvider pageId={pageId}>
+ <PageAgentProvider pageId={pageId} syncActiveAgent={syncPageAgentActiveState}>
<EditorProvider>
<PageEditorProvider
emoji={emoji}
@@ -374,7 +391,11 @@ export const PageEditor: FC<PageEditorProps> = ({
onTitleChange?.(nextTitle);
}}
>
- <PageEditorCanvas fullWidthHeader={fullWidthHeader} header={header} />
+ <PageEditorCanvas
+ fullWidthHeader={fullWidthHeader}
+ header={header}
+ rightPanel={rightPanel}
+ />
</PageEditorProvider>
</EditorProvider>
</PageAgentProvider>
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index 1e0bdde719d..e9add3a2b58 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -11,12 +11,12 @@ import { useTranslation } from 'react-i18next';
import CodeEditorPane from '@/components/CodeEditorPane';
import FloatingChatPanel from '@/features/FloatingChatPanel';
+import WideScreenContainer from '@/features/WideScreenContainer';
import { useClientDataSWR } from '@/libs/swr';
import { portalKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
import { useDocumentStore } from '@/store/document';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
@@ -27,6 +27,11 @@ import {
parseSkillMarkdownMetadata,
} from '@/utils/skillMarkdown';
+import {
+ useDocumentViewFullPage,
+ useResolvedAgentDocumentId,
+ useResolvedDocumentId,
+} from './documentViewContext';
import EditorCanvas from './EditorCanvas';
import TodoList from './TodoList';
@@ -36,6 +41,11 @@ const styles = createStaticStyles(({ css }) => ({
flex: 1;
padding-inline: 16px;
`,
+ contentFull: css`
+ /* Width is handled by WideScreenContainer; keep only the scroll host. */
+ overflow: auto;
+ flex: 1;
+ `,
frontmatter: css`
margin-block: 16px 12px;
border: 1px solid ${cssVar.colorBorderSecondary};
@@ -310,8 +320,9 @@ const HighlightEditor = memo<HighlightEditorProps>(({ content, documentId, langu
HighlightEditor.displayName = 'HighlightEditor';
const DocumentBody = memo(() => {
- const documentId = useChatStore(chatPortalSelectors.portalDocumentId);
- const agentDocumentId = useChatStore(chatPortalSelectors.portalAgentDocumentId);
+ const documentId = useResolvedDocumentId();
+ const agentDocumentId = useResolvedAgentDocumentId();
+ const fullPage = useDocumentViewFullPage();
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const activeTopicId = useChatStore((s) => s.activeTopicId);
const enableFloatingChatPanel = useUserStore(
@@ -341,26 +352,34 @@ const DocumentBody = memo(() => {
[mutateDocumentMeta],
);
+ const editorContent = (
+ <>
+ {documentId && isSkillMarkdown && (
+ <SkillFrontmatterBlock documentId={documentId} frontmatter={skillFrontmatter} />
+ )}
+ {renderMode.mode === 'highlight' && documentId ? (
+ <HighlightEditor
+ content={documentMeta?.content ?? ''}
+ documentId={documentId}
+ key={documentId}
+ language={renderMode.language}
+ onSaved={handleHighlightSaved}
+ />
+ ) : (
+ <EditorCanvas />
+ )}
+ </>
+ );
+
return (
<Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
- <div className={styles.content}>
- {documentId && isSkillMarkdown && (
- <SkillFrontmatterBlock documentId={documentId} frontmatter={skillFrontmatter} />
- )}
- {renderMode.mode === 'highlight' && documentId ? (
- <HighlightEditor
- content={documentMeta?.content ?? ''}
- documentId={documentId}
- key={documentId}
- language={renderMode.language}
- onSaved={handleHighlightSaved}
- />
- ) : (
- <EditorCanvas />
- )}
+ <div className={fullPage ? styles.contentFull : styles.content}>
+ {fullPage ? <WideScreenContainer>{editorContent}</WideScreenContainer> : editorContent}
</div>
<TodoList />
- {enableFloatingChatPanel && activeAgentId && (
+ {/* The full-page route surfaces chat through the working sidebar, so the
+ floating panel only belongs to the compact in-chat portal. */}
+ {!fullPage && enableFloatingChatPanel && activeAgentId && (
<FloatingChatPanel
agentDocumentId={agentDocumentId}
agentId={activeAgentId}
diff --git a/src/features/Portal/Document/EditorCanvas.tsx b/src/features/Portal/Document/EditorCanvas.tsx
index f628d6d97bc..0bc75b2a53a 100644
--- a/src/features/Portal/Document/EditorCanvas.tsx
+++ b/src/features/Portal/Document/EditorCanvas.tsx
@@ -4,13 +4,13 @@ import { useEditor } from '@lobehub/editor/react';
import { memo } from 'react';
import { EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
+
+import { useResolvedDocumentId } from './documentViewContext';
const EditorCanvas = memo(() => {
const editor = useEditor();
- const documentId = useChatStore(chatPortalSelectors.portalDocumentId);
+ const documentId = useResolvedDocumentId();
return <SharedEditorCanvas documentId={documentId} editor={editor} sourceType="notebook" />;
});
diff --git a/src/features/Portal/Document/Header.tsx b/src/features/Portal/Document/Header.tsx
index ea2c5cff836..ad4e3d0bf44 100644
--- a/src/features/Portal/Document/Header.tsx
+++ b/src/features/Portal/Document/Header.tsx
@@ -6,15 +6,14 @@ import { cx } from 'antd-style';
import { useClientDataSWR } from '@/libs/swr';
import { portalKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
import { oneLineEllipsis } from '@/styles';
import { getDocumentRenderMode } from '@/utils/documentRenderMode';
import AutoSaveHint from './AutoSaveHint';
+import { useResolvedDocumentId } from './documentViewContext';
const Header = () => {
- const documentId = useChatStore(chatPortalSelectors.portalDocumentId);
+ const documentId = useResolvedDocumentId();
const { data: document, isLoading } = useClientDataSWR(
documentId ? portalKeys.documentHeader(documentId) : null,
diff --git a/src/features/Portal/Document/PortalHeader.tsx b/src/features/Portal/Document/PortalHeader.tsx
new file mode 100644
index 00000000000..770e44dc3dd
--- /dev/null
+++ b/src/features/Portal/Document/PortalHeader.tsx
@@ -0,0 +1,48 @@
+'use client';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
+import { ActionIcon } from '@lobehub/ui';
+import { Maximize2Icon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';
+import PortalChromeHeader from '@/features/Portal/components/Header';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+
+import { useResolvedDocumentId } from './documentViewContext';
+import DocumentTitle from './Header';
+
+/**
+ * Expands the in-chat document portal into the full-page document route, then
+ * collapses the portal so returning to chat lands on a clean conversation.
+ */
+const OpenAsPageAction = memo(() => {
+ const { t } = useTranslation('chat');
+ const documentId = useResolvedDocumentId();
+ const agentId = useAgentStore((s) => s.activeAgentId);
+ const navigate = useWorkspaceAwareNavigate();
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+
+ if (!documentId || !agentId) return null;
+
+ return (
+ <ActionIcon
+ icon={Maximize2Icon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('agentDocument.openAsPage')}
+ onClick={() => {
+ navigate(buildAgentDocumentPath(agentId, documentId));
+ clearPortalStack();
+ }}
+ />
+ );
+});
+
+const PortalHeader = memo(() => (
+ <PortalChromeHeader rightExtra={<OpenAsPageAction />} title={<DocumentTitle />} />
+));
+
+export default PortalHeader;
diff --git a/src/features/Portal/Document/Wrapper.tsx b/src/features/Portal/Document/Wrapper.tsx
index 96769986920..3026f2a0de0 100644
--- a/src/features/Portal/Document/Wrapper.tsx
+++ b/src/features/Portal/Document/Wrapper.tsx
@@ -4,11 +4,10 @@ import { EditorProvider } from '@lobehub/editor/react';
import { type PropsWithChildren } from 'react';
import { memo } from 'react';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useResolvedDocumentId } from './documentViewContext';
const Wrapper = memo<PropsWithChildren>(({ children }) => {
- const documentId = useChatStore(chatPortalSelectors.portalDocumentId);
+ const documentId = useResolvedDocumentId();
if (!documentId) return null;
diff --git a/src/features/Portal/Document/documentViewContext.ts b/src/features/Portal/Document/documentViewContext.ts
new file mode 100644
index 00000000000..a8de68f671b
--- /dev/null
+++ b/src/features/Portal/Document/documentViewContext.ts
@@ -0,0 +1,47 @@
+'use client';
+
+import { createContext, useContext } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+interface DocumentViewContextValue {
+ agentDocumentId?: string;
+ documentId?: string;
+ /**
+ * Standalone full-page document route (vs. the in-chat portal). When set, the
+ * editor content is width-constrained like the conversation and the floating
+ * chat panel is hidden (the working sidebar already provides chat).
+ */
+ fullPage?: boolean;
+}
+
+const DocumentViewContext = createContext<DocumentViewContextValue | null>(null);
+
+/**
+ * Provide an explicit document id to the shared Document viewer primitives
+ * (Wrapper / Header / Body / EditorCanvas), so they can render outside the chat
+ * portal stack — e.g. on the standalone `/agent/:aid/docs/:docId` route.
+ */
+export const DocumentViewProvider = DocumentViewContext.Provider;
+
+/**
+ * Document id for the current viewer. Inside a {@link DocumentViewProvider} it
+ * returns the provided id; otherwise it falls back to the portal stack, so the
+ * in-chat portal keeps working unchanged.
+ */
+export const useResolvedDocumentId = (): string | undefined => {
+ const ctx = useContext(DocumentViewContext);
+ const portalDocumentId = useChatStore(chatPortalSelectors.portalDocumentId);
+ return ctx ? ctx.documentId : portalDocumentId;
+};
+
+/** Agent-documents association id, resolved the same way as the document id. */
+export const useResolvedAgentDocumentId = (): string | undefined => {
+ const ctx = useContext(DocumentViewContext);
+ const portalAgentDocumentId = useChatStore(chatPortalSelectors.portalAgentDocumentId);
+ return ctx ? ctx.agentDocumentId : portalAgentDocumentId;
+};
+
+/** Whether the viewer is the standalone full-page route (vs. the in-chat portal). */
+export const useDocumentViewFullPage = (): boolean => !!useContext(DocumentViewContext)?.fullPage;
diff --git a/src/features/Portal/Document/index.ts b/src/features/Portal/Document/index.ts
index 20b62f609c4..09ac04e7cb5 100644
--- a/src/features/Portal/Document/index.ts
+++ b/src/features/Portal/Document/index.ts
@@ -1,10 +1,12 @@
import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
+import PortalHeader from './PortalHeader';
import Wrapper from './Wrapper';
export const Document: PortalImpl = {
Body,
+ Header: PortalHeader,
Title: Header,
Wrapper,
};
diff --git a/src/routes/(main)/agent/(chat)/_layout/index.tsx b/src/routes/(main)/agent/(chat)/_layout/index.tsx
index a28ac0d4f1f..dceeb55a5e5 100644
--- a/src/routes/(main)/agent/(chat)/_layout/index.tsx
+++ b/src/routes/(main)/agent/(chat)/_layout/index.tsx
@@ -13,7 +13,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import HeaderSlot from './HeaderSlot';
const ChatLayout = memo(() => {
- const showHeader = useGlobalStore(systemStatusSelectors.showChatHeader);
+ const showChatHeader = useGlobalStore(systemStatusSelectors.showChatHeader);
return (
<HeaderSlot.Provider>
@@ -25,7 +25,7 @@ const ChatLayout = memo(() => {
width={'100%'}
>
<Flexbox flex={1} style={{ minHeight: 0, minWidth: 0 }}>
- {showHeader && <ChatHeader />}
+ {showChatHeader && <ChatHeader />}
<Flexbox flex={1} style={{ minHeight: 0, position: 'relative' }}>
<Outlet />
</Flexbox>
diff --git a/src/routes/(main)/agent/docs/[docId]/index.tsx b/src/routes/(main)/agent/docs/[docId]/index.tsx
new file mode 100644
index 00000000000..2306a7c7028
--- /dev/null
+++ b/src/routes/(main)/agent/docs/[docId]/index.tsx
@@ -0,0 +1,24 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+import { useParams } from 'react-router-dom';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentDocumentPage from '@/features/AgentDocumentPage';
+import { getIdFromIdentifier } from '@/utils/identifier';
+
+const AgentDocumentRoute = memo(() => {
+ const { docId } = useParams<{ docId: string }>();
+ const documentId = getIdFromIdentifier(docId ?? '', 'docs');
+
+ return (
+ <Suspense fallback={<Loading debugId="AgentDocumentRoute" />}>
+ {/* key remounts the editor when switching between documents */}
+ <AgentDocumentPage documentId={documentId} key={documentId} />
+ </Suspense>
+ );
+});
+
+AgentDocumentRoute.displayName = 'AgentDocumentRoute';
+
+export default AgentDocumentRoute;
diff --git a/src/routes/(main)/agent/docs/_layout/index.tsx b/src/routes/(main)/agent/docs/_layout/index.tsx
new file mode 100644
index 00000000000..bc9568fcaee
--- /dev/null
+++ b/src/routes/(main)/agent/docs/_layout/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/AgentDocumentPage/Layout';
diff --git a/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsx b/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsx
index 1de1882b6d8..b46056b4a2b 100644
--- a/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsx
+++ b/src/routes/(main)/agent/features/Conversation/AgentWelcome/ToolAuthAlert.tsx
@@ -2,11 +2,11 @@
import { type ComposioAppType } from '@lobechat/const';
import { COMPOSIO_APP_TYPES } from '@lobechat/const';
-import { Alert, Avatar, Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { ActionIcon, Alert, Avatar, Button, Flexbox, Icon, Text } from '@lobehub/ui';
import { Divider } from 'antd';
-import { cssVar } from 'antd-style';
+import { createStyles, cssVar } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { PlusIcon } from 'lucide-react';
+import { PlusIcon, XIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -20,6 +20,19 @@ import { ComposioServerStatus, composioStoreSelectors } from '@/store/tool/slice
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+const useStyles = createStyles(({ css }) => ({
+ // Reveal the remove icon only when the row is hovered.
+ row: css`
+ &:hover .tool-auth-remove {
+ opacity: 1;
+ }
+ `,
+ removeIcon: css`
+ opacity: 0;
+ transition: opacity 0.2s ease;
+ `,
+}));
+
// Tools that require Market authentication
const MARKET_AUTH_TOOLS = [
{
@@ -53,6 +66,7 @@ interface ComposioToolAuthItemProps {
const ComposioToolAuthItem = memo<ComposioToolAuthItemProps>(({ tool, onAuthComplete }) => {
const { t } = useTranslation('chat');
+ const { styles, cx } = useStyles();
const [isConnecting, setIsConnecting] = useState(false);
const [isWaitingAuth, setIsWaitingAuth] = useState(false);
@@ -64,6 +78,8 @@ const ComposioToolAuthItem = memo<ComposioToolAuthItemProps>(({ tool, onAuthComp
const userId = useUserStore(userProfileSelectors.userId);
const createComposioConnection = useToolStore((s) => s.createComposioConnection);
const refreshComposioConnectionStatus = useToolStore((s) => s.refreshComposioConnectionStatus);
+ const removeComposioConnection = useToolStore((s) => s.removeComposioConnection);
+ const removePlugin = useAgentStore((s) => s.removePlugin);
const cleanup = useCallback(() => {
if (windowCheckIntervalRef.current) {
@@ -190,6 +206,17 @@ const ComposioToolAuthItem = memo<ComposioToolAuthItemProps>(({ tool, onAuthComp
}
};
+ // Remove this connector from the agent. It's not authorized yet, so also drop
+ // any pending connection (best-effort) so a later reconnect starts clean.
+ const handleRemove = async () => {
+ if (tool.server) await removeComposioConnection(tool.server.identifier);
+ try {
+ await removePlugin(tool.identifier);
+ } catch (error) {
+ console.error('[ToolAuthAlert] Failed to remove plugin:', error);
+ }
+ };
+
const renderIcon = () => {
if (typeof tool.icon === 'string') {
return <Avatar alt={tool.label} avatar={tool.icon} size={20} style={{ flex: 'none' }} />;
@@ -203,6 +230,7 @@ const ComposioToolAuthItem = memo<ComposioToolAuthItemProps>(({ tool, onAuthComp
<Flexbox
horizontal
align="center"
+ className={cx(styles.row)}
gap={12}
justify="space-between"
style={{
@@ -213,6 +241,16 @@ const ComposioToolAuthItem = memo<ComposioToolAuthItemProps>(({ tool, onAuthComp
<Flexbox horizontal align="center" gap={8}>
{renderIcon()}
<Text>{tool.label}</Text>
+ <ActionIcon
+ className={cx('tool-auth-remove', styles.removeIcon)}
+ icon={XIcon}
+ size="small"
+ title={t('toolAuth.remove')}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleRemove();
+ }}
+ />
</Flexbox>
<Button
disabled={isLoading}
@@ -236,7 +274,9 @@ interface MarketToolAuthItemProps {
const MarketToolAuthItem = memo<MarketToolAuthItemProps>(({ tool }) => {
const { t } = useTranslation('chat');
+ const { styles, cx } = useStyles();
const { signIn, isLoading } = useMarketAuth();
+ const removePlugin = useAgentStore((s) => s.removePlugin);
const handleSignIn = async () => {
try {
@@ -246,10 +286,19 @@ const MarketToolAuthItem = memo<MarketToolAuthItemProps>(({ tool }) => {
}
};
+ const handleRemove = async () => {
+ try {
+ await removePlugin(tool.identifier);
+ } catch (error) {
+ console.error('[ToolAuthAlert] Failed to remove plugin:', error);
+ }
+ };
+
return (
<Flexbox
horizontal
align="center"
+ className={cx(styles.row)}
gap={12}
justify="space-between"
style={{
@@ -260,6 +309,16 @@ const MarketToolAuthItem = memo<MarketToolAuthItemProps>(({ tool }) => {
<Flexbox horizontal align="center" gap={8}>
<Avatar alt={tool.label} avatar={tool.avatar} size={20} style={{ flex: 'none' }} />
<Text>{tool.label}</Text>
+ <ActionIcon
+ className={cx('tool-auth-remove', styles.removeIcon)}
+ icon={XIcon}
+ size="small"
+ title={t('toolAuth.remove')}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleRemove();
+ }}
+ />
</Flexbox>
<Button
disabled={isLoading}
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 dca11d90b89..548e0d843b8 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
@@ -6,6 +6,7 @@ import {
} from '@lobechat/const';
import { fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import type * as ReactRouterDom from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import AgentDocumentsGroup from './AgentDocumentsGroup';
@@ -14,7 +15,10 @@ const useClientDataSWR = vi.fn();
const modalConfirm = vi.hoisted(() => vi.fn());
const messageError = vi.hoisted(() => vi.fn());
const messageSuccess = vi.hoisted(() => vi.fn());
+const navigateMock = vi.hoisted(() => vi.fn());
+const openDocumentMock = vi.hoisted(() => vi.fn());
const removeDocumentMock = vi.hoisted(() => vi.fn());
+const useParamsMock = vi.hoisted(() => vi.fn());
vi.mock('@lobehub/ui/base-ui', () => ({
confirmModal: modalConfirm,
@@ -88,11 +92,31 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('@/features/AgentDocumentsExplorer', () => ({
- DocumentExplorerTree: ({ data }: { data: unknown[] }) => (
- <div data-doc-count={data.length} data-testid="document-explorer-tree" />
+ DocumentExplorerTree: ({
+ data,
+ onOpenDocument,
+ }: {
+ data: { documentId: string; id: string; title?: string }[];
+ onOpenDocument?: (documentId: string, agentDocumentId?: string) => void;
+ }) => (
+ <div data-doc-count={data.length} data-testid="document-explorer-tree">
+ {data.map((doc) => (
+ <button
+ data-testid={`tree-open-${doc.id}`}
+ key={doc.id}
+ onClick={() => onOpenDocument?.(doc.documentId, doc.id)}
+ >
+ {doc.title}
+ </button>
+ ))}
+ </div>
),
}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => navigateMock,
+}));
+
vi.mock('@/features/SkillsList', () => {
type Item = { fileCount?: number; id: string; name: string };
const SkillsList = ({
@@ -183,19 +207,18 @@ vi.mock('@/store/agent', () => ({
selector({ activeAgentId: 'agent-1', agentMap: {} }),
}));
-const openDocument = vi.fn();
-const closeDocument = vi.fn();
-
vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({ closeDocument, openDocument, portalStack: [] }),
+ useChatStore: (selector: (state: { openDocument: typeof openDocumentMock }) => unknown) =>
+ selector({ openDocument: openDocumentMock }),
}));
-vi.mock('@/store/chat/selectors', () => ({
- chatPortalSelectors: {
- portalDocumentId: () => null,
- },
-}));
+vi.mock('react-router-dom', async () => {
+ const actual = await vi.importActual<typeof ReactRouterDom>('react-router-dom');
+ return {
+ ...actual,
+ useParams: useParamsMock,
+ };
+});
const skillBundleRow = {
category: AGENT_DOCUMENT_SKILL_CATEGORY,
@@ -272,13 +295,14 @@ const webDocRow = {
describe('AgentDocumentsGroup', () => {
beforeEach(() => {
useClientDataSWR.mockReset();
- closeDocument.mockReset();
modalConfirm.mockReset();
messageError.mockReset();
messageSuccess.mockReset();
- openDocument.mockReset();
+ navigateMock.mockReset();
+ openDocumentMock.mockReset();
removeDocumentMock.mockReset();
removeDocumentMock.mockResolvedValue({ deleted: true, id: 'doc-1' });
+ useParamsMock.mockReturnValue({});
});
it('defaults to the Skills tab and renders skill bundles via SkillsList', () => {
@@ -301,7 +325,7 @@ describe('AgentDocumentsGroup', () => {
expect(screen.queryByText('Example')).not.toBeInTheDocument();
});
- it('opens the SKILL.md document when clicking a skill bundle row', () => {
+ it('opens the SKILL.md document in the portal when clicking a skill bundle row', () => {
useClientDataSWR.mockReturnValue({
data: [skillBundleRow, skillIndexRow],
error: undefined,
@@ -312,7 +336,8 @@ describe('AgentDocumentsGroup', () => {
render(<AgentDocumentsGroup />);
fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));
- expect(openDocument).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');
+ expect(openDocumentMock).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');
+ expect(navigateMock).not.toHaveBeenCalled();
});
it('falls back to the bundle id when opening an orphan skill bundle', () => {
@@ -326,7 +351,8 @@ describe('AgentDocumentsGroup', () => {
render(<AgentDocumentsGroup />);
fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));
- expect(openDocument).toHaveBeenCalledWith('skill-bundle-doc', 'skill-bundle-row');
+ expect(openDocumentMock).toHaveBeenCalledWith('skill-bundle-doc', 'skill-bundle-row');
+ expect(navigateMock).not.toHaveBeenCalled();
});
it('opens a child file by relative path through onOpenFile', () => {
@@ -340,7 +366,24 @@ describe('AgentDocumentsGroup', () => {
render(<AgentDocumentsGroup />);
fireEvent.click(screen.getByTestId('skill-skill-bundle-doc-open-skill-md'));
- expect(openDocument).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');
+ expect(openDocumentMock).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');
+ expect(navigateMock).not.toHaveBeenCalled();
+ });
+
+ it('routes directly when opening a skill from document mode', () => {
+ useParamsMock.mockReturnValue({ docId: 'doc-content-1' });
+ useClientDataSWR.mockReturnValue({
+ data: [skillBundleRow, skillIndexRow],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup activeFilter="skills" />);
+
+ fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agent-1/docs/skill-index-doc');
+ expect(openDocumentMock).not.toHaveBeenCalled();
});
it('renders the document tree when switching to the Documents tab', () => {
@@ -362,6 +405,113 @@ describe('AgentDocumentsGroup', () => {
expect(tree).toHaveAttribute('data-doc-count', '1');
});
+ it('opens document tree files in the portal by default', () => {
+ useClientDataSWR.mockReturnValue({
+ data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ fireEvent.click(screen.getByText('Documents'));
+ fireEvent.click(screen.getByTestId('tree-open-doc-1'));
+
+ expect(openDocumentMock).toHaveBeenCalledWith('doc-content-1', 'doc-1');
+ expect(navigateMock).not.toHaveBeenCalled();
+ });
+
+ it('routes document tree files directly in document mode', () => {
+ useParamsMock.mockReturnValue({ docId: 'doc-content-1' });
+ useClientDataSWR.mockReturnValue({
+ data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ fireEvent.click(screen.getByTestId('tree-open-doc-1'));
+
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agent-1/docs/doc-content-1');
+ expect(openDocumentMock).not.toHaveBeenCalled();
+ });
+
+ it('defaults to Documents first in document mode and keeps Skills as the second tab', () => {
+ useParamsMock.mockReturnValue({ docId: 'doc-content-1' });
+ useClientDataSWR.mockReturnValue({
+ data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual([
+ 'Documents',
+ 'Skills',
+ ]);
+ expect(screen.queryByText('Web')).not.toBeInTheDocument();
+
+ const tree = screen.getByTestId('document-explorer-tree');
+ expect(tree).toBeInTheDocument();
+ expect(tree).toHaveAttribute('data-doc-count', '1');
+ expect(screen.queryByTestId('skills-list')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Skills'));
+ expect(screen.getByTestId('skills-list')).toBeInTheDocument();
+ });
+
+ it('can be controlled by an outer page-mode tab bar', () => {
+ useParamsMock.mockReturnValue({ docId: 'doc-content-1' });
+ useClientDataSWR.mockReturnValue({
+ data: [skillBundleRow, skillIndexRow, fileDocRow, webDocRow],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ const { rerender } = render(
+ <AgentDocumentsGroup activeFilter="skills" showFilterTabs={false} />,
+ );
+
+ expect(screen.queryByRole('tab')).not.toBeInTheDocument();
+ expect(screen.getByTestId('skills-list')).toBeInTheDocument();
+ expect(screen.queryByTestId('document-explorer-tree')).not.toBeInTheDocument();
+
+ rerender(<AgentDocumentsGroup activeFilter="documents" showFilterTabs={false} />);
+
+ expect(screen.queryByRole('tab')).not.toBeInTheDocument();
+ expect(screen.getByTestId('document-explorer-tree')).toBeInTheDocument();
+ expect(screen.queryByTestId('skills-list')).not.toBeInTheDocument();
+ });
+
+ it('resets to Documents when entering document mode', () => {
+ useClientDataSWR.mockReturnValue({
+ data: [fileDocRow, webDocRow],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ const { rerender } = render(<AgentDocumentsGroup />);
+ fireEvent.click(screen.getByText('Web'));
+ expect(screen.getByText('Example')).toBeInTheDocument();
+
+ useParamsMock.mockReturnValue({ docId: 'doc-content-1' });
+ rerender(<AgentDocumentsGroup style={{ minHeight: 0 }} />);
+
+ expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual([
+ 'Documents',
+ 'Skills',
+ ]);
+ expect(screen.getByTestId('document-explorer-tree')).toBeInTheDocument();
+ expect(screen.queryByText('Example')).not.toBeInTheDocument();
+ });
+
it('renders web items as cards in the Web tab and supports deletion', async () => {
const mutate = vi.fn().mockResolvedValue(undefined);
useClientDataSWR.mockReturnValue({
@@ -378,7 +528,9 @@ describe('AgentDocumentsGroup', () => {
expect(screen.queryByText('Brief')).not.toBeInTheDocument();
fireEvent.click(screen.getByText('Example'));
- expect(openDocument).toHaveBeenCalledWith('doc-content-2', 'doc-2');
+ expect(openDocumentMock).toHaveBeenCalledWith('doc-content-2', 'doc-2');
+ expect(navigateMock).not.toHaveBeenCalled();
+ openDocumentMock.mockClear();
fireEvent.click(screen.getByLabelText('delete'));
const [firstConfirmCall] = modalConfirm.mock.calls;
@@ -391,6 +543,8 @@ describe('AgentDocumentsGroup', () => {
id: 'doc-2',
});
expect(mutate).toHaveBeenCalled();
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(openDocumentMock).not.toHaveBeenCalled();
expect(messageSuccess).toHaveBeenCalledWith('workingPanel.resources.deleteSuccess');
});
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 a4517dd3f27..f18b49593c3 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -13,10 +13,12 @@ import relativeTime from 'dayjs/plugin/relativeTime';
import type { LucideIcon } from 'lucide-react';
import { EyeIcon, FileTextIcon, GlobeIcon, PencilIcon, Trash2Icon } from 'lucide-react';
import type { CSSProperties, MouseEvent } from 'react';
-import { memo, useMemo, useState } from 'react';
+import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router-dom';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';
import { DocumentExplorerTree } from '@/features/AgentDocumentsExplorer';
import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';
import {
@@ -27,12 +29,13 @@ import {
SkillsList,
useProjectSkills,
} from '@/features/SkillsList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useClientDataSWR } from '@/libs/swr';
import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
+import { standardizeIdentifier } from '@/utils/identifier';
import ProjectLevelSkills from './ProjectLevelSkills';
import UserLevelSkills, { useUserSkills } from './UserLevelSkills';
@@ -40,6 +43,7 @@ import UserLevelSkills, { useUserSkills } from './UserLevelSkills';
dayjs.extend(relativeTime);
type ResourceFilter = 'skills' | 'documents' | 'web';
+type DocumentOpenMode = 'portal' | 'route';
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -107,23 +111,36 @@ const FILTER_OPTIONS = [
{ labelKey: 'workingPanel.resources.filter.web', value: 'web' },
] as const satisfies readonly { labelKey: string; value: ResourceFilter }[];
+const DOCUMENT_MODE_FILTER_OPTIONS = [
+ { labelKey: 'workingPanel.resources.filter.documents', value: 'documents' },
+ { labelKey: 'workingPanel.resources.filter.skills', value: 'skills' },
+] as const satisfies readonly { labelKey: string; value: ResourceFilter }[];
+
type AgentDocumentListItem = Awaited<ReturnType<typeof agentDocumentService.listDocuments>>[number];
interface DocumentItemProps {
+ activeDocumentIdentifier?: string;
agentId: string;
document: AgentDocumentListItem;
hideDelete?: boolean;
mutate: () => Promise<unknown>;
+ onCurrentDeleted?: () => void;
+ onOpenDocument: (documentId: string, agentDocumentId?: string) => void;
}
const DocumentItem = memo<DocumentItemProps>(
- ({ agentId, document, hideDelete = false, mutate }) => {
+ ({
+ activeDocumentIdentifier,
+ agentId,
+ document,
+ hideDelete = false,
+ mutate,
+ onCurrentDeleted,
+ onOpenDocument,
+ }) => {
const { t } = useTranslation(['chat', 'common']);
const { message } = 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 title = document.title || document.filename || '';
const description = document.description ?? undefined;
@@ -136,11 +153,11 @@ const DocumentItem = memo<DocumentItemProps>(
})
: null;
- const isActive = portalDocumentId === document.documentId;
+ const isActive = activeDocumentIdentifier === standardizeIdentifier(document.documentId);
const handleOpen = () => {
if (!document.documentId) return;
- openDocument(document.documentId, document.id);
+ onOpenDocument(document.documentId, document.id);
};
const handleDelete = (e: MouseEvent) => {
@@ -153,13 +170,13 @@ const DocumentItem = memo<DocumentItemProps>(
onOk: async () => {
setDeleting(true);
try {
- if (isActive) closeDocument();
await agentDocumentService.removeDocument({
agentId,
documentId: document.documentId,
id: document.id,
});
await mutate();
+ if (isActive) onCurrentDeleted?.();
message.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));
} catch (error) {
message.error(
@@ -254,26 +271,56 @@ const buildSkillBundleViews = (data: AgentDocumentListItem[]): SkillBundleView[]
};
interface AgentDocumentsGroupProps {
+ activeFilter?: ResourceFilter;
/** Bound remote device id (device mode); skills are then scanned over RPC. */
deviceId?: string;
+ openMode?: DocumentOpenMode;
+ showFilterTabs?: boolean;
+ showLocalProjectSkills?: boolean;
style?: CSSProperties;
workingDirectory?: string;
}
const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
- ({ deviceId, style, workingDirectory }) => {
+ ({
+ activeFilter: controlledFilter,
+ deviceId,
+ openMode,
+ showFilterTabs = true,
+ showLocalProjectSkills = false,
+ style,
+ workingDirectory,
+ }) => {
const { t } = useTranslation('chat');
const { t: tCommon } = useTranslation('common');
const { message } = App.useApp();
const agentId = useAgentStore((s) => s.activeAgentId);
+ const { docId } = useParams<{ docId?: string }>();
+ const navigate = useWorkspaceAwareNavigate();
+ const openDocument = useChatStore((s) => s.openDocument);
+ const isDocumentMode = !!docId;
+ const resolvedOpenMode = openMode ?? (isDocumentMode ? 'route' : 'portal');
const isLocalEnabled = useAgentStore((s) =>
agentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(s) : false,
);
- const openDocument = useChatStore((s) => s.openDocument);
- const [filter, setFilter] = useState<ResourceFilter>('skills');
+ const [filter, setFilter] = useState<ResourceFilter>(() =>
+ isDocumentMode ? 'documents' : 'skills',
+ );
+ const activeDocumentIdentifier = docId ? standardizeIdentifier(docId) : undefined;
+ const filterOptions = isDocumentMode ? DOCUMENT_MODE_FILTER_OPTIONS : FILTER_OPTIONS;
+ const resolvedFilter = controlledFilter ?? filter;
+ const activeFilter = filterOptions.some((option) => option.value === resolvedFilter)
+ ? resolvedFilter
+ : filterOptions[0].value;
+
+ useEffect(() => {
+ if (controlledFilter) return;
+ setFilter(isDocumentMode ? 'documents' : 'skills');
+ }, [controlledFilter, isDocumentMode]);
// Local desktop reads skills over IPC; a bound device reads over RPC.
- const showProjectSkills = (isLocalEnabled || !!deviceId) && !!workingDirectory;
+ const showProjectSkills =
+ (showLocalProjectSkills || isLocalEnabled || !!deviceId) && !!workingDirectory;
// Mirror what each child component reads so the parent can decide the
// section layout (flat when a single source has items, sectioned otherwise).
@@ -335,14 +382,30 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
);
}
+ const openAgentDocument = (documentId: string, agentDocumentId?: string) => {
+ if (!agentId) return;
+ if (resolvedOpenMode === 'portal') {
+ openDocument(
+ documentId,
+ agentDocumentId ?? data.find((doc) => doc.documentId === documentId)?.id,
+ );
+ return;
+ }
+ navigate(buildAgentDocumentPath(agentId, documentId));
+ };
+
+ const backToChat = () => {
+ if (!agentId) return;
+ navigate(`/agent/${agentId}`);
+ };
+
// Open the SKILL.md (skills/index child) when present; fall back to the
// bundle itself (orphan bundles surface for recovery).
const openAgentSkill = (item: SkillListItem) => {
const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
const indexChild = data.find((doc) => doc.parentId === item.id && doc.isSkillIndex);
const targetDocId = indexChild?.documentId ?? view?.bundle.documentId ?? item.id;
- const targetRow = data.find((d) => d.documentId === targetDocId);
- openDocument(targetDocId, targetRow?.id);
+ openAgentDocument(targetDocId);
};
// Agent skills are document bundles, so view / rename / delete map onto the
@@ -425,8 +488,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);
const docId = view?.pathToDocumentId.get(relativePath);
if (!docId) return;
- const row = data.find((d) => d.documentId === docId);
- openDocument(docId, row?.id);
+ openAgentDocument(docId);
}}
onSkillDragStart={(item, event) => {
// The runtime resolves these via the `agent-skills:<filename>`
@@ -512,6 +574,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
data={documentsData}
mutate={mutate}
style={{ height: '100%' }}
+ onOpenDocument={openAgentDocument}
/>
</Flexbox>
);
@@ -527,7 +590,15 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
return (
<Flexbox gap={8}>
{webData.map((doc) => (
- <DocumentItem agentId={agentId} document={doc} key={doc.id} mutate={mutate} />
+ <DocumentItem
+ activeDocumentIdentifier={activeDocumentIdentifier}
+ agentId={agentId}
+ document={doc}
+ key={doc.id}
+ mutate={mutate}
+ onCurrentDeleted={backToChat}
+ onOpenDocument={openAgentDocument}
+ />
))}
</Flexbox>
);
@@ -535,25 +606,27 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
return (
<Flexbox gap={12} style={style}>
- <Flexbox horizontal gap={4} role={'tablist'}>
- {FILTER_OPTIONS.map((option) => {
- const active = filter === option.value;
- return (
- <div
- aria-selected={active}
- className={cx(styles.pillTab, active && styles.pillActive)}
- key={option.value}
- role={'tab'}
- onClick={() => setFilter(option.value)}
- >
- {t(option.labelKey)}
- </div>
- );
- })}
- </Flexbox>
- {filter === 'skills' && renderSkills()}
- {filter === 'documents' && renderDocuments()}
- {filter === 'web' && renderWeb()}
+ {showFilterTabs && (
+ <Flexbox horizontal gap={4} role={'tablist'}>
+ {filterOptions.map((option) => {
+ const active = activeFilter === option.value;
+ return (
+ <div
+ aria-selected={active}
+ className={cx(styles.pillTab, active && styles.pillActive)}
+ key={option.value}
+ role={'tab'}
+ onClick={() => setFilter(option.value)}
+ >
+ {t(option.labelKey)}
+ </div>
+ );
+ })}
+ </Flexbox>
+ )}
+ {activeFilter === 'skills' && renderSkills()}
+ {activeFilter === 'documents' && renderDocuments()}
+ {activeFilter === 'web' && renderWeb()}
</Flexbox>
);
},
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 41049fcbee6..b57f55e9680 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -15,6 +15,7 @@ import {
BusinessDesktopRoutesWithMainLayout,
BusinessDesktopRoutesWithoutMainLayout,
} from '@/business/client/BusinessDesktopRoutes';
+import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { fleetRouteMeta } from '@/features/Fleet/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
@@ -48,6 +49,8 @@ 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 AgentDocumentLayout from '@/routes/(main)/agent/docs/_layout';
+import AgentDocumentRoute from '@/routes/(main)/agent/docs/[docId]';
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import AgentProfilePage from '@/routes/(main)/agent/profile';
import AgentTaskDetailRoute from '@/routes/(main)/agent/task/[taskId]';
@@ -152,6 +155,17 @@ export const sharedMainAreaChildren: RouteObject[] = [
],
element: <DesktopAgentChatLayout />,
},
+ {
+ children: [
+ {
+ element: <AgentDocumentRoute />,
+ handle: { meta: agentDocumentRouteMeta },
+ path: ':docId',
+ },
+ ],
+ element: <AgentDocumentLayout />,
+ path: 'docs',
+ },
{
element: <AgentProfilePage />,
path: 'profile',
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index 87e802b6b86..b499c595a87 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -15,6 +15,7 @@ import {
BusinessDesktopRoutesWithMainLayout,
BusinessDesktopRoutesWithoutMainLayout,
} from '@/business/client/BusinessDesktopRoutes';
+import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { fleetRouteMeta } from '@/features/Fleet/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
@@ -64,6 +65,23 @@ export const sharedMainAreaChildren: RouteObject[] = [
'Desktop > Chat > ChatLayout',
),
},
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/docs/[docId]'),
+ 'Desktop > Chat > Document',
+ ),
+ handle: { meta: agentDocumentRouteMeta },
+ path: ':docId',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/agent/docs/_layout'),
+ 'Desktop > Chat > DocumentLayout',
+ ),
+ path: 'docs',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/agent/profile'),
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 921f718299f..ac30342a26a 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -211,6 +211,12 @@ export interface SystemStatus {
showAgentBuilderPanel?: boolean;
showCommandMenu?: boolean;
showFilePanel?: boolean;
+ /**
+ * Collapse state of the nav panel while the Fleet (Observation Mode) view is active.
+ * Persisted independently from `showLeftPanel` so collapsing the running-task list
+ * does not carry over to / from the standard chat nav rail (and vice versa).
+ */
+ showFleetPanel?: boolean;
showHotkeyHelper?: boolean;
showImagePanel?: boolean;
showImageTopicPanel?: boolean;
@@ -370,6 +376,7 @@ export const INITIAL_STATUS = {
},
showCommandMenu: false,
showFilePanel: true,
+ showFleetPanel: true,
showHotkeyHelper: false,
showImagePanel: true,
showImageTopicPanel: true,
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 3bafcea1a60..455388fc63b 100644
--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
@@ -1,23 +1,37 @@
import type { DocumentLoadFormat, DocumentLoadRule } from '@lobechat/agent-templates';
+import { buildAgentDocumentUrl } from '@lobechat/builtin-tool-agent-documents';
import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';
import { AgentDocumentsExecutor } from '@lobechat/builtin-tool-agent-documents/executor';
+import { isDesktop } from '@lobechat/const';
+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { agentDocumentService } from '@/services/agentDocument';
+import { useElectronStore } from '@/store/electron';
+import { electronSyncSelectors } from '@/store/electron/selectors';
-const runtime = new AgentDocumentsExecutionRuntime({
- copyDocument: ({ agentId, id, newTitle }) =>
- agentDocumentService.copyDocument({ agentId, id, newTitle }),
- createDocument: ({ agentId, content, hintIsSkill, title, toolContext, trigger }) =>
- agentDocumentService.createDocument({
- agentId,
- content,
- hintIsSkill,
- title,
- toolContext,
- trigger,
- }),
- createTopicDocument: ({ agentId, content, hintIsSkill, title, toolContext, topicId, trigger }) =>
- agentDocumentService.createForTopic({
+/**
+ * App origin for share links. Desktop points at the connected remote server so
+ * the link opens the cloud app; web uses the current origin.
+ */
+const getAppOrigin = (): string | undefined => {
+ if (isDesktop) return electronSyncSelectors.remoteServerUrl(useElectronStore.getState());
+ return typeof window === 'undefined' ? undefined : window.location.origin;
+};
+
+const runtime = new AgentDocumentsExecutionRuntime(
+ {
+ copyDocument: ({ agentId, id, newTitle }) =>
+ agentDocumentService.copyDocument({ agentId, id, newTitle }),
+ createDocument: ({ agentId, content, hintIsSkill, title, toolContext, trigger }) =>
+ agentDocumentService.createDocument({
+ agentId,
+ content,
+ hintIsSkill,
+ title,
+ toolContext,
+ trigger,
+ }),
+ createTopicDocument: ({
agentId,
content,
hintIsSkill,
@@ -25,57 +39,73 @@ const runtime = new AgentDocumentsExecutionRuntime({
toolContext,
topicId,
trigger,
- }),
- listDocuments: async ({ agentId, sourceType }) => {
- // The agent listing tool surfaces archived `.tool-results` so the model can
- // discover them; user-facing lists keep the default (filtered) behavior.
- const docs = await agentDocumentService.listDocuments({
- agentId,
- includeArchivedToolResults: true,
- sourceType,
- });
- return docs.map((d) => ({
- documentId: d.documentId,
- filename: d.filename,
- id: d.id,
- title: d.title,
- }));
+ }) =>
+ agentDocumentService.createForTopic({
+ agentId,
+ content,
+ hintIsSkill,
+ title,
+ toolContext,
+ topicId,
+ trigger,
+ }),
+ listDocuments: async ({ agentId, sourceType }) => {
+ // The agent listing tool surfaces archived `.tool-results` so the model can
+ // discover them; user-facing lists keep the default (filtered) behavior.
+ const docs = await agentDocumentService.listDocuments({
+ agentId,
+ includeArchivedToolResults: true,
+ sourceType,
+ });
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
+ },
+ listTopicDocuments: async ({ agentId, sourceType, topicId }) => {
+ const docs = await agentDocumentService.listDocuments({
+ agentId,
+ includeArchivedToolResults: true,
+ scope: 'currentTopic',
+ sourceType,
+ topicId,
+ });
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
+ },
+ modifyNodes: ({ agentId, id, operations }) =>
+ agentDocumentService.modifyNodes({ agentId, id, operations }),
+ readDocument: ({ agentId, format, id }) =>
+ agentDocumentService.readDocument({ agentId, format: format ?? 'xml', id }),
+ removeDocument: async ({ agentId, id }) =>
+ (await agentDocumentService.removeDocument({ agentId, id })).deleted,
+ renameDocument: ({ agentId, id, newTitle }) =>
+ agentDocumentService.renameDocument({ agentId, id, newTitle }),
+ replaceDocumentContent: ({ agentId, content, id }) =>
+ agentDocumentService.replaceDocumentContent({ agentId, content, id }),
+ updateLoadRule: ({ agentId, id, rule }) =>
+ agentDocumentService.updateLoadRule({
+ agentId,
+ id,
+ rule: {
+ ...rule,
+ policyLoadFormat: rule.policyLoadFormat as DocumentLoadFormat | undefined,
+ rule: rule.rule as DocumentLoadRule | undefined,
+ },
+ }),
},
- listTopicDocuments: async ({ agentId, sourceType, topicId }) => {
- const docs = await agentDocumentService.listDocuments({
- agentId,
- includeArchivedToolResults: true,
- scope: 'currentTopic',
- sourceType,
- topicId,
- });
- return docs.map((d) => ({
- documentId: d.documentId,
- filename: d.filename,
- id: d.id,
- title: d.title,
- }));
+ {
+ getDocumentUrl: ({ agentId, documentId }) =>
+ buildAgentDocumentUrl(getAppOrigin(), agentId, documentId, {
+ workspaceSlug: getActiveWorkspaceSlug(),
+ }),
},
- modifyNodes: ({ agentId, id, operations }) =>
- agentDocumentService.modifyNodes({ agentId, id, operations }),
- readDocument: ({ agentId, format, id }) =>
- agentDocumentService.readDocument({ agentId, format: format ?? 'xml', id }),
- removeDocument: async ({ agentId, id }) =>
- (await agentDocumentService.removeDocument({ agentId, id })).deleted,
- renameDocument: ({ agentId, id, newTitle }) =>
- agentDocumentService.renameDocument({ agentId, id, newTitle }),
- replaceDocumentContent: ({ agentId, content, id }) =>
- agentDocumentService.replaceDocumentContent({ agentId, content, id }),
- updateLoadRule: ({ agentId, id, rule }) =>
- agentDocumentService.updateLoadRule({
- agentId,
- id,
- rule: {
- ...rule,
- policyLoadFormat: rule.policyLoadFormat as DocumentLoadFormat | undefined,
- rule: rule.rule as DocumentLoadRule | undefined,
- },
- }),
-});
+);
export const agentDocumentsExecutor = new AgentDocumentsExecutor(runtime);