Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import {
openDetectedFilePath,
terminalLinkWslDistro
} from './terminal-file-open-routing'
import { getTerminalPathExistsCacheKey } from './terminal-path-exists-cache'
import { createTerminalPathExistenceBatch } from './terminal-path-existence-batch'
import {
getTerminalPathExistsCacheKey,
writeTerminalPathExistsCache
} from './terminal-path-exists-cache'
import { resolveKnownWorktreeRootPathLink } from './terminal-worktree-path-link'
import {
buildHardWrappedPathLogicalLineCandidates,
Expand Down Expand Up @@ -38,15 +42,22 @@ export function openFilePathLinkAtBufferPosition(
return false
}

const fileContext = getTerminalFileContext(
deps.worktreeId,
deps.worktreePath,
deps.runtimeEnvironmentId
)
const matches: {
absolutePath: string
line: number | null
column: number | null
pathText: string
cacheKey: string
isRemoteRuntimePath: boolean
cachedExists: boolean | undefined
isKnownWorktreeRoot: boolean
}[] = []
for (const logicalLine of logicalLines) {
const matches: {
absolutePath: string
line: number | null
column: number | null
pathText: string
cachedExists: boolean | undefined
isKnownWorktreeRoot: boolean
}[] = []
for (const parsed of extractTerminalFileLinkCandidates(logicalLine.text)) {
const resolved = deps.startupCwd
? resolveTerminalFileLink(parsed, deps.startupCwd, deps.terminalHomePath)
Expand All @@ -58,20 +69,16 @@ export function openFilePathLinkAtBufferPosition(
if (!range || !rangeContainsBufferPosition(range, position, terminalColumns)) {
continue
}
const fileContext = getTerminalFileContext(
deps.worktreeId,
deps.worktreePath,
deps.runtimeEnvironmentId
)
const mappedPath = mapTerminalFilePath(
resolved.absolutePath,
deps.worktreePath,
terminalLinkWslDistro(deps.wslDistro, deps.runtimeEnvironmentId)
)
const isRemoteRuntimePath = isRemoteRuntimeFileOperation(fileContext, mappedPath)
const cacheKey = getTerminalPathExistsCacheKey({
absolutePath: mappedPath,
connectionId: fileContext.connectionId,
isRemoteRuntimePath: isRemoteRuntimeFileOperation(fileContext, mappedPath),
isRemoteRuntimePath,
runtimeEnvironmentId: deps.runtimeEnvironmentId
})
const isKnownWorktreeRoot = Boolean(resolveKnownWorktreeRootPathLink(mappedPath))
Expand All @@ -83,29 +90,76 @@ export function openFilePathLinkAtBufferPosition(
line: resolved.line,
column: resolved.column,
pathText: parsed.pathText,
cacheKey,
isRemoteRuntimePath,
cachedExists: deps.pathExistsCache?.get(cacheKey),
isKnownWorktreeRoot
})
}
}

const cachedMatch = matches
.filter((match) => match.cachedExists)
.sort((a, b) => b.pathText.length - a.pathText.length)[0]
const knownWorktreeRootMatch = matches
.filter((match) => match.isKnownWorktreeRoot)
.sort((a, b) => b.pathText.length - a.pathText.length)[0]
const uncachedMatch = matches.find((match) => match.cachedExists !== false)
const match = cachedMatch ?? knownWorktreeRootMatch ?? uncachedMatch
if (match) {
openDetectedFilePath(match.absolutePath, match.line, match.column, {
...deps,
openWithSystemDefault: deps.openWithSystemDefault === true
})
return true
}
const openMatch = (match: (typeof matches)[number]): void => {
openDetectedFilePath(match.absolutePath, match.line, match.column, {
...deps,
openWithSystemDefault: deps.openWithSystemDefault === true
})
}
const byLongestPath = (a: (typeof matches)[number], b: (typeof matches)[number]): number =>
b.pathText.length - a.pathText.length
const cachedMatch = matches.filter((match) => match.cachedExists).sort(byLongestPath)[0]
const knownWorktreeRootMatch = matches
.filter((match) => match.isKnownWorktreeRoot)
.sort(byLongestPath)[0]
const match = cachedMatch ?? knownWorktreeRootMatch
if (match) {
openMatch(match)
return true
}

return false
const uncached = matches.filter(
(candidate, index) =>
candidate.cachedExists === undefined &&
matches.findIndex((other) => other.absolutePath === candidate.absolutePath) === index
)
if (uncached.length === 0) {
return false
}
if (uncached.length === 1) {
openMatch(uncached[0])
return true
}

// Why: hard-wrap joining can offer a real single-row path alongside a bogus
// path glued to the next row; opening the first unprobed guess fails silently
// when the hover probe has not answered yet, so probe them all first.
const pathExists = createTerminalPathExistenceBatch()
void Promise.all(
uncached.map(async (candidate) => {
const exists = await pathExists(
fileContext,
candidate.absolutePath,
candidate.isRemoteRuntimePath
)
if (deps.pathExistsCache) {
writeTerminalPathExistsCache(deps.pathExistsCache, candidate.cacheKey, exists)
}
return exists ? candidate : null
})
).then(
(probed) => {
const existing = probed
.filter((candidate): candidate is (typeof matches)[number] => candidate !== null)
.sort(byLongestPath)[0]
if (existing) {
openMatch(existing)
}
},
() => {
// Why: a lost host connection is not evidence the file is missing; the
// click simply does nothing rather than opening a guessed path.
}
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return true
}

export function buildCandidateLogicalLinesForBufferPosition(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,42 @@ describe('createFilePathLinkProvider range bounds', () => {
expect(openFilePathMock).not.toHaveBeenCalled()
})

it('probes before opening when a next-row prompt offers a glued path guess', async () => {
setPlatform('Macintosh')
vi.mocked(window.api.shell.pathExists).mockImplementation(
async (path: string) => path === '/root/.claude/settings.json'
)
const pathExistsCache = new Map<string, boolean>()

const opened = openFilePathLinkAtBufferPosition(
makeBuffer([
makeBufferLine('/root/.claude/settings.json'),
makeBufferLine('root@ubuntu:/mnt/data/sniper_eco_paper_final# ')
]),
{ x: 8, y: 1 },
80,
{
startupCwd: '/mnt/data/sniper_eco_paper_final',
worktreeId: 'wt-1',
worktreePath: '/mnt/data/sniper_eco_paper_final',
runtimeEnvironmentId: null,
pathExistsCache
}
)
await flushAsyncWork()

expect(opened).toBe(true)
expect(window.api.shell.pathExists).toHaveBeenCalledWith(
'/root/.claude/settings.jsonroot@ubuntu'
)
expect(openFileMock).toHaveBeenCalledTimes(1)
expect(openFileMock).toHaveBeenCalledWith(
expect.objectContaining({ filePath: '/root/.claude/settings.json' }),
{ forceContentReload: true }
)
expect(pathExistsCache.get('active\0/root/.claude/settings.jsonroot@ubuntu')).toBe(false)
})

it('does not open an unknown trailing-slash directory from direct fallback', async () => {
setPlatform('Macintosh')

Expand Down
46 changes: 46 additions & 0 deletions src/renderer/src/lib/terminal-file-link-detection-ranges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,52 @@ export function* detectTerminalFileLinkRanges(
}
}

// Why: the broad spaced-path scan runs to line end, so a shell prompt cwd or
// `cp /a/b /c/d` swallows every later path into one nonexistent candidate.
// Whitespace followed by an explicit root/relative/drive prefix always starts a
// new path (`Foo Bar/file` is not one, so spaced folder names stay whole).
const SPACED_PATH_NEXT_START_PATTERN = /\s(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/])/g

export function splitSpacedPathRangeAtNextPathStart(
range: DetectedTerminalFileLinkRange
): DetectedTerminalFileLinkRange[] {
const ranges: DetectedTerminalFileLinkRange[] = []
let start = 0
for (const match of range.text.matchAll(SPACED_PATH_NEXT_START_PATTERN)) {
const end = match.index ?? 0
if (end > start) {
ranges.push({
text: range.text.slice(start, end),
startIndex: range.startIndex + start,
endIndex: range.startIndex + end
})
}
start = end + 1
}
if (start === 0) {
return [range]
}
if (start < range.text.length) {
ranges.push({
text: range.text.slice(start),
startIndex: range.startIndex + start,
endIndex: range.endIndex
})
}
return ranges
}

export function trimTerminalFileLinkRangeEnd(
range: DetectedTerminalFileLinkRange
): DetectedTerminalFileLinkRange {
const text = range.text.trimEnd()
return {
text,
startIndex: range.startIndex,
endIndex: range.startIndex + text.length
}
}

export function mergeTerminalFileLinkRanges(ranges: [number, number][]): [number, number][] {
if (ranges.length <= 1) {
return ranges
Expand Down
12 changes: 12 additions & 0 deletions src/renderer/src/lib/terminal-links.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,18 @@ describe('terminal path helpers', () => {
})
})

it('links a path typed after a prompt whose cwd is also a path', () => {
const links = extractTerminalFileLinks(
'root@ubuntu:/mnt/data/sniper_eco_paper_final# echo /root/.claude/settings.json'
)
expect(links.map((link) => link.pathText)).toContain('/root/.claude/settings.json')
})

it('links every extensionless path in a multi-argument command', () => {
const links = extractTerminalFileLinks('cp /a/b /c/d')
expect(links.map((link) => link.pathText)).toEqual(['/a/b', '/c/d'])
})

it('does not treat mid-line command arguments as line-ending spaced paths', () => {
const links = extractTerminalFileLinks('run /usr/bin/env node, then continue')
expect(links.map((link) => link.pathText)).not.toContain('/usr/bin/env node')
Expand Down
19 changes: 6 additions & 13 deletions src/renderer/src/lib/terminal-links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import {
detectTerminalFileLinkRanges,
insertTerminalFileLinkClaimedRange,
mergeTerminalFileLinkRanges,
splitSpacedPathRangeAtNextPathStart,
terminalFileLinkRangesOverlap,
toParsedTerminalFileLink,
trimTerminalFileLinkRangeEnd,
type DetectedTerminalFileLinkRange
} from './terminal-file-link-detection-ranges'
import { detectTerminalFileUriLinks } from './terminal-file-uri-link'
Expand Down Expand Up @@ -157,17 +159,6 @@ function trimSpacedPathTrailingProse(
}
}

function trimTrailingWhitespace(
range: DetectedTerminalFileLinkRange
): DetectedTerminalFileLinkRange {
const text = range.text.trimEnd()
return {
text,
startIndex: range.startIndex,
endIndex: range.startIndex + text.length
}
}

function buildLineEndingSpacedPathPrefixRanges(
range: DetectedTerminalFileLinkRange
): DetectedTerminalFileLinkRange[] {
Expand Down Expand Up @@ -230,7 +221,9 @@ function detectSpacedLocalPathLinks(
const links: ParsedTerminalFileLink[] = []
const claimedRanges: [number, number][] = []
for (const regex of SPACED_LOCAL_PATH_REGEXES) {
for (const range of detectTerminalFileLinkRanges(lineText, regex)) {
for (const range of Array.from(detectTerminalFileLinkRanges(lineText, regex)).flatMap(
splitSpacedPathRangeAtNextPathStart
)) {
if (regex === SPACED_PATH_WITH_SEPARATOR_REGEX && !hasSeparatorAfterWhitespace(range.text)) {
continue
}
Expand All @@ -257,7 +250,7 @@ function detectSpacedLocalPathLinks(
const candidateLinks = candidateRanges
.map((candidateRange) =>
toParsedTerminalFileLink(
trimSpacedPathTrailingProse(trimTrailingWhitespace(candidateRange))
trimSpacedPathTrailingProse(trimTerminalFileLinkRangeEnd(candidateRange))
)
)
.filter((link): link is ParsedTerminalFileLink => link !== null)
Expand Down
Loading