feat(links): add a "Download…" save-only action to remote file link menus (#43294)

Remote (SSH or paired-host) file links only offered "Download & open with
default app". Add a "Download…" row that saves a copy to a user-picked path
without opening it. Folder links are saved over SSH when the host supports
recursive transfer and reported otherwise; paths that resolve to this
computer are reported as already local. Hidden in paired web clients, which
have no local disk.

Shares the downloaded-file toast and SSH folder download with the file
explorer's Download action.

Fixes #43038

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Neil
2026-11-16 15:11:23 -08:00
committed by GitHub
co-authored by Claude
parent 11403c1475
commit ca7f11596f
9 changed files with 387 additions and 96 deletions
@@ -1,81 +1,43 @@
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host/execution-host'
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { extractIpcErrorMessage } from '@/runtime/errors/ipc-error'
import { downloadRuntimeFile } from '@/runtime/files/reads/runtime-file-read-client'
import { showDownloadedFileToast } from '@/lib/files/download/downloaded-file-toast'
import { downloadSshFolder } from '@/lib/files/download/ssh-folder-download'
import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types'
import type { TreeNode } from '../tree/file-explorer-types'
import { shouldShowCopyFileAction } from './file-explorer-row-action-visibility'
function getLocalDownloadName(destinationPath: string, platform: NodeJS.Platform): string {
const lastSeparatorIndex =
platform === 'win32'
? Math.max(destinationPath.lastIndexOf('/'), destinationPath.lastIndexOf('\\'))
: destinationPath.lastIndexOf('/')
return destinationPath.slice(lastSeparatorIndex + 1)
}
export async function downloadRemoteFile(
node: TreeNode,
connectionIdOrRuntimeContext: string | RuntimeFileOperationArgs
): Promise<void> {
// Folder downloads are only offered over SSH (see shouldShowRemoteDownloadAction).
if (node.isDirectory && typeof connectionIdOrRuntimeContext === 'string') {
await downloadSshFolder(node.path, node.name, connectionIdOrRuntimeContext)
return
}
try {
const result =
typeof connectionIdOrRuntimeContext === 'string'
? node.isDirectory
? await window.api.fs.downloadFolder({
dirPath: node.path,
connectionId: connectionIdOrRuntimeContext
})
: await window.api.fs.downloadFile({
filePath: node.path,
connectionId: connectionIdOrRuntimeContext
})
? await window.api.fs.downloadFile({
filePath: node.path,
connectionId: connectionIdOrRuntimeContext
})
: await downloadRuntimeFile(connectionIdOrRuntimeContext, node.path, node.name)
if (result.canceled) {
return
}
// POSIX allows backslashes in filenames; only Windows treats them as separators.
const savedName = getLocalDownloadName(
result.destinationPath,
window.api.platform.get().platform
)
toast.success(
node.isDirectory
? translate(
'auto.components.right.sidebar.FileExplorerRow.a4029c996b',
"Downloaded folder '{{value0}}'",
{ value0: savedName }
)
: translate(
'auto.components.right.sidebar.FileExplorerRow.bce4d4e44f',
"Downloaded '{{value0}}'",
{ value0: savedName }
),
{
action: {
label: translate('auto.components.right.sidebar.FileExplorerRow.1a3df04ae1', 'Open'),
onClick: () => {
void window.api.shell.openPath(result.destinationPath, LOCAL_EXECUTION_HOST_ID)
}
}
}
)
showDownloadedFileToast(result.destinationPath)
} catch (error) {
toast.error(
extractIpcErrorMessage(
error,
node.isDirectory
? translate(
'auto.components.right.sidebar.FileExplorerRow.f729bcd97d',
"Failed to download folder '{{value0}}'.",
{ value0: node.name }
)
: translate(
'auto.components.right.sidebar.FileExplorerRow.b3e288bf41',
"Failed to download '{{value0}}'.",
{ value0: node.name }
)
translate(
'auto.components.right.sidebar.FileExplorerRow.b3e288bf41',
"Failed to download '{{value0}}'.",
{ value0: node.name }
)
)
)
}
@@ -23,6 +23,7 @@ import {
} from '@/lib/files/os-open/local-path-open-guard'
import '@/store/slices/editor/tabs/editor-open-target-group'
import { canOpenLinkInSourceGroup } from '@/lib/links/placement/link-open-intent'
import { isPairedWebClientWindow } from '@/app-shell/chrome/desktop-window-chrome'
import type { FileOpenFailure } from './terminal-file-open-failure'
import type { LinkActionRequest } from '@/components/link-actions/link-action-request'
import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing'
@@ -150,6 +151,14 @@ export function buildFileLinkActions(
openWithSystemDefault: true
})
}
// Why: a paired web client has no local disk to save into.
const downloadRow =
systemDefaultRow && !canOpenWithSystemDefault && !isPairedWebClientWindow()
? {
label: t('auto.components.terminal.pane.TerminalLinkActionPopover.download', 'Download…'),
run: () => openDetectedFilePath(filePath, line, column, { ...deps, downloadOnly: true })
}
: null
// Omit remote reveal: rows have no disabled state and the file manager only shows local files.
const revealOwner = getLocalPathOpenOwnerForRoute({
runtimeEnvironmentId: deps.runtimeEnvironmentId
@@ -185,7 +194,7 @@ export function buildFileLinkActions(
})
}
: null
const secondaryActions = [openInGroupRow, revealRow].filter((row) => row !== null)
const secondaryActions = [downloadRow, openInGroupRow, revealRow].filter((row) => row !== null)
const rows =
!worktreeRoot && canOpenWithSystemDefault && isHtmlFilePath(mappedPath)
? buildHttpLinkActions(
@@ -0,0 +1,143 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { toast } from 'sonner'
import { getConnectionId } from '@/lib/workspace/ownership/connection-context'
import { buildFileLinkActions } from './terminal-file-link-actions'
import { downloadRemoteTerminalFile } from './terminal-remote-file-download-open'
import { openDetectedFolder } from './terminal-folder-open'
import type * as ArtifactGrantModule from '@/runtime/files/grants/runtime-terminal-artifact-grant'
import { createTerminalLinkTestDoubles } from '../terminal-link-handlers-test-fixtures'
import {
flushAsyncWork,
installTerminalLinkTestEnvironment,
setPlatform
} from '../terminal-link-handlers-test-harness'
const doubles = createTerminalLinkTestDoubles()
const { storeState, openFileMock, openFilePathMock, statMock } = doubles
const downloadFileMock = vi.fn()
const downloadFolderMock = vi.fn()
vi.mock('sonner', () => ({
toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() }
}))
vi.mock('@/store/index', () => ({
useAppStore: {
getState: () => storeState
}
}))
vi.mock('@/lib/workspace/activation/worktree-activation', () => ({
activateAndRevealWorkspace: vi.fn(),
activateAndRevealWorktree: vi.fn()
}))
vi.mock('./terminal-folder-open', () => ({ openDetectedFolder: vi.fn() }))
vi.mock('@/runtime/files/grants/runtime-terminal-artifact-grant', async (importOriginal) => ({
...(await importOriginal<typeof ArtifactGrantModule>()),
hostStreamsGrantedFiles: vi.fn(async () => false)
}))
vi.mock('@/lib/workspace/ownership/connection-context', () => ({
getConnectionId: vi.fn(() => null)
}))
installTerminalLinkTestEnvironment(doubles)
beforeEach(() => {
setPlatform('Windows')
vi.mocked(getConnectionId).mockReturnValue('box')
storeState.worktreesByRepo = {
repo1: [{ id: 'wt-1', path: '/home/me/repo', repoId: 'repo1', hostId: 'ssh:box' }]
}
downloadFileMock.mockResolvedValue({ canceled: false, destinationPath: 'C:\\Users\\me\\run.sh' })
downloadFolderMock.mockResolvedValue({ canceled: false, destinationPath: 'C:\\Users\\me\\out' })
Object.assign(window.api.fs, {
downloadFile: downloadFileMock,
downloadFolder: downloadFolderMock
})
Object.assign(storeState, { sshConnectionStates: new Map() })
Object.assign(window.api, { platform: { get: () => ({ platform: 'win32' }) } })
})
describe('remote file link download action', () => {
it('saves an SSH file without opening it', async () => {
const actions = buildFileLinkActions(
'/home/me/repo/run.sh',
null,
null,
{ worktreeId: 'wt-1', worktreePath: '/home/me/repo', runtimeEnvironmentId: null },
{ kind: 'ssh', connectionId: 'box' }
)
const download = actions.secondaryActions?.find((row) => row.label === 'Download…')
expect(download).toBeDefined()
await download?.run()
await flushAsyncWork()
expect(downloadFileMock).toHaveBeenCalledWith({
filePath: '/home/me/repo/run.sh',
connectionId: 'box'
})
expect(openFilePathMock).not.toHaveBeenCalled()
expect(openFileMock).not.toHaveBeenCalled()
})
it.each([
[true, 1, 'success'],
[false, 0, 'error']
] as const)(
'with folder transfer %s, saves or reports a folder link instead of revealing it',
async (supportsFolderDownload, downloads, toastKind) => {
statMock.mockResolvedValue({ isDirectory: true })
Object.assign(storeState, {
sshConnectionStates: new Map([['box', { supportsFolderDownload }]])
})
const actions = buildFileLinkActions(
'/home/me/repo/out',
null,
null,
{ worktreeId: 'wt-1', worktreePath: '/home/me/repo', runtimeEnvironmentId: null },
{ kind: 'ssh', connectionId: 'box' }
)
const download = actions.secondaryActions?.find((row) => row.label === 'Download…')
expect(download).toBeDefined()
await download?.run()
await flushAsyncWork()
expect(downloadFolderMock).toHaveBeenCalledTimes(downloads)
expect(toast[toastKind]).toHaveBeenCalledTimes(1)
expect(openDetectedFolder).not.toHaveBeenCalled()
expect(downloadFileMock).not.toHaveBeenCalled()
}
)
it('reports a path the host disowned that is on this computer instead of opening it', async () => {
await downloadRemoteTerminalFile(
{ target: { kind: 'local' }, worktreeId: 'wt-1', worktreePath: '/home/me/repo' },
'/home/me/repo/run.sh',
null
)
expect(toast.info).toHaveBeenCalledTimes(1)
expect(downloadFileMock).not.toHaveBeenCalled()
expect(openFilePathMock).not.toHaveBeenCalled()
})
it('tells the user to update a paired server that cannot stream a granted file', async () => {
await downloadRemoteTerminalFile(
{
target: { kind: 'environment', environmentId: 'env-1' },
worktreeId: 'wt-1',
worktreePath: '/home/me/repo'
},
'/tmp/run.sh',
{ terminalArtifactGrantId: 'g1' }
)
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('newer Orca server'))
expect(openFilePathMock).not.toHaveBeenCalled()
})
})
@@ -1,4 +1,8 @@
import { downloadAndOpenRemoteTerminalFile } from './terminal-remote-file-download-open'
import {
downloadAndOpenRemoteTerminalFile,
downloadRemoteTerminalFile,
downloadRemoteTerminalFolder
} from './terminal-remote-file-download-open'
import { isMissingRuntimePathError } from '@/runtime/files/metadata/runtime-file-metadata-client'
import { useAppStore } from '@/store/index'
import {
@@ -46,6 +50,8 @@ type TerminalFileOpenDeps = {
wslDistro?: string | null
/** Shift+modifier: the OS default app, or the other link-routing browser for a local HTML file. */
openWithSystemDefault?: boolean
/** Routes like openWithSystemDefault, but only saves a copy of the file or folder; never opens it. */
downloadOnly?: boolean
/** Where a local HTML file opens, chosen from its popover; otherwise link routing decides. */
browserDestination?: HttpLinkDestination
/** The paired-server terminal that printed the link; lets its host grant a file outside workspaces. */
@@ -67,7 +73,8 @@ export function openDetectedFilePath(
column: number | null,
deps: TerminalFileOpenDeps
): void {
const { openWithSystemDefault = false, runtimeEnvironmentId } = deps
const { runtimeEnvironmentId } = deps
const openWithSystemDefault = deps.openWithSystemDefault === true || deps.downloadOnly === true
let { worktreeId, worktreePath } = deps
let mappedFilePath = mapTerminalFilePath(
filePath,
@@ -136,7 +143,10 @@ export function openDetectedFilePath(
}
try {
const linkOwner = await resolveHostWorkspaceFile(fileContext, mappedFilePath, deps)
const linkOwner = await resolveHostWorkspaceFile(fileContext, mappedFilePath, {
...deps,
openWithSystemDefault
})
if (linkOwner?.kind === 'grant') {
hostGrant = hostGrantedEditorFields(linkOwner)
mappedFilePath = linkOwner.absolutePath
@@ -178,6 +188,13 @@ export function openDetectedFilePath(
refuseExplicitNonEditorRoute()
return
}
// Why: download-only never opens or reveals the path, even one that turned out to be on this computer.
if (deps.downloadOnly) {
await (statResult.isDirectory
? downloadRemoteTerminalFolder(fileContext, mappedFilePath)
: downloadRemoteTerminalFile(fileContext, mappedFilePath, hostGrant))
return
}
// Remote hints promise Orca before resolution; explicit group requests must reach HTML branch to be refused.
const pageDestination =
canOpenWithSystemDefault &&
@@ -2,11 +2,67 @@ import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { extractIpcErrorMessage } from '@/runtime/errors/ipc-error'
import { basename } from '@/lib/path'
import { openRuntimeFileWithDefaultApp } from '@/runtime/files/reads/runtime-file-default-app-open'
import {
downloadRuntimeFileToClient,
isClientLocalRuntimeFile,
openRuntimeFileWithDefaultApp
} from '@/runtime/files/reads/runtime-file-default-app-open'
import { showDownloadedFileToast } from '@/lib/files/download/downloaded-file-toast'
import { downloadSshFolder } from '@/lib/files/download/ssh-folder-download'
import { getRelativePathInsideWorktree } from '@/runtime/files/runtime-file-routing'
import { hostStreamsGrantedFiles } from '@/runtime/files/grants/runtime-terminal-artifact-grant'
import { isPairedWebClientWindow } from '@/app-shell/chrome/desktop-window-chrome'
import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types'
import type {
RuntimeFileOperationArgs,
RuntimeFileReadArgs
} from '@/runtime/files/runtime-file-client-types'
import { useAppStore } from '@/store/index'
type TerminalFileGrant = { terminalArtifactGrantId: string } | null | undefined
function linkFileReadSource(
fileContext: RuntimeFileOperationArgs,
filePath: string,
grant: TerminalFileGrant
): RuntimeFileReadArgs {
return {
target: fileContext.target,
filePath,
relativePath: getRelativePathInsideWorktree(fileContext.worktreePath, filePath) ?? filePath,
worktreeId: fileContext.worktreeId ?? undefined,
connectionId: fileContext.connectionId,
expectedExternalSshTargetId: fileContext.expectedExternalSshTargetId,
expectedEnvironmentPairingRevision: fileContext.expectedEnvironmentPairingRevision,
terminalArtifactGrantId: grant?.terminalArtifactGrantId
}
}
function linkName(path: string): string {
return basename(path) || path
}
function showDownloadFailedToast(error: unknown, name: string): void {
toast.error(
extractIpcErrorMessage(
error,
translate(
'auto.components.terminal.pane.TerminalLinkActionPopover.downloadOpenFailed',
"Failed to download '{{value0}}'.",
{ value0: name }
)
)
)
}
function showAlreadyLocalToast(name: string): void {
toast.info(
translate(
'auto.components.terminal.pane.TerminalLinkActionPopover.downloadAlreadyLocal',
"'{{value0}}' is already on this computer.",
{ value0: name }
)
)
}
/**
* Remote counterpart of "Open with default app": the OS can only launch a local
@@ -17,12 +73,8 @@ import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-clie
export async function downloadAndOpenRemoteTerminalFile(
fileContext: RuntimeFileOperationArgs,
filePath: string,
{
grant,
isCurrent = () => true
}: { grant?: { terminalArtifactGrantId: string } | null; isCurrent?: () => boolean } = {}
{ grant, isCurrent = () => true }: { grant?: TerminalFileGrant; isCurrent?: () => boolean } = {}
): Promise<boolean> {
const name = basename(filePath) || filePath
const { target, worktreeId } = fileContext
if (grant) {
if (
@@ -40,27 +92,57 @@ export async function downloadAndOpenRemoteTerminalFile(
}
}
try {
await openRuntimeFileWithDefaultApp({
target,
filePath,
relativePath: getRelativePathInsideWorktree(fileContext.worktreePath, filePath) ?? filePath,
worktreeId: worktreeId ?? undefined,
connectionId: fileContext.connectionId,
expectedExternalSshTargetId: fileContext.expectedExternalSshTargetId,
expectedEnvironmentPairingRevision: fileContext.expectedEnvironmentPairingRevision,
terminalArtifactGrantId: grant?.terminalArtifactGrantId
})
await openRuntimeFileWithDefaultApp(linkFileReadSource(fileContext, filePath, grant))
} catch (error) {
toast.error(
extractIpcErrorMessage(
error,
translate(
'auto.components.terminal.pane.TerminalLinkActionPopover.downloadOpenFailed',
"Failed to download '{{value0}}'.",
{ value0: name }
)
)
)
showDownloadFailedToast(error, linkName(filePath))
}
return true
}
/** Saves a link's file to a path the user picks without opening it; a host that can't serve it is reported. */
export async function downloadRemoteTerminalFile(
fileContext: RuntimeFileOperationArgs,
filePath: string,
grant: TerminalFileGrant
): Promise<void> {
const name = linkName(filePath)
try {
const download = await downloadRuntimeFileToClient(
linkFileReadSource(fileContext, filePath, grant)
)
if (!download) {
showAlreadyLocalToast(name)
} else if (!download.canceled) {
showDownloadedFileToast(download.destinationPath)
}
} catch (error) {
showDownloadFailedToast(error, name)
}
}
/** Download-only for a folder link: SSH hosts with recursive transfer save it; anything else is reported, not opened. */
export async function downloadRemoteTerminalFolder(
fileContext: Pick<RuntimeFileOperationArgs, 'target' | 'connectionId'>,
folderPath: string
): Promise<void> {
const name = linkName(folderPath)
const { connectionId } = fileContext
if (isClientLocalRuntimeFile(fileContext)) {
showAlreadyLocalToast(name)
return
}
if (
!connectionId ||
useAppStore.getState().sshConnectionStates.get(connectionId)?.supportsFolderDownload !== true
) {
toast.error(
translate(
'auto.components.terminal.pane.TerminalLinkActionPopover.downloadFolderUnsupported',
"Folder '{{value0}}' can't be downloaded from this host.",
{ value0: name }
)
)
return
}
await downloadSshFolder(folderPath, name, connectionId)
}
+3
View File
@@ -4846,6 +4846,9 @@
"copyLinkFailed": "Failed to copy link",
"copyFilePathFailed": "Failed to copy file path",
"downloadOpenWithDefaultApp": "Download & open with default app",
"download": "Download…",
"downloadAlreadyLocal": "'{{value0}}' is already on this computer.",
"downloadFolderUnsupported": "Folder '{{value0}}' can't be downloaded from this host.",
"downloadOpenFailed": "Failed to download '{{value0}}'.",
"openInNewTab": "Open in new tab",
"openInThisGroupRefused": "Couldn't open {{value0}} in this group"
@@ -0,0 +1,38 @@
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host/execution-host'
function getLocalDownloadName(destinationPath: string, platform: NodeJS.Platform): string {
const lastSeparatorIndex =
platform === 'win32'
? Math.max(destinationPath.lastIndexOf('/'), destinationPath.lastIndexOf('\\'))
: destinationPath.lastIndexOf('/')
return destinationPath.slice(lastSeparatorIndex + 1)
}
/** Confirms a finished download by the name it was saved under, with a way to open it. */
export function showDownloadedFileToast(destinationPath: string, isDirectory = false): void {
// POSIX allows backslashes in filenames; only Windows treats them as separators.
const savedName = getLocalDownloadName(destinationPath, window.api.platform.get().platform)
toast.success(
isDirectory
? translate(
'auto.components.right.sidebar.FileExplorerRow.a4029c996b',
"Downloaded folder '{{value0}}'",
{ value0: savedName }
)
: translate(
'auto.components.right.sidebar.FileExplorerRow.bce4d4e44f',
"Downloaded '{{value0}}'",
{ value0: savedName }
),
{
action: {
label: translate('auto.components.right.sidebar.FileExplorerRow.1a3df04ae1', 'Open'),
onClick: () => {
void window.api.shell.openPath(destinationPath, LOCAL_EXECUTION_HOST_ID)
}
}
}
)
}
@@ -0,0 +1,29 @@
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { extractIpcErrorMessage } from '@/runtime/errors/ipc-error'
import { showDownloadedFileToast } from './downloaded-file-toast'
/** Saves an SSH folder to a path the user picks and reports the outcome; the host must support recursive transfer. */
export async function downloadSshFolder(
dirPath: string,
name: string,
connectionId: string
): Promise<void> {
try {
const result = await window.api.fs.downloadFolder({ dirPath, connectionId })
if (!result.canceled) {
showDownloadedFileToast(result.destinationPath, true)
}
} catch (error) {
toast.error(
extractIpcErrorMessage(
error,
translate(
'auto.components.right.sidebar.FileExplorerRow.f729bcd97d',
"Failed to download folder '{{value0}}'.",
{ value0: name }
)
)
)
}
}
@@ -19,25 +19,33 @@ import {
} from './runtime-remote-file-download'
/** True when this client's OS can open the file in place; any other file is downloaded first. */
export function isClientLocalRuntimeFile(source: RuntimeFileReadArgs): boolean {
export function isClientLocalRuntimeFile(
source: Pick<RuntimeFileReadArgs, 'target' | 'connectionId'>
): boolean {
return source.target.kind === 'local' && !source.connectionId
}
/** Saves an SSH or paired-host file to a path the user picks; null for a file already on this client. */
export async function downloadRuntimeFileToClient(
source: RuntimeFileReadArgs
): Promise<RuntimeFileDownloadResult | null> {
const { filePath, connectionId } = source
const remote = rangeReadTarget(source)
if (remote) {
return downloadPairedHostFile(source, remote)
}
return connectionId ? window.api.fs.downloadFile({ filePath, connectionId }) : null
}
/**
* Opens a file with this client's default app, on the route it was read from. The OS can only
* launch a local file, so an SSH or paired-host file is downloaded to a path the user picks first.
* False when no app opened it; a cancelled save dialog counts as handled.
*/
export async function openRuntimeFileWithDefaultApp(source: RuntimeFileReadArgs): Promise<boolean> {
const { filePath, connectionId } = source
const remote = rangeReadTarget(source)
let download: RuntimeFileDownloadResult
if (remote) {
download = await downloadPairedHostFile(source, remote)
} else if (connectionId) {
download = await window.api.fs.downloadFile({ filePath, connectionId })
} else {
return window.api.shell.openFilePath(filePath, LOCAL_EXECUTION_HOST_ID)
const download = await downloadRuntimeFileToClient(source)
if (!download) {
return window.api.shell.openFilePath(source.filePath, LOCAL_EXECUTION_HOST_ID)
}
if (download.canceled) {
return true