🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(agent-document): propagate sourceType and dedupe web crawls (#15088)
Arvin Xu83b8aa5a04fc
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4f92a4f3f76..de506291207 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -970,6 +970,9 @@"workingPanel.review.wordWrap.disable": "Disable word wrap","workingPanel.review.wordWrap.enable": "Enable word wrap","workingPanel.skills.empty": "No skills found in this project",+ "workingPanel.skills.emptyAgent": "No skills attached to this agent",+ "workingPanel.skills.section.agent": "Agent skills",+ "workingPanel.skills.section.project": "Project skills","workingPanel.skills.title": "Skills","workingPanel.space": "Space","workingPanel.title": "Working Panel",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 0b3861a7ff0..6bbf2421e26 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -530,6 +530,7 @@"localSystem.workingDirectory.checkoutAction": "Checkout","localSystem.workingDirectory.checkoutFailed": "Checkout failed","localSystem.workingDirectory.chooseDifferentFolder": "Choose a folder...",+ "localSystem.workingDirectory.clear": "Clear","localSystem.workingDirectory.createBranchAction": "Checkout new branch…","localSystem.workingDirectory.current": "Current working directory","localSystem.workingDirectory.detachedHead": "Detached HEAD at {{sha}}",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 8a42c119150..3d704ee377e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -970,6 +970,9 @@"workingPanel.review.wordWrap.disable": "关闭自动换行","workingPanel.review.wordWrap.enable": "启用自动换行","workingPanel.skills.empty": "当前项目未发现 Skills",+ "workingPanel.skills.emptyAgent": "该智能体未附加 Skills",+ "workingPanel.skills.section.agent": "智能体 Skills",+ "workingPanel.skills.section.project": "项目 Skills","workingPanel.skills.title": "Skills","workingPanel.space": "空间","workingPanel.title": "工作面板",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 06ce66082ea..7919e7baed1 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -530,6 +530,7 @@"localSystem.workingDirectory.checkoutAction": "切换分支","localSystem.workingDirectory.checkoutFailed": "切换分支失败","localSystem.workingDirectory.chooseDifferentFolder": "选择其他文件夹",+ "localSystem.workingDirectory.clear": "清除目录","localSystem.workingDirectory.createBranchAction": "检出新分支…","localSystem.workingDirectory.current": "当前工作目录","localSystem.workingDirectory.detachedHead": "游离 HEAD,当前提交 {{sha}}",diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.tsindex 8c979ef3fc6..5a6820140c7 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts@@ -1,3 +1,5 @@+import type { AgentDocumentPolicyLoad } from '@lobechat/types';+import type {AgentDocumentLoadRule,AgentDocumentLoadRules,@@ -5,6 +7,7 @@ import type {import { matchesLoadRules } from '../../../../database/src/models/agentDocuments';export type { AgentDocumentLoadRule, AgentDocumentLoadRules };+export type { AgentDocumentPolicyLoad };export const AGENT_DOCUMENT_INJECTION_POSITIONS = ['after-first-user',@@ -31,7 +34,7 @@ export interface AgentContextDocument {loadPosition?: AgentDocumentInjectionPosition;loadRules?: AgentDocumentLoadRules;policyId?: string | null;- policyLoad?: 'always' | 'progressive';+ policyLoad?: AgentDocumentPolicyLoad;policyLoadFormat?: AgentDocumentLoadFormat;sourceType?: AgentDocumentSourceType;title?: string;@@ -79,8 +82,9 @@ export function getDocumentsForPositions(context: AgentDocumentFilterContext,): AgentContextDocument[] {const positionSet = new Set(positions);- const docs = allDocuments.filter((doc) =>- positionSet.has(doc.loadPosition || 'before-first-user'),+ const docs = allDocuments.filter(+ (doc) =>+ doc.policyLoad !== 'disabled' && positionSet.has(doc.loadPosition || 'before-first-user'),);const filtered = filterDocumentsByRules(docs, context);return sortByPriority(filtered);@@ -222,8 +226,15 @@ export function combineDocuments(docs: AgentContextDocument[],context: AgentDocumentFilterContext,): string {- const fullDocs = docs.filter((d) => d.policyLoad !== 'progressive');- const progressiveDocs = docs.filter((d) => d.policyLoad === 'progressive');+ // Missing `policyLoad` defaults to progressive (matches the DB default and+ // `AgentDocumentModel.createWithTx`'s fallback). A doc must be explicitly+ // marked `'always'` to land in the inline bucket; everything else that+ // survived `getDocumentsForPositions` (which already drops `'disabled'`)+ // is routed through the progressive index. Doing the default here means+ // hand-rolled `AgentContextDocument` callers can't silently lose their+ // content by forgetting the field.+ const fullDocs = docs.filter((d) => d.policyLoad === 'always');+ const progressiveDocs = docs.filter((d) => (d.policyLoad ?? 'progressive') === 'progressive');const parts: string[] = [];diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.tsindex 5cd8fbc8aba..f3f9d9e8897 100644--- a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts@@ -34,6 +34,7 @@ describe('AgentDocumentInjector', () => {loadPosition: 'before-first-user',loadRules: { priority: 1, rule: 'always' },policyId: 'claw',+ policyLoad: 'always',},],});@@ -57,6 +58,7 @@ describe('AgentDocumentInjector', () => {content: 'Only show for release keyword',filename: 'todo.md',loadRules: { keywords: ['release'], rule: 'by-keywords' },+ policyLoad: 'always',},],});@@ -76,6 +78,7 @@ describe('AgentDocumentInjector', () => {filename: 'instruction.md',loadPosition: 'before-first-user',loadRules: { rule: 'always' },+ policyLoad: 'always',},],});@@ -99,6 +102,7 @@ describe('AgentDocumentInjector', () => {keywordMatchMode: 'all',rule: 'by-keywords',},+ policyLoad: 'always',},],});@@ -117,6 +121,7 @@ describe('AgentDocumentInjector', () => {content: 'Sprint TODO policy',filename: 'todo.md',loadRules: { regexp: '\\btodo\\b', rule: 'by-regexp' },+ policyLoad: 'always',},],});@@ -138,6 +143,7 @@ describe('AgentDocumentInjector', () => {rule: 'by-time-range',timeRange: { from: '2026-03-13T11:00:00.000Z', to: '2026-03-13T13:00:00.000Z' },},+ policyLoad: 'always',},],});@@ -157,6 +163,7 @@ describe('AgentDocumentInjector', () => {id: 'doc-1',loadPosition: 'before-first-user',loadRules: { rule: 'always' },+ policyLoad: 'always',policyLoadFormat: 'file',title: 'Rules',},@@ -338,6 +345,79 @@ describe('AgentDocumentInjector', () => {expect(injected).toContain('doc-p');expect(injected).not.toContain('Progressive content hidden');});++ // Regression: LOBE-9385 — `policyLoad: 'disabled'` rows were being routed+ // into the full-content bucket (the old `!== 'progressive'` filter), so+ // documents the user explicitly turned off still got inlined into the LLM+ // payload. The disabled row must show up in neither bucket.+ it('should drop disabled documents from both inline and progressive index', async () => {+ const provider = new AgentDocumentContextInjector({+ currentTime: new Date('2026-04-29T00:00:00.000Z'),+ documents: [+ {+ content: 'DISABLED skill body that must never leak',+ filename: 'SKILL.md',+ id: 'disabled-1',+ loadPosition: 'before-first-user',+ loadRules: { rule: 'always' },+ policyLoad: 'disabled',+ sourceType: 'agent',+ title: 'Disabled Skill',+ updatedAt: new Date('2026-04-27T00:00:00.000Z'),+ },+ {+ content: 'Always-loaded full content',+ filename: 'full.md',+ id: 'always-1',+ loadPosition: 'before-first-user',+ loadRules: { rule: 'always' },+ policyLoad: 'always',+ },+ ],+ });++ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);+ const result = await provider.process(context);++ const injected = result.messages[0].content;+ expect(injected).toContain('Always-loaded full content');+ expect(injected).not.toContain('DISABLED skill body that must never leak');+ expect(injected).not.toContain('disabled-1');+ expect(injected).not.toContain('Disabled Skill');+ expect(injected).not.toContain('<agent_documents_index>');+ });++ // Regression: combineDocuments switched to a strict `=== 'always'` inline+ // whitelist. `policyLoad` is optional on AgentContextDocument, and some+ // callers pass docs without it — those must default to progressive (shown+ // in the index, not silently dropped from BOTH buckets).+ it('routes documents with missing policyLoad into the progressive index', async () => {+ const provider = new AgentDocumentContextInjector({+ currentTime: new Date('2026-04-29T00:00:00.000Z'),+ documents: [+ {+ content: 'Body of a doc that forgot to set policyLoad',+ filename: 'setup.md',+ id: 'no-policy-1',+ loadPosition: 'before-first-user',+ loadRules: { rule: 'always' },+ sourceType: 'agent',+ title: 'Setup',+ updatedAt: new Date('2026-04-27T00:00:00.000Z'),+ },+ ],+ });++ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);+ const result = await provider.process(context);++ const injected = result.messages[0].content;+ // Surfaced via the index (title + id), not inlined as full content.+ expect(injected).toContain('<agent_documents_index>');+ expect(injected).toContain('Setup');+ expect(injected).toContain('no-policy-1');+ expect(injected).not.toContain('Body of a doc that forgot to set policyLoad');+ });});describe('AgentDocumentBeforeSystemInjector (before-system)', () => {@@ -349,6 +429,7 @@ describe('AgentDocumentInjector', () => {filename: 'framework.md',loadPosition: 'before-system',loadRules: { rule: 'always' },+ policyLoad: 'always',},],});@@ -375,6 +456,7 @@ describe('AgentDocumentInjector', () => {filename: 'system.md',loadPosition: 'system-append',loadRules: { rule: 'always' },+ policyLoad: 'always',},],});@@ -401,6 +483,7 @@ describe('AgentDocumentInjector', () => {filename: 'override.md',loadPosition: 'system-replace',loadRules: { rule: 'always' },+ policyLoad: 'always',},],});@@ -427,6 +510,7 @@ describe('AgentDocumentInjector', () => {filename: 'summary.md',loadPosition: 'context-end',loadRules: { rule: 'always' },+ policyLoad: 'always',},],});@@ -450,6 +534,7 @@ describe('AgentDocumentInjector', () => {filename: 'after.md',loadPosition: 'after-first-user',loadRules: { rule: 'always' },+ policyLoad: 'always',},],});diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.tsindex 8bce45a9abf..2abfeb641dd 100644--- a/packages/database/src/models/__tests__/document.test.ts+++ b/packages/database/src/models/__tests__/document.test.ts@@ -454,6 +454,68 @@ describe('DocumentModel', () => {});});+ describe('findBySource', () => {+ // Crawl dedupe (LOBE-9384) leans on this finder — same URL + sourceType+ // must always return the existing row so repeated crawls update in place+ // instead of stacking new rows.+ it('finds a document by (source, sourceType)', async () => {+ const url = 'https://example.com/pull/1';+ const { id } = await documentModel.create({+ content: 'pr body',+ fileType: 'article',+ filename: 'pr',+ source: url,+ sourceType: 'web',+ title: 'PR title',+ totalCharCount: 7,+ totalLineCount: 1,+ });++ const found = await documentModel.findBySource(url, 'web');+ expect(found?.id).toBe(id);+ });++ it('is scoped to the current user', async () => {+ const url = 'https://example.com/shared-url';+ await documentModel.create({+ content: 'mine',+ fileType: 'article',+ filename: 'mine',+ source: url,+ sourceType: 'web',+ totalCharCount: 4,+ totalLineCount: 1,+ });++ const otherUserFound = await documentModel2.findBySource(url, 'web');+ expect(otherUserFound).toBeUndefined();+ });++ it('distinguishes by sourceType so an api-source URL is not returned as a web crawl', async () => {+ const url = 'https://example.com/cross-type';+ const { id: apiId } = await documentModel.create({+ content: 'api',+ fileType: 'article',+ filename: 'api',+ source: url,+ sourceType: 'api',+ totalCharCount: 3,+ totalLineCount: 1,+ });++ const webHit = await documentModel.findBySource(url, 'web');+ expect(webHit).toBeUndefined();++ const apiHit = await documentModel.findBySource(url, 'api');+ expect(apiHit?.id).toBe(apiId);+ });++ it('returns undefined when no matching document exists', async () => {+ const found = await documentModel.findBySource('https://example.com/missing', 'web');+ expect(found).toBeUndefined();+ });+ });+describe('findByFileId', () => {it('should find document by fileId', async () => {const { documentId, file } = await createTestDocument(diff --git a/packages/database/src/models/__tests__/topicDocument.test.ts b/packages/database/src/models/__tests__/topicDocument.test.tsindex 25ed739bdea..f65ab91a3a7 100644--- a/packages/database/src/models/__tests__/topicDocument.test.ts+++ b/packages/database/src/models/__tests__/topicDocument.test.ts@@ -91,6 +91,22 @@ describe('TopicDocumentModel', () => {const docs = await topicDocumentModel.findByTopicId(topicId);expect(docs).toHaveLength(2);});++ // The PK is (documentId, topicId), so re-associating the same pair must+ // be a silent no-op — callers (e.g. re-crawl flows) rely on this to keep+ // associate calls fire-and-forget.+ it('should be idempotent — re-associating the same pair does not throw or duplicate', async () => {+ const doc = await createTestDocument(documentModel, 'Idempotent doc');++ await topicDocumentModel.associate({ documentId: doc.id, topicId });+ await expect(topicDocumentModel.associate({ documentId: doc.id, topicId })).resolves.toEqual({+ documentId: doc.id,+ topicId,+ });++ const docs = await topicDocumentModel.findByTopicId(topicId);+ expect(docs.filter((d) => d.id === doc.id)).toHaveLength(1);+ });});describe('disassociate', () => {diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex 3df4bce8416..54807e28cbe 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -157,6 +157,26 @@ export class DocumentModel {});};+ /**+ * Look up the user's existing document for a given `(source, sourceType)` pair.+ *+ * Crawl-style ingestion flows (`sourceType: 'web'`) use this to dedupe by URL+ * so repeated crawls of the same page update the existing row instead of+ * appending a fresh one — see LOBE-9384.+ */+ findBySource = async (+ source: string,+ sourceType: NonNullable<NewDocument['sourceType']>,+ ): Promise<DocumentItem | undefined> => {+ return this.db.query.documents.findFirst({+ where: and(+ eq(documents.userId, this.userId),+ eq(documents.source, source),+ eq(documents.sourceType, sourceType),+ ),+ });+ };+update = async (id: string, value: Partial<DocumentItem>) => {return this.db.update(documents)diff --git a/packages/database/src/models/topicDocument.ts b/packages/database/src/models/topicDocument.tsindex 626d9af6c6a..1e2e9fa1d30 100644--- a/packages/database/src/models/topicDocument.ts+++ b/packages/database/src/models/topicDocument.ts@@ -18,17 +18,22 @@ export class TopicDocumentModel {}/**- * Associate a document with a topic+ * Associate a document with a topic.+ *+ * Idempotent: the primary key is `(documentId, topicId)`, so re-binding the+ * same pair is a no-op via `ON CONFLICT DO NOTHING` instead of a+ * unique-violation. Callers can safely retry or call this on every save+ * without checking existence first.*/associate = async (params: Omit<NewTopicDocument, 'userId'>,): Promise<{ documentId: string; topicId: string }> => {- const [result] = await this.db+ await this.db.insert(topicDocuments).values({ ...params, userId: this.userId })- .returning();+ .onConflictDoNothing();- return { documentId: result.documentId, topicId: result.topicId };+ return { documentId: params.documentId, topicId: params.topicId };};/**diff --git a/packages/types/src/agent/document.ts b/packages/types/src/agent/document.tsnew file mode 100644index 00000000000..bb3340119f1--- /dev/null+++ b/packages/types/src/agent/document.ts@@ -0,0 +1,17 @@+/**+ * Persisted enum on `agent_documents.policy_load` (varchar(30)).+ *+ * - `always` — inject the full content on every step.+ * - `progressive` — surface in the progressive-disclosure index; the model+ * must call `readDocument(id)` to fetch full content.+ * - `disabled` — soft-off. The row is kept (still restorable / auditable)+ * but must not participate in the injection pipeline. Also written by+ * the soft-delete path.+ */+export type AgentDocumentPolicyLoad = 'always' | 'progressive' | 'disabled';++export const AGENT_DOCUMENT_POLICY_LOADS = [+ 'always',+ 'progressive',+ 'disabled',+] as const satisfies readonly AgentDocumentPolicyLoad[];diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.tsindex 1807df92ac5..741bd726a29 100644--- a/packages/types/src/agent/index.ts+++ b/packages/types/src/agent/index.ts@@ -1,5 +1,6 @@export * from './agencyConfig';export * from './agentConfig';export * from './chatConfig';+export * from './document';export * from './item';export * from './tts';diff --git a/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsx b/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsxindex e82088b7b59..4bdea25faee 100644--- a/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsx+++ b/src/features/ChatInput/RuntimeConfig/WorkingDirectory.tsx@@ -88,6 +88,22 @@ const styles = createStaticStyles(({ css }) => ({overflow-y: auto;max-height: 360px;`,+ clearText: css`+ cursor: pointer;++ padding-block: 6px 2px;+ padding-inline: 8px;++ font-size: 11px;+ font-weight: 500;+ color: ${cssVar.colorTextTertiary};++ transition: color 0.2s;++ &:hover {+ color: ${cssVar.colorText};+ }+ `,sectionTitle: css`padding-block: 6px 2px;padding-inline: 8px;@@ -196,6 +212,47 @@ const WorkingDirectoryContent = memo<WorkingDirectoryContentProps>(({ agentId, o],);+ const clearDir = useCallback(async () => {+ // Mirror selectDir's scope: clear the topic binding once a topic is active,+ // otherwise clear the agent-level default. Each falls back to the next+ // level (topic → agent → desktop home) rather than to a hard-empty value.+ const commit = async () => {+ if (activeTopicId) {+ await updateTopicMetadata(activeTopicId, { workingDirectory: undefined });+ } else {+ await updateAgentRuntimeEnvConfig(agentId, { workingDirectory: undefined });+ }+ onClose?.();+ };++ // Clearing changes the topic's cwd, which invalidates a pinned CC session+ // the same way switching folders does — warn before the implicit reset.+ const priorSessionId = activeTopic?.metadata?.heteroSessionId;+ const priorCwd = activeTopic?.metadata?.workingDirectory;+ const wouldResetSession = !!priorSessionId && !!priorCwd;++ if (wouldResetSession) {+ confirmModal({+ cancelText: t('heteroAgent.switchCwd.cancel', { ns: 'chat' }),+ content: t('heteroAgent.switchCwd.content', { ns: 'chat' }),+ okText: t('heteroAgent.switchCwd.ok', { ns: 'chat' }),+ onOk: commit,+ title: t('heteroAgent.switchCwd.title', { ns: 'chat' }),+ });+ return;+ }++ await commit();+ }, [+ activeTopicId,+ activeTopic,+ agentId,+ t,+ updateAgentRuntimeEnvConfig,+ updateTopicMetadata,+ onClose,+ ]);+const handleChooseFolder = useCallback(async () => {if (!isDesktop) return;const result = await electronSystemService.selectFolder({@@ -216,7 +273,14 @@ const WorkingDirectoryContent = memo<WorkingDirectoryContentProps>(({ agentId, oreturn (<Flexbox gap={4} style={{ minWidth: 280 }}>- <div className={styles.sectionTitle}>{t('localSystem.workingDirectory.recent')}</div>+ <Flexbox horizontal align={'center'} distribution={'space-between'}>+ <div className={styles.sectionTitle}>{t('localSystem.workingDirectory.recent')}</div>+ {effectiveDir && (+ <div className={styles.clearText} onClick={clearDir}>+ {t('localSystem.workingDirectory.clear')}+ </div>+ )}+ </Flexbox><div className={styles.scrollContainer}>{displayDirs.length === 0 ? (<Flexboxdiff --git a/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsxindex 4eec7bd49d8..3252329c840 100644--- a/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx+++ b/src/features/Conversation/Markdown/plugins/LobeAgents/Render/index.tsx@@ -17,9 +17,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({card: css`cursor: pointer;- padding-block: 10px;- padding-inline: 12px;- border-radius: 8px;+ padding-block: 14px;+ padding-inline: 14px;+ border-radius: 10px;background: ${cssVar.colorFillQuaternary};@@ -37,9 +37,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({text-overflow: ellipsis;white-space: nowrap;`,+ content: css`+ /* Allow the text column to shrink below its content width so the+ nowrap title/description ellipsize instead of overflowing the card. */+ min-width: 0;+ `,title: css`- font-size: 13px;+ overflow: hidden;++ font-size: 14px;font-weight: 500;+ text-overflow: ellipsis;+ white-space: nowrap;`,}));@@ -63,21 +72,15 @@ const Render = memo<LobeAgentsProps>(if (!identifier) return null;return (- <Flexbox- align={'center'}- className={styles.card}- gap={12}- horizontal- onClick={handleClick}- >+ <Flexbox horizontal align={'center'} className={styles.card} gap={12} onClick={handleClick}><Avataravatar={avatar || '🤖'}background={backgroundColor}shape={'square'}- size={36}+ size={40}title={title || undefined}/>- <Flexbox flex={1} gap={2}>+ <Flexbox className={styles.content} flex={1} gap={4}><span className={styles.title}>{title || identifier}</span>{description && <span className={styles.description}>{description}</span>}</Flexbox>diff --git a/src/features/Conversation/utils/markdown.test.ts b/src/features/Conversation/utils/markdown.test.tsindex 484fad015bd..4d5a2d5fafe 100644--- a/src/features/Conversation/utils/markdown.test.ts+++ b/src/features/Conversation/utils/markdown.test.ts@@ -567,4 +567,48 @@ This HTML document includes the temperature converter with the requested featureexpect(output).not.toContain('</lobeThinking>\n\n<lobeArtifact');});});++ describe('lobeAgents tag', () => {+ it('strips newlines inside a self-closing tag whose attributes span lines', () => {+ const input = `<lobeAgents+ identifier="session-abc"+ title="高密度信息图生成器"+/>`;++ const output = processWithArtifact(input);++ expect(output).toEqual('<lobeAgents identifier="session-abc" title="高密度信息图生成器"/>');+ });++ it('preserves trailing block-level Markdown after a self-closing tag', () => {+ const input = `<lobeAgents identifier="session-abc" title="高密度信息图生成器" />++---+### 这个 Agent 的核心能力:++| 维度 | 说明 |+|------|------|+| 风格 | 实验室精密手册感 |`;++ const output = processWithArtifact(input);++ expect(output).toEqual(input);+ });++ it('does not swallow trailing Markdown when the model omits the self-closing slash', () => {+ // Some models (e.g. deepseek) emit a bare opening tag without `/>`.+ // The newline stripper must still only touch the tag, not the rest.+ const input = `<lobeAgents identifier="session-abc" title="高密度信息图生成器">++---+### 这个 Agent 的核心能力:++| 维度 | 说明 |+|------|------|`;++ const output = processWithArtifact(input);++ expect(output).toEqual(input);+ });+ });});diff --git a/src/features/Conversation/utils/markdown.ts b/src/features/Conversation/utils/markdown.tsindex 0dffd8bc0f5..bd08c68613b 100644--- a/src/features/Conversation/utils/markdown.ts+++ b/src/features/Conversation/utils/markdown.ts@@ -3,7 +3,15 @@ import { ARTIFACT_THINKING_TAG_REGEX } from '@lobechat/const';const ARTIFACT_TAG_REGEX_GLOBAL =/<lobeArtifact\b[^>]*>(?<content>[\S\s]*?)(?:<\/lobeArtifact>|$)/g;-const AGENTS_TAG_REGEX_GLOBAL = /<lobeAgents\b[^>]*(?:\/>|>([\S\s]*?)(?:<\/lobeAgents>|$))/g;+// Match only the `lobeAgents` tag itself (self-closing `/>` or a bare opening+// `>`), never the content that follows it. The card is built purely from the+// tag's attributes (the rehype plugin renders it with no children), so there is+// nothing to capture inside. A previous `>([\S\s]*?)(?:<\/lobeAgents>|$)` form+// fell back to `$` when a model omitted the self-closing slash and emitted+// `<lobeAgents ...>`; with no `</lobeAgents>` to anchor on, it swallowed the+// rest of the message and stripped its newlines, collapsing all trailing+// block-level Markdown (headings, tables, `---`) into one paragraph.+const AGENTS_TAG_REGEX_GLOBAL = /<lobeAgents\b[^>]*>/g;/*** Replace all line breaks in the matched `lobeArtifact` tag with an empty string@@ -65,10 +73,9 @@ export const processWithArtifact = (input: string = '') => {output = output.replace(regex, '<lobeArtifact>');}- // Strip newlines inside lobeAgents tags (self-closing or wrapping)- output = output.replaceAll(AGENTS_TAG_REGEX_GLOBAL, (match) =>- match.replaceAll(/\r?\n|\r/g, ''),- );+ // Strip newlines inside the lobeAgents tag so attributes spread across lines+ // stay a single contiguous raw HTML node for the rehype agents plugin.+ output = output.replaceAll(AGENTS_TAG_REGEX_GLOBAL, (match) => match.replaceAll(/\r?\n|\r/g, ''));return output;};diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex f2d1a457b89..a5d6a973283 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -986,6 +986,9 @@ export default {'workingPanel.localFile.preview.render': 'Preview','workingPanel.localFile.truncated': 'File preview truncated to {{limit}} characters','workingPanel.skills.empty': 'No skills found in this project',+ 'workingPanel.skills.emptyAgent': 'No skills attached to this agent',+ 'workingPanel.skills.section.agent': 'Agent skills',+ 'workingPanel.skills.section.project': 'Project skills','workingPanel.skills.title': 'Skills','workingPanel.files.count_one': '{{count}} file','workingPanel.files.count_other': '{{count}} files',diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex c352468aedb..8087044a734 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -535,6 +535,7 @@ export default {'localSystem.workingDirectory.branchesNoMatch': 'No matching branches','localSystem.workingDirectory.branchSearchPlaceholder': 'Search branches','localSystem.workingDirectory.cancel': 'Cancel',+ 'localSystem.workingDirectory.clear': 'Clear','localSystem.workingDirectory.checkoutAction': 'Checkout','localSystem.workingDirectory.checkoutFailed': 'Checkout failed','localSystem.workingDirectory.createBranchAction': 'Checkout new branch…',diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex 7b947d4e5df..0b9872c37b0 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -232,7 +232,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metatitle={title === '...' ? <DotsLoading gap={3} size={4} /> : title}icon={(() => {if (isWaitingForHuman) {- return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorWarning }} />;+ return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorInfo }} />;}if (isLoading || isRunning) {return (diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsxindex d8912cce6f8..de3c6a205b8 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ProgressSection/index.tsx@@ -28,7 +28,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,container: css`margin-block-start: 4px;- margin-inline: 16px;+ margin-inline: 8px 12px;padding-block: 8px 10px;padding-inline: 12px;border: 1px solid ${cssVar.colorBorderSecondary};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.tsxindex b9c8b45c558..52f2751f560 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@@ -13,6 +13,13 @@ const useMatchMock = vi.hoisted(() => vi.fn());const useNavigateMock = vi.hoisted(() => vi.fn());vi.mock('@lobehub/ui', () => ({+ Accordion: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ AccordionItem: ({ children, title }: { children?: ReactNode; title?: ReactNode }) => (+ <div>+ {title}+ {children}+ </div>+ ),ActionIcon: ({ onClick, title }: { onClick?: (e: React.MouseEvent) => void; title?: string }) => (<button aria-label={title} onClick={onClick}>{title}@@ -122,8 +129,8 @@ vi.mock('@/services/agentDocument', () => ({}));vi.mock('@/store/agent', () => ({- useAgentStore: (selector: (state: { activeAgentId: string }) => unknown) =>- selector({ activeAgentId: 'agent-1' }),+ useAgentStore: (selector: (state: { activeAgentId: string; agentMap: object }) => unknown) =>+ selector({ activeAgentId: 'agent-1', agentMap: {} }),}));const openDocument = vi.fn();diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsxindex 1ca99140eb9..5213dce6194 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,4 @@-import { ActionIcon, Center, Empty, Flexbox, Text } from '@lobehub/ui';+import { Accordion, AccordionItem, ActionIcon, Center, Empty, Flexbox, Text } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';import { App } from 'antd';import { createStaticStyles, cx } from 'antd-style';@@ -17,9 +17,14 @@ import SkillsList, { type SkillListItem } from '@/features/AgentDocumentsExploreimport { useClientDataSWR } from '@/libs/swr';import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';import { useAgentStore } from '@/store/agent';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';+import ProjectLevelSkills from './ProjectLevelSkills';++const AGENT_SKILLS_ITEM_KEY = 'agent-skills';+const PAGE_ROUTE_PATTERN = '/agent/:aid/:topicId/page/:docId?';dayjs.extend(relativeTime);@@ -81,6 +86,19 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: ${cssVar.colorFillTertiary};}`,+ sectionCount: css`+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextTertiary};+ `,+ sectionEmpty: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ sectionLabel: css`+ font-size: 12px;+ font-weight: 500;+ `,title: css`font-weight: 500;`,@@ -251,15 +269,22 @@ const buildSkillBundleViews = (data: AgentDocumentListItem[]): SkillBundleView[]interface AgentDocumentsGroupProps {style?: CSSProperties;+ workingDirectory?: string;}-const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style }) => {+const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDirectory }) => {const { t } = useTranslation('chat');const agentId = useAgentStore((s) => s.activeAgentId);+ const isLocalEnabled = useAgentStore((s) =>+ agentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(s) : false,+ );const openDocument = useChatStore((s) => s.openDocument);const navigate = useNavigate();const pageMatch = useMatch(PAGE_ROUTE_PATTERN);const [filter, setFilter] = useState<ResourceFilter>('skills');+ const [agentSkillsExpanded, setAgentSkillsExpanded] = useState(true);++ const showProjectSkills = isLocalEnabled && !!workingDirectory;const {data = [],@@ -314,15 +339,12 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style }) => {);}- const renderSkills = () => {- if (skillItems.length === 0) {- return (- <Center flex={1} gap={8} paddingBlock={24}>- <Empty description={t('workingPanel.skills.empty')} icon={SkillsIcon} />- </Center>- );- }- return (+ const renderAgentSkillsList = () =>+ skillItems.length === 0 ? (+ <Center paddingBlock={8}>+ <Text className={styles.sectionEmpty}>{t('workingPanel.skills.emptyAgent')}</Text>+ </Center>+ ) : (<SkillsListitems={skillItems}onOpenFile={(item, relativePath) => {@@ -339,6 +361,54 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style }) => {}}/>);++ const renderAgentSkillsSection = () => (+ <Accordion+ expandedKeys={agentSkillsExpanded ? [AGENT_SKILLS_ITEM_KEY] : []}+ gap={4}+ onExpandedChange={(keys) => setAgentSkillsExpanded(keys.length > 0)}+ >+ <AccordionItem+ itemKey={AGENT_SKILLS_ITEM_KEY}+ paddingBlock={2}+ paddingInline={4}+ title={+ <Flexbox horizontal align={'center'} gap={6}>+ <Text className={styles.sectionLabel} type={'secondary'}>+ {t('workingPanel.skills.section.agent')}+ </Text>+ {skillItems.length > 0 && (+ <span className={styles.sectionCount}>{skillItems.length}</span>+ )}+ </Flexbox>+ }+ >+ {renderAgentSkillsList()}+ </AccordionItem>+ </Accordion>+ );++ const renderSkills = () => {+ // No project section (not local mode / no working dir): show the agent+ // skills flat, without the redundant "Agent skills" group header.+ if (!showProjectSkills) {+ if (skillItems.length === 0) {+ return (+ <Center flex={1} gap={8} paddingBlock={24}>+ <Empty description={t('workingPanel.skills.empty')} icon={SkillsIcon} />+ </Center>+ );+ }+ return renderAgentSkillsList();+ }++ // Both sections coexist — label each so the source is clear.+ return (+ <Flexbox gap={16}>+ {renderAgentSkillsSection()}+ <ProjectLevelSkills workingDirectory={workingDirectory!} />+ </Flexbox>+ );};const renderDocuments = () => (diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsxnew file mode 100644index 00000000000..f0c00d38551--- /dev/null+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx@@ -0,0 +1,125 @@+import { type ListProjectSkillsResult, type ProjectSkillItem } from '@lobechat/electron-client-ipc';+import { Accordion, AccordionItem, Center, Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import path from 'pathe';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import SkillsList, { type SkillListItem } from '@/features/AgentDocumentsExplorer/SkillsList';+import { useClientDataSWR } from '@/libs/swr';+import { localFileService } from '@/services/electron/localFileService';+import { useChatStore } from '@/store/chat';++const ITEM_KEY = 'project-skills';++const styles = createStaticStyles(({ css, cssVar }) => ({+ count: css`+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextTertiary};+ `,+ empty: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ label: css`+ font-size: 12px;+ font-weight: 500;+ `,+}));++interface ProjectLevelSkillsProps {+ workingDirectory: string;+}++const ProjectLevelSkills = memo<ProjectLevelSkillsProps>(({ workingDirectory }) => {+ const { t } = useTranslation('chat');+ const openLocalFile = useChatStore((s) => s.openLocalFile);+ const [expanded, setExpanded] = useState(true);++ const { data, isLoading } = useClientDataSWR<ListProjectSkillsResult>(+ ['project-skills', workingDirectory],+ () => localFileService.listProjectSkills({ scope: workingDirectory }),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++ // listProjectSkills approves `data.root` for preview. Hand that exact value+ // back to openLocalFile so LocalFileProtocolManager.createPreviewUrl's+ // approved-root check matches; fall back to the requested workingDirectory+ // while the SWR fetch is in flight.+ const previewRoot = data?.root || workingDirectory;++ const items = useMemo<SkillListItem[]>(+ () =>+ (data?.skills ?? []).map((skill) => ({+ description: skill.description,+ fileCount: skill.fileCount,+ files: skill.files,+ id: skill.skillDir,+ name: skill.name,+ })),+ [data?.skills],+ );++ const skillByDir = useMemo(() => {+ const map = new Map<string, ProjectSkillItem>();+ for (const skill of data?.skills ?? []) map.set(skill.skillDir, skill);+ return map;+ }, [data?.skills]);++ const count = items.length;++ return (+ <Accordion+ expandedKeys={expanded ? [ITEM_KEY] : []}+ gap={4}+ onExpandedChange={(keys) => setExpanded(keys.length > 0)}+ >+ <AccordionItem+ itemKey={ITEM_KEY}+ paddingBlock={2}+ paddingInline={4}+ title={+ <Flexbox horizontal align={'center'} gap={6}>+ <Text className={styles.label} type={'secondary'}>+ {t('workingPanel.skills.section.project')}+ </Text>+ {count > 0 && <span className={styles.count}>{count}</span>}+ </Flexbox>+ }+ >+ {isLoading ? (+ <Center paddingBlock={12}>+ <NeuralNetworkLoading size={24} />+ </Center>+ ) : count === 0 ? (+ <Center paddingBlock={8}>+ <Text className={styles.empty}>{t('workingPanel.skills.empty')}</Text>+ </Center>+ ) : (+ <SkillsList+ items={items}+ onOpenFile={(item, relativePath) => {+ const skill = skillByDir.get(item.id);+ if (!skill) return;+ openLocalFile({+ filePath: path.join(skill.skillDir, relativePath),+ workingDirectory: previewRoot,+ });+ }}+ onOpenSkill={(item) => {+ const skill = skillByDir.get(item.id);+ if (!skill) return;+ openLocalFile({ filePath: skill.path, workingDirectory: previewRoot });+ }}+ />+ )}+ </AccordionItem>+ </Accordion>+ );+});++ProjectLevelSkills.displayName = 'ProjectLevelSkills';++export default ProjectLevelSkills;diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsxindex bf6db155195..847a648d207 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx@@ -28,7 +28,12 @@ const ResourcesSection = memo(() => {style={{ minHeight: 0 }}>{isHetero && workingDirectory && <SkillsGroup workingDirectory={workingDirectory} />}- {!isHetero && <AgentDocumentsGroup style={{ flex: 1, minHeight: 0 }} />}+ {!isHetero && (+ <AgentDocumentsGroup+ style={{ flex: 1, minHeight: 0 }}+ workingDirectory={workingDirectory}+ />+ )}</Flexbox>);});diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsxindex 7c6c45458ac..cb0723e666a 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx@@ -235,7 +235,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stattitle={title === '...' ? <DotsLoading gap={3} size={4} /> : title}icon={(() => {if (isWaitingForHuman) {- return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorWarning }} />;+ return <Icon icon={Hand} size={'small'} style={{ color: cssVar.colorInfo }} />;}if (isLoading || isRunning) {return (diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex e49e0dce8d2..49c2ed393a0 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -17,7 +17,6 @@ import { CredsIdentifier, type CredSummary, generateCredsList } from '@lobechat/import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { BRANDING_PROVIDER } from '@lobechat/business-const';import {- AGENT_DOCUMENT_INJECTION_POSITIONS,type AgentContextDocument,type BotPlatformContext,buildStepSkillDelta,@@ -65,6 +64,7 @@ import {type ToolExecutionService,} from '@/server/services/toolExecution';import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';+import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';import { dispatchClientTool } from './dispatchClientTool';import { formatErrorEventData } from './formatErrorEventData';@@ -81,19 +81,6 @@ import { type IStreamEventManager } from './types';const log = debug('lobe-server:agent-runtime:streaming-executors');const timing = debug('lobe-server:agent-runtime:timing');-const VALID_DOCUMENT_POSITIONS = new Set<AgentContextDocument['loadPosition']>(- AGENT_DOCUMENT_INJECTION_POSITIONS,-);--const normalizeDocumentPosition = (- position: string | null | undefined,-): AgentContextDocument['loadPosition'] | undefined => {- if (!position) return undefined;- return VALID_DOCUMENT_POSITIONS.has(position as AgentContextDocument['loadPosition'])- ? (position as AgentContextDocument['loadPosition'])- : undefined;-};-// Tool pricing configuration (USD per call)const TOOL_PRICING: Record<string, number> = {'lobe-web-browsing/craw': 0,@@ -482,20 +469,7 @@ export const createRuntimeExecutors = (const agentDocService = new AgentDocumentsService(ctx.serverDB, ctx.userId);const docs = await agentDocService.getAgentDocuments(agentId);if (docs.length > 0) {- agentDocuments = docs.map((doc) => ({- content: doc.content,- description: doc.description ?? undefined,- filename: doc.filename,- id: doc.id,- loadPosition: normalizeDocumentPosition(- doc.policy?.context?.position || doc.policyLoadPosition,- ),- loadRules: doc.loadRules,- policyId: doc.templateId,- policyLoad: doc.policyLoad as 'always' | 'progressive',- policyLoadFormat: doc.policy?.context?.policyLoadFormat || doc.policyLoadFormat,- title: doc.title,- }));+ agentDocuments = toAgentContextDocuments(docs);log('Resolved %d agent documents for agent %s', agentDocuments.length, agentId);}} catch (error) {diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex d0c818e6a03..2f89e8e3e38 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -65,6 +65,7 @@ import { userRouter } from './user';import { userMemoriesRouter } from './userMemories';import { userMemoryRouter } from './userMemory';import { videoRouter } from './video';+import { webBrowsingRouter } from './webBrowsing';export const lambdaRouter = router({agent: agentRouter,@@ -124,6 +125,7 @@ export const lambdaRouter = router({userMemories: userMemoriesRouter,userMemory: userMemoryRouter,video: videoRouter,+ webBrowsing: webBrowsingRouter,accountDeletion: accountDeletionRouter,referral: referralRouter,spend: spendRouter,diff --git a/src/server/routers/lambda/webBrowsing.ts b/src/server/routers/lambda/webBrowsing.tsnew file mode 100644index 00000000000..d8699cd2a69--- /dev/null+++ b/src/server/routers/lambda/webBrowsing.ts@@ -0,0 +1,35 @@+import { z } from 'zod';++import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { WebBrowsingDocumentService } from '@/server/services/webBrowsing';++const webBrowsingProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ webBrowsingService: new WebBrowsingDocumentService(ctx.serverDB, ctx.userId),+ },+ });+});++export const webBrowsingRouter = router({+ /**+ * Persist a crawled page as a `documents` row, deduping by URL and+ * short-circuiting on byte-identical content. See+ * `WebBrowsingDocumentService.upsertCrawledDocument` for the dispatch.+ */+ upsertCrawledDocument: webBrowsingProcedure+ .input(+ z.object({+ content: z.string(),+ description: z.string().optional(),+ title: z.string(),+ topicId: z.string().optional(),+ url: z.string().url(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return ctx.webBrowsingService.upsertCrawledDocument(input);+ }),+});diff --git a/src/server/services/toolExecution/serverRuntimes/webBrowsing.ts b/src/server/services/toolExecution/serverRuntimes/webBrowsing.tsindex af37869cd0f..50279fb7b26 100644--- a/src/server/services/toolExecution/serverRuntimes/webBrowsing.ts+++ b/src/server/services/toolExecution/serverRuntimes/webBrowsing.ts@@ -1,9 +1,9 @@import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import { WebBrowsingExecutionRuntime } from '@lobechat/builtin-tool-web-browsing/executionRuntime';-import { DocumentModel } from '@/database/models/document';import { AgentDocumentsService } from '@/server/services/agentDocuments';import { SearchService } from '@/server/services/search';+import { WebBrowsingDocumentService } from '@/server/services/webBrowsing';import { type ServerRuntimeRegistration } from './types';@@ -19,19 +19,12 @@ export const webBrowsingRuntime: ServerRuntimeRegistration = {const service = new AgentDocumentsService(serverDB, userId);await service.associateDocument(agentId, documentId);},- createDocument: async ({ content, description, title, url }) => {- const model = new DocumentModel(serverDB, userId);- return model.create({- content,- description,- fileType: 'article',- filename: title,- source: url,- sourceType: 'web',- title,- totalCharCount: content.length,- totalLineCount: content.split('\n').length,- });+ createDocument: async (params) => {+ // Same service the client trpc procedure uses — dedupe by URL,+ // short-circuit on byte-identical content, write a history+ // snapshot when content actually changed (LOBE-9384).+ const service = new WebBrowsingDocumentService(serverDB, userId);+ return service.upsertCrawledDocument(params);},}: undefined,diff --git a/src/server/services/webBrowsing/__tests__/index.test.ts b/src/server/services/webBrowsing/__tests__/index.test.tsnew file mode 100644index 00000000000..d2e00f8d8ef--- /dev/null+++ b/src/server/services/webBrowsing/__tests__/index.test.ts@@ -0,0 +1,241 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { WebBrowsingDocumentService } from '../index';++const mocks = vi.hoisted(() => ({+ documentModel: {+ create: vi.fn(),+ findBySource: vi.fn(),+ },+ documentService: {+ updateDocument: vi.fn(),+ },+ topicDocumentModel: {+ associate: vi.fn(),+ },+}));++vi.mock('@/database/models/document', () => ({+ DocumentModel: vi.fn(() => mocks.documentModel),+}));++vi.mock('@/database/models/topicDocument', () => ({+ TopicDocumentModel: vi.fn(() => mocks.topicDocumentModel),+}));++vi.mock('@/server/services/document', () => ({+ DocumentService: vi.fn(() => mocks.documentService),+}));++vi.mock('@/server/services/agentDocuments/headlessEditor', () => ({+ createMarkdownEditorSnapshot: vi.fn(async (content: string) => ({+ content,+ editorData: { root: { fakeNodeFor: content } },+ })),+}));++describe('WebBrowsingDocumentService.upsertCrawledDocument (LOBE-9384)', () => {+ let service: WebBrowsingDocumentService;++ beforeEach(() => {+ mocks.documentModel.create.mockReset();+ mocks.documentModel.findBySource.mockReset();+ mocks.documentService.updateDocument.mockReset();+ mocks.topicDocumentModel.associate.mockReset();+ mocks.topicDocumentModel.associate.mockResolvedValue({+ documentId: 'doc',+ topicId: 'topic',+ });++ service = new WebBrowsingDocumentService({} as never, 'user-1');+ });++ it('creates a new document the first time a URL is crawled', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce(undefined);+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-1' });++ const result = await service.upsertCrawledDocument({+ content: 'body\nline2',+ description: 'a page',+ title: 'Crawled',+ url: 'https://example.com/a',+ });++ expect(mocks.documentModel.findBySource).toHaveBeenCalledWith('https://example.com/a', 'web');+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();+ expect(mocks.documentModel.create).toHaveBeenCalledWith({+ content: 'body\nline2',+ description: 'a page',+ editorData: { root: { fakeNodeFor: 'body\nline2' } },+ fileType: 'article',+ filename: 'Crawled',+ source: 'https://example.com/a',+ sourceType: 'web',+ title: 'Crawled',+ totalCharCount: 10,+ totalLineCount: 2,+ });+ expect(result).toEqual({ id: 'doc-1', status: 'created' });+ });++ // Byte-identical re-crawl must NOT write — neither `documents` nor+ // `document_histories` should churn for a no-op crawl, otherwise the+ // history list fills with empty revisions.+ it('short-circuits on byte-identical content (status: unchanged, no writes)', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce({+ content: 'same content',+ id: 'doc-existing',+ } as any);++ const result = await service.upsertCrawledDocument({+ content: 'same content',+ title: 'No change',+ url: 'https://example.com/a',+ });++ expect(mocks.documentModel.create).not.toHaveBeenCalled();+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();+ expect(result).toEqual({ id: 'doc-existing', status: 'unchanged' });+ });++ // Content changed → must route through DocumentService.updateDocument so+ // the document_histories snapshot pipeline fires.+ it('routes through DocumentService.updateDocument when content changed (status: updated)', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce({+ content: 'old body',+ id: 'doc-existing',+ } as any);+ mocks.documentService.updateDocument.mockResolvedValueOnce({+ historyAppended: true,+ id: 'doc-existing',+ });++ const result = await service.upsertCrawledDocument({+ content: 'new body',+ description: 'updated description',+ title: 'Updated title',+ url: 'https://example.com/a',+ });++ expect(mocks.documentModel.create).not.toHaveBeenCalled();+ expect(mocks.documentService.updateDocument).toHaveBeenCalledWith('doc-existing', {+ content: 'new body',+ editorData: { root: { fakeNodeFor: 'new body' } },+ saveSource: 'llm_call',+ title: 'Updated title',+ });+ expect(result).toEqual({ id: 'doc-existing', status: 'updated' });+ });++ it('treats different URLs as distinct documents', async () => {+ mocks.documentModel.findBySource.mockResolvedValue(undefined);+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-a' });+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-b' });++ const a = await service.upsertCrawledDocument({+ content: 'a',+ title: 'A',+ url: 'https://example.com/a',+ });+ const b = await service.upsertCrawledDocument({+ content: 'b',+ title: 'B',+ url: 'https://example.com/b',+ });++ expect(a).toEqual({ id: 'doc-a', status: 'created' });+ expect(b).toEqual({ id: 'doc-b', status: 'created' });+ expect(mocks.documentModel.create).toHaveBeenCalledTimes(2);+ expect(mocks.documentService.updateDocument).not.toHaveBeenCalled();+ });++ it('persists the markdown editor snapshot on first create so future diffs have a baseline', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce(undefined);+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-1' });++ await service.upsertCrawledDocument({+ content: 'hello',+ title: 'Hello',+ url: 'https://example.com/h',+ });++ expect(mocks.documentModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ editorData: { root: { fakeNodeFor: 'hello' } },+ sourceType: 'web',+ }),+ );+ });++ // Topic binding restores parity with the old `notebook.createDocument`+ // client path so crawled docs still show up under the active topic in+ // the notebook UI.+ it('binds the document to a topic when topicId is provided', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce(undefined);+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-1' });++ await service.upsertCrawledDocument({+ content: 'body',+ title: 'Crawled',+ topicId: 'topic-1',+ url: 'https://example.com/a',+ });++ expect(mocks.topicDocumentModel.associate).toHaveBeenCalledWith({+ documentId: 'doc-1',+ topicId: 'topic-1',+ });+ });++ it('skips topic binding when topicId is omitted (server agent runtime path)', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce(undefined);+ mocks.documentModel.create.mockResolvedValueOnce({ id: 'doc-1' });++ await service.upsertCrawledDocument({+ content: 'body',+ title: 'Crawled',+ url: 'https://example.com/a',+ });++ expect(mocks.topicDocumentModel.associate).not.toHaveBeenCalled();+ });++ it('binds the topic even on unchanged short-circuit so cross-topic re-crawls still appear', async () => {+ mocks.documentModel.findBySource.mockResolvedValueOnce({+ content: 'same body',+ id: 'doc-existing',+ } as any);++ const result = await service.upsertCrawledDocument({+ content: 'same body',+ title: 'Same',+ topicId: 'topic-other',+ url: 'https://example.com/a',+ });++ expect(result).toEqual({ id: 'doc-existing', status: 'unchanged' });+ expect(mocks.topicDocumentModel.associate).toHaveBeenCalledWith({+ documentId: 'doc-existing',+ topicId: 'topic-other',+ });+ });++ it('hashes existing.content treating null/undefined as empty string', async () => {+ // Defensive: legacy rows may have null content but hash compare should+ // still work (md5('') !== md5('new content')) so we fall into update.+ mocks.documentModel.findBySource.mockResolvedValueOnce({+ content: null,+ id: 'doc-legacy',+ } as any);+ mocks.documentService.updateDocument.mockResolvedValueOnce({ id: 'doc-legacy' });++ const result = await service.upsertCrawledDocument({+ content: 'fresh body',+ title: 'Title',+ url: 'https://example.com/legacy',+ });++ expect(mocks.documentService.updateDocument).toHaveBeenCalled();+ expect(result).toEqual({ id: 'doc-legacy', status: 'updated' });+ });+});diff --git a/src/server/services/webBrowsing/index.ts b/src/server/services/webBrowsing/index.tsnew file mode 100644index 00000000000..b578316b901--- /dev/null+++ b/src/server/services/webBrowsing/index.ts@@ -0,0 +1,124 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { Md5 } from 'ts-md5';++import { DocumentModel } from '@/database/models/document';+import { TopicDocumentModel } from '@/database/models/topicDocument';+import { createMarkdownEditorSnapshot } from '@/server/services/agentDocuments/headlessEditor';+import { DocumentService } from '@/server/services/document';++export interface UpsertCrawledDocumentParams {+ content: string;+ description?: string;+ title: string;+ /**+ * When provided, the resulting document is also (idempotently) linked to+ * the topic so the notebook UI can list it. Server agent runtimes leave+ * this unset — they bind to the agent instead via `associateDocument`.+ */+ topicId?: string;+ url: string;+}++export interface UpsertCrawledDocumentResult {+ id: string;+ /**+ * - `created`: this URL is new for the user; a `documents` row was inserted.+ * - `updated`: the URL existed and the content changed; the row was updated+ * and a `document_histories` snapshot was written.+ * - `unchanged`: the URL existed with byte-identical content; no write+ * happened — repeat crawls of the same unchanged page short-circuit.+ */+ status: 'created' | 'updated' | 'unchanged';+}++const hashContent = (content: string): string => Md5.hashStr(content);++/**+ * Single owner of "crawl a web page, persist it as a document" semantics.+ *+ * Both the server agent runtime (`serverRuntimes/webBrowsing.ts`) and the+ * client builtin-tool executor (`store/.../lobe-web-browsing.ts`) route+ * through `upsertCrawledDocument`, so dedupe + content-hash short-circuit ++ * `document_histories` snapshot all live in one place. Splitting these+ * across two call sites previously caused LOBE-9384 (client path created a+ * fresh row every crawl while the server path was being patched to dedupe).+ */+export class WebBrowsingDocumentService {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;+ private readonly documentModel: DocumentModel;+ private readonly topicDocumentModel: TopicDocumentModel;+ private documentServiceInstance?: DocumentService;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ this.documentModel = new DocumentModel(db, userId);+ this.topicDocumentModel = new TopicDocumentModel(db, userId);+ }++ private get documentService() {+ this.documentServiceInstance ??= new DocumentService(this.db, this.userId);+ return this.documentServiceInstance;+ }++ upsertCrawledDocument = async (+ params: UpsertCrawledDocumentParams,+ ): Promise<UpsertCrawledDocumentResult> => {+ const { content, description, title, topicId, url } = params;++ const existing = await this.documentModel.findBySource(url, 'web');++ let documentId: string;+ let status: UpsertCrawledDocumentResult['status'];++ if (existing) {+ if (hashContent(existing.content ?? '') === hashContent(content)) {+ // Byte-identical content → skip the write entirely. Both `documents`+ // and `document_histories` would only churn `updated_at`, which is+ // not worth the cost (and pollutes the history list with no-op rows).+ documentId = existing.id;+ status = 'unchanged';+ } else {+ const snapshot = await createMarkdownEditorSnapshot(content);+ // `DocumentService.updateDocument` runs inside a transaction and+ // writes a `document_histories` row when `editorData` differs from+ // the row's current snapshot, so each refresh becomes a revision.+ await this.documentService.updateDocument(existing.id, {+ content: snapshot.content,+ editorData: snapshot.editorData,+ saveSource: 'llm_call',+ title,+ });+ documentId = existing.id;+ status = 'updated';+ }+ } else {+ const snapshot = await createMarkdownEditorSnapshot(content);+ const created = await this.documentModel.create({+ content: snapshot.content,+ description,+ editorData: snapshot.editorData,+ fileType: 'article',+ filename: title,+ source: url,+ sourceType: 'web',+ title,+ totalCharCount: snapshot.content.length,+ totalLineCount: snapshot.content.split('\n').length,+ });+ documentId = created.id;+ status = 'created';+ }++ // Topic binding fires across all three statuses: the user may open the+ // same URL in a new topic on a later crawl, and the binding should+ // appear there even if the underlying document didn't change.+ // `topicDocumentModel.associate` is idempotent on (documentId, topicId).+ if (topicId) {+ await this.topicDocumentModel.associate({ documentId, topicId });+ }++ return { id: documentId, status };+ };+}diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.tsindex 212ce2bffaa..2edfff2689d 100644--- a/src/services/agentDocument.test.ts+++ b/src/services/agentDocument.test.ts@@ -2,11 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { mutate } from '@/libs/swr';-import {- agentDocumentService,- mapAgentDocumentsToContext,- resolveAgentDocumentsContext,-} from './agentDocument';+import { agentDocumentService, resolveAgentDocumentsContext } from './agentDocument';const { queryMock } = vi.hoisted(() => ({queryMock: vi.fn(),@@ -82,35 +78,6 @@ describe('AgentDocumentService', () => {expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);});- it('should map fetched documents into context format', () => {- expect(- mapAgentDocumentsToContext([- {- content: 'Target agent setup',- filename: 'setup.md',- id: 'doc-1',- loadRules: [],- policy: null,- policyLoadFormat: null,- policyLoadPosition: null,- templateId: null,- title: 'Setup',- },- ] as any),- ).toEqual([- {- content: 'Target agent setup',- filename: 'setup.md',- id: 'doc-1',- loadPosition: undefined,- loadRules: [],- policyId: null,- policyLoadFormat: undefined,- title: 'Setup',- },- ]);- });-it('should fetch target agent documents when cache is missing', async () => {queryMock.mockResolvedValueOnce([{diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex be350ae1d8d..8481e2e774c 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -1,28 +1,12 @@import type { DocumentLoadFormat, DocumentLoadRule } from '@lobechat/agent-templates';-import {- AGENT_DOCUMENT_INJECTION_POSITIONS,- type AgentContextDocument,-} from '@lobechat/context-engine';+import { type AgentContextDocument } from '@lobechat/context-engine';import { lambdaClient } from '@/libs/trpc/client';import { invalidateDocumentMutation } from '@/services/document/invalidation';+import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';export { agentDocumentSWRKeys } from '@/services/document/swrKeys';-const VALID_DOCUMENT_POSITIONS = new Set<AgentContextDocument['loadPosition']>(- AGENT_DOCUMENT_INJECTION_POSITIONS,-);--export const normalizeAgentDocumentPosition = (- position: string | null | undefined,-): AgentContextDocument['loadPosition'] | undefined => {- if (!position) return undefined;-- return VALID_DOCUMENT_POSITIONS.has(position as AgentContextDocument['loadPosition'])- ? (position as AgentContextDocument['loadPosition'])- : undefined;-};-const revalidateAgentDocuments = async (agentId: string) => {await invalidateDocumentMutation({ agentId, cause: 'agent-document' });};@@ -289,26 +273,6 @@ class AgentDocumentService {};}-export const mapAgentDocumentsToContext = (- documents: Awaited<ReturnType<AgentDocumentService['getDocuments']>>,-): AgentContextDocument[] =>- documents.map((doc) => ({- content: doc.content,- description: doc.description ?? undefined,- filename: doc.filename,- id: doc.id,- loadPosition: normalizeAgentDocumentPosition(- doc.policy?.context?.position || doc.policyLoadPosition,- ),- loadRules: doc.loadRules,- policyId: doc.templateId,- policyLoad: doc.policyLoad as 'always' | 'progressive',- policyLoadFormat: doc.policy?.context?.policyLoadFormat || doc.policyLoadFormat || undefined,- sourceType: doc.sourceType ?? undefined,- title: doc.title,- updatedAt: doc.updatedAt ?? undefined,- }));-export const resolveAgentDocumentsContext = async (params: {agentId?: string;cachedDocuments?: AgentContextDocument[];@@ -320,7 +284,7 @@ export const resolveAgentDocumentsContext = async (params: {const documents = await agentDocumentService.getDocuments({ agentId });- return mapAgentDocumentsToContext(documents);+ return toAgentContextDocuments(documents);};export const agentDocumentService = new AgentDocumentService();diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.tsindex 1d1c5b7626a..e7f41d2f588 100644--- a/src/services/chat/mecha/contextEngineering.test.ts+++ b/src/services/chat/mecha/contextEngineering.test.ts@@ -99,6 +99,9 @@ describe('contextEngineering', () => {content: 'Project setup steps',filename: 'setup.md',id: 'doc-1',+ // `always` keeps this doc in the inline bucket; without it the+ // default is progressive (metadata-only index, content hidden).+ policyLoad: 'always',title: 'Setup',},],diff --git a/src/services/webBrowsing.ts b/src/services/webBrowsing.tsnew file mode 100644index 00000000000..84ad927eced--- /dev/null+++ b/src/services/webBrowsing.ts@@ -0,0 +1,17 @@+import { lambdaClient } from '@/libs/trpc/client';++interface UpsertCrawledDocumentParams {+ content: string;+ description?: string;+ title: string;+ topicId?: string;+ url: string;+}++class WebBrowsingService {+ upsertCrawledDocument = async (params: UpsertCrawledDocumentParams) => {+ return lambdaClient.webBrowsing.upsertCrawledDocument.mutate(params);+ };+}++export const webBrowsingService = new WebBrowsingService();diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex ac7d697b960..fb7c734db67 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -29,7 +29,10 @@ vi.mock('@/services/agentDocument', () => ({agentDocumentService: {getDocuments: vi.fn(),},- mapAgentDocumentsToContext: (documents: any[]) =>+}));++vi.mock('@/utils/agentDocumentContextMapping', () => ({+ toAgentContextDocuments: (documents: any[]) =>documents.map((doc) => ({content: doc.content,filename: doc.filename,diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex 119f35b80ed..cdf51f8ee44 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -14,7 +14,6 @@ import { agentService } from '@/services/agent';import {agentDocumentService,agentDocumentSWRKeys,- mapAgentDocumentsToContext,resolveAgentDocumentsContext,} from '@/services/agentDocument';import type { StoreSetter } from '@/store/types';@@ -26,6 +25,7 @@ import type {LobeAgentConfig,RuntimeEnvConfig,} from '@/types/agent';+import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';import { merge } from '@/utils/merge';import type { AgentStore } from '../../store';@@ -318,7 +318,7 @@ export class AgentSliceActionImpl {return useClientDataSWRWithSync<AgentContextDocument[]>(agentId ? agentDocumentSWRKeys.documents(agentId) : null,async () =>- mapAgentDocumentsToContext(await agentDocumentService.getDocuments({ agentId: agentId! })),+ toAgentContextDocuments(await agentDocumentService.getDocuments({ agentId: agentId! })),{onData: (data) => {if (!agentId) return;diff --git a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts b/src/store/tool/slices/builtin/executors/lobe-web-browsing.tsindex f0847d57d28..59cc8608ec5 100644--- a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts+++ b/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts@@ -17,8 +17,8 @@ import {import { BaseExecutor, SEARCH_SEARXNG_NOT_CONFIG } from '@lobechat/types';import { agentDocumentService } from '@/services/agentDocument';-import { notebookService } from '@/services/notebook';import { searchService } from '@/services/search';+import { webBrowsingService } from '@/services/webBrowsing';const searchRuntime = new WebBrowsingExecutionRuntime({ searchService });@@ -27,18 +27,14 @@ const createDocumentService = (ctx: BuiltinToolContext): WebBrowsingDocumentServif (!ctx.agentId) return;await agentDocumentService.associateDocument({ agentId: ctx.agentId, documentId });},- createDocument: async ({ content, description, title, url }) => {- if (!ctx.topicId) throw new Error('topicId is required to save document');- return notebookService.createDocument({+ createDocument: async ({ content, description, title, url }) =>+ webBrowsingService.upsertCrawledDocument({content,description: description || `Crawled from ${url}`,- source: url,- sourceType: 'web',title,- topicId: ctx.topicId,- type: 'article',- });- },+ topicId: ctx.topicId ?? undefined,+ url,+ }),});class WebBrowsingExecutor extends BaseExecutor<typeof WebBrowsingApiName> {diff --git a/src/utils/__tests__/agentDocumentContextMapping.test.ts b/src/utils/__tests__/agentDocumentContextMapping.test.tsnew file mode 100644index 00000000000..6411558c2d4--- /dev/null+++ b/src/utils/__tests__/agentDocumentContextMapping.test.ts@@ -0,0 +1,201 @@+import { DocumentLoadFormat, DocumentLoadRule, PolicyLoad } from '@lobechat/agent-templates';+import { describe, expect, it } from 'vitest';++import type { AgentDocumentWithRules } from '@/database/models/agentDocuments';+import {+ normalizeAgentDocumentPosition,+ toAgentContextDocument,+ toAgentContextDocuments,+} from '@/utils/agentDocumentContextMapping';++const buildDoc = (overrides: Partial<AgentDocumentWithRules> = {}): AgentDocumentWithRules =>+ ({+ accessPublic: 0,+ accessSelf: 31,+ accessShared: 0,+ agentId: 'agent-1',+ category: 'document',+ content: 'body',+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ deleteReason: null,+ deletedAt: null,+ deletedByAgentId: null,+ deletedByUserId: null,+ description: 'a description',+ documentId: 'doc-row-1',+ editorData: null,+ fileType: 'article',+ filename: 'doc.md',+ id: 'agent-doc-1',+ isFolder: false,+ isSkillBundle: false,+ isSkillIndex: false,+ loadRules: {},+ metadata: null,+ parentId: null,+ policy: null,+ policyLoad: PolicyLoad.PROGRESSIVE,+ policyLoadFormat: DocumentLoadFormat.RAW,+ policyLoadPosition: 'before-first-user',+ policyLoadRule: 'always',+ source: 'https://example.com/post',+ sourceType: 'web',+ templateId: null,+ title: 'Doc title',+ updatedAt: new Date('2026-05-21T00:00:00.000Z'),+ userId: 'user-1',+ ...overrides,+ }) as AgentDocumentWithRules;++describe('toAgentContextDocument', () => {+ // Regression: LOBE-9383 — server-side mapper used to drop sourceType, which+ // disabled the "hide web-crawled docs from the progressive index" filter for+ // 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: 'file' })).sourceType).toBe('file');+ });++ it('propagates updatedAt so sortByRecency has a real timestamp', () => {+ const ts = new Date('2026-05-21T12:34:56.000Z');+ expect(toAgentContextDocument(buildDoc({ updatedAt: ts })).updatedAt).toBe(ts);+ });++ it('maps a fully populated row into the AgentContextDocument shape', () => {+ const doc = buildDoc({+ description: 'web-crawled article',+ filename: 'crawl.md',+ id: 'agent-doc-2',+ loadRules: { priority: 3, rule: DocumentLoadRule.ALWAYS },+ policyLoad: PolicyLoad.PROGRESSIVE,+ policyLoadFormat: DocumentLoadFormat.RAW,+ policyLoadPosition: 'before-first-user',+ sourceType: 'web',+ templateId: 'claw',+ title: 'Crawled',+ updatedAt: new Date('2026-05-21T00:00:00.000Z'),+ });++ expect(toAgentContextDocument(doc)).toEqual({+ content: 'body',+ description: 'web-crawled article',+ filename: 'crawl.md',+ id: 'agent-doc-2',+ loadPosition: 'before-first-user',+ loadRules: { priority: 3, rule: DocumentLoadRule.ALWAYS },+ policyId: 'claw',+ policyLoad: PolicyLoad.PROGRESSIVE,+ policyLoadFormat: DocumentLoadFormat.RAW,+ sourceType: 'web',+ title: 'Crawled',+ updatedAt: new Date('2026-05-21T00:00:00.000Z'),+ });+ });++ it('prefers policy.context overrides over the indexed projection fields', () => {+ const doc = buildDoc({+ policy: {+ context: { policyLoadFormat: 'file', position: 'system-append' },+ } as AgentDocumentWithRules['policy'],+ policyLoadFormat: DocumentLoadFormat.RAW,+ policyLoadPosition: 'before-first-user',+ });++ const mapped = toAgentContextDocument(doc);+ expect(mapped.loadPosition).toBe('system-append');+ expect(mapped.policyLoadFormat).toBe('file');+ });++ it('coerces null description / sourceType / updatedAt into undefined', () => {+ const mapped = toAgentContextDocument(+ buildDoc({+ description: null,+ sourceType: null as unknown as AgentDocumentWithRules['sourceType'],+ updatedAt: null as unknown as Date,+ }),+ );++ expect(mapped.description).toBeUndefined();+ expect(mapped.sourceType).toBeUndefined();+ expect(mapped.updatedAt).toBeUndefined();+ });++ it('drops unknown loadPosition values rather than smuggling them through', () => {+ const mapped = toAgentContextDocument(+ buildDoc({ policyLoadPosition: 'definitely-not-a-real-position' }),+ );+ expect(mapped.loadPosition).toBeUndefined();+ });+});++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: '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']);+ });++ // Regression: LOBE-9386 — folder VFS nodes (plain folders + skill bundles)+ // carry empty content but inherit loadRules/loadPosition, so they used to+ // leak into the injection candidate pool as empty slots. They must never+ // become context documents.+ 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: 'bundle', isFolder: true, isSkillBundle: true, fileType: 'skills/bundle' }),+ ];++ const result = toAgentContextDocuments(rows);++ expect(result.map((d) => d.id)).toEqual(['doc']);+ });++ it('keeps non-folder skill rows such as the SKILL.md index', () => {+ const rows = [+ buildDoc({+ id: 'skill-index',+ isFolder: false,+ isSkillIndex: true,+ fileType: 'skills/index',+ }),+ ];++ const result = toAgentContextDocuments(rows);++ expect(result.map((d) => d.id)).toEqual(['skill-index']);+ });+});++describe('normalizeAgentDocumentPosition', () => {+ it('accepts every position in AGENT_DOCUMENT_INJECTION_POSITIONS', () => {+ for (const position of [+ 'after-first-user',+ 'before-first-user',+ 'before-system',+ 'context-end',+ 'manual',+ 'on-demand',+ 'system-append',+ 'system-replace',+ ] as const) {+ expect(normalizeAgentDocumentPosition(position)).toBe(position);+ }+ });++ it('returns undefined for nullish or unknown positions', () => {+ expect(normalizeAgentDocumentPosition(null)).toBeUndefined();+ expect(normalizeAgentDocumentPosition(undefined)).toBeUndefined();+ expect(normalizeAgentDocumentPosition('')).toBeUndefined();+ expect(normalizeAgentDocumentPosition('not-a-position')).toBeUndefined();+ });+});diff --git a/src/utils/agentDocumentContextMapping.ts b/src/utils/agentDocumentContextMapping.tsnew file mode 100644index 00000000000..7de1c15e8a0--- /dev/null+++ b/src/utils/agentDocumentContextMapping.ts@@ -0,0 +1,64 @@+import {+ AGENT_DOCUMENT_INJECTION_POSITIONS,+ type AgentContextDocument,+ type AgentDocumentInjectionPosition,+} from '@lobechat/context-engine';++import type { AgentDocumentWithRules } from '@/database/models/agentDocuments';++const VALID_DOCUMENT_POSITIONS = new Set<AgentDocumentInjectionPosition>(+ AGENT_DOCUMENT_INJECTION_POSITIONS,+);++export const normalizeAgentDocumentPosition = (+ position: string | null | undefined,+): AgentDocumentInjectionPosition | undefined => {+ if (!position) return undefined;++ return VALID_DOCUMENT_POSITIONS.has(position as AgentDocumentInjectionPosition)+ ? (position as AgentDocumentInjectionPosition)+ : undefined;+};++/**+ * Map a database `AgentDocumentWithRules` row into the `AgentContextDocument`+ * shape consumed by the context-engine providers.+ *+ * Lives in the app layer (not in `@lobechat/database` nor `@lobechat/context-engine`)+ * because it bridges two independent packages — adding a field here propagates+ * to every caller (client SWR fetch, server agent runtime) at once. Two+ * hand-rolled copies of this map previously diverged when `sourceType` was+ * added on the client only, which broke the "hide web crawls from the+ * progressive index" filter on every server-driven chat (LOBE-9383).+ */+export const toAgentContextDocument = (doc: AgentDocumentWithRules): AgentContextDocument => ({+ content: doc.content,+ description: doc.description ?? undefined,+ filename: doc.filename,+ id: doc.id,+ loadPosition: normalizeAgentDocumentPosition(+ doc.policy?.context?.position || doc.policyLoadPosition,+ ),+ loadRules: doc.loadRules,+ policyId: doc.templateId,+ policyLoad: doc.policyLoad,+ policyLoadFormat: doc.policy?.context?.policyLoadFormat || doc.policyLoadFormat || undefined,+ sourceType: doc.sourceType ?? undefined,+ title: doc.title,+ updatedAt: doc.updatedAt ?? undefined,+});++/**+ * Map a list of agent document rows into context-engine documents, dropping+ * folder-like rows (plain folders and skill bundles).+ *+ * Folders are structural VFS nodes with no readable body — they carry an+ * empty `content` but inherit `loadRules`/`loadPosition`, so without this+ * filter they slip into the injection candidate pool and either bloat the+ * progressive index with empty "slots" or emit empty `<agent_document>`+ * blocks (LOBE-9386). `AgentContextDocument` deliberately has no `fileType`+ * field, so the folder check has to happen here, at the DB→context boundary,+ * where the derived `isFolder` flag is still available.+ */+export const toAgentContextDocuments = (docs: AgentDocumentWithRules[]): AgentContextDocument[] =>+ docs.filter((doc) => !doc.isFolder).map((doc) => toAgentContextDocument(doc));