Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat(agent): highlight text files in the file preview dialog (#45032)
yyh5e0e69f500a8
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/detail-dialog.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/detail-dialog.spec.tsxnew file mode 100644index 00000000000..5b629f5f26d--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/detail-dialog.spec.tsx@@ -0,0 +1,103 @@+import type { AgentSkillDetail } from '../detail-dialog'+import { Dialog } from '@langgenius/dify-ui/dialog'+import { codeToTokens, isSupportedLanguage } from '@pierre/highlights'+import { render, screen, waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createTestQueryClient } from '@/test/query-client'+import { AgentSkillDetailDialog } from '../detail-dialog'++// Spy on the real highlighter so tests can assert which files reach the lexers.+vi.mock('@pierre/highlights', { spy: true })++const mockCodeToTokens = vi.mocked(codeToTokens)+const mockIsSupportedLanguage = vi.mocked(isSupportedLanguage)++const highlighterQueryKey = ['agent-v2', 'file-highlighter']++const renderPreview = (+ filePreview: AgentSkillDetail['filePreview'],+ queryClient = createTestQueryClient(),+) =>+ render(+ <QueryClientTestProvider queryClient={queryClient}>+ <Dialog open>+ <AgentSkillDetailDialog+ skillName="demo"+ detail={{ description: 'Demo files', files: [], filePreview, sections: [] }}+ />+ </Dialog>+ </QueryClientTestProvider>,+ )++const getLineCode = (text: string) =>+ screen.getByText((_, element) => element?.tagName === 'CODE' && element.textContent === text)++const waitForHighlighted = (text: string) =>+ waitFor(() => expect(getLineCode(text).children.length).toBeGreaterThan(0), { timeout: 5000 })++describe('AgentSkillDetailDialog file preview', () => {+ beforeEach(() => {+ mockCodeToTokens.mockClear()+ mockIsSupportedLanguage.mockClear()+ })++ it('should color tokens for both themes', async () => {+ renderPreview({ content: 'const a = 1\n\nexport { a }', fileName: 'run.ts' })++ await waitForHighlighted('const a = 1')+ const token = getLineCode('const a = 1').querySelector('span')+ expect(token?.style.getPropertyValue('--hls-light')).not.toBe('')+ expect(token?.style.getPropertyValue('--hls-dark')).not.toBe('')+ expect(getLineCode('export { a }').children.length).toBeGreaterThan(0)+ })++ it.each([+ ['SKILL.md', 'md', '# Skill\n\nUse the tool.', '# Skill'],+ ['Dockerfile', 'dockerfile', 'FROM node:22\nRUN pnpm install', 'FROM node:22'],+ ['run.ts', 'ts', 'const a = 1\r\nconst b = 2', 'const b = 2'],+ ])('should highlight %s without changing line text', async (fileName, lang, content, line) => {+ renderPreview({ content, fileName })++ await waitForHighlighted(line)+ expect(mockCodeToTokens.mock.calls[0]![1]).toMatchObject({ lang })+ })++ it('should keep the full text of lines past the token limit', async () => {+ const longLine = `const a = '${'x'.repeat(1200)}'`+ renderPreview({ content: `const b = 1\n${longLine}`, fileName: 'run.ts' })++ await waitForHighlighted('const b = 1')+ expect(getLineCode(longLine)).toBeInTheDocument()+ })++ it('should render plain text files without loading the highlighter', () => {+ const queryClient = createTestQueryClient()+ renderPreview({ content: 'first line\nsecond line', fileName: 'notes.txt' }, queryClient)++ expect(getLineCode('first line').children).toHaveLength(0)+ expect(getLineCode('second line').children).toHaveLength(0)+ expect(queryClient.getQueryState(highlighterQueryKey)).toMatchObject({ fetchStatus: 'idle' })+ expect(mockIsSupportedLanguage).not.toHaveBeenCalled()+ })++ it('should render unsupported languages as plain text', async () => {+ renderPreview({ content: 'first line', fileName: 'notes.unknown-language' })++ await waitFor(() => expect(mockIsSupportedLanguage).toHaveBeenCalledWith('unknown-language'), {+ timeout: 5000,+ })+ expect(getLineCode('first line').children).toHaveLength(0)+ expect(mockCodeToTokens).not.toHaveBeenCalled()+ })++ it('should fall back to plain text when tokenizing fails', async () => {+ mockCodeToTokens.mockImplementationOnce(() => {+ throw new RangeError('lexer failed')+ })+ renderPreview({ content: 'const a = 1', fileName: 'run.ts' })++ await waitFor(() => expect(mockCodeToTokens).toHaveBeenCalled(), { timeout: 5000 })+ expect(getLineCode('const a = 1').children).toHaveLength(0)+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsxindex 848b99c6154..dd30de57ab9 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx@@ -17,9 +17,11 @@ import {ScrollAreaThumb,ScrollAreaViewport,} from '@langgenius/dify-ui/scroll-area'-import { useCallback, useId } from 'react'+import { queryOptions, useQuery } from '@tanstack/react-query'+import { useCallback, useId, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'+import { getFileExtension } from '@/features/agent-v2/file-icon'import { AgentFileTree } from '../files/tree'type AgentSkillDetailSection = {@@ -311,10 +313,54 @@ function AgentFilePreviewContent({)}+ return <AgentFileTextPreview content={content} fileName={fileName} />+}++const loadFileHighlighter = async () => {+ const [{ codeToTokens, isSupportedLanguage }, { default: light }, { default: dark }] =+ await Promise.all([+ import('@pierre/highlights'),+ import('@pierre/highlights/themes/github-light'),+ import('@pierre/highlights/themes/github-dark'),+ ])++ return (code: string, lang: string) => {+ if (!isSupportedLanguage(lang)) return undefined++ try {+ return codeToTokens(code, {+ lang,+ themes: { light, dark },+ defaultColor: false,+ tokenizeMaxLineLength: 1000,+ }).tokens+ } catch {+ return undefined+ }+ }+}++function AgentFileTextPreview({ content, fileName }: { content: string; fileName?: string }) {+ const extension = fileName ? getFileExtension(fileName) : ''+ const language = extension && extension !== 'txt' ? extension : undefined+ const { data: highlight } = useQuery(+ queryOptions({+ queryKey: ['agent-v2', 'file-highlighter'],+ queryFn: loadFileHighlighter,+ enabled: !!language,+ networkMode: 'always',+ staleTime: Infinity,+ }),+ )+ const highlightedLines = useMemo(+ () => (highlight && language ? highlight(content, language) : undefined),+ [content, highlight, language],+ )const lines = content.split('\n').map((line, index) => ({content: line,key: `${index}:${line}`,lineNumber: String(index + 1).padStart(2, '0'),+ tokens: highlightedLines?.[index],}))return (@@ -328,7 +374,18 @@ function AgentFilePreviewContent({{line.lineNumber}</span><code className="block min-w-0 flex-1 wrap-anywhere whitespace-pre-wrap text-text-primary">- {line.content}+ {line.tokens+ ? line.tokens.map((token, tokenIndex) => (+ <span+ // oxlint-disable-next-line react/no-array-index-key -- Tokens are positional within their line.+ key={tokenIndex}+ style={token.htmlStyle}+ className="[font-weight:var(--hls-light-font-weight)] text-(--hls-light) [font-style:var(--hls-light-font-style)] in-data-[theme=dark]:[font-weight:var(--hls-dark-font-weight)] in-data-[theme=dark]:text-(--hls-dark) in-data-[theme=dark]:[font-style:var(--hls-dark-font-style)]"+ >+ {token.content}+ </span>+ ))+ : line.content}</code></div>))}diff --git a/web/features/agent-v2/file-icon.ts b/web/features/agent-v2/file-icon.tsindex 104cc2b8e9c..6d3adf503b6 100644--- a/web/features/agent-v2/file-icon.ts+++ b/web/features/agent-v2/file-icon.ts@@ -49,7 +49,7 @@ function isFileTreeIconType(value: string): value is FileTreeIconType {return driveFileIconTypes.has(value)}-function getFileExtension(fileName: string) {+export function getFileExtension(fileName: string) {return fileName.split('.').pop()?.toLowerCase() ?? ''}