Add remote SSH file download (#4957)

* Add remote SSH file download

Implement the remote file download flow described in docs/remote-file-download.md, including main/preload IPC wiring, SSH provider support, file explorer UI actions, and tests.

* Add open action to download toast

* rm design doc
This commit is contained in:
Jinjing
2026-06-08 23:12:01 -07:00
committed by GitHub
parent 03c2532ae7
commit 7d353523d1
13 changed files with 692 additions and 5 deletions
+274
View File
@@ -5,12 +5,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const handlers = new Map<string, (_event: unknown, args: unknown) => Promise<unknown> | unknown>()
const {
handleMock,
showSaveDialogMock,
fromWebContentsMock,
trashItemMock,
readdirMock,
readFileMock,
writeFileMock,
statMock,
openMock,
renameMock,
rmMock,
realpathMock,
lstatMock,
commitChangesMock,
@@ -40,12 +44,16 @@ const {
getSshGitProviderMock
} = vi.hoisted(() => ({
handleMock: vi.fn(),
showSaveDialogMock: vi.fn(),
fromWebContentsMock: vi.fn(),
trashItemMock: vi.fn(),
readdirMock: vi.fn(),
readFileMock: vi.fn(),
writeFileMock: vi.fn(),
statMock: vi.fn(),
openMock: vi.fn(),
renameMock: vi.fn(),
rmMock: vi.fn(),
realpathMock: vi.fn(),
lstatMock: vi.fn(),
commitChangesMock: vi.fn(),
@@ -76,6 +84,12 @@ const {
}))
vi.mock('electron', () => ({
BrowserWindow: {
fromWebContents: fromWebContentsMock
},
dialog: {
showSaveDialog: showSaveDialogMock
},
ipcMain: {
handle: handleMock
},
@@ -90,6 +104,8 @@ vi.mock('fs/promises', () => ({
writeFile: writeFileMock,
stat: statMock,
open: openMock,
rename: renameMock,
rm: rmMock,
realpath: realpathMock,
lstat: lstatMock
}))
@@ -200,12 +216,16 @@ describe('registerFilesystemHandlers', () => {
handlers.clear()
for (const mock of [
handleMock,
showSaveDialogMock,
fromWebContentsMock,
trashItemMock,
readdirMock,
readFileMock,
writeFileMock,
statMock,
openMock,
renameMock,
rmMock,
realpathMock,
lstatMock,
commitChangesMock,
@@ -255,8 +275,12 @@ describe('registerFilesystemHandlers', () => {
}
])
trashItemMock.mockResolvedValue(undefined)
showSaveDialogMock.mockResolvedValue({ canceled: true })
fromWebContentsMock.mockReturnValue(null)
getSshGitProviderMock.mockReturnValue(null)
statMock.mockResolvedValue({ size: 10, isDirectory: () => false, mtimeMs: 123 })
renameMock.mockResolvedValue(undefined)
rmMock.mockResolvedValue(undefined)
openMock.mockResolvedValue({
read: vi.fn(async (buffer: Buffer) => {
buffer.fill(0x61)
@@ -277,6 +301,256 @@ describe('registerFilesystemHandlers', () => {
)
})
it('rejects remote downloads with missing required arguments', async () => {
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!({ sender: {} }, { filePath: ' ', connectionId: 'ssh-1' })
).rejects.toThrow('filePath is required')
await expect(
handlers.get('fs:downloadFile')!({ sender: {} }, { filePath: '/remote/file.txt' })
).rejects.toThrow('connectionId is required')
expect(showSaveDialogMock).not.toHaveBeenCalled()
})
it('surfaces provider lookup errors for remote downloads before opening a dialog', async () => {
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/file.txt',
connectionId: 'ssh-1'
}
)
).rejects.toThrow(
'Remote connection dropped. Click Reconnect on the SSH target before retrying.'
)
expect(showSaveDialogMock).not.toHaveBeenCalled()
})
it('rejects remote download directories before opening a dialog', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 0, type: 'directory', mtime: 123 }),
downloadFile: vi.fn()
}
getSshFilesystemProviderMock.mockReturnValue(provider)
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/src',
connectionId: 'ssh-1'
}
)
).rejects.toThrow('Cannot download a directory')
expect(showSaveDialogMock).not.toHaveBeenCalled()
expect(provider.downloadFile).not.toHaveBeenCalled()
})
it('returns canceled remote downloads without transferring', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 }),
downloadFile: vi.fn()
}
getSshFilesystemProviderMock.mockReturnValue(provider)
showSaveDialogMock.mockResolvedValue({ canceled: true })
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/report.pdf',
connectionId: 'ssh-1'
}
)
).resolves.toEqual({ canceled: true })
expect(showSaveDialogMock).toHaveBeenCalledWith({ defaultPath: 'report.pdf' })
expect(statMock).not.toHaveBeenCalled()
expect(provider.downloadFile).not.toHaveBeenCalled()
})
it('parents the remote download save dialog and sanitizes reserved filename suggestions', async () => {
const parentWindow = { id: 7 }
const sender = { id: 42 }
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 }),
downloadFile: vi.fn()
}
getSshFilesystemProviderMock.mockReturnValue(provider)
fromWebContentsMock.mockReturnValue(parentWindow)
showSaveDialogMock.mockResolvedValue({ canceled: true })
registerFilesystemHandlers(store as never)
await handlers.get('fs:downloadFile')!(
{ sender },
{
filePath: 'C:\\repo\\CON.txt',
connectionId: 'ssh-1'
}
)
expect(fromWebContentsMock).toHaveBeenCalledWith(sender)
expect(showSaveDialogMock).toHaveBeenCalledWith(parentWindow, { defaultPath: 'download' })
})
it('rejects remote downloads when raw provider transfer is unavailable', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 })
}
getSshFilesystemProviderMock.mockReturnValue(provider)
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/file.txt',
connectionId: 'ssh-1'
}
)
).rejects.toThrow('Remote file download is unavailable. Reconnect the SSH target and retry.')
expect(showSaveDialogMock).not.toHaveBeenCalled()
})
it('rejects selected local directories before transferring a remote download', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 }),
downloadFile: vi.fn()
}
getSshFilesystemProviderMock.mockReturnValue(provider)
showSaveDialogMock.mockResolvedValue({ canceled: false, filePath: '/downloads/report.pdf' })
statMock.mockResolvedValue({ isDirectory: () => true })
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/report.pdf',
connectionId: 'ssh-1'
}
)
).rejects.toThrow('Cannot download to a directory')
expect(provider.downloadFile).not.toHaveBeenCalled()
})
it('downloads to a temp sibling then promotes a new destination', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 }),
downloadFile: vi.fn().mockResolvedValue(undefined)
}
getSshFilesystemProviderMock.mockReturnValue(provider)
showSaveDialogMock.mockResolvedValue({ canceled: false, filePath: '/downloads/report.pdf' })
statMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }))
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/report.pdf',
connectionId: 'ssh-1'
}
)
).resolves.toEqual({ canceled: false, destinationPath: '/downloads/report.pdf' })
const tempPath = provider.downloadFile.mock.calls[0][1]
expect(tempPath).toContain('/downloads')
expect(provider.downloadFile).toHaveBeenCalledWith('/remote/report.pdf', tempPath)
expect(renameMock).toHaveBeenCalledWith(tempPath, '/downloads/report.pdf')
expect(rmMock).not.toHaveBeenCalledWith(tempPath, expect.anything())
})
it('cleans up the temp sibling when remote download transfer fails', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 }),
downloadFile: vi.fn().mockRejectedValue(new Error('transfer failed'))
}
getSshFilesystemProviderMock.mockReturnValue(provider)
showSaveDialogMock.mockResolvedValue({ canceled: false, filePath: '/downloads/report.pdf' })
statMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }))
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/report.pdf',
connectionId: 'ssh-1'
}
)
).rejects.toThrow('transfer failed')
const tempPath = provider.downloadFile.mock.calls[0][1]
expect(renameMock).not.toHaveBeenCalled()
expect(rmMock).toHaveBeenCalledWith(tempPath, { force: true })
})
it('fails rather than overwriting a destination that appears after the dialog', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 }),
downloadFile: vi.fn().mockResolvedValue(undefined)
}
getSshFilesystemProviderMock.mockReturnValue(provider)
showSaveDialogMock.mockResolvedValue({ canceled: false, filePath: '/downloads/report.pdf' })
statMock
.mockRejectedValueOnce(Object.assign(new Error('missing'), { code: 'ENOENT' }))
.mockResolvedValueOnce({ isDirectory: () => false })
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/report.pdf',
connectionId: 'ssh-1'
}
)
).rejects.toThrow('Destination file appeared before download completed')
const tempPath = provider.downloadFile.mock.calls[0][1]
expect(renameMock).not.toHaveBeenCalled()
expect(rmMock).toHaveBeenCalledWith(tempPath, { force: true })
})
it('uses a backup swap when overwriting an existing destination', async () => {
const provider = {
stat: vi.fn().mockResolvedValue({ size: 10, type: 'file', mtime: 123 }),
downloadFile: vi.fn().mockResolvedValue(undefined)
}
getSshFilesystemProviderMock.mockReturnValue(provider)
showSaveDialogMock.mockResolvedValue({ canceled: false, filePath: '/downloads/report.pdf' })
statMock.mockResolvedValue({ isDirectory: () => false })
registerFilesystemHandlers(store as never)
await expect(
handlers.get('fs:downloadFile')!(
{ sender: {} },
{
filePath: '/remote/report.pdf',
connectionId: 'ssh-1'
}
)
).resolves.toEqual({ canceled: false, destinationPath: '/downloads/report.pdf' })
const tempPath = provider.downloadFile.mock.calls[0][1]
const backupPath = renameMock.mock.calls[0][1]
expect(renameMock.mock.calls[0]).toEqual(['/downloads/report.pdf', backupPath])
expect(renameMock.mock.calls[1]).toEqual([tempPath, '/downloads/report.pdf'])
expect(rmMock).toHaveBeenCalledWith(backupPath, { force: true })
})
it('rejects readFile when the real path escapes allowed roots', async () => {
const linkPath = path.resolve('/workspace/repo/link.txt')
realpathMock.mockImplementation(async (targetPath: string) => {
+136 -3
View File
@@ -1,7 +1,8 @@
/* eslint-disable max-lines */
import { ipcMain, shell } from 'electron'
import { readdir, readFile, writeFile, stat, lstat, open } from 'fs/promises'
import { extname, resolve } from 'path'
import { BrowserWindow, dialog, ipcMain, shell } from 'electron'
import { readdir, readFile, writeFile, stat, lstat, open, rename, rm } from 'fs/promises'
import { randomUUID } from 'crypto'
import { dirname, extname, join, resolve } from 'path'
import type { ChildProcess } from 'child_process'
import { gitExecFileAsync, wslAwareSpawn } from '../git/runner'
import { parseWslPath, toWindowsWslPath } from '../wsl'
@@ -98,6 +99,7 @@ import {
} from '../text-generation/commit-message-agent-environment'
import { listRepoWorktrees } from '../repo-worktrees'
import { splitWorktreeId } from '../../shared/worktree-id'
import { getRuntimePathBasename } from '../../shared/cross-platform-path'
// Why: Monaco has large-file optimizations like VS Code; blocking at 5MB makes
// ordinary JSON/log files inaccessible before the editor can degrade features.
@@ -123,6 +125,93 @@ const PREVIEWABLE_BINARY_MIME_TYPES: Record<string, string> = {
'.ico': 'image/x-icon',
'.pdf': 'application/pdf'
}
const WINDOWS_RESERVED_LOCAL_BASENAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i
const LOCAL_FILENAME_REPLACEMENT_CHARS = new Set(['<', '>', ':', '"', '/', '\\', '|', '?', '*'])
type DownloadFileResult = { canceled: true } | { canceled: false; destinationPath: string }
function validateRequiredString(value: unknown, label: string): string {
if (typeof value !== 'string' || value.trim() === '') {
throw new Error(`${label} is required`)
}
return value
}
function sanitizeSaveDialogFilename(remoteBasename: string): string {
const sanitized = Array.from(remoteBasename, (char) =>
char.charCodeAt(0) < 32 || LOCAL_FILENAME_REPLACEMENT_CHARS.has(char) ? '_' : char
)
.join('')
.replace(/[. ]+$/g, '')
if (!sanitized || WINDOWS_RESERVED_LOCAL_BASENAME.test(sanitized)) {
return 'download'
}
return sanitized
}
function createSiblingTransferPath(destinationPath: string, suffix: string): string {
return join(dirname(destinationPath), `.${randomUUID()}.${suffix}`)
}
async function cleanupLocalTransferPath(filePath: string | null): Promise<void> {
if (!filePath) {
return
}
await rm(filePath, { force: true }).catch(() => {})
}
async function inspectDownloadDestination(destinationPath: string): Promise<{ existed: boolean }> {
try {
const destinationStat = await stat(destinationPath)
if (destinationStat.isDirectory()) {
throw new Error('Cannot download to a directory')
}
return { existed: true }
} catch (error) {
if (isENOENT(error)) {
return { existed: false }
}
throw error
}
}
async function assertDestinationStillUnclaimed(destinationPath: string): Promise<void> {
try {
await stat(destinationPath)
} catch (error) {
if (isENOENT(error)) {
return
}
throw error
}
throw new Error('Destination file appeared before download completed')
}
async function promoteDownloadedFile(
tempPath: string,
destinationPath: string,
destinationExisted: boolean
): Promise<void> {
if (!destinationExisted) {
await assertDestinationStillUnclaimed(destinationPath)
await rename(tempPath, destinationPath)
return
}
const backupPath = createSiblingTransferPath(destinationPath, 'backup')
let backupCreated = false
try {
await rename(destinationPath, backupPath)
backupCreated = true
await rename(tempPath, destinationPath)
await cleanupLocalTransferPath(backupPath)
} catch (error) {
if (backupCreated) {
await rename(backupPath, destinationPath).catch(() => {})
}
throw error
}
}
function comparableLocalPath(value: string): string {
const normalized = resolve(value)
@@ -384,6 +473,50 @@ export function registerFilesystemHandlers(
}
)
ipcMain.handle(
'fs:downloadFile',
async (
event,
args: { filePath?: string; connectionId?: string }
): Promise<DownloadFileResult> => {
const filePath = validateRequiredString(args?.filePath, 'filePath')
const connectionId = validateRequiredString(args?.connectionId, 'connectionId')
const provider = requireSshFilesystemProvider(connectionId)
const remoteStat = await provider.stat(filePath)
if (remoteStat.type === 'directory') {
throw new Error('Cannot download a directory')
}
if (!provider.downloadFile) {
throw new Error('Remote file download is unavailable. Reconnect the SSH target and retry.')
}
const remoteBasename = getRuntimePathBasename(filePath)
const defaultPath = sanitizeSaveDialogFilename(remoteBasename)
const parentWindow = BrowserWindow.fromWebContents(event.sender) ?? undefined
const dialogResult = parentWindow
? await dialog.showSaveDialog(parentWindow, { defaultPath })
: await dialog.showSaveDialog({ defaultPath })
if (dialogResult.canceled || !dialogResult.filePath) {
return { canceled: true }
}
const destinationPath = dialogResult.filePath
const { existed } = await inspectDownloadDestination(destinationPath)
const tempPath = createSiblingTransferPath(destinationPath, 'download')
let promoted = false
try {
await provider.downloadFile(filePath, tempPath)
await promoteDownloadedFile(tempPath, destinationPath, existed)
promoted = true
return { canceled: false, destinationPath }
} finally {
if (!promoted) {
await cleanupLocalTransferPath(tempPath)
}
}
}
)
ipcMain.handle(
'fs:listMarkdownDocuments',
async (
@@ -162,6 +162,45 @@ describe('SshFilesystemProvider', () => {
})
})
describe('downloadFile', () => {
it('downloads raw bytes through SFTP and closes the session', async () => {
const sftp = {
fastGet: vi.fn(
(_source: string, _destination: string, callback: (err?: Error | null) => void) =>
callback()
),
end: vi.fn()
}
provider = new SshFilesystemProvider('conn-1', mux as never, async () => sftp as never)
await provider.downloadFile('/home/user/archive.zip', '/tmp/archive.zip')
expect(sftp.fastGet).toHaveBeenCalledWith(
'/home/user/archive.zip',
'/tmp/archive.zip',
expect.any(Function)
)
expect(sftp.end).toHaveBeenCalled()
})
it('closes the SFTP session when raw download fails', async () => {
const sftp = {
fastGet: vi.fn(
(_source: string, _destination: string, callback: (err?: Error | null) => void) =>
callback(new Error('download failed'))
),
end: vi.fn()
}
provider = new SshFilesystemProvider('conn-1', mux as never, async () => sftp as never)
await expect(
provider.downloadFile('/home/user/archive.zip', '/tmp/archive.zip')
).rejects.toThrow('download failed')
expect(sftp.end).toHaveBeenCalled()
})
})
describe('createDirNoClobber', () => {
it('sends fs.createDirNoClobber request', async () => {
await provider.createDirNoClobber('/home/user/new-dir')
@@ -37,6 +37,22 @@ function lstatViaSftp(sftp: SFTPWrapper, filePath: string): Promise<FileStat> {
})
}
function fastGetViaSftp(
sftp: SFTPWrapper,
sourcePath: string,
destinationPath: string
): Promise<void> {
return new Promise((resolve, reject) => {
sftp.fastGet(sourcePath, destinationPath, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
export class SshFilesystemProvider implements IFilesystemProvider {
private connectionId: string
private mux: SshChannelMultiplexer
@@ -123,6 +139,18 @@ export class SshFilesystemProvider implements IFilesystemProvider {
}
}
async downloadFile(sourcePath: string, destinationPath: string): Promise<void> {
if (!this.createSftp) {
throw new Error('Remote file download is unavailable. Reconnect the SSH target and retry.')
}
const sftp = await this.createSftp()
try {
await fastGetViaSftp(sftp, sourcePath, destinationPath)
} finally {
sftp.end()
}
}
async getTempDir(): Promise<string> {
this.tempDirPromise ??= this.mux.request('fs.tempDir', {}).then(
(result) => result as string,
+1
View File
@@ -133,6 +133,7 @@ export type FileReadResult = {
export type IFilesystemProvider = {
readDir(dirPath: string): Promise<DirEntry[]>
readFile(filePath: string): Promise<FileReadResult>
downloadFile?(sourcePath: string, destinationPath: string): Promise<void>
getTempDir?(): Promise<string>
writeFile(filePath: string, content: string): Promise<void>
writeFileBase64(filePath: string, contentBase64: string): Promise<void>
+4
View File
@@ -1829,6 +1829,10 @@ export type PreloadApi = {
filePath: string
connectionId?: string
}) => Promise<{ content: string; isBinary: boolean; isImage?: boolean; mimeType?: string }>
downloadFile: (args: {
filePath: string
connectionId: string
}) => Promise<{ canceled: true } | { canceled: false; destinationPath: string }>
listMarkdownDocuments: (args: {
rootPath: string
connectionId?: string
+5
View File
@@ -2270,6 +2270,11 @@ const api = {
connectionId?: string
}): Promise<{ content: string; isBinary: boolean; isImage?: boolean; mimeType?: string }> =>
ipcRenderer.invoke('fs:readFile', args),
downloadFile: (args: {
filePath: string
connectionId: string
}): Promise<{ canceled: true } | { canceled: false; destinationPath: string }> =>
ipcRenderer.invoke('fs:downloadFile', args),
listMarkdownDocuments: (args: {
rootPath: string
connectionId?: string
@@ -1,19 +1,33 @@
/* eslint-disable max-lines -- File Explorer toolbar and row tests share element-walking fixtures. */
import { describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Ellipsis, ListCollapse, Loader2, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { DropdownMenuCheckboxItem } from '@/components/ui/dropdown-menu'
import { WorktreeOpenInMenuItems } from '@/components/sidebar/WorktreeOpenInMenu'
import { FileExplorerToolbar } from './FileExplorerToolbar'
import {
downloadRemoteFile,
FileExplorerRow,
shouldShowCollapseFolderAction,
shouldShowFindInFolderAction
shouldShowFindInFolderAction,
shouldShowRemoteDownloadAction
} from './FileExplorerRow'
import { FileExplorerVirtualRows } from './FileExplorerVirtualRows'
import type { TreeNode } from './file-explorer-types'
import { createFileExplorerRowProjection } from './file-explorer-row-projection'
const { toastErrorMock, toastSuccessMock } = vi.hoisted(() => ({
toastErrorMock: vi.fn(),
toastSuccessMock: vi.fn()
}))
vi.mock('sonner', () => ({
toast: {
error: toastErrorMock,
success: toastSuccessMock
}
}))
type ReactElementLike = {
type: unknown
props: Record<string, unknown>
@@ -216,6 +230,12 @@ function makeToolbar(overrides: Partial<Parameters<typeof FileExplorerToolbar>[0
})
}
beforeEach(() => {
toastErrorMock.mockReset()
toastSuccessMock.mockReset()
delete (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__
})
describe('FileExplorerToolbar', () => {
it('fires the refresh action from the icon button', () => {
const onRefresh = vi.fn()
@@ -337,6 +357,13 @@ describe('FileExplorerRow collapse folder action', () => {
isDirectory: true,
depth: 0
}
const fileNode: TreeNode = {
name: 'index.ts',
path: '/repo/src/index.ts',
relativePath: 'src/index.ts',
isDirectory: false,
depth: 1
}
it('only shows collapse folder for expanded directories', () => {
expect(shouldShowCollapseFolderAction(directoryNode, true)).toBe(true)
@@ -368,6 +395,68 @@ describe('FileExplorerRow collapse folder action', () => {
).toBe(false)
})
it('shows remote download only for desktop SSH file-like rows', () => {
expect(shouldShowRemoteDownloadAction(fileNode, 'ssh-1')).toBe(true)
expect(shouldShowRemoteDownloadAction({ ...fileNode, isSymlink: true }, 'ssh-1')).toBe(true)
expect(shouldShowRemoteDownloadAction(fileNode, null)).toBe(false)
expect(shouldShowRemoteDownloadAction(directoryNode, 'ssh-1')).toBe(false)
;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true
expect(shouldShowRemoteDownloadAction(fileNode, 'ssh-1')).toBe(false)
})
it('calls the preload download API and shows success only when not canceled', async () => {
const downloadFile = vi
.fn()
.mockResolvedValueOnce({ canceled: false, destinationPath: '/downloads/index.ts' })
.mockResolvedValueOnce({ canceled: true })
const openPath = vi.fn().mockResolvedValue(undefined)
;(
globalThis as unknown as {
window: {
api: {
fs: { downloadFile: typeof downloadFile }
shell: { openPath: typeof openPath }
}
}
}
).window = { api: { fs: { downloadFile }, shell: { openPath } } }
await downloadRemoteFile(fileNode, 'ssh-1')
await downloadRemoteFile(fileNode, 'ssh-1')
expect(downloadFile).toHaveBeenCalledWith({
filePath: '/repo/src/index.ts',
connectionId: 'ssh-1'
})
expect(toastSuccessMock).toHaveBeenCalledTimes(1)
expect(toastSuccessMock).toHaveBeenCalledWith("Downloaded 'index.ts'", {
action: {
label: 'Open',
onClick: expect.any(Function)
}
})
const action = toastSuccessMock.mock.calls[0]?.[1]?.action as
| { onClick: () => void }
| undefined
action?.onClick()
expect(openPath).toHaveBeenCalledWith('/downloads/index.ts')
expect(toastErrorMock).not.toHaveBeenCalled()
})
it('shows a failure toast when remote download fails', async () => {
const downloadFile = vi.fn().mockRejectedValue(new Error('Remote connection dropped'))
;(
globalThis as unknown as { window: { api: { fs: { downloadFile: typeof downloadFile } } } }
).window = { api: { fs: { downloadFile } } }
await downloadRemoteFile(fileNode, 'ssh-1')
expect(toastErrorMock).toHaveBeenCalledWith('Remote connection dropped')
expect(toastSuccessMock).not.toHaveBeenCalled()
})
it('passes the row node to the collapse folder handler', () => {
const onCollapseFolderSubtree = vi.fn()
const element = FileExplorerVirtualRows({
@@ -469,4 +558,54 @@ describe('FileExplorerRow collapse folder action', () => {
expect(onFindInFolder).toHaveBeenCalledWith(directoryNode)
})
it('passes the active connection id to virtualized rows', () => {
const element = FileExplorerVirtualRows({
virtualizer: {
getTotalSize: () => 26,
getVirtualItems: () => [{ index: 0, key: 'index.ts', start: 0 }],
measureElement: vi.fn()
} as never,
inlineInputIndex: -1,
rowProjection: createFileExplorerRowProjection([fileNode]),
inlineInput: null,
handleInlineSubmit: vi.fn(),
dismissInlineInput: vi.fn(),
folderStatusByRelativePath: new Map(),
statusByRelativePath: new Map(),
ignoredByRelativePath: new Set(),
expanded: new Set(),
dirCache: {},
selectedPaths: new Set(),
activeFileId: null,
flashingPath: null,
deleteShortcutLabel: 'Del',
connectionId: 'ssh-1',
onClick: vi.fn(),
onDoubleClick: vi.fn(),
onContextMenuSelect: vi.fn(),
onCopyPaths: vi.fn(),
onStartNew: vi.fn(),
onStartRename: vi.fn(),
onDuplicate: vi.fn(),
onAddFolderAsProject: vi.fn(),
canAddFolderAsProject: () => false,
onRequestDelete: vi.fn(),
onCollapseFolderSubtree: vi.fn(),
onFindInFolder: vi.fn(),
onMoveDrop: vi.fn(),
onDragTargetChange: vi.fn(),
onDragSourceChange: vi.fn(),
onDragExpandDir: vi.fn(),
onNativeDragTargetChange: vi.fn(),
onNativeDragExpandDir: vi.fn(),
dropTargetDir: null,
dragSourcePath: null,
nativeDropTargetDir: null
})
const row = findFileExplorerRow(element)
expect(row.props.connectionId).toBe('ssh-1')
})
})
@@ -533,6 +533,7 @@ function FileExplorerInner(): React.JSX.Element {
activeFileId={activeFileId}
flashingPath={flashingPath}
deleteShortcutLabel={deleteShortcutLabel}
connectionId={activeRepo?.connectionId ?? null}
onClick={handleRowClick}
onDoubleClick={handleDoubleClick}
onContextMenuSelect={preserveSelectionForContextMenu}
@@ -5,6 +5,7 @@ import {
ChevronRight,
CircleSlash,
Copy,
Download,
ExternalLink,
Eye,
File,
@@ -46,6 +47,7 @@ import { STATUS_LABELS } from './status-display'
import type { TreeNode } from './file-explorer-types'
import { useFileExplorerRowDrag } from './useFileExplorerRowDrag'
import { isLocalPathOpenBlocked, showLocalPathOpenBlockedToast } from '@/lib/local-path-open-guard'
import { extractIpcErrorMessage } from '@/lib/ipc-error'
const isMac = navigator.userAgent.includes('Mac')
const isLinux = navigator.userAgent.includes('Linux')
@@ -265,6 +267,7 @@ type FileExplorerRowProps = {
statusColor: string | null
isIgnored: boolean
deleteShortcutLabel: string
connectionId?: string | null
targetDir: string
targetDepth: number
selectionSize: number
@@ -296,6 +299,38 @@ export function shouldShowFindInFolderAction(node: TreeNode): boolean {
return node.isDirectory
}
export function shouldShowRemoteDownloadAction(
node: TreeNode,
connectionId?: string | null
): boolean {
// Why: Desktop-only because download depends on Electron's native save dialog.
return (
!node.isDirectory &&
Boolean(connectionId) &&
(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ !== true
)
}
export async function downloadRemoteFile(node: TreeNode, connectionId: string): Promise<void> {
try {
const result = await window.api.fs.downloadFile({ filePath: node.path, connectionId })
// Why: Suppress toasts when the user cancels the native save dialog per design.
if (result.canceled) {
return
}
toast.success(`Downloaded '${node.name}'`, {
action: {
label: 'Open',
onClick: () => {
void window.api.shell.openPath(result.destinationPath)
}
}
})
} catch (error) {
toast.error(extractIpcErrorMessage(error, `Failed to download '${node.name}'.`))
}
}
export function FileExplorerRow({
node,
isExpanded,
@@ -307,6 +342,7 @@ export function FileExplorerRow({
statusColor,
isIgnored,
deleteShortcutLabel,
connectionId,
targetDir,
targetDepth,
selectionSize,
@@ -336,6 +372,7 @@ export function FileExplorerRow({
const findInFolderShortcutLabel = useShortcutLabel('sidebar.search.toggle')
const FileIcon = getFileTypeIcon(node.relativePath || node.name)
const rowDropDir = node.isDirectory ? node.path : targetDir
const showRemoteDownloadAction = shouldShowRemoteDownloadAction(node, connectionId)
const { setRowDragNode, handleDragOver, handleDragEnter, handleDragLeave, handleDrop } =
useFileExplorerRowDrag({
rowDropDir,
@@ -357,6 +394,12 @@ export function FileExplorerRow({
toast.error(result.message)
}
}, [activeWorktreeId, node.path])
const handleDownload = useCallback(() => {
if (!connectionId) {
return
}
void downloadRemoteFile(node, connectionId)
}, [connectionId, node])
return (
<ContextMenu>
@@ -563,6 +606,12 @@ export function FileExplorerRow({
Open Markdown Preview
</ContextMenuItem>
)}
{showRemoteDownloadAction && (
<ContextMenuItem onSelect={handleDownload}>
<Download />
Download
</ContextMenuItem>
)}
{shouldShowCollapseFolderAction(node, isExpanded) && (
<ContextMenuItem onSelect={onCollapseFolderSubtree}>
<ListCollapse />
@@ -24,6 +24,7 @@ type FileExplorerVirtualRowsProps = {
activeFileId: string | null
flashingPath: string | null
deleteShortcutLabel: string
connectionId?: string | null
onClick: (node: TreeNode, event: React.MouseEvent<HTMLButtonElement>) => void
onDoubleClick: (node: TreeNode) => void
onContextMenuSelect: (node: TreeNode) => void
@@ -64,6 +65,7 @@ export function FileExplorerVirtualRows(props: FileExplorerVirtualRowsProps): Re
activeFileId,
flashingPath,
deleteShortcutLabel,
connectionId,
onClick,
onDoubleClick,
onContextMenuSelect,
@@ -163,6 +165,7 @@ export function FileExplorerVirtualRows(props: FileExplorerVirtualRowsProps): Re
statusColor={nodeStatus ? STATUS_COLORS[nodeStatus] : null}
isIgnored={isIgnored}
deleteShortcutLabel={deleteShortcutLabel}
connectionId={connectionId}
targetDir={n.isDirectory ? n.path : dirname(n.path)}
targetDepth={n.isDirectory ? n.depth + 1 : n.depth}
selectionSize={selectedPaths.has(n.path) ? visibleSelectionCount : 1}
@@ -1048,6 +1048,14 @@ describe('web file preload API', () => {
vi.doUnmock('./web-runtime-client')
})
it('rejects native save-dialog downloads in paired web clients', async () => {
const { api } = await installApi('Linux')
await expect(
api.fs.downloadFile({ filePath: '/workspace/repo/file.txt', connectionId: 'ssh-1' })
).rejects.toThrow('Remote file download is unavailable in paired web clients.')
})
it('returns false for runtime missing-path errors from fs.pathExists', async () => {
const runtimeCalls: { method: string; params: unknown }[] = []
const worktree = {
+3
View File
@@ -1120,6 +1120,9 @@ function createFileApi(): NonNullable<Partial<PreloadApi>['fs']> {
relativePath: file.relativePath
})
},
downloadFile: async () => {
throw new Error('Remote file download is unavailable in paired web clients.')
},
listMarkdownDocuments: async ({ rootPath }) => {
const file = await resolveRuntimeFilePath(rootPath)
return callRuntimeResult('files.listMarkdownDocuments', {