Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(agent-documents): render system docs in editor (#15462)

Innei65ba08668596
diff --git a/packages/const/src/agentDocument.ts b/packages/const/src/agentDocument.ts
new file mode 100644
index 00000000000..254a751608f
--- /dev/null
+++ b/packages/const/src/agentDocument.ts
@@ -0,0 +1,26 @@
+export const AGENT_DOCUMENT_CATEGORY = 'document';
+export const AGENT_DOCUMENT_SKILL_CATEGORY = 'skill';
+export const AGENT_DOCUMENT_WEB_CATEGORY = 'web';
+
+export const AGENT_DOCUMENT_SOURCE_TYPE = 'agent';
+export const AGENT_SIGNAL_SOURCE_TYPE = 'agent-signal';
+export const DERIVED_DOCUMENT_SOURCE_TYPE = 'document';
+export const WEB_DOCUMENT_SOURCE_TYPE = 'web';
+
+export const AGENT_DOCUMENT_FILE_TYPE = 'agent/document';
+export const AGENT_PLAN_FILE_TYPE = 'agent/plan';
+export const CUSTOM_DOCUMENT_FILE_TYPE = 'custom/document';
+export const CUSTOM_FOLDER_FILE_TYPE = 'custom/folder';
+
+export const MARKDOWN_MIME_TYPES = ['text/markdown', 'text/x-markdown'];
+
+export const MARKDOWN_DOCUMENT_FILE_TYPES = ['markdown', ...MARKDOWN_MIME_TYPES];
+
+export const EDITOR_DOCUMENT_SOURCE_TYPES = [
+ AGENT_DOCUMENT_SOURCE_TYPE,
+ AGENT_SIGNAL_SOURCE_TYPE,
+ DERIVED_DOCUMENT_SOURCE_TYPE,
+];
+
+export const hasFilenameExtension = (filename: string): boolean =>
+ /(?:^|[^.])\.[^.]+$/.test(filename);
diff --git a/packages/const/src/index.ts b/packages/const/src/index.ts
index 01693da66ea..40d806463d1 100644
--- a/packages/const/src/index.ts
+++ b/packages/const/src/index.ts
@@ -1,3 +1,4 @@
+export * from './agentDocument';
export * from './bot';
export * from './currency';
export * from './desktop';
diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
index bd9cf930524..babde6a50bd 100644
--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
@@ -1,4 +1,9 @@
// @vitest-environment node
+import {
+ AGENT_DOCUMENT_FILE_TYPE,
+ AGENT_DOCUMENT_SOURCE_TYPE,
+ AGENT_SIGNAL_SOURCE_TYPE,
+} from '@lobechat/const';
import { and, eq } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
@@ -167,17 +172,17 @@ describe('AgentDocumentModel', () => {
it('creates ordinary agent documents with agent source attribution by default', async () => {
const created = await agentDocumentModel.create(agentId, 'brief', 'content');
- expect(created.sourceType).toBe('agent');
+ expect(created.sourceType).toBe(AGENT_DOCUMENT_SOURCE_TYPE);
expect(created.source).toBe(`agent-document://${agentId}/brief`);
});
it('allows trusted callers to set document source attribution', async () => {
const created = await agentDocumentModel.create(agentId, 'skill-a', 'content', {
source: 'agent-signal:skill-management',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
});
- expect(created.sourceType).toBe('agent-signal');
+ expect(created.sourceType).toBe(AGENT_SIGNAL_SOURCE_TYPE);
expect(created.source).toBe('agent-signal:skill-management');
});
@@ -451,6 +456,24 @@ describe('AgentDocumentModel', () => {
expect(renamed?.filename).toBe('IDENTITY 2');
});
+ it('should allow rename callers to keep title and filename separate', async () => {
+ const created = await agentDocumentModel.create(agentId, 'old-name.md', 'hello');
+
+ const renamed = await agentDocumentModel.rename(created.id, 'New Name', {
+ filename: 'New Name.md',
+ });
+
+ expect(renamed?.title).toBe('New Name');
+ expect(renamed?.filename).toBe('New Name.md');
+
+ const [doc] = await serverDB
+ .select()
+ .from(documents)
+ .where(eq(documents.id, created.documentId));
+
+ expect(doc?.source).toBe(`agent-document://${agentId}/${encodeURIComponent('New Name.md')}`);
+ });
+
it('should move path metadata without changing agent document identity', async () => {
const folder = await agentDocumentModel.create(agentId, 'folder', '', {
fileType: DOCUMENT_FOLDER_TYPE,
@@ -542,7 +565,7 @@ describe('AgentDocumentModel', () => {
fileType: 'skills/bundle',
policyLoad: PolicyLoad.DISABLED,
source: 'agent-signal:skill-management',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
});
const converted = await agentDocumentModel.convertAgentDocumentToSkillIndex({
@@ -556,7 +579,7 @@ describe('AgentDocumentModel', () => {
},
parentId: bundle.documentId,
source: 'agent-signal:skill-management',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
title: 'Workflow Note',
});
@@ -566,7 +589,7 @@ describe('AgentDocumentModel', () => {
expect(converted?.filename).toBe('workflow-note');
expect(converted?.parentId).toBe(bundle.documentId);
expect(converted?.policyLoad).toBe(PolicyLoad.DISABLED);
- expect(converted?.sourceType).toBe('agent-signal');
+ expect(converted?.sourceType).toBe(AGENT_SIGNAL_SOURCE_TYPE);
expect(converted?.source).toBe('agent-signal:skill-management');
expect(converted?.templateId).toBe('agent-skill');
expect(converted?.title).toBe('Workflow Note');
@@ -599,7 +622,7 @@ describe('AgentDocumentModel', () => {
fileType: 'skills/bundle',
policyLoad: PolicyLoad.DISABLED,
source: 'agent-signal:skill-management',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
});
await expect(
@@ -614,7 +637,7 @@ describe('AgentDocumentModel', () => {
},
parentId: bundle.documentId,
source: 'agent-signal:skill-management',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
title: 'SKILL.md',
});
@@ -626,11 +649,11 @@ describe('AgentDocumentModel', () => {
expect(unchanged).toMatchObject({
documentId: source.documentId,
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'workflow-note',
parentId: null,
policyLoad: PolicyLoad.PROGRESSIVE,
- sourceType: 'agent',
+ sourceType: AGENT_DOCUMENT_SOURCE_TYPE,
});
});
diff --git a/packages/database/src/models/agentDocuments/__tests__/deriveFields.test.ts b/packages/database/src/models/agentDocuments/__tests__/deriveFields.test.ts
index 91fcade2924..dc0e88677b8 100644
--- a/packages/database/src/models/agentDocuments/__tests__/deriveFields.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/deriveFields.test.ts
@@ -1,3 +1,13 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_FILE_TYPE,
+ AGENT_DOCUMENT_SKILL_CATEGORY,
+ AGENT_DOCUMENT_SOURCE_TYPE,
+ AGENT_DOCUMENT_WEB_CATEGORY,
+ AGENT_SIGNAL_SOURCE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ WEB_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
import { describe, expect, it } from 'vitest';
import { deriveAgentDocumentFields } from '../deriveFields';
@@ -7,11 +17,11 @@ describe('deriveAgentDocumentFields', () => {
expect(
deriveAgentDocumentFields({
fileType: 'skills/bundle',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
templateId: 'agent-skill',
}),
).toEqual({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
isFolder: true,
isSkillBundle: true,
isSkillIndex: false,
@@ -22,11 +32,11 @@ describe('deriveAgentDocumentFields', () => {
expect(
deriveAgentDocumentFields({
fileType: 'skills/index',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
templateId: 'agent-skill',
}),
).toEqual({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
isFolder: false,
isSkillBundle: false,
isSkillIndex: true,
@@ -37,21 +47,21 @@ describe('deriveAgentDocumentFields', () => {
expect(
deriveAgentDocumentFields({
fileType: 'skills/bundle',
- sourceType: 'agent',
+ sourceType: AGENT_DOCUMENT_SOURCE_TYPE,
templateId: null,
}).category,
- ).toBe('skill');
+ ).toBe(AGENT_DOCUMENT_SKILL_CATEGORY);
});
it('classifies web-sourced articles as web', () => {
expect(
deriveAgentDocumentFields({
fileType: 'article',
- sourceType: 'web',
+ sourceType: WEB_DOCUMENT_SOURCE_TYPE,
templateId: null,
}),
).toEqual({
- category: 'web',
+ category: AGENT_DOCUMENT_WEB_CATEGORY,
isFolder: false,
isSkillBundle: false,
isSkillIndex: false,
@@ -61,12 +71,12 @@ describe('deriveAgentDocumentFields', () => {
it('marks custom folders as folders without changing the category', () => {
expect(
deriveAgentDocumentFields({
- fileType: 'custom/folder',
- sourceType: 'agent',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ sourceType: AGENT_DOCUMENT_SOURCE_TYPE,
templateId: null,
}),
).toEqual({
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
isFolder: true,
isSkillBundle: false,
isSkillIndex: false,
@@ -76,12 +86,12 @@ describe('deriveAgentDocumentFields', () => {
it('falls back to document for ordinary file-backed agent documents', () => {
expect(
deriveAgentDocumentFields({
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
sourceType: 'file',
templateId: null,
}),
).toEqual({
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
isFolder: false,
isSkillBundle: false,
isSkillIndex: false,
@@ -94,9 +104,9 @@ describe('deriveAgentDocumentFields', () => {
expect(
deriveAgentDocumentFields({
fileType: 'skills/index',
- sourceType: 'web',
+ sourceType: WEB_DOCUMENT_SOURCE_TYPE,
templateId: 'agent-skill',
}).category,
- ).toBe('skill');
+ ).toBe(AGENT_DOCUMENT_SKILL_CATEGORY);
});
});
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index c6ec7d7c87f..e7bb723ca81 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -1,3 +1,4 @@
+import { AGENT_DOCUMENT_FILE_TYPE, AGENT_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
import { and, asc, desc, eq, inArray, isNotNull, isNull, like, or, sql } from 'drizzle-orm';
import type { DocumentItem, NewAgentDocument, NewDocument } from '../../schemas';
@@ -290,7 +291,7 @@ export class AgentDocumentModel {
const {
createdAt,
editorData,
- fileType = 'agent/document',
+ fileType = AGENT_DOCUMENT_FILE_TYPE,
loadPosition,
loadRules,
metadata,
@@ -298,7 +299,7 @@ export class AgentDocumentModel {
policy,
policyLoad,
source,
- sourceType = 'agent',
+ sourceType = AGENT_DOCUMENT_SOURCE_TYPE,
templateId,
title: providedTitle,
updatedAt,
@@ -635,14 +636,18 @@ export class AgentDocumentModel {
* - The renamed agent document, or `undefined` when the binding is not visible.
*
*/
- async rename(documentId: string, newTitle: string): Promise<AgentDocument | undefined> {
+ async rename(
+ documentId: string,
+ newTitle: string,
+ options?: { filename?: string },
+ ): Promise<AgentDocument | undefined> {
const existing = await this.findById(documentId);
if (!existing) return undefined;
const title = newTitle.trim();
if (!title) return existing;
- const filename = buildDocumentFilename(title);
+ const filename = options?.filename?.trim() || buildDocumentFilename(title);
const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;
await this.db.transaction(async (trx) => {
diff --git a/packages/database/src/models/agentDocuments/deriveFields.ts b/packages/database/src/models/agentDocuments/deriveFields.ts
index 10c6312ba5b..b36aafadd9b 100644
--- a/packages/database/src/models/agentDocuments/deriveFields.ts
+++ b/packages/database/src/models/agentDocuments/deriveFields.ts
@@ -1,3 +1,10 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_SKILL_CATEGORY,
+ AGENT_DOCUMENT_WEB_CATEGORY,
+ WEB_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
+
import {
AGENT_SKILL_TEMPLATE_ID,
DOCUMENT_FOLDER_TYPE,
@@ -12,9 +19,9 @@ const isManagedSkill = (doc: DeriveInput): boolean =>
doc.templateId === AGENT_SKILL_TEMPLATE_ID || doc.fileType?.startsWith('skills/');
const deriveCategory = (doc: DeriveInput): AgentDocumentCategory => {
- if (isManagedSkill(doc)) return 'skill';
- if (doc.sourceType === 'web') return 'web';
- return 'document';
+ if (isManagedSkill(doc)) return AGENT_DOCUMENT_SKILL_CATEGORY;
+ if (doc.sourceType === WEB_DOCUMENT_SOURCE_TYPE) return AGENT_DOCUMENT_WEB_CATEGORY;
+ return AGENT_DOCUMENT_CATEGORY;
};
export const deriveAgentDocumentFields = (doc: DeriveInput): AgentDocumentDerivedFields => {
diff --git a/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.ts b/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.ts
index 448ae2a7499..46394ae9d25 100644
--- a/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.ts
+++ b/packages/heterogeneous-agents/src/askUser/AskUserMcpServer.ts
@@ -32,7 +32,7 @@ const askUserQuestionShape = z.object({
question: z.string(),
});
-const askUserInputShape = {
+const askUserInputShape: z.ZodRawShape = {
questions: z.array(askUserQuestionShape).min(1).max(4),
};
@@ -41,6 +41,30 @@ const ASK_USER_TOOL_DESCRIPTION =
'Ask the user one or more clarifying questions with multiple-choice options. ' +
"Use this whenever the user's intent is ambiguous and you need them to pick.";
+interface AskUserToolExtra {
+ _meta?: Record<string, unknown>;
+ sendNotification?: (notification: {
+ method: 'notifications/progress';
+ params: {
+ message: string;
+ progress: number;
+ progressToken: number | string;
+ total: number;
+ };
+ }) => Promise<void>;
+ sessionId?: string;
+}
+
+type AskUserToolRegistrar = (
+ name: string,
+ config: {
+ description: string;
+ inputSchema: typeof askUserInputShape;
+ title: string;
+ },
+ cb: (args: unknown, extra: AskUserToolExtra) => Promise<unknown>,
+) => void;
+
export interface StartedServer {
/** Effective listen port (auto-assigned when constructed with port=0). */
port: number;
@@ -331,7 +355,9 @@ export class AskUserMcpServer {
}
private registerAskUserTool(mcp: McpServer) {
- mcp.registerTool(
+ const registerTool = mcp.registerTool.bind(mcp) as AskUserToolRegistrar;
+
+ registerTool(
ASK_USER_TOOL_NAME,
{
description: ASK_USER_TOOL_DESCRIPTION,
@@ -339,7 +365,7 @@ export class AskUserMcpServer {
title: 'Ask User Question',
},
async (args, extra) => {
- const sessionId = (extra as { sessionId?: string } | undefined)?.sessionId;
+ const sessionId = extra.sessionId;
const operationId = sessionId ? this.sessionIdToOpId.get(sessionId) : undefined;
if (!operationId) {
return errorResult(
@@ -353,16 +379,17 @@ export class AskUserMcpServer {
);
}
- const ccToolUseId = (extra?._meta as { 'claudecode/toolUseId'?: string } | undefined)?.[
- 'claudecode/toolUseId'
- ];
- const progressToken = (extra?._meta as { progressToken?: string | number } | undefined)
- ?.progressToken;
+ const ccToolUseId = extra._meta?.['claudecode/toolUseId'];
+ const rawProgressToken = extra._meta?.progressToken;
+ const progressToken =
+ typeof rawProgressToken === 'string' || typeof rawProgressToken === 'number'
+ ? rawProgressToken
+ : undefined;
// Use CC's own tool_use id as the bridge correlation key so the
// outbound `agent_intervention_request` shares an id with the
// existing tool message on the renderer side. Without this the
// renderer can't tie the intervention card to its tool bubble.
- const toolCallId = ccToolUseId;
+ const toolCallId = typeof ccToolUseId === 'string' ? ccToolUseId : undefined;
// SSE keepalive: every progressIntervalMs send a progress
// notification so CC's transport doesn't time out on long waits.
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
index fb39851abe7..580ce841575 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
@@ -1,3 +1,9 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_SKILL_CATEGORY,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+} from '@lobechat/const';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -136,7 +142,7 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentIte
accessSelf: 0,
accessShared: 0,
agentId: 'agent-1',
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
content: '',
createdAt: new Date('2026-05-09T00:00:00Z'),
deletedAt: null,
@@ -147,7 +153,7 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentIte
documentId: 'doc-1',
editorData: null,
filename: 'document.md',
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
id: 'agent-doc-1',
isFolder: false,
isSkillBundle: false,
@@ -183,7 +189,7 @@ describe('DocumentExplorerTree', () => {
it('renders managed skill bundle as a folder with SKILL.md underneath', () => {
const data = [
createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'skill-bundle-doc',
fileType: 'skills/bundle',
filename: 'youtube-comment-retrieval-workflow',
@@ -194,7 +200,7 @@ describe('DocumentExplorerTree', () => {
title: 'YouTube Comment Retrieval Workflow',
}),
createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'skill-index-doc',
fileType: 'skills/index',
filename: 'SKILL.md',
@@ -206,7 +212,7 @@ describe('DocumentExplorerTree', () => {
}),
createDocument({
documentId: 'folder-doc',
- fileType: 'custom/folder',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
filename: 'Notes',
id: 'folder-row',
isFolder: true,
@@ -231,7 +237,7 @@ describe('DocumentExplorerTree', () => {
it('opens SKILL.md but does not open the empty skill bundle', () => {
const data = [
createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'skill-bundle-doc',
fileType: 'skills/bundle',
filename: 'youtube-comment-retrieval-workflow',
@@ -242,7 +248,7 @@ describe('DocumentExplorerTree', () => {
title: 'YouTube Comment Retrieval Workflow',
}),
createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'skill-index-doc',
fileType: 'skills/index',
filename: 'SKILL.md',
@@ -267,7 +273,7 @@ describe('DocumentExplorerTree', () => {
const mutate = vi.fn().mockResolvedValue(undefined);
const data = [
createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'skill-bundle-doc',
fileType: 'skills/bundle',
filename: 'youtube-comment-retrieval-workflow',
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
index adafeab90ab..ffe5073a240 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
@@ -1,3 +1,4 @@
+import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';
import type { MenuProps } from 'antd';
import { createStaticStyles } from 'antd-style';
import { Trash2Icon } from 'lucide-react';
@@ -185,12 +186,14 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {
);
const canDrag = useCallback(
- (node: ExplorerTreeNode<AgentDocumentItem>) => !!node.data && node.data.category === 'document',
+ (node: ExplorerTreeNode<AgentDocumentItem>) =>
+ !!node.data && node.data.category === AGENT_DOCUMENT_CATEGORY,
[],
);
const canRename = useCallback(
- (node: ExplorerTreeNode<AgentDocumentItem>) => !!node.data && node.data.category === 'document',
+ (node: ExplorerTreeNode<AgentDocumentItem>) =>
+ !!node.data && node.data.category === AGENT_DOCUMENT_CATEGORY,
[],
);
diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
index 84159cae4dc..d556a8c2a4b 100644
--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
@@ -18,7 +18,6 @@ interface UseDocumentTreeOpsArgs {
}
const ROOT_PATH = './';
-const DEFAULT_DOCUMENT_EXTENSION = '.md';
const joinPath = (parentPath: string, segment: string) =>
parentPath === ROOT_PATH ? `${ROOT_PATH}${segment}` : `${parentPath}/${segment}`;
@@ -189,11 +188,7 @@ export const useDocumentTreeOps = ({
const baseStem = t('workingPanel.resources.tree.untitledDocument');
const parentDocumentId = parentId ? (byRowId.get(parentId)?.documentId ?? null) : null;
- const pendingFilename = pickUniqueFilename(
- parentDocumentId,
- baseStem,
- DEFAULT_DOCUMENT_EXTENSION,
- );
+ const pendingFilename = pickUniqueFilename(parentDocumentId, baseStem);
const pending = makePendingDocument({
agentId,
@@ -208,10 +203,7 @@ export const useDocumentTreeOps = ({
try {
const result =
parentPath === ROOT_PATH
- ? // Pass the client-picked filename (with extension) as the title so
- // the server keeps the `.md` suffix; server dedup remains a safety
- // net for racing clients.
- await agentDocumentService.createDocument({
+ ? await agentDocumentService.createDocument({
agentId,
content: '',
title: pendingFilename,
diff --git a/src/features/AgentDocumentsExplorer/types.test.ts b/src/features/AgentDocumentsExplorer/types.test.ts
index 2d77c2f5e46..f81f9054c0f 100644
--- a/src/features/AgentDocumentsExplorer/types.test.ts
+++ b/src/features/AgentDocumentsExplorer/types.test.ts
@@ -1,3 +1,8 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_SKILL_CATEGORY,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+} from '@lobechat/const';
import { describe, expect, it } from 'vitest';
import type { AgentDocumentItem } from './types';
@@ -9,7 +14,7 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentIte
accessSelf: 0,
accessShared: 0,
agentId: 'agent-1',
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
content: '',
createdAt: new Date('2026-05-09T00:00:00Z'),
deletedAt: null,
@@ -20,7 +25,7 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentIte
documentId: 'doc-1',
editorData: null,
filename: 'document.md',
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
id: 'agent-doc-1',
isFolder: false,
isSkillBundle: false,
@@ -43,7 +48,7 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentIte
}) as AgentDocumentItem;
const bundle = createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'bundle-doc',
isFolder: true,
isSkillBundle: true,
@@ -51,7 +56,7 @@ const bundle = createDocument({
});
const index = createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'index-doc',
isSkillIndex: true,
parentId: 'bundle-doc',
diff --git a/src/features/AgentDocumentsExplorer/utils/canDrop.test.ts b/src/features/AgentDocumentsExplorer/utils/canDrop.test.ts
index 456a0dd3268..bf26c0f52f7 100644
--- a/src/features/AgentDocumentsExplorer/utils/canDrop.test.ts
+++ b/src/features/AgentDocumentsExplorer/utils/canDrop.test.ts
@@ -1,3 +1,9 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_SKILL_CATEGORY,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+} from '@lobechat/const';
import { describe, expect, it } from 'vitest';
import type { ExplorerTreeCanDropCtx, ExplorerTreeNode } from '@/features/ExplorerTree';
@@ -11,7 +17,7 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentIte
accessSelf: 0,
accessShared: 0,
agentId: 'agent-1',
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
content: '',
createdAt: new Date('2026-05-09T00:00:00Z'),
deletedAt: null,
@@ -22,7 +28,7 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentIte
documentId: 'doc-1',
editorData: null,
filename: 'document.md',
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
id: 'agent-doc-1',
isFolder: false,
isSkillBundle: false,
@@ -72,7 +78,7 @@ describe('canDropDocument', () => {
const target = createNode(
'folder-row',
createDocument({
- fileType: 'custom/folder',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
id: 'folder-row',
isFolder: true,
title: 'Folder',
@@ -90,7 +96,7 @@ describe('canDropDocument', () => {
const target = createNode(
'skill-row',
createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
documentId: 'skill-bundle-doc',
fileType: 'skills/bundle',
id: 'skill-row',
@@ -111,7 +117,7 @@ describe('canDropDocument', () => {
const source = createNode(
'skill-index-row',
createDocument({
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
fileType: 'skills/index',
id: 'skill-index-row',
isSkillIndex: true,
@@ -122,7 +128,7 @@ describe('canDropDocument', () => {
const target = createNode(
'folder-row',
createDocument({
- fileType: 'custom/folder',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
id: 'folder-row',
isFolder: true,
title: 'Folder',
diff --git a/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts b/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts
index a9c0f9dac91..841c0ec2eac 100644
--- a/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts
+++ b/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts
@@ -1,3 +1,9 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_SOURCE_TYPE,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+} from '@lobechat/const';
import { nanoid } from 'nanoid';
import { type AgentDocumentItem, PENDING_ID_PREFIX } from '../types';
@@ -22,7 +28,7 @@ export const makePendingDocument = ({
accessSelf: 1,
accessShared: 0,
agentId,
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
content: '',
createdAt: now,
deletedAt: null,
@@ -33,7 +39,7 @@ export const makePendingDocument = ({
documentId: id,
editorData: null,
filename: title,
- fileType: isFolder ? 'custom/folder' : 'custom/document',
+ fileType: isFolder ? CUSTOM_FOLDER_FILE_TYPE : CUSTOM_DOCUMENT_FILE_TYPE,
id,
isFolder,
isSkillBundle: false,
@@ -47,7 +53,7 @@ export const makePendingDocument = ({
policyLoadPosition: '',
policyLoadRule: '',
source: null,
- sourceType: 'agent',
+ sourceType: AGENT_DOCUMENT_SOURCE_TYPE,
templateId: null,
title,
updatedAt: now,
diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsx
index e2759d6ef09..7c22c5896fd 100644
--- a/src/features/FileViewer/index.tsx
+++ b/src/features/FileViewer/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import { MARKDOWN_MIME_TYPES } from '@lobechat/const';
import { type CSSProperties } from 'react';
import { memo } from 'react';
@@ -160,8 +161,7 @@ const CODE_MIME_TYPES = new Set([
// Markdown
'md',
'mdx',
- 'text/markdown',
- 'text/x-markdown',
+ ...MARKDOWN_MIME_TYPES,
// Other
'graphql',
'txt',
diff --git a/src/features/PageExplorer/PageExplorerPlaceholder.tsx b/src/features/PageExplorer/PageExplorerPlaceholder.tsx
index 9f22ec49f6f..6689f7e1aa8 100644
--- a/src/features/PageExplorer/PageExplorerPlaceholder.tsx
+++ b/src/features/PageExplorer/PageExplorerPlaceholder.tsx
@@ -1,4 +1,5 @@
import { FILE_URL } from '@lobechat/business-const';
+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { Notion } from '@lobehub/icons';
import { Center, FileTypeIcon, Flexbox, Icon, Text } from '@lobehub/ui';
import { Upload } from 'antd';
@@ -138,7 +139,7 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
typeof newDoc.editorData === 'string'
? JSON.parse(newDoc.editorData)
: newDoc.editorData || null,
- fileType: 'custom/document' as const,
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
filename: newDoc.title || title,
id: newDoc.id,
metadata: newDoc.metadata || {},
@@ -206,7 +207,7 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(
typeof parsedDocument.editorData === 'string'
? JSON.parse(parsedDocument.editorData)
: parsedDocument.editorData || null,
- fileType: parsedDocument.fileType || 'custom/document',
+ fileType: parsedDocument.fileType || CUSTOM_DOCUMENT_FILE_TYPE,
filename: parsedDocument.filename || fileName,
id: parsedDocument.id,
metadata: parsedDocument.metadata || {},
diff --git a/src/features/Pages/routeMeta.ts b/src/features/Pages/routeMeta.ts
index 98567ab8711..7c5aa0f3afc 100644
--- a/src/features/Pages/routeMeta.ts
+++ b/src/features/Pages/routeMeta.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { t } from 'i18next';
import { FilePenIcon } from 'lucide-react';
@@ -7,7 +8,7 @@ import { listSelectors } from '@/store/page/slices/list/selectors';
import { DocumentSourceType, type LobeDocument } from '@/types/document';
import { getIdFromIdentifier } from '@/utils/identifier';
-const EDITOR_PAGE_FILE_TYPE = 'custom/document';
+const EDITOR_PAGE_FILE_TYPE = CUSTOM_DOCUMENT_FILE_TYPE;
export const pageRouteMeta = routeMeta({
createNewTab: () => ({
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 9a1b0319eb3..4fb2bdc9f30 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -1,6 +1,6 @@
-import { render, screen } from '@testing-library/react';
+import { act, fireEvent, render, screen } from '@testing-library/react';
import { type ReactNode } from 'react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import DocumentBody from './Body';
@@ -31,8 +31,26 @@ vi.mock('@lobehub/ui', () => ({
}));
vi.mock('@/components/CodeEditorPane', () => ({
- default: ({ value }: { value: string }) => (
- <textarea readOnly data-testid="highlight-editor" value={value} />
+ default: ({
+ onChange,
+ onSave,
+ value,
+ }: {
+ onChange?: (next: string) => void;
+ onSave?: () => void;
+ value: string;
+ }) => (
+ <textarea
+ data-testid="highlight-editor"
+ value={value}
+ onChange={(event) => onChange?.(event.target.value)}
+ onKeyDown={(event) => {
+ if ((event.metaKey || event.ctrlKey) && event.key === 's') {
+ event.preventDefault();
+ onSave?.();
+ }
+ }}
+ />
),
}));
@@ -49,8 +67,13 @@ vi.mock('@/libs/swr', () => ({
useClientDataSWR: () => ({ data: mockDocumentMeta.current }),
}));
+const mockUpdateDocument = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+
vi.mock('@/services/document', () => ({
- documentService: { getDocumentById: vi.fn() },
+ documentService: {
+ getDocumentById: vi.fn(),
+ updateDocument: mockUpdateDocument,
+ },
}));
vi.mock('./EditorCanvas', () => ({
@@ -125,6 +148,12 @@ describe('DocumentBody', () => {
mockAgentState.current.activeAgentId = 'agent-1';
mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = false;
mockDocumentMeta.current = { content: '', filename: 'doc.md' };
+ mockUpdateDocument.mockClear();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
});
it('does not render FloatingChatPanel when the lab feature is disabled', () => {
@@ -172,4 +201,54 @@ describe('DocumentBody', () => {
expect(screen.getByTestId('editor-canvas')).toBeDefined();
expect(screen.queryByTestId('highlight-editor')).toBeNull();
});
+
+ it('autosaves highlight editor edits after the debounce window', () => {
+ mockDocumentMeta.current = { content: 'before', filename: 'config.json' };
+
+ render(<DocumentBody />);
+ const editor = screen.getByTestId('highlight-editor');
+
+ fireEvent.change(editor, { target: { value: 'after' } });
+ expect(mockUpdateDocument).not.toHaveBeenCalled();
+
+ act(() => {
+ vi.advanceTimersByTime(5000);
+ });
+
+ expect(mockUpdateDocument).toHaveBeenCalledWith({
+ content: 'after',
+ id: 'document-1',
+ saveSource: 'autosave',
+ });
+ });
+
+ it('flushes pending highlight edits when the editor unmounts', async () => {
+ mockDocumentMeta.current = { content: 'before', filename: 'config.json' };
+
+ const { unmount } = render(<DocumentBody />);
+ const editor = screen.getByTestId('highlight-editor');
+
+ fireEvent.change(editor, { target: { value: 'after' } });
+ expect(mockUpdateDocument).not.toHaveBeenCalled();
+
+ unmount();
+ await Promise.resolve();
+
+ expect(mockUpdateDocument).toHaveBeenCalledWith({
+ content: 'after',
+ id: 'document-1',
+ saveSource: 'autosave',
+ });
+ });
+
+ it('does not save on unmount when the highlight buffer is clean', async () => {
+ mockDocumentMeta.current = { content: 'before', filename: 'config.json' };
+
+ const { unmount } = render(<DocumentBody />);
+
+ unmount();
+ await Promise.resolve();
+
+ expect(mockUpdateDocument).not.toHaveBeenCalled();
+ });
});
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index 29e688a945a..da2420b0e2b 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -1,10 +1,12 @@
'use client';
+import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';
import { ActionIcon, Button, Flexbox, Text, TextArea } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
+import { debounce } from 'es-toolkit/compat';
import { CheckIcon, PencilIcon, XIcon } from 'lucide-react';
import type { ChangeEvent } from 'react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import CodeEditorPane from '@/components/CodeEditorPane';
@@ -209,30 +211,89 @@ const HighlightEditor = memo<HighlightEditorProps>(({ content, documentId, langu
const [buffer, setBuffer] = useState<string | undefined>(undefined);
const editingValue = buffer ?? content;
- const handleChange = useCallback(
- (next: string) => {
- setBuffer(next === content ? undefined : next);
- },
- [content],
- );
+ const bufferRef = useRef(buffer);
+ const documentIdRef = useRef(documentId);
+ const onSavedRef = useRef(onSaved);
+ bufferRef.current = buffer;
+ documentIdRef.current = documentId;
+ onSavedRef.current = onSaved;
- const handleSave = useCallback(async () => {
- if (buffer === undefined) return;
- const toWrite = buffer;
+ const writeBuffer = useCallback(async (source: 'manual' | 'autosave') => {
+ const toWrite = bufferRef.current;
+ if (toWrite === undefined) return;
try {
await documentService.updateDocument({
content: toWrite,
- id: documentId,
- saveSource: 'manual',
+ id: documentIdRef.current,
+ saveSource: source,
});
// Update SWR cache before clearing the buffer so the editor's value prop
// never falls back to stale content, which would otherwise reset the cursor.
- onSaved(toWrite);
- setBuffer(undefined);
- } catch {
- /* swallow */
+ onSavedRef.current(toWrite);
+ if (bufferRef.current === toWrite) setBuffer(undefined);
+ } catch (error) {
+ console.error('[HighlightEditor] save failed:', error);
}
- }, [buffer, documentId, onSaved]);
+ }, []);
+
+ const debouncedAutoSave = useMemo(
+ () =>
+ debounce(() => writeBuffer('autosave'), EDITOR_DEBOUNCE_TIME, {
+ leading: false,
+ maxWait: EDITOR_MAX_WAIT,
+ trailing: true,
+ }),
+ [writeBuffer],
+ );
+
+ const handleChange = useCallback(
+ (next: string) => {
+ const isDirty = next !== content;
+ setBuffer(isDirty ? next : undefined);
+ if (isDirty) debouncedAutoSave();
+ else debouncedAutoSave.cancel();
+ },
+ [content, debouncedAutoSave],
+ );
+
+ const handleSave = useCallback(async () => {
+ debouncedAutoSave.cancel();
+ await writeBuffer('manual');
+ }, [debouncedAutoSave, writeBuffer]);
+
+ const isMountedRef = useRef(false);
+
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ debouncedAutoSave.cancel();
+ const pendingContent = bufferRef.current;
+ if (pendingContent === undefined) return;
+ const pendingDocumentId = documentIdRef.current;
+ // Defer the fire-and-forget save to a microtask so that StrictMode's synchronous
+ // unmount/remount in development does not trigger a save. If the component is
+ // immediately remounted, isMountedRef flips back to true before this runs.
+ queueMicrotask(() => {
+ if (isMountedRef.current) return;
+ void documentService.updateDocument({
+ content: pendingContent,
+ id: pendingDocumentId,
+ saveSource: 'autosave',
+ });
+ });
+ };
+ }, [debouncedAutoSave]);
+
+ useEffect(() => {
+ const handler = (event: BeforeUnloadEvent) => {
+ if (bufferRef.current === undefined) return;
+ event.preventDefault();
+ event.returnValue = '';
+ };
+ window.addEventListener('beforeunload', handler);
+ return () => window.removeEventListener('beforeunload', handler);
+ }, []);
return (
<CodeEditorPane
diff --git a/src/features/Portal/Document/TodoList.tsx b/src/features/Portal/Document/TodoList.tsx
index b95c5b39ce7..6eeb0748a37 100644
--- a/src/features/Portal/Document/TodoList.tsx
+++ b/src/features/Portal/Document/TodoList.tsx
@@ -1,5 +1,6 @@
'use client';
+import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';
import { Checkbox, Flexbox, Icon, Tag } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { ChevronDown, ChevronUp, ListTodo } from 'lucide-react';
@@ -121,7 +122,7 @@ const TodoList = memo(() => {
const document = useNotebookStore(notebookSelectors.getDocumentById(topicId, documentId));
// Only show for agent/plan documents with todos in metadata
- if (!document || document.fileType !== 'agent/plan') return null;
+ if (!document || document.fileType !== AGENT_PLAN_FILE_TYPE) return null;
const todos: TodoState | undefined = document.metadata?.todos;
const items = todos?.items || [];
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index e832c676b3e..6c43ddf49fd 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -1,4 +1,4 @@
-import { isDesktop } from '@lobechat/const';
+import { isDesktop, MARKDOWN_MIME_TYPES } from '@lobechat/const';
import { Center, Empty, Flexbox, Icon, Markdown, Segmented, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { CodeIcon, EyeIcon } from 'lucide-react';
@@ -28,8 +28,7 @@ const TEXT_PREVIEW_MIME_TYPES = new Set([
'application/toml',
'application/xml',
'application/yaml',
- 'text/markdown',
- 'text/x-markdown',
+ ...MARKDOWN_MIME_TYPES,
]);
interface BinaryLocalFilePreview {
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index 60fe2602098..7ac80faf023 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -1,3 +1,4 @@
+import { CUSTOM_FOLDER_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
import { copyToClipboard, createRawModal, Icon } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
@@ -73,7 +74,7 @@ export const useFileItemDropdown = ({
const libraries = useKnowledgeBaseListContext();
const isInLibrary = !!libraryId;
- const isFolder = fileType === 'custom/folder';
+ const isFolder = fileType === CUSTOM_FOLDER_FILE_TYPE;
// PDF and Office files should not be treated as pages
const lowerFilename = filename?.toLowerCase();
const isPDF = fileType?.toLowerCase() === 'pdf' || lowerFilename?.endsWith('.pdf');
@@ -86,7 +87,9 @@ export const useFileItemDropdown = ({
lowerFilename?.endsWith('.pptx') ||
lowerFilename?.endsWith('.odt');
const isPage =
- !isPDF && !isOfficeFile && (sourceType === 'document' || fileType === PAGE_FILE_TYPE);
+ !isPDF &&
+ !isOfficeFile &&
+ (sourceType === DERIVED_DOCUMENT_SOURCE_TYPE || fileType === PAGE_FILE_TYPE);
const menuItems = useCallback(() => {
// Filter out current knowledge base and create submenu items
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts
index 5393da6b242..aa3ca0fc92c 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_FOLDER_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
import dayjs from 'dayjs';
import { useMemo } from 'react';
@@ -39,9 +40,15 @@ export const useFileListItemMeta = ({
dayjs().diff(dayjs(createdAt), 'd') < 7
? dayjs(createdAt).fromNow()
: dayjs(createdAt).format('YYYY-MM-DD'),
- emoji: sourceType === 'document' || fileType === PAGE_FILE_TYPE ? metadata?.emoji : null,
- isFolder: fileType === 'custom/folder',
- isPage: !isPDF && !isOfficeFile && (sourceType === 'document' || fileType === PAGE_FILE_TYPE),
+ emoji:
+ sourceType === DERIVED_DOCUMENT_SOURCE_TYPE || fileType === PAGE_FILE_TYPE
+ ? metadata?.emoji
+ : null,
+ isFolder: fileType === CUSTOM_FOLDER_FILE_TYPE,
+ isPage:
+ !isPDF &&
+ !isOfficeFile &&
+ (sourceType === DERIVED_DOCUMENT_SOURCE_TYPE || fileType === PAGE_FILE_TYPE),
isSupportedForChunking: !isChunkingUnsupported(fileType),
};
}, [createdAt, fileType, metadata?.emoji, name, sourceType]);
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
index 0a03778f18f..0701d7e6011 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
@@ -1,3 +1,4 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { Button, Flexbox, stopPropagation, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { isNull } from 'es-toolkit/compat';
@@ -74,7 +75,7 @@ const DefaultFileItem = memo<DefaultFileItemProps>(
s.parseFilesToChunks,
]);
- const isFolder = fileType === 'custom/folder';
+ const isFolder = fileType === CUSTOM_FOLDER_FILE_TYPE;
const isSupportedForChunking = !isChunkingUnsupported(fileType || '');
return (
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
index 9cc6024b40e..3b4145bd3bc 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
@@ -1,3 +1,8 @@
+import {
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ MARKDOWN_MIME_TYPES,
+} from '@lobechat/const';
import { Checkbox, showContextMenu, stopPropagation } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -30,10 +35,10 @@ const IMAGE_TYPES = new Set([
]);
// Markdown file types
-const MARKDOWN_TYPES = new Set(['text/markdown', 'text/x-markdown']);
+const MARKDOWN_TYPES = new Set(MARKDOWN_MIME_TYPES);
// Custom note file type
-const CUSTOM_NOTE_TYPE = 'custom/document';
+const CUSTOM_NOTE_TYPE = CUSTOM_DOCUMENT_FILE_TYPE;
// Helper to check if filename ends with .md or is a custom note
const isMarkdownFile = (name: string, fileType?: string) => {
@@ -212,7 +217,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
// Memoize computed values that don't change
const computedValues = useMemo(
() => ({
- isFolder: fileType === 'custom/folder',
+ isFolder: fileType === CUSTOM_FOLDER_FILE_TYPE,
isImage: fileType && IMAGE_TYPES.has(fileType),
isMarkdown: isMarkdownFile(name, fileType),
isPage: isCustomPage(fileType, name),
diff --git a/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx b/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx
index 02944cdd5dc..be50d3aa958 100644
--- a/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx
+++ b/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx
@@ -1,3 +1,4 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { Button, Flexbox, Icon, Modal } from '@lobehub/ui';
import { App } from 'antd';
import { FolderIcon } from 'lucide-react';
@@ -49,7 +50,7 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(
// Filter only folders
const folderItems = response.items
- .filter((item) => item.fileType === 'custom/folder')
+ .filter((item) => item.fileType === CUSTOM_FOLDER_FILE_TYPE)
.map((item) => ({
children: undefined,
id: item.id,
@@ -85,7 +86,7 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(
// Filter only folders
const childFolders: FolderTreeItem[] = response.items
- .filter((item) => item.fileType === 'custom/folder')
+ .filter((item) => item.fileType === CUSTOM_FOLDER_FILE_TYPE)
.map((item) => ({
children: undefined,
id: item.id,
@@ -131,7 +132,7 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(
// Filter only folders
const childFolders: FolderTreeItem[] = response.items
- .filter((item) => item.fileType === 'custom/folder')
+ .filter((item) => item.fileType === CUSTOM_FOLDER_FILE_TYPE)
.map((item) => ({
children: undefined,
id: item.id,
diff --git a/src/features/ResourceManager/components/Header/AddButton.tsx b/src/features/ResourceManager/components/Header/AddButton.tsx
index 94de13ebe9c..93899a80482 100644
--- a/src/features/ResourceManager/components/Header/AddButton.tsx
+++ b/src/features/ResourceManager/components/Header/AddButton.tsx
@@ -1,6 +1,11 @@
'use client';
import { FILE_URL } from '@lobechat/business-const';
+import {
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ DERIVED_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
import { Notion } from '@lobehub/icons';
import { type MenuProps } from '@lobehub/ui';
import { Button, DropdownMenu, Icon } from '@lobehub/ui';
@@ -73,10 +78,10 @@ const AddButton = () => {
const untitledTitle = t('pageList.untitled');
const realId = await createResourceAndSync({
content: '',
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
knowledgeBaseId: libraryId,
parentId: currentFolderId ?? undefined,
- sourceType: 'document',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
title: untitledTitle,
});
@@ -108,7 +113,7 @@ const AddButton = () => {
// Filter for folders at the same level
const foldersAtSameLevel = resourceList.filter(
(item) =>
- item.fileType === 'custom/folder' &&
+ item.fileType === CUSTOM_FOLDER_FILE_TYPE &&
(item.parentId ?? null) === (currentFolderId ?? null),
);
@@ -127,10 +132,10 @@ const AddButton = () => {
// Wait for sync to complete to get the real ID
const realId = await createResourceAndSync({
content: '',
- fileType: 'custom/folder',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
knowledgeBaseId: libraryId,
parentId: currentFolderId ?? undefined,
- sourceType: 'document',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
title: uniqueName,
});
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
index 9f028f06518..ae6fa1ef7cc 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/HierarchyNode.tsx
@@ -1,6 +1,7 @@
'use client';
import { CaretDownFilled, LoadingOutlined } from '@ant-design/icons';
+import { DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
import { ActionIcon, Block, Flexbox, Icon, showContextMenu, stopPropagation } from '@lobehub/ui';
import { App, Input } from 'antd';
import { cx } from 'antd-style';
@@ -62,7 +63,7 @@ export const HierarchyNode = memo<HierarchyNodeProps>(
const pageMatch =
!isPDF &&
!isOfficeFile &&
- (item.sourceType === 'document' || item.fileType === PAGE_FILE_TYPE);
+ (item.sourceType === DERIVED_DOCUMENT_SOURCE_TYPE || item.fileType === PAGE_FILE_TYPE);
return {
emoji: pageMatch ? item.metadata?.emoji : null,
diff --git a/src/features/ResourceManager/constants.ts b/src/features/ResourceManager/constants.ts
index f95e6d81255..f76af20a953 100644
--- a/src/features/ResourceManager/constants.ts
+++ b/src/features/ResourceManager/constants.ts
@@ -1,3 +1,5 @@
-const PAGE_FILE_TYPE = 'custom/document';
+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+
+const PAGE_FILE_TYPE = CUSTOM_DOCUMENT_FILE_TYPE;
export { PAGE_FILE_TYPE };
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 6e8e1cb892d..ef47dc1bf2a 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
@@ -1,3 +1,9 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_FILE_TYPE,
+ AGENT_DOCUMENT_SKILL_CATEGORY,
+ AGENT_SIGNAL_SOURCE_TYPE,
+} from '@lobechat/const';
import { fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -192,7 +198,7 @@ vi.mock('@/store/chat/selectors', () => ({
}));
const skillBundleRow = {
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
createdAt: new Date('2026-05-09T00:00:00Z'),
description: 'Use for YouTube comments',
documentId: 'skill-bundle-doc',
@@ -203,14 +209,14 @@ const skillBundleRow = {
isSkillBundle: true,
isSkillIndex: false,
parentId: null,
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
templateId: 'agent-skill',
title: 'YouTube Comment Retrieval Workflow',
updatedAt: new Date(),
};
const skillIndexRow = {
- category: 'skill',
+ category: AGENT_DOCUMENT_SKILL_CATEGORY,
createdAt: new Date('2026-05-09T00:00:00Z'),
description: 'Use for YouTube comments',
documentId: 'skill-index-doc',
@@ -221,18 +227,18 @@ const skillIndexRow = {
isSkillBundle: false,
isSkillIndex: true,
parentId: 'skill-bundle-doc',
- sourceType: 'agent-signal',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPE,
templateId: 'agent-skill',
title: 'SKILL.md',
updatedAt: new Date(),
};
const fileDocRow = {
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
createdAt: new Date('2026-04-16T00:00:00Z'),
description: 'A short brief',
documentId: 'doc-content-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'brief.md',
id: 'doc-1',
isFolder: false,
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 23d2de3fae2..959907696b6 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -1,4 +1,8 @@
-import { buildAgentSkillIdentifier } from '@lobechat/const';
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_WEB_CATEGORY,
+ buildAgentSkillIdentifier,
+} from '@lobechat/const';
import { ActionIcon, Center, Empty, Flexbox, Text } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { SkillsIcon } from '@lobehub/ui/icons';
@@ -280,9 +284,15 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDire
agentDocumentService.getDocuments({ agentId: agentId! }),
);
- const webData = useMemo(() => data.filter((doc) => doc.category === 'web'), [data]);
+ const webData = useMemo(
+ () => data.filter((doc) => doc.category === AGENT_DOCUMENT_WEB_CATEGORY),
+ [data],
+ );
- const documentsData = useMemo(() => data.filter((doc) => doc.category === 'document'), [data]);
+ const documentsData = useMemo(
+ () => data.filter((doc) => doc.category === AGENT_DOCUMENT_CATEGORY),
+ [data],
+ );
const skillBundleViews = useMemo(() => buildSkillBundleViews(data), [data]);
diff --git a/src/routes/(main)/resource/features/DndContextWrapper.tsx b/src/routes/(main)/resource/features/DndContextWrapper.tsx
index a3e20437493..aa9efe8f938 100644
--- a/src/routes/(main)/resource/features/DndContextWrapper.tsx
+++ b/src/routes/(main)/resource/features/DndContextWrapper.tsx
@@ -1,5 +1,6 @@
'use client';
+import { CUSTOM_DOCUMENT_FILE_TYPE, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { Icon, useAppElement } from '@lobehub/ui';
import { App } from 'antd';
import { cssVar } from 'antd-style';
@@ -263,9 +264,9 @@ export const DndContextWrapper = memo<PropsWithChildren>(({ children }) => {
justifyContent: 'center',
}}
>
- {currentDrag.data.fileType === 'custom/folder' ? (
+ {currentDrag.data.fileType === CUSTOM_FOLDER_FILE_TYPE ? (
<Icon icon={FolderIcon} size={20} />
- ) : currentDrag.data.fileType === 'custom/document' ? (
+ ) : currentDrag.data.fileType === CUSTOM_DOCUMENT_FILE_TYPE ? (
<Icon icon={FileText} size={20} />
) : (
<FileIcon
diff --git a/src/routes/(main)/resource/features/hooks/useInitFileCheck.ts b/src/routes/(main)/resource/features/hooks/useInitFileCheck.ts
index c155e1b890d..305cf688857 100644
--- a/src/routes/(main)/resource/features/hooks/useInitFileCheck.ts
+++ b/src/routes/(main)/resource/features/hooks/useInitFileCheck.ts
@@ -1,5 +1,6 @@
'use client';
+import { CUSTOM_DOCUMENT_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
@@ -41,8 +42,8 @@ export const useInitFileCheck = () => {
const isPage =
!isPDF &&
- (fileData?.sourceType === 'document' ||
- fileData?.fileType === 'custom/document' ||
+ (fileData?.sourceType === DERIVED_DOCUMENT_SOURCE_TYPE ||
+ fileData?.fileType === CUSTOM_DOCUMENT_FILE_TYPE ||
!!documentData);
if (isPDF) {
diff --git a/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts b/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts
index 78265697303..4644b7aa26e 100644
--- a/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/agentDocumentVfs.integration.test.ts
@@ -110,6 +110,77 @@ describe('AgentDocument VFS Router Integration Tests', () => {
);
});
+ it('keeps extensionless ordinary VFS writes as system document names', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+
+ const created = await caller.writeDocumentByPath({
+ agentId,
+ content: '# Draft',
+ path: './draft',
+ });
+
+ expect(created).toEqual(
+ expect.objectContaining({
+ name: 'draft',
+ path: './draft',
+ type: 'file',
+ }),
+ );
+
+ const read = await caller.readDocumentByPath({ agentId, path: './draft' });
+
+ expect(read).toEqual(
+ expect.objectContaining({
+ content: '# Draft\n',
+ path: './draft',
+ }),
+ );
+ });
+
+ it('resolves extensionless ordinary VFS writes to the existing system document', async () => {
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+
+ await caller.writeDocumentByPath({
+ agentId,
+ content: 'first',
+ path: './draft',
+ });
+ await caller.writeDocumentByPath({
+ agentId,
+ content: 'second',
+ path: './draft',
+ });
+
+ const nodes = await caller.listDocumentsByPath({ agentId, path: './' });
+ if (!nodes) throw new Error('Expected root document listing');
+
+ const draftNodes = nodes.filter((node) => node.name === 'draft');
+ const read = await caller.readDocumentByPath({ agentId, path: './draft' });
+
+ expect(draftNodes).toHaveLength(1);
+ expect(read).toEqual(expect.objectContaining({ content: 'second\n', path: './draft' }));
+ });
+
+ it('updates existing legacy extensionless ordinary documents by exact path', async () => {
+ await agentDocumentModel.create(agentId, 'draft', 'first');
+
+ const caller = agentDocumentRouter.createCaller(createTestContext(userId));
+ const updated = await caller.writeDocumentByPath({
+ agentId,
+ content: 'second',
+ path: './draft',
+ });
+
+ const nodes = await caller.listDocumentsByPath({ agentId, path: './' });
+ if (!nodes) throw new Error('Expected root document listing');
+
+ const read = await caller.readDocumentByPath({ agentId, path: './draft' });
+
+ expect(updated).toEqual(expect.objectContaining({ name: 'draft', path: './draft' }));
+ expect(nodes.some((node) => node.name === 'draft.md')).toBe(false);
+ expect(read).toEqual(expect.objectContaining({ content: 'second\n', path: './draft' }));
+ });
+
it('stats mounted agent skills through unified ./lobe paths', async () => {
const caller = agentDocumentRouter.createCaller(createTestContext(userId));
diff --git a/src/server/routers/lambda/file.ts b/src/server/routers/lambda/file.ts
index f19cd1df94f..53153333d19 100644
--- a/src/server/routers/lambda/file.ts
+++ b/src/server/routers/lambda/file.ts
@@ -1,3 +1,8 @@
+import {
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ DERIVED_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -27,7 +32,13 @@ const filterKnowledgeItems = <
knowledgeBaseId?: string,
) => {
return !knowledgeBaseId
- ? items.filter((item) => !(item.sourceType === 'document' && item.fileType === 'custom/folder'))
+ ? items.filter(
+ (item) =>
+ !(
+ item.sourceType === DERIVED_DOCUMENT_SOURCE_TYPE &&
+ item.fileType === CUSTOM_FOLDER_FILE_TYPE
+ ),
+ )
: items;
};
@@ -433,7 +444,7 @@ export const fileRouter = router({
const filteredItems = filterKnowledgeItems(itemsToProcess, input.knowledgeBaseId);
for (const item of filteredItems) {
- if (item.sourceType === 'document') {
+ if (item.sourceType === DERIVED_DOCUMENT_SOURCE_TYPE) {
documentIds.push(item.documentId ?? item.id);
continue;
}
@@ -475,7 +486,7 @@ export const fileRouter = router({
// Query recent items and filter for files only (exclude documents/pages)
const allItems = await ctx.knowledgeRepo.queryRecent(limit * 3); // Query more to ensure we have enough files after filtering
const fileItems = allItems
- .filter((item) => item.sourceType === 'file' && item.fileType !== 'custom/document')
+ .filter((item) => item.sourceType === 'file' && item.fileType !== CUSTOM_DOCUMENT_FILE_TYPE)
.slice(0, limit);
if (fileItems.length === 0) return [];
@@ -535,7 +546,11 @@ export const fileRouter = router({
// Query recent items and filter for pages (documents) only, exclude folders
const allItems = await ctx.knowledgeRepo.queryRecent(limit * 3); // Query more to ensure we have enough pages after filtering
return allItems
- .filter((item) => item.sourceType === 'document' && item.fileType !== 'custom/folder')
+ .filter(
+ (item) =>
+ item.sourceType === DERIVED_DOCUMENT_SOURCE_TYPE &&
+ item.fileType !== CUSTOM_FOLDER_FILE_TYPE,
+ )
.slice(0, limit);
}),
diff --git a/src/server/services/agentDocumentVfs/index.test.ts b/src/server/services/agentDocumentVfs/index.test.ts
index d5ea94564e5..111b65d6f19 100644
--- a/src/server/services/agentDocumentVfs/index.test.ts
+++ b/src/server/services/agentDocumentVfs/index.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentAccess, AgentDocumentModel } from '@/database/models/agentDocuments';
@@ -16,6 +17,7 @@ vi.mock('@/database/models/agentDocuments', () => ({
WRITE: 4,
},
AgentDocumentModel: vi.fn(),
+ buildDocumentFilename: vi.fn((title: string) => title),
}));
vi.mock('./mounts/skills/createSkillMount', () => ({
@@ -70,7 +72,7 @@ describe('AgentDocumentVfsService', () => {
content: 'hello',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'documents-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'SOUL.md',
id: 'agent-doc-1',
updatedAt: new Date('2024-01-02T00:00:00.000Z'),
@@ -80,7 +82,7 @@ describe('AgentDocumentVfsService', () => {
content: 'newer duplicate',
createdAt: new Date('2024-01-02T00:00:00.000Z'),
documentId: 'documents-duplicate',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'SOUL.md',
id: 'agent-doc-duplicate',
updatedAt: new Date('2024-01-03T00:00:00.000Z'),
@@ -164,7 +166,7 @@ describe('AgentDocumentVfsService', () => {
content: '# Soul',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'documents-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'SOUL.md',
id: 'agent-doc-1',
metadata: { category: 'system' },
@@ -197,7 +199,7 @@ describe('AgentDocumentVfsService', () => {
content: ['line 0', 'line 1', 'line 2', 'line 3'].join('\n'),
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'documents-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'SOUL.md',
id: 'agent-doc-1',
updatedAt: new Date('2024-01-02T00:00:00.000Z'),
@@ -258,7 +260,7 @@ describe('AgentDocumentVfsService', () => {
content: 'hello',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'documents-2',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'notes.md',
id: 'agent-doc-2',
metadata: null,
@@ -294,7 +296,7 @@ describe('AgentDocumentVfsService', () => {
content: 'first',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'documents-first',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'notes.md',
id: 'agent-doc-first',
},
@@ -303,7 +305,7 @@ describe('AgentDocumentVfsService', () => {
content: 'second',
createdAt: new Date('2024-01-02T00:00:00.000Z'),
documentId: 'documents-second',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'notes.md',
id: 'agent-doc-second',
},
@@ -435,7 +437,7 @@ describe('AgentDocumentVfsService', () => {
content: 'hello',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'child-doc-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'todo.md',
id: 'child-agent-doc-1',
updatedAt: new Date('2024-01-02T00:00:00.000Z'),
@@ -503,7 +505,7 @@ describe('AgentDocumentVfsService', () => {
content: 'hello',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'documents-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'old.md',
id: 'agent-doc-1',
parentId: null,
@@ -579,7 +581,7 @@ describe('AgentDocumentVfsService', () => {
accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
content: `file ${index}`,
documentId: `doc-${index}`,
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: `file-${index}.md`,
id: `agent-doc-${index}`,
})),
@@ -604,7 +606,7 @@ describe('AgentDocumentVfsService', () => {
createdAt: new Date('2024-01-01T00:00:00.000Z'),
deletedAt: new Date('2024-01-03T00:00:00.000Z'),
documentId: 'deleted-doc-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'draft.md',
id: 'deleted-agent-doc-1',
parentId: null,
@@ -616,7 +618,7 @@ describe('AgentDocumentVfsService', () => {
content: 'live',
createdAt: new Date('2024-01-04T00:00:00.000Z'),
documentId: 'live-doc-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'draft.md',
id: 'live-agent-doc-1',
parentId: null,
@@ -628,7 +630,7 @@ describe('AgentDocumentVfsService', () => {
content: 'deleted',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'deleted-doc-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'draft.md',
id: 'deleted-agent-doc-1',
parentId: null,
@@ -639,7 +641,7 @@ describe('AgentDocumentVfsService', () => {
content: 'live',
createdAt: new Date('2024-01-04T00:00:00.000Z'),
documentId: 'live-doc-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'draft.md',
id: 'live-agent-doc-1',
parentId: null,
@@ -676,7 +678,7 @@ describe('AgentDocumentVfsService', () => {
createdAt: new Date('2024-01-01T00:00:00.000Z'),
deletedAt: new Date('2024-01-03T00:00:00.000Z'),
documentId: 'child-doc-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'todo.md',
id: 'child-agent-doc-1',
parentId: 'folder-doc-1',
@@ -728,7 +730,7 @@ describe('AgentDocumentVfsService', () => {
accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
content: '# Leaf',
documentId: 'file-c',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'c.md',
id: 'agent-doc-c',
});
@@ -747,7 +749,7 @@ describe('AgentDocumentVfsService', () => {
accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
content: `file ${index}`,
documentId: `doc-${index}`,
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: `file-${index}.md`,
id: `agent-doc-${index}`,
})),
@@ -773,7 +775,7 @@ describe('AgentDocumentVfsService', () => {
deleteReason: 'user-delete',
deletedAt: new Date('2024-01-03T00:00:00.000Z'),
documentId: 'child-doc-1',
- fileType: 'agent/document',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
filename: 'todo.md',
id: 'child-agent-doc-1',
parentId: 'folder-doc-1',
diff --git a/src/server/services/agentDocumentVfs/index.ts b/src/server/services/agentDocumentVfs/index.ts
index cd0421db4c9..651da0e2eb7 100644
--- a/src/server/services/agentDocumentVfs/index.ts
+++ b/src/server/services/agentDocumentVfs/index.ts
@@ -1,9 +1,10 @@
import type { LobeChatDatabase } from '@lobechat/database';
+import type { AgentDocument } from '@/database/models/agentDocuments';
import {
AgentAccess,
- type AgentDocument,
AgentDocumentModel,
+ buildDocumentFilename,
} from '@/database/models/agentDocuments';
import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';
@@ -784,15 +785,17 @@ export class AgentDocumentVfsService {
throw new AgentDocumentVfsError(`Cannot write reserved path: ${path}`, 'BAD_REQUEST');
}
- const existing = await this.resolveOrdinaryPath(path, ctx.agentId);
+ const exactExisting = await this.resolveOrdinaryPath(path, ctx.agentId);
+ const writablePath = exactExisting ? path : normalizeOrdinaryDocumentPath(path);
+ const existing = exactExisting ?? (await this.resolveOrdinaryPath(writablePath, ctx.agentId));
if (existing) {
if (existing.fileType === DOCUMENT_FOLDER_TYPE) {
- throw new AgentDocumentVfsError(`Path is not a file: ${path}`, 'BAD_REQUEST');
+ throw new AgentDocumentVfsError(`Path is not a file: ${writablePath}`, 'BAD_REQUEST');
}
if (createMode === 'always-new') {
- throw new AgentDocumentVfsError(`Path already exists: ${path}`, 'BAD_REQUEST');
+ throw new AgentDocumentVfsError(`Path already exists: ${writablePath}`, 'BAD_REQUEST');
}
const snapshot = await createMarkdownEditorSnapshot(content);
@@ -801,24 +804,27 @@ export class AgentDocumentVfsService {
editorData: snapshot.editorData,
});
- const updated = await this.resolveOrdinaryPath(path, ctx.agentId);
+ const updated = await this.resolveOrdinaryPath(writablePath, ctx.agentId);
if (!updated) {
- throw new AgentDocumentVfsError(`Failed to reload updated path: ${path}`, 'BAD_REQUEST');
+ throw new AgentDocumentVfsError(
+ `Failed to reload updated path: ${writablePath}`,
+ 'BAD_REQUEST',
+ );
}
- return this.toOrdinaryStats(updated, path);
+ return this.toOrdinaryStats(updated, writablePath);
}
if (createMode === 'must-exist') {
- throw new AgentDocumentVfsError(`Path not found: ${path}`, 'NOT_FOUND');
+ throw new AgentDocumentVfsError(`Path not found: ${writablePath}`, 'NOT_FOUND');
}
- const segments = splitAgentDocumentPath(path);
+ const segments = splitAgentDocumentPath(writablePath);
const filename = segments.at(-1);
if (!filename) {
- throw new AgentDocumentVfsError(`Invalid VFS path: ${path}`, 'BAD_REQUEST');
+ throw new AgentDocumentVfsError(`Invalid VFS path: ${writablePath}`, 'BAD_REQUEST');
}
const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;
@@ -836,14 +842,20 @@ export class AgentDocumentVfsService {
);
}
+ const normalizedFilename = buildDocumentFilename(filename);
const snapshot = await createMarkdownEditorSnapshot(content);
- const created = await this.agentDocumentModel.create(ctx.agentId, filename, snapshot.content, {
- editorData: snapshot.editorData,
- parentId: parentNode?.documentId ?? null,
- title: filename,
- });
+ const created = await this.agentDocumentModel.create(
+ ctx.agentId,
+ normalizedFilename,
+ snapshot.content,
+ {
+ editorData: snapshot.editorData,
+ parentId: parentNode?.documentId ?? null,
+ title: normalizedFilename,
+ },
+ );
- return this.toOrdinaryStats(created, path);
+ return this.toOrdinaryStats(created, buildOrdinaryPath(parentPath, normalizedFilename));
}
private async renameOrdinaryPath(
@@ -1150,6 +1162,16 @@ const splitAgentDocumentPath = (path: string) =>
const buildOrdinaryPath = (parentPath: string, filename: string) =>
parentPath === './' ? `./${filename}` : `${parentPath}/${filename}`;
+const normalizeOrdinaryDocumentPath = (path: string): string => {
+ const segments = splitAgentDocumentPath(path);
+ const filename = segments.at(-1);
+ if (!filename) return path;
+
+ const parentPath = segments.length === 1 ? './' : `./${segments.slice(0, -1).join('/')}`;
+ const normalizedFilename = buildDocumentFilename(filename);
+ return buildOrdinaryPath(parentPath, normalizedFilename);
+};
+
const normalizeListLimit = (limit?: number) => {
if (limit === undefined) return DEFAULT_LIST_LIMIT;
diff --git a/src/server/services/agentDocuments/index.test.ts b/src/server/services/agentDocuments/index.test.ts
index ddcc7498980..983ddcb2711 100644
--- a/src/server/services/agentDocuments/index.test.ts
+++ b/src/server/services/agentDocuments/index.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentModel } from '@/database/models/agent';
@@ -154,6 +155,20 @@ describe('AgentDocumentsService', () => {
expect(result).toEqual({ id: 'new-doc', filename: 'note-2' });
});
+ it('should preserve an explicit filename extension', async () => {
+ mockModel.findByFilename.mockResolvedValueOnce(undefined);
+ mockModel.create.mockResolvedValue({ id: 'new-doc', filename: 'notes.txt' });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.createDocument('agent-1', 'notes.txt', 'content');
+
+ expect(mockModel.findByFilename).toHaveBeenCalledWith('agent-1', 'notes.txt');
+ expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'notes.txt', 'content', {
+ editorData: { root: { children: [] } },
+ title: 'notes.txt',
+ });
+ });
+
it('should append collision suffix before the filename extension', async () => {
mockModel.findByFilename
.mockResolvedValueOnce({ id: 'existing-doc' })
@@ -599,6 +614,7 @@ describe('AgentDocumentsService', () => {
agentId: 'agent-1',
content: 'content',
documentId: 'documents-1',
+ filename: 'Old title.md',
id: 'agent-doc-1',
title: 'Old title',
});
@@ -620,6 +636,35 @@ describe('AgentDocumentsService', () => {
expect(
mockDocumentService.trySaveCurrentDocumentHistory.mock.invocationCallOrder[0],
).toBeLessThan(mockModel.rename.mock.invocationCallOrder[0]);
+ expect(mockModel.rename).toHaveBeenCalledWith('agent-doc-1', 'New title', {
+ filename: 'New title',
+ });
+ });
+
+ it('should preserve explicit extensions when renaming a document', async () => {
+ mockModel.findById.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'content',
+ documentId: 'documents-1',
+ filename: 'Old title.md',
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
+ id: 'agent-doc-1',
+ title: 'Old title',
+ });
+ mockModel.rename.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'content',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'notes.txt',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.renameDocumentById('agent-doc-1', 'notes.txt', 'agent-1');
+
+ expect(mockModel.rename).toHaveBeenCalledWith('agent-doc-1', 'notes.txt', {
+ filename: 'notes.txt',
+ });
});
it('should reject renaming skill-managed documents', async () => {
diff --git a/src/server/services/agentDocuments/index.ts b/src/server/services/agentDocuments/index.ts
index 0d608f3e4ba..7d3ebb766a2 100644
--- a/src/server/services/agentDocuments/index.ts
+++ b/src/server/services/agentDocuments/index.ts
@@ -730,12 +730,21 @@ export class AgentDocumentsService {
);
}
- const title = newTitle.trim();
- if (title && title !== doc.title) {
+ const trimmedTitle = newTitle.trim();
+ if (doc.fileType === DOCUMENT_FOLDER_TYPE || !trimmedTitle) {
+ if (trimmedTitle && trimmedTitle !== doc.title) {
+ await this.documentService.trySaveCurrentDocumentHistory(doc.documentId, 'llm_call');
+ }
+
+ return this.agentDocumentModel.rename(documentId, trimmedTitle);
+ }
+
+ const filename = buildDocumentFilename(trimmedTitle);
+ if (trimmedTitle !== doc.title || filename !== doc.filename) {
await this.documentService.trySaveCurrentDocumentHistory(doc.documentId, 'llm_call');
}
- return this.agentDocumentModel.rename(documentId, newTitle);
+ return this.agentDocumentModel.rename(documentId, trimmedTitle, { filename });
}
async copyDocumentById(documentId: string, newTitle?: string, expectedAgentId?: string) {
diff --git a/src/server/services/document/index.ts b/src/server/services/document/index.ts
index f31873e67c8..31acd8bb3ed 100644
--- a/src/server/services/document/index.ts
+++ b/src/server/services/document/index.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
import { type DocumentItem } from '@lobechat/database/schemas';
import { documents, files } from '@lobechat/database/schemas';
@@ -94,7 +95,7 @@ export class DocumentService {
content,
editorData,
title,
- fileType = 'custom/document',
+ fileType = CUSTOM_DOCUMENT_FILE_TYPE,
metadata,
knowledgeBaseId,
parentId,
@@ -109,7 +110,7 @@ export class DocumentService {
// If creating in a knowledge base, create a corresponding file record
// BUT skip for folders - folders should only exist in the documents table
- if (knowledgeBaseId && fileType !== 'custom/folder') {
+ if (knowledgeBaseId && fileType !== CUSTOM_FOLDER_FILE_TYPE) {
const file = await this.fileModel.create(
{
fileType,
@@ -127,7 +128,9 @@ export class DocumentService {
// Store knowledgeBaseId in metadata for folders (which don't have fileId)
const finalMetadata =
- knowledgeBaseId && fileType === 'custom/folder' ? { ...metadata, knowledgeBaseId } : metadata;
+ knowledgeBaseId && fileType === CUSTOM_FOLDER_FILE_TYPE
+ ? { ...metadata, knowledgeBaseId }
+ : metadata;
const document = await this.documentModel.create({
content,
@@ -273,7 +276,7 @@ export class DocumentService {
if (!document) return;
// If it's a folder, recursively delete all children first
- if (document.fileType === 'custom/folder') {
+ if (document.fileType === CUSTOM_FOLDER_FILE_TYPE) {
const children = await this.db.query.documents.findMany({
where: eq(documents.parentId, id),
});
@@ -433,7 +436,7 @@ export class DocumentService {
const document = await this.documentModel.create({
content: cleanContent,
fileId,
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
filename: title,
metadata: fileDocument.metadata,
parentId: file.parentId,
@@ -486,7 +489,7 @@ export class DocumentService {
const document = await this.documentModel.create({
content: fileDocument.content,
fileId,
- fileType: 'custom/document', // Use custom/document for all parsed files
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE, // Use custom/document for all parsed files
filename: title,
metadata: fileDocument.metadata,
pages: fileDocument.pages,
diff --git a/src/server/services/toolExecution/serverRuntimes/lobeAgentPlan.ts b/src/server/services/toolExecution/serverRuntimes/lobeAgentPlan.ts
index 36e293f83fa..c87e93915d5 100644
--- a/src/server/services/toolExecution/serverRuntimes/lobeAgentPlan.ts
+++ b/src/server/services/toolExecution/serverRuntimes/lobeAgentPlan.ts
@@ -1,11 +1,10 @@
import { type PlanDocument, type PlanRuntimeService } from '@lobechat/builtin-tool-lobe-agent';
+import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
import { DocumentModel } from '@/database/models/document';
import { TopicDocumentModel } from '@/database/models/topicDocument';
-const PLAN_FILE_TYPE = 'agent/plan';
-
/**
* Build a server-side `PlanRuntimeService` backed by the application database.
*
@@ -49,7 +48,7 @@ export const createServerPlanRuntimeService = (
const doc = await documentModel.create({
content,
description,
- fileType: PLAN_FILE_TYPE,
+ fileType: AGENT_PLAN_FILE_TYPE,
source: `lobe-agent:${topicId}`,
sourceType: 'api',
title: goal,
@@ -64,12 +63,12 @@ export const createServerPlanRuntimeService = (
findPlanById: async (id) => {
const doc = await documentModel.findById(id);
- if (!doc || doc.fileType !== PLAN_FILE_TYPE) return null;
+ if (!doc || doc.fileType !== AGENT_PLAN_FILE_TYPE) return null;
return toPlanDocument(doc);
},
findPlanByTopic: async (topicId) => {
- const docs = await topicDocumentModel.findByTopicId(topicId, { type: PLAN_FILE_TYPE });
+ const docs = await topicDocumentModel.findByTopicId(topicId, { type: AGENT_PLAN_FILE_TYPE });
const first = docs[0];
return first ? toPlanDocument(first) : null;
},
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 6e9f7b417b0..2018cafc600 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -12,7 +12,11 @@ import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-
import { LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { WebOnboardingIdentifier } from '@lobechat/builtin-tool-web-onboarding';
-import { KLAVIS_SERVER_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
+import {
+ AGENT_PLAN_FILE_TYPE,
+ KLAVIS_SERVER_TYPES,
+ LOBEHUB_SKILL_PROVIDERS,
+} from '@lobechat/const';
import type {
AgentBuilderContext,
AgentContextDocument,
@@ -332,7 +336,7 @@ export const contextEngineering = async ({
// Fetch plan document for the current topic
const planResult = await notebookService.listDocuments({
topicId,
- type: 'agent/plan',
+ type: AGENT_PLAN_FILE_TYPE,
});
if (planResult.data.length > 0) {
diff --git a/src/services/document/index.ts b/src/services/document/index.ts
index 5c8221ea7b9..ab2e7eef1a6 100644
--- a/src/services/document/index.ts
+++ b/src/services/document/index.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { type DocumentItem } from '@lobechat/database/schemas';
import { lambdaClient } from '@/libs/trpc/client';
@@ -175,7 +176,7 @@ export class DocumentService {
async getPageDocuments(pageSize: number = 20): Promise<DocumentItem[]> {
const result = await this.queryDocuments({
current: 0,
- fileTypes: ['custom/document', 'application/pdf'],
+ fileTypes: [CUSTOM_DOCUMENT_FILE_TYPE, 'application/pdf'],
pageSize,
sourceTypes: ['editor', 'file', 'api'],
});
@@ -184,7 +185,7 @@ export class DocumentService {
.filter(
(doc) =>
['editor', 'file', 'api'].includes(doc.sourceType) &&
- ['custom/document', 'application/pdf'].includes(doc.fileType),
+ [CUSTOM_DOCUMENT_FILE_TYPE, 'application/pdf'].includes(doc.fileType),
)
.map((doc) => ({ ...doc, filename: doc.filename ?? doc.title ?? 'Untitled' }));
}
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index 0336d20d4e9..bf52589e365 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -1,3 +1,5 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
+
import { lambdaClient } from '@/libs/trpc/client';
import {
type CheckFileHashResult,
@@ -90,7 +92,7 @@ export class FileService {
editorData: doc.editorData,
embeddingError: null,
embeddingStatus: null,
- fileType: doc.fileType || 'custom/document',
+ fileType: doc.fileType || CUSTOM_DOCUMENT_FILE_TYPE,
finishEmbedding: false,
id: doc.id,
metadata: doc.metadata,
@@ -98,7 +100,7 @@ export class FileService {
parentId: doc.parentId,
size: doc.totalCharCount || 0,
slug: doc.slug,
- sourceType: 'document',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : new Date(),
url: doc.source || '',
} as FileListItem;
diff --git a/src/services/notebook.ts b/src/services/notebook.ts
index c2d8835ff91..6c340e2ba47 100644
--- a/src/services/notebook.ts
+++ b/src/services/notebook.ts
@@ -1,8 +1,9 @@
import { type DocumentType } from '@lobechat/builtin-tool-notebook';
+import type { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';
import { lambdaClient } from '@/libs/trpc/client';
-type ExtendedDocumentType = DocumentType | 'agent/plan';
+type ExtendedDocumentType = DocumentType | typeof AGENT_PLAN_FILE_TYPE;
interface CreateDocumentParams {
content: string;
diff --git a/src/services/resource/index.ts b/src/services/resource/index.ts
index e8ae6b55722..900931db72e 100644
--- a/src/services/resource/index.ts
+++ b/src/services/resource/index.ts
@@ -1,3 +1,5 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
+
import { type FileListItem, type KnowledgeItemStatus } from '@/types/files';
import {
type CreateResourceParams,
@@ -196,14 +198,14 @@ export class ResourceService {
typeof created.editorData === 'string'
? JSON.parse(created.editorData)
: created.editorData,
- fileType: created.fileType || 'custom/document',
+ fileType: created.fileType || CUSTOM_DOCUMENT_FILE_TYPE,
id: created.id,
metadata: created.metadata || undefined,
name: created.title || 'Untitled',
parentId: created.parentId,
size: created.totalCharCount || 0,
slug: created.slug || undefined,
- sourceType: 'document',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
title: created.title || undefined,
updatedAt: created.updatedAt ? new Date(created.updatedAt) : new Date(),
url: created.source || '',
diff --git a/src/store/file/slices/document/action.test.ts b/src/store/file/slices/document/action.test.ts
index eebd58179f3..19a7ab9680a 100644
--- a/src/store/file/slices/document/action.test.ts
+++ b/src/store/file/slices/document/action.test.ts
@@ -1,3 +1,8 @@
+import {
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ DERIVED_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -24,7 +29,7 @@ const createDocumentFixture = (overrides: Partial<LobeDocument> = {}): LobeDocum
content: 'Body',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
editorData: {},
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
filename: 'Old title',
id: 'doc-1',
metadata: {},
@@ -41,14 +46,14 @@ const createResourceFixture = (overrides: Partial<ResourceItem> = {}): ResourceI
content: 'Body',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
editorData: {},
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
id: 'doc-1',
knowledgeBaseId: 'kb-1',
metadata: {},
name: 'Old title',
parentId: null,
size: 4,
- sourceType: 'document',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
title: 'Old title',
updatedAt: new Date('2024-01-01T00:00:00.000Z'),
url: 'document',
@@ -82,7 +87,7 @@ describe('DocumentAction', () => {
content: '',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
editorData: '{}',
- fileType: 'custom/folder',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
id: 'folder-1',
metadata: {},
parentId: null,
@@ -111,13 +116,13 @@ describe('DocumentAction', () => {
expect(useStore.getState().resourceList.map((item) => item.id)).toEqual(['folder-1']);
expect(useStore.getState().resourceMap.get('folder-1')).toMatchObject({
- fileType: 'custom/folder',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
id: 'folder-1',
knowledgeBaseId: 'kb-1',
name: 'New Folder',
parentId: null,
slug: 'new-folder',
- sourceType: 'document',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
title: 'New Folder',
});
});
diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.ts
index ca51459fbe2..6cbbc46b55f 100644
--- a/src/store/file/slices/document/action.ts
+++ b/src/store/file/slices/document/action.ts
@@ -1,3 +1,8 @@
+import {
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ DERIVED_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
import { createNanoId } from '@lobechat/utils';
import { type SWRResponse } from 'swr';
@@ -17,8 +22,8 @@ import { type DocumentQueryFilter } from './initialState';
const n = setNamespace('document');
const ALLOWED_DOCUMENT_SOURCE_TYPES = new Set(['editor', 'file', 'api']);
-const ALLOWED_DOCUMENT_FILE_TYPES = new Set(['custom/document', 'application/pdf']);
-const EDITOR_DOCUMENT_FILE_TYPE = 'custom/document';
+const ALLOWED_DOCUMENT_FILE_TYPES = new Set([CUSTOM_DOCUMENT_FILE_TYPE, 'application/pdf']);
+const EDITOR_DOCUMENT_FILE_TYPE = CUSTOM_DOCUMENT_FILE_TYPE;
interface ResourceDocumentSnapshot {
content?: string | null;
@@ -171,7 +176,7 @@ export class DocumentActionImpl {
parentId: document.parentId !== undefined ? document.parentId : (fallback?.parentId ?? null),
size: document.totalCharCount ?? fallback?.size ?? document.content?.length ?? 0,
slug: document.slug !== undefined ? document.slug : fallback?.slug,
- sourceType: 'document',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
title:
document.title !== undefined
? (document.title ?? undefined)
@@ -266,7 +271,7 @@ export class DocumentActionImpl {
const folder = await documentService.createDocument({
content: '',
editorData: '{}',
- fileType: 'custom/folder',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
knowledgeBaseId,
metadata: {
createdAt: now,
diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.ts
index 020c7ac41bd..b5fa4083280 100644
--- a/src/store/home/slices/homeInput/action.ts
+++ b/src/store/home/slices/homeInput/action.ts
@@ -1,4 +1,5 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { chatGroupService } from '@/services/chatGroup';
import { documentService } from '@/services/document';
@@ -225,7 +226,7 @@ export class HomeInputActionImpl {
// 2. Create new Document
const newDoc = await documentService.createDocument({
editorData: '{}',
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
title: markdownToTxt(message ?? '').slice(0, 50) || 'Untitled',
});
diff --git a/src/store/notebook/action.ts b/src/store/notebook/action.ts
index d9d28914b6f..53bd2d7a246 100644
--- a/src/store/notebook/action.ts
+++ b/src/store/notebook/action.ts
@@ -1,4 +1,5 @@
import { type DocumentType } from '@lobechat/builtin-tool-notebook';
+import type { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';
import { type DocumentItem } from '@lobechat/database/schemas';
import { type NotebookDocument } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
@@ -18,7 +19,7 @@ const n = setNamespace('notebook');
export { SWR_USE_FETCH_NOTEBOOK_DOCUMENTS } from '@/services/document/swrKeys';
-type ExtendedDocumentType = DocumentType | 'agent/plan';
+type ExtendedDocumentType = DocumentType | typeof AGENT_PLAN_FILE_TYPE;
interface CreateDocumentParams {
content: string;
diff --git a/src/store/page/slices/crud/action.ts b/src/store/page/slices/crud/action.ts
index 49890781160..71451fdc090 100644
--- a/src/store/page/slices/crud/action.ts
+++ b/src/store/page/slices/crud/action.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { type SWRResponse } from 'swr';
import { useClientDataSWRWithSync } from '@/libs/swr';
@@ -13,7 +14,7 @@ import { type PageStore } from '../../store';
const n = setNamespace('page/crud');
-const EDITOR_PAGE_FILE_TYPE = 'custom/document';
+const EDITOR_PAGE_FILE_TYPE = CUSTOM_DOCUMENT_FILE_TYPE;
/**
* Page update parameters - flattened for easier use
@@ -56,7 +57,7 @@ export class CrudActionImpl {
typeof newPage.editorData === 'string'
? JSON.parse(newPage.editorData)
: newPage.editorData || null,
- fileType: 'custom/document',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
filename: newPage.title || title,
id: newPage.id,
metadata: newPage.metadata || {},
diff --git a/src/store/page/slices/list/action.ts b/src/store/page/slices/list/action.ts
index f2115a498bd..32480d87ece 100644
--- a/src/store/page/slices/list/action.ts
+++ b/src/store/page/slices/list/action.ts
@@ -1,3 +1,4 @@
+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';
import { type DocumentItem } from '@lobechat/database/schemas';
import { type SWRResponse } from 'swr';
@@ -33,7 +34,7 @@ const documentItemToLobeDocument = (document: DocumentItem): LobeDocument => ({
const n = setNamespace('page/list');
const ALLOWED_PAGE_SOURCE_TYPES = new Set(['editor', 'file', 'api']);
-const ALLOWED_PAGE_FILE_TYPES = new Set(['custom/document', 'application/pdf']);
+const ALLOWED_PAGE_FILE_TYPES = new Set([CUSTOM_DOCUMENT_FILE_TYPE, 'application/pdf']);
/**
* Check if a page should be displayed in the page list
diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.ts
index e75416488dd..2b29af5e365 100644
--- a/src/store/tree/actions.ts
+++ b/src/store/tree/actions.ts
@@ -1,3 +1,5 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
+
import { fileService } from '@/services/file';
import { resourceService } from '@/services/resource';
import type { StoreSetter } from '@/store/types';
@@ -24,7 +26,7 @@ export const toTreeItem = (item: {
}): TreeItem => ({
fileType: item.fileType,
id: item.id,
- isFolder: item.fileType === 'custom/folder',
+ isFolder: item.fileType === CUSTOM_FOLDER_FILE_TYPE,
metadata: item.metadata ?? undefined,
name: item.name,
slug: item.slug,
diff --git a/src/utils/__tests__/agentDocumentContextMapping.test.ts b/src/utils/__tests__/agentDocumentContextMapping.test.ts
index 2d612d2d149..6f30f3f30ca 100644
--- a/src/utils/__tests__/agentDocumentContextMapping.test.ts
+++ b/src/utils/__tests__/agentDocumentContextMapping.test.ts
@@ -1,4 +1,10 @@
import { DocumentLoadFormat, DocumentLoadRule, PolicyLoad } from '@lobechat/agent-templates';
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_SOURCE_TYPE,
+ CUSTOM_FOLDER_FILE_TYPE,
+ WEB_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
import { describe, expect, it } from 'vitest';
import type { AgentDocumentWithRules } from '@/database/models/agentDocuments';
@@ -14,7 +20,7 @@ const buildDoc = (overrides: Partial<AgentDocumentWithRules> = {}): AgentDocumen
accessSelf: 31,
accessShared: 0,
agentId: 'agent-1',
- category: 'document',
+ category: AGENT_DOCUMENT_CATEGORY,
content: 'body',
createdAt: new Date('2026-05-01T00:00:00.000Z'),
deleteReason: null,
@@ -39,7 +45,7 @@ const buildDoc = (overrides: Partial<AgentDocumentWithRules> = {}): AgentDocumen
policyLoadPosition: 'before-first-user',
policyLoadRule: 'always',
source: 'https://example.com/post',
- sourceType: 'web',
+ sourceType: WEB_DOCUMENT_SOURCE_TYPE,
templateId: null,
title: 'Doc title',
updatedAt: new Date('2026-05-21T00:00:00.000Z'),
@@ -53,8 +59,12 @@ describe('toAgentContextDocument', () => {
// every chat that went through RuntimeExecutors. Keep this lock tight so any
// future field addition that forgets one side trips here.
it('propagates sourceType so the progressive web-doc filter can fire', () => {
- expect(toAgentContextDocument(buildDoc({ sourceType: 'web' })).sourceType).toBe('web');
- expect(toAgentContextDocument(buildDoc({ sourceType: 'agent' })).sourceType).toBe('agent');
+ expect(
+ toAgentContextDocument(buildDoc({ sourceType: WEB_DOCUMENT_SOURCE_TYPE })).sourceType,
+ ).toBe(WEB_DOCUMENT_SOURCE_TYPE);
+ expect(
+ toAgentContextDocument(buildDoc({ sourceType: AGENT_DOCUMENT_SOURCE_TYPE })).sourceType,
+ ).toBe(AGENT_DOCUMENT_SOURCE_TYPE);
expect(toAgentContextDocument(buildDoc({ sourceType: 'file' })).sourceType).toBe('file');
});
@@ -134,15 +144,19 @@ describe('toAgentContextDocument', () => {
describe('toAgentContextDocuments', () => {
it('preserves order and maps each row through toAgentContextDocument', () => {
const rows = [
- buildDoc({ id: 'a', sourceType: 'web' }),
- buildDoc({ id: 'b', sourceType: 'agent' }),
+ buildDoc({ id: 'a', sourceType: WEB_DOCUMENT_SOURCE_TYPE }),
+ buildDoc({ id: 'b', sourceType: AGENT_DOCUMENT_SOURCE_TYPE }),
buildDoc({ id: 'c', sourceType: 'file' }),
];
const result = toAgentContextDocuments(rows);
expect(result.map((d) => d.id)).toEqual(['a', 'b', 'c']);
- expect(result.map((d) => d.sourceType)).toEqual(['web', 'agent', 'file']);
+ expect(result.map((d) => d.sourceType)).toEqual([
+ WEB_DOCUMENT_SOURCE_TYPE,
+ AGENT_DOCUMENT_SOURCE_TYPE,
+ 'file',
+ ]);
});
// Regression: — folder VFS nodes (plain folders + skill bundles)
@@ -152,7 +166,7 @@ describe('toAgentContextDocuments', () => {
it('drops folder rows (plain folders and skill bundles) from context', () => {
const rows = [
buildDoc({ id: 'doc', isFolder: false }),
- buildDoc({ id: 'folder', isFolder: true, fileType: 'custom/folder' }),
+ buildDoc({ id: 'folder', isFolder: true, fileType: CUSTOM_FOLDER_FILE_TYPE }),
buildDoc({ id: 'bundle', isFolder: true, isSkillBundle: true, fileType: 'skills/bundle' }),
];
diff --git a/src/utils/__tests__/documentRenderMode.test.ts b/src/utils/__tests__/documentRenderMode.test.ts
index 73f6556e6ca..d848e86d8e0 100644
--- a/src/utils/__tests__/documentRenderMode.test.ts
+++ b/src/utils/__tests__/documentRenderMode.test.ts
@@ -1,3 +1,8 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_FILE_TYPE,
+ AGENT_DOCUMENT_SOURCE_TYPE,
+} from '@lobechat/const';
import { describe, expect, it } from 'vitest';
import { getDocumentRenderMode } from '../documentRenderMode';
@@ -21,6 +26,41 @@ describe('getDocumentRenderMode', () => {
});
});
+ it('returns editor for agent document metadata even when filename has no extension', () => {
+ expect(
+ getDocumentRenderMode({
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
+ filename: 'workflow-note',
+ sourceType: AGENT_DOCUMENT_SOURCE_TYPE,
+ title: 'workflow-note',
+ }),
+ ).toEqual({ mode: 'editor' });
+ });
+
+ it('returns editor for derived document category', () => {
+ expect(
+ getDocumentRenderMode({
+ category: AGENT_DOCUMENT_CATEGORY,
+ filename: 'draft',
+ title: 'draft',
+ }),
+ ).toEqual({ mode: 'editor' });
+ });
+
+ it('returns highlight for agent document metadata with explicit code filename', () => {
+ expect(
+ getDocumentRenderMode({
+ fileType: AGENT_DOCUMENT_FILE_TYPE,
+ filename: 'config.json',
+ sourceType: AGENT_DOCUMENT_SOURCE_TYPE,
+ title: 'config',
+ }),
+ ).toEqual({
+ language: 'json',
+ mode: 'highlight',
+ });
+ });
+
it('returns highlight with detected language for known code filenames', () => {
expect(getDocumentRenderMode({ filename: 'topic_call.txt', title: 'topic_call' })).toEqual({
language: 'txt',
diff --git a/src/utils/documentRenderMode.ts b/src/utils/documentRenderMode.ts
index 20adf78cdf8..80101817453 100644
--- a/src/utils/documentRenderMode.ts
+++ b/src/utils/documentRenderMode.ts
@@ -1,14 +1,39 @@
+import {
+ AGENT_DOCUMENT_CATEGORY,
+ AGENT_DOCUMENT_FILE_TYPE,
+ AGENT_PLAN_FILE_TYPE,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ EDITOR_DOCUMENT_SOURCE_TYPES,
+ hasFilenameExtension,
+ MARKDOWN_DOCUMENT_FILE_TYPES,
+} from '@lobechat/const';
+
import { getLanguageFromFilename } from './fileLanguage';
import { isSkillMarkdownDocument } from './skillMarkdown';
interface DocumentRenderModeFields {
+ category?: string | null;
filename?: string | null;
fileType?: string | null;
+ sourceType?: string | null;
title?: string | null;
}
export type DocumentRenderMode = { mode: 'editor' } | { language: string; mode: 'highlight' };
+const EDITOR_DOCUMENT_FILE_TYPES = new Set([
+ AGENT_DOCUMENT_FILE_TYPE,
+ AGENT_PLAN_FILE_TYPE,
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ ...MARKDOWN_DOCUMENT_FILE_TYPES,
+]);
+
+const isEditorDocument = (document: DocumentRenderModeFields): boolean => {
+ if (document.category === AGENT_DOCUMENT_CATEGORY) return true;
+ if (document.fileType && EDITOR_DOCUMENT_FILE_TYPES.has(document.fileType)) return true;
+ return !!document.sourceType && EDITOR_DOCUMENT_SOURCE_TYPES.includes(document.sourceType);
+};
+
export const getDocumentRenderMode = (document: DocumentRenderModeFields): DocumentRenderMode => {
if (isSkillMarkdownDocument(document)) return { mode: 'editor' };
@@ -17,6 +42,8 @@ export const getDocumentRenderMode = (document: DocumentRenderModeFields): Docum
const language = getLanguageFromFilename(document.filename);
if (language === 'markdown') return { mode: 'editor' };
+ if (isEditorDocument(document) && !hasFilenameExtension(document.filename))
+ return { mode: 'editor' };
return { language, mode: 'highlight' };
};