From 4e18e06f134b5263b59b080903f823f03a0048f5 Mon Sep 17 00:00:00 2001 From: ian-nocturne <326290628+ian-nocturne@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:03:42 +0900 Subject: [PATCH 1/5] fix(mobile): show workspace images in session Markdown tabs Session Markdown tabs now open in reading mode through MobileFileMarkdownPreview, which already loads images with files.readPreview. An Edit/Preview toggle in the action row switches to the rich editor and back without losing the local draft. Relative, absolute and file:// image and link paths resolve under the document's workspace root and are refused before any request when they escape it. Fixes #36332 Co-Authored-By: Claude Opus 5.5 --- .../src/files/MobileMarkdownPreviewImage.tsx | 20 +++- .../files/mobile-markdown-file-link.test.ts | 24 +++++ mobile/src/files/mobile-markdown-file-link.ts | 45 ++++++-- .../mobile-markdown-image-source.test.ts | 27 +++++ .../src/files/mobile-markdown-image-source.ts | 20 +--- mobile/src/i18n/locales/de.json | 6 +- mobile/src/i18n/locales/en.json | 6 +- mobile/src/i18n/locales/es.json | 6 +- mobile/src/i18n/locales/fr.json | 6 +- mobile/src/i18n/locales/ja.json | 6 +- mobile/src/i18n/locales/ko.json | 6 +- mobile/src/i18n/locales/pt.json | 6 +- mobile/src/i18n/locales/ru.json | 6 +- mobile/src/i18n/locales/tr.json | 6 +- mobile/src/i18n/locales/zh-Hant.json | 6 +- mobile/src/i18n/locales/zh.json | 6 +- .../session/MobileSessionActiveContent.tsx | 6 ++ .../MobileSessionMarkdownReader.test.tsx | 73 ++++++++++++- .../session/MobileSessionMarkdownReader.tsx | 100 ++++++++++++++++-- .../mobile-session-review-comment-styles.ts | 5 + .../session-markdown-source-copy.test.tsx | 8 ++ 21 files changed, 344 insertions(+), 50 deletions(-) diff --git a/mobile/src/files/MobileMarkdownPreviewImage.tsx b/mobile/src/files/MobileMarkdownPreviewImage.tsx index 847035aececf..d434602ea7db 100644 --- a/mobile/src/files/MobileMarkdownPreviewImage.tsx +++ b/mobile/src/files/MobileMarkdownPreviewImage.tsx @@ -14,11 +14,19 @@ type Props = { client: MobileFilePreviewRpcSender | null worktreeId: string documentPath: string + documentAbsolutePath?: string href: string alt: string } -export function MobileMarkdownPreviewImage({ client, worktreeId, documentPath, href, alt }: Props) { +export function MobileMarkdownPreviewImage({ + client, + worktreeId, + documentPath, + documentAbsolutePath, + href, + alt +}: Props) { useMobileColorScheme() const t = useMobileTranslation() const [load, setLoad] = useState<{ uri?: string; error?: string }>({}) @@ -27,7 +35,13 @@ export function MobileMarkdownPreviewImage({ client, worktreeId, documentPath, h const [expanded, setExpanded] = useState(false) useEffect(() => { let cancelled = false - void loadMarkdownPreviewImage(client, worktreeId, documentPath, href).then( + void loadMarkdownPreviewImage( + client, + worktreeId, + documentPath, + href, + documentAbsolutePath + ).then( (uri) => { if (!cancelled) { setLoad({ uri }) @@ -56,7 +70,7 @@ export function MobileMarkdownPreviewImage({ client, worktreeId, documentPath, h return () => { cancelled = true } - }, [client, worktreeId, documentPath, href, attempt]) + }, [client, worktreeId, documentPath, documentAbsolutePath, href, attempt]) return ( diff --git a/mobile/src/files/mobile-markdown-file-link.test.ts b/mobile/src/files/mobile-markdown-file-link.test.ts index 34d926ef4410..bc105ae611d0 100644 --- a/mobile/src/files/mobile-markdown-file-link.test.ts +++ b/mobile/src/files/mobile-markdown-file-link.test.ts @@ -51,6 +51,30 @@ describe('Markdown preview file links', () => { (path) => expect(mobileMarkdownFileLink(params, path)).toBeNull() ) + it.each([ + ['/remote/project/docs/notes.md', '/remote/project/images/photo.png', 'images/photo.png'], + ['/docs/notes.md', '/images/photo.png', 'images/photo.png'], + ['C:\\Project\\docs\\notes.md', 'c:\\project\\images\\photo.png', 'images/photo.png'], + ['C:\\docs\\notes.md', 'C:\\images\\photo.png', 'images/photo.png'], + ['\\\\host\\share\\docs\\notes.md', '\\\\host\\share\\images\\photo.png', 'images/photo.png'], + ['/remote/project/docs/notes.md', '../images/photo.png', 'images/photo.png'] + ])('resolves host paths using the document location %s', (absolute, path, relativePath) => { + expect(mobileMarkdownFileLink(params, path, absolute)?.params.relativePath).toBe(relativePath) + }) + + it.each([ + '/remote/project-sibling/private.md', + '../../private.md', + '/etc/private.md', + 'D:\\private.md' + ])('rejects a host path outside the known workspace: %s', (path) => { + expect(mobileMarkdownFileLink(params, path, '/remote/project/docs/notes.md')).toBeNull() + }) + + it('refuses an inconsistent document location', () => { + expect(mobileMarkdownFileLink(params, 'photo.png', '/different/notes.md')).toBeNull() + }) + it('does not reuse terminal artifact grants for another file', () => { expect(mobileMarkdownFileLink({ ...params, source: 'terminalArtifact' }, 'other.md')).toBeNull() }) diff --git a/mobile/src/files/mobile-markdown-file-link.ts b/mobile/src/files/mobile-markdown-file-link.ts index c5f8ea0552bc..f13d2354b3f0 100644 --- a/mobile/src/files/mobile-markdown-file-link.ts +++ b/mobile/src/files/mobile-markdown-file-link.ts @@ -9,20 +9,47 @@ import { type MobileFilePreviewRouteParams } from './mobile-file-preview-route' -export function mobileMarkdownFileLink(params: MobileFilePreviewRouteParams, pathText: string) { - if (params.source === 'terminalArtifact' || !params.relativePath) { +export function resolveMarkdownFilePath( + documentPath: string, + path: string, + documentAbsolutePath?: string +): string | null { + if (!path || path.includes('\0')) { return null } - const { path, line, column } = splitFilePathLineSuffix(pathText) - if (!path || /^[\\/]/.test(path) || isWindowsAbsolutePathLike(path) || path.includes('\0')) { + const source = documentPath.replaceAll('\\', '/') + if ( + !source || + source.startsWith('/') || + isWindowsAbsolutePathLike(source) || + source.split('/').includes('..') + ) { + return null + } + let root = '/workspace' + if (documentAbsolutePath) { + const absolute = documentAbsolutePath.replaceAll('\\', '/') + if (!absolute.endsWith(`/${source}`)) { + return null + } + root = absolute.slice(0, -source.length) + } else if (/^[\\/]/.test(path) || isWindowsAbsolutePathLike(path)) { return null } - // Resolve under a virtual root; the host still authorizes the actual workspace read. - const root = '/workspace' - const source = params.relativePath.replaceAll('\\', '/') const directory = source.slice(0, source.lastIndexOf('/') + 1) - const target = resolveRuntimePath(`${root}/${directory}`, path) - const relativePath = relativePathInsideRoot(root, target) + return relativePathInsideRoot(root, resolveRuntimePath(resolveRuntimePath(root, directory), path)) +} + +export function mobileMarkdownFileLink( + params: MobileFilePreviewRouteParams, + pathText: string, + documentAbsolutePath?: string +) { + if (params.source === 'terminalArtifact' || !params.relativePath) { + return null + } + const { path, line, column } = splitFilePathLineSuffix(pathText) + const relativePath = resolveMarkdownFilePath(params.relativePath, path, documentAbsolutePath) if (!relativePath) { return null } diff --git a/mobile/src/files/mobile-markdown-image-source.test.ts b/mobile/src/files/mobile-markdown-image-source.test.ts index 68b611b8a28c..d510212b8f34 100644 --- a/mobile/src/files/mobile-markdown-image-source.test.ts +++ b/mobile/src/files/mobile-markdown-image-source.test.ts @@ -61,6 +61,33 @@ describe('Markdown preview images', () => { worktree: 'id:wt', relativePath: 'docs/logo.svg' }) + + it('previews file URLs inside the known remote workspace without reading phone files', async () => { + const client = host() + await expect( + loadMarkdownPreviewImage( + client, + 'folder-workspace', + 'docs/readme.md', + 'file:///remote/project/assets/a%20b.png', + '/remote/project/docs/readme.md' + ) + ).resolves.toBe('data:image/png;base64,cG5n') + expect(client.sendRequest).toHaveBeenCalledWith('files.readPreview', { + worktree: 'id:folder-workspace', + relativePath: 'assets/a b.png' + }) + client.sendRequest.mockClear() + await expect( + loadMarkdownPreviewImage( + client, + 'folder-workspace', + 'docs/readme.md', + 'file:///remote/other/photo.png', + '/remote/project/docs/readme.md' + ) + ).rejects.toThrow() + expect(client.sendRequest).not.toHaveBeenCalled() }) it('lets native Image load public URLs without sending them to the workspace host', async () => { diff --git a/mobile/src/files/mobile-markdown-image-source.ts b/mobile/src/files/mobile-markdown-image-source.ts index b9507d021fba..da9544dab8f0 100644 --- a/mobile/src/files/mobile-markdown-image-source.ts +++ b/mobile/src/files/mobile-markdown-image-source.ts @@ -1,8 +1,4 @@ -import { - isWindowsAbsolutePathLike, - relativePathInsideRoot, - resolveRuntimePath -} from '../../../src/shared/cross-platform-path' +import { resolveMarkdownFilePath } from './mobile-markdown-file-link' import { routeMarkdownHref } from '../components/markdown-href-routing' import type { MobileFilePreviewRpcSender } from './mobile-file-preview-operations' import { loadMobileFilePreview } from './mobile-file-preview-request' @@ -13,7 +9,8 @@ export async function loadMarkdownPreviewImage( client: MobileFilePreviewRpcSender | null, worktreeId: string, documentPath: string, - href: string + href: string, + documentAbsolutePath?: string ): Promise { if (/^https?:\/\//i.test(href)) { return href @@ -22,16 +19,7 @@ export async function loadMarkdownPreviewImage( if (link.kind !== 'file') { throw new Error('Unsupported image location') } - const path = link.pathText - if (/^[\\/]/.test(path) || isWindowsAbsolutePathLike(path) || path.includes('\0')) { - throw new Error('Image must be inside this workspace') - } - const source = documentPath.replaceAll('\\', '/') - const directory = source.slice(0, source.lastIndexOf('/') + 1) - const relativePath = relativePathInsideRoot( - '/workspace', - resolveRuntimePath(`/workspace/${directory}`, path) - ) + const relativePath = resolveMarkdownFilePath(documentPath, link.pathText, documentAbsolutePath) const artifactKind = relativePath ? classifyMobileArtifact(relativePath) : null if (!relativePath || (artifactKind !== 'image' && artifactKind !== 'vector')) { throw new Error('Unsupported image location') diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index d8ee66b8a4ab..71338a3f0c9b 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -2131,7 +2131,11 @@ "discard": "Verwerfen", "dismissKeyboard": "Tastatur ausblenden", "dismissKeyboardHint": "Blendet die Bildschirmtastatur aus und lässt den Markdown-Editor geöffnet.", - "readOnly": "Schreibgeschützt" + "readOnly": "Schreibgeschützt", + "editLabel": "Markdown bearbeiten", + "previewLabel": "Markdown-Vorschau anzeigen", + "preview": "Vorschau", + "fileUnavailable": "Diese Datei liegt außerhalb des aktuellen Arbeitsbereichs oder ist nicht verfügbar." }, "nativeChatAttachActions": { "availableSkills": "{{count}} verfügbar", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index d3cd6fa4c011..d5777d0e6d60 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -1760,7 +1760,11 @@ "copyLoaded": "Copy loaded", "copyPathLabel": "Copy Markdown path", "copyPath": "Copy path", - "loading": "Loading document…" + "loading": "Loading document…", + "editLabel": "Edit Markdown", + "previewLabel": "Preview Markdown", + "preview": "Preview", + "fileUnavailable": "This file is outside the current workspace or is unavailable." }, "nativeChatCardHeaderAction": { "collapse": "Collapse" diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index bbd238409d30..b5f623781b63 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -2204,7 +2204,11 @@ "discard": "Descartar", "dismissKeyboard": "Ocultar teclado", "dismissKeyboardHint": "Oculta el teclado en pantalla y mantiene abierto el editor de Markdown.", - "readOnly": "Solo lectura" + "readOnly": "Solo lectura", + "editLabel": "Editar Markdown", + "previewLabel": "Vista previa de Markdown", + "preview": "Vista previa", + "fileUnavailable": "Este archivo está fuera del espacio de trabajo actual o no está disponible." }, "nativeChatAttachActions": { "availableSkills": "Disponibles: {{count}}", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index f7055803dcdd..6d4b53cec816 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -2204,7 +2204,11 @@ "discard": "Abandonner", "dismissKeyboard": "Masquer le clavier", "dismissKeyboardHint": "Masque le clavier virtuel et laisse l'éditeur Markdown ouvert.", - "readOnly": "Lecture seule" + "readOnly": "Lecture seule", + "editLabel": "Modifier le Markdown", + "previewLabel": "Aperçu du Markdown", + "preview": "Aperçu", + "fileUnavailable": "Ce fichier se trouve en dehors de l'espace de travail actuel ou n'est pas disponible." }, "nativeChatAttachActions": { "availableSkills": "Disponibles : {{count}}", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index a03eaffe77de..8c0401962da9 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -2127,7 +2127,11 @@ "discard": "破棄", "dismissKeyboard": "キーボードを閉じる", "dismissKeyboardHint": "Markdown エディターを開いたまま、ソフトウェアキーボードを非表示にします。", - "readOnly": "読み取り専用" + "readOnly": "読み取り専用", + "editLabel": "Markdown を編集", + "previewLabel": "Markdown をプレビュー", + "preview": "プレビュー", + "fileUnavailable": "このファイルは現在のワークスペースの外にあるか、利用できません。" }, "nativeChatAttachActions": { "availableSkills": "{{count}} 件が利用可能", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index f4ab2a50cc96..cf1a3a971dcb 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -2127,7 +2127,11 @@ "discard": "버리기", "dismissKeyboard": "키보드 닫기", "dismissKeyboardHint": "소프트웨어 키보드를 숨기고 Markdown 편집기를 열린 상태로 유지합니다.", - "readOnly": "읽기 전용" + "readOnly": "읽기 전용", + "editLabel": "Markdown 편집", + "previewLabel": "Markdown 미리보기", + "preview": "미리보기", + "fileUnavailable": "이 파일은 현재 워크스페이스 밖에 있거나 사용할 수 없습니다." }, "nativeChatAttachActions": { "availableSkills": "{{count}}개 사용 가능", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index 33382222722d..eb9411bd5eb3 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -2204,7 +2204,11 @@ "discard": "Descartar", "dismissKeyboard": "Ocultar teclado", "dismissKeyboardHint": "Oculta o teclado virtual e mantém o editor Markdown aberto.", - "readOnly": "Somente leitura" + "readOnly": "Somente leitura", + "editLabel": "Editar Markdown", + "previewLabel": "Pré-visualizar Markdown", + "preview": "Pré-visualização", + "fileUnavailable": "Este arquivo está fora do espaço de trabalho atual ou não está disponível." }, "nativeChatAttachActions": { "availableSkills": "Disponíveis: {{count}}", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 48686ae6d7db..e38d6094ba0f 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -2277,7 +2277,11 @@ "discard": "Отменить изменения", "dismissKeyboard": "Скрыть клавиатуру", "dismissKeyboardHint": "Скрывает экранную клавиатуру и оставляет редактор Markdown открытым.", - "readOnly": "Только чтение" + "readOnly": "Только чтение", + "editLabel": "Редактировать Markdown", + "previewLabel": "Предпросмотр Markdown", + "preview": "Предпросмотр", + "fileUnavailable": "Этот файл находится вне текущего рабочего пространства или недоступен." }, "nativeChatAttachActions": { "availableSkills": "Доступно: {{count}}", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index 0d4ce515455a..cf00e93342ed 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -2131,7 +2131,11 @@ "discard": "Vazgeç", "dismissKeyboard": "Klavyeyi gizle", "dismissKeyboardHint": "Ekran klavyesini gizler ve Markdown düzenleyicisini açık tutar.", - "readOnly": "Salt okunur" + "readOnly": "Salt okunur", + "editLabel": "Markdown'ı düzenle", + "previewLabel": "Markdown önizlemesi", + "preview": "Önizleme", + "fileUnavailable": "Bu dosya geçerli çalışma alanının dışında veya kullanılamıyor." }, "nativeChatAttachActions": { "availableSkills": "{{count}} beceri mevcut", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index f2a96b617814..cbffc0ac7f3e 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -2127,7 +2127,11 @@ "discard": "放棄", "dismissKeyboard": "收起鍵盤", "dismissKeyboardHint": "隱藏螢幕鍵盤,並保持 Markdown 編輯器開啟。", - "readOnly": "唯讀" + "readOnly": "唯讀", + "editLabel": "編輯 Markdown", + "previewLabel": "預覽 Markdown", + "preview": "預覽", + "fileUnavailable": "此檔案位於目前工作區之外或無法使用。" }, "nativeChatAttachActions": { "availableSkills": "{{count}} 項可用", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 2176c9aab6ef..a650c2a1aff7 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -2127,7 +2127,11 @@ "discard": "放弃", "dismissKeyboard": "关闭键盘", "dismissKeyboardHint": "隐藏软键盘,并保持 Markdown 编辑器打开。", - "readOnly": "只读" + "readOnly": "只读", + "editLabel": "编辑 Markdown", + "previewLabel": "预览 Markdown", + "preview": "预览", + "fileUnavailable": "此文件位于当前工作区之外或不可用。" }, "nativeChatAttachActions": { "availableSkills": "{{count}} 个可用", diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index d2fde1e7d60b..b54e1c8041de 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -152,6 +152,12 @@ export function MobileSessionActiveContent({ void readMarkdownTab(activeMarkdownTab)} onChange={(content) => updateMarkdownLocalContent(activeMarkdownTab.id, content)} diff --git a/mobile/src/session/MobileSessionMarkdownReader.test.tsx b/mobile/src/session/MobileSessionMarkdownReader.test.tsx index e3d6c1b1dd00..532cdb1ef951 100644 --- a/mobile/src/session/MobileSessionMarkdownReader.test.tsx +++ b/mobile/src/session/MobileSessionMarkdownReader.test.tsx @@ -16,6 +16,14 @@ vi.mock('../components/MobileRichMarkdownEditor', () => ({ MobileRichMarkdownEditor: 'MobileRichMarkdownEditor' })) vi.mock('./mobile-session-styles', () => ({ styles: {} })) +vi.mock('../files/MobileFileMarkdownPreview', () => ({ + MobileFileMarkdownPreview: 'MobileFileMarkdownPreview' +})) +const { pushFile } = vi.hoisted(() => ({ pushFile: vi.fn() })) +vi.mock('../navigation/workspace-route-handoff', () => ({ + useWorkspaceRouteHandoff: () => ({ push: pushFile }) +})) +vi.mock('../platform/external-link', () => ({ openExternalLink: vi.fn() })) const doc: MarkdownDocState = { status: 'ready', @@ -38,6 +46,10 @@ describe('live session markdown reader copy', () => { renderer = create( createElement(MarkdownReader, { documentId: 'doc', + hostId: 'remote', + worktreeId: 'folder:project', + relativePath: 'docs/notes.md', + filePath: '/remote/project/docs/notes.md', doc: value, onCopy, onCopyPath, @@ -70,12 +82,11 @@ describe('live session markdown reader copy', () => { ('truncated' in fields ? 'Copy loaded Markdown source' : 'Copy Markdown source') ) expect(copy).toBeDefined() - expect(buttons()[0]).toBe(copy) expect(copy?.props.accessibilityRole).toBe('button') expect(copy?.props.disabled).not.toBe(true) act(() => copy?.props.onPress()) expect(onCopy).toHaveBeenCalledOnce() - const pathCopy = buttons()[1]! + const pathCopy = buttons()[buttons().indexOf(copy!) + 1]! expect(pathCopy.props.accessibilityLabel).toBe('Copy Markdown path') expect(pathCopy.props.accessibilityRole).toBe('button') expect(pathCopy.props.disabled).not.toBe(true) @@ -87,6 +98,64 @@ describe('live session markdown reader copy', () => { } ) + it('opens in reading mode and preserves the current draft across explicit editing', () => { + render({ ...doc, isDirty: true, localContent: '# Draft' }) + const preview = () => renderer!.root.findByType('MobileFileMarkdownPreview') + expect(preview().props.content).toBe('# Draft') + act(() => + buttons() + .find((button) => button.props.accessibilityLabel === 'Edit Markdown')! + .props.onPress() + ) + expect(renderer!.root.findByType('MobileRichMarkdownEditor').props.content).toBe('# Draft') + act(() => + buttons() + .find((button) => button.props.accessibilityLabel === 'Preview Markdown')! + .props.onPress() + ) + expect(preview().props.content).toBe('# Draft') + expect(onSave).not.toHaveBeenCalled() + expect(onDiscard).not.toHaveBeenCalled() + }) + + it('keeps Preview available when the document turns read-only while editing', () => { + render() + const toggle = () => + buttons().find((button) => + ['Edit Markdown', 'Preview Markdown'].includes(button.props.accessibilityLabel) + )! + act(() => toggle().props.onPress()) + const props = renderer!.root.findByType(MarkdownReader).props + act(() => + renderer!.update( + createElement(MarkdownReader, { ...props, doc: { ...doc, editable: false } }) + ) + ) + expect(toggle().props.accessibilityLabel).toBe('Preview Markdown') + expect(toggle().props.disabled).toBe(false) + act(() => toggle().props.onPress()) + expect(toggle().props.accessibilityLabel).toBe('Edit Markdown') + expect(toggle().props.disabled).toBe(true) + }) + + it('opens a workspace file from the live document on the same remote host', () => { + render() + act(() => + renderer!.root + .findByType('MobileFileMarkdownPreview') + .props.onOpenFile('/remote/project/assets/photo.png') + ) + expect(pushFile).toHaveBeenCalledWith({ + pathname: '/h/[hostId]/files/preview/[worktreeId]', + params: { + hostId: 'remote', + worktreeId: 'folder:project', + source: 'worktree', + relativePath: 'assets/photo.png' + } + }) + }) + it('keeps loading and error states free of copy actions', () => { render({ status: 'loading' }) expect(buttons()).toHaveLength(0) diff --git a/mobile/src/session/MobileSessionMarkdownReader.tsx b/mobile/src/session/MobileSessionMarkdownReader.tsx index 1dc322d2a89f..dda245541062 100644 --- a/mobile/src/session/MobileSessionMarkdownReader.tsx +++ b/mobile/src/session/MobileSessionMarkdownReader.tsx @@ -1,4 +1,10 @@ import { useState } from 'react' +import { MobileFileMarkdownPreview } from '../files/MobileFileMarkdownPreview' +import type { MobileFilePreviewRpcSender } from '../files/mobile-file-preview-operations' +import { mobileMarkdownFileLink } from '../files/mobile-markdown-file-link' +import { routeMarkdownHref } from '../components/markdown-href-routing' +import { openExternalLink } from '../platform/external-link' +import { useWorkspaceRouteHandoff } from '../navigation/workspace-route-handoff' import { View, Text, Pressable, ActivityIndicator } from 'react-native' import { RefreshCw } from 'lucide-react-native' import { MobileRichMarkdownEditor } from '../components/MobileRichMarkdownEditor' @@ -13,6 +19,12 @@ import { MobileLoadErrorState, MobileStateView } from '../components/MobileState export function MarkdownReader({ documentId, + hostId, + worktreeId, + relativePath, + filePath, + client, + onLinkError, doc, onRefresh, onChange, @@ -23,6 +35,12 @@ export function MarkdownReader({ keyboardLift }: { documentId: string + hostId?: string + worktreeId?: string + relativePath?: string + filePath?: string + client?: MobileFilePreviewRpcSender | null + onLinkError?: (message: string) => void doc: MarkdownDocState | undefined onRefresh: () => void onChange: (content: string) => void @@ -34,6 +52,33 @@ export function MarkdownReader({ }) { useMobileColorScheme() const t = useMobileTranslation() + const router = useWorkspaceRouteHandoff() + const [editingDocumentId, setEditingDocumentId] = useState(null) + const editing = editingDocumentId === documentId + const openFile = (pathText: string) => { + const href = + hostId && worktreeId && relativePath + ? mobileMarkdownFileLink({ hostId, worktreeId, relativePath }, pathText, filePath) + : null + if (href) { + router.push(href) + } else { + onLinkError?.( + t( + 'session.markdownReader.fileUnavailable', + 'This file is outside the current workspace or is unavailable.' + ) + ) + } + } + const openLink = (href: string) => { + const route = routeMarkdownHref(href) + if (route.kind === 'file') { + openFile(route.pathText) + } else if (route.kind === 'web') { + openExternalLink(route.url) + } + } // Native Keyboard events under-report the WebView editor's covered area, so prefer the larger WebView-measured inset. const [webviewKeyboardInset, setWebviewKeyboardInset] = useState(0) const effectiveKeyboardLift = Math.max(keyboardLift, webviewKeyboardInset) @@ -49,22 +94,39 @@ export function MarkdownReader({ const statusText = markdownReaderStatusText(doc) const showRefresh = (doc.stale && !doc.isDirty) || !doc.editable const showSave = doc.isDirty || doc.saving + // Leaving the editor stays possible even when the document turns read-only mid-edit. + const editToggleDisabled = !editing && (!doc.editable || doc.saving) return ( - + {editing ? ( + + ) : ( + + )} ) : null} + [ + styles.markdownFloatingButton, + styles.markdownCopyButton, + editToggleDisabled && styles.markdownButtonDisabled, + pressed && pressedStyle + ]} + accessibilityRole="button" + accessibilityLabel={ + editing + ? t('session.markdownReader.previewLabel', 'Preview Markdown') + : t('session.markdownReader.editLabel', 'Edit Markdown') + } + disabled={editToggleDisabled} + onPress={() => setEditingDocumentId(editing ? null : documentId)} + > + + {editing ? t('session.markdownReader.preview', 'Preview') : t('common.edit', 'Edit')} + + [ styles.markdownFloatingButton, diff --git a/mobile/src/session/mobile-session-review-comment-styles.ts b/mobile/src/session/mobile-session-review-comment-styles.ts index c42ec9fe32f6..2b098ea3d04b 100644 --- a/mobile/src/session/mobile-session-review-comment-styles.ts +++ b/mobile/src/session/mobile-session-review-comment-styles.ts @@ -63,6 +63,11 @@ export const mobileSessionReviewCommentStyles = themedStyleSheet(() => ({ markdownButtonDisabled: { opacity: 0.45 }, + markdownReaderFooter: { + padding: spacing.md, + alignItems: 'flex-end', + gap: spacing.xs + }, markdownFloatingBar: { position: 'absolute', left: spacing.md, diff --git a/mobile/src/session/session-markdown-source-copy.test.tsx b/mobile/src/session/session-markdown-source-copy.test.tsx index d6431aed8e67..3f0eca85dfb6 100644 --- a/mobile/src/session/session-markdown-source-copy.test.tsx +++ b/mobile/src/session/session-markdown-source-copy.test.tsx @@ -28,6 +28,14 @@ vi.mock('../components/MobileRichMarkdownEditor', () => ({ MobileRichMarkdownEditor: 'MobileRichMarkdownEditor' })) vi.mock('./mobile-session-styles', () => ({ styles: {} })) +vi.mock('../files/MobileFileMarkdownPreview', () => ({ + MobileFileMarkdownPreview: 'MobileFileMarkdownPreview' +})) +const { pushFile } = vi.hoisted(() => ({ pushFile: vi.fn() })) +vi.mock('../navigation/workspace-route-handoff', () => ({ + useWorkspaceRouteHandoff: () => ({ push: pushFile }) +})) +vi.mock('../platform/external-link', () => ({ openExternalLink: vi.fn() })) vi.mock('../navigation/use-back-claim', () => ({ useBackClaim: () => {} })) vi.mock('../platform/clipboard', () => ({ useClipboardWriter: () => ({ writeText }) })) vi.mock('../platform/haptics', () => ({ triggerSuccess: success, triggerError: error })) From 4231c9d1e791c92f3566445a4788a153d8bcc292 Mon Sep 17 00:00:00 2001 From: ian-nocturne <326290628+ian-nocturne@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:07:26 +0900 Subject: [PATCH 2/5] fix(mobile): route editor workspace links and fold Windows document case Address review feedback on #36333: - The rich editor dropped relative and file: links before they reached the reader, so tapping a workspace link while editing did nothing. Editor links now go through openEditorLink: web and mailto links keep their validation, and workspace links reach an explicit onOpenWorkspaceFile callback. - A Windows drive or UNC document location is compared with the tab's relative path case-insensitively through isCaseInsensitiveRuntimeRoot; POSIX and WSL paths stay case-sensitive. Co-Authored-By: Claude Opus 5.5 --- .../components/MobileRichMarkdownEditor.tsx | 9 ++++- .../mobile-rich-markdown-editor-contract.ts | 1 + ...le-rich-markdown-editor-controller.test.ts | 23 ++++++++++++ ...-mobile-rich-markdown-editor-controller.ts | 37 ++++++++++++++++--- .../files/mobile-markdown-file-link.test.ts | 8 ++++ mobile/src/files/mobile-markdown-file-link.ts | 7 +++- .../MobileSessionMarkdownReader.test.tsx | 29 +++++++++++---- .../session/MobileSessionMarkdownReader.tsx | 12 +----- 8 files changed, 100 insertions(+), 26 deletions(-) create mode 100644 mobile/src/components/use-mobile-rich-markdown-editor-controller.test.ts diff --git a/mobile/src/components/MobileRichMarkdownEditor.tsx b/mobile/src/components/MobileRichMarkdownEditor.tsx index 250fe530425a..5f90a87d48b3 100644 --- a/mobile/src/components/MobileRichMarkdownEditor.tsx +++ b/mobile/src/components/MobileRichMarkdownEditor.tsx @@ -48,7 +48,13 @@ export type MobileRichMarkdownEditorHandle = { // Link/Image ask TextInputModal because both native shells’ window.prompt returns null (no dialog delegate). // Accept but never call onKeyboardInsetChange: page visualViewport and keyboard-occlusion already measure same cover, so callback would double-lift toolbar. function MobileRichMarkdownEditorWebInner( - { content, editable, onChange, onOpenLink }: MobileRichMarkdownEditorComponentProps, + { + content, + editable, + onChange, + onOpenLink, + onOpenWorkspaceFile + }: MobileRichMarkdownEditorComponentProps, ref: ForwardedRef ) { const t = useMobileTranslation() @@ -107,6 +113,7 @@ function MobileRichMarkdownEditorWebInner( editable, onChange, onOpenLink: openLink, + onOpenWorkspaceFile, transport }) diff --git a/mobile/src/components/mobile-rich-markdown-editor-contract.ts b/mobile/src/components/mobile-rich-markdown-editor-contract.ts index 5e133e6e23b2..f29f8955ebb1 100644 --- a/mobile/src/components/mobile-rich-markdown-editor-contract.ts +++ b/mobile/src/components/mobile-rich-markdown-editor-contract.ts @@ -27,6 +27,7 @@ export type MobileRichMarkdownEditorProps = { onChange: (content: string) => void onKeyboardInsetChange?: (bottom: number) => void onOpenLink: (url: string) => void + onOpenWorkspaceFile?: (pathText: string) => void } /** How a host delivers a command into whatever surface renders the editor document. */ diff --git a/mobile/src/components/use-mobile-rich-markdown-editor-controller.test.ts b/mobile/src/components/use-mobile-rich-markdown-editor-controller.test.ts new file mode 100644 index 000000000000..e6de6060101b --- /dev/null +++ b/mobile/src/components/use-mobile-rich-markdown-editor-controller.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it, vi } from 'vitest' +import { openEditorLink } from './use-mobile-rich-markdown-editor-controller' + +describe('rich Markdown editor links', () => { + it.each([ + ['https://example.com/a', [['https://example.com/a']], []], + ['mailto:team@example.com', [['mailto:team@example.com']], []], + ['images/photo.png', [], [['images/photo.png']]], + ['javascript:alert(1)', [], []] + ])('routes %s to the matching handler', (href, webCalls, workspaceCalls) => { + const onOpenLink = vi.fn() + const onOpenWorkspaceFile = vi.fn() + openEditorLink(href, onOpenLink, onOpenWorkspaceFile) + expect(onOpenLink.mock.calls).toEqual(webCalls) + expect(onOpenWorkspaceFile.mock.calls).toEqual(workspaceCalls) + }) + + it('keeps workspace links inert when the caller does not handle them', () => { + const onOpenLink = vi.fn() + openEditorLink('images/photo.png', onOpenLink) + expect(onOpenLink).not.toHaveBeenCalled() + }) +}) diff --git a/mobile/src/components/use-mobile-rich-markdown-editor-controller.ts b/mobile/src/components/use-mobile-rich-markdown-editor-controller.ts index 75d5733253af..918bc2f56877 100644 --- a/mobile/src/components/use-mobile-rich-markdown-editor-controller.ts +++ b/mobile/src/components/use-mobile-rich-markdown-editor-controller.ts @@ -1,4 +1,5 @@ import { useCallback, useEffect, useRef } from 'react' +import { routeMarkdownHref } from './markdown-href-routing' import { normalizeMobileRichMarkdownKeyboardInset } from './mobile-rich-markdown-editor-keyboard-inset' import type { MobileRichMarkdownCommand, @@ -32,12 +33,32 @@ export function normalizeExternalEditorUrl(value: string): string | null { } } +export function openEditorLink( + value: string, + onOpenLink: (url: string) => void, + onOpenWorkspaceFile?: (pathText: string) => void +): void { + const url = normalizeExternalEditorUrl(value) + if (url) { + onOpenLink(url) + return + } + if (!onOpenWorkspaceFile) { + return + } + const route = routeMarkdownHref(value.trim()) + if (route.kind === 'file') { + onOpenWorkspaceFile(route.pathText) + } +} + export function useMobileRichMarkdownEditorController({ content, editable, onChange, onKeyboardInsetChange, onOpenLink, + onOpenWorkspaceFile, transport }: MobileRichMarkdownEditorProps & { transport: MobileRichMarkdownEditorTransport }) { const readyRef = useRef(false) @@ -88,10 +109,7 @@ export function useMobileRichMarkdownEditorController({ return } if (message.type === 'openLink' && typeof message.url === 'string') { - const url = normalizeExternalEditorUrl(message.url) - if (url) { - onOpenLink(url) - } + openEditorLink(message.url, onOpenLink, onOpenWorkspaceFile) return } if (message.type === 'keyboardInset' && typeof message.bottom === 'number') { @@ -101,7 +119,16 @@ export function useMobileRichMarkdownEditorController({ } } }, - [applyContent, content, editable, onChange, onKeyboardInsetChange, onOpenLink, transport] + [ + applyContent, + content, + editable, + onChange, + onKeyboardInsetChange, + onOpenLink, + onOpenWorkspaceFile, + transport + ] ) const runCommand = useCallback( diff --git a/mobile/src/files/mobile-markdown-file-link.test.ts b/mobile/src/files/mobile-markdown-file-link.test.ts index bc105ae611d0..8c01f9d40422 100644 --- a/mobile/src/files/mobile-markdown-file-link.test.ts +++ b/mobile/src/files/mobile-markdown-file-link.test.ts @@ -75,6 +75,14 @@ describe('Markdown preview file links', () => { expect(mobileMarkdownFileLink(params, 'photo.png', '/different/notes.md')).toBeNull() }) + it('folds case only for Windows document locations', () => { + expect( + mobileMarkdownFileLink(params, 'photo.png', 'C:\\Project\\Docs\\Notes.md')?.params + .relativePath + ).toBe('docs/photo.png') + expect(mobileMarkdownFileLink(params, 'photo.png', '/remote/project/Docs/Notes.md')).toBeNull() + }) + it('does not reuse terminal artifact grants for another file', () => { expect(mobileMarkdownFileLink({ ...params, source: 'terminalArtifact' }, 'other.md')).toBeNull() }) diff --git a/mobile/src/files/mobile-markdown-file-link.ts b/mobile/src/files/mobile-markdown-file-link.ts index f13d2354b3f0..978bd640dbe3 100644 --- a/mobile/src/files/mobile-markdown-file-link.ts +++ b/mobile/src/files/mobile-markdown-file-link.ts @@ -1,4 +1,5 @@ import { + isCaseInsensitiveRuntimeRoot, isWindowsAbsolutePathLike, relativePathInsideRoot, resolveRuntimePath @@ -29,7 +30,11 @@ export function resolveMarkdownFilePath( let root = '/workspace' if (documentAbsolutePath) { const absolute = documentAbsolutePath.replaceAll('\\', '/') - if (!absolute.endsWith(`/${source}`)) { + const tail = `/${source}` + const matches = isCaseInsensitiveRuntimeRoot(documentAbsolutePath) + ? absolute.toLowerCase().endsWith(tail.toLowerCase()) + : absolute.endsWith(tail) + if (!matches) { return null } root = absolute.slice(0, -source.length) diff --git a/mobile/src/session/MobileSessionMarkdownReader.test.tsx b/mobile/src/session/MobileSessionMarkdownReader.test.tsx index 532cdb1ef951..906fc28a8259 100644 --- a/mobile/src/session/MobileSessionMarkdownReader.test.tsx +++ b/mobile/src/session/MobileSessionMarkdownReader.test.tsx @@ -139,13 +139,7 @@ describe('live session markdown reader copy', () => { }) it('opens a workspace file from the live document on the same remote host', () => { - render() - act(() => - renderer!.root - .findByType('MobileFileMarkdownPreview') - .props.onOpenFile('/remote/project/assets/photo.png') - ) - expect(pushFile).toHaveBeenCalledWith({ + const photoRoute = { pathname: '/h/[hostId]/files/preview/[worktreeId]', params: { hostId: 'remote', @@ -153,7 +147,26 @@ describe('live session markdown reader copy', () => { source: 'worktree', relativePath: 'assets/photo.png' } - }) + } + render() + act(() => + renderer!.root + .findByType('MobileFileMarkdownPreview') + .props.onOpenFile('/remote/project/assets/photo.png') + ) + expect(pushFile).toHaveBeenLastCalledWith(photoRoute) + act(() => + buttons() + .find((button) => button.props.accessibilityLabel === 'Edit Markdown')! + .props.onPress() + ) + act(() => + renderer!.root + .findByType('MobileRichMarkdownEditor') + .props.onOpenWorkspaceFile('../assets/photo.png') + ) + expect(pushFile).toHaveBeenCalledTimes(2) + expect(pushFile).toHaveBeenLastCalledWith(photoRoute) }) it('keeps loading and error states free of copy actions', () => { diff --git a/mobile/src/session/MobileSessionMarkdownReader.tsx b/mobile/src/session/MobileSessionMarkdownReader.tsx index dda245541062..0f74022a4475 100644 --- a/mobile/src/session/MobileSessionMarkdownReader.tsx +++ b/mobile/src/session/MobileSessionMarkdownReader.tsx @@ -2,8 +2,6 @@ import { useState } from 'react' import { MobileFileMarkdownPreview } from '../files/MobileFileMarkdownPreview' import type { MobileFilePreviewRpcSender } from '../files/mobile-file-preview-operations' import { mobileMarkdownFileLink } from '../files/mobile-markdown-file-link' -import { routeMarkdownHref } from '../components/markdown-href-routing' -import { openExternalLink } from '../platform/external-link' import { useWorkspaceRouteHandoff } from '../navigation/workspace-route-handoff' import { View, Text, Pressable, ActivityIndicator } from 'react-native' import { RefreshCw } from 'lucide-react-native' @@ -71,14 +69,6 @@ export function MarkdownReader({ ) } } - const openLink = (href: string) => { - const route = routeMarkdownHref(href) - if (route.kind === 'file') { - openFile(route.pathText) - } else if (route.kind === 'web') { - openExternalLink(route.url) - } - } // Native Keyboard events under-report the WebView editor's covered area, so prefer the larger WebView-measured inset. const [webviewKeyboardInset, setWebviewKeyboardInset] = useState(0) const effectiveKeyboardLift = Math.max(keyboardLift, webviewKeyboardInset) @@ -105,7 +95,7 @@ export function MarkdownReader({ content={doc.localContent} editable={doc.editable && !doc.saving} onChange={onChange} - onOpenLink={openLink} + onOpenWorkspaceFile={openFile} onKeyboardInsetChange={setWebviewKeyboardInset} /> ) : ( From 009b02a3112abf0683b1e49f7bfccc903a28e355 Mon Sep 17 00:00:00 2001 From: ian-nocturne <326290628+ian-nocturne@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:41:22 +0900 Subject: [PATCH 3/5] test(mobile): cover editor workspace links through the mounted document Mount MobileRichMarkdownEditor on the page and click links inside its document. Workspace links reach onOpenWorkspaceFile and web links stay on onOpenLink, which covers the handoff from the editor component to its controller. Co-Authored-By: Claude Opus 5.5 --- ...bile-webview-editor-web-fallbacks.test.tsx | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/mobile/src/components/mobile-webview-editor-web-fallbacks.test.tsx b/mobile/src/components/mobile-webview-editor-web-fallbacks.test.tsx index f6a9bef57263..6ab4cf105674 100644 --- a/mobile/src/components/mobile-webview-editor-web-fallbacks.test.tsx +++ b/mobile/src/components/mobile-webview-editor-web-fallbacks.test.tsx @@ -139,6 +139,34 @@ describe('the rich markdown editor on the page', () => { }) expect(onChange.mock.calls).toEqual([['accepted']]) }) + + it('hands workspace links to the host and keeps web links on the link handler', () => { + const host = document.createElement('div') + const onOpenLink = vi.fn() + const onOpenWorkspaceFile = vi.fn() + render( + createElement(MobileRichMarkdownEditor, { + content: 'body', + editable: true, + onChange: vi.fn(), + onOpenLink, + onOpenWorkspaceFile + }), + host + ) + const surface = host.querySelector('#editor')! + + act(() => { + surface.innerHTML = + '

photo site

' + surface.querySelectorAll('a').forEach((link) => { + link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) + }) + }) + + expect(onOpenWorkspaceFile.mock.calls).toEqual([['images/photo.png']]) + expect(onOpenLink.mock.calls).toEqual([['https://example.com/a']]) + }) }) describe('the html preview on the page', () => { From 6d97353e7bc7545860a6307c6b2fb45c6e674876 Mon Sep 17 00:00:00 2001 From: ian-nocturne <326290628+ian-nocturne@users.noreply.github.com> Date: Sat, 31 Oct 2026 00:39:20 +0900 Subject: [PATCH 4/5] test(mobile): carry an edited draft from the editor into the preview The reader test now edits through the editor's onChange, updates the parent-held document, and checks that the editor and the preview both show the new draft. Co-Authored-By: Claude Opus 5.5 --- .../MobileSessionMarkdownReader.test.tsx | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/mobile/src/session/MobileSessionMarkdownReader.test.tsx b/mobile/src/session/MobileSessionMarkdownReader.test.tsx index 906fc28a8259..7e027aa7da41 100644 --- a/mobile/src/session/MobileSessionMarkdownReader.test.tsx +++ b/mobile/src/session/MobileSessionMarkdownReader.test.tsx @@ -40,7 +40,8 @@ describe('live session markdown reader copy', () => { onCopyPath = vi.fn(), onSave = vi.fn(), onDiscard = vi.fn(), - onRefresh = vi.fn() + onRefresh = vi.fn(), + onChange = vi.fn() function render(value: MarkdownDocState | undefined = doc) { act(() => { renderer = create( @@ -56,7 +57,7 @@ describe('live session markdown reader copy', () => { onSave, onDiscard, onRefresh, - onChange: vi.fn(), + onChange, keyboardLift: 0 }) ) @@ -98,7 +99,7 @@ describe('live session markdown reader copy', () => { } ) - it('opens in reading mode and preserves the current draft across explicit editing', () => { + it('opens in reading mode and carries edits from the editor into the preview', () => { render({ ...doc, isDirty: true, localContent: '# Draft' }) const preview = () => renderer!.root.findByType('MobileFileMarkdownPreview') expect(preview().props.content).toBe('# Draft') @@ -107,13 +108,26 @@ describe('live session markdown reader copy', () => { .find((button) => button.props.accessibilityLabel === 'Edit Markdown')! .props.onPress() ) - expect(renderer!.root.findByType('MobileRichMarkdownEditor').props.content).toBe('# Draft') + const editor = renderer!.root.findByType('MobileRichMarkdownEditor') + expect(editor.props.content).toBe('# Draft') + act(() => editor.props.onChange('# Edited')) + expect(onChange.mock.calls).toEqual([['# Edited']]) + const props = renderer!.root.findByType(MarkdownReader).props + act(() => + renderer!.update( + createElement(MarkdownReader, { + ...props, + doc: { ...doc, isDirty: true, localContent: '# Edited' } + }) + ) + ) + expect(renderer!.root.findByType('MobileRichMarkdownEditor').props.content).toBe('# Edited') act(() => buttons() .find((button) => button.props.accessibilityLabel === 'Preview Markdown')! .props.onPress() ) - expect(preview().props.content).toBe('# Draft') + expect(preview().props.content).toBe('# Edited') expect(onSave).not.toHaveBeenCalled() expect(onDiscard).not.toHaveBeenCalled() }) From e5434524ee8bad117f22201d9ed418699706aacd Mon Sep 17 00:00:00 2001 From: ian-nocturne <326290628+ian-nocturne@users.noreply.github.com> Date: Sat, 31 Oct 2026 20:45:20 +0900 Subject: [PATCH 5/5] fix(mobile): decouple session Markdown preview from file explorer mode bar --- .../mobile-markdown-image-source.test.ts | 1 + .../MobileSessionMarkdownPreview.test.tsx | 48 +++++++++++++++ .../session/MobileSessionMarkdownPreview.tsx | 59 +++++++++++++++++++ .../MobileSessionMarkdownReader.test.tsx | 8 +-- .../session/MobileSessionMarkdownReader.tsx | 4 +- .../session-markdown-source-copy.test.tsx | 4 +- 6 files changed, 116 insertions(+), 8 deletions(-) create mode 100644 mobile/src/session/MobileSessionMarkdownPreview.test.tsx create mode 100644 mobile/src/session/MobileSessionMarkdownPreview.tsx diff --git a/mobile/src/files/mobile-markdown-image-source.test.ts b/mobile/src/files/mobile-markdown-image-source.test.ts index d510212b8f34..294488e551f3 100644 --- a/mobile/src/files/mobile-markdown-image-source.test.ts +++ b/mobile/src/files/mobile-markdown-image-source.test.ts @@ -61,6 +61,7 @@ describe('Markdown preview images', () => { worktree: 'id:wt', relativePath: 'docs/logo.svg' }) + }) it('previews file URLs inside the known remote workspace without reading phone files', async () => { const client = host() diff --git a/mobile/src/session/MobileSessionMarkdownPreview.test.tsx b/mobile/src/session/MobileSessionMarkdownPreview.test.tsx new file mode 100644 index 000000000000..bfb12e8e5580 --- /dev/null +++ b/mobile/src/session/MobileSessionMarkdownPreview.test.tsx @@ -0,0 +1,48 @@ +import { createElement, type ReactNode } from 'react' +import { act, create } from 'react-test-renderer' +import { describe, expect, it, vi } from 'vitest' +import { MobileSessionMarkdownPreview } from './MobileSessionMarkdownPreview' + +vi.mock('react-native', () => ({ ScrollView: 'ScrollView' })) +vi.mock('../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'dark' })) +vi.mock('../files/mobile-file-preview-styles', () => ({ + filePreviewStyles: { scroll: {}, markdownContent: {} } +})) +vi.mock('../files/MobileFilePreviewSourceText', () => ({ + MobileFilePreviewTruncatedNote: 'MobileFilePreviewTruncatedNote' +})) +vi.mock('../files/MobileMarkdownPreviewImage', () => ({ + MobileMarkdownPreviewImage: 'MobileMarkdownPreviewImage' +})) +vi.mock('../components/MobileMarkdown', () => ({ + MobileMarkdown: ({ renderImage }: { renderImage?: (href: string, alt: string) => ReactNode }) => + renderImage?.('images/diagram.png', 'Diagram') ?? null +})) + +describe('MobileSessionMarkdownPreview', () => { + it('forwards documentAbsolutePath and relativePath to MobileMarkdownPreviewImage', () => { + let renderer: ReturnType | undefined + act(() => { + renderer = create( + createElement(MobileSessionMarkdownPreview, { + relativePath: 'docs/notes.md', + documentAbsolutePath: '/workspace/docs/notes.md', + content: '![Diagram](images/diagram.png)', + truncated: false, + byteLength: 30, + worktreeId: 'folder:project', + client: null + }) + ) + }) + const image = renderer!.root.findByType('MobileMarkdownPreviewImage') + expect(image.props).toMatchObject({ + worktreeId: 'folder:project', + documentPath: 'docs/notes.md', + documentAbsolutePath: '/workspace/docs/notes.md', + href: 'images/diagram.png', + alt: 'Diagram' + }) + act(() => renderer?.unmount()) + }) +}) diff --git a/mobile/src/session/MobileSessionMarkdownPreview.tsx b/mobile/src/session/MobileSessionMarkdownPreview.tsx new file mode 100644 index 000000000000..678038748929 --- /dev/null +++ b/mobile/src/session/MobileSessionMarkdownPreview.tsx @@ -0,0 +1,59 @@ +import { ScrollView } from 'react-native' +import { MobileMarkdown } from '../components/MobileMarkdown' +import { MobileMarkdownPreviewImage } from '../files/MobileMarkdownPreviewImage' +import { MobileFilePreviewTruncatedNote } from '../files/MobileFilePreviewSourceText' +import type { MobileFilePreviewRpcSender } from '../files/mobile-file-preview-operations' +import { filePreviewStyles as styles } from '../files/mobile-file-preview-styles' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' + +// Lifts the 13pt base to 14pt body text; headings scale with it. +const DOCUMENT_TEXT_SCALE = 14 / 13 + +type Props = { + relativePath: string + documentAbsolutePath?: string + content: string + truncated: boolean + byteLength: number + client?: MobileFilePreviewRpcSender | null + worktreeId?: string + onOpenFile?: (pathText: string) => void +} + +export function MobileSessionMarkdownPreview({ + relativePath, + documentAbsolutePath, + content, + truncated, + byteLength, + client, + worktreeId, + onOpenFile +}: Props) { + useMobileColorScheme() + return ( + + {truncated ? : null} + ( + + ) + : undefined + } + /> + + ) +} diff --git a/mobile/src/session/MobileSessionMarkdownReader.test.tsx b/mobile/src/session/MobileSessionMarkdownReader.test.tsx index 7e027aa7da41..c1885a210032 100644 --- a/mobile/src/session/MobileSessionMarkdownReader.test.tsx +++ b/mobile/src/session/MobileSessionMarkdownReader.test.tsx @@ -16,8 +16,8 @@ vi.mock('../components/MobileRichMarkdownEditor', () => ({ MobileRichMarkdownEditor: 'MobileRichMarkdownEditor' })) vi.mock('./mobile-session-styles', () => ({ styles: {} })) -vi.mock('../files/MobileFileMarkdownPreview', () => ({ - MobileFileMarkdownPreview: 'MobileFileMarkdownPreview' +vi.mock('./MobileSessionMarkdownPreview', () => ({ + MobileSessionMarkdownPreview: 'MobileSessionMarkdownPreview' })) const { pushFile } = vi.hoisted(() => ({ pushFile: vi.fn() })) vi.mock('../navigation/workspace-route-handoff', () => ({ @@ -101,7 +101,7 @@ describe('live session markdown reader copy', () => { it('opens in reading mode and carries edits from the editor into the preview', () => { render({ ...doc, isDirty: true, localContent: '# Draft' }) - const preview = () => renderer!.root.findByType('MobileFileMarkdownPreview') + const preview = () => renderer!.root.findByType('MobileSessionMarkdownPreview') expect(preview().props.content).toBe('# Draft') act(() => buttons() @@ -165,7 +165,7 @@ describe('live session markdown reader copy', () => { render() act(() => renderer!.root - .findByType('MobileFileMarkdownPreview') + .findByType('MobileSessionMarkdownPreview') .props.onOpenFile('/remote/project/assets/photo.png') ) expect(pushFile).toHaveBeenLastCalledWith(photoRoute) diff --git a/mobile/src/session/MobileSessionMarkdownReader.tsx b/mobile/src/session/MobileSessionMarkdownReader.tsx index 0f74022a4475..5758d9b64b56 100644 --- a/mobile/src/session/MobileSessionMarkdownReader.tsx +++ b/mobile/src/session/MobileSessionMarkdownReader.tsx @@ -1,5 +1,5 @@ import { useState } from 'react' -import { MobileFileMarkdownPreview } from '../files/MobileFileMarkdownPreview' +import { MobileSessionMarkdownPreview } from './MobileSessionMarkdownPreview' import type { MobileFilePreviewRpcSender } from '../files/mobile-file-preview-operations' import { mobileMarkdownFileLink } from '../files/mobile-markdown-file-link' import { useWorkspaceRouteHandoff } from '../navigation/workspace-route-handoff' @@ -99,7 +99,7 @@ export function MarkdownReader({ onKeyboardInsetChange={setWebviewKeyboardInset} /> ) : ( - ({ MobileRichMarkdownEditor: 'MobileRichMarkdownEditor' })) vi.mock('./mobile-session-styles', () => ({ styles: {} })) -vi.mock('../files/MobileFileMarkdownPreview', () => ({ - MobileFileMarkdownPreview: 'MobileFileMarkdownPreview' +vi.mock('./MobileSessionMarkdownPreview', () => ({ + MobileSessionMarkdownPreview: 'MobileSessionMarkdownPreview' })) const { pushFile } = vi.hoisted(() => ({ pushFile: vi.fn() })) vi.mock('../navigation/workspace-route-handoff', () => ({