Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(chat): open local file links in the editor (#1114)
Call White82e34dd34e72
diff --git a/ui/src/components/ui/chat-image.tsx b/ui/src/components/ui/chat-image.tsxindex 926cb5226..7c7a901f9 100644--- a/ui/src/components/ui/chat-image.tsx+++ b/ui/src/components/ui/chat-image.tsx@@ -17,6 +17,12 @@ const LinkedImageContext = React.createContext(false);export const LinkedImageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => (<LinkedImageContext.Provider value={true}>{children}</LinkedImageContext.Provider>);+export const LinkedImageContent: React.FC<{+ linked: React.ReactNode;+ unlinked: React.ReactNode;+}> = ({ linked, unlinked }) => (+ React.useContext(LinkedImageContext) ? linked : unlinked+);// Preview caps (mirror the design): an image renders at its natural size, scaled// down to fit a max width of 22rem and a max height of 15rem, never upscaled.diff --git a/ui/src/components/ui/file-viewer-modal.tsx b/ui/src/components/ui/file-viewer-modal.tsxindex 51135b284..21e3df4c0 100644--- a/ui/src/components/ui/file-viewer-modal.tsx+++ b/ui/src/components/ui/file-viewer-modal.tsx@@ -7,6 +7,7 @@ import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';import { FilePreview } from '@/components/ui/file-preview';import { apiFetch } from '@/lib/apiFetch';import { handleMediaDownloadClick } from '@/lib/downloadMedia';+import { contentUrl, downloadFile } from '@/lib/filesApi';import { isProxyMediaUrl } from '@/lib/mediaProxy';import { formatBytes } from '@/lib/filePreview';import { copyTextToClipboard } from '@/lib/utils';@@ -16,33 +17,38 @@ import type { FilePreviewTarget } from '@/components/ui/file-viewer';// kernel, which owns every renderer (Shiki, the JSON tree, papaparse, the Office parsers, images, PDF,// HTML) and lazy-loads each. Default export so ``React.lazy`` can split it out of the main bundle.//-// A lightweight /meta fetch resolves the real name / size / content-type before rendering, so the-// kernel can pick the right renderer for a proxy URL whose path is just a token. In-app preview is-// restricted to our own same-origin media proxy — a non-proxy URL is never auto-fetched (it would-// leak the viewer's network to a third-party host).+// A lightweight /meta fetch resolves media-proxy metadata before rendering. Local file targets are+// already classified from `/api/files/meta` by the caller and use the same-origin Files content API.+// Arbitrary non-proxy URLs are never auto-fetched, so preview cannot leak a request to a third party.type Meta = { name: string; size: number | null; mime: string | null; ext: string | null };export default function FileViewerModal({ target, onClose }: { target: FilePreviewTarget; onClose: () => void }) {const { t } = useTranslation();- const proxy = isProxyMediaUrl(target.url);- const [meta, setMeta] = React.useState<Meta>(() => ({ name: target.name || '', size: null, mime: null, ext: null }));- const [metaLoaded, setMetaLoaded] = React.useState(false);+ const local = target.kind === 'local';+ const localPath = local ? target.path : null;+ const mediaUrl = target.kind === 'local' ? null : target.url;+ const targetName = target.name || '';+ const proxy = mediaUrl ? isProxyMediaUrl(mediaUrl) : false;+ const [meta, setMeta] = React.useState<Meta>(() => target.kind === 'local'+ ? { name: target.name, size: target.size, mime: target.mime, ext: target.ext }+ : { name: targetName, size: null, mime: null, ext: null });+ const [metaLoaded, setMetaLoaded] = React.useState(local);// The kernel reports the file's text when it loads a text kind — enables the copy button (and stays// null for image / pdf / office, where copy is meaningless).const [text, setText] = React.useState<string | null>(null);const [copied, setCopied] = React.useState(false);React.useEffect(() => {- if (!proxy) return; // non-proxy → never fetch; the body shows an error instead+ if (!proxy || !mediaUrl) return; // local metadata is supplied; arbitrary remote URLs are never fetchedlet alive = true;- apiFetch(`${target.url}/meta`, { headers: { Accept: 'application/json' } })+ apiFetch(`${mediaUrl}/meta`, { headers: { Accept: 'application/json' } }).then((res) => (res.ok ? res.json() : null)).then((m: { name?: string; size?: number; content_type?: string; ext?: string } | null) => {if (!alive) return;if (m) {setMeta({- name: m.name || target.name || '',+ name: m.name || targetName,size: typeof m.size === 'number' ? m.size : null,mime: m.content_type || null,ext: m.ext || null,@@ -56,7 +62,7 @@ export default function FileViewerModal({ target, onClose }: { target: FilePrevireturn () => {alive = false;};- }, [target.url, target.name, proxy]);+ }, [mediaUrl, targetName, proxy]);const copy = async () => {if (text == null) return;@@ -66,14 +72,15 @@ export default function FileViewerModal({ target, onClose }: { target: FilePrevi}};- const name = meta.name || target.name || '';+ const name = meta.name || targetName;const ext = name.includes('.') ? (name.split('.').pop() || '').toUpperCase() : '';const metaLine = [ext || null, formatBytes(meta.size) || null].filter(Boolean).join(' · ');let body: React.ReactNode;- if (!proxy) body = <div className="vr-fileview-msg">{t('preview.failed')}</div>;+ const previewUrl = localPath ? contentUrl(localPath) : mediaUrl || '';+ if (!local && !proxy) body = <div className="vr-fileview-msg">{t('preview.failed')}</div>;else if (!metaLoaded) body = <div className="vr-fileview-msg">{t('common.loading')}</div>;- else body = <FilePreview source={{ url: target.url, name, ext: meta.ext, mime: meta.mime, size: meta.size }} onText={setText} />;+ else body = <FilePreview source={{ url: previewUrl, name, ext: meta.ext, mime: meta.mime, size: meta.size }} onText={setText} />;return (<Dialog@@ -99,11 +106,24 @@ export default function FileViewerModal({ target, onClose }: { target: FilePrevi{copied ? <Check className="size-4 text-mint" /> : <Copy className="size-4" />}</Button>)}- <Button asChild variant="ghost" size="icon" className="size-8 text-mint" aria-label={t('chat.media.download')}>- <a href={`${target.url}?download=1`} download onClick={(e) => handleMediaDownloadClick(e, target.url, name || undefined)}>+ {local && localPath ? (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-8 text-mint"+ aria-label={t('chat.media.download')}+ onClick={() => downloadFile(localPath)}+ ><Download className="size-4" />- </a>- </Button>+ </Button>+ ) : (+ <Button asChild variant="ghost" size="icon" className="size-8 text-mint" aria-label={t('chat.media.download')}>+ <a href={`${mediaUrl}?download=1`} download onClick={(e) => handleMediaDownloadClick(e, mediaUrl || '', name || undefined)}>+ <Download className="size-4" />+ </a>+ </Button>+ )}</div><div className="vr-fileview-body min-h-0 flex-1 overflow-hidden">{body}</div></DialogContent>diff --git a/ui/src/components/ui/file-viewer.tsx b/ui/src/components/ui/file-viewer.tsxindex 49688a649..bd21cfe6e 100644--- a/ui/src/components/ui/file-viewer.tsx+++ b/ui/src/components/ui/file-viewer.tsx@@ -1,14 +1,23 @@import * as React from 'react';// Session-scoped in-app file preview. ChatPage mounts the provider; a FileCard-// with a previewable file calls ``open({ url, name })`` to show the modal. The+// with a previewable proxy file or a classified local rich file opens the modal. The// heavy modal (Shiki, the JSON viewer, the CSV parser) is ``React.lazy``-loaded,// so none of it touches the main app bundle — it arrives only when the first// preview opens. Mirrors ImageViewerProvider so the two media viewers stay// structurally consistent; FileCard falls back to a plain link where no// provider is mounted (``useFileViewer()`` returns null).-export type FilePreviewTarget = { url: string; name?: string };+export type FilePreviewTarget =+ | { kind?: 'media'; url: string; name?: string }+ | {+ kind: 'local';+ path: string;+ name: string;+ size: number | null;+ mime: string | null;+ ext: string | null;+ };type FileViewerContextValue = { open: (target: FilePreviewTarget) => void };@@ -31,9 +40,13 @@ export const FileViewerProvider: React.FC<{ children: React.ReactNode }> = ({ ch{children}{target && (<React.Suspense fallback={null}>- {/* key by url so opening a different file remounts the modal: state+ {/* Key by source so opening a different file remounts the modal: stateresets to ``loading`` without a setState-in-effect. */}- <FileViewerModal key={target.url} target={target} onClose={close} />+ <FileViewerModal+ key={target.kind === 'local' ? `local:${target.path}` : target.url}+ target={target}+ onClose={close}+ /></React.Suspense>)}</FileViewerContext.Provider>diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsxindex d2f921b77..8450bd958 100644--- a/ui/src/components/ui/markdown.tsx+++ b/ui/src/components/ui/markdown.tsx@@ -6,10 +6,11 @@ import { useTranslation } from 'react-i18next';import { Check, Copy } from 'lucide-react';import { Badge } from '@/components/ui/badge';-import { ChatImage, LinkedImageProvider } from '@/components/ui/chat-image';+import { ChatImage, LinkedImageContent, LinkedImageProvider } from '@/components/ui/chat-image';import { FileCard } from '@/components/ui/file-card';import { SecretRequestCard } from '@/components/ui/secret-request-card';import { isProxyMediaUrl, readMediaDims } from '@/lib/mediaProxy';+import { isAbsoluteWindowsFileHref, resolveLocalFileLink, type LocalFileLinkTarget } from '@/lib/localFileLinks';import {MENTION_LINK_SCHEME,linkifyMentions,@@ -71,8 +72,12 @@ function linkifySecretRequests(text: string): string {// Keep react-markdown's URL sanitizer from stripping our custom schemes (it allows// only http/https/mailto/tel/relative by default).-function mentionUrlTransform(url: string): string {- if (url.startsWith(`${MENTION_LINK_SCHEME}:`) || url.startsWith(`${SECRET_LINK_SCHEME}:`)) return url;+function mentionUrlTransform(url: string, allowLocalFiles: boolean): string {+ if (+ url.startsWith(`${MENTION_LINK_SCHEME}:`)+ || url.startsWith(`${SECRET_LINK_SCHEME}:`)+ || (allowLocalFiles && isAbsoluteWindowsFileHref(url))+ ) return url;return defaultUrlTransform(url);}@@ -108,6 +113,57 @@ const CodeBlock: React.FC<{ children?: React.ReactNode }> = ({ children }) => {);};+const MarkdownImage: React.FC<{+ src?: string;+ alt?: string;+ interactive: boolean;+ localFileWorkdir?: string | null;+ onOpenLocalFile?: (target: LocalFileLinkTarget) => void | Promise<void>;+}> = ({ src, alt, interactive, localFileWorkdir, onOpenLocalFile }) => {+ if (!src) return null;++ const url = String(src);+ if (interactive && isProxyMediaUrl(url)) {+ // Pixel dimensions ride on the proxy URL (``?w=&h=``) so the image's+ // box is reserved before it loads — no scroll shift on the transcript.+ const { width, height } = readMediaDims(url);+ return <ChatImage src={url} alt={alt || ''} width={width} height={height} />;+ }++ const label = `🖼 ${alt || url}`;+ const localFile = interactive && onOpenLocalFile+ ? resolveLocalFileLink(url, localFileWorkdir)+ : null;+ let unlinked: React.ReactNode;+ if (localFile) {+ unlinked = (+ <a+ href={url}+ data-local-file-link="true"+ onClick={(event) => {+ event.preventDefault();+ void onOpenLocalFile?.(localFile);+ }}+ onAuxClick={(event) => event.preventDefault()}+ >+ {label}+ </a>+ );+ } else {+ unlinked = interactive ? (+ <a href={url} target="_blank" rel="noopener noreferrer nofollow">+ {label}+ </a>+ ) : (+ <span>{label}</span>+ );+ }++ // The surrounding Markdown link owns the click. Rendering another anchor+ // here would create invalid nested links and invoke both local-file handlers.+ return <LinkedImageContent linked={<span>{label}</span>} unlinked={unlinked} />;+};+export const Markdown: React.FC<{content: string;className?: string;@@ -121,6 +177,10 @@ export const Markdown: React.FC<{* or quoted text could mint an "agent asked for this secret" card that creates a vault* secret on click. */secretRequests?: boolean;+ /** Agent-reply opt-in: `/abs/path` and `./relative/path` Markdown links open+ * in Avibe's Editor. Relative paths resolve from the owning Session workdir. */+ localFileWorkdir?: string | null;+ onOpenLocalFile?: (target: LocalFileLinkTarget) => void | Promise<void>;/** The surface can never accept another write (an archived session's transcript).* Narrow by design: it locks the interactive markers this renderer can mint —* today the secret-request cards — and deliberately does NOT touch reads@@ -134,6 +194,8 @@ export const Markdown: React.FC<{softBreaks = false,references,secretRequests = false,+ localFileWorkdir,+ onOpenLocalFile,readOnly = false,}) => {// Stable ``remarkPlugins`` + ``components`` identities across re-renders.@@ -160,24 +222,15 @@ export const Markdown: React.FC<{// render a real inline <img> for our OWN same-origin media proxy; every// other URL stays a click-through link (or plain text when// non-interactive) so nothing is fetched without an explicit action.- img: ({ src, alt }) => {- if (!src) return null;- const url = String(src);- if (interactive && isProxyMediaUrl(url)) {- // Pixel dimensions ride on the proxy URL (``?w=&h=``) so the image's- // box is reserved before it loads — no scroll shift on the transcript.- const { width, height } = readMediaDims(url);- return <ChatImage src={url} alt={alt || ''} width={width} height={height} />;- }- const label = `🖼 ${alt || url}`;- return interactive ? (- <a href={url} target="_blank" rel="noopener noreferrer nofollow">- {label}- </a>- ) : (- <span>{label}</span>- );- },+ img: ({ src, alt }) => (+ <MarkdownImage+ src={src ? String(src) : undefined}+ alt={alt || undefined}+ interactive={interactive}+ localFileWorkdir={localFileWorkdir}+ onOpenLocalFile={onOpenLocalFile}+ />+ ),// Links to our media proxy are agent-produced files → render the// download card (filename + type + download / preview). Other links keep// the normal anchor (interactive) or collapse to plain text inside a@@ -211,6 +264,24 @@ export const Markdown: React.FC<{if (interactive && url && isProxyMediaUrl(url)) {return <FileCard href={url}>{children}</FileCard>;}+ const localFile = interactive && onOpenLocalFile+ ? resolveLocalFileLink(url, localFileWorkdir)+ : null;+ if (localFile) {+ return (+ <a+ href={url}+ data-local-file-link="true"+ onClick={(event) => {+ event.preventDefault();+ void onOpenLocalFile?.(localFile);+ }}+ onAuxClick={(event) => event.preventDefault()}+ >+ <LinkedImageProvider>{children}</LinkedImageProvider>+ </a>+ );+ }if (!interactive) return <span>{children}</span>;// Wrap children so a nested ChatImage (``[](href)``) renders// bare — without its own download anchor inside this one.@@ -244,7 +315,7 @@ export const Markdown: React.FC<{),}),}),- [interactive, secretRequests, readOnly],+ [interactive, secretRequests, readOnly, localFileWorkdir, onOpenLocalFile],);// Mention markers are rewritten to `avibe-mention:` links BEFORE markdown sees@@ -254,12 +325,13 @@ export const Markdown: React.FC<{// (secretRequests) — user bubbles / previews / docs keep them as plain text.let rendered = references && references.length ? linkifyMentions(content, references) : content;if (secretRequests) rendered = linkifySecretRequests(rendered);+ const urlTransform = (url: string) => mentionUrlTransform(url, Boolean(onOpenLocalFile));return (<div className={cn('vr-markdown', className)}><ReactMarkdownremarkPlugins={remarkPlugins}components={components}- urlTransform={mentionUrlTransform}+ urlTransform={urlTransform}>{rendered}</ReactMarkdown>diff --git a/ui/src/components/workbench/AppsEditorPage.tsx b/ui/src/components/workbench/AppsEditorPage.tsxindex 8a66f729e..4f381bdb4 100644--- a/ui/src/components/workbench/AppsEditorPage.tsx+++ b/ui/src/components/workbench/AppsEditorPage.tsx@@ -21,16 +21,29 @@ const DESKTOP_QUERY = '(min-width: 768px)';// A file handed to the editor when navigating in from the File Browser (mobile) or a direct link.// Carried in router state — like the window params `wm.openApp` passes — so absolute paths stay out// of the URL; a refresh (no state) just lands on the empty/welcome state.-type LaunchFile = { path: string; filename: string; mtime: number | null };+type LaunchFile = {+ path: string;+ filename: string;+ mtime: number | null;+ line?: number;+ column?: number;+ endColumn?: number;+};function readLaunch(state: unknown): LaunchFile | null {if (!state || typeof state !== 'object') return null;const s = state as Record<string, unknown>;if (typeof s.path !== 'string') return null;+ const line = typeof s.line === 'number' && Number.isInteger(s.line) && s.line > 0 ? s.line : undefined;+ const column = typeof s.column === 'number' && Number.isInteger(s.column) && s.column >= 0 ? s.column : 0;+ const endColumn = typeof s.endColumn === 'number' && Number.isInteger(s.endColumn) && s.endColumn >= column+ ? s.endColumn+ : column;return {path: s.path,filename: typeof s.filename === 'string' ? s.filename : s.path.split('/').filter(Boolean).pop() || s.path,mtime: typeof s.mtime === 'number' ? s.mtime : null,+ ...(line ? { line, column, endColumn } : {}),};}@@ -99,7 +112,7 @@ const DesktopEditor: React.FC<{<Suspense fallback={<PaneLoading />}><EditorApponDirtyChange={onDirtyChange}- params={launch ? { path: launch.path, filename: launch.filename, mtime: launch.mtime } : undefined}+ params={launch ?? undefined}/></Suspense></div>@@ -144,6 +157,12 @@ const MobileEditor: React.FC<{onOpenFile={openAnother}headerActions={<EditorFontSizePopover trigger="mobile" />}onDirtyChange={onDirtyChange}+ reveal={file.line ? {+ line: file.line,+ column: file.column ?? 0,+ endColumn: file.endColumn ?? file.column ?? 0,+ nonce: 0,+ } : null}/>) : (<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4 p-8 text-center">diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsxindex 355d99288..db03c61f5 100644--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx@@ -502,3 +502,93 @@ describe('read-only transcript locks the secret-request cards', () => {}});});++describe('agent-authored local file links', () => {+ const linkedMessage = (author: 'agent' | 'user'): WorkbenchMessage => ({+ ...agentWithQuickReplies(),+ author,+ type: author === 'agent' ? 'result' : 'user',+ text: '[open report](./reports/result.md)',+ content: {},+ }) as WorkbenchMessage;++ it('opts only Agent replies into the Editor link handler', () => {+ const props = {+ session: session({ workdir: '/workspace/project' }),+ messageFontSize: 13,+ onOpenLocalFile: () => undefined,+ };++ const agent = render(<MessageRow {...props} message={linkedMessage('agent')} />);+ expect(agent).toContain('data-local-file-link="true"');+ expect(agent).not.toContain('target="_blank"');++ const user = render(<MessageRow {...props} message={linkedMessage('user')} />);+ expect(user).not.toContain('data-local-file-link');+ expect(user).toContain('target="_blank"');+ });++ it('preserves absolute Windows destinations through Markdown URL sanitization', () => {+ const props = {+ session: session({ workdir: 'C:\\workspace' }),+ messageFontSize: 13,+ onOpenLocalFile: () => undefined,+ };+ const windowsMessage = {+ ...linkedMessage('agent'),+ text: '[open source](C:/workspace/app.py:42)',+ } as WorkbenchMessage;++ const markup = render(<MessageRow {...props} message={windowsMessage} />);+ expect(markup).toContain('data-local-file-link="true"');+ expect(markup).toContain('href="C:/workspace/app.py:42"');++ const userMarkup = render(<MessageRow {...props} message={{ ...windowsMessage, author: 'user', type: 'user' }} />);+ expect(userMarkup).not.toContain('data-local-file-link');+ expect(userMarkup).not.toContain('href="C:/workspace/app.py:42"');+ });++ it('opens UNC files locally while leaving Workbench routes as browser links', () => {+ const props = {+ session: session({ workdir: '\\\\server\\share' }),+ messageFontSize: 13,+ onOpenLocalFile: () => undefined,+ };+ const uncMessage = {+ ...linkedMessage('agent'),+ text: '[open source](%5C%5Cserver%5Cshare%5Capp.py:42)',+ } as WorkbenchMessage;+ const routeMessage = {+ ...linkedMessage('agent'),+ text: '[open files](/apps/files)',+ } as WorkbenchMessage;++ const uncMarkup = render(<MessageRow {...props} message={uncMessage} />);+ expect(uncMarkup).toContain('data-local-file-link="true"');+ expect(uncMarkup).toContain('href="%5C%5Cserver%5Cshare%5Capp.py:42"');++ const routeMarkup = render(<MessageRow {...props} message={routeMessage} />);+ expect(routeMarkup).not.toContain('data-local-file-link');+ expect(routeMarkup).toContain('href="/apps/files"');+ expect(routeMarkup).toContain('target="_blank"');+ });++ it('lets the outer local link own clicks for a linked local image', () => {+ const linkedImageMessage = {+ ...linkedMessage('agent'),+ text: '[](/tmp/report.md)',+ } as WorkbenchMessage;+ const markup = render(+ <MessageRow+ message={linkedImageMessage}+ session={session({ workdir: '/workspace/project' })}+ messageFontSize={13}+ onOpenLocalFile={() => undefined}+ />,+ );++ expect(markup.match(/data-local-file-link/g)).toHaveLength(1);+ expect(markup).toContain('href="/tmp/report.md"');+ expect(markup).not.toContain('href="/tmp/preview.png"');+ });+});diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex cd6062f3b..ebd24fc23 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -9,6 +9,7 @@ import { useApi } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';+import { useWindowManager } from '../../context/WindowManagerContext';import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';import { apiFetch } from '../../lib/apiFetch';import { readChatViewMode, writeChatViewMode } from '../../lib/chatViewMemory';@@ -20,6 +21,10 @@ import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';import { isProxyMediaUrl } from '../../lib/mediaProxy';import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';import { showPageEmbeddedPath } from '../../apps/showPageAvatar';+import { downloadFile, fileMeta } from '../../lib/filesApi';+import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/filePreview';+import { recentPathLabel } from '../../lib/editorRecents';+import type { LocalFileLinkTarget } from '../../lib/localFileLinks';import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';import {activityItemKind,@@ -57,7 +62,7 @@ import { Button } from '../ui/button';import { ChatImage } from '../ui/chat-image';import { FileCard } from '../ui/file-card';import { ImageViewerProvider } from '../ui/image-viewer';-import { FileViewerProvider } from '../ui/file-viewer';+import { FileViewerProvider, useFileViewer } from '../ui/file-viewer';import { Input } from '../ui/input';import { Markdown } from '../ui/markdown';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';@@ -2844,6 +2849,44 @@ const Transcript: React.FC<TranscriptProps> = ({footer,}) => {const { t } = useTranslation();+ const navigate = useNavigate();+ const { openApp } = useWindowManager();+ const fileViewer = useFileViewer();+ const openLocalFile = useCallback(async (target: LocalFileLinkTarget) => {+ const pathLabel = recentPathLabel(target.path);+ const desktop = window.matchMedia('(min-width: 768px)').matches;+ const openPreview = (name: string, size: number | null, mime: string | null, ext: string | null) => {+ if (desktop) {+ openApp('preview', { title: name, params: { path: target.path, name } });+ } else if (fileViewer) {+ fileViewer.open({ kind: 'local', path: target.path, name, size, mime, ext });+ } else {+ downloadFile(target.path);+ }+ };+ const openEditor = (filename: string, mtime: number | null) => {+ const launch = { ...target, filename, mtime };+ if (desktop) openApp('editor', { title: filename, params: launch });+ else navigate('/apps/editor', { state: launch });+ };++ try {+ const meta = await fileMeta(target.path);+ if (previewOverlayKind(meta)) {+ openPreview(meta.name || pathLabel, meta.size, meta.mime, meta.ext);+ } else if (isEditableMeta(meta)) {+ openEditor(meta.name || pathLabel, meta.mtime);+ } else {+ downloadFile(target.path);+ }+ } catch {+ // Mirror the File Browser's name-only fallback when metadata is unavailable.+ const fallback = { kind: 'file', name: pathLabel, size: null };+ if (previewOverlayKind(fallback)) openPreview(pathLabel, null, null, null);+ else if (isEditableFile(fallback)) openEditor(pathLabel, null);+ else downloadFile(target.path);+ }+ }, [fileViewer, navigate, openApp]);const selectionActions = transcriptSelectionActions(session, readOnly);const forkSourceSessionId =typeof session.metadata?.fork_source_session_id === 'string'@@ -3220,6 +3263,7 @@ const Transcript: React.FC<TranscriptProps> = ({session={session}messageFontSize={messageFontSize}onQuickReply={onQuickReply}+ onOpenLocalFile={openLocalFile}readOnly={readOnly}highlighted={message.id === highlightedId}/>@@ -3318,6 +3362,7 @@ type MessageRowProps = {session: WorkbenchSession;messageFontSize: number;onQuickReply?: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;+ onOpenLocalFile?: (target: LocalFileLinkTarget) => void | Promise<void>;// Archived session: the row still renders in full — including the quick-reply// group and which option was chosen, which is part of the transcript — but the// group is frozen, so an old quick reply can no longer POST a doomed message.@@ -3339,7 +3384,7 @@ type MessageRowProps = {// useCallback), so the default shallow compare is correct here.// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),// which renders a single row rather than mounting the whole page.-export const MessageRow = memo(function MessageRow({ message, session, messageFontSize, onQuickReply, readOnly, highlighted }: MessageRowProps) {+export const MessageRow = memo(function MessageRow({ message, session, messageFontSize, onQuickReply, onOpenLocalFile, readOnly, highlighted }: MessageRowProps) {const { t } = useTranslation();const navigate = useNavigate();// Harness rows are collapsed by default; this tracks the per-row expand state.@@ -3440,6 +3485,8 @@ export const MessageRow = memo(function MessageRow({ message, session, messageFo// card). Keyed to authorship, not to the card family, so the agent's reverse annotation// keeps the card it had before that row had its own type.secretRequests={agentAuthored}+ localFileWorkdir={agentAuthored ? session.workdir : undefined}+ onOpenLocalFile={agentAuthored ? onOpenLocalFile : undefined}// …and on an archived transcript the card is locked: archiving EXPIRED the// session's provision requests, so an enabled Provide button would tell the// reader an agent is waiting for this secret when none is.diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsxindex 57120af6b..fe7e4a822 100644--- a/ui/src/components/workbench/EditorApp.tsx+++ b/ui/src/components/workbench/EditorApp.tsx@@ -407,7 +407,23 @@ export const EditorApp: React.FC<{if (p) {const name = (typeof params?.filename === 'string' ? params.filename : p.split('/').filter(Boolean).pop()) || p;if (previewOverlayKind({ kind: 'file', name, size: null })) openPreview(p, name);- else openFile(p, name, typeof params?.mtime === 'number' ? params.mtime : null);+ else {+ const line = typeof params?.line === 'number' && Number.isInteger(params.line) && params.line > 0+ ? params.line+ : null;+ const column = typeof params?.column === 'number' && Number.isInteger(params.column) && params.column >= 0+ ? params.column+ : 0;+ const endColumn = typeof params?.endColumn === 'number' && Number.isInteger(params.endColumn) && params.endColumn >= column+ ? params.endColumn+ : column;+ openFile(+ p,+ name,+ typeof params?.mtime === 'number' ? params.mtime : null,+ line ? { line, column, endColumn } : undefined,+ );+ }return;}const dir = typeof params?.newFileDir === 'string' ? params.newFileDir : null;diff --git a/ui/src/lib/localFileLinks.test.ts b/ui/src/lib/localFileLinks.test.tsnew file mode 100644index 000000000..3b695be10--- /dev/null+++ b/ui/src/lib/localFileLinks.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from 'vitest';++import { resolveLocalFileLink } from './localFileLinks';++describe('resolveLocalFileLink', () => {+ it('keeps absolute POSIX paths and decodes Markdown URL escapes', () => {+ expect(resolveLocalFileLink('/root/My%20Report.md')).toEqual({ path: '/root/My Report.md' });+ });++ it('resolves ./ paths against the Agent Session workdir', () => {+ expect(resolveLocalFileLink('./src/main.ts', '/workspace/project')).toEqual({+ path: '/workspace/project/src/main.ts',+ });+ expect(resolveLocalFileLink('./src/main.ts', '/')).toEqual({ path: '/src/main.ts' });+ expect(resolveLocalFileLink('./src/main.ts', 'C:\\workspace\\project\\')).toEqual({+ path: 'C:\\workspace\\project\\src\\main.ts',+ });+ expect(resolveLocalFileLink('./a%5Cb', '/workspace')).toEqual({+ path: '/workspace/a\\b',+ });+ expect(resolveLocalFileLink('./a%5Cb', 'C:\\workspace')).toEqual({+ path: 'C:\\workspace\\a\\b',+ });+ });++ it('extracts common source line and column suffixes', () => {+ expect(resolveLocalFileLink('/root/app.py:42')).toEqual({+ path: '/root/app.py',+ line: 42,+ column: 0,+ endColumn: 0,+ });+ expect(resolveLocalFileLink('./app.py:42:7', '/workspace')).toEqual({+ path: '/workspace/app.py',+ line: 42,+ column: 6,+ endColumn: 6,+ });+ });++ it('recognizes absolute Windows destinations without treating the drive as a URL scheme', () => {+ expect(resolveLocalFileLink('C:/workspace/app.py:42')).toEqual({+ path: 'C:/workspace/app.py',+ line: 42,+ column: 0,+ endColumn: 0,+ });+ expect(resolveLocalFileLink('C:%5Cworkspace%5Capp.py:42:7')).toEqual({+ path: 'C:\\workspace\\app.py',+ line: 42,+ column: 6,+ endColumn: 6,+ });+ });++ it('recognizes raw and encoded absolute UNC destinations', () => {+ expect(resolveLocalFileLink('\\\\server\\share\\app.py:42')).toEqual({+ path: '\\\\server\\share\\app.py',+ line: 42,+ column: 0,+ endColumn: 0,+ });+ expect(resolveLocalFileLink('%5C%5Cserver%5Cshare%5Capp.py:42:7')).toEqual({+ path: '\\\\server\\share\\app.py',+ line: 42,+ column: 6,+ endColumn: 6,+ });+ });++ it('decodes filenames only after identifying literal source suffixes', () => {+ expect(resolveLocalFileLink('/tmp/report%3A2026')).toEqual({+ path: '/tmp/report:2026',+ });+ expect(resolveLocalFileLink('/tmp/report%3A2026:42')).toEqual({+ path: '/tmp/report:2026',+ line: 42,+ column: 0,+ endColumn: 0,+ });+ });++ it('leaves web URLs and unresolved relative paths alone', () => {+ for (const href of ['https://example.com/file', 'c:relative-file', '//cdn.example.com/file', '../file.ts', 'file.ts', '/', './']) {+ expect(resolveLocalFileLink(href, '/workspace')).toBeNull();+ }+ expect(resolveLocalFileLink('./file.ts', null)).toBeNull();+ expect(resolveLocalFileLink('./file.ts', 'relative/workdir')).toBeNull();+ });++ it('leaves current application routes as same-origin browser links', () => {+ for (const href of [+ '/chat/session-123',+ '/apps/show/session-123',+ '/apps/files',+ '/apps/files/',+ '/admin/settings/backends/codex',+ '/settings/models?source=custom',+ '/doctor/logs#latest',+ ]) {+ expect(resolveLocalFileLink(href, '/workspace')).toBeNull();+ }+ });++ it('does not reserve application route namespaces as filesystem roots', () => {+ for (const path of [+ '/projects/report.md',+ '/apps/source.ts',+ '/chat/session-123/notes.md',+ '/admin/settings/custom.json',+ ]) {+ expect(resolveLocalFileLink(path, '/workspace')).toEqual({ path });+ }+ });+});diff --git a/ui/src/lib/localFileLinks.ts b/ui/src/lib/localFileLinks.tsnew file mode 100644index 000000000..a97566e98--- /dev/null+++ b/ui/src/lib/localFileLinks.ts@@ -0,0 +1,149 @@+export type LocalFileLinkTarget = {+ path: string;+ line?: number;+ column?: number;+ endColumn?: number;+};++// Exact routes declared in App.tsx remain same-origin browser links even+// though their leading slash also looks like a POSIX path. Do not reserve an+// entire top-level namespace: `/projects/report.md` may be a real local file.+const APPLICATION_ROUTES = new Set([+ '/',+ '/setup',+ '/inbox',+ '/search',+ '/agents',+ '/skills',+ '/harness',+ '/vaults',+ '/projects',+ '/more',+ '/apps',+ '/apps/files',+ '/apps/terminal',+ '/apps/editor',+ '/apps/library',+ '/admin',+ '/admin/dashboard',+ '/admin/remote-access',+ '/admin/groups',+ '/admin/users',+ '/admin/show-pages',+ '/admin/logs',+ '/admin/settings/service',+ '/admin/settings/platforms',+ '/admin/settings/backends',+ '/admin/settings/backends/opencode',+ '/admin/settings/backends/claude',+ '/admin/settings/backends/codex',+ '/admin/settings/models',+ '/admin/settings/dependencies',+ '/admin/settings/messaging',+ '/admin/settings/diagnostics',+ '/admin/settings/logs',+ '/dashboard',+ '/groups',+ '/channels',+ '/users',+ '/logs',+ '/settings',+ '/settings/service',+ '/settings/platforms',+ '/settings/backends',+ '/settings/backends/opencode',+ '/settings/backends/claude',+ '/settings/backends/codex',+ '/settings/models',+ '/settings/dependencies',+ '/settings/messaging',+ '/settings/diagnostics',+ '/settings/logs',+ '/remote-access',+ '/doctor',+ '/doctor/logs',+]);++const APPLICATION_ROUTE_PATTERNS = [+ /^\/apps\/show\/[^/]+$/,+ /^\/chat\/[^/]+$/,+];++function isApplicationRouteHref(href: string): boolean {+ const rawPathname = href.split(/[?#]/, 1)[0];+ const pathname = rawPathname.replace(/\/+$/, '') || '/';+ return APPLICATION_ROUTES.has(pathname)+ || APPLICATION_ROUTE_PATTERNS.some((pattern) => pattern.test(pathname));+}++/** Windows drive and UNC paths are valid local destinations, not URL schemes.+ * Accept encoded separators because Markdown destinations commonly escape+ * backslashes before the URL sanitizer sees them. */+export function isAbsoluteWindowsFileHref(href: string): boolean {+ return /^[A-Za-z]:(?:[\\/]|%(?:2f|5c))/i.test(href) || /^(?:\\|%5c){2}/i.test(href);+}++function decodePath(path: string): string {+ try {+ return decodeURIComponent(path);+ } catch {+ return path;+ }+}++function splitSourcePosition(path: string): LocalFileLinkTarget {+ const match = path.match(/:(\d+)(?::(\d+))?$/);+ if (!match) return { path };++ const line = Number.parseInt(match[1], 10);+ const sourceColumn = match[2] ? Number.parseInt(match[2], 10) : 1;+ if (line < 1 || sourceColumn < 1) return { path };++ // Source links use human-facing 1-based columns; Editor reveal targets use+ // 0-based offsets and convert to Monaco coordinates at the final boundary.+ const column = sourceColumn - 1;++ return {+ path: path.slice(0, match.index),+ line,+ column,+ endColumn: column,+ };+}++function isAbsoluteWorkdir(path: string): boolean {+ return path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith('\\\\');+}++function joinWorkdir(workdir: string, relativePath: string): string {+ const windowsPath = /^[A-Za-z]:[\\/]/.test(workdir) || workdir.startsWith('\\\\');+ const separator = windowsPath ? '\\' : '/';+ const base = windowsPath ? workdir.replace(/[\\/]+$/, '') : workdir.replace(/\/+$/, '');+ const tail = windowsPath ? relativePath.replace(/[\\/]+/g, separator) : relativePath;+ return base ? `${base}${separator}${tail}` : `${separator}${tail}`;+}++/** Resolve a Markdown destination that represents a local file.+ *+ * Absolute POSIX paths open as-is. `./` destinations are relative to the+ * Agent Session's immutable workdir snapshot, not the browser URL. A leading+ * `//` remains a protocol-relative web URL. Common Codex `:line[:column]`+ * suffixes are kept as an editor reveal target rather than part of the path.+ */+export function resolveLocalFileLink(href: string, workdir?: string | null): LocalFileLinkTarget | null {+ const absolutePosix =+ href.startsWith('/') && !href.startsWith('//') && href !== '/' && !isApplicationRouteHref(href);+ const absoluteWindows = isAbsoluteWindowsFileHref(href);+ const relative = href.startsWith('./') && href !== './';+ if (!absolutePosix && !absoluteWindows && !relative) return null;++ // Parse only literal source suffixes. An escaped colon belongs to the+ // filename, so decoding the whole href before this step would be ambiguous.+ const target = splitSourcePosition(href);+ const decodedPath = decodePath(target.path);+ if (!decodedPath) return null;+ if (absolutePosix || absoluteWindows) return { ...target, path: decodedPath };+ if (!workdir || !isAbsoluteWorkdir(workdir)) return null;++ return { ...target, path: joinWorkdir(workdir, decodedPath.slice(2)) };+}