🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 style(tool): line-numbered code preview and open-in-panel for readFile card (#19894)
Arvin Xu30d101516693
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.jsonindex a88c6737553..5f7e4c74eb0 100644--- a/locales/en-US/tool.json+++ b/locales/en-US/tool.json@@ -159,6 +159,7 @@"localFiles.open": "Open","localFiles.openFile": "Open File","localFiles.openFolder": "Open Folder",+ "localFiles.openInPanel": "Open in side panel","localFiles.outOfScope.requestedPaths": "Requested Paths","localFiles.outOfScope.warning": "Warning: The following path(s) are outside the configured working directory. Please confirm you want to allow access.","localFiles.outOfScope.workingDirectory": "Working Directory",diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.jsonindex a848405c02e..ef92d48905c 100644--- a/locales/zh-CN/tool.json+++ b/locales/zh-CN/tool.json@@ -159,6 +159,7 @@"localFiles.open": "打开","localFiles.openFile": "打开文件","localFiles.openFolder": "打开文件夹",+ "localFiles.openInPanel": "在右侧打开","localFiles.outOfScope.requestedPaths": "请求的路径","localFiles.outOfScope.warning": "警告:以下路径超出了配置的工作目录范围。请确认是否允许访问。","localFiles.outOfScope.workingDirectory": "工作目录",diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsxindex 4e5b791ff61..f1ba84a4290 100644--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx@@ -1,14 +1,17 @@import { useToolRenderCapabilities } from '@lobechat/shared-tool-ui';import type { ReadFileState } from '@lobechat/tool-runtime';-import { Flexbox, Image, Markdown, PreviewGroup } from '@lobehub/ui';+import { Flexbox, Image, Markdown, PreviewGroup, SyntaxHighlighter } from '@lobehub/ui';import { ActionIcon, Text } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';-import { ExternalLink, FolderOpen } from 'lucide-react';-import React, { memo } from 'react';+import { ExternalLink, FolderOpen, SquareArrowOutUpRight } from 'lucide-react';+import type { CSSProperties } from 'react';+import React, { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import FileIcon from '@/components/FileIcon';import { InlineHtmlPreview, isHtmlFile } from '@/components/HtmlPreview';+import { useOpenEditedFile } from '@/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile';++import { stripFinalLineTerminator } from './buildReadFileState';const styles = createStaticStyles(({ css, cssVar }) => ({actions: css`@@ -28,31 +31,54 @@ const styles = createStaticStyles(({ css, cssVar }) => ({opacity: 1;}`,- fileName: css`- flex: 1;- margin-inline-start: 8px;- color: ${cssVar.colorTextSecondary};-- &:hover {- color: ${cssVar.colorText};- }- `,- header: css`- cursor: pointer;- `,image: css`border-radius: ${cssVar.borderRadiusLG};`,imageList: css`flex-wrap: wrap;`,+ // Gutter drawn with a CSS counter on shiki's `.line` spans, so the numbers+ // never get copied along with the code. `&&` outranks the highlighter's own+ // `.line` padding.+ lineNumbers: css`+ && pre code {+ counter-reset: read-file-line var(--read-file-line-offset);+ }++ && pre code .line {+ counter-increment: read-file-line;+ position: relative;+ padding-inline-start: calc(var(--read-file-gutter) + 16px + 12px);+ }++ && pre code .line::before {+ content: counter(read-file-line);+ user-select: none;++ position: absolute;+ inset-inline-start: 16px;++ width: var(--read-file-gutter);++ color: ${cssVar.colorTextQuaternary};+ text-align: end;+ }++ /* Blank lines render as empty spans; give them a line box so they keep+ their row and number. */+ && pre code .line:empty::after {+ content: ' ';+ }+ `,+ // Shrinks to its text so the hover actions sit right after the path.path: css`- margin-block-start: 4px;+ flex: 0 1 auto;++ min-width: 0;padding-inline: 4px;font-size: 12px;color: ${cssVar.colorTextSecondary};- word-break: break-all;`,previewBox: css`position: relative;@@ -65,23 +91,40 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: ${cssVar.colorBgContainer};`,- previewText: css`- overflow: auto;-- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- line-height: 1.6;- word-break: break-all;- white-space: pre-wrap;- `,}));-const ReadFileView = memo<ReadFileState>(- ({ filename: filenameProp, path, fileType, content, images }) => {+interface ReadFileViewProps extends ReadFileState {+ /** 1-based number of the first line in `content`, seeds the gutter. */+ firstLineNumber?: number;+ /** The file lives in the cloud sandbox rather than on a local filesystem. */+ sandboxBacked?: boolean;+}++const ReadFileView = memo<ReadFileViewProps>(+ ({+ filename: filenameProp,+ path,+ fileType,+ content,+ images,+ firstLineNumber = 1,+ sandboxBacked = false,+ }) => {const { t } = useTranslation('tool');const { openFile, openFolder, displayRelativePath } = useToolRenderCapabilities();+ const resolveOpenInPanel = useOpenEditedFile();const filename = filenameProp || path.split('/').pop() || path;+ const code = useMemo(() => stripFinalLineTerminator(content), [content]);++ const lineNumberVars = useMemo(() => {+ const lastLine = firstLineNumber + code.split('\n').length - 1;+ return {+ '--read-file-gutter': `${String(lastLine).length}ch`,+ '--read-file-line-offset': firstLineNumber - 1,+ } as CSSProperties;+ }, [code, firstLineNumber]);+// Reading an image is best shown as the image itself: no card, no header, no path.if (images && images.length > 0) {return (@@ -104,6 +147,9 @@ const ReadFileView = memo<ReadFileState>(}const isHtml = isHtmlFile({ fileName: filename, fileType, path });+ const isMarkdown = fileType === 'md';++ const openInPanel = resolveOpenInPanel({ kind: 'modified', path, sandboxBacked });const handleOpenFile = openFile? (e: React.MouseEvent) => {@@ -121,54 +167,49 @@ const ReadFileView = memo<ReadFileState>(const displayPath = displayRelativePath ? displayRelativePath(path) : path;+ // The inspector header already names the file, so the card only carries its path.return (<Flexbox className={styles.container} gap={8}>- <Flexbox>- <Flexbox- horizontal- align={'center'}- className={styles.header}- gap={12}- justify={'space-between'}- >- <Flexbox horizontal align={'center'} flex={1} gap={0} style={{ overflow: 'hidden' }}>- <FileIcon fileName={filename} fileType={fileType} size={16} variant={'raw'} />- <Flexbox horizontal>- <Text ellipsis className={styles.fileName}>- {filename}- </Text>- {(handleOpenFile || handleOpenFolder) && (- <Flexbox- horizontal- className={`${styles.actions} local-file-actions`}- gap={2}- style={{ marginLeft: 8 }}- >- {handleOpenFile && (- <ActionIcon- icon={ExternalLink}- size="small"- title={t('localFiles.openFile')}- onClick={handleOpenFile}- />- )}- {handleOpenFolder && (- <ActionIcon- icon={FolderOpen}- size="small"- title={t('localFiles.openFolder')}- onClick={handleOpenFolder}- />- )}- </Flexbox>- )}- </Flexbox>- </Flexbox>- </Flexbox>-- <Text ellipsis className={styles.path} type={'secondary'}>+ <Flexbox horizontal align={'center'} gap={4}>+ <Text ellipsis className={styles.path} title={path} type={'secondary'}>{displayPath}</Text>+ {(openInPanel || handleOpenFile || handleOpenFolder) && (+ <Flexbox+ horizontal+ className={`${styles.actions} local-file-actions`}+ flex={'none'}+ gap={2}+ >+ {openInPanel && (+ <ActionIcon+ icon={SquareArrowOutUpRight}+ size="small"+ title={t('localFiles.openInPanel')}+ onClick={(e) => {+ e.stopPropagation();+ openInPanel();+ }}+ />+ )}+ {handleOpenFile && (+ <ActionIcon+ icon={ExternalLink}+ size="small"+ title={t('localFiles.openFile')}+ onClick={handleOpenFile}+ />+ )}+ {handleOpenFolder && (+ <ActionIcon+ icon={FolderOpen}+ size="small"+ title={t('localFiles.openFolder')}+ onClick={handleOpenFolder}+ />+ )}+ </Flexbox>+ )}</Flexbox><Flexbox@@ -177,12 +218,19 @@ const ReadFileView = memo<ReadFileState>(>{isHtml ? (<InlineHtmlPreview content={content} />- ) : fileType === 'md' ? (+ ) : isMarkdown ? (<Markdown style={{ overflow: 'auto' }}>{content}</Markdown>) : (- <div className={styles.previewText} style={{ width: '100%' }}>- {content}- </div>+ // The bare highlighter: `Highlighter` trims its input, which would+ // strip the first line's indentation and misalign the gutter.+ <SyntaxHighlighter+ className={styles.lineNumbers}+ language={fileType || 'text'}+ style={{ ...lineNumberVars, overflow: 'auto' }}+ variant={'borderless'}+ >+ {code}+ </SyntaxHighlighter>)}</Flexbox></Flexbox>diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.test.ts b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.test.tsindex 703a0553d5a..e3af271d982 100644--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.test.ts+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from 'vitest';-import { buildReadFileState } from './buildReadFileState';+import {+ buildReadFileState,+ getFirstLineNumber,+ stripFinalLineTerminator,+} from './buildReadFileState';describe('buildReadFileState', () => {it('keeps the card for a successful builtin read of an empty file', () => {@@ -71,3 +75,46 @@ describe('buildReadFileState', () => {expect(state?.loc).toEqual([5, 14]);});});++describe('getFirstLineNumber', () => {+ it('converts the builtin 0-based loc into a 1-based line number', () => {+ expect(getFirstLineNumber({ pluginState: { loc: [160, 181] } })).toBe(161);+ expect(getFirstLineNumber({ pluginState: { loc: [0, 200] } })).toBe(1);+ });++ it('keeps the 1-based offset arg used by OpenCode and Pi', () => {+ expect(getFirstLineNumber({ args: { offset: 20, path: '/repo/a.ts' } })).toBe(20);+ });++ it('prefers the reported loc over the requested offset', () => {+ expect(+ getFirstLineNumber({+ args: { offset: 5, path: '/repo/a.ts' },+ pluginState: { loc: [9, 20] },+ }),+ ).toBe(10);+ });++ it('uses the cloud sandbox 1-based startLine when no loc is reported', () => {+ expect(getFirstLineNumber({ pluginState: { startLine: 201 } })).toBe(201);+ });++ it('starts at line 1 when no range is known', () => {+ expect(getFirstLineNumber({ args: { path: '/repo/a.ts' } })).toBe(1);+ });+});++describe('stripFinalLineTerminator', () => {+ it('drops only the final line terminator', () => {+ expect(stripFinalLineTerminator('a\nb\n')).toBe('a\nb');+ expect(stripFinalLineTerminator('a\r\n')).toBe('a');+ });++ it('keeps intentional trailing blank lines', () => {+ expect(stripFinalLineTerminator('value\n\n')).toBe('value\n');+ });++ it('leaves content without a terminator unchanged', () => {+ expect(stripFinalLineTerminator('value')).toBe('value');+ });+});diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.ts b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.tsindex 158aad4aac9..603e235174c 100644--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.ts+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/buildReadFileState.ts@@ -62,3 +62,29 @@ export const buildReadFileState = ({path: filePath,};};++/**+ * 1-based number of the first line in the read content, used to seed the+ * preview's line-number gutter.+ *+ * Mirrors `ComputerRuntime`: a reported `loc` is a 0-based, end-exclusive+ * slice (see local-file-shell `readLocalFile`), so it wins; otherwise the+ * cloud sandbox's 1-based `startLine` arg lands in `pluginState.startLine`,+ * and OpenCode / Pi take a 1-based `offset` arg.+ */+export const getFirstLineNumber = ({+ args,+ pluginState,+}: Pick<BuildReadFileStateInput, 'args' | 'pluginState'>): number => {+ const loc = pluginState?.loc;+ if (loc) return Math.max(loc[0], 0) + 1;+ if (pluginState?.startLine !== undefined) return Math.max(pluginState.startLine, 1);+ if (args?.offset !== undefined) return Math.max(args.offset, 1);+ return 1;+};++/**+ * Drop only the file's final line terminator: it ends the last line rather+ * than starting a new one, while any blank lines before it are real content.+ */+export const stripFinalLineTerminator = (content: string): string => content.replace(/\r?\n$/, '');diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/index.tsxindex 4f14d2d619c..96029cac893 100644--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/index.tsx+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/index.tsx@@ -4,11 +4,14 @@ import type { BuiltinRenderProps } from '@lobechat/types';import { memo, useMemo } from 'react';import type { ReadFileArgs } from './buildReadFileState';-import { buildReadFileState } from './buildReadFileState';+import { buildReadFileState, getFirstLineNumber } from './buildReadFileState';import { parseOpenCodeReadContent } from './parseReadContent';import ReadFileSkeleton from './ReadFileSkeleton';import ReadFileView from './ReadFileView';+// Cloud-sandbox reuses this render; its files live in the sandbox, not on disk.+const CLOUD_SANDBOX_IDENTIFIER = 'lobe-cloud-sandbox';+const ReadFileQuery = memo<BuiltinRenderProps<ReadFileArgs, Partial<ReadFileState>, string>>(({ args, content, identifier, messageId, pluginError, pluginState }) => {const { isLoading } = useToolRenderCapabilities();@@ -25,13 +28,24 @@ const ReadFileQuery = memo<BuiltinRenderProps<ReadFileArgs, Partial<ReadFileStat[args, identifier, parsedContent, pluginError, pluginState],);+ const firstLineNumber = useMemo(+ () => getFirstLineNumber({ args, pluginState }),+ [args, pluginState],+ );+if (loading) {return <ReadFileSkeleton />;}if (!readState) return null;- return <ReadFileView {...readState} />;+ return (+ <ReadFileView+ {...readState}+ firstLineNumber={firstLineNumber}+ sandboxBacked={identifier === CLOUD_SANDBOX_IDENTIFIER}+ />+ );},);diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.tsindex 72fd28c37cf..3d73f34a090 100644--- a/packages/locales/src/default/tool.ts+++ b/packages/locales/src/default/tool.ts@@ -170,6 +170,7 @@ export default {'localFiles.open': 'Open','localFiles.openFile': 'Open File','localFiles.openFolder': 'Open Folder',+ 'localFiles.openInPanel': 'Open in side panel','localFiles.outOfScope.requestedPaths': 'Requested Paths','localFiles.outOfScope.warning':'Warning: The following path(s) are outside the configured working directory. Please confirm you want to allow access.',diff --git a/packages/shared-tool-ui/src/Inspector/ReadLocalFile/formatLineRange.test.ts b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/formatLineRange.test.tsnew file mode 100644index 00000000000..e593342e29a--- /dev/null+++ b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/formatLineRange.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { formatReadLineRange } from './formatLineRange';++describe('formatReadLineRange', () => {+ it('shifts the builtin 0-based, end-exclusive loc to 1-based lines', () => {+ expect(formatReadLineRange({ loc: [160, 181] })).toBe('L161-L181');+ expect(formatReadLineRange({ loc: [0, 200] })).toBe('L1-L200');+ });++ it('keeps 1-based startLine / endLine as-is', () => {+ expect(formatReadLineRange({ endLine: 20, startLine: 10 })).toBe('L10-L20');+ });++ it('derives the end from a 1-based offset and limit', () => {+ expect(formatReadLineRange({ limit: 10, offset: 5 })).toBe('L5-L14');+ expect(formatReadLineRange({ offset: 5 })).toBe('L5');+ });++ it('returns nothing without a range', () => {+ expect(formatReadLineRange({})).toBeUndefined();+ expect(formatReadLineRange()).toBeUndefined();+ });+});diff --git a/packages/shared-tool-ui/src/Inspector/ReadLocalFile/formatLineRange.ts b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/formatLineRange.tsnew file mode 100644index 00000000000..78e9887987f--- /dev/null+++ b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/formatLineRange.ts@@ -0,0 +1,27 @@+export interface ReadLineRangeSource {+ endLine?: number;+ limit?: number;+ loc?: [number, number];+ offset?: number;+ startLine?: number;+}++/**+ * Inspector label for the lines a read covers, e.g. `L161-L181`.+ *+ * `loc` is the builtin tools' 0-based, end-exclusive slice, so its start is+ * shifted to the 1-based line number the render's gutter shows; the end index+ * already equals the last 1-based line. `startLine` / `offset` are 1-based.+ */+export const formatReadLineRange = (source?: ReadLineRangeSource): string | undefined => {+ const start = source?.startLine ?? (source?.loc ? source.loc[0] + 1 : source?.offset);+ const end =+ source?.endLine ??+ source?.loc?.[1] ??+ (start !== undefined && source?.limit !== undefined+ ? start + Math.max(source.limit - 1, 0)+ : undefined);+ if (start !== undefined && end !== undefined) return `L${start}-L${end}`;+ if (start !== undefined) return `L${start}`;+ return undefined;+};diff --git a/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsx b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsxindex 95ec85d4d90..127542feb4d 100644--- a/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsx+++ b/packages/shared-tool-ui/src/Inspector/ReadLocalFile/index.tsx@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';import { FilePathDisplay, getFilePathDisplayInfo } from '../../components/FilePathDisplay';import { inspectorTextStyles, shinyTextStyles } from '../../styles';+import { formatReadLineRange } from './formatLineRange';interface ReadFileArgs {endLine?: number;@@ -45,19 +46,10 @@ export const createReadLocalFileInspector = (? `${imageTranslationKey}${isArgumentsStreaming || isLoading ? '.loading' : ''}`: translationKey;- const lineRange = useMemo(() => {- const source = args || partialArgs;- const start = source?.startLine ?? source?.loc?.[0] ?? source?.offset;- const end =- source?.endLine ??- source?.loc?.[1] ??- (start !== undefined && source?.limit !== undefined- ? start + Math.max(source.limit - 1, 0)- : undefined);- if (start !== undefined && end !== undefined) return `L${start}-L${end}`;- if (start !== undefined) return `L${start}`;- return undefined;- }, [args, partialArgs]);+ const lineRange = useMemo(+ () => formatReadLineRange(args || partialArgs),+ [args, partialArgs],+ );if (isArgumentsStreaming) {if (!filePath)diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.tsindex a5e6c418c6f..3ec5b71d0cb 100644--- a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts+++ b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts@@ -171,7 +171,9 @@ export const useOpenEditedFile = () => {const filesystemAvailable = (effectiveTarget === 'local' && isDesktop) || isDeviceMode;return useCallback(- (entry: OperationEditedFile): (() => void) | undefined => {+ (+ entry: Pick<OperationEditedFile, 'kind' | 'path' | 'sandboxBacked'>,+ ): (() => void) | undefined => {if (!canPreviewEditedFile(entry)) return undefined;if (entry.sandboxBacked) {if (!activeTopicId) return undefined;