fix(tab-bar): open absolute local paths from worktree tab create entry (#10222)

* fix(tab-bar): open absolute local paths from worktree tab create entry

Local worktrees can paste absolute file paths into tab create; remote and
SSH workspaces stay blocked. Harden classifier ordering, ownership gating,
and render-time fail-closed behavior from review.

* fix(tab-bar): restore typecheck after worktree path refactor

Add the missing editor file-operation import, finish the global file
drop relative-path helper migration, and align the runtime env test mock.

* fix(tab-bar): fail closed for absolute local paths

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
Trevin Chow
2026-07-23 23:26:39 -07:00
committed by GitHub
co-authored by OrcaWin
parent 462020d372
commit bd45d705bf
16 changed files with 1024 additions and 37 deletions
@@ -10,7 +10,9 @@ import type { TabAgentLaunchOption } from './tab-agent-launch-options'
// keyboard behavior under test only needs a controllable option list.
const entryOptionsMock = vi.hoisted(() => ({ options: [] as TabEntryOption[] }))
vi.mock('./tab-create-entry-action', () => ({
getTabEntryOptions: () => entryOptionsMock.options
getTabEntryOptions: () => entryOptionsMock.options,
createTabEntryAllowAbsolutePathsSelector: () => () => true,
isTabEntryAbsolutePathLike: () => false
}))
vi.mock('../quick-open-file-list', () => ({
useRuntimeFileListForWorktree: () => ({ files: [], loading: false, loadError: null })
@@ -1,7 +1,12 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Input } from '@/components/ui/input'
import { useRuntimeFileListForWorktree } from '../quick-open-file-list'
import { getTabEntryOptions, type TabCreateEntryArgs } from './tab-create-entry-action'
import {
createTabEntryAllowAbsolutePathsSelector,
getTabEntryOptions,
isTabEntryAbsolutePathLike,
type TabCreateEntryArgs
} from './tab-create-entry-action'
import {
findMatchingTabAgentLaunchOptions,
type TabAgentLaunchOption
@@ -23,6 +28,8 @@ import {
} from './TabBarCreateEntryRow'
import type { TuiAgent } from '../../../../shared/types'
import { translate } from '@/i18n/i18n'
import { getRendererAppPlatform } from '@/lib/renderer-app-platform'
import { useAppStore } from '@/store'
const EMPTY_AGENT_OPTIONS: readonly TabAgentLaunchOption[] = []
const EMPTY_MENU_OPTIONS: readonly TabCreateMenuOption[] = []
@@ -62,6 +69,16 @@ export default function TabBarCreateEntry({
const [lastMenuOpen, setLastMenuOpen] = useState(menuOpen)
const inputRef = useRef<HTMLInputElement>(null)
const fileList = useRuntimeFileListForWorktree({ enabled: menuOpen, worktreeId })
const shouldResolveAbsolutePaths = menuOpen && isTabEntryAbsolutePathLike(query.trim())
const allowAbsolutePathsSelector = useMemo(
() =>
createTabEntryAllowAbsolutePathsSelector(worktreeId, {
skip: !shouldResolveAbsolutePaths
}),
[shouldResolveAbsolutePaths, worktreeId]
)
const allowAbsolutePaths = useAppStore(allowAbsolutePathsSelector)
const localPlatform = getRendererAppPlatform() === 'win32' ? 'windows' : 'posix'
// Why: once ArrowDown moves focus into the static menu list, ArrowUp on the
// first item should return to the search box so the keyboard trip isn't
@@ -105,13 +122,16 @@ export default function TabBarCreateEntry({
[menuOptions, query]
)
const options = useMemo(() => {
const entryOptions = getTabEntryOptions(query, fileList)
const entryOptions = getTabEntryOptions(query, fileList, 4, {
allowAbsolutePaths,
localPlatform
})
if (matchingMenuOptions.length === 0) {
return entryOptions
}
// Why: a matched create-menu action should win over a generic new-file fallback.
return entryOptions.filter((option) => option.classification.kind !== 'new-file')
}, [fileList, matchingMenuOptions.length, query])
}, [allowAbsolutePaths, fileList, localPlatform, matchingMenuOptions.length, query])
const matchingAgentOptions = useMemo(
() => findMatchingTabAgentLaunchOptions(query, agentOptions),
[agentOptions, query]
@@ -114,9 +114,12 @@ function getActionPresentation(option: ActiveOption): {
showDetail: true
}
}
if (classification.kind === 'existing-file') {
if (classification.kind === 'existing-file' || classification.kind === 'absolute-file') {
return {
detail: classification.relativePath,
detail:
classification.kind === 'absolute-file'
? classification.filePath
: classification.relativePath,
icon: <FileText className="size-3.5 shrink-0" aria-hidden="true" />,
label: translate('auto.components.tab.bar.TabBarCreateEntry.25dc1cd653', 'Open file'),
showDetail: true
@@ -0,0 +1,54 @@
import { detectLanguage } from '@/lib/language-detect'
import { toWorktreeRelativePath } from '@/lib/terminal-links'
import type { RuntimeFileOperationArgs, statRuntimePath } from '@/runtime/runtime-file-client'
import type { OpenFile } from '@/store/slices/editor'
import {
validateNewTabEntryAbsolutePath,
type TabEntryLocalPlatform
} from './tab-create-entry-path-validation'
type AbsoluteFileOperations = {
assertAbsolutePathAllowed: () => void
authorizeExternalPath: (args: { targetPath: string }) => Promise<void>
openFile: (
file: Omit<OpenFile, 'id' | 'isDirty'>,
options?: { preview?: boolean; targetGroupId?: string }
) => void
statRuntimePath: typeof statRuntimePath
}
export async function openAbsoluteTabEntryFile(args: {
context: RuntimeFileOperationArgs
groupId: string
operations: AbsoluteFileOperations
filePath: string
localPlatform: TabEntryLocalPlatform
worktreeId: string
worktreePath: string
}): Promise<void> {
const filePath = validateNewTabEntryAbsolutePath(args.filePath, args.localPlatform)
args.operations.assertAbsolutePathAllowed()
await args.operations.authorizeExternalPath({ targetPath: filePath })
args.operations.assertAbsolutePathAllowed()
let stat: Awaited<ReturnType<typeof statRuntimePath>>
try {
stat = await args.operations.statRuntimePath(args.context, filePath)
} catch {
throw new Error(`File not found: ${filePath}`)
}
if (stat.isDirectory) {
throw new Error(`Cannot open a directory: ${filePath}`)
}
args.operations.assertAbsolutePathAllowed()
args.operations.openFile(
{
filePath,
relativePath: toWorktreeRelativePath(filePath, args.worktreePath) || filePath,
worktreeId: args.worktreeId,
language: detectLanguage(filePath),
mode: 'edit'
},
{ preview: false, targetGroupId: args.groupId }
)
}
@@ -1,5 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import { openTabEntryWithOperations, type TabEntryOperations } from './tab-create-entry-action'
import {
openTabEntryWithOperations,
TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE,
type TabEntryOperations
} from './tab-create-entry-action'
const readyFiles = (files: string[]) => ({ files, loading: false, loadError: null })
@@ -12,6 +16,8 @@ describe('openTabEntryWithOperations', () => {
isWebRuntimeSessionActive: vi.fn().mockReturnValue(false),
openFile: vi.fn(),
statRuntimePath: vi.fn().mockResolvedValue({ size: 1, isDirectory: false, mtime: 1 }),
authorizeExternalPath: vi.fn().mockResolvedValue(undefined),
assertAbsolutePathAllowed: vi.fn(),
...overrides
}
}
@@ -26,7 +32,9 @@ describe('openTabEntryWithOperations', () => {
worktreeId: 'wt-1',
worktreePath: '/repo'
},
activeRuntimeEnvironmentId: null
activeRuntimeEnvironmentId: null,
allowAbsolutePaths: true,
localPlatform: 'posix' as const
}
it('stats existing files before opening and rejects directories', async () => {
@@ -221,4 +229,138 @@ describe('openTabEntryWithOperations', () => {
title: 'https://example.com/'
})
})
it('authorizes and opens absolute local files in the target group', async () => {
const operations = makeOperations()
await openTabEntryWithOperations({
...baseArgs,
classification: { kind: 'absolute-file', filePath: '/tmp/notes.md' },
query: '/tmp/notes.md',
operations
})
expect(operations.authorizeExternalPath).toHaveBeenCalledWith({ targetPath: '/tmp/notes.md' })
expect(operations.statRuntimePath).toHaveBeenCalledWith(
baseArgs.runtimeContext,
'/tmp/notes.md'
)
expect(operations.openFile).toHaveBeenCalledWith(
expect.objectContaining({
filePath: '/tmp/notes.md',
relativePath: '/tmp/notes.md',
worktreeId: 'wt-1'
}),
{ preview: false, targetGroupId: 'group-1' }
)
})
it('normalizes worktree absolute paths to relative paths before opening', async () => {
const operations = makeOperations()
await openTabEntryWithOperations({
...baseArgs,
classification: { kind: 'absolute-file', filePath: '/repo/src/index.ts' },
query: '/repo/src/index.ts',
operations
})
expect(operations.openFile).toHaveBeenCalledWith(
expect.objectContaining({
filePath: '/repo/src/index.ts',
relativePath: 'src/index.ts'
}),
{ preview: false, targetGroupId: 'group-1' }
)
})
it('rejects absolute paths when remote workspaces disallow them', async () => {
const operations = makeOperations()
await expect(
openTabEntryWithOperations({
...baseArgs,
allowAbsolutePaths: false,
classification: { kind: 'absolute-file', filePath: '/tmp/notes.md' },
query: '/tmp/notes.md',
operations
})
).rejects.toThrow(TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE)
expect(operations.authorizeExternalPath).not.toHaveBeenCalled()
expect(operations.statRuntimePath).not.toHaveBeenCalled()
expect(operations.createRuntimePath).not.toHaveBeenCalled()
expect(operations.openFile).not.toHaveBeenCalled()
})
it('rejects Windows path syntax before native POSIX authorization', async () => {
const operations = makeOperations()
await expect(
openTabEntryWithOperations({
...baseArgs,
classification: { kind: 'absolute-file', filePath: 'C:\\tmp\\notes.md' },
query: 'C:\\tmp\\notes.md',
operations
})
).rejects.toThrow('Enter an absolute path for this computer.')
expect(operations.authorizeExternalPath).not.toHaveBeenCalled()
expect(operations.statRuntimePath).not.toHaveBeenCalled()
expect(operations.openFile).not.toHaveBeenCalled()
})
it('normalizes and opens Windows drive paths on Windows', async () => {
const operations = makeOperations()
await openTabEntryWithOperations({
...baseArgs,
localPlatform: 'windows',
worktreePath: 'C:/repo',
classification: { kind: 'absolute-file', filePath: 'C:\\tmp\\notes.md' },
query: 'C:\\tmp\\notes.md',
operations
})
expect(operations.authorizeExternalPath).toHaveBeenCalledWith({
targetPath: 'C:/tmp/notes.md'
})
expect(operations.statRuntimePath).toHaveBeenCalledWith(
baseArgs.runtimeContext,
'C:/tmp/notes.md'
)
})
it('stops after authorization when ownership becomes remote or ambiguous', async () => {
let releaseAuthorization: (() => void) | undefined
const authorization = new Promise<void>((resolve) => {
releaseAuthorization = resolve
})
let allowed = true
const operations = makeOperations({
authorizeExternalPath: vi.fn(() => authorization),
assertAbsolutePathAllowed: vi.fn(() => {
if (!allowed) {
throw new Error(TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE)
}
})
})
const opening = openTabEntryWithOperations({
...baseArgs,
classification: { kind: 'absolute-file', filePath: '/tmp/notes.md' },
query: '/tmp/notes.md',
operations
})
await vi.waitFor(() => expect(operations.authorizeExternalPath).toHaveBeenCalledTimes(1))
const rejection = expect(opening).rejects.toThrow(
TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE
)
allowed = false
releaseAuthorization?.()
await rejection
expect(operations.statRuntimePath).not.toHaveBeenCalled()
expect(operations.openFile).not.toHaveBeenCalled()
})
})
@@ -1,5 +1,6 @@
import { detectLanguage } from '@/lib/language-detect'
import { joinPath } from '@/lib/path'
import { getRendererAppPlatform } from '@/lib/renderer-app-platform'
import {
createRuntimePath,
statRuntimePath,
@@ -13,19 +14,36 @@ import { useAppStore } from '@/store'
import type { OpenFile } from '@/store/slices/editor'
import type { BrowserTab as BrowserTabState } from '../../../../shared/types'
import type { RuntimeFileListState } from '../quick-open-file-list'
import { getEditorFileOperationContext } from '@/lib/editor-file-operation-owner'
import {
classifyTabEntryQuery,
type TabEntryActionClassification
TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE,
type TabEntryActionClassification,
type TabEntryOptionsContext
} from './tab-create-entry-classifier'
import { openAbsoluteTabEntryFile } from './tab-create-entry-absolute-file'
import {
getTabEntryAllowAbsolutePaths,
getTabEntryFileOperationContext,
isTabEntryAbsolutePathAllowed
} from './tab-create-entry-local-path'
import type { TabEntryLocalPlatform } from './tab-create-entry-path-validation'
export {
classifyTabEntryQuery,
getTabEntryOptions,
isTabEntryAbsolutePathLike,
TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE,
validateNewTabEntryAbsolutePath,
validateNewTabEntryRelativePath,
type TabEntryActionClassification,
type TabEntryClassification,
type TabEntryOption
type TabEntryOption,
type TabEntryOptionsContext
} from './tab-create-entry-classifier'
export {
createTabEntryAllowAbsolutePathsSelector,
getTabEntryAllowAbsolutePaths,
isTabEntryAbsolutePathAllowed
} from './tab-create-entry-local-path'
export type TabCreateEntryArgs = {
classification?: TabEntryActionClassification
@@ -54,6 +72,8 @@ export type TabEntryOperations = {
options?: { preview?: boolean; targetGroupId?: string }
) => void
statRuntimePath: typeof statRuntimePath
authorizeExternalPath: (args: { targetPath: string }) => Promise<void>
assertAbsolutePathAllowed: () => void
}
type OpenTabEntryWithOperationsArgs = {
@@ -64,6 +84,8 @@ type OpenTabEntryWithOperationsArgs = {
worktreePath: string
runtimeContext: RuntimeFileOperationArgs
activeRuntimeEnvironmentId: string | null
allowAbsolutePaths: boolean
localPlatform: TabEntryLocalPlatform
classification?: TabEntryActionClassification
operations: TabEntryOperations
}
@@ -132,16 +154,20 @@ async function openExistingFile(args: {
export async function openTabEntryWithOperations({
activeRuntimeEnvironmentId,
allowAbsolutePaths,
classification: selectedClassification,
fileList,
groupId,
localPlatform,
operations,
query,
runtimeContext,
worktreeId,
worktreePath
}: OpenTabEntryWithOperationsArgs): Promise<void> {
const classification = selectedClassification ?? classifyTabEntryQuery(query, fileList)
const entryContext: TabEntryOptionsContext = { allowAbsolutePaths, localPlatform }
const classification =
selectedClassification ?? classifyTabEntryQuery(query, fileList, entryContext)
if (classification.kind === 'empty' || classification.kind === 'blocked') {
throw new Error(classification.message)
}
@@ -176,6 +202,22 @@ export async function openTabEntryWithOperations({
return
}
if (classification.kind === 'absolute-file') {
if (!allowAbsolutePaths) {
throw new Error(TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE)
}
await openAbsoluteTabEntryFile({
context: runtimeContext,
groupId,
operations,
filePath: classification.filePath,
localPlatform,
worktreeId,
worktreePath
})
return
}
if (classification.kind === 'existing-file') {
await openExistingFile({
context: runtimeContext,
@@ -218,11 +260,9 @@ export async function openTabBarEntry(args: TabCreateEntryArgs): Promise<void> {
if (!worktree) {
throw new Error('No active worktree.')
}
const runtimeContext: RuntimeFileOperationArgs = getEditorFileOperationContext(
state,
{ worktreeId: args.worktreeId },
worktree.path
)
const runtimeContext = getTabEntryFileOperationContext(state, args.worktreeId, worktree.path)
const allowAbsolutePaths = isTabEntryAbsolutePathAllowed(runtimeContext)
const localPlatform = getRendererAppPlatform() === 'win32' ? 'windows' : 'posix'
await openTabEntryWithOperations({
query: args.query,
fileList: args.fileList,
@@ -231,6 +271,8 @@ export async function openTabBarEntry(args: TabCreateEntryArgs): Promise<void> {
worktreePath: worktree.path,
runtimeContext,
activeRuntimeEnvironmentId: runtimeContext.settings?.activeRuntimeEnvironmentId?.trim() ?? null,
allowAbsolutePaths,
localPlatform,
classification: args.classification,
operations: {
createBrowserTab: state.createBrowserTab,
@@ -238,7 +280,13 @@ export async function openTabBarEntry(args: TabCreateEntryArgs): Promise<void> {
createWebRuntimeSessionBrowserTab,
isWebRuntimeSessionActive,
openFile: state.openFile,
statRuntimePath
statRuntimePath,
authorizeExternalPath: window.api.fs.authorizeExternalPath,
assertAbsolutePathAllowed: () => {
if (!getTabEntryAllowAbsolutePaths(useAppStore.getState(), args.worktreeId)) {
throw new Error(TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE)
}
}
}
})
}
@@ -3,6 +3,8 @@ import { QUICK_OPEN_QUERY_MAX_BYTES } from '../quick-open-search'
import {
classifyTabEntryQuery,
getTabEntryOptions,
TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE,
validateNewTabEntryAbsolutePath,
validateNewTabEntryRelativePath
} from './tab-create-entry-action'
@@ -182,6 +184,61 @@ describe('tab create entry classification', () => {
{ kind: 'host-url', url: 'https://example.com/' }
])
})
it('classifies POSIX absolute paths only for POSIX clients', () => {
expect(
classifyTabEntryQuery('/tmp/notes.md', readyFiles([]), {
allowAbsolutePaths: true,
localPlatform: 'posix'
})
).toEqual({ kind: 'absolute-file', filePath: '/tmp/notes.md' })
expect(
classifyTabEntryQuery('C:\\tmp\\notes.md', readyFiles([]), {
allowAbsolutePaths: true,
localPlatform: 'posix'
})
).toMatchObject({ kind: 'blocked', message: 'Enter an absolute path for this computer.' })
})
it('classifies drive and UNC paths only for Windows clients', () => {
for (const [query, filePath] of [
['C:\\tmp\\notes.md', 'C:/tmp/notes.md'],
['C:/tmp/notes.md', 'C:/tmp/notes.md'],
['\\\\server\\share\\notes.md', '//server/share/notes.md'],
['//server/share/notes.md', '//server/share/notes.md']
]) {
expect(
classifyTabEntryQuery(query, readyFiles([]), {
allowAbsolutePaths: true,
localPlatform: 'windows'
})
).toEqual({
kind: 'absolute-file',
filePath
})
}
expect(
classifyTabEntryQuery('/tmp/notes.md', readyFiles([]), {
allowAbsolutePaths: true,
localPlatform: 'windows'
})
).toMatchObject({ kind: 'blocked', message: 'Enter an absolute path for this computer.' })
})
it('blocks absolute paths for remote workspaces', () => {
for (const query of [
'/tmp/notes.md',
'C:\\tmp\\notes.md',
'C:/tmp/notes.md',
'\\\\server\\share\\notes.md',
'//server/share/notes.md'
]) {
expect(classifyTabEntryQuery(query, readyFiles([]))).toMatchObject({
kind: 'blocked',
message: TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE
})
}
})
})
describe('tab create entry path validation', () => {
@@ -209,4 +266,33 @@ describe('tab create entry path validation', () => {
expect(validateNewTabEntryRelativePath(' docs/My Note.md ')).toBe('docs/My Note.md')
expect(validateNewTabEntryRelativePath('src\\new-file.ts')).toBe('src/new-file.ts')
})
it('normalizes absolute paths for local open', () => {
expect(validateNewTabEntryAbsolutePath('/tmp/notes.md', 'posix')).toBe('/tmp/notes.md')
expect(validateNewTabEntryAbsolutePath('C:\\tmp\\notes.md', 'windows')).toBe('C:/tmp/notes.md')
expect(validateNewTabEntryAbsolutePath('\\\\server\\share\\notes.md', 'windows')).toBe(
'//server/share/notes.md'
)
expect(validateNewTabEntryAbsolutePath('/repo/../repo/src/file.ts', 'posix')).toBe(
'/repo/src/file.ts'
)
})
it('rejects path families that are not native to the client', () => {
expect(() => validateNewTabEntryAbsolutePath('C:\\tmp\\notes.md', 'posix')).toThrow(
'this computer'
)
expect(() => validateNewTabEntryAbsolutePath('\\\\server\\share\\notes.md', 'posix')).toThrow(
'this computer'
)
expect(() => validateNewTabEntryAbsolutePath('/tmp/notes.md', 'windows')).toThrow(
'this computer'
)
})
it('rejects invalid absolute paths', () => {
for (const path of ['', '~/file.ts', 'src/file.ts', 'C:tmp/file.ts', '/tmp/']) {
expect(() => validateNewTabEntryAbsolutePath(path), path).toThrow()
}
})
})
@@ -2,10 +2,27 @@ import { isQuickOpenQueryTooLarge, prepareQuickOpenFiles } from '../quick-open-s
import type { RuntimeFileListState } from '../quick-open-file-list'
import { translate } from '@/i18n/i18n'
import { findExistingFileMatches, isLikelyNewFileIntent } from './tab-create-entry-file-matches'
import { validateNewTabEntryRelativePath } from './tab-create-entry-path-validation'
import {
isTabEntryAbsolutePathLike,
type TabEntryLocalPlatform,
validateNewTabEntryAbsolutePath,
validateNewTabEntryRelativePath
} from './tab-create-entry-path-validation'
import { classifyExplicitUrl, classifyHostUrl } from './tab-create-entry-url-classification'
export { validateNewTabEntryRelativePath } from './tab-create-entry-path-validation'
export {
isTabEntryAbsolutePathLike,
validateNewTabEntryAbsolutePath,
validateNewTabEntryRelativePath
} from './tab-create-entry-path-validation'
export type TabEntryOptionsContext = {
allowAbsolutePaths?: boolean
localPlatform?: TabEntryLocalPlatform
}
export const TAB_ENTRY_ABSOLUTE_PATH_REMOTE_BLOCKED_MESSAGE =
'Absolute paths require a local workspace.'
export type TabEntryClassification =
| { kind: 'empty'; message: string }
@@ -17,6 +34,7 @@ export type TabEntryClassification =
}
| { kind: 'host-url'; url: string }
| { kind: 'new-file'; relativePath: string }
| { kind: 'absolute-file'; filePath: string }
| { kind: 'blocked'; message: string }
export type TabEntryActionClassification = Exclude<
@@ -29,12 +47,26 @@ export type TabEntryOption = {
id: string
}
function tabEntryActionOptionId(classification: TabEntryActionClassification): string {
switch (classification.kind) {
case 'existing-file':
case 'new-file':
return `${classification.kind}:${classification.relativePath}`
case 'absolute-file':
return `${classification.kind}:${classification.filePath}`
case 'explicit-url':
case 'host-url':
return `${classification.kind}:${classification.url}`
}
}
export function classifyTabEntryQuery(
query: string,
fileList: RuntimeFileListState
fileList: RuntimeFileListState,
context: TabEntryOptionsContext = {}
): TabEntryClassification {
return (
getTabEntryOptions(query, fileList, 1)[0]?.classification ?? {
getTabEntryOptions(query, fileList, 1, context)[0]?.classification ?? {
kind: 'empty',
message: translate(
'auto.components.tab.bar.tab.create.entry.classifier.5553b283ce',
@@ -47,7 +79,8 @@ export function classifyTabEntryQuery(
export function getTabEntryOptions(
query: string,
fileList: RuntimeFileListState,
limit = 4
limit = 4,
context: TabEntryOptionsContext = {}
): TabEntryOption[] {
if (isQuickOpenQueryTooLarge(query)) {
return [
@@ -80,6 +113,42 @@ export function getTabEntryOptions(
]
}
if (isTabEntryAbsolutePathLike(trimmed)) {
if (!context.allowAbsolutePaths) {
return [
{
id: 'absolute-path-blocked',
classification: {
kind: 'blocked',
message: translate(
'auto.components.tab.bar.tab.create.entry.classifier.absolutePathRemoteBlocked',
'Absolute paths require a local workspace.'
)
}
}
]
}
try {
const filePath = validateNewTabEntryAbsolutePath(trimmed, context.localPlatform)
return [
{
id: `absolute-file:${filePath}`,
classification: { kind: 'absolute-file', filePath }
}
]
} catch (error) {
return [
{
id: 'invalid-absolute-path',
classification: {
kind: 'blocked',
message: error instanceof Error ? error.message : String(error)
}
}
]
}
}
const explicitUrl = classifyExplicitUrl(trimmed)
if (explicitUrl) {
return [
@@ -144,12 +213,7 @@ export function getTabEntryOptions(
if (options.length > 0) {
return options.slice(0, limit).map((classification) => ({
id:
classification.kind === 'existing-file'
? `${classification.kind}:${classification.relativePath}`
: classification.kind === 'new-file'
? `${classification.kind}:${classification.relativePath}`
: `${classification.kind}:${classification.url}`,
id: tabEntryActionOptionId(classification),
classification
}))
}
@@ -0,0 +1,394 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { FolderWorkspace, ProjectGroup, Repo } from '../../../../shared/types'
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
import { useAppStore } from '@/store'
import {
createTabEntryAllowAbsolutePathsSelector,
getTabEntryAllowAbsolutePaths,
getTabEntryFileOperationContext
} from './tab-create-entry-local-path'
const initialState = useAppStore.getInitialState()
const localWorktreeId = 'repo-local::/Users/me/repo'
function makeRepo(overrides: Partial<Repo> & { id: string }): Repo {
return {
path: '/Users/me/repo',
displayName: 'repo',
badgeColor: '#000',
addedAt: 0,
...overrides
}
}
function makeFolderWorkspace(overrides: Partial<FolderWorkspace> = {}): FolderWorkspace {
return {
id: 'folder-local',
projectGroupId: 'group-local',
name: 'Local folder',
folderPath: '/Users/me/folder',
linkedTask: null,
comment: '',
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0,
createdAt: 0,
updatedAt: 0,
...overrides
}
}
function makeProjectGroup(overrides: Partial<ProjectGroup> = {}): ProjectGroup {
return {
id: 'group-local',
name: 'Local group',
parentPath: null,
parentGroupId: null,
createdFrom: 'manual',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 0,
updatedAt: 0,
...overrides
}
}
describe('getTabEntryAllowAbsolutePaths', () => {
afterEach(() => {
useAppStore.setState(initialState, true)
})
it('allows absolute paths for a known local worktree', () => {
useAppStore.setState({
repos: [makeRepo({ id: 'repo-local' })],
worktreesByRepo: {
'repo-local': [
{
id: localWorktreeId,
repoId: 'repo-local',
path: '/Users/me/repo',
hostId: 'local'
} as never
]
},
runtimeEnvironmentCatalogHydrated: true,
runtimeEnvironments: [],
removedRuntimeEnvironmentIds: new Set(),
settings: { activeRuntimeEnvironmentId: null } as never
})
expect(getTabEntryAllowAbsolutePaths(useAppStore.getState(), localWorktreeId)).toBe(true)
})
it('blocks absolute paths when the worktree has an SSH connectionId', () => {
useAppStore.setState({
repos: [makeRepo({ id: 'repo-ssh', connectionId: 'ssh-1' })],
worktreesByRepo: {
'repo-ssh': [
{
id: 'repo-ssh::/home/neil/repo',
repoId: 'repo-ssh',
path: '/home/neil/repo'
} as never
]
},
settings: { activeRuntimeEnvironmentId: null } as never
})
expect(getTabEntryAllowAbsolutePaths(useAppStore.getState(), 'repo-ssh::/home/neil/repo')).toBe(
false
)
})
it('blocks absolute paths when activeRuntimeEnvironmentId is set', () => {
useAppStore.setState({
repos: [makeRepo({ id: 'repo-local' })],
worktreesByRepo: {
'repo-local': [
{
id: localWorktreeId,
repoId: 'repo-local',
path: '/Users/me/repo',
hostId: 'runtime:hub-a',
runtimeOwnerEnvironmentId: 'hub-a'
} as never
]
},
runtimeEnvironmentCatalogHydrated: true,
runtimeEnvironments: [{ id: 'hub-a' } as never],
removedRuntimeEnvironmentIds: new Set(),
settings: { activeRuntimeEnvironmentId: 'hub-a' } as never
})
expect(getTabEntryAllowAbsolutePaths(useAppStore.getState(), localWorktreeId)).toBe(false)
})
it('blocks absolute paths while worktree connection ownership is unresolved', () => {
useAppStore.setState({
repos: [],
worktreesByRepo: {}
})
expect(
getTabEntryAllowAbsolutePaths(useAppStore.getState(), 'repo-missing::/tmp/repo-feature')
).toBe(false)
})
it('blocks absolute paths when the worktree is missing from a known local repo', () => {
useAppStore.setState({
repos: [makeRepo({ id: 'repo-local' })],
worktreesByRepo: { 'repo-local': [] },
runtimeEnvironmentCatalogHydrated: true,
runtimeEnvironments: [],
removedRuntimeEnvironmentIds: new Set(),
settings: { activeRuntimeEnvironmentId: null } as never
})
expect(
getTabEntryAllowAbsolutePaths(useAppStore.getState(), 'repo-local::/Users/me/repo-missing')
).toBe(false)
})
it('blocks absolute paths for conflicting local and paired-runtime ownership', () => {
useAppStore.setState({
repos: [makeRepo({ id: 'repo-local' }), makeRepo({ id: 'repo-runtime' })],
worktreesByRepo: {
'repo-local': [
{
id: localWorktreeId,
repoId: 'repo-local',
path: '/Users/me/repo',
hostId: 'local'
} as never
],
'repo-runtime': [
{
id: localWorktreeId,
repoId: 'repo-runtime',
path: '/Users/me/repo',
hostId: 'runtime:hub-a',
runtimeOwnerEnvironmentId: 'hub-a'
} as never
]
},
runtimeEnvironmentCatalogHydrated: true,
runtimeEnvironments: [{ id: 'hub-a' } as never],
removedRuntimeEnvironmentIds: new Set(),
settings: { activeRuntimeEnvironmentId: null } as never
})
expect(getTabEntryAllowAbsolutePaths(useAppStore.getState(), localWorktreeId)).toBe(false)
})
it('allows positively known local folder workspaces', () => {
const folderWorkspace = makeFolderWorkspace()
const worktreeId = folderWorkspaceKey(folderWorkspace.id)
useAppStore.setState({
folderWorkspaces: [folderWorkspace],
projectGroups: [makeProjectGroup()],
repos: [],
settings: { activeRuntimeEnvironmentId: null } as never
})
expect(getTabEntryAllowAbsolutePaths(useAppStore.getState(), worktreeId)).toBe(true)
expect(
getTabEntryFileOperationContext(
useAppStore.getState(),
worktreeId,
folderWorkspace.folderPath
)
).toMatchObject({
expectedExecutionHostId: 'local',
worktreeId,
worktreePath: folderWorkspace.folderPath
})
})
it('blocks SSH-owned folder workspaces', () => {
const folderWorkspace = makeFolderWorkspace({
id: 'folder-ssh',
folderPath: '/home/me/folder',
connectionId: 'ssh-1'
})
const worktreeId = folderWorkspaceKey(folderWorkspace.id)
useAppStore.setState({
folderWorkspaces: [folderWorkspace],
projectGroups: [makeProjectGroup()],
repos: [],
settings: { activeRuntimeEnvironmentId: null } as never
})
expect(getTabEntryAllowAbsolutePaths(useAppStore.getState(), worktreeId)).toBe(false)
})
it('blocks folder workspaces until their project group owner is hydrated', () => {
const folderWorkspace = makeFolderWorkspace()
useAppStore.setState({
folderWorkspaces: [folderWorkspace],
projectGroups: [],
repos: []
})
expect(
getTabEntryAllowAbsolutePaths(useAppStore.getState(), folderWorkspaceKey(folderWorkspace.id))
).toBe(false)
})
it('blocks paired-runtime folder workspaces', () => {
const folderWorkspace = makeFolderWorkspace()
useAppStore.setState({
folderWorkspaces: [folderWorkspace],
projectGroups: [makeProjectGroup({ executionHostId: 'runtime:hub-a' })],
repos: [],
settings: { activeRuntimeEnvironmentId: null } as never
})
expect(
getTabEntryAllowAbsolutePaths(useAppStore.getState(), folderWorkspaceKey(folderWorkspace.id))
).toBe(false)
})
it('blocks folder workspaces restored from a paired runtime', () => {
const folderWorkspace = makeFolderWorkspace()
const worktreeId = folderWorkspaceKey(folderWorkspace.id)
useAppStore.setState({
folderWorkspaces: [folderWorkspace],
projectGroups: [makeProjectGroup()],
repos: [],
restoredRuntimeHostIdByWorkspaceSessionKey: {
[worktreeId]: 'runtime:hub-a'
}
})
expect(getTabEntryAllowAbsolutePaths(useAppStore.getState(), worktreeId)).toBe(false)
})
it('blocks folder workspaces whose repos infer SSH ownership', () => {
const folderWorkspace = makeFolderWorkspace()
useAppStore.setState({
folderWorkspaces: [folderWorkspace],
projectGroups: [makeProjectGroup()],
repos: [
makeRepo({
id: 'repo-ssh',
path: '/Users/me/folder/repo',
projectGroupId: 'group-local',
connectionId: 'ssh-1'
})
]
})
expect(
getTabEntryAllowAbsolutePaths(useAppStore.getState(), folderWorkspaceKey(folderWorkspace.id))
).toBe(false)
})
it('blocks folder workspaces with mixed local and SSH repo ownership', () => {
const folderWorkspace = makeFolderWorkspace()
useAppStore.setState({
folderWorkspaces: [folderWorkspace],
projectGroups: [makeProjectGroup()],
repos: [
makeRepo({
id: 'repo-local-child',
path: '/Users/me/folder/local',
projectGroupId: 'group-local'
}),
makeRepo({
id: 'repo-ssh-child',
path: '/Users/me/folder/remote',
projectGroupId: 'group-local',
connectionId: 'ssh-1'
})
]
})
expect(
getTabEntryAllowAbsolutePaths(useAppStore.getState(), folderWorkspaceKey(folderWorkspace.id))
).toBe(false)
})
it('does not repeat owner resolution for unrelated store writes', () => {
useAppStore.setState({
repos: [makeRepo({ id: 'repo-local' })],
worktreesByRepo: {
'repo-local': [
{
id: localWorktreeId,
repoId: 'repo-local',
path: '/Users/me/repo',
hostId: 'local'
} as never
]
},
runtimeEnvironmentCatalogHydrated: true,
runtimeEnvironments: [],
removedRuntimeEnvironmentIds: new Set(),
settings: { activeRuntimeEnvironmentId: null } as never
})
const state = useAppStore.getState()
const getKnownWorktreeById = vi.fn(state.getKnownWorktreeById)
const selector = createTabEntryAllowAbsolutePathsSelector(localWorktreeId)
const selectedState = { ...state, getKnownWorktreeById }
expect(selector(selectedState)).toBe(true)
for (let index = 0; index < 1_000; index += 1) {
expect(selector({ ...selectedState, pendingToastCount: index } as never)).toBe(true)
}
expect(getKnownWorktreeById).toHaveBeenCalledTimes(1)
})
it('recomputes when an ownership-causal slice changes', () => {
useAppStore.setState({
repos: [makeRepo({ id: 'repo-local' })],
worktreesByRepo: {
'repo-local': [
{
id: localWorktreeId,
repoId: 'repo-local',
path: '/Users/me/repo',
hostId: 'local'
} as never
]
},
runtimeEnvironmentCatalogHydrated: true,
runtimeEnvironments: [],
removedRuntimeEnvironmentIds: new Set(),
settings: { activeRuntimeEnvironmentId: null } as never
})
const state = useAppStore.getState()
const selector = createTabEntryAllowAbsolutePathsSelector(localWorktreeId)
expect(selector(state)).toBe(true)
expect(
selector({
...state,
worktreesByRepo: {
'repo-local': [
{
id: localWorktreeId,
repoId: 'repo-local',
path: '/Users/me/repo',
hostId: 'runtime:hub-a',
runtimeOwnerEnvironmentId: 'hub-a'
} as never
]
},
runtimeEnvironments: [{ id: 'hub-a' } as never]
})
).toBe(false)
})
it('skips owner resolution until an absolute query needs it', () => {
const state = useAppStore.getState()
const getKnownWorktreeById = vi.fn(state.getKnownWorktreeById)
const selector = createTabEntryAllowAbsolutePathsSelector(localWorktreeId, { skip: true })
expect(selector({ ...state, getKnownWorktreeById })).toBe(false)
expect(getKnownWorktreeById).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,123 @@
import { getEditorFileOperationContext } from '@/lib/editor-file-operation-owner'
import { getFolderWorkspaceConnectionId } from '@/lib/folder-workspace-connection'
import { isLocalPathOpenBlocked } from '@/lib/local-path-open-guard'
import { getResolvedExecutionHostIdForWorktree } from '@/lib/resolved-worktree-execution-host'
import type { RuntimeFileOperationArgs } from '@/runtime/runtime-file-client'
import type { useAppStore } from '@/store'
import { parseWorkspaceKey } from '../../../../shared/workspace-scope'
type TabEntryAbsolutePathOwnerState = Pick<
ReturnType<typeof useAppStore.getState>,
| 'settings'
| 'repos'
| 'worktreesByRepo'
| 'detectedWorktreesByRepo'
| 'folderWorkspaces'
| 'projectGroups'
| 'runtimeEnvironments'
| 'runtimeEnvironmentCatalogHydrated'
| 'removedRuntimeEnvironmentIds'
| 'restoredRuntimeHostIdByWorkspaceSessionKey'
| 'sshConnectionStates'
| 'sshStateByEnvironment'
>
export function isTabEntryAbsolutePathAllowed(
context: Pick<RuntimeFileOperationArgs, 'connectionId' | 'settings'>
): boolean {
return !isLocalPathOpenBlocked(context.settings, { connectionId: context.connectionId })
}
export function getTabEntryAllowAbsolutePaths(
state: ReturnType<typeof useAppStore.getState>,
worktreeId: string
): boolean {
const worktree = state.getKnownWorktreeById(worktreeId)
if (!worktree) {
return false
}
const workspaceKey = parseWorkspaceKey(worktreeId)
if (workspaceKey?.type === 'folder') {
return (
getResolvedExecutionHostIdForWorktree(state, worktreeId) === 'local' &&
getFolderWorkspaceConnectionId(state, workspaceKey.folderWorkspaceId) === null
)
}
try {
const runtimeContext = getEditorFileOperationContext(state, { worktreeId }, worktree.path)
return isTabEntryAbsolutePathAllowed(runtimeContext)
} catch {
return false
}
}
export function getTabEntryFileOperationContext(
state: ReturnType<typeof useAppStore.getState>,
worktreeId: string,
worktreePath: string
): RuntimeFileOperationArgs {
const workspaceKey = parseWorkspaceKey(worktreeId)
if (workspaceKey?.type === 'folder') {
if (
getResolvedExecutionHostIdForWorktree(state, worktreeId) === 'local' &&
getFolderWorkspaceConnectionId(state, workspaceKey.folderWorkspaceId) === null
) {
return {
settings: state.settings
? { ...state.settings, activeRuntimeEnvironmentId: null }
: { activeRuntimeEnvironmentId: null },
worktreeId,
worktreePath,
expectedExecutionHostId: 'local'
}
}
}
return getEditorFileOperationContext(state, { worktreeId }, worktreePath)
}
export function createTabEntryAllowAbsolutePathsSelector(
worktreeId: string,
{ skip = false }: { skip?: boolean } = {}
): (state: ReturnType<typeof useAppStore.getState>) => boolean {
let previousSlices: TabEntryAbsolutePathOwnerState | null = null
let previousResult = false
return (state) => {
if (skip) {
return false
}
if (
previousSlices?.settings === state.settings &&
previousSlices.repos === state.repos &&
previousSlices.worktreesByRepo === state.worktreesByRepo &&
previousSlices.detectedWorktreesByRepo === state.detectedWorktreesByRepo &&
previousSlices.folderWorkspaces === state.folderWorkspaces &&
previousSlices.projectGroups === state.projectGroups &&
previousSlices.runtimeEnvironments === state.runtimeEnvironments &&
previousSlices.runtimeEnvironmentCatalogHydrated ===
state.runtimeEnvironmentCatalogHydrated &&
previousSlices.removedRuntimeEnvironmentIds === state.removedRuntimeEnvironmentIds &&
previousSlices.restoredRuntimeHostIdByWorkspaceSessionKey ===
state.restoredRuntimeHostIdByWorkspaceSessionKey &&
previousSlices.sshConnectionStates === state.sshConnectionStates &&
previousSlices.sshStateByEnvironment === state.sshStateByEnvironment
) {
return previousResult
}
previousSlices = {
settings: state.settings,
repos: state.repos,
worktreesByRepo: state.worktreesByRepo,
detectedWorktreesByRepo: state.detectedWorktreesByRepo,
folderWorkspaces: state.folderWorkspaces,
projectGroups: state.projectGroups,
runtimeEnvironments: state.runtimeEnvironments,
runtimeEnvironmentCatalogHydrated: state.runtimeEnvironmentCatalogHydrated,
removedRuntimeEnvironmentIds: state.removedRuntimeEnvironmentIds,
restoredRuntimeHostIdByWorkspaceSessionKey: state.restoredRuntimeHostIdByWorkspaceSessionKey,
sshConnectionStates: state.sshConnectionStates,
sshStateByEnvironment: state.sshStateByEnvironment
}
previousResult = getTabEntryAllowAbsolutePaths(state, worktreeId)
return previousResult
}
}
@@ -1,3 +1,8 @@
import { normalizeAbsolutePath } from '@/lib/terminal-path-normalization'
import { isAbsolutePathLike } from '../editor/editor-panel-file-mode'
export type TabEntryLocalPlatform = 'posix' | 'windows'
function hasPathSeparator(query: string): boolean {
return /[\\/]/.test(query)
}
@@ -10,6 +15,49 @@ export function isLikelyNewFileIntent(query: string): boolean {
return hasPathSeparator(query) || hasFilenameExtension(query)
}
export function isTabEntryAbsolutePathLike(query: string): boolean {
return isAbsolutePathLike(query.trim())
}
function assertTabEntryPathHasNoControlCharacters(trimmed: string): void {
if (Array.from(trimmed).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
throw new Error('File paths cannot contain control characters.')
}
}
export function validateNewTabEntryAbsolutePath(
query: string,
localPlatform?: TabEntryLocalPlatform
): string {
const trimmed = query.trim()
if (!trimmed) {
throw new Error('Enter a URL or file path.')
}
assertTabEntryPathHasNoControlCharacters(trimmed)
if (trimmed === '~' || trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
throw new Error('Home-relative paths are not supported here.')
}
if (/[\\/]$/.test(trimmed)) {
throw new Error('Enter a file path, not a directory path.')
}
if (!isAbsolutePathLike(trimmed)) {
throw new Error('Enter an absolute file path.')
}
const normalized = normalizeAbsolutePath(trimmed)
if (!normalized) {
throw new Error('Enter an absolute file path.')
}
const rootMatchesLocalPlatform =
localPlatform === undefined ||
(localPlatform === 'posix' && normalized.rootKind === 'posix') ||
(localPlatform === 'windows' &&
(normalized.rootKind === 'windows' || normalized.rootKind === 'unc'))
if (!rootMatchesLocalPlatform) {
throw new Error('Enter an absolute path for this computer.')
}
return normalized.normalized
}
export function validateNewTabEntryRelativePath(query: string): string {
// Keep tab-created paths workspace-relative and unambiguous across platforms.
// Absolute, home-relative, traversal, and UNC variants are handled elsewhere.
@@ -17,9 +65,7 @@ export function validateNewTabEntryRelativePath(query: string): string {
if (!trimmed) {
throw new Error('Enter a URL or file path.')
}
if (Array.from(trimmed).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
throw new Error('File paths cannot contain control characters.')
}
assertTabEntryPathHasNoControlCharacters(trimmed)
if (trimmed.startsWith('/')) {
throw new Error('Enter a relative file path.')
}
+2 -1
View File
@@ -2927,7 +2927,8 @@
"5a9c83c04b": "Open any file, URL, agent, ...",
"90eb94dc48": "Enter an http:// or https:// URL.",
"5553b283ce": "Enter a URL or file path.",
"queryTooLarge": "Search text is too large."
"queryTooLarge": "Search text is too large.",
"absolutePathRemoteBlocked": "Absolute paths require a local workspace."
}
},
"menu": {
+2 -1
View File
@@ -2904,7 +2904,8 @@
"5a9c83c04b": "Abrir cualquier archivo, URL, agente, ...",
"90eb94dc48": "Introduce una URL http:// o https://.",
"5553b283ce": "Introduce una URL o ruta de archivo.",
"queryTooLarge": "El texto de búsqueda es demasiado grande."
"queryTooLarge": "El texto de búsqueda es demasiado grande.",
"absolutePathRemoteBlocked": "Las rutas absolutas requieren un espacio de trabajo local."
}
},
"menu": {
+2 -1
View File
@@ -2904,7 +2904,8 @@
"5a9c83c04b": "任意のファイル、URL、agent などを開きます...",
"90eb94dc48": "http:// または https:// URL を入力します。",
"5553b283ce": "URL またはファイル パスを入力します。",
"queryTooLarge": "検索テキストが大きすぎます。"
"queryTooLarge": "検索テキストが大きすぎます。",
"absolutePathRemoteBlocked": "絶対パスにはローカル ワークスペースが必要です。"
}
},
"menu": {
+2 -1
View File
@@ -2904,7 +2904,8 @@
"5a9c83c04b": "모든 파일, URL, agent를 엽니다...",
"90eb94dc48": "http:// 또는 https:// URL을 입력하세요.",
"5553b283ce": "URL 또는 파일 경로를 입력하세요.",
"queryTooLarge": "검색 텍스트가 너무 큽니다."
"queryTooLarge": "검색 텍스트가 너무 큽니다.",
"absolutePathRemoteBlocked": "절대 경로에는 로컬 워크스페이스가 필요합니다."
}
},
"menu": {
+2 -1
View File
@@ -2904,7 +2904,8 @@
"5a9c83c04b": "打开任何文件、URL、智能体...",
"90eb94dc48": "输入 http:// 或 https:// URL。",
"5553b283ce": "输入 URL 或文件路径。",
"queryTooLarge": "搜索文本过长。"
"queryTooLarge": "搜索文本过长。",
"absolutePathRemoteBlocked": "绝对路径需要本地工作区。"
}
},
"menu": {