diff --git a/crates/ide-docker/src/lib.rs b/crates/ide-docker/src/lib.rs index 84f3e59067..bc7f8b27cd 100644 --- a/crates/ide-docker/src/lib.rs +++ b/crates/ide-docker/src/lib.rs @@ -27,18 +27,24 @@ const QUICK: Duration = Duration::from_secs(20); /// Stop / restart wait for the container's grace period (10 s by default). const LIFECYCLE: Duration = Duration::from_secs(90); -/// Locates the docker executable once per process. GUI apps on macOS start with a -/// minimal `PATH`, so the usual install locations are probed after the lookup. +/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so +/// the login/reloaded `PATH` and usual install locations are probed after the lookup. +/// Only a found path is cached, so installing Docker while the backend runs is picked up. pub fn docker_executable() -> Option { - static DOCKER: OnceLock> = OnceLock::new(); - DOCKER - .get_or_init(|| { - if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) { - return Some(explicit); - } - if let Ok(found) = which::which("docker") { - return Some(found); - } + if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) { + return Some(explicit); + } + static DOCKER: OnceLock = OnceLock::new(); + if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) { + return Some(cached.clone()); + } + let found = which::which("docker") + .ok() + .or_else(|| { + let path = ide_core::process::host_var_os("PATH")?; + which::which_in("docker", Some(path), ".").ok() + }) + .or_else(|| { let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from); let mut candidates: Vec = if cfg!(windows) { vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")] @@ -60,8 +66,11 @@ pub fn docker_executable() -> Option { candidates.push(home.join(".docker/bin/docker")); } candidates.into_iter().find(|p| p.is_file()) - }) - .clone() + }); + if let Some(ref path) = found { + let _ = DOCKER.set(path.clone()); + } + found } /// Environment for docker command lines a run configuration launches: the endpoint's diff --git a/crates/ide-host/src/ops/docker.rs b/crates/ide-host/src/ops/docker.rs index 58bef2029e..7bb60819b2 100644 --- a/crates/ide-host/src/ops/docker.rs +++ b/crates/ide-host/src/ops/docker.rs @@ -1,9 +1,14 @@ -//! Docker run configurations: the environment their `docker` command line runs with; and Docker -//! connections through an SSH configuration, tunnelled with the IDE's own SSH client. +//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the +//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections +//! tunnelled through the host's own SSH client. +use super::Channel; use crate::Host; use ide_command::command; -use ide_core::{IdeError, IdeResult}; -use ide_docker::DockerEndpoint; +use ide_core::{CancellationToken, IdeError, IdeResult, RequestId}; +use ide_docker::{ + ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine, + DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth, +}; use ide_ssh::Tunnel; use std::collections::{BTreeMap, HashMap}; @@ -54,6 +59,242 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) { host.ssh.release(id); } +/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers. +async fn cancellable( + host: &Host, + request: RequestId, + f: impl FnOnce(&CancellationToken) -> IdeResult + Send + 'static, +) -> IdeResult { + let cancel = host.begin_request(request); + let result = host.blocking(move || f(&cancel)).await; + host.end_request(request); + result +} + +/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection +/// (Services › Disconnect); other endpoints keep nothing open. +#[command(trust = always)] +pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> { + disconnect(host, &endpoint).await; + Ok(()) +} + +/// Availability plus containers, images, volumes and networks. +#[command(trust = trusted)] +pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await +} + +#[command(trust = trusted)] +pub async fn docker_container_op( + host: &Host, + endpoint: DockerEndpoint, + ids: Vec, + op: ContainerOp, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await +} + +#[command(trust = trusted)] +pub async fn docker_remove( + host: &Host, + endpoint: DockerEndpoint, + object: DockerObject, + ids: Vec, + force: bool, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await +} + +/// Pretty-printed `docker inspect` JSON. +#[command(trust = trusted)] +pub async fn docker_inspect( + host: &Host, + endpoint: DockerEndpoint, + object: DockerObject, + id: String, +) -> IdeResult { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await +} + +/// Layers of an image (`docker image history`). +#[command(trust = trusted)] +pub async fn docker_image_history( + host: &Host, + endpoint: DockerEndpoint, + id: String, +) -> IdeResult> { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || ide_docker::image_history(&endpoint, &id)).await +} + +/// Processes running inside a container (`docker top`). +#[command(trust = trusted)] +pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || ide_docker::container_top(&endpoint, &id)).await +} + +/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`). +#[command(trust = trusted)] +pub async fn docker_container_stats( + host: &Host, + endpoint: DockerEndpoint, + id: String, +) -> IdeResult { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await +} + +/// Disk usage per volume name (`docker system df -v`). +#[command(trust = trusted)] +pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult> { + let endpoint = resolve(host, endpoint).await?; + host.blocking(move || ide_docker::volume_sizes(&endpoint)).await +} + +/// Streams a container's log lines, in batches, until it stops or the request is cancelled. +#[command(trust = trusted)] +#[allow(clippy::too_many_arguments)] +pub async fn docker_logs( + host: &Host, + request: RequestId, + endpoint: DockerEndpoint, + id: String, + tail: u32, + follow: bool, + timestamps: bool, + on_lines: Channel>, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + cancellable(host, request, move |cancel| { + ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| { + let _ = on_lines.send(lines); + }) + }) + .await +} + +/// Follows `docker events` until the daemon goes away or the request is cancelled. +#[command(trust = trusted)] +pub async fn docker_events( + host: &Host, + request: RequestId, + endpoint: DockerEndpoint, + on_event: Channel, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + cancellable(host, request, move |cancel| { + ide_docker::watch_events(&endpoint, cancel, &|e| { + let _ = on_event.send(e); + }) + }) + .await +} + +/// `docker pull`, logging in first when a saved registry with a password serves the image. +#[command(trust = trusted)] +pub async fn docker_pull( + host: &Host, + request: RequestId, + endpoint: DockerEndpoint, + reference: String, + on_output: Channel, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + let data_dir = host.data_dir.clone(); + cancellable(host, request, move |cancel| { + let auth = ide_docker::auth_for(&data_dir, &reference); + ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| { + let _ = on_output.send(line); + }) + }) + .await +} + +#[command(trust = trusted)] +pub async fn docker_prune( + host: &Host, + request: RequestId, + endpoint: DockerEndpoint, + target: PruneTarget, + on_output: Channel, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + cancellable(host, request, move |cancel| { + ide_docker::prune(&endpoint, target, cancel, &|line| { + let _ = on_output.send(line); + }) + }) + .await +} + +/// `docker compose` start / stop / restart / down of a project found through labels. +#[command(trust = trusted)] +#[allow(clippy::too_many_arguments)] +pub async fn docker_compose_op( + host: &Host, + request: RequestId, + endpoint: DockerEndpoint, + project: String, + files: Vec, + working_dir: Option, + op: ComposeOp, + on_output: Channel, +) -> IdeResult<()> { + let endpoint = resolve(host, endpoint).await?; + cancellable(host, request, move |cancel| { + ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| { + let _ = on_output.send(line); + }) + }) + .await +} + +/// Docker connections and registries of the project host. +#[command(trust = always)] +pub async fn docker_settings(host: &Host) -> IdeResult { + let data_dir = host.data_dir.clone(); + host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await +} + +#[command(trust = always)] +pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> { + let data_dir = host.data_dir.clone(); + host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await +} + +/// Saves (`None`: forgets) a registry's password. +#[command(trust = always)] +pub async fn docker_set_registry_password(host: &Host, id: String, password: Option) -> IdeResult<()> { + let data_dir = host.data_dir.clone(); + host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await +} + +/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon. +#[command(trust = trusted)] +pub async fn docker_registry_login( + host: &Host, + endpoint: DockerEndpoint, + registry: DockerRegistry, + password: Option, +) -> IdeResult { + let endpoint = resolve(host, endpoint).await?; + let data_dir = host.data_dir.clone(); + host.blocking(move || { + let password = password + .or_else(|| ide_docker::registry_password(&data_dir, ®istry.id)) + .ok_or_else(|| IdeError::invalid("enter the registry password"))?; + let auth = RegistryAuth { address: registry.address, username: registry.username, password }; + ide_docker::login(&endpoint, &auth) + }) + .await +} + /// Environment for a Docker run configuration's command line: selects `endpoint`'s /// daemon and puts the docker executable on `PATH`. #[command(trust = always)] @@ -64,4 +305,25 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult< host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await } -ide_command::domain!(docker: docker_run_env); +ide_command::domain!( + docker: + docker_compose_op, + docker_container_op, + docker_container_stats, + docker_container_top, + docker_disconnect, + docker_events, + docker_image_history, + docker_inspect, + docker_logs, + docker_prune, + docker_pull, + docker_registry_login, + docker_remove, + docker_run_env, + docker_save_settings, + docker_set_registry_password, + docker_settings, + docker_snapshot, + docker_volume_sizes, +); diff --git a/crates/ide-host/tests/rpc.rs b/crates/ide-host/tests/rpc.rs index 8eda9f6ad8..0427f440de 100644 --- a/crates/ide-host/tests/rpc.rs +++ b/crates/ide-host/tests/rpc.rs @@ -271,6 +271,9 @@ async fn serves_projects_files_documents_search_and_runs() { .await .unwrap(); assert_eq!(env["DOCKER_HOST"], "unix:///run/user/1/docker.sock"); + // Services › Docker commands are served by the project host too. + assert!(Dispatcher::standard().commands().contains(&"docker_snapshot")); + assert_eq!(invoke(&peer, "docker_settings", json!({})).await.unwrap()["connections"], json!([])); // Real project-host ignore writes travel through the remote command dispatcher. assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore")); diff --git a/docs/en/guide/services.mdx b/docs/en/guide/services.mdx index e6cef4910a..f534dcef4d 100644 --- a/docs/en/guide/services.mdx +++ b/docs/en/guide/services.mdx @@ -38,7 +38,7 @@ With nothing configured, Services lists no Docker connection. To add one (the fi | **Name:** | Shown in the tree. | | **Connect to Docker daemon with:** | **Docker CLI default (DOCKER_HOST / current context)**, **Unix socket** (a socket path or an Engine API URL such as `npipe://`), **TCP / SSH host** (`tcp://host:2376` or `ssh://user@host`, with an optional TLS certificates folder holding `ca.pem`, `cert.pem` and `key.pem`), or **Docker context** (a context name such as `desktop-linux`, `orbstack` or `colima`). | -Right-click a connection for **Edit Connection…** and **Remove Connection**. Connections are app-wide, not per project. The tree updates live from `docker events`; when the daemon is not running, Services retries every 10 seconds. +Right-click a connection for **Edit Connection…** and **Remove Connection**. Connections are stored per host, not per project: a remote window keeps its connections on the remote host and talks to that host's Docker daemon. The tree updates live from `docker events`; when the daemon is not running, Services retries every 10 seconds. ### Registries diff --git a/docs/zh/guide/services.mdx b/docs/zh/guide/services.mdx index 5691a4df68..3cd61fb5e7 100644 --- a/docs/zh/guide/services.mdx +++ b/docs/zh/guide/services.mdx @@ -38,7 +38,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的 | **名称:** | 树中显示的名称。 | | **连接 Docker 守护进程的方式:** | **Docker CLI 默认值(DOCKER_HOST/当前上下文)**;**Unix 套接字**(套接字路径,或 `npipe://` 这类 Engine API URL);**TCP/SSH 主机**(`tcp://host:2376` 或 `ssh://user@host`,可选一个包含 `ca.pem`、`cert.pem`、`key.pem` 的 TLS 证书文件夹);**Docker 上下文**(上下文名称,例如 `desktop-linux`、`orbstack`、`colima`)。 | -右键连接可以 **编辑连接…** 或 **移除连接**。连接是全局的,不属于某个项目。树通过 `docker events` 实时更新;守护进程未运行时,每 10 秒重试一次。 +右键连接可以 **编辑连接…** 或 **移除连接**。连接按运行主机保存(不属于某个项目):远程窗口将连接保存在远端主机上,并连接该主机的 Docker 守护进程。树通过 `docker events` 实时更新;守护进程未运行时,每 10 秒重试一次。 ### 镜像注册表 diff --git a/e2e/services.spec.ts b/e2e/services.spec.ts index c13aa5587b..cbc13b9194 100644 --- a/e2e/services.spec.ts +++ b/e2e/services.spec.ts @@ -912,3 +912,179 @@ test("Docker volume, Compose, and container dashboards show volume disk usage", await expect(detail.getByText("Volume & Bind Mounts")).toBeVisible(); await expect(detail).toContainText("380.2kB"); }); + +test("Services Docker routes to the remote host daemon and switches back on disconnect", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(async () => { + const localSnapshot = { + availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "desktop-linux" }, + executable: "/Applications/Docker.app/Contents/Resources/bin/docker", + containers: [ + { + id: "local-1", + name: "local-dev-nginx", + image: "nginx:alpine", + command: "nginx -g 'daemon off;'", + state: "running", + status: "Up 3 hours", + ports: "8080->80/tcp", + createdAt: "2026-11-26T20:00:00Z", + composeProject: null, + composeService: null, + composeWorkingDir: null, + composeFiles: [], + mounts: [], + networks: ["bridge"], + }, + ], + images: [], + volumes: [], + networks: [], + errors: [], + }; + + const remoteContainers = [ + { + id: "ec397677d395", + name: "selfhost-runner-github-runner-1", + image: "myoung34/github-runner:2.338.2-ubuntu-noble", + command: '"/bin/bash -ec \'mkdir…"', + state: "running", + status: "Up 7 minutes", + ports: "", + createdAt: "2026-11-26T20:40:00Z", + composeProject: "selfhost-runner", + composeService: "github-runner-1", + composeWorkingDir: "/home/deng/selfhost-runner", + composeFiles: ["/home/deng/selfhost-runner/docker-compose.yml"], + mounts: [], + networks: ["selfhost_default"], + }, + { + id: "4d7591278f60", + name: "selfhost-runner-github-runner-2", + image: "myoung34/github-runner:2.338.2-ubuntu-noble", + command: '"/bin/bash -ec \'mkdir…"', + state: "running", + status: "Up 7 minutes", + ports: "", + createdAt: "2026-11-26T20:40:00Z", + composeProject: "selfhost-runner", + composeService: "github-runner-2", + composeWorkingDir: "/home/deng/selfhost-runner", + composeFiles: ["/home/deng/selfhost-runner/docker-compose.yml"], + mounts: [], + networks: ["selfhost_default"], + }, + ]; + + (window as unknown as { __emitRemoteDockerEvent?: () => void }).__emitRemoteDockerEvent = undefined; + + window.__ipc.handlers.docker_settings = () => ({ + connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], + registries: [], + }); + window.__ipc.handlers.docker_snapshot = () => localSnapshot; + window.__ipc.handlers.docker_events = () => new Promise(() => {}); + window.__ipc.handlers.cancel_request = () => null; + + window.__ipc.handlers.remote_invoke = ({ cmd, args, onChannel }) => { + const parsed = JSON.parse(String(args ?? "{}")) as Record; + if (cmd === "docker_settings") { + return JSON.stringify({ + connections: [{ id: "remote", name: "Docker", endpoint: { kind: "default" } }], + registries: [], + }); + } + if (cmd === "docker_snapshot") { + return JSON.stringify({ + availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: "default" }, + executable: "/usr/bin/docker", + containers: [...remoteContainers], + images: [], + volumes: [], + networks: [], + errors: [], + }); + } + if (cmd === "docker_events") { + const eventChannelId = (parsed.onEvent as { $channel: number }).$channel; + (window as unknown as { __emitRemoteDockerEvent?: () => void }).__emitRemoteDockerEvent = () => { + remoteContainers.push({ + ...remoteContainers[0]!, + id: "256e85609198", + name: "selfhost-runner-github-runner-3", + composeService: "github-runner-3", + }); + window.__ipc.send(onChannel, { + id: eventChannelId, + data: JSON.stringify({ kind: "container", action: "start", id: "256e85609198" }), + }); + }; + return new Promise(() => {}); + } + if (cmd === "cancel_request") return JSON.stringify(null); + throw { kind: "unavailable", message: `remote ${String(cmd)} is not stubbed`, detail: null }; + }; + + const storeMod = "/src/features/services/store.ts"; + const { loadSettings, useServices } = await import(/* @vite-ignore */ storeMod); + useServices.setState({ settings: null, conns: {} }); + await loadSettings(); + }); + + // 1. Local window initially shows the local desktop-linux Docker daemon and its container. + await page.keyboard.press("Meta+8"); + const services = page.getByRole("region", { name: "Services", exact: true }); + const tree = services.getByRole("tree", { name: "Services", exact: true }); + await expect(tree.getByRole("treeitem", { name: /desktop-linux/ })).toBeVisible(); + await tree.getByRole("treeitem", { name: /^Containers\b/ }).click(); + await page.keyboard.press("ArrowRight"); + await expect(tree.getByRole("treeitem", { name: /local-dev-nginx/ })).toBeVisible(); + + // 2. Attaching the window to SSH host deng@deng-thinkpad.local switches Services to remote Docker. + await page.evaluate(async () => { + const remoteMod = "/src/platform/remote.ts"; + const projectMod = "/src/platform/project.ts"; + const { enableRemote } = await import(/* @vite-ignore */ remoteMod); + const { useProject } = await import(/* @vite-ignore */ projectMod); + enableRemote({ + target: { kind: "ssh", config: "thinkpad" }, + root: useProject.getState().project.root, + host: "deng@deng-thinkpad.local", + os: "linux", + commands: ["docker_settings", "docker_snapshot", "docker_events", "cancel_request"], + }); + }); + + await expect(page.getByRole("button", { name: "SSH: deng@deng-thinkpad.local" })).toBeVisible(); + await expect(tree.getByRole("treeitem", { name: /desktop-linux/ })).toHaveCount(0); + const composeNode = tree.getByRole("treeitem", { name: /Docker-compose: selfhost-runner/ }); + await expect(composeNode).toBeVisible(); + await composeNode.click(); + await page.keyboard.press("ArrowRight"); + await expect(tree.getByRole("treeitem", { name: /github-runner-1/ })).toBeVisible(); + await expect(tree.getByRole("treeitem", { name: /github-runner-2/ })).toBeVisible(); + + const remoteCmds = (await ipcCalls(page, "remote_invoke")).map((c) => c.cmd); + expect(remoteCmds).toContain("docker_settings"); + expect(remoteCmds).toContain("docker_snapshot"); + expect(remoteCmds).toContain("docker_events"); + + // 3. Live docker_events streamed from the remote daemon update the Services tree in place. + await page.evaluate(() => { + (window as unknown as { __emitRemoteDockerEvent?: () => void }).__emitRemoteDockerEvent?.(); + }); + await expect(tree.getByRole("treeitem", { name: /github-runner-3/ })).toBeVisible(); + + // 4. Disconnecting from the remote host restores the local Docker connection. + await page.evaluate(async () => { + const remoteMod = "/src/platform/remote.ts"; + const { disableRemote } = await import(/* @vite-ignore */ remoteMod); + disableRemote(); + }); + await expect(tree.getByRole("treeitem", { name: /desktop-linux/ })).toBeVisible(); + await expect(tree.getByRole("treeitem", { name: /selfhost-runner/ })).toHaveCount(0); +}); diff --git a/src-tauri/src/commands/docker.rs b/src-tauri/src/commands/docker.rs deleted file mode 100644 index 55a60347b0..0000000000 --- a/src-tauri/src/commands/docker.rs +++ /dev/null @@ -1,324 +0,0 @@ -//! Services tool window › Docker (`ide-docker`). - -use crate::state::AppState; -use ide_command::desktop_command; -use ide_core::{IdeError, IdeResult, RequestId}; -use ide_docker::{ - ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine, - DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth, -}; -use tauri::State; -use tauri::ipc::Channel; - -async fn blocking(f: impl FnOnce() -> IdeResult + Send + 'static) -> IdeResult { - tauri::async_runtime::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))? -} - -/// `endpoint` with an SSH configuration's tunnel opened (see [`ide_host::ops::docker::resolve`]). -async fn resolve(state: &AppState, endpoint: DockerEndpoint) -> IdeResult { - ide_host::ops::docker::resolve(&state.host, endpoint).await -} - -/// Runs a cancellable docker command (`request` → `cancel_request`) off the command threads. -async fn cancellable( - state: &AppState, - request: RequestId, - f: impl FnOnce(&ide_core::CancellationToken) -> IdeResult + Send + 'static, -) -> IdeResult { - let cancel = state.begin_request(request); - let result = blocking(move || f(&cancel)).await; - state.end_request(request); - result -} - -/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection -/// (Services › Disconnect); other endpoints keep nothing open. -#[desktop_command(trust = always)] -#[tauri::command] -#[specta::specta] -pub async fn docker_disconnect(state: State<'_, AppState>, endpoint: DockerEndpoint) -> IdeResult<()> { - ide_host::ops::docker::disconnect(&state.host, &endpoint).await; - Ok(()) -} - -/// Availability plus containers, images, volumes and networks. -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_snapshot(state: State<'_, AppState>, endpoint: DockerEndpoint) -> IdeResult { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || Ok(ide_docker::snapshot(&endpoint))).await -} - -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_container_op( - state: State<'_, AppState>, - endpoint: DockerEndpoint, - ids: Vec, - op: ContainerOp, -) -> IdeResult<()> { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await -} - -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_remove( - state: State<'_, AppState>, - endpoint: DockerEndpoint, - object: DockerObject, - ids: Vec, - force: bool, -) -> IdeResult<()> { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await -} - -/// Pretty-printed `docker inspect` JSON. -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_inspect( - state: State<'_, AppState>, - endpoint: DockerEndpoint, - object: DockerObject, - id: String, -) -> IdeResult { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || ide_docker::inspect(&endpoint, object, &id)).await -} - -/// Layers of an image (`docker image history`). -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_image_history( - state: State<'_, AppState>, - endpoint: DockerEndpoint, - id: String, -) -> IdeResult> { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || ide_docker::image_history(&endpoint, &id)).await -} - -/// Processes running inside a container (`docker top`). -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_container_top( - state: State<'_, AppState>, - endpoint: DockerEndpoint, - id: String, -) -> IdeResult { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || ide_docker::container_top(&endpoint, &id)).await -} - -/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`). -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_container_stats( - state: State<'_, AppState>, - endpoint: DockerEndpoint, - id: String, -) -> IdeResult { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || ide_docker::container_stats(&endpoint, &id)).await -} - -/// Disk usage per volume name (`docker system df -v`). -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_volume_sizes( - state: State<'_, AppState>, - endpoint: DockerEndpoint, -) -> IdeResult> { - let endpoint = resolve(&state, endpoint).await?; - blocking(move || ide_docker::volume_sizes(&endpoint)).await -} - -/// Streams a container's log lines, in batches, until it stops or the request is cancelled. -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -#[allow(clippy::too_many_arguments)] -pub async fn docker_logs( - state: State<'_, AppState>, - request: RequestId, - endpoint: DockerEndpoint, - id: String, - tail: u32, - follow: bool, - timestamps: bool, - on_lines: Channel>, -) -> IdeResult<()> { - let endpoint = resolve(&state, endpoint).await?; - cancellable(&state, request, move |cancel| { - ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| { - let _ = on_lines.send(lines); - }) - }) - .await -} - -/// Follows `docker events` until the daemon goes away or the request is cancelled. -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_events( - state: State<'_, AppState>, - request: RequestId, - endpoint: DockerEndpoint, - on_event: Channel, -) -> IdeResult<()> { - let endpoint = resolve(&state, endpoint).await?; - cancellable(&state, request, move |cancel| { - ide_docker::watch_events(&endpoint, cancel, &|e| { - let _ = on_event.send(e); - }) - }) - .await -} - -/// `docker pull`, logging in first when a saved registry with a password serves the image. -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_pull( - state: State<'_, AppState>, - request: RequestId, - endpoint: DockerEndpoint, - reference: String, - on_output: Channel, -) -> IdeResult<()> { - let endpoint = resolve(&state, endpoint).await?; - let data_dir = state.data_dir.clone(); - cancellable(&state, request, move |cancel| { - let auth = ide_docker::auth_for(&data_dir, &reference); - ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| { - let _ = on_output.send(line); - }) - }) - .await -} - -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_prune( - state: State<'_, AppState>, - request: RequestId, - endpoint: DockerEndpoint, - target: PruneTarget, - on_output: Channel, -) -> IdeResult<()> { - let endpoint = resolve(&state, endpoint).await?; - cancellable(&state, request, move |cancel| { - ide_docker::prune(&endpoint, target, cancel, &|line| { - let _ = on_output.send(line); - }) - }) - .await -} - -/// `docker compose` start / stop / restart / down of a project found through labels. -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -#[allow(clippy::too_many_arguments)] -pub async fn docker_compose_op( - state: State<'_, AppState>, - request: RequestId, - endpoint: DockerEndpoint, - project: String, - files: Vec, - working_dir: Option, - op: ComposeOp, - on_output: Channel, -) -> IdeResult<()> { - let endpoint = resolve(&state, endpoint).await?; - cancellable(&state, request, move |cancel| { - ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| { - let _ = on_output.send(line); - }) - }) - .await -} - -/// Docker connections and registries (app-wide). -#[desktop_command(trust = always)] -#[tauri::command] -#[specta::specta] -pub async fn docker_settings(state: State<'_, AppState>) -> IdeResult { - let data_dir = state.data_dir.clone(); - blocking(move || Ok(ide_docker::load_settings(&data_dir))).await -} - -#[desktop_command(trust = always)] -#[tauri::command] -#[specta::specta] -pub async fn docker_save_settings(state: State<'_, AppState>, settings: DockerSettings) -> IdeResult<()> { - let data_dir = state.data_dir.clone(); - blocking(move || ide_docker::save_settings(&data_dir, &settings)).await -} - -/// Saves (`None`: forgets) a registry's password. -#[desktop_command(trust = always)] -#[tauri::command] -#[specta::specta] -pub async fn docker_set_registry_password( - state: State<'_, AppState>, - id: String, - password: Option, -) -> IdeResult<()> { - let data_dir = state.data_dir.clone(); - blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await -} - -/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon. -#[desktop_command(trust = trusted)] -#[tauri::command] -#[specta::specta] -pub async fn docker_registry_login( - state: State<'_, AppState>, - endpoint: DockerEndpoint, - registry: DockerRegistry, - password: Option, -) -> IdeResult { - let endpoint = resolve(&state, endpoint).await?; - let data_dir = state.data_dir.clone(); - blocking(move || { - let password = password - .or_else(|| ide_docker::registry_password(&data_dir, ®istry.id)) - .ok_or_else(|| IdeError::invalid("enter the registry password"))?; - let auth = RegistryAuth { address: registry.address, username: registry.username, password }; - ide_docker::login(&endpoint, &auth) - }) - .await -} - -ide_command::desktop_domain!( - docker_compose_op, - docker_container_op, - docker_container_stats, - docker_container_top, - docker_disconnect, - docker_events, - docker_image_history, - docker_inspect, - docker_logs, - docker_prune, - docker_pull, - docker_registry_login, - docker_remove, - docker_save_settings, - docker_set_registry_password, - docker_settings, - docker_snapshot, - docker_volume_sizes, -); diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 53b22769e1..2726d2f951 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -15,7 +15,6 @@ pub mod clipboard; pub mod db; pub mod debug; pub mod doc; -pub mod docker; pub mod file_dialog; pub mod fonts; pub mod fs; @@ -198,7 +197,6 @@ fn catalogue() -> (tauri_specta::Commands, Vec) { desktop clipboard; desktop db; desktop debug; - desktop docker; desktop file_dialog; desktop fonts; desktop fs; diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 5a54f0464b..808c737bac 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -1251,6 +1251,7 @@ pub async fn remote_invoke( c.channels.lock().insert(own, (on_channel.clone(), id)); if (batch_execution && name == "onProgress") || (cmd == "vcs_watch_commit_messages" && name == "onMessages") + || cmd.starts_with("docker_") { finite_channel = Some(own); } diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index d6973b0529..614b9dba37 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -255,25 +255,25 @@ doc_set_encoding always project_host bin doc_set_line_ending always project_host bindings async doc_snapshot always project_host bindings async doc_sync_from_disk always project_host bindings async -docker_compose_op trusted desktop bindings async -docker_container_op trusted desktop bindings async -docker_container_stats trusted desktop bindings async -docker_container_top trusted desktop bindings async -docker_disconnect always desktop bindings async -docker_events trusted desktop bindings async -docker_image_history trusted desktop bindings async -docker_inspect trusted desktop bindings async -docker_logs trusted desktop bindings async -docker_prune trusted desktop bindings async -docker_pull trusted desktop bindings async -docker_registry_login trusted desktop bindings async -docker_remove trusted desktop bindings async +docker_compose_op trusted project_host bindings async +docker_container_op trusted project_host bindings async +docker_container_stats trusted project_host bindings async +docker_container_top trusted project_host bindings async +docker_disconnect always project_host bindings async +docker_events trusted project_host bindings async +docker_image_history trusted project_host bindings async +docker_inspect trusted project_host bindings async +docker_logs trusted project_host bindings async +docker_prune trusted project_host bindings async +docker_pull trusted project_host bindings async +docker_registry_login trusted project_host bindings async +docker_remove trusted project_host bindings async docker_run_env always project_host bindings async -docker_save_settings always desktop bindings async -docker_set_registry_password always desktop bindings async -docker_settings always desktop bindings async -docker_snapshot trusted desktop bindings async -docker_volume_sizes trusted desktop bindings async +docker_save_settings always project_host bindings async +docker_set_registry_password always project_host bindings async +docker_settings always project_host bindings async +docker_snapshot trusted project_host bindings async +docker_volume_sizes trusted project_host bindings async end_process trusted desktop bindings async env_reload always project_host bindings async file_dialog_needs_gtk trusted desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 3110ee6563..fde50d434c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -684,7 +684,7 @@ export const commands = { dockerSaveSettings: (settings: DockerSettings) => typedError(__TAURI_INVOKE("docker_save_settings", { settings })), /** Saves (`None`: forgets) a registry's password. */ dockerSetRegistryPassword: (id: string, password: string | null) => typedError(__TAURI_INVOKE("docker_set_registry_password", { id, password })), - /** Docker connections and registries (app-wide). */ + /** Docker connections and registries of the project host. */ dockerSettings: () => typedError(__TAURI_INVOKE("docker_settings")), /** Availability plus containers, images, volumes and networks. */ dockerSnapshot: (endpoint: DockerEndpoint) => typedError(__TAURI_INVOKE("docker_snapshot", { endpoint })), diff --git a/src/features/services/connectionState.test.ts b/src/features/services/connectionState.test.ts index 6b1e628913..dc744234ae 100644 --- a/src/features/services/connectionState.test.ts +++ b/src/features/services/connectionState.test.ts @@ -21,6 +21,8 @@ vi.mock("@/platform/ipc", async (original) => ({ dockerDisconnect: backend.disconnect, }, })); +import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; import { connectConnection, connectionState, @@ -195,4 +197,64 @@ describe("Docker connections", () => { expect(backend.snapshot).toHaveBeenCalledOnce(); }); }); + + describe("remote session switching", () => { + it("reloads the remote host's connections and drops in-flight local snapshots", async () => { + const stop = watch(); + try { + await vi.waitFor(() => expect(connectionState("box").snapshot).toEqual(ready)); + + let resolveStale!: (v: unknown) => void; + backend.snapshot.mockReturnValueOnce(new Promise((r) => (resolveStale = r))); + const staleRefresh = refresh("box"); + + const remoteSnap = { availability: { kind: "ready", context: "default" }, errors: [] }; + backend.settings.mockResolvedValueOnce( + ok({ + connections: [{ id: "remote", name: "Docker", endpoint: { kind: "default" } }], + registries: [], + }), + ); + backend.snapshot.mockResolvedValueOnce(ok(remoteSnap)); + + useRemote.setState({ + session: { + target: { kind: "ssh", config: "thinkpad" }, + root: "/home/deng/proj", + host: "deng@deng-thinkpad.local", + os: "linux", + commands: ["docker_settings", "docker_snapshot", "docker_events"], + }, + }); + + await vi.waitFor(() => expect(connectionState("remote").snapshot).toEqual(remoteSnap)); + expect(useServices.getState().settings?.connections.map((c) => c.id)).toEqual(["remote"]); + expect(backend.cancel).toHaveBeenCalledOnce(); + + // Completing the stale local snapshot must not leak back into the remote view. + resolveStale(ok(ready)); + await staleRefresh; + expect(useServices.getState().conns.box).toBeUndefined(); + } finally { + stop(); + useRemote.setState({ session: null }); + } + }); + + it("refreshes immediately when a Restricted Mode project becomes trusted", async () => { + useProject.setState({ project: { root: "/remote", name: "p", isGit: false, trusted: false } as never }); + backend.snapshot.mockRejectedValueOnce(new Error("Project is in Restricted Mode")); + + const stop = watch(); + try { + await vi.waitFor(() => expect(connectionState("box").error).toContain("Restricted Mode")); + backend.snapshot.mockResolvedValueOnce(ok(ready)); + useProject.setState({ project: { root: "/remote", name: "p", isGit: false, trusted: true } as never }); + await vi.waitFor(() => expect(connectionState("box").snapshot).toEqual(ready)); + } finally { + stop(); + useProject.setState({ project: null }); + } + }); + }); }); diff --git a/src/features/services/store.ts b/src/features/services/store.ts index 8dd919740c..858a298168 100644 --- a/src/features/services/store.ts +++ b/src/features/services/store.ts @@ -21,6 +21,8 @@ import type { } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; import { notifications } from "@/workbench/contributions"; import { DEFAULT_DOCKER_FILTERS, type DockerFilters } from "./model"; @@ -120,6 +122,7 @@ function patchConn(id: string, patch: Partial) { // --------------------------------------------------------------------------- // Settings +let sessionEpoch = 0; let settingsLoad: Promise | null = null; export function loadSettings(): Promise { @@ -127,8 +130,10 @@ export function loadSettings(): Promise { useServices.setState({ settings: { connections: [], registries: [] } }); return Promise.resolve(); } + const epoch = sessionEpoch; settingsLoad ??= call(commands.dockerSettings()) .then((s: DockerSettings) => { + if (epoch !== sessionEpoch) return; const connections = s.connections ?? []; useServices.setState((state) => ({ settings: { connections, registries: s.registries ?? [] }, @@ -141,6 +146,7 @@ export function loadSettings(): Promise { })); }) .catch((e) => { + if (epoch !== sessionEpoch) return; settingsLoad = null; notifications().notify({ group: "run", @@ -155,22 +161,26 @@ export function loadSettings(): Promise { let settingsWrite = Promise.resolve(true); function saveSettings(update: (current: Settings) => Settings): Promise { + const epoch = sessionEpoch; // Each write replaces the settings file, so derive it after the previous save. settingsWrite = settingsWrite.then(async () => { + if (epoch !== sessionEpoch) return false; try { const current = useServices.getState().settings ?? { connections: [], registries: [] }; const settings = update(current); if (settings === current) return true; if (isTauri()) await call(commands.dockerSaveSettings(settings)); - useServices.setState({ settings }); + if (epoch === sessionEpoch) useServices.setState({ settings }); return true; } catch (e) { - notifications().notify({ - group: "run", - level: "error", - title: "Cannot save Docker settings", - body: errorMessage(e), - }); + if (epoch === sessionEpoch) { + notifications().notify({ + group: "run", + level: "error", + title: "Cannot save Docker settings", + body: errorMessage(e), + }); + } return false; } }); @@ -277,17 +287,21 @@ export function refresh(id?: string): Promise { return running; } patchConn(id, { loading: true }); + const epoch = sessionEpoch; const p = call(commands.dockerSnapshot(endpointOf(id))) .then((snapshot) => { + if (epoch !== sessionEpoch) return; if (!connections().some((c) => c.id === id) || connectionState(id).disconnected) return; const wasReady = connectionState(id).snapshot?.availability.kind === "ready"; patchConn(id, { snapshot, error: null }); if (snapshot.availability.kind === "ready" && !wasReady) startEvents(id); }) .catch((e) => { + if (epoch !== sessionEpoch) return; if (!connectionState(id).disconnected) patchConn(id, { error: errorMessage(e) }); }) .finally(() => { + if (epoch !== sessionEpoch) return; inflight.delete(id); if (connections().some((c) => c.id === id)) patchConn(id, { loading: false }); if (again.delete(id)) void refresh(id); @@ -311,14 +325,17 @@ let watchers = 0; function startEvents(id: string) { if (events.has(id) || watchers === 0 || connectionState(id).disconnected) return; + const epoch = sessionEpoch; const request = nextRequestId(); events.set(id, request); const channel = new Channel(); - channel.onmessage = () => refreshSoon(id); + channel.onmessage = () => { + if (epoch === sessionEpoch) refreshSoon(id); + }; void call(commands.dockerEvents(request, endpointOf(id), channel)) .catch(() => undefined) .finally(() => { - if (events.get(id) !== request) return; + if (epoch !== sessionEpoch || events.get(id) !== request) return; events.delete(id); // The stream ended on its own (daemon stopped): re-check the state. if (watchers > 0) refreshSoon(id); @@ -333,6 +350,35 @@ function stopEvents(id?: string) { } } +function resetForHostChange() { + sessionEpoch++; + for (const r of events.values()) { + void Promise.resolve(commands.cancelRequest?.(r)).catch(() => undefined); + } + events.clear(); + for (const timer of debounces.values()) clearTimeout(timer); + debounces.clear(); + inflight.clear(); + again.clear(); + closing.clear(); + settingsLoad = null; + settingsWrite = Promise.resolve(true); + useServices.setState({ settings: null, conns: {}, task: null }); + if (watchers > 0) void loadSettings().then(() => refresh()); +} + +// Switching between a local window and a remote host (or reconnecting) moves Docker to that host. +useRemote.subscribe((state, previous) => { + if (state.session !== previous.session) resetForHostChange(); +}); + +// Trusting a Restricted Mode project unlocks `docker_snapshot` without waiting for the 10 s poll. +useProject.subscribe((state, previous) => { + if (state.project?.trusted && !previous.project?.trusted && watchers > 0) { + void loadSettings().then(() => refresh()); + } +}); + /** * Keeps the snapshots live while the tree is shown: events while a daemon runs, * a poll every 10 s while it does not (or its events stream is down). diff --git a/src/platform/remote.ts b/src/platform/remote.ts index 172d83fdec..9058e1ccab 100644 --- a/src/platform/remote.ts +++ b/src/platform/remote.ts @@ -67,7 +67,7 @@ export function encodeArgs(args: unknown): { json: string; channels: Map { const { json, channels } = encodeArgs(args); - if (cmd === "db_execute_stream" || cmd === "vcs_watch_commit_messages") { + if (cmd === "db_execute_stream" || cmd === "vcs_watch_commit_messages" || cmd.startsWith("docker_")) { // These callbacks are reached through onChannel; their own Tauri registrations are unused. const runtime = "__TAURI_INTERNALS__" in window ? window.__TAURI_INTERNALS__ : undefined; if (