Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(terminal): preview linked local files in nodeterm

Igor Schlumbergerb6766317fd59
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 05bcdc1e2..b61f1fedd 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -612,7 +612,7 @@ import {
nodeSshFor,
createVideoNode,
createWebNode,
- isMediaFile,
+ fileViewerKind,
duplicateNode,
flowToNodeStates,
addSelectionToGroup,
@@ -4220,7 +4220,9 @@ export function Canvas() {
[confirmAndMount]
)
- /** Open a file as a code editor node on the canvas. `sshFs` must be passed explicitly by the
+ /** Open a file in the appropriate canvas viewer. Local HTML gets a locked-down WebNode;
+ * Markdown/text, images and PDFs use EditorNode (which already provides their previews), and
+ * audio/video use VideoNode. `sshFs` must be passed explicitly by the
* caller: only genuinely-remote, Explorer-opened files in an SSH project pass `true`; native
* dialog / quick-open paths are LOCAL and stay local (so their ⌘S never writes to the host).
* A file that is already open focuses its existing node instead of stacking a duplicate;
@@ -4228,18 +4230,23 @@ export function Canvas() {
const openFile = useCallback(
(filePath: string, center?: { x: number; y: number }, sshFs?: boolean) => {
const existing = nodesRef.current.find(
- (n) => (n.type === 'editor' || n.type === 'video') && n.data?.filePath === filePath
+ (n) =>
+ (n.type === 'editor' || n.type === 'video' || n.type === 'web') &&
+ n.data?.filePath === filePath
)
if (existing) {
focusNodeRef.current(existing.id)
return
}
+ const viewerKind = fileViewerKind(filePath, sshFs)
setNodes((ns) => [
...ns.map((n) => (n.selected ? { ...n, selected: false } : n)),
{
- ...(isMediaFile(filePath)
- ? createVideoNode(ns.length, filePath, center ?? viewCenter(), sshFs)
- : createEditorNode(ns.length, filePath, center ?? viewCenter(), sshFs)),
+ ...(viewerKind === 'web'
+ ? createWebNode(ns.length, { filePath }, center ?? viewCenter())
+ : viewerKind === 'video'
+ ? createVideoNode(ns.length, filePath, center ?? viewCenter(), sshFs)
+ : createEditorNode(ns.length, filePath, center ?? viewCenter(), sshFs)),
selected: true
}
])
@@ -4410,15 +4417,27 @@ export function Canvas() {
}, [showExplorer])
// Cmd+click file links inside terminal output (TerminalNode dispatches these — it has no
- // direct line to the canvas). Files open as editor nodes; directories reveal in Explorer.
+ // direct line to the canvas). A link activated from a Kanban card must also uncover the canvas:
+ // creating a selected viewer behind the full-page board would make a successful click look dead.
useEffect(() => {
+ const uncoverCanvas = (): void => {
+ const projectId = useProjects.getState().activeProjectId
+ if (isGlobalKanbanOpen()) useViewMode.getState().toggleGlobalKanban()
+ if (isKanbanOpen(projectId)) useViewMode.getState().toggle(projectId)
+ }
const onOpen = (e: Event): void => {
const d = (e as CustomEvent<{ path: string; ssh?: boolean }>).detail
- if (d?.path) openFile(d.path, undefined, d.ssh)
+ if (d?.path) {
+ uncoverCanvas()
+ openFile(d.path, undefined, d.ssh)
+ }
}
const onReveal = (e: Event): void => {
const d = (e as CustomEvent<{ path: string }>).detail
- if (d?.path) revealProjectFile(d.path)
+ if (d?.path) {
+ uncoverCanvas()
+ revealProjectFile(d.path)
+ }
}
// A file-manager node asking for a terminal in the folder it is showing. Same
// no-direct-line-to-the-canvas pattern as the two above.
diff --git a/src/renderer/components/kanban/CardModal.test.tsx b/src/renderer/components/kanban/CardModal.test.tsx
index 92d0d64d8..deae68e63 100644
--- a/src/renderer/components/kanban/CardModal.test.tsx
+++ b/src/renderer/components/kanban/CardModal.test.tsx
@@ -31,9 +31,23 @@ vi.mock('../ContextMeter', () => ({
// Mock ModalTerminal and BrowserSurface to keep tests lightweight and focused on CardModal
vi.mock('./ModalTerminal', () => ({
- ModalTerminal: ({ nodeId }: { nodeId: string }) => (
+ ModalTerminal: ({ nodeId, onOpenFile }: { nodeId: string; onOpenFile?: (file: { path: string; ssh: boolean }) => void }) => (
<div className="kanban-modal__term" data-node-id={nodeId} tabIndex={0}>
Terminal Mock
+ <button
+ className="modal-terminal-file-link"
+ onClick={() => onOpenFile?.({ path: '/project/docs/plan.md', ssh: false })}
+ >
+ Open file
+ </button>
+ </div>
+ )
+}))
+
+vi.mock('./LocalFilePreviewModal', () => ({
+ LocalFilePreviewModal: ({ file, onClose }: { file: { path: string }; onClose: () => void }) => (
+ <div className="local-file-preview-mock" data-path={file.path}>
+ <button className="local-file-preview-close" onClick={onClose}>Close preview</button>
</div>
)
}))
@@ -67,6 +81,52 @@ describe('CardModal', () => {
document.body.innerHTML = ''
})
+ it('opens a terminal file link in an overlay without leaving the Kanban card', () => {
+ const session: KanbanSession = {
+ id: 'node-term-preview',
+ title: 'Preview docs',
+ color: '#0a84ff',
+ kind: 'terminal',
+ spawn: { cwd: '/project' }
+ }
+ const onClose = vi.fn()
+ const onOpenCanvas = vi.fn()
+ const root = createRoot(host)
+
+ act(() =>
+ root.render(
+ <CardModal
+ session={session}
+ columnTitle="To Do"
+ board={board}
+ onChangeBoard={vi.fn()}
+ onClose={onClose}
+ onOpenCanvas={onOpenCanvas}
+ onRename={vi.fn()}
+ onEditSticky={vi.fn()}
+ onSetIcon={vi.fn()}
+ onBrowserNav={vi.fn()}
+ />
+ )
+ )
+
+ act(() => {
+ document.body.querySelector<HTMLButtonElement>('.modal-terminal-file-link')!.click()
+ })
+ const preview = document.body.querySelector<HTMLElement>('.local-file-preview-mock')
+ expect(preview?.dataset.path).toBe('/project/docs/plan.md')
+ expect(onClose).not.toHaveBeenCalled()
+ expect(onOpenCanvas).not.toHaveBeenCalled()
+
+ act(() => {
+ document.body.querySelector<HTMLButtonElement>('.local-file-preview-close')!.click()
+ })
+ expect(document.body.querySelector('.local-file-preview-mock')).toBeNull()
+ expect(document.body.querySelector('.kanban-modal')).toBeTruthy()
+
+ act(() => root.unmount())
+ })
+
it('writes through raw textarea value on sticky note edit (including whitespace and newlines)', () => {
const session: KanbanSession = {
id: 'node-sticky-1',
diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsx
index b6cbef528..da891dbdd 100644
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@ -43,6 +43,10 @@ import { BrowserSurface } from '../../nodes/BrowserSurface'
import { BrowserDrivingIndicator } from '../../nodes/BrowserDrivingChip'
import { NoteMarkdown } from '../NoteMarkdown'
import { relativeTime } from '../../lib/relativeTime'
+import {
+ LocalFilePreviewModal,
+ type LocalFileTarget
+} from './LocalFilePreviewModal'
interface CardModalProps {
session: KanbanSession
@@ -75,6 +79,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
const [editingTitle, setEditingTitle] = useState(false)
const [title, setTitle] = useState(session.title)
const [searchOpen, setSearchOpen] = useState(false)
+ const [previewFile, setPreviewFile] = useState<LocalFileTarget | null>(null)
// Sticky body: rendered markdown until clicked, the plain textarea while editing (mirrors
// StickyNode's toggle, so the canvas and the card can't disagree about how a note reads).
const [editingNote, setEditingNote] = useState(false)
@@ -450,6 +455,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
spawn={session.spawn}
searchOpen={searchOpen}
onCloseSearch={() => setSearchOpen(false)}
+ onOpenFile={setPreviewFile}
/>
) : isBrowser ? (
// A live browser webview seeded with the node's URL; navigation persists back to
@@ -471,6 +477,9 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
{panelOpen && <BoardLogPanel card={session} />}
</div>
</div>
+ {previewFile && (
+ <LocalFilePreviewModal file={previewFile} onClose={() => setPreviewFile(null)} />
+ )}
</div>,
document.body
)
diff --git a/src/renderer/components/kanban/LocalFilePreviewModal.tsx b/src/renderer/components/kanban/LocalFilePreviewModal.tsx
new file mode 100644
index 000000000..ae1999518
--- /dev/null
+++ b/src/renderer/components/kanban/LocalFilePreviewModal.tsx
@@ -0,0 +1,185 @@
+import { useEffect, useMemo, useState } from 'react'
+import { createPortal } from 'react-dom'
+import { tooLargeSize, formatBytes } from '@shared/fsLimits'
+import { IconClose, IconExternal } from '../icons'
+import { useDialogStack } from '../dialog-stack'
+import { pdfBlobUrl } from '../../lib/pdfBlob'
+import {
+ localFilePreviewKind,
+ localImageMime,
+ type LocalFilePreviewKind
+} from '../../lib/localFilePreview'
+import { useSession } from '../../session/session'
+import { useProjects } from '../../state/projects'
+import { sshFs } from '../../terminal/ssh-fs'
+
+export interface LocalFileTarget {
+ path: string
+ ssh: boolean
+}
+
+interface LocalFilePreviewModalProps {
+ file: LocalFileTarget
+ onClose: () => void
+}
+
+/** Read-only local-document preview stacked over a Kanban card. It deliberately does not reuse
+ * EditorNode/WebNode: those components are React Flow nodes and mounting them here would create a
+ * hidden dependency on the canvas. The bytes still travel through the exact same routed fs APIs. */
+export function LocalFilePreviewModal({ file, onClose }: LocalFilePreviewModalProps) {
+ const isTopDialog = useDialogStack()
+ const { api } = useSession()
+ const activeProjectId = useProjects((s) => s.activeProjectId)
+ const fs = useMemo(
+ () => (file.ssh && activeProjectId ? sshFs(activeProjectId) : api.fs),
+ [activeProjectId, api, file.ssh]
+ )
+ const kind = useMemo<LocalFilePreviewKind>(() => localFilePreviewKind(file.path), [file.path])
+ const fileName = file.path.replace(/\\/g, '/').split('/').pop() || file.path
+ const [content, setContent] = useState('')
+ const [binarySrc, setBinarySrc] = useState('')
+ const [error, setError] = useState('')
+ const [loading, setLoading] = useState(true)
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent): void => {
+ if (event.key !== 'Escape' || !isTopDialog()) return
+ event.preventDefault()
+ event.stopPropagation()
+ onClose()
+ }
+ window.addEventListener('keydown', onKey, true)
+ return () => window.removeEventListener('keydown', onKey, true)
+ }, [isTopDialog, onClose])
+
+ useEffect(() => {
+ let live = true
+ let blobUrl = ''
+ setLoading(true)
+ setError('')
+ setContent('')
+ setBinarySrc('')
+
+ const fail = (message: string): void => {
+ if (!live) return
+ setError(message)
+ setLoading(false)
+ }
+
+ if (kind === 'image' || kind === 'pdf') {
+ const readBinary = fs.readBinary
+ if (typeof readBinary !== 'function') {
+ fail('Preview needs an app restart.')
+ return
+ }
+ void readBinary(file.path)
+ .then((b64) => {
+ if (!live) return
+ const tooBig = b64 ? tooLargeSize(b64) : null
+ if (tooBig != null) {
+ fail(`File too large to preview (${formatBytes(tooBig)}).`)
+ return
+ }
+ if (!b64) {
+ fail('Couldn’t read this file.')
+ return
+ }
+ if (kind === 'image') {
+ const mime = localImageMime(file.path)
+ if (!mime) {
+ fail('Unsupported image format.')
+ return
+ }
+ setBinarySrc(`data:${mime};base64,${b64}`)
+ } else {
+ const made = pdfBlobUrl(b64)
+ if (!made) {
+ fail('Couldn’t read this PDF.')
+ return
+ }
+ blobUrl = made
+ setBinarySrc(made)
+ }
+ setLoading(false)
+ })
+ .catch(() => fail('Couldn’t read this file.'))
+ } else {
+ void fs
+ .read(file.path)
+ .then(async (text) => {
+ if (!live) return
+ const tooBig = tooLargeSize(text)
+ if (tooBig != null) {
+ fail(`File too large to preview (${formatBytes(tooBig)}).`)
+ return
+ }
+ if (kind === 'html') {
+ // Copy the page into the app-managed agent-web jail. Unlike loading an arbitrary local
+ // HTML file directly, this applies the restrictive CSP: inline rendering works, network
+ // requests and sibling-file reads do not.
+ const localPath = await window.nodeTerminal.media.writeHtml(text)
+ const src = await window.nodeTerminal.media.allow(localPath)
+ if (!live) return
+ setBinarySrc(src)
+ } else if (kind === 'markdown') {
+ // The markdown renderer is sizeable and Kanban itself does not otherwise need it on
+ // startup. Keep it lazy, like NoteMarkdown, so this optional preview does not inflate
+ // the main renderer bundle.
+ const markdown = await import('../../lib/markdown')
+ if (!live) return
+ setContent(markdown.renderMarkdown(text))
+ } else {
+ setContent(text)
+ }
+ setLoading(false)
+ })
+ .catch(() => fail('Couldn’t read this file.'))
+ }
+
+ return () => {
+ live = false
+ if (blobUrl) URL.revokeObjectURL(blobUrl)
+ }
+ }, [file.path, fs, kind])
+
+ const openOnCanvas = (): void => {
+ window.dispatchEvent(
+ new CustomEvent('nodeterm:open-file', { detail: { path: file.path, ssh: file.ssh } })
+ )
+ }
+
+ return createPortal(
+ <div className="local-file-preview-scrim" onMouseDown={onClose}>
+ <div className="local-file-preview" onMouseDown={(event) => event.stopPropagation()}>
+ <div className="local-file-preview__header">
+ <span className="local-file-preview__title" title={file.path}>{fileName}</span>
+ <span className="local-file-preview__path" title={file.path}>{file.path}</span>
+ <button className="kanban-modal__action" title="Open on canvas" onClick={openOnCanvas}>
+ <IconExternal />
+ </button>
+ <button className="kanban-modal__action" title="Close preview" onClick={onClose}>
+ <IconClose />
+ </button>
+ </div>
+ <div className={`local-file-preview__body local-file-preview__body--${kind}`}>
+ {loading ? (
+ <span className="local-file-preview__message">Loading…</span>
+ ) : error ? (
+ <span className="local-file-preview__message local-file-preview__message--error">{error}</span>
+ ) : kind === 'html' ? (
+ <webview src={binarySrc} />
+ ) : kind === 'image' ? (
+ <img src={binarySrc} alt={fileName} />
+ ) : kind === 'pdf' ? (
+ <iframe src={binarySrc} title={fileName} />
+ ) : kind === 'markdown' ? (
+ <div className="term-md__content" dangerouslySetInnerHTML={{ __html: content }} />
+ ) : (
+ <pre>{content}</pre>
+ )}
+ </div>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 16f619729..85b31dfd7 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -25,10 +25,17 @@ import { LocalTransport } from '../../terminal/local-transport'
import { clipboardImages, droppedPaths, pasteHasText, pastedFiles } from '../../terminal/file-drop'
import { guardMiddleClickPaste } from '../../terminal/middle-click'
import {
+ createFileLinkProvider,
createOsc8LinkHandler,
createUrlLinkProvider,
- installLinkClickFallback
+ installLinkClickFallback,
+ makeDirListingLookup
} from '../../terminal/file-links'
+import { isBrowserRuntime } from '../../bridge/runtime'
+import { isWindowsPlatform } from '@shared/platform-utils'
+import { fileLinkDialect } from '../../terminal/file-link-dialect'
+import { hostPlatformFor } from '../../terminal/host-platform'
+import { sshFs } from '../../terminal/ssh-fs'
import { parseOsc52 } from '../../terminal/osc52'
import { activateUnicode11 } from '../../terminal/unicode-width'
import { useCopyFeedback } from '../../terminal/useCopyFeedback'
@@ -52,6 +59,7 @@ import {
sshConnectionScope
} from '../../nodes/TerminalNode'
import { buildSshArgs, type SshConnection } from '@shared/ssh'
+import type { LocalFileTarget } from './LocalFilePreviewModal'
/** The subset of a node's `data` a SECOND client needs to attach to its session the same way the
* canvas TerminalNode does. Canvas fills it from the node's data; sticky/chat cards pass `{}`. */
@@ -84,10 +92,32 @@ interface ModalTerminalProps {
/** The modal header's 🔍 toggle — the FindBar renders inside this pane. */
searchOpen: boolean
onCloseSearch: () => void
+ /** Kanban keeps document links in its own overlay instead of uncovering the canvas. */
+ onOpenFile?: (file: LocalFileTarget) => void
}
-export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: ModalTerminalProps) {
- const { api } = useSession()
+export function ModalTerminal({
+ nodeId,
+ spawn,
+ searchOpen,
+ onCloseSearch,
+ onOpenFile
+}: ModalTerminalProps) {
+ const session = useSession()
+ const { api } = session
+ // File-path syntax belongs to the core that owns this session, which may not be the machine
+ // showing the modal (relay / Server Edition). Resolve it once without respawning the terminal.
+ const corePlatformRef = useRef<string | null>(null)
+ useEffect(() => {
+ let live = true
+ corePlatformRef.current = null
+ void hostPlatformFor(api).then((platform) => {
+ if (live) corePlatformRef.current = platform
+ })
+ return () => {
+ live = false
+ }
+ }, [api])
const hostRef = useRef<HTMLDivElement>(null)
const middleClickPaste = useSettings((st) => st.settings.terminalMiddleClickPaste)
// Chromium pastes the X PRIMARY selection into xterm's hidden textarea on middle click — a path
@@ -212,24 +242,73 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
let dead = false
const cleanups: Array<() => void> = []
- // MIRROR TerminalNode's link wiring, minus file links. The provider handles Cmd/Ctrl+click on
+ // MIRROR TerminalNode's link wiring. The URL provider handles Cmd/Ctrl+click on
// URL text when mouse-reporting is off (plain-shell sessions); the capture-phase fallback is
// what works under tmux/agent mouse-reporting — the norm, and the only path on which the OSC 8
// linkHandler above can ever fire in a tmux-backed session (xterm's own link activation is
- // swallowed by the mouse report, see installLinkClickFallback). File links stay a canvas-node
- // affordance: the modal has no project-fs/dialect routing, and resolving a path against the
- // wrong machine is worse than not linking it — hence fileEnabled: false, not stub deps that
- // pretend to resolve.
+ // swallowed by the mouse report, see installLinkClickFallback). File paths — including
+ // relative paths and explicit file:/// URLs — resolve against the SAME cwd and routed
+ // filesystem as the canvas terminal, then ask Canvas to open its built-in viewer.
const openUrl = (uri: string): void => window.nodeTerminal.shell.openExternal(uri)
+ const projectFs = (): { fs: typeof api.fs; ssh: boolean } => {
+ const st = useProjects.getState()
+ const project = st.projects.find((p) => p.id === st.activeProjectId)
+ return project?.ssh ? { fs: sshFs(project.id), ssh: true } : { fs: api.fs, ssh: false }
+ }
+ const fileConvention = (): { windows?: boolean } | null => {
+ const st = useProjects.getState()
+ const project = st.projects.find((p) => p.id === st.activeProjectId)
+ const dialect = fileLinkDialect({
+ source: session.source,
+ browserRuntime: isBrowserRuntime(),
+ viewerWindows: isWindowsPlatform(),
+ corePlatform: corePlatformRef.current,
+ sshProject: !!project?.ssh,
+ standaloneSsh: !project?.ssh && !!spawn.ssh
+ })
+ return dialect ? { windows: dialect === 'windows' } : null
+ }
+ const fileLookup = makeDirListingLookup(
+ async (dir) => projectFs().fs.list(dir),
+ 3000,
+ fileConvention
+ )
+ const openFile = (abs: string, isDir: boolean): void => {
+ if (isDir) {
+ window.dispatchEvent(new CustomEvent('nodeterm:reveal-file', { detail: { path: abs } }))
+ } else if (onOpenFile) {
+ onOpenFile({ path: abs, ssh: projectFs().ssh })
+ } else {
+ window.dispatchEvent(
+ new CustomEvent('nodeterm:open-file', {
+ detail: { path: abs, ssh: projectFs().ssh }
+ })
+ )
+ }
+ }
+ const fileEnabled = (): boolean => fileConvention() !== null
term.registerLinkProvider(createUrlLinkProvider(term, openUrl))
+ term.registerLinkProvider(
+ createFileLinkProvider(term, {
+ getCwd: () => spawn.cwd,
+ convention: fileConvention,
+ lookup: fileLookup,
+ activate: openFile,
+ activateFileUrl: openFile,
+ fileUrlEnabled: fileEnabled
+ })
+ )
if (term.element) {
cleanups.push(
installLinkClickFallback(term, term.element, {
- getCwd: () => undefined,
- lookup: () => Promise.resolve({ exists: false, dir: false }),
- activateFile: () => {},
+ getCwd: () => spawn.cwd,
+ convention: fileConvention,
+ lookup: fileLookup,
+ activateFile: openFile,
+ activateFileUrl: openFile,
+ fileUrlEnabled: fileEnabled,
openUrl,
- fileEnabled: () => false
+ fileEnabled
}).dispose
)
}
diff --git a/src/renderer/lib/localFilePreview.test.ts b/src/renderer/lib/localFilePreview.test.ts
new file mode 100644
index 000000000..cd3675fab
--- /dev/null
+++ b/src/renderer/lib/localFilePreview.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest'
+import { localFileExtension, localFilePreviewKind, localImageMime } from './localFilePreview'
+
+describe('local file preview routing', () => {
+ it('recognizes the document types shown over Kanban', () => {
+ expect(localFilePreviewKind('/tmp/report.HTML')).toBe('html')
+ expect(localFilePreviewKind('/tmp/plan.markdown')).toBe('markdown')
+ expect(localFilePreviewKind('/tmp/report.pdf')).toBe('pdf')
+ expect(localFilePreviewKind('/tmp/screenshot.webp')).toBe('image')
+ expect(localFilePreviewKind('/tmp/notes.txt')).toBe('text')
+ })
+
+ it('handles Windows paths and returns the image MIME', () => {
+ expect(localFileExtension(String.raw`C:\work\shots\screen.PNG`)).toBe('png')
+ expect(localImageMime(String.raw`C:\work\shots\screen.PNG`)).toBe('image/png')
+ expect(localImageMime('/tmp/notes.md')).toBeNull()
+ })
+})
diff --git a/src/renderer/lib/localFilePreview.ts b/src/renderer/lib/localFilePreview.ts
new file mode 100644
index 000000000..8ff0af0da
--- /dev/null
+++ b/src/renderer/lib/localFilePreview.ts
@@ -0,0 +1,32 @@
+export type LocalFilePreviewKind = 'html' | 'markdown' | 'pdf' | 'image' | 'text'
+
+const IMAGE_MIME: Record<string, string> = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ gif: 'image/gif',
+ webp: 'image/webp',
+ bmp: 'image/bmp',
+ ico: 'image/x-icon',
+ svg: 'image/svg+xml',
+ avif: 'image/avif'
+}
+
+export function localFileExtension(path: string): string {
+ const name = path.replace(/\\/g, '/').split('/').pop() ?? ''
+ const dot = name.lastIndexOf('.')
+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''
+}
+
+export function localFilePreviewKind(path: string): LocalFilePreviewKind {
+ const ext = localFileExtension(path)
+ if (ext === 'html' || ext === 'htm') return 'html'
+ if (ext === 'md' || ext === 'markdown' || ext === 'mdown' || ext === 'mkd') return 'markdown'
+ if (ext === 'pdf') return 'pdf'
+ if (ext in IMAGE_MIME) return 'image'
+ return 'text'
+}
+
+export function localImageMime(path: string): string | null {
+ return IMAGE_MIME[localFileExtension(path)] ?? null
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 0387a59bc..ab3550b57 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -2927,11 +2927,18 @@ export function TerminalNode({
new CustomEvent('nodeterm:open-file', { detail: { path: abs, ssh: projectFs().ssh } })
)
}
+ // file:/// URLs use the same routed canvas viewers as ordinary paths. This keeps generated
+ // HTML, Markdown, PDFs and images beside the session, and remains safe for SSH projects:
+ // `openFile` carries the remote-fs flag instead of handing the path to this Mac's OS.
+ const fileUrlEnabled = (): boolean => pathConvention() !== null
+ const openFileUrl = openFile
term.registerLinkProvider(
createFileLinkProvider(term, {
getCwd,
lookup,
activate: openFile,
+ activateFileUrl: openFileUrl,
+ fileUrlEnabled,
convention: pathConvention
})
)
@@ -2944,6 +2951,8 @@ export function TerminalNode({
getCwd,
lookup,
activateFile: openFile,
+ activateFileUrl: openFileUrl,
+ fileUrlEnabled,
openUrl: (uri) => window.nodeTerminal.shell.openExternal(uri),
fileEnabled: () => pathConvention() !== null,
convention: pathConvention
diff --git a/src/renderer/state/workspace.media.test.ts b/src/renderer/state/workspace.media.test.ts
index 135ac82da..f520ce092 100644
--- a/src/renderer/state/workspace.media.test.ts
+++ b/src/renderer/state/workspace.media.test.ts
@@ -2,12 +2,31 @@ import { describe, it, expect } from 'vitest'
import {
createVideoNode,
createWebNode,
+ fileViewerKind,
+ isHtmlFile,
isVideoFile,
nodeStatesToFlow,
flowToNodeStates
} from './workspace'
describe('video/web nodes', () => {
+ it('isHtmlFile matches local page extensions only', () => {
+ expect(isHtmlFile('/a/b/report.html')).toBe(true)
+ expect(isHtmlFile('/a/b/REPORT.HTM')).toBe(true)
+ expect(isHtmlFile('/a/b/readme.md')).toBe(false)
+ expect(isHtmlFile('/a/b/report.pdf')).toBe(false)
+ })
+
+ it('routes generated documents to their built-in canvas viewers', () => {
+ expect(fileViewerKind('/tmp/page.html')).toBe('web')
+ expect(fileViewerKind('/tmp/page.htm')).toBe('web')
+ expect(fileViewerKind('/tmp/interview.mp3')).toBe('video')
+ expect(fileViewerKind('/tmp/notes.md')).toBe('editor')
+ expect(fileViewerKind('/tmp/report.pdf')).toBe('editor')
+ expect(fileViewerKind('/tmp/screenshot.png')).toBe('editor')
+ expect(fileViewerKind('/tmp/page.html', true)).toBe('editor')
+ })
+
it('isVideoFile matches common video extensions, not images', () => {
expect(isVideoFile('/a/b/clip.mp4')).toBe(true)
expect(isVideoFile('/a/b/CLIP.WEBM')).toBe(true)
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index e2d0a99b6..710e868a7 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -956,12 +956,28 @@ export function isMediaFile(path: string): boolean {
return isVideoFile(path) || isAudioFile(path)
}
+const HTML_EXTS = ['html', 'htm']
+
+/** True when a local file can be rendered as a page inside a WebNode. */
+export function isHtmlFile(path: string): boolean {
+ const ext = path.split('.').pop()?.toLowerCase() ?? ''
+ return HTML_EXTS.includes(ext)
+}
+
/** True when a path looks like a playable video file (by extension). */
export function isVideoFile(path: string): boolean {
const ext = path.split('.').pop()?.toLowerCase() ?? ''
return VIDEO_EXTS.includes(ext)
}
+/** Pick the canvas surface used for a linked file. Remote HTML stays source-editable because a
+ * WebNode can only serve a local file; every other preview works through EditorNode's routed fs. */
+export function fileViewerKind(path: string, sshFs = false): 'editor' | 'video' | 'web' {
+ if (!sshFs && isHtmlFile(path)) return 'web'
+ if (isMediaFile(path)) return 'video'
+ return 'editor'
+}
+
/** Creates a video player node for a video file (streamed via nt-media://). When `sshFs` is true,
* `data.sshFs` is stamped so VideoNode fetches the file from the SSH project's host into the
* local media cache (media.allowSsh) instead of allowlisting a local path — mirroring
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index e30fe13a7..b9d2917c1 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -10912,6 +10912,118 @@ button.group-node__setup:disabled {
color: #fff;
}
+/* Read-only document preview stacked over a Kanban card. The card and board remain mounted below,
+ so closing this layer returns the user to exactly the terminal and scroll position they left. */
+.local-file-preview-scrim {
+ position: fixed;
+ inset: 0;
+ z-index: 62; /* above card modal (55), below confirmation/palette dialogs (70+) */
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 12px;
+ background: rgba(0, 0, 0, 0.68);
+ animation: kanban-fade 0.14s ease-out;
+}
+.local-file-preview {
+ width: min(1180px, calc(100vw - 24px));
+ height: min(820px, calc(100vh - 24px));
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ background: var(--surface-sunken);
+ border: 1px solid rgba(var(--tint-rgb), 0.15);
+ border-radius: 12px;
+ box-shadow: 0 28px 90px rgba(0, 0, 0, calc(0.72 * var(--shadow-k)));
+ animation: kanban-pop 0.16s ease-out;
+}
+.local-file-preview__header {
+ flex: 0 0 auto;
+ min-height: 48px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px 10px 16px;
+ border-bottom: 1px solid rgba(var(--tint-rgb), 0.09);
+}
+.local-file-preview__title {
+ min-width: 0;
+ max-width: 38%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: rgba(var(--tint-rgb), 0.92);
+ font-size: 14px;
+ font-weight: 700;
+}
+.local-file-preview__path {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: rgba(var(--tint-rgb), 0.4);
+ font-family: var(--mono-font, monospace);
+ font-size: 10px;
+}
+.local-file-preview__body {
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ position: relative;
+ overflow: auto;
+ background: var(--term-bg, var(--surface-sunken));
+}
+.local-file-preview__body webview,
+.local-file-preview__body iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ display: flex;
+}
+.local-file-preview__body--image {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 20px;
+}
+.local-file-preview__body--image img {
+ display: block;
+ max-width: 100%;
+ max-height: 100%;
+ object-fit: contain;
+}
+.local-file-preview__body--markdown .term-md__content {
+ max-width: 920px;
+ margin: 0 auto;
+ padding: 28px 34px 50px;
+ user-select: text;
+ -webkit-user-select: text;
+}
+.local-file-preview__body--text pre {
+ box-sizing: border-box;
+ min-height: 100%;
+ margin: 0;
+ padding: 22px 26px;
+ overflow: auto;
+ white-space: pre-wrap;
+ word-break: break-word;
+ color: rgba(var(--tint-rgb), 0.88);
+ font: 12px/1.55 var(--mono-font, monospace);
+}
+.local-file-preview__message {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: rgba(var(--tint-rgb), 0.45);
+ font-size: 12px;
+}
+.local-file-preview__message--error {
+ color: rgba(255, 120, 120, 0.88);
+}
+
/* ---- Node comments flyout: the header 💬 expands the board-log feed to the node's right ---- */
@keyframes kanban-slide-in {
from {
diff --git a/src/renderer/terminal/file-links.test.ts b/src/renderer/terminal/file-links.test.ts
index a8e1fb794..719c32b0d 100644
--- a/src/renderer/terminal/file-links.test.ts
+++ b/src/renderer/terminal/file-links.test.ts
@@ -1,12 +1,14 @@
import { describe, expect, it } from 'vitest'
import type { Terminal } from '@xterm/xterm'
import {
+ createFileLinkProvider,
createOsc8LinkHandler,
makeDirListingLookup,
matchFileTokens,
matchUrlTokens,
osc8UrlAt,
paragraphContaining,
+ pathFromFileUrl,
resolveFileToken,
type BufferView
} from './file-links'
@@ -36,11 +38,117 @@ describe('matchFileTokens', () => {
expect(matchFileTokens('https://example.com/a/b plain word')).toEqual([])
})
+ it('recognizes local file URLs and decodes their path', () => {
+ const [t] = matchFileTokens('open file:///Users/me/My%20Report/report.html now')
+ expect(t).toEqual({
+ text: 'file:///Users/me/My%20Report/report.html',
+ startIndex: 5,
+ path: '/Users/me/My Report/report.html',
+ fileUrl: true
+ })
+ })
+
+ it('refuses non-local file URL hosts and encoded separators', () => {
+ expect(matchFileTokens('file://server/share/report.html')).toEqual([])
+ expect(matchFileTokens('file:///tmp/a%2Fb.html')).toEqual([])
+ })
+
it('skips ~ paths (no home resolution in v1)', () => {
expect(matchFileTokens('~/notes.md')).toEqual([])
})
})
+describe('pathFromFileUrl', () => {
+ it('accepts localhost and converts a Windows drive URL for a Windows-owned terminal', () => {
+ expect(pathFromFileUrl('file://localhost/tmp/report.html')).toBe('/tmp/report.html')
+ expect(pathFromFileUrl('file:///C:/Users/me/report.html', { windows: true })).toBe(
+ 'C:/Users/me/report.html'
+ )
+ })
+
+ it('refuses browser-only URL suffixes that openPath cannot preserve', () => {
+ expect(pathFromFileUrl('file:///tmp/report.html#section')).toBeNull()
+ expect(pathFromFileUrl('file:///tmp/report.html?preview=1')).toBeNull()
+ })
+})
+
+describe('file URL-only provider', () => {
+ const term = (text: string): Terminal =>
+ ({
+ cols: 160,
+ buffer: {
+ active: {
+ length: 1,
+ getLine: (row: number) =>
+ row === 0
+ ? { isWrapped: false, translateToString: () => text }
+ : undefined
+ }
+ }
+ }) as unknown as Terminal
+
+ const linksFor = (text: string): Promise<import('@xterm/xterm').ILink[] | undefined> =>
+ new Promise((resolve) => {
+ createFileLinkProvider(term(text), {
+ getCwd: () => undefined,
+ lookup: async () => ({ exists: true, dir: false }),
+ activate: () => {},
+ pathEnabled: () => false,
+ activateFileUrl: () => {},
+ fileUrlEnabled: () => true
+ }).provideLinks(1, resolve)
+ })
+
+ it('offers explicit file URLs while keeping ordinary path tokens disabled', async () => {
+ await expect(linksFor('/Users/me/report.html')).resolves.toBeUndefined()
+ const links = await linksFor('file:///Users/me/report.html')
+ expect(links?.map((link) => link.text)).toEqual(['file:///Users/me/report.html'])
+ })
+
+ it('offers one existing file URL across Claude TUI rows with repeated indentation', async () => {
+ const prefix = ' Le même fichier en local : '
+ const head = 'file:///private/tmp/claude-501/project/74215372-82c3-45cd-'
+ const tail = ' adcd-865837a61b4c/scratchpad/maquette-options.html'
+ const cols = prefix.length + head.length
+ const rows = [prefix + head, tail]
+ const opened: Array<{ path: string; dir: boolean }> = []
+ const wrappedTerm = {
+ cols,
+ buffer: {
+ active: {
+ length: rows.length,
+ getLine: (row: number) =>
+ rows[row] === undefined
+ ? undefined
+ : { isWrapped: false, translateToString: (trim: boolean) =>
+ trim ? rows[row].replace(/\s+$/, '') : rows[row].padEnd(cols) }
+ }
+ }
+ } as unknown as Terminal
+ const links = await new Promise<import('@xterm/xterm').ILink[] | undefined>((resolve) => {
+ createFileLinkProvider(wrappedTerm, {
+ getCwd: () => '/project',
+ lookup: async () => ({ exists: true, dir: false }),
+ activate: () => {},
+ activateFileUrl: (path, dir) => opened.push({ path, dir }),
+ fileUrlEnabled: () => true
+ }).provideLinks(2, resolve)
+ })
+
+ expect(links).toHaveLength(1)
+ expect(links![0].text).toBe(head + tail.slice(2))
+ expect(links![0].range.start).toEqual({ x: prefix.length + 1, y: 1 })
+ expect(links![0].range.end).toEqual({ x: tail.length, y: 2 })
+ links![0].activate({ metaKey: true, ctrlKey: false } as MouseEvent, links![0].text)
+ expect(opened).toEqual([
+ {
+ path: '/private/tmp/claude-501/project/74215372-82c3-45cd-adcd-865837a61b4c/scratchpad/maquette-options.html',
+ dir: false
+ }
+ ])
+ })
+})
+
describe('resolveFileToken', () => {
it('passes absolutes through and resolves relatives against cwd', () => {
expect(resolveFileToken('/etc/hosts', '/repo')).toBe('/etc/hosts')
@@ -127,6 +235,26 @@ describe('paragraphContaining', () => {
)
})
+ it('joins a file URL when Claude repaints its content indent on the continuation row', () => {
+ const prefix = ' Le même fichier en local : '
+ const head = 'file:///private/tmp/claude-501/project/74215372-82c3-45cd-'
+ const tail = ' adcd-865837a61b4c/scratchpad/maquette-options.html'
+ const cols = prefix.length + head.length
+ const v = view(cols, [prefix + head, tail])
+
+ // Generic web-link joining stays strict: indented prose must never extend an HTTP URL.
+ expect(paragraphContaining(v, 1)!.startRow).toBe(1)
+
+ const p = paragraphContaining(v, 1, { indentedFileWraps: true })!
+ expect(p.startRow).toBe(0)
+ expect(p.text).toBe(prefix + head + tail.slice(2))
+ const [token] = matchFileTokens(p.text)
+ expect(token.text).toBe(head + tail.slice(2))
+ expect(token.path).toBe(
+ '/private/tmp/claude-501/project/74215372-82c3-45cd-adcd-865837a61b4c/scratchpad/maquette-options.html'
+ )
+ })
+
it('does NOT join when the row is not full to the last column', () => {
const v = view(10, ['https://x ', 'unrelated'])
expect(paragraphContaining(v, 0)!.text).toBe('https://x')
diff --git a/src/renderer/terminal/file-links.ts b/src/renderer/terminal/file-links.ts
index d1ed21121..13c6825d7 100644
--- a/src/renderer/terminal/file-links.ts
+++ b/src/renderer/terminal/file-links.ts
@@ -16,10 +16,11 @@
// full-width rows with NO wrapped flags. This is what a `claude /login` OAuth URL looks
// like in practice; matching per-row opened just the clicked row's fragment (a truncated,
// wrong URL). A row is treated as continuing onto the next when it is full to the LAST
-// column and the next row starts at column 0 with a non-space — a heuristic (the buffer
-// genuinely cannot distinguish a repainted wrap from prose that exactly fills the row),
-// gated tightly and capped at MAX_JOIN_ROWS, and the regex still has to match across the
-// seam for a link to result.
+// column and the next row starts at column 0 with a non-space. Claude's TUI additionally
+// repeats its two-column content indent on a continuation; the file-link path may normalize
+// that indent while retaining a per-character buffer map for accurate hit testing. Both are
+// heuristics (the buffer cannot distinguish a repainted wrap from prose that fills the row),
+// gated tightly and capped at MAX_JOIN_ROWS, and a real existing path is still required.
import type { ILink, ILinkHandler, ILinkProvider, Terminal } from '@xterm/xterm'
export interface FileToken {
@@ -30,6 +31,8 @@ export interface FileToken {
/** The cleaned path portion. */
path: string
line?: number
+ /** True when the terminal printed an explicit file:/// URL rather than a path token. */
+ fileUrl?: boolean
}
// Path-ish token: an optional ./ ../ / prefix, then segments of path-safe chars with at
@@ -65,15 +68,55 @@ const SUFFIX_RE = /^(.*?):(\d+)(?::\d+)?$/
const TRAILING_PUNCT = /[.,;:!?'")\]}>]+$/
/** `C:\…`, `C:/…`, or a UNC `\\host\share` / `//host/share`. */
const WIN_ABSOLUTE_RE = /^(?:[A-Za-z]:[\\/]|\\\\|\/\/)/
+const FILE_URL_RE = /\bfile:\/\/[^\s"'`<>()[\]{}|\\^]+/gi
export interface PathConventionOpts {
/** Match and resolve Windows-shaped paths. Off by default, so POSIX behaviour is unchanged. */
windows?: boolean
}
-export function matchFileTokens(lineText: string, opts: PathConventionOpts = {}): FileToken[] {
+/**
+ * Convert a local file URL to the path owned by the terminal's filesystem.
+ *
+ * Only an empty host or `localhost` is local. Encoded separators are refused instead of being
+ * decoded into a different path shape, and query/fragment suffixes are refused because the
+ * canvas viewers open a filesystem path rather than a browser URL. The returned path is therefore
+ * safe to existence-check through the same project-fs route as ordinary terminal file links.
+ */
+export function pathFromFileUrl(text: string, opts: PathConventionOpts = {}): string | null {
+ try {
+ const u = new URL(text)
+ if (u.protocol !== 'file:') return null
+ if (u.hostname && u.hostname.toLowerCase() !== 'localhost') return null
+ if (u.username || u.password || u.port || u.search || u.hash) return null
+ if (/%(?:00|2f|5c)/i.test(u.pathname)) return null
+ let path = decodeURIComponent(u.pathname)
+ if (!path || path.includes('\0')) return null
+ if (opts.windows) {
+ if (/^\/[A-Za-z]:\//.test(path)) path = path.slice(1)
+ return /^[A-Za-z]:\//.test(path) ? path : null
+ }
+ return path.startsWith('/') ? path : null
+ } catch {
+ return null
+ }
+}
+
+function matchFileUrlTokens(lineText: string, opts: PathConventionOpts): FileToken[] {
const out: FileToken[] = []
- if (opts.windows) return matchWindowsFileTokens(lineText)
+ for (const m of lineText.matchAll(FILE_URL_RE)) {
+ const text = m[0].replace(TRAILING_PUNCT, '')
+ const path = pathFromFileUrl(text, opts)
+ if (!path) continue
+ out.push({ text, startIndex: m.index, path, fileUrl: true })
+ }
+ return out
+}
+
+export function matchFileTokens(lineText: string, opts: PathConventionOpts = {}): FileToken[] {
+ const out = matchFileUrlTokens(lineText, opts)
+ if (opts.windows)
+ return [...out, ...matchWindowsFileTokens(lineText)].sort((a, b) => a.startIndex - b.startIndex)
for (const m of lineText.matchAll(TOKEN_RE)) {
let text = m[0]
// URLs (and protocol-ish tokens) belong to the web-links addon. A token preceded by
@@ -96,7 +139,7 @@ export function matchFileTokens(lineText: string, opts: PathConventionOpts = {})
if (!path || !path.includes('/')) continue
out.push({ text, startIndex: m.index, path, line })
}
- return out
+ return out.sort((a, b) => a.startIndex - b.startIndex)
}
/**
@@ -274,6 +317,12 @@ export interface FileLinkDeps {
convention?: () => PathConventionOpts | null
lookup(abs: string): Promise<{ exists: boolean; dir: boolean }>
activate(abs: string, dir: boolean): void
+ /** False on surfaces that support explicit file URLs but cannot route relative/path tokens. */
+ pathEnabled?(): boolean
+ /** Explicit file:/// links may use a distinct activation path on a hosting surface. */
+ activateFileUrl?(abs: string, dir: boolean): void
+ /** False when this surface cannot route a file URL to the filesystem that printed it. */
+ fileUrlEnabled?(): boolean
}
/** The minimal buffer slice paragraph joining needs — unit tests drive a fake. */
@@ -301,19 +350,46 @@ export function bufferView(term: Terminal): BufferView {
* full-width walls of text; a wrapped OAuth URL is ~7 rows at 80 cols. */
const MAX_JOIN_ROWS = 32
+export interface ParagraphOpts {
+ /** Claude's TUI repaints a wrapped paragraph with its two-column content indent on EVERY row.
+ * File matching may discard that repeated indent; web URLs deliberately keep the stricter
+ * behavior so ordinary indented prose cannot silently extend an http(s) URL. */
+ indentedFileWraps?: boolean
+}
+
+export interface LogicalParagraph {
+ text: string
+ startRow: number
+ rows: number
+ /** Buffer cell for every character in `text` (indent-normalized paragraphs are not rectangular). */
+ positions: Array<{ row: number; col: number }>
+}
+
// Whether `row` runs into `row + 1`: the successor carries xterm's soft-wrap flag, OR the
-// hard-wrap heuristic holds — `row` is full to its last column (untrimmed non-space in the
-// final cell) and the successor starts at column 0 with a non-space. See the header comment.
-function continuesOnNextRow(view: BufferView, row: number): boolean {
+// hard-wrap heuristic holds — `row` is full to its last column. Usually the successor must start
+// at column 0; the file-only mode also recognizes Claude's repeated 1–4 column content indent.
+function continuationToNext(
+ view: BufferView,
+ row: number,
+ opts: ParagraphOpts
+): { skipNext: number } | null {
const next = view.line(row + 1)
- if (!next) return false
- if (next.isWrapped) return true
+ if (!next) return null
+ if (next.isWrapped) return { skipNext: 0 }
const cur = view.line(row)
- if (!cur) return false
+ if (!cur) return null
const raw = cur.text(false)
- if (raw.length < view.cols || raw[view.cols - 1] === ' ') return false
+ if (raw.length < view.cols || raw[view.cols - 1] === ' ') return null
const nextRaw = next.text(false)
- return nextRaw.length > 0 && nextRaw[0] !== ' '
+ if (nextRaw.length > 0 && nextRaw[0] !== ' ') return { skipNext: 0 }
+ if (!opts.indentedFileWraps) return null
+ const indent = /^( {1,4})(\S)/.exec(nextRaw)
+ if (!indent) return null
+ const last = raw[view.cols - 1]
+ // Both sides must look like file-URL/path characters. This mode is consumed only by the file
+ // provider and still has to produce an existing path before a link is offered.
+ if (!/[\w.@+~%:/\\-]/.test(last) || !/[\w.@+~%:/\\-]/.test(indent[2])) return null
+ return { skipNext: indent[1].length }
}
/**
@@ -324,45 +400,64 @@ function continuesOnNextRow(view: BufferView, row: number): boolean {
*/
export function paragraphContaining(
view: BufferView,
- row: number
-): { text: string; startRow: number; rows: number } | null {
+ row: number,
+ opts: ParagraphOpts = {}
+): LogicalParagraph | null {
if (!view.line(row)) return null
let start = row
- while (start > 0 && row - start < MAX_JOIN_ROWS && continuesOnNextRow(view, start - 1)) start--
+ while (
+ start > 0 &&
+ row - start < MAX_JOIN_ROWS &&
+ continuationToNext(view, start - 1, opts)
+ )
+ start--
let text = ''
+ const positions: LogicalParagraph['positions'] = []
let r = start
+ let skipStart = 0
for (;;) {
- const joins = r - start + 1 < MAX_JOIN_ROWS && continuesOnNextRow(view, r)
- const lineText = view.line(r)!.text(!joins)
- // Continuing rows must contribute exactly `cols` chars so the index math above holds.
- text += joins ? lineText.padEnd(view.cols).slice(0, view.cols) : lineText
- if (!joins) break
+ const continuation =
+ r - start + 1 < MAX_JOIN_ROWS ? continuationToNext(view, r, opts) : null
+ const joins = !!continuation
+ const raw = view.line(r)!.text(!joins)
+ const lineText = joins ? raw.padEnd(view.cols).slice(0, view.cols) : raw
+ const kept = lineText.slice(skipStart)
+ text += kept
+ for (let col = skipStart; col < lineText.length; col++) positions.push({ row: r, col })
+ if (!continuation) break
+ skipStart = continuation.skipNext
r++
}
- return { text, startRow: start, rows: r - start + 1 }
+ return { text, startRow: start, rows: r - start + 1, positions }
}
/** ILink range (1-based, inclusive) for a token at `startIndex..+len` of a paragraph. */
function tokenRange(
- startRow: number,
- cols: number,
+ logical: LogicalParagraph,
startIndex: number,
len: number
): ILink['range'] {
- const endIndex = startIndex + len - 1
+ const start = logical.positions[startIndex]
+ const end = logical.positions[startIndex + len - 1]
return {
- start: { x: (startIndex % cols) + 1, y: startRow + Math.floor(startIndex / cols) + 1 },
- end: { x: (endIndex % cols) + 1, y: startRow + Math.floor(endIndex / cols) + 1 }
+ start: { x: start.col + 1, y: start.row + 1 },
+ end: { x: end.col + 1, y: end.row + 1 }
}
}
+function logicalIndexAt(logical: LogicalParagraph, row: number, col: number): number {
+ return logical.positions.findIndex((p) => p.row === row && p.col === col)
+}
+
/** xterm link provider for file paths. Register once per terminal with a reachable filesystem. */
export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILinkProvider {
return {
provideLinks(bufferLineNumber: number, callback: (links: ILink[] | undefined) => void): void {
// Resolve the paragraph CONTAINING the hovered row (not just one starting at it), so
// hovering any wrapped tail row of a long path underlines and activates the whole token.
- const logical = paragraphContaining(bufferView(term), bufferLineNumber - 1)
+ const logical = paragraphContaining(bufferView(term), bufferLineNumber - 1, {
+ indentedFileWraps: true
+ })
if (!logical) {
callback(undefined)
return
@@ -377,19 +472,22 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILin
callback(undefined)
return
}
- const cols = term.cols
void Promise.all(
tokens.map(async (t): Promise<ILink | null> => {
+ if (t.fileUrl && (!deps.activateFileUrl || !(deps.fileUrlEnabled?.() ?? true))) return null
+ if (!t.fileUrl && !(deps.pathEnabled?.() ?? true)) return null
const abs = resolveFileToken(t.path, deps.getCwd(), convention)
if (!abs) return null
const found = await deps.lookup(abs)
if (!found.exists) return null
return {
text: t.text,
- range: tokenRange(logical.startRow, cols, t.startIndex, t.text.length),
+ range: tokenRange(logical, t.startIndex, t.text.length),
activate: (event: MouseEvent) => {
if (!(event.metaKey || event.ctrlKey)) return
- deps.activate(abs, found.dir)
+ if (t.fileUrl) {
+ if (deps.fileUrlEnabled?.() ?? true) deps.activateFileUrl?.(abs, found.dir)
+ } else deps.activate(abs, found.dir)
}
}
})
@@ -418,7 +516,7 @@ export function createUrlLinkProvider(term: Terminal, openUrl: (url: string) =>
const links = matchUrlTokens(logical.text).map(
(u): ILink => ({
text: u.text,
- range: tokenRange(logical.startRow, term.cols, u.startIndex, u.text.length),
+ range: tokenRange(logical, u.startIndex, u.text.length),
activate: (event: MouseEvent) => {
if (event.metaKey || event.ctrlKey) openUrl(u.url)
}
@@ -495,6 +593,8 @@ export interface LinkClickDeps {
convention?: () => PathConventionOpts | null
lookup(abs: string): Promise<{ exists: boolean; dir: boolean }>
activateFile(abs: string, dir: boolean): void
+ activateFileUrl?(abs: string, dir: boolean): void
+ fileUrlEnabled?(): boolean
openUrl(url: string): void
/** False while no correctly-routed filesystem/dialect is available. */
fileEnabled(): boolean
@@ -534,7 +634,8 @@ export function installLinkClickFallback(
}
const logical = paragraphContaining(bufferView(term), pos.row)
if (!logical) return
- const idx = (pos.row - logical.startRow) * term.cols + pos.col
+ const idx = logicalIndexAt(logical, pos.row, pos.col)
+ if (idx < 0) return
const inRange = (startIndex: number, len: number): boolean =>
idx >= startIndex && idx < startIndex + len
@@ -547,11 +648,22 @@ export function installLinkClickFallback(
return
}
}
- if (!deps.fileEnabled()) return
+ const pathEnabled = deps.fileEnabled()
+ const fileUrlEnabled = !!deps.activateFileUrl && (deps.fileUrlEnabled?.() ?? true)
+ if (!pathEnabled && !fileUrlEnabled) return
const convention = deps.convention ? deps.convention() : { windows: deps.windows }
if (!convention) return
- for (const t of matchFileTokens(logical.text, convention)) {
- if (inRange(t.startIndex, t.text.length)) {
+ const fileLogical = paragraphContaining(bufferView(term), pos.row, {
+ indentedFileWraps: true
+ })
+ if (!fileLogical) return
+ const fileIdx = logicalIndexAt(fileLogical, pos.row, pos.col)
+ if (fileIdx < 0) return
+ const inFileRange = (startIndex: number, len: number): boolean =>
+ fileIdx >= startIndex && fileIdx < startIndex + len
+ for (const t of matchFileTokens(fileLogical.text, convention)) {
+ if (inFileRange(t.startIndex, t.text.length)) {
+ if (t.fileUrl ? !fileUrlEnabled : !pathEnabled) return
const abs = resolveFileToken(t.path, deps.getCwd(), convention)
if (!abs) return
// Swallow the click NOW so tmux never gets the mouse report; existence is async and a
@@ -560,7 +672,10 @@ export function installLinkClickFallback(
ev.stopPropagation()
term.clearSelection()
void deps.lookup(abs).then((f) => {
- if (f.exists) deps.activateFile(abs, f.dir)
+ if (!f.exists) return
+ if (t.fileUrl) {
+ if (deps.fileUrlEnabled?.() ?? true) deps.activateFileUrl?.(abs, f.dir)
+ } else deps.activateFile(abs, f.dir)
})
return
}