From 7fa280e9e0b7f596ea8c495d92bb2f9ad53888f0 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 2 Dec 2026 23:24:09 +0800 Subject: [PATCH] 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 --- docs/en/guide/remote/containers.mdx | 32 ++-- docs/zh/guide/remote/containers.mdx | 24 +-- src/features/project-trust/index.tsx | 43 +++-- .../remote-dev/ConnectDialog.test.tsx | 52 +++++- src/features/remote-dev/ConnectDialog.tsx | 114 +++++++++++-- src/features/remote-dev/connectWindow.tsx | 13 +- src/features/remote-dev/container.test.ts | 61 ++++++- src/features/remote-dev/container.ts | 154 ++++++++++++++++-- src/features/remote-dev/index.ts | 8 +- src/platform/locales/text/en.json | 9 + src/platform/locales/text/es.json | 1 - src/platform/locales/text/fr.json | 1 - src/platform/locales/text/ko.json | 1 - src/platform/locales/text/pl.json | 1 - src/platform/locales/text/pt.json | 1 - src/platform/locales/text/ru.json | 1 - src/platform/locales/text/tr.json | 1 - src/platform/locales/text/zh-TW.json | 1 - src/platform/locales/text/zh.json | 10 +- src/platform/projectTrust.ts | 12 +- src/workbench/Workbench.test.tsx | 3 + src/workbench/contributions.ts | 2 + src/workbench/notificationStore.ts | 6 +- 23 files changed, 454 insertions(+), 97 deletions(-) diff --git a/docs/en/guide/remote/containers.mdx b/docs/en/guide/remote/containers.mdx index 71af278e83..a0de84e985 100644 --- a/docs/en/guide/remote/containers.mdx +++ b/docs/en/guide/remote/containers.mdx @@ -21,30 +21,28 @@ tool window. is bind-mounted into the container, so a daemon on another machine doesn't work. - The Dev Containers CLI (`devcontainer`). Install **Dev Containers CLI** from **Settings › Languages & Frameworks › Language Servers** (it needs Node.js), or put `devcontainer` on your `PATH`. -- A `.devcontainer/devcontainer.json` or `.devcontainer.json` in the project folder. +- A `.devcontainer/devcontainer.json`, `.devcontainer.json`, or `.devcontainer//devcontainer.json` in the project folder. - The project must be trusted: building the container runs the project's commands (`initializeCommand`, the Dockerfile build). - A Linux container on x86_64 or aarch64. -### Reopen a project in its container +### Open a project in its container - - Open the folder that contains the `devcontainer.json` and trust it. - - Choose **File › Reopen in Container**, then **This Window** or **New Window** if asked. - - - OpenIDEA runs `devcontainer up` for the folder, which builds or starts the container. The first build can take a - while. Then it installs and starts [`openidea-server`](/en/guide/remote/server) in the container and opens the - project folder there. - - +- From the Welcome screen, select **Remote Development › Dev Container** and choose the project folder. If the + folder has several configurations, select the one to use. Click **Open** and trust the folder if prompted. +- From a local project, use the **Reopen in Container** action in the editor banner for the configuration you want + to use. You can also choose **File › Reopen in Container** to use the default configuration. +- When you open a trusted local project with a dev container configuration, the IDE offers **Reopen in Container**. + Choose **Don't ask again** to hide the notification for that project. + +OpenIDEA runs `devcontainer up` to build or start the container, then installs and starts +[`openidea-server`](/en/guide/remote/server) inside it. The first build can take a while. The project then opens at the container's `remoteWorkspaceFolder`, as its `remoteUser`. The status bar shows **Dev Container: ``**, and the project appears in the recent projects list on the Welcome screen. -If something fails (no `devcontainer.json`, Docker not installed, the build failed), a notification -**Could not reopen the project in a container** shows the reason, including the end of the CLI's log. +The Welcome dialog shows connection errors inline. In a local project, **Reopen in Container** reports failures in +a notification. The message includes the end of the CLI's log when available. ### What applies from `devcontainer.json` @@ -75,8 +73,8 @@ Language servers and debuggers that OpenIDEA installs go into the container, und ### Limits -- Only the default configuration is used (`.devcontainer/devcontainer.json`, then `.devcontainer.json`). There is no - picker for several configurations in subfolders of `.devcontainer/`. +- **File › Reopen in Container** uses `.devcontainer/devcontainer.json`, then `.devcontainer.json`. To select a + configuration in a subfolder of `.devcontainer/`, use the Welcome screen or the editor banner. - **Reopen in Container** is available for local projects only, not from an SSH or WSL window. - There is no command to attach to an arbitrary running container; the container always comes from the project's `devcontainer.json`. diff --git a/docs/zh/guide/remote/containers.mdx b/docs/zh/guide/remote/containers.mdx index f74a6a6e8b..5062c1bc58 100644 --- a/docs/zh/guide/remote/containers.mdx +++ b/docs/zh/guide/remote/containers.mdx @@ -18,25 +18,24 @@ OpenIDEA 以两种方式使用容器: - 本机已安装 Docker,且当前 Docker 上下文的守护进程运行在本机。项目文件夹要绑定挂载进容器,所以其他机器上的守护进程不行。 - Dev Containers CLI(`devcontainer`)。可以在**设置 › 语言和框架 › 语言服务器**中安装 **Dev Containers CLI**(需要 Node.js), 也可以自己把 `devcontainer` 放到 `PATH` 中。 -- 项目文件夹中有 `.devcontainer/devcontainer.json` 或 `.devcontainer.json`。 +- 项目文件夹中有 `.devcontainer/devcontainer.json`、`.devcontainer.json` 或 `.devcontainer/<名称>/devcontainer.json`。 - 项目必须已受信任:构建容器会执行项目自带的命令(`initializeCommand`、Dockerfile 构建)。 - 容器为 x86_64 或 aarch64 上的 Linux。 -### 在容器中重新打开项目 +### 在容器中打开项目 - - 打开包含 `devcontainer.json` 的文件夹,并信任它。 - 选择**文件 › 在容器中重新打开**,如有提示再选择**当前窗口**或**新窗口**。 - - OpenIDEA 会对该文件夹运行 `devcontainer up` 来构建或启动容器,首次构建可能需要一段时间。随后在容器中安装并启动 - [`openidea-server`](/zh/guide/remote/server),再打开容器里的项目文件夹。 - - +- 在欢迎页中选择**远程开发 › 开发容器**,然后选择项目文件夹。如果该文件夹有多个配置,请选择要使用的配置。 + 点击**打开**,并在提示时信任该文件夹。 +- 在本地项目中,打开要使用的配置,然后点击编辑器横幅中的**在容器中重新打开**。也可以选择**文件 › 在容器中重新打开**以使用默认配置。 +- 打开含有开发容器配置的受信任本地项目时,IDE 会提示**在容器中重新打开**。选择**不再询问**可隐藏此项目的通知。 + +OpenIDEA 会运行 `devcontainer up` 来构建或启动容器,然后在其中安装并启动 +[`openidea-server`](/zh/guide/remote/server)。首次构建可能需要一段时间。 项目会以容器的 `remoteUser` 身份、在 `remoteWorkspaceFolder` 中打开。状态栏显示 **Dev Container: ``**, 该项目也会出现在欢迎页的最近项目列表中。 -如果失败(没有 `devcontainer.json`、未安装 Docker、构建出错等),会弹出**无法在容器中重新打开项目**通知,说明原因并附上 CLI 日志的末尾部分。 +欢迎页的对话框会直接显示连接错误。在本地项目中,**在容器中重新打开**操作会通过通知报告失败。如果有 CLI 日志,错误消息会附上日志末尾的内容。 ### `devcontainer.json` 中哪些内容生效 @@ -55,7 +54,8 @@ OpenIDEA 安装的语言服务器和调试器会装进容器,位于容器用 ### 限制 -- 只使用默认配置(先找 `.devcontainer/devcontainer.json`,再找 `.devcontainer.json`),不能在 `.devcontainer/` 子文件夹中的多个配置之间选择。 +- **文件 › 在容器中重新打开**优先使用 `.devcontainer/devcontainer.json`,其次使用 `.devcontainer.json`。 + 如需选择 `.devcontainer/` 子文件夹中的配置,请使用欢迎页或编辑器横幅。 - **在容器中重新打开**只适用于本地项目,在 SSH 或 WSL 窗口中不可用。 - 没有附加到任意运行中容器的命令;容器总是来自项目的 `devcontainer.json`。 diff --git a/src/features/project-trust/index.tsx b/src/features/project-trust/index.tsx index ba9bf2786e..a92882cda6 100644 --- a/src/features/project-trust/index.tsx +++ b/src/features/project-trust/index.tsx @@ -13,11 +13,13 @@ import styles from "./trust.module.css"; const usePrompt = create<{ path: string | null; scope: ProjectTrustScope; + requireTrust: boolean; folder: boolean; finish: ((open: boolean) => void) | null; }>(() => ({ path: null, scope: "current", + requireTrust: false, folder: false, finish: null, })); @@ -34,7 +36,7 @@ function PathLine({ path }: { path: string }) { } function TrustDialog() { - const { path, folder } = usePrompt(); + const { path, folder, requireTrust } = usePrompt(); return ( void executeAction("project.dontOpen")} buttons={[ - { - label: "Preview in Restricted Mode", - autoFocus: true, - onClick: () => void executeAction("project.previewRestricted"), - }, - { label: "Don't Open", role: "cancel" }, + ...(requireTrust + ? [] + : [ + { + label: "Preview in Restricted Mode", + autoFocus: true, + onClick: () => void executeAction("project.previewRestricted"), + }, + ]), + { label: "Don't Open", role: "cancel", autoFocus: requireTrust }, { label: folder ? "Trust Folder" : "Trust Project", role: "default", @@ -78,12 +84,14 @@ function TrustDialog() {

Loading, running or building a project may execute potentially malicious code from its build scripts.

-

- - If you don't trust the source, preview the project in Restricted Mode, where project commands and tools - can't run. - -

+ {!requireTrust && ( +

+ + If you don't trust the source, preview the project in Restricted Mode, where project commands and tools + can't run. + +

+ )}
); @@ -234,7 +242,7 @@ function TrustSettings() { async function decide(trusted: boolean) { const pending = usePrompt.getState(); const path = pending.path ?? useProject.getState().project?.root; - if (!path) return; + if (!path || (pending.requireTrust && !trusted)) return; const folder = trusted && pending.folder; if (pending.scope === "local") { await callDesktop("project_trust_set", { path, trusted, folder }); @@ -247,17 +255,19 @@ async function decide(trusted: boolean) { pending.finish?.(true); } -function promptForTrust(status: TrustStatus, scope: ProjectTrustScope): Promise { +function promptForTrust(status: TrustStatus, scope: ProjectTrustScope, requireTrust = false): Promise { usePrompt.getState().finish?.(false); const answer = new Promise((resolve) => usePrompt.setState({ path: status.root, scope, + requireTrust, folder: false, finish: (open) => { usePrompt.setState({ path: null, scope: "current", + requireTrust: false, finish: null, folder: false, }); @@ -283,10 +293,11 @@ async function trustProject() { export function activate(): () => void { initializeRemoteTrustMigration(); const disposers = [ - provideProjectTrustPrompt(async (path, scope) => { + provideProjectTrustPrompt(async (path, scope, requireTrust) => { const status = await (scope === "local" ? callDesktop("project_trust_status", { path }) : call(commands.projectTrustStatus(path))); + if (requireTrust) return status.trusted || promptForTrust(status, scope, true); if (scope === "current" && isRemoteRoot(path)) { // The server's answer covers what runs there; commands run here need this machine's own. const desktop = await call(commands.remoteTrustStatus()); diff --git a/src/features/remote-dev/ConnectDialog.test.tsx b/src/features/remote-dev/ConnectDialog.test.tsx index ecd73806a2..4c0fcad6d9 100644 --- a/src/features/remote-dev/ConnectDialog.test.tsx +++ b/src/features/remote-dev/ConnectDialog.test.tsx @@ -6,22 +6,31 @@ import { useRemoteProgress } from "@/platform/remote"; import { ConnectDialog, ConnectHost } from "./ConnectDialog"; import { closeConnectDialog, openConnectDialog, useConnectDialog } from "./model"; -const { list, distros, globalSettings, openRemote, executeAction } = vi.hoisted(() => ({ +const { list, distros, globalSettings, openRemote, executeAction, readDir, pickFolder } = vi.hoisted(() => ({ list: vi.fn(), distros: vi.fn(), globalSettings: vi.fn(), openRemote: vi.fn(), executeAction: vi.fn(), + readDir: vi.fn(), + pickFolder: vi.fn(), })); vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal(); return { ...real, - commands: { ...real.commands, remoteBootstrapList: list, wslDistros: distros, settingsGetGlobal: globalSettings }, + commands: { + ...real.commands, + remoteBootstrapList: list, + wslDistros: distros, + settingsGetGlobal: globalSettings, + fsReadDir: readDir, + }, }; }); vi.mock("@/workbench/projectWindow", () => ({ openRemoteProject: openRemote })); +vi.mock("@/platform/dialog", () => ({ open: pickFolder })); vi.mock("@/platform/actions", async (importOriginal) => ({ ...(await importOriginal()), executeAction, @@ -136,7 +145,44 @@ it("offers SSH configuration and disables Browse until one exists, then lists th it("hides the WSL choice when no distribution is installed", async () => { render(); await waitFor(() => expect(distros).toHaveBeenCalled()); - expect(screen.queryByRole("button", { name: "Connect through" })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Connect through" })); + expect(screen.queryByRole("option", { name: "WSL" })).toBeNull(); + expect(screen.getByRole("option", { name: "Dev Container" })).toBeVisible(); +}); + +it("hands off the selected local dev container configuration from the Welcome window", async () => { + const connect = vi.fn().mockResolvedValue(true); + pickFolder.mockResolvedValue("C:\\dev\\app"); + const listings: Record> = { + "C:/dev/app": [{ name: ".devcontainer", path: "C:/dev/app/.devcontainer", kind: "dir" }], + "C:/dev/app/.devcontainer": [ + { name: "devcontainer.json", path: "C:/dev/app/.devcontainer/devcontainer.json", kind: "file" }, + { name: "python", path: "C:/dev/app/.devcontainer/python", kind: "dir" }, + ], + "C:/dev/app/.devcontainer/python": [ + { name: "devcontainer.json", path: "C:/dev/app/.devcontainer/python/devcontainer.json", kind: "file" }, + ], + }; + readDir.mockImplementation(async (path: string) => ({ status: "ok", data: listings[path] ?? [] })); + + render( {}} />); + fireEvent.click(screen.getByRole("button", { name: "Connect through" })); + fireEvent.click(screen.getByRole("option", { name: "Dev Container" })); + expect(screen.getByRole("button", { name: "Open" })).toBeDisabled(); + fireEvent.change(screen.getByLabelText("Project directory:"), { target: { value: "/empty" } }); + await screen.findByText("No dev container configuration found in this folder."); + expect(screen.getByRole("button", { name: "Open" })).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "Browse" })); + fireEvent.click(await screen.findByRole("button", { name: "Dev container configuration" })); + fireEvent.click(screen.getByRole("option", { name: ".devcontainer/python/devcontainer.json" })); + fireEvent.click(screen.getByRole("button", { name: "Open" })); + await waitFor(() => + expect(connect).toHaveBeenCalledWith( + { kind: "devContainer", folder: "C:/dev/app", config: ".devcontainer/python/devcontainer.json" }, + "C:/dev/app", + ), + ); + expect(openRemote).not.toHaveBeenCalled(); }); it("opens a folder of the chosen WSL distribution, without browsing over SFTP", async () => { diff --git a/src/features/remote-dev/ConnectDialog.tsx b/src/features/remote-dev/ConnectDialog.tsx index 7d7971b7ee..8ec459af6a 100644 --- a/src/features/remote-dev/ConnectDialog.tsx +++ b/src/features/remote-dev/ConnectDialog.tsx @@ -1,17 +1,21 @@ /** - * Picks an SSH configuration and a folder on that host, then opens it in this or a new window. + * 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 { localGlobalSettings, useRemoteProgress } from "@/platform/remote"; +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, @@ -28,6 +32,7 @@ export function ConnectHost() { } 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 @@ -99,13 +104,18 @@ export function ConnectDialog({ const [distros, setDistros] = useState([]); 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(null); const [browse, setBrowse] = useState<{ dir: string; folders: RemoteEntry[] } | null>(null); useEffect(() => { let live = true; - // Detection is a convenience: any failure just leaves SSH as the only choice. + // Detection is a convenience: a failure leaves WSL unavailable. void call(commands.wslDistros()) .then((found) => { if (!live) return; @@ -119,9 +129,46 @@ export function ConnectDialog({ }, []); 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); @@ -141,8 +188,17 @@ export function ConnectDialog({ setError(null); setBusy(true); try { - const dir = path.trim() || "~"; - if (await (onConnect ? onConnect(target, dir) : openRemoteProject(target, dir))) onClose(); + 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)); @@ -157,7 +213,7 @@ export function ConnectDialog({ label: c.name.trim() || sshLabel(c), detail: sshLabel(c), })); - const ready = !!name && !busy && !!path.trim(); + const ready = !busy && (container ? Boolean(config) : Boolean(name && path.trim())); const connecting = useRemoteProgress((s) => s.progress !== null); const configure = () => @@ -187,26 +243,30 @@ export function ConnectDialog({ }} >

- {tx("The project runs on the remote host; the IDE backend is installed there on first use.")} + {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.")}

- {distros.length > 0 && ( + {(distros.length > 0 || canUseContainer) && ( <> setPath(e.target.value)} + 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 && ( - )} + {container && containerConfigs.length > 1 && ( + <> + +