feat(deployment): start an SSH session in a Remote Host folder (#8284)

Remote Host's context menu on an SFTP server gains Start SSH Session in Directory: a terminal tab on the server's SSH configuration whose login shell starts in the chosen folder (a file's parent, or the root on empty space). ssh_open_terminal takes an optional remote folder and runs cd -- <folder>; exec "$SHELL" -l, so a missing folder reports the error and leaves the shell in home.
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-06 03:37:57 +08:00
1 джерело cfbc0e3ed3
коміт 8e8a3f397b
13 files changed
+141 -29

No files matched your search

+14 -2
Переглянути файл
@@ -74,11 +74,13 @@ pub(crate) fn apply_output_rate(host: &Host, window: &str) {
}
/// Tools › Start SSH Session: a login shell on SSH configuration `id`, opened by the
/// built-in client with the configuration's saved password, key or agent.
/// built-in client with the configuration's saved password, key or agent. With `cwd` (Remote
/// Host › Start SSH Session in Directory) the shell starts in that remote folder.
pub async fn spawn_ssh(
host: &Host,
window: &str,
id: &str,
cwd: Option<&str>,
cols: u16,
rows: u16,
on_output: Emit<String>,
@@ -93,7 +95,7 @@ pub async fn spawn_ssh(
let out = feed.clone();
let process = session
.spawn(
"",
&ssh_shell_command(cwd),
Some(size),
Box::new(move |chunk| match chunk {
ide_ssh::Output::Stdout(data) | ide_ssh::Output::Stderr(data) => out.output(data),
@@ -134,6 +136,16 @@ pub async fn spawn_ssh(
)
}
/// The exec command of an SSH terminal: empty for the account's shell, or a `cd` into `cwd` that
/// then replaces itself with the login shell. A `cd` that fails prints its error and leaves the
/// shell in the home folder.
fn ssh_shell_command(cwd: Option<&str>) -> String {
match cwd.map(str::trim).filter(|d| !d.is_empty()) {
None => String::new(),
Some(dir) => format!("cd -- {}; exec \"${{SHELL:-/bin/sh}}\" -l", ide_ssh::shell::tilde_quote(dir)),
}
}
enum SshInput {
Data(Vec<u8>),
Resize(u16, u16),
+26 -1
Переглянути файл
@@ -91,6 +91,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
&host,
"main",
"box",
None,
100,
30,
Arc::new(move |s| {
@@ -116,7 +117,7 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
assert!(!host.terminals.contains(info.id));
// Closing the tab hangs up a running shell.
let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", 80, 24, Arc::new(|_| {})).await.unwrap();
let info = ide_host::ops::term::spawn_ssh(&host, "main", "box", None, 80, 24, Arc::new(|_| {})).await.unwrap();
host.terminals.kill(info.id).unwrap();
let code = loop {
match events.recv_timeout(Duration::from_secs(10)).expect("exit event") {
@@ -128,6 +129,30 @@ async fn ssh_session_opens_a_shell_with_the_saved_password() {
host.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ssh_session_in_a_directory_starts_the_login_shell_there() {
let tmp = tempfile::tempdir().unwrap();
let (host, _events) = host_with_ssh_box(tmp.path(), Arc::new(|cmd| (format!("ran: {cmd}\n"), 0))).await;
let (tx, output) = mpsc::channel();
let tx = Mutex::new(tx);
ide_host::ops::term::spawn_ssh(
&host,
"main",
"box",
Some("~/my app's"),
80,
24,
Arc::new(move |s| {
let _ = tx.lock().unwrap().send(s);
}),
)
.await
.unwrap();
let out = read_until(&output, "\n");
assert!(out.contains(r#"ran: cd -- ~/'my app'\''s'; exec "${SHELL:-/bin/sh}" -l"#), "{out:?}");
host.shutdown().await;
}
/// Reads what a connection to the local end of a Docker tunnel gets back.
async fn dial(port: u16) -> std::io::Result<String> {
use tokio::io::AsyncReadExt;
+1 -1
Переглянути файл
@@ -156,7 +156,7 @@ The actions work on the selection in the Project view, or on the file in the act
- **Delete from Server**
- **Automatic Upload**: turns automatic upload on (Always) or off.
- **Open in Browser (Deployed)**: opens the file's URL on the web server.
- **Browse Remote Host**: opens the **Remote Host** tool window, a tree of the server's files with **Open** (edit a copy; saving uploads it back), **Download to Project**, **New Folder…**, **Rename…**, **Delete…**, **Refresh** and **Copy Path**.
- **Browse Remote Host**: opens the **Remote Host** tool window, a tree of the server's files with **Open** (edit a copy; saving uploads it back), **Download to Project**, **New Folder…**, **Rename…**, **Delete…**, **Refresh** and **Copy Path**. On an SFTP server, **Start SSH Session in Directory** opens a terminal tab with a login shell in the chosen folder (a file's parent folder, or the root on empty space).
Drag files or folders from **Project** or your desktop file manager into **Remote Host** to upload them without configuring mappings. Drop onto a folder to upload inside it, onto a file to use its parent folder, or onto the root path or empty tree space to use the displayed root. **Upload Files…** in the context menu opens a file picker (multiple files), and **Upload Folder…** opens a folder picker. The selected folder is uploaded under its own name, including its contents. Existing names ask for confirmation before replacing files and merging folders; cancelling leaves them unchanged. The transfer appears in background tasks and can be cancelled. These direct uploads do not apply deployment exclusions; source symbolic links are skipped. Desktop file-manager drops are not available in Remote Development windows; dragging paths from that window's **Project** tree is supported.
+1 -1
Переглянути файл
@@ -153,7 +153,7 @@ OpenIDEA 能识别 `Dockerfile`、`Containerfile`、`Dockerfile.<名称>`、`*.d
- **从服务器删除**
- **自动上传**:开启(始终)或关闭自动上传。
- **在浏览器中打开(已部署)**:在 Web 服务器上打开文件对应的 URL。
- **浏览远程主机**:打开 **远程主机** 工具窗口,以树的形式浏览服务器文件,支持 **打开**(编辑本地副本,保存时自动上传回去)、**下载到项目**、**新建文件夹…**、**重命名…**、**删除…**、**刷新** 和 **复制路径**。
- **浏览远程主机**:打开 **远程主机** 工具窗口,以树的形式浏览服务器文件,支持 **打开**(编辑本地副本,保存时自动上传回去)、**下载到项目**、**新建文件夹…**、**重命名…**、**删除…**、**刷新** 和 **复制路径**。SFTP 服务器上的 **在目录中启动 SSH 会话** 会打开一个终端标签页,登录 shell 从所选文件夹启动(选中文件时为其父文件夹,在空白处时为根目录)。
可以从 **项目** 视图或桌面文件管理器拖入文件、文件夹到 **远程主机**,无需配置路径映射。拖到文件夹上传到其内部,拖到文件上传到其父目录,拖到根路径或文件树空白处则上传到当前显示的根目录。右键菜单中的 **上传文件…** 可多选文件,**上传文件夹…** 则打开文件夹选择器;选中的文件夹会连同其内容以原文件夹名称上传。同名项目会先询问是否替换文件并合并文件夹;取消确认不会修改它们。传输会显示在后台任务中,可以取消。这类直接上传不应用部署排除规则,源符号链接会被跳过。远程开发窗口暂不支持从桌面文件管理器拖入本机文件,但支持从该窗口的 **项目** 文件树拖入。
+36 -6
Переглянути файл
@@ -8,12 +8,13 @@ async function showRemoteHost(page: Page) {
const settingsModule = "/src/platform/remoteSettings.ts";
const routeModule = "/src/platform/tauriCore.ts";
const actionsModule = "/src/platform/actions.ts";
const [{ useProject }, { DEFAULT_DEPLOYMENT_SERVER }, { setInvokeRoute }, { executeAction }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ settingsModule),
import(/* @vite-ignore */ routeModule),
import(/* @vite-ignore */ actionsModule),
]);
const [{ useProject }, { DEFAULT_DEPLOYMENT_SERVER, DEFAULT_SSH_CONFIG }, { setInvokeRoute }, { executeAction }] =
await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ settingsModule),
import(/* @vite-ignore */ routeModule),
import(/* @vite-ignore */ actionsModule),
]);
const entry = (path: string, isDir: boolean) => ({
path,
name: path.split("/").at(-1)!,
@@ -52,6 +53,7 @@ async function showRemoteHost(page: Page) {
useProject.setState({
settings: {
...useProject.getState().settings,
ssh: { configs: [{ ...DEFAULT_SSH_CONFIG, id: "demo", name: "Demo", host: "demo.example" }] },
deployment: {
servers: [
{
@@ -180,3 +182,31 @@ test("Upload Folder… opens a directory picker and cancellation leaves the serv
await expect.poll(async () => (await ipcCalls(page, "plugin:dialog|open")).length).toBe(2);
expect(await uploads(page)).toHaveLength(1);
});
test("Start SSH Session in Directory opens a shell in the folder, a file's folder or the root", async ({
workbench: page,
}) => {
await showRemoteHost(page);
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers["ssh_open_terminal"] = () => {
throw new Error("connection refused");
};
});
const remote = page.getByRole("tree", { name: "Remote files" });
const item = page.getByRole("menuitem", { name: "Start SSH Session in Directory", exact: true });
await remote.getByRole("treeitem", { name: "assets", exact: true }).click({ button: "right" });
await item.click();
await remote.getByRole("treeitem", { name: "index.html", exact: true }).click({ button: "right" });
await item.click();
const box = (await remote.boundingBox())!;
await page.mouse.click(box.x + 70, box.y + box.height - 10, { button: "right" });
await item.click();
const sessions = async () => (await ipcCalls(page, "ssh_open_terminal")).map(({ id, cwd }) => ({ id, cwd }));
await expect.poll(async () => (await sessions()).length).toBe(3);
expect(await sessions()).toEqual([
{ id: "demo", cwd: "/srv/demo/assets" },
{ id: "demo", cwd: "/srv/demo" },
{ id: "demo", cwd: "/srv/demo" },
]);
});
+2
Переглянути файл
@@ -49,6 +49,7 @@ pub async fn ssh_open_terminal(
window: tauri::Window,
state: State<'_, AppState>,
id: String,
cwd: Option<String>,
cols: u16,
rows: u16,
on_output: tauri::ipc::Channel<String>,
@@ -58,6 +59,7 @@ pub async fn ssh_open_terminal(
&host,
window.label(),
&id,
cwd.as_deref(),
cols,
rows,
std::sync::Arc::new(move |chunk| {
+1 -1
Переглянути файл
@@ -2460,7 +2460,7 @@ export const commands = {
* Tools › Start SSH Session: a shell on configuration `id` in a terminal tab, through the
* built-in client with the configuration's saved credentials.
*/
sshOpenTerminal: (id: string, cols: number, rows: number, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("ssh_open_terminal", { id, cols, rows, onOutput })),
sshOpenTerminal: (id: string, cwd: string | null, cols: number, rows: number, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("ssh_open_terminal", { id, cwd, cols, rows, onOutput })),
/** Whether a password is saved under `key` (an FTP deployment server's). */
sshPasswordSaved: (key: string) => __TAURI_INVOKE<boolean>("ssh_password_saved", { key }),
/** Remembers the password / passphrase of configuration `id` (`None` forgets it). */
+12
Переглянути файл
@@ -115,6 +115,18 @@ export function RemoteHostView() {
disabled: !entries.length,
run: () => void downloadTo(server, entries),
},
...(server.kind === "sftp" && server.sshConfig
? [
{ kind: "separator" as const },
{
id: "sshSession",
label: "Start SSH Session in Directory",
icon: "terminal" as const,
disabled: !target,
run: () => target && void executeAction("ssh.startSession", { id: server.sshConfig, cwd: target }),
},
]
: []),
{ kind: "separator" },
{
id: "newFolder",
+6 -2
Переглянути файл
@@ -9,7 +9,7 @@ import { registerOverlay } from "@/workbench/contributions";
import { dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { AskpassHost } from "./AskpassDialog";
import { startPasswordMigrationNotice } from "./passwordMigration";
import { chooseSshSession, SSH_SETTINGS_PAGE, startSshSession } from "./session";
import { chooseSshSession, sessionArg, SSH_SETTINGS_PAGE, startSshSession } from "./session";
export function activate(): () => void {
const disposers = [
@@ -21,12 +21,16 @@ export function activate(): () => void {
{
id: "ssh.startSession",
title: "Start SSH Session…",
// `arg`: a configuration id or `{ id, cwd }` (Remote Host › Start SSH Session in Directory).
description: "Opens a terminal tab connected to an SSH configuration (`arg`: its id; otherwise a chooser).",
category: "Tools",
icon: "terminal",
when: "projectOpen",
keywords: ["ssh", "remote", "terminal", "shell", "connect"],
run: ({ arg }) => (typeof arg === "string" && arg ? startSshSession(arg) : chooseSshSession()),
run: ({ arg }) => {
const { id, cwd } = sessionArg(arg);
return id ? startSshSession(id, cwd) : chooseSshSession();
},
},
{
id: "ssh.configurations",
+17 -7
Переглянути файл
@@ -51,7 +51,7 @@ export function sshRemedy(message: string, auth: SshConfigValid["auth"]): SshRem
}
export interface ConnectDeps {
open: (id: string, cols: number, rows: number, output: Channel<string>) => Promise<TerminalInfo>;
open: (id: string, cwd: string | null, cols: number, rows: number, output: Channel<string>) => Promise<TerminalInfo>;
confirmTrust: (message: string) => Promise<boolean>;
askSecret: (message: string) => Promise<string | null>;
trustHost: (id: string) => Promise<unknown>;
@@ -59,11 +59,11 @@ export interface ConnectDeps {
}
const defaultDeps: ConnectDeps = {
open: (id, cols, rows, output) => {
open: (id, cwd, cols, rows, output) => {
// A channel is unusable once a failed attempt dropped it on the backend; each attempt gets its own.
const attempt = new Channel<string>();
attempt.onmessage = (chunk) => output.onmessage(chunk);
return call(commands.sshOpenTerminal(id, cols, rows, attempt));
return call(commands.sshOpenTerminal(id, cwd, cols, rows, attempt));
},
confirmTrust: (message) =>
confirm({
@@ -86,12 +86,14 @@ const defaultDeps: ConnectDeps = {
};
/**
* Opens a shell on configuration `config` with the built-in client. When the
* Opens a shell on configuration `config` with the built-in client, in remote folder `cwd` when
* given. When the
* host key is unknown or a password / passphrase is missing or wrong, asks for
* it and retries; other errors, and declined prompts, rethrow.
*/
export async function openSshTerminal(
config: SshConfigValid,
cwd: string | null,
cols: number,
rows: number,
output: Channel<string>,
@@ -101,7 +103,7 @@ export async function openSshTerminal(
for (let attempt = 0; ; attempt++) {
try {
// oxlint-disable-next-line no-await-in-loop -- each retry depends on the failure of the previous attempt
return await deps.open(config.id, cols, rows, output);
return await deps.open(config.id, cwd, cols, rows, output);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
const remedy = attempt < 4 ? sshRemedy(message, config.auth) : null;
@@ -122,7 +124,15 @@ export async function openSshTerminal(
}
}
export async function startSshSession(id: string) {
/** The `ssh.startSession` argument: a configuration id, or `{ id, cwd }` to start in a remote folder. */
export function sessionArg(arg: unknown): { id: string | null; cwd: string | null } {
if (typeof arg === "string") return { id: arg || null, cwd: null };
if (!arg || typeof arg !== "object") return { id: null, cwd: null };
const { id, cwd } = arg as { id?: unknown; cwd?: unknown };
return { id: typeof id === "string" && id ? id : null, cwd: typeof cwd === "string" && cwd ? cwd : null };
}
export async function startSshSession(id: string, cwd: string | null = null) {
const config = workflowSettings().ssh.configs.find((c) => c.id === id);
if (!config) {
notifications().notify({
@@ -135,7 +145,7 @@ export async function startSshSession(id: string) {
}
await executeAction("terminal.runCommand", {
name: config.name.trim() || sshLabel(config) || config.id,
spawn: (cols: number, rows: number, output: Channel<string>) => openSshTerminal(config, cols, rows, output),
spawn: (cols: number, rows: number, output: Channel<string>) => openSshTerminal(config, cwd, cols, rows, output),
});
}
+23 -8
Переглянути файл
@@ -5,7 +5,7 @@ import * as contributions from "@/workbench/contributions";
import * as messages from "@/workbench/messages";
import { answerAskpass, askpassAnswer, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { startPasswordMigrationNotice } from "./passwordMigration";
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
import { type ConnectDeps, openSshTerminal, sessionArg, sessionItems, sshRemedy } from "./session";
it("offers recovery for legacy plaintext but never removes it without confirmation", async () => {
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
@@ -126,7 +126,7 @@ describe("Start SSH Session chooser", () => {
describe("Start SSH Session connection", () => {
const config: SshConfigValid = { ...DEFAULT_SSH_CONFIG, id: "box", host: "box", auth: "password", saveSecret: true };
const output = {} as Parameters<typeof openSshTerminal>[3];
const output = {} as Parameters<typeof openSshTerminal>[4];
const deps = (errors: string[], patch: Partial<ConnectDeps> = {}): ConnectDeps => ({
open: vi.fn(async () => {
const error = errors.shift();
@@ -140,6 +140,14 @@ describe("Start SSH Session connection", () => {
...patch,
});
it("reads a configuration id or an id with a remote folder from the action argument", () => {
expect(sessionArg("box")).toEqual({ id: "box", cwd: null });
expect(sessionArg({ id: "box", cwd: "/srv/app" })).toEqual({ id: "box", cwd: "/srv/app" });
expect(sessionArg({ id: "box", cwd: "" })).toEqual({ id: "box", cwd: null });
expect(sessionArg(undefined)).toEqual({ id: null, cwd: null });
expect(sessionArg({ cwd: "/srv" })).toEqual({ id: null, cwd: "/srv" });
});
it("classifies what a failed connection needs", () => {
expect(sshRemedy("Unknown SSH host key for box:22 (SHA256:x)", "password")).toBe("trustHost");
expect(sshRemedy("SSH password required for dev@box", "password")).toBe("secret");
@@ -151,14 +159,21 @@ describe("Start SSH Session connection", () => {
it("opens with the saved credentials without asking", async () => {
const d = deps([]);
expect(await openSshTerminal(config, 80, 24, output, d)).toMatchObject({ id: 7 });
expect(d.open).toHaveBeenCalledWith("box", 80, 24, output);
expect(await openSshTerminal(config, null, 80, 24, output, d)).toMatchObject({ id: 7 });
expect(d.open).toHaveBeenCalledWith("box", null, 80, 24, output);
expect(d.askSecret).not.toHaveBeenCalled();
});
it("opens in the requested remote folder on every attempt", async () => {
const d = deps(["SSH password required for dev@box"]);
await openSshTerminal(config, "/srv/app", 80, 24, output, d);
expect(d.open).toHaveBeenNthCalledWith(1, "box", "/srv/app", 80, 24, output);
expect(d.open).toHaveBeenNthCalledWith(2, "box", "/srv/app", 80, 24, output);
});
it("trusts a new host key and asks for a missing password, then connects", async () => {
const d = deps(["Unknown SSH host key for box:22 (SHA256:x)", "SSH password required for dev@box"]);
await openSshTerminal(config, 80, 24, output, d);
await openSshTerminal(config, null, 80, 24, output, d);
expect(d.trustHost).toHaveBeenCalledWith("box");
expect(d.setSecret).toHaveBeenCalledWith("box", "pw", true);
expect(d.open).toHaveBeenCalledTimes(3);
@@ -166,11 +181,11 @@ describe("Start SSH Session connection", () => {
it("stops when a prompt is declined or the error has no remedy", async () => {
const declined = deps(["SSH password required for dev@box"], { askSecret: vi.fn(async () => null) });
await expect(openSshTerminal(config, 80, 24, output, declined)).rejects.toThrow("SSH password required");
await expect(openSshTerminal(config, null, 80, 24, output, declined)).rejects.toThrow("SSH password required");
expect(declined.setSecret).not.toHaveBeenCalled();
const refused = deps(["connection refused"]);
await expect(openSshTerminal(config, 80, 24, output, refused)).rejects.toThrow("connection refused");
await expect(openSshTerminal(config, null, 80, 24, output, refused)).rejects.toThrow("connection refused");
const changed = deps(["Unknown SSH host key a", "Unknown SSH host key b"]);
await expect(openSshTerminal(config, 80, 24, output, changed)).rejects.toThrow("Unknown SSH host key b");
await expect(openSshTerminal(config, null, 80, 24, output, changed)).rejects.toThrow("Unknown SSH host key b");
});
});
+1
Переглянути файл
@@ -4425,6 +4425,7 @@
"Cannot upload files": "Cannot upload files",
"Desktop uploads are not available in a remote development window": "Desktop uploads are not available in a remote development window",
"Upload Folder…": "Upload Folder…",
"Start SSH Session in Directory": "Start SSH Session in Directory",
"Upload Folder": "Upload Folder",
"Mark as Read": "Mark as Read",
"Mark as Unread": "Mark as Unread",
+1
Переглянути файл
@@ -11017,6 +11017,7 @@
"Cannot upload files": "无法上传文件",
"Desktop uploads are not available in a remote development window": "远程开发窗口暂不支持从本机桌面上传文件",
"Upload Folder…": "上传文件夹…",
"Start SSH Session in Directory": "在目录中启动 SSH 会话",
"Upload Folder": "上传文件夹",
"Mark as Read": "标记为已读",
"Mark as Unread": "标记为未读",