From a341c1a2cdafd1d9948050022964b09c3296f603 Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Fri, 20 Nov 2026 17:23:54 +0800 Subject: [PATCH] fix(editor): open relative Markdown links as workspace files --- .../markdown/MarkdownRenderer.tsx | 100 ++---------------- .../markdown/markdownFileLinks.ts | 67 ++++++++++++ src/web-ui/src/locales/en-US/tools.json | 1 + src/web-ui/src/locales/zh-CN/tools.json | 1 + src/web-ui/src/locales/zh-TW/tools.json | 1 + .../editor/components/MarkdownEditor.tsx | 12 +-- .../meditor/components/MEditor.test.tsx | 60 ++++++++++- .../meditor/components/TiptapEditor.tsx | 48 +++++++++ src/web-ui/tests/e2e/markdown-editor.tsx | 29 +++-- tests/e2e/browser/markdown-editor.spec.ts | 35 ++++-- tests/e2e/config/wdio.markdown-browser.ts | 2 +- 11 files changed, 241 insertions(+), 115 deletions(-) create mode 100644 src/web-ui/src/infrastructure/markdown/markdownFileLinks.ts diff --git a/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx b/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx index 98e5112f19..69004e4d34 100644 --- a/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx +++ b/src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx @@ -38,7 +38,6 @@ import { recordReactRenderProfile, startupTrace, } from '@/shared/utils/startupTrace'; -import path from 'path-browserify'; import { getActiveSurfaceScope, onSurfaceActivated, type SurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; import './Markdown.scss'; import { useStreamingTextReveal } from './useStreamingTextReveal'; @@ -46,11 +45,17 @@ import { SessionMarkdownImage, type SessionImageReader } from './SessionMarkdown import { ImageLightbox, type ImageLightboxState } from '@/shared/ui/ImageLightbox'; import { rehypeSourceRange, type MarkdownSourceRange } from './rehypeSourceRange'; import { rehypeWindowsDrivePaths } from './rehypeWindowsDrivePaths'; +import { + COMPUTER_LINK_PREFIX, + FILE_LINK_PREFIX, + WORKSPACE_FOLDER_PLACEHOLDER, + isAbsoluteFilesystemPath, + normalizeFileLikeHref, + parseMarkdownLineRange, + resolveBaseRelativePath, +} from './markdownFileLinks'; const log = createLogger('Markdown'); -const COMPUTER_LINK_PREFIX = 'computer://'; -const FILE_LINK_PREFIX = 'file://'; -const WORKSPACE_FOLDER_PLACEHOLDER = '{{workspaceFolder}}'; const MarkdownMathRenderer = lazyWithRecovery(() => import('./MarkdownMathRenderer')); const ThinkingMarkdown = lazyWithRecovery(() => import('./ThinkingMarkdown')); @@ -386,46 +391,8 @@ function remarkAutolinkInternalLinks() { }; } -function normalizeFileLikeHref(rawHref: string): string { - if (/^openbitfun:\/\/(?:runtime|current-session)\//.test(rawHref)) return rawHref; - let filePath = rawHref; - - if (rawHref.startsWith(COMPUTER_LINK_PREFIX)) { - filePath = rawHref.slice(COMPUTER_LINK_PREFIX.length); - } else if (rawHref.startsWith(FILE_LINK_PREFIX)) { - filePath = rawHref.slice(FILE_LINK_PREFIX.length); - } else if (rawHref.startsWith('file:')) { - filePath = rawHref.slice('file:'.length); - } - - if (filePath.startsWith(WORKSPACE_FOLDER_PLACEHOLDER)) { - filePath = filePath.slice(WORKSPACE_FOLDER_PLACEHOLDER.length); - if (filePath.startsWith('/')) { - filePath = filePath.slice(1); - } - } - - // Normalize URI-style Windows drive paths to native absolute paths. - if (/^\/{2,}[A-Za-z]:[\\/]/.test(filePath)) { - filePath = filePath.replace(/^\/+/, '/'); - } - if (/^\/[A-Za-z]:[\\/]/.test(filePath)) { - filePath = filePath.slice(1); - } - - try { - return decodeURIComponent(filePath); - } catch { - return filePath; - } -} - -function normalizePath(filePath: string): string { - return filePath.replace(/\\/g, '/'); -} - function normalizeDisplayPath(filePath: string): string { - const normalized = normalizePath(filePath); + const normalized = filePath.replace(/\\/g, '/'); if (/^[A-Za-z]:\//.test(normalized)) { return normalized.replace(/\//g, '\\'); @@ -438,29 +405,6 @@ function normalizeDisplayPath(filePath: string): string { return normalized; } -function isAbsoluteFilesystemPath(filePath: string): boolean { - const normalized = normalizePath(filePath); - if (/^[A-Za-z]:/.test(normalized) || /^\/[A-Za-z]:/.test(normalized)) { - return true; - } - - return normalized.startsWith('/') && !normalized.startsWith('//'); -} - -function resolveBaseRelativePath(targetPath: string, basePath?: string): string { - if (/^openbitfun:\/\/(?:runtime|current-session)\//.test(targetPath)) return targetPath; - if (!targetPath || !basePath || isAbsoluteFilesystemPath(targetPath)) { - return targetPath; - } - - const normalizedTarget = normalizePath(targetPath); - if (normalizedTarget.startsWith('./') || normalizedTarget.startsWith('../')) { - return path.normalize(path.join(basePath, normalizedTarget)); - } - - return path.normalize(path.join(basePath, normalizedTarget)); -} - function resolveDisplayFilePath(targetPath: string, basePath?: string, workspacePath?: string): string { const baseResolved = resolveBaseRelativePath(targetPath, basePath); @@ -1082,27 +1026,6 @@ const MarkdownSurface = React.memo { - const cleanHash = hash.replace(/^#/, ''); - - const lineMatchWithL = cleanHash.match(/^L(\d+)(?:-L?(\d+))?$/i); - if (lineMatchWithL) { - const start = parseInt(lineMatchWithL[1], 10); - const end = lineMatchWithL[2] ? parseInt(lineMatchWithL[2], 10) : undefined; - return { start, end }; - } - - const lineMatchWithoutL = cleanHash.match(/^(\d+)(?:-(\d+))?$/); - if (lineMatchWithoutL) { - const start = parseInt(lineMatchWithoutL[1], 10); - const end = lineMatchWithoutL[2] ? parseInt(lineMatchWithoutL[2], 10) : undefined; - return { start, end }; - } - - return undefined; - }, []); - const handleFileViewRequest = useCallback((filePath: string, fileName: string, lineRange?: LineRange) => { if (onFileViewRequestRef.current) onFileViewRequestRef.current(filePath, fileName, lineRange); else if (fileAccessRef.current) openFileInBestTarget({ filePath, fileName, jumpToRange: lineRange, scope: fileAccessRef.current.scope }); @@ -1464,7 +1387,7 @@ const MarkdownSurface = React.memo = ({ hasChangesRef.current = hasChanges; }, [hasChanges]); - const basePath = React.useMemo(() => { - if (!filePath) return undefined; - const normalizedPath = filePath.replace(/\\/g, '/'); - const lastSlashIndex = normalizedPath.lastIndexOf('/'); - if (lastSlashIndex >= 0) { - return normalizedPath.substring(0, lastSlashIndex); - } - return undefined; - }, [filePath]); + const basePath = filePath ? dirnameAbsolutePath(filePath).replace(/\\/g, '/') || undefined : undefined; useEffect(() => { isUnmountedRef.current = false; diff --git a/src/web-ui/src/tools/editor/meditor/components/MEditor.test.tsx b/src/web-ui/src/tools/editor/meditor/components/MEditor.test.tsx index 76930a47cd..32da28a0d2 100644 --- a/src/web-ui/src/tools/editor/meditor/components/MEditor.test.tsx +++ b/src/web-ui/src/tools/editor/meditor/components/MEditor.test.tsx @@ -6,9 +6,15 @@ import { closeHistory } from '@tiptap/pm/history' import type { EditorInstance } from '../types' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ResourceFileContext, type ResourceFileAccess } from '@/infrastructure/api/ResourceFileContext' const mocks = vi.hoisted(() => ({ logError: vi.fn(), + openFile: vi.fn(), +})) + +vi.mock('@/shared/utils/tabUtils', () => ({ + openFileInBestTarget: mocks.openFile, })) vi.mock('@/infrastructure/markdown', () => ({ @@ -44,6 +50,7 @@ describe('MEditorErrorBoundary', () => { root = createRoot(container) consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined) mocks.logError.mockReset() + mocks.openFile.mockReset() }) afterEach(() => { @@ -83,7 +90,7 @@ describe('MEditorErrorBoundary', () => { return (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor }).editor; } - async function renderEditor(markdown = sourceMarkdown, readonly = false) { + async function renderEditor(markdown = sourceMarkdown, readonly = false, fileAccess?: ResourceFileAccess) { const ref = createRef(); const onDirtyChange = vi.fn(); const onSave = vi.fn(); @@ -97,8 +104,10 @@ describe('MEditorErrorBoundary', () => { - + + + ; } await act(async () => root.render()); @@ -106,6 +115,51 @@ describe('MEditorErrorBoundary', () => { return { ref, onDirtyChange, onSave, setDocumentValue: (next: string) => setDocumentValue(next) }; } + it('opens relative file links from the document directory on its owning device and workspace', async () => { + const scope = { + surfaceId: 'peer:desktop', + workspaceId: 'ssh-workspace', + workspacePath: '/workspace', + remoteConnectionId: 'ssh-connection', + }; + const markdown = '[Workflow](references/workflow.md) and [README](../README%20notes.md#L3-L5)'; + const { ref, onDirtyChange } = await renderEditor(markdown, false, { scope, files: { readFileContent: vi.fn() } }); + const [workflow, readme] = getEditor().view.dom.querySelectorAll('a'); + expect(workflow.getAttribute('href')).toBe('references/workflow.md'); + + function click(link: HTMLAnchorElement, options?: MouseEventInit) { + const event = new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1, ...options }); + act(() => { link.dispatchEvent(event); }); + expect(event.defaultPrevented).toBe(true); + } + + click(workflow); + expect(mocks.openFile).not.toHaveBeenCalled(); + click(workflow, { metaKey: true }); + expect(mocks.openFile).toHaveBeenCalledExactlyOnceWith({ + filePath: '/workspace/docs/references/workflow.md', scope, jumpToRange: undefined, + }); + + act(() => { container.querySelector('#readonly')?.click(); }); + click(readme); + expect(mocks.openFile).toHaveBeenLastCalledWith({ + filePath: '/workspace/README notes.md', scope, jumpToRange: { start: 3, end: 5 }, + }); + expect(ref.current?.getValue()).toBe(markdown); + expect(onDirtyChange).not.toHaveBeenCalledWith(true); + }); + + it('keeps external URLs and blocks unsafe schemes when rendering file links', async () => { + await renderEditor('[Web](https://example.com/docs) and [Unsafe](javascript:alert%281%29)', true); + const [web, unsafe] = getEditor().view.dom.querySelectorAll('a'); + expect(web.getAttribute('href')).toBe('https://example.com/docs'); + expect(unsafe.getAttribute('href')).toBe(''); + const event = new MouseEvent('click', { bubbles: true, cancelable: true }); + act(() => { unsafe.dispatchEvent(event); }); + expect(event.defaultPrevented).toBe(true); + expect(mocks.openFile).not.toHaveBeenCalled(); + }); + function pasteClipboard(text: string, html = '', metadata: Record = {}) { const event = new Event('paste', { bubbles: true, cancelable: true }); Object.defineProperty(event, 'clipboardData', { value: { diff --git a/src/web-ui/src/tools/editor/meditor/components/TiptapEditor.tsx b/src/web-ui/src/tools/editor/meditor/components/TiptapEditor.tsx index f1fd4e43cc..79a77e982d 100644 --- a/src/web-ui/src/tools/editor/meditor/components/TiptapEditor.tsx +++ b/src/web-ui/src/tools/editor/meditor/components/TiptapEditor.tsx @@ -21,9 +21,17 @@ import { Selection } from '@tiptap/pm/state'; import { useI18n } from '@/infrastructure/i18n'; import { editorAiAPI } from '@/infrastructure/api/service-api/EditorAiAPI'; +import { + isAbsoluteFilesystemPath, + isMarkdownFileHref, + normalizeFileLikeHref, + parseMarkdownLineRange, + resolveBaseRelativePath, +} from '@/infrastructure/markdown/markdownFileLinks'; import { notificationService } from '@/shared/notification-system'; import { createLogger } from '@/shared/utils/logger'; import { getMotionAwareScrollBehavior } from '@/shared/utils/motionPreference'; +import { openFileInBestTarget } from '@/shared/utils/tabUtils'; import { activeEditTargetService } from '@/tools/editor/services/ActiveEditTargetService'; import { MarkdownAlignmentExtension } from '../extensions/MarkdownAlignmentExtension'; import { BlockIdExtension } from '../extensions/BlockIdExtension'; @@ -430,6 +438,43 @@ export const TiptapEditor = React.forwardRef { + if (event.button > 1 || !(event.target instanceof Element)) return false; + const anchor = event.target.closest('a[href]'); + if (!anchor || !view.dom.contains(anchor)) return false; + const href = anchor.getAttribute('href'); + if (href === null || (href && !isMarkdownFileHref(href))) return false; + + event.preventDefault(); + if (!href) return true; + // A regular pointer click in an editable document still positions the caret. + if (view.editable && event.button === 0 && event.detail > 0 && !event.metaKey && !event.ctrlKey) return false; + + const { basePath, scope, fileLinkUnavailable } = fileLinkContextRef.current; + const [pathPart] = href.split(/[?#]/, 1); + const hashIndex = href.indexOf('#'); + const targetPath = normalizeFileLikeHref(pathPart); + if (!targetPath || (!basePath && !isAbsoluteFilesystemPath(targetPath)) || (!scope?.workspaceId && !scope?.workspacePath)) { + notificationService.warning(fileLinkUnavailable); + return true; + } + + try { + openFileInBestTarget({ + filePath: resolveBaseRelativePath(targetPath, basePath), + jumpToRange: hashIndex < 0 ? undefined : parseMarkdownLineRange(href.slice(hashIndex)), + scope, + }); + } catch (error) { + log.warn('Failed to open Markdown file link', { error }); + notificationService.warning(fileLinkUnavailable); + } + return true; + }, []); useEffect(() => { inlineAiStateRef.current = inlineAiState; @@ -568,6 +613,7 @@ export const TiptapEditor = React.forwardRef Boolean(defaultValidate(href) || isMarkdownFileHref(href)), }), // Placeholder decorations keep hints outside the document mutation path. // Direct paragraph DOM changes can reparse and destroy active embed editors. @@ -648,6 +694,8 @@ export const TiptapEditor = React.forwardRef { plainTextPasteRef.current = false; return false; diff --git a/src/web-ui/tests/e2e/markdown-editor.tsx b/src/web-ui/tests/e2e/markdown-editor.tsx index e07ed83114..3e70938657 100644 --- a/src/web-ui/tests/e2e/markdown-editor.tsx +++ b/src/web-ui/tests/e2e/markdown-editor.tsx @@ -8,15 +8,22 @@ import { I18nProvider, i18nService } from '../../src/infrastructure/i18n'; import { OpenBitFunDesignSystemProvider } from '../../src/infrastructure/design-system'; import { appearanceRuntime, buildBuiltinAppearance, openBitFunDarkPalette } from '../../src/infrastructure/appearance'; import { workspaceAPI } from '../../src/infrastructure/api'; +import { ResourceFileContext } from '../../src/infrastructure/api/ResourceFileContext'; +import { getActiveSurfaceId } from '../../src/infrastructure/peer-device/deviceSurface'; +import { useContentResourceStore } from '../../src/app/workbench/contentResourceStore'; import MarkdownEditor from '../../src/tools/editor/components/MarkdownEditor'; +import { EditorDocument, EditorDocumentContext } from '../../src/tools/editor/services/EditorDocument'; import { Preview } from './preview-reference'; // Only the filesystem boundary is replaced. The production file editor, parser, // renderer, dirty tracking, disk polling and save/conflict flow all run normally. const endpoint = 'http://127.0.0.1:1450'; -workspaceAPI.readFileContent = async () => (await fetch(`${endpoint}/file`)).text(); -workspaceAPI.getFileMetadata = async () => (await fetch(`${endpoint}/metadata`)).json(); -workspaceAPI.writeFileContent = async (_workspace, _file, content) => { +const filePath = '/workspace/docs/test.md'; +const scope = { surfaceId: getActiveSurfaceId(), workspaceId: 'fixture-workspace', workspacePath: '/workspace' }; +const editorDocument = new EditorDocument('markdown-browser-fixture', scope, filePath); +workspaceAPI.readWorkspaceFile = async () => (await fetch(`${endpoint}/file`)).text(); +workspaceAPI.getWorkspaceFileMetadata = async () => (await fetch(`${endpoint}/metadata`)).json(); +workspaceAPI.writeWorkspaceFile = async (_workspace, _file, content) => { const response = await fetch(`${endpoint}/file`, { method: 'PUT', body: content }); if (!response.ok) throw new Error('Fixture file write failed'); }; @@ -24,17 +31,27 @@ await i18nService.initialize(); await appearanceRuntime.initialize(buildBuiltinAppearance(openBitFunDarkPalette)); const showReference = new URLSearchParams(location.search).has('reference'); -const referenceContent = showReference ? await workspaceAPI.readFileContent('/workspace/test.md') : ''; +const referenceContent = showReference ? await workspaceAPI.readWorkspaceFile(scope.workspaceId, filePath) : ''; function Fixture() { const [dirty, setDirty] = useState(false); const [readonly, setReadonly] = useState(false); + const resources = useContentResourceStore(state => state.resources); return
{dirty ? 'Unsaved' : 'Saved'}
- {showReference ? : setDirty(changed)} />} + + {showReference ? : ( + + + setDirty(changed)} /> + + + )}
; } diff --git a/tests/e2e/browser/markdown-editor.spec.ts b/tests/e2e/browser/markdown-editor.spec.ts index 08fbaa8524..d9eafa8748 100644 --- a/tests/e2e/browser/markdown-editor.spec.ts +++ b/tests/e2e/browser/markdown-editor.spec.ts @@ -14,6 +14,29 @@ describe('Markdown rich text browser E2E', () => { }); + it('opens relative Markdown links as workspace files without browser navigation', async () => { + await browser.url('about:blank'); + await fetch('http://127.0.0.1:1450/file', { + method: 'PUT', + body: '[Workflow](references/workflow.md)\n\n[README](../README.md)', + }); + await editor.open(); + await $('[data-testid="readonly"]').click(); + await expect($('.ProseMirror')).toHaveAttribute('contenteditable', 'false'); + const startUrl = await browser.getUrl(); + const startWindows = await browser.getWindowHandles(); + + const [workflow, readme] = await editor.richText.$$('a'); + await expect(workflow).toHaveAttribute('href', 'references/workflow.md'); + await workflow.click(); + await readme.click(); + const opened = await $('[data-testid="opened-files"]').getProperty('textContent'); + expect(opened?.trim().split('\n')).toEqual(['/workspace/docs/references/workflow.md', '/workspace/README.md']); + expect(await browser.getUrl()).toBe(startUrl); + expect(await browser.getWindowHandles()).toEqual(startWindows); + await expect(editor.dirty).toHaveText('Saved'); + }); + it('preserves escaped text, link titles and code spaces after a native edit, save and reload', async () => { const source = '# Edge cases\n\n[label]( "a & title")\n\n\\# literal\n\n`` padded ``\n\n~~**Remaining**: work~~\n\nAfter'; await editor.mode(1); @@ -134,11 +157,11 @@ describe('Markdown rich text browser E2E', () => { const box = checkbox.getBoundingClientRect(); return { ...appearance, taskOnOneLine: box.top < line.bottom && box.bottom > line.top }; }, reference); - await editor.block('mermaid').$('svg').waitForDisplayed(); + await editor.block('mermaid').$('.mermaid-block__diagram svg').waitForDisplayed(); const rich = await styles(false); expect(rich.taskOnOneLine).toBe(true); await browser.url('/tests/e2e/markdown-editor.html?reference=1'); - await $('.m-editor-preview .mermaid-block svg').waitForDisplayed(); + await $('.m-editor-preview .mermaid-block__diagram svg').waitForDisplayed(); const original = await styles(true); expect(rich).toEqual(original); }); @@ -295,11 +318,11 @@ describe('Markdown rich text browser E2E', () => { // Track only the fixture filesystem boundary; use the production image loader. const { workspaceAPI } = await import('/src/infrastructure/api/index.ts'); (window as any).__imageReads = []; - const original = workspaceAPI.readFileContent; - workspaceAPI.readFileContent = async (path: string) => { + const original = workspaceAPI.readWorkspaceFile; + workspaceAPI.readWorkspaceFile = async (workspaceId: string, path: string, encoding?: string) => { (window as any).__imageReads.push(path); if (path.endsWith('.png')) return 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAFElEQVR4nGNoIBEwjGoY1TB8NQAAJYSAEGy7FvQAAAAASUVORK5CYII='; - return original(path); + return original.call(workspaceAPI, workspaceId, path, encoding); }; }); for (const name of ['new.png', 'another.png']) { @@ -307,7 +330,7 @@ describe('Markdown rich text browser E2E', () => { await $('[data-testid="md-image-src"]').setValue(`./${name}`); await browser.keys('Enter'); await browser.waitUntil(async () => browser.execute((path: string) => - (window as any).__imageReads.includes(path), `/workspace/${name}`)); + (window as any).__imageReads.includes(path), `/workspace/docs/${name}`)); await expect($('[data-testid="md-image"] img')).toHaveAttribute('src', expect.stringContaining('data:image/png;base64,')); await browser.waitUntil(async () => browser.execute(() => document.querySelector('[data-testid="md-image"] img')?.naturalWidth === 16)); diff --git a/tests/e2e/config/wdio.markdown-browser.ts b/tests/e2e/config/wdio.markdown-browser.ts index 5485560938..c773caa60e 100644 --- a/tests/e2e/config/wdio.markdown-browser.ts +++ b/tests/e2e/config/wdio.markdown-browser.ts @@ -38,7 +38,7 @@ export const config: Options.Testrunner = { } else if (request.url === '/metadata') { const info = await stat(file); response.setHeader('Content-Type', 'application/json'); - response.end(JSON.stringify({ path: '/workspace/test.md', modified: info.mtimeMs, size: info.size, isFile: true, isDir: false })); + response.end(JSON.stringify({ path: '/workspace/docs/test.md', modified: info.mtimeMs, size: info.size, isFile: true, isDir: false })); } else { response.statusCode = 404; response.end(); } } catch (error) { response.statusCode = 500; response.end(String(error)); } });