feat(file-explorer): support drag-and-drop file import over SSH (#1279)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-04-30 01:28:43 -07:00
committed by GitHub
co-authored by Orca
parent 79faafcc98
commit cb73b372ff
10 changed files with 1098 additions and 61 deletions
@@ -0,0 +1,270 @@
import path from 'path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const handlers = new Map<string, (_event: unknown, args: unknown) => Promise<unknown>>()
const {
handleMock,
lstatMock,
mkdirMock,
realpathMock,
copyFileMock,
readdirMock,
sftpExistsMock,
uploadFileMock,
uploadDirMock,
mkdirSftpMock,
getConnMgrMock
} = vi.hoisted(() => ({
handleMock: vi.fn(),
lstatMock: vi.fn(),
mkdirMock: vi.fn(),
realpathMock: vi.fn(),
copyFileMock: vi.fn(),
readdirMock: vi.fn(),
sftpExistsMock: vi.fn(),
uploadFileMock: vi.fn(),
uploadDirMock: vi.fn(),
mkdirSftpMock: vi.fn(),
getConnMgrMock: vi.fn()
}))
vi.mock('electron', () => ({ ipcMain: { handle: handleMock } }))
vi.mock('fs/promises', () => ({
lstat: lstatMock,
mkdir: mkdirMock,
rename: vi.fn(),
writeFile: vi.fn(),
realpath: realpathMock,
copyFile: copyFileMock,
readdir: readdirMock
}))
vi.mock('../ssh/sftp-upload', () => ({
sftpPathExists: sftpExistsMock,
uploadFile: uploadFileMock,
uploadDirectory: uploadDirMock,
mkdirSftp: mkdirSftpMock
}))
vi.mock('./ssh', () => ({ getSshConnectionManager: getConnMgrMock }))
import { registerFilesystemMutationHandlers } from './filesystem-mutations'
const store = {
getRepos: () => [
{
id: 'r1',
path: path.resolve('/workspace/repo'),
displayName: 'repo',
badgeColor: '#000',
addedAt: 0
}
],
getSettings: () => ({ workspaceDir: path.resolve('/workspace') })
}
const enoent = (): Error => Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
describe('fs:importExternalPaths — SSH operations', () => {
const destDir = '/home/user/project/src'
const connId = 'ssh-conn-1'
const mockSftp = { end: vi.fn() }
const makeConn = () => ({
getState: () => ({ status: 'connected' }),
sftp: vi.fn().mockResolvedValue(mockSftp)
})
const mockDir = (p: string): void => {
const rp = path.resolve(p)
lstatMock.mockImplementation(async (x: string) => {
if (x === rp) {
return { isFile: () => false, isDirectory: () => true, isSymbolicLink: () => false }
}
throw enoent()
})
}
const invoke = (args: Record<string, unknown>) =>
handlers.get('fs:importExternalPaths')!(null, args) as Promise<{
results: Record<string, unknown>[]
}>
beforeEach(() => {
handlers.clear()
;[
handleMock,
lstatMock,
mkdirMock,
realpathMock,
copyFileMock,
readdirMock,
sftpExistsMock,
uploadFileMock,
uploadDirMock,
mkdirSftpMock,
getConnMgrMock
].forEach((m) => m.mockReset())
mockSftp.end.mockReset()
handleMock.mockImplementation((ch: string, h: never) => {
handlers.set(ch, h)
})
realpathMock.mockImplementation(async (p: string) => p)
lstatMock.mockRejectedValue(enoent())
sftpExistsMock.mockResolvedValue(false)
uploadFileMock.mockResolvedValue(undefined)
uploadDirMock.mockResolvedValue(undefined)
mkdirSftpMock.mockResolvedValue(undefined)
getConnMgrMock.mockReturnValue({ getConnection: () => makeConn() })
registerFilesystemMutationHandlers(store as never)
})
it('deconflicts file names via SFTP lstat', async () => {
const rp = path.resolve('/tmp/dropped/logo.png')
lstatMock.mockImplementation(async (x: string) => {
if (x === rp) {
return { isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false }
}
throw enoent()
})
sftpExistsMock.mockImplementation(async (_s: unknown, p: string) => p === `${destDir}/logo.png`)
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/logo.png'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({
status: 'imported',
destPath: `${destDir}/logo copy.png`,
renamed: true
})
})
it('rejects symlink sources', async () => {
const rp = path.resolve('/tmp/dropped/link.txt')
lstatMock.mockImplementation(async (p: string) => {
if (p === rp) {
return { isFile: () => false, isDirectory: () => false, isSymbolicLink: () => true }
}
throw enoent()
})
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/link.txt'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'skipped', reason: 'symlink' })
})
it('handles partial failure with correct per-item results', async () => {
const sources = ['/tmp/dropped/good.txt', '/tmp/dropped/bad.txt', '/tmp/dropped/ok.txt']
lstatMock.mockImplementation(async (p: string) => {
if (sources.map((s) => path.resolve(s)).includes(p)) {
return { isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false }
}
throw enoent()
})
uploadFileMock.mockImplementation(async (_s: unknown, lp: string) => {
if (lp === path.resolve('/tmp/dropped/bad.txt')) {
throw new Error('permission denied')
}
})
const { results } = await invoke({ sourcePaths: sources, destDir, connectionId: connId })
expect(results).toHaveLength(3)
expect(results[0]).toMatchObject({ status: 'imported' })
expect(results[1]).toMatchObject({ status: 'failed', reason: 'permission denied' })
expect(results[2]).toMatchObject({ status: 'imported' })
})
it('uploads directories via mkdirSftp + uploadDirectory', async () => {
mockDir('/tmp/dropped/assets')
readdirMock.mockResolvedValue([])
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/assets'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'imported', kind: 'directory' })
expect(mkdirSftpMock).toHaveBeenCalledWith(mockSftp, `${destDir}/assets`)
})
it('reports per-item failure when deconfliction throws', async () => {
const rp = path.resolve('/tmp/dropped/file.txt')
lstatMock.mockImplementation(async (x: string) => {
if (x === rp) {
return { isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false }
}
throw enoent()
})
sftpExistsMock.mockRejectedValue(new Error('SFTP channel closed'))
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/file.txt'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'failed', reason: 'SFTP channel closed' })
})
it('reports failure when mkdirSftp rejects', async () => {
mockDir('/tmp/dropped/mydir')
readdirMock.mockResolvedValue([])
mkdirSftpMock.mockRejectedValue(new Error('permission denied'))
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/mydir'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'failed', reason: 'permission denied' })
})
it('deconflicts directory names via SFTP lstat', async () => {
mockDir('/tmp/dropped/assets')
readdirMock.mockResolvedValue([])
sftpExistsMock.mockImplementation(async (_s: unknown, p: string) => p === `${destDir}/assets`)
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/assets'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({
status: 'imported',
destPath: `${destDir}/assets copy`,
renamed: true
})
})
it('rejects directory containing nested symlinks', async () => {
mockDir('/tmp/dropped/project')
const rd = path.resolve('/tmp/dropped/project')
readdirMock.mockImplementation(async (p: string) => {
if (p === rd) {
return [
{
name: 'l.txt',
isFile: () => false,
isDirectory: () => false,
isSymbolicLink: () => true
}
]
}
return []
})
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/project'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'skipped', reason: 'symlink' })
expect(uploadDirMock).not.toHaveBeenCalled()
})
it('reports skipped when source lstat returns EACCES', async () => {
const rp = path.resolve('/tmp/dropped/secret.txt')
lstatMock.mockImplementation(async (p: string) => {
if (p === rp) {
throw Object.assign(new Error('EACCES'), { code: 'EACCES' })
}
throw enoent()
})
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/secret.txt'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'skipped', reason: 'permission-denied' })
})
})
+195
View File
@@ -0,0 +1,195 @@
import path from 'path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const handlers = new Map<string, (_event: unknown, args: unknown) => Promise<unknown>>()
const {
handleMock,
lstatMock,
mkdirMock,
realpathMock,
copyFileMock,
readdirMock,
sftpExistsMock,
uploadFileMock,
uploadDirMock,
mkdirSftpMock,
getConnMgrMock
} = vi.hoisted(() => ({
handleMock: vi.fn(),
lstatMock: vi.fn(),
mkdirMock: vi.fn(),
realpathMock: vi.fn(),
copyFileMock: vi.fn(),
readdirMock: vi.fn(),
sftpExistsMock: vi.fn(),
uploadFileMock: vi.fn(),
uploadDirMock: vi.fn(),
mkdirSftpMock: vi.fn(),
getConnMgrMock: vi.fn()
}))
vi.mock('electron', () => ({ ipcMain: { handle: handleMock } }))
vi.mock('fs/promises', () => ({
lstat: lstatMock,
mkdir: mkdirMock,
rename: vi.fn(),
writeFile: vi.fn(),
realpath: realpathMock,
copyFile: copyFileMock,
readdir: readdirMock
}))
vi.mock('../ssh/sftp-upload', () => ({
sftpPathExists: sftpExistsMock,
uploadFile: uploadFileMock,
uploadDirectory: uploadDirMock,
mkdirSftp: mkdirSftpMock
}))
vi.mock('./ssh', () => ({ getSshConnectionManager: getConnMgrMock }))
import { registerFilesystemMutationHandlers } from './filesystem-mutations'
const store = {
getRepos: () => [
{
id: 'r1',
path: path.resolve('/workspace/repo'),
displayName: 'repo',
badgeColor: '#000',
addedAt: 0
}
],
getSettings: () => ({ workspaceDir: path.resolve('/workspace') })
}
const enoent = (): Error => Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
describe('fs:importExternalPaths — SSH routing & connection', () => {
const destDir = '/home/user/project/src'
const connId = 'ssh-conn-1'
const mockSftp = { end: vi.fn() }
const makeConn = (status = 'connected') => ({
getState: () => ({ status }),
sftp: vi.fn().mockResolvedValue(mockSftp)
})
const mockFile = (p: string): void => {
const rp = path.resolve(p)
lstatMock.mockImplementation(async (x: string) => {
if (x === rp) {
return { isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false }
}
throw enoent()
})
}
const invoke = (args: Record<string, unknown>) =>
handlers.get('fs:importExternalPaths')!(null, args) as Promise<{
results: Record<string, unknown>[]
}>
beforeEach(() => {
handlers.clear()
;[
handleMock,
lstatMock,
mkdirMock,
realpathMock,
copyFileMock,
readdirMock,
sftpExistsMock,
uploadFileMock,
uploadDirMock,
mkdirSftpMock,
getConnMgrMock
].forEach((m) => m.mockReset())
mockSftp.end.mockReset()
handleMock.mockImplementation((ch: string, h: never) => {
handlers.set(ch, h)
})
realpathMock.mockImplementation(async (p: string) => p)
lstatMock.mockRejectedValue(enoent())
sftpExistsMock.mockResolvedValue(false)
uploadFileMock.mockResolvedValue(undefined)
uploadDirMock.mockResolvedValue(undefined)
mkdirSftpMock.mockResolvedValue(undefined)
registerFilesystemMutationHandlers(store as never)
})
it('routes to SFTP when connectionId is present', async () => {
getConnMgrMock.mockReturnValue({ getConnection: () => makeConn() })
mockFile('/tmp/dropped/file.txt')
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/file.txt'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'imported', kind: 'file' })
expect(uploadFileMock).toHaveBeenCalled()
expect(copyFileMock).not.toHaveBeenCalled()
})
it('falls back to local import when connectionId is absent', async () => {
mockFile('/tmp/dropped/file.txt')
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/file.txt'],
destDir: path.resolve('/workspace/repo/src')
})
expect(results[0]).toMatchObject({ status: 'imported' })
expect(copyFileMock).toHaveBeenCalled()
})
it('returns empty results without opening SFTP', async () => {
const conn = makeConn()
getConnMgrMock.mockReturnValue({ getConnection: () => conn })
const { results } = await invoke({ sourcePaths: [], destDir, connectionId: connId })
expect(results).toHaveLength(0)
expect(conn.sftp).not.toHaveBeenCalled()
})
it('throws when connectionId has no matching connection', async () => {
getConnMgrMock.mockReturnValue({ getConnection: () => null })
await expect(
invoke({ sourcePaths: ['/tmp/x'], destDir, connectionId: connId })
).rejects.toThrow('No SSH connection')
})
it('throws when connection is reconnecting', async () => {
getConnMgrMock.mockReturnValue({ getConnection: () => makeConn('reconnecting') })
await expect(
invoke({ sourcePaths: ['/tmp/x'], destDir, connectionId: connId })
).rejects.toThrow('reconnecting')
})
it('throws when connection is not active', async () => {
getConnMgrMock.mockReturnValue({ getConnection: () => makeConn('disconnected') })
await expect(
invoke({ sourcePaths: ['/tmp/x'], destDir, connectionId: connId })
).rejects.toThrow('not active')
})
it('throws when conn.sftp() rejects', async () => {
const conn = makeConn()
conn.sftp.mockRejectedValue(new Error('SFTP subsystem not available'))
getConnMgrMock.mockReturnValue({ getConnection: () => conn })
await expect(
invoke({ sourcePaths: ['/tmp/x'], destDir, connectionId: connId })
).rejects.toThrow('SFTP subsystem')
})
it('closes SFTP channel after success', async () => {
getConnMgrMock.mockReturnValue({ getConnection: () => makeConn() })
mockFile('/tmp/dropped/file.txt')
await invoke({ sourcePaths: ['/tmp/dropped/file.txt'], destDir, connectionId: connId })
expect(mockSftp.end).toHaveBeenCalledOnce()
})
it('closes SFTP channel after upload error', async () => {
getConnMgrMock.mockReturnValue({ getConnection: () => makeConn() })
mockFile('/tmp/dropped/file.txt')
uploadFileMock.mockRejectedValue(new Error('disk full'))
const { results } = await invoke({
sourcePaths: ['/tmp/dropped/file.txt'],
destDir,
connectionId: connId
})
expect(results[0]).toMatchObject({ status: 'failed', reason: 'disk full' })
expect(mockSftp.end).toHaveBeenCalledOnce()
})
})
+188
View File
@@ -0,0 +1,188 @@
import { lstat, readdir } from 'fs/promises'
import { basename, join, posix, resolve } from 'path'
import type { SFTPWrapper } from 'ssh2'
import { authorizeExternalPath, isENOENT } from './filesystem-auth'
import { getSshConnectionManager } from './ssh'
import { uploadFile, uploadDirectory, mkdirSftp, sftpPathExists } from '../ssh/sftp-upload'
import type { ImportItemResult } from './filesystem-mutations'
// Why: the SSH import path bypasses SshFilesystemProvider and uses
// SshConnection.sftp() directly because the relay's JSON-RPC fs.writeFile
// is text-only and cannot carry binary data without base64 overhead.
export async function importExternalPathsSsh(
sourcePaths: string[],
destDir: string,
connectionId: string
): Promise<{ results: ImportItemResult[] }> {
if (sourcePaths.length === 0) {
return { results: [] }
}
const connManager = getSshConnectionManager()
const conn = connManager?.getConnection(connectionId)
if (!conn) {
throw new Error(`No SSH connection for "${connectionId}"`)
}
const state = conn.getState()
if (state.status !== 'connected') {
if (state.status === 'reconnecting') {
throw new Error('SSH connection is reconnecting — please try again in a moment')
}
throw new Error('SSH connection is not active — please reconnect and try again')
}
const sftp = await conn.sftp()
try {
const results: ImportItemResult[] = []
const reservedNames = new Set<string>()
for (const sourcePath of sourcePaths) {
const result = await importOneSourceSsh(sftp, sourcePath, destDir, reservedNames)
results.push(result)
if (result.status === 'imported') {
// Why: destPath is a remote POSIX path (e.g. /home/user/foo/bar.txt).
// Node's basename() uses the OS separator, which on Windows would
// return the entire string instead of just the filename.
reservedNames.add(posix.basename(result.destPath))
}
}
return { results }
} finally {
sftp.end()
}
}
async function importOneSourceSsh(
sftp: SFTPWrapper,
sourcePath: string,
destDir: string,
reservedNames: Set<string>
): Promise<ImportItemResult> {
const resolvedSource = resolve(sourcePath)
authorizeExternalPath(resolvedSource)
let sourceStat: Awaited<ReturnType<typeof lstat>>
try {
sourceStat = await lstat(resolvedSource)
} catch (error) {
if (isENOENT(error)) {
return { sourcePath, status: 'skipped', reason: 'missing' }
}
if (
error instanceof Error &&
'code' in error &&
((error as NodeJS.ErrnoException).code === 'EACCES' ||
(error as NodeJS.ErrnoException).code === 'EPERM')
) {
return { sourcePath, status: 'skipped', reason: 'permission-denied' }
}
return {
sourcePath,
status: 'failed',
reason: error instanceof Error ? error.message : String(error)
}
}
if (sourceStat.isSymbolicLink()) {
return { sourcePath, status: 'skipped', reason: 'symlink' }
}
if (!sourceStat.isFile() && !sourceStat.isDirectory()) {
return { sourcePath, status: 'skipped', reason: 'unsupported' }
}
const isDir = sourceStat.isDirectory()
if (isDir) {
const hasSymlink = await preScanForSymlinks(resolvedSource)
if (hasSymlink) {
return { sourcePath, status: 'skipped', reason: 'symlink' }
}
}
const originalName = basename(resolvedSource)
try {
const finalName = await deconflictNameSftp(sftp, destDir, originalName, reservedNames)
const destPath = `${destDir}/${finalName}`
const renamed = finalName !== originalName
if (isDir) {
await mkdirSftp(sftp, destPath)
await uploadDirectory(sftp, resolvedSource, destPath)
} else {
await uploadFile(sftp, resolvedSource, destPath)
}
return {
sourcePath,
status: 'imported',
destPath,
kind: isDir ? 'directory' : 'file',
renamed
}
} catch (error) {
return {
sourcePath,
status: 'failed',
reason: error instanceof Error ? error.message : String(error)
}
}
}
async function deconflictNameSftp(
sftp: SFTPWrapper,
destDir: string,
originalName: string,
reservedNames: Set<string>
): Promise<string> {
if (
!(await sftpPathExists(sftp, `${destDir}/${originalName}`)) &&
!reservedNames.has(originalName)
) {
return originalName
}
const dotIndex = originalName.lastIndexOf('.')
const hasMeaningfulExt = dotIndex > 0
const stem = hasMeaningfulExt ? originalName.slice(0, dotIndex) : originalName
const ext = hasMeaningfulExt ? originalName.slice(dotIndex) : ''
let candidate = `${stem} copy${ext}`
if (!(await sftpPathExists(sftp, `${destDir}/${candidate}`)) && !reservedNames.has(candidate)) {
return candidate
}
let counter = 2
while (counter < 10000) {
candidate = `${stem} copy ${counter}${ext}`
if (!(await sftpPathExists(sftp, `${destDir}/${candidate}`)) && !reservedNames.has(candidate)) {
return candidate
}
counter += 1
}
throw new Error(
`Could not generate a unique name for '${originalName}' after ${counter} attempts`
)
}
async function preScanForSymlinks(dirPath: string): Promise<boolean> {
const entries = await readdir(dirPath, { withFileTypes: true })
for (const entry of entries) {
if (entry.isSymbolicLink()) {
return true
}
if (entry.isDirectory()) {
const childPath = join(dirPath, entry.name)
if (await preScanForSymlinks(childPath)) {
return true
}
}
}
return false
}
+8 -3
View File
@@ -4,6 +4,7 @@ import { basename, dirname, join, resolve } from 'path'
import type { Store } from '../persistence'
import { authorizeExternalPath, resolveAuthorizedPath, isENOENT } from './filesystem-auth'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import { importExternalPathsSsh } from './filesystem-import-ssh'
/**
* Re-throw filesystem errors with user-friendly messages.
@@ -120,15 +121,19 @@ export function registerFilesystemMutationHandlers(store: Store): void {
'fs:importExternalPaths',
async (
_event,
args: { sourcePaths: string[]; destDir: string }
args: { sourcePaths: string[]; destDir: string; connectionId?: string }
): Promise<{ results: ImportItemResult[] }> => {
if (args.connectionId) {
return importExternalPathsSsh(args.sourcePaths, args.destDir, args.connectionId)
}
// Why: destDir must be authorized before any copy work begins. If the
// destination is outside allowed roots, the entire import fails.
// This only applies to local imports — remote paths are authorized by
// the SSH connection boundary (see importExternalPathsSsh).
const resolvedDest = await resolveAuthorizedPath(args.destDir, store)
const results: ImportItemResult[] = []
// Track names reserved during this import batch to avoid collisions
// between multiple dropped items that share the same basename.
const reservedNames = new Set<string>()
for (const sourcePath of args.sourcePaths) {
+97
View File
@@ -0,0 +1,97 @@
import { createReadStream } from 'fs'
import { readdir } from 'fs/promises'
import { join as pathJoin } from 'path'
import type { SFTPWrapper } from 'ssh2'
export function mkdirSftp(sftp: SFTPWrapper, path: string): Promise<void> {
return new Promise((resolve, reject) => {
sftp.mkdir(path, (err) => {
// Why: SFTP status code 4 (SSH_FX_FAILURE) is a generic code that
// OpenSSH returns for "already exists," but could also cover other
// failures (e.g. permission denied on parent). We accept this ambiguity
// because the next operation (write/recurse) will surface the real error.
if (err && (err as { code?: number }).code !== 4) {
reject(err)
} else {
resolve()
}
})
})
}
export function uploadFile(
sftp: SFTPWrapper,
localPath: string,
remotePath: string
): Promise<void> {
return new Promise((resolve, reject) => {
let settled = false
const readStream = createReadStream(localPath)
const writeStream = sftp.createWriteStream(remotePath)
const settle = (fn: typeof resolve | typeof reject, val?: unknown): void => {
if (settled) {
return
}
settled = true
readStream.destroy()
writeStream.destroy()
fn(val as never)
}
writeStream.on('close', () => settle(resolve))
writeStream.on('error', (err) => settle(reject, err))
readStream.on('error', (err) => settle(reject, err))
readStream.pipe(writeStream)
})
}
export async function uploadDirectory(
sftp: SFTPWrapper,
localDir: string,
remoteDir: string
): Promise<void> {
const entries = await readdir(localDir, { withFileTypes: true })
for (const entry of entries) {
const localPath = pathJoin(localDir, entry.name)
const remotePath = `${remoteDir}/${entry.name}`
// Why: skip symlinks and special files (sockets, FIFOs, devices) to
// prevent following symlinks that could exfiltrate local files to the
// remote. The caller's pre-scan catches symlinks up-front, but this
// guard closes the TOCTOU gap if one is created between scan and upload.
if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) {
continue
}
if (entry.isDirectory()) {
await mkdirSftp(sftp, remotePath)
await uploadDirectory(sftp, localPath, remotePath)
} else {
await uploadFile(sftp, localPath, remotePath)
}
}
}
/**
* Check whether a path exists on the remote via SFTP lstat.
* Returns true if the path exists (file, directory, or symlink).
*/
export function sftpPathExists(sftp: SFTPWrapper, remotePath: string): Promise<boolean> {
return new Promise((resolve, reject) => {
sftp.lstat(remotePath, (err) => {
if (!err) {
resolve(true)
return
}
// Why: SFTP status code 2 = SSH_FX_NO_SUCH_FILE — the path does not
// exist, which is the expected "no collision" signal for deconfliction.
if ((err as { code?: number }).code === 2) {
resolve(false)
return
}
reject(err)
})
})
}
+2 -56
View File
@@ -1,63 +1,9 @@
import { createReadStream } from 'fs'
import type { SFTPWrapper, ClientChannel } from 'ssh2'
import type { ClientChannel } from 'ssh2'
import type { SshConnection } from './ssh-connection'
import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from './relay-protocol'
import type { MultiplexerTransport } from './ssh-channel-multiplexer'
// ── SFTP upload helpers ───────────────────────────────────────────────
export async function uploadDirectory(
sftp: SFTPWrapper,
localDir: string,
remoteDir: string
): Promise<void> {
const { readdirSync, statSync } = await import('fs')
const { join: pathJoin } = await import('path')
const entries = readdirSync(localDir)
for (const entry of entries) {
const localPath = pathJoin(localDir, entry)
const remotePath = `${remoteDir}/${entry}`
const stat = statSync(localPath)
if (stat.isDirectory()) {
await mkdirSftp(sftp, remotePath)
await uploadDirectory(sftp, localPath, remotePath)
} else {
await uploadFile(sftp, localPath, remotePath)
}
}
}
export function mkdirSftp(sftp: SFTPWrapper, path: string): Promise<void> {
return new Promise((resolve, reject) => {
sftp.mkdir(path, (err) => {
// Ignore "already exists" errors (SFTP status code 4 = SSH_FX_FAILURE)
if (err && (err as { code?: number }).code !== 4) {
reject(err)
} else {
resolve()
}
})
})
}
export function uploadFile(
sftp: SFTPWrapper,
localPath: string,
remotePath: string
): Promise<void> {
return new Promise((resolve, reject) => {
const readStream = createReadStream(localPath)
const writeStream = sftp.createWriteStream(remotePath)
writeStream.on('close', resolve)
writeStream.on('error', reject)
readStream.on('error', reject)
readStream.pipe(writeStream)
})
}
export { uploadFile, uploadDirectory, mkdirSftp } from './sftp-upload'
// ── Sentinel detection ────────────────────────────────────────────────
+5 -1
View File
@@ -657,7 +657,11 @@ export type PreloadApi = {
excludePaths?: string[]
}) => Promise<string[]>
search: (args: SearchOptions & { connectionId?: string }) => Promise<SearchResult>
importExternalPaths: (args: { sourcePaths: string[]; destDir: string }) => Promise<{
importExternalPaths: (args: {
sourcePaths: string[]
destDir: string
connectionId?: string
}) => Promise<{
results: (
| {
sourcePath: string
+1
View File
@@ -1158,6 +1158,7 @@ const api = {
importExternalPaths: (args: {
sourcePaths: string[]
destDir: string
connectionId?: string
}): Promise<{
results: (
| {
@@ -1,5 +1,8 @@
import { useEffect, useRef } from 'react'
import type { Dispatch, SetStateAction } from 'react'
import { toast } from 'sonner'
import { getConnectionId } from '@/lib/connection-context'
import { extractIpcErrorMessage } from '@/lib/ipc-error'
type UseFileExplorerImportParams = {
worktreePath: string | null
@@ -54,12 +57,14 @@ export function useFileExplorerImport({
}
const { paths, destinationDir } = data
const connectionId = getConnectionId(wtId) ?? undefined
void (async () => {
try {
const { results } = await window.api.fs.importExternalPaths({
sourcePaths: paths,
destDir: destinationDir
destDir: destinationDir,
connectionId
})
// Refresh the destination directory once per gesture
@@ -71,9 +76,18 @@ export function useFileExplorerImport({
// scroll-to-center races with FS watcher refreshes and can snap the
// viewport back to the top of the tree.
const imported = results.filter((r) => r.status === 'imported')
const failed = results.filter((r) => r.status === 'failed')
if (imported.length > 0) {
setSelectedPathRef.current(imported[0].destPath)
}
if (failed.length > 0) {
const noun = failed.length === 1 ? 'file' : 'files'
toast.error(`Failed to import ${failed.length} ${noun}.`)
}
} catch (err) {
toast.error(extractIpcErrorMessage(err, 'Failed to import files.'))
} finally {
clearNativeDragStateRef.current()
}