Skip to content

fix(mobile): render and zoom relative images in markdown, pinch-scale the file preview - #24469

Closed
dudupii wants to merge 19 commits into
stablyai:mainfrom
dudupii:fix/mobile-markdown-relative-images
Closed

dudupii wants to merge 19 commits into
stablyai:mainfrom
dudupii:fix/mobile-markdown-relative-images

Conversation

@dudupii

@dudupii dudupii commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Pictures referenced by a Markdown file (like a screenshot next to the text it explains) showed up as broken placeholders on the phone. The phone now reads those picture files and shows them inside the document — in the file preview and in the editor. Tapping a picture opens it full-screen, where a pinch zooms it in and out. And pinching the document itself now grows its text — including table text and code, which used to stay tiny.

What Changed

1. Relative images render in the markdown file preview.
Before: every ![alt](relative/path.png) in a worktree Markdown file rendered as tappable text with the path — no picture. After: once the document renders, the preview scans it for relative image srcs, resolves each against the document's directory, and reads the bytes over the same files.readPreview a file tab's image doc already uses. Resolved images render in place — standalone images full width with their real aspect ratio, inline images as fixed thumbnails. The document publishes first and images attach as each read settles, so a slow image never delays text; a missing or unreadable image stays the tappable fallback it already was.

2. Tapping a markdown image opens a full-screen zoomable viewer.
A tap on any image (block, inline, or in the fallback) pushes the image-viewer route the file tab already uses. That viewer gains react-native-gesture-handler pinch/pan, so zooming works identically on Android, iOS, and web instead of one platform's built-in gesture.

3. A pinch scales the file preview's rendered text.
Before: the rendered markdown and source views of a worktree file had no zoom at all, while native chat scales its font with a pinch. After: the preview reuses the chat's pinch gesture hook — the rendered document grows as one (paragraphs, lists, headings, quotes, code, table cells, and inline image thumbnails share the same multiplier), and the source view scales its mono font from the same committed scale.

4. The editor (this PR's original commit) resolves relative images inside the WebView.
The editor document is a WebView served from a placeholder origin, so a relative src resolved against a host that cannot serve anything. When the document loads, the session scans it for relative image srcs, resolves each against the document's worktree-relative directory, reads the bytes over the same files.readPreview, and delivers the resulting data URLs through a new setImageSources host command. Display and storage stay apart: the rendered <img> carries the authored src in data-orca-src, the host swaps only the display src, and serialization reads data-orca-src — so a displayed image never round-trips its data URL into the saved file. Editor images open the same zoomable viewer on tap.

One internal fix rides along: markdown-href-routing had started importing the image-srcs module, dragging the image-read RPC graph into every route that renders prose and regrouping esbuild chunks past the mobile web bundle's fenced asset count (packaging failed on linux/mac). The one-regex predicate stays local to each light consumer instead; the fence's sweep table is re-derived from the new layout, never widened, and the bundle is back inside it (73 scripts / 122 assets).

Why

  • Reuses files.readPreview (already in the mobile allowlist for image file tabs), so no host-side or wire changes: an older paired desktop serves these reads today.
  • data-orca-src rather than rewriting the markdown: the editor serializes <img> back to ![alt](src) from the live DOM, so swapping src in place would corrupt the file on save.
  • SVG is included for the editor's <img> even though the shared file-tab classifier excludes it (RN <Image> cannot decode SVG; a WebView <img> can, and never scripts it as an image subresource).
  • Desktop parity: the desktop editor resolves relative image srcs against the document's directory and displays local blob URLs while keeping the authored src in the file.
  • The pinch reuses the gesture hook native chat already ships, so the file preview inherits the same feel and bounds instead of a second gesture implementation; react-native-gesture-handler is already a dependency, so the cross-platform viewer zoom adds none.

Linked Issue

Fixes #24468

Visual Proof

BEFORE: images in a Markdown document render as broken placeholders.

before: broken images in a mobile markdown document

BEFORE (pinch, tables): the document is pinched — body text grows, but table text stays at its base size.

before pinch: prose scaled up, table text stays small

AFTER (pinch, tables): the same document pinched further — table text now scales with the prose (device acceptance on a fork build of this branch's commits).

after pinch: table text scales with the prose

Testing

  • Automated tests added/updated: src collection and path resolution (relative, rooted, escaping, escapes, query tails), the RPC read (image / refused / non-image / unclassified), editor surface display-slot swap and round-trip preservation, the bundled document end-to-end through the injected handle, the session doc patch, the preview's image-src resolution and tap routing, the viewer's gesture wiring, and the textScale rendering of tables, headings, code, and inline thumbnails
  • I manually tested these changes locally — device acceptance on a fork build of these commits (pinch-scaled table shot above); image rendering and the zoom viewer exercised on the same build

AI Disclosure

Implemented by the fork maintainer (dupi).

Review

  • Security: reads go through the existing checked RPC operation; the data URL only ever reaches an <img> display slot, and isSafeUrl still gates what renders at all
  • Cross-platform: pure TS plus react-native-gesture-handler (already shipped); paths are worktree-relative repo paths, no platform branches
  • SSH/remote: reads execute on the paired host exactly like a file tab's image doc; loss of contact leaves the broken glyph, never a wrong verdict
  • Mobile: no protocol, opcode, or capability changes — the one new editor command is inside the existing WebView injection transport, and the web bundle stays inside its fenced asset count
  • Performance: at most 24 distinct images per document, parallel reads, doc renders first and images attach after; the pinch only re-renders on the committed scale, not per gesture frame

Agent skill upstream boundary

  • Not applicable: no skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation touched

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • Before and after screenshots attached
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • Typecheck, the tests-typecheck ratchet, the full mobile suite, and oxlint pass on the branch

The markdown editor document runs in a WebView whose origin is a
placeholder host, so a relative ![alt](docs/a.png) resolved against it
and rendered as a broken image. Nothing on mobile resolved those paths
to file content.

The session now scans a loaded markdown doc for relative image srcs,
resolves each against the doc's worktree-relative directory, and reads
the bytes over the same files.readPreview a file tab's image doc uses.
The data URLs reach the editor through a new setImageSources host
command that swaps only the display src; the authored src rides in
data-orca-src and serialization reads that, so a displayed image never
round-trips its data URL into the saved file.

Missing or unreadable images stay the broken glyph they already were,
and the doc publishes before the image reads settle, so a slow image
never delays the document.
@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 3/5

[Medium risk] Adds image display support to the markdown editor.

The PR is not safe to merge until native image delivery works and late image results cannot overwrite a newer document’s display.

Findings

  1. P1 Native image map becomes a string ▶
  2. P1 Older images overwrite newer ones ▶
  3. P2 Code examples use image slots ▶

Summary

The PR reads repository-relative Markdown images through files.readPreview and passes display data URLs to the mobile editor while preserving authored paths for serialization.

  • The native transport currently passes the map in the wrong shape.
  • Concurrent document reads can attach stale image results, and non-rendered Markdown examples can consume the image limit.

Reviews (1) · Last reviewed commit: "fix(mobile): render repository-relative ..."

),
setImageSources: (sources: Record<string, string>) =>
inject(
`window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${escapeInjectedJavaScriptString(JSON.stringify(sources))});`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Native image map becomes a string When a Markdown document opens on the phone, escapeInjectedJavaScriptString stringifies the already-stringified image map. The editor receives a string instead of an object, so it cannot look up any image paths and repository-relative images remain broken.

Suggested change
`window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${escapeInjectedJavaScriptString(JSON.stringify(sources))});`
`window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(JSON.parse(${escapeInjectedJavaScriptString(JSON.stringify(sources))}));`

Comment on lines +29 to +34
setMarkdownDocs((prev) => {
const doc = prev.get(tabId)
if (!doc || doc.status !== 'ready') {
return prev
}
return new Map(prev).set(tabId, { ...doc, imageSources })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Older images overwrite newer ones Refreshing or revisiting a tab can start a new document read while its previous image reads are still pending. This update checks only that the tab is ready, so an older result can attach its image map to the newer document and show stale images.

Comment on lines +112 to +114
await Promise.all(
collectMarkdownImageSrcs(content)
.slice(0, MAX_RESOLVED_IMAGE_SRCS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Code examples use image slots The 24-image limit is applied to matches in raw Markdown, including image syntax inside fenced or inline code that the editor never renders as an image. If 24 such examples appear before a real image, that image is skipped and remains broken despite its file being available.

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8d65195f-f122-4ab4-a096-cf5ee7a09a68
📥 Commits

Reviewing files that changed from the base of the PR and between 5fafd08 and 7438260.

📒 Files selected for processing (2)
  • mobile/src/components/markdown-href-routing.test.ts
  • mobile/src/session/use-mobile-session-document-readers.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📝 Walkthrough

The mobile session reader resolves eligible local Markdown image paths and stores successful previews as data URLs. The rich editor applies mapped URLs for display while preserving authored URLs for Markdown serialization. Markdown previews render resolved images and route image taps to file previews or external handlers. File previews add pinch-based image zoom and text scaling.

Fixed issue severity: Medium

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 74382

Relative images still fail to render in the Android editor, a central goal of this change. Fix the native transport before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 12684

Image loading reuses existing file-preview permissions and preserves authored Markdown rather than saving preview data. However, delayed image results can overwrite a refreshed document’s previews, and cross-platform path confinement and native transport compatibility remain incompletely verified.

Retained concerns

  • Low · reliability · inferred: An earlier image-read batch can replace the image map of a newer ready document with the same tab ID. Refresh and discard initiate new reads without invalidating the earlier batch; where authored image keys overlap, the refreshed document can display outdated bytes. The existing editor generation control protects Markdown change messages, not these asynchronous image updates. Authored-source serialization limits the impact to preview ownership rather than demonstrated saved-content corruption.
Security review details

Security Blast Radius

  • inferred — A contributor able to influence Markdown opened by a paired user can now trigger automatic image-preview requests using that user’s existing file-read authority. Requests identify the selected worktree and can reference image-like paths elsewhere within it. Maximum effective scope after platform normalization and symlink or remote-provider resolution remains incompletely verified.

Security Findings and Attack Paths

  • inferred — The new path delivers preview data to image src attributes rather than HTML or script insertion. This is counterevidence to script execution through resolved image bytes, not proof that every supported decoder or platform boundary is safe. No introduced execution or authorization bypass was established.

Trust Boundaries and Controls

  • observed — The host resolves a worktree target before preview reads. Local reads then pass through authorization that checks both the resolved path and its canonical real path against allowed roots. Remote-provider reads use a separate branch, whose canonical confinement was not fully inspected.
  • observed — Web transport passes the source map directly to the editor API. Native transport injects a JSON-escaped serialized string, while the inspected API declares a record. End-to-end native decoding or adaptation was not established, so equivalent native behavior remains unresolved.

Resilience and Maintainability Implications

  • observed — Automatic reads inherit host preview byte limits and shared raster-rendering limits. The 24-source cap bounds fan-out per read, but image batches have no generation check or cancellation in the inspected reader; ownership across refresh and recovery is therefore weaker than the existing Markdown-change generation control.

Hardening Proposals

  • proposed — Bind each image batch to an initiating document generation and worktree identity, invalidate it on replacement or teardown, and accept completion only while that ownership remains current. Keep authored-source serialization independent of this display state.
Pre-merge checks | Passed 3 | Failed 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check Warning Issue [#24468] targets image rendering in the mobile editor. The PR also changes the separate file preview by adding image resolution, image tap routing, pinch text scaling, and a general zoomable ima… Remove the separate file-preview rendering, preview text-scaling, and general image-viewer changes, or link each change to an active issue that requires it.
Docstring Coverage Warning Docstring coverage is 38.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 62 functions across 45 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check Passed The title clearly and concisely summarizes the main changes: relative Markdown image rendering, image zooming, and pinch-scaling the mobile file preview.
Description check Passed The description covers the required sections and provides clear user impact, implementation details, rationale, linked issue, visual proof, testing, AI disclosure, review considerations, and checklist…
Linked Issues check Passed Issue [#24468] requires repository-relative images to render in the mobile Markdown editor. The PR resolves image paths against the worktree document directory, reads image data through `files.readPre…
Full details: Out of Scope Changes check

Explanation

Issue [#24468] targets image rendering in the mobile editor. The PR also changes the separate file preview by adding image resolution, image tap routing, pinch text scaling, and a general zoomable image viewer. These changes are not required to resolve the linked issue.

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6ee47b68-ef06-4746-8c96-c10663c1e976

📥 Commits

Reviewing files that changed from the base of the PR and between 8b76683 and 1268466.

📒 Files selected for processing (19)
  • mobile/src/components/MobileRichMarkdownEditor.tsx
  • mobile/src/components/MobileRichMarkdownEditor.web.tsx
  • mobile/src/components/mobile-rich-markdown-editor-contract.ts
  • mobile/src/components/rich-markdown/create-rich-markdown-editor-document.ts
  • mobile/src/components/rich-markdown/document-host-seams.ts
  • mobile/src/components/rich-markdown/document-scope.ts
  • mobile/src/components/rich-markdown/editor-content.ts
  • mobile/src/components/rich-markdown/editor-image-sources.test.ts
  • mobile/src/components/rich-markdown/editor-image-sources.ts
  • mobile/src/components/rich-markdown/html-inline-markdown.ts
  • mobile/src/components/rich-markdown/markdown-inline-render.ts
  • mobile/src/components/rich-markdown/native-document-bundle.test.ts
  • mobile/src/components/use-mobile-rich-markdown-editor-controller.ts
  • mobile/src/session/MobileMarkdownReader.tsx
  • mobile/src/session/markdown-relative-image-srcs.test.ts
  • mobile/src/session/markdown-relative-image-srcs.ts
  • mobile/src/session/mobile-session-route-types.ts
  • mobile/src/session/use-mobile-session-document-readers.test.ts
  • mobile/src/session/use-mobile-session-document-readers.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +73 to +75
setImageSources: (sources: Record<string, string>) =>
inject(
`window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${escapeInjectedJavaScriptString(JSON.stringify(sources))});`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Check whether the WebView handle (host bridge) parses string arguments before calling setImageSources.
rg -n -C5 'setImageSources|__orcaRichMarkdown' mobile/src/components/rich-markdown

Repository: stablyai/orca

Length of output: 17528


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- changed file ---'
cat -n mobile/src/components/MobileRichMarkdownEditor.tsx | sed -n '1,125p'
printf '%s\n' '--- escape helper references/definition ---'
rg -n -C6 'escapeInjectedJavaScriptString' mobile/src
printf '%s\n' '--- host bridge and document API ---'
cat -n mobile/src/components/rich-markdown/host-bridge.ts | sed -n '1,180p'
cat -n mobile/src/components/rich-markdown/create-rich-markdown-editor-document.ts | sed -n '1,80p'
cat -n mobile/src/components/rich-markdown/editor-image-sources.ts | sed -n '1,100p'
printf '%s\n' '--- PR diff for relevant file ---'
git diff --no-ext-diff --unified=15 cb11a9ff1ae9b2c2d31e117f86ba71dd8b3271d8 1268466ef29099038eb180cf79ff703ed09636b0 -- mobile/src/components/MobileRichMarkdownEditor.tsx mobile/src/components/rich-markdown

Repository: stablyai/orca

Length of output: 41618


Pass an object to setImageSources.

escapeInjectedJavaScriptString serializes its input. Passing JSON.stringify(sources) serializes the source map twice, so the document receives a string. applyImageSources then cannot find map entries, and relative images remain unresolved.

🐛 Suggested fix
-          `window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${escapeInjectedJavaScriptString(JSON.stringify(sources))});`
+          `window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${JSON.stringify(sources).replace(/&lt;\/script/gi, '&lt;\\/script')});`
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setImageSources: (sources: Record<string, string>) =>
inject(
`window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${escapeInjectedJavaScriptString(JSON.stringify(sources))});`
setImageSources: (sources: Record<string, string>) =>
inject(
`window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${JSON.stringify(sources).replace(/&lt;\/script/gi, '&lt;\\/script')});`

Comment on lines +16 to +40

// Why: relative images cannot render in the editor's WebView, and reading them is N more RPCs —
// the doc publishes first and the resolved map lands on the ready doc when the reads settle.
const resolveMarkdownImages = useCallback(
(tabId: string, relativePath: string, content: string) => {
if (!client) {
return
}
void readMarkdownImageSources(client, worktreeId, relativePath, content).then(
(imageSources) => {
if (Object.keys(imageSources).length === 0) {
return
}
setMarkdownDocs((prev) => {
const doc = prev.get(tabId)
if (!doc || doc.status !== 'ready') {
return prev
}
return new Map(prev).set(tabId, { ...doc, imageSources })
})
}
)
},
[client, setMarkdownDocs, worktreeId]
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,180p' mobile/src/session/use-mobile-session-document-readers.ts
rg -n 'readMarkdownTab|setMarkdownDocs|markdownDocs' mobile/src/session

Repository: stablyai/orca

Length of output: 13910


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- outlines ---'
ast-grep outline mobile/src/session/use-mobile-session-terminal-webview.ts
ast-grep outline mobile/src/session/use-mobile-session-tab-switching.ts
ast-grep outline mobile/src/session/use-mobile-session-markdown-actions.ts
ast-grep outline mobile/src/session/use-mobile-session-tab-reconciliation.ts
ast-grep outline mobile/src/session/use-mobile-session-screen-state.ts
ast-grep outline mobile/src/session/use-mobile-session-tab-application.ts
printf '%s\n' '--- caller/state excerpts ---'
sed -n '1,190p' mobile/src/session/use-mobile-session-terminal-webview.ts
sed -n '1,190p' mobile/src/session/use-mobile-session-tab-switching.ts
sed -n '1,270p' mobile/src/session/use-mobile-session-markdown-actions.ts
sed -n '1,130p' mobile/src/session/use-mobile-session-tab-reconciliation.ts
sed -n '1,210p' mobile/src/session/use-mobile-session-screen-state.ts
sed -n '1,130p' mobile/src/session/use-mobile-session-tab-application.ts
printf '%s\n' '--- document types and image helper ---'
rg -n -A35 -B10 'type MarkdownDocState|interface MarkdownDocState|readMarkdownImageSources|imageSources|type MobileSessionTab' mobile/src/session mobile/src | head -n 500
printf '%s\n' '--- relevant tests ---'
sed -n '1,220p' mobile/src/session/use-mobile-session-document-readers.test.ts

Repository: stablyai/orca

Length of output: 41675


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 47735


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- reconciliation and application ---'
sed -n '1,240p' mobile/src/session/use-mobile-session-tab-reconciliation.ts
sed -n '1,290p' mobile/src/session/use-mobile-session-tab-application.ts
sed -n '1,280p' mobile/src/session/use-mobile-session-screen-state.ts
printf '%s\n' '--- markdown rendering and active content ---'
sed -n '1,180p' mobile/src/session/MobileSessionActiveContent.tsx
rg -n -A80 -B20 'imageSources|Markdown.*Editor|Markdown.*Preview|markdownDocs.get|onRefresh|localContent' mobile/src/session mobile/src | head -n 600
printf '%s\n' '--- exact tab identity and read callers ---'
rg -n -A45 -B15 'readMarkdownTab\\(|switchSessionTab\\(|setSessionTabs|sessionTabs|tab.id|documentVersion|filePath|relativePath' mobile/src/session --glob '*.{ts,tsx}' | head -n 1000
printf '%s\n' '--- changed hunk and baseline comparison ---'
git diff --no-ext-diff --unified=80 cb11a9ff1ae9b2c2d31e117f86ba71dd8b3271d8..1268466ef29099038eb180cf79ff703ed09636b0 -- mobile/src/session/use-mobile-session-document-readers.ts

Repository: stablyai/orca

Length of output: 41793


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- reconciliation and application ---'
sed -n '1,240p' mobile/src/session/use-mobile-session-tab-reconciliation.ts
sed -n '1,290p' mobile/src/session/use-mobile-session-tab-application.ts
sed -n '1,280p' mobile/src/session/use-mobile-session-screen-state.ts
printf '%s\n' '--- markdown rendering and active content ---'
sed -n '1,180p' mobile/src/session/MobileSessionActiveContent.tsx
rg -n -A80 -B20 'imageSources|Markdown.*Editor|Markdown.*Preview|markdownDocs.get|onRefresh|localContent' mobile/src/session mobile/src | head -n 600
printf '%s\n' '--- exact tab identity and read callers ---'
rg -n -A45 -B15 'readMarkdownTab\(|switchSessionTab\(|setSessionTabs|sessionTabs|tab.id|documentVersion|filePath|relativePath' mobile/src/session --glob '*.{ts,tsx}' | head -n 1000
printf '%s\n' '--- changed hunk and baseline comparison ---'
git diff --no-ext-diff --unified=80 cb11a9ff1ae9b2c2d31e117f86ba71dd8b3271d8..1268466ef29099038eb180cf79ff703ed09636b0 -- mobile/src/session/use-mobile-session-document-readers.ts

Repository: stablyai/orca

Length of output: 42103


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- exact rendering and refresh ---'
cat -n mobile/src/session/MobileSessionMarkdownReader.tsx | sed -n '1,150p'
cat -n mobile/src/session/MobileSessionActiveContent.tsx | sed -n '90,135p'
cat -n mobile/src/session/use-mobile-session-markdown-actions.ts | sed -n '125,185p'
printf '%s\n' '--- exact clean-tab reread and active read ---'
cat -n mobile/src/session/use-mobile-session-tab-switching.ts | sed -n '110,155p'
cat -n mobile/src/session/use-mobile-session-terminal-webview.ts | sed -n '105,130p'
printf '%s\n' '--- image helper and tab identity ---'
cat -n mobile/src/session/markdown-relative-image-srcs.ts | sed -n '100,140p'
cat -n mobile/src/session/mobile-session-route-types.ts | sed -n '40,105p'

Repository: stablyai/orca

Length of output: 16964


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- every imageSources reference ---'
rg -n -C5 'imageSources' mobile src --glob '*.{ts,tsx}' || true
printf '%s\n' '--- editor declaration and callers ---'
rg -n -C12 'export function MobileRichMarkdownEditor|function MobileRichMarkdownEditor|MobileRichMarkdownEditor' mobile/src --glob '*.{ts,tsx}'
printf '%s\n' '--- editor image rendering/configuration ---'
rg -n -C8 'image|markdown|resolve|data:' mobile/src/components/MobileRichMarkdownEditor* mobile/src/components --glob '*Markdown*' --glob '*.{ts,tsx}' 2>/dev/null || true

Repository: stablyai/orca

Length of output: 45665


Guard image-source publication by document generation.

readMarkdownTab can run again for the same tab while an earlier readMarkdownImageSources call is pending. The callback checks only ready status, so the earlier map can replace the newer document's map. The web editor applies this map to displayed images. Track a per-tab generation and require the captured content to match before publishing.

Suggested fix
-import { useCallback } from 'react'
+import { useCallback, useRef } from 'react'
...
   const { worktreeId, client, setMarkdownDocs, setFileDocs } = scope
+  const markdownReadGenerationRef = useRef&lt;Map&lt;string, number&gt;&gt;(new Map())
...
-    (tabId: string, relativePath: string, content: string) => {
+    (tabId: string, relativePath: string, content: string, generation: number) => {
...
-            if (!doc || doc.status !== 'ready') {
+            if (
+              !doc ||
+              doc.status !== 'ready' ||
+              doc.content !== content ||
+              markdownReadGenerationRef.current.get(tabId) !== generation
+            ) {
               return prev
             }
...
       if (!client) {
         return
       }
+      const generation = (markdownReadGenerationRef.current.get(tab.id) ?? 0) + 1
+      markdownReadGenerationRef.current.set(tab.id, generation)
       setMarkdownDocs((prev) => new Map(prev).set(tab.id, { status: 'loading' }))
...
-          resolveMarkdownImages(tab.id, tab.relativePath, result.content)
+          resolveMarkdownImages(tab.id, tab.relativePath, result.content, generation)
...
-        resolveMarkdownImages(tab.id, tab.relativePath, fileResult.content)
+        resolveMarkdownImages(tab.id, tab.relativePath, fileResult.content, generation)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

The fix does not work on native phones. MobileRichMarkdownEditor.tsx:75 double-encodes the image map into a JSON string, so the editor receives a string where it expects an object and never resolves a single relative image. Only the react-native-web sibling (which passes the object) works. The new bundle test calls the handle directly and never exercises the native transport, which is why CI is green.

Reviewed changes

Reviewed the complete 19-file diff at 1268466.

  • Relative image resolution — markdown-relative-image-srcs.ts scans a doc for non-external image srcs, resolves each against the document's directory (worktree-rooted /, rejects .. climb-out, decodes escapes, strips ?/#), keeps editor-renderable images (raster + SVG), and reads them through files.readPreview, answering authored-src → data-URL.
  • Session wiring — use-mobile-session-document-readers.ts patches the ready MarkdownDocState with the resolved map after the doc publishes; the route type gains an optional imageSources.
  • Editor display — a new setImageSources host command stores the map and re-applies it whenever the surface is rebuilt; data-orca-src keeps the authored src so a displayed image never round-trips into the saved file.
  • Serialization — html-inline-markdown.ts now reads data-orca-src before src.
  • Tests — collection/resolution, the session patch, the editor display-slot swap and round-trip, and the bundled document driven through the injected handle.

ℹ️ Saving a Markdown tab drops its resolved image sources

saveMarkdownTab replaces the ready doc with a fresh object that omits imageSources, unlike the ...existing spreads every other update in the session uses. After a save the doc is still ready, so nothing re-runs resolveMarkdownImages; if the editor remounts (tab switch) or the surface rebuilds, relative images render broken again with no recovery path.

Technical details
# Saving loses the resolved image map

## Affected sites
- `mobile/src/session/use-mobile-session-markdown-actions.ts:193-202` (untouched by this PR) — the save-success `setMarkdownDocs` publishes `{ status, content, localContent, baseVersion, isDirty, editable }` and drops `imageSources`.
- `mobile/src/session/use-mobile-session-document-readers.ts` — `resolveMarkdownImages` only runs from `readMarkdownTab`, which is not re-invoked for an already-ready doc.

## Required outcome
- A saved document keeps its resolved `imageSources` (or transparently re-resolves them), so switching away and back does not reintroduce broken images.

## Suggested approach
- Spread `...existing` in the save-success update, or call `resolveMarkdownImages` after a successful save.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

),
setImageSources: (sources: Record<string, string>) =>
inject(
`window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${escapeInjectedJavaScriptString(JSON.stringify(sources))});`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

escapeInjectedJavaScriptString(JSON.stringify(sources)) produces a JavaScript string literal, so the document's setImageSources receives the JSON text as a string. applyImageSources then evaluates sources[src] on that string (always undefined), so no relative image resolves on a phone. The web sibling passes the object and works, and the bundle test calls the handle directly, so neither surfaces this.

Technical details
# Native transport passes a JSON string where the document expects an object

## Affected sites
- `mobile/src/components/MobileRichMarkdownEditor.tsx:75` — double-encodes via `escapeInjectedJavaScriptString(JSON.stringify(sources))`; the injected argument evaluates to a string.
- `mobile/src/components/MobileRichMarkdownEditor.web.tsx:100-103` — passes the object directly, which is the contract `RichMarkdownEditorApi.setImageSources` declares.
- `mobile/src/components/rich-markdown/native-document-bundle.test.ts:108` — calls `handle.setImageSources({...})` directly, bypassing the native transport (unlike `setMarkdown`, which is injected at line 145).

## Required outcome
- The script injected by the native transport must evaluate to a `Record<string, string>` when it runs, matching the handle and the web transport.

## Suggested approach
- Inject the JSON as a value (`${JSON.stringify(sources)}`) instead of passing it through `escapeInjectedJavaScriptString`, and add a bundle test that drives `setImageSources` through `inject(...)`.

const sources: Record<string, string> = {}
await Promise.all(
collectMarkdownImageSrcs(content)
.slice(0, MAX_RESOLVED_IMAGE_SRCS)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

collectMarkdownImageSrcs scans raw Markdown, so image syntax inside fenced or inline code — which the editor renders as text, not as an image — still consumes the MAX_RESOLVED_IMAGE_SRCS budget and issues a read. A document with 24 such examples before a real image leaves that real image broken even though its file is available. Consider skipping fenced/inline code when collecting.

if (!doc || doc.status !== 'ready') {
return prev
}
return new Map(prev).set(tabId, { ...doc, imageSources })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The patch only checks that the tab is ready, not that the doc still belongs to the content this read started from. A refresh or re-read can begin more image reads while an earlier read is pending, and the older map then lands on the newer doc — stale bytes for a src whose file changed. Guard on doc.content === content (or a per-read generation) before patching.

…eview

The file preview rendered every image as tappable link text; the editor's
data-URL resolution never reached it. The preview screen now resolves the
same authored srcs over files.readPreview and renders real images: full
width for standalone tokens, thumbnails inline in prose and table cells.
Also mock the fork-only media handoff in the retry test, whose unconditional
screen import broke the suite at collect time.
Tapping an image in the markdown file preview now pushes that image's own
file-preview route, with the src resolved against the document the way the
data-URL reads already resolve, so it lands in the existing pinch-zoom image
viewer (1x-4x). MobileMarkdown gains an optional onOpenImage so image taps
route through the document owner instead of the generic file-href opener;
callers that do not pass it keep exactly the old behavior.
…editor

The relative-image fix landed in MobileMarkdownReader, a component with no
production consumer; the session's live file-tab editor
(MobileSessionMarkdownReader) never received the resolved imageSources, so
repository-relative images stayed broken in the surface users actually edit
in, and tapping one did nothing.

The live editor now receives the doc's imageSources, and a tap on an image
reports openImage with its authored src through the WebView bridge. The
session resolves the src against the markdown tab's directory — the same
markdownImageTapPreviewHref the file preview uses — and pushes the image's
own preview route, the existing pinch-zoom viewer.

External image srcs (schemed or protocol-relative URLs) have no worktree
file behind them: they route as web hrefs like before, on both the editor
and the file preview, instead of pushing a bogus worktree route.
markdown-href-routing had started importing the image-srcs module for the
external-src predicate, dragging the image-read RPC graph into every route
that renders prose and regrouping esbuild chunks: the mobile web bundle
read 74 scripts against the swept 69 + 4 margin and failed packaging on
linux/mac.

The predicate is one regex and stays local to each light consumer —
markdown-href-routing here, editor-listeners in the WebView document —
and the tapped-image href builder folds into markdown-relative-image-srcs,
whose importer set already covers both routes that call it, so no new
shared chunk is emitted. The sweep table is re-derived, never bumped: the
bundle reads 73 scripts / 122 assets again with the fence untouched.
…form

The image viewer leaned on ScrollView maximumZoomScale/centerContent, which
React Native only honors on iOS — on Android the pinch did nothing at all,
so a tapped markdown image opened a preview that could never zoom. Replace
it with a GestureDetector pinch/pan/double-tap viewer (focal-anchored zoom,
pan clamped to the grown image edge, double-tap toggling 1x/2.5x), with the
transform math in a plain module the worklets bundle.
The rendered markdown and source views of a worktree file had no zoom at
all, while the native chat scales its font with a pinch. Reuse the chat's
pinch gesture hook here: the preview's MobileMarkdown gets the gesture's
fontScale as textScale, and the source view scales its mono font from the
same committed scale.
…s with the pinch

The file preview's pinch gesture only reached paragraph and list text:
table cells, headings, quotes, code blocks, and list markers kept their
base size, and inline image thumbnails stayed fixed. textScale now covers
every text block in MobileMarkdown and threads the same multiplier into
MarkdownInlineImage, so a pinched document grows as one — including table
text and images inside table cells. Tapping any image still opens the
full-screen zoomable viewer.
@dudupii dudupii changed the title fix(mobile): render repository-relative images in the markdown editor fix(mobile): render and zoom relative images in markdown, pinch-scale the file preview Oct 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
mobile/src/components/MobileRichMarkdownEditor.tsx (1)

74-77: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Pass the source map as an object, not as a JSON string literal.

escapeInjectedJavaScriptString(JSON.stringify(sources)) produces a JavaScript string literal. The document's setImageSources therefore receives a string. Lookups on that string return undefined, so no relative image resolves in the native WebView. The web transport passes the object directly, and the bundle test calls the handle directly, so neither path shows this failure.

🐛 Proposed fix
-          `window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${escapeInjectedJavaScriptString(JSON.stringify(sources))});`
+          `window.__orcaRichMarkdown && window.__orcaRichMarkdown.setImageSources(${JSON.stringify(sources).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')});`

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7b6170eb-f881-466b-b58b-50081226f1b7
📥 Commits

Reviewing files that changed from the base of the PR and between 1268466 and 8e55456.

📒 Files selected for processing (31)
  • mobile/src/components/MobileMarkdown.file-links.test.ts
  • mobile/src/components/MobileMarkdown.text-scale.test.tsx
  • mobile/src/components/MobileMarkdown.tsx
  • mobile/src/components/MobileRichMarkdownEditor.tsx
  • mobile/src/components/MobileRichMarkdownEditor.web.tsx
  • mobile/src/components/markdown-href-routing.test.ts
  • mobile/src/components/markdown-href-routing.ts
  • mobile/src/components/markdown-image-view.tsx
  • mobile/src/components/mobile-markdown-styles.ts
  • mobile/src/components/mobile-rich-markdown-editor-contract.ts
  • mobile/src/components/rich-markdown/editor-listeners.ts
  • mobile/src/components/rich-markdown/native-document-bundle.test.ts
  • mobile/src/components/use-mobile-rich-markdown-editor-controller.ts
  • mobile/src/files/MobileFileMarkdownPreview.test.ts
  • mobile/src/files/MobileFileMarkdownPreview.tsx
  • mobile/src/files/MobileFilePreviewBody.tsx
  • mobile/src/files/MobileFilePreviewScreen.tsx
  • mobile/src/files/MobileFilePreviewSourceText.tsx
  • mobile/src/files/MobileZoomableImage.test.tsx
  • mobile/src/files/MobileZoomableImage.tsx
  • mobile/src/files/mobile-file-preview-markdown-images.test.tsx
  • mobile/src/files/mobile-file-preview-retry.test.tsx
  • mobile/src/files/mobile-file-preview-styles.ts
  • mobile/src/files/zoomable-image-transform.test.ts
  • mobile/src/files/zoomable-image-transform.ts
  • mobile/src/session/MobileSessionActiveContent.tsx
  • mobile/src/session/MobileSessionMarkdownReader.test.tsx
  • mobile/src/session/MobileSessionMarkdownReader.tsx
  • mobile/src/session/markdown-relative-image-srcs.test.ts
  • mobile/src/session/markdown-relative-image-srcs.ts
  • mobile/src/session/use-mobile-session-file-actions.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

dudupii added 11 commits October 7, 2026 00:00
upstream main moved 615 commits past the PR's fork base; the one textual
conflict (MobileMarkdown.tsx) keeps both upstream's android transcript
long-press forwarding and this branch's pinch text scaling.
…kdown

The upstream merge brought the android transcript long-press forwarding
into the same file as the pinch text scaling, pushing MobileMarkdown.tsx
past the 400-line oxlint cap. The cap is not disabled or bumped: the
context-backed MarkdownText moves to markdown-text.tsx and the inline
token renderer to markdown-inline-render.tsx, leaving the block renderer
in MobileMarkdown.tsx. The text-scale test's react-native mock gains the
Platform member the shared inline-text-selection import reads.
Keeps upstream's orca-visual directive blocks, useMobileMarkdownBlocks
hook, and media preview kind alongside this branch's pinch text scaling,
resolved image sources, and zoomable image viewer.
The upstream merge puts MobileFileMediaPreview in the preview body's
import graph; without the mock its expo-file-system dependency breaks
collection (__DEV__ is not defined). Replaces the phantom
MobileFileMediaHandoff mock the cherry-pick carried over from the fork
branch, which never resolved on this branch.
…-relative-images

# Conflicts:
#	mobile/src/components/markdown-href-routing.test.ts
…-relative-images

# Conflicts:
#	mobile/src/session/MobileSessionMarkdownReader.test.tsx
- session-markdown-source-copy probe renders MarkdownReader with the
  onOpenImage prop this PR adds as required
- replace upstream's 'as never' type assertions and hoisted-seam casts
  with String(node.type) comparisons and return-type annotations so the
  changed-lines casting gate stays clean
…-relative-images

# Conflicts:
#	mobile/src/files/MobileFilePreviewBody.tsx
#	mobile/src/session/MobileSessionMarkdownReader.test.tsx
…-relative-images

# Conflicts:
#	mobile/src/components/MobileMarkdown.tsx
…-relative-images

# Conflicts:
#	.github/scripts/check-required-pr-context.mjs

@nwparker nwparker left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scope review and cross-reference for #24468: I compared this patch's paired-host files.readPreview reads, authored data-orca-src preservation, inline/block image rendering, file-preview wiring, and zoom changes with #31304. Thank you @dudupii for the report, diagnosis, implementation, and device evidence.

#31304 is the narrower standalone-image fix for the read-only file preview and reuses the existing full-screen viewer. It does not replace this PR's rich-editor serialization, inline-image, or pinch-zoom work. #25594 also preserves your authored editor implementation. Credit and these scope links have been added to #31304; #24468 will remain open for the broader editor scope. This is a code/scope comparison, not a claim that I ran this branch's device tests.

nwparker added a commit that referenced this pull request Oct 21, 2026
Render standalone embedded images in Markdown file previews and open them in the existing full-screen viewer. Resolve relative paths through authorized paired-host reads.

Thanks to @dudupii for reporting and diagnosing #24468 and implementing the broader solution in #24469; related editor integration is preserved in #25594. This independently implemented preview fix leaves editor image serialization, inline images, and pinch zoom as separate work.

Validation: focused tests, iPhone simulator proof, and all CI checks passed.
@nwparker

nwparker commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded — the linked issue (#24468) has been resolved on main by #31304 (ecc4a6cacf). Thanks for the contribution!

@nwparker nwparker closed this Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mobile: images in Markdown documents render as broken

2 participants