Файли
openidea/src/features/remote-dev/ConnectDialog.tsx
T
l0ng-ai 7fa280e9e0 feat(remote): open a dev container from the Welcome screen and from devcontainer.json (#7565)
The Welcome screen lists local dev container configurations and an open devcontainer.json offers Open in Container, both through the existing Reopen in Container flow with trust and host checks; the reopen prompt remembers dismissal per project.

Fixes #7417
2026-12-02 23:24:09 +08:00

389 рядки
13 KiB
TypeScript

/**
* Picks a remote project, then opens it in this or a new window.
* In the desktop app it has its own window (`connectWindow.tsx`).
*/
import { useEffect, useState, type ReactNode } from "react";
import { executeAction } from "@/platform/actions";
import { open } from "@/platform/dialog";
import { useTx } from "@/platform/i18n";
import { call, commands, isCancelled, onIdeEvent, type RemoteEntry, type RemoteTarget } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
import { isRemoteWindow, localGlobalSettings, useRemoteProgress } from "@/platform/remote";
import { sshLabel, type SshConfigValid, validateRemote } from "@/platform/remoteSettings";
import { isWebMode } from "@/platform/webBridge";
import { Button, Dialog, Icon, Input, ProgressBar, Select, Spinner, type DialogButton } from "@/ui";
import { openRemoteProject } from "@/workbench/projectWindow";
import { windowBackgroundHex } from "@/workbench/theme";
import { WindowDialogFrame } from "@/workbench/WindowDialogFrame";
import { devContainerTargetConfig, findDevContainerConfigs, openDevContainer } from "./container";
import {
browsableFolders,
closeConnectDialog,
listedDirectory,
remoteParent,
stageLabel,
useConnectDialog,
} from "./model";
import styles from "./RemoteDev.module.css";
export function ConnectHost() {
const open = useConnectDialog((s) => s.open);
return open ? <ConnectDialog /> : null;
}
const SSH_SETTINGS_PAGE = "tools.sshConfigurations";
const absolutePath = (path: string) => path.startsWith("/") || /^[A-Za-z]:\//.test(path);
/**
* This machine's SSH configurations: the connection is made from here. A remote project's
* window has the remote host's settings, which don't list them.
*/
function useLocalSshConfigs(): SshConfigValid[] {
const [configs, setConfigs] = useState<SshConfigValid[]>([]);
useEffect(() => {
let live = true;
const load = () =>
void localGlobalSettings().then(
(s) => live && setConfigs(validateRemote(s).ssh.configs),
() => {},
);
load();
const off = onIdeEvent("settingsChanged", load);
return () => {
live = false;
off();
};
}, []);
return configs;
}
function Frame({
standalone,
onClose,
buttons,
children,
}: {
standalone: boolean;
onClose: () => void;
buttons: readonly DialogButton[];
children: ReactNode;
}) {
const tx = useTx();
if (standalone)
return (
<WindowDialogFrame title="Remote Development" buttons={buttons} onCancel={onClose}>
{children}
</WindowDialogFrame>
);
return (
<Dialog open title={tx("Remote Development")} onClose={onClose} width={560} buttons={buttons}>
{children}
</Dialog>
);
}
/**
* `standalone`: fills the Remote Development window, whose project window connects
* (`onConnect`: true once the project is open).
*/
export function ConnectDialog({
standalone = false,
onClose = closeConnectDialog,
onConnect,
}: {
standalone?: boolean;
onClose?: () => void;
onConnect?: (target: RemoteTarget, path: string) => Promise<boolean>;
}) {
const tx = useTx();
const configs = useLocalSshConfigs();
const [picked, setSsh] = useState("");
const ssh = configs.some((c) => c.id === picked) ? picked : (configs[0]?.id ?? "");
const [kind, setKind] = useState<RemoteTarget["kind"]>("ssh");
// Installed WSL distributions; none (or no WSL at all) hides the WSL choice.
const [distros, setDistros] = useState<string[]>([]);
const [distro, setDistro] = useState("");
const [path, setPath] = useState("~");
const [localPath, setLocalPath] = useState("");
const [containerFolder, setContainerFolder] = useState<{ path: string; configs: string[]; error?: string } | null>(
null,
);
const [pickedConfig, setPickedConfig] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [browse, setBrowse] = useState<{ dir: string; folders: RemoteEntry[] } | null>(null);
useEffect(() => {
let live = true;
// Detection is a convenience: a failure leaves WSL unavailable.
void call(commands.wslDistros())
.then((found) => {
if (!live) return;
setDistros(found);
setDistro((d) => d || (found[0] ?? ""));
})
.catch(() => {});
return () => {
live = false;
};
}, []);
const wsl = kind === "wsl";
const container = kind === "devContainer";
const canUseContainer = !isRemoteWindow() && !isWebMode();
const folder = container ? ipcPath(localPath.trim()) : "";
const scanned = containerFolder?.path === folder ? containerFolder : null;
const containerConfigs = scanned?.configs ?? [];
const config = containerConfigs.includes(pickedConfig) ? pickedConfig : containerConfigs[0];
const name = wsl ? distro : ssh;
const target: RemoteTarget = wsl ? { kind: "wsl", distro } : { kind: "ssh", config: ssh };
useEffect(() => {
if (!absolutePath(folder)) return;
let live = true;
const timer = setTimeout(() => {
void findDevContainerConfigs(folder).then(
(configs) => live && setContainerFolder({ path: folder, configs }),
(e: unknown) => live && setContainerFolder({ path: folder, configs: [], error: String(e) }),
);
}, 150);
return () => {
clearTimeout(timer);
live = false;
};
}, [folder]);
const changeFolder = (value: string) => {
setLocalPath(value);
setPickedConfig("");
setError(null);
};
const browseLocal = async () => {
setError(null);
try {
const picked = await open({ directory: true, defaultPath: absolutePath(folder) ? folder : undefined });
if (picked) changeFolder(ipcPath(picked));
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
};
const list = async (dir: string) => {
setError(null);
setBusy(true);
try {
const entries = await call(commands.remoteBootstrapList(ssh, dir));
const shown = listedDirectory(dir, entries);
setBrowse({ dir: shown, folders: browsableFolders(entries) });
setPath(shown);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};
const connect = async () => {
setError(null);
setBusy(true);
try {
const dir = container ? folder : path.trim() || "~";
const destination: RemoteTarget =
container && config
? { kind: "devContainer", folder, config: devContainerTargetConfig(containerConfigs, config) }
: target;
const opened = onConnect
? await onConnect(destination, dir)
: destination.kind === "devContainer"
? await openDevContainer(dir, destination.config)
: await openRemoteProject(destination, dir);
if (opened) onClose();
else setBusy(false);
} catch (e) {
if (!isCancelled(e)) setError(e instanceof Error ? e.message : String(e));
setBusy(false);
}
};
const options = configs.map((c) => ({
value: c.id,
verbatim: true,
verbatimDetail: true,
label: c.name.trim() || sshLabel(c),
detail: sshLabel(c),
}));
const ready = !busy && (container ? Boolean(config) : Boolean(name && path.trim()));
const connecting = useRemoteProgress((s) => s.progress !== null);
const configure = () =>
standalone
? void call(commands.windowOpenSettings(SSH_SETTINGS_PAGE, false, windowBackgroundHex())).catch(() => {})
: void executeAction("file.settings", SSH_SETTINGS_PAGE);
return (
<Frame
standalone={standalone}
onClose={onClose}
buttons={[
{
label: connecting ? "Connecting…" : "Open",
role: "default",
disabled: !ready,
onClick: () => void connect(),
},
{ label: "Cancel", role: "cancel" },
]}
>
<form
className={standalone ? `${styles.form} ${styles.windowForm}` : styles.form}
onSubmit={(e) => {
e.preventDefault();
if (ready) void connect();
}}
>
<p className={styles.hint}>
{container
? tx("Select a local project folder to build or start its dev container.")
: tx("The project runs on the remote host; the IDE backend is installed there on first use.")}
</p>
{(distros.length > 0 || canUseContainer) && (
<>
<label className={styles.label}>{tx("Connect through:")}</label>
<Select
value={kind}
options={[
{ value: "ssh", label: "SSH" },
...(distros.length ? [{ value: "wsl", label: "WSL" }] : []),
...(canUseContainer ? [{ value: "devContainer", label: "Dev Container" }] : []),
]}
onChange={(k) => {
setKind(k as RemoteTarget["kind"]);
setBrowse(null);
setError(null);
}}
aria-label={tx("Connect through")}
/>
</>
)}
{container ? null : wsl ? (
<>
<label className={styles.label}>{tx("WSL distribution:")}</label>
<Select
value={distro || null}
options={distros.map((d) => ({ value: d, verbatim: true, label: d }))}
onChange={setDistro}
aria-label={tx("WSL distribution")}
/>
</>
) : (
<>
<label className={styles.label}>{tx("SSH configuration:")}</label>
<div className={styles.row}>
<Select
className={styles.grow}
value={ssh || null}
options={options}
placeholder={tx("No SSH configurations")}
onChange={(id) => {
setSsh(id);
setBrowse(null);
}}
aria-label={tx("SSH configuration")}
/>
<Button onClick={configure}>{tx("Configure…")}</Button>
</div>
</>
)}
<label className={styles.label} htmlFor="remote-dev-path">
{tx("Project directory:")}
</label>
<div className={styles.row}>
<Input
id="remote-dev-path"
className={styles.grow}
data-autofocus
value={container ? localPath : path}
spellCheck={false}
disabled={container && busy}
onChange={(e) => (container ? changeFolder(e.target.value) : setPath(e.target.value))}
/>
{/* Browsing lists over SFTP; a WSL distribution has no such session before connecting. */}
{!wsl && (
<Button
disabled={busy || (!container && !ssh)}
onClick={() => void (container ? browseLocal() : list(path.trim() || "~"))}
>
{tx("Browse")}
</Button>
)}
</div>
{container && containerConfigs.length > 1 && (
<>
<label className={styles.label}>{tx("Dev container configuration:")}</label>
<Select
value={config ?? null}
options={containerConfigs.map((value) => ({ value, label: value, verbatim: true }))}
disabled={busy}
onChange={setPickedConfig}
aria-label={tx("Dev container configuration")}
/>
</>
)}
{container && folder && !absolutePath(folder) && (
<p className={styles.hint}>{tx("Enter an absolute folder path.")}</p>
)}
{container && scanned && !scanned.error && !config && (
<p className={styles.hint} role="status">
{tx("No dev container configuration found in this folder.")}
</p>
)}
{browse && (
<ul className={styles.folders} aria-label={tx("Remote folders")}>
{browse.dir !== "/" && (
<li>
<button type="button" className={styles.folder} onClick={() => void list(remoteParent(browse.dir))}>
<Icon name="folder" />
..
</button>
</li>
)}
{browse.folders.map((f) => (
<li key={f.path}>
<button type="button" className={styles.folder} onClick={() => void list(f.path)}>
<Icon name="folder" />
{f.name}
</button>
</li>
))}
</ul>
)}
<ConnectProgress />
{(error || (container && scanned?.error)) && (
<div className={styles.error} role="alert">
{error || scanned?.error}
</div>
)}
</form>
</Frame>
);
}
/** The stage of the connection in progress (and how far a download / upload is). */
function ConnectProgress() {
const tx = useTx();
const progress = useRemoteProgress((s) => s.progress);
if (!progress) return null;
const percent = progress.fraction == null ? null : Math.round(progress.fraction * 100);
return (
<div className={styles.progress} role="status">
<div className={styles.progressLine}>
<Spinner size={12} />
<span>{tx(stageLabel(progress.stage))}</span>
{percent != null && <span className={styles.percent}>{percent}%</span>}
</div>
<ProgressBar value={progress.fraction} aria-label={tx(stageLabel(progress.stage))} />
</div>
);
}