diff --git a/src/main/ipc/filesystem/filesystem-host-browse-handlers.test.ts b/src/main/ipc/filesystem/filesystem-host-browse-handlers.test.ts new file mode 100644 index 000000000000..c46c6ba53f83 --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-host-browse-handlers.test.ts @@ -0,0 +1,136 @@ +import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { HostDirectoryListing } from '../../../shared/file-listing/host-directory-browse' +import type { Store } from '../../persistence/loading-store/store' +import { isPathAllowed, resolveAuthorizedPath } from './access/filesystem-auth' +import { + registerFilesystemHostBrowseHandlers, + resolveHostBrowseEntry +} from './filesystem-host-browse-handlers' + +const { handlers } = vi.hoisted(() => ({ + handlers: new Map unknown>() +})) + +vi.mock('electron', () => ({ + ipcMain: { + handle: (channel: string, handler: (event: unknown, args: unknown) => unknown) => + handlers.set(channel, handler) + } +})) + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: allowed-root lookups read only these four accessors. +const store = { + getRepos: () => [], + getProjectGroups: () => [], + getFolderWorkspaces: () => [], + getSettings: () => ({}) +} as unknown as Store + +describe('host browse handlers', () => { + let root: string + + beforeEach(async () => { + root = await realpath(await mkdtemp(join(tmpdir(), 'orca-host-browse-'))) + await mkdir(join(root, 'outside', 'nested'), { recursive: true }) + await writeFile(join(root, 'outside', 'notes.txt'), 'hi') + }) + + afterEach(async () => { + await rm(root, { recursive: true, force: true }) + }) + + it('lists a directory outside allowed roots without granting access to it', async () => { + registerFilesystemHostBrowseHandlers() + const outside = join(root, 'outside') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fs:browseHostDir resolves to a HostDirectoryListing. + const listing = (await handlers.get('fs:browseHostDir')?.(null, { + dirPath: outside + })) as HostDirectoryListing + + expect(listing.resolvedPath).toBe(outside) + expect(listing.entries.map((entry) => entry.name).sort()).toEqual(['nested', 'notes.txt']) + await expect(isPathAllowed(outside, store)).resolves.toBe(false) + await expect(isPathAllowed(join(outside, 'nested', 'x'), store)).resolves.toBe(false) + await expect(resolveAuthorizedPath(join(outside, 'nested'), store)).rejects.toThrow( + /Access denied/ + ) + }) + + it('classifies a regular file outside the workspace without granting it', async () => { + const file = join(root, 'outside', 'notes.txt') + const resolution = await resolveHostBrowseEntry(file) + + expect(resolution).toEqual({ kind: 'file', realPath: file, workspaceRelativePath: null }) + await expect(isPathAllowed(file, store)).resolves.toBe(false) + await expect(isPathAllowed(join(root, 'outside'), store)).resolves.toBe(false) + await expect(isPathAllowed(join(root, 'outside', 'nested'), store)).resolves.toBe(false) + }) + + it('classifies a symlink to a directory as a directory and grants nothing', async () => { + const target = join(root, 'outside', 'nested') + const link = join(root, 'dir-link') + await symlink(target, link, 'dir') + + const resolution = await resolveHostBrowseEntry(link) + + expect(resolution).toEqual({ kind: 'directory', realPath: target, workspaceRelativePath: null }) + await expect(isPathAllowed(join(target, 'anything'), store)).resolves.toBe(false) + await expect(isPathAllowed(join(link, 'anything'), store)).resolves.toBe(false) + }) + + it('reports the canonical path of a symlinked file for worktree ownership checks', async () => { + const target = join(root, 'outside', 'notes.txt') + const link = join(root, 'file-link') + await symlink(target, link, 'file') + + await expect(resolveHostBrowseEntry(link)).resolves.toEqual({ + kind: 'file', + realPath: target, + workspaceRelativePath: null + }) + }) + + it('rejects relative and null-byte paths', async () => { + await expect(resolveHostBrowseEntry('outside/notes.txt'), 'relative').rejects.toThrow( + /absolute/ + ) + await expect(resolveHostBrowseEntry(`${root}\0x`), 'NUL').rejects.toThrow(/null bytes/) + }) + + it('resolves workspace ownership against the canonical workspace root', async () => { + const realWorkspace = join(root, 'real-workspace') + await mkdir(join(realWorkspace, 'src'), { recursive: true }) + await writeFile(join(realWorkspace, 'src', 'a.ts'), 'x') + const workspaceAlias = join(root, 'workspace-alias') + await symlink(realWorkspace, workspaceAlias, 'dir') + const outsideLink = join(root, 'outside', 'a-link.ts') + await symlink(join(realWorkspace, 'src', 'a.ts'), outsideLink, 'file') + + const resolution = await resolveHostBrowseEntry(outsideLink, workspaceAlias) + + expect(resolution).toEqual({ + kind: 'file', + realPath: join(realWorkspace, 'src', 'a.ts'), + workspaceRelativePath: 'src/a.ts' + }) + // Why: workspace files are reached through allowed roots; no external grant is added. + await expect(isPathAllowed(outsideLink, store)).resolves.toBe(false) + }) + + it('keeps a workspace symlink that leaves the workspace outside it', async () => { + const workspace = join(root, 'workspace') + await mkdir(workspace) + const target = join(root, 'outside', 'notes.txt') + const link = join(workspace, 'notes-link.txt') + await symlink(target, link, 'file') + + await expect(resolveHostBrowseEntry(link, workspace)).resolves.toEqual({ + kind: 'file', + realPath: target, + workspaceRelativePath: null + }) + }) +}) diff --git a/src/main/ipc/filesystem/filesystem-host-browse-handlers.ts b/src/main/ipc/filesystem/filesystem-host-browse-handlers.ts new file mode 100644 index 000000000000..c13f01dcca85 --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-host-browse-handlers.ts @@ -0,0 +1,64 @@ +import { ipcMain } from 'electron' +import { realpath, stat } from 'node:fs/promises' +import { isAbsolute } from 'node:path' +import { relativePathInsideRoot } from '../../../shared/file-access/cross-platform-path' +import type { + HostBrowseEntryResolution, + HostDirectoryListing +} from '../../../shared/file-listing/host-directory-browse' +import { browseServerDirectory } from '../../runtime/files/server-browse/runtime-server-environment-commands' + +async function canonicalRelativePath( + realPath: string, + workspaceRoot: string | undefined, + canonicalize: (path: string) => Promise +): Promise { + if (!workspaceRoot) { + return null + } + try { + return relativePathInsideRoot(await canonicalize(workspaceRoot), realPath) + } catch { + return null + } +} + +export async function resolveHostBrowseEntry( + targetPath: string, + workspaceRoot?: string +): Promise { + if (targetPath.includes('\0')) { + throw new Error('Path cannot contain null bytes') + } + if (!isAbsolute(targetPath)) { + throw new Error('Host browse path must be absolute') + } + const realPath = await realpath(targetPath) + const target = await stat(realPath) + const workspaceRelativePath = await canonicalRelativePath(realPath, workspaceRoot, realpath) + if (target.isDirectory()) { + return { kind: 'directory', realPath, workspaceRelativePath } + } + if (!target.isFile()) { + return { kind: 'unsupported', realPath, workspaceRelativePath } + } + return { kind: 'file', realPath, workspaceRelativePath } +} + +export function registerFilesystemHostBrowseHandlers(): void { + // Why: names-only listing never touches the external-path allowlist, so browsing + // outside the workspace grants nothing to later read/write/delete handlers. + ipcMain.handle( + 'fs:browseHostDir', + (_event, args: { dirPath: string }): Promise => + browseServerDirectory(args.dirPath) + ) + ipcMain.handle( + 'fs:resolveHostBrowseEntry', + ( + _event, + args: { targetPath: string; workspaceRoot?: string } + ): Promise => + resolveHostBrowseEntry(args.targetPath, args.workspaceRoot) + ) +} diff --git a/src/main/ipc/filesystem/filesystem.ts b/src/main/ipc/filesystem/filesystem.ts index 602ffd716ec5..c54aa27de304 100644 --- a/src/main/ipc/filesystem/filesystem.ts +++ b/src/main/ipc/filesystem/filesystem.ts @@ -19,6 +19,7 @@ import { registerFilesystemGitRemoteHandlers } from './git-remote/filesystem-git import { registerFilesystemGitDiffHandlers } from './source-control/filesystem-git-diff-handlers' import { registerFilesystemGitIndexHandlers } from './source-control/filesystem-git-index-handlers' import { registerFilesystemGitUrlHandlers } from './source-control/filesystem-git-url-handlers' +import { registerFilesystemHostBrowseHandlers } from './filesystem-host-browse-handlers' export function registerFilesystemHandlers( store: Store, @@ -44,5 +45,6 @@ export function registerFilesystemHandlers( registerFilesystemGitDiffHandlers(context) registerFilesystemGitIndexHandlers(context) registerFilesystemGitUrlHandlers(context) + registerFilesystemHostBrowseHandlers() registerLocalLogTailHandlers(store) } diff --git a/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts b/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts index 7bce94c36da4..bde67bf4fafd 100644 --- a/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts +++ b/src/main/runtime/files/server-browse/runtime-server-environment-commands.ts @@ -2,8 +2,7 @@ import { readdir, stat } from 'node:fs/promises' import { homedir } from 'node:os' import type { Dirent } from 'node:fs' import { isAbsolute, join, resolve } from 'node:path' -import type { DirEntry } from '../../../../shared/file-listing/directory-entry' -import type { FilesystemPathFlavor } from '../../../../shared/file-access/filesystem-path-flavor' +import type { HostDirectoryListing } from '../../../../shared/file-listing/host-directory-browse' import { sortDirEntries } from '../../../../shared/file-listing/file-name-sort' import { probeGitAvailability } from '../../../git/command-runner/host-routing/git-availability' import { gitExecFileAsync } from '../../../git/command-runner/git-exec-file' @@ -41,36 +40,36 @@ async function isBrowseEntryDirectory(dirPath: string, entry: Dirent): Promise { + if (isServerDriveListRequest(pathValue)) { + return listWindowsDrives() + } + const dirPath = resolveServerBrowsePath(pathValue) + const dirStat = await stat(dirPath) + if (!dirStat.isDirectory()) { + throw new Error(`${dirPath} is not a directory`) + } + const entries = await readdir(dirPath, { withFileTypes: true }) + const mapped = await Promise.all( + entries + .filter((entry) => entry.name !== '.' && entry.name !== '..') + .map(async (entry) => ({ + name: entry.name, + isDirectory: await isBrowseEntryDirectory(dirPath, entry), + isSymlink: entry.isSymbolicLink() + })) + ) + sortDirEntries(mapped) + return { + resolvedPath: dirPath, + entries: mapped, + pathFlavor: process.platform === 'win32' ? 'win32' : 'posix' + } +} + export class RuntimeServerEnvironmentCommands { - async browseDirectory(pathValue: string): Promise<{ - resolvedPath: string - entries: DirEntry[] - pathFlavor: FilesystemPathFlavor - }> { - if (isServerDriveListRequest(pathValue)) { - return listWindowsDrives() - } - const dirPath = resolveServerBrowsePath(pathValue) - const dirStat = await stat(dirPath) - if (!dirStat.isDirectory()) { - throw new Error(`${dirPath} is not a directory`) - } - const entries = await readdir(dirPath, { withFileTypes: true }) - const mapped = await Promise.all( - entries - .filter((entry) => entry.name !== '.' && entry.name !== '..') - .map(async (entry) => ({ - name: entry.name, - isDirectory: await isBrowseEntryDirectory(dirPath, entry), - isSymlink: entry.isSymbolicLink() - })) - ) - sortDirEntries(mapped) - return { - resolvedPath: dirPath, - entries: mapped, - pathFlavor: process.platform === 'win32' ? 'win32' : 'posix' - } + async browseDirectory(pathValue: string): Promise { + return browseServerDirectory(pathValue) } async isGitAvailable(): Promise { diff --git a/src/preload/api/filesystem/filesystem-api.ts b/src/preload/api/filesystem/filesystem-api.ts index 27c232910e34..f7039bff0fca 100644 --- a/src/preload/api/filesystem/filesystem-api.ts +++ b/src/preload/api/filesystem/filesystem-api.ts @@ -5,6 +5,10 @@ import type { PdfExportResult } from '../../../shared/document-preview/pdf-expor import type { DirEntry } from '../../../shared/file-listing/directory-entry' import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' import type { MarkdownDocument } from '../../../shared/file-listing/file-document' +import type { + HostBrowseEntryResolution, + HostDirectoryListing +} from '../../../shared/file-listing/host-directory-browse' import type { ImportItemResult, ResolveDroppedPathsResult @@ -184,6 +188,13 @@ export type FilesystemApi = { permanent?: boolean } & SshMutationExpectation ) => Promise + /** Desktop-only names listing for the Explorer's Host mode; never widens path grants. */ + browseHostDir?: (args: { dirPath: string }) => Promise + /** Desktop-only; classifies a host path against the workspace without granting access. */ + resolveHostBrowseEntry?: (args: { + targetPath: string + workspaceRoot?: string + }) => Promise stat: (args: { filePath: string connectionId?: string diff --git a/src/preload/api/filesystem/fs-bridge.ts b/src/preload/api/filesystem/fs-bridge.ts index 8f8f838779c8..9d741a0a389b 100644 --- a/src/preload/api/filesystem/fs-bridge.ts +++ b/src/preload/api/filesystem/fs-bridge.ts @@ -22,6 +22,10 @@ import type { } from '../../../shared/agent-session/agent-session-attachments' import type { SearchResult } from '../../../shared/file-search/code-search-types' import type { FsChangedPayload } from '../../../shared/file-watch/filesystem-change-event' +import type { + HostBrowseEntryResolution, + HostDirectoryListing +} from '../../../shared/file-listing/host-directory-browse' import type { ImportItemResult, ResolveDroppedPathsResult @@ -185,6 +189,12 @@ export const fsApi = { permanent?: boolean } & SshMutationExpectation ): Promise => ipcRenderer.invoke('fs:deletePath', args), + browseHostDir: (args: { dirPath: string }): Promise => + ipcRenderer.invoke('fs:browseHostDir', args), + resolveHostBrowseEntry: (args: { + targetPath: string + workspaceRoot?: string + }): Promise => ipcRenderer.invoke('fs:resolveHostBrowseEntry', args), stat: (args: { filePath: string connectionId?: string diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/FileExplorerSearchResultsLayer.tsx b/src/renderer/src/components/right-sidebar/file-explorer/content-search/FileExplorerSearchResultsLayer.tsx new file mode 100644 index 000000000000..18836153b8c3 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/content-search/FileExplorerSearchResultsLayer.tsx @@ -0,0 +1,30 @@ +import { cn } from '@/lib/class-names' +import { useTranslate } from '@/i18n/use-translate' +import { SearchResultsPane } from './SearchResultsPane' +import type { FileSearchPanelModel } from './useFileSearchPanel' + +export function FileExplorerSearchResultsLayer({ + explorerView, + searchPanel +}: { + explorerView: 'files' | 'search' + searchPanel: FileSearchPanelModel +}): React.JSX.Element { + const t = useTranslate() + return ( +
+ {searchPanel.activeWorktreeId ? ( + + ) : ( +
+ {t('auto.components.right.sidebar.Search.98c8435e36', 'Select a workspace to search')} +
+ )} +
+ ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostBar.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostBar.test.tsx new file mode 100644 index 000000000000..818e6393a4d1 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostBar.test.tsx @@ -0,0 +1,75 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { FileExplorerHostBar } from './FileExplorerHostBar' +import type { FileExplorerHostMode } from './use-file-explorer-host-mode' + +let root: Root +let container: HTMLDivElement + +function hostMode(listing: boolean, showLoading: boolean): FileExplorerHostMode { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the bar reads only these fields. + return { + active: true, + hostLabel: 'Local Mac', + exit: vi.fn(), + browser: { + listing: listing ? { resolvedPath: '/home/allen', entries: [], pathFlavor: 'posix' } : null, + loading: true, + showLoading, + error: null, + canNavigateUp: listing, + navigate: vi.fn(), + navigateUp: vi.fn(), + refresh: vi.fn(), + activateEntry: vi.fn(), + reset: vi.fn() + } + } as unknown as FileExplorerHostMode +} + +async function render(mode: FileExplorerHostMode): Promise { + await act(async () => { + root.render( + + + + ) + }) + const bar = container.querySelector('[data-file-explorer-host-bar]') + if (!bar) { + throw new Error('host bar not rendered') + } + return bar +} + +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + document.body.replaceChildren() +}) + +describe('FileExplorerHostBar', () => { + it('reserves the breadcrumb row so the first listing does not grow the bar', async () => { + const before = await render(hostMode(false, false)) + const rowsBefore = before.children.length + + const after = await render(hostMode(true, false)) + + expect(after.children.length).toBe(rowsBefore) + }) + + it('shows the refresh spinner only once loading has lasted', async () => { + expect((await render(hostMode(true, false))).querySelector('.animate-spin')).toBeNull() + expect((await render(hostMode(true, true))).querySelector('.animate-spin')).not.toBeNull() + }) +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostBar.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostBar.tsx new file mode 100644 index 000000000000..c1abfb65e3ca --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostBar.tsx @@ -0,0 +1,72 @@ +import React from 'react' +import { FolderGit2, Loader2, RefreshCw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { useTranslate } from '@/i18n/use-translate' +import { RemoteFileBrowserBreadcrumbs } from '../../../sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs' +import type { FileExplorerHostMode } from './use-file-explorer-host-mode' + +export function FileExplorerHostBar({ + hostMode +}: { + hostMode: FileExplorerHostMode +}): React.JSX.Element { + const t = useTranslate() + const { browser, hostLabel, exit: onReturnToProject } = hostMode + const returnLabel = t('fileExplorer.host.returnToProject', 'Return to workspace root') + const refreshLabel = t('fileExplorer.host.refresh', 'Refresh folder') + return ( +
+
+ + + + + {returnLabel} + + + {t('fileExplorer.host.browsing', 'Host: {{host}}', { host: hostLabel })} + + + + + + {refreshLabel} + +
+ {browser.listing ? ( + + ) : ( + // Why: reserve the breadcrumb row so the first listing does not grow the bar again. +
+ )} +
+ ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostList.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostList.test.tsx new file mode 100644 index 000000000000..9533d948b4d5 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostList.test.tsx @@ -0,0 +1,143 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' +import { FileExplorerHostList } from './FileExplorerHostList' +import { shouldIgnoreFileExplorerKeyTarget } from '../selection/useFileExplorerKeys' +import type { FileExplorerHostMode } from './use-file-explorer-host-mode' + +let root: Root +let container: HTMLDivElement + +function hostMode(entries: DirEntry[], overrides: Partial = {}) { + const browser = { + listing: { resolvedPath: '/home/allen', entries, pathFlavor: 'posix' as const }, + loading: false, + error: null, + canNavigateUp: true, + navigate: vi.fn(), + navigateUp: vi.fn(), + refresh: vi.fn(), + activateEntry: vi.fn(), + ...overrides + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the list reads only `browser` and `filterQuery`. + return { browser, filterQuery: '' } as unknown as FileExplorerHostMode +} + +async function render(mode: FileExplorerHostMode, showDotfiles = true): Promise { + await act(async () => { + root.render() + }) +} + +function rowLabels(): string[] { + return [...container.querySelectorAll('button')].map((button) => button.textContent ?? '') +} + +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + document.body.replaceChildren() +}) + +const codes = { name: 'codes', isDirectory: true, isSymlink: false } +const documents = { name: 'Documents', isDirectory: true, isSymlink: false } +const bashrc = { name: '.bashrc', isDirectory: false, isSymlink: false } + +describe('FileExplorerHostList', () => { + it('lists a Parent row above sibling folders and activates entries', async () => { + const mode = hostMode([codes, documents, bashrc]) + await render(mode) + + expect(rowLabels()).toEqual(['Parent directory', 'codes', 'Documents', '.bashrc']) + act(() => container.querySelectorAll('button')[0]?.click()) + act(() => container.querySelectorAll('button')[2]?.click()) + expect(mode.browser.navigateUp).toHaveBeenCalledTimes(1) + expect(mode.browser.activateEntry).toHaveBeenCalledWith(documents) + }) + + it('omits the Parent row at a filesystem root and hides dotfiles when asked', async () => { + await render(hostMode([codes, bashrc], { canNavigateUp: false }), false) + + expect(rowLabels()).toEqual(['codes']) + }) + + it('keeps tree shortcuts from acting on the hidden tree selection', async () => { + await render(hostMode([codes])) + + const row = container.querySelectorAll('button')[1] + expect(shouldIgnoreFileExplorerKeyTarget(row ?? null)).toBe(true) + }) + + it('mounts only a window of rows for very large folders', async () => { + const many = Array.from({ length: 5_000 }, (_, index) => ({ + name: `f${index}`, + isDirectory: false, + isSymlink: false + })) + await render(hostMode(many)) + + const mounted = container.querySelectorAll('[data-file-explorer-host-list] button').length + expect(container.querySelector('[data-testid="virtualized-list"]')).not.toBeNull() + expect(mounted).toBeGreaterThan(0) + expect(mounted).toBeLessThan(200) + }) + + it('dims the folder on screen while a slow navigation is pending', async () => { + await render(hostMode([codes], { showLoading: true })) + expect(container.querySelector('[data-file-explorer-host-list]')?.className).toContain( + 'opacity-60' + ) + + await render(hostMode([codes], { showLoading: false })) + expect(container.querySelector('[data-file-explorer-host-list]')?.className).not.toContain( + 'opacity-60' + ) + }) + + it('starts a new folder or filter at the top but keeps the place on revalidation', async () => { + const at = ( + path: string, + entries: DirEntry[], + filterQuery = '', + error: string | null = null + ) => { + const mode = hostMode(entries, { + listing: { resolvedPath: path, entries, pathFlavor: 'posix' as const }, + error + }) + return { ...mode, filterQuery } + } + const scroller = () => container.querySelector('[data-file-explorer-host-list]') + const scrollTo = (top: number) => { + const el = scroller() + if (el) { + el.scrollTop = top + } + } + + await render(at('/home/allen', [codes, documents])) + scrollTo(500) + await render(at('/home/allen', [codes, documents, bashrc])) + expect(scroller()?.scrollTop).toBe(500) + + await render(at('/home/allen', [codes, documents, bashrc])) + expect(scroller()?.scrollTop).toBe(500) + + await render(at('/home/allen/Documents', [bashrc])) + expect(scroller()?.scrollTop).toBe(0) + + scrollTo(500) + await render(at('/home/allen/Documents', [bashrc], 'bash')) + expect(scroller()?.scrollTop).toBe(0) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostList.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostList.tsx new file mode 100644 index 000000000000..5ef255bb14ed --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostList.tsx @@ -0,0 +1,104 @@ +import React, { useDeferredValue, useLayoutEffect, useMemo, useState } from 'react' +import { CornerLeftUp, Folder, Link } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/class-names' +import { getFileTypeIcon } from '@/lib/file-icons/file-type-icons' +import { VirtualizedList } from '@/components/ui/virtualized-list' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' +import { FileExplorerTreeStatus } from '../tree/FileExplorerTreeStatus' +import { filterHostEntries } from './file-explorer-host-mode' +import type { FileExplorerHostMode } from './use-file-explorer-host-mode' + +const ROW_CLASS = + 'flex w-full items-center gap-1 rounded-sm px-2 py-1 text-left text-xs transition-colors hover:bg-accent hover:text-foreground' + +function HostEntryIcon({ entry }: { entry: DirEntry }): React.JSX.Element { + if (entry.isDirectory) { + return + } + if (entry.isSymlink) { + return + } + return React.createElement(getFileTypeIcon(entry.name), { + className: 'size-3 shrink-0 text-muted-foreground' + }) +} + +export function FileExplorerHostList({ + hostMode, + showDotfiles +}: { + hostMode: FileExplorerHostMode + showDotfiles: boolean +}): React.JSX.Element { + const t = useTranslate() + const { browser, filterQuery } = hostMode + const deferredQuery = useDeferredValue(filterQuery) + const listingEntries = browser.listing?.entries + const entries = useMemo( + () => (listingEntries ? filterHostEntries(listingEntries, deferredQuery, showDotfiles) : []), + [listingEntries, deferredQuery, showDotfiles] + ) + // Why: state, not a ref, so the virtualizer observes the scroller once it attaches. + const [scrollElement, setScrollElement] = useState(null) + const resolvedPath = browser.listing?.resolvedPath ?? null + // Why: a new folder or filter starts at the top; reloading the same folder (refresh, a failed + // navigation) keeps the user's place. + useLayoutEffect(() => { + if (scrollElement) { + scrollElement.scrollTo({ top: 0 }) + } + }, [scrollElement, resolvedPath, deferredQuery]) + const status = ( + + ) + return ( + + ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostQueryRow.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostQueryRow.tsx new file mode 100644 index 000000000000..bcb86593d63d --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/FileExplorerHostQueryRow.tsx @@ -0,0 +1,40 @@ +import React from 'react' +import { useTranslate } from '@/i18n/use-translate' +import type { RightSidebarExplorerView } from '../../../../../../shared/ui-chrome/ui-chrome-types' +import { FileExplorerNameFilter } from '../panel/FileExplorerNameFilter' +import { useFileExplorerHostModeContext } from './file-explorer-host-mode-context-value' + +/** + * Host mode filters only the listed folder; Contents search stays scoped to Project mode. It covers + * the Names/Contents slot in place so the Project query rows stay mounted and nothing shifts. + */ +export function FileExplorerHostQueryRow({ + view +}: { + view: RightSidebarExplorerView +}): React.JSX.Element | null { + const t = useTranslate() + const { active, filterQuery, setFilterQuery } = useFileExplorerHostModeContext() + if (!active) { + return null + } + return ( +
+ {view === 'search' ? ( +

+ {t( + 'fileExplorer.host.contentsUnavailable', + 'Contents search covers the workspace. Return to the workspace root to use it.' + )} +

+ ) : ( + setFilterQuery('')} + /> + )} +
+ ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode-context-value.ts b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode-context-value.ts new file mode 100644 index 000000000000..46b005b6f08f --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode-context-value.ts @@ -0,0 +1,13 @@ +import { createContext, useContext } from 'react' +import type { FileExplorerHostMode } from './use-file-explorer-host-mode' + +// Why: kept apart from the components so React Fast Refresh can hot-swap them in dev. +export const HostModeContext = createContext(null) + +export function useFileExplorerHostModeContext(): FileExplorerHostMode { + const hostMode = useContext(HostModeContext) + if (!hostMode) { + throw new Error('FileExplorerHostModeProvider is missing') + } + return hostMode +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode-context.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode-context.tsx new file mode 100644 index 000000000000..bbe48413b0fb --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode-context.tsx @@ -0,0 +1,114 @@ +import React from 'react' +import { cn } from '@/lib/class-names' +import { FileExplorerHostBar } from './FileExplorerHostBar' +import { FileExplorerHostList } from './FileExplorerHostList' +import { FileExplorerToolbar } from '../panel/FileExplorerToolbar' +import { FileExplorerQueryStrip } from '../panel/FileExplorerQueryStrip' +import { + HostModeContext, + useFileExplorerHostModeContext +} from './file-explorer-host-mode-context-value' +import { useFileExplorerHostMode } from './use-file-explorer-host-mode' + +/** + * Owns Host-mode state below FileExplorerFiles so toggling re-renders only its subscribers; + * `children` are elements from the parent render, so the tree bails out untouched. + */ +export function FileExplorerHostModeProvider({ + activeWorktreeId, + worktreePath, + children +}: { + activeWorktreeId: string | null + worktreePath: string | null + children: React.ReactNode +}): React.JSX.Element { + const hostMode = useFileExplorerHostMode({ activeWorktreeId, worktreePath }) + return {children} +} + +export function FileExplorerHostAwareToolbar( + props: Omit, 'hostMode'> +): React.JSX.Element { + const hostMode = useFileExplorerHostModeContext() + return ( + + ) +} + +/** Contents search covers the workspace, so choosing it in Host mode returns to Project first. */ +export function FileExplorerHostAwareQueryStrip( + props: React.ComponentProps +): React.JSX.Element { + const { active, exit } = useFileExplorerHostModeContext() + const { onSelectView } = props + return ( + { + if (active && view === 'search') { + exit() + } + onSelectView(view) + }} + /> + ) +} + +/** Hides Project-only chrome in Host mode without unmounting it. */ +export function FileExplorerProjectOnly({ + children +}: { + children: React.ReactNode +}): React.JSX.Element { + const { active } = useFileExplorerHostModeContext() + return
{children}
+} + +/** Project UI covered by the Host overlay must not take focus or keystrokes (Tab, focus requests). */ +export function FileExplorerHostInertBoundary({ + className = 'h-full min-h-0', + children +}: { + className?: string + children: React.ReactNode +}): React.JSX.Element { + const { active } = useFileExplorerHostModeContext() + return ( +
+ {children} +
+ ) +} + +/** Layered over the tree so entering Host mode never shifts the surrounding layout. */ +export function FileExplorerHostOverlay({ + showDotfiles +}: { + showDotfiles: boolean +}): React.JSX.Element | null { + const hostMode = useFileExplorerHostModeContext() + if (!hostMode.active) { + return null + } + return ( +
+
+ + +
+
+ ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode.test.ts b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode.test.ts new file mode 100644 index 000000000000..a6091984f984 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode.test.ts @@ -0,0 +1,323 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + fetchHostDirectoryListing, + filterHostEntries, + getHostBrowseSource, + planHostFileOpen, + resolveHostEntry +} from './file-explorer-host-mode' + +const { browseRuntimeDir, callRuntimeRpc, hostAbsentRefusal } = vi.hoisted(() => ({ + browseRuntimeDir: vi.fn(), + callRuntimeRpc: vi.fn(), + hostAbsentRefusal: vi.fn() +})) +vi.mock('../../../terminal-pane/host-files/host-file-refusal', () => ({ hostAbsentRefusal })) +vi.mock('@/runtime/files/reads/runtime-server-directory-browser', () => ({ + browseRuntimeServerDirectory: browseRuntimeDir +})) +vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc })) + +const browseHostDir = vi.fn() +const resolveHostBrowseEntry = vi.fn() +const listFiles = vi.fn() +const search = vi.fn() + +beforeEach(() => { + for (const mock of [ + browseHostDir, + resolveHostBrowseEntry, + listFiles, + search, + browseRuntimeDir, + callRuntimeRpc, + hostAbsentRefusal + ]) { + mock.mockReset() + } + vi.stubGlobal('window', { + api: { fs: { browseHostDir, resolveHostBrowseEntry, listFiles, search } } + }) +}) + +const runtime = { + kind: 'runtime', + environmentId: 'env-1', + executionHostId: 'ssh:box' +} as const + +const file = { name: 'notes.txt', isDirectory: false, isSymlink: false } +const link = { name: 'link', isDirectory: false, isSymlink: true } +const dir = { name: 'src', isDirectory: true, isSymlink: false } + +describe('getHostBrowseSource', () => { + it('browses local workspaces on the desktop client and runtime-owned ones anywhere', () => { + expect(getHostBrowseSource({ kind: 'local' }, true)).toEqual({ kind: 'local' }) + expect(getHostBrowseSource(runtime, true)).toEqual(runtime) + expect(getHostBrowseSource(runtime, false)).toEqual(runtime) + }) + + it('is unavailable for local without the desktop APIs, bare SSH owners, and while unresolved', () => { + expect(getHostBrowseSource({ kind: 'local' }, false)).toBeNull() + expect(getHostBrowseSource({ kind: 'ssh', connectionId: 'ssh-1' }, true)).toBeNull() + expect(getHostBrowseSource({ kind: 'unresolved' }, true)).toBeNull() + }) +}) + +describe('fetchHostDirectoryListing', () => { + it('lists local directories through the names-only host channel', async () => { + const listing = { resolvedPath: '/home/allen', entries: [dir], pathFlavor: 'posix' } + browseHostDir.mockResolvedValue(listing) + + await expect(fetchHostDirectoryListing({ kind: 'local' }, '/home/allen')).resolves.toBe(listing) + expect(browseHostDir).toHaveBeenCalledWith({ dirPath: '/home/allen' }) + expect(listFiles).not.toHaveBeenCalled() + expect(search).not.toHaveBeenCalled() + }) + + it('lists runtime-owned hosts through the host runtime, not the desktop channel', async () => { + const listing = { resolvedPath: '/Data2/allen', entries: [dir], pathFlavor: 'posix' } + browseRuntimeDir.mockResolvedValue(listing) + + await expect(fetchHostDirectoryListing(runtime, '/Data2/allen')).resolves.toBe(listing) + expect(browseRuntimeDir).toHaveBeenCalledWith('env-1', '/Data2/allen') + expect(browseHostDir).not.toHaveBeenCalled() + }) +}) + +describe('resolveHostEntry', () => { + const root = '/home/allen/codes' + const workspace = { worktreeId: 'wt-1', worktreePath: root } + const resolution = (overrides: Record) => ({ + worktree: 'wt-1', + relativePath: null, + absolutePath: '/home/allen/x', + exists: true, + isDirectory: false, + ...overrides + }) + + it('trusts listed directories without a round trip', async () => { + await expect( + resolveHostEntry({ kind: 'local' }, '/home/allen/src', dir, workspace) + ).resolves.toEqual({ + kind: 'directory', + realPath: '/home/allen/src', + workspaceRelativePath: null + }) + expect(resolveHostBrowseEntry).not.toHaveBeenCalled() + }) + + it('classifies local non-directories in the main process', async () => { + const resolved = { kind: 'directory', realPath: '/mnt/data', workspaceRelativePath: null } + resolveHostBrowseEntry.mockResolvedValue(resolved) + + await expect( + resolveHostEntry({ kind: 'local' }, '/home/allen/link', link, workspace) + ).resolves.toEqual(resolved) + expect(resolveHostBrowseEntry).toHaveBeenCalledWith({ + targetPath: '/home/allen/link', + workspaceRoot: root + }) + }) + + it('asks the host runtime about the clicked path in this workspace, never main', async () => { + callRuntimeRpc.mockResolvedValue(resolution({ isDirectory: true })) + + await expect(resolveHostEntry(runtime, '/home/allen/x', link, workspace)).resolves.toEqual({ + kind: 'directory', + realPath: '/home/allen/x', + workspaceRelativePath: null + }) + expect(callRuntimeRpc).toHaveBeenCalledWith( + { kind: 'environment', environmentId: 'env-1' }, + 'files.resolveTerminalPath', + { worktree: 'id:wt-1', pathText: '/home/allen/x' } + ) + expect(resolveHostBrowseEntry).not.toHaveBeenCalled() + }) + + it('opens a runtime file inside the workspace by its workspace path', async () => { + callRuntimeRpc.mockResolvedValue( + resolution({ + relativePath: 'src/a.ts', + absolutePath: `${root}/src/a.ts`, + openTarget: { + kind: 'worktree-file', + provider: 'local', + relativePath: 'src/a.ts', + absolutePath: `${root}/src/a.ts` + } + }) + ) + + await expect(resolveHostEntry(runtime, `${root}/src/a.ts`, file, workspace)).resolves.toEqual({ + kind: 'file', + realPath: `${root}/src/a.ts`, + workspaceRelativePath: 'src/a.ts' + }) + }) + + it("carries the host's single-file grant and canonical path for an outside file", async () => { + callRuntimeRpc.mockResolvedValue( + resolution({ + absolutePath: '/srv/real/notes.txt', + openTarget: { + kind: 'absolute-file', + provider: 'local', + absolutePath: '/srv/real/notes.txt', + grantId: 'grant-1' + } + }) + ) + + await expect(resolveHostEntry(runtime, '/home/allen/x', file, workspace)).resolves.toEqual({ + kind: 'file', + realPath: '/srv/real/notes.txt', + workspaceRelativePath: null, + grantId: 'grant-1' + }) + }) + + it('reports a vanished workspace file as missing and an ungranted one as unsupported', async () => { + callRuntimeRpc.mockResolvedValueOnce( + resolution({ + exists: false, + relativePath: 'src/gone.ts', + absolutePath: `${root}/src/gone.ts` + }) + ) + await expect(resolveHostEntry(runtime, `${root}/src/gone.ts`, file, workspace)).rejects.toThrow( + /ENOENT/ + ) + expect(hostAbsentRefusal).not.toHaveBeenCalled() + + callRuntimeRpc.mockResolvedValueOnce(resolution({})) + await expect(resolveHostEntry(runtime, '/home/allen/x', file, workspace)).resolves.toEqual({ + kind: 'unsupported', + realPath: '/home/allen/x', + workspaceRelativePath: null + }) + }) +}) + +describe('resolveHostEntry outside the workspace', () => { + it("lets the host's capability decide what an absent outside file means", async () => { + const refusal = new Error('Update Orca on hostbox to open files outside its workspaces') + hostAbsentRefusal.mockResolvedValue(refusal) + callRuntimeRpc.mockResolvedValue({ + worktree: 'wt-1', + relativePath: null, + absolutePath: '/home/allen/notes.txt', + exists: false, + isDirectory: false + }) + + await expect( + resolveHostEntry(runtime, '/home/allen/notes.txt', file, { + worktreeId: 'wt-1', + worktreePath: '/home/allen/codes' + }) + ).rejects.toBe(refusal) + expect(hostAbsentRefusal).toHaveBeenCalledWith('env-1', '/home/allen/notes.txt') + }) + + it('enters an outside folder symlink that such a host can list, and refuses one it cannot', async () => { + const workspace = { worktreeId: 'wt-1', worktreePath: '/home/allen/codes' } + callRuntimeRpc.mockResolvedValue({ + worktree: 'wt-1', + relativePath: null, + absolutePath: '/home/allen/linkdir', + exists: false, + isDirectory: false + }) + browseRuntimeDir.mockResolvedValueOnce({ + resolvedPath: '/srv/x', + entries: [], + pathFlavor: 'posix' + }) + + await expect( + resolveHostEntry(runtime, '/home/allen/linkdir', link, workspace) + ).resolves.toEqual({ + kind: 'directory', + realPath: '/home/allen/linkdir', + workspaceRelativePath: null + }) + expect(browseRuntimeDir).toHaveBeenCalledWith('env-1', '/home/allen/linkdir') + expect(hostAbsentRefusal).not.toHaveBeenCalled() + + const refusal = new Error('refused') + hostAbsentRefusal.mockResolvedValue(refusal) + browseRuntimeDir.mockRejectedValueOnce(new Error('ENOTDIR')) + await expect(resolveHostEntry(runtime, '/home/allen/linkdir', link, workspace)).rejects.toBe( + refusal + ) + browseRuntimeDir.mockClear() + await expect(resolveHostEntry(runtime, '/home/allen/notes.txt', file, workspace)).rejects.toBe( + refusal + ) + expect(browseRuntimeDir, 'a plain file is never probed').not.toHaveBeenCalled() + }) +}) + +describe('planHostFileOpen', () => { + it('opens workspace files through the writable tree path, including symlinks pointing in', () => { + expect( + planHostFileOpen({ + worktreePath: '/home/allen/codes', + entryPath: '/home/allen/shortcut/a.ts', + workspaceRelativePath: 'src/a.ts' + }) + ).toEqual({ + kind: 'workspace', + filePath: '/home/allen/codes/src/a.ts', + relativePath: 'src/a.ts' + }) + }) + + it('keeps a workspace symlink that leaves the workspace read-only (canonical verdict wins)', () => { + expect( + planHostFileOpen({ + worktreePath: '/home/allen/codes', + entryPath: '/home/allen/codes/link-out', + workspaceRelativePath: null + }) + ).toEqual({ kind: 'external', filePath: '/home/allen/codes/link-out' }) + }) + + it('opens a granted outside file at the canonical path its grant is bound to', () => { + expect( + planHostFileOpen({ + worktreePath: '/home/allen/codes', + entryPath: '/home/allen/link-out', + workspaceRelativePath: null, + realPath: '/srv/real/notes.txt', + grantId: 'grant-1' + }) + ).toEqual({ kind: 'external', filePath: '/srv/real/notes.txt', grantId: 'grant-1' }) + }) + + it('keeps Windows workspace files on the workspace separator', () => { + expect( + planHostFileOpen({ + worktreePath: 'C:\\Users\\allen\\codes', + entryPath: 'C:\\Users\\allen\\codes\\src\\a.ts', + workspaceRelativePath: 'src\\a.ts' + }) + ).toEqual({ + kind: 'workspace', + filePath: 'C:\\Users\\allen\\codes\\src\\a.ts', + relativePath: 'src/a.ts' + }) + }) +}) + +describe('filterHostEntries', () => { + it('filters only the listed folder by name and honors hidden dotfiles', () => { + const entries = [dir, file, { name: '.ssh', isDirectory: true, isSymlink: false }] + expect(filterHostEntries(entries, 'NOTES', true)).toEqual([file]) + expect(filterHostEntries(entries, '', false)).toEqual([dir, file]) + expect(filterHostEntries(entries, 'ssh', true)).toHaveLength(1) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode.ts b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode.ts new file mode 100644 index 000000000000..22e5373df0b6 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-mode.ts @@ -0,0 +1,165 @@ +import { joinPath } from '@/lib/path' +import { normalizeRelativePath } from '../../../../../../shared/file-access/cross-platform-path' +import { filterEntries } from '../../../sidebar/host-path-browser/remote-file-browser-entry-actions' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' +import type { + HostBrowseEntryResolution, + HostDirectoryListing +} from '../../../../../../shared/file-listing/host-directory-browse' +import type { RuntimeTerminalPathResolution } from '../../../../../../shared/terminal/runtime-terminal-file-path' +import { browseRuntimeServerDirectory } from '@/runtime/files/reads/runtime-server-directory-browser' +import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +import { toRuntimeWorktreeSelector } from '@/runtime/rpc/targets/runtime-worktree-selector' +import { hostAbsentRefusal } from '../../../terminal-pane/host-files/host-file-refusal' +import type { FileExplorerOperationOwner } from '../tree/file-explorer-types' +import type { ExecutionHostId } from '../../../../../../shared/execution-host/execution-host' + +export type HostBrowseSource = + | { kind: 'local' } + | { kind: 'runtime'; environmentId: string; executionHostId: ExecutionHostId } + +/** A host's verdict on a clicked entry; `grantId` is the host's single-file read grant. */ +export type HostEntryResolution = HostBrowseEntryResolution & { grantId?: string } + +/** Null when Host mode cannot browse this workspace's host from this client. */ +export function getHostBrowseSource( + owner: FileExplorerOperationOwner, + hasDesktopHostBrowse: boolean +): HostBrowseSource | null { + // Why: SSH workspaces run on the host's runtime; a bare SSH owner has no file provider to open with. + if (owner.kind === 'runtime') { + return { + kind: 'runtime', + environmentId: owner.environmentId, + executionHostId: owner.executionHostId + } + } + return owner.kind === 'local' && hasDesktopHostBrowse ? { kind: 'local' } : null +} + +export function hasDesktopHostBrowseApi(): boolean { + return ( + typeof window.api.fs.browseHostDir === 'function' && + typeof window.api.fs.resolveHostBrowseEntry === 'function' + ) +} + +function requireDesktopFs(): Required< + Pick +> { + const { browseHostDir, resolveHostBrowseEntry } = window.api.fs + if (!browseHostDir || !resolveHostBrowseEntry) { + throw new Error('Host browsing is not available in this client') + } + return { browseHostDir, resolveHostBrowseEntry } +} + +export async function fetchHostDirectoryListing( + source: HostBrowseSource, + dirPath: string +): Promise { + return source.kind === 'local' + ? requireDesktopFs().browseHostDir({ dirPath }) + : browseRuntimeServerDirectory(source.environmentId, dirPath) +} + +async function listsAsDirectory(environmentId: string, path: string): Promise { + try { + await browseRuntimeServerDirectory(environmentId, path) + return true + } catch { + return false + } +} + +export async function resolveHostEntry( + source: HostBrowseSource, + entryPath: string, + entry: DirEntry, + workspace: { worktreeId: string; worktreePath: string } +): Promise { + if (entry.isDirectory) { + return { kind: 'directory', realPath: entryPath, workspaceRelativePath: null } + } + if (source.kind === 'local') { + return requireDesktopFs().resolveHostBrowseEntry({ + targetPath: entryPath, + workspaceRoot: workspace.worktreePath + }) + } + const resolved = await callRuntimeRpc( + { kind: 'environment', environmentId: source.environmentId }, + 'files.resolveTerminalPath', + { worktree: toRuntimeWorktreeSelector(workspace.worktreeId), pathText: entryPath } + ) + if (!resolved.exists) { + if (resolved.relativePath !== null) { + throw new Error(`ENOENT: not found: ${entryPath}`) + } + // Why: hosts without outside-file grants answer "absent" for every path outside their + // workspaces, so a symlinked folder there is only provable by listing it. + if (entry.isSymlink && (await listsAsDirectory(source.environmentId, entryPath))) { + return { kind: 'directory', realPath: entryPath, workspaceRelativePath: null } + } + throw await hostAbsentRefusal(source.environmentId, resolved.absolutePath ?? entryPath) + } + const realPath = resolved.absolutePath ?? entryPath + const target = resolved.openTarget + if (resolved.isDirectory) { + return { kind: 'directory', realPath, workspaceRelativePath: null } + } + if (target?.kind === 'worktree-file') { + return { kind: 'file', realPath, workspaceRelativePath: target.relativePath } + } + if (target?.kind === 'absolute-file') { + // Why: the grant is bound to the host's canonical path, so the tab must read that path. + return { + kind: 'file', + realPath: target.absolutePath, + workspaceRelativePath: null, + grantId: target.grantId + } + } + return { kind: 'unsupported', realPath, workspaceRelativePath: null } +} + +export type HostFileOpenPlan = + | { kind: 'workspace'; filePath: string; relativePath: string } + | { kind: 'external'; filePath: string; grantId?: string } + +// Why: ownership follows main's canonical verdict, so a workspace symlink that leaves the +// workspace stays read-only and one pointing in reuses the tree's tab. +export function planHostFileOpen({ + worktreePath, + entryPath, + workspaceRelativePath, + realPath, + grantId +}: { + worktreePath: string + entryPath: string + workspaceRelativePath: string | null + realPath?: string + grantId?: string +}): HostFileOpenPlan { + return workspaceRelativePath + ? { + kind: 'workspace', + filePath: joinPath(worktreePath, workspaceRelativePath), + relativePath: normalizeRelativePath(workspaceRelativePath) + } + : grantId && realPath + ? { kind: 'external', filePath: realPath, grantId } + : { kind: 'external', filePath: entryPath } +} + +export function filterHostEntries( + entries: DirEntry[], + query: string, + showDotfiles: boolean +): DirEntry[] { + return filterEntries( + showDotfiles ? entries : entries.filter((entry) => !entry.name.startsWith('.')), + query + ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-open.test.ts b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-open.test.ts new file mode 100644 index 000000000000..9903c5b83802 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-open.test.ts @@ -0,0 +1,80 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { openFileMock } = vi.hoisted(() => ({ openFileMock: vi.fn() })) + +vi.mock('@/store', () => ({ useAppStore: { getState: () => ({ openFile: openFileMock }) } })) + +import { openHostFile } from './file-explorer-host-open' + +beforeEach(() => { + openFileMock.mockReset() +}) + +describe('openHostFile', () => { + it('opens files outside the workspace read-only and marks them session-only', () => { + openHostFile({ + plan: { kind: 'external', filePath: '/home/allen/.bashrc' }, + source: { kind: 'local' }, + worktreeId: 'wt-1' + }) + + const [file, options] = openFileMock.mock.calls[0] ?? [] + expect(file).toEqual( + expect.objectContaining({ + filePath: '/home/allen/.bashrc', + relativePath: '/home/allen/.bashrc', + worktreeId: 'wt-1', + mode: 'edit', + readOnly: true, + hostBrowse: true, + runtimeEnvironmentId: null + }) + ) + expect(file).not.toHaveProperty('liveTail') + expect(file).not.toHaveProperty('terminalArtifactGrantId') + expect(options).toEqual(expect.objectContaining({ suppressActiveRuntimeFallback: true })) + }) + + it("reads runtime-host files through the host's runtime and its single-file grant", () => { + const runtime = { kind: 'runtime', environmentId: 'env-1', executionHostId: 'ssh:box' } as const + openHostFile({ + plan: { kind: 'external', filePath: '/srv/real/notes.md', grantId: 'grant-1' }, + source: runtime, + worktreeId: 'wt-1' + }) + openHostFile({ + plan: { kind: 'workspace', filePath: '/Data2/allen/project/a.ts', relativePath: 'a.ts' }, + source: runtime, + worktreeId: 'wt-1' + }) + + expect(openFileMock.mock.calls[0]?.[0]).toEqual( + expect.objectContaining({ + readOnly: true, + hostBrowse: true, + runtimeEnvironmentId: 'env-1', + terminalArtifactGrantId: 'grant-1' + }) + ) + expect(openFileMock.mock.calls[1]?.[0]).toEqual( + expect.objectContaining({ relativePath: 'a.ts', runtimeEnvironmentId: 'env-1' }) + ) + expect(openFileMock.mock.calls[1]?.[0]).not.toHaveProperty('terminalArtifactGrantId') + for (const [, options] of openFileMock.mock.calls) { + expect(options).toEqual(expect.objectContaining({ suppressActiveRuntimeFallback: false })) + } + }) + + it('opens workspace files through the normal writable Explorer path', () => { + openHostFile({ + plan: { kind: 'workspace', filePath: '/home/allen/codes/src/a.ts', relativePath: 'src/a.ts' }, + source: { kind: 'local' }, + worktreeId: 'wt-1' + }) + + const [file] = openFileMock.mock.calls[0] ?? [] + expect(file).toEqual(expect.objectContaining({ relativePath: 'src/a.ts' })) + expect(file).not.toHaveProperty('readOnly') + expect(file).not.toHaveProperty('hostBrowse') + }) +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-open.ts b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-open.ts new file mode 100644 index 000000000000..49a14568c349 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/file-explorer-host-open.ts @@ -0,0 +1,41 @@ +import { detectLanguage } from '../../../../../../shared/editor-language/editor-language-detect' +import { useAppStore } from '@/store' +import type { HostBrowseSource, HostFileOpenPlan } from './file-explorer-host-mode' + +export function openHostFile({ + plan, + source, + worktreeId +}: { + plan: HostFileOpenPlan + source: HostBrowseSource + worktreeId: string +}): void { + const { openFile } = useAppStore.getState() + const external = plan.kind === 'external' + openFile( + { + filePath: plan.filePath, + // Why: relativePath === filePath is the external-file contract the editor reads by. + relativePath: external ? plan.filePath : plan.relativePath, + worktreeId, + runtimeEnvironmentId: source.kind === 'runtime' ? source.environmentId : null, + language: detectLanguage(plan.filePath), + mode: 'edit', + ...(external + ? { + readOnly: true, + hostBrowse: true, + ...(plan.grantId ? { terminalArtifactGrantId: plan.grantId } : {}) + } + : {}) + }, + { + preview: true, + focusEditor: true, + ...(external ? { forceContentReload: true } : {}), + // Why: only a local open may skip the runtime; a runtime open must keep its owner. + suppressActiveRuntimeFallback: source.kind === 'local' + } + ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-browser.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-browser.test.tsx new file mode 100644 index 000000000000..814eca344c0f --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-browser.test.tsx @@ -0,0 +1,337 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { HostDirectoryListing } from '../../../../../../shared/file-listing/host-directory-browse' +import type * as HostModeModule from './file-explorer-host-mode' +import type { HostBrowseSource } from './file-explorer-host-mode' +import { + useFileExplorerHostBrowser, + type FileExplorerHostBrowser +} from './use-file-explorer-host-browser' +import { HostFileRefusal } from '../../../terminal-pane/host-files/host-file-refusal' + +const { fetchListingMock, resolveEntryMock, openHostFileMock } = vi.hoisted(() => ({ + fetchListingMock: vi.fn(), + resolveEntryMock: vi.fn(), + openHostFileMock: vi.fn() +})) + +vi.mock('./file-explorer-host-mode', async (importOriginal) => ({ + ...(await importOriginal()), + fetchHostDirectoryListing: fetchListingMock, + resolveHostEntry: resolveEntryMock +})) +vi.mock('./file-explorer-host-open', () => ({ openHostFile: openHostFileMock })) +const { toastErrorMock } = vi.hoisted(() => ({ toastErrorMock: vi.fn() })) +vi.mock('sonner', () => ({ toast: { error: toastErrorMock } })) +vi.mock('../../../terminal-pane/host-files/host-file-refusal', () => ({ + HostFileRefusal: class HostFileRefusal extends Error {} +})) + +function listingFor(path: string, flavor: 'posix' | 'win32' = 'posix'): HostDirectoryListing { + return { resolvedPath: path, entries: [], pathFlavor: flavor } +} + +async function flush(): Promise { + for (let i = 0; i < 6; i += 1) { + await Promise.resolve() + } +} + +type Props = { + active: boolean + visit?: string + source?: HostBrowseSource | null + worktreePath?: string +} + +const local: HostBrowseSource = { kind: 'local' } + +let root: Root +let latest: FileExplorerHostBrowser + +function Harness(props: Props): null { + const { active, visit = '1', source = local, worktreePath = '/home/allen/codes' } = props + latest = useFileExplorerHostBrowser({ + source, + worktreePath, + visitKey: active ? visit : null, + worktreeId: 'wt-1' + }) + return null +} + +async function render(props: Props): Promise { + await act(async () => { + root.render() + await flush() + }) +} + +async function run(action: () => void): Promise { + await act(async () => { + action() + await flush() + }) +} + +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + fetchListingMock.mockReset() + fetchListingMock.mockImplementation(async (_source: HostBrowseSource, path: string) => + listingFor(path, /^[A-Z]:/.test(path) ? 'win32' : 'posix') + ) + resolveEntryMock.mockReset() + openHostFileMock.mockReset() + toastErrorMock.mockReset() + root = createRoot(document.createElement('div')) +}) + +afterEach(() => { + act(() => root.unmount()) +}) + +describe('useFileExplorerHostBrowser', () => { + it('stays idle in Project mode', async () => { + await render({ active: false }) + + expect(fetchListingMock).not.toHaveBeenCalled() + expect(latest.listing).toBeNull() + expect(latest.canNavigateUp).toBe(false) + }) + + it('navigates to breadcrumb targets and cannot climb above /', async () => { + await render({ active: true }) + + await run(() => latest.navigate('/')) + expect(latest.listing?.resolvedPath).toBe('/') + expect(latest.canNavigateUp).toBe(false) + + const calls = fetchListingMock.mock.calls.length + await run(() => latest.navigateUp()) + expect(fetchListingMock.mock.calls.length).toBe(calls) + }) + + it('walks Windows paths up to the drive root, then the drive list', async () => { + await render({ active: true, worktreePath: 'C:\\Users\\allen\\codes' }) + + await run(() => latest.navigateUp()) + expect(latest.listing?.resolvedPath).toBe('C:\\Users\\allen') + + await run(() => latest.navigate('C:\\')) + await run(() => latest.navigateUp()) + expect(fetchListingMock).toHaveBeenLastCalledWith(local, '/') + }) + + it('browses a runtime host and opens a granted outside file at its canonical path', async () => { + const runtime: HostBrowseSource = { + kind: 'runtime', + environmentId: 'env-1', + executionHostId: 'ssh:box' + } + await render({ active: true, source: runtime, worktreePath: '/Data2/allen921103/project' }) + + await run(() => latest.navigateUp()) + resolveEntryMock.mockResolvedValueOnce({ + kind: 'directory', + realPath: '/Data2/allen921103/other', + workspaceRelativePath: null + }) + await run(() => latest.activateEntry({ name: 'other', isDirectory: true, isSymlink: false })) + expect(fetchListingMock).toHaveBeenLastCalledWith(runtime, '/Data2/allen921103/other') + + resolveEntryMock.mockResolvedValueOnce({ + kind: 'file', + realPath: '/srv/real/notes.md', + workspaceRelativePath: null, + grantId: 'grant-1' + }) + await run(() => latest.activateEntry({ name: 'notes.md', isDirectory: false, isSymlink: true })) + expect(resolveEntryMock).toHaveBeenLastCalledWith( + runtime, + '/Data2/allen921103/other/notes.md', + { name: 'notes.md', isDirectory: false, isSymlink: true }, + { worktreeId: 'wt-1', worktreePath: '/Data2/allen921103/project' } + ) + expect(openHostFileMock).toHaveBeenLastCalledWith( + expect.objectContaining({ + plan: { kind: 'external', filePath: '/srv/real/notes.md', grantId: 'grant-1' }, + source: runtime + }) + ) + }) + + it('ignores a slow listing that a newer navigation superseded', async () => { + await render({ active: true }) + const slow = Promise.withResolvers() + fetchListingMock.mockImplementationOnce(() => slow.promise) + + await run(() => latest.navigate('/slow')) + await run(() => latest.navigate('/fast')) + await run(() => slow.resolve(listingFor('/slow'))) + + expect(latest.listing?.resolvedPath).toBe('/fast') + }) + + it('follows symlinked directories and opens resolved files', async () => { + await render({ active: true }) + await run(() => latest.navigateUp()) + + resolveEntryMock.mockResolvedValueOnce({ + kind: 'directory', + realPath: '/mnt/data', + workspaceRelativePath: null + }) + await run(() => latest.activateEntry({ name: 'data', isDirectory: false, isSymlink: true })) + expect(fetchListingMock).toHaveBeenLastCalledWith(local, '/home/allen/data') + + resolveEntryMock.mockResolvedValueOnce({ + kind: 'file', + realPath: '/home/allen/data/x.txt', + workspaceRelativePath: null + }) + await run(() => latest.activateEntry({ name: 'x.txt', isDirectory: false, isSymlink: false })) + expect(openHostFileMock).toHaveBeenCalledWith( + expect.objectContaining({ + plan: { kind: 'external', filePath: '/home/allen/data/x.txt' }, + worktreeId: 'wt-1' + }) + ) + }) + + it('starts each new visit at the workspace root', async () => { + await render({ active: true, visit: '1' }) + await run(() => latest.navigateUp()) + + await render({ active: false, visit: '1' }) + expect(latest.listing).toBeNull() + + await render({ active: true, visit: '2' }) + expect(latest.listing?.resolvedPath).toBe('/home/allen/codes') + }) + + it.each([ + { + name: 'the user navigates elsewhere', + entry: { name: 'link', isDirectory: false, isSymlink: true }, + interrupt: () => run(() => latest.navigate('/var')), + after: () => expect(latest.listing?.resolvedPath, 'the new folder stays shown').toBe('/var') + }, + { + name: 'the visit ends', + entry: { name: 'notes.md', isDirectory: false, isSymlink: false }, + interrupt: () => render({ active: false }) + } + ])('drops a slow click resolution once $name', async ({ entry, interrupt, after }) => { + await render({ active: true }) + const click = Promise.withResolvers() + resolveEntryMock.mockImplementationOnce(() => click.promise) + + await run(() => latest.activateEntry(entry)) + await interrupt() + await run(() => + click.resolve({ + kind: 'file', + realPath: `/home/allen/codes/${entry.name}`, + workspaceRelativePath: null + }) + ) + + after?.() + expect(openHostFileMock).not.toHaveBeenCalled() + }) + + it("shows the host's own refusal for a file it will not open", async () => { + await render({ active: true }) + resolveEntryMock.mockRejectedValueOnce( + new HostFileRefusal('Update Orca on hostbox to open files outside its workspaces') + ) + + await run(() => + latest.activateEntry({ name: 'notes.txt', isDirectory: false, isSymlink: false }) + ) + + expect(toastErrorMock).toHaveBeenCalledWith( + 'Update Orca on hostbox to open files outside its workspaces' + ) + expect(openHostFileMock).not.toHaveBeenCalled() + }) + + it('stays on the current folder when a folder cannot be opened', async () => { + await render({ active: true }) + fetchListingMock.mockRejectedValueOnce(new Error('EACCES: permission denied')) + + await run(() => latest.navigate('/root')) + + expect(latest.error).toBeNull() + expect(latest.loading).toBe(false) + expect(latest.listing?.resolvedPath).toBe('/home/allen/codes') + expect(toastErrorMock).toHaveBeenCalledTimes(1) + await run(() => latest.navigateUp()) + expect(latest.listing?.resolvedPath).toBe('/home/allen') + expect(fetchListingMock, 'navigateUp lists the parent folder').toHaveBeenLastCalledWith( + local, + '/home/allen' + ) + }) + + it('shows a full error only when the first Host listing fails', async () => { + fetchListingMock.mockRejectedValueOnce(new Error('connection lost')) + + await render({ active: true }) + + expect(latest.listing).toBeNull() + expect(latest.error).toMatch(/connection lost/) + }) + + it('keeps the spinner hidden for fast listings and shows it for slow ones', async () => { + vi.useFakeTimers() + try { + await render({ active: true }) + fetchListingMock.mockImplementationOnce(() => new Promise(() => {})) + + await run(() => latest.navigate('/slow')) + expect(latest.loading).toBe(true) + expect(latest.showLoading).toBe(false) + + await act(async () => { + vi.advanceTimersByTime(250) + }) + expect(latest.showLoading).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it('keeps a shown spinner visible for the minimum hold after the listing lands', async () => { + vi.useFakeTimers() + try { + await render({ active: true }) + let resolveListing: (listing: HostDirectoryListing) => void = () => {} + fetchListingMock.mockImplementationOnce( + () => new Promise((resolve) => (resolveListing = resolve)) + ) + + await run(() => latest.navigate('/slow')) + await act(async () => { + vi.advanceTimersByTime(250) + }) + expect(latest.showLoading).toBe(true) + + await act(async () => { + resolveListing(listingFor('/slow')) + }) + expect(latest.loading).toBe(false) + expect(latest.showLoading).toBe(true) + + await act(async () => { + vi.advanceTimersByTime(400) + }) + expect(latest.showLoading).toBe(false) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-browser.ts b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-browser.ts new file mode 100644 index 000000000000..9ae6c0cd9547 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-browser.ts @@ -0,0 +1,262 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { extractIpcErrorMessage } from '@/runtime/errors/ipc-error' +import { isMissingRuntimePathError } from '@/runtime/files/metadata/runtime-file-metadata-client' +import { HostFileRefusal } from '../../../terminal-pane/host-files/host-file-refusal' +import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' +import type { HostDirectoryListing } from '../../../../../../shared/file-listing/host-directory-browse' +import { + joinPath, + parentPath +} from '../../../sidebar/host-path-browser/remote-file-browser-entry-actions' +import { + fetchHostDirectoryListing, + planHostFileOpen, + resolveHostEntry, + type HostBrowseSource +} from './file-explorer-host-mode' +import { openHostFile } from './file-explorer-host-open' + +// Why: local listings land in a few ms; a spinner that short reads as a glitch (STYLEGUIDE UX rule 1). +const HOST_LOADING_SHOW_DELAY_MS = 200 +// Why: once shown, a spinner that vanishes a few ms later flickers just the same. +const HOST_LOADING_MIN_VISIBLE_MS = 400 + +export type FileExplorerHostBrowser = { + listing: HostDirectoryListing | null + loading: boolean + /** `loading` once it has outlasted HOST_LOADING_SHOW_DELAY_MS, held for HOST_LOADING_MIN_VISIBLE_MS; drives visible spinners. */ + showLoading: boolean + error: string | null + canNavigateUp: boolean + navigate: (dirPath: string) => void + navigateUp: () => void + refresh: () => void + activateEntry: (entry: DirEntry) => void +} + +type HostBrowserSession = { + key: string + listing: HostDirectoryListing | null + error: string | null + pendingPath: string | null +} + +/** One browsing session per Host visit; `visitKey` is null outside Host mode. */ +export function useFileExplorerHostBrowser({ + visitKey: sessionKey, + source, + worktreeId, + worktreePath +}: { + visitKey: string | null + source: HostBrowseSource | null + worktreeId: string | null + worktreePath: string | null +}): FileExplorerHostBrowser { + const [session, setSession] = useState(null) + const current = session && session.key === sessionKey ? session : null + // Why: breadcrumb clicks race over SSH exec channels; only the latest request may land. + const listingGenerationRef = useRef(0) + const activationGenerationRef = useRef(0) + // Why: source objects are rebuilt each render; requests only need the latest host. + const sourceRef = useRef(source) + const sessionRef = useRef(session) + useLayoutEffect(() => { + sourceRef.current = source + sessionRef.current = session + }) + + const startListing = useCallback((key: string, dirPath: string, generation: number) => { + const source = sourceRef.current + if (!source) { + return + } + void fetchHostDirectoryListing(source, dirPath).then( + (next) => { + if (generation === listingGenerationRef.current) { + setSession({ key, listing: next, error: null, pendingPath: null }) + } + }, + (err: unknown) => { + if (generation !== listingGenerationRef.current) { + return + } + const message = extractIpcErrorMessage(err, 'Unknown error') + const previous = sessionRef.current + if (previous?.key === key && previous.listing) { + // Why: like Finder/MobaXterm, an unopenable folder leaves you where you were. + setSession({ ...previous, pendingPath: null }) + toast.error( + translate( + 'fileExplorer.host.folderOpenFailed', + 'Could not open this folder: {{error}}', + { + error: message + } + ) + ) + return + } + setSession({ key, listing: null, error: message, pendingPath: null }) + } + ) + }, []) + + useEffect(() => { + const generation = ++listingGenerationRef.current + activationGenerationRef.current++ + if (sessionKey && worktreePath) { + startListing(sessionKey, worktreePath, generation) + } + }, [sessionKey, startListing, worktreePath]) + + const navigate = useCallback( + (dirPath: string) => { + if (!sessionKey) { + return + } + const generation = ++listingGenerationRef.current + // Why: a slow click resolution must not pull the user back after they navigated away. + activationGenerationRef.current++ + setSession((prev) => + prev?.key === sessionKey + ? { ...prev, pendingPath: dirPath } + : { key: sessionKey, listing: null, error: null, pendingPath: dirPath } + ) + startListing(sessionKey, dirPath, generation) + }, + [sessionKey, startListing] + ) + + const listing = current?.listing ?? null + const loading = sessionKey !== null && (current === null || current.pendingPath !== null) + const [shownLoadingKey, setShownLoadingKey] = useState(null) + const shownLoadingAtRef = useRef(0) + useEffect(() => { + if (sessionKey === null) { + setShownLoadingKey(null) + return + } + if (loading) { + if (shownLoadingKey === sessionKey) { + return + } + const timer = setTimeout(() => { + shownLoadingAtRef.current = Date.now() + setShownLoadingKey(sessionKey) + }, HOST_LOADING_SHOW_DELAY_MS) + return () => clearTimeout(timer) + } + if (shownLoadingKey === null) { + return + } + if (shownLoadingKey !== sessionKey) { + setShownLoadingKey(null) + return + } + const remaining = HOST_LOADING_MIN_VISIBLE_MS - (Date.now() - shownLoadingAtRef.current) + const timer = setTimeout(() => setShownLoadingKey(null), Math.max(0, remaining)) + return () => clearTimeout(timer) + }, [loading, sessionKey, shownLoadingKey]) + const showLoading = sessionKey !== null && shownLoadingKey === sessionKey + const currentPath = listing?.resolvedPath ?? null + const parent = currentPath ? parentPath(currentPath, listing?.pathFlavor ?? 'posix') : null + const canNavigateUp = !loading && currentPath !== null && parent !== currentPath + + const navigateUp = useCallback(() => { + if (canNavigateUp && parent) { + navigate(parent) + } + }, [canNavigateUp, navigate, parent]) + + const refresh = useCallback(() => { + const target = currentPath ?? worktreePath + if (target) { + navigate(target) + } + }, [currentPath, navigate, worktreePath]) + + const activateEntry = useCallback( + (entry: DirEntry) => { + if (!source || !listing || !worktreeId || !worktreePath) { + return + } + const entryPath = joinPath(listing.resolvedPath, entry.name, listing.pathFlavor) + const generation = ++activationGenerationRef.current + void resolveHostEntry(source, entryPath, entry, { worktreeId, worktreePath }).then( + (resolution) => { + if (generation !== activationGenerationRef.current) { + return + } + if (resolution.kind === 'directory') { + navigate(entryPath) + return + } + if (resolution.kind === 'unsupported') { + toast.error( + translate('fileExplorer.host.unsupportedEntry', 'This item cannot be opened.') + ) + return + } + openHostFile({ + plan: planHostFileOpen({ + worktreePath, + entryPath, + workspaceRelativePath: resolution.workspaceRelativePath, + realPath: resolution.realPath, + grantId: resolution.grantId + }), + source, + worktreeId + }) + }, + (err: unknown) => { + if (generation !== activationGenerationRef.current) { + return + } + // Why: loss of contact with the host is not evidence the file is gone. + toast.error( + isMissingRuntimePathError(err) + ? translate('fileExplorer.host.entryMissing', 'This item no longer exists.') + : err instanceof HostFileRefusal + ? err.message + : translate( + 'fileExplorer.host.entryUnverifiable', + 'Could not reach this item: {{error}}', + { error: extractIpcErrorMessage(err, 'Unknown error') } + ) + ) + } + ) + }, + [listing, navigate, source, worktreeId, worktreePath] + ) + + const error = current?.error ?? null + return useMemo( + () => ({ + listing, + loading, + showLoading, + error, + canNavigateUp, + navigate, + navigateUp, + refresh, + activateEntry + }), + [ + listing, + loading, + showLoading, + error, + canNavigateUp, + navigate, + navigateUp, + refresh, + activateEntry + ] + ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-mode.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-mode.test.tsx new file mode 100644 index 000000000000..25bc362698ba --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-mode.test.tsx @@ -0,0 +1,184 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createStore, type StoreApi } from 'zustand/vanilla' +import { useStore } from 'zustand' +import { useFileExplorerHostMode, type FileExplorerHostMode } from './use-file-explorer-host-mode' + +type FakeState = { + sshTargetLabels: Map + runtimeEnvironments: { id: string; name: string }[] + sshStateByEnvironment: Map< + string, + { targetLabels: Map; removedTargetLabels: Map } + > + fileSearchStateByWorktree: Record +} + +let mockStore: StoreApi + +vi.mock('@/store', () => { + const api = () => mockStore + const useAppStore = (selector: (state: FakeState) => T): T => useStore(api(), selector) + useAppStore.subscribe = (listener: (s: FakeState, p: FakeState) => void) => + api().subscribe(listener) + useAppStore.getState = () => api().getState() + return { useAppStore } +}) +const { ownerKind } = vi.hoisted(() => ({ ownerKind: { current: 'local' } })) +vi.mock('../navigation/file-explorer-operation-owner', () => ({ + getFileExplorerOperationOwnerFromState: (state: FakeState) => + !state || ownerKind.current === 'unresolved' + ? { kind: 'unresolved' } + : ownerKind.current === 'local' + ? { kind: 'local' } + : { + kind: 'runtime', + environmentId: ownerKind.current, + executionHostId: `ssh:${ownerKind.current}` + } +})) +const { visitKeys } = vi.hoisted(() => { + const visitKeys: (string | null)[] = [] + return { visitKeys } +}) +vi.mock('./use-file-explorer-host-browser', () => ({ + useFileExplorerHostBrowser: ({ visitKey }: { visitKey: string | null }) => { + visitKeys.push(visitKey) + return {} + } +})) + +let root: Root +let latest: FileExplorerHostMode + +function Harness({ worktreeId = 'wt-1' }: { worktreeId?: string }): null { + latest = useFileExplorerHostMode({ activeWorktreeId: worktreeId, worktreePath: '/repo' }) + return null +} + +beforeEach(async () => { + ownerKind.current = 'local' + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + mockStore = createStore(() => ({ + sshTargetLabels: new Map(), + runtimeEnvironments: [], + sshStateByEnvironment: new Map(), + fileSearchStateByWorktree: {} + })) + Object.defineProperty(window, 'api', { + configurable: true, + value: { fs: { browseHostDir: vi.fn(), resolveHostBrowseEntry: vi.fn() } } + }) + root = createRoot(document.createElement('div')) + await act(async () => root.render()) +}) + +afterEach(() => { + act(() => root.unmount()) +}) + +const api = () => mockStore + +describe('useFileExplorerHostMode', () => { + it('returns to Project mode when a workspace Contents search is requested', async () => { + await act(async () => latest.enter()) + expect(latest.active).toBe(true) + + await act(async () => + api().setState({ fileSearchStateByWorktree: { 'wt-1': { focusRequestId: 1 } } }) + ) + expect(latest.active).toBe(false) + + await act(async () => latest.enter()) + await act(async () => + api().setState({ + fileSearchStateByWorktree: { 'wt-1': { focusRequestId: 1, seedRequestId: 3 } } + }) + ) + expect(latest.active).toBe(false) + }) + + it('ignores search requests for other workspaces', async () => { + await act(async () => latest.enter()) + + await act(async () => + api().setState({ fileSearchStateByWorktree: { 'wt-2': { focusRequestId: 1 } } }) + ) + + expect(latest.active).toBe(true) + }) + + it('ends Host mode when the user leaves the workspace, even after coming back', async () => { + await act(async () => latest.enter()) + await act(async () => latest.setFilterQuery('notes')) + expect(latest.active).toBe(true) + + await act(async () => root.render()) + expect(latest.active).toBe(false) + + await act(async () => root.render()) + expect(latest.active).toBe(false) + expect(latest.filterQuery).toBe('') + }) + + it('gives every entry a fresh browsing session so an old listing never reappears', async () => { + await act(async () => latest.enter()) + const firstVisit = visitKeys.at(-1) + await act(async () => latest.exit()) + expect(visitKeys.at(-1)).toBeNull() + + await act(async () => latest.enter()) + + expect(firstVisit).not.toBeNull() + expect(visitKeys.at(-1)).not.toBeNull() + expect(visitKeys.at(-1)).not.toBe(firstVisit) + }) + + it('ends Host mode when the host becomes unavailable, even after it returns', async () => { + await act(async () => latest.enter()) + expect(latest.active).toBe(true) + + ownerKind.current = 'unresolved' + await act(async () => api().setState({ fileSearchStateByWorktree: {} })) + expect(latest.active).toBe(false) + + ownerKind.current = 'local' + await act(async () => api().setState({ fileSearchStateByWorktree: {} })) + expect(latest.active).toBe(false) + }) + + it("labels a runtime-owned SSH host by the runtime's name for that target", async () => { + ownerKind.current = 'env-1' + await act(async () => + api().setState({ + sshStateByEnvironment: new Map([ + [ + 'env-1', + { targetLabels: new Map([['env-1', 'GPU box']]), removedTargetLabels: new Map() } + ] + ]) + }) + ) + + expect(latest.available).toBe(true) + expect(latest.hostLabel).toBe('GPU box') + }) + + it('ends Host mode when the workspace is repointed to another host', async () => { + ownerKind.current = 'env-1' + await act(async () => api().setState({ fileSearchStateByWorktree: {} })) + await act(async () => latest.enter()) + expect(latest.active).toBe(true) + + ownerKind.current = 'env-2' + await act(async () => api().setState({ fileSearchStateByWorktree: {} })) + expect(latest.active).toBe(false) + + ownerKind.current = 'env-1' + await act(async () => api().setState({ fileSearchStateByWorktree: {} })) + expect(latest.active).toBe(false) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-mode.ts b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-mode.ts new file mode 100644 index 000000000000..670413112ba8 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/host-mode/use-file-explorer-host-mode.ts @@ -0,0 +1,115 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useShallow } from 'zustand/react/shallow' +import { useAppStore } from '@/store' +import { + getExecutionHostLabel, + LOCAL_EXECUTION_HOST_ID +} from '../../../../../../shared/execution-host/execution-host' +import { selectExecutionHostDisplayLabel } from '@/runtime/hosts/display/execution-host-display-label' +import { getFileExplorerOperationOwnerFromState } from '../navigation/file-explorer-operation-owner' +import { + getHostBrowseSource, + hasDesktopHostBrowseApi, + type HostBrowseSource +} from './file-explorer-host-mode' +import { + useFileExplorerHostBrowser, + type FileExplorerHostBrowser +} from './use-file-explorer-host-browser' + +export type FileExplorerHostMode = { + active: boolean + hostLabel: string + filterQuery: string + setFilterQuery: (query: string) => void + enter: () => void + exit: () => void + /** False when this workspace's host cannot be browsed from this client. */ + available: boolean + browser: FileExplorerHostBrowser +} + +type HostVisit = { worktreeId: string; hostKey: string; entry: number } + +function getHostKey(source: HostBrowseSource | null): string | null { + if (!source) { + return null + } + return source.kind === 'runtime' ? `${source.environmentId}@${source.executionHostId}` : 'local' +} + +/** Host mode is a session-only visit to one workspace; leaving the workspace ends it. */ +export function useFileExplorerHostMode({ + activeWorktreeId, + worktreePath +}: { + activeWorktreeId: string | null + worktreePath: string | null +}): FileExplorerHostMode { + const [visit, setVisit] = useState(null) + const [filterQuery, setFilterQuery] = useState('') + // Why: every entry gets a fresh browsing session, so a later visit never reuses an old listing. + const entryCounterRef = useRef(0) + const owner = useAppStore( + useShallow((s) => getFileExplorerOperationOwnerFromState(s, activeWorktreeId)) + ) + const source = useMemo(() => getHostBrowseSource(owner, hasDesktopHostBrowseApi()), [owner]) + const hostKey = getHostKey(source) + // Why: a visit belongs to one workspace on one host. Leaving the workspace, losing the host + // (e.g. owner briefly unresolved during reconnect) or repointing it to another host ends the + // visit, so a listing from another machine is never shown or clicked. Adjusted during render, + // not in an effect, so a stale visit never paints. + if (visit && (visit.worktreeId !== activeWorktreeId || visit.hostKey !== hostKey)) { + setVisit(null) + setFilterQuery('') + } + const active = visit !== null + + const hostLabel = useAppStore((s) => + source?.kind === 'runtime' + ? selectExecutionHostDisplayLabel(s, source.executionHostId, { + sshEnvironmentId: source.environmentId + }) + : getExecutionHostLabel(LOCAL_EXECUTION_HOST_ID) + ) + + const browser = useFileExplorerHostBrowser({ + visitKey: active ? `${visit.entry}` : null, + source, + worktreeId: activeWorktreeId, + worktreePath + }) + + const enter = useCallback(() => { + if (hostKey && activeWorktreeId) { + setVisit({ worktreeId: activeWorktreeId, hostKey, entry: ++entryCounterRef.current }) + } + }, [activeWorktreeId, hostKey]) + const exit = useCallback(() => { + setVisit(null) + setFilterQuery('') + }, []) + + // Why: a workspace Contents search (seed or focus request) must be visible, not run behind the Host overlay. + useEffect(() => { + if (!active || !activeWorktreeId) { + return + } + return useAppStore.subscribe((state, prev) => { + const next = state.fileSearchStateByWorktree[activeWorktreeId] + const before = prev.fileSearchStateByWorktree[activeWorktreeId] + if ( + next?.seedRequestId !== before?.seedRequestId || + next?.focusRequestId !== before?.focusRequestId + ) { + exit() + } + }) + }, [active, activeWorktreeId, exit]) + + const available = source !== null + return useMemo( + () => ({ active, available, hostLabel, filterQuery, setFilterQuery, enter, exit, browser }), + [active, available, hostLabel, filterQuery, enter, exit, browser] + ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorer.host-mode.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorer.host-mode.test.tsx new file mode 100644 index 000000000000..74f4d496cd84 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorer.host-mode.test.tsx @@ -0,0 +1,242 @@ +// @vitest-environment happy-dom + +import { act, useEffect } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const h = vi.hoisted(() => ({ + hostActive: false, + setHostActive: (_active: boolean) => {}, + treeMounts: 0, + treeUnmounts: 0, + treeRenders: 0, + enter: () => {}, + exit: () => {} +})) + +const state = { + rightSidebarExplorerView: 'files', + setRightSidebarExplorerView: vi.fn(), + showRightSidebarFiles: () => {}, + showRightSidebarSearch: () => {}, + activeWorktreeId: 'wt-1', + expandedDirs: {}, + collapseAllDirs: () => {}, + activeFileId: null, + openFiles: [], + rightSidebarOpen: true, + showDotfilesByWorktree: {}, + toggleShowDotfilesForWorktree: () => {}, + explorerDisplayRootByWorktree: {}, + runtimeEnvironments: [], + repos: [] +} + +vi.mock('@/store', () => ({ + useAppStore: (selector: (s: typeof state) => unknown) => selector(state) +})) +vi.mock('@/store/workspaces/selection/use-selected-worktree', () => ({ + useActiveWorktree: () => ({ id: 'wt-1', repoId: 'repo-1', path: '/home/allen/codes' }) +})) +vi.mock('@/store/repos/use-repository-catalog', () => ({ useRepoById: () => null })) +vi.mock('../tree/FileExplorerFilesTreePane', () => ({ + FileExplorerFilesTreePane: () => { + h.treeRenders += 1 + useEffect(() => { + h.treeMounts += 1 + return () => { + h.treeUnmounts += 1 + } + }, []) + return
+ } +})) +vi.mock('./FileExplorerToolbar', () => ({ + FileExplorerToolbar: ({ hostMode }: { hostMode: { onToggle: () => void } }) => ( + + + + + {hostModeLabel} + + + {hostOverlay ?
: null} +
+ ) +} + +// Why: Host mode can leave focus on the shared toolbar, so Delete must not reach the hidden tree. +it.each([ + ['trashes the selection without the Host overlay', false, [[[selectedFile]]]], + ['leaves the hidden tree alone under the Host overlay', true, []] +])('Delete with focus on the toolbar %s', (_label, hostOverlay, expected) => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + const requestDeleteAll = vi.fn() + act(() => root.render()) + container.querySelector('button')?.focus() + + h.keydown?.(new KeyboardEvent('keydown', { key: 'Delete' })) + + expect(requestDeleteAll.mock.calls).toEqual(expected) + act(() => root.unmount()) + container.remove() +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/selection/useFileExplorerKeys.ts b/src/renderer/src/components/right-sidebar/file-explorer/selection/useFileExplorerKeys.ts index c889093b9792..516af36cfea8 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer/selection/useFileExplorerKeys.ts +++ b/src/renderer/src/components/right-sidebar/file-explorer/selection/useFileExplorerKeys.ts @@ -31,6 +31,12 @@ export function shouldIgnoreFileExplorerKeyTarget(target: EventTarget | null): b ) } +// Why: Host mode covers the tree but can leave focus on shared chrome (toolbar); tree +// shortcuts would otherwise act on the hidden tree's selection (Delete trashes it). +function isExplorerTreeCoveredByHostMode(shell: Element | null): boolean { + return shell?.querySelector('[data-file-explorer-host-overlay]') != null +} + /** Scope all explorer shortcuts to its focused container so editor/terminal input remains untouched. */ export function useFileExplorerKeys(opts: { containerRef: React.RefObject @@ -151,6 +157,9 @@ export function useFileExplorerKeys(opts: { if (shouldIgnoreFileExplorerKeyTarget(e.target)) { return } + if (isExplorerTreeCoveredByHostMode(opts.containerRef.current)) { + return + } // Undo owns the whole shell, including Radix’s scrollbar sibling outside the viewport. const inExplorer = focusInExplorer() diff --git a/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx b/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx index 2d126189a796..bbabc29d8bc3 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx +++ b/src/renderer/src/components/sidebar/host-path-browser/RemoteFileBrowserBreadcrumbs.tsx @@ -2,6 +2,7 @@ import React, { useCallback } from 'react' import { ChevronRight, ArrowUp, Home } from 'lucide-react' import { cn } from '@/lib/class-names' import { driveBreadcrumbPath, splitBrowsePath } from './remote-file-browser-drive-paths' +import { parentPath } from './remote-file-browser-entry-actions' import type { FilesystemPathFlavor } from '../../../../../shared/file-access/filesystem-path-flavor' type RemoteFileBrowserBreadcrumbsProps = { @@ -22,11 +23,21 @@ export function RemoteFileBrowserBreadcrumbs({ // Retain drive separator shape when reconstructing breadcrumb paths. const browseParts = splitBrowsePath(resolvedPath, pathFlavor) const pathSegments = browseParts.segments + const anchorRoot = + browseParts.kind === 'drive' + ? browseParts.driveRoot + : browseParts.kind === 'unc' + ? browseParts.uncRoot + : null const breadcrumbPathTo = useCallback( (segmentIndex: number): string => - browseParts.kind === 'drive' - ? driveBreadcrumbPath(browseParts.driveRoot, browseParts.segments, segmentIndex) - : `/${browseParts.segments.slice(0, segmentIndex + 1).join('/')}`, + browseParts.kind === 'posix' + ? `/${browseParts.segments.slice(0, segmentIndex + 1).join('/')}` + : driveBreadcrumbPath( + browseParts.kind === 'drive' ? browseParts.driveRoot : browseParts.uncRoot, + browseParts.segments, + segmentIndex + ), [browseParts] ) @@ -35,7 +46,7 @@ export function RemoteFileBrowserBreadcrumbs({
- - {browseParts.kind === 'drive' && ( + {browseParts.kind !== 'unc' && ( + + )} + {anchorRoot !== null && ( <> - + {browseParts.kind === 'drive' && ( + + )} )} diff --git a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts index aaf7a0662510..fe174f5ed297 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-drive-paths.ts @@ -1,6 +1,7 @@ export type BrowsePathParts = | { kind: 'posix'; segments: string[] } | { kind: 'drive'; driveRoot: string; segments: string[] } + | { kind: 'unc'; uncRoot: string; segments: string[] } // Bare `M:` is a root here because forwarding it would be drive-relative. const DRIVE_ANCHOR_RE = /^[A-Za-z]:([\\/]|$)/ @@ -17,10 +18,30 @@ export function driveRootOf(p: string): string { return `${p[0].toUpperCase()}:\\` } +// `\\server\share`, `\\?\UNC\server\share` and `\\?\C:` roots; nothing is browsable above them. +const UNC_ROOT_RE = + /^(?:[\\/]{2}\?[\\/](?:UNC[\\/][^\\/]+[\\/][^\\/]+|[A-Za-z]:)|[\\/]{2}(?![?.][\\/])[^\\/]+[\\/][^\\/]+)/i + +export function uncRootOf(p: string): string | null { + const match = UNC_ROOT_RE.exec(p) + return match ? `${match[0].replace(/\//g, '\\')}\\` : null +} + export function splitBrowsePath( p: string, pathFlavor: FilesystemPathFlavor = 'posix' ): BrowsePathParts { + const uncRoot = pathFlavor === 'win32' ? uncRootOf(p) : null + if (uncRoot) { + return { + kind: 'unc', + uncRoot, + segments: p + .slice(uncRoot.length - 1) + .split(/[\\/]/) + .filter(Boolean) + } + } if (pathFlavor === 'win32' && isDrivePath(p)) { return { kind: 'drive', @@ -51,6 +72,17 @@ export function parentOfDrivePath(p: string): string { : `${parts.driveRoot}${parentSegments.join('\\')}` } +// UNC share roots have no browsable parent, so up stays put. +export function parentOfUncPath(p: string): string { + const parts = splitBrowsePath(p, 'win32') + if (parts.kind !== 'unc') { + return p + } + return parts.segments.length === 0 + ? p + : driveBreadcrumbPath(parts.uncRoot, parts.segments, parts.segments.length - 2) +} + export function driveBreadcrumbPath( driveRoot: string, segments: string[], diff --git a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.test.ts b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.test.ts new file mode 100644 index 000000000000..80e805966be8 --- /dev/null +++ b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { joinPath, parentPath } from './remote-file-browser-entry-actions' + +describe('UNC paths', () => { + it('stops at the share root when walking up', () => { + expect(parentPath('\\\\wsl.localhost\\Ubuntu\\home\\allen', 'win32')).toBe( + '\\\\wsl.localhost\\Ubuntu\\home' + ) + expect(parentPath('\\\\wsl.localhost\\Ubuntu\\home', 'win32')).toBe( + '\\\\wsl.localhost\\Ubuntu\\' + ) + expect(parentPath('\\\\wsl.localhost\\Ubuntu\\', 'win32')).toBe('\\\\wsl.localhost\\Ubuntu\\') + expect(parentPath('\\\\server\\share', 'win32')).toBe('\\\\server\\share') + expect(parentPath('\\\\server\\share\\', 'win32')).toBe('\\\\server\\share\\') + expect(parentPath('//server/share', 'win32')).toBe('//server/share') + expect(parentPath('\\\\?\\UNC\\server\\share', 'win32')).toBe('\\\\?\\UNC\\server\\share') + expect(parentPath('\\\\?\\UNC\\server\\share\\dir', 'win32')).toBe( + '\\\\?\\UNC\\server\\share\\' + ) + expect(parentPath('\\\\?\\C:\\Users\\allen', 'win32')).toBe('\\\\?\\C:\\Users') + expect(parentPath('\\\\?\\C:\\', 'win32')).toBe('\\\\?\\C:\\') + expect(parentPath('\\\\?\\C:', 'win32')).toBe('\\\\?\\C:') + }) + + it('joins below a UNC root with a backslash', () => { + expect(joinPath('\\\\wsl.localhost\\Ubuntu\\', 'home', 'win32')).toBe( + '\\\\wsl.localhost\\Ubuntu\\home' + ) + expect(joinPath('\\\\server\\share\\dir', 'x', 'win32')).toBe('\\\\server\\share\\dir\\x') + }) + + it('treats SSH-Windows forward-slash drive paths as drives, not POSIX or UNC', () => { + expect(parentPath('C:/Users/allen/codes', 'win32')).toBe('C:\\Users\\allen') + expect(parentPath('C:/', 'win32')).toBe('/') + expect(parentPath('//server/share/dir', 'posix')).toBe('//server/share') + }) +}) diff --git a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts index fcd52789b584..bd0bbdbf3577 100644 --- a/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts +++ b/src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.ts @@ -6,7 +6,9 @@ import { driveRootOf, isDrivePath, joinDrivePath, - parentOfDrivePath + parentOfDrivePath, + parentOfUncPath, + uncRootOf } from './remote-file-browser-drive-paths' export type DirEntry = { @@ -23,7 +25,7 @@ export function isRemoteFileBrowserFilterQueryTooLarge( return isClipboardTextByteLengthOverLimit(query, maxBytes) } -export function filterEntries(entries: DirEntry[], filter: string): DirEntry[] { +export function filterEntries(entries: T[], filter: string): T[] { if (isRemoteFileBrowserFilterQueryTooLarge(filter)) { return [] } @@ -67,13 +69,16 @@ export function joinPath( if (pathFlavor === 'win32' && resolvedPath === '/' && isDrivePath(name)) { return driveRootOf(name) } - if (pathFlavor === 'win32' && isDrivePath(resolvedPath)) { + if (pathFlavor === 'win32' && (isDrivePath(resolvedPath) || uncRootOf(resolvedPath))) { return joinDrivePath(resolvedPath, name) } return resolvedPath === '/' ? `/${name}` : `${resolvedPath}/${name}` } export function parentPath(p: string, pathFlavor: FilesystemPathFlavor = 'posix'): string { + if (pathFlavor === 'win32' && uncRootOf(p)) { + return parentOfUncPath(p) + } if (pathFlavor === 'win32' && isDrivePath(p)) { return parentOfDrivePath(p) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3af36c5d02af..26fcb4012da2 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -24789,6 +24789,20 @@ "folderLoadError": "Could not load this folder:", "emptyFolder": "No files in this folder" }, + "host": { + "returnToProject": "Return to workspace root", + "refresh": "Refresh folder", + "browsing": "Host: {{host}}", + "parentDirectory": "Parent directory", + "contentsUnavailable": "Contents search covers the workspace. Return to the workspace root to use it.", + "thisFolder": "this folder", + "enter": "Browse host filesystem", + "folderOpenFailed": "Could not open this folder: {{error}}", + "unsupportedEntry": "This item cannot be opened.", + "entryMissing": "This item no longer exists.", + "entryUnverifiable": "Could not reach this item: {{error}}", + "unavailable": "Host browsing is not available for this workspace" + }, "trashFailed": { "titleRecycleBin": "Couldn't move '{{name}}' to the Recycle Bin. Delete it permanently?", "titleTrash": "Couldn't move '{{name}}' to the Trash. Delete it permanently?", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 34615693a3f2..1d6dbecedfb7 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -21350,6 +21350,20 @@ "folderLoadError": "No se pudo cargar esta carpeta:", "emptyFolder": "No hay archivos en esta carpeta" }, + "host": { + "returnToProject": "Volver a la raíz del espacio de trabajo", + "refresh": "Actualizar carpeta", + "browsing": "Host: {{host}}", + "parentDirectory": "Carpeta superior", + "contentsUnavailable": "La búsqueda de contenido abarca el espacio de trabajo. Vuelve a la raíz del espacio de trabajo para usarla.", + "thisFolder": "esta carpeta", + "enter": "Explorar el sistema de archivos del host", + "folderOpenFailed": "No se pudo abrir esta carpeta: {{error}}", + "unsupportedEntry": "Este elemento no se puede abrir.", + "entryMissing": "Este elemento ya no existe.", + "entryUnverifiable": "No se pudo acceder a este elemento: {{error}}", + "unavailable": "La exploración del host no está disponible para este espacio de trabajo" + }, "trashFailed": { "titleRecycleBin": "No se pudo mover '{{name}}' a la Papelera de reciclaje. ¿Eliminarlo permanentemente?", "titleTrash": "No se pudo mover '{{name}}' a la Papelera. ¿Eliminarlo permanentemente?", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 0fa744b4d8a9..05e15a016cae 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -22081,6 +22081,20 @@ "folderLoadError": "Impossible de charger ce dossier :", "emptyFolder": "Aucun fichier dans ce dossier" }, + "host": { + "returnToProject": "Revenir à la racine de l’espace de travail", + "refresh": "Actualiser le dossier", + "browsing": "Hôte : {{host}}", + "parentDirectory": "Dossier parent", + "contentsUnavailable": "La recherche de contenu porte sur l’espace de travail. Revenez à la racine de l’espace de travail pour l’utiliser.", + "thisFolder": "ce dossier", + "enter": "Parcourir le système de fichiers de l’hôte", + "folderOpenFailed": "Impossible d’ouvrir ce dossier : {{error}}", + "unsupportedEntry": "Cet élément ne peut pas être ouvert.", + "entryMissing": "Cet élément n’existe plus.", + "entryUnverifiable": "Impossible d’accéder à cet élément : {{error}}", + "unavailable": "La navigation sur l’hôte n’est pas disponible pour cet espace de travail" + }, "trashFailed": { "titleRecycleBin": "Impossible de déplacer « {{name}} » vers la Corbeille. Le supprimer définitivement ?", "titleTrash": "Impossible de déplacer « {{name}} » vers la Corbeille. Le supprimer définitivement ?", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 6e711f7d7ddc..276889b185ed 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -22816,6 +22816,20 @@ "folderLoadError": "このフォルダーを読み込めませんでした:", "emptyFolder": "このフォルダーにはファイルがありません" }, + "host": { + "returnToProject": "ワークスペースのルートに戻る", + "refresh": "フォルダーを更新", + "browsing": "ホスト: {{host}}", + "parentDirectory": "親フォルダー", + "contentsUnavailable": "内容検索はワークスペースが対象です。使用するにはワークスペースのルートに戻ってください。", + "thisFolder": "このフォルダー", + "enter": "ホストのファイルシステムを参照", + "folderOpenFailed": "このフォルダーを開けませんでした: {{error}}", + "unsupportedEntry": "この項目は開けません。", + "entryMissing": "この項目はもう存在しません。", + "entryUnverifiable": "この項目にアクセスできませんでした: {{error}}", + "unavailable": "このワークスペースではホストの参照は使用できません" + }, "trashFailed": { "titleRecycleBin": "「{{name}}」をごみ箱に移動できませんでした。完全に削除しますか?", "titleTrash": "「{{name}}」をごみ箱に移動できませんでした。完全に削除しますか?", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 2110e082cd88..f6925b3fe631 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -21400,6 +21400,20 @@ "folderLoadError": "이 폴더를 불러오지 못했습니다:", "emptyFolder": "이 폴더에 파일이 없습니다" }, + "host": { + "returnToProject": "작업 공간 루트로 돌아가기", + "refresh": "폴더 새로 고침", + "browsing": "호스트: {{host}}", + "parentDirectory": "상위 폴더", + "contentsUnavailable": "내용 검색은 작업 공간을 대상으로 합니다. 사용하려면 작업 공간 루트로 돌아가세요.", + "thisFolder": "이 폴더", + "enter": "호스트 파일 시스템 탐색", + "folderOpenFailed": "이 폴더를 열 수 없습니다: {{error}}", + "unsupportedEntry": "이 항목은 열 수 없습니다.", + "entryMissing": "이 항목은 더 이상 존재하지 않습니다.", + "entryUnverifiable": "이 항목에 접근할 수 없습니다: {{error}}", + "unavailable": "이 작업 공간에서는 호스트 탐색을 사용할 수 없습니다" + }, "trashFailed": { "titleRecycleBin": "'{{name}}'을(를) 휴지통으로 이동하지 못했습니다. 영구적으로 삭제하시겠습니까?", "titleTrash": "'{{name}}'을(를) 휴지통으로 이동하지 못했습니다. 영구적으로 삭제하시겠습니까?", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index b2c234dc7fe3..5a2559cfd578 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -23238,6 +23238,20 @@ "folderLoadError": "无法加载此文件夹:", "emptyFolder": "此文件夹中没有文件" }, + "host": { + "returnToProject": "返回工作区根目录", + "refresh": "刷新文件夹", + "browsing": "主机:{{host}}", + "parentDirectory": "上级文件夹", + "contentsUnavailable": "内容搜索的范围是工作区。请返回工作区根目录后使用。", + "thisFolder": "此文件夹", + "enter": "浏览主机文件系统", + "folderOpenFailed": "无法打开此文件夹:{{error}}", + "unsupportedEntry": "无法打开此项目。", + "entryMissing": "此项目已不存在。", + "entryUnverifiable": "无法访问此项目:{{error}}", + "unavailable": "此工作区不支持浏览主机" + }, "trashFailed": { "titleRecycleBin": "无法将“{{name}}”移到回收站。是否永久删除?", "titleTrash": "无法将“{{name}}”移到废纸篓。是否永久删除?", diff --git a/src/renderer/src/lib/workspace/persistence/workspace-session-unified-tabs.ts b/src/renderer/src/lib/workspace/persistence/workspace-session-unified-tabs.ts index faf2b76959b2..3791400d6aee 100644 --- a/src/renderer/src/lib/workspace/persistence/workspace-session-unified-tabs.ts +++ b/src/renderer/src/lib/workspace/persistence/workspace-session-unified-tabs.ts @@ -141,6 +141,25 @@ export function buildPersistedUnifiedTabSessionData( snapshot.unifiedTabsByWorktree, snapshot.groupsByWorktree ) + // Why: Host-mode files are not persisted, and hydration keeps editor chrome with no + // backing file, so their tabs must not be written either. Incremental patches rely on + // `hostBrowse` only ever clearing alongside a tab-state change; a path that sets it on + // an existing tab must also re-trigger this rebuild. + const sessionOnlyEditorIds = new Set( + (snapshot.openFiles ?? []).filter((file) => file.hostBrowse === true).map((file) => file.id) + ) + if (sessionOnlyEditorIds.size > 0) { + for (const [worktreeId, tabs] of Object.entries(sourceTabs)) { + const kept = tabs.filter( + (tab) => + !(isEditorTabContentType(tab.contentType) && sessionOnlyEditorIds.has(tab.entityId)) + ) + // Why: the session cache is keyed by array identity; keep it when nothing was dropped. + if (kept.length !== tabs.length) { + sourceTabs[worktreeId] = kept + } + } + } return buildUnifiedTabSessionData(snapshot, sourceTabs, sourceGroups, cache) } diff --git a/src/renderer/src/lib/workspace/persistence/workspace-session.ts b/src/renderer/src/lib/workspace/persistence/workspace-session.ts index 42d396902c80..554a82a71a9f 100644 --- a/src/renderer/src/lib/workspace/persistence/workspace-session.ts +++ b/src/renderer/src/lib/workspace/persistence/workspace-session.ts @@ -132,7 +132,8 @@ export function buildEditorSessionData( | 'activeTabTypeByWorktree' | 'markdownFrontmatterVisible' > { - const editFiles = openFiles.filter((f) => f.mode === 'edit') + // Why: Host-mode tabs hold a session-only grant; restoring them would read without the file-only check. + const editFiles = openFiles.filter((f) => f.mode === 'edit' && f.hostBrowse !== true) const byWorktree: Record = {} const editFileIdsByWorktree: Record> = {} for (const f of editFiles) { diff --git a/src/renderer/src/store/slices/editor/hydration/editor-session-host-browse-restore.test.ts b/src/renderer/src/store/slices/editor/hydration/editor-session-host-browse-restore.test.ts new file mode 100644 index 000000000000..d554bff1b595 --- /dev/null +++ b/src/renderer/src/store/slices/editor/hydration/editor-session-host-browse-restore.test.ts @@ -0,0 +1,128 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + buildWorkspaceSessionPayload, + SESSION_RELEVANT_FIELDS +} from '../../../../lib/workspace/persistence/workspace-session' +import { buildWorkspaceSessionPatch } from '../../../../lib/workspace/persistence/workspace-session-patch' +import { createStoreSessionMockApi } from '../../../testing/app-store-session-api.test-fixture' +import { createTestStore } from '../../../testing/app-store-test-fixture' +import { makeWorktree } from '../../worktrees/worktree.test-fixture' + +vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) + +createStoreSessionMockApi() + +const WORKTREE_ID = 'repo-1::/workspace' +const WORKSPACE_FILE = '/workspace/src/a.ts' +const HOST_FILE = '/home/allen/.bashrc' + +function prepareStore() { + const store = createTestStore() + store.setState({ + repos: [ + { id: 'repo-1', path: '/workspace', displayName: 'Repo', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + 'repo-1': [makeWorktree({ id: WORKTREE_ID, repoId: 'repo-1', path: '/workspace' })] + }, + activeWorktreeId: WORKTREE_ID + }) + return store +} + +function openWorkspaceAndHostFiles(store: ReturnType): void { + store.getState().openFile( + { + filePath: WORKSPACE_FILE, + relativePath: 'src/a.ts', + worktreeId: WORKTREE_ID, + language: 'typescript', + mode: 'edit', + runtimeEnvironmentId: null + }, + { preview: false, suppressActiveRuntimeFallback: true } + ) + store.getState().openFile( + { + filePath: HOST_FILE, + relativePath: HOST_FILE, + worktreeId: WORKTREE_ID, + language: 'shell', + mode: 'edit', + readOnly: true, + hostBrowse: true, + runtimeEnvironmentId: null + }, + { preview: false, forceContentReload: true, suppressActiveRuntimeFallback: true } + ) +} + +describe('Explorer Host mode tabs across restart', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('drops the Host tab chrome with its file and keeps group references valid', () => { + const store = prepareStore() + openWorkspaceAndHostFiles(store) + const hostTab = store + .getState() + .unifiedTabsByWorktree[WORKTREE_ID]?.find( + (tab) => tab.contentType === 'editor' && tab.entityId === HOST_FILE + ) + expect(hostTab).toBeDefined() + expect(store.getState().activeFileIdByWorktree[WORKTREE_ID]).toBe(hostTab?.entityId) + + const persisted = buildWorkspaceSessionPayload(store.getState()) + const restarted = prepareStore() + restarted.getState().hydrateTabsSession(persisted) + restarted.getState().hydrateEditorSession(persisted) + const state = restarted.getState() + + const tabs = state.unifiedTabsByWorktree[WORKTREE_ID] ?? [] + expect(tabs.map((tab) => tab.entityId)).toEqual([WORKSPACE_FILE]) + expect(state.openFiles.map((file) => file.filePath)).toEqual([WORKSPACE_FILE]) + const tabIds = new Set(tabs.map((tab) => tab.id)) + for (const group of state.groupsByWorktree[WORKTREE_ID] ?? []) { + expect(group.activeTabId === null || tabIds.has(group.activeTabId)).toBe(true) + expect(group.tabOrder.every((tabId) => tabIds.has(tabId))).toBe(true) + } + expect(state.activeFileIdByWorktree[WORKTREE_ID]).not.toBe(hostTab?.entityId) + }) + + it('persists and patches the Host tab chrome once the file is reopened writable', () => { + const store = prepareStore() + openWorkspaceAndHostFiles(store) + const before = store.getState() + + store.getState().openFile({ + filePath: HOST_FILE, + relativePath: HOST_FILE, + worktreeId: WORKTREE_ID, + language: 'shell', + mode: 'edit', + runtimeEnvironmentId: null + }) + const after = store.getState() + const persisted = buildWorkspaceSessionPayload(after) + // Why: mirror the session writer, which patches only the fields whose references changed. + const changed = SESSION_RELEVANT_FIELDS.filter((field) => before[field] !== after[field]) + const patch = buildWorkspaceSessionPatch(after, changed) + + expect( + persisted.unifiedTabs?.[WORKTREE_ID]?.map((tab) => tab.entityId), + 'full payload persists the writable tab' + ).toContain(HOST_FILE) + expect( + persisted.openFilesByWorktree?.[WORKTREE_ID]?.map((file) => file.filePath), + 'full payload persists the writable file' + ).toContain(HOST_FILE) + expect(changed, 'tab chrome reference changes so the writer patches it').toContain( + 'unifiedTabsByWorktree' + ) + expect( + patch.unifiedTabs?.[WORKTREE_ID]?.map((tab) => tab.entityId), + 'incremental patch rewrites the tab chrome' + ).toEqual([WORKSPACE_FILE, HOST_FILE]) + }) +}) diff --git a/src/renderer/src/store/slices/editor/opening/editor-read-only-tabs.test.ts b/src/renderer/src/store/slices/editor/opening/editor-read-only-tabs.test.ts index 83e9870cbbb3..b7ea41eaa570 100644 --- a/src/renderer/src/store/slices/editor/opening/editor-read-only-tabs.test.ts +++ b/src/renderer/src/store/slices/editor/opening/editor-read-only-tabs.test.ts @@ -81,4 +81,77 @@ describe('read-only editor tabs (AI Vault View Log)', () => { ) expect(store.getState().editorDrafts[LOG_PATH]).toBeUndefined() }) + + describe('Explorer Host mode tabs', () => { + const HOST_PATH = '/home/user/.bashrc' + const openHostTab = (store: StoreApi): void => { + store.getState().openFile( + { + filePath: HOST_PATH, + relativePath: HOST_PATH, + worktreeId: 'wt-1', + language: 'shell', + mode: 'edit', + readOnly: true, + hostBrowse: true, + runtimeEnvironmentId: null + }, + { preview: true, forceContentReload: true, suppressActiveRuntimeFallback: true } + ) + } + const openWritable = (store: StoreApi): void => { + store.getState().openFile({ + filePath: HOST_PATH, + relativePath: HOST_PATH, + worktreeId: 'wt-1', + language: 'shell', + mode: 'edit', + runtimeEnvironmentId: null + }) + } + + it('only focuses an existing View Log tab without ending its live tail', () => { + const store = createEditorStore() + store.getState().openFile( + { + filePath: HOST_PATH, + relativePath: HOST_PATH, + worktreeId: 'wt-1', + language: 'shell', + mode: 'edit', + readOnly: true, + liveTail: true, + runtimeEnvironmentId: null + }, + { preview: false, forceContentReload: true, suppressActiveRuntimeFallback: true } + ) + + openHostTab(store) + + expect(store.getState().openFiles).toHaveLength(1) + expect(store.getState().openFiles[0]).toEqual( + expect.objectContaining({ readOnly: true, liveTail: true }) + ) + expect(store.getState().openFiles[0]?.hostBrowse).toBeUndefined() + }) + + it('drops the Host marker and captures owner provenance once opened writable', () => { + const store = createEditorStore() + openHostTab(store) + expect( + store.getState().openFiles[0]?.operationProvenance, + 'read-only Host tab carries no provenance' + ).toBeUndefined() + + openWritable(store) + + const tab = store.getState().openFiles[0] + expect(tab?.readOnly, 'tab is writable once reopened for edit').toBeUndefined() + expect(tab?.hostBrowse, 'Host marker is dropped once opened writable').toBeUndefined() + expect( + tab?.operationProvenance, + 'provenance captured on the read-only -> writable transition' + ).toBeDefined() + }) + }) }) diff --git a/src/renderer/src/store/slices/editor/opening/open-file-existing-tab-refresh.ts b/src/renderer/src/store/slices/editor/opening/open-file-existing-tab-refresh.ts index 8f3fbbee07d0..464cfbdbb039 100644 --- a/src/renderer/src/store/slices/editor/opening/open-file-existing-tab-refresh.ts +++ b/src/renderer/src/store/slices/editor/opening/open-file-existing-tab-refresh.ts @@ -27,9 +27,17 @@ export function refreshExistingOpenFile(args: { ) ? (existing.fileContentReloadNonce ?? 0) + 1 : existing.fileContentReloadNonce - // Normal open explicitly enables editing of a View Log; View Log must never downgrade an already writable tab. + // Normal open explicitly enables editing of a View Log or Explorer Host tab; read-only opens must never downgrade an already writable tab. const nextReadOnly = existing.readOnly === true && file.readOnly === true ? true : undefined - const nextLiveTail = file.liveTail === true && nextReadOnly === true ? true : undefined + // Why: a Host-mode open only focuses an existing View Log tab; it must not end its + // live tail or make it session-only. + const hostOpenOfReadOnlyTab = file.hostBrowse === true && nextReadOnly === true + const nextLiveTail = hostOpenOfReadOnlyTab + ? existing.liveTail + : file.liveTail === true && nextReadOnly === true + ? true + : undefined + const nextHostBrowse = hostOpenOfReadOnlyTab && existing.hostBrowse === true ? true : undefined const needsExistingUpdate = existing.mode !== file.mode || existing.diffSource !== file.diffSource || @@ -50,7 +58,8 @@ export function refreshExistingOpenFile(args: { existing.operationProvenance !== nextOperationProvenance || existing.fileContentReloadNonce !== fileContentReloadNonce || existing.readOnly !== nextReadOnly || - existing.liveTail !== nextLiveTail + existing.liveTail !== nextLiveTail || + existing.hostBrowse !== nextHostBrowse if (!needsExistingUpdate) { return null } @@ -77,6 +86,7 @@ export function refreshExistingOpenFile(args: { isPreview: updatedPreview, fileContentReloadNonce, readOnly: nextReadOnly, - liveTail: nextLiveTail + liveTail: nextLiveTail, + hostBrowse: nextHostBrowse } } diff --git a/src/renderer/src/store/slices/editor/types/open-file.ts b/src/renderer/src/store/slices/editor/types/open-file.ts index 7cace52f1f57..b238c59de722 100644 --- a/src/renderer/src/store/slices/editor/types/open-file.ts +++ b/src/renderer/src/store/slices/editor/types/open-file.ts @@ -91,6 +91,8 @@ export type OpenFile = { csvPreviewOnly?: boolean /** Why: explicit live tail, only meaningful for a read-only local log. */ liveTail?: boolean + /** Why: opened read-only from Explorer Host mode outside the workspace; never persisted, so restore cannot replay its path grant. */ + hostBrowse?: boolean mode: 'edit' | 'diff' | 'conflict-review' | 'markdown-preview' | 'check-details' | 'git-graph' } diff --git a/src/shared/file-listing/host-directory-browse.ts b/src/shared/file-listing/host-directory-browse.ts new file mode 100644 index 000000000000..678077ee4a39 --- /dev/null +++ b/src/shared/file-listing/host-directory-browse.ts @@ -0,0 +1,16 @@ +import type { FilesystemPathFlavor } from '../file-access/filesystem-path-flavor' +import type { DirEntry } from './directory-entry' + +export type HostDirectoryListing = { + resolvedPath: string + entries: DirEntry[] + pathFlavor: FilesystemPathFlavor +} + +/** Host-mode Explorer clicks: classification only; external files open read-only as user-named files. */ +export type HostBrowseEntryResolution = { + kind: 'directory' | 'file' | 'unsupported' + realPath: string + /** Canonical path relative to the canonical workspace root, or null when outside it. */ + workspaceRelativePath: string | null +}