Skip to content
Closed
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
9 changes: 8 additions & 1 deletion mobile/src/components/MobileRichMarkdownEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<MobileRichMarkdownEditorHandle>
) {
const t = useMobileTranslation()
Expand Down Expand Up @@ -107,6 +113,7 @@ function MobileRichMarkdownEditorWebInner(
editable,
onChange,
onOpenLink: openLink,
onOpenWorkspaceFile,
transport
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
28 changes: 28 additions & 0 deletions mobile/src/components/mobile-webview-editor-web-fallbacks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>('#editor')!

act(() => {
surface.innerHTML =
'<p><a href="images/photo.png">photo</a> <a href="https://example.com/a">site</a></p>'
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', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -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()
})
})
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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') {
Expand All @@ -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(
Expand Down
20 changes: 17 additions & 3 deletions mobile/src/files/MobileMarkdownPreviewImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 }>({})
Expand All @@ -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 })
Expand Down Expand Up @@ -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 (
<View style={styles.frame}>
Expand Down
32 changes: 32 additions & 0 deletions mobile/src/files/mobile-markdown-file-link.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,38 @@ 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('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()
})
Expand Down
50 changes: 41 additions & 9 deletions mobile/src/files/mobile-markdown-file-link.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
isCaseInsensitiveRuntimeRoot,
isWindowsAbsolutePathLike,
relativePathInsideRoot,
resolveRuntimePath
Expand All @@ -9,20 +10,51 @@ 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('\\', '/')
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)
} 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
}
Expand Down
28 changes: 28 additions & 0 deletions mobile/src/files/mobile-markdown-image-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,34 @@ describe('Markdown preview images', () => {
})
})

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 () => {
const client = host()
await expect(
Expand Down
20 changes: 4 additions & 16 deletions mobile/src/files/mobile-markdown-image-source.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -13,7 +9,8 @@ export async function loadMarkdownPreviewImage(
client: MobileFilePreviewRpcSender | null,
worktreeId: string,
documentPath: string,
href: string
href: string,
documentAbsolutePath?: string
): Promise<string> {
if (/^https?:\/\//i.test(href)) {
return href
Expand All @@ -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')
Expand Down
6 changes: 5 additions & 1 deletion mobile/src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading