Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 85117b8e88 feat(remote): Download to… in a remote project's Project view
In an SSH project window, files and folders had no way back to this
computer. The Project view's context menu (after Open In) and the
action "Download to…" now copy the selection into a local folder over
the window's SSH session: each item under its own name, folders
recursively, with a cancellable progress task and a notification
listing failures. Nested selections are downloaded once.

The download loop of Remote Host › Download to… moves to a function
taking an open RemoteFs, so both use it, including its guard against
writing outside the chosen folder.

Fixes #4718
2026-11-20 17:11:04 +08:00
11 змінених файлів з 356 додано та 59 видалено

No files matched your search

+71 -57
Переглянути файл
@@ -349,64 +349,9 @@ impl RemoteService {
progress: &mut (dyn FnMut(&str, usize, usize) + Send),
) -> IdeResult<TransferReport> {
let fs = self.fs(connection).await?;
let mut report = TransferReport::default();
let mut folders = Vec::new();
let mut jobs = Vec::new();
for remote in remotes {
let Some(top) = download_target(dir, remote, remote) else {
report.skipped += 1;
continue;
};
match fs.stat(remote).await {
Ok(Some(e)) if e.is_dir => {
folders.push(top);
let mut entries = Vec::new();
if let Err(e) = remote_tree(&fs, remote, cancel, &mut entries).await {
report.fail(remote.clone(), e);
}
for entry in entries {
match download_target(dir, remote, &entry.path) {
Some(local) if entry.is_dir => folders.push(local),
Some(local) => jobs.push((entry.path, local)),
None => report.skipped += 1,
}
}
}
Ok(Some(_)) => jobs.push((remote.clone(), top)),
Ok(None) => report.fail(remote.clone(), IdeError::not_found(format!("{remote} does not exist"))),
Err(e) => report.fail(remote.clone(), e),
}
}
let root = tokio::fs::canonicalize(dir).await?;
for folder in &folders {
if !stays_inside(&root, folder).await {
report.fail(folder.display().to_string(), outside(folder));
} else if let Err(e) = tokio::fs::create_dir_all(folder).await {
report.fail(folder.display().to_string(), e.into());
}
}
for (i, (remote, local)) in jobs.iter().enumerate() {
if cancel.is_cancelled() {
break;
}
progress(remote, i, jobs.len());
if !stays_inside(&root, local).await {
report.fail(remote.clone(), outside(local));
continue;
}
if let Some(parent) = local.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
report.fail(remote.clone(), e.into());
continue;
}
match fs.download(remote, local).await {
Ok(()) => report.files += 1,
Err(e) => report.fail(remote.clone(), e),
}
}
let r = download_into(&fs, remotes, dir, cancel, progress).await;
fs.close().await;
Ok(report)
r
}
// --- save hook -----------------------------------------------------------------
@@ -656,6 +601,75 @@ fn cache_key(connection: &FsConnection) -> String {
}
/// Files and folders under remote folder `dir` (symlinked folders are not followed).
/// `remotes` (folders recursively) into the local folder `dir`, each under its own name, without
/// the remote path above it; existing files are replaced. Remote Host › Download to…, and the
/// project view's Download to… in a remote project.
pub async fn download_into(
fs: &RemoteFs,
remotes: &[String],
dir: &Path,
cancel: &CancellationToken,
progress: &mut (dyn FnMut(&str, usize, usize) + Send),
) -> IdeResult<TransferReport> {
let mut report = TransferReport::default();
let mut folders = Vec::new();
let mut jobs = Vec::new();
for remote in remotes {
let Some(top) = download_target(dir, remote, remote) else {
report.skipped += 1;
continue;
};
match fs.stat(remote).await {
Ok(Some(e)) if e.is_dir => {
folders.push(top);
let mut entries = Vec::new();
if let Err(e) = remote_tree(fs, remote, cancel, &mut entries).await {
report.fail(remote.clone(), e);
}
for entry in entries {
match download_target(dir, remote, &entry.path) {
Some(local) if entry.is_dir => folders.push(local),
Some(local) => jobs.push((entry.path, local)),
None => report.skipped += 1,
}
}
}
Ok(Some(_)) => jobs.push((remote.clone(), top)),
Ok(None) => report.fail(remote.clone(), IdeError::not_found(format!("{remote} does not exist"))),
Err(e) => report.fail(remote.clone(), e),
}
}
let root = tokio::fs::canonicalize(dir).await?;
for folder in &folders {
if !stays_inside(&root, folder).await {
report.fail(folder.display().to_string(), outside(folder));
} else if let Err(e) = tokio::fs::create_dir_all(folder).await {
report.fail(folder.display().to_string(), e.into());
}
}
for (i, (remote, local)) in jobs.iter().enumerate() {
if cancel.is_cancelled() {
break;
}
progress(remote, i, jobs.len());
if !stays_inside(&root, local).await {
report.fail(remote.clone(), outside(local));
continue;
}
if let Some(parent) = local.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
report.fail(remote.clone(), e.into());
continue;
}
match fs.download(remote, local).await {
Ok(()) => report.files += 1,
Err(e) => report.fail(remote.clone(), e),
}
}
Ok(report)
}
async fn remote_tree(
fs: &RemoteFs,
dir: &str,
+45
Переглянути файл
@@ -1161,6 +1161,50 @@ pub async fn remote_import_local(
result
}
/// One file of a [`remote_download_local`] transfer starting: `done` of `total` files are finished.
#[derive(Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DownloadProgress {
pub path: String,
pub done: u32,
pub total: u32,
}
/// The project view's Download to…: remote files and folders of this window's project into the
/// local folder `target`, each under its own name. Like Remote Host › Download to…, nothing is
/// written outside `target`, even through a local symlink inside it.
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn remote_download_local(
window: Window,
state: State<'_, AppState>,
paths: Vec<String>,
target: std::path::PathBuf,
request: ide_core::RequestId,
on_progress: Channel<DownloadProgress>,
) -> IdeResult<ide_remote::TransferReport> {
let label = AppState::owner_window(window.label());
let c = state.remote_dev.get(label).ok_or_else(|| IdeError::unavailable("Remote project is disconnected"))?;
let Some(session) = c.session.clone() else {
return Err(IdeError::unavailable("Downloading files is not supported in a WSL project yet"));
};
let cancel = state.host.begin_request(request);
let result = async {
let fs = ide_ssh::RemoteFs::new(session.sftp().await?);
let mut progress = |path: &str, done: usize, total: usize| {
let _ =
on_progress.send(DownloadProgress { path: path.to_owned(), done: done as u32, total: total as u32 });
};
let result = ide_remote::service::download_into(&fs, &paths, &target, &cancel, &mut progress).await;
fs.close().await;
result
}
.await;
state.host.end_request(request);
result
}
/// A command the server does not know, from a server of another version than this app: says so,
/// instead of the bare JSON-RPC error.
fn older_server_error(e: IdeError, server_version: &str, host: &str) -> IdeError {
@@ -1391,6 +1435,7 @@ ide_command::desktop_domain!(
remote_connect,
remote_current,
remote_disconnect,
remote_download_local,
remote_forward_port,
remote_forwarded_ports,
remote_import_local,
+1
Переглянути файл
@@ -512,6 +512,7 @@ remote_current always desktop bin
remote_delete trusted project_host bindings async
remote_disconnect always desktop bindings sync
remote_download_into trusted project_host bindings async
remote_download_local trusted desktop bindings async
remote_forward_port trusted desktop bindings async
remote_forwarded_ports trusted desktop bindings sync
remote_import_local trusted desktop bindings async
+13
Переглянути файл
@@ -1345,6 +1345,12 @@ export const commands = {
remoteDelete: (connection: FsConnection, path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_delete", { connection, path })),
remoteDisconnect: () => __TAURI_INVOKE<void>("remote_disconnect"),
remoteDownloadInto: (connection: FsConnection, paths: string[], target: IpcPath, request: RequestId) => typedError<TransferReport, IdeError>(__TAURI_INVOKE("remote_download_into", { connection, paths, target, request })),
/**
* The project view's Download to…: remote files and folders of this window's project into the
* local folder `target`, each under its own name. Like Remote Host › Download to…, nothing is
* written outside `target`, even through a local symlink inside it.
*/
remoteDownloadLocal: (paths: string[], target: string, request: RequestId, onProgress: Channel<DownloadProgress>) => typedError<TransferReport, IdeError>(__TAURI_INVOKE("remote_download_local", { paths, target, request, onProgress })),
/**
* Forwards `localhost:<remote_port>` of the remote host to the same port here when it is free,
* else to a free one. Nothing needs to listen there yet; connections are opened per use.
@@ -5480,6 +5486,13 @@ export type DocumentTextChange = {
insert: string,
};
/** One file of a [`remote_download_local`] transfer starting: `done` of `total` files are finished. */
export type DownloadProgress = {
path: string,
done: number,
total: number,
};
export type DuplicateGroup = {
tokens: number,
/** Lines of the first fragment. */
+12
Переглянути файл
@@ -36,6 +36,7 @@ import {
} from "./operations";
import { nameOf, parentOf } from "./paths";
import { showFilePathPopup } from "./filePath";
import { canDownload, downloadTo } from "./download";
import { showNewPopup, treeHandle } from "./ProjectView";
import { lastFileRefactoring, undoFileRefactoring } from "./fileRefactor";
import {
@@ -412,6 +413,17 @@ export function registerProjectActions(): () => void {
keywords: ["show in explorer", "open in finder"],
run: ({ arg }) => revealInFinder(nodesFrom(contextTarget(arg))),
},
{
id: "project.downloadTo",
title: "Download to…",
category: "Project View",
icon: "download",
when: OPEN,
enabled: () => canDownload(),
description: "Copy the selected files and folders of a remote project to a folder on this computer",
keywords: ["save to local", "copy to local", "scp", "remote"],
run: ({ arg }) => downloadTo(nodesFrom(contextTarget(arg)).map((n) => n.path)),
},
{
id: "project.openWithAssociatedApp",
title: "Open in Associated Application",
+16
Переглянути файл
@@ -215,6 +215,22 @@ describe("project view context menu", () => {
}
});
it("offers Download to… for remote project files only (#4718)", () => {
const off = registerActions([{ id: "project.downloadTo", title: "Download to…", run: () => undefined }]);
try {
const files = [node(`${ROOT}/src`, true), node(`${ROOT}/a.py`)];
expect(labels(contextMenuItems(files))).not.toContain("Download to…");
useRemote.setState({
session: { target: { kind: "ssh", config: "box" }, root: ROOT, host: "h", os: "linux", commands: [] },
});
const l = labels(contextMenuItems(files));
expect(l.indexOf("Download to…")).toBe(l.indexOf("Open In") + 1);
expect(labels(contextMenuItems([node(`${SCRATCHES}/s.py`)]))).not.toContain("Download to…");
} finally {
off();
}
});
it("offers file revision actions only for a single file", () => {
expect(sub(contextMenuItems([node("/p/a.py")]), "Git")).toEqual(
expect.arrayContaining(["Compare with Revision…", "Show Current Revision"]),
+9
Переглянути файл
@@ -34,6 +34,7 @@ import {
revealInFinder,
vcsArg,
} from "./operations";
import { canDownload } from "./download";
import { isSameOrInside } from "./paths";
import { useProjectTree } from "./store";
import { tx } from "@/platform/i18n";
@@ -355,6 +356,14 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
{ kind: "separator" },
...menuGroupItems("openIn", menuGroupContext(nodes)),
]),
inWorkspace &&
canDownload() &&
delegated(
"project.downloadTo",
nodes.map((n) => n.path),
"Download to…",
{ icon: "download" },
),
{ kind: "separator" },
);
+120
Переглянути файл
@@ -0,0 +1,120 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { DownloadProgress, TransferReport } from "@/bindings";
import { commands } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { invokeLocal } from "@/platform/tauriCore";
import { useTasks } from "@/workbench/tasks";
const open = vi.fn();
vi.mock("@/platform/dialog", () => ({ open: (...args: unknown[]) => open(...args) }));
// `@tauri-apps/api/core` resolves to this module (vite.config.ts).
vi.mock("@/platform/tauriCore", async (orig) => ({
...(await orig<typeof import("@/platform/tauriCore")>()),
invokeLocal: vi.fn(async () => undefined),
Channel: class {
onmessage = (_p: unknown) => {};
},
}));
const notify = vi.fn();
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const { canDownload, downloadTo } = await import("./download");
const report = (r: Partial<TransferReport>): TransferReport => ({ files: 0, skipped: 0, errors: [], ...r });
beforeEach(() => {
useTasks.setState({ tasks: [] });
useRemote.setState({
session: { target: { kind: "ssh", config: "s" }, root: "/srv/app", host: "box", os: "linux", commands: [] },
});
open.mockResolvedValue("/Users/me/Downloads");
});
afterEach(() => {
vi.restoreAllMocks();
open.mockReset();
notify.mockReset();
useRemote.setState({ session: null });
useTasks.setState({ tasks: [] });
});
describe("Download to… (#4718)", () => {
it("is offered only in a remote window", () => {
expect(canDownload()).toBe(true);
useRemote.setState({ session: null });
expect(canDownload()).toBe(false);
});
it("downloads the top-level selection into the chosen folder and reports progress", async () => {
let finish!: (r: { status: "ok"; data: TransferReport }) => void;
const download = vi.spyOn(commands, "remoteDownloadLocal").mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const work = downloadTo(["/srv/app/src", "/srv/app/src/main.rs", "/srv/app/Cargo.toml"]);
await vi.waitFor(() => expect(download).toHaveBeenCalled());
const [paths, target, request, channel] = download.mock.calls[0]!;
expect(paths).toEqual(["/srv/app/src", "/srv/app/Cargo.toml"]);
expect(target).toBe("/Users/me/Downloads");
(channel as unknown as { onmessage: (p: DownloadProgress) => void }).onmessage({
path: "/srv/app/src/main.rs",
done: 1,
total: 4,
});
const task = useTasks.getState().tasks[0]!;
expect(task).toMatchObject({ title: "Downloading files", message: "main.rs", fraction: 0.25, done: false });
task.cancel!();
expect(invokeLocal).toHaveBeenCalledWith("cancel_request", { id: request });
finish({ status: "ok", data: report({ files: 4 }) });
await work;
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "info", title: "Downloaded 4 files to /Users/me/Downloads" }),
);
expect(useTasks.getState().tasks[0]?.done).toBe(true);
});
it("lists the files that failed", async () => {
vi.spyOn(commands, "remoteDownloadLocal").mockResolvedValue({
status: "ok",
data: report({ files: 1, errors: [{ path: "/srv/app/link", message: "leads outside the target folder" }] }),
});
await downloadTo(["/srv/app"]);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "warning",
title: "Download to /Users/me/Downloads finished with errors",
body: "/srv/app/link: leads outside the target folder",
}),
);
});
it("does nothing when the folder picker is cancelled", async () => {
open.mockResolvedValue(null);
const download = vi.spyOn(commands, "remoteDownloadLocal");
await downloadTo(["/srv/app/a.txt"]);
expect(download).not.toHaveBeenCalled();
expect(useTasks.getState().tasks).toEqual([]);
});
it("reports a failed download, but not a cancelled one", async () => {
vi.spyOn(commands, "remoteDownloadLocal").mockResolvedValueOnce({
status: "error",
error: { kind: "unavailable", message: "Remote project is disconnected" },
});
await downloadTo(["/srv/app/a.txt"]);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", body: "Remote project is disconnected" }),
);
notify.mockReset();
vi.spyOn(commands, "remoteDownloadLocal").mockResolvedValueOnce({
status: "error",
error: { kind: "cancelled", message: "Cancelled" },
});
await downloadTo(["/srv/app/a.txt"]);
expect(notify).not.toHaveBeenCalled();
expect(useTasks.getState().tasks.every((t) => t.done)).toBe(true);
});
});
+57
Переглянути файл
@@ -0,0 +1,57 @@
/** Download to… in a remote project: copies the selected remote files and folders to this machine. */
import { Channel } from "@tauri-apps/api/core";
import type { DownloadProgress } from "@/bindings";
import { open } from "@/platform/dialog";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { isRemoteWindow } from "@/platform/remote";
import { invokeLocal } from "@/platform/tauriCore";
import { notifications } from "@/workbench/contributions";
import { upsertTask } from "@/workbench/tasks";
import { isInside, nameOf } from "./paths";
/** Whether this window's project files live on another machine, so they can be downloaded. */
export const canDownload = () => isRemoteWindow();
/** Asks for a local folder and downloads `paths` into it, each under its own name. */
export async function downloadTo(paths: readonly string[]) {
// A selected folder brings its selected children along; downloading them again would duplicate them.
const tops = paths.filter((p, i) => paths.indexOf(p) === i && !paths.some((q) => isInside(p, q)));
if (!tops.length || !canDownload()) return;
const folder = await open({ directory: true, multiple: false, title: tx("Download to") });
if (typeof folder !== "string") return;
const request = nextRequestId();
const task = {
id: `file-download-${request}`,
title: tx("Downloading files"),
message: null as string | null,
fraction: null as number | null,
cancel: () => void invokeLocal("cancel_request", { id: request }).catch(() => {}),
};
upsertTask({ ...task, done: false });
const progress = new Channel<DownloadProgress>();
progress.onmessage = (p) =>
upsertTask({ ...task, message: nameOf(p.path), fraction: p.total ? p.done / p.total : null, done: false });
try {
const report = await call(commands.remoteDownloadLocal([...tops], folder, request, progress));
const failed = report.errors.length > 0;
notifications().notify({
level: failed ? (report.files ? "warning" : "error") : "info",
title: failed
? tx`Download to ${folder} finished with errors`
: tx`Downloaded ${report.files} files to ${folder}`,
body: failed ? report.errors.map((e) => `${e.path}: ${e.message}`).join("\n") : undefined,
key: "project.download",
});
} catch (e) {
if (isCancelled(e)) return;
notifications().notify({
level: "error",
title: tx`Cannot download to ${folder}`,
body: e instanceof Error ? e.message : String(e),
key: "project.download",
});
} finally {
upsertTask({ ...task, done: true });
}
}
+6 -1
Переглянути файл
@@ -2783,5 +2783,10 @@
"Test source: {location}": "Test source: {location}",
"Expected:": "Expected:",
"Actual:": "Actual:",
"… {more} more lines": "… {more} more lines"
"… {more} more lines": "… {more} more lines",
"Downloading files": "Downloading files",
"Downloaded {files} files to {folder}": "Downloaded {files} files to {folder}",
"Download to {folder} finished with errors": "Download to {folder} finished with errors",
"Cannot download to {folder}": "Cannot download to {folder}",
"Copy the selected files and folders of a remote project to a folder on this computer": "Copy the selected files and folders of a remote project to a folder on this computer"
}
+6 -1
Переглянути файл
@@ -9146,5 +9146,10 @@
"Test source: {location}": "测试源码:{location}",
"Expected:": "期望:",
"Actual:": "实际:",
"… {more} more lines": "… 另有 {more} 行"
"… {more} more lines": "… 另有 {more} 行",
"Downloading files": "正在下载文件",
"Downloaded {files} files to {folder}": "已下载 {files} 个文件到 {folder}",
"Download to {folder} finished with errors": "下载到 {folder} 完成,但有错误",
"Cannot download to {folder}": "无法下载到 {folder}",
"Copy the selected files and folders of a remote project to a folder on this computer": "把远程项目中选中的文件和文件夹复制到本机的文件夹"
}