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: recognize local file links and unify attachment chips (#19229)

Arvin Xuadc3a6b07097
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index a3d51aee7bc..dd0a71bac58 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2069,6 +2069,8 @@
"upload.preview.status.error": "Upload failed",
"upload.preview.status.pending": "Preparing to upload...",
"upload.preview.status.processing": "Processing file...",
+ "upload.preview.status.success": "Upload complete",
+ "upload.preview.status.uploading": "Uploading file...",
"upload.validation.mediaNotSupported": "The current model cannot read these media files, so they were not added: {{files}}. Switch to a model that supports them, or upload a different file type.",
"upload.validation.unsupportedFileType": "Unsupported file type: {{files}}. Supported images: JPG, PNG, GIF, WebP. Supported documents include PDF, Word, Excel, PowerPoint, Markdown, text, CSV, JSON, and code files.",
"upload.validation.videoSizeExceeded": "Video file size must not exceed {{maxSize}}. Current file size is {{actualSize}}.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index bb1271fceb7..6b02677ee3a 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2069,6 +2069,8 @@
"upload.preview.status.error": "上传失败",
"upload.preview.status.pending": "准备上传…",
"upload.preview.status.processing": "文件处理中…",
+ "upload.preview.status.success": "上传完成",
+ "upload.preview.status.uploading": "正在上传文件…",
"upload.validation.mediaNotSupported": "当前模型无法解析以下媒体文件,未添加:{{files}}。请切换到支持该媒体的模型,或改用其他文件类型。",
"upload.validation.unsupportedFileType": "不支持的文件类型:{{files}}。支持的图片格式:JPG、PNG、GIF、WebP。支持的文档包括PDF、Word、Excel、PowerPoint、Markdown、文本、CSV、JSON和代码文件。",
"upload.validation.videoSizeExceeded": "视频文件不能超过 {{maxSize}}。当前为 {{actualSize}}",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 1830deb1dd1..0ba9f0df1b5 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2364,6 +2364,8 @@ export default {
'upload.preview.status.error': 'Upload failed',
'upload.preview.status.pending': 'Preparing to upload...',
'upload.preview.status.processing': 'Processing file...',
+ 'upload.preview.status.success': 'Upload complete',
+ 'upload.preview.status.uploading': 'Uploading file...',
'upload.validation.mediaNotSupported':
'The current model cannot read these media files, so they were not added: {{files}}. Switch to a model that supports them, or upload a different file type.',
'upload.validation.unsupportedFileType':
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx
index 7a93778feef..2e4904c869f 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/Content.tsx
@@ -10,26 +10,40 @@ const styles = createStaticStyles(({ css }) => ({
width: 100%;
height: 100%;
margin-block: 0 !important;
+ border-radius: 2px;
+
box-shadow: none;
img {
width: 100%;
height: 100%;
- border-radius: 4px;
+ border-radius: 2px;
object-fit: cover;
}
`,
+ imageRoot: css`
+ border-radius: 2px;
+ `,
video: css`
overflow: hidden;
width: 100%;
height: 100%;
- border-radius: 4px;
+ border-radius: 2px;
`,
}));
const Content = memo<UploadFileItem>(({ file, previewUrl }) => {
if (file.type.startsWith('image')) {
- return <Image alt={file.name} classNames={{ wrapper: styles.image }} src={previewUrl} />;
+ return (
+ <Image
+ alt={file.name}
+ className={styles.imageRoot}
+ classNames={{ wrapper: styles.image }}
+ height={20}
+ src={previewUrl}
+ width={20}
+ />
+ );
}
if (file.type.startsWith('video')) {
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
index aee5ed8356b..678c0291108 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
@@ -1,55 +1,59 @@
-import { Flexbox, Tooltip } from '@lobehub/ui';
-import { Tag } from '@lobehub/ui/base-ui';
+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { ActionIcon, Tag } from '@lobehub/ui/base-ui';
import { Progress } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleAlertIcon, CircleCheckIcon, Loader2Icon, RotateCwIcon } from 'lucide-react';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';
import { useEventCallback } from '@/hooks/useEventCallback';
import { useFileStore } from '@/store/file';
import { type UploadFileItem } from '@/types/files/upload';
-import { UPLOAD_STATUS_SET } from '@/types/files/upload';
+import UploadDetail from '../../../components/UploadDetail';
import Content from './Content';
import { openFilePreviewModal } from './FilePreviewModal.loader';
-import { getFileBasename } from './utils';
+import { useUploadCompletion } from './useUploadCompletion';
+import { getFileBasename, getUploadChipSize, getUploadChipState } from './utils';
const styles = createStaticStyles(({ css }) => ({
- closeBtn: css`
- flex-shrink: 0;
- color: ${cssVar.colorTextTertiary};
-
- &:hover {
- color: ${cssVar.colorError};
- background: ${cssVar.colorErrorBg};
- }
+ chip: css`
+ max-width: 100%;
+ height: 28px;
`,
content: css`
display: flex;
- gap: 6px;
+ gap: 4px;
align-items: center;
+
min-width: 0;
+ max-width: 380px;
`,
- icon: css`
- position: relative;
+ size: css`
+ flex-shrink: 0;
+ font-variant-numeric: tabular-nums;
+ line-height: 18px;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+ `,
+ thumbnail: css`
+ flex-shrink: 0;
+ width: 20px;
+ height: 20px;
+ line-height: 0;
+ `,
+ statusIcon: css`
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
- width: 18px;
- height: 18px;
- border-radius: 4px;
+ width: 12px;
+ height: 12px;
line-height: 0;
-
- img,
- video {
- width: 100%;
- height: 100%;
- border-radius: 4px;
- object-fit: cover;
- }
`,
name: css`
overflow: hidden;
@@ -61,58 +65,119 @@ const styles = createStaticStyles(({ css }) => ({
text-overflow: ellipsis;
white-space: nowrap;
`,
- progress: css`
- position: absolute;
- inset: -3px;
-
- display: flex;
- align-items: center;
- justify-content: center;
-
- border-radius: 4px;
-
- background: ${cssVar.colorBgMask};
- `,
}));
type FileItemProps = UploadFileItem;
const ContextItem = memo<FileItemProps>((props) => {
- const { file, id, status, uploadState } = props;
- const [removeChatUploadFile] = useFileStore((s) => [s.removeChatUploadFile]);
-
+ const { error, errorCode, file, id, status, tasks, uploadState } = props;
+ const { t } = useTranslation(['chat', 'common']);
+ const removeChatUploadFile = useFileStore((s) => s.removeChatUploadFile);
+ const retryChatUploadFile = useFileStore((s) => s.retryChatUploadFile);
+ const { busy, canPreview, canRetry, indicator, progress } = getUploadChipState(props);
const basename = getFileBasename(file.name);
- const isUploading = UPLOAD_STATUS_SET.has(status);
- const progress = uploadState?.progress ?? 0;
+ const sizeLabel = getUploadChipSize(props);
+ const showCompletion = useUploadCompletion(status);
const handleClick = useEventCallback(() => {
- void openFilePreviewModal(props);
+ if (canPreview) void openFilePreviewModal(props);
});
-
const handleClose = useEventCallback(() => {
- removeChatUploadFile(id);
+ void removeChatUploadFile(id);
});
+
+ const detail = (
+ <Flexbox gap={4}>
+ <span>{file.name}</span>
+ <UploadDetail
+ error={error}
+ size={file.size}
+ status={status}
+ tasks={tasks}
+ uploadState={uploadState}
+ />
+ </Flexbox>
+ );
+
return (
- <Tag closable size={'large'} onClick={handleClick} onClose={handleClose}>
- <Flexbox horizontal align={'center'} className={styles.content}>
- <Flexbox className={styles.icon}>
- <Content {...props} />
- {isUploading && (
- <div className={styles.progress}>
- <Progress
- percent={progress}
- showInfo={false}
- size={14}
- strokeWidth={2}
- type="circle"
- />
- </div>
+ <Tag
+ closable
+ aria-busy={busy}
+ className={styles.chip}
+ size={'large'}
+ onClick={canPreview ? handleClick : undefined}
+ onClose={handleClose}
+ >
+ <Tooltip title={detail}>
+ <Flexbox horizontal align={'center'} className={styles.content}>
+ <Flexbox className={styles.thumbnail}>
+ <Content {...props} />
+ </Flexbox>
+ <span className={styles.name}>{basename}</span>
+ {(indicator !== 'file' || showCompletion) && (
+ <Flexbox className={styles.statusIcon}>
+ {showCompletion ? (
+ <Icon
+ aria-label={t('upload.preview.status.success')}
+ icon={CircleCheckIcon}
+ size={12}
+ style={{ color: cssVar.colorSuccess }}
+ />
+ ) : indicator === 'loading' ? (
+ <Icon
+ spin
+ icon={Loader2Icon}
+ size={12}
+ aria-label={t(
+ status === 'processing'
+ ? 'upload.preview.status.processing'
+ : status === 'pending'
+ ? 'upload.preview.status.pending'
+ : 'upload.preview.status.uploading',
+ )}
+ />
+ ) : indicator === 'progress' ? (
+ <span
+ aria-label={t('upload.preview.status.uploading')}
+ aria-valuemax={100}
+ aria-valuemin={0}
+ aria-valuenow={progress}
+ className={styles.statusIcon}
+ role={'progressbar'}
+ >
+ <Progress
+ percent={progress}
+ showInfo={false}
+ size={12}
+ status={'normal'}
+ strokeWidth={12}
+ type={'circle'}
+ />
+ </span>
+ ) : (
+ <Icon icon={CircleAlertIcon} size={12} style={{ color: cssVar.colorError }} />
+ )}
+ </Flexbox>
)}
+ {sizeLabel && <span className={styles.size}>{sizeLabel}</span>}
</Flexbox>
- <Tooltip title={file.name}>
- <span className={styles.name}>{basename}</span>
- </Tooltip>
- </Flexbox>
+ </Tooltip>
+ {canRetry && (
+ <Flexbox horizontal onClick={(event) => event.stopPropagation()}>
+ {errorCode ? (
+ <FileUploadErrorActions compact code={errorCode} />
+ ) : (
+ <ActionIcon
+ icon={RotateCwIcon}
+ size={{ blockSize: 24, size: 12 }}
+ title={t('retry', { ns: 'common' })}
+ onClick={() => {
+ void retryChatUploadFile(id);
+ }}
+ />
+ )}
+ </Flexbox>
+ )}
</Tag>
);
});
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useUploadCompletion.test.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useUploadCompletion.test.ts
new file mode 100644
index 00000000000..906b22cbca0
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useUploadCompletion.test.ts
@@ -0,0 +1,46 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FileUploadStatus } from '@/types/files/upload';
+
+import { useUploadCompletion } from './useUploadCompletion';
+
+describe('useUploadCompletion', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('acknowledges success for two seconds, then returns to the compact chip', () => {
+ const { result, rerender } = renderHook(
+ ({ status }: { status: FileUploadStatus }) => useUploadCompletion(status),
+ { initialProps: { status: 'uploading' as FileUploadStatus } },
+ );
+ expect(result.current).toBe(false);
+ rerender({ status: 'processing' });
+ expect(result.current).toBe(false);
+ rerender({ status: 'success' });
+ expect(result.current).toBe(true);
+ act(() => vi.advanceTimersByTime(1999));
+ expect(result.current).toBe(true);
+ act(() => vi.advanceTimersByTime(1));
+ expect(result.current).toBe(false);
+ });
+
+ it('does not acknowledge already completed attachments on mount', () => {
+ const { result } = renderHook(() => useUploadCompletion('success'));
+ expect(result.current).toBe(false);
+ });
+
+ it('clears completion feedback when a new upload starts and cancels timers on unmount', () => {
+ const { result, rerender, unmount } = renderHook(
+ ({ status }: { status: FileUploadStatus }) => useUploadCompletion(status),
+ { initialProps: { status: 'uploading' as FileUploadStatus } },
+ );
+ rerender({ status: 'success' });
+ rerender({ status: 'uploading' });
+ expect(result.current).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ rerender({ status: 'success' });
+ unmount();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useUploadCompletion.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useUploadCompletion.ts
new file mode 100644
index 00000000000..99e3718c8ca
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useUploadCompletion.ts
@@ -0,0 +1,23 @@
+import { useEffect, useState } from 'react';
+
+import type { FileUploadStatus } from '@/types/files/upload';
+
+/** Acknowledge newly completed uploads without decorating already uploaded attachments. */
+export const useUploadCompletion = (status: FileUploadStatus) => {
+ const [previousStatus, setPreviousStatus] = useState(status);
+ const [showCompletion, setShowCompletion] = useState(false);
+
+ if (previousStatus !== status) {
+ setPreviousStatus(status);
+ setShowCompletion(status === 'success');
+ }
+
+ useEffect(() => {
+ if (!showCompletion) return;
+
+ const timer = setTimeout(() => setShowCompletion(false), 2000);
+ return () => clearTimeout(timer);
+ }, [showCompletion]);
+
+ return showCompletion;
+};
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.test.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.test.ts
new file mode 100644
index 00000000000..36c65a2bdf1
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FileUploadStatus } from '@/types/files/upload';
+
+import { getUploadChipSize, getUploadChipState } from './utils';
+
+const uploadState = (progress: number) => ({ progress, restTime: 0, speed: 0 });
+
+describe('getUploadChipState', () => {
+ it.each(['pending', 'processing'] as const)(
+ 'shows an indeterminate indicator for %s',
+ (status) => {
+ expect(getUploadChipState({ status, uploadState: uploadState(100) })).toMatchObject({
+ busy: true,
+ canPreview: false,
+ canRetry: false,
+ indicator: 'loading',
+ });
+ },
+ );
+
+ it('shows upload progress, then marks the upload complete', () => {
+ expect(getUploadChipState({ status: 'uploading', uploadState: uploadState(42) })).toMatchObject(
+ {
+ busy: true,
+ canPreview: false,
+ indicator: 'progress',
+ progress: 42,
+ },
+ );
+ expect(getUploadChipState({ status: 'success', uploadState: uploadState(100) })).toMatchObject({
+ busy: false,
+ canPreview: true,
+ canRetry: false,
+ indicator: 'file',
+ });
+ });
+
+ it.each(['error', 'cancelled'] as const)(
+ 'keeps recovery available for %s without opening a preview',
+ (status) => {
+ expect(getUploadChipState({ status })).toMatchObject({
+ busy: false,
+ canPreview: false,
+ canRetry: true,
+ indicator: 'error',
+ });
+ },
+ );
+
+ it.each([undefined, Number.NaN, Number.POSITIVE_INFINITY])(
+ 'uses indeterminate feedback when progress is unavailable (%s)',
+ (progress) => {
+ expect(
+ getUploadChipState({
+ status: 'uploading',
+ uploadState: progress === undefined ? undefined : uploadState(progress),
+ }).indicator,
+ ).toBe('loading');
+ },
+ );
+
+ it.each([
+ [-10, 0],
+ [0, 0],
+ [150, 100],
+ ])('bounds progress %s to %s', (progress, expected) => {
+ expect(
+ getUploadChipState({ status: 'uploading', uploadState: uploadState(progress) }).progress,
+ ).toBe(expected);
+ });
+
+ it.each<FileUploadStatus>([
+ 'pending',
+ 'uploading',
+ 'processing',
+ 'success',
+ 'error',
+ 'cancelled',
+ ])('allows preview only after success (%s)', (status) => {
+ expect(getUploadChipState({ status }).canPreview).toBe(status === 'success');
+ });
+});
+
+describe('getUploadChipSize', () => {
+ const file = new File([new Uint8Array(Math.round(2.4 * 1024 ** 2))], 'screenshot.png');
+
+ it('shows transferred bytes and total size with a shared unit during upload', () => {
+ expect(getUploadChipSize({ file, status: 'uploading', uploadState: uploadState(42) })).toBe(
+ '1.0/2.4 MB',
+ );
+ expect(getUploadChipSize({ file, status: 'uploading', uploadState: uploadState(10) })).toBe(
+ '0.2/2.4 MB',
+ );
+ });
+
+ it('shows zero transferred while pending even with stale progress', () => {
+ expect(getUploadChipSize({ file, status: 'pending', uploadState: uploadState(100) })).toBe(
+ '0.0/2.4 MB',
+ );
+ });
+
+ it('does not invent transferred bytes when progress is unknown', () => {
+ expect(getUploadChipSize({ file, status: 'uploading' })).toBe('—/2.4 MB');
+ });
+
+ it('hides size after upload succeeds', () => {
+ expect(
+ getUploadChipSize({ file, status: 'success', uploadState: uploadState(100) }),
+ ).toBeUndefined();
+ });
+
+ it('clamps transferred bytes to the total', () => {
+ expect(getUploadChipSize({ file, status: 'uploading', uploadState: uploadState(150) })).toBe(
+ '2.4/2.4 MB',
+ );
+ });
+
+ it.each(['processing', 'error', 'cancelled'] as const)(
+ 'keeps the total size visible for %s',
+ (status) => {
+ expect(getUploadChipSize({ file, status })).toBe('2.4 MB');
+ },
+ );
+
+ it('handles empty files without NaN', () => {
+ expect(
+ getUploadChipSize({
+ file: new File([], 'empty.txt'),
+ status: 'uploading',
+ uploadState: uploadState(0),
+ }),
+ ).toBe('0.0/0.0 KB');
+ });
+});
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
index cb8504edc9d..686347d6bc1 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
@@ -1,3 +1,6 @@
+import type { UploadFileItem } from '@/types/files/upload';
+import { formatSize } from '@/utils/format';
+
export const getFileBasename = (filename: string): string => {
const lastDotIndex = filename.lastIndexOf('.');
if (lastDotIndex <= 0) return filename;
@@ -32,3 +35,55 @@ export const getHarmoniousSize = (
return { height, width };
};
+
+/** Keep upload feedback and available actions consistent throughout the chip lifecycle. */
+export const getUploadChipState = ({
+ status,
+ uploadState,
+}: Pick<UploadFileItem, 'status' | 'uploadState'>) => {
+ const busy = status === 'pending' || status === 'uploading' || status === 'processing';
+ const rawProgress = uploadState?.progress;
+ const progress =
+ typeof rawProgress === 'number' && Number.isFinite(rawProgress)
+ ? Math.min(100, Math.max(0, rawProgress))
+ : undefined;
+
+ return {
+ busy,
+ canPreview: status === 'success',
+ canRetry: status === 'error' || status === 'cancelled',
+ indicator:
+ status === 'error' || status === 'cancelled'
+ ? 'error'
+ : status === 'uploading' && progress !== undefined
+ ? 'progress'
+ : busy
+ ? 'loading'
+ : 'file',
+ progress,
+ };
+};
+
+/** Express transferred and total bytes in the same unit so the ratio is easy to compare. */
+export const getUploadChipSize = ({
+ file,
+ status,
+ uploadState,
+}: Pick<UploadFileItem, 'file' | 'status' | 'uploadState'>) => {
+ if (status === 'success') return undefined;
+
+ const total = formatSize(file.size);
+ if (status !== 'pending' && status !== 'uploading') return total;
+
+ const { progress } = getUploadChipState({ status, uploadState });
+ if (status === 'uploading' && progress === undefined) return `—/${total}`;
+
+ const unit = total.split(' ')[1];
+ const divisor = unit === 'GB' ? 1024 ** 3 : unit === 'MB' ? 1024 ** 2 : 1024;
+ const transferred = (
+ (file.size * (status === 'pending' ? 0 : progress!)) /
+ 100 /
+ divisor
+ ).toFixed(1);
+ return `${transferred}/${total}`;
+};
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
index 26729f14bdb..e7207194361 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
@@ -1,12 +1,10 @@
import { Flexbox, ScrollShadow } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import { memo, useMemo } from 'react';
+import { memo } from 'react';
import { useChatInputStore } from '@/features/ChatInput/store';
import { fileChatSelectors, useFileStore } from '@/store/file';
-import { UPLOAD_STATUS_SET } from '@/types/files/upload';
-import FileItem from '../FilePreview/FileItem';
import ContextItem from './ContextItem';
import ElementItem from './ElementItem';
import SelectionItem from './SelectionItem';
@@ -16,11 +14,6 @@ const styles = createStaticStyles(({ css }) => ({
overflow-x: scroll;
width: 100%;
`,
- uploadingContainer: css`
- overflow-x: auto;
- width: 100%;
- padding-block: 8px;
- `,
}));
const ContextList = memo(() => {
@@ -39,73 +32,32 @@ const ContextList = memo(() => {
(item, index, self) => index === self.findIndex((t) => t.preview === item.preview),
);
- // Separate files into uploading/error and completed
- const { uploadingFiles, completedFiles } = useMemo(() => {
- const uploading = inputFilesList.filter(
- (file) => UPLOAD_STATUS_SET.has(file.status) || file.status === 'error',
- );
- const completed = inputFilesList.filter(
- (file) => !UPLOAD_STATUS_SET.has(file.status) && file.status !== 'error',
- );
- return { completedFiles: completed, uploadingFiles: uploading };
- }, [inputFilesList]);
-
- const hasUploadingFiles = uploadingFiles.length > 0;
- const hasCompletedFiles = completedFiles.length > 0;
const hasSelections = showSelectionList && selectionList.length > 0;
if (!showFileList && !showSelectionList) return null;
- if (!hasUploadingFiles && !hasCompletedFiles && !hasSelections) return null;
+ if (inputFilesList.length === 0 && !hasSelections) return null;
return (
- <Flexbox gap={0}>
- {/* Uploading/Error files - show with detailed FileItem */}
- {hasUploadingFiles && (
- <ScrollShadow
- hideScrollBar
- horizontal
- className={styles.uploadingContainer}
- orientation={'horizontal'}
- size={8}
- >
- <Flexbox horizontal gap={8}>
- {uploadingFiles.map((item) => (
- <FileItem key={item.id} {...item} />
- ))}
- </Flexbox>
- </ScrollShadow>
- )}
-
- {/* Completed files and selections - show with compact Tag */}
- {(hasCompletedFiles || hasSelections) && (
- <ScrollShadow
- hideScrollBar
- horizontal
- className={styles.container}
- orientation={'horizontal'}
- size={8}
- >
- <Flexbox
- horizontal
- gap={4}
- paddingInline={0}
- style={{ paddingBlockStart: 8 }}
- wrap={'wrap'}
- >
- {selectionList.map((item) =>
- item.source === 'element' ? (
- <ElementItem key={item.id} {...item} />
- ) : (
- <SelectionItem key={item.id} {...item} />
- ),
- )}
- {completedFiles.map((item) => (
- <ContextItem key={item.id} {...item} />
- ))}
- </Flexbox>
- </ScrollShadow>
- )}
- </Flexbox>
+ <ScrollShadow
+ hideScrollBar
+ horizontal
+ className={styles.container}
+ orientation={'horizontal'}
+ size={8}
+ >
+ <Flexbox horizontal gap={4} paddingInline={0} style={{ paddingBlockStart: 8 }} wrap={'wrap'}>
+ {selectionList.map((item) =>
+ item.source === 'element' ? (
+ <ElementItem key={item.id} {...item} />
+ ) : (
+ <SelectionItem key={item.id} {...item} />
+ ),
+ )}
+ {inputFilesList.map((item) => (
+ <ContextItem key={item.id} {...item} />
+ ))}
+ </Flexbox>
+ </ScrollShadow>
);
});
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
index b6aac4dc847..469fe5013da 100644
--- a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
@@ -1,6 +1,6 @@
import { isDesktop } from '@lobechat/const';
import { Flexbox, Icon, Popover } from '@lobehub/ui';
-import { Button, Text } from '@lobehub/ui/base-ui';
+import { Button, Tag, Text } 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';
@@ -41,7 +41,11 @@ const styles = createStaticStyles(({ css }) => ({
`,
label: css`
overflow: hidden;
- font-weight: 500;
+ align-self: baseline;
+
+ min-width: 0;
+
+ font-weight: 400;
text-overflow: ellipsis;
white-space: nowrap;
`,
@@ -86,17 +90,26 @@ const styles = createStaticStyles(({ css }) => ({
user-select: none;
display: inline-flex;
- gap: 4px;
+ gap: 6px;
align-items: center;
- max-width: 240px;
+ box-sizing: border-box;
+ max-width: min(240px, 100%);
+ height: 24px;
margin-inline-end: ${TAG_MARGIN_INLINE_END}px;
- padding-inline: 2px;
+ padding-block: 2px;
+ padding-inline: 8px;
border-radius: ${cssVar.borderRadius};
- color: ${cssVar.colorInfo};
+ font-size: inherit;
+ line-height: 20px;
+ color: ${cssVar.colorTextSecondary};
vertical-align: baseline;
+ &:hover {
+ background: ${cssVar.colorFillSecondary};
+ }
+
&.selected {
outline: 2px solid ${cssVar.colorInfo};
outline-offset: 1px;
@@ -194,9 +207,9 @@ const LocalFileTagTrigger = memo<LocalFileTagTriggerProps>(
}, [editor, nodeKey, onClick]);
return (
- <span {...rest} className={cx(styles.tag, className)} ref={setSpanRef} title={title}>
+ <Tag {...rest} className={cx(styles.tag, className)} ref={setSpanRef} title={title}>
{children}
- </span>
+ </Tag>
);
},
);
@@ -214,7 +227,7 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
);
const allowExternalFilePreview =
!!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);
- const canPreview = isDesktop && !file.isDirectory && !!parsed;
+ const canPreview = isDesktop && !file.isDirectory && !!parsed?.workingDirectory;
const canRenderImagePreview = canPreview && isPreviewableImageFile(file);
const { data: imagePreview } = useClientDataSWR<LocalFilePreview>(
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
index 45e2712f472..4ba02c2d94e 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
@@ -30,9 +30,13 @@ const createRenderProps = (
type: 'element',
});
+const platform = vi.hoisted(() => ({ isDesktop: true }));
+
vi.mock('@lobechat/const', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
- isDesktop: true,
+ get isDesktop() {
+ return platform.isDesktop;
+ },
}));
vi.mock('@/components/FileIcon', () => ({
@@ -57,9 +61,40 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
describe('LocalFileLink Render', () => {
afterEach(() => {
+ platform.isDesktop = true;
useChatStore.setState(useChatStore.getInitialState());
});
+ it.each(['/home/ubuntu/workspace/src/client.ts:391', './src/client.ts:391'])(
+ 'renders %s as a non-navigable file reference on web',
+ (href) => {
+ platform.isDesktop = false;
+ const { container } = render(
+ <Render {...createRenderProps({ linkHref: href, linkLabel: 'client.ts' })} />,
+ );
+
+ expect(screen.queryByRole('link')).toBeNull();
+ expect(container.querySelector('[href]')).toBeNull();
+ expect(screen.getByTestId('file-icon')).toHaveAttribute('data-file-name', 'client.ts');
+ fireEvent.click(screen.getByText('client.ts'));
+ fireEvent.click(screen.getByText('client.ts'), { metaKey: true });
+ fireEvent(
+ screen.getByText('client.ts'),
+ new MouseEvent('auxclick', { bubbles: true, button: 1 }),
+ );
+ expect(useChatStore.getState().openLocalFiles).toEqual([]);
+ },
+ );
+
+ it('keeps unresolved relative references non-navigable on desktop', () => {
+ const { container } = render(
+ <Render {...createRenderProps({ linkHref: './client.ts', linkLabel: 'client.ts' })} />,
+ );
+ expect(container.querySelector('[href]')).toBeNull();
+ fireEvent.click(screen.getByText('client.ts'));
+ expect(useChatStore.getState().openLocalFiles).toEqual([]);
+ });
+
it('opens local file links in the right-side local file portal', () => {
useChatStore.setState({
activeAgentId: 'agent-1',
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
index 68e26ec500f..6db6951cd55 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
@@ -21,6 +21,12 @@ interface LocalFileLinkProperties {
}
const styles = createStaticStyles(({ css, cssVar }) => ({
+ reference: css`
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+ vertical-align: -0.16em;
+ `,
icon: css`
display: inline-flex;
flex-shrink: 0;
@@ -78,7 +84,8 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
const { linkHref, linkLabel } = node?.properties || {};
const openLocalFile = useChatStore((s) => s.openLocalFile);
const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
- const parsed = isDesktop ? parseLocalFileHref(linkHref, { workingDirectory }) : null;
+ const parsed = parseLocalFileHref(linkHref, { workingDirectory });
+ const canPreview = isDesktop && !!parsed?.workingDirectory;
const allowExternalFilePreview =
!!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);
const label = linkLabel || parsed?.filePath || linkHref || '';
@@ -87,9 +94,7 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
const handleClick = useCallback(
(event: MouseEvent<HTMLAnchorElement>) => {
- // `parsed` is only non-null on desktop, where a local path has no meaningful
- // modifier-click behaviour — always take over the click.
- if (!parsed) return;
+ if (!parsed || !canPreview) return;
if (event.button !== 0) return;
event.preventDefault();
@@ -99,9 +104,22 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
workingDirectory: parsed.workingDirectory,
});
},
- [allowExternalFilePreview, openLocalFile, parsed],
+ [allowExternalFilePreview, canPreview, openLocalFile, parsed],
);
+ if (!canPreview) {
+ return (
+ <Tooltip mouseEnterDelay={0.1} placement={'topLeft'} title={title}>
+ <span className={styles.reference} data-file-path={parsed?.filePath}>
+ <span aria-hidden className={styles.icon}>
+ <FileIcon fileName={iconFileName} size={16} variant={'raw'} />
+ </span>
+ <span>{label}</span>
+ </span>
+ </Tooltip>
+ );
+ }
+
return (
<Tooltip mouseEnterDelay={0.1} placement={'topLeft'} title={title}>
<A
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.test.ts b/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.test.ts
index 4f62dd76838..12f411d7415 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.test.ts
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.test.ts
@@ -31,6 +31,21 @@ describe('parseLocalFileHref', () => {
});
});
+ it.each(['./src/client.ts:391', '../src/client.ts:391', '~/src/client.ts:391'])(
+ 'recognizes explicit relative file reference %s without inventing a workspace',
+ (href) => {
+ expect(parseLocalFileHref(href)).toEqual({
+ filePath: href.replace(':391', ''),
+ line: 391,
+ workingDirectory: '',
+ });
+ },
+ );
+
+ it('keeps protocol-relative URLs as web links', () => {
+ expect(parseLocalFileHref('//home/example.ts')).toBeNull();
+ });
+
it('ignores normal app routes and external URLs', () => {
expect(parseLocalFileHref('/settings/profile')).toBeNull();
expect(parseLocalFileHref('https://example.com/file.ts')).toBeNull();
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.ts b/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.ts
index ac3e2a62114..b9c86af6b3c 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.ts
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/parse.ts
@@ -19,10 +19,13 @@ const KNOWN_LOCAL_PATH_PREFIXES = [
'/Applications/',
'/Users/',
'/Volumes/',
+ '/etc/',
'/home/',
'/mnt/',
'/opt/',
'/private/',
+ '/root/',
+ '/srv/',
'/tmp/',
'/var/',
'/workspace/',
@@ -129,7 +132,13 @@ export const parseLocalFileHref = (
if (!candidate) return null;
const { filePath, line, column } = extractLineSuffix(candidate);
- if (!isAbsoluteLocalPath(filePath)) return null;
+ // Keep explicit relative references as files even without a resolvable workspace.
+ if (/^(?:\.\.?[\\/]|~[\\/])/.test(filePath)) {
+ return { column, filePath, line, workingDirectory: '' };
+ }
+
+ // Protocol-relative web URLs must never be treated as local files.
+ if (filePath.startsWith('//') || !isAbsoluteLocalPath(filePath)) return null;
const matchedWorkingDirectory =
workingDirectory && isWithinDirectory(filePath, workingDirectory)
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.test.ts b/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.test.ts
index 9b0a3f8f0e3..d0ef422856c 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.test.ts
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.test.ts
@@ -1,11 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
+import { rehypeLobeLink } from '../Link/rehypePlugin';
import { LOBE_LOCAL_FILE_LINK_TAG } from './parse';
import { rehypeLocalFileLink } from './rehypePlugin';
vi.mock('@lobechat/const', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
- isDesktop: true,
+ isDesktop: false,
}));
const createAnchor = (href: string, text: string) => ({
@@ -33,6 +34,20 @@ describe('rehypeLocalFileLink', () => {
});
});
+ it.each(['/home/ubuntu/workspace/device-gateway/src/client.ts:391', './src/client.ts:391'])(
+ 'marks %s as a file before the generic link plugin on web',
+ (href) => {
+ const anchor = createAnchor(href, 'client.ts');
+ const tree = { children: [anchor], type: 'root' };
+
+ rehypeLocalFileLink()(tree);
+ rehypeLobeLink()(tree);
+
+ expect(anchor.tagName).toBe(LOBE_LOCAL_FILE_LINK_TAG);
+ expect(anchor.properties).toEqual({ linkHref: href, linkLabel: 'client.ts' });
+ },
+ );
+
it('keeps regular app routes untouched', () => {
const anchor = createAnchor('/settings/profile', 'settings');
const tree = { children: [anchor], type: 'root' };
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.ts b/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.ts
index d45b5b97736..469e72dbe07 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.ts
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/rehypePlugin.ts
@@ -1,4 +1,3 @@
-import { isDesktop } from '@lobechat/const';
import { SKIP, visit } from 'unist-util-visit';
import { LOBE_LOCAL_FILE_LINK_TAG, parseLocalFileHref } from './parse';
@@ -11,8 +10,6 @@ const getNodeText = (node: any): string => {
};
export const rehypeLocalFileLink = () => (tree: any) => {
- if (!isDesktop) return;
-
visit(tree, 'element', (node: any) => {
if (node.tagName !== 'a') return;