🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-document): render non-markdown docs as readonly highlight (#15272)
Innei1ae8498fc76c
diff --git a/src/features/FileViewer/Renderer/Code/index.tsx b/src/features/FileViewer/Renderer/Code/index.tsxindex c52d0d879e1..0d6b200fd80 100644--- a/src/features/FileViewer/Renderer/Code/index.tsx+++ b/src/features/FileViewer/Renderer/Code/index.tsx@@ -5,6 +5,7 @@ import { createStaticStyles } from 'antd-style';import { memo } from 'react';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import { getLanguageFromFilename } from '@/utils/fileLanguage';import { useTextFileLoader } from '../../hooks/useTextFileLoader';@@ -16,195 +17,15 @@ const styles = createStaticStyles(({ css }) => ({`,}));-const getLanguage = (fileName?: string): string => {- if (!fileName) return 'txt';-- const ext = fileName.toLowerCase().split('.').pop();- switch (ext) {- // JavaScript/TypeScript- case 'js':- case 'mjs':- case 'cjs': {- return 'javascript';- }- case 'ts': {- return 'typescript';- }- case 'tsx': {- return 'tsx';- }- case 'jsx': {- return 'jsx';- }-- // Python- case 'py':- case 'pyw': {- return 'python';- }-- // Java/JVM Languages- case 'java': {- return 'java';- }- case 'kt':- case 'kts': {- return 'kotlin';- }- case 'scala': {- return 'scala';- }- case 'groovy': {- return 'groovy';- }-- // C/C++- case 'c':- case 'h': {- return 'c';- }- case 'cpp':- case 'cxx':- case 'cc':- case 'hpp':- case 'hxx': {- return 'cpp';- }-- // C#- case 'cs': {- return 'csharp';- }-- // Go- case 'go': {- return 'go';- }-- // Rust- case 'rs': {- return 'rust';- }-- // Ruby- case 'rb': {- return 'ruby';- }-- // PHP- case 'php': {- return 'php';- }-- // Swift- case 'swift': {- return 'swift';- }-- // Shell- case 'sh':- case 'bash':- case 'zsh': {- return 'bash';- }-- // Web- case 'html':- case 'htm': {- return 'html';- }- case 'css': {- return 'css';- }- case 'scss': {- return 'scss';- }- case 'sass': {- return 'sass';- }- case 'less': {- return 'less';- }-- // Data formats- case 'json': {- return 'json';- }- case 'xml': {- return 'xml';- }- case 'yaml':- case 'yml': {- return 'yaml';- }- case 'toml': {- return 'toml';- }-- // Markdown- case 'md':- case 'mdx': {- return 'markdown';- }-- // SQL- case 'sql': {- return 'sql';- }-- // Other popular languages- case 'lua': {- return 'lua';- }- case 'r': {- return 'r';- }- case 'dart': {- return 'dart';- }- case 'elixir':- case 'ex':- case 'exs': {- return 'elixir';- }- case 'erl':- case 'hrl': {- return 'erlang';- }- case 'clj':- case 'cljs':- case 'cljc': {- return 'clojure';- }- case 'vim': {- return 'vim';- }- case 'dockerfile': {- return 'dockerfile';- }- case 'graphql':- case 'gql': {- return 'graphql';- }-- default: {- return 'txt';- }- }-};-interface CodeViewerProps {fileId: string;fileName?: string;url: string | null;}-/**- * Render any code file.- */const CodeViewer = memo<CodeViewerProps>(({ url, fileName }) => {const { fileData, loading } = useTextFileLoader(url);- const language = getLanguage(fileName);+ const language = getLanguageFromFilename(fileName);return (<Flexbox className={styles.page}>diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsxindex 196a32ac8ee..2bec96d2de6 100644--- a/src/features/Portal/Document/Body.test.tsx+++ b/src/features/Portal/Document/Body.test.tsx@@ -26,10 +26,30 @@ vi.mock('@lobehub/ui', () => ({ActionIcon: () => null,Button: ({ children }: { children: ReactNode }) => <button>{children}</button>,Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Highlighter: ({ children }: { children: ReactNode }) => (+ <pre data-testid="highlighter">{children}</pre>+ ),Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,TextArea: () => <textarea />,}));+const mockDocumentMeta = vi.hoisted(() => ({+ current: { content: '', filename: 'doc.md' } as {+ content?: string;+ fileType?: string | null;+ filename?: string | null;+ title?: string | null;+ },+}));++vi.mock('@/libs/swr', () => ({+ useClientDataSWR: () => ({ data: mockDocumentMeta.current }),+}));++vi.mock('@/services/document', () => ({+ documentService: { getDocumentById: vi.fn() },+}));+vi.mock('./EditorCanvas', () => ({default: () => <div data-testid="editor-canvas" />,}));@@ -101,6 +121,7 @@ describe('DocumentBody', () => {beforeEach(() => {mockAgentState.current.activeAgentId = 'agent-1';mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = false;+ mockDocumentMeta.current = { content: '', filename: 'doc.md' };});it('does not render FloatingChatPanel when the lab feature is disabled', () => {@@ -116,4 +137,36 @@ describe('DocumentBody', () => {expect(screen.getByTestId('floating-chat-panel')).toBeDefined();});++ it('renders Highlighter for non-markdown files', () => {+ mockDocumentMeta.current = { content: 'raw log content', filename: 'topic_call.txt' };++ render(<DocumentBody />);++ expect(screen.getByTestId('highlighter')).toBeDefined();+ expect(screen.queryByTestId('editor-canvas')).toBeNull();+ });++ it('renders EditorCanvas for markdown files', () => {+ mockDocumentMeta.current = { content: '# hi', filename: 'note.md' };++ render(<DocumentBody />);++ expect(screen.getByTestId('editor-canvas')).toBeDefined();+ expect(screen.queryByTestId('highlighter')).toBeNull();+ });++ it('renders EditorCanvas for notebook documents that have no filename', () => {+ mockDocumentMeta.current = {+ content: '# notes',+ fileType: 'markdown',+ filename: null,+ title: 'Meeting notes',+ };++ render(<DocumentBody />);++ expect(screen.getByTestId('editor-canvas')).toBeDefined();+ expect(screen.queryByTestId('highlighter')).toBeNull();+ });});diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsxindex 8765586191b..f0a0aa135f5 100644--- a/src/features/Portal/Document/Body.tsx+++ b/src/features/Portal/Document/Body.tsx@@ -1,6 +1,6 @@'use client';-import { ActionIcon, Button, Flexbox, Text, TextArea } from '@lobehub/ui';+import { ActionIcon, Button, Flexbox, Highlighter, Text, TextArea } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import { CheckIcon, PencilIcon, XIcon } from 'lucide-react';import type { ChangeEvent } from 'react';@@ -8,12 +8,15 @@ import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import FloatingChatPanel from '@/features/FloatingChatPanel';+import { useClientDataSWR } from '@/libs/swr';+import { documentService } from '@/services/document';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';import { useDocumentStore } from '@/store/document';import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';+import { getDocumentRenderMode } from '@/utils/documentRenderMode';import {getSkillMarkdownMetadataError,parseSkillMarkdownFrontmatterFields,@@ -209,13 +212,27 @@ const DocumentBody = memo(() => {);const isSkillMarkdown = contentFormat === 'skillMarkdown';+ const { data: documentMeta } = useClientDataSWR(+ documentId ? ['portal-document-header', documentId] : null,+ () => documentService.getDocumentById(documentId!),+ );+ const renderMode = documentMeta+ ? getDocumentRenderMode(documentMeta)+ : { mode: 'editor' as const };+return (<Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}><div className={styles.content}>{documentId && isSkillMarkdown && (<SkillFrontmatterBlock documentId={documentId} frontmatter={skillFrontmatter} />)}- <EditorCanvas />+ {renderMode.mode === 'highlight' ? (+ <Highlighter language={renderMode.language} showLanguage={false} variant="borderless">+ {documentMeta?.content ?? ''}+ </Highlighter>+ ) : (+ <EditorCanvas />+ )}</div><TodoList />{enableFloatingChatPanel && activeAgentId && (diff --git a/src/features/Portal/Document/Header.tsx b/src/features/Portal/Document/Header.tsxindex fbe7c276da4..c457e8e9077 100644--- a/src/features/Portal/Document/Header.tsx+++ b/src/features/Portal/Document/Header.tsx@@ -8,6 +8,7 @@ import { documentService } from '@/services/document';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';import { oneLineEllipsis } from '@/styles';+import { getDocumentRenderMode } from '@/utils/documentRenderMode';import AutoSaveHint from './AutoSaveHint';@@ -20,6 +21,7 @@ const Header = () => {);const title = document?.filename || document?.title;+ const isReadonly = !!document && getDocumentRenderMode(document).mode === 'highlight';if (!documentId) return null;@@ -47,9 +49,11 @@ const Header = () => {{title}</Text></Flexbox>- <Flexbox horizontal align={'center'} gap={8}>- <AutoSaveHint />- </Flexbox>+ {!isReadonly && (+ <Flexbox horizontal align={'center'} gap={8}>+ <AutoSaveHint />+ </Flexbox>+ )}</Flexbox>);};diff --git a/src/server/services/toolExecution/__tests__/archiveToolResult.test.ts b/src/server/services/toolExecution/__tests__/archiveToolResult.test.tsindex dd402409236..5a0c4d57e64 100644--- a/src/server/services/toolExecution/__tests__/archiveToolResult.test.ts+++ b/src/server/services/toolExecution/__tests__/archiveToolResult.test.ts@@ -71,7 +71,7 @@ describe('archiveToolResultIfNeeded', () => {{ recursive: true },);expect(mockVfsService.write).toHaveBeenCalledWith(- './.tool-results/topic-1_call_1.md',+ './.tool-results/topic-1_call_1.txt','0123456789',{ agentId: 'agent-1', topicId: 'topic-1' },);@@ -80,9 +80,9 @@ describe('archiveToolResultIfNeeded', () => {topicId: 'topic-1',});expect(result.archived).toBe(true);- expect(result.archivePath).toBe('./.tool-results/topic-1_call_1.md');+ expect(result.archivePath).toBe('./.tool-results/topic-1_call_1.txt');expect(result.content).toContain('01234');- expect(result.content).toContain('./.tool-results/topic-1_call_1.md');+ expect(result.content).toContain('./.tool-results/topic-1_call_1.txt');expect(result.content).toContain('lobe-agent-documents');expect(result.content).toContain('readDocument');expect(result.content).toContain('agent-doc-1');diff --git a/src/server/services/toolExecution/archiveToolResult.ts b/src/server/services/toolExecution/archiveToolResult.tsindex a46308f0bdf..64470cfc514 100644--- a/src/server/services/toolExecution/archiveToolResult.ts+++ b/src/server/services/toolExecution/archiveToolResult.ts@@ -31,7 +31,7 @@ interface ArchiveToolResultParams {}const buildArchivePath = (topicId: string, toolCallId: string) =>- `${TOOL_RESULTS_DIR}/${topicId}_${toolCallId}.md`;+ `${TOOL_RESULTS_DIR}/${topicId}_${toolCallId}.txt`;const getErrorMessage = (error: unknown) =>error instanceof Error ? error.message : String(error || 'Unknown archive error');diff --git a/src/utils/__tests__/documentRenderMode.test.ts b/src/utils/__tests__/documentRenderMode.test.tsnew file mode 100644index 00000000000..73f6556e6ca--- /dev/null+++ b/src/utils/__tests__/documentRenderMode.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';++import { getDocumentRenderMode } from '../documentRenderMode';++describe('getDocumentRenderMode', () => {+ it('returns editor for SKILL.md skill index', () => {+ expect(getDocumentRenderMode({ fileType: 'skills/index', title: 'SKILL.md' })).toEqual({+ mode: 'editor',+ });+ });++ it('returns editor when filename ends with .md', () => {+ expect(getDocumentRenderMode({ filename: 'note.md', title: 'note' })).toEqual({+ mode: 'editor',+ });+ });++ it('returns editor when filename ends with .mdx', () => {+ expect(getDocumentRenderMode({ filename: 'note.mdx', title: 'note' })).toEqual({+ mode: 'editor',+ });+ });++ it('returns highlight with detected language for known code filenames', () => {+ expect(getDocumentRenderMode({ filename: 'topic_call.txt', title: 'topic_call' })).toEqual({+ language: 'txt',+ mode: 'highlight',+ });+ expect(getDocumentRenderMode({ filename: 'config.json', title: 'config' })).toEqual({+ language: 'json',+ mode: 'highlight',+ });+ });++ it('returns editor when filename is missing (notebook markdown document)', () => {+ expect(+ getDocumentRenderMode({ fileType: 'markdown', filename: null, title: 'Meeting notes' }),+ ).toEqual({ mode: 'editor' });+ });++ it('returns editor when filename is missing regardless of title extension shape', () => {+ expect(getDocumentRenderMode({ fileType: 'note', title: 'plans.draft' })).toEqual({+ mode: 'editor',+ });+ expect(getDocumentRenderMode({ fileType: 'agent/plan', title: 'Untitled' })).toEqual({+ mode: 'editor',+ });+ });+});diff --git a/src/utils/documentRenderMode.ts b/src/utils/documentRenderMode.tsnew file mode 100644index 00000000000..20adf78cdf8--- /dev/null+++ b/src/utils/documentRenderMode.ts@@ -0,0 +1,22 @@+import { getLanguageFromFilename } from './fileLanguage';+import { isSkillMarkdownDocument } from './skillMarkdown';++interface DocumentRenderModeFields {+ filename?: string | null;+ fileType?: string | null;+ title?: string | null;+}++export type DocumentRenderMode = { mode: 'editor' } | { language: string; mode: 'highlight' };++export const getDocumentRenderMode = (document: DocumentRenderModeFields): DocumentRenderMode => {+ if (isSkillMarkdownDocument(document)) return { mode: 'editor' };++ if (!document.filename) return { mode: 'editor' };++ const language = getLanguageFromFilename(document.filename);++ if (language === 'markdown') return { mode: 'editor' };++ return { language, mode: 'highlight' };+};diff --git a/src/utils/fileLanguage.ts b/src/utils/fileLanguage.tsnew file mode 100644index 00000000000..31f1d8a4856--- /dev/null+++ b/src/utils/fileLanguage.ts@@ -0,0 +1,160 @@+export const getLanguageFromFilename = (fileName?: string | null): string => {+ if (!fileName) return 'txt';++ const ext = fileName.toLowerCase().split('.').pop();+ switch (ext) {+ case 'js':+ case 'mjs':+ case 'cjs': {+ return 'javascript';+ }+ case 'ts': {+ return 'typescript';+ }+ case 'tsx': {+ return 'tsx';+ }+ case 'jsx': {+ return 'jsx';+ }++ case 'py':+ case 'pyw': {+ return 'python';+ }++ case 'java': {+ return 'java';+ }+ case 'kt':+ case 'kts': {+ return 'kotlin';+ }+ case 'scala': {+ return 'scala';+ }+ case 'groovy': {+ return 'groovy';+ }++ case 'c':+ case 'h': {+ return 'c';+ }+ case 'cpp':+ case 'cxx':+ case 'cc':+ case 'hpp':+ case 'hxx': {+ return 'cpp';+ }++ case 'cs': {+ return 'csharp';+ }++ case 'go': {+ return 'go';+ }++ case 'rs': {+ return 'rust';+ }++ case 'rb': {+ return 'ruby';+ }++ case 'php': {+ return 'php';+ }++ case 'swift': {+ return 'swift';+ }++ case 'sh':+ case 'bash':+ case 'zsh': {+ return 'bash';+ }++ case 'html':+ case 'htm': {+ return 'html';+ }+ case 'css': {+ return 'css';+ }+ case 'scss': {+ return 'scss';+ }+ case 'sass': {+ return 'sass';+ }+ case 'less': {+ return 'less';+ }++ case 'json': {+ return 'json';+ }+ case 'xml': {+ return 'xml';+ }+ case 'yaml':+ case 'yml': {+ return 'yaml';+ }+ case 'toml': {+ return 'toml';+ }++ case 'md':+ case 'mdx': {+ return 'markdown';+ }++ case 'sql': {+ return 'sql';+ }++ case 'lua': {+ return 'lua';+ }+ case 'r': {+ return 'r';+ }+ case 'dart': {+ return 'dart';+ }+ case 'elixir':+ case 'ex':+ case 'exs': {+ return 'elixir';+ }+ case 'erl':+ case 'hrl': {+ return 'erlang';+ }+ case 'clj':+ case 'cljs':+ case 'cljc': {+ return 'clojure';+ }+ case 'vim': {+ return 'vim';+ }+ case 'dockerfile': {+ return 'dockerfile';+ }+ case 'graphql':+ case 'gql': {+ return 'graphql';+ }++ default: {+ return 'txt';+ }+ }+};