Skip to content

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

🐛 fix(desktop): reference local paths on drag (#15899)

Arvin Xu1dbcacd0e98f
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index 105160f2049..f28520d5d72 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -5,9 +5,11 @@
"DragUpload.dragDesc": "Drag and drop files here to upload multiple images.",
"DragUpload.dragFileDesc": "Drag and drop images and files here to upload multiple images and files.",
"DragUpload.dragFileTitle": "Upload Files",
- "DragUpload.dragFolderDesc": "Drop the folder to reference it as @mention in the chat input.",
+ "DragUpload.dragFolderDesc": "Drop the folder to reference it in the chat input.",
"DragUpload.dragFolderTitle": "Reference Folder",
- "DragUpload.dragMixedDesc": "Folders are inserted as @mentions; files are uploaded.",
+ "DragUpload.dragLocalPathDesc": "Drop files or folders to reference their local paths in the chat input.",
+ "DragUpload.dragLocalPathTitle": "Reference Local Paths",
+ "DragUpload.dragMixedDesc": "Folders are inserted as references; files are uploaded.",
"DragUpload.dragMixedTitle": "Reference Folder & Upload Files",
"DragUpload.dragTitle": "Upload Images",
"FileManager.actions.addToLibrary": "Add to Library",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index b62dd7b34fd..a54db582638 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -5,9 +5,11 @@
"DragUpload.dragDesc": "拖拽文件到这里,支持上传多个图片。",
"DragUpload.dragFileDesc": "拖拽图片和文件到这里,支持上传多个图片和文件。",
"DragUpload.dragFileTitle": "上传文件",
- "DragUpload.dragFolderDesc": "释放文件夹,将以 @mention 方式插入到输入框中。",
+ "DragUpload.dragFolderDesc": "释放文件夹,将其引用到输入框中。",
"DragUpload.dragFolderTitle": "引用文件夹",
- "DragUpload.dragMixedDesc": "文件夹将作为 @mention 插入,文件将上传。",
+ "DragUpload.dragLocalPathDesc": "释放文件或文件夹,将其本地路径引用到输入框中。",
+ "DragUpload.dragLocalPathTitle": "引用本地路径",
+ "DragUpload.dragMixedDesc": "文件夹将作为引用插入,文件将上传。",
"DragUpload.dragMixedTitle": "引用文件夹 & 上传文件",
"DragUpload.dragTitle": "上传图片",
"FileManager.actions.addToLibrary": "添加到资料库",
diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.ts
index 1d0a8a46d3b..621da9981e2 100644
--- a/packages/locales/src/default/components.ts
+++ b/packages/locales/src/default/components.ts
@@ -6,9 +6,12 @@ export default {
'DragUpload.dragFileDesc':
'Drag and drop images and files here to upload multiple images and files.',
'DragUpload.dragFileTitle': 'Upload Files',
- 'DragUpload.dragFolderDesc': 'Drop the folder to reference it as @mention in the chat input.',
+ 'DragUpload.dragFolderDesc': 'Drop the folder to reference it in the chat input.',
'DragUpload.dragFolderTitle': 'Reference Folder',
- 'DragUpload.dragMixedDesc': 'Folders are inserted as @mentions; files are uploaded.',
+ 'DragUpload.dragLocalPathDesc':
+ 'Drop files or folders to reference their local paths in the chat input.',
+ 'DragUpload.dragLocalPathTitle': 'Reference Local Paths',
+ 'DragUpload.dragMixedDesc': 'Folders are inserted as references; files are uploaded.',
'DragUpload.dragMixedTitle': 'Reference Folder & Upload Files',
'DragUpload.dragTitle': 'Upload Images',
'FileManager.actions.addToLibrary': 'Add to Library',
diff --git a/src/components/DragUploadZone/index.tsx b/src/components/DragUploadZone/index.tsx
index f330af8c80a..fab83113601 100644
--- a/src/components/DragUploadZone/index.tsx
+++ b/src/components/DragUploadZone/index.tsx
@@ -8,21 +8,37 @@ import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useDragUploadContext } from './DragUploadProvider';
-import { type DroppedFolder, useLocalDragUpload } from './useLocalDragUpload';
+import { type DroppedLocalPath, useLocalDragUpload } from './useLocalDragUpload';
const BLOCK_SIZE = 48;
const ICON_SIZE = { size: 28, strokeWidth: 1.5 };
+const OVERLAY_INSET = 28;
+
+const DEFAULT_TONE = {
+ iconColor: `color-mix(in srgb, ${cssVar.geekblue} 95%, black)`,
+ iconStrongBg: `color-mix(in srgb, ${cssVar.geekblue} 38%, white)`,
+ iconSoftBg: `color-mix(in srgb, ${cssVar.geekblue} 68%, white)`,
+};
+
+const LOCAL_PATH_TONE = {
+ iconColor: `color-mix(in srgb, ${cssVar.purple} 82%, black)`,
+ iconStrongBg: `color-mix(in srgb, ${cssVar.purple} 36%, white)`,
+ iconSoftBg: `color-mix(in srgb, ${cssVar.purple} 64%, white)`,
+};
const styles = createStaticStyles(({ css }) => ({
container: css`
position: relative;
`,
content: css`
+ position: relative;
+ z-index: 1;
+
+ box-sizing: border-box;
width: 100%;
height: 100%;
- padding: 12px;
- border: 1.5px dashed #fff;
- border-radius: ${cssVar.borderRadiusLG};
+ padding-block: 32px 24px;
+ padding-inline: 28px;
`,
desc: css`
font-size: 12px;
@@ -31,8 +47,6 @@ const styles = createStaticStyles(({ css }) => ({
`,
icon: css`
border-radius: ${cssVar.borderRadiusSM};
- color: color-mix(in srgb, ${cssVar.geekblue} 95%, black);
- background: color-mix(in srgb, ${cssVar.geekblue} 38%, white);
`,
iconGroup: css`
margin-block-start: -32px;
@@ -53,9 +67,29 @@ const styles = createStaticStyles(({ css }) => ({
transition: all 0.2s ease-in-out;
`,
overlayContent: css`
- padding: ${cssVar.borderRadiusLG};
- border-radius: 12px;
+ position: relative;
+
+ min-width: min(640px, 72vw);
+ padding: ${OVERLAY_INSET}px;
+ border-radius: 16px;
+
background: ${cssVar.geekblue};
+ box-shadow: 0 16px 48px color-mix(in srgb, ${cssVar.geekblue} 32%, transparent);
+
+ &::before {
+ pointer-events: none;
+ content: '';
+
+ position: absolute;
+ inset: ${OVERLAY_INSET}px;
+
+ border: 1.5px dashed #fff;
+ border-radius: ${cssVar.borderRadiusLG};
+ }
+ `,
+ overlayContentLocalPath: css`
+ background: color-mix(in srgb, ${cssVar.purple} 82%, ${cssVar.geekblue});
+ box-shadow: 0 16px 48px color-mix(in srgb, ${cssVar.purple} 32%, transparent);
`,
title: css`
font-size: 16px;
@@ -83,15 +117,16 @@ export interface DragUploadZoneProps {
*/
enabledFiles?: boolean;
/**
- * Whether dropping a folder should route to onLocalFolders (as @mention) instead
- * of being flattened and uploaded. Requires Electron (uses webUtils to resolve
- * folder paths). Files in a mixed drop continue to flow through onUploadFiles.
+ * Whether dropping local files/folders should insert their filesystem paths
+ * into the chat input instead of uploading them. Requires Electron (uses
+ * webUtils to resolve paths). Unresolved items fall back to upload.
*/
- enableLocalFolderMention?: boolean;
+ enableLocalPathReference?: boolean;
/**
- * Callback when top-level folders are dropped and enableLocalFolderMention is on.
+ * Callback when top-level local files/folders are dropped and local path
+ * reference mode is on.
*/
- onLocalFolders?: (folders: DroppedFolder[]) => void | Promise<void>;
+ onLocalPaths?: (paths: DroppedLocalPath[]) => void | Promise<void>;
/**
* Callback when files are dropped
*/
@@ -112,8 +147,8 @@ const DragUploadZone = memo<DragUploadZoneProps>(
className,
disabled = false,
enabledFiles = true,
- enableLocalFolderMention = false,
- onLocalFolders,
+ enableLocalPathReference = false,
+ onLocalPaths,
overlayMinHeight = 160,
onUploadFiles,
style,
@@ -126,25 +161,33 @@ const DragUploadZone = memo<DragUploadZoneProps>(
// Local drop handler - only handles drop events
const { getContainerProps } = useLocalDragUpload({
disabled,
- enableLocalFolderMention,
- onLocalFolders,
+ enableLocalPathReference,
+ onLocalPaths,
onUploadFiles,
});
// Show overlay when files are being dragged anywhere on the page
const showOverlay = isDraggingGlobally && !disabled;
+ const isLocalPathReferenceOverlay = enableLocalPathReference && dragContentKind !== 'none';
- // When local folder mention is on AND dragged content includes a folder,
- // surface a folder-aware hint instead of the default upload hint.
+ // Local path reference mode has distinct copy and tone so users can tell it
+ // will insert filesystem references rather than upload files.
const overlayCopy = useMemo(() => {
- if (enableLocalFolderMention && dragContentKind === 'folders') {
+ if (isLocalPathReferenceOverlay) {
+ return {
+ desc: t('DragUpload.dragLocalPathDesc'),
+ showFolderIcon: dragContentKind === 'folders',
+ title: t('DragUpload.dragLocalPathTitle'),
+ };
+ }
+ if (dragContentKind === 'folders') {
return {
desc: t('DragUpload.dragFolderDesc'),
showFolderIcon: true,
title: t('DragUpload.dragFolderTitle'),
};
}
- if (enableLocalFolderMention && dragContentKind === 'mixed') {
+ if (dragContentKind === 'mixed') {
return {
desc: t('DragUpload.dragMixedDesc'),
showFolderIcon: true,
@@ -156,14 +199,29 @@ const DragUploadZone = memo<DragUploadZoneProps>(
showFolderIcon: false,
title: t(enabledFiles ? 'DragUpload.dragFileTitle' : 'DragUpload.dragTitle'),
};
- }, [dragContentKind, enableLocalFolderMention, enabledFiles, t]);
+ }, [dragContentKind, enabledFiles, isLocalPathReferenceOverlay, t]);
+
+ const overlayIcons = useMemo(() => {
+ if (isLocalPathReferenceOverlay && dragContentKind === 'mixed') {
+ return [FolderIcon, FileUpIcon, FileText];
+ }
+ if (overlayCopy.showFolderIcon) return [FolderIcon, FolderIcon, FolderIcon];
+ return [FileImage, FileUpIcon, FileText];
+ }, [dragContentKind, isLocalPathReferenceOverlay, overlayCopy.showFolderIcon]);
+ const tone = isLocalPathReferenceOverlay ? LOCAL_PATH_TONE : DEFAULT_TONE;
return (
<div className={cx(styles.container, className)} style={style} {...getContainerProps()}>
{children}
{showOverlay && (
<div className={styles.overlay}>
- <div className={styles.overlayContent} style={{ minHeight: overlayMinHeight }}>
+ <div
+ style={{ minHeight: overlayMinHeight }}
+ className={cx(
+ styles.overlayContent,
+ isLocalPathReferenceOverlay && styles.overlayContentLocalPath,
+ )}
+ >
<Center className={styles.content} gap={8}>
<Flexbox horizontal className={styles.iconGroup}>
<Center
@@ -171,42 +229,37 @@ const DragUploadZone = memo<DragUploadZoneProps>(
height={BLOCK_SIZE * 1.2}
width={BLOCK_SIZE}
style={{
- background: `color-mix(in srgb, ${cssVar.geekblue} 68%, white)`,
+ background: tone.iconSoftBg,
+ color: tone.iconColor,
transform: 'rotateZ(-20deg) translateX(8px)',
}}
>
- <Icon
- icon={overlayCopy.showFolderIcon ? FolderIcon : FileImage}
- size={ICON_SIZE}
- />
+ <Icon icon={overlayIcons[0]} size={ICON_SIZE} />
</Center>
<Center
className={styles.icon}
height={BLOCK_SIZE * 1.2}
width={BLOCK_SIZE}
style={{
+ background: tone.iconStrongBg,
+ color: tone.iconColor,
transform: 'translateY(-10px)',
zIndex: 1,
}}
>
- <Icon
- icon={overlayCopy.showFolderIcon ? FolderIcon : FileUpIcon}
- size={ICON_SIZE}
- />
+ <Icon icon={overlayIcons[1]} size={ICON_SIZE} />
</Center>
<Center
className={styles.icon}
height={BLOCK_SIZE * 1.2}
width={BLOCK_SIZE}
style={{
- background: `color-mix(in srgb, ${cssVar.geekblue} 68%, white)`,
+ background: tone.iconSoftBg,
+ color: tone.iconColor,
transform: 'rotateZ(20deg) translateX(-8px)',
}}
>
- <Icon
- icon={overlayCopy.showFolderIcon ? FolderIcon : FileText}
- size={ICON_SIZE}
- />
+ <Icon icon={overlayIcons[2]} size={ICON_SIZE} />
</Center>
</Flexbox>
<Flexbox align={'center'} gap={4} style={{ textAlign: 'center' }}>
@@ -224,7 +277,7 @@ const DragUploadZone = memo<DragUploadZoneProps>(
DragUploadZone.displayName = 'DragUploadZone';
-export type { DroppedFolder } from './useLocalDragUpload';
+export type { DroppedLocalPath } from './useLocalDragUpload';
export { usePasteFile } from './usePasteFile';
export { useUploadFiles } from './useUploadFiles';
export default DragUploadZone;
diff --git a/src/components/DragUploadZone/useLocalDragUpload.test.ts b/src/components/DragUploadZone/useLocalDragUpload.test.ts
index 2ca77d34d5a..484e005265d 100644
--- a/src/components/DragUploadZone/useLocalDragUpload.test.ts
+++ b/src/components/DragUploadZone/useLocalDragUpload.test.ts
@@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
detectDragContentKind,
- type DroppedFolder,
- partitionDroppedItems,
+ type DroppedLocalPath,
+ partitionDroppedItemsAsLocalPaths,
} from './useLocalDragUpload';
type EntryShape = { isDirectory: boolean; isFile: boolean; name?: string };
@@ -63,7 +63,7 @@ describe('detectDragContentKind', () => {
});
});
-describe('partitionDroppedItems', () => {
+describe('partitionDroppedItemsAsLocalPaths', () => {
const originalElectron = (globalThis as any).window?.electron;
beforeEach(() => {
@@ -83,7 +83,7 @@ describe('partitionDroppedItems', () => {
}
});
- it('routes top-level folders to the folders bucket with absolute paths', async () => {
+ it('routes top-level folders to the local paths bucket with absolute paths', async () => {
const folderFile = makeFile('my-folder');
const items = [
makeItem({
@@ -92,15 +92,15 @@ describe('partitionDroppedItems', () => {
}),
];
- const result = await partitionDroppedItems(items);
+ const result = await partitionDroppedItemsAsLocalPaths(items);
expect(result.files).toEqual([]);
- expect(result.folders).toEqual<DroppedFolder[]>([
- { name: 'my-folder', path: '/abs/my-folder' },
+ expect(result.localPaths).toEqual<DroppedLocalPath[]>([
+ { isDirectory: true, name: 'my-folder', path: '/abs/my-folder' },
]);
});
- it('routes top-level files to the files bucket', async () => {
+ it('routes top-level files to the local paths bucket with absolute paths', async () => {
const fileA = makeFile('a.txt');
const fileB = makeFile('b.txt');
const items = [
@@ -108,15 +108,16 @@ describe('partitionDroppedItems', () => {
makeItem({ entry: { isDirectory: false, isFile: true }, file: fileB }),
];
- const result = await partitionDroppedItems(items);
+ const result = await partitionDroppedItemsAsLocalPaths(items);
- expect(result.folders).toEqual([]);
- expect(result.files).toHaveLength(2);
- expect(result.files[0].name).toBe('a.txt');
- expect(result.files[1].name).toBe('b.txt');
+ expect(result.files).toEqual([]);
+ expect(result.localPaths).toEqual<DroppedLocalPath[]>([
+ { isDirectory: false, name: 'a.txt', path: '/abs/a.txt' },
+ { isDirectory: false, name: 'b.txt', path: '/abs/b.txt' },
+ ]);
});
- it('preserves drop order across mixed folders and files', async () => {
+ it('preserves drop order across mixed local paths', async () => {
const folderFile = makeFile('docs');
const file = makeFile('readme.md');
const items = [
@@ -127,10 +128,13 @@ describe('partitionDroppedItems', () => {
makeItem({ entry: { isDirectory: false, isFile: true }, file }),
];
- const result = await partitionDroppedItems(items);
+ const result = await partitionDroppedItemsAsLocalPaths(items);
- expect(result.folders).toEqual<DroppedFolder[]>([{ name: 'docs', path: '/abs/docs' }]);
- expect(result.files.map((f) => f.name)).toEqual(['readme.md']);
+ expect(result.files).toEqual([]);
+ expect(result.localPaths).toEqual<DroppedLocalPath[]>([
+ { isDirectory: true, name: 'docs', path: '/abs/docs' },
+ { isDirectory: false, name: 'readme.md', path: '/abs/readme.md' },
+ ]);
});
it('falls back to flattening a folder when Electron path resolution fails', async () => {
@@ -160,18 +164,30 @@ describe('partitionDroppedItems', () => {
}),
];
- const result = await partitionDroppedItems(items);
+ const result = await partitionDroppedItemsAsLocalPaths(items);
- expect(result.folders).toEqual([]);
+ expect(result.localPaths).toEqual([]);
expect(result.files.map((f) => f.name)).toEqual(['child.txt']);
});
+ it('falls back to uploading a file when Electron path resolution fails', async () => {
+ (globalThis as any).window.electron = undefined;
+
+ const file = makeFile('fallback.txt');
+ const items = [makeItem({ entry: { isDirectory: false, isFile: true }, file })];
+
+ const result = await partitionDroppedItemsAsLocalPaths(items);
+
+ expect(result.localPaths).toEqual([]);
+ expect(result.files.map((f) => f.name)).toEqual(['fallback.txt']);
+ });
+
it('skips items whose kind is not "file"', async () => {
const items = [makeItem({ kind: 'string', entry: { isDirectory: true, isFile: false } })];
- const result = await partitionDroppedItems(items);
+ const result = await partitionDroppedItemsAsLocalPaths(items);
- expect(result.folders).toEqual([]);
+ expect(result.localPaths).toEqual([]);
expect(result.files).toEqual([]);
});
});
diff --git a/src/components/DragUploadZone/useLocalDragUpload.ts b/src/components/DragUploadZone/useLocalDragUpload.ts
index 0ec9df4b390..637bbe33960 100644
--- a/src/components/DragUploadZone/useLocalDragUpload.ts
+++ b/src/components/DragUploadZone/useLocalDragUpload.ts
@@ -5,14 +5,15 @@ const log = debug('lobe-client:drag-upload:local');
export type DragContentKind = 'files' | 'folders' | 'mixed' | 'none';
-export interface DroppedFolder {
+export interface DroppedLocalPath {
+ isDirectory: boolean;
name: string;
path: string;
}
-export interface PartitionedDroppedItems {
+export interface PartitionedDroppedLocalPaths {
files: File[];
- folders: DroppedFolder[];
+ localPaths: DroppedLocalPath[];
}
/**
@@ -26,7 +27,7 @@ const resolveElectronFilePath = (file: File): string | null => {
}
).window?.electron?.webUtils;
if (!webUtils?.getPathForFile) {
- log('webUtils.getPathForFile unavailable on window.electron — folder path cannot be resolved');
+ log('webUtils.getPathForFile unavailable on window.electron — local path cannot be resolved');
return null;
}
try {
@@ -129,52 +130,51 @@ export const detectDragContentKind = (items: DataTransferItemList | null): DragC
};
/**
- * Partition dropped DataTransferItems into top-level folders (with absolute
- * filesystem paths via Electron's webUtils) and top-level files. Folders are
- * NOT recursed into — the caller is expected to treat them as mention targets.
+ * Partition dropped DataTransferItems into top-level local path references (with
+ * absolute filesystem paths via Electron's webUtils) and upload fallback files.
+ * Folders are NOT recursed into when their path resolves — the caller is
+ * expected to reference the folder itself.
*
- * When a folder is encountered without an Electron path (e.g. running in
- * browser), it is skipped from the folders list — callers may still fall back
- * to upload by inspecting unhandled items.
+ * When a path cannot be resolved (e.g. running in browser), the item falls back
+ * to upload. Directories are flattened so the user does not silently lose data.
*/
-export const partitionDroppedItems = async (
+export const partitionDroppedItemsAsLocalPaths = async (
items: DataTransferItem[],
-): Promise<PartitionedDroppedItems> => {
- const folders: DroppedFolder[] = [];
+): Promise<PartitionedDroppedLocalPaths> => {
const files: File[] = [];
+ const localPaths: DroppedLocalPath[] = [];
for (const item of items) {
if (item.kind !== 'file') continue;
const entry = safeGetEntry(item);
+ const topLevelFile = item.getAsFile();
+ const path = topLevelFile ? resolveElectronFilePath(topLevelFile) : null;
+
+ if (path) {
+ localPaths.push({
+ isDirectory: !!entry?.isDirectory,
+ name: topLevelFile?.name || entry?.name || path.split('/').pop() || path,
+ path,
+ });
+ continue;
+ }
if (entry?.isDirectory) {
- const directoryFile = item.getAsFile();
- const path = directoryFile ? resolveElectronFilePath(directoryFile) : null;
- if (path) {
- folders.push({
- name: directoryFile?.name || entry.name || path.split('/').pop() || path,
- path,
- });
- continue;
- }
- // Fallback (no Electron / no path): flatten the directory's files for
- // upload so the user isn't silently dropped.
const flattened = await processEntry(entry);
files.push(...flattened);
continue;
}
- const file = item.getAsFile();
- if (file) {
- files.push(file);
+ if (topLevelFile) {
+ files.push(topLevelFile);
} else if (entry) {
const flattened = await processEntry(entry);
files.push(...flattened);
}
}
- return { files, folders };
+ return { files, localPaths };
};
export interface UseLocalDragUploadOptions {
@@ -183,15 +183,16 @@ export interface UseLocalDragUploadOptions {
*/
disabled?: boolean;
/**
- * When true, top-level folders are routed to onLocalFolders instead of being
- * recursively flattened for upload. Top-level files still flow to onUploadFiles.
- * Requires Electron (uses webUtils.getPathForFile) to resolve folder paths.
+ * When true, top-level files and folders are routed to onLocalPaths instead of
+ * being uploaded. Requires Electron (uses webUtils.getPathForFile) to resolve
+ * absolute filesystem paths.
*/
- enableLocalFolderMention?: boolean;
+ enableLocalPathReference?: boolean;
/**
- * Callback for top-level dropped folders when enableLocalFolderMention is on.
+ * Callback for top-level dropped files and folders when local path reference
+ * mode is on.
*/
- onLocalFolders?: (folders: DroppedFolder[]) => void | Promise<void>;
+ onLocalPaths?: (paths: DroppedLocalPath[]) => void | Promise<void>;
/**
* Callback when files are dropped
*/
@@ -220,7 +221,7 @@ export interface UseLocalDragUploadResult {
export const useLocalDragUpload = (
options: UseLocalDragUploadOptions,
): UseLocalDragUploadResult => {
- const { onUploadFiles, disabled = false, enableLocalFolderMention, onLocalFolders } = options;
+ const { onUploadFiles, disabled = false, enableLocalPathReference, onLocalPaths } = options;
// Only preventDefault to allow drop, do NOT stopPropagation
const handleDragOver = useCallback(
@@ -247,11 +248,15 @@ export const useLocalDragUpload = (
const items = Array.from(e.dataTransfer.items);
- if (enableLocalFolderMention && onLocalFolders) {
- const { folders, files } = await partitionDroppedItems(items);
- log('drop partitioned: %d folder(s), %d file(s)', folders.length, files.length);
- if (folders.length > 0) {
- await onLocalFolders(folders);
+ if (enableLocalPathReference && onLocalPaths) {
+ const { localPaths, files } = await partitionDroppedItemsAsLocalPaths(items);
+ log(
+ 'drop partitioned: %d local path(s), %d upload fallback file(s)',
+ localPaths.length,
+ files.length,
+ );
+ if (localPaths.length > 0) {
+ await onLocalPaths(localPaths);
}
if (files.length > 0) {
await onUploadFiles(files);
@@ -259,12 +264,12 @@ export const useLocalDragUpload = (
return;
}
- log('drop without folder-mention path, uploading files only');
+ log('drop without local-path reference, uploading files only');
const files = await getFileListFromDataTransferItems(items);
if (files.length === 0) return;
await onUploadFiles(files);
},
- [disabled, enableLocalFolderMention, onLocalFolders, onUploadFiles],
+ [disabled, enableLocalPathReference, onLocalPaths, onUploadFiles],
);
const getContainerProps = useCallback(
diff --git a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionView.tsx b/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionView.tsx
deleted file mode 100644
index c27177584ee..00000000000
--- a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionView.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-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.tsx
deleted file mode 100644
index 691b041e486..00000000000
--- a/src/features/ChatInput/InputEditor/LocalFileMention/ReactLocalFileMentionPlugin.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-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.ts
deleted file mode 100644
index d8a8b2cdc84..00000000000
--- a/src/features/ChatInput/InputEditor/LocalFileMention/index.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-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/LocalFileTag/LocalFileTag.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
new file mode 100644
index 00000000000..a9a5d644e2d
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
@@ -0,0 +1,346 @@
+import { isDesktop } from '@lobechat/const';
+import { Flexbox, Icon, Popover, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import type { LexicalEditor } from 'lexical';
+import { $createNodeSelection, $setSelection, CLICK_COMMAND, COMMAND_PRIORITY_LOW } from 'lexical';
+import { ExternalLink, EyeIcon, FolderOpen } from 'lucide-react';
+import type { ComponentPropsWithRef, MouseEvent as ReactMouseEvent, ReactNode } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import FileIcon from '@/components/FileIcon';
+import { useClientDataSWR } from '@/libs/swr';
+import { localFileKeys } from '@/libs/swr/keys';
+import { localFileService } from '@/services/electron/localFileService';
+import type { LocalFilePreview } from '@/services/projectFile';
+import { projectFileService } from '@/services/projectFile';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import { parseLocalFileHref } from '../../../Conversation/Markdown/plugins/LocalFileLink/parse';
+import { TAG_MARGIN_INLINE_END } from '../constants';
+import { getFileExtension } from '../MentionMenu/localFileDisplay';
+
+const PREVIEWABLE_IMAGE_EXTENSIONS = new Set([
+ 'avif',
+ 'bmp',
+ 'gif',
+ 'ico',
+ 'jpeg',
+ 'jpg',
+ 'png',
+ 'svg',
+ 'webp',
+]);
+
+const styles = createStaticStyles(({ css }) => ({
+ actionBar: css`
+ flex-wrap: wrap;
+ max-width: 320px;
+ `,
+ label: css`
+ overflow: hidden;
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ path: css`
+ max-width: 360px;
+ padding-block: 8px;
+ padding-inline: 10px;
+ border-radius: ${cssVar.borderRadius};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextSecondary};
+ word-break: break-all;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ popover: css`
+ max-width: 392px;
+ `,
+ previewFrame: css`
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: min(360px, 72vw);
+ max-height: 240px;
+ border: 1px solid ${cssVar.colorFillSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ previewImage: css`
+ display: block;
+ max-width: 100%;
+ max-height: 240px;
+ object-fit: contain;
+ `,
+ tag: css`
+ cursor: default;
+ user-select: none;
+
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ max-width: 240px;
+ margin-inline-end: ${TAG_MARGIN_INLINE_END}px;
+ padding-inline: 2px;
+ border-radius: ${cssVar.borderRadius};
+
+ color: ${cssVar.colorInfo};
+ vertical-align: baseline;
+
+ &.selected {
+ outline: 2px solid ${cssVar.colorInfo};
+ outline-offset: 1px;
+ }
+ `,
+ thumbnail: css`
+ flex-shrink: 0;
+
+ width: 16px;
+ height: 16px;
+ border-radius: ${cssVar.borderRadiusXS};
+
+ object-fit: cover;
+ background: ${cssVar.colorFillQuaternary};
+ box-shadow: inset 0 0 0 1px ${cssVar.colorFillSecondary};
+ `,
+}));
+
+export interface LocalFileTagData {
+ isDirectory?: boolean;
+ name: string;
+ path: string;
+}
+
+export interface LocalFileTagProps {
+ className?: string;
+ editor?: LexicalEditor;
+ file: LocalFileTagData;
+ nodeKey?: string;
+}
+
+interface LocalFileTagTriggerProps extends Omit<
+ ComponentPropsWithRef<'span'>,
+ 'children' | 'className' | 'title'
+> {
+ children: ReactNode;
+ className?: string;
+ editor?: LexicalEditor;
+ nodeKey?: string;
+ title?: string;
+}
+
+const isPreviewableImageFile = (file: LocalFileTagData) =>
+ !file.isDirectory && PREVIEWABLE_IMAGE_EXTENSIONS.has(getFileExtension(file.name || file.path));
+
+const stopActionPropagation = (event: ReactMouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+};
+
+const LocalFileTagTrigger = memo<LocalFileTagTriggerProps>(
+ ({ children, className, editor, nodeKey, ref: forwardedRef, title, ...rest }) => {
+ const spanRef = useRef<HTMLSpanElement>(null);
+
+ const setSpanRef = useCallback(
+ (element: HTMLSpanElement | null) => {
+ spanRef.current = element;
+
+ if (!forwardedRef) return;
+ if (typeof forwardedRef === 'function') {
+ forwardedRef(element);
+ return;
+ }
+
+ const mutableRef = forwardedRef as { current: HTMLSpanElement | null };
+ mutableRef.current = element;
+ },
+ [forwardedRef],
+ );
+
+ const onClick = useCallback(
+ (payload: MouseEvent) => {
+ if (!editor || !nodeKey) return false;
+ if (
+ payload.target !== spanRef.current &&
+ !spanRef.current?.contains(payload.target as Node)
+ ) {
+ return false;
+ }
+
+ payload.preventDefault();
+ editor.update(() => {
+ const selection = $createNodeSelection();
+ selection.add(nodeKey);
+ $setSelection(selection);
+ });
+ return true;
+ },
+ [editor, nodeKey],
+ );
+
+ useEffect(() => {
+ if (!editor || !nodeKey) return;
+ return editor.registerCommand(CLICK_COMMAND, onClick, COMMAND_PRIORITY_LOW);
+ }, [editor, nodeKey, onClick]);
+
+ return (
+ <span {...rest} className={cx(styles.tag, className)} ref={setSpanRef} title={title}>
+ {children}
+ </span>
+ );
+ },
+);
+
+LocalFileTagTrigger.displayName = 'LocalFileTagTrigger';
+
+export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file, nodeKey }) => {
+ const { t } = useTranslation('chat');
+ const openLocalFile = useChatStore((s) => s.openLocalFile);
+ const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
+
+ const parsed = useMemo(
+ () => parseLocalFileHref(file.path, { workingDirectory }),
+ [file.path, workingDirectory],
+ );
+ const allowExternalFilePreview =
+ !!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);
+ const canPreview = isDesktop && !file.isDirectory && !!parsed;
+ const canRenderImagePreview = canPreview && isPreviewableImageFile(file);
+
+ const { data: imagePreview } = useClientDataSWR<LocalFilePreview>(
+ canRenderImagePreview && parsed
+ ? localFileKeys.preview({
+ accept: 'image',
+ allowExternalFile: allowExternalFilePreview || undefined,
+ filePath: parsed.filePath,
+ workingDirectory: parsed.workingDirectory,
+ })
+ : null,
+ () =>
+ projectFileService.getLocalFilePreview({
+ accept: 'image',
+ allowExternalFile: allowExternalFilePreview || undefined,
+ path: parsed!.filePath,
+ workingDirectory: parsed!.workingDirectory,
+ }),
+ { revalidateOnFocus: false },
+ );
+ const [imageSrc, setImageSrc] = useState<string>();
+
+ useEffect(() => {
+ if (!canRenderImagePreview || imagePreview?.type !== 'image') {
+ setImageSrc(undefined);
+ return;
+ }
+
+ const objectUrl = URL.createObjectURL(imagePreview.blob);
+ setImageSrc(objectUrl);
+
+ return () => {
+ URL.revokeObjectURL(objectUrl);
+ };
+ }, [canRenderImagePreview, imagePreview]);
+
+ const handlePreview = useCallback(
+ (event: ReactMouseEvent<HTMLElement>) => {
+ stopActionPropagation(event);
+ if (!parsed) return;
+
+ openLocalFile({
+ allowExternalFilePreview,
+ filePath: parsed.filePath,
+ workingDirectory: parsed.workingDirectory,
+ });
+ },
+ [allowExternalFilePreview, openLocalFile, parsed],
+ );
+
+ const handleOpen = useCallback(
+ (event: ReactMouseEvent<HTMLElement>) => {
+ stopActionPropagation(event);
+ void localFileService.openLocalFileOrFolder(file.path, !!file.isDirectory);
+ },
+ [file.isDirectory, file.path],
+ );
+
+ const handleReveal = useCallback(
+ (event: ReactMouseEvent<HTMLElement>) => {
+ stopActionPropagation(event);
+ void localFileService.openFileFolder(file.path);
+ },
+ [file.path],
+ );
+
+ const content = (
+ <Flexbox className={styles.popover} gap={10} onClick={(event) => event.stopPropagation()}>
+ {imageSrc && (
+ <div className={styles.previewFrame}>
+ <img
+ alt={file.name}
+ className={styles.previewImage}
+ data-testid="local-file-image-hover-preview"
+ draggable={false}
+ src={imageSrc}
+ />
+ </div>
+ )}
+ <Text className={styles.path}>{file.path}</Text>
+ {isDesktop && (
+ <Flexbox horizontal className={styles.actionBar} gap={6}>
+ {canPreview && (
+ <Button icon={<Icon icon={EyeIcon} />} size={'small'} onClick={handlePreview}>
+ {t('workingPanel.documents.preview')}
+ </Button>
+ )}
+ <Button icon={<Icon icon={ExternalLink} />} size={'small'} onClick={handleOpen}>
+ {t('workingPanel.files.open')}
+ </Button>
+ <Button icon={<Icon icon={FolderOpen} />} size={'small'} onClick={handleReveal}>
+ {t('workingPanel.files.showInSystem')}
+ </Button>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+
+ return (
+ <Popover content={content} styles={{ content: { padding: 8 } }} trigger={'hover'}>
+ <LocalFileTagTrigger
+ className={className}
+ editor={editor}
+ nodeKey={nodeKey}
+ title={file.path}
+ >
+ {imageSrc ? (
+ <img
+ alt=""
+ className={styles.thumbnail}
+ data-testid="local-file-image-preview"
+ draggable={false}
+ src={imageSrc}
+ />
+ ) : (
+ <FileIcon
+ fileName={file.name}
+ isDirectory={!!file.isDirectory}
+ size={16}
+ variant={'raw'}
+ />
+ )}
+ <span className={styles.label}>{file.name}</span>
+ </LocalFileTagTrigger>
+ </Popover>
+ );
+});
+
+LocalFileTag.displayName = 'LocalFileTag';
diff --git a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionNode.ts b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagNode.ts
similarity index 73%
rename from src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionNode.ts
rename to src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagNode.ts
index 380fabf2790..29487e99eb1 100644
--- a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionNode.ts
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagNode.ts
@@ -12,7 +12,7 @@ import {
type Spread,
} from 'lexical';
-export type SerializedLocalFileMentionNode = Spread<
+export type SerializedLocalFileTagNode = Spread<
{
isDirectory: boolean;
name: string;
@@ -28,21 +28,21 @@ export type SerializedLocalFileMentionNode = Spread<
* `@`) 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> {
+export class LocalFileTagNode extends DecoratorNode<any> {
__name: string;
__path: string;
__isDirectory: boolean;
static getType(): string {
- return 'local-file-mention';
+ return 'local-file-tag';
}
- static clone(node: LocalFileMentionNode): LocalFileMentionNode {
- return new LocalFileMentionNode(node.__name, node.__path, node.__isDirectory, node.__key);
+ static clone(node: LocalFileTagNode): LocalFileTagNode {
+ return new LocalFileTagNode(node.__name, node.__path, node.__isDirectory, node.__key);
}
- static importJSON(serializedNode: SerializedLocalFileMentionNode): LocalFileMentionNode {
- return $createLocalFileMentionNode(
+ static importJSON(serializedNode: SerializedLocalFileTagNode): LocalFileTagNode {
+ return $createLocalFileTagNode(
serializedNode.name,
serializedNode.path,
serializedNode.isDirectory,
@@ -78,7 +78,7 @@ export class LocalFileMentionNode extends DecoratorNode<any> {
createDOM(config: EditorConfig): HTMLElement {
const element = document.createElement('span');
- addClassNamesToElement(element, config.theme.localFileMention);
+ addClassNamesToElement(element, config.theme.localFileTag);
return element;
}
@@ -94,7 +94,7 @@ export class LocalFileMentionNode extends DecoratorNode<any> {
return false;
}
- exportJSON(): SerializedLocalFileMentionNode {
+ exportJSON(): SerializedLocalFileTagNode {
return {
...super.exportJSON(),
isDirectory: this.__isDirectory,
@@ -103,12 +103,12 @@ export class LocalFileMentionNode extends DecoratorNode<any> {
};
}
- updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedLocalFileMentionNode>): this {
+ updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedLocalFileTagNode>): this {
return super.updateFromJSON(serializedNode);
}
decorate(editor: LexicalEditor): any {
- const decorator = getKernelFromEditor(editor)?.getDecorator(LocalFileMentionNode.getType());
+ const decorator = getKernelFromEditor(editor)?.getDecorator(LocalFileTagNode.getType());
if (!decorator) return null;
if (typeof decorator === 'function') return decorator(this, editor);
return {
@@ -118,16 +118,16 @@ export class LocalFileMentionNode extends DecoratorNode<any> {
}
}
-export function $createLocalFileMentionNode(
+export function $createLocalFileTagNode(
name: string,
path: string,
isDirectory = false,
-): LocalFileMentionNode {
- return $applyNodeReplacement(new LocalFileMentionNode(name, path, isDirectory));
+): LocalFileTagNode {
+ return $applyNodeReplacement(new LocalFileTagNode(name, path, isDirectory));
}
-export function $isLocalFileMentionNode(
+export function $isLocalFileTagNode(
node: LexicalNode | null | undefined,
-): node is LocalFileMentionNode {
- return node instanceof LocalFileMentionNode;
+): node is LocalFileTagNode {
+ return node instanceof LocalFileTagNode;
}
diff --git a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionPlugin.ts b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.ts
similarity index 58%
rename from src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionPlugin.ts
rename to src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.ts
index 7a67069dfa7..f1e5828aeb3 100644
--- a/src/features/ChatInput/InputEditor/LocalFileMention/LocalFileMentionPlugin.ts
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTagPlugin.ts
@@ -16,31 +16,31 @@ import {
} from 'lexical';
import {
- $createLocalFileMentionNode,
- $isLocalFileMentionNode,
- LocalFileMentionNode,
- type SerializedLocalFileMentionNode,
-} from './LocalFileMentionNode';
+ $createLocalFileTagNode,
+ $isLocalFileTagNode,
+ LocalFileTagNode,
+ type SerializedLocalFileTagNode,
+} from './LocalFileTagNode';
-export interface InsertLocalFileMentionPayload {
+export interface InsertLocalFileTagPayload {
isDirectory?: boolean;
name: string;
path: string;
}
-export const INSERT_LOCAL_FILE_MENTION_COMMAND = createCommand<InsertLocalFileMentionPayload>(
- 'INSERT_LOCAL_FILE_MENTION_COMMAND',
+export const INSERT_LOCAL_FILE_TAG_COMMAND = createCommand<InsertLocalFileTagPayload>(
+ 'INSERT_LOCAL_FILE_TAG_COMMAND',
);
type IEditorKernel = ReturnType<typeof getKernelFromEditor>;
-export interface LocalFileMentionPluginOptions {
- decorator: (node: LocalFileMentionNode, editor: LexicalEditor) => any;
- theme?: { localFileMention?: string };
+export interface LocalFileTagPluginOptions {
+ decorator: (node: LocalFileTagNode, editor: LexicalEditor) => any;
+ theme?: { localFileTag?: string };
}
/**
- * Owns the `local-file-mention` node: its decorator, its `<localFile … />`
+ * Owns the `local-file-tag` 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
@@ -48,24 +48,24 @@ export interface LocalFileMentionPluginOptions {
* 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';
+export class LocalFileTagPlugin {
+ static pluginName = 'LocalFileTagPlugin';
- config?: LocalFileMentionPluginOptions;
+ config?: LocalFileTagPluginOptions;
private kernel: IEditorKernel;
- constructor(kernel: IEditorKernel, config?: LocalFileMentionPluginOptions) {
+ constructor(kernel: IEditorKernel, config?: LocalFileTagPluginOptions) {
this.kernel = kernel;
this.config = config;
- kernel.registerNodes([LocalFileMentionNode]);
+ kernel.registerNodes([LocalFileTagNode]);
if (config?.theme) {
kernel.registerThemes(config.theme);
}
- kernel.registerDecorator(LocalFileMentionNode.getType(), (node, editor) => {
- return config?.decorator ? config.decorator(node as LocalFileMentionNode, editor) : null;
+ kernel.registerDecorator(LocalFileTagNode.getType(), (node, editor) => {
+ return config?.decorator ? config.decorator(node as LocalFileTagNode, editor) : null;
});
}
@@ -78,8 +78,8 @@ export class LocalFileMentionPlugin {
private registerMarkdown(): void {
const mdService = this.kernel.requireService(IMarkdownShortCutService);
- mdService?.registerMarkdownWriter(LocalFileMentionNode.getType(), (ctx: any, node: any) => {
- if ($isLocalFileMentionNode(node)) {
+ mdService?.registerMarkdownWriter(LocalFileTagNode.getType(), (ctx: any, node: any) => {
+ if ($isLocalFileTagNode(node)) {
const name = escapeXmlAttr(node.name);
const path = escapeXmlAttr(node.path);
const isDirectory = node.isDirectory ? ' isDirectory' : '';
@@ -90,14 +90,10 @@ export class LocalFileMentionPlugin {
private registerCommand(editor: LexicalEditor): void {
editor.registerCommand(
- INSERT_LOCAL_FILE_MENTION_COMMAND,
+ INSERT_LOCAL_FILE_TAG_COMMAND,
(payload) => {
editor.update(() => {
- const node = $createLocalFileMentionNode(
- payload.name,
- payload.path,
- !!payload.isDirectory,
- );
+ const node = $createLocalFileTagNode(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())) {
@@ -113,10 +109,10 @@ export class LocalFileMentionPlugin {
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' : '',
+ xmlService?.registerXMLWriter(LocalFileTagNode.getType(), (node: any, ctx: any) => {
+ if ($isLocalFileTagNode(node)) {
+ return ctx.createXmlNode('localFile', {
+ ...(node.isDirectory ? { isDirectory: 'true' } : {}),
name: node.name,
path: node.path,
});
@@ -124,18 +120,23 @@ export class LocalFileMentionPlugin {
return false;
});
- xmlService?.registerXMLReader('localFileMention', (xmlElement: any) => {
+ const readLocalFile = (xmlElement: any) => {
return {
- isDirectory: xmlElement.getAttribute('isDirectory') === 'true',
+ isDirectory:
+ xmlElement.hasAttribute?.('isDirectory') ||
+ xmlElement.getAttribute('isDirectory') === 'true',
name: xmlElement.getAttribute('name') || '',
path: xmlElement.getAttribute('path') || '',
- type: LocalFileMentionNode.getType(),
+ type: LocalFileTagNode.getType(),
version: 1,
- } satisfies SerializedLocalFileMentionNode;
- });
+ } satisfies SerializedLocalFileTagNode;
+ };
+
+ xmlService?.registerXMLReader('localFile', readLocalFile);
+ xmlService?.registerXMLReader('localFileTag', readLocalFile);
}
destroy(): void {
- this.kernel.unregisterDecorator?.(LocalFileMentionNode.getType());
+ this.kernel.unregisterDecorator?.(LocalFileTagNode.getType());
}
}
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/ReactLocalFileTagPlugin.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/ReactLocalFileTagPlugin.tsx
new file mode 100644
index 00000000000..0053ed4f950
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/ReactLocalFileTagPlugin.tsx
@@ -0,0 +1,33 @@
+import { useLexicalComposerContext } from '@lobehub/editor';
+import { type FC, useLayoutEffect } from 'react';
+
+import { LocalFileTag } from './LocalFileTag';
+import { LocalFileTagPlugin } from './LocalFileTagPlugin';
+
+const ReactLocalFileTagPlugin: FC = () => {
+ const [editor] = useLexicalComposerContext();
+
+ useLayoutEffect(() => {
+ editor.registerPlugin(LocalFileTagPlugin, {
+ decorator: (node, lexicalEditor) => {
+ return (
+ <LocalFileTag
+ editor={lexicalEditor}
+ nodeKey={node.getKey()}
+ file={{
+ isDirectory: node.isDirectory,
+ name: node.name,
+ path: node.path,
+ }}
+ />
+ );
+ },
+ });
+ }, [editor]);
+
+ return null;
+};
+
+ReactLocalFileTagPlugin.displayName = 'ReactLocalFileTagPlugin';
+
+export default ReactLocalFileTagPlugin;
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/index.ts b/src/features/ChatInput/InputEditor/LocalFileTag/index.ts
new file mode 100644
index 00000000000..28064a7b7f8
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/index.ts
@@ -0,0 +1,11 @@
+export {
+ $createLocalFileTagNode,
+ $isLocalFileTagNode,
+ LocalFileTagNode,
+ type SerializedLocalFileTagNode,
+} from './LocalFileTagNode';
+export {
+ INSERT_LOCAL_FILE_TAG_COMMAND,
+ type InsertLocalFileTagPayload,
+} from './LocalFileTagPlugin';
+export { default as ReactLocalFileTagPlugin } from './ReactLocalFileTagPlugin';
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index 2e09918c984..e4d235441ea 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -214,12 +214,12 @@ 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('./LocalFileTag', () => ({
+ INSERT_LOCAL_FILE_TAG_COMMAND: 'insert-local-file-tag',
}));
-vi.mock('./useLocalFileMention', () => ({
- useLocalFileMention: () => ({
- enableLocalFileMention: false,
+vi.mock('./useLocalFileTag', () => ({
+ useLocalFileTag: () => ({
+ enableLocalFileTag: false,
searchLocalFiles: vi.fn(async () => []),
}),
}));
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index a326fd81ad8..744417c2653 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -45,12 +45,12 @@ import {
} from './ActionTag';
import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';
import InputHistoryPopup, { getHistoryPreviewText } from './InputHistoryPopup';
-import { INSERT_LOCAL_FILE_MENTION_COMMAND } from './LocalFileMention';
+import { INSERT_LOCAL_FILE_TAG_COMMAND } from './LocalFileTag';
import { mentionFilledClassName } from './mentionStyle';
import Placeholder, { type PlaceholderVariant } from './Placeholder';
import { CHAT_INPUT_EMBED_PLUGINS, createChatInputRichPlugins } from './plugins';
import { INSERT_REFER_TOPIC_COMMAND } from './ReferTopic';
-import { useLocalFileMention } from './useLocalFileMention';
+import { useLocalFileTag } from './useLocalFileTag';
import { useMentionCategories } from './useMentionCategories';
const className = cx(
@@ -139,7 +139,7 @@ const InputEditor = memo<{
(s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.type,
);
- const { enableLocalFileMention, searchLocalFiles } = useLocalFileMention();
+ const { enableLocalFileTag, searchLocalFiles } = useLocalFileTag();
const allMentionItems = useMemo(() => categories.flatMap((c) => c.items), [categories]);
const mentionSections = useMemo<ISlashSectionOption[]>(
@@ -211,7 +211,7 @@ const InputEditor = memo<{
[categories, fuse, mentionSections, searchLocalFiles, t],
);
- const enableMention = isMentionEnabled && (allMentionItems.length > 0 || enableLocalFileMention);
+ const enableMention = isMentionEnabled && (allMentionItems.length > 0 || enableLocalFileTag);
const heterogeneousName = heterogeneousType
? (HETEROGENEOUS_TYPE_LABELS[heterogeneousType] ?? heterogeneousType)
: undefined;
@@ -435,7 +435,7 @@ const InputEditor = memo<{
if (mention.metadata?.type === 'topic') {
return `<refer_topic name="${mention.metadata.topicTitle}" id="${mention.metadata.topicId}" />`;
}
- // localFile references are their own node (LocalFileMentionNode) and serialize
+ // localFile references are their own node (LocalFileTagNode) 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}" />`;
@@ -455,7 +455,7 @@ const InputEditor = memo<{
};
editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);
} else if (option.metadata?.type === 'localFile') {
- editor.dispatchCommand(INSERT_LOCAL_FILE_MENTION_COMMAND, {
+ editor.dispatchCommand(INSERT_LOCAL_FILE_TAG_COMMAND, {
isDirectory: !!option.metadata.isDirectory,
name: String(option.metadata.name ?? option.label),
path: String(option.metadata.path ?? ''),
diff --git a/src/features/ChatInput/InputEditor/insertLocalFileTags.test.ts b/src/features/ChatInput/InputEditor/insertLocalFileTags.test.ts
new file mode 100644
index 00000000000..bc420e99fad
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/insertLocalFileTags.test.ts
@@ -0,0 +1,97 @@
+import type { IEditor } from '@lobehub/editor';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { insertLocalPathTags } from './insertLocalFileTags';
+
+const {
+ dispatchCommandMock,
+ focusMock,
+ isRangeSelectionMock,
+ selectEndMock,
+ selectionRef,
+ updateMock,
+} = vi.hoisted(() => ({
+ dispatchCommandMock: vi.fn(),
+ focusMock: vi.fn(),
+ isRangeSelectionMock: vi.fn(),
+ selectEndMock: vi.fn(),
+ selectionRef: { current: null as unknown },
+ updateMock: vi.fn((fn: () => void) => fn()),
+}));
+
+vi.mock('lexical', () => ({
+ $getRoot: () => ({ selectEnd: selectEndMock }),
+ $getSelection: () => selectionRef.current,
+ $isRangeSelection: isRangeSelectionMock,
+}));
+
+vi.mock('./LocalFileTag', () => ({
+ INSERT_LOCAL_FILE_TAG_COMMAND: 'insert-local-file-tag',
+}));
+
+const createEditor = () =>
+ ({
+ dispatchCommand: dispatchCommandMock,
+ getLexicalEditor: () => ({
+ focus: focusMock,
+ update: updateMock,
+ }),
+ }) as unknown as IEditor;
+
+describe('insertLocalPathTags', () => {
+ beforeEach(() => {
+ dispatchCommandMock.mockClear();
+ focusMock.mockClear();
+ isRangeSelectionMock.mockReset();
+ selectEndMock.mockClear();
+ selectionRef.current = null;
+ updateMock.mockClear();
+ });
+
+ it('moves the cursor to the end when there is no range selection', () => {
+ isRangeSelectionMock.mockReturnValue(false);
+
+ insertLocalPathTags(createEditor(), [
+ { isDirectory: false, name: 'image.png', path: '/repo/image.png' },
+ { isDirectory: true, name: 'docs', path: '/repo/docs' },
+ ]);
+
+ expect(focusMock).toHaveBeenCalledTimes(1);
+ expect(updateMock).toHaveBeenCalledTimes(1);
+ expect(selectEndMock).toHaveBeenCalledTimes(1);
+ expect(dispatchCommandMock).toHaveBeenNthCalledWith(1, 'insert-local-file-tag', {
+ isDirectory: false,
+ name: 'image.png',
+ path: '/repo/image.png',
+ });
+ expect(dispatchCommandMock).toHaveBeenNthCalledWith(2, 'insert-local-file-tag', {
+ isDirectory: true,
+ name: 'docs',
+ path: '/repo/docs',
+ });
+ });
+
+ it('keeps the current selection when it is already a range selection', () => {
+ selectionRef.current = {};
+ isRangeSelectionMock.mockReturnValue(true);
+
+ insertLocalPathTags(createEditor(), [
+ { isDirectory: false, name: 'readme.md', path: '/repo/readme.md' },
+ ]);
+
+ expect(selectEndMock).not.toHaveBeenCalled();
+ expect(dispatchCommandMock).toHaveBeenCalledWith('insert-local-file-tag', {
+ isDirectory: false,
+ name: 'readme.md',
+ path: '/repo/readme.md',
+ });
+ });
+
+ it('does nothing for an empty path list', () => {
+ insertLocalPathTags(createEditor(), []);
+
+ expect(focusMock).not.toHaveBeenCalled();
+ expect(updateMock).not.toHaveBeenCalled();
+ expect(dispatchCommandMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/insertLocalFileTags.ts b/src/features/ChatInput/InputEditor/insertLocalFileTags.ts
new file mode 100644
index 00000000000..128a39e7069
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/insertLocalFileTags.ts
@@ -0,0 +1,36 @@
+import type { IEditor } from '@lobehub/editor';
+import { $getRoot, $getSelection, $isRangeSelection } from 'lexical';
+
+import type { DroppedLocalPath } from '@/components/DragUploadZone';
+
+import { INSERT_LOCAL_FILE_TAG_COMMAND } from './LocalFileTag';
+
+const ensureRangeSelection = (editor: IEditor) => {
+ const lexicalEditor = editor.getLexicalEditor();
+ lexicalEditor?.update(() => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) {
+ $getRoot().selectEnd();
+ }
+ });
+};
+
+/**
+ * Insert one LocalFileTag node per local path at the editor's current selection.
+ * The command appends a trailing space for each tag so the user can keep typing.
+ */
+export const insertLocalPathTags = (editor: IEditor, paths: DroppedLocalPath[]) => {
+ if (paths.length === 0) return;
+
+ const lexicalEditor = editor.getLexicalEditor();
+ lexicalEditor?.focus();
+ ensureRangeSelection(editor);
+
+ paths.forEach((item) => {
+ editor.dispatchCommand(INSERT_LOCAL_FILE_TAG_COMMAND, {
+ isDirectory: item.isDirectory,
+ name: item.name,
+ path: item.path,
+ });
+ });
+};
diff --git a/src/features/ChatInput/InputEditor/insertLocalFolderMentions.ts b/src/features/ChatInput/InputEditor/insertLocalFolderMentions.ts
deleted file mode 100644
index ffaf7f237e5..00000000000
--- a/src/features/ChatInput/InputEditor/insertLocalFolderMentions.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { IEditor } from '@lobehub/editor';
-
-import type { DroppedFolder } from '@/components/DragUploadZone';
-
-import { INSERT_LOCAL_FILE_MENTION_COMMAND } from './LocalFileMention';
-
-/**
- * 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.
- *
- * 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;
-
- const lexicalEditor = editor.getLexicalEditor();
- lexicalEditor?.focus();
-
- folders.forEach((folder) => {
- editor.dispatchCommand(INSERT_LOCAL_FILE_MENTION_COMMAND, {
- isDirectory: true,
- name: folder.name,
- path: folder.path,
- });
- });
-};
diff --git a/src/features/ChatInput/InputEditor/plugins.ts b/src/features/ChatInput/InputEditor/plugins.ts
index 0f47199b76e..c3ce820da04 100644
--- a/src/features/ChatInput/InputEditor/plugins.ts
+++ b/src/features/ChatInput/InputEditor/plugins.ts
@@ -11,7 +11,7 @@ import {
import { type Editor } from '@lobehub/editor/react';
import { ReactActionTagPlugin } from './ActionTag';
-import { ReactLocalFileMentionPlugin } from './LocalFileMention';
+import { ReactLocalFileTagPlugin } from './LocalFileTag';
import { ReactReferTopicPlugin } from './ReferTopic';
type EditorPlugins = NonNullable<Parameters<typeof Editor>[0]['plugins']>;
@@ -24,7 +24,7 @@ interface CreateChatInputRichPluginsOptions {
export const CHAT_INPUT_EMBED_PLUGINS: EditorPlugins = [
ReactActionTagPlugin,
ReactReferTopicPlugin,
- ReactLocalFileMentionPlugin,
+ ReactLocalFileTagPlugin,
ReactMentionPlugin,
];
diff --git a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.test.ts b/src/features/ChatInput/InputEditor/useLocalFileTag.desktop.test.ts
similarity index 93%
rename from src/features/ChatInput/InputEditor/useLocalFileMention.desktop.test.ts
rename to src/features/ChatInput/InputEditor/useLocalFileTag.desktop.test.ts
index 8088e71d673..b38da5d9dd5 100644
--- a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.test.ts
+++ b/src/features/ChatInput/InputEditor/useLocalFileTag.desktop.test.ts
@@ -1,7 +1,7 @@
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useLocalFileMention } from './useLocalFileMention.desktop';
+import { useLocalFileTag } from './useLocalFileTag.desktop';
const { agentState, chatState, electronState, searchProjectFilesMock } = vi.hoisted(() => ({
agentState: {
@@ -67,7 +67,7 @@ vi.mock('./MentionMenu/LocalFileIcon', () => ({
default: () => null,
}));
-describe('useLocalFileMention.desktop', () => {
+describe('useLocalFileTag.desktop', () => {
beforeEach(() => {
agentState.agencyConfig = undefined;
agentState.isLocalSystemEnabled = true;
@@ -84,7 +84,7 @@ describe('useLocalFileMention.desktop', () => {
});
it('does not pass the local gateway device id for local desktop file search', async () => {
- const { result } = renderHook(() => useLocalFileMention());
+ const { result } = renderHook(() => useLocalFileTag());
await result.current.searchLocalFiles('button');
@@ -111,7 +111,7 @@ describe('useLocalFileMention.desktop', () => {
source: 'git',
});
- const { result } = renderHook(() => useLocalFileMention());
+ const { result } = renderHook(() => useLocalFileTag());
const items = await result.current.searchLocalFiles('readme');
@@ -136,7 +136,7 @@ describe('useLocalFileMention.desktop', () => {
};
agentState.workingDirectory = '/remote/repo';
- const { result } = renderHook(() => useLocalFileMention());
+ const { result } = renderHook(() => useLocalFileTag());
await result.current.searchLocalFiles('button');
diff --git a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts b/src/features/ChatInput/InputEditor/useLocalFileTag.desktop.ts
similarity index 84%
rename from src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
rename to src/features/ChatInput/InputEditor/useLocalFileTag.desktop.ts
index d610a33acd3..f3e5c1c1783 100644
--- a/src/features/ChatInput/InputEditor/useLocalFileMention.desktop.ts
+++ b/src/features/ChatInput/InputEditor/useLocalFileTag.desktop.ts
@@ -14,15 +14,15 @@ import { useAgentId } from '../hooks/useAgentId';
import { compactDirectoryTail, compactFileName } from './MentionMenu/localFileDisplay';
import LocalFileIcon from './MentionMenu/LocalFileIcon';
-const MAX_LOCAL_FILE_MENTION_ITEMS = 20;
-const log = debug('chat-input:local-file-mention');
+const MAX_LOCAL_FILE_TAG_ITEMS = 20;
+const log = debug('chat-input:local-file-tag');
-export interface UseLocalFileMentionResult {
- enableLocalFileMention: boolean;
+export interface UseLocalFileTagResult {
+ enableLocalFileTag: boolean;
searchLocalFiles: (matchingString: string) => Promise<ISlashMenuOption[]>;
}
-export const useLocalFileMention = (): UseLocalFileMentionResult => {
+export const useLocalFileTag = (): UseLocalFileTagResult => {
const agentId = useAgentId();
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
const heterogeneousType = agencyConfig?.heterogeneousProvider?.type;
@@ -39,14 +39,14 @@ export const useLocalFileMention = (): UseLocalFileMentionResult => {
const searchDeviceId =
targetDeviceId && targetDeviceId !== currentDeviceId ? targetDeviceId : undefined;
- const enableLocalFileMention = !!heterogeneousType || isLocalSystemEnabled;
+ const enableLocalFileTag = !!heterogeneousType || isLocalSystemEnabled;
const searchLocalFiles = useCallback(
async (matchingString: string): Promise<ISlashMenuOption[]> => {
const keywords = matchingString.trim();
- if (!enableLocalFileMention || !keywords) {
+ if (!enableLocalFileTag || !keywords) {
log('Skip search', {
- enableLocalFileMention,
+ enableLocalFileTag,
hasKeywords: !!keywords,
matchingString,
workingDirectory,
@@ -57,14 +57,14 @@ export const useLocalFileMention = (): UseLocalFileMentionResult => {
try {
log('Search indexed local files', {
keywords,
- limit: MAX_LOCAL_FILE_MENTION_ITEMS,
+ limit: MAX_LOCAL_FILE_TAG_ITEMS,
workingDirectory,
});
if (!workingDirectory) return [];
const result = await projectFileService.searchProjectFiles({
deviceId: searchDeviceId,
- limit: MAX_LOCAL_FILE_MENTION_ITEMS,
+ limit: MAX_LOCAL_FILE_TAG_ITEMS,
query: keywords,
scope: workingDirectory,
});
@@ -106,12 +106,12 @@ export const useLocalFileMention = (): UseLocalFileMentionResult => {
};
});
} catch (error) {
- console.error('[useLocalFileMention] Failed to search local files:', error);
+ console.error('[useLocalFileTag] Failed to search local files:', error);
return [];
}
},
- [enableLocalFileMention, searchDeviceId, workingDirectory],
+ [enableLocalFileTag, searchDeviceId, workingDirectory],
);
- return { enableLocalFileMention, searchLocalFiles };
+ return { enableLocalFileTag, searchLocalFiles };
};
diff --git a/src/features/ChatInput/InputEditor/useLocalFileMention.ts b/src/features/ChatInput/InputEditor/useLocalFileTag.ts
similarity index 55%
rename from src/features/ChatInput/InputEditor/useLocalFileMention.ts
rename to src/features/ChatInput/InputEditor/useLocalFileTag.ts
index 8381096af3f..f1070d27a76 100644
--- a/src/features/ChatInput/InputEditor/useLocalFileMention.ts
+++ b/src/features/ChatInput/InputEditor/useLocalFileTag.ts
@@ -1,13 +1,13 @@
import type { ISlashMenuOption } from '@lobehub/editor';
-export interface UseLocalFileMentionResult {
- enableLocalFileMention: boolean;
+export interface UseLocalFileTagResult {
+ enableLocalFileTag: boolean;
searchLocalFiles: (matchingString: string) => Promise<ISlashMenuOption[]>;
}
const searchLocalFiles = async (): Promise<ISlashMenuOption[]> => [];
-export const useLocalFileMention = (): UseLocalFileMentionResult => ({
- enableLocalFileMention: false,
+export const useLocalFileTag = (): UseLocalFileTagResult => ({
+ enableLocalFileTag: false,
searchLocalFiles,
});
diff --git a/src/features/ChatInput/InputEditor/useWorkspaceFileDrop.ts b/src/features/ChatInput/InputEditor/useWorkspaceFileDrop.ts
index 7c35eb7bedd..a531b2a8559 100644
--- a/src/features/ChatInput/InputEditor/useWorkspaceFileDrop.ts
+++ b/src/features/ChatInput/InputEditor/useWorkspaceFileDrop.ts
@@ -3,7 +3,7 @@ import type React from 'react';
import { useCallback } from 'react';
import { useChatInputStore } from '../store';
-import { INSERT_LOCAL_FILE_MENTION_COMMAND } from './LocalFileMention';
+import { INSERT_LOCAL_FILE_TAG_COMMAND } from './LocalFileTag';
import { readWorkspaceFileDragData } from './workspaceFileDragData';
interface UseWorkspaceFileDropResult {
@@ -17,7 +17,7 @@ interface UseWorkspaceFileDropResult {
* 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
+ * On drop it inserts a `LocalFileTag` 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
@@ -45,7 +45,7 @@ export const useWorkspaceFileDrop = (): UseWorkspaceFileDropResult => {
if (!editor) return;
editor.getLexicalEditor()?.focus();
- editor.dispatchCommand(INSERT_LOCAL_FILE_MENTION_COMMAND, {
+ editor.dispatchCommand(INSERT_LOCAL_FILE_TAG_COMMAND, {
isDirectory: payload.isDirectory,
name: payload.name,
path: payload.path,
diff --git a/src/routes/(main)/agent/features/Conversation/index.tsx b/src/routes/(main)/agent/features/Conversation/index.tsx
index bbb1c5d34e1..de12725e73a 100644
--- a/src/routes/(main)/agent/features/Conversation/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/index.tsx
@@ -2,9 +2,10 @@ import { isDesktop } from '@lobechat/const';
import { Flexbox, TooltipGroup } from '@lobehub/ui';
import React, { memo, Suspense, useCallback } from 'react';
-import DragUploadZone, { type DroppedFolder, useUploadFiles } from '@/components/DragUploadZone';
+import DragUploadZone, { type DroppedLocalPath, useUploadFiles } from '@/components/DragUploadZone';
import Loading from '@/components/Loading/BrandTextLoading';
-import { insertLocalFolderMentions } from '@/features/ChatInput/InputEditor/insertLocalFolderMentions';
+import { insertLocalPathTags } from '@/features/ChatInput/InputEditor/insertLocalFileTags';
+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -26,21 +27,23 @@ const ChatConversation = memo(() => {
const isLocalSystemEnabled = useAgentStore(agentChatConfigSelectors.isLocalSystemEnabled);
const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+ const workingDirectory = useEffectiveWorkingDirectory(agentId);
- const enableLocalFolderMention = isDesktop && (isHeterogeneous || isLocalSystemEnabled);
+ const enableLocalPathReference =
+ isDesktop && !!workingDirectory && (isHeterogeneous || isLocalSystemEnabled);
- const handleLocalFolders = useCallback((folders: DroppedFolder[]) => {
+ const handleLocalPaths = useCallback((paths: DroppedLocalPath[]) => {
const editor = useChatStore.getState().mainInputEditor?.instance;
if (!editor) return;
- insertLocalFolderMentions(editor, folders);
+ insertLocalPathTags(editor, paths);
}, []);
return (
<Suspense fallback={<Loading debugId="Agent > ChatConversation" />}>
<DragUploadZone
- enableLocalFolderMention={enableLocalFolderMention}
+ enableLocalPathReference={enableLocalPathReference}
style={wrapperStyle}
- onLocalFolders={enableLocalFolderMention ? handleLocalFolders : undefined}
+ onLocalPaths={enableLocalPathReference ? handleLocalPaths : undefined}
onUploadFiles={handleUploadFiles}
>
<Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>