π€― 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): drag workspace files into the chat input (#16555)
Arvin Xu372dfdf671a2
diff --git a/packages/const/src/file.ts b/packages/const/src/file.tsindex c826e8606e9..595772d72ef 100644--- a/packages/const/src/file.ts+++ b/packages/const/src/file.ts@@ -18,3 +18,11 @@ export const SYSTEM_FILES_BLACKLIST = [export const FILE_UPLOAD_BLACKLIST = SYSTEM_FILES_BLACKLIST;export const MAX_UPLOAD_FILE_COUNT = 10;++/**+ * DataTransfer MIME type used when dragging a file/folder row from the working+ * sidebar file tree into the chat input. A custom (non-`Files`) type so the+ * file-upload drop zone ignores it β it only reacts to `Files` β and the drop+ * handler turns it into a `<localFile />` mention instead of uploading a blob.+ */+export const WORKSPACE_FILE_DRAG_MIME = 'application/x-lobe-workspace-file';diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsxindex 889d686dfcc..6d3ee6f87ab 100644--- a/src/features/ChatInput/Desktop/index.tsx+++ b/src/features/ChatInput/Desktop/index.tsx@@ -24,6 +24,7 @@ import ControlBar from '../ControlBar';import InputEditor from '../InputEditor';import { useSkillDrop } from '../InputEditor/ActionTag/useSkillDrop';import { type PlaceholderVariant } from '../InputEditor/Placeholder';+import { useWorkspaceFileDrop } from '../InputEditor/useWorkspaceFileDrop';import SendArea from '../SendArea';import TypoBar from '../TypoBar';import ContextContainer from './ContextContainer';@@ -132,6 +133,18 @@ const DesktopChatInput = memo<DesktopChatInputProps>(const setExpand = useChatInputStore((s) => s.setExpand);const skillDrop = useSkillDrop();+ const workspaceFileDrop = useWorkspaceFileDrop();++ // Fan a single drag event out to every custom-MIME drop handler. Each one+ // no-ops unless its own MIME is present, so ordering is irrelevant.+ const handleDragOver = (event: React.DragEvent) => {+ skillDrop.onDragOver(event);+ workspaceFileDrop.onDragOver(event);+ };+ const handleDrop = (event: React.DragEvent) => {+ skillDrop.onDrop(event);+ workspaceFileDrop.onDrop(event);+ };useEffect(() => {if (editor) editor.focus();@@ -163,8 +176,8 @@ const DesktopChatInput = memo<DesktopChatInputProps>(gap={8}paddingBlock={expand ? 0 : showFootnote ? '0 12px' : '0 8px'}style={{ display: hidden ? 'none' : undefined }}- onDragOver={skillDrop.onDragOver}- onDrop={skillDrop.onDrop}+ onDragOver={handleDragOver}+ onDrop={handleDrop}>{!isConfigLoading && <ChatInputNotice />}<ChatInputdiff --git a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionNode.ts b/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionNode.tsnew file mode 100644index 00000000000..380fabf2790--- /dev/null+++ b/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionNode.ts@@ -0,0 +1,133 @@+import { addClassNamesToElement } from '@lexical/utils';+import { getKernelFromEditor } from '@lobehub/editor';+import {+ $applyNodeReplacement,+ DecoratorNode,+ type DOMExportOutput,+ type EditorConfig,+ type LexicalEditor,+ type LexicalNode,+ type LexicalUpdateJSON,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';++export type SerializedLocalFileMentionNode = Spread<+ {+ isDirectory: boolean;+ name: string;+ path: string;+ },+ SerializedLexicalNode+>;++/**+ * A local-file reference rendered as a compact "icon + name" chip, mirroring the+ * ReferTopic / ActionTag custom-node pattern. Kept separate from the generic+ * `mention` node so it can render a file/folder icon (instead of the hardcoded+ * `@`) and β crucially β own its `<localFile β¦ />` markdown writer via a plugin+ * that is always registered, independent of whether `mentionOption` is enabled.+ */+export class LocalFileMentionNode extends DecoratorNode<any> {+ __name: string;+ __path: string;+ __isDirectory: boolean;++ static getType(): string {+ return 'local-file-mention';+ }++ static clone(node: LocalFileMentionNode): LocalFileMentionNode {+ return new LocalFileMentionNode(node.__name, node.__path, node.__isDirectory, node.__key);+ }++ static importJSON(serializedNode: SerializedLocalFileMentionNode): LocalFileMentionNode {+ return $createLocalFileMentionNode(+ serializedNode.name,+ serializedNode.path,+ serializedNode.isDirectory,+ ).updateFromJSON(serializedNode);+ }++ static importDOM(): null {+ return null;+ }++ constructor(name: string, path: string, isDirectory = false, key?: string) {+ super(key);+ this.__name = name;+ this.__path = path;+ this.__isDirectory = isDirectory;+ }++ get name(): string {+ return this.__name;+ }++ get path(): string {+ return this.__path;+ }++ get isDirectory(): boolean {+ return this.__isDirectory;+ }++ exportDOM(): DOMExportOutput {+ return { element: document.createElement('span') };+ }++ createDOM(config: EditorConfig): HTMLElement {+ const element = document.createElement('span');+ addClassNamesToElement(element, config.theme.localFileMention);+ return element;+ }++ getTextContent(): string {+ return this.__name;+ }++ isInline(): true {+ return true;+ }++ updateDOM(): boolean {+ return false;+ }++ exportJSON(): SerializedLocalFileMentionNode {+ return {+ ...super.exportJSON(),+ isDirectory: this.__isDirectory,+ name: this.__name,+ path: this.__path,+ };+ }++ updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedLocalFileMentionNode>): this {+ return super.updateFromJSON(serializedNode);+ }++ decorate(editor: LexicalEditor): any {+ const decorator = getKernelFromEditor(editor)?.getDecorator(LocalFileMentionNode.getType());+ if (!decorator) return null;+ if (typeof decorator === 'function') return decorator(this, editor);+ return {+ queryDOM: decorator.queryDOM,+ render: decorator.render(this, editor),+ };+ }+}++export function $createLocalFileMentionNode(+ name: string,+ path: string,+ isDirectory = false,+): LocalFileMentionNode {+ return $applyNodeReplacement(new LocalFileMentionNode(name, path, isDirectory));+}++export function $isLocalFileMentionNode(+ node: LexicalNode | null | undefined,+): node is LocalFileMentionNode {+ return node instanceof LocalFileMentionNode;+}diff --git a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionPlugin.ts b/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionPlugin.tsnew file mode 100644index 00000000000..7a67069dfa7--- /dev/null+++ b/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionPlugin.ts@@ -0,0 +1,141 @@+import { $wrapNodeInElement } from '@lexical/utils';+import { escapeXmlAttr } from '@lobechat/prompts';+import {+ type getKernelFromEditor,+ ILitexmlService,+ IMarkdownShortCutService,+} from '@lobehub/editor';+import {+ $createParagraphNode,+ $createTextNode,+ $insertNodes,+ $isRootOrShadowRoot,+ COMMAND_PRIORITY_HIGH,+ createCommand,+ type LexicalEditor,+} from 'lexical';++import {+ $createLocalFileMentionNode,+ $isLocalFileMentionNode,+ LocalFileMentionNode,+ type SerializedLocalFileMentionNode,+} from './LocalFileMentionNode';++export interface InsertLocalFileMentionPayload {+ isDirectory?: boolean;+ name: string;+ path: string;+}++export const INSERT_LOCAL_FILE_MENTION_COMMAND = createCommand<InsertLocalFileMentionPayload>(+ 'INSERT_LOCAL_FILE_MENTION_COMMAND',+);++type IEditorKernel = ReturnType<typeof getKernelFromEditor>;++export interface LocalFileMentionPluginOptions {+ decorator: (node: LocalFileMentionNode, editor: LexicalEditor) => any;+ theme?: { localFileMention?: string };+}++/**+ * Owns the `local-file-mention` node: its decorator, its `<localFile β¦ />`+ * markdown writer, and its insert command. Because this plugin is registered+ * unconditionally (via `CHAT_INPUT_EMBED_PLUGINS`), the markdown serialization+ * is always available β unlike the generic mention writer, which is only wired+ * up when `mentionOption` has items. This is what keeps workspace-file drops+ * serializing to the tag the gateway/device run needs, even on the web client+ * with no other mention categories.+ */+export class LocalFileMentionPlugin {+ static pluginName = 'LocalFileMentionPlugin';++ config?: LocalFileMentionPluginOptions;+ private kernel: IEditorKernel;++ constructor(kernel: IEditorKernel, config?: LocalFileMentionPluginOptions) {+ this.kernel = kernel;+ this.config = config;++ kernel.registerNodes([LocalFileMentionNode]);++ if (config?.theme) {+ kernel.registerThemes(config.theme);+ }++ kernel.registerDecorator(LocalFileMentionNode.getType(), (node, editor) => {+ return config?.decorator ? config.decorator(node as LocalFileMentionNode, editor) : null;+ });+ }++ onInit(editor: LexicalEditor): void {+ this.registerMarkdown();+ this.registerLiteXml();+ this.registerCommand(editor);+ }++ private registerMarkdown(): void {+ const mdService = this.kernel.requireService(IMarkdownShortCutService);++ mdService?.registerMarkdownWriter(LocalFileMentionNode.getType(), (ctx: any, node: any) => {+ if ($isLocalFileMentionNode(node)) {+ const name = escapeXmlAttr(node.name);+ const path = escapeXmlAttr(node.path);+ const isDirectory = node.isDirectory ? ' isDirectory' : '';+ ctx.appendLine(`<localFile name="${name}" path="${path}"${isDirectory} />`);+ }+ });+ }++ private registerCommand(editor: LexicalEditor): void {+ editor.registerCommand(+ INSERT_LOCAL_FILE_MENTION_COMMAND,+ (payload) => {+ editor.update(() => {+ const node = $createLocalFileMentionNode(+ payload.name,+ payload.path,+ !!payload.isDirectory,+ );+ // Trailing space so the user can keep typing without adding one manually.+ $insertNodes([node, $createTextNode(' ')]);+ if ($isRootOrShadowRoot(node.getParentOrThrow())) {+ $wrapNodeInElement(node, $createParagraphNode).selectEnd();+ }+ });+ return true;+ },+ COMMAND_PRIORITY_HIGH,+ );+ }++ private registerLiteXml(): void {+ const xmlService = this.kernel.requireService(ILitexmlService);++ xmlService?.registerXMLWriter(LocalFileMentionNode.getType(), (node: any, ctx: any) => {+ if ($isLocalFileMentionNode(node)) {+ return ctx.createXmlNode('localFileMention', {+ isDirectory: node.isDirectory ? 'true' : '',+ name: node.name,+ path: node.path,+ });+ }+ return false;+ });++ xmlService?.registerXMLReader('localFileMention', (xmlElement: any) => {+ return {+ isDirectory: xmlElement.getAttribute('isDirectory') === 'true',+ name: xmlElement.getAttribute('name') || '',+ path: xmlElement.getAttribute('path') || '',+ type: LocalFileMentionNode.getType(),+ version: 1,+ } satisfies SerializedLocalFileMentionNode;+ });+ }++ destroy(): void {+ this.kernel.unregisterDecorator?.(LocalFileMentionNode.getType());+ }+}diff --git a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionView.tsx b/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionView.tsxnew file mode 100644index 00000000000..c27177584ee--- /dev/null+++ b/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionView.tsx@@ -0,0 +1,46 @@+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';++import FileIcon from '@/components/FileIcon';++import { TAG_MARGIN_INLINE_END } from '../constants';++const styles = createStaticStyles(({ css }) => ({+ label: css`+ overflow: hidden;+ font-weight: 500;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ tag: css`+ cursor: default;+ user-select: none;++ display: inline-flex;+ gap: 3px;+ align-items: center;++ max-width: 240px;+ margin-inline-end: ${TAG_MARGIN_INLINE_END}px;+ padding-inline: 1px;++ color: ${cssVar.colorTextSecondary};+ vertical-align: baseline;+ `,+}));++export interface LocalFileMentionViewProps {+ isDirectory?: boolean;+ name: string;+}++export const LocalFileMentionView = memo<LocalFileMentionViewProps>(({ name, isDirectory }) => {+ return (+ <span className={styles.tag} title={name}>+ <FileIcon fileName={name} isDirectory={isDirectory} size={16} variant={'raw'} />+ <span className={styles.label}>{name}</span>+ </span>+ );+});++LocalFileMentionView.displayName = 'LocalFileMentionView';diff --git a/src/features/ChatInput/InputEditor/LocalFileMention/ReactLocalFileMentionPlugin.tsx b/src/features/ChatInput/InputEditor/LocalFileMention/ReactLocalFileMentionPlugin.tsxnew file mode 100644index 00000000000..691b041e486--- /dev/null+++ b/src/features/ChatInput/InputEditor/LocalFileMention/ReactLocalFileMentionPlugin.tsx@@ -0,0 +1,23 @@+import { useLexicalComposerContext } from '@lobehub/editor';+import { type FC, useLayoutEffect } from 'react';++import { LocalFileMentionPlugin } from './LocalFileMentionPlugin';+import { LocalFileMentionView } from './LocalFileMentionView';++const ReactLocalFileMentionPlugin: FC = () => {+ const [editor] = useLexicalComposerContext();++ useLayoutEffect(() => {+ editor.registerPlugin(LocalFileMentionPlugin, {+ decorator: (node) => {+ return <LocalFileMentionView isDirectory={node.isDirectory} name={node.name} />;+ },+ });+ }, [editor]);++ return null;+};++ReactLocalFileMentionPlugin.displayName = 'ReactLocalFileMentionPlugin';++export default ReactLocalFileMentionPlugin;diff --git a/src/features/ChatInput/InputEditor/LocalFileMention/index.ts b/src/features/ChatInput/InputEditor/LocalFileMention/index.tsnew file mode 100644index 00000000000..d8a8b2cdc84--- /dev/null+++ b/src/features/ChatInput/InputEditor/LocalFileMention/index.ts@@ -0,0 +1,11 @@+export {+ $createLocalFileMentionNode,+ $isLocalFileMentionNode,+ LocalFileMentionNode,+ type SerializedLocalFileMentionNode,+} from './LocalFileMentionNode';+export {+ INSERT_LOCAL_FILE_MENTION_COMMAND,+ type InsertLocalFileMentionPayload,+} from './LocalFileMentionPlugin';+export { default as ReactLocalFileMentionPlugin } from './ReactLocalFileMentionPlugin';diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsxindex db75ef5620c..2e09918c984 100644--- a/src/features/ChatInput/InputEditor/index.test.tsx+++ b/src/features/ChatInput/InputEditor/index.test.tsx@@ -214,6 +214,9 @@ vi.mock('./plugins', () => ({createChatInputRichPlugins: () => [],}));vi.mock('./ReferTopic', () => ({ INSERT_REFER_TOPIC_COMMAND: 'insert-refer-topic' }));+vi.mock('./LocalFileMention', () => ({+ INSERT_LOCAL_FILE_MENTION_COMMAND: 'insert-local-file-mention',+}));vi.mock('./useLocalFileMention', () => ({useLocalFileMention: () => ({enableLocalFileMention: false,diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 97e1746f64c..a326fd81ad8 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -3,7 +3,6 @@ import { HotkeyEnum, KeyEnum } from '@lobechat/const/hotkeys';import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import {chainInputCompletion,- escapeXmlAttr,INPUT_COMPLETION_PROMPT_VERSION,INPUT_COMPLETION_SCHEMA_NAME,} from '@lobechat/prompts';@@ -46,6 +45,7 @@ import {} from './ActionTag';import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';import InputHistoryPopup, { getHistoryPreviewText } from './InputHistoryPopup';+import { INSERT_LOCAL_FILE_MENTION_COMMAND } from './LocalFileMention';import { mentionFilledClassName } from './mentionStyle';import Placeholder, { type PlaceholderVariant } from './Placeholder';import { CHAT_INPUT_EMBED_PLUGINS, createChatInputRichPlugins } from './plugins';@@ -435,13 +435,9 @@ const InputEditor = memo<{if (mention.metadata?.type === 'topic') {return `<refer_topic name="${mention.metadata.topicTitle}" id="${mention.metadata.topicId}" />`;}- if (mention.metadata?.type === 'localFile') {- const name = escapeXmlAttr(String(mention.metadata.name ?? mention.label));- const path = escapeXmlAttr(String(mention.metadata.path ?? ''));- const isDirectory = mention.metadata.isDirectory ? ' isDirectory' : '';-- return `<localFile name="${name}" path="${path}"${isDirectory} />`;- }+ // localFile references are their own node (LocalFileMentionNode) and serialize+ // via that plugin's always-registered markdown writer β they never reach this+ // generic mention writer, which is only wired up when mentionOption is enabled.return `<mention name="${mention.label}" id="${mention.metadata.id}" />`;}, []);@@ -458,6 +454,12 @@ const InputEditor = memo<{type: String(option.metadata.actionType),};editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);+ } else if (option.metadata?.type === 'localFile') {+ editor.dispatchCommand(INSERT_LOCAL_FILE_MENTION_COMMAND, {+ isDirectory: !!option.metadata.isDirectory,+ name: String(option.metadata.name ?? option.label),+ path: String(option.metadata.path ?? ''),+ });} else {editor.dispatchCommand(INSERT_MENTION_COMMAND, {label: String(option.label),diff --git a/src/features/ChatInput/InputEditor/insertLocalFolderMentions.ts b/src/features/ChatInput/InputEditor/insertLocalFolderMentions.tsindex 929014e27fe..ffaf7f237e5 100644--- a/src/features/ChatInput/InputEditor/insertLocalFolderMentions.ts+++ b/src/features/ChatInput/InputEditor/insertLocalFolderMentions.ts@@ -1,16 +1,17 @@import type { IEditor } from '@lobehub/editor';-import { INSERT_MENTION_COMMAND } from '@lobehub/editor';-import { $getSelection, $isRangeSelection } from 'lexical';import type { DroppedFolder } from '@/components/DragUploadZone';+import { INSERT_LOCAL_FILE_MENTION_COMMAND } from './LocalFileMention';+/**- * Insert one localFile mention node per dropped folder at the editor's current- * selection, separating consecutive mentions with a space so they read as- * distinct tokens.+ * Insert one LocalFileMention node per dropped folder at the editor's current+ * selection. Each insert appends a trailing space (handled by the command) so+ * consecutive mentions read as distinct tokens and the user can keep typing.*- * Mirrors the metadata shape used by the `@`-menu local-file mention path so- * the markdownWriter in InputEditor renders `<localFile name="..." path="..." isDirectory />`.+ * Shares the LocalFileMention node with the `@`-menu and the working-sidebar+ * drag path, so every local-file reference renders as the same compact+ * icon + name chip and serializes to `<localFile name="β¦" path="β¦" isDirectory />`.*/export const insertLocalFolderMentions = (editor: IEditor, folders: DroppedFolder[]) => {if (folders.length === 0) return;@@ -18,31 +19,11 @@ export const insertLocalFolderMentions = (editor: IEditor, folders: DroppedFoldeconst lexicalEditor = editor.getLexicalEditor();lexicalEditor?.focus();- folders.forEach((folder, index) => {- if (index > 0) {- lexicalEditor?.update(() => {- const selection = $getSelection();- if ($isRangeSelection(selection)) {- selection.insertText(' ');- }- });- }- editor.dispatchCommand(INSERT_MENTION_COMMAND, {- label: folder.name,- metadata: {- isDirectory: true,- name: folder.name,- path: folder.path,- type: 'localFile',- },+ folders.forEach((folder) => {+ editor.dispatchCommand(INSERT_LOCAL_FILE_MENTION_COMMAND, {+ isDirectory: true,+ name: folder.name,+ path: folder.path,});});-- // Trailing space so the user can keep typing without manually adding one.- lexicalEditor?.update(() => {- const selection = $getSelection();- if ($isRangeSelection(selection)) {- selection.insertText(' ');- }- });};diff --git a/src/features/ChatInput/InputEditor/plugins.ts b/src/features/ChatInput/InputEditor/plugins.tsindex 28fac10ceaf..0f47199b76e 100644--- a/src/features/ChatInput/InputEditor/plugins.ts+++ b/src/features/ChatInput/InputEditor/plugins.ts@@ -11,6 +11,7 @@ import {import { type Editor } from '@lobehub/editor/react';import { ReactActionTagPlugin } from './ActionTag';+import { ReactLocalFileMentionPlugin } from './LocalFileMention';import { ReactReferTopicPlugin } from './ReferTopic';type EditorPlugins = NonNullable<Parameters<typeof Editor>[0]['plugins']>;@@ -23,6 +24,7 @@ interface CreateChatInputRichPluginsOptions {export const CHAT_INPUT_EMBED_PLUGINS: EditorPlugins = [ReactActionTagPlugin,ReactReferTopicPlugin,+ ReactLocalFileMentionPlugin,ReactMentionPlugin,];diff --git a/src/features/ChatInput/InputEditor/useWorkspaceFileDrop.ts b/src/features/ChatInput/InputEditor/useWorkspaceFileDrop.tsnew file mode 100644index 00000000000..7c35eb7bedd--- /dev/null+++ b/src/features/ChatInput/InputEditor/useWorkspaceFileDrop.ts@@ -0,0 +1,58 @@+import { WORKSPACE_FILE_DRAG_MIME } from '@lobechat/const';+import type React from 'react';+import { useCallback } from 'react';++import { useChatInputStore } from '../store';+import { INSERT_LOCAL_FILE_MENTION_COMMAND } from './LocalFileMention';+import { readWorkspaceFileDragData } from './workspaceFileDragData';++interface UseWorkspaceFileDropResult {+ onDragOver: (event: React.DragEvent) => void;+ onDrop: (event: React.DragEvent) => void;+}++/**+ * Handles file/folder rows dragged from the working sidebar tree into the chat+ * input. Reacts only to the custom {@link WORKSPACE_FILE_DRAG_MIME} payload, so+ * it never interferes with the file-upload drop zone (keyed off `Files`) or the+ * skill-chip drop (keyed off its own MIME).+ *+ * On drop it inserts a `LocalFileMention` node β the same compact icon+name chip+ * used by the `@`-menu and folder-drop paths. That node owns its+ * `<localFile β¦ />` markdown writer via an always-registered plugin, so the drop+ * serializes correctly even when the generic `mentionOption` writer is disabled+ * (e.g. the web client with no other mention categories).+ */+export const useWorkspaceFileDrop = (): UseWorkspaceFileDropResult => {+ const editor = useChatInputStore((s) => s.editor);++ const onDragOver = useCallback((event: React.DragEvent) => {+ if (!event.dataTransfer.types.includes(WORKSPACE_FILE_DRAG_MIME)) return;+ // preventDefault marks this element as a valid drop target.+ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ }, []);++ const onDrop = useCallback(+ (event: React.DragEvent) => {+ if (!event.dataTransfer.types.includes(WORKSPACE_FILE_DRAG_MIME)) return;+ const payload = readWorkspaceFileDragData(event.dataTransfer);+ if (!payload) return;++ event.preventDefault();+ event.stopPropagation();++ if (!editor) return;++ editor.getLexicalEditor()?.focus();+ editor.dispatchCommand(INSERT_LOCAL_FILE_MENTION_COMMAND, {+ isDirectory: payload.isDirectory,+ name: payload.name,+ path: payload.path,+ });+ },+ [editor],+ );++ return { onDragOver, onDrop };+};diff --git a/src/features/ChatInput/InputEditor/workspaceFileDragData.test.ts b/src/features/ChatInput/InputEditor/workspaceFileDragData.test.tsnew file mode 100644index 00000000000..7e7e2b27f65--- /dev/null+++ b/src/features/ChatInput/InputEditor/workspaceFileDragData.test.ts@@ -0,0 +1,57 @@+import { WORKSPACE_FILE_DRAG_MIME } from '@lobechat/const';+import { describe, expect, it } from 'vitest';++import { readWorkspaceFileDragData, writeWorkspaceFileDragData } from './workspaceFileDragData';++describe('workspaceFileDragData', () => {+ it('round-trips a file payload through the custom MIME', () => {+ const dt = new DataTransfer();+ writeWorkspaceFileDragData(dt, {+ isDirectory: false,+ name: 'index.zh.mdx',+ path: '/repo/docs/index.zh.mdx',+ });++ expect(dt.types).toContain(WORKSPACE_FILE_DRAG_MIME);+ expect(dt.effectAllowed).toBe('copy');+ expect(readWorkspaceFileDragData(dt)).toEqual({+ isDirectory: false,+ name: 'index.zh.mdx',+ path: '/repo/docs/index.zh.mdx',+ });+ });++ it('preserves the isDirectory flag for folders', () => {+ const dt = new DataTransfer();+ writeWorkspaceFileDragData(dt, { isDirectory: true, name: 'docs', path: '/repo/docs' });+ expect(readWorkspaceFileDragData(dt)?.isDirectory).toBe(true);+ });++ it('returns undefined when the custom MIME is absent (no false trigger)', () => {+ const dt = new DataTransfer();+ dt.setData('text/plain', 'just text');+ expect(readWorkspaceFileDragData(dt)).toBeUndefined();+ });++ it('returns undefined for malformed payloads', () => {+ const dt = new DataTransfer();+ dt.setData(WORKSPACE_FILE_DRAG_MIME, '{ not json');+ expect(readWorkspaceFileDragData(dt)).toBeUndefined();+ });++ it('rejects a payload without a path', () => {+ const dt = new DataTransfer();+ dt.setData(WORKSPACE_FILE_DRAG_MIME, JSON.stringify({ name: 'x' }));+ expect(readWorkspaceFileDragData(dt)).toBeUndefined();+ });++ it('falls back to the path when name is missing', () => {+ const dt = new DataTransfer();+ dt.setData(WORKSPACE_FILE_DRAG_MIME, JSON.stringify({ path: '/repo/a.ts' }));+ expect(readWorkspaceFileDragData(dt)).toEqual({+ isDirectory: false,+ name: '/repo/a.ts',+ path: '/repo/a.ts',+ });+ });+});diff --git a/src/features/ChatInput/InputEditor/workspaceFileDragData.ts b/src/features/ChatInput/InputEditor/workspaceFileDragData.tsnew file mode 100644index 00000000000..8b1bd5058b5--- /dev/null+++ b/src/features/ChatInput/InputEditor/workspaceFileDragData.ts@@ -0,0 +1,173 @@+import { WORKSPACE_FILE_DRAG_MIME } from '@lobechat/const';+import { cssVar } from 'antd-style';+import type React from 'react';++/**+ * Payload serialized into the drag `dataTransfer` when a file/folder row is+ * dragged out of the working sidebar tree. Mirrors the `localFile` mention+ * metadata so the drop handler can dispatch `INSERT_MENTION_COMMAND` directly.+ */+export interface WorkspaceFileDragPayload {+ isDirectory: boolean;+ /** Display name (basename) shown on the mention chip. */+ name: string;+ /** Absolute path on the working device's filesystem. */+ path: string;+}++/**+ * Write only our custom MIME β no `text/plain` fallback. The Lexical chat input+ * reacts to `text/plain` drops and would race with the drop handler. Mark the+ * drag as `copy` so the input can accept it even though the source tree is not a+ * reorder target (the working files panel has no `onMove`).+ */+export const writeWorkspaceFileDragData = (+ dataTransfer: DataTransfer,+ payload: WorkspaceFileDragPayload,+): void => {+ dataTransfer.setData(WORKSPACE_FILE_DRAG_MIME, JSON.stringify(payload));+ dataTransfer.effectAllowed = 'copy';+};++export const readWorkspaceFileDragData = (+ dataTransfer: DataTransfer,+): WorkspaceFileDragPayload | undefined => {+ const raw = dataTransfer.getData(WORKSPACE_FILE_DRAG_MIME);+ if (!raw) return undefined;++ try {+ const parsed = JSON.parse(raw) as Partial<WorkspaceFileDragPayload>;+ if (!parsed || typeof parsed.path !== 'string' || parsed.path.length === 0) {+ return undefined;+ }+ return {+ isDirectory: !!parsed.isDirectory,+ name: typeof parsed.name === 'string' && parsed.name ? parsed.name : parsed.path,+ path: parsed.path,+ };+ } catch {+ return undefined;+ }+};++/**+ * Resolve a `var(--x)` reference (e.g. from antd-style `cssVar.*`) to its+ * concrete computed value in the context of `ctx`. Lets the drag preview live on+ * `document.body` (free of transformed ancestors that would break fixed-position+ * cursor tracking) while still picking up the themed token. Mirrors the skill+ * drag chip in `ActionTag/skillDragData.ts`.+ */+const resolveCssVar = (ref: string, ctx: Element): string => {+ const name = /var\((--[^\s),]+)/.exec(ref)?.[1];+ if (!name) return ref;+ return getComputedStyle(ctx).getPropertyValue(name).trim() || ref;+};++/** Vertical gap between the cursor and the bottom of the floating chip. */+const DRAG_GAP = 0;++const dragTransform = (x: number, y: number) =>+ `translate(${x}px, ${y}px) translate(-50%, calc(-100% - ${DRAG_GAP}px))`;++// Inline lucide `File` / `Folder` glyphs so the preview never depends on cloning+// the pierre/trees row icon out of its shadow DOM.+const FILE_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"/>';+const FOLDER_ICON_SVG =+ '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>';++const buildIconSvg = (isDirectory: boolean, color: string): SVGElement => {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ svg.setAttribute('width', '16');+ svg.setAttribute('height', '16');+ svg.setAttribute('viewBox', '0 0 24 24');+ svg.setAttribute('fill', 'none');+ svg.setAttribute('stroke', color);+ svg.setAttribute('stroke-width', '2');+ svg.setAttribute('stroke-linecap', 'round');+ svg.setAttribute('stroke-linejoin', 'round');+ svg.style.flexShrink = '0';+ svg.innerHTML = isDirectory ? FOLDER_ICON_SVG : FILE_ICON_SVG;+ return svg;+};++/**+ * Render a custom "icon + name" chip that follows the cursor during a+ * workspace-file drag, matching the skill drag preview. Suppresses the browser's+ * native drag image (a bitmap the OS draws with its own shadow) via an invisible+ * 1Γ1 ghost, then tracks the cursor through the document-level `dragover` event+ * (`drag` reports 0,0 in Chromium).+ */+const setWorkspaceFileDragImage = (+ event: React.DragEvent,+ payload: WorkspaceFileDragPayload,+): void => {+ if (typeof document === 'undefined') return;++ const host = event.currentTarget as Element;++ const ghost = document.createElement('div');+ Object.assign(ghost.style, {+ height: '1px',+ left: '-9999px',+ opacity: '0',+ position: 'fixed',+ top: '-9999px',+ width: '1px',+ });+ document.body.append(ghost);+ event.dataTransfer.setDragImage(ghost, 0, 0);++ const preview = document.createElement('div');+ Object.assign(preview.style, {+ alignItems: 'center',+ background: resolveCssVar(cssVar.colorBgElevated, host),+ border: `1px solid ${resolveCssVar(cssVar.colorBorderSecondary, host)}`,+ borderRadius: '10px',+ color: resolveCssVar(cssVar.colorText, host),+ display: 'inline-flex',+ fontSize: '13px',+ gap: '8px',+ left: '0',+ lineHeight: '1',+ maxWidth: '280px',+ padding: '8px 14px',+ pointerEvents: 'none',+ position: 'fixed',+ top: '0',+ transform: dragTransform(event.clientX, event.clientY),+ whiteSpace: 'nowrap',+ zIndex: '9999',+ });++ preview.append(buildIconSvg(payload.isDirectory, resolveCssVar(cssVar.colorTextTertiary, host)));++ const text = document.createElement('span');+ text.textContent = payload.name;+ text.style.overflow = 'hidden';+ text.style.textOverflow = 'ellipsis';+ preview.append(text);++ document.body.append(preview);++ const move = (e: DragEvent) => {+ preview.style.transform = dragTransform(e.clientX, e.clientY);+ };+ const cleanup = () => {+ document.removeEventListener('dragover', move);+ preview.remove();+ ghost.remove();+ };++ document.addEventListener('dragover', move);+ host.addEventListener('dragend', cleanup as EventListener, { once: true });+};++/** Start a workspace-file drag: write the payload and swap in the custom chip. */+export const startWorkspaceFileDrag = (+ event: React.DragEvent,+ payload: WorkspaceFileDragPayload,+): void => {+ writeWorkspaceFileDragData(event.dataTransfer, payload);+ setWorkspaceFileDragImage(event, payload);+};diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsxindex 02238b6eb18..9717f30d0c5 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/index.tsx@@ -6,10 +6,12 @@ import type { MenuProps } from 'antd';import { message } from 'antd';import { createStaticStyles } from 'antd-style';import { FileIcon } from 'lucide-react';+import type { DragEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import { startWorkspaceFileDrag } from '@/features/ChatInput/InputEditor/workspaceFileDragData';import type { ExplorerTreeNode } from '@/features/ExplorerTree';import {ExplorerTree,@@ -245,6 +247,22 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {[openNode],);+ // Dragging a row into the chat input inserts a `<localFile />` mention instead+ // of uploading it. We stamp a custom MIME on dragstart; the input's+ // useWorkspaceFileDrop reads it. The panel has no onMove, so overriding the+ // drag effect here can't disturb any internal reorder behaviour.+ const handleNodeDragStart = useCallback(+ (node: ExplorerTreeNode<ProjectFileIndexEntry>, event: DragEvent<HTMLElement>) => {+ if (!node.data) return;+ startWorkspaceFileDrag(event, {+ isDirectory: !!node.isFolder,+ name: node.data.name,+ path: node.data.path,+ });+ },+ [],+ );+const getContextMenuItems = useCallback((node: ExplorerTreeNode<ProjectFileIndexEntry>): MenuProps['items'] => {if (!node.data) return [];@@ -359,6 +377,7 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {unsafeCSS={FILE_TREE_UNSAFE_CSS}onExpandedChange={setExpandedIds}onNodeClick={handleNodeClick}+ onNodeDragStart={handleNodeDragStart}/></div>)}