Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 11 additions & 89 deletions src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,24 @@ 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';
import { SessionMarkdownImage, type SessionImageReader } from './SessionMarkdownImage';
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'));
Expand Down Expand Up @@ -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, '\\');
Expand All @@ -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);

Expand Down Expand Up @@ -1082,27 +1026,6 @@ const MarkdownSurface = React.memo<MarkdownRendererProps & { thinking?: boolean;
[markdownContent],
);

// Parse line ranges like #L42 / 1-20
const parseLineRange = useCallback((hash: string): LineRange | undefined => {
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 });
Expand Down Expand Up @@ -1464,7 +1387,7 @@ const MarkdownSurface = React.memo<MarkdownRendererProps & { thinking?: boolean;
if (hashIndex !== -1) {
const hash = filePath.substring(hashIndex);
filePath = filePath.substring(0, hashIndex);
lineRange = parseLineRange(hash);
lineRange = parseMarkdownLineRange(hash);
} else {
// Note: exclude Windows drive letters (e.g. C:)
const colonMatch = filePath.match(/^(.+?):(\d+)(?:-(\d+))?$/);
Expand Down Expand Up @@ -1762,7 +1685,6 @@ const MarkdownSurface = React.memo<MarkdownRendererProps & { thinking?: boolean;
handleOpenBuiltInBrowserLink,
handleOpenVisualization,
handleTabOpen,
parseLineRange,
basePathRef,
currentWorkspacePathRef,
expandDetailsByDefaultRef,
Expand Down
67 changes: 67 additions & 0 deletions src/web-ui/src/infrastructure/markdown/markdownFileLinks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import path from 'path-browserify';
import type { LineRange } from '@/shared/editor/LineRange';

export const COMPUTER_LINK_PREFIX = 'computer://';
export const FILE_LINK_PREFIX = 'file://';
export const WORKSPACE_FOLDER_PLACEHOLDER = '{{workspaceFolder}}';

/** A filesystem destination that can be handled by the owning workspace. */
export function isMarkdownFileHref(href: string): boolean {
if (!href || href !== href.trim() || /\p{Cc}/u.test(href)) return false;
if (/^[?#]|^[\\/]{2}/.test(href)) return false;
return href.startsWith('file:') || href.startsWith(COMPUTER_LINK_PREFIX)
|| /^[a-z]:[\\/]/i.test(href) || !/^[^/\\?#]*:/.test(href);
}

export 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;
}
}

export function isAbsoluteFilesystemPath(filePath: string): boolean {
const normalized = filePath.replace(/\\/g, '/');
return /^\/?[A-Za-z]:/.test(normalized) || (normalized.startsWith('/') && !normalized.startsWith('//'));
}

export function resolveBaseRelativePath(targetPath: string, basePath?: string): string {
if (/^openbitfun:\/\/(?:runtime|current-session)\//.test(targetPath)) return targetPath;
if (!targetPath || !basePath || isAbsoluteFilesystemPath(targetPath)) return targetPath;
return path.posix.join(basePath, targetPath.replace(/\\/g, '/'));
}

export function parseMarkdownLineRange(hash: string): LineRange | undefined {
const cleanHash = hash.replace(/^#/, '');
const match = cleanHash.match(/^L(\d+)(?:-L?(\d+))?$/i) ?? cleanHash.match(/^(\d+)(?:-(\d+))?$/);
if (!match) return undefined;
const [, start, end] = match;
return { start: parseInt(start, 10), end: end ? parseInt(end, 10) : undefined };
}
1 change: 1 addition & 0 deletions src/web-ui/src/locales/en-US/tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"copiedMarkdown": "Copied Markdown",
"viewModeLabel": "Document and source mode",
"notice": {
"fileLinkUnavailable": "This file link could not be opened from the current document.",
"sourcePreviewFallback": "Rich text could not load. You can continue editing the Markdown source."
}
},
Expand Down
1 change: 1 addition & 0 deletions src/web-ui/src/locales/zh-CN/tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"copiedMarkdown": "已复制 Markdown",
"viewModeLabel": "文档与源码模式",
"notice": {
"fileLinkUnavailable": "无法从当前文档打开此文件链接。",
"sourcePreviewFallback": "富文本加载失败,你可以继续编辑 Markdown 源码。"
}
},
Expand Down
1 change: 1 addition & 0 deletions src/web-ui/src/locales/zh-TW/tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"copiedMarkdown": "已複製 Markdown",
"viewModeLabel": "文件與源碼模式",
"notice": {
"fileLinkUnavailable": "無法從目前的文件開啟此檔案連結。",
"sourcePreviewFallback": "富文字載入失敗,你可以繼續編輯 Markdown 原始碼。"
}
},
Expand Down
12 changes: 2 additions & 10 deletions src/web-ui/src/tools/editor/components/MarkdownEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { createLogger } from '@/shared/utils/logger';
import { sendDebugProbe } from '@/shared/utils/debugProbe';
import { elapsedMs, nowMs } from '@/shared/utils/timing';
import { globalEventBus } from '@/infrastructure/event-bus';
import { isSamePath } from '@/shared/utils/pathUtils';
import { dirnameAbsolutePath, isSamePath } from '@/shared/utils/pathUtils';
import { startEditorFileSyncPolling } from '../utils/fileSyncPolling';
import { LoadingState } from '@openbitfun/ui';
import { useI18n } from '@/infrastructure/i18n';
Expand Down Expand Up @@ -139,15 +139,7 @@ const MarkdownEditor: React.FC<MarkdownEditorProps> = ({
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;
Expand Down
60 changes: 57 additions & 3 deletions src/web-ui/src/tools/editor/meditor/components/MEditor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => ({
Expand Down Expand Up @@ -44,6 +50,7 @@ describe('MEditorErrorBoundary', () => {
root = createRoot(container)
consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined)
mocks.logError.mockReset()
mocks.openFile.mockReset()
})

afterEach(() => {
Expand Down Expand Up @@ -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<EditorInstance>();
const onDirtyChange = vi.fn();
const onSave = vi.fn();
Expand All @@ -97,15 +104,62 @@ describe('MEditorErrorBoundary', () => {
<button id="readonly" onClick={() => setLocked(!locked)}>Toggle readonly</button>
<button id="reload" onClick={() => setValue('# Reloaded')}>Reload</button>
<button id="mode" onClick={() => setMode(mode === 'ir' ? 'edit' : 'ir')}>Switch</button>
<MEditor ref={ref} value={value} onChange={setValue} onDirtyChange={onDirtyChange}
onSave={onSave} mode={mode} readonly={locked} />
<ResourceFileContext.Provider value={fileAccess ?? null}>
<MEditor ref={ref} value={value} onChange={setValue} onDirtyChange={onDirtyChange}
onSave={onSave} mode={mode} readonly={locked} basePath={fileAccess ? '/workspace/docs' : undefined} />
</ResourceFileContext.Provider>
</>;
}
await act(async () => root.render(<Document />));
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
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<HTMLButtonElement>('#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<string, string> = {}) {
const event = new Event('paste', { bubbles: true, cancelable: true });
Object.defineProperty(event, 'clipboardData', { value: {
Expand Down
Loading
Loading