🤯 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
✨ feat(chat-input): drag agent documents into the chat input (#22104)
Arvin Xuf1976f10776e
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex 794e6f1e1f0..f1a73ce6330 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -231,6 +231,9 @@ export const buildServerCallLlmContext = async ({}),enableAgentMode,...(facts.step.topicReferences && { topicReferences: facts.step.topicReferences }),+ ...(facts.step.documentReferences && {+ documentReferences: facts.step.documentReferences,+ }),...(facts.step.onboardingContext && { onboardingContext: facts.step.onboardingContext }),};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex 9c1a8875c65..e8ec972d230 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -24,6 +24,7 @@ export const toContextSnapshot = ({capabilities,connectorOwnershipNote,discordContext,+ documentReferences,enableAgentMode,enableExpertise,enableHistoryCount,@@ -93,6 +94,7 @@ export const toContextSnapshot = ({step: {agentBuilderContext,agentManagementContext,+ documentReferences,groupAgentBuilderContext,onboardingContext,planTodo,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex e6b20f870a7..a64a03d26c5 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -77,6 +77,17 @@ export const createServerContextFactProviders = ({: ordinaryDocumentAccessScope;return {+ findAgentDocument: async (agentId, documentId) => {+ const doc = await new AgentDocumentsService(+ db,+ userId,+ workspaceId,+ undefined,+ documentAccessScope,+ ).getDocumentById(documentId, agentId);+ return doc ? { content: doc.content, title: doc.title } : null;+ },+findTopic: async (topicId) => {const topic = await new TopicModel(db, userId, ctx.workspaceId).findById(topicId);if (!topic) return null;diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.tsindex 8ab419df056..f2a0da9ac37 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts@@ -6,6 +6,7 @@ import type {AgentManagementContext,BotPlatformContext,DiscordContext,+ DocumentReferenceItem,EvalContext,FileContent,GroupAgentBuilderContext,@@ -194,6 +195,9 @@ export interface ServerMessagesEngineParams {// ========== Topic References ==========/** Topic reference summaries to inject into last user message */topicReferences?: TopicReferenceItem[];+ // ========== Document References ==========+ /** Agent documents referenced via `<refer_document>`, injected into last user message */+ documentReferences?: DocumentReferenceItem[];// ========== User memory ==========/** User memory configuration */userMemory?: ServerUserMemoryConfig;diff --git a/packages/const/src/agentDocumentDrag.ts b/packages/const/src/agentDocumentDrag.tsnew file mode 100644index 00000000000..c91ec158e65--- /dev/null+++ b/packages/const/src/agentDocumentDrag.ts@@ -0,0 +1,6 @@+/**+ * DataTransfer MIME type used when dragging an agent document row from the+ * working sidebar into the chat input. A custom type avoids Lexical treating+ * the payload as dropped plain text.+ */+export const AGENT_DOCUMENT_DRAG_MIME = 'application/x-lobe-agent-document';diff --git a/packages/const/src/index.ts b/packages/const/src/index.tsindex 54320f01513..b0be93d57e8 100644--- a/packages/const/src/index.ts+++ b/packages/const/src/index.ts@@ -1,5 +1,6 @@export * from './acceptanceReview';export * from './agentDocument';+export * from './agentDocumentDrag';export * from './agentName';export * from './agentShare';export * from './apiKeyScope';diff --git a/packages/context-engine/src/engine/documentReference/__tests__/resolveDocumentReferences.test.ts b/packages/context-engine/src/engine/documentReference/__tests__/resolveDocumentReferences.test.tsnew file mode 100644index 00000000000..566e0127565--- /dev/null+++ b/packages/context-engine/src/engine/documentReference/__tests__/resolveDocumentReferences.test.ts@@ -0,0 +1,182 @@+import { describe, expect, it, vi } from 'vitest';++import {+ MAX_DOCUMENT_REFERENCE_CHARS,+ MAX_DOCUMENT_REFERENCES,+ parseReferDocumentTags,+ resolveDocumentReferences,+} from '../resolveDocumentReferences';++describe('parseReferDocumentTags', () => {+ it('parses tags across messages and dedupes by id', () => {+ const refs = parseReferDocumentTags([+ { content: 'See <refer_document name="Voice" id="doc-1" /> and' },+ { content: 'again <refer_document name="Voice" id="doc-1" />' },+ { content: '<refer_document id="doc-2" name="Spec" />' },+ { content: [{ type: 'text', text: '<refer_document id="ignored" />' }] },+ ]);++ expect(refs).toEqual([+ { documentId: 'doc-1', latest: false, title: 'Voice' },+ { documentId: 'doc-2', latest: false, title: 'Spec' },+ ]);+ });++ it('orders references by their most recent use', () => {+ const refs = parseReferDocumentTags([+ { content: '<refer_document name="A" id="doc-a" />', role: 'user' },+ { content: '<refer_document name="B" id="doc-b" />', role: 'user' },+ { content: '<refer_document id="doc-a" />', role: 'user' },+ ]);++ expect(refs).toEqual([+ { documentId: 'doc-b', latest: false, title: 'B' },+ { documentId: 'doc-a', latest: true, title: 'A' },+ ]);+ });++ it('reads tags whose markup was markdown-escaped', () => {+ expect(+ parseReferDocumentTags([{ content: '\\<refer\\_document name="Voice" id="doc-1" />' }]),+ ).toEqual([{ documentId: 'doc-1', latest: true, title: 'Voice' }]);+ });++ it('ignores refer_topic tags', () => {+ expect(parseReferDocumentTags([{ content: '<refer_topic name="T" id="tpc_1" />' }])).toEqual(+ [],+ );+ });+});++describe('resolveDocumentReferences', () => {+ it('returns undefined without tags', async () => {+ const lookup = vi.fn();+ expect(await resolveDocumentReferences([{ content: 'plain' }], lookup)).toBeUndefined();+ expect(lookup).not.toHaveBeenCalled();+ });++ it('resolves content and prefers the stored title', async () => {+ const refs = await resolveDocumentReferences(+ [{ content: '<refer_document name="Old" id="doc-1" />' }],+ async () => ({ content: 'Body', title: 'Current' }),+ );++ expect(refs).toEqual([{ content: 'Body', documentId: 'doc-1', title: 'Current' }]);+ });++ it('truncates long content to the budget', async () => {+ const refs = await resolveDocumentReferences(+ [{ content: '<refer_document name="Long" id="doc-1" />' }],+ async () => ({ content: 'x'.repeat(MAX_DOCUMENT_REFERENCE_CHARS + 10) }),+ );++ expect(refs?.[0].content).toHaveLength(MAX_DOCUMENT_REFERENCE_CHARS);+ expect(refs?.[0].truncated).toBe(true);+ expect(refs?.[0].title).toBe('Long');+ });++ it('keeps a reference without content when the lookup misses or throws', async () => {+ const refs = await resolveDocumentReferences(+ [+ {+ content:+ '<refer_document name="Missing" id="doc-1" /><refer_document name="Broken" id="doc-2" />',+ },+ ],+ async (id) => {+ if (id === 'doc-2') throw new Error('boom');+ return null;+ },+ );++ expect(refs).toEqual([+ { documentId: 'doc-1', title: 'Missing' },+ { documentId: 'doc-2', title: 'Broken' },+ ]);+ });++ it('inlines only documents the latest user message references', async () => {+ const lookup = vi.fn(async () => ({ content: 'Body' }));++ const refs = await resolveDocumentReferences(+ [+ { content: '<refer_document name="Old" id="doc-old" />', role: 'user' },+ { content: 'Done.', role: 'assistant' },+ { content: '<refer_document name="New" id="doc-new" />', role: 'user' },+ { content: 'Reading.', role: 'assistant' },+ ],+ lookup,+ );++ expect(refs).toEqual([+ { documentId: 'doc-old', earlierTurn: true, title: 'Old' },+ { content: 'Body', documentId: 'doc-new', title: 'New' },+ ]);+ expect(lookup).toHaveBeenCalledTimes(1);+ expect(lookup).toHaveBeenCalledWith('doc-new');+ });++ it('inlines a document referenced again after older ones exceed the cap', async () => {+ const count = MAX_DOCUMENT_REFERENCES + 1;+ const messages = [+ ...Array.from({ length: count }, (_, i) => ({+ content: `<refer_document name="D${i}" id="doc-${i}" />`,+ role: 'user',+ })),+ { content: '<refer_document name="D0" id="doc-0" />', role: 'user' },+ ];+ const lookup = vi.fn(async () => ({ content: 'c' }));++ const refs = await resolveDocumentReferences(messages, lookup);++ expect(refs?.filter((ref) => ref.earlierTurn)).toHaveLength(MAX_DOCUMENT_REFERENCES);+ expect(refs?.at(-1)).toMatchObject({ content: 'c', documentId: 'doc-0' });+ expect(lookup).toHaveBeenCalledTimes(1);+ });++ it('keeps the latest user turn during a multi-step tool loop and ignores echoed tags', async () => {+ const lookup = vi.fn(async () => ({ content: 'Body' }));++ const refs = await resolveDocumentReferences(+ [+ { content: '<refer_document name="New" id="doc-new" />', role: 'user' },+ { content: 'Echo <refer_document name="New" id="doc-new" />', role: 'assistant' },+ { content: '<refer_document name="Other" id="doc-other" />', role: 'tool' },+ ],+ lookup,+ );++ expect(refs).toEqual([{ content: 'Body', documentId: 'doc-new', title: 'New' }]);+ expect(lookup).toHaveBeenCalledTimes(1);+ });++ it('inlines earlier-turn documents when asked to', async () => {+ const lookup = vi.fn(async (id: string) => ({ content: `Body ${id}` }));++ const refs = await resolveDocumentReferences(+ [+ { content: '<refer_document name="Old" id="doc-old" />', role: 'user' },+ { content: 'Follow-up', role: 'user' },+ ],+ lookup,+ { inlineEarlierTurns: true },+ );++ expect(refs).toEqual([{ content: 'Body doc-old', documentId: 'doc-old', title: 'Old' }]);+ });++ it('caps the number of inlined documents to the most recent ones', async () => {+ const count = MAX_DOCUMENT_REFERENCES + 2;+ const content = Array.from(+ { length: count },+ (_, i) => `<refer_document name="D${i}" id="doc-${i}" />`,+ ).join(' ');+ const lookup = vi.fn(async () => ({ content: 'c' }));++ const refs = await resolveDocumentReferences([{ content, role: 'user' }], lookup);++ expect(refs).toHaveLength(MAX_DOCUMENT_REFERENCES);+ expect(refs?.[0].documentId).toBe('doc-2');+ expect(lookup).toHaveBeenCalledTimes(MAX_DOCUMENT_REFERENCES);+ });+});diff --git a/packages/context-engine/src/engine/documentReference/index.ts b/packages/context-engine/src/engine/documentReference/index.tsnew file mode 100644index 00000000000..2e2f3743af7--- /dev/null+++ b/packages/context-engine/src/engine/documentReference/index.ts@@ -0,0 +1,7 @@+export type { DocumentLookupResult, ParsedDocumentReference } from './resolveDocumentReferences';+export {+ MAX_DOCUMENT_REFERENCE_CHARS,+ MAX_DOCUMENT_REFERENCES,+ parseReferDocumentTags,+ resolveDocumentReferences,+} from './resolveDocumentReferences';diff --git a/packages/context-engine/src/engine/documentReference/resolveDocumentReferences.ts b/packages/context-engine/src/engine/documentReference/resolveDocumentReferences.tsnew file mode 100644index 00000000000..8e19682e545--- /dev/null+++ b/packages/context-engine/src/engine/documentReference/resolveDocumentReferences.ts@@ -0,0 +1,122 @@+import type { DocumentReferenceItem } from '../../providers/DocumentReferenceContextInjector';++/** Parsed `<refer_document>` tag info */+export interface ParsedDocumentReference {+ documentId: string;+ /** Whether the latest user message carries this tag. */+ latest: boolean;+ title?: string;+}++/** Document lookup result (common interface for client and server sources) */+export interface DocumentLookupResult {+ content?: string | null;+ title?: string | null;+}++/** Character budget per referenced document. */+export const MAX_DOCUMENT_REFERENCE_CHARS = 20_000;+/** Most documents listed for a single request, counted separately for latest and earlier turns. */+export const MAX_DOCUMENT_REFERENCES = 5;++type ReferenceMessage = { content: string | unknown; role?: string };++const findLatestUserIndex = (messages: ReferenceMessage[]) => {+ for (let i = messages.length - 1; i >= 0; i--) {+ if (messages[i].role === 'user') return i;+ }+ return messages.length - 1;+};++/**+ * Parse `<refer_document>` tags from message contents, ordered by last use. The+ * injection is rebuilt on every request, so tags from earlier turns are kept:+ * dropping them would hide that the document was referenced at all.+ */+export function parseReferDocumentTags(messages: ReferenceMessage[]): ParsedDocumentReference[] {+ const refs = new Map<string, ParsedDocumentReference>();+ const latestUserIndex = findLatestUserIndex(messages);++ const hasRoles = messages.some((msg) => msg.role !== undefined);++ messages.forEach((msg, index) => {+ // Only the user writes these tags; an assistant or tool echo must not add+ // or re-order references.+ if (hasRoles && msg.role !== 'user') return;+ // Strip markdown escape backslashes (e.g. \< → <, \_ → _) before parsing+ const raw = typeof msg.content === 'string' ? msg.content : '';+ const content = raw.replaceAll(/\\([<>_*[\]()#`~|])/g, '$1');+ const tagRegex = /<refer_document\s([^>]*)>/g;+ let tagMatch;+ while ((tagMatch = tagRegex.exec(content)) !== null) {+ const attrs = tagMatch[1];+ const idMatch = /\bid="([^"]+)"/.exec(attrs);+ if (!idMatch) continue;+ const documentId = idMatch[1];+ const nameMatch = /\bname="([^"]*)"/.exec(attrs);+ const previous = refs.get(documentId);+ // Re-insert so Map order follows the most recent use.+ refs.delete(documentId);+ refs.set(documentId, {+ documentId,+ latest: index === latestUserIndex,+ title: nameMatch?.[1] || previous?.title,+ });+ }+ });++ return [...refs.values()];+}++/**+ * Resolve document references through the provided lookup. Only documents the+ * latest user message references are read and inlined; earlier ones are listed+ * by id so the agent can read them on demand, which keeps a long topic from+ * re-sending every document on every turn. `inlineEarlierTurns` inlines them+ * too, for agents that cannot read documents on demand. A lookup that returns nothing+ * (missing, or not readable by this run) leaves the reference without content.+ */+export async function resolveDocumentReferences(+ messages: ReferenceMessage[],+ lookupDocument: (documentId: string) => Promise<DocumentLookupResult | null | undefined>,+ { inlineEarlierTurns = false }: { inlineEarlierTurns?: boolean } = {},+): Promise<DocumentReferenceItem[] | undefined> {+ const parsed = parseReferDocumentTags(messages);+ if (parsed.length === 0) return undefined;++ const isInlined = (ref: ParsedDocumentReference) => ref.latest || inlineEarlierTurns;+ // Keep the most recent references when a conversation exceeds the cap.+ const earlier = parsed.filter((ref) => !isInlined(ref)).slice(-MAX_DOCUMENT_REFERENCES);+ const latest = parsed.filter(isInlined).slice(-MAX_DOCUMENT_REFERENCES);++ const refs: DocumentReferenceItem[] = earlier.map(({ documentId, title }) => ({+ documentId,+ earlierTurn: true,+ title,+ }));++ for (const { documentId, title } of latest) {+ try {+ const doc = await lookupDocument(documentId);+ const resolvedTitle = doc?.title || title;+ const content = typeof doc?.content === 'string' ? doc.content : undefined;++ if (content === undefined) {+ refs.push({ documentId, title: resolvedTitle });+ continue;+ }++ const truncated = content.length > MAX_DOCUMENT_REFERENCE_CHARS;+ refs.push({+ content: truncated ? content.slice(0, MAX_DOCUMENT_REFERENCE_CHARS) : content,+ documentId,+ title: resolvedTitle,+ ...(truncated && { truncated }),+ });+ } catch {+ refs.push({ documentId, title });+ }+ }++ return refs;+}diff --git a/packages/context-engine/src/engine/index.ts b/packages/context-engine/src/engine/index.tsindex f0f50a7889f..92f4a32076b 100644--- a/packages/context-engine/src/engine/index.ts+++ b/packages/context-engine/src/engine/index.ts@@ -4,5 +4,7 @@ export * from './skills';export * from './tools';// Messages Engineexport * from './messages';+// Document Reference+export * from './documentReference';// Topic Referenceexport * from './topicReference';diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex 093feeaafa6..7f0333fcb75 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -45,6 +45,7 @@ import {ConnectorOwnershipInjector,ContextSelectionsInjector,DiscordContextProvider,+ DocumentReferenceContextInjector,EvalContextSystemInjector,ExpertiseContextInjector,ForceFinishSummaryInjector,@@ -87,6 +88,7 @@ const log = debug('context-engine:MessagesEngine');/** `AttachmentsIdentifier` from `@lobechat/builtin-tool-attachments`, inlined to avoid a package cycle */const ATTACHMENTS_TOOL_ID = 'lobe-attachments';+const AGENT_DOCUMENTS_TOOL_ID = 'lobe-agent-documents';/*** MessagesEngine - High-level message processing engine@@ -200,6 +202,7 @@ export class MessagesEngine {initialContext,stepContext,topicReferences,+ documentReferences,enableSystemDate,timezone,} = this.params;@@ -253,6 +256,9 @@ export class MessagesEngine {// Oversized file previews may only promise `readAttachment` when the model is actually sent that// tool; custom / exclusive tool modes, share visitors and clients without it get a plain preview.const canReadAttachment = toolIds.includes(ATTACHMENTS_TOOL_ID) && !!canUseFC(model, provider);+ // Same gate for referenced agent documents: only point at `readDocument` when it is sent.+ const canReadDocuments =+ toolIds.includes(AGENT_DOCUMENTS_TOOL_ID) && !!canUseFC(model, provider);const injectedActivatedSkills =isAgentMode && (skillsConfig?.enabledSkills?.length ?? 0) > 0? selectActivatedSkills(skillsConfig?.enabledSkills)@@ -469,6 +475,12 @@ export class MessagesEngine {enabled: !!(topicReferences && topicReferences.length > 0),topicReferences,}),+ // Document Reference context (dragged/referenced agent documents to last user message)+ new DocumentReferenceContextInjector({+ canReadDocuments,+ documentReferences,+ enabled: !!(documentReferences && documentReferences.length > 0),+ }),// =============================================// Phase 4.5: Virtual Tail Guidancediff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.tsindex b25e48ef367..982558b44eb 100644--- a/packages/context-engine/src/engine/messages/types.ts+++ b/packages/context-engine/src/engine/messages/types.ts@@ -17,6 +17,7 @@ import type { AgentContextDocument } from '../../providers/AgentDocumentInjectorimport type { AgentManagementContext } from '../../providers/AgentManagementContextInjector';import type { BotPlatformContext } from '../../providers/BotPlatformContextInjector';import type { DiscordContext } from '../../providers/DiscordContextProvider';+import type { DocumentReferenceItem } from '../../providers/DocumentReferenceContextInjector';import type { EvalContext } from '../../providers/EvalContextSystemInjector';import type { GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';import type { GroupMemberInfo } from '../../providers/GroupContextInjector';@@ -350,6 +351,10 @@ export interface MessagesEngineParams {/** Topic reference summaries to inject into last user message */topicReferences?: TopicReferenceItem[];+ // ========== Document References ==========+ /** Agent documents referenced via `<refer_document>`, injected into last user message */+ documentReferences?: DocumentReferenceItem[];+// ========== Page Editor context ==========/*** Initial context captured at operation start (frontend runtime usage)@@ -389,6 +394,7 @@ export { type AgentBuilderContext } from '../../providers/AgentBuilderContextInjexport { type AgentManagementContext } from '../../providers/AgentManagementContextInjector';export { type BotPlatformContext } from '../../providers/BotPlatformContextInjector';export { type DiscordContext } from '../../providers/DiscordContextProvider';+export { type DocumentReferenceItem } from '../../providers/DocumentReferenceContextInjector';export { type EvalContext } from '../../providers/EvalContextSystemInjector';export { type GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';export { type Plan } from '../../providers/PlanInjector';diff --git a/packages/context-engine/src/providers/DocumentReferenceContextInjector.ts b/packages/context-engine/src/providers/DocumentReferenceContextInjector.tsnew file mode 100644index 00000000000..de828f77411--- /dev/null+++ b/packages/context-engine/src/providers/DocumentReferenceContextInjector.ts@@ -0,0 +1,130 @@+import debug from 'debug';++import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';+import type { PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ documentReferenceCount?: number;+ documentReferenceInjected?: boolean;+ }+}++const log = debug('context-engine:provider:DocumentReferenceContextInjector');++/** An agent document the user referenced with a `<refer_document>` tag. */+export interface DocumentReferenceItem {+ /** Document content, cut to the injection budget; absent when it could not be read. */+ content?: string;+ /** Agent-document id carried by the tag (`agent_documents.id`). */+ documentId: string;+ /** Referenced in an earlier turn only, so listed without content. */+ earlierTurn?: boolean;+ /** Document title */+ title?: string;+ /** Whether `content` was cut short of the full document */+ truncated?: boolean;+}++export interface DocumentReferenceContextInjectorConfig {+ /**+ * Whether this request is sent the lobe-agent-documents tool. Without it the hint+ * must not promise a `readDocument` call the model cannot make.+ */+ canReadDocuments?: boolean;+ documentReferences?: DocumentReferenceItem[];+ enabled?: boolean;+}++const escapeAttr = (value: string) =>+ value.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<');++const READABLE_HINT =+ 'The user referenced the following agent documents. Use their content as context. When a document is marked truncated, earlier_turn or unavailable, read it in full with the lobe-agent-documents readDocument tool using its id.';+const UNREADABLE_HINT =+ 'The user referenced the following agent documents. Use their content as context. A document marked truncated only includes its beginning, and one marked earlier_turn or unavailable has no content here; you cannot read more of them in this conversation, so tell the user when the answer depends on the missing part.';++const formatDocumentReferences = (+ items: DocumentReferenceItem[],+ canReadDocuments: boolean,+): string | null => {+ if (items.length === 0) return null;++ const lines: string[] = [+ `<referred_documents hint="${canReadDocuments ? READABLE_HINT : UNREADABLE_HINT}">`,+ ];++ for (const item of items) {+ const attrs = [+ `id="${escapeAttr(item.documentId)}"`,+ item.title ? `title="${escapeAttr(item.title)}"` : undefined,+ item.truncated ? 'truncated="true"' : undefined,+ ]+ .filter(Boolean)+ .join(' ');++ if (item.earlierTurn) {+ lines.push(`<document ${attrs} status="earlier_turn" />`);+ continue;+ }++ if (item.content === undefined) {+ lines.push(`<document ${attrs} status="unavailable" />`);+ continue;+ }++ lines.push(`<document ${attrs}>`, item.content, '</document>');+ }++ lines.push('</referred_documents>');++ return lines.join('\n');+};++/**+ * Document Reference Context Injector+ *+ * When user messages contain `<refer_document>` tags, appends the referenced+ * agent documents' content to the last user message.+ */+export class DocumentReferenceContextInjector extends BaseLastUserContentProvider {+ readonly name = 'DocumentReferenceContextInjector';++ constructor(+ private config: DocumentReferenceContextInjectorConfig,+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ const clonedContext = this.cloneContext(context);+ const references = this.config.documentReferences;++ if (!this.config.enabled || !references || references.length === 0) {+ log('Document reference not enabled or no references, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ const formattedContent = formatDocumentReferences(references, !!this.config.canReadDocuments);+ if (!formattedContent) return this.markAsExecuted(clonedContext);++ const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);+ if (lastUserIndex === -1) {+ log('No user messages found, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ const hasExistingWrapper = this.hasExistingSystemContext(clonedContext);+ const contentToAppend = hasExistingWrapper+ ? this.createContextBlock(formattedContent, 'document_reference_context')+ : this.wrapWithSystemContext(formattedContent, 'document_reference_context');++ this.appendToLastUserMessage(clonedContext, contentToAppend);++ clonedContext.metadata.documentReferenceInjected = true;+ clonedContext.metadata.documentReferenceCount = references.length;++ return this.markAsExecuted(clonedContext);+ }+}diff --git a/packages/context-engine/src/providers/__tests__/DocumentReferenceContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/DocumentReferenceContextInjector.test.tsnew file mode 100644index 00000000000..9bf1e361614--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/DocumentReferenceContextInjector.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { DocumentReferenceContextInjector } from '../DocumentReferenceContextInjector';++const createContext = (messages: any[] = []): PipelineContext => ({+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ },+ isAborted: false,+ messages,+ metadata: {+ maxTokens: 4096,+ model: 'gpt-4',+ },+});++describe('DocumentReferenceContextInjector', () => {+ it('skips when disabled or without references', async () => {+ for (const config of [{ enabled: false }, { documentReferences: [], enabled: true }]) {+ const injector = new DocumentReferenceContextInjector(config);+ const result = await injector.process(+ createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]),+ );++ expect(result.messages[0].content).toBe('Hello');+ expect(result.metadata.documentReferenceInjected).toBeUndefined();+ }+ });++ it('appends referenced document content to the last user message', async () => {+ const injector = new DocumentReferenceContextInjector({+ documentReferences: [+ { content: '# Voice\nShort sentences.', documentId: 'doc-1', title: 'Voice "Guide"' },+ ],+ enabled: true,+ });+ const result = await injector.process(+ createContext([+ { content: 'First', id: 'user-1', role: 'user' },+ { content: 'Reply', id: 'assistant-1', role: 'assistant' },+ { content: 'Use <refer_document name="Voice" id="doc-1" />', id: 'user-2', role: 'user' },+ ]),+ );++ expect(result.messages[0].content).toBe('First');+ const last = result.messages[2].content as string;+ expect(last).toContain('<referred_documents');+ expect(last).toContain('<document id="doc-1" title="Voice "Guide"">');+ expect(last).toContain('# Voice\nShort sentences.');+ expect(last).toContain('document_reference_context');+ expect(result.metadata.documentReferenceInjected).toBe(true);+ expect(result.metadata.documentReferenceCount).toBe(1);+ });++ it('marks truncated and unreadable documents so the agent can read them via the tool', async () => {+ const injector = new DocumentReferenceContextInjector({+ canReadDocuments: true,+ documentReferences: [+ { content: 'partial', documentId: 'doc-1', title: 'Long', truncated: true },+ { documentId: 'doc-2', title: 'Gone' },+ { documentId: 'doc-3', earlierTurn: true, title: 'Before' },+ ],+ enabled: true,+ });+ const result = await injector.process(+ createContext([{ content: 'Hi', id: 'user-1', role: 'user' }]),+ );+ const content = result.messages[0].content as string;++ expect(content).toContain('<document id="doc-1" title="Long" truncated="true">');+ expect(content).toContain('<document id="doc-2" title="Gone" status="unavailable" />');+ expect(content).toContain('<document id="doc-3" title="Before" status="earlier_turn" />');+ expect(content).toContain('readDocument');+ });++ it('does not point at readDocument when the documents tool is not sent', async () => {+ const injector = new DocumentReferenceContextInjector({+ canReadDocuments: false,+ documentReferences: [+ { content: 'partial', documentId: 'doc-1', title: 'Long', truncated: true },+ ],+ enabled: true,+ });+ const result = await injector.process(+ createContext([{ content: 'Hi', id: 'user-1', role: 'user' }]),+ );+ const content = result.messages[0].content as string;++ expect(content).toContain('<document id="doc-1" title="Long" truncated="true">');+ expect(content).not.toContain('readDocument');+ expect(content).toContain('tell the user');+ });+});diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex c93b3b0aee3..6bdb4d66b5c 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -15,6 +15,7 @@ export { BotPlatformContextInjector } from './BotPlatformContextInjector';export { ConnectorOwnershipInjector } from './ConnectorOwnershipInjector';export { ContextSelectionsInjector } from './ContextSelectionsInjector';export { DiscordContextProvider } from './DiscordContextProvider';+export { DocumentReferenceContextInjector } from './DocumentReferenceContextInjector';export { EvalContextSystemInjector } from './EvalContextSystemInjector';export {buildExpertiseContextSnapshot,@@ -96,6 +97,10 @@ export type {export type { ConnectorOwnershipInjectorConfig } from './ConnectorOwnershipInjector';export type { ContextSelectionsInjectorConfig } from './ContextSelectionsInjector';export type { DiscordContext, DiscordContextProviderConfig } from './DiscordContextProvider';+export type {+ DocumentReferenceContextInjectorConfig,+ DocumentReferenceItem,+} from './DocumentReferenceContextInjector';export type { EvalContext, EvalContextSystemInjectorConfig } from './EvalContextSystemInjector';export type {ExpertiseContextInjectorConfig,diff --git a/packages/mecha/package.json b/packages/mecha/package.jsonindex 8f59d3f8e37..d511b310621 100644--- a/packages/mecha/package.json+++ b/packages/mecha/package.json@@ -16,6 +16,7 @@"@lobechat/builtin-agents": "workspace:*","@lobechat/builtin-skills": "workspace:*","@lobechat/builtin-tool-agent-builder": "workspace:*",+ "@lobechat/builtin-tool-agent-documents": "workspace:*","@lobechat/builtin-tool-agent-management": "workspace:*","@lobechat/builtin-tool-attachments": "workspace:*","@lobechat/builtin-tool-auv": "workspace:*",diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.tsindex dbfb449a76d..0066c38e8ad 100644--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts@@ -29,22 +29,27 @@ describe('buildMessagesEngineParams', () => {expect(explicit.toolsConfig?.disabledToolIdentifiers).toEqual(['x']);});- it('only sets skills and topic references when there is something to inject', () => {+ it('only sets skills, topic and document references when there is something to inject', () => {const empty = buildMessagesEngineParams({...baseSnapshot(),- step: { topicReferences: [] },+ step: { documentReferences: [], topicReferences: [] },tools: { enabledSkills: [] },});expect(empty).not.toHaveProperty('skillsConfig');expect(empty).not.toHaveProperty('topicReferences');+ expect(empty).not.toHaveProperty('documentReferences');const filled = buildMessagesEngineParams({...baseSnapshot(),- step: { topicReferences: [{ id: 't1' } as any] },+ step: {+ documentReferences: [{ documentId: 'd1' }],+ topicReferences: [{ id: 't1' } as any],+ },tools: { enabledSkills: [{ identifier: 's1' } as any] },});expect(filled.skillsConfig).toEqual({ enabledSkills: [{ identifier: 's1' }] });expect(filled.topicReferences).toEqual([{ id: 't1' }]);+ expect(filled.documentReferences).toEqual([{ documentId: 'd1' }]);});it('places world and step facts without leaking undefined keys', () => {diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.tsindex db9547582da..23cb89aa151 100644--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts@@ -96,5 +96,6 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEnworkspaceContext: step?.workspaceContext,}),...(step?.topicReferences?.length && { topicReferences: step.topicReferences }),+ ...(step?.documentReferences?.length && { documentReferences: step.documentReferences }),};};diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.tsindex d57c29979be..9f1267c4a82 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts@@ -147,6 +147,61 @@ describe('gatherContextFacts', () => {});});+ describe('document references', () => {+ it('resolves referenced documents against the executing agent', async () => {+ const findAgentDocument = vi.fn(async (_agentId: string, documentId: string) =>+ documentId === 'doc-1' ? { content: 'Voice rules', title: 'Voice' } : null,+ );++ const facts = await gatherContextFacts(+ request({+ messages: [+ message(+ 'Use <refer_document name="Voice" id="doc-1" /> and <refer_document name="X" id="doc-2" />',+ ),+ ],+ }),+ { findAgentDocument },+ );++ expect(findAgentDocument).toHaveBeenCalledWith('agt_1', 'doc-1');+ expect(facts.step.documentReferences).toEqual([+ { content: 'Voice rules', documentId: 'doc-1', title: 'Voice' },+ { documentId: 'doc-2', title: 'X' },+ ]);+ });++ it('lists earlier-turn references without a lookup only when the documents tool can read them', async () => {+ const findAgentDocument = vi.fn(async () => ({ content: 'Voice rules' }));+ const messages = [message('<refer_document name="Voice" id="doc-1" />'), message('Next')];++ const withTool = await gatherContextFacts(+ request({ enabledToolIds: ['lobe-agent-documents'], messages }),+ { findAgentDocument },+ );+ expect(withTool.step.documentReferences).toEqual([+ { documentId: 'doc-1', earlierTurn: true, title: 'Voice' },+ ]);+ expect(findAgentDocument).not.toHaveBeenCalled();++ const withoutTool = await gatherContextFacts(request({ messages }), { findAgentDocument });+ expect(withoutTool.step.documentReferences).toEqual([+ { content: 'Voice rules', documentId: 'doc-1', title: 'Voice' },+ ]);+ });++ it('skips the lookup when no message references a document', async () => {+ const findAgentDocument = vi.fn();++ const facts = await gatherContextFacts(request({ messages: [message('hello')] }), {+ findAgentDocument,+ });++ expect(facts.step.documentReferences).toBeUndefined();+ expect(findAgentDocument).not.toHaveBeenCalled();+ });+ });+describe('share visitor gates', () => {const visitor = { agentId: 'agt_1', visitorUserId: 'visitor_1' };@@ -198,6 +253,21 @@ describe('gatherContextFacts', () => {expect(summaries).not.toContain('creator secret');});+ it('never resolves document references for a visitor', async () => {+ const findAgentDocument = vi.fn(async () => ({ content: 'creator secret', title: 'Doc' }));++ const facts = await gatherContextFacts(+ request({+ messages: [message('<refer_document name="Doc" id="doc-1" />')],+ shareVisitor: visitor,+ }),+ { findAgentDocument },+ );++ expect(facts.step.documentReferences).toBeUndefined();+ expect(findAgentDocument).not.toHaveBeenCalled();+ });+it('never enumerates the owner’s agents, providers or plugins for a visitor', async () => {const listRecentAgents = vi.fn(async () => [{ id: 'agt_2', title: 'Owner private' }]);const listEnabledProviders = vi.fn(async () => [{ id: 'openai', models: [], name: 'x' }]);diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex efb61ae914d..b935f167bd4 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -1,5 +1,6 @@import { extractTodosFromMessages, normalizeTodosState } from '@lobechat/agent-runtime';import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';import {CloudSandboxIdentifier,@@ -23,8 +24,10 @@ import { COMPOSIO_APP_TYPES } from '@lobechat/const';import {type AgentBuilderContext,type AgentManagementContext,+ type DocumentReferenceItem,type GroupAgentBuilderContext,type PlanTodoConfig,+ resolveDocumentReferences,resolveTopicReferences,type TopicReferenceItem,type WorkspaceContext,@@ -119,6 +122,32 @@ const gatherTopicReferences = async ();};+/**+ * Resolve `<refer_document>` tags against the executing agent's documents. A+ * share visitor never reads the creator's documents through a typed tag.+ */+const gatherDocumentReferences = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<DocumentReferenceItem[] | undefined> => {+ // Client-side preprocessing may already have injected the references.+ if (contains(request.messages, ['document_reference_context'])) return undefined;+ if (!contains(request.messages, ['refer_document', 'refer\\_document'])) return undefined;+ const agentId = request.agentId;+ const { findAgentDocument } = providers;+ if (request.shareVisitor || !agentId || !findAgentDocument) return undefined;++ return attempt('documentReferences', () =>+ resolveDocumentReferences(+ request.messages as Array<{ content: string | unknown; role?: string }>,+ (documentId) => findAgentDocument(agentId, documentId),+ // Without the documents tool the agent cannot read an earlier-turn+ // reference on demand, so keep inlining those too.+ { inlineEarlierTurns: !request.enabledToolIds.includes(AgentDocumentsIdentifier) },+ ),+ );+};+/*** The agent whose documents the model reads: the one being edited while the* agent builder is active, otherwise the executing agent. Never for a share@@ -474,6 +503,7 @@ export const gatherContextFacts = async (() => gatherAgentManagementContext(request, providers),() => gatherComposioServices(request, providers),() => gatherCredentials(request, providers),+ () => gatherDocumentReferences(request, providers),() => gatherGroupAgentBuilderContext(request, providers),() => gatherOnboardingContext(request, providers),() => gatherPlanTodo(request, providers),@@ -502,6 +532,7 @@ export const gatherContextFacts = async (agentManagementContext,composioServicesList,credentials,+ documentReferences,groupAgentBuilderContext,onboardingContext,planTodo,@@ -518,6 +549,7 @@ export const gatherContextFacts = async (step: {agentBuilderContext,agentManagementContext,+ documentReferences,groupAgentBuilderContext,onboardingContext,planTodo,diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsindex d5098b26487..d74a6d2979e 100644--- a/packages/mecha/src/contextEngineering/facts/types.ts+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -126,6 +126,14 @@ export interface ContextFactRequest {* fact" and never blocks the turn.*/export interface ContextFactProviders {+ /**+ * An agent document by its `agent_documents.id`, or null when it is missing,+ * belongs to another agent, or the caller may not read it.+ */+ findAgentDocument?: (+ agentId: string,+ documentId: string,+ ) => Promise<{ content?: string | null; title?: string | null } | null | undefined>;/** A topic by id, or null when the caller may not see it. */findTopic?: (topicId: string) => Promise<TopicFacts | null | undefined>;/** The agent row the builder or group builder is editing. */diff --git a/packages/mecha/src/contextEngineering/types.ts b/packages/mecha/src/contextEngineering/types.tsindex 9811ef5d653..26f0d84363f 100644--- a/packages/mecha/src/contextEngineering/types.ts+++ b/packages/mecha/src/contextEngineering/types.ts@@ -5,6 +5,7 @@ import type {AgentManagementContext,BotPlatformContext,DiscordContext,+ DocumentReferenceItem,EvalContext,FileContextConfig,GroupAgentBuilderContext,@@ -130,6 +131,7 @@ export interface ContextWorldSnapshot {export interface ContextStepSnapshot {agentBuilderContext?: AgentBuilderContext;agentManagementContext?: AgentManagementContext;+ documentReferences?: DocumentReferenceItem[];groupAgentBuilderContext?: GroupAgentBuilderContext;onboardingContext?: OnboardingContext;planTodo?: PlanTodoConfig;diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsxindex fd0a62faac9..76f52dff016 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx@@ -5,7 +5,7 @@ import {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 type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode } from 'react';import { MemoryRouter } from 'react-router';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -91,6 +91,7 @@ vi.mock('@/features/ExplorerTree', async () => {header?: ReactNode;nodes: ExplorerTreeNode<unknown>[];onNodeClick?: (node: ExplorerTreeNode<unknown>, event: ReactMouseEvent<HTMLElement>) => void;+ onNodeDragStart?: (node: ExplorerTreeNode<unknown>, event: ReactDragEvent<HTMLElement>) => void;}interface MockMenuItem {@@ -106,6 +107,7 @@ vi.mock('@/features/ExplorerTree', async () => {header,nodes,onNodeClick,+ onNodeDragStart,}: MockExplorerTreeProps) => {const renderNodes = (parentId: string | null): ReactNode =>nodes@@ -120,6 +122,10 @@ vi.mock('@/features/ExplorerTree', async () => {data-menu-count={String(menuItems.length)}data-testid={`tree-node-${node.id}`}key={node.id}+ onDragStart={(event) => {+ event.stopPropagation();+ onNodeDragStart?.(node, event);+ }}><buttondata-testid={`tree-node-button-${node.id}`}@@ -452,6 +458,39 @@ describe('DocumentExplorerTree', () => {expect(navigateMock).not.toHaveBeenCalled();});+ it('only drags plain documents out of the tree', () => {+ const onDocumentDragStart = vi.fn();+ const data = [+ createDocument({ documentId: 'doc-plain', id: 'plain-row', title: 'Plain' }),+ createDocument({ documentId: 'doc-folder', id: 'folder-row', isFolder: true }),+ createDocument({ documentId: 'doc-pending', id: 'pending:new-row', title: 'Creating' }),+ createDocument({+ category: AGENT_DOCUMENT_SKILL_CATEGORY,+ documentId: 'doc-skill',+ id: 'skill-row',+ }),+ ];++ render(+ <DocumentExplorerTree+ agentId="agent-1"+ data={data}+ mutate={vi.fn()}+ onDocumentDragStart={onDocumentDragStart}+ />,+ { wrapper: MemoryRouter },+ );++ fireEvent.dragStart(screen.getByTestId('tree-node-folder-row'));+ fireEvent.dragStart(screen.getByTestId('tree-node-skill-row'));+ fireEvent.dragStart(screen.getByTestId('tree-node-pending:new-row'));+ expect(onDocumentDragStart).not.toHaveBeenCalled();++ fireEvent.dragStart(screen.getByTestId('tree-node-plain-row'));+ expect(onDocumentDragStart).toHaveBeenCalledTimes(1);+ expect(onDocumentDragStart.mock.calls[0][0]).toMatchObject({ id: 'plain-row', title: 'Plain' });+ });+it('does not default-expand document folders', () => {const data = [createDocument({diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex b6c744032d4..928338078d3 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -10,7 +10,7 @@ import {PenLineIcon,Trash2Icon,} from 'lucide-react';-import type { ChangeEvent, CSSProperties, MouseEvent } from 'react';+import type { ChangeEvent, CSSProperties, DragEvent, MouseEvent } from 'react';import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -42,7 +42,7 @@ import { openConvertToSkillModal, slugifySkillName } from './ConvertToSkillModalimport DocumentExplorerToolbar from './DocumentExplorerToolbar';import { useDocumentTreeOps } from './hooks/useDocumentTreeOps';import type { AgentDocumentItem, AgentDocumentListMutator } from './types';-import { isOrphanSkillBundleItem } from './types';+import { isOrphanSkillBundleItem, isPendingId } from './types';import { canDropDocument } from './utils/canDrop';import { createDocumentComparator } from './utils/sortDocuments';@@ -115,11 +115,17 @@ interface Props {agentId: string;data: AgentDocumentItem[];mutate: AgentDocumentListMutator;+ /**+ * Starts dragging a plain document out of the tree (e.g. into the chat+ * input). Folders, skills and web pages never reach it.+ */+ onDocumentDragStart?: (doc: AgentDocumentItem, event: DragEvent<HTMLElement>) => void;onOpenDocument?: (documentId: string, agentDocumentId?: string) => void;style?: CSSProperties;}-const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocument, style }) => {+const DocumentExplorerTree = memo<Props>((props) => {+ const { agentId, data, mutate, onDocumentDragStart, onOpenDocument, style } = props;const { t } = useTranslation(['chat', 'common']);const navigate = useWorkspaceAwareNavigate();const treeRef = useRef<ExplorerTreeHandle | null>(null);@@ -360,6 +366,17 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen[],);+ const handleNodeDragStart = useCallback(+ (node: ExplorerTreeNode<AgentDocumentItem>, event: DragEvent<HTMLElement>) => {+ const doc = node.data;+ if (!onDocumentDragStart || !doc || doc.isFolder) return;+ // A row still being created has no persisted id the agent could read.+ if (doc.category !== AGENT_DOCUMENT_CATEGORY || isPendingId(doc.id)) return;+ onDocumentDragStart(doc, event);+ },+ [onDocumentDragStart],+ );+const canRename = useCallback((node: ExplorerTreeNode<AgentDocumentItem>) =>!!node.data && node.data.category === AGENT_DOCUMENT_CATEGORY,@@ -558,6 +575,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumenonCommitRename={handleCommitRename}onMove={handleMove}onNodeClick={handleNodeClick}+ onNodeDragStart={onDocumentDragStart ? handleNodeDragStart : undefined}/>)}</div>diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsxindex fd982e4f9df..59244a5340d 100644--- a/src/features/ChatInput/Desktop/index.tsx+++ b/src/features/ChatInput/Desktop/index.tsx@@ -23,6 +23,7 @@ import ControlBar from '../ControlBar';import InputEditor from '../InputEditor';import { useSkillDrop } from '../InputEditor/ActionTag/useSkillDrop';import { type PlaceholderVariant } from '../InputEditor/Placeholder';+import { useDocumentDrop } from '../InputEditor/ReferDocument/useDocumentDrop';import { useTopicDrop } from '../InputEditor/ReferTopic/useTopicDrop';import { useWorkspaceFileDrop } from '../InputEditor/useWorkspaceFileDrop';import SendArea from '../SendArea';@@ -156,6 +157,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(const setExpand = useChatInputStore((s) => s.setExpand);const skillDrop = useSkillDrop();const topicDrop = useTopicDrop();+ const documentDrop = useDocumentDrop();const workspaceFileDrop = useWorkspaceFileDrop();// Fan a single drag event out to every custom-MIME drop handler. Each one@@ -163,11 +165,13 @@ const DesktopChatInput = memo<DesktopChatInputProps>(const handleDragOver = (event: React.DragEvent) => {skillDrop.onDragOver(event);topicDrop.onDragOver(event);+ documentDrop.onDragOver(event);workspaceFileDrop.onDragOver(event);};const handleDrop = (event: React.DragEvent) => {skillDrop.onDrop(event);topicDrop.onDrop(event);+ documentDrop.onDrop(event);workspaceFileDrop.onDrop(event);};diff --git a/src/features/ChatInput/InputEditor/InputHistoryPopup.tsx b/src/features/ChatInput/InputEditor/InputHistoryPopup.tsxindex 6919f219f12..3896f97c0b2 100644--- a/src/features/ChatInput/InputEditor/InputHistoryPopup.tsx+++ b/src/features/ChatInput/InputEditor/InputHistoryPopup.tsx@@ -53,6 +53,7 @@ export const getHistoryPreviewText = (markdown: string): string =>markdown.replaceAll(/<mention\s[^>]*name="([^"]*)"[^>]*>/g, '@$1').replaceAll(/<refer_topic\s[^>]*name="([^"]*)"[^>]*>/g, '#$1')+ .replaceAll(/<refer_document\s[^>]*name="([^"]*)"[^>]*>/g, '#$1').replaceAll(/<localFile\s[^>]*name="([^"]*)"[^>]*>/g, '$1').replaceAll(/<[^>]+>/g, ' ').replaceAll(/\s+/g, ' ')diff --git a/src/features/ChatInput/InputEditor/ReferDocument/ReactReferDocumentPlugin.tsx b/src/features/ChatInput/InputEditor/ReferDocument/ReactReferDocumentPlugin.tsxnew file mode 100644index 00000000000..06b3b8c7a04--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/ReactReferDocumentPlugin.tsx@@ -0,0 +1,23 @@+import { useLexicalComposerContext } from '@lobehub/editor';+import { type FC, useLayoutEffect } from 'react';++import ReferDocument from './ReferDocument';+import { ReferDocumentPlugin } from './ReferDocumentPlugin';++const ReactReferDocumentPlugin: FC = () => {+ const [editor] = useLexicalComposerContext();++ useLayoutEffect(() => {+ editor.registerPlugin(ReferDocumentPlugin, {+ decorator: (node) => {+ return <ReferDocument node={node} />;+ },+ });+ }, [editor]);++ return null;+};++ReactReferDocumentPlugin.displayName = 'ReactReferDocumentPlugin';++export default ReactReferDocumentPlugin;diff --git a/src/features/ChatInput/InputEditor/ReferDocument/ReferDocument.tsx b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocument.tsxnew file mode 100644index 00000000000..1f5c1cf9699--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocument.tsx@@ -0,0 +1,16 @@+import { memo } from 'react';++import type { ReferDocumentNode } from './ReferDocumentNode';+import { ReferDocumentView } from './ReferDocumentView';++interface ReferDocumentProps {+ node: ReferDocumentNode;+}++const ReferDocument = memo<ReferDocumentProps>(({ node }) => {+ return <ReferDocumentView title={node.title} />;+});++ReferDocument.displayName = 'ReferDocument';++export default ReferDocument;diff --git a/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentNode.ts b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentNode.tsnew file mode 100644index 00000000000..d61ff3cfd29--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentNode.ts@@ -0,0 +1,118 @@+import { addClassNamesToElement } from '@lexical/utils';+import { getKernelFromEditor } from '@lobehub/editor';+import type { HeadlessRenderableNode, HeadlessRenderContext } from '@lobehub/editor/renderer';+import {+ $applyNodeReplacement,+ DecoratorNode,+ type DOMExportOutput,+ type EditorConfig,+ type LexicalEditor,+ type LexicalNode,+ type LexicalUpdateJSON,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';+import { createElement } from 'react';++import { ReferDocumentView } from './ReferDocumentView';++export type SerializedReferDocumentNode = Spread<+ {+ documentId: string;+ title: string;+ },+ SerializedLexicalNode+>;++export class ReferDocumentNode extends DecoratorNode<any> implements HeadlessRenderableNode {+ __documentId: string;+ __title: string;++ static getType(): string {+ return 'refer-document';+ }++ static clone(node: ReferDocumentNode): ReferDocumentNode {+ return new ReferDocumentNode(node.__documentId, node.__title, node.__key);+ }++ static importJSON(serializedNode: SerializedReferDocumentNode): ReferDocumentNode {+ return $createReferDocumentNode(serializedNode.documentId, serializedNode.title).updateFromJSON(+ serializedNode,+ );+ }++ static importDOM(): null {+ return null;+ }++ constructor(documentId: string, title: string, key?: string) {+ super(key);+ this.__documentId = documentId;+ this.__title = title;+ }++ get documentId(): string {+ return this.__documentId;+ }++ get title(): string {+ return this.__title;+ }++ exportDOM(): DOMExportOutput {+ return { element: document.createElement('span') };+ }++ createDOM(config: EditorConfig): HTMLElement {+ const element = document.createElement('span');+ addClassNamesToElement(element, config.theme.referDocument);+ return element;+ }++ getTextContent(): string {+ return this.__title;+ }++ isInline(): true {+ return true;+ }++ updateDOM(): boolean {+ return false;+ }++ exportJSON(): SerializedReferDocumentNode {+ return {+ ...super.exportJSON(),+ documentId: this.__documentId,+ title: this.__title,+ };+ }++ updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedReferDocumentNode>): this {+ return super.updateFromJSON(serializedNode);+ }++ decorate(editor: LexicalEditor): any {+ const decorator = getKernelFromEditor(editor)?.getDecorator(ReferDocumentNode.getType());+ if (!decorator) return null;+ if (typeof decorator === 'function') return decorator(this, editor);+ return {+ queryDOM: decorator.queryDOM,+ render: decorator.render(this, editor),+ };+ }++ renderHeadless({ key }: HeadlessRenderContext) {+ return createElement(ReferDocumentView, { key, title: this.__title });+ }+}++export function $createReferDocumentNode(documentId: string, title: string): ReferDocumentNode {+ return $applyNodeReplacement(new ReferDocumentNode(documentId, title));+}++export function $isReferDocumentNode(node: LexicalNode): node is ReferDocumentNode {+ return node.getType() === ReferDocumentNode.getType();+}diff --git a/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentPlugin.ts b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentPlugin.tsnew file mode 100644index 00000000000..6f1d7ec1eea--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentPlugin.ts@@ -0,0 +1,112 @@+import { $wrapNodeInElement } from '@lexical/utils';+import {+ type getKernelFromEditor,+ ILitexmlService,+ IMarkdownShortCutService,+} from '@lobehub/editor';+import {+ $createParagraphNode,+ $insertNodes,+ $isRootOrShadowRoot,+ COMMAND_PRIORITY_HIGH,+ createCommand,+ type LexicalEditor,+} from 'lexical';++import {+ $createReferDocumentNode,+ $isReferDocumentNode,+ ReferDocumentNode,+ type SerializedReferDocumentNode,+} from './ReferDocumentNode';+import { formatReferDocumentTag } from './referDocumentTag';++export const INSERT_REFER_DOCUMENT_COMMAND = createCommand<{ documentId: string; title: string }>(+ 'INSERT_REFER_DOCUMENT_COMMAND',+);++type IEditorKernel = ReturnType<typeof getKernelFromEditor>;++export interface ReferDocumentPluginOptions {+ decorator: (node: ReferDocumentNode, editor: LexicalEditor) => any;+ theme?: { referDocument?: string };+}++export class ReferDocumentPlugin {+ static pluginName = 'ReferDocumentPlugin';++ config?: ReferDocumentPluginOptions;+ private kernel: IEditorKernel;++ constructor(kernel: IEditorKernel, config?: ReferDocumentPluginOptions) {+ this.kernel = kernel;+ this.config = config;++ kernel.registerNodes([ReferDocumentNode]);++ if (config?.theme) {+ kernel.registerThemes(config.theme);+ }++ kernel.registerDecorator(ReferDocumentNode.getType(), (node, editor) => {+ return config?.decorator ? config.decorator(node as ReferDocumentNode, editor) : null;+ });+ }++ onInit(editor: LexicalEditor): void {+ this.registerMarkdown();+ this.registerLiteXml();+ this.registerCommand(editor);+ }++ private registerMarkdown(): void {+ const mdService = this.kernel.requireService(IMarkdownShortCutService);++ mdService?.registerMarkdownWriter(ReferDocumentNode.getType(), (ctx: any, node: any) => {+ if ($isReferDocumentNode(node)) {+ ctx.appendLine(formatReferDocumentTag(node.documentId, node.title));+ }+ });+ }++ private registerCommand(editor: LexicalEditor): void {+ editor.registerCommand(+ INSERT_REFER_DOCUMENT_COMMAND,+ (payload) => {+ editor.update(() => {+ const node = $createReferDocumentNode(payload.documentId, payload.title);+ $insertNodes([node]);+ if ($isRootOrShadowRoot(node.getParentOrThrow())) {+ $wrapNodeInElement(node, $createParagraphNode).selectEnd();+ }+ });+ return true;+ },+ COMMAND_PRIORITY_HIGH,+ );+ }++ private registerLiteXml(): void {+ const xmlService = this.kernel.requireService(ILitexmlService);++ xmlService?.registerXMLWriter(ReferDocumentNode.getType(), (node: any, ctx: any) => {+ if ($isReferDocumentNode(node)) {+ return ctx.createXmlNode('referDocument', { id: node.documentId, name: node.title });+ }+ return false;+ });++ xmlService?.registerXMLReader('referDocument', (xmlElement: any) => {+ return {+ documentId: xmlElement.getAttribute('id') || '',+ title: xmlElement.getAttribute('name') || '',+ type: ReferDocumentNode.getType(),+ version: 1,+ } satisfies SerializedReferDocumentNode;+ });+ }++ destroy(): void {+ this.kernel.unregisterDecorator?.(ReferDocumentNode.getType());+ }+}diff --git a/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentView.tsx b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentView.tsxnew file mode 100644index 00000000000..43edff43482--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/ReferDocumentView.tsx@@ -0,0 +1,30 @@+import { Tag } from '@lobehub/ui';+import { FileTextIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { TAG_MARGIN_INLINE_END } from '../constants';++export interface ReferDocumentViewProps {+ title?: string;+}++export const ReferDocumentView = memo<ReferDocumentViewProps>(({ title }) => {+ const { t } = useTranslation('file');++ return (+ <span+ style={{+ display: 'inline-flex',+ marginInlineEnd: TAG_MARGIN_INLINE_END,+ userSelect: 'none',+ }}+ >+ <Tag color="geekblue" icon={<FileTextIcon size={12} />} variant="borderless">+ {title || t('pageList.untitled')}+ </Tag>+ </span>+ );+});++ReferDocumentView.displayName = 'ReferDocumentView';diff --git a/src/features/ChatInput/InputEditor/ReferDocument/documentDragData.test.ts b/src/features/ChatInput/InputEditor/ReferDocument/documentDragData.test.tsnew file mode 100644index 00000000000..ef931ad6a09--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/documentDragData.test.ts@@ -0,0 +1,55 @@+import { AGENT_DOCUMENT_DRAG_MIME } from '@lobechat/const';+import { describe, expect, it } from 'vitest';++import { readDocumentDragData, writeDocumentDragData } from './documentDragData';+import { formatReferDocumentTag } from './referDocumentTag';++describe('documentDragData', () => {+ it('round-trips a document payload through the custom MIME', () => {+ const dataTransfer = new DataTransfer();+ writeDocumentDragData(dataTransfer, { documentId: 'doc-1', title: 'Style Guide' });++ expect(dataTransfer.types).toContain(AGENT_DOCUMENT_DRAG_MIME);+ expect(readDocumentDragData(dataTransfer)).toEqual({+ documentId: 'doc-1',+ title: 'Style Guide',+ });+ });++ it('does not react to unrelated drag data', () => {+ const dataTransfer = new DataTransfer();+ dataTransfer.setData('text/plain', 'doc-1');++ expect(readDocumentDragData(dataTransfer)).toBeUndefined();+ });++ it('rejects malformed data and payloads without an id', () => {+ const dataTransfer = new DataTransfer();+ dataTransfer.setData(AGENT_DOCUMENT_DRAG_MIME, '{invalid');+ expect(readDocumentDragData(dataTransfer)).toBeUndefined();++ dataTransfer.setData(AGENT_DOCUMENT_DRAG_MIME, JSON.stringify({ title: 'Missing id' }));+ expect(readDocumentDragData(dataTransfer)).toBeUndefined();+ });++ it('uses an untitled fallback when the title is empty', () => {+ const dataTransfer = new DataTransfer();+ dataTransfer.setData(AGENT_DOCUMENT_DRAG_MIME, JSON.stringify({ documentId: 'doc-1' }));++ expect(readDocumentDragData(dataTransfer)).toEqual({ documentId: 'doc-1', title: 'Untitled' });+ });+});++describe('formatReferDocumentTag', () => {+ it('serializes a self-closing refer_document tag', () => {+ expect(formatReferDocumentTag('doc-1', 'Style Guide')).toBe(+ '<refer_document name="Style Guide" id="doc-1" />',+ );+ });++ it('drops characters that would break the attribute or tag', () => {+ expect(formatReferDocumentTag('doc-1', 'A "quoted" <b>title</b>')).toBe(+ '<refer_document name="A quoted btitle/b" id="doc-1" />',+ );+ });+});diff --git a/src/features/ChatInput/InputEditor/ReferDocument/documentDragData.ts b/src/features/ChatInput/InputEditor/ReferDocument/documentDragData.tsnew file mode 100644index 00000000000..deb81b6d10d--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/documentDragData.ts@@ -0,0 +1,55 @@+import { AGENT_DOCUMENT_DRAG_MIME } from '@lobechat/const';+import type React from 'react';++import { setDragLabelPreview } from '../ReferTopic/dragLabelPreview';++/** Payload carried when an agent document row is dragged into the chat input. */+export interface DocumentDragPayload {+ /** Agent-document binding id (`agent_documents.id`), as read by `readDocument`. */+ documentId: string;+ title: string;+}++/**+ * Write only our custom MIME — no `text/plain` fallback, which the Lexical chat+ * input would race to insert as text.+ */+export const writeDocumentDragData = (+ dataTransfer: DataTransfer,+ payload: DocumentDragPayload,+): void => {+ dataTransfer.setData(AGENT_DOCUMENT_DRAG_MIME, JSON.stringify(payload));+};++const FILE_TEXT_ICON_SVG =+ '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>';++/**+ * Start a document drag. The source tree also moves rows on drop, so keep+ * `copyMove`: the chat input accepts `copy`, the tree its own `move`.+ */+export const startDocumentDrag = (event: React.DragEvent, payload: DocumentDragPayload): void => {+ writeDocumentDragData(event.dataTransfer, payload);+ event.dataTransfer.effectAllowed = 'copyMove';+ setDragLabelPreview(event, { iconSvg: FILE_TEXT_ICON_SVG, label: payload.title });+};++export const readDocumentDragData = (+ dataTransfer: DataTransfer,+): DocumentDragPayload | undefined => {+ const raw = dataTransfer.getData(AGENT_DOCUMENT_DRAG_MIME);+ if (!raw) return undefined;++ try {+ const parsed = JSON.parse(raw) as Partial<DocumentDragPayload>;+ if (typeof parsed.documentId !== 'string' || parsed.documentId.length === 0) return undefined;++ return {+ documentId: parsed.documentId,+ title:+ typeof parsed.title === 'string' && parsed.title.length > 0 ? parsed.title : 'Untitled',+ };+ } catch {+ return undefined;+ }+};diff --git a/src/features/ChatInput/InputEditor/ReferDocument/index.ts b/src/features/ChatInput/InputEditor/ReferDocument/index.tsnew file mode 100644index 00000000000..049e289d288--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/index.ts@@ -0,0 +1,9 @@+export { default as ReactReferDocumentPlugin } from './ReactReferDocumentPlugin';+export type { SerializedReferDocumentNode } from './ReferDocumentNode';+export {+ $createReferDocumentNode,+ $isReferDocumentNode,+ ReferDocumentNode,+} from './ReferDocumentNode';+export { INSERT_REFER_DOCUMENT_COMMAND } from './ReferDocumentPlugin';+export { formatReferDocumentTag, REFER_DOCUMENT_TAG } from './referDocumentTag';diff --git a/src/features/ChatInput/InputEditor/ReferDocument/referDocumentTag.ts b/src/features/ChatInput/InputEditor/ReferDocument/referDocumentTag.tsnew file mode 100644index 00000000000..7b32797d123--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/referDocumentTag.ts@@ -0,0 +1,12 @@+export const REFER_DOCUMENT_TAG = 'refer_document';++/**+ * The self-closing tag parsers (remark render + server resolver) read quoted+ * attributes verbatim and do not decode entities, so drop the characters that+ * would end the attribute or the tag instead of escaping them.+ */+const sanitizeAttr = (value: string): string => value.replaceAll(/["<>]/g, '').trim();++/** Markdown wire format for a document reference inside a user message. */+export const formatReferDocumentTag = (documentId: string, title: string): string =>+ `<${REFER_DOCUMENT_TAG} name="${sanitizeAttr(title)}" id="${sanitizeAttr(documentId)}" />`;diff --git a/src/features/ChatInput/InputEditor/ReferDocument/useDocumentDrop.test.ts b/src/features/ChatInput/InputEditor/ReferDocument/useDocumentDrop.test.tsnew file mode 100644index 00000000000..0c9295d7834--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/useDocumentDrop.test.ts@@ -0,0 +1,59 @@+import { act, renderHook } from '@testing-library/react';+import type { DragEvent } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { writeDocumentDragData } from './documentDragData';+import { INSERT_REFER_DOCUMENT_COMMAND } from './ReferDocumentPlugin';+import { useDocumentDrop } from './useDocumentDrop';++const editor = vi.hoisted(() => ({+ dispatchCommand: vi.fn(),+ focus: vi.fn(),+}));++vi.mock('../../store', () => ({+ useChatInputStore: (selector: (state: { editor: typeof editor }) => unknown) =>+ selector({ editor }),+}));++const createDragEvent = (dataTransfer: DataTransfer) =>+ ({+ dataTransfer,+ preventDefault: vi.fn(),+ stopPropagation: vi.fn(),+ }) as unknown as DragEvent;++describe('useDocumentDrop', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('inserts the dragged document reference into the editor', () => {+ const dataTransfer = new DataTransfer();+ writeDocumentDragData(dataTransfer, { documentId: 'doc-1', title: 'Style Guide' });+ const event = createDragEvent(dataTransfer);+ const { result } = renderHook(() => useDocumentDrop());++ act(() => result.current.onDrop(event));++ expect(event.preventDefault).toHaveBeenCalled();+ expect(event.stopPropagation).toHaveBeenCalled();+ expect(editor.focus).toHaveBeenCalled();+ expect(editor.dispatchCommand).toHaveBeenCalledWith(INSERT_REFER_DOCUMENT_COMMAND, {+ documentId: 'doc-1',+ title: 'Style Guide',+ });+ });++ it('ignores unrelated drag data', () => {+ const dataTransfer = new DataTransfer();+ dataTransfer.setData('text/plain', 'plain text');+ const event = createDragEvent(dataTransfer);+ const { result } = renderHook(() => useDocumentDrop());++ act(() => result.current.onDrop(event));++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(editor.dispatchCommand).not.toHaveBeenCalled();+ });+});diff --git a/src/features/ChatInput/InputEditor/ReferDocument/useDocumentDrop.ts b/src/features/ChatInput/InputEditor/ReferDocument/useDocumentDrop.tsnew file mode 100644index 00000000000..ef99d95af6c--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferDocument/useDocumentDrop.ts@@ -0,0 +1,44 @@+import { AGENT_DOCUMENT_DRAG_MIME } from '@lobechat/const';+import type React from 'react';+import { useCallback } from 'react';++import { useChatInputStore } from '../../store';+import { readDocumentDragData } from './documentDragData';+import { INSERT_REFER_DOCUMENT_COMMAND } from './ReferDocumentPlugin';++interface UseDocumentDropResult {+ onDragOver: (event: React.DragEvent) => void;+ onDrop: (event: React.DragEvent) => void;+}++/** Inserts an agent document dragged from the working sidebar as a reference chip. */+export const useDocumentDrop = (): UseDocumentDropResult => {+ const editor = useChatInputStore((state) => state.editor);++ const onDragOver = useCallback((event: React.DragEvent) => {+ if (!event.dataTransfer.types.includes(AGENT_DOCUMENT_DRAG_MIME)) return;++ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ }, []);++ const onDrop = useCallback(+ (event: React.DragEvent) => {+ if (!event.dataTransfer.types.includes(AGENT_DOCUMENT_DRAG_MIME)) return;++ const payload = readDocumentDragData(event.dataTransfer);+ if (!payload) return;++ event.preventDefault();+ event.stopPropagation();++ if (!editor) return;++ editor.focus();+ editor.dispatchCommand(INSERT_REFER_DOCUMENT_COMMAND, payload);+ },+ [editor],+ );++ return { onDragOver, onDrop };+};diff --git a/src/features/ChatInput/InputEditor/plugins.ts b/src/features/ChatInput/InputEditor/plugins.tsindex 6f8e5890327..116b655625b 100644--- a/src/features/ChatInput/InputEditor/plugins.ts+++ b/src/features/ChatInput/InputEditor/plugins.ts@@ -12,6 +12,7 @@ import { type Editor } from '@lobehub/editor/react';import { ReactActionTagPlugin } from './ActionTag';import { ReactLocalFileTagPlugin } from './LocalFileTag';+import { ReactReferDocumentPlugin } from './ReferDocument';import { ReactReferTopicPlugin } from './ReferTopic';type EditorPlugins = NonNullable<Parameters<typeof Editor>[0]['plugins']>;@@ -24,6 +25,7 @@ interface CreateChatInputRichPluginsOptions {export const CHAT_INPUT_EMBED_PLUGINS: EditorPlugins = [ReactActionTagPlugin,ReactReferTopicPlugin,+ ReactReferDocumentPlugin,ReactLocalFileTagPlugin,ReactMentionPlugin,];diff --git a/src/features/Conversation/Markdown/plugins/ReferDocument/Render.tsx b/src/features/Conversation/Markdown/plugins/ReferDocument/Render.tsxnew file mode 100644index 00000000000..219abbd8d6c--- /dev/null+++ b/src/features/Conversation/Markdown/plugins/ReferDocument/Render.tsx@@ -0,0 +1,22 @@+'use client';++import { memo } from 'react';++import { ReferDocumentView } from '@/features/ChatInput/InputEditor/ReferDocument/ReferDocumentView';++import { type MarkdownElementProps } from '../type';++interface ReferDocumentNodeProps {+ id?: string;+ name?: string;+}++const Render = memo<MarkdownElementProps<ReferDocumentNodeProps>>(({ node }) => {+ const { name } = node?.properties || {};++ return <ReferDocumentView title={name} />;+});++Render.displayName = 'ReferDocumentRender';++export default Render;diff --git a/src/features/Conversation/Markdown/plugins/ReferDocument/index.ts b/src/features/Conversation/Markdown/plugins/ReferDocument/index.tsnew file mode 100644index 00000000000..983453d4d37--- /dev/null+++ b/src/features/Conversation/Markdown/plugins/ReferDocument/index.ts@@ -0,0 +1,14 @@+import { REFER_DOCUMENT_TAG } from '@/features/ChatInput/InputEditor/ReferDocument/referDocumentTag';++import { createRemarkSelfClosingTagPlugin } from '../remarkPlugins/createRemarkSelfClosingTagPlugin';+import { type MarkdownElement } from '../type';+import Render from './Render';++const ReferDocument: MarkdownElement = {+ Component: Render,+ remarkPlugin: createRemarkSelfClosingTagPlugin(REFER_DOCUMENT_TAG),+ scope: 'user',+ tag: REFER_DOCUMENT_TAG,+};++export default ReferDocument;diff --git a/src/features/Conversation/Markdown/plugins/index.ts b/src/features/Conversation/Markdown/plugins/index.tsindex f9947b8fcfd..6eb16c0009c 100644--- a/src/features/Conversation/Markdown/plugins/index.ts+++ b/src/features/Conversation/Markdown/plugins/index.ts@@ -8,6 +8,7 @@ import LobeThinking from './LobeThinking';import LocalFile from './LocalFile';import LocalFileLink from './LocalFileLink';import Mention from './Mention';+import ReferDocument from './ReferDocument';import ReferTopic from './ReferTopic';import ScmEvent from './ScmEvent';import Skill from './Skill';@@ -26,6 +27,7 @@ export const markdownElements: MarkdownElement[] = [LocalFile,Mention,ReferTopic,+ ReferDocument,Skill,Tool,Task,diff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.tsxindex bc55fe7e06e..cde6c46d780 100644--- a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.tsx@@ -7,6 +7,7 @@ import { memo, useMemo } from 'react';import { ActionTagNode } from '@/features/ChatInput/InputEditor/ActionTag/ActionTagNode';import { LocalFileTagNode } from '@/features/ChatInput/InputEditor/LocalFileTag';import { mentionPlainClassName } from '@/features/ChatInput/InputEditor/mentionStyle';+import { ReferDocumentNode } from '@/features/ChatInput/InputEditor/ReferDocument/ReferDocumentNode';import { ReferTopicNode } from '@/features/ChatInput/InputEditor/ReferTopic/ReferTopicNode';import { downloadPreviewImage } from '../../components/downloadPreviewImage';@@ -19,7 +20,7 @@ interface RichTextMessageProps {const LINE_HEIGHT = 1.6;const style: CSSProperties = { '--common-line-height': LINE_HEIGHT } as CSSProperties;-const EXTRA_NODES = [ActionTagNode, ReferTopicNode, LocalFileTagNode];+const EXTRA_NODES = [ActionTagNode, ReferTopicNode, ReferDocumentNode, LocalFileTagNode];const PREVIEW_OPTIONS = { onDownload: downloadPreviewImage };const RichTextMessage = memo<RichTextMessageProps>(({ editorState, variant = 'chat' }) => {diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsxindex 8d850a6c300..1d46d324ad3 100644--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx@@ -34,6 +34,7 @@ import {DocumentExplorerTree,} from '@/features/AgentDocumentsExplorer';import { startSkillDrag } from '@/features/ChatInput/InputEditor/ActionTag/skillDragData';+import { startDocumentDrag } from '@/features/ChatInput/InputEditor/ReferDocument/documentDragData';import {filterSkillItems,openRenameSkillModal,@@ -426,6 +427,15 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>([agentId, data, navigate, openDocument, resolvedOpenMode],);+ // Dragging a document into the chat input inserts a `<refer_document>` chip;+ // the server resolves it against this agent's documents when sending.+ const handleDocumentDragStart = useCallback(+ (doc: { filename?: string | null; id: string; title?: string | null }, event: DragEvent) => {+ startDocumentDrag(event, { documentId: doc.id, title: doc.title || doc.filename || '' });+ },+ [],+ );+// Open the SKILL.md (skills/index child) when present; fall back to the// bundle itself (orphan bundles surface for recovery).const openAgentSkill = useCallback(@@ -688,6 +698,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(data={documentsData}mutate={mutate}style={{ height: '100%' }}+ onDocumentDragStart={handleDocumentDragStart}onOpenDocument={openAgentDocument}/></Flexbox>diff --git a/src/services/chat/mecha/contextFactProviders.ts b/src/services/chat/mecha/contextFactProviders.tsindex e0ac245f3c8..ce489765477 100644--- a/src/services/chat/mecha/contextFactProviders.ts+++ b/src/services/chat/mecha/contextFactProviders.ts@@ -4,6 +4,7 @@ import { type AgentShareVisitorContext, getActivePluginIds } from '@lobechat/typimport { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { lambdaClient } from '@/libs/trpc/client';+import { agentDocumentService } from '@/services/agentDocument';import { messageService } from '@/services/message';import { notebookService } from '@/services/notebook';import { sandboxStorageService } from '@/services/sandboxStorage';@@ -82,6 +83,11 @@ export const createBrowserContextFactProviders = ({groupId,shareVisitor,}: BrowserContextFactSource = {}): ContextFactProviders => ({+ findAgentDocument: async (targetAgentId, documentId) => {+ const doc = await agentDocumentService.readDocument({ agentId: targetAgentId, id: documentId });+ return doc ? { content: doc.content, title: doc.title } : null;+ },+findTopic: async (topicId) => {const topic = topicSelectors.getTopicById(topicId)(getChatStoreState());if (!topic) return null;