Fix wrapped terminal file links (#2690)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -23,6 +23,7 @@ import { rebuild } from '@electron/rebuild'
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { createRequire } from 'node:module'
|
||||
import { existsSync, globSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { platform as osPlatform } from 'node:os'
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
@@ -141,6 +142,11 @@ function ensureElectronPackageInstalled() {
|
||||
try {
|
||||
execFileSync(process.execPath, [require.resolve('electron/install.js')], {
|
||||
cwd: projectDir,
|
||||
env: {
|
||||
...process.env,
|
||||
ELECTRON_SKIP_BINARY_DOWNLOAD: '',
|
||||
force_no_cache: 'true'
|
||||
},
|
||||
stdio: 'inherit'
|
||||
})
|
||||
} catch (/** @type {any} */ err) {
|
||||
@@ -151,8 +157,57 @@ function ensureElectronPackageInstalled() {
|
||||
try {
|
||||
require('electron')
|
||||
} catch (/** @type {any} */ err) {
|
||||
console.error('[rebuild] Electron package is still unavailable after retry:', err?.message ?? err)
|
||||
process.exit(1)
|
||||
if (!repairElectronPathFile()) {
|
||||
console.error(
|
||||
'[rebuild] Electron package is still unavailable after retry:',
|
||||
err?.message ?? err
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
try {
|
||||
require('electron')
|
||||
} catch (/** @type {any} */ retryErr) {
|
||||
console.error(
|
||||
'[rebuild] Electron package is still unavailable after repairing path.txt:',
|
||||
retryErr?.message ?? retryErr
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function repairElectronPathFile() {
|
||||
const electronPackageDir = resolve(projectDir, 'node_modules/electron')
|
||||
const platformPath = getElectronPlatformPath()
|
||||
const electronPath = process.env.ELECTRON_OVERRIDE_DIST_PATH
|
||||
? resolve(process.env.ELECTRON_OVERRIDE_DIST_PATH, platformPath)
|
||||
: resolve(electronPackageDir, 'dist', platformPath)
|
||||
if (!existsSync(electronPath)) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Why: Electron's install script has exited successfully in CI after
|
||||
// extraction without leaving path.txt. The package main only needs this file
|
||||
// to point at the already-extracted executable.
|
||||
writeFileSync(resolve(electronPackageDir, 'path.txt'), platformPath)
|
||||
console.log(`[rebuild] Repaired Electron path.txt -> ${platformPath}`)
|
||||
return true
|
||||
}
|
||||
|
||||
function getElectronPlatformPath() {
|
||||
const targetPlatform = process.env.npm_config_platform || osPlatform()
|
||||
switch (targetPlatform) {
|
||||
case 'mas':
|
||||
case 'darwin':
|
||||
return 'Electron.app/Contents/MacOS/Electron'
|
||||
case 'freebsd':
|
||||
case 'openbsd':
|
||||
case 'linux':
|
||||
return 'electron'
|
||||
case 'win32':
|
||||
return 'electron.exe'
|
||||
default:
|
||||
throw new Error(`Electron builds are not available on platform: ${targetPlatform}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -729,18 +729,13 @@ export function FloatingTerminalPanel({
|
||||
context,
|
||||
terminalShortcutPolicy: state.settings?.terminalShortcutPolicy
|
||||
}
|
||||
const nativeEvent = event.nativeEvent ?? event
|
||||
const matches = (actionId: KeybindingActionId): boolean =>
|
||||
keybindingMatchesAction(
|
||||
actionId,
|
||||
event.nativeEvent,
|
||||
platform,
|
||||
state.keybindings,
|
||||
matchOptions
|
||||
)
|
||||
keybindingMatchesAction(actionId, nativeEvent, platform, state.keybindings, matchOptions)
|
||||
|
||||
if (
|
||||
!isFloatingWorkspacePanelShortcut(
|
||||
event.nativeEvent,
|
||||
nativeEvent,
|
||||
platform,
|
||||
panelRef.current,
|
||||
state.keybindings,
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { IBufferLine, IBufferRange } from '@xterm/xterm'
|
||||
import { extractTerminalFileLinks, resolveTerminalFileLink } from '@/lib/terminal-links'
|
||||
import { openDetectedFilePath } from './terminal-file-open-routing'
|
||||
import {
|
||||
buildHardWrappedPathLogicalLineCandidates,
|
||||
buildWrappedLogicalLine,
|
||||
rangeForParsedFileLink,
|
||||
type WrappedLogicalLine
|
||||
} from './wrapped-terminal-link-ranges'
|
||||
|
||||
type FileLinkHitTestDeps = {
|
||||
startupCwd: string
|
||||
worktreeId: string
|
||||
worktreePath: string
|
||||
runtimeEnvironmentId?: string | null
|
||||
}
|
||||
|
||||
export function openFilePathLinkAtBufferPosition(
|
||||
buffer: { getLine(y: number): IBufferLine | undefined },
|
||||
position: { x: number; y: number },
|
||||
terminalColumns: number,
|
||||
deps: FileLinkHitTestDeps
|
||||
): boolean {
|
||||
const logicalLines = buildCandidateLogicalLinesForBufferPosition(buffer, position.y)
|
||||
if (logicalLines.length === 0) {
|
||||
return false
|
||||
}
|
||||
|
||||
for (const logicalLine of logicalLines) {
|
||||
for (const parsed of extractTerminalFileLinks(logicalLine.text)) {
|
||||
const resolved = deps.startupCwd ? resolveTerminalFileLink(parsed, deps.startupCwd) : null
|
||||
if (!resolved) {
|
||||
continue
|
||||
}
|
||||
const range = rangeForParsedFileLink(logicalLine, parsed.startIndex, parsed.endIndex)
|
||||
if (!range || !rangeContainsBufferPosition(range, position, terminalColumns)) {
|
||||
continue
|
||||
}
|
||||
openDetectedFilePath(resolved.absolutePath, resolved.line, resolved.column, deps)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export function buildCandidateLogicalLinesForBufferPosition(
|
||||
buffer: { getLine(y: number): IBufferLine | undefined },
|
||||
bufferLineNumber: number
|
||||
): WrappedLogicalLine[] {
|
||||
const hardWrappedCandidates = buildHardWrappedPathLogicalLineCandidates(buffer, bufferLineNumber)
|
||||
const softWrappedLogicalLine = buildWrappedLogicalLine(buffer, bufferLineNumber)
|
||||
const candidates = softWrappedLogicalLine
|
||||
? [...hardWrappedCandidates, softWrappedLogicalLine]
|
||||
: hardWrappedCandidates
|
||||
return dedupeLogicalLines(candidates)
|
||||
}
|
||||
|
||||
export function dedupeLogicalLines(logicalLines: WrappedLogicalLine[]): WrappedLogicalLine[] {
|
||||
const seen = new Set<string>()
|
||||
return logicalLines.filter((logicalLine) => {
|
||||
if (seen.has(logicalLine.fingerprint)) {
|
||||
return false
|
||||
}
|
||||
seen.add(logicalLine.fingerprint)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
function rangeContainsBufferPosition(
|
||||
range: IBufferRange,
|
||||
position: { x: number; y: number },
|
||||
terminalColumns: number
|
||||
): boolean {
|
||||
const lower = range.start.y * terminalColumns + range.start.x
|
||||
const upper = range.end.y * terminalColumns + range.end.x
|
||||
const current = position.y * terminalColumns + position.x
|
||||
return lower <= current && current <= upper
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { absolutePathToFileUri } from '@/components/editor/markdown-internal-links'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import { detectLanguage } from '@/lib/language-detect'
|
||||
import { isPathInsideWorktree, toWorktreeRelativePath } from '@/lib/terminal-links'
|
||||
import {
|
||||
isRemoteRuntimeFileOperation,
|
||||
statRuntimePath,
|
||||
type RuntimeFileOperationArgs
|
||||
} from '@/runtime/runtime-file-client'
|
||||
import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client'
|
||||
import { useAppStore } from '@/store'
|
||||
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
|
||||
|
||||
type TerminalFileOpenDeps = {
|
||||
worktreeId: string
|
||||
worktreePath: string
|
||||
runtimeEnvironmentId?: string | null
|
||||
}
|
||||
|
||||
export function isHtmlFilePath(filePath: string): boolean {
|
||||
return /\.html?$/i.test(filePath)
|
||||
}
|
||||
|
||||
function openHtmlFileInBrowser(filePath: string, worktreeId: string): void {
|
||||
const store = useAppStore.getState()
|
||||
if (worktreeId) {
|
||||
// Why: following an HTML file link changes which worktree is foregrounded,
|
||||
// so it must record a history visit before opening the browser tab.
|
||||
activateAndRevealWorktree(worktreeId)
|
||||
}
|
||||
const fileUrl = absolutePathToFileUri(filePath)
|
||||
const title = filePath.split(/[/\\]/).pop() ?? filePath
|
||||
store.createBrowserTab(worktreeId, fileUrl, { title, activate: true })
|
||||
}
|
||||
|
||||
export function getTerminalFileContext(
|
||||
worktreeId: string,
|
||||
worktreePath: string,
|
||||
runtimeEnvironmentId?: string | null
|
||||
): RuntimeFileOperationArgs {
|
||||
const settings = useAppStore.getState().settings
|
||||
return {
|
||||
settings: settingsForRuntimeOwner(settings, runtimeEnvironmentId),
|
||||
worktreeId: worktreeId || null,
|
||||
worktreePath,
|
||||
connectionId: getConnectionId(worktreeId || null) ?? undefined
|
||||
}
|
||||
}
|
||||
|
||||
let latestOpenDetectedFilePathRequestId = 0
|
||||
|
||||
export function openDetectedFilePath(
|
||||
filePath: string,
|
||||
line: number | null,
|
||||
column: number | null,
|
||||
deps: TerminalFileOpenDeps
|
||||
): void {
|
||||
const { runtimeEnvironmentId, worktreeId, worktreePath } = deps
|
||||
const requestId = ++latestOpenDetectedFilePathRequestId
|
||||
|
||||
void (async () => {
|
||||
let statResult
|
||||
try {
|
||||
const fileContext = getTerminalFileContext(worktreeId, worktreePath, runtimeEnvironmentId)
|
||||
const isRemoteRuntimePath = isRemoteRuntimeFileOperation(fileContext, filePath)
|
||||
// Why: remote paths don't need local auth — the relay/runtime is the security boundary.
|
||||
if (!fileContext.connectionId && !isRemoteRuntimePath) {
|
||||
await window.api.fs.authorizeExternalPath({ targetPath: filePath })
|
||||
}
|
||||
statResult = await statRuntimePath(fileContext, filePath)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
if (requestId !== latestOpenDetectedFilePathRequestId) {
|
||||
return
|
||||
}
|
||||
|
||||
if (statResult.isDirectory) {
|
||||
const fileContext = getTerminalFileContext(worktreeId, worktreePath, runtimeEnvironmentId)
|
||||
if (fileContext.connectionId || isRemoteRuntimeFileOperation(fileContext, filePath)) {
|
||||
return
|
||||
}
|
||||
await window.api.shell.openFilePath(filePath)
|
||||
return
|
||||
}
|
||||
|
||||
// Why: .html/.htm files render in Orca's embedded browser instead of opening
|
||||
// as source in Monaco — ⌘/Ctrl+click on an HTML path in the terminal should
|
||||
// feel like clicking an http link and render the page, not dump HTML source.
|
||||
// Mirrors the editor's "Open Preview to the Side" action.
|
||||
const fileContext = getTerminalFileContext(worktreeId, worktreePath, runtimeEnvironmentId)
|
||||
if (
|
||||
isHtmlFilePath(filePath) &&
|
||||
!fileContext.connectionId &&
|
||||
!isRemoteRuntimeFileOperation(fileContext, filePath)
|
||||
) {
|
||||
openHtmlFileInBrowser(filePath, worktreeId)
|
||||
return
|
||||
}
|
||||
|
||||
let relativePath = filePath
|
||||
if (worktreePath && isPathInsideWorktree(filePath, worktreePath)) {
|
||||
const maybeRelative = toWorktreeRelativePath(filePath, worktreePath)
|
||||
if (maybeRelative !== null && maybeRelative.length > 0) {
|
||||
relativePath = maybeRelative
|
||||
}
|
||||
}
|
||||
|
||||
const store = useAppStore.getState()
|
||||
if (worktreeId) {
|
||||
// Why: terminal file links can jump across worktrees. Reusing the shared
|
||||
// activation path keeps those jumps in the same history stack as sidebar
|
||||
// and palette navigation before the editor opens the destination file.
|
||||
activateAndRevealWorktree(worktreeId)
|
||||
}
|
||||
|
||||
store.openFile({
|
||||
filePath,
|
||||
relativePath,
|
||||
worktreeId: worktreeId || '',
|
||||
language: detectLanguage(filePath),
|
||||
mode: 'edit',
|
||||
runtimeEnvironmentId
|
||||
})
|
||||
|
||||
if (line !== null) {
|
||||
const targetColumn = column ?? 1
|
||||
store.setPendingEditorReveal(null)
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (requestId !== latestOpenDetectedFilePathRequestId) {
|
||||
return
|
||||
}
|
||||
store.setPendingEditorReveal({
|
||||
filePath,
|
||||
line,
|
||||
column: targetColumn,
|
||||
matchLength: 0
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
})()
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
createFilePathLinkProvider,
|
||||
getTerminalHtmlFileOpenHint,
|
||||
handleOscLink,
|
||||
installFilePathLinkClickFallback,
|
||||
isTerminalLinkActivation,
|
||||
openFilePathLinkAtBufferPosition,
|
||||
openDetectedFilePath
|
||||
} from './terminal-link-handlers'
|
||||
import { registerHttpLinkStoreAccessor } from '@/lib/http-link-routing'
|
||||
@@ -522,27 +524,65 @@ describe('handleOscLink', () => {
|
||||
})
|
||||
|
||||
describe('createFilePathLinkProvider range bounds', () => {
|
||||
function makePane(lineText: string): { id: number; terminal: unknown } {
|
||||
type TestBufferLine = {
|
||||
isWrapped: boolean
|
||||
length: number
|
||||
translateToString: (
|
||||
trimRight?: boolean,
|
||||
startColumn?: number,
|
||||
endColumn?: number,
|
||||
outColumns?: number[]
|
||||
) => string
|
||||
}
|
||||
|
||||
function defaultColumnsForText(text: string): number[] {
|
||||
return Array.from({ length: text.length + 1 }, (_value, index) => index)
|
||||
}
|
||||
|
||||
function makeBufferLine(
|
||||
text: string,
|
||||
options: { isWrapped?: boolean; columns?: number[] } = {}
|
||||
): TestBufferLine {
|
||||
const columns = options.columns ?? defaultColumnsForText(text)
|
||||
return {
|
||||
isWrapped: options.isWrapped ?? false,
|
||||
length: text.length,
|
||||
translateToString: (
|
||||
_trimRight?: boolean,
|
||||
startColumn = 0,
|
||||
endColumn = text.length,
|
||||
outColumns?: number[]
|
||||
) => {
|
||||
if (outColumns) {
|
||||
outColumns.length = 0
|
||||
for (let index = startColumn; index <= endColumn; index++) {
|
||||
outColumns.push(columns[index] ?? index)
|
||||
}
|
||||
}
|
||||
return text.slice(startColumn, endColumn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makePane(rows: TestBufferLine[]): { id: number; terminal: unknown } {
|
||||
return {
|
||||
id: 1,
|
||||
terminal: {
|
||||
buffer: {
|
||||
active: {
|
||||
getLine: (_y: number) => ({
|
||||
translateToString: (_trim: boolean) => lineText
|
||||
})
|
||||
getLine: (y: number) => rows[y]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function collectLinks(lineText: string): Promise<ILink[]> {
|
||||
const pane = makePane(lineText)
|
||||
function createProvider(rows: TestBufferLine[]) {
|
||||
const pane = makePane(rows)
|
||||
const managerRef = {
|
||||
current: { getPanes: () => [pane] } as unknown as PaneManager
|
||||
}
|
||||
const provider = createFilePathLinkProvider(
|
||||
return createFilePathLinkProvider(
|
||||
1,
|
||||
{
|
||||
worktreeId: 'wt-1',
|
||||
@@ -558,11 +598,94 @@ describe('createFilePathLinkProvider range bounds', () => {
|
||||
{ textContent: '', style: { display: '' } } as unknown as HTMLElement,
|
||||
'hint'
|
||||
)
|
||||
}
|
||||
|
||||
function collectLinks(
|
||||
rowsOrText: TestBufferLine[] | string,
|
||||
bufferLineNumber = 1
|
||||
): Promise<ILink[]> {
|
||||
const rows = typeof rowsOrText === 'string' ? [makeBufferLine(rowsOrText)] : rowsOrText
|
||||
const provider = createProvider(rows)
|
||||
return new Promise<ILink[]>((resolve) => {
|
||||
provider.provideLinks(1, (links) => resolve(links ?? []))
|
||||
provider.provideLinks(bufferLineNumber, (links) => resolve(links ?? []))
|
||||
})
|
||||
}
|
||||
|
||||
function containsBufferPoint(link: ILink, x: number, y: number): boolean {
|
||||
const { start, end } = link.range
|
||||
if (y < start.y || y > end.y) {
|
||||
return false
|
||||
}
|
||||
if (start.y === end.y) {
|
||||
return x >= start.x && x <= end.x
|
||||
}
|
||||
if (y === start.y) {
|
||||
return x >= start.x
|
||||
}
|
||||
if (y === end.y) {
|
||||
return x <= end.x
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function makeBuffer(
|
||||
rows: TestBufferLine[]
|
||||
): Parameters<typeof openFilePathLinkAtBufferPosition>[0] {
|
||||
return { getLine: (y: number) => rows[y] } as Parameters<
|
||||
typeof openFilePathLinkAtBufferPosition
|
||||
>[0]
|
||||
}
|
||||
|
||||
function makeFallbackTerminal(rows: TestBufferLine[]): {
|
||||
terminal: Parameters<typeof installFilePathLinkClickFallback>[1]
|
||||
element: {
|
||||
addEventListener: ReturnType<typeof vi.fn>
|
||||
removeEventListener: ReturnType<typeof vi.fn>
|
||||
querySelector: ReturnType<typeof vi.fn>
|
||||
}
|
||||
} {
|
||||
const screen = {
|
||||
classList: { contains: vi.fn(() => true) },
|
||||
getBoundingClientRect: () => ({
|
||||
left: 10,
|
||||
top: 20,
|
||||
width: 800,
|
||||
height: 400
|
||||
})
|
||||
}
|
||||
const element = {
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
querySelector: vi.fn(() => screen)
|
||||
}
|
||||
return {
|
||||
terminal: {
|
||||
cols: 80,
|
||||
rows: 40,
|
||||
element,
|
||||
buffer: {
|
||||
active: {
|
||||
viewportY: 0,
|
||||
getLine: (y: number) => rows[y]
|
||||
}
|
||||
},
|
||||
clearSelection: vi.fn()
|
||||
} as unknown as Parameters<typeof installFilePathLinkClickFallback>[1],
|
||||
element
|
||||
}
|
||||
}
|
||||
|
||||
function getRegisteredMouseUpHandler(element: {
|
||||
addEventListener: ReturnType<typeof vi.fn>
|
||||
}): (event: MouseEvent) => void {
|
||||
const registration = element.addEventListener.mock.calls.find(
|
||||
([eventName]) => eventName === 'mouseup'
|
||||
)
|
||||
expect(registration, 'mouseup handler should be registered').toBeDefined()
|
||||
expect(registration![2]).toEqual({ capture: true })
|
||||
return registration![1] as (event: MouseEvent) => void
|
||||
}
|
||||
|
||||
it('underlines only the filename itself, not the column padding from `ls`', async () => {
|
||||
// ls pads each column with trailing spaces. Regression: the provider used
|
||||
// to report `end.x = endIndex + 1`, which in xterm's 1-based *inclusive*
|
||||
@@ -585,4 +708,232 @@ describe('createFilePathLinkProvider range bounds', () => {
|
||||
expect(pkg!.range.start.x).toBe(pkgStartIndex + 1)
|
||||
expect(pkg!.range.end.x).toBe(pkgStartIndex + 'package.json'.length)
|
||||
})
|
||||
|
||||
it('opens a single-row file path from a direct modifier-click fallback', async () => {
|
||||
setPlatform('Macintosh')
|
||||
const pathExists = createDeferred<boolean>()
|
||||
vi.mocked(window.api.shell.pathExists).mockImplementation(() => pathExists.promise)
|
||||
|
||||
const opened = openFilePathLinkAtBufferPosition(
|
||||
makeBuffer([makeBufferLine('package.json')]),
|
||||
{ x: 4, y: 1 },
|
||||
80,
|
||||
{
|
||||
startupCwd: '/tmp',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/tmp',
|
||||
runtimeEnvironmentId: null
|
||||
}
|
||||
)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(opened).toBe(true)
|
||||
// Why: direct click fallback cannot wait for xterm's hover-time async
|
||||
// existence probe; openDetectedFilePath still stats before routing.
|
||||
expect(window.api.shell.pathExists).not.toHaveBeenCalled()
|
||||
expect(openFileMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filePath: '/tmp/package.json' })
|
||||
)
|
||||
})
|
||||
|
||||
it('opens a wrapped continuation-row html path from a direct modifier-click fallback', async () => {
|
||||
setPlatform('Macintosh')
|
||||
const rows = [
|
||||
makeBufferLine('open mobile/mock-'),
|
||||
makeBufferLine('homepage.html', { isWrapped: true })
|
||||
]
|
||||
|
||||
const opened = openFilePathLinkAtBufferPosition(
|
||||
makeBuffer(rows),
|
||||
{ x: 'home'.length, y: 2 },
|
||||
20,
|
||||
{
|
||||
startupCwd: '/tmp',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/tmp',
|
||||
runtimeEnvironmentId: null
|
||||
}
|
||||
)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(opened).toBe(true)
|
||||
expect(createBrowserTabMock).toHaveBeenCalledWith(
|
||||
'wt-1',
|
||||
'file:///tmp/mobile/mock-homepage.html',
|
||||
expect.objectContaining({ title: 'mock-homepage.html', activate: true })
|
||||
)
|
||||
})
|
||||
|
||||
it('retries a wrapped file click even when xterm already marked the link active', async () => {
|
||||
setPlatform('Macintosh')
|
||||
const rows = [
|
||||
makeBufferLine('/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5/mobile/'),
|
||||
makeBufferLine('packages/expo-two-way-audio/android/src/main/java/expo/modules/'),
|
||||
makeBufferLine('twowayaudio/ExpoTwoWayAudioLifeCycleListener.kt')
|
||||
]
|
||||
const { terminal, element } = makeFallbackTerminal(rows)
|
||||
const disposable = installFilePathLinkClickFallback(1, terminal, {
|
||||
startupCwd: '/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5',
|
||||
runtimeEnvironmentId: null,
|
||||
managerRef: { current: null },
|
||||
linkProviderDisposablesRef: { current: new Map<number, IDisposable>() },
|
||||
pathExistsCache: new Map<string, boolean>()
|
||||
})
|
||||
const mouseUp = getRegisteredMouseUpHandler(element)
|
||||
const preventDefault = vi.fn()
|
||||
const stopPropagation = vi.fn()
|
||||
|
||||
mouseUp({
|
||||
button: 0,
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
clientX: 20,
|
||||
clientY: 45,
|
||||
preventDefault,
|
||||
stopPropagation
|
||||
} as unknown as MouseEvent)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(openFileMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
filePath:
|
||||
'/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5/mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/ExpoTwoWayAudioLifeCycleListener.kt'
|
||||
})
|
||||
)
|
||||
expect(preventDefault).toHaveBeenCalled()
|
||||
expect(stopPropagation).toHaveBeenCalled()
|
||||
expect(terminal.clearSelection).toHaveBeenCalled()
|
||||
|
||||
disposable.dispose()
|
||||
expect(element.removeEventListener).toHaveBeenCalledWith('mouseup', mouseUp, { capture: true })
|
||||
})
|
||||
|
||||
it('opens a deeply wrapped absolute path from its final short continuation row', async () => {
|
||||
setPlatform('Macintosh')
|
||||
const rows = [
|
||||
makeBufferLine('/private/tmp/or'),
|
||||
makeBufferLine('ca-setup-e2e.hO'),
|
||||
makeBufferLine('W01f/workspaces'),
|
||||
makeBufferLine('/test-wt-5/mob'),
|
||||
makeBufferLine('ile/packages/ex'),
|
||||
makeBufferLine('po-two-way-aud'),
|
||||
makeBufferLine('io/android/src/'),
|
||||
makeBufferLine('main/java/expo'),
|
||||
makeBufferLine('/modules/twoway'),
|
||||
makeBufferLine('audio/ExpoTwoW'),
|
||||
makeBufferLine('ayAudioLifeCyc'),
|
||||
makeBufferLine('leListener.kt')
|
||||
]
|
||||
|
||||
const opened = openFilePathLinkAtBufferPosition(makeBuffer(rows), { x: 4, y: 12 }, 15, {
|
||||
startupCwd: '/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5',
|
||||
runtimeEnvironmentId: null
|
||||
})
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(opened).toBe(true)
|
||||
expect(openFileMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
filePath:
|
||||
'/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5/mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/ExpoTwoWayAudioLifeCycleListener.kt'
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('returns a wrapped file link when hovering the first physical row', async () => {
|
||||
const rows = [
|
||||
makeBufferLine('open src/components/'),
|
||||
makeBufferLine('terminal-link-handlers.ts', { isWrapped: true })
|
||||
]
|
||||
|
||||
const links = await collectLinks(rows, 1)
|
||||
const link = links.find(
|
||||
(candidate) => candidate.text === 'src/components/terminal-link-handlers.ts'
|
||||
)
|
||||
|
||||
expect(link, 'wrapped path should be linkified from the first row').toBeDefined()
|
||||
expect(link!.range).toEqual({
|
||||
start: { x: 'open '.length + 1, y: 1 },
|
||||
end: { x: 'terminal-link-handlers.ts'.length, y: 2 }
|
||||
})
|
||||
})
|
||||
|
||||
it('returns the same wrapped file link when hovering the continuation row', async () => {
|
||||
const rows = [
|
||||
makeBufferLine('open src/components/'),
|
||||
makeBufferLine('terminal-link-handlers.ts', { isWrapped: true })
|
||||
]
|
||||
|
||||
const firstRowLinks = await collectLinks(rows, 1)
|
||||
const continuationLinks = await collectLinks(rows, 2)
|
||||
const firstRowLink = firstRowLinks.find(
|
||||
(candidate) => candidate.text === 'src/components/terminal-link-handlers.ts'
|
||||
)
|
||||
const continuationLink = continuationLinks.find(
|
||||
(candidate) => candidate.text === 'src/components/terminal-link-handlers.ts'
|
||||
)
|
||||
|
||||
expect(
|
||||
continuationLink,
|
||||
'wrapped path should be linkified from the continuation row'
|
||||
).toBeDefined()
|
||||
expect(continuationLink!.text).toBe(firstRowLink!.text)
|
||||
expect(continuationLink!.range).toEqual(firstRowLink!.range)
|
||||
})
|
||||
|
||||
it('maps file link columns through multi-code-unit characters before the path', async () => {
|
||||
const text = 'e\u0301 src/main.ts'
|
||||
const columns = [0, 0, 1]
|
||||
for (let index = 3; index < text.length; index++) {
|
||||
columns[index] = index - 1
|
||||
}
|
||||
columns[text.length] = text.length - 1
|
||||
|
||||
const links = await collectLinks([makeBufferLine(text, { columns })])
|
||||
const link = links.find((candidate) => candidate.text === 'src/main.ts')
|
||||
|
||||
expect(link, 'unicode-prefixed path should be linkified').toBeDefined()
|
||||
expect(link!.range.start.x).toBe(3)
|
||||
expect(link!.range.end.x).toBe(text.length - 1)
|
||||
})
|
||||
|
||||
it('drops stale async file links when wrapped rows change before existence resolves', async () => {
|
||||
const rows = [
|
||||
makeBufferLine('open src/components/'),
|
||||
makeBufferLine('terminal-link-handlers.ts', { isWrapped: true })
|
||||
]
|
||||
const provider = createProvider(rows)
|
||||
const exists = createDeferred<boolean>()
|
||||
vi.mocked(window.api.shell.pathExists).mockImplementation(() => exists.promise)
|
||||
const callback = vi.fn()
|
||||
|
||||
provider.provideLinks(1, callback)
|
||||
rows[0] = makeBufferLine('changed src/other/')
|
||||
|
||||
exists.resolve(true)
|
||||
await flushAsyncWork()
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(callback).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports multi-row ranges that hit-test at wrapped-link boundaries', async () => {
|
||||
const rows = [
|
||||
makeBufferLine('trace src/very/long/'),
|
||||
makeBufferLine('nested/file.ts done', { isWrapped: true })
|
||||
]
|
||||
|
||||
const links = await collectLinks(rows, 2)
|
||||
const link = links.find((candidate) => candidate.text === 'src/very/long/nested/file.ts')
|
||||
|
||||
expect(link, 'multi-row path should be linkified').toBeDefined()
|
||||
expect(containsBufferPoint(link!, 'trace '.length, 1)).toBe(false)
|
||||
expect(containsBufferPoint(link!, 'trace '.length + 1, 1)).toBe(true)
|
||||
expect(containsBufferPoint(link!, 'nested/file.ts'.length, 2)).toBe(true)
|
||||
expect(containsBufferPoint(link!, 'nested/file.ts'.length + 1, 2)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,26 +1,32 @@
|
||||
import type { IDisposable, ILink, ILinkProvider } from '@xterm/xterm'
|
||||
import { detectLanguage } from '@/lib/language-detect'
|
||||
import type { IDisposable, ILink, ILinkProvider, Terminal } from '@xterm/xterm'
|
||||
import {
|
||||
extractTerminalFileLinks,
|
||||
isPathInsideWorktree,
|
||||
resolveTerminalFileLink,
|
||||
resolveTerminalFileLinkText,
|
||||
toWorktreeRelativePath
|
||||
resolveTerminalFileLinkText
|
||||
} from '@/lib/terminal-links'
|
||||
import { useAppStore } from '@/store'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import { absolutePathToFileUri } from '@/components/editor/markdown-internal-links'
|
||||
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
|
||||
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
|
||||
import { openHttpLink } from '@/lib/http-link-routing'
|
||||
import {
|
||||
isRemoteRuntimeFileOperation,
|
||||
runtimePathExists,
|
||||
statRuntimePath,
|
||||
type RuntimeFileOperationArgs
|
||||
} from '@/runtime/runtime-file-client'
|
||||
import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client'
|
||||
import { isRemoteRuntimeFileOperation, runtimePathExists } from '@/runtime/runtime-file-client'
|
||||
import { resolveTerminalFileUrlTarget } from './terminal-file-url-target'
|
||||
import {
|
||||
buildCandidateLogicalLinesForBufferPosition,
|
||||
dedupeLogicalLines,
|
||||
openFilePathLinkAtBufferPosition
|
||||
} from './terminal-file-link-hit-testing'
|
||||
import {
|
||||
getTerminalFileContext,
|
||||
isHtmlFilePath,
|
||||
openDetectedFilePath
|
||||
} from './terminal-file-open-routing'
|
||||
import {
|
||||
buildHardWrappedPathLogicalLineCandidates,
|
||||
buildWrappedLogicalLine,
|
||||
rangeForParsedFileLink,
|
||||
type WrappedLogicalLine
|
||||
} from './wrapped-terminal-link-ranges'
|
||||
|
||||
export { openDetectedFilePath } from './terminal-file-open-routing'
|
||||
export { openFilePathLinkAtBufferPosition } from './terminal-file-link-hit-testing'
|
||||
|
||||
export type LinkHandlerDeps = {
|
||||
worktreeId: string
|
||||
@@ -36,6 +42,11 @@ export type LinkHandlerDeps = {
|
||||
type TerminalLinkEvent = Pick<MouseEvent, 'metaKey' | 'ctrlKey'> &
|
||||
Partial<Pick<MouseEvent, 'shiftKey' | 'preventDefault' | 'stopPropagation'>>
|
||||
|
||||
type ProvidedFileLink = {
|
||||
link: ILink
|
||||
logicalLine: WrappedLogicalLine
|
||||
}
|
||||
|
||||
function isMacPlatform(): boolean {
|
||||
return navigator.userAgent.includes('Mac')
|
||||
}
|
||||
@@ -58,133 +69,6 @@ export function getTerminalUrlOpenHint(): string {
|
||||
: 'Ctrl+click to open or Shift+Ctrl+click for system browser'
|
||||
}
|
||||
|
||||
function isHtmlFilePath(filePath: string): boolean {
|
||||
return /\.html?$/i.test(filePath)
|
||||
}
|
||||
|
||||
function openHtmlFileInBrowser(filePath: string, worktreeId: string): void {
|
||||
const store = useAppStore.getState()
|
||||
if (worktreeId) {
|
||||
// Why: following an HTML file link changes which worktree is foregrounded,
|
||||
// so it must record a history visit before opening the browser tab.
|
||||
activateAndRevealWorktree(worktreeId)
|
||||
}
|
||||
const fileUrl = absolutePathToFileUri(filePath)
|
||||
const title = filePath.split(/[/\\]/).pop() ?? filePath
|
||||
store.createBrowserTab(worktreeId, fileUrl, { title, activate: true })
|
||||
}
|
||||
|
||||
function getTerminalFileContext(
|
||||
worktreeId: string,
|
||||
worktreePath: string,
|
||||
runtimeEnvironmentId?: string | null
|
||||
): RuntimeFileOperationArgs {
|
||||
const settings = useAppStore.getState().settings
|
||||
return {
|
||||
settings: settingsForRuntimeOwner(settings, runtimeEnvironmentId),
|
||||
worktreeId: worktreeId || null,
|
||||
worktreePath,
|
||||
connectionId: getConnectionId(worktreeId || null) ?? undefined
|
||||
}
|
||||
}
|
||||
|
||||
let latestOpenDetectedFilePathRequestId = 0
|
||||
|
||||
export function openDetectedFilePath(
|
||||
filePath: string,
|
||||
line: number | null,
|
||||
column: number | null,
|
||||
deps: Pick<LinkHandlerDeps, 'worktreeId' | 'worktreePath' | 'runtimeEnvironmentId'>
|
||||
): void {
|
||||
const { runtimeEnvironmentId, worktreeId, worktreePath } = deps
|
||||
const requestId = ++latestOpenDetectedFilePathRequestId
|
||||
|
||||
void (async () => {
|
||||
let statResult
|
||||
try {
|
||||
const fileContext = getTerminalFileContext(worktreeId, worktreePath, runtimeEnvironmentId)
|
||||
const isRemoteRuntimePath = isRemoteRuntimeFileOperation(fileContext, filePath)
|
||||
// Why: remote paths don't need local auth — the relay/runtime is the security boundary.
|
||||
if (!fileContext.connectionId && !isRemoteRuntimePath) {
|
||||
await window.api.fs.authorizeExternalPath({ targetPath: filePath })
|
||||
}
|
||||
statResult = await statRuntimePath(fileContext, filePath)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
if (requestId !== latestOpenDetectedFilePathRequestId) {
|
||||
return
|
||||
}
|
||||
|
||||
if (statResult.isDirectory) {
|
||||
const fileContext = getTerminalFileContext(worktreeId, worktreePath, runtimeEnvironmentId)
|
||||
if (fileContext.connectionId || isRemoteRuntimeFileOperation(fileContext, filePath)) {
|
||||
return
|
||||
}
|
||||
await window.api.shell.openFilePath(filePath)
|
||||
return
|
||||
}
|
||||
|
||||
// Why: .html/.htm files render in Orca's embedded browser instead of opening
|
||||
// as source in Monaco — ⌘/Ctrl+click on an HTML path in the terminal should
|
||||
// feel like clicking an http link and render the page, not dump HTML source.
|
||||
// Mirrors the editor's "Open Preview to the Side" action.
|
||||
const fileContext = getTerminalFileContext(worktreeId, worktreePath, runtimeEnvironmentId)
|
||||
if (
|
||||
isHtmlFilePath(filePath) &&
|
||||
!fileContext.connectionId &&
|
||||
!isRemoteRuntimeFileOperation(fileContext, filePath)
|
||||
) {
|
||||
openHtmlFileInBrowser(filePath, worktreeId)
|
||||
return
|
||||
}
|
||||
|
||||
let relativePath = filePath
|
||||
if (worktreePath && isPathInsideWorktree(filePath, worktreePath)) {
|
||||
const maybeRelative = toWorktreeRelativePath(filePath, worktreePath)
|
||||
if (maybeRelative !== null && maybeRelative.length > 0) {
|
||||
relativePath = maybeRelative
|
||||
}
|
||||
}
|
||||
|
||||
const store = useAppStore.getState()
|
||||
if (worktreeId) {
|
||||
// Why: terminal file links can jump across worktrees. Reusing the shared
|
||||
// activation path keeps those jumps in the same history stack as sidebar
|
||||
// and palette navigation before the editor opens the destination file.
|
||||
activateAndRevealWorktree(worktreeId)
|
||||
}
|
||||
|
||||
store.openFile({
|
||||
filePath,
|
||||
relativePath,
|
||||
worktreeId: worktreeId || '',
|
||||
language: detectLanguage(filePath),
|
||||
mode: 'edit',
|
||||
runtimeEnvironmentId
|
||||
})
|
||||
|
||||
if (line !== null) {
|
||||
const targetColumn = column ?? 1
|
||||
store.setPendingEditorReveal(null)
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (requestId !== latestOpenDetectedFilePathRequestId) {
|
||||
return
|
||||
}
|
||||
store.setPendingEditorReveal({
|
||||
filePath,
|
||||
line,
|
||||
column: targetColumn,
|
||||
matchLength: 0
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
export function createFilePathLinkProvider(
|
||||
paneId: number,
|
||||
deps: LinkHandlerDeps,
|
||||
@@ -200,88 +84,191 @@ export function createFilePathLinkProvider(
|
||||
return
|
||||
}
|
||||
|
||||
const bufferLine = pane.terminal.buffer.active.getLine(bufferLineNumber - 1)
|
||||
const lineText = bufferLine?.translateToString(true)
|
||||
if (!lineText) {
|
||||
const buffer = pane.terminal.buffer.active
|
||||
const softWrappedLogicalLine = buildWrappedLogicalLine(buffer, bufferLineNumber)
|
||||
if (!softWrappedLogicalLine?.text) {
|
||||
callback(undefined)
|
||||
return
|
||||
}
|
||||
|
||||
const fileLinks = extractTerminalFileLinks(lineText)
|
||||
if (fileLinks.length === 0) {
|
||||
const logicalLines = dedupeLogicalLines([
|
||||
...buildHardWrappedPathLogicalLineCandidates(buffer, bufferLineNumber),
|
||||
softWrappedLogicalLine
|
||||
])
|
||||
if (
|
||||
logicalLines.every((logicalLine) => extractTerminalFileLinks(logicalLine.text).length === 0)
|
||||
) {
|
||||
callback(undefined)
|
||||
return
|
||||
}
|
||||
|
||||
void Promise.all(
|
||||
fileLinks.map(async (parsed): Promise<ILink | null> => {
|
||||
const resolved = startupCwd ? resolveTerminalFileLink(parsed, startupCwd) : null
|
||||
if (!resolved) {
|
||||
return null
|
||||
}
|
||||
|
||||
const runtimeEnvironmentId =
|
||||
deps.getRuntimeEnvironmentIdForPane?.(paneId) ?? deps.runtimeEnvironmentId ?? null
|
||||
const cacheKey = `${runtimeEnvironmentId ?? 'active'}\0${resolved.absolutePath}`
|
||||
const cachedExists = pathExistsCache.get(cacheKey)
|
||||
const fileContext = getTerminalFileContext(worktreeId, worktreePath, runtimeEnvironmentId)
|
||||
const exists =
|
||||
cachedExists ??
|
||||
(fileContext.connectionId ||
|
||||
isRemoteRuntimeFileOperation(fileContext, resolved.absolutePath)
|
||||
? await runtimePathExists(fileContext, resolved.absolutePath)
|
||||
: await window.api.shell.pathExists(resolved.absolutePath))
|
||||
pathExistsCache.set(cacheKey, exists)
|
||||
if (!exists) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
range: {
|
||||
// Why: xterm's IBufferRange uses 1-based *inclusive* coords on
|
||||
// both ends (the hit-test is `x >= start.x && x <= end.x`),
|
||||
// but `parsed.endIndex` is the exclusive string-slice end.
|
||||
// Converting start = +1 but end = +0 maps correctly so the
|
||||
// underline stops on the last filename cell instead of bleeding
|
||||
// into the trailing whitespace of column-padded `ls` output.
|
||||
start: { x: parsed.startIndex + 1, y: bufferLineNumber },
|
||||
end: { x: parsed.endIndex, y: bufferLineNumber }
|
||||
},
|
||||
text: parsed.displayText,
|
||||
activate: (event) => {
|
||||
if (!isTerminalLinkActivation(event)) {
|
||||
return
|
||||
logicalLines.flatMap((logicalLine) =>
|
||||
extractTerminalFileLinks(logicalLine.text).map(
|
||||
async (parsed): Promise<ProvidedFileLink | null> => {
|
||||
const resolved = startupCwd ? resolveTerminalFileLink(parsed, startupCwd) : null
|
||||
if (!resolved) {
|
||||
return null
|
||||
}
|
||||
openDetectedFilePath(resolved.absolutePath, resolved.line, resolved.column, {
|
||||
const range = rangeForParsedFileLink(logicalLine, parsed.startIndex, parsed.endIndex)
|
||||
if (!range) {
|
||||
return null
|
||||
}
|
||||
|
||||
const runtimeEnvironmentId =
|
||||
deps.getRuntimeEnvironmentIdForPane?.(paneId) ?? deps.runtimeEnvironmentId ?? null
|
||||
const cacheKey = `${runtimeEnvironmentId ?? 'active'}\0${resolved.absolutePath}`
|
||||
const cachedExists = pathExistsCache.get(cacheKey)
|
||||
const fileContext = getTerminalFileContext(
|
||||
worktreeId,
|
||||
worktreePath,
|
||||
runtimeEnvironmentId
|
||||
})
|
||||
},
|
||||
hover: () => {
|
||||
// Why: HTML files get a distinct hint because ⌘/Ctrl+click opens
|
||||
// them rendered in the embedded browser, not as source in the
|
||||
// editor — parallels the "open in system browser" affordance
|
||||
// shown for http URLs.
|
||||
const hint = isHtmlFilePath(resolved.absolutePath)
|
||||
? getTerminalHtmlFileOpenHint()
|
||||
: openLinkHint
|
||||
linkTooltip.textContent = `${resolved.absolutePath} (${hint})`
|
||||
linkTooltip.style.display = ''
|
||||
},
|
||||
leave: () => {
|
||||
linkTooltip.style.display = 'none'
|
||||
)
|
||||
const exists =
|
||||
cachedExists ??
|
||||
(fileContext.connectionId ||
|
||||
isRemoteRuntimeFileOperation(fileContext, resolved.absolutePath)
|
||||
? await runtimePathExists(fileContext, resolved.absolutePath)
|
||||
: await window.api.shell.pathExists(resolved.absolutePath))
|
||||
pathExistsCache.set(cacheKey, exists)
|
||||
if (!exists) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
logicalLine,
|
||||
link: {
|
||||
range,
|
||||
text: parsed.displayText,
|
||||
activate: (event) => {
|
||||
if (!isTerminalLinkActivation(event)) {
|
||||
return
|
||||
}
|
||||
openDetectedFilePath(resolved.absolutePath, resolved.line, resolved.column, {
|
||||
worktreeId,
|
||||
worktreePath,
|
||||
runtimeEnvironmentId
|
||||
})
|
||||
},
|
||||
hover: () => {
|
||||
// Why: HTML files get a distinct hint because ⌘/Ctrl+click opens
|
||||
// them rendered in the embedded browser, not as source in the
|
||||
// editor — parallels the "open in system browser" affordance
|
||||
// shown for http URLs.
|
||||
const hint = isHtmlFilePath(resolved.absolutePath)
|
||||
? getTerminalHtmlFileOpenHint()
|
||||
: openLinkHint
|
||||
linkTooltip.textContent = `${resolved.absolutePath} (${hint})`
|
||||
linkTooltip.style.display = ''
|
||||
},
|
||||
leave: () => {
|
||||
linkTooltip.style.display = 'none'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
)
|
||||
).then((resolvedLinks) => {
|
||||
const links = resolvedLinks.filter((link): link is ILink => link !== null)
|
||||
const latestFingerprints = new Set(
|
||||
buildCandidateLogicalLinesForBufferPosition(buffer, bufferLineNumber).map(
|
||||
(logicalLine) => logicalLine.fingerprint
|
||||
)
|
||||
)
|
||||
const providedLinks = resolvedLinks.filter(
|
||||
(link): link is ProvidedFileLink => link !== null
|
||||
)
|
||||
const links = providedLinks
|
||||
.filter(({ logicalLine }) => latestFingerprints.has(logicalLine.fingerprint))
|
||||
.map(({ link }) => link)
|
||||
if (providedLinks.length > 0 && links.length === 0) {
|
||||
return
|
||||
}
|
||||
callback(links.length > 0 ? links : undefined)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getTerminalScreenElement(terminal: Terminal): HTMLElement | null {
|
||||
return terminal.element?.querySelector('.xterm-screen') ?? null
|
||||
}
|
||||
|
||||
function getBufferPositionForTerminalMouseEvent(
|
||||
terminal: Terminal,
|
||||
event: MouseEvent
|
||||
): { x: number; y: number } | null {
|
||||
const screenElement = getTerminalScreenElement(terminal)
|
||||
if (!screenElement || terminal.cols <= 0 || terminal.rows <= 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const rect = screenElement.getBoundingClientRect()
|
||||
const relativeX = event.clientX - rect.left
|
||||
const relativeY = event.clientY - rect.top
|
||||
if (relativeX < 0 || relativeY < 0 || relativeX >= rect.width || relativeY >= rect.height) {
|
||||
return null
|
||||
}
|
||||
|
||||
const cellWidth = rect.width / terminal.cols
|
||||
const cellHeight = rect.height / terminal.rows
|
||||
if (cellWidth <= 0 || cellHeight <= 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
x: Math.floor(relativeX / cellWidth) + 1,
|
||||
y: Math.floor(relativeY / cellHeight) + terminal.buffer.active.viewportY + 1
|
||||
}
|
||||
}
|
||||
|
||||
export function installFilePathLinkClickFallback(
|
||||
paneId: number,
|
||||
terminal: Terminal,
|
||||
deps: LinkHandlerDeps
|
||||
): IDisposable {
|
||||
const mouseUpListenerOptions = { capture: true }
|
||||
const handleMouseUp = (event: MouseEvent): void => {
|
||||
if (event.button !== 0 || !isTerminalLinkActivation(event)) {
|
||||
return
|
||||
}
|
||||
|
||||
const position = getBufferPositionForTerminalMouseEvent(terminal, event)
|
||||
if (!position) {
|
||||
return
|
||||
}
|
||||
const runtimeEnvironmentId =
|
||||
deps.getRuntimeEnvironmentIdForPane?.(paneId) ?? deps.runtimeEnvironmentId ?? null
|
||||
// Why: xterm can show a wrapped provider link as active while still missing
|
||||
// activation for the clicked wrapped row. Always retry file-path hit testing
|
||||
// on modifier mouseup; openDetectedFilePath coalesces duplicate opens.
|
||||
const opened = openFilePathLinkAtBufferPosition(
|
||||
terminal.buffer.active,
|
||||
position,
|
||||
terminal.cols,
|
||||
{
|
||||
startupCwd: deps.startupCwd,
|
||||
worktreeId: deps.worktreeId,
|
||||
worktreePath: deps.worktreePath,
|
||||
runtimeEnvironmentId
|
||||
}
|
||||
)
|
||||
if (opened) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
terminal.clearSelection()
|
||||
}
|
||||
}
|
||||
|
||||
const terminalElement = terminal.element
|
||||
terminalElement?.addEventListener('mouseup', handleMouseUp, mouseUpListenerOptions)
|
||||
return {
|
||||
dispose: () => {
|
||||
terminalElement?.removeEventListener('mouseup', handleMouseUp, mouseUpListenerOptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function isTerminalLinkActivation(
|
||||
event: Pick<MouseEvent, 'metaKey' | 'ctrlKey'> | undefined
|
||||
): boolean {
|
||||
|
||||
@@ -9,7 +9,8 @@ import {
|
||||
createFilePathLinkProvider,
|
||||
getTerminalFileOpenHint,
|
||||
getTerminalUrlOpenHint,
|
||||
handleOscLink
|
||||
handleOscLink,
|
||||
installFilePathLinkClickFallback
|
||||
} from './terminal-link-handlers'
|
||||
import type { LinkHandlerDeps } from './terminal-link-handlers'
|
||||
import type {
|
||||
@@ -271,6 +272,7 @@ export function useTerminalPaneLifecycle({
|
||||
const systemPrefersDarkRef = useRef(systemPrefersDark)
|
||||
systemPrefersDarkRef.current = systemPrefersDark
|
||||
const linkProviderDisposablesRef = useRef(new Map<number, IDisposable>())
|
||||
const fileLinkClickFallbackDisposablesRef = useRef(new Map<number, IDisposable>())
|
||||
// Why: read settingsRef at fire time so toggling "copy on select" takes
|
||||
// effect without recreating panes.
|
||||
const selectionDisposablesRef = useRef(new Map<number, IDisposable>())
|
||||
@@ -338,6 +340,7 @@ export function useTerminalPaneLifecycle({
|
||||
const paneTransports = paneTransportsRef.current
|
||||
const panePtyBindings = panePtyBindingsRef.current
|
||||
const linkDisposables = linkProviderDisposablesRef.current
|
||||
const fileLinkClickFallbackDisposables = fileLinkClickFallbackDisposablesRef.current
|
||||
const selectionDisposables = selectionDisposablesRef.current
|
||||
const selectionCaptureTimers = selectionCaptureTimersRef.current
|
||||
const mouseHideDisposables = mouseHideDisposablesRef.current
|
||||
@@ -349,6 +352,9 @@ export function useTerminalPaneLifecycle({
|
||||
cwd ??
|
||||
''
|
||||
const startupCwd = cwd ?? worktreePath
|
||||
// Why: existence probes can cross SSH/runtime boundaries. This cache is
|
||||
// lifecycle-scoped, so external mutations and the initial 'active' runtime
|
||||
// fallback can temporarily leave stale entries.
|
||||
const pathExistsCache = new Map<string, boolean>()
|
||||
const linkDeps: LinkHandlerDeps = {
|
||||
worktreeId,
|
||||
@@ -534,6 +540,12 @@ export function useTerminalPaneLifecycle({
|
||||
createFilePathLinkProvider(pane.id, linkDeps, pane.linkTooltip, fileOpenLinkHint)
|
||||
)
|
||||
linkProviderDisposablesRef.current.set(pane.id, linkProviderDisposable)
|
||||
const fileLinkClickFallbackDisposable = installFilePathLinkClickFallback(
|
||||
pane.id,
|
||||
pane.terminal,
|
||||
linkDeps
|
||||
)
|
||||
fileLinkClickFallbackDisposablesRef.current.set(pane.id, fileLinkClickFallbackDisposable)
|
||||
// Why: skip empty selections so clicking to deselect doesn't clobber
|
||||
// whatever the user last copied elsewhere.
|
||||
const selectionDisposable = pane.terminal.onSelectionChange(() => {
|
||||
@@ -660,6 +672,12 @@ export function useTerminalPaneLifecycle({
|
||||
linkProviderDisposable.dispose()
|
||||
linkProviderDisposablesRef.current.delete(paneId)
|
||||
}
|
||||
const fileLinkClickFallbackDisposable =
|
||||
fileLinkClickFallbackDisposablesRef.current.get(paneId)
|
||||
if (fileLinkClickFallbackDisposable) {
|
||||
fileLinkClickFallbackDisposable.dispose()
|
||||
fileLinkClickFallbackDisposablesRef.current.delete(paneId)
|
||||
}
|
||||
const selectionDisposable = selectionDisposablesRef.current.get(paneId)
|
||||
if (selectionDisposable) {
|
||||
selectionDisposable.dispose()
|
||||
@@ -1066,6 +1084,10 @@ export function useTerminalPaneLifecycle({
|
||||
disposable.dispose()
|
||||
}
|
||||
linkDisposables.clear()
|
||||
for (const disposable of fileLinkClickFallbackDisposables.values()) {
|
||||
disposable.dispose()
|
||||
}
|
||||
fileLinkClickFallbackDisposables.clear()
|
||||
for (const disposable of selectionDisposables.values()) {
|
||||
disposable.dispose()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import type { IBufferLine, IBufferRange } from '@xterm/xterm'
|
||||
|
||||
type TerminalBufferLineWithColumns = IBufferLine & {
|
||||
translateToString(
|
||||
trimRight?: boolean,
|
||||
startColumn?: number,
|
||||
endColumn?: number,
|
||||
outColumns?: number[]
|
||||
): string
|
||||
}
|
||||
|
||||
type WrappedLogicalRow = {
|
||||
y: number
|
||||
text: string
|
||||
columns: number[]
|
||||
startIndex: number
|
||||
isWrapped: boolean
|
||||
lineLength: number
|
||||
}
|
||||
|
||||
export type WrappedLogicalLine = {
|
||||
text: string
|
||||
rows: WrappedLogicalRow[]
|
||||
fingerprint: string
|
||||
}
|
||||
|
||||
function translateLineWithCells(line: IBufferLine): { text: string; columns: number[] } | null {
|
||||
let text = ''
|
||||
const columns: number[] = []
|
||||
let endColumn = 0
|
||||
|
||||
for (let x = 0; x < line.length; x++) {
|
||||
const cell = line.getCell(x)
|
||||
if (!cell) {
|
||||
return null
|
||||
}
|
||||
|
||||
const width = cell.getWidth()
|
||||
if (width === 0) {
|
||||
continue
|
||||
}
|
||||
|
||||
const chars = cell.getChars() || ' '
|
||||
text += chars
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
columns.push(x)
|
||||
}
|
||||
endColumn = x + Math.max(width, 1)
|
||||
}
|
||||
|
||||
columns.push(endColumn)
|
||||
return { text, columns }
|
||||
}
|
||||
|
||||
function translateLineWithColumns(line: IBufferLine): { text: string; columns: number[] } {
|
||||
const columns: number[] = []
|
||||
const text = (line as TerminalBufferLineWithColumns).translateToString(
|
||||
false,
|
||||
0,
|
||||
undefined,
|
||||
columns
|
||||
)
|
||||
|
||||
if (columns.length === text.length + 1) {
|
||||
return { text, columns }
|
||||
}
|
||||
|
||||
const cellTranslation = translateLineWithCells(line)
|
||||
if (cellTranslation) {
|
||||
return cellTranslation
|
||||
}
|
||||
|
||||
return {
|
||||
text,
|
||||
columns: Array.from({ length: text.length + 1 }, (_value, index) => index)
|
||||
}
|
||||
}
|
||||
|
||||
function trimHardWrappedPathRow(line: IBufferLine): { text: string; columns: number[] } | null {
|
||||
const translated = translateLineWithColumns(line)
|
||||
const startIndex = translated.text.search(/\S/)
|
||||
if (startIndex === -1) {
|
||||
return null
|
||||
}
|
||||
|
||||
let endIndex = translated.text.length
|
||||
while (endIndex > startIndex && /\s/.test(translated.text[endIndex - 1])) {
|
||||
endIndex--
|
||||
}
|
||||
|
||||
return {
|
||||
text: translated.text.slice(startIndex, endIndex),
|
||||
columns: translated.columns.slice(startIndex, endIndex + 1)
|
||||
}
|
||||
}
|
||||
|
||||
const HARD_WRAPPED_PATH_FRAGMENT_PATTERN = /^[A-Za-z0-9._~@%+=:,/\\-]+$/
|
||||
|
||||
function isHardWrappedPathFragment(text: string): boolean {
|
||||
return HARD_WRAPPED_PATH_FRAGMENT_PATTERN.test(text) && /[A-Za-z0-9]/.test(text)
|
||||
}
|
||||
|
||||
function canStartHardWrappedPath(text: string): boolean {
|
||||
if (!isHardWrappedPathFragment(text)) {
|
||||
return /(?:^|[\s•*>-])(?:\/|\.{1,2}\/|[A-Za-z0-9._-]+\/)[A-Za-z0-9._~@%+=:,/\\-]*$/.test(text)
|
||||
}
|
||||
|
||||
return /(?:\/|\\)/.test(text)
|
||||
}
|
||||
|
||||
export function buildWrappedLogicalLine(
|
||||
buffer: { getLine(y: number): IBufferLine | undefined },
|
||||
bufferLineNumber: number
|
||||
): WrappedLogicalLine | null {
|
||||
const y = bufferLineNumber - 1
|
||||
if (!buffer.getLine(y)) {
|
||||
return null
|
||||
}
|
||||
|
||||
let startY = y
|
||||
while (startY > 0 && buffer.getLine(startY)?.isWrapped) {
|
||||
startY--
|
||||
}
|
||||
|
||||
let endY = y
|
||||
while (buffer.getLine(endY + 1)?.isWrapped) {
|
||||
endY++
|
||||
}
|
||||
|
||||
let text = ''
|
||||
const rows: WrappedLogicalRow[] = []
|
||||
for (let rowY = startY; rowY <= endY; rowY++) {
|
||||
const line = buffer.getLine(rowY)
|
||||
if (!line) {
|
||||
return null
|
||||
}
|
||||
const translated = translateLineWithColumns(line)
|
||||
rows.push({
|
||||
y: rowY,
|
||||
text: translated.text,
|
||||
columns: translated.columns,
|
||||
startIndex: text.length,
|
||||
isWrapped: line.isWrapped,
|
||||
lineLength: line.length
|
||||
})
|
||||
text += translated.text
|
||||
}
|
||||
|
||||
const fingerprint = rows
|
||||
.map((row) => `${row.y}:${row.isWrapped ? 1 : 0}:${row.lineLength}:${row.text}`)
|
||||
.join('\n')
|
||||
return { text, rows, fingerprint }
|
||||
}
|
||||
|
||||
export function buildHardWrappedPathLogicalLineCandidates(
|
||||
buffer: { getLine(y: number): IBufferLine | undefined },
|
||||
bufferLineNumber: number,
|
||||
maxRows = 20
|
||||
): WrappedLogicalLine[] {
|
||||
// Why: agent TUIs may hard-wrap long paths into separate terminal rows, so
|
||||
// xterm's isWrapped metadata is absent even though the visible path continues.
|
||||
const currentY = bufferLineNumber - 1
|
||||
if (!buffer.getLine(currentY)) {
|
||||
return []
|
||||
}
|
||||
|
||||
const minY = Math.max(0, currentY - maxRows + 1)
|
||||
const candidates: WrappedLogicalLine[] = []
|
||||
for (let startY = currentY; startY >= minY; startY--) {
|
||||
const startLine = buffer.getLine(startY)
|
||||
const start = startLine ? trimHardWrappedPathRow(startLine) : null
|
||||
if (!start || !canStartHardWrappedPath(start.text)) {
|
||||
continue
|
||||
}
|
||||
|
||||
let text = ''
|
||||
const rows: WrappedLogicalRow[] = []
|
||||
for (let rowY = startY; rowY < startY + maxRows; rowY++) {
|
||||
const line = buffer.getLine(rowY)
|
||||
const translated = line ? trimHardWrappedPathRow(line) : null
|
||||
if (!translated) {
|
||||
break
|
||||
}
|
||||
if (rowY > startY && !isHardWrappedPathFragment(translated.text)) {
|
||||
break
|
||||
}
|
||||
|
||||
rows.push({
|
||||
y: rowY,
|
||||
text: translated.text,
|
||||
columns: translated.columns,
|
||||
startIndex: text.length,
|
||||
isWrapped: line?.isWrapped ?? false,
|
||||
lineLength: line?.length ?? translated.text.length
|
||||
})
|
||||
text += translated.text
|
||||
|
||||
if (rowY >= currentY) {
|
||||
const fingerprint = rows
|
||||
.map((row) => `${row.y}:${row.isWrapped ? 1 : 0}:${row.lineLength}:${row.text}`)
|
||||
.join('\n')
|
||||
candidates.push({ text, rows: [...rows], fingerprint })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return candidates.sort((left, right) => right.rows.length - left.rows.length)
|
||||
}
|
||||
|
||||
function mapLogicalIndexToBufferPosition(
|
||||
logicalLine: WrappedLogicalLine,
|
||||
index: number,
|
||||
bias: 'start' | 'end'
|
||||
): { x: number; y: number } | null {
|
||||
for (let rowIndex = 0; rowIndex < logicalLine.rows.length; rowIndex++) {
|
||||
const row = logicalLine.rows[rowIndex]
|
||||
const rowStart = row.startIndex
|
||||
const rowEnd = rowStart + row.text.length
|
||||
const isTarget =
|
||||
bias === 'start'
|
||||
? index < rowEnd || (index === rowEnd && rowIndex === logicalLine.rows.length - 1)
|
||||
: index <= rowEnd && (index > rowStart || rowIndex === 0)
|
||||
|
||||
if (!isTarget) {
|
||||
continue
|
||||
}
|
||||
|
||||
const localIndex = Math.max(0, Math.min(index - rowStart, row.columns.length - 1))
|
||||
const column = row.columns[localIndex] ?? localIndex
|
||||
return { x: column, y: row.y + 1 }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function rangeForParsedFileLink(
|
||||
logicalLine: WrappedLogicalLine,
|
||||
startIndex: number,
|
||||
endIndex: number
|
||||
): IBufferRange | null {
|
||||
const start = mapLogicalIndexToBufferPosition(logicalLine, startIndex, 'start')
|
||||
const end = mapLogicalIndexToBufferPosition(logicalLine, endIndex, 'end')
|
||||
if (!start || !end) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
// Why: xterm's link hit-test uses 1-based inclusive coordinates, while
|
||||
// parsed file links use zero-based half-open string indexes.
|
||||
start: { x: start.x + 1, y: start.y },
|
||||
end: { x: end.x, y: end.y }
|
||||
}
|
||||
}
|
||||
@@ -188,7 +188,10 @@ export function isFloatingWorkspaceTerminalInputTarget(target: EventTarget | nul
|
||||
if (target.closest(FLOATING_WORKSPACE_PANEL_SELECTOR) === null) {
|
||||
return false
|
||||
}
|
||||
return target.classList.contains('xterm-helper-textarea') || target.closest('.xterm') !== null
|
||||
return (
|
||||
target.classList?.contains('xterm-helper-textarea') === true ||
|
||||
target.closest('.xterm') !== null
|
||||
)
|
||||
}
|
||||
|
||||
export function shouldMinimizeFloatingWorkspacePanelOnCloseShortcut({
|
||||
|
||||
Reference in New Issue
Block a user