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

..
Автор SHA1 Повідомлення Дата
l0ng-ai f2fb2b79ea feat(editor): support Helm and Go templates 2026-11-24 10:47:53 +08:00
124 змінених файлів з 882 додано та 5442 видалено

No files matched your search

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 138 KiB

Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 169 KiB

-6
Переглянути файл
@@ -155,12 +155,6 @@ jobs:
# Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false
- run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose
if: runner.os == 'Linux'
run: |
docker pull busybox:latest
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
# nextest skips doctests; ide-command's are its compile-fail tests.
- if: runner.os == 'Linux'
run: cargo test --doc -p ide-command
+1 -2
Переглянути файл
@@ -79,9 +79,8 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
+1 -1
Переглянути файл
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
+5 -20
Переглянути файл
@@ -661,15 +661,6 @@ impl AgentManager {
self.shared.sinks.write().remove(subscriber);
}
pub fn has_live_work(&self) -> bool {
self.tasks.read().values().any(|task| {
let state = task.state.lock();
state.busy
|| !state.background_tasks.is_empty()
|| matches!(state.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
})
}
/// Sets the callback used to read the active command execution security policy.
pub fn set_security_hook(&self, hook: SecurityHook) {
*self.shared.security.write() = Some(hook);
@@ -2523,8 +2514,6 @@ impl Task {
/// the user stops one. The caller set `busy`.
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
loop {
// The message shows before the checkout is recorded, which can take a while in a large repository.
self.show_prompt(&prompt);
self.checkout_before_turn().await;
let result = self.turn(&prompt).await;
self.cancel_pending.store(false, Ordering::Release);
@@ -2838,8 +2827,11 @@ impl Task {
Ok(())
}
/// Adds the user's message to the conversation and shows the task starting.
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt) {
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
self.turns.fetch_add(1, Ordering::AcqRel);
self.turn_started.store(false, Ordering::Release);
self.state.lock().task.resets_ms = None;
let attachments = prompt
.files
.iter()
@@ -2857,13 +2849,6 @@ impl Task {
// Launching the agent can take a while (`npx` fetches its adapter on first use).
let starting = self.live.lock().as_ref().is_none_or(|l| l.peer.is_closed());
self.set_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
}
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
self.turns.fetch_add(1, Ordering::AcqRel);
self.turn_started.store(false, Ordering::Release);
self.state.lock().task.resets_ms = None;
let mut live = self.ensure_session().await.map_err(Failure::from)?;
// Stopped while the agent started: the prompt is never sent.
if self.cancel_pending.load(Ordering::Acquire) {
+2 -3
Переглянути файл
@@ -40,11 +40,10 @@ pub enum IdeEvent {
McpBackgroundProjectsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection ended or another window took over the session.
/// This remote window's connection to its host ended on its own (network loss, the host or
/// its server went away); the window's project is unreachable until it reconnects.
RemoteConnectionLost {
host: String,
#[serde(default)]
taken_over: bool,
},
ProjectTrustChanged {
root: crate::IpcPath,
-14
Переглянути файл
@@ -4,20 +4,6 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// Tools › Remote Development. This is a user setting on the remote host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct RemoteDevelopmentSettings {
/// Zero disables idle shutdown. Positive values from older configurations keep their meaning.
pub idle_timeout_minutes: u16,
}
impl Default for RemoteDevelopmentSettings {
fn default() -> Self {
Self { idle_timeout_minutes: 180 }
}
}
/// How an SSH connection authenticates.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
-2
Переглянути файл
@@ -60,7 +60,6 @@ pub struct Settings {
pub spelling: SpellingSettings,
/// Tools › SSH Configurations.
pub ssh: SshSettings,
pub remote_development: RemoteDevelopmentSettings,
/// Build, Execution, Deployment › Deployment.
pub deployment: DeploymentSettings,
/// Build, Execution, Deployment › Run Targets.
@@ -579,7 +578,6 @@ impl Default for Settings {
inspections: InspectionSettings::default(),
spelling: SpellingSettings::default(),
ssh: SshSettings::default(),
remote_development: RemoteDevelopmentSettings::default(),
deployment: DeploymentSettings::default(),
run_targets: Vec::new(),
cmake: CMakeSettings::default(),
+2 -28
Переглянути файл
@@ -143,9 +143,6 @@ pub struct DockerConnection {
pub id: String,
pub name: String,
pub endpoint: DockerEndpoint,
/// Whether the user explicitly disconnected this connection in Services.
#[serde(default)]
pub disconnected: bool,
}
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
@@ -417,7 +414,6 @@ mod tests {
id: "c1".into(),
name: "Build box".into(),
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
disconnected: true,
}],
registries: vec![DockerRegistry {
id: "r1".into(),
@@ -439,34 +435,12 @@ mod tests {
assert!(load_settings(dir).connections.is_empty());
}
#[test]
fn connection_intent_defaults_to_connected_and_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
std::fs::write(
dir.join(SETTINGS_FILE),
r#"{"connections":[{"id":"box","name":"Box","endpoint":{"kind":"ssh","config":"build"}}]}"#,
)
.unwrap();
let mut settings = load_settings(dir);
assert!(!settings.connections[0].disconnected);
for disconnected in [true, false] {
settings.connections[0].disconnected = disconnected;
save_settings(dir, &settings).unwrap();
assert_eq!(load_settings(dir), settings);
}
}
#[test]
fn load_drops_the_injected_default_connection() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let injected = || DockerConnection {
id: "default".into(),
name: "Docker".into(),
endpoint: DockerEndpoint::Default,
disconnected: false,
};
let injected =
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
let registry =
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
+39 -138
Переглянути файл
@@ -1,6 +1,5 @@
//! `openidea-server`: the IDE backend for remote development, either serving one
//! desktop client over stdin / stdout (`--stdio`) or running as a persistent
//! per-project daemon (`--attach <project>`).
//! `openidea-server --stdio`: the IDE backend for remote development, serving
//! one desktop client over stdin / stdout (started by the client over SSH).
use ide_host::catalogue::TrustClass;
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
@@ -11,12 +10,6 @@ use ide_language::LanguageRegistry;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
enum Mode {
Stdio,
#[cfg(unix)]
Daemon(PathBuf, ide_host::daemon::BuildId),
}
fn main() {
let raw_args: Vec<String> = std::env::args().collect();
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
@@ -42,48 +35,18 @@ fn main() {
};
std::process::exit(code);
}
let base = server_home();
#[cfg(unix)]
if args.first().is_some_and(|a| a == "--attach") {
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
eprintln!("usage: openidea-server --attach <project-path>");
std::process::exit(2);
};
let home = dirs::home_dir().unwrap_or_default();
let code =
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
Ok(()) => 0,
Err(e) => {
eprintln!("{e}");
1
}
};
std::process::exit(code);
if !args.iter().any(|a| a == "--stdio") {
eprintln!(
"usage: openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
std::process::exit(2);
}
let mode = match args.as_slice() {
#[cfg(unix)]
[flag, sock, build] if flag == "--daemon" => {
let Ok(build) = build.as_bytes().try_into() else {
eprintln!("invalid daemon build identifier");
std::process::exit(2);
};
Mode::Daemon(PathBuf::from(sock), build)
}
#[cfg(not(unix))]
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
eprintln!(
"usage: openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
std::process::exit(2);
}
};
// stdout carries the protocol: logs go to stderr.
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
.init();
let base = server_home();
// An SSH exec channel gets a minimal environment: take the login shell's, read
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
ide_host::shell_env::inherit_login_shell_env("openidea-server");
@@ -92,7 +55,7 @@ fn main() {
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
let code = runtime.block_on(run(base, mode));
let code = runtime.block_on(run(base));
std::process::exit(code);
}
@@ -101,7 +64,7 @@ fn server_home() -> PathBuf {
std::env::var_os("OPENIDEA_SERVER_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".openidea"))
}
async fn run(base: PathBuf, mode: Mode) -> i32 {
async fn run(base: PathBuf) -> i32 {
let (config_dir, data_dir) = (base.join("config"), base.join("data"));
for dir in [&config_dir, &data_dir] {
if let Err(e) = std::fs::create_dir_all(dir) {
@@ -119,103 +82,40 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
// The desktop's plugin languages (`plugin_sync_languages`); programs pinned on this machine.
let plugin_languages = RemotePluginLanguages::new(Some(&data_dir));
languages.attach_plugins(plugin_languages.store().clone());
match mode {
Mode::Stdio => {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
let dispatcher = build_dispatcher(&plugins, plugin_languages);
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
shutdown_all(&host, plugins.as_ref()).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
let dispatcher = build_dispatcher(&plugins, plugin_languages);
let result = ide_host::daemon::serve(
&socket,
build,
host.clone(),
dispatcher,
peer,
shutdown_all(&host, plugins.as_ref()),
)
.await;
match result {
Ok(()) => 0,
Err(e) => {
eprintln!("daemon error: {e}");
1
}
}
}
}
}
fn start_mcp(host: &Arc<Host>, base: &std::path::Path) {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
// A stable path for `--mcp-stdio` client configurations across server upgrades.
host.mcp.set_stdio_link(base.join("bin").join("openidea-server"));
host.mcp_background.serve_none();
host.mcp.apply(host);
}
fn start_plugins<P: rpc::PeerHandle>(
plugins_data: &std::path::Path,
host: &Arc<Host>,
peer: Arc<P>,
) -> Option<Arc<RemotePlugins>> {
match RemotePlugins::start(plugins_data, host, peer) {
host.mcp.apply(&host);
// The desktop's code plugins run here, next to the project (`plugin_sync_packages`).
let plugins = match RemotePlugins::start(&plugins_data, &host, peer.clone()) {
Ok(p) => Some(p),
Err(e) => {
tracing::warn!("plugins are unavailable: {e}");
None
}
}
}
fn inherit_trust(host: &Host) {
};
if let Some(root) = std::env::var_os(ide_host::trust::TRUSTED_ROOT_ENV)
&& let Err(e) = host.trust.inherit(std::path::Path::new(&root))
{
tracing::warn!("cannot trust {}: {e}", root.to_string_lossy());
}
}
fn build_dispatcher(plugins: &Option<Arc<RemotePlugins>>, plugin_languages: Arc<RemotePluginLanguages>) -> Dispatcher {
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
let mut dispatcher = Dispatcher::standard();
if let Some(plugins) = plugins {
if let Some(plugins) = &plugins {
plugins.register(&mut dispatcher);
}
dispatcher.add(SYNC_COMMAND, TrustClass::Trusted, move |c| {
@@ -226,13 +126,14 @@ fn build_dispatcher(plugins: &Option<Arc<RemotePlugins>>, plugin_languages: Arc<
Ok(report)
}
});
dispatcher
}
async fn shutdown_all(host: &Host, plugins: Option<&Arc<RemotePlugins>>) {
host.mcp.stop(host);
if let Some(plugins) = plugins {
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
host.mcp.stop(&host);
if let Some(plugins) = &plugins {
plugins.host().shutdown();
}
host.shutdown().await;
// `process::exit` skips destructors: nothing started for the client may outlive it.
if tokio::time::timeout(std::time::Duration::from_secs(10), host.shutdown()).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
0
}
-482
Переглянути файл
@@ -1,482 +0,0 @@
//! Persistent per-project `openidea-server` daemon over a local Unix domain socket.
//!
//! * `openidea-server --attach <project_path>` connects to the daemon for `<project_path>`
//! (spawning it detached in a new session if none is listening) and bridges its own
//! stdin / stdout to the Unix socket. Closing the desktop window ends the SSH / WSL /
//! `docker exec` attach relay while the daemon — and its index, language servers,
//! terminals, runs and agent sessions — keeps running.
//! * `openidea-server --daemon <socket_path> <build>` is the process `--attach` starts.
use crate::Host;
use crate::rpc::{self, Dispatcher, PeerSlot, RemoteIdlePolicy};
use ide_core::CancellationToken;
use rustix::fs::{FlockOperation, flock};
use std::fs::{File, OpenOptions};
use std::future::{Future, pending};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::net::Shutdown;
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
use std::os::unix::net::UnixStream;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::signal::unix::{SignalKind, signal};
/// Keep socket paths well below macOS (104) and Linux (108) `sun_path` limits.
const MAX_SUN_PATH: usize = 96;
const STARTUP_TIMEOUT: Duration = Duration::from_secs(15);
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
const EOF_DRAIN: Duration = Duration::from_secs(2);
const EMPTY_IDLE_EXIT: Duration = Duration::from_secs(30);
const IDLE_ENV: &str = "OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS";
pub type BuildId = [u8; 16];
const ATTACHED: u8 = b'A';
const RETIRING: u8 = b'R';
const BUSY: u8 = b'B';
pub struct DaemonPaths {
pub key: String,
pub socket: PathBuf,
pub lock: PathBuf,
pub log: PathBuf,
}
/// Resolves `raw_path` (`~`, `~/…`, symlinks) the same way `open_project` does so
/// `~/repo` and `/home/user/repo` attach to the same daemon.
pub fn normalize_project_path(raw_path: &str, home: &Path) -> PathBuf {
let trimmed = raw_path.trim();
let expanded = if trimmed.is_empty() || trimmed == "~" {
home.to_path_buf()
} else if let Some(rest) = trimmed.strip_prefix("~/") {
home.join(rest)
} else {
PathBuf::from(trimmed)
};
let canonical = dunce::canonicalize(&expanded).unwrap_or(expanded);
let text = canonical.to_string_lossy();
if text.len() > 1 && text.ends_with('/') { PathBuf::from(text.trim_end_matches('/')) } else { canonical }
}
/// Deterministic socket, lock and log paths for a project and server home, across builds.
pub fn paths_for(base: &Path, home: &Path, raw_project_path: &str) -> io::Result<DaemonPaths> {
let project = normalize_project_path(raw_project_path, home);
std::fs::create_dir_all(base)?;
let base_canon = dunce::canonicalize(base).unwrap_or_else(|_| base.to_path_buf());
let mut hasher = blake3::Hasher::new();
hasher.update(project.as_os_str().as_encoded_bytes());
hasher.update(&[0]);
hasher.update(base_canon.as_os_str().as_encoded_bytes());
let key = hasher.finalize().to_hex()[..16].to_owned();
let sock_name = format!("s-{key}.sock");
let lock_name = format!("s-{key}.lock");
let preferred_dir = base.join("run");
let run_dir = if preferred_dir.join(&sock_name).as_os_str().len() <= MAX_SUN_PATH {
ensure_private_dir(&preferred_dir)?;
preferred_dir
} else {
let uid = rustix::process::geteuid().as_raw();
let fallback = PathBuf::from(format!("/tmp/openidea-{uid}"));
ensure_private_dir(&fallback)?;
fallback
};
let log_dir = base.join("logs");
std::fs::create_dir_all(&log_dir)?;
Ok(DaemonPaths {
socket: run_dir.join(sock_name),
lock: run_dir.join(lock_name),
log: log_dir.join(format!("server-{key}.log")),
key,
})
}
fn ensure_private_dir(dir: &Path) -> io::Result<()> {
if !dir.exists() {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true).mode(0o700);
builder.create(dir)?;
}
let meta = std::fs::symlink_metadata(dir)?;
if meta.file_type().is_symlink() || !meta.is_dir() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is not a private directory", dir.display()),
));
}
let uid = rustix::process::geteuid().as_raw();
if meta.uid() != uid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is owned by uid {}, expected {uid}", dir.display(), meta.uid()),
));
}
if meta.mode() & 0o077 != 0 {
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
/// `input` / `output` to its Unix socket.
pub fn attach(
base: &Path,
home: &Path,
project_path: &str,
input: impl Read + Send + 'static,
output: impl Write,
) -> Result<(), String> {
let exe = std::env::current_exe().map_err(|e| format!("cannot locate openidea-server: {e}"))?;
let paths = paths_for(base, home, project_path).map_err(|e| format!("cannot prepare runtime dir: {e}"))?;
let mut hasher = blake3::Hasher::new();
hasher
.update_reader(File::open(&exe).map_err(|e| format!("cannot open openidea-server: {e}"))?)
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
let hex = hasher.finalize().to_hex();
let build = &hex.as_str()[..16];
let stream = connect_or_spawn(&exe, &paths, build)?;
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
}
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
let lock_file = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.mode(0o600)
.open(&paths.lock)
.map_err(|e| format!("cannot open {}: {e}", paths.lock.display()))?;
flock(&lock_file, FlockOperation::LockExclusive)
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
if let Some(stream) = existing_daemon(paths, build)? {
return Ok(stream);
}
match std::fs::remove_file(&paths.socket) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("cannot remove stale socket {}: {e}", paths.socket.display())),
}
let mut log_file = OpenOptions::new()
.create(true)
.append(true)
.read(true)
.mode(0o600)
.open(&paths.log)
.map_err(|e| format!("cannot open {}: {e}", paths.log.display()))?;
let log_offset = log_file.metadata().map(|m| m.len()).unwrap_or(0);
let stderr_file = log_file.try_clone().map_err(|e| format!("cannot clone log handle: {e}"))?;
let mut cmd = Command::new(exe);
cmd.arg("--daemon")
.arg(&paths.socket)
.arg(build)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr_file));
// SAFETY: `setsid` is an async-signal-safe POSIX call that detaches the daemon into
// a new session without a controlling terminal, outliving the SSH / WSL / docker exec call.
unsafe {
cmd.pre_exec(|| {
let _ = rustix::process::setsid();
Ok(())
});
}
let mut child = cmd.spawn().map_err(|e| format!("cannot spawn openidea-server daemon: {e}"))?;
let deadline = Instant::now() + STARTUP_TIMEOUT;
loop {
if let Some(stream) = existing_daemon(paths, build)? {
return Ok(stream);
}
if let Ok(Some(status)) = child.try_wait() {
let tail = read_log_tail(&mut log_file, log_offset);
let detail = if tail.is_empty() { format!("exited with {status}") } else { tail };
return Err(format!("openidea-server daemon failed to start: {detail}"));
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
let tail = read_log_tail(&mut log_file, log_offset);
let detail = if tail.is_empty() { "timed out waiting for socket".to_owned() } else { tail };
return Err(format!("openidea-server daemon did not start: {detail}"));
}
std::thread::sleep(Duration::from_millis(15));
}
}
fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream>, String> {
let exchange = |mut stream: UnixStream| -> io::Result<Option<UnixStream>> {
stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT))?;
stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT))?;
stream.write_all(build.as_bytes())?;
let mut reply = [0];
stream.read_exact(&mut reply)?;
match reply[0] {
ATTACHED => {
stream.set_read_timeout(None)?;
stream.set_write_timeout(None)?;
Ok(Some(stream))
}
RETIRING => {
// This stream stays open until project cleanup and socket removal finish.
stream.set_read_timeout(Some(rpc::SHUTDOWN_TIMEOUT))?;
if stream.read(&mut reply)? == 0 {
Ok(None)
} else {
Err(io::Error::other("unexpected response from stopping daemon"))
}
}
BUSY => Err(io::Error::other(
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
Reconnect with that build, then stop the remote backend before upgrading.",
)),
_ => Err(io::Error::other("unrecognized remote backend response")),
}
};
let stream = match UnixStream::connect(&paths.socket) {
Ok(stream) => stream,
Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused) => return Ok(None),
Err(e) => return Err(format!("cannot connect to remote backend at {}: {e}", paths.socket.display())),
};
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
}
fn read_log_tail(file: &mut File, offset: u64) -> String {
if file.seek(SeekFrom::Start(offset)).is_err() {
return String::new();
}
let mut text = String::new();
let _ = file.read_to_string(&mut text);
text.trim().to_owned()
}
/// Copies `input` to `stream` and `stream` to `output`, returning promptly when either
/// side closes.
pub fn bridge(
mut from_daemon: UnixStream,
mut input: impl Read + Send + 'static,
mut output: impl Write,
) -> io::Result<()> {
from_daemon.set_read_timeout(Some(Duration::from_millis(100)))?;
let mut to_daemon = from_daemon.try_clone()?;
let (eof_tx, eof_rx) = mpsc::channel();
std::thread::spawn(move || {
let mut buf = [0u8; 16 * 1024];
loop {
match input.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if to_daemon.write_all(&buf[..n]).is_err() {
break;
}
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
let _ = to_daemon.shutdown(Shutdown::Write);
let _ = eof_tx.send(Instant::now());
});
let mut buf = [0u8; 16 * 1024];
let mut input_closed: Option<Instant> = None;
loop {
if let Ok(at) = eof_rx.try_recv() {
input_closed = Some(at);
}
if input_closed.is_some_and(|at| at.elapsed() >= EOF_DRAIN) {
break;
}
match from_daemon.read(&mut buf) {
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => continue,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Ok(0) | Err(_) => break,
Ok(n) => {
if output.write_all(&buf[..n]).and_then(|()| output.flush()).is_err() {
break;
}
}
}
}
let _ = from_daemon.shutdown(Shutdown::Both);
Ok(())
}
/// The socket remains bound until cleanup finishes, so an attach can't start a
/// replacement while the previous backend is still stopping its processes.
pub async fn serve(
socket_path: &Path,
build: BuildId,
host: Arc<Host>,
dispatcher: Dispatcher,
slot: Arc<PeerSlot>,
cleanup: impl Future<Output = ()>,
) -> io::Result<()> {
let start = || {
if let Some(parent) = socket_path.parent() {
ensure_private_dir(parent)?;
}
let terminate = signal(SignalKind::terminate())?;
let listener = tokio::net::UnixListener::bind(socket_path)?;
if let Err(e) = std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600)) {
let _ = std::fs::remove_file(socket_path);
return Err(e);
}
Ok((listener, terminate))
};
let (listener, mut terminate) = match start() {
Ok(started) => started,
Err(e) => {
cleanup.await;
return Err(e);
}
};
let shutdown = CancellationToken::new();
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
let mut idle = None;
let mut retiring = None;
let mut active: Option<ide_jsonrpc::Peer> = None;
let result = loop {
tokio::select! {
_ = shutdown.cancelled() => break Ok(()),
_ = terminate.recv() => break Ok(()),
_ = async {
match &active {
Some(peer) => { peer.closed().await; }
None => pending().await,
}
} => {
active = None;
slot.remove();
host.client_disconnected();
idle = None;
}
accepted = listener.accept() => {
let mut stream = match accepted {
Ok((stream, _)) => stream,
Err(e) => break Err(e),
};
let mut requested_build = [0; 16];
if !matches!(
tokio::time::timeout(HANDSHAKE_TIMEOUT, stream.read_exact(&mut requested_build)).await,
Ok(Ok(_))
) {
continue;
}
if active.as_ref().is_some_and(ide_jsonrpc::Peer::is_closed) {
active = None;
slot.remove();
host.client_disconnected();
idle = None;
}
if shutdown.is_cancelled() {
break Ok(());
}
if requested_build != build {
let busy = active.is_some() || has_live_work(&host);
if busy {
let _ = stream.write_u8(BUSY).await;
} else if stream.write_u8(RETIRING).await.is_ok() {
retiring = Some(stream);
break Ok(());
}
continue;
}
if stream.write_u8(ATTACHED).await.is_err() {
continue;
}
if let Some(old) = slot.remove() {
// Await an acknowledgement before tearing down the old transport.
let _ = tokio::time::timeout(
Duration::from_millis(750),
old.request::<_, ()>(rpc::SESSION_REPLACED, (), None),
).await;
old.kill();
host.client_disconnected();
}
let (reader, writer) = stream.into_split();
active = Some(rpc::connect_persistent(
host.clone(), dispatcher.clone(), slot.clone(), shutdown.clone(), idle_policy, reader, writer,
));
idle = None;
}
_ = check.tick() => {
if active.is_some() || has_live_work(&host) {
idle = None;
} else {
if idle.is_none() {
let since = Instant::now();
let timeout = match disconnected_timeout(&host, idle_policy).await {
Ok(timeout) => timeout,
Err(e) => break Err(e),
};
idle = Some((since, timeout));
}
if let Some((since, Some(timeout))) = idle && since.elapsed() >= timeout {
tracing::info!("idle openidea-server daemon exiting");
break Ok(());
}
}
}
}
};
shutdown.cancel();
slot.remove();
if let Some(peer) = &active {
let _ = tokio::time::timeout(HANDSHAKE_TIMEOUT, peer.flush()).await;
host.client_disconnected();
}
cleanup.await;
if let Err(e) = std::fs::remove_file(socket_path) {
tracing::warn!("cannot remove remote backend socket {}: {e}", socket_path.display());
}
if let Some(active) = active {
active.kill();
}
drop(retiring);
result
}
fn idle_override() -> Option<u64> {
if let Some(value) = std::env::var_os(IDLE_ENV) {
if let Some(seconds) = value.to_str().and_then(|s| s.parse::<u64>().ok()).filter(|&n| n > 0) {
return Some(seconds);
}
tracing::warn!("{IDLE_ENV} must be a positive number of seconds; using the host setting");
}
None
}
async fn disconnected_timeout(host: &Arc<Host>, policy: RemoteIdlePolicy) -> io::Result<Option<Duration>> {
let override_timeout = policy.override_seconds.map(Duration::from_secs);
if host.projects().is_empty() {
return Ok(Some(override_timeout.unwrap_or(EMPTY_IDLE_EXIT).min(EMPTY_IDLE_EXIT)));
}
if let Some(timeout) = override_timeout {
return Ok(Some(timeout));
}
let minutes = crate::ops::project::remote_idle_timeout_minutes(host).await.map_err(io::Error::other)?;
Ok((minutes != 0).then(|| Duration::from_secs(u64::from(minutes) * 60)))
}
/// Keeps a disconnected daemon alive: expiring would end this work, or lose the unsaved
/// edits a dropped connection left behind.
fn has_live_work(host: &Host) -> bool {
!host.terminals.list().is_empty()
|| host.processes.has_live_runs()
|| !host.debugger.sessions(None).is_empty()
|| host
.projects()
.iter()
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
}
+9 -40
Переглянути файл
@@ -5,8 +5,6 @@
pub mod agent_secrets;
pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
pub mod data_dirs;
pub mod diagnostics_store;
mod direnv;
@@ -528,25 +526,6 @@ impl Host {
}
}
/// Cleans up per-connection client state when a remote window disconnects from a
/// persistent daemon, leaving the project, index, language servers, terminals,
/// runs and agent sessions running.
pub fn client_disconnected(&self) {
let windows: Vec<String> = self.projects.read().keys().cloned().collect();
for window in &windows {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
self.cancel_request(request);
}
}
self.terminals.detach_output();
self.processes.detach_output();
for project in self.projects() {
project.documents.release_client_refs();
}
}
/// Stops what this host started: heap snapshots, notebook kernels, language servers, agents,
/// runs and terminals.
/// For a process that exits without dropping the host (the remote server).
@@ -554,6 +533,7 @@ impl Host {
// A capture's dump may hold secrets from the debuggee's memory: delete it before exiting.
ops::heap::shutdown(self).await;
self.environment.shutdown();
self.processes.kill_all();
self.terminals.kill_all();
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
for project in &projects {
@@ -573,33 +553,22 @@ impl Host {
project.notebooks.stop_admission();
project.agents.shutdown();
}
let stop_processes = async {
for project in &projects {
self.debugger.stop_under(&project.root).await;
}
self.processes.shutdown().await;
};
// Kernel cleanup owns its interrupt/termination/reaping deadlines. An
// outer LSP timeout must never abort it before owned children are reaped.
let stop_kernels = async {
for project in &projects {
if let Some(bridge) = &project.kotlin_bridge {
bridge.shutdown().await;
}
project.notebooks.shutdown().await;
for project in &projects {
if let Some(bridge) = &project.kotlin_bridge {
bridge.shutdown().await;
}
};
project.notebooks.shutdown().await;
}
let stop_language_servers = async {
for project in &projects {
project.lsp.shutdown_all().await;
}
};
let stop_lsp = async {
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
};
tokio::join!(stop_processes, stop_kernels, stop_lsp);
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
tracing::warn!("language servers did not shut down in time");
}
}
// ---- cancellable requests: the UI allocates ids, `cancel_request` cancels ----
-1
Переглянути файл
@@ -2319,7 +2319,6 @@ mod tests {
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
}
#[cfg(unix)]
fn action_stub() -> CodeAction {
CodeAction {
title: String::new(),
-10
Переглянути файл
@@ -87,15 +87,6 @@ pub fn settings_get_global(host: &Host) -> Settings {
host.with_proxy_password(host.global_settings.effective())
}
/// Read the same host-wide value for the close dialog and the idle timer: another project's
/// daemon may have edited the file since this host loaded its settings.
#[command(trust = always)]
pub async fn remote_idle_timeout_minutes(host: &Arc<Host>) -> IdeResult<u16> {
let h = host.clone();
host.blocking(move || Ok(h.global_settings.layer(SettingsScope::Global).remote_development.idle_timeout_minutes))
.await
}
/// The removed built-in theme id a settings file of this window still names, if any:
/// `settings_get` reports the built-in that stands in for it, so the notice about
/// a theme that moved to a plugin can address the installs it concerns.
@@ -490,7 +481,6 @@ ide_command::domain!(
project_trust_status,
project_workspace_member_set,
project_workspace_members,
remote_idle_timeout_minutes,
settings_get,
settings_get_global,
settings_removed_theme,
+1 -15
Переглянути файл
@@ -3,7 +3,7 @@ use crate::Host;
use ide_command::command;
use ide_core::remote_settings::RunTargetKind;
use ide_core::{IdeError, IdeResult, RunId};
use ide_run::{OutputChunk, RunAttach, RunConfig, RunInfo, StartOptions};
use ide_run::{OutputChunk, RunConfig, RunInfo, StartOptions};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
@@ -644,19 +644,6 @@ pub fn run_list(host: &Host) -> Vec<RunInfo> {
runs
}
/// Reattaches to a running process `id` on this host, returning its buffered output
/// and configuration while streaming subsequent chunks to `on_output`.
#[command(trust = always)]
pub async fn run_attach(host: &Host, window: &str, id: RunId, on_output: Channel<OutputChunk>) -> IdeResult<RunAttach> {
host.processes.reattach(
id,
host.window_sink(window),
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
)
}
pub mod commands;
pub(crate) mod container;
pub use commands::*;
@@ -829,7 +816,6 @@ mod ownership_tests {
ide_command::domain!(
run:
run_apply_settings,
run_attach,
run_close_stdin,
run_configs,
run_list,
+1 -34
Переглянути файл
@@ -2,7 +2,7 @@ use super::{Channel, Emit};
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, IpcBytes, TerminalId};
use ide_terminal::{TerminalAttach, TerminalInfo, TerminalOptions, TerminalSessionInfo};
use ide_terminal::{TerminalInfo, TerminalOptions};
mod images;
@@ -53,7 +53,6 @@ pub async fn term_spawn(
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
None,
)?;
if let Some(line) = activation {
let _ = host.terminals.write(info.id, &format!(" {line}\r"));
@@ -161,36 +160,6 @@ pub fn term_kill(host: &Host, id: TerminalId) -> IdeResult<()> {
host.terminals.kill(id)
}
/// Live terminal sessions of this window, for reattaching after a reconnect.
#[command(trust = always)]
pub async fn term_list(host: &Host, window: &str) -> Vec<TerminalSessionInfo> {
host.terminals.list_key(host.owner_window(window))
}
/// Reattaches to an existing terminal session `id`, returning its buffered output
/// and streaming subsequent chunks to `on_output`.
#[command(trust = always)]
pub async fn term_attach(
host: &Host,
window: &str,
id: TerminalId,
cols: u16,
rows: u16,
on_output: Channel<String>,
) -> IdeResult<TerminalAttach> {
let key = host.owner_window(window);
host.terminals.reattach(
id,
key,
cols,
rows,
host.window_sink(window),
Box::new(move |chunk| {
let _ = on_output.send(chunk);
}),
)
}
/// Whether the session is running a command (closing its tab asks first). A
/// `tcgetpgrp` or one process snapshot: async only to stay off the main thread.
#[command(trust = always)]
@@ -233,12 +202,10 @@ mod tests {
ide_command::domain!(
term:
term_attach,
term_available_shells,
term_default_shell,
term_is_busy,
term_kill,
term_list,
term_resize,
term_spawn,
term_store_image,
+10 -10
Переглянути файл
@@ -20,16 +20,17 @@
use super::{Consent, HostWorkspace, PluginEvent, PluginHost, PluginSource, SecretStore};
use crate::catalogue::TrustClass;
use crate::rpc::{Dispatcher, PeerHandle};
use crate::rpc::Dispatcher;
use base64::Engine as _;
use ide_core::{IdeError, IdeResult};
use ide_extension::{MANIFEST_FILE, ledger};
use ide_jsonrpc::Peer;
use ide_plugin::Limits;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Weak};
use std::sync::{Arc, OnceLock, Weak};
use std::time::Duration;
/// The server command the desktop calls with its packages.
@@ -245,13 +246,13 @@ pub struct RemotePlugins {
/// Secrets from the desktop's keychain, asked for when used.
struct ClientSecrets {
peer: Arc<dyn PeerHandle>,
peer: Arc<OnceLock<Peer>>,
runtime: tokio::runtime::Handle,
}
impl SecretStore for ClientSecrets {
fn get(&self, plugin: &str, name: &str) -> Option<String> {
let peer = self.peer.current()?;
let peer = self.peer.get()?.clone();
let request = SecretRequest { plugin: plugin.to_owned(), name: name.to_owned() };
let ask = async move {
tokio::time::timeout(SECRET_TIMEOUT, peer.request::<_, Option<String>>(SECRET_REQUEST, request, None)).await
@@ -274,7 +275,7 @@ impl SecretStore for ClientSecrets {
}
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
let peer = self.peer.current().ok_or("desktop disconnected")?;
let peer = self.peer.get().ok_or("desktop disconnected")?.clone();
let request = SecretWrite { plugin: plugin.into(), name: name.into(), value: value.map(str::to_owned) };
let ask = async {
tokio::time::timeout(SECRET_TIMEOUT, peer.request::<_, Result<(), String>>(SECRET_WRITE, request, None))
@@ -292,12 +293,11 @@ impl SecretStore for ClientSecrets {
impl RemotePlugins {
/// Creates the host over `<data_dir>/remote-plugins`, loads what earlier
/// sessions installed and starts event delivery and supervision.
pub fn start<P: PeerHandle>(data_dir: &Path, projects: &Arc<crate::Host>, peer: Arc<P>) -> IdeResult<Arc<Self>> {
let peer: Arc<dyn PeerHandle> = peer;
pub fn start(data_dir: &Path, projects: &Arc<crate::Host>, peer: Arc<OnceLock<Peer>>) -> IdeResult<Arc<Self>> {
let sink_peer = peer.clone();
let sink = move |client: Option<&str>, event: PluginEvent| {
if forwarded(&event)
&& let Some(p) = sink_peer.current()
&& let Some(p) = sink_peer.get()
{
let _ = p.notify(EVENT_NOTIFICATION, PluginEventMessage { window: client.map(str::to_owned), event });
}
@@ -486,7 +486,7 @@ fn safe_relative(path: &str) -> IdeResult<PathBuf> {
}
struct ClientLoopbacks {
peer: Arc<dyn PeerHandle>,
peer: Arc<OnceLock<Peer>>,
runtime: tokio::runtime::Handle,
}
impl ClientLoopbacks {
@@ -496,7 +496,7 @@ impl ClientLoopbacks {
operation: AuthOperation,
cancel: Option<ide_core::CancellationToken>,
) -> Result<serde_json::Value, ide_plugin::HostError> {
let peer = self.peer.current().ok_or(ide_plugin::HostError::Cancelled)?;
let peer = self.peer.get().ok_or(ide_plugin::HostError::Cancelled)?.clone();
let timeout = match &operation {
AuthOperation::Wait { timeout_ms, .. } => Duration::from_millis(u64::from(*timeout_ms)) + SECRET_TIMEOUT,
_ => SECRET_TIMEOUT,
+12 -3
Переглянути файл
@@ -16,6 +16,7 @@ use ide_extension::{Package, check_relative};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
/// Most files under one web root.
const MAX_FILES: usize = 4096;
@@ -168,7 +169,7 @@ impl PluginHost {
plugin_id: &str,
window: &str,
output: crate::ops::Emit<String>,
completion: Option<ide_terminal::TerminalExitHook>,
completion: Option<Arc<dyn Fn(Option<i32>) + Send + Sync>>,
options: impl FnOnce() -> IdeResult<ide_terminal::TerminalOptions>,
) -> IdeResult<ide_terminal::TerminalInfo> {
let _guard = self.lifecycle.lock();
@@ -183,12 +184,20 @@ impl PluginHost {
return Err(IdeError::invalid("a plugin may own at most 8 PTYs"));
}
let cwd = options.cwd.0.clone();
let previous = host.window_sink(window);
let sink: Arc<dyn ide_core::EventSink> = Arc::new(move |event: ide_core::IdeEvent| {
if let ide_core::IdeEvent::TerminalExited { code, .. } = &event
&& let Some(completion) = &completion
{
completion(*code);
}
previous.emit(event);
});
let info = host.terminals.spawn_program(
options,
host.owner_window(window).to_owned(),
host.window_sink(window),
sink,
Box::new(move |data| output(data)),
completion,
)?;
if !self
.shared
+4 -115
Переглянути файл
@@ -76,8 +76,6 @@ pub struct Project {
/// watchers for (a virtualenv elsewhere, a path dependency).
lsp_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
pub(crate) _scratch_watcher: Option<Watcher>,
/// Git metadata of repositories whose git directory lies outside the project folder.
pub(crate) git_metadata: Option<Arc<ide_vcs::MetadataWatch>>,
/// Picks up data sources edited on disk outside the Database tool window.
_db_sources_watch: Option<ide_db::SourcesWatch>,
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
@@ -108,14 +106,6 @@ impl Host {
&& current.root == root
&& !current.light
{
let status = current.index.status();
if status.indexing {
current.sink.emit(IdeEvent::IndexState {
indexing: true,
files: status.files,
symbols: status.symbols,
});
}
return Ok(current);
}
// A window takes the root over from the MCP server's background project, whose
@@ -387,10 +377,6 @@ impl Host {
for repo in repos.read().all() {
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
}
let git_metadata = git_metadata_watch(&root, &sink);
if let Some(watch) = &git_metadata {
watch.set_repos(repos.read().all(), &root);
}
// Shared handle: `unwatched_reason` is a live query on the watcher,
// filled after `start` returns so the on-change callback can reach it.
let watcher_weak = Arc::new(std::sync::OnceLock::<std::sync::Weak<Watcher>>::new());
@@ -404,7 +390,6 @@ impl Host {
let kotlin_bridge = kotlin_bridge.clone();
let phpstan = phpstan.clone();
let repos = repos.clone();
let git_metadata = git_metadata.clone();
let settings = settings.clone();
let index = index.clone();
let documents = documents.clone();
@@ -528,7 +513,6 @@ impl Host {
scan_repositories(
&root,
&repos,
git_metadata.as_deref(),
&settings,
&sink,
&build_cache,
@@ -619,11 +603,11 @@ impl Host {
mark("watcher");
{
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone());
let build_cache = build_cache.clone();
let trusted = trusted.load(Ordering::Acquire);
std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || {
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted)
})?;
std::thread::Builder::new()
.name("openidea-vcs-roots".into())
.spawn(move || scan_repositories(&root, &repos, &settings, &sink, &build_cache, trusted))?;
}
mark("git");
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
@@ -672,7 +656,6 @@ impl Host {
content_watchers: Mutex::new(content_watchers),
lsp_watchers: Mutex::new(Vec::new()),
_scratch_watcher: scratch_watcher,
git_metadata,
_db_sources_watch: db_sources_watch,
files_events_active,
light: false,
@@ -920,7 +903,6 @@ impl Host {
content_watchers: Mutex::new(Vec::new()),
lsp_watchers: Mutex::new(Vec::new()),
_scratch_watcher: None,
git_metadata: None,
_db_sources_watch: None,
files_events_active: Arc::new(AtomicBool::new(false)),
light: true,
@@ -1024,7 +1006,6 @@ fn light_watcher(
fn scan_repositories(
root: &Path,
repos: &RwLock<Repos>,
git_metadata: Option<&ide_vcs::MetadataWatch>,
settings: &SettingsStore,
sink: &SharedSink,
build_cache: &Path,
@@ -1033,9 +1014,6 @@ fn scan_repositories(
match discover_repositories(root, settings, build_cache, trusted) {
Ok(found) => {
if found.roots() != repos.read().roots() {
if let Some(watch) = git_metadata {
watch.set_repos(found.all(), root);
}
*repos.write() = found;
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
}
@@ -1089,7 +1067,6 @@ impl Project {
scan_repositories(
&self.root,
&self.repos,
self.git_metadata.as_deref(),
&self.settings,
&self.sink,
&self.build_cache_dir(),
@@ -2344,20 +2321,6 @@ mod maven_linkage_tests {
}
}
/// Commits, checkouts and resets made outside the IDE in a git directory the project
/// watcher doesn't see (the project is a subfolder of its repository, or a linked worktree).
fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option<Arc<ide_vcs::MetadataWatch>> {
let (root, sink) = (root.to_path_buf(), sink.clone());
ide_vcs::MetadataWatch::new(move |paths| {
if paths.iter().any(|p| vcs_path_changed(p)) {
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
}
})
.map(Arc::new)
.map_err(|e| tracing::warn!("{}", e.message))
.ok()
}
fn vcs_path_changed(path: &Path) -> bool {
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
}
@@ -2642,77 +2605,3 @@ mod content_roots_tests {
assert_eq!(members[&root], ["/dist", "/target"]);
}
}
#[cfg(test)]
mod external_git_metadata_tests {
use crate::{Host, HostConfig};
use ide_core::{IdeEvent, SharedSink};
use parking_lot::Mutex;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
fn git(dir: &Path, args: &[&str]) {
let out = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "[email protected]", "-c", "user.name=t", "-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
/// A commit made in a terminal refreshes the project's VCS state when the project folder
/// is the repository root, a subfolder of it, or a linked worktree, and for a submodule.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn external_commits_refresh_vcs_wherever_the_git_dir_lives() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let main = base.join("main");
std::fs::create_dir_all(main.join("sub")).unwrap();
git(&main, &["init", "-q", "-b", "main"]);
git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]);
let lib = base.join("lib");
std::fs::create_dir(&lib).unwrap();
git(&lib, &["init", "-q", "-b", "main"]);
git(&lib, &["commit", "-q", "--allow-empty", "-m", "init"]);
let sup = base.join("super");
std::fs::create_dir(&sup).unwrap();
git(&sup, &["init", "-q", "-b", "main"]);
git(&sup, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", lib.to_str().unwrap(), "lib"]);
git(&sup, &["commit", "-q", "-m", "submodule"]);
let seen = Arc::new(Mutex::new(0usize));
let counted = seen.clone();
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
if matches!(e, IdeEvent::VcsChanged { .. }) {
*counted.lock() += 1;
}
});
let host = Host::new(HostConfig {
sink_for: Box::new(move |_| sink.clone()),
local_data_dir: base.join("local"),
..HostConfig::for_test(&base)
});
let cases = [
(main.clone(), main.clone()),
(main.join("sub"), main.join("sub")),
(base.join("wt"), base.join("wt")),
(sup.clone(), sup.join("lib")),
];
for (project, repo) in cases {
host.open_project("main", &project).unwrap();
std::thread::sleep(Duration::from_millis(1500));
*seen.lock() = 0;
std::fs::write(repo.join("a.txt"), repo.to_string_lossy().as_bytes()).unwrap();
git(&repo, &["add", "a.txt"]);
git(&repo, &["commit", "-q", "-m", "change"]);
let deadline = Instant::now() + Duration::from_secs(10);
while *seen.lock() == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(50));
}
assert!(*seen.lock() > 0, "no VcsChanged for a commit in {}", repo.display());
host.close_project("main");
}
}
}
+14 -133
Переглянути файл
@@ -29,15 +29,6 @@ use std::sync::{Arc, OnceLock};
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
pub const PROTOCOL_VERSION: u32 = 3;
pub const SESSION_REPLACED: &str = "session_replaced";
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
/// Advertised only by a persistent backend with an editable idle timeout.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct RemoteIdlePolicy {
pub override_seconds: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -47,8 +38,6 @@ pub struct ServerInfo {
pub os: String,
pub arch: String,
pub home: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idle_policy: Option<RemoteIdlePolicy>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -71,71 +60,12 @@ pub struct ChannelMessage {
pub data: Value,
}
/// Holds the active client [`Peer`]: once for `--stdio` ([`OnceLock<Peer>`]) or
/// rebound across client reconnects for a persistent daemon ([`PeerSlot`]).
pub trait PeerHandle: Send + Sync + 'static {
fn current(&self) -> Option<Peer>;
fn install(&self, peer: Peer) -> (u64, Option<Peer>);
fn clear(&self, generation: u64) -> bool;
}
impl PeerHandle for OnceLock<Peer> {
fn current(&self) -> Option<Peer> {
self.get().cloned()
}
fn install(&self, peer: Peer) -> (u64, Option<Peer>) {
let _ = self.set(peer);
(1, None)
}
fn clear(&self, _: u64) -> bool {
true
}
}
/// Rebindable client connection slot for a persistent `openidea-server` daemon.
#[derive(Default)]
pub struct PeerSlot {
inner: parking_lot::RwLock<Option<(u64, Peer)>>,
seq: std::sync::atomic::AtomicU64,
}
impl PeerSlot {
#[cfg(unix)]
pub(crate) fn remove(&self) -> Option<Peer> {
self.inner.write().take().map(|(_, p)| p)
}
}
impl PeerHandle for PeerSlot {
fn current(&self) -> Option<Peer> {
self.inner.read().as_ref().map(|(_, p)| p.clone())
}
fn install(&self, peer: Peer) -> (u64, Option<Peer>) {
let id = self.seq.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let previous = self.inner.write().replace((id, peer)).map(|(_, p)| p);
(id, previous)
}
fn clear(&self, generation: u64) -> bool {
let mut guard = self.inner.write();
if guard.as_ref().is_some_and(|(id, _)| *id == generation) {
*guard = None;
true
} else {
false
}
}
}
/// One `invoke`: its arguments and a way to stream values back.
pub struct Call {
pub host: Arc<Host>,
pub window: String,
pub args: Value,
peer: Arc<dyn PeerHandle>,
peer: Arc<OnceLock<Peer>>,
}
impl Call {
@@ -161,7 +91,7 @@ impl Call {
.ok_or_else(|| IdeError::invalid(format!("argument {name}: expected a channel")))?;
let peer = self.peer.clone();
Ok(Arc::new(move |data: T| {
let Some(peer) = peer.current() else { return };
let Some(peer) = peer.get() else { return };
match serde_json::to_value(&data) {
Ok(data) => {
let _ = peer.notify("channel", ChannelMessage { id, data });
@@ -221,56 +151,23 @@ impl Dispatcher {
/// Serves `host` over `reader` / `writer` until the client disconnects.
/// `peer` must be the one whose events `host` sends ([`event_sink`]).
pub async fn serve<R, W, P>(host: Arc<Host>, dispatcher: Dispatcher, peer: Arc<P>, reader: R, writer: W)
pub async fn serve<R, W>(host: Arc<Host>, dispatcher: Dispatcher, peer: Arc<OnceLock<Peer>>, reader: R, writer: W)
where
R: tokio::io::AsyncRead + Unpin + Send + 'static,
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
P: PeerHandle,
{
let slot: Arc<dyn PeerHandle> = peer;
let handler = Arc::new(ServerHandler { host: host.clone(), dispatcher, peer: slot.clone(), daemon: None });
let handler = Arc::new(ServerHandler { host: host.clone(), dispatcher, peer: peer.clone() });
let p = Peer::connect(reader, writer, handler);
let (generation, previous) = slot.install(p.clone());
if let Some(old) = previous {
old.kill();
}
let _ = peer.set(p.clone());
p.closed().await;
if slot.clear(generation) {
// Reports belong to the disconnected desktop, even while the host shuts down.
for window in host.projects.read().keys() {
host.mcp_reports.forget_window(window);
}
// Reports belong to the disconnected desktop, even while the host shuts down.
for window in host.projects.read().keys() {
host.mcp_reports.forget_window(window);
}
}
/// The daemon owns the peer and handles replacement and disconnect serially.
#[cfg(unix)]
pub(crate) fn connect_persistent<R, W>(
host: Arc<Host>,
dispatcher: Dispatcher,
peer: Arc<PeerSlot>,
shutdown: ide_core::CancellationToken,
idle_policy: RemoteIdlePolicy,
reader: R,
writer: W,
) -> Peer
where
R: tokio::io::AsyncRead + Unpin + Send + 'static,
W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
// Streaming ids belong to the calling connection, not the next window to attach.
let connection = Arc::new(OnceLock::new());
let handler =
Arc::new(ServerHandler { host, dispatcher, peer: connection.clone(), daemon: Some((shutdown, idle_policy)) });
let p = Peer::connect(reader, writer, handler);
let _ = connection.set(p.clone());
let (_, previous) = peer.install(p.clone());
debug_assert!(previous.is_none());
p
}
/// Sends a window's events to the client as `event` notifications.
pub fn event_sink<P: PeerHandle>(peer: Arc<P>, window: Option<String>) -> ide_core::SharedSink {
pub fn event_sink(peer: Arc<OnceLock<Peer>>, window: Option<String>) -> ide_core::SharedSink {
Arc::new(PeerSink { peer, window })
}
@@ -321,13 +218,13 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
}
struct PeerSink {
peer: Arc<dyn PeerHandle>,
peer: Arc<OnceLock<Peer>>,
window: Option<String>,
}
impl ide_core::EventSink for PeerSink {
fn emit(&self, event: IdeEvent) {
if let Some(peer) = self.peer.current() {
if let Some(peer) = self.peer.get() {
let _ = peer.notify("event", EventMessage { window: self.window.clone(), event });
}
}
@@ -336,18 +233,16 @@ impl ide_core::EventSink for PeerSink {
struct ServerHandler {
host: Arc<Host>,
dispatcher: Dispatcher,
peer: Arc<dyn PeerHandle>,
daemon: Option<(ide_core::CancellationToken, RemoteIdlePolicy)>,
peer: Arc<OnceLock<Peer>>,
}
fn server_info(idle_policy: Option<RemoteIdlePolicy>) -> ServerInfo {
pub fn server_info() -> ServerInfo {
ServerInfo {
version: env!("CARGO_PKG_VERSION").into(),
protocol: PROTOCOL_VERSION,
os: std::env::consts::OS.into(),
arch: std::env::consts::ARCH.into(),
home: dirs::home_dir().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default(),
idle_policy,
}
}
@@ -355,16 +250,10 @@ impl Handler for ServerHandler {
fn on_notification(&self, _method: &str, _params: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
if self.daemon.as_ref().is_some_and(|(shutdown, _)| shutdown.is_cancelled()) {
return Err((codes::INTERNAL_ERROR, "remote backend is stopping".into()));
}
let internal = |e: serde_json::Error| (codes::INTERNAL_ERROR, e.to_string());
match method {
"initialize" => {
serde_json::to_value(server_info(self.daemon.as_ref().map(|(_, policy)| *policy))).map_err(internal)
}
"initialize" => serde_json::to_value(server_info()).map_err(internal),
"commands" => serde_json::to_value(self.dispatcher.commands()).map_err(internal),
"shutdown" => Ok(Value::Null),
"invoke" => {
let call: Invoke =
serde_json::from_value(params).map_err(|e| (codes::INVALID_PARAMS, e.to_string()))?;
@@ -379,14 +268,6 @@ impl Handler for ServerHandler {
_ => Err((codes::METHOD_NOT_FOUND, format!("unknown method {method}"))),
}
}
fn after_response(&self, method: &str) {
if method == "shutdown"
&& let Some((shutdown, _)) = &self.daemon
{
shutdown.cancel();
}
}
}
/// An `IdeError` as a JSON-RPC error: the JSON of the error is the message.
-877
Переглянути файл
@@ -1,877 +0,0 @@
//! End-to-end tests of persistent `openidea-server --attach <project>`:
//! closing a client relay keeps the daemon, project index, terminals, runs
//! (including `stopCommand` configs such as `docker compose`) and dirty buffers
//! running until a client sends `"shutdown"` or the backend has been idle long enough.
#![cfg(unix)]
use ide_host::rpc::{self, ChannelMessage, EventMessage, Invoke, ServerInfo};
use ide_jsonrpc::{Handler, Peer};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
const SERVER: &str = env!("CARGO_BIN_EXE_openidea-server");
const IDLE_TIMEOUT: &str = "OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS";
#[derive(Default)]
struct Client {
channels: Mutex<Vec<ChannelMessage>>,
events: Mutex<Vec<EventMessage>>,
taken_over: AtomicBool,
}
impl Handler for Client {
fn on_notification(&self, method: &str, params: Value) {
match method {
"channel" => self.channels.lock().push(serde_json::from_value(params).unwrap()),
"event" => self.events.lock().push(serde_json::from_value(params).unwrap()),
_ => {}
}
}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
if method == rpc::SESSION_REPLACED {
self.taken_over.store(true, Ordering::Release);
return Ok(Value::Null);
}
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
async fn invoke(peer: &Peer, cmd: &str, args: Value) -> Result<Value, ide_core::IdeError> {
let call = Invoke { window: "main".into(), cmd: cmd.into(), args };
tokio::time::timeout(Duration::from_secs(15), peer.request::<_, Value>("invoke", call, None))
.await
.unwrap_or_else(|_| panic!("timed out calling {cmd}"))
.map_err(rpc::error_from_reply)
}
async fn until(what: &str, mut done: impl FnMut() -> bool) {
for _ in 0..600 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(15)).await;
}
panic!("timed out waiting for {what}");
}
struct DaemonGuard(PathBuf);
fn test_build() -> &'static [u8] {
static BUILD: OnceLock<String> = OnceLock::new();
BUILD
.get_or_init(|| {
let mut hasher = blake3::Hasher::new();
hasher.update_reader(std::fs::File::open(SERVER).unwrap()).unwrap();
hasher.finalize().to_hex()[..16].to_owned()
})
.as_bytes()
}
impl Drop for DaemonGuard {
fn drop(&mut self) {
use std::io::{Read, Write};
if let Ok(mut stream) = std::os::unix::net::UnixStream::connect(&self.0) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
let mut reply = [0];
if stream.write_all(test_build()).and_then(|_| stream.read_exact(&mut reply)).is_ok() && reply == *b"A" {
let request = r#"{"jsonrpc":"2.0","id":1,"method":"shutdown"}"#;
let _ = write!(stream, "Content-Length: {}\r\n\r\n{request}", request.len());
let _ = std::io::copy(&mut stream, &mut std::io::sink());
}
}
}
}
fn server_env(home: &Path, server_home: &Path, idle_seconds: u64) -> [(String, String); 4] {
[
("HOME".to_owned(), home.to_string_lossy().into_owned()),
("OPENIDEA_SERVER_HOME".to_owned(), server_home.to_string_lossy().into_owned()),
("OPENIDEA_SKIP_SHELL_ENV".to_owned(), "1".into()),
(IDLE_TIMEOUT.into(), idle_seconds.to_string()),
]
}
fn attach_client(home: &Path, server_home: &Path, attach_arg: &str, idle_seconds: u64) -> (Peer, Arc<Client>) {
let client = Arc::new(Client::default());
let args = vec!["--attach".to_owned(), attach_arg.to_owned()];
let env = server_env(home, server_home, idle_seconds);
let peer = Peer::spawn(SERVER, &args, home, &env, client.clone(), Box::new(|line| eprintln!("{line}"))).unwrap();
(peer, client)
}
async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_ssh::Session> {
use ide_core::remote_settings::{SshAuth, SshConfiguration};
use ide_ssh::{SshFiles, SshManager};
let project = project.to_owned();
let env = server_env(home, server_home, 10_800);
let port = ide_ssh::testing::sshd_with_process(home.join("sftp"), move |command| {
let path = if command == "openidea-test-attach" {
project.to_str().unwrap()
} else if command == "openidea-test-reattach" {
"~/demo"
} else {
return None;
};
let mut cmd = tokio::process::Command::new(SERVER);
cmd.args(["--attach", path]).envs(env.iter().cloned());
Some(cmd)
})
.await;
let ssh = SshManager::with_files(
home.join("secrets.json"),
SshFiles { known_hosts: home.join("known_hosts"), config: None },
);
ssh.set_configs(vec![SshConfiguration {
id: "local-test".into(),
host: "127.0.0.1".into(),
port: Some(port),
user: "dev".into(),
auth: SshAuth::Password,
save_secret: true,
..Default::default()
}]);
ssh.set_secret("local-test", Some("secret".into()), true);
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
ssh.trust_host("local-test").await.unwrap();
ssh.session("local-test").await.unwrap()
}
async fn ssh_attach(ssh: &ide_ssh::Session, command: &str) -> (Peer, Arc<Client>) {
let stream = ssh.exec_stream(command).await.unwrap();
let (reader, writer) = tokio::io::split(stream);
let client = Arc::new(Client::default());
(Peer::connect(reader, writer, client.clone()), client)
}
async fn initialize(peer: &Peer) -> ServerInfo {
tokio::time::timeout(
Duration::from_secs(15),
peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None),
)
.await
.expect("initialize timed out")
.unwrap()
}
async fn shutdown(peer: &Peer) {
tokio::time::timeout(Duration::from_secs(15), async {
peer.request::<_, ()>("shutdown", Value::Null, None).await.unwrap();
peer.closed().await;
})
.await
.expect("backend did not shut down");
}
async fn assert_indexed(peer: &Peer, name: &str) {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let syms =
invoke(peer, "find_symbols", json!({ "query": name, "filter": "all", "limit": 10 })).await.unwrap();
if syms.as_array().is_some_and(|a| a.iter().any(|sym| sym["name"] == name)) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.unwrap_or_else(|_| panic!("symbol {name} was not indexed"));
}
fn pid_alive(pid: u32) -> bool {
let Ok(pid) = i32::try_from(pid) else { return false };
if pid <= 0 {
return false;
}
// Check `kill(pid, 0)` and exclude zombies on macOS/Linux via `ps`.
let out = std::process::Command::new("ps").args(["-o", "stat=", "-p", &pid.to_string()]).output();
match out {
Ok(o) if o.status.success() => {
let stat = String::from_utf8_lossy(&o.stdout);
let s = stat.trim();
!s.is_empty() && !s.starts_with('Z')
}
_ => false,
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn ssh_disconnect_keeps_terminals_runs_index_and_dirty_docs_until_shutdown() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let project = home.join("demo");
let subdir = project.join("sub");
std::fs::create_dir_all(&subdir).unwrap();
let subdir = dunce::canonicalize(subdir).unwrap();
std::fs::write(project.join("app.py"), "def greet():\n return 42\n").unwrap();
let server_home = tmp.path().join("s");
let guard = DaemonGuard(ide_host::daemon::paths_for(&server_home, &home, "~/demo").unwrap().socket);
let ssh = ssh_server(&home, &server_home, &project).await;
// --- Session 1: open project, start a TUI terminal (`watch date`) and a compose-like run ---
let (peer1, client1) = ssh_attach(&ssh, "openidea-test-attach").await;
let info1 = initialize(&peer1).await;
assert_eq!(info1.protocol, rpc::PROTOCOL_VERSION);
assert_eq!(info1.idle_policy.unwrap().override_seconds, Some(10_800));
let opened = invoke(&peer1, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(opened["name"], "demo");
invoke(&peer1, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
assert_indexed(&peer1, "greet").await;
// Spawn a long-running terminal emitting OSC 7 cwd, OSC 2 title (`watch date`), OSC 133;C and periodic ticks.
let term_script = format!(
"printf '\\033]7;file://localhost{}\\007\\033]2;watch date\\007\\033]133;C\\007'; \
i=0; while true; do i=$((i+1)); echo \"tick-$i\"; sleep 0.05; done",
subdir.display()
);
let term = invoke(
&peer1,
"term_spawn",
json!({
"options": {
"cwd": project,
"shell": "/bin/sh",
"args": ["-c", term_script],
"env": {},
"cols": 80,
"rows": 24,
"shellIntegration": false
},
"onOutput": { "$channel": 101 }
}),
)
.await
.unwrap();
let term_id = term["id"].as_u64().unwrap();
let term_pid = term["pid"].as_u64().unwrap() as u32;
until("initial terminal tick", || {
client1.channels.lock().iter().any(|c| c.id == 101 && c.data.as_str().is_some_and(|s| s.contains("tick-")))
})
.await;
// Start a Docker-Compose-style run with a `stopCommand` that writes `down.marker` ONLY when stopped.
let down_marker = project.join("down.marker");
let run_config = json!({
"id": "docker:compose:up",
"name": "docker compose up",
"kind": "docker-compose",
"command": "/bin/sh",
"args": ["-c", "n=0; while true; do n=$((n+1)); echo \"compose-$n\"; sleep 0.05; done"],
"cwd": project,
"env": {},
"detected": false,
"isTest": false,
"debugAdapter": null,
"stopCommand": format!("touch '{}'", down_marker.display()),
});
let run = invoke(
&peer1,
"run_start",
json!({
"config": run_config,
"onOutput": { "$channel": 102 },
"request": 1
}),
)
.await
.unwrap();
let run_id = run["id"].as_u64().unwrap();
let run_pid = run["pid"].as_u64().unwrap() as u32;
until("initial compose output", || {
client1
.channels
.lock()
.iter()
.any(|c| c.id == 102 && c.data["text"].as_str().is_some_and(|s| s.contains("compose-")))
})
.await;
// Leave an unsaved edit in `app.py` to simulate an unexpected disconnect, plus a clean file `clean.txt`.
std::fs::write(project.join("clean.txt"), "before\n").unwrap();
let _clean_doc = invoke(&peer1, "doc_open", json!({ "path": project.join("clean.txt") })).await.unwrap();
let dirty_doc = invoke(&peer1, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
invoke(
&peer1,
"doc_edit",
json!({
"doc": dirty_doc["id"],
"baseVersion": dirty_doc["version"],
"changes": { "changes": [{ "from": 0, "to": 0, "insert": "# unsaved\n" }] }
}),
)
.await
.unwrap();
// --- Close window / disconnect client #1 ---
peer1.kill();
peer1.closed().await;
// Let both background processes produce output while NO client is connected, and update `clean.txt` on disk.
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(pid_alive(term_pid), "terminal PTY process must keep running after window close");
assert!(pid_alive(run_pid), "docker-compose run process must keep running after window close");
assert!(!down_marker.exists(), "closing the remote window must NOT run docker compose down");
std::fs::write(project.join("clean.txt"), "updated-while-closed\n").unwrap();
std::fs::write(project.join("added.py"), "def indexed_while_disconnected():\n pass\n").unwrap();
// --- Session 2: reopen via `~/demo` (tests `~` canonicalization attaching to the SAME daemon) ---
let (peer2, client2) = ssh_attach(&ssh, "openidea-test-reattach").await;
initialize(&peer2).await;
let reopened = invoke(&peer2, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(reopened["trusted"], true);
assert_indexed(&peer2, "indexed_while_disconnected").await;
// 1. Terminal list & reattach restores `watch date` title, cwd, buffered ticks and live output!
let terms = invoke(&peer2, "term_list", json!({})).await.unwrap();
let listed = terms.as_array().unwrap();
assert_eq!(listed.len(), 1, "{listed:?}");
assert_eq!(listed[0]["id"], term_id);
assert_eq!(listed[0]["appTitle"], "watch date");
assert_eq!(listed[0]["commandRunning"], true);
assert_eq!(listed[0]["cwd"], subdir.to_string_lossy().as_ref());
let attached_term = invoke(
&peer2,
"term_attach",
json!({ "id": term_id, "cols": 100, "rows": 30, "onOutput": { "$channel": 201 } }),
)
.await
.unwrap();
assert!(attached_term["buffered"].as_str().unwrap().contains("tick-"));
until("live terminal ticks on client 2", || {
client2.channels.lock().iter().any(|c| c.id == 201 && c.data.as_str().is_some_and(|s| s.contains("tick-")))
})
.await;
// 2. Run list & reattach restores the running `docker compose up` session and streams live output!
let runs = invoke(&peer2, "run_list", json!({})).await.unwrap();
assert!(runs.as_array().unwrap().iter().any(|r| r["id"] == run_id && r["running"] == true));
let attached_run =
invoke(&peer2, "run_attach", json!({ "id": run_id, "onOutput": { "$channel": 202 } })).await.unwrap();
assert_eq!(attached_run["config"]["id"], "docker:compose:up");
assert!(
attached_run["buffered"]
.as_array()
.unwrap()
.iter()
.any(|c| c["text"].as_str().is_some_and(|s| s.contains("compose-")))
);
until("live compose output on client 2", || {
client2
.channels
.lock()
.iter()
.any(|c| c.id == 202 && c.data["text"].as_str().is_some_and(|s| s.contains("compose-")))
})
.await;
// 3. Clean documents reload external disk changes; dirty documents retain unsaved edits without ref leaks!
let clean_reopened = invoke(&peer2, "doc_open", json!({ "path": project.join("clean.txt") })).await.unwrap();
assert_eq!(clean_reopened["text"], "updated-while-closed\n");
let dirty_reopened = invoke(&peer2, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
assert!(dirty_reopened["text"].as_str().unwrap().starts_with("# unsaved\n"));
assert_eq!(dirty_reopened["dirty"], true);
// 4. Explicit `"shutdown"` (Stop Remote Backend) stops the daemon and cleans up processes.
shutdown(&peer2).await;
until("terminal and run processes terminated on explicit backend shutdown", || {
!pid_alive(term_pid) && !pid_alive(run_pid)
})
.await;
assert!(down_marker.exists(), "stopping the backend runs the configured stop command");
assert!(!guard.0.exists(), "the shutdown connection stays open until daemon cleanup finishes");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn ongoing_agent_session_continues_running_while_remote_window_is_closed() {
agent_roundtrip(false).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn stopping_the_backend_terminates_an_agent_mid_turn() {
agent_roundtrip(true).await;
}
async fn agent_roundtrip(stop_during_turn: bool) {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let project = home.join("agent-demo");
std::fs::create_dir_all(&project).unwrap();
let server_home = tmp.path().join("s");
let guard = DaemonGuard(ide_host::daemon::paths_for(&server_home, &home, "~/agent-demo").unwrap().socket);
let agents_dir = server_home.join("config/agents");
std::fs::create_dir_all(&agents_dir).unwrap();
let agent_script = home.join("mock-acp-agent.py");
std::fs::write(
&agent_script,
r#"#!/usr/bin/env python3
import json, os, sys, time
from pathlib import Path
def send(obj):
sys.stdout.write(json.dumps(obj) + "\n")
sys.stdout.flush()
while True:
raw = sys.stdin.readline()
if not raw:
break
raw = raw.strip()
if not raw:
continue
msg = json.loads(raw)
method = msg.get("method")
mid = msg.get("id")
if method == "initialize":
send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": 2, "capabilities": {}, "info": {"name": "mock", "version": "1.0"}}})
elif method == "session/new":
send({"jsonrpc": "2.0", "id": mid, "result": {"sessionId": "sess-1", "configOptions": []}})
elif method == "session/prompt":
send({"jsonrpc": "2.0", "id": mid, "result": {"messageId": "u1"}})
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "state_update", "state": "running"}}})
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "agent_message_chunk", "messageId": "a1", "content": {"type": "text", "text": "part-1 "}}}})
Path("agent.pid").write_text(str(os.getpid()))
while not Path("agent.release").exists():
time.sleep(0.03)
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "agent_message_chunk", "messageId": "a1", "content": {"type": "text", "text": "finished-while-window-closed"}}}})
send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "sess-1", "update": {"sessionUpdate": "state_update", "state": "idle", "stopReason": "end_turn"}}})
Path("agent.finished").touch()
"#,
)
.unwrap();
std::fs::set_permissions(&agent_script, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(
agents_dir.join("mock-agent.toml"),
format!("name = \"Mock Agent\"\ncommand = \"{}\"\nargs = []\n", agent_script.display()),
)
.unwrap();
// Client 1 opens the project, starts the agent task, then disconnects mid-turn.
let (peer1, _) = attach_client(&home, &server_home, "~/agent-demo", 1);
initialize(&peer1).await;
invoke(&peer1, "open_project", json!({ "path": project })).await.unwrap();
invoke(&peer1, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
invoke(&peer1, "agent_subscribe", json!({ "subscriber": "main", "onEvent": { "$channel": 301 } })).await.unwrap();
let created = invoke(
&peer1,
"agent_create",
json!({
"request": {
"provider": "mock-agent",
"prompt": { "text": "run background task", "files": [], "images": [] },
"isolation": "local",
"baseBranch": null,
"config": [],
"projectRoot": project,
"mcpOverrides": {}
}
}),
)
.await
.unwrap();
let task_id = created["id"].as_str().unwrap().to_owned();
let pid_path = project.join("agent.pid");
let read_pid = || std::fs::read_to_string(&pid_path).ok().and_then(|text| text.parse::<u32>().ok());
until("agent prompt started", || read_pid().is_some()).await;
let agent_pid = read_pid().unwrap();
peer1.kill();
peer1.exited().await;
// The turn alone keeps the daemon running past its idle deadline.
tokio::time::sleep(Duration::from_millis(2300)).await;
assert!(guard.0.exists(), "the daemon expired during an agent turn");
assert!(pid_alive(agent_pid));
if !stop_during_turn {
std::fs::write(project.join("agent.release"), "").unwrap();
until("agent completed with the window closed", || project.join("agent.finished").exists()).await;
}
let (peer2, _) = attach_client(&home, &server_home, "~/agent-demo", 1);
initialize(&peer2).await;
invoke(&peer2, "open_project", json!({ "path": project })).await.unwrap();
if stop_during_turn {
shutdown(&peer2).await;
until("agent process stopped", || !pid_alive(agent_pid)).await;
assert!(!project.join("agent.finished").exists());
assert!(!guard.0.exists());
return;
}
for _ in 0..200 {
let tasks = invoke(&peer2, "agent_subscribe", json!({ "subscriber": "main", "onEvent": { "$channel": 401 } }))
.await
.unwrap();
let task = tasks.as_array().unwrap().iter().find(|t| t["id"] == task_id).expect("persisted agent task");
if task["status"] == "ready" {
break;
}
assert_ne!(task["status"], "failed", "{task:?}");
tokio::time::sleep(Duration::from_millis(20)).await;
}
let tasks = invoke(&peer2, "agent_subscribe", json!({ "subscriber": "main", "onEvent": { "$channel": 401 } }))
.await
.unwrap();
let task = tasks.as_array().unwrap().iter().find(|t| t["id"] == task_id).expect("persisted agent task");
assert_eq!(task["status"], "ready", "{task:?}");
let entries = invoke(&peer2, "agent_entries", json!({ "task": task_id, "subagent": null })).await.unwrap();
let texts: Vec<&str> = entries
.as_array()
.unwrap()
.iter()
.filter(|e| e["type"] == "agent")
.filter_map(|e| e["text"].as_str())
.collect();
assert!(
texts.iter().any(|t| t.contains("part-1 finished-while-window-closed")),
"expected full agent output across window close, got: {entries:?}"
);
shutdown(&peer2).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_idle_open_project_expires_but_an_attached_view_does_not() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(project.join("hello.py"), "def kept_during_index():\n pass\n").unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let (peer, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&peer).await;
invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
assert_indexed(&peer, "kept_during_index").await;
invoke(
&peer,
"settings_set",
json!({ "scope": "global", "key": "remoteDevelopment.idleTimeoutMinutes", "value": "0" }),
)
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(2300)).await;
assert!(!invoke(&peer, "project_current", json!({})).await.unwrap().is_null());
peer.kill();
peer.exited().await;
until("a disconnected, opened project expires", || !guard.0.exists()).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn unsaved_edits_of_a_dropped_connection_keep_an_idle_daemon() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(project.join("app.py"), "print(1)\n").unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let (peer, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&peer).await;
invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
let doc = invoke(&peer, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
invoke(
&peer,
"doc_edit",
json!({
"doc": doc["id"],
"baseVersion": doc["version"],
"changes": { "changes": [{ "from": 0, "to": 0, "insert": "# unsaved\n" }] }
}),
)
.await
.unwrap();
peer.kill();
peer.exited().await;
tokio::time::sleep(Duration::from_millis(2300)).await;
assert!(guard.0.exists(), "an idle daemon expired with unsaved edits");
let (again, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&again).await;
let reopened = invoke(&again, "doc_open", json!({ "path": project.join("app.py") })).await.unwrap();
assert!(reopened["text"].as_str().unwrap().starts_with("# unsaved\n"));
shutdown(&again).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn applying_the_host_timeout_expires_the_running_daemon_without_a_restart() {
saved_idle_policy(false).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn never_keeps_the_same_idle_daemon_until_explicit_shutdown() {
saved_idle_policy(true).await;
}
async fn saved_idle_policy(never: bool) {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let mut daemon = tokio::process::Command::new(SERVER)
.arg("--daemon")
.arg(&guard.0)
.arg(std::str::from_utf8(test_build()).unwrap())
.envs(server_env(&home, &base, 1))
.env_remove(IDLE_TIMEOUT)
.kill_on_drop(true)
.spawn()
.unwrap();
until("daemon bound its socket", || guard.0.exists()).await;
let (peer, _) = attach_client(&home, &base, "~/demo", 1);
assert_eq!(initialize(&peer).await.idle_policy.unwrap().override_seconds, None);
invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
let set = |scope: &str, value: &str| {
invoke(
&peer,
"settings_set",
json!({ "scope": scope, "key": "remoteDevelopment.idleTimeoutMinutes", "value": value }),
)
};
let global = invoke(&peer, "settings_get_global", json!({})).await.unwrap();
assert_eq!(global["remoteDevelopment"]["idleTimeoutMinutes"], 180);
assert!(set("global", "-1").await.is_err());
assert!(set("project", "1").await.is_err());
let updated = set("global", "1").await.unwrap();
assert_eq!(updated["remoteDevelopment"]["idleTimeoutMinutes"], 1);
assert!(std::fs::read_to_string(base.join("config/settings.toml")).unwrap().contains("idleTimeoutMinutes = 1"));
if never {
// A different project's daemon can change the host preference after this window connected.
let other = ide_workspace::SettingsStore::load(&base.join("config"), None);
other.set(ide_workspace::SettingsScope::Global, "remoteDevelopment.idleTimeoutMinutes", json!(0)).unwrap();
assert_eq!(invoke(&peer, "remote_idle_timeout_minutes", json!({})).await.unwrap(), 0);
}
let disconnect = std::time::Instant::now();
peer.kill();
peer.exited().await;
if never {
assert!(
tokio::time::timeout(Duration::from_secs(72), daemon.wait()).await.is_err(),
"Never expired at the previous one-minute timeout"
);
let (resumed, _) = attach_client(&home, &base, "~/demo", 1);
assert!(!invoke(&resumed, "project_current", json!({})).await.unwrap().is_null());
shutdown(&resumed).await;
}
let status =
tokio::time::timeout(Duration::from_secs(80), daemon.wait()).await.expect("saved timeout not used").unwrap();
assert!(status.success());
assert!(disconnect.elapsed() >= Duration::from_secs(60), "daemon stopped before the configured minute");
assert!(!guard.0.exists());
}
async fn looping_terminal(peer: &Peer, project: &Path) -> Value {
invoke(
peer,
"term_spawn",
json!({
"options": {
"cwd": project, "shell": "/bin/sh", "args": ["-c", "exec sleep 300"],
"env": {}, "cols": 80, "rows": 24, "shellIntegration": false
},
"onOutput": { "$channel": 1 }
}),
)
.await
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_takeover_notifies_the_first_window_and_keeps_its_terminal() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
let _guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let (first, original) = attach_client(&home, &base, "~/demo", 1);
initialize(&first).await;
invoke(&first, "open_project", json!({ "path": project })).await.unwrap();
invoke(&first, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
let term = looping_terminal(&first, &project).await;
let (second, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&second).await;
tokio::time::timeout(Duration::from_secs(5), first.closed()).await.expect("first window was not disconnected");
assert!(original.taken_over.load(Ordering::Acquire), "the first window saw an unexplained EOF");
assert_eq!(invoke(&second, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
second.kill();
second.exited().await;
tokio::time::sleep(Duration::from_millis(2300)).await;
let (third, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&third).await;
assert_eq!(invoke(&third, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
shutdown(&third).await;
until("terminal child stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
const OLD_BUILD: &str = "0123456789abcdef";
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let mut previous_build = tokio::process::Command::new(SERVER)
.arg("--daemon")
.arg(&guard.0)
.arg(OLD_BUILD)
.envs(server_env(&home, &base, 10_800))
.kill_on_drop(true)
.spawn()
.unwrap();
until("old backend socket", || guard.0.exists()).await;
let old_open = || async {
let mut stream = UnixStream::connect(&guard.0).await.unwrap();
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
assert_eq!(stream.read_u8().await.unwrap(), b'A');
let (reader, writer) = stream.into_split();
Peer::connect(reader, writer, Arc::new(Client::default()))
};
let old = old_open().await;
initialize(&old).await;
invoke(&old, "open_project", json!({ "path": project })).await.unwrap();
invoke(&old, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
let term = looping_terminal(&old, &project).await;
old.kill();
old.closed().await;
let rejected = tokio::time::timeout(
Duration::from_secs(15),
tokio::process::Command::new(SERVER)
.args(["--attach", "~/demo"])
.envs(server_env(&home, &base, 10_800))
.kill_on_drop(true)
.output(),
)
.await
.unwrap()
.unwrap();
assert!(!rejected.status.success());
assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}");
assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced");
let resumed = old_open().await;
assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
invoke(&resumed, "term_kill", json!({ "id": term["id"] })).await.unwrap();
resumed.kill();
resumed.closed().await;
let (new, _) = attach_client(&home, &base, "~/demo", 10_800);
initialize(&new).await;
let old_exit = tokio::time::timeout(Duration::from_secs(5), previous_build.wait()).await.unwrap().unwrap();
assert!(old_exit.success(), "handoff did not shut down the old daemon cleanly");
assert!(invoke(&new, "project_current", json!({})).await.unwrap().is_null());
shutdown(&new).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires a Docker context with Docker Compose and the busybox image"]
async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("h");
let base = tmp.path().join("s");
let project = home.join("demo");
std::fs::create_dir_all(&project).unwrap();
std::fs::write(
project.join("compose.yml"),
"services:\n worker:\n image: busybox:latest\n command: ['sleep', '300']\n stop_grace_period: 1s\n",
)
.unwrap();
let suffix = tmp.path().file_name().unwrap().to_str().unwrap().trim_start_matches('.').to_ascii_lowercase();
let name = format!("openidea-compose-{suffix}");
let docker = ide_docker::docker_executable().expect("Docker is not installed");
// The test server has its own HOME; keep Docker Desktop's CLI plugins and context accessible.
let docker_config = std::env::var_os("DOCKER_CONFIG")
.map(PathBuf::from)
.unwrap_or_else(|| dirs::home_dir().expect("home").join(".docker"));
struct ComposeCleanup<'a>(&'a Path, &'a Path, &'a str);
impl Drop for ComposeCleanup<'_> {
fn drop(&mut self) {
let _ = std::process::Command::new(self.0)
.current_dir(self.1)
.args(["compose", "-p", self.2, "down", "--timeout", "1"])
.output();
}
}
let _compose = ComposeCleanup(&docker, &project, &name);
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
let compose_ids = |all| {
let mut cmd = tokio::process::Command::new(&docker);
cmd.current_dir(&project).args(["compose", "-p", &name, "ps", "-q"]);
if all {
cmd.arg("-a");
}
async move {
let out = cmd.output().await.unwrap();
assert!(out.status.success(), "docker compose ps: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap().trim().to_owned()
}
};
let (first, client) = attach_client(&home, &base, "~/demo", 1);
initialize(&first).await;
invoke(&first, "open_project", json!({ "path": project })).await.unwrap();
invoke(&first, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
let run = invoke(
&first,
"run_start",
json!({
"config": {
"id": "docker:compose:worker", "name": "Compose worker", "kind": "docker-compose",
"command": docker, "args": ["compose", "-p", name, "up", "--pull", "never"], "cwd": project,
"env": { "DOCKER_CONFIG": docker_config }, "detected": false, "isTest": false,
"stopCommand": format!("{} compose -p {name} down", ide_ssh::shell::quote(docker.to_str().unwrap())),
},
"onOutput": { "$channel": 1 }, "request": 1,
}),
)
.await
.unwrap();
let container = tokio::time::timeout(Duration::from_secs(20), async {
loop {
let id = compose_ids(false).await;
if !id.is_empty() {
break id;
}
tokio::time::sleep(Duration::from_millis(150)).await;
}
})
.await
.unwrap_or_else(|_| panic!("the compose service did not start: {:?}", client.channels.lock()));
first.kill();
first.exited().await;
tokio::time::sleep(Duration::from_millis(2300)).await;
assert_eq!(compose_ids(false).await, container, "close without stop interrupted the compose service");
let (second, _) = attach_client(&home, &base, "~/demo", 1);
initialize(&second).await;
let runs = invoke(&second, "run_list", json!({})).await.unwrap();
assert!(runs.as_array().unwrap().iter().any(|r| r["id"] == run["id"] && r["running"] == true));
shutdown(&second).await;
assert!(!guard.0.exists());
assert!(compose_ids(true).await.is_empty(), "the stop command did not remove the compose service");
}
+9 -24
Переглянути файл
@@ -720,14 +720,6 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution
.await
.unwrap();
assert_eq!(run.await.unwrap(), operation);
let attached = invoke(
&peer,
"term_attach",
json!({"id": terminal["id"], "cols": 80, "rows": 24, "onOutput": {"$channel": 41}}),
)
.await
.unwrap();
assert_eq!(attached["session"]["id"], terminal["id"]);
invoke(
&peer,
"plugin_run_command",
@@ -737,23 +729,16 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution
.unwrap();
until("PTY exit", 5, || client.events.lock().iter().any(|m| matches!(m.event, IdeEvent::TerminalExited { .. })))
.await;
let received = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let received = invoke(
&peer,
"plugin_run_command",
json!({"pluginId": "execution", "commandId": "events", "arg": null, "editor": null}),
)
.await
.unwrap();
if let Some(events) = received.as_str() {
break serde_json::from_str::<Value>(events).unwrap();
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
plugins.host().flush_events_at(std::time::Instant::now() + Duration::from_secs(3));
plugins.host().wait_events(Duration::from_secs(5));
let received = invoke(
&peer,
"plugin_run_command",
json!({"pluginId": "execution", "commandId": "events", "arg": null, "editor": null}),
)
.await
.expect("plugin terminal completion after reattach");
.unwrap();
let received: Value = serde_json::from_str(received.as_str().unwrap()).unwrap();
assert_eq!(received.as_array().unwrap().len(), 1);
assert_eq!(received[0]["kind"], "terminal-exited");
let data: Value = serde_json::from_str(received[0]["data"].as_str().unwrap()).unwrap();
-1
Переглянути файл
@@ -30,7 +30,6 @@ async fn storage_requires_a_registered_terminal() {
"main".into(),
Arc::new(NullSink),
Box::new(|_| {}),
None,
)
.unwrap();
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
+4 -37
Переглянути файл
@@ -250,13 +250,8 @@ impl Handler for NoopHandler {
type Pending = HashMap<i64, oneshot::Sender<Result<Value, RpcError>>>;
enum Outgoing {
Message(Vec<u8>),
Flush(oneshot::Sender<()>),
}
struct Inner {
out: mpsc::UnboundedSender<Outgoing>,
out: mpsc::UnboundedSender<Vec<u8>>,
pending: Mutex<Pending>,
next_id: AtomicI64,
/// Set once the transport is gone; new requests fail fast.
@@ -280,7 +275,7 @@ impl Inner {
}
let body = serde_json::to_vec(value).map_err(|e| RpcError::Protocol(e.to_string()))?;
tracing::trace!(target: "ide_jsonrpc::wire", "--> {}", String::from_utf8_lossy(&body));
self.out.send(Outgoing::Message(body)).map_err(|_| RpcError::Closed)
self.out.send(body).map_err(|_| RpcError::Closed)
}
/// Fails every in-flight request and refuses new ones.
@@ -484,20 +479,6 @@ impl Peer {
Self::start(reader, writer, handler, true, None, Framing::ContentLength, None)
}
/// Like [`Peer::connect`], with diagnostics from a launcher sharing the stdout stream.
pub fn connect_with_output<R, W>(
reader: R,
writer: W,
handler: Arc<dyn Handler>,
on_output: impl Fn(String) + Send + Sync + 'static,
) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None, Framing::ContentLength, Some(Arc::new(on_output)))
}
/// [`connect`](Self::connect) with the given wire framing.
pub fn connect_framed<R, W>(reader: R, writer: W, handler: Arc<dyn Handler>, framing: Framing) -> Self
where
@@ -539,7 +520,7 @@ impl Peer {
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
let (out_tx, mut out_rx) = mpsc::unbounded_channel();
let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
let (closed, _) = watch::channel(None);
let inner = Arc::new(Inner {
out: out_tx,
@@ -566,14 +547,7 @@ impl Peer {
body = out_rx.recv() => body,
_ = kill.cancelled() => None,
};
let body = match body {
Some(Outgoing::Message(body)) => body,
Some(Outgoing::Flush(done)) => {
let _ = done.send(());
continue;
}
None => break,
};
let Some(body) = body else { break };
if let Err(e) = framing.write(&mut writer, &body).await {
tracing::debug!("jsonrpc write failed: {e}");
if let Some(inner) = weak.upgrade() {
@@ -732,13 +706,6 @@ impl Peer {
self.inner.send_value(&msg)
}
/// Waits until previously queued messages have been written.
pub async fn flush(&self) -> Result<(), RpcError> {
let (tx, rx) = oneshot::channel();
self.inner.out.send(Outgoing::Flush(tx)).map_err(|_| RpcError::Closed)?;
rx.await.map_err(|_| RpcError::Closed)
}
/// Resolves when the connection closes (process exit or EOF), with the exit code if known.
pub async fn closed(&self) -> Option<i32> {
let mut rx = self.inner.closed.subscribe();
-9
Переглянути файл
@@ -242,15 +242,6 @@ pub struct RunInfo {
pub pty: bool,
}
/// Snapshot and live output binding returned when reattaching to a running process.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RunAttach {
pub info: RunInfo,
pub config: RunConfig,
pub buffered: Vec<OutputChunk>,
}
pub use external::{EXTERNAL_PREFIX, ExternalDetection, set_external_detection};
/// Detects configs from package.json scripts, Cargo.toml targets, build.gradle(.kts),
+26 -134
Переглянути файл
@@ -2,11 +2,11 @@
//! for "Emulate terminal in output console"), stream output, stdin, stop.
use crate::utf8::OutputDecoder;
use crate::{OutputChunk, RunAttach, RunConfig, RunInfo};
use crate::{OutputChunk, RunConfig, RunInfo};
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
use parking_lot::Mutex;
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use std::collections::{BTreeMap, VecDeque};
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
@@ -32,43 +32,11 @@ const STOP_GRACE: Duration = Duration::from_secs(3);
const STOP_COMMAND_TIMEOUT: Duration = Duration::from_secs(60);
/// Finished runs kept for [`ProcessManager::list`].
const MAX_FINISHED: usize = 20;
/// Bounded console scrollback retained per run for reattaching across window reconnects.
const MAX_BUFFERED_OUTPUT: usize = 256 * 1024;
/// PTY size until the console reports its own.
const DEFAULT_PTY: (u16, u16) = (120, 30);
type OutputFn = Arc<dyn Fn(OutputChunk) + Send + Sync>;
struct RunOutputState {
buffered: VecDeque<OutputChunk>,
buffered_bytes: usize,
on_output: OutputFn,
}
impl RunOutputState {
fn new(on_output: OutputFn) -> Self {
Self { buffered: VecDeque::new(), buffered_bytes: 0, on_output }
}
fn emit(&mut self, chunk: OutputChunk) {
let len = chunk_len(&chunk);
self.buffered_bytes += len;
self.buffered.push_back(chunk.clone());
while self.buffered_bytes > MAX_BUFFERED_OUTPUT && self.buffered.len() > 1 {
if let Some(removed) = self.buffered.pop_front() {
self.buffered_bytes = self.buffered_bytes.saturating_sub(chunk_len(&removed));
}
}
(self.on_output)(chunk);
}
}
fn chunk_len(chunk: &OutputChunk) -> usize {
match chunk {
OutputChunk::Stdout { text } | OutputChunk::Stderr { text } | OutputChunk::System { text } => text.len(),
}
}
/// Environment of a launched process: the inherited one (unless cleared) plus `vars`.
#[derive(Clone, Debug, Default)]
struct LaunchEnv {
@@ -86,7 +54,6 @@ struct StopCommand {
struct Entry {
project_root: PathBuf,
id: RunId,
config: RunConfig,
config_id: String,
name: String,
pid: Mutex<Option<u32>>,
@@ -100,18 +67,13 @@ struct Entry {
#[cfg(windows)]
job: Option<ide_core::process::Job>,
stop: Option<StopCommand>,
output: Mutex<RunOutputState>,
sink: Mutex<SharedSink>,
output: OutputFn,
exited: AtomicBool,
code: Mutex<Option<i32>>,
stopping: AtomicBool,
}
impl Entry {
fn emit_output(&self, chunk: OutputChunk) {
self.output.lock().emit(chunk);
}
fn info(&self) -> RunInfo {
RunInfo {
id: self.id,
@@ -517,7 +479,6 @@ impl ProcessManager {
let entry = Arc::new(Entry {
project_root: root.to_path_buf(),
id,
config: config.clone(),
config_id: config.id.clone(),
name: config.name.clone(),
pid: Mutex::new(Some(child.id())),
@@ -526,15 +487,14 @@ impl ProcessManager {
#[cfg(windows)]
job,
stop,
output: Mutex::new(RunOutputState::new(on_output)),
sink: Mutex::new(sink),
output: on_output.clone(),
exited: AtomicBool::new(false),
code: Mutex::new(None),
stopping: AtomicBool::new(false),
});
self.register(entry.clone());
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let (tx, rx) = output_queue();
let stdout = child.stdout.take();
@@ -561,7 +521,7 @@ impl ProcessManager {
)?;
}
let decoder = || OutputDecoder::for_pipes(options.encoding.as_deref());
spawn_pump(rx, entry.clone(), [decoder(), decoder()], notice)?;
spawn_pump(rx, on_output.clone(), entry.clone(), sink, [decoder(), decoder()], notice)?;
Ok(())
})();
if let Err(e) = result {
@@ -666,7 +626,6 @@ impl ProcessManager {
let entry = Arc::new(Entry {
project_root: root.to_path_buf(),
id,
config: config.clone(),
config_id: config.id.clone(),
name: config.name.clone(),
pid: Mutex::new(child.process_id()),
@@ -676,14 +635,13 @@ impl ProcessManager {
#[cfg(windows)]
job: child.process_id().and_then(ide_core::process::Job::for_pid),
stop,
output: Mutex::new(RunOutputState::new(on_output)),
sink: Mutex::new(sink),
output: on_output.clone(),
exited: AtomicBool::new(false),
code: Mutex::new(None),
stopping: AtomicBool::new(false),
});
self.register(entry.clone());
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let (tx, rx) = output_queue();
let result = spawn_reader(
@@ -696,7 +654,7 @@ impl ProcessManager {
)
.and_then(|_| {
let decoder = || OutputDecoder::for_label(options.encoding.as_deref());
spawn_pump(rx, entry.clone(), [decoder(), decoder()], None)
spawn_pump(rx, on_output, entry.clone(), sink, [decoder(), decoder()], None)
});
if let Err(e) = result {
let _ = child.kill();
@@ -805,7 +763,7 @@ impl ProcessManager {
!group_alive(pid, &entry)
};
if let Some(stop) = &entry.stop {
run_stop_command(stop, &entry);
run_stop_command(stop, &entry.output);
if exits_within(grace) {
return;
}
@@ -842,40 +800,6 @@ impl ProcessManager {
live.map(|e| e.info()).collect()
}
pub fn has_live_runs(&self) -> bool {
self.runs.lock().values().any(|entry| {
!entry.exited.load(Ordering::Acquire) || entry.pid.lock().is_some_and(|pid| group_alive(pid, entry))
})
}
/// Rebinds `id`'s output stream to `on_output`, returning its buffered console chunks
/// and configuration without dropping or duplicating output.
pub fn reattach(
&self,
id: RunId,
sink: SharedSink,
on_output: Box<dyn Fn(OutputChunk) + Send + Sync>,
) -> IdeResult<RunAttach> {
let entry = self.entry(id)?;
*entry.sink.lock() = sink;
let buffered = {
let mut out = entry.output.lock();
let chunks: Vec<OutputChunk> = out.buffered.iter().cloned().collect();
out.on_output = Arc::from(on_output);
chunks
};
Ok(RunAttach { info: entry.info(), config: entry.config.clone(), buffered })
}
/// Drops live client output callbacks when a remote window disconnects, keeping
/// running processes and their console ring buffers alive.
pub fn detach_output(&self) {
let entries: Vec<Arc<Entry>> = self.runs.lock().values().cloned().collect();
for entry in entries {
entry.output.lock().on_output = Arc::new(|_| {});
}
}
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
for entry in self.runs.lock().values().filter(|e| e.project_root == root) {
@@ -897,34 +821,6 @@ impl ProcessManager {
}
}
}
/// Honor external service stop actions (for example `docker compose down`) before
/// forcing run processes to exit.
pub async fn shutdown(&self) {
let entries: Vec<_> = self.runs.lock().values().cloned().collect();
let mut stops = tokio::task::JoinSet::new();
for entry in entries {
let Some(pid) = *entry.pid.lock() else { continue };
if entry.exited.load(Ordering::Acquire) && !group_alive(pid, &entry) {
continue;
}
stops.spawn_blocking(move || {
if !entry.stopping.swap(true, Ordering::AcqRel)
&& let Some(stop) = &entry.stop
{
run_stop_command(stop, &entry);
}
if group_alive(pid, &entry) {
kill_tree(&entry, pid, true);
}
});
}
while let Some(result) = stops.join_next().await {
if let Err(e) = result {
tracing::warn!("could not stop a run during shutdown: {e}");
}
}
}
}
impl Drop for ProcessManager {
@@ -969,7 +865,7 @@ fn run_followup(
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0000_0200 | ide_core::process::CREATE_NO_WINDOW);
}
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
(entry.output)(OutputChunk::System { text: format!("{}\n", inv.display) });
let mut child = cmd.spawn()?;
// The follow-up run continues the same launch: it joins the run's job, so a Stop
// reaches its tree too.
@@ -1101,12 +997,11 @@ fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
/// Runs `stop.line` through the platform shell and waits for it (bounded), echoing it
/// and any error output to the console.
fn run_stop_command(stop: &StopCommand, entry: &Entry) {
entry.emit_output(OutputChunk::System { text: format!("{}\n", stop.line) });
fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
output(OutputChunk::System { text: format!("{}\n", stop.line) });
let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok());
let mut cmd = Command::new(&inv.program);
ide_core::process::prepare(&mut cmd);
ide_core::process::own_group(&mut cmd);
if inv.raw_args {
add_raw_args(&mut cmd, &inv.args);
} else {
@@ -1117,18 +1012,16 @@ fn run_stop_command(stop: &StopCommand, entry: &Entry) {
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
entry.emit_output(OutputChunk::Stderr { text: format!("Cannot run the stop command: {e}\n") });
output(OutputChunk::Stderr { text: format!("Cannot run the stop command: {e}\n") });
return;
}
};
let stderr = child.stderr.take().map(|mut pipe| {
let (send, receive) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
let _ = send.send(String::from_utf8_lossy(&buf).into_owned());
});
receive
String::from_utf8_lossy(&buf).into_owned()
})
});
let deadline = Instant::now() + STOP_COMMAND_TIMEOUT;
let status = loop {
@@ -1136,17 +1029,15 @@ fn run_stop_command(stop: &StopCommand, entry: &Entry) {
Ok(Some(status)) => break Some(status),
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
_ => {
ide_core::process::kill_tree(&mut child);
let _ = child.kill();
let _ = child.wait();
break None;
}
}
};
if !status.is_some_and(|s| s.success()) {
let err = stderr.and_then(|r| r.recv_timeout(Duration::from_millis(100)).ok()).unwrap_or_default();
let detail = status.map_or_else(|| "timed out".to_string(), |s| s.to_string());
tracing::warn!("run stop command failed: {detail}");
entry.emit_output(OutputChunk::Stderr { text: format!("Stop command failed ({detail})\n{err}") });
let err = stderr.and_then(|h| h.join().ok()).unwrap_or_default();
if !status.is_some_and(|s| s.success()) && !err.trim().is_empty() {
output(OutputChunk::Stderr { text: format!("{}\n", err.trim_end()) });
}
}
@@ -1302,7 +1193,9 @@ fn emit(
/// `decoders` decode stdout and stderr.
fn spawn_pump(
rx: mpsc::Receiver<Msg>,
on_output: OutputFn,
entry: Arc<Entry>,
sink: SharedSink,
decoders: [OutputDecoder; 2],
notice: Option<String>,
) -> std::io::Result<()> {
@@ -1323,7 +1216,7 @@ fn spawn_pump(
let flush = |pending: &mut String, stream: Stream, started: &mut Option<Instant>| {
if !pending.is_empty() {
entry.emit_output(chunk(stream, std::mem::take(pending)));
on_output(chunk(stream, std::mem::take(pending)));
}
*started = None;
};
@@ -1403,12 +1296,12 @@ fn spawn_pump(
rest.push_str(&filter.finish());
}
if !rest.is_empty() {
entry.emit_output(chunk(stream, rest));
on_output(chunk(stream, rest));
}
}
let (code, message) = describe_exit(status);
entry.emit_output(OutputChunk::System { text: format!("\n{message}\n") });
on_output(OutputChunk::System { text: format!("\n{message}\n") });
entry.stdin.lock().take();
if let Some(pty) = &entry.pty {
pty.lock().take();
@@ -1440,8 +1333,7 @@ fn spawn_pump(
*entry.code.lock() = code;
entry.exited.store(true, Ordering::Release);
tracing::debug!(id = %entry.id, ?code, "run exited");
let target_sink = entry.sink.lock().clone();
target_sink.emit(IdeEvent::RunExited { run: entry.id, code });
sink.emit(IdeEvent::RunExited { run: entry.id, code });
})?;
Ok(())
}
+4 -60
Переглянути файл
@@ -1,5 +1,5 @@
//! An in-process SSH server for tests (feature `testing`): password `dev` /
//! `secret`, commands answered by a closure or an explicitly allowed process, SFTP served from a local
//! `secret`, commands answered by a closure, SFTP served from a local
//! folder (remote `/x` is `<root>/x`), and a shell that echoes its input
//! (`exit` ends it with status 0). `direct-tcpip` channels are forwarded to local TCP
//! ports, and refused when nothing listens there.
@@ -10,34 +10,15 @@ use russh_sftp::protocol::{Attrs, Data, File, FileAttributes, Handle, Name, Open
use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::process::Command;
use tokio::sync::Mutex;
/// Reply of a command: (stdout, exit status).
pub type ExecFn = Arc<dyn Fn(&str) -> (String, u32) + Send + Sync>;
type SpawnFn = Arc<dyn Fn(&str) -> Option<Command> + Send + Sync>;
#[derive(Clone)]
enum Exec {
Reply(ExecFn),
Process(SpawnFn),
}
/// Starts the server; returns its port. `root` backs SFTP.
pub async fn sshd(root: PathBuf, exec: ExecFn) -> u16 {
start(root, Exec::Reply(exec)).await
}
/// Serves stdio of an explicitly chosen command over an SSH exec channel.
pub async fn sshd_with_process(root: PathBuf, exec: impl Fn(&str) -> Option<Command> + Send + Sync + 'static) -> u16 {
start(root, Exec::Process(Arc::new(exec))).await
}
async fn start(root: PathBuf, exec: Exec) -> u16 {
let config = Arc::new(server::Config {
keys: vec![russh::keys::decode_secret_key(include_str!("../tests/fixtures/ssh/host"), None).expect("host key")],
auth_rejection_time: std::time::Duration::from_millis(10),
@@ -56,7 +37,7 @@ async fn start(root: PathBuf, exec: Exec) -> u16 {
#[derive(Clone)]
struct Sshd {
root: PathBuf,
exec: Exec,
exec: ExecFn,
}
impl server::Server for Sshd {
@@ -68,7 +49,7 @@ impl server::Server for Sshd {
struct Conn {
root: PathBuf,
exec: Exec,
exec: ExecFn,
channels: Arc<Mutex<HashMap<ChannelId, Channel<Msg>>>>,
shells: std::collections::HashSet<ChannelId>,
}
@@ -118,44 +99,7 @@ impl server::Handler for Conn {
data: &[u8],
session: &mut Session,
) -> Result<(), Self::Error> {
let command = String::from_utf8_lossy(data);
let Exec::Reply(exec) = &self.exec else {
let Exec::Process(spawn) = &self.exec else { unreachable!() };
let Some(ch) = self.channels.lock().await.remove(&channel) else {
session.channel_failure(channel)?;
return Ok(());
};
let Some(mut cmd) = spawn(&command) else {
session.channel_failure(channel)?;
return Ok(());
};
let mut child = cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).kill_on_drop(true).spawn()?;
let mut input = child.stdin.take().expect("piped stdin");
let mut output = child.stdout.take().expect("piped stdout");
session.channel_success(channel)?;
tokio::spawn(async move {
let (mut reader, mut writer) = tokio::io::split(ch.into_stream());
let feed = async {
let _ = tokio::io::copy(&mut reader, &mut input).await;
drop(input);
};
let drain = async {
let _ = tokio::io::copy(&mut output, &mut writer).await;
let _ = writer.shutdown().await;
};
tokio::pin!(drain);
// EOF from the SSH client closes the child stdin; EOF from the child completes the channel.
tokio::select! {
_ = &mut drain => {}
_ = feed => {
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), &mut drain).await;
}
}
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), child.wait()).await;
});
return Ok(());
};
let (out, code) = exec(&command);
let (out, code) = (self.exec)(&String::from_utf8_lossy(data));
session.channel_success(channel)?;
session.data(channel, out.into_bytes())?;
session.exit_status_request(channel, code)?;
+25 -203
Переглянути файл
@@ -2,7 +2,6 @@
//! such as an SSH shell. Rendering is xterm.js.
mod integration;
mod scrollback;
use ide_core::utf8::Utf8Decoder;
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId};
@@ -131,26 +130,6 @@ pub struct TerminalInfo {
pub pid: Option<u32>,
}
/// Live terminal session state for reattaching across window reconnects.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TerminalSessionInfo {
pub id: TerminalId,
pub title: String,
pub pid: Option<u32>,
pub cwd: String,
pub app_title: Option<String>,
pub command_running: bool,
}
/// Snapshot and live binding returned when reattaching to an existing session.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct TerminalAttach {
pub session: TerminalSessionInfo,
pub buffered: String,
}
/// A terminal whose shell runs elsewhere (an SSH channel). Its output and exit
/// arrive through the [`TerminalFeed`] paired with it by [`feed`].
pub trait TerminalChannel: Send + Sync {
@@ -228,18 +207,11 @@ enum Io {
},
}
struct OutputState {
scrollback: scrollback::Scrollback,
on_output: Box<dyn Fn(String) + Send>,
}
struct Session {
/// The window that opened it: closing that window's project closes its terminals.
key: String,
info: TerminalInfo,
io: Io,
output: Arc<Mutex<OutputState>>,
sink: Arc<Mutex<SharedSink>>,
exited: Arc<AtomicBool>,
started: Instant,
/// The first input was logged (startup diagnostics, see `spawn`).
@@ -258,9 +230,6 @@ enum Msg {
Exited(Option<i32>),
}
/// Runs when a PTY exits, before the exit event is forwarded to the current sink.
pub type TerminalExitHook = Arc<dyn Fn(Option<i32>) + Send + Sync>;
impl TerminalManager {
pub fn new() -> Self {
Self::default()
@@ -268,16 +237,15 @@ impl TerminalManager {
/// Starts a shell; output goes to `on_output` from a reader thread, batched
/// (~4ms) to limit IPC chatter and always split on UTF-8 boundaries.
/// Calls `on_exit` if supplied and emits `IdeEvent::TerminalExited` to the current sink.
/// Emits `IdeEvent::TerminalExited` to `sink` (the starter's) only.
pub fn spawn(
&self,
options: TerminalOptions,
key: String,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
on_exit: Option<TerminalExitHook>,
) -> IdeResult<TerminalInfo> {
self.spawn_impl(options, key, sink, on_output, on_exit, false)
self.spawn_impl(options, key, sink, on_output, false)
}
/// Runs an approved absolute executable with exact arguments and cwd.
@@ -288,7 +256,6 @@ impl TerminalManager {
key: String,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
on_exit: Option<TerminalExitHook>,
) -> IdeResult<TerminalInfo> {
if !options.shell.as_deref().is_some_and(|p| Path::new(p).is_absolute())
|| !options.cwd.is_absolute()
@@ -296,7 +263,7 @@ impl TerminalManager {
{
return Err(IdeError::invalid("a program PTY requires an absolute executable and an existing cwd"));
}
self.spawn_impl(options, key, sink, on_output, on_exit, true)
self.spawn_impl(options, key, sink, on_output, true)
}
fn spawn_impl(
@@ -305,7 +272,6 @@ impl TerminalManager {
key: String,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
on_exit: Option<TerminalExitHook>,
exact: bool,
) -> IdeResult<TerminalInfo> {
let size = pty_size(options.cols, options.rows);
@@ -385,17 +351,10 @@ impl TerminalManager {
let _ = child.kill();
let _ = child.wait();
})?;
let output = Arc::new(Mutex::new(OutputState {
scrollback: scrollback::Scrollback::new(cwd.to_string_lossy().into_owned()),
on_output,
}));
let sink = Arc::new(Mutex::new(sink));
let session = Arc::new(Session {
key,
info: info.clone(),
io: Io::Pty { writer, master: Mutex::new(pair.master), killer: Mutex::new(child.clone_killer()) },
output: output.clone(),
sink: sink.clone(),
exited: exited.clone(),
started: Instant::now(),
input_logged: AtomicBool::new(false),
@@ -404,7 +363,7 @@ impl TerminalManager {
let (tx, rx) = mpsc::channel::<Msg>();
let budget = ByteBudget::default();
let out = OutputSender { tx, budget: budget.clone() };
let out = OutputSender { tx: tx.clone(), budget: budget.clone() };
let spawned = spawn_reader(
id,
reader,
@@ -416,16 +375,15 @@ impl TerminalManager {
.and_then(|_| {
spawn_pump(
id,
OutputReceiver { rx, budget: budget.clone() },
output,
OutputReceiver { rx, budget },
on_output,
exited,
self.sessions.clone(),
sink,
on_exit,
Instant::now(),
)
});
if let Err(e) = spawned {
budget.close();
if let Some(s) = self.sessions.lock().remove(&id) {
terminate(&s);
}
@@ -453,23 +411,18 @@ impl TerminalManager {
let id = TerminalId::next();
let info = TerminalInfo { id, title, pid: None };
let exited = Arc::new(AtomicBool::new(false));
let output =
Arc::new(Mutex::new(OutputState { scrollback: scrollback::Scrollback::new(String::new()), on_output }));
let sink = Arc::new(Mutex::new(sink));
let session = Arc::new(Session {
key,
info: info.clone(),
io: Io::Channel { channel, size: Mutex::new(size) },
output: output.clone(),
sink: sink.clone(),
exited: exited.clone(),
started: Instant::now(),
input_logged: AtomicBool::new(false),
});
self.sessions.lock().insert(id, session);
let receiver = feed.into_parts();
let budget = receiver.budget.clone();
if let Err(e) = spawn_pump(id, receiver, output, exited, self.sessions.clone(), sink, None) {
let output = feed.into_parts();
let budget = output.budget.clone();
if let Err(e) = spawn_pump(id, output, on_output, exited, self.sessions.clone(), sink, Instant::now()) {
budget.close();
if let Some(s) = self.sessions.lock().remove(&id) {
terminate(&s);
@@ -547,85 +500,6 @@ impl TerminalManager {
out
}
/// Live sessions belonging to `key`, with their current working directory,
/// running-program title and busy state.
pub fn list_key(&self, key: &str) -> Vec<TerminalSessionInfo> {
let sessions: Vec<Arc<Session>> = self
.sessions
.lock()
.values()
.filter(|s| s.key == key && !s.exited.load(Ordering::Acquire))
.cloned()
.collect();
let mut out: Vec<TerminalSessionInfo> = sessions.iter().map(|s| session_info(s)).collect();
out.sort_by_key(|i| i.id);
out
}
/// Rebinds `id`'s output stream to `on_output`, returning its buffered scrollback
/// and current state without dropping or duplicating bytes between them.
pub fn reattach(
&self,
id: TerminalId,
key: &str,
cols: u16,
rows: u16,
sink: SharedSink,
on_output: Box<dyn Fn(String) + Send>,
) -> IdeResult<TerminalAttach> {
let session = self.session(id)?;
if session.key != key || session.exited.load(Ordering::Acquire) {
return Err(not_found(id));
}
*session.sink.lock() = sink;
let (buffered, cwd, app_title, osc_running, alt_screen) = {
let mut out = session.output.lock();
let buffered = out.scrollback.snapshot();
let cwd = out.scrollback.cwd.clone();
let app_title = out.scrollback.app_title.clone();
let osc_running = out.scrollback.command_running;
let alt_screen = out.scrollback.is_alt_screen();
out.on_output = on_output;
(buffered, cwd, app_title, osc_running, alt_screen)
};
if cols > 0 && rows > 0 {
let _ = self.resize(id, cols, rows);
}
#[cfg(unix)]
if alt_screen
&& let Io::Pty { master, .. } = &session.io
&& let Some(fg) = master.lock().process_group_leader().filter(|&fg| fg > 0)
{
// Full-screen TUIs (`watch`, `vim`, `htop`) repaint on SIGWINCH even when cols×rows matched.
unsafe {
libc::kill(-fg, libc::SIGWINCH);
}
}
#[cfg(not(unix))]
let _ = alt_screen;
let busy = session.info.pid.is_some_and(|pid| foreground_busy(&session, pid));
Ok(TerminalAttach {
session: TerminalSessionInfo {
id: session.info.id,
title: session.info.title.clone(),
pid: session.info.pid,
cwd,
app_title,
command_running: osc_running || busy,
},
buffered,
})
}
/// Drops live client output callbacks when a remote window disconnects, while
/// keeping the PTYs and their scrollback buffers running.
pub fn detach_output(&self) {
let sessions: Vec<Arc<Session>> = self.sessions.lock().values().cloned().collect();
for s in sessions {
s.output.lock().on_output = Box::new(|_| {});
}
}
/// Current PTY size of a session (for diagnostics and tests).
pub fn size(&self, id: TerminalId) -> IdeResult<(u16, u16)> {
let session = self.session(id)?;
@@ -837,44 +711,25 @@ fn spawn_waiter(
Ok(())
}
fn session_info(session: &Session) -> TerminalSessionInfo {
let (cwd, app_title, osc_running) = {
let out = session.output.lock();
(out.scrollback.cwd.clone(), out.scrollback.app_title.clone(), out.scrollback.command_running)
};
let busy = session.info.pid.is_some_and(|pid| foreground_busy(session, pid));
TerminalSessionInfo {
id: session.info.id,
title: session.info.title.clone(),
pid: session.info.pid,
cwd,
app_title,
command_running: osc_running || busy,
}
}
fn spawn_pump(
id: TerminalId,
receiver: OutputReceiver,
output: Arc<Mutex<OutputState>>,
output: OutputReceiver,
on_output: Box<dyn Fn(String) + Send>,
exited: Arc<AtomicBool>,
sessions: Sessions,
sink: Arc<Mutex<SharedSink>>,
on_exit: Option<TerminalExitHook>,
sink: SharedSink,
started: Instant,
) -> std::io::Result<()> {
let started = Instant::now();
std::thread::Builder::new().name(format!("openidea-term-pump-{}", id.0)).spawn(move || {
let first_output = std::cell::Cell::new(true);
let emit_output = |text: String| {
let on_output = move |text: String| {
if first_output.replace(false) {
// ConPTY asks for the cursor position (`ESC[6n`) and waits for the answer.
let cursor_query = text.contains("\x1b[6n");
let ms = started.elapsed().as_millis();
tracing::info!(%id, ms, bytes = text.len(), cursor_query, "terminal first output");
}
let mut out = output.lock();
out.scrollback.push(&text);
(out.on_output)(text);
on_output(text)
};
let mut decoder = Utf8Decoder::new();
let mut pending = String::new();
@@ -884,7 +739,7 @@ fn spawn_pump(
let flush = |pending: &mut String, batch_started: &mut Option<Instant>| {
if !pending.is_empty() {
emit_output(std::mem::take(pending));
on_output(std::mem::take(pending));
}
*batch_started = None;
};
@@ -898,10 +753,10 @@ fn spawn_pump(
(Some(a), None) | (None, Some(a)) => a,
(None, None) => Duration::from_secs(3600),
};
match receiver.rx.recv_timeout(wait) {
match output.rx.recv_timeout(wait) {
Ok(Msg::Data(bytes)) => {
// The pump owns these bytes now; wake any producer waiting on the cap.
receiver.budget.release(bytes.len());
output.budget.release(bytes.len());
decoder.decode_into(&bytes, &mut pending);
if !pending.is_empty() && batch_started.is_none() {
batch_started = Some(Instant::now());
@@ -928,15 +783,11 @@ fn spawn_pump(
pending.push_str(&decoder.finish());
flush(&mut pending, &mut batch_started);
exited.store(true, Ordering::Release);
receiver.budget.close();
output.budget.close();
sessions.lock().remove(&id);
let code = exit.flatten();
tracing::debug!(%id, ?code, "terminal exited");
let target_sink = sink.lock().clone();
if let Some(on_exit) = on_exit {
on_exit(code);
}
target_sink.emit(IdeEvent::TerminalExited { terminal: id, code });
sink.emit(IdeEvent::TerminalExited { terminal: id, code });
})?;
Ok(())
}
@@ -1275,7 +1126,6 @@ mod tests {
Box::new(move |s| {
let _ = tx.send(s);
}),
None,
)
.expect("spawn");
(info, rx)
@@ -1342,14 +1192,14 @@ mod tests {
let h = harness();
let mut options = sh("exit 0");
options.shell = None;
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).is_err());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {})).is_err());
let mut options = sh("exit 0");
options.shell = Some("sh".into());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).is_err());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {})).is_err());
let mut options = sh("exit 0");
options.cwd = std::env::temp_dir().join(format!("openidea-missing-{}", std::process::id())).into();
assert!(!options.cwd.exists());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).is_err());
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {})).is_err());
assert!(h.manager.list().is_empty());
}
@@ -1479,7 +1329,7 @@ mod tests {
let h = harness();
let (other_sink, other_events) = channel_sink();
let (mine, _rx) = spawn_collect(&h, sh("exit 1"));
let theirs = h.manager.spawn(sh("exit 2"), "other".into(), other_sink, Box::new(|_| {}), None).expect("spawn");
let theirs = h.manager.spawn(sh("exit 2"), "other".into(), other_sink, Box::new(|_| {})).expect("spawn");
match h.events.recv_timeout(Duration::from_secs(10)).expect("exit event") {
IdeEvent::TerminalExited { terminal, code } => assert_eq!((terminal, code), (mine.id, Some(1))),
e => panic!("unexpected {e:?}"),
@@ -1492,34 +1342,6 @@ mod tests {
assert!(h.events.try_recv().is_err() && other_events.try_recv().is_err(), "no cross delivery");
}
#[test]
fn reattach_keeps_the_program_exit_hook_and_rebinds_the_event_sink() {
let h = harness();
let (completion, completed) = mpsc::channel();
let info = h
.manager
.spawn_program(
sh("read _; exit 7"),
"test".into(),
h.sink.clone(),
Box::new(|_| {}),
Some(Arc::new(move |code| {
let _ = completion.send(code);
})),
)
.unwrap();
let (sink, events) = channel_sink();
h.manager.reattach(info.id, "test", 80, 24, sink, Box::new(|_| {})).unwrap();
h.manager.write(info.id, "\n").unwrap();
match events.recv_timeout(Duration::from_secs(10)).expect("exit event after reattach") {
IdeEvent::TerminalExited { terminal, code } => assert_eq!((terminal, code), (info.id, Some(7))),
e => panic!("unexpected {e:?}"),
}
assert_eq!(completed.try_recv(), Ok(Some(7)));
assert!(h.events.try_recv().is_err(), "exit delivered to the old sink");
}
#[test]
fn wsl_folder_gets_the_distro_shell_unless_one_is_chosen() {
let mut o = sh("true");
-297
Переглянути файл
@@ -1,297 +0,0 @@
//! Bounded UTF-8 scrollback and OSC state tracker so a reattached terminal
//! restores recent output, alternate-screen state, working directory, title
//! and command-running state without gaps.
/// Maximum scrollback retained per live PTY session (256 KiB).
const MAX_SCROLLBACK_BYTES: usize = 256 * 1024;
/// Maximum incomplete OSC sequence buffered across chunks.
const MAX_OSC_TAIL: usize = 2048;
/// PowerShell / OpenIDEA clear-scrollback OSC marker.
const CLEAR_MARKER: &str = "\x1b]133;OpenIDEA;ClearScrollback\x07";
const CLEAR_CSI: &str = "\x1b[3J";
const ALT_ON: [&str; 3] = ["\x1b[?1049h", "\x1b[?1047h", "\x1b[?47h"];
const ALT_OFF: [&str; 3] = ["\x1b[?1049l", "\x1b[?1047l", "\x1b[?47l"];
pub(crate) struct Scrollback {
buf: String,
/// Whether text evicted before `buf` left the terminal on the alternate screen.
evicted_alt_screen: bool,
/// Whether the current terminal state (evicted + `buf`) is on the alternate screen.
alt_screen: bool,
osc_tail: String,
pub cwd: String,
pub app_title: Option<String>,
pub command_running: bool,
}
impl Scrollback {
pub fn new(initial_cwd: String) -> Self {
Self {
buf: String::new(),
evicted_alt_screen: false,
alt_screen: false,
osc_tail: String::new(),
cwd: initial_cwd,
app_title: None,
command_running: false,
}
}
pub fn is_alt_screen(&self) -> bool {
self.alt_screen
}
pub fn push(&mut self, chunk: &str) {
if chunk.is_empty() {
return;
}
self.scan_osc(chunk);
self.alt_screen = scan_alt_screen(self.alt_screen, chunk);
// Honour explicit scrollback clears so `clear` / Cmd+K doesn't replay cleared history.
let mut slice = chunk;
if let Some(idx) = last_clear_end(slice) {
self.buf.clear();
self.evicted_alt_screen = false;
slice = &slice[idx..];
} else if !self.buf.is_empty() {
// Handle a clear marker split across the boundary between `self.buf` and `chunk`.
let tail_start = floor_char_boundary(&self.buf, self.buf.len().saturating_sub(CLEAR_MARKER.len()));
let combined = format!("{}{}", &self.buf[tail_start..], slice);
if let Some(idx) = last_clear_end(&combined) {
let tail_len = self.buf.len() - tail_start;
self.buf.clear();
self.evicted_alt_screen = false;
if idx > tail_len {
slice = &slice[idx - tail_len..];
} else {
slice = "";
}
}
}
self.buf.push_str(slice);
if self.buf.len() > MAX_SCROLLBACK_BYTES {
let mut cut = self.buf.len() - MAX_SCROLLBACK_BYTES;
while cut < self.buf.len() && !self.buf.is_char_boundary(cut) {
cut += 1;
}
// Avoid slicing inside a short CSI/ESC sequence near `cut`.
cut = avoid_mid_escape(&self.buf, cut);
if cut > 0 {
self.evicted_alt_screen = scan_alt_screen(self.evicted_alt_screen, &self.buf[..cut]);
self.buf.drain(..cut);
}
}
}
/// Buffered output to replay into a freshly attached xterm.js instance.
pub fn snapshot(&self) -> String {
if self.evicted_alt_screen {
let mut out = String::with_capacity("\x1b[?1049h".len() + self.buf.len());
out.push_str("\x1b[?1049h");
out.push_str(&self.buf);
out
} else {
self.buf.clone()
}
}
fn scan_osc(&mut self, chunk: &str) {
if self.osc_tail.is_empty() && !chunk.contains("\x1b]") {
return;
}
let mut combined = std::mem::take(&mut self.osc_tail);
combined.push_str(chunk);
let bytes = combined.as_bytes();
let mut i = 0;
while i < bytes.len() {
let Some(rel) = find_osc_start(&bytes[i..]) else {
// Keep a trailinglone ESC in case `]` arrives in the next chunk.
if bytes.last() == Some(&0x1b) {
self.osc_tail.push('\x1b');
}
return;
};
let start = i + rel;
let body_start = start + 2;
if let Some((body_end, next_i)) = find_osc_end(bytes, body_start) {
if let Ok(body) = std::str::from_utf8(&bytes[body_start..body_end]) {
self.apply_osc(body);
}
i = next_i;
} else {
let rem = &combined[start..];
if rem.len() <= MAX_OSC_TAIL {
self.osc_tail.push_str(rem);
}
return;
}
}
}
fn apply_osc(&mut self, body: &str) {
if let Some(title) = body.strip_prefix("0;").or_else(|| body.strip_prefix("2;")) {
let trimmed = title.trim();
self.app_title = (!trimmed.is_empty()).then(|| trimmed.to_owned());
} else if let Some(url) = body.strip_prefix("7;") {
if let Some(path) = parse_file_url_path(url) {
self.cwd = path;
}
} else if let Some(rest) = body.strip_prefix("133;") {
if rest == "C" {
self.command_running = true;
} else if rest == "D" || rest.starts_with("D;") {
self.command_running = false;
}
}
}
}
fn floor_char_boundary(s: &str, mut index: usize) -> usize {
if index >= s.len() {
return s.len();
}
while index > 0 && !s.is_char_boundary(index) {
index -= 1;
}
index
}
fn last_clear_end(s: &str) -> Option<usize> {
let a = s.rfind(CLEAR_MARKER).map(|i| i + CLEAR_MARKER.len());
let b = s.rfind(CLEAR_CSI).map(|i| i + CLEAR_CSI.len());
match (a, b) {
(Some(x), Some(y)) => Some(x.max(y)),
(x, y) => x.or(y),
}
}
fn scan_alt_screen(mut current: bool, text: &str) -> bool {
if !text.contains("\x1b[?") {
return current;
}
let bytes = text.as_bytes();
let mut i = 0;
while i + 4 < bytes.len() {
if bytes[i] == 0x1b && bytes[i + 1] == b'[' && bytes[i + 2] == b'?' {
let tail = &text[i..];
if ALT_ON.iter().any(|p| tail.starts_with(p)) {
current = true;
} else if ALT_OFF.iter().any(|p| tail.starts_with(p)) {
current = false;
}
}
i += 1;
}
current
}
fn avoid_mid_escape(s: &str, cut: usize) -> usize {
let lookback = floor_char_boundary(s, cut.saturating_sub(16));
let Some(esc_rel) = s[lookback..cut].rfind('\x1b') else {
return cut;
};
let esc = lookback + esc_rel;
// Check whether the escape sequence already ended before `cut`.
let bytes = &s.as_bytes()[esc + 1..cut];
if bytes.first() == Some(&b'[') {
if bytes[1..].iter().any(|&b| (0x40..=0x7e).contains(&b)) {
return cut;
}
// Advance to end of CSI sequence (bounded to 32 bytes).
let max = (cut + 32).min(s.len());
for idx in cut..max {
let b = s.as_bytes()[idx];
if (0x40..=0x7e).contains(&b) {
return idx + 1;
}
}
}
cut
}
fn find_osc_start(bytes: &[u8]) -> Option<usize> {
bytes.windows(2).position(|w| w == b"\x1b]")
}
fn find_osc_end(bytes: &[u8], mut i: usize) -> Option<(usize, usize)> {
while i < bytes.len() {
if bytes[i] == 0x07 {
return Some((i, i + 1));
}
if bytes[i] == 0x1b && bytes.get(i + 1) == Some(&b'\\') {
return Some((i, i + 2));
}
i += 1;
}
None
}
fn parse_file_url_path(url: &str) -> Option<String> {
let rest = url.trim().strip_prefix("file://")?;
let slash = rest.find('/')?;
let raw_path = &rest[slash..];
let decoded = percent_decode(raw_path)?;
(!decoded.is_empty()).then_some(decoded)
}
fn percent_decode(input: &str) -> Option<String> {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hi = (bytes[i + 1] as char).to_digit(16)?;
let lo = (bytes[i + 2] as char).to_digit(16)?;
out.push(((hi << 4) | lo) as u8);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tracks_osc_cwd_title_and_command_across_split_chunks() {
let mut sb = Scrollback::new("/initial".into());
sb.push("\x1b]7;file://host/home/coder/my%20");
sb.push("repo\x07\x1b]2;watch date\x1b\\\x1b]133;C\x07tick 1\r\n");
assert_eq!(sb.cwd, "/home/coder/my repo");
assert_eq!(sb.app_title.as_deref(), Some("watch date"));
assert!(sb.command_running);
sb.push("\x1b]133;D;0\x07");
assert!(!sb.command_running);
}
#[test]
fn preserves_alt_screen_prefix_when_initial_enter_scrolls_off() {
let mut sb = Scrollback::new("/".into());
sb.push("\x1b[?1049hframe-0\r\n");
assert!(sb.is_alt_screen());
let filler = "x".repeat(MAX_SCROLLBACK_BYTES + 1024);
sb.push(&filler);
let snap = sb.snapshot();
assert!(snap.starts_with("\x1b[?1049h"));
assert!(sb.is_alt_screen());
sb.push("\x1b[?1049lprompt$ ");
assert!(!sb.is_alt_screen());
}
#[test]
fn clear_scrollback_drops_prior_history() {
let mut sb = Scrollback::new("/".into());
sb.push("old line 1\r\nold line 2\r\n");
sb.push("\x1b[2J\x1b[3Jfresh prompt$ ");
assert_eq!(sb.snapshot(), "fresh prompt$ ");
}
}
-2
Переглянути файл
@@ -933,8 +933,6 @@ mod ignore;
mod index_writes;
mod log_index;
mod manage;
mod metadata_watch;
pub use metadata_watch::MetadataWatch;
mod ops;
mod patch;
mod preserve;
-224
Переглянути файл
@@ -1,224 +0,0 @@
use crate::Repo;
use ide_core::{IdeError, IdeResult};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
const QUIET: Duration = Duration::from_millis(100);
const MAX_WAIT: Duration = Duration::from_secs(1);
/// Watches the Git metadata (`HEAD`, `index`, `packed-refs`, `refs/**`) of repositories whose
/// git directories lie outside the project's own file watcher: a project opened in a
/// subfolder of its repository, a linked worktree, a mapped repository elsewhere. Commits,
/// checkouts and resets run in a terminal then reach the IDE like those below the project.
pub struct MetadataWatch {
watcher: Mutex<RecommendedWatcher>,
/// Watched directory → whether only its top-level metadata files count (`false`: a
/// recursively watched `refs` directory, where every non-lock file counts).
dirs: Arc<Mutex<BTreeMap<PathBuf, bool>>>,
}
impl MetadataWatch {
/// `changed` receives the metadata files that changed, coalesced over short bursts.
pub fn new(changed: impl Fn(Vec<PathBuf>) + Send + 'static) -> IdeResult<Self> {
let dirs = Arc::new(Mutex::new(BTreeMap::<PathBuf, bool>::new()));
let (tx, rx) = mpsc::channel::<PathBuf>();
let watched = dirs.clone();
let watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let Ok(event) = event else { return };
if event.kind.is_access() {
return;
}
let dirs = watched.lock().unwrap_or_else(|e| e.into_inner());
for path in event.paths.iter().filter(|p| is_metadata(&dirs, p)) {
let _ = tx.send(path.clone());
}
})
.map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?;
std::thread::Builder::new()
.name("openidea-git-metadata".into())
.spawn(move || {
while let Ok(first) = rx.recv() {
let deadline = Instant::now() + MAX_WAIT;
let mut paths = BTreeSet::from([first]);
while Instant::now() < deadline
&& let Ok(path) = rx.recv_timeout(QUIET)
{
paths.insert(path);
}
changed(paths.into_iter().collect());
}
})
.map_err(|e| IdeError::internal(format!("Git metadata watcher: {e}")))?;
Ok(Self { watcher: Mutex::new(watcher), dirs })
}
/// Watches the metadata of `repos` that the project watcher of `covered` doesn't report:
/// git directories outside it, and submodule git directories (`.git/modules/…`) inside it.
pub fn set_repos(&self, repos: &[Arc<Repo>], covered: &Path) {
let covered = dunce::canonicalize(covered).unwrap_or_else(|_| covered.to_path_buf());
let mut wanted = BTreeMap::new();
for repo in repos {
let Ok([git_dir, common_dir]) = repo.metadata_dirs() else { continue };
for (dir, top_level) in [(git_dir, true), (common_dir.clone(), true), (common_dir.join("refs"), false)] {
if let Ok(dir) = dunce::canonicalize(&dir)
&& !watched_by_project(&covered, &dir)
{
wanted.insert(dir, top_level);
}
}
}
let mut watcher = self.watcher.lock().unwrap_or_else(|e| e.into_inner());
let mut dirs = self.dirs.lock().unwrap_or_else(|e| e.into_inner());
for dir in dirs.keys().filter(|d| !wanted.contains_key(*d)) {
let _ = watcher.unwatch(dir);
}
wanted.retain(|dir, top_level| {
if dirs.contains_key(dir) {
return true;
}
let mode = if *top_level { RecursiveMode::NonRecursive } else { RecursiveMode::Recursive };
watcher.watch(dir, mode).map_err(|e| tracing::debug!("Git metadata watcher {}: {e}", dir.display())).is_ok()
});
*dirs = wanted;
}
pub fn watched_dirs(&self) -> Vec<PathBuf> {
self.dirs.lock().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect()
}
}
fn watched_by_project(root: &Path, dir: &Path) -> bool {
dir.strip_prefix(root)
.is_ok_and(|rel| !rel.components().skip_while(|c| c.as_os_str() != ".git").any(|c| c.as_os_str() == "modules"))
}
fn is_metadata(dirs: &BTreeMap<PathBuf, bool>, path: &Path) -> bool {
if path.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".lock")) {
return false;
}
dirs.iter().any(|(dir, top_level)| match path.strip_prefix(dir) {
Ok(rest) if *top_level => rest.to_str().is_some_and(|r| matches!(r, "HEAD" | "index" | "packed-refs")),
Ok(rest) => !rest.as_os_str().is_empty(),
Err(_) => false,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn git(dir: &Path, args: &[&str]) {
let out = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "[email protected]", "-c", "user.name=t", "-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
fn wait_for(seen: &Mutex<Vec<PathBuf>>, pred: impl Fn(&[PathBuf]) -> bool) -> bool {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if pred(&seen.lock().unwrap()) {
return true;
}
std::thread::sleep(Duration::from_millis(50));
}
false
}
#[test]
fn metadata_files_count_and_locks_and_objects_do_not() {
let dirs = BTreeMap::from([(PathBuf::from("/r/.git"), true), (PathBuf::from("/r/.git/refs"), false)]);
for (path, expected) in [
("/r/.git/HEAD", true),
("/r/.git/index", true),
("/r/.git/packed-refs", true),
("/r/.git/refs/heads/main", true),
("/r/.git/refs/heads/feature/x", true),
("/r/.git/index.lock", false),
("/r/.git/refs/heads/main.lock", false),
("/r/.git/objects/aa/bb", false),
("/r/.git/logs/HEAD", false),
("/r/.git/COMMIT_EDITMSG", false),
("/r/src/HEAD", false),
] {
assert_eq!(is_metadata(&dirs, Path::new(path)), expected, "{path}");
}
}
/// The project folder is a subfolder of its repository, or a linked worktree: a commit made
/// in a terminal writes only outside it, and still surfaces.
#[test]
fn external_commits_surface_for_projects_outside_their_git_dir() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let main = base.join("main");
std::fs::create_dir_all(main.join("sub")).unwrap();
git(&main, &["init", "-q", "-b", "main"]);
git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
git(&main, &["worktree", "add", "-q", "-b", "topic", base.join("wt").to_str().unwrap()]);
for project in [main.join("sub"), base.join("wt")] {
let repo = Arc::new(Repo::discover(&project).unwrap().unwrap());
let seen = Arc::new(Mutex::new(Vec::new()));
let watch = {
let seen = seen.clone();
MetadataWatch::new(move |paths| seen.lock().unwrap().extend(paths)).unwrap()
};
watch.set_repos(std::slice::from_ref(&repo), &project);
assert!(!watch.watched_dirs().is_empty(), "{}", project.display());
std::thread::sleep(Duration::from_millis(300));
std::fs::write(project.join("a.txt"), project.to_string_lossy().as_bytes()).unwrap();
git(&project, &["add", "a.txt"]);
git(&project, &["commit", "-q", "-m", "change"]);
assert!(
wait_for(&seen, |p| p.iter().any(|p| p.starts_with(repo.metadata_dirs().unwrap()[1].join("refs")))),
"{}: {:?}",
project.display(),
seen.lock().unwrap()
);
assert!(
wait_for(&seen, |p| p.iter().any(|p| p.ends_with("index"))),
"{}: {:?}",
project.display(),
seen.lock().unwrap()
);
}
}
#[test]
fn the_project_watcher_reports_its_git_dirs_but_not_submodule_ones() {
let root = Path::new("/p");
for (dir, expected) in [
("/p/.git", true),
("/p/.git/refs", true),
("/p/.git/worktrees/wt", true),
("/p/nested/.git", true),
("/p/.git/modules/lib", false),
("/p/.git/modules/lib/refs", false),
("/p/.git/modules/a/modules/b", false),
("/elsewhere/.git", false),
] {
assert_eq!(watched_by_project(root, Path::new(dir)), expected, "{dir}");
}
}
#[test]
fn metadata_below_the_covered_folder_is_left_to_the_project_watcher() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git(&root, &["init", "-q"]);
let repo = Arc::new(Repo::discover(&root).unwrap().unwrap());
let watch = MetadataWatch::new(|_| {}).unwrap();
watch.set_repos(std::slice::from_ref(&repo), &root);
assert!(watch.watched_dirs().is_empty());
watch.set_repos(std::slice::from_ref(&repo), &root.join("elsewhere"));
assert_eq!(watch.watched_dirs().len(), 2, "{:?}", watch.watched_dirs());
watch.set_repos(&[], &root);
assert!(watch.watched_dirs().is_empty());
}
}
-42
Переглянути файл
@@ -668,44 +668,6 @@ impl Documents {
}
}
/// Releases client-held document references when a remote window disconnects:
/// clean documents close so external changes on disk are picked up cleanly on
/// reopen, while dirty buffers remain registered (`refs = 0`) so reconnecting
/// after a dropped connection keeps unsaved edits without leaking refcounts.
pub fn release_client_refs(&self) {
let _operation = self.operations.lock();
let mut to_close = Vec::new();
{
let mut reg = self.registry.lock();
let ids: Vec<DocId> = reg.docs.keys().copied().collect();
for id in ids {
let dirty = reg.docs.get(&id).is_some_and(|e| e.slot.lock().dirty);
if dirty {
if let Some(entry) = reg.docs.get_mut(&id) {
entry.refs = 0;
}
} else if let Some(entry) = reg.docs.remove(&id) {
for k in &entry.keys {
if reg.by_key.get(k) == Some(&id) {
reg.by_key.remove(k);
}
}
to_close.push((id, entry.slot));
}
}
}
let observers = self.observers();
for (doc, slot) in to_close {
let mut st = slot.lock();
st.closed = true;
if st.observed {
for o in &observers {
o.closed(doc, &st.path);
}
}
}
}
fn set_dirty(&self, doc: DocId, st: &mut DocState, dirty: bool) {
if st.dirty != dirty {
st.dirty = dirty;
@@ -979,10 +941,6 @@ impl Documents {
})
}
pub fn has_unsaved_changes(&self) -> bool {
self.registry.lock().docs.values().any(|entry| entry.slot.lock().dirty)
}
/// Saves every dirty document; reports the first failure after trying all.
pub fn save_all(&self) -> IdeResult<()> {
let ids: Vec<DocId> = self.registry.lock().docs.keys().copied().collect();
+2 -3
Переглянути файл
@@ -66,9 +66,8 @@ pub enum SettingsScope {
/// Settings a project's own file can't hold: the IDE's MCP server, imported color schemes, and
/// what agents may do without asking (commands run without asking, the modes new tasks start in,
/// whether new tasks ask for approvals).
const USER_ONLY: &[&[&str]] = &[
const USER_ONLY: [&[&str]; 6] = [
&["mcpServer"],
&["remoteDevelopment"],
&["editor", "customSchemes"],
&["agentSecurity", "allowedCommands"],
&["agents", "defaults"],
@@ -92,7 +91,7 @@ fn user_only_setting(key: &str, value: &Json) -> Option<String> {
/// Applies a project layer's limits before it merges onto `below`: [`USER_ONLY`] settings are
/// dropped, and its blocked agent commands add to the ones below instead of replacing them.
fn restrict_project_layer(below: &Json, layer: &mut Json) {
for &path in USER_ONLY {
for path in USER_ONLY {
let (last, parents) = path.split_last().expect("non-empty path");
if let Some(table) = parents.iter().try_fold(&mut *layer, |v, seg| v.get_mut(seg)).and_then(Json::as_object_mut)
{
+2 -4
Переглянути файл
@@ -28,7 +28,6 @@ flowchart LR
| Piece | Where |
| --------------------------------- | ----------------------------------------------------------------------------- |
| Server binary | `crates/ide-host/src/bin/server.rs` (`openidea-server`) |
| Persistent daemon and attach | `crates/ide-host/src/daemon.rs` (`openidea-server --attach` / `--daemon`) |
| Protocol and dispatcher | `crates/ide-host/src/rpc.rs` |
| Client: connect, install, forward | `src-tauri/src/remote_dev.rs` |
| WSL and dev container transports | `src-tauri/src/remote_wsl.rs`, `src-tauri/src/remote_container.rs` |
@@ -39,11 +38,10 @@ flowchart LR
## The server
```text
openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
```
- `--attach <project-path>` bridges stdin/stdout to a detached daemon on a `0600` Unix socket in a `0700` directory. The socket key is stable across builds. The relay checks the daemon's build before attaching; a different build can replace it only when no window, live workload, or unsaved document remains. Idle or explicit shutdown keeps the socket bound until cleanup is complete.
- `--stdio` serves a single desktop client directly over stdin/stdout and exits on EOF. stdout carries the protocol, so logs go to stderr (filter with `OPENIDEA_LOG`).
- `--stdio` serves one desktop client over stdin/stdout. stdout carries the protocol, so logs go to stderr (filter with `OPENIDEA_LOG`).
- Its state lives under `OPENIDEA_SERVER_HOME` (default `~/.openidea`), in `config/` and `data/`. Language definitions can be added in `config/languages/`.
- An SSH exec channel gets a minimal environment, so on every start the server takes the login shell's environment and adds the IDE-managed tools directory to `PATH`.
- `--version` prints the app version and the protocol version.
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ mise run dev
`setup` runs `pnpm install` in this worktree. `dev` and `dev:app` use the same worktree-aware launchers as the direct commands. No shell activation is needed for `mise run`.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:local` builds and locally installs a grey-icon dogfood desktop app (`--build-only` skips installation) that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:local` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override), and `mise run dogfood:all <remote_name>` runs `dogfood:local` and `dogfood:remote <remote_name>` in parallel. `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
## Worktrees
+6 -33
Переглянути файл
@@ -9,27 +9,9 @@ language servers, terminals, runs, debugging, build tools and Git. The desktop w
commands to it.
You don't start it yourself. When you open a remote project ([SSH](/en/guide/remote/ssh),
[Containers](/en/guide/remote/containers)), the desktop app installs the server on the host if needed, runs
`openidea-server --attach <project>` over the SSH connection (or `wsl.exe` / `docker exec`) to attach to a persistent
per-project daemon over a private Unix socket, and talks to it over stdin and stdout.
## Closing or stopping a remote backend
- **Keep Backend Running** (the default when closing a remote window) disconnects the window without interrupting
terminal sessions, runs, indexing or agent turns. Reopen the same project to reattach. A network drop also leaves
the backend running.
- **Stop Backend** on close, or **File › Stop Remote Backend**, shuts down the IDE backend and its workloads.
Active Run configurations with a stop command, such as `docker compose down`, run that command first. Stopping the
IDE backend in a dev container does not stop the dev container itself.
- By default, a backend stops after **3 hours** with no connected window, live terminal, run, debug session, or agent
work. In a connected window, open **Settings › Tools › Remote Development › Stop backend when idle**. Pick a
preset, choose **Custom…** to enter minutes, hours, or days, or choose **Never** to keep an idle project running.
**Apply** saves the choice for your user on that host. It takes effect the next time a backend becomes idle, without a restart.
**Never** does not prevent **Stop Backend**, and backends that never opened a project still clean themselves up.
- The close dialog shows what **Keep Backend Running** means for this host. A positive
`OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS` set at server startup takes precedence, even over **Never**;
Settings shows that value read-only. Reconnecting resets the idle timer. Save
your edits before leaving a project idle: unsaved buffers retained after a network drop are kept only in memory.
[Containers](/en/guide/remote/containers)), the desktop app installs the server on the host if needed, starts it as
`openidea-server --stdio` over the SSH connection (or `wsl.exe` / `docker exec`) and talks to it over stdin and
stdout. The server serves one desktop window and exits when that window disconnects.
## Supported hosts
@@ -53,10 +35,8 @@ On every connection the desktop app checks whether the host already has the serv
desktop's local data directory under `server/<version>/<os>-<arch>/`.
3. It uploads the binary to the host and removes older builds of the same version.
After you update OpenIDEA, the next connection replaces the old backend for that project if it has no connected
window, live work, or unsaved documents. Otherwise OpenIDEA asks you to finish or save your work using the previous
build and stop that backend before upgrading. Two windows on the same build can use the same project in turn; the
previous window shows that another window took over and does not reconnect automatically.
The desktop and the server always run the same version. After you update OpenIDEA, the next connection installs the
new server next to the old one.
## Files on the host
@@ -65,12 +45,6 @@ previous window shows that another window took over and does not reconnect autom
| `~/.openidea/server/<version>/<build>/openidea-server` | The installed server binaries, one folder per version and build. |
| `~/.openidea/config/` | The host's settings, including custom language definitions in `languages/`. |
| `~/.openidea/data/` | Tools OpenIDEA installs on the host (language servers, debuggers, JDKs), caches and indexes. |
| `~/.openidea/logs/server-<key>.log` | Backend log for each project (under `OPENIDEA_SERVER_HOME` if set). |
To stop all of your backends by hand, open a shell on the remote host, WSL distribution, or dev container and list
your processes with `ps -u "$(id -un)" -o pid=,args=`. Review the rows for `openidea-server --daemon`, then run
`kill -TERM <pid>` for each of those daemon PIDs. Save any open work first: this shuts down those backends even if
a window is still connected. It does not stop unrelated processes.
To free space, delete old version folders under `~/.openidea/server/`. After deleting `~/.openidea/data/`, OpenIDEA
installs its tools again when they are needed.
@@ -121,8 +95,7 @@ The flags are meant for the desktop app, but `--version` is handy for checking a
| Flag | Meaning |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `--version` | Print the server version and protocol version, then exit. |
| `--attach <project>` | Start or attach to the persistent per-project daemon and bridge stdin / stdout to its Unix socket. |
| `--stdio` | Serve a single desktop client directly over stdin / stdout and exit on EOF. Logs go to stderr. |
| `--stdio` | Serve one desktop client over stdin / stdout. Logs go to stderr. |
| `--mcp-stdio [--project <dir>]` | Relay stdio MCP traffic to the running `openidea-server` MCP server on this host. |
| `--connect <host> <port>` | Relay one TCP connection to `<host>:<port>` over stdin / stdout. Used for port forwarding into dev containers. |
+1 -2
Переглянути файл
@@ -96,8 +96,7 @@ After the project opens you are asked whether to trust it, as for a local folder
- Your keymap, appearance, editor font and colour scheme stay on the desktop. Project and tool settings live on the
host.
- Your code plugins are synced to the server and run next to the project.
- **Keep Backend Running** when closing a remote window, or **File › Disconnect from Remote Host**, leaves the remote IDE backend and its workloads running. Reopen the project to reattach.
- **Stop Backend** when closing the window, or **File › Stop Remote Backend**, shuts down the backend and its workloads. See [Stopping a remote backend](/en/guide/remote/server#closing-or-stopping-a-remote-backend) for idle timeout and manual cleanup.
- **File › Disconnect from Remote Host** closes the project and ends the connection.
### Forward ports
+1 -1
Переглянути файл
@@ -27,7 +27,7 @@ When a session's process exits, the terminal prints the exit code; press `Enter`
### Across restarts
OpenIDEA remembers each project's terminal tabs: their directory, custom names, the shell used and the split layout (up to 32 tabs). For local projects, a restart starts a **new** session in each tab's directory without restoring scrollback or running commands. In a remote project, closing and reopening the window reattaches to the running PTY sessions on `openidea-server` along with their recent scrollback and active commands.
OpenIDEA remembers each project's terminal tabs: their directory, custom names, the shell used and the split layout (up to 32 tabs). After a restart each tab starts a **new** session in its directory. Scrollback and running commands are not restored.
## Keys in the terminal
+11 -13
Переглянути файл
@@ -25,25 +25,23 @@ flowchart LR
S1 --> H["ide-host: Host<br/>项目、LSP、索引、git、<br/>终端、运行、调试器、插件"]
```
| 部分 | 位置 |
| ------------------------- | -------------------------------------------------------------------------- |
| 服务端二进制 | `crates/ide-host/src/bin/server.rs`(`openidea-server`) |
| 持久化守护进程与连接桥接 | `crates/ide-host/src/daemon.rs`(`openidea-server --attach` / `--daemon`) |
| 协议与 dispatcher | `crates/ide-host/src/rpc.rs` |
| 客户端:连接、安装、转发 | `src-tauri/src/remote_dev.rs` |
| WSL 与 dev container 传输 | `src-tauri/src/remote_wsl.rs`、`src-tauri/src/remote_container.rs` |
| 容器内的端口中继 | `crates/ide-host/src/relay.rs`(`openidea-server --connect`) |
| 前端路由 | `src/platform/remote.ts`,由 `src/platform/tauriCore.ts` 挂到 `invoke` 上 |
| UI(文件 › 远程开发…) | `src/features/remote-dev/` |
| 部分 | 位置 |
| ------------------------- | ------------------------------------------------------------------------- |
| 服务端二进制 | `crates/ide-host/src/bin/server.rs`(`openidea-server`) |
| 协议与 dispatcher | `crates/ide-host/src/rpc.rs` |
| 客户端:连接、安装、转发 | `src-tauri/src/remote_dev.rs` |
| WSL 与 dev container 传输 | `src-tauri/src/remote_wsl.rs`、`src-tauri/src/remote_container.rs` |
| 容器内的端口中继 | `crates/ide-host/src/relay.rs`(`openidea-server --connect`) |
| 前端路由 | `src/platform/remote.ts`,由 `src/platform/tauriCore.ts` 挂到 `invoke` 上 |
| UI(文件 › 远程开发…) | `src/features/remote-dev/` |
## 服务端
```text
openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
```
- `--attach <project-path>` 将 stdin/stdout 桥接到独立守护进程,套接字权限为 `0600`,目录权限为 `0700`。套接字键不随构建变化;连接前会核对构建,只有在没有连接的窗口、活动任务或未保存的文档时才替换旧后端。空闲退出或主动关闭时会保留套接字,直到清理完成。
- `--stdio` 直接通过 stdin/stdout 为单个桌面客户端提供服务并在断开时退出。stdout 承载协议,所以日志写到 stderr(用 `OPENIDEA_LOG` 过滤)。
- `--stdio` 通过 stdin/stdout 为一个桌面客户端提供服务。stdout 承载协议,所以日志写到 stderr(用 `OPENIDEA_LOG` 过滤)。
- 状态保存在 `OPENIDEA_SERVER_HOME`(默认 `~/.openidea`)下的 `config/` 和 `data/` 中。可以在 `config/languages/` 里追加语言定义。
- SSH exec channel 只给最小的环境变量,所以服务端每次启动都会读取登录 shell 的环境,并把 IDE 托管的工具目录加入 `PATH`。
- `--version` 打印应用版本和协议版本。
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ mise run dev
`setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:local` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据;`--build-only` 仅构建不安装)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:local`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖),`mise run dogfood:all <remote_name>` 则并行执行 `dogfood:local` 与 `dogfood:remote <remote_name>`。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖)。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
## Worktree
+4 -23
Переглянути файл
@@ -7,19 +7,8 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
承担桌面端在本地时要做的工作:文件系统、索引、语言服务器、终端、运行、调试、构建工具和 Git。桌面窗口只负责显示界面,并把命令发给它。
你不需要手动启动它。打开远程项目时([SSH](/zh/guide/remote/ssh)、[容器](/zh/guide/remote/containers)),桌面端会按需在主机上安装服务端,
通过 SSH 连接(或 `wsl.exe` / `docker exec`)运行 `openidea-server --attach <project>`,连接到按项目隔离的后台守护进程(经由私有 Unix 套接字),
并经由标准输入输出与它通信。
## 关闭窗口或停止远程后端
- 关闭窗口时默认选择**保持后端运行**。窗口断开连接,但终端、运行配置、索引和智能体任务不受影响。重新打开同一项目即可接回。网络中断也不会停止后端。
- 关闭时选择**停止后端**,或使用**文件 › 停止远程后端**,会关闭 IDE 后端及其任务。正在运行且配置了停止命令的运行配置会先执行该命令,例如 `docker compose down`。
停止开发容器里的 IDE 后端不会关闭开发容器本身。
- 默认情况下,没有窗口连接,且没有活动的终端、运行配置、调试会话或智能体任务时,后端闲置**三小时**后自动退出。
在已连接的窗口中,打开**设置 › 工具 › 远程开发 › 空闲时停止后端**。选择预设时长、通过**自定义…**输入分钟、小时或天数,或选择**从不**让空闲项目保持运行。
点击**应用**后,设置保存在远程主机的用户设置中;后端下次进入空闲时即生效,无需重启。选择**从不**后仍可手动**停止后端**;从未打开项目的后端仍会自动退出。
- 关闭窗口的对话框会说明在当前主机上**保持后端运行**的效果。启动环境中的 `OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS` 如为正整数秒数,会优先于所有用户选择(包括**从不**),并在设置页以只读形式显示。重新连接会重置计时。
请在项目闲置前保存修改:网络中断后,未保存的文档仅保留在后端内存里。
通过 SSH 连接(或 `wsl.exe` / `docker exec`)以 `openidea-server --stdio` 启动,并经由标准输入输出与它通信。一个服务端进程只服务一个桌面窗口,
窗口断开后即退出。
## 支持的主机
@@ -41,9 +30,7 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
校验 SHA-256 后缓存到本机本地数据目录的 `server/<version>/<os>-<arch>/` 下。
3. 把二进制上传到主机,并删除同一版本的旧构建。
升级 OpenIDEA 后,若旧后端没有窗口连接、活动任务或未保存的文档,下一次连接会替换该项目的旧后端。
否则,OpenIDEA 会提示你用旧版本结束任务或保存文档,再停止旧后端并升级。同一版本的两个窗口可以轮流连接同一项目;
原窗口会提示会话已被另一个窗口接管,不会自动重新连接。
桌面端和服务端始终是同一版本。升级 OpenIDEA 后,下一次连接会在旧版本旁边安装新的服务端。
## 主机上的文件
@@ -52,11 +39,6 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
| `~/.openidea/server/<version>/<build>/openidea-server` | 已安装的服务端,每个版本、每个构建一个文件夹。 |
| `~/.openidea/config/` | 主机端的设置,包括 `languages/` 中的自定义语言定义。 |
| `~/.openidea/data/` | OpenIDEA 在主机上安装的工具(语言服务器、调试器、JDK)、缓存和索引。 |
| `~/.openidea/logs/server-<key>.log` | 各项目的后端日志(如设置了 `OPENIDEA_SERVER_HOME`,则在其下)。 |
若要手动停止自己的所有后端,请在远程主机、WSL 发行版或开发容器中打开 shell,运行 `ps -u "$(id -un)" -o pid=,args=`。
确认属于 `openidea-server --daemon` 的 PID,再对每个 PID 运行 `kill -TERM <pid>`。请先保存工作:
即使窗口仍然连接,此操作也会关闭这些后端,不会停止无关进程。
想释放空间,可以删除 `~/.openidea/server/` 下的旧版本文件夹。删除 `~/.openidea/data/` 后,OpenIDEA 会在需要时重新安装工具。
@@ -100,8 +82,7 @@ cargo build --release -p ide-host --bin openidea-server
| 参数 | 含义 |
| ------------------------------- | -------------------------------------------------------------------------------- |
| `--version` | 输出服务端版本和协议版本后退出。 |
| `--attach <project>` | 启动或连接到该项目的持久化后台守护进程,并将标准输入输出桥接到其 Unix 套接字。 |
| `--stdio` | 直接通过标准输入输出服务单个桌面客户端并在断开时退出,日志写到 stderr。 |
| `--stdio` | 通过标准输入输出服务一个桌面客户端,日志写到 stderr。 |
| `--mcp-stdio [--project <dir>]` | 将标准输入输出上的 MCP 消息转发给当前主机正在运行的 `openidea-server` MCP 服务。 |
| `--connect <host> <port>` | 通过标准输入输出中转一个到 `<host>:<port>` 的 TCP 连接,用于开发容器的端口转发。 |
+1 -2
Переглянути файл
@@ -74,8 +74,7 @@ SSH 代理使用 `IdentityAgent` 指定的那个,未指定时使用登录 shel
- OpenIDEA 安装的语言服务器、调试器等工具都装在远程主机的 `~/.openidea/data` 下。
- 快捷键、外观、编辑器字体和配色方案保留在本机;项目和工具相关的设置保存在主机上。
- 你的代码插件会同步到服务端,在项目所在的机器上运行。
- 关闭窗口时选择**保持后端运行**,或使用**文件 › 断开与远程主机的连接**,会保留远程 IDE 后端及其任务。重新打开项目即可接回。
- 关闭窗口时选择**停止后端**,或使用**文件 › 停止远程后端**,会关闭后端及其任务。有关空闲超时和手动清理,请参阅[关闭窗口或停止远程后端](/zh/guide/remote/server#关闭窗口或停止远程后端)。
- **文件 › 断开与远程主机的连接**会关闭项目并断开连接。
### 端口转发
+1 -1
Переглянути файл
@@ -27,7 +27,7 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
### 重启 IDE 之后
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。对于本地项目,重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令;对于远程项目,关闭并重新打开窗口会重新连接到 `openidea-server` 上仍在运行的终端会话,并恢复最近的终端输出与正在执行的命令。
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令。
## 终端中的按键
+2 -7
Переглянути файл
@@ -34,7 +34,6 @@ export interface IpcStub {
send(channel: unknown, message: unknown): void;
/** Emits an `IdeEvent` the way the backend does. */
emit(event: { type: string } & Record<string, unknown>): void;
dispatch(event: string, payload: unknown): void;
}
declare global {
@@ -72,12 +71,8 @@ export async function stubDesktop(page: Page) {
callbacks.get(id)?.({ index, message });
},
emit(event) {
ipc.dispatch("ide://event", event);
},
dispatch(event, payload) {
for (const l of listeners) {
if (l.event === event) callbacks.get(l.handler)?.({ event, id: 0, payload });
}
for (const l of listeners)
if (l.event === "ide://event") callbacks.get(l.handler)?.({ event: l.event, id: 0, payload: event });
},
};
window.__ipc = ipc;
+44
Переглянути файл
@@ -0,0 +1,44 @@
/** The npm tool window lists package.json scripts without run configurations and runs them. */
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const PKG = JSON.stringify({ name: "acme-api", scripts: { dev: "vite", build: "vite build" } });
/** The root package.json has scripts; there are no run configurations. */
async function stubNpm(page: Page) {
await stubDesktop(page);
await page.evaluate(async (pkg) => {
const h = window.__ipc.handlers;
h.fs_read_text = (args) => (String(args.path).endsWith("/package.json") ? pkg : "");
h.run_configs = () => [];
h.run_start = (args) => {
const config = args.config as { id: string; name: string };
return { id: 8, configId: config.id, name: config.name, pid: 4242, running: true, pty: false };
};
const npmModule = "/src/features/run/npmScripts.ts";
const { loadNpmScripts } = await import(/* @vite-ignore */ npmModule);
await loadNpmScripts();
}, PKG);
}
test("lists scripts without run configurations and runs one on double-click", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await expect(tree).toBeVisible();
await expect(tree.getByRole("treeitem", { name: /^acme-api/ })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "dev" })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "build" })).toBeVisible();
await tree.getByRole("treeitem", { name: "dev" }).dblclick();
const [started] = await ipcCalls(page, "run_start");
expect(started).toMatchObject({ config: { args: ["run", "dev"], kind: "npm" } });
});
test("offers Run / Debug in a script's context menu", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await tree.getByRole("treeitem", { name: "build" }).click({ button: "right" });
await expect(page.getByRole("menuitem", { name: /Run '.*run build'/ })).toBeVisible();
await expect(page.getByRole("menuitem", { name: /Debug '.*run build'/ })).toBeVisible();
});
-298
Переглянути файл
@@ -1,298 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const CLOSE = "tauri://close-requested";
const DESTROY = "plugin:window|destroy";
const CANCEL_CLOSE = "window_group_cancel_close";
const STOP = "remote_stop_backend";
interface CloseOptions {
windows?: number;
quitting?: boolean;
dirty?: boolean;
fail?: boolean;
idleMinutes?: number | null;
overrideSeconds?: number | null;
}
async function requestClose(
page: Page,
{
windows = 2,
quitting = false,
dirty = false,
fail = false,
idleMinutes = 180,
overrideSeconds = null,
}: CloseOptions = {},
) {
await stubDesktop(page);
await page.evaluate(
async ({ windows, quitting, dirty, fail, idleMinutes, overrideSeconds }) => {
const closes = "/src/features/app/closeGuard.ts";
const remote = "/src/platform/remote.ts";
const project = "/src/platform/project.ts";
const { installCloseGuard } = await import(/* @vite-ignore */ closes);
const { enableRemote } = await import(/* @vite-ignore */ remote);
const { useProject } = await import(/* @vite-ignore */ project);
enableRemote({
target: { kind: "ssh", config: "devbox" },
root: useProject.getState().project.root,
host: "devbox",
os: "linux",
commands: ["doc_close", "remote_idle_timeout_minutes"],
idlePolicy: { overrideSeconds },
});
window.__ipc.handlers.window_close_context = () => ({ windows, quitting });
window.__ipc.handlers.close_project = () => null;
window.__ipc.handlers.remote_invoke = ({ cmd }) => {
if (cmd === "remote_idle_timeout_minutes") {
if (idleMinutes === null) throw { kind: "unavailable", message: "offline", detail: null };
return JSON.stringify(idleMinutes);
}
return JSON.stringify(null);
};
window.__ipc.handlers.window_group_cancel_close = () => null;
window.__ipc.handlers.app_cancel_quit = () => null;
window.__ipc.handlers.remote_stop_backend = () => {
if (fail) throw { kind: "unavailable", message: "Backend did not respond", detail: null };
return null;
};
installCloseGuard();
if (dirty) window.__ipc.emit({ type: "docDirty", doc: 100, dirty: true });
},
{ windows, quitting, dirty, fail, idleMinutes, overrideSeconds },
);
await expect.poll(async () => (await ipcCalls(page, "plugin:event|listen")).map((e) => e.event)).toContain(CLOSE);
await page.evaluate((event) => window.__ipc.dispatch(event, null), CLOSE);
return page.getByRole("dialog", { name: "Close Remote Development Window" });
}
for (const windows of [1, 2]) {
for (const stop of [false, true]) {
test(`${stop ? "stops" : "keeps"} the backend on close (${windows === 1 ? "last" : "other"} window)`, async ({
workbench: page,
}) => {
await openFromTree(page, "README.md");
const dialog = await requestClose(page, { windows });
await expect(dialog.getByRole("status")).toHaveText("If kept running, the backend stops after 3 hours idle.");
const keep = dialog.getByRole("button", { name: "Keep Backend Running" });
await expect(keep).toBeFocused();
await (stop ? dialog.getByRole("button", { name: "Stop Backend" }) : keep).click();
const close = windows === 1 ? "close_project" : DESTROY;
await expect.poll(() => ipcCalls(page, close)).toHaveLength(1);
const actions = await page.evaluate(
({ stop, close }) => window.__ipc.calls.map((c) => c.cmd).filter((cmd) => cmd === stop || cmd === close),
{ stop: STOP, close },
);
expect(actions).toEqual(stop ? [STOP, close] : [close]);
if (windows === 1) await expect(page.getByRole("tree", { name: "Project" })).toHaveCount(0);
});
}
}
test("Escape leaves the remote project, backend and window open", async ({ workbench: page }) => {
const dialog = await requestClose(page, { idleMinutes: 0 });
await expect(dialog.getByRole("status")).toHaveText("Idle shutdown is off on devbox.");
await page.keyboard.press("Escape");
await expect.poll(() => ipcCalls(page, CANCEL_CLOSE)).toHaveLength(1);
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
expect(await ipcCalls(page, STOP)).toHaveLength(0);
expect(await ipcCalls(page, DESTROY)).toHaveLength(0);
});
test("cancelling unsaved changes after choosing Stop Backend also cancels quit", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
const dialog = await requestClose(page, {
windows: 1,
quitting: true,
dirty: true,
idleMinutes: 0,
overrideSeconds: 90,
});
await expect(dialog.getByRole("status")).toHaveText("If kept running, the backend stops after 90 seconds idle.");
expect((await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "remote_idle_timeout_minutes")).toHaveLength(
0,
);
await dialog.getByRole("button", { name: "Stop Backend" }).click();
const unsaved = page.getByRole("dialog", { name: /unsaved changes/i });
await unsaved.getByRole("button", { name: "Cancel" }).click();
await expect.poll(() => ipcCalls(page, "app_cancel_quit")).toHaveLength(1);
expect(await ipcCalls(page, STOP)).toHaveLength(0);
expect(await ipcCalls(page, DESTROY)).toHaveLength(0);
});
test("reports a shutdown failure and does not close the window", async ({ workbench: page }) => {
const dialog = await requestClose(page, { fail: true });
await dialog.getByRole("button", { name: "Stop Backend" }).click();
await expect(page.getByText("Could not stop the remote backend")).toBeVisible();
await expect.poll(() => ipcCalls(page, CANCEL_CLOSE)).toHaveLength(1);
expect(await ipcCalls(page, DESTROY)).toHaveLength(0);
});
test("can disconnect even if the host cannot report its current idle timeout", async ({ workbench: page }) => {
const dialog = await requestClose(page, { idleMinutes: null });
await expect(dialog.getByRole("status")).toHaveText("The host’s idle timeout is unavailable.");
await dialog.getByRole("button", { name: "Keep Backend Running" }).click();
await expect.poll(() => ipcCalls(page, DESTROY)).toHaveLength(1);
});
test("Don't Save discards remote edits even when keeping the backend alive", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
const dialog = await requestClose(page, { dirty: true });
await dialog.getByRole("button", { name: "Keep Backend Running" }).click();
await page
.getByRole("dialog", { name: /unsaved changes/i })
.getByRole("button", { name: /don.t save/i })
.click();
await expect.poll(() => ipcCalls(page, DESTROY)).toHaveLength(1);
expect((await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "doc_close")).toEqual([
expect.objectContaining({ args: '{"doc":100}' }),
]);
expect(await ipcCalls(page, STOP)).toHaveLength(0);
});
async function enablePolicy(page: Page, overrideSeconds: number | null, initialMinutes = 180) {
await stubDesktop(page);
await page.evaluate(
async ({ overrideSeconds, initialMinutes }) => {
const remote = "/src/platform/remote.ts";
const project = "/src/platform/project.ts";
const { enableRemote } = await import(/* @vite-ignore */ remote);
const { useProject } = await import(/* @vite-ignore */ project);
const settings = { remoteDevelopment: { idleTimeoutMinutes: initialMinutes } };
window.__ipc.handlers.settings_get_global = () => ({});
window.__ipc.handlers.remote_invoke = ({ cmd, args }) => {
if (cmd === "settings_set") {
const change = JSON.parse(String(args));
if (change.scope !== "global" || change.key !== "remoteDevelopment.idleTimeoutMinutes")
throw new Error("Unexpected settings write");
settings.remoteDevelopment.idleTimeoutMinutes = JSON.parse(change.value);
}
return JSON.stringify(settings);
};
enableRemote({
target: { kind: "ssh", config: "devbox" },
root: useProject.getState().project.root,
host: "devbox",
os: "linux",
commands: ["settings_get", "settings_get_global", "settings_set"],
idlePolicy: { overrideSeconds },
});
// The Settings window reconciles its global snapshot with the connected host after first paint.
const staging = "/src/features/settings/model/staging.ts";
const schema = "/src/features/settings/model/schema.ts";
(await import(/* @vite-ignore */ staging)).rebaseSettings(
(await import(/* @vite-ignore */ schema)).validateSettings(settings),
);
},
{ overrideSeconds, initialMinutes },
);
}
for (const override of [null, 90]) {
test(`remote idle timeout ${override ? "shows the host override read-only" : "is searchable and saves only on Apply"}`, async ({
workbench: page,
}) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Idle timeout");
await dialog.getByRole("treeitem", { name: "Remote Development", exact: true }).click();
const picker = dialog.getByRole("button", { name: "Stop backend when idle", exact: true });
await expect(picker).toBeDisabled();
await enablePolicy(page, override);
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
if (override) {
await expect(dialog.getByText("90 seconds", { exact: true })).toBeVisible();
await expect(dialog.getByText("Set by OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS on devbox.")).toBeVisible();
await expect(picker).toHaveCount(0);
await expect(apply).toBeDisabled();
} else {
await expect(picker).toHaveText("After 3 hours (default)");
await picker.click();
const options = page.getByRole("listbox").getByRole("option");
expect(await options.allTextContents()).toEqual([
"After 30 minutes",
"After 1 hour",
"After 3 hours (default)",
"After 8 hours",
"After 1 day",
"Custom…",
"Never",
]);
await page.getByRole("option", { name: "After 1 day", exact: true }).click();
await apply.click();
await expect(apply).toBeDisabled();
await picker.click();
await page.getByRole("option", { name: "Never", exact: true }).click();
await expect(
dialog.getByText("Idle shutdown is off on devbox. You can still stop the backend manually."),
).toBeVisible();
await expect(dialog.getByRole("textbox", { name: "Custom duration" })).toHaveCount(0);
await apply.click();
await expect(apply).toBeDisabled();
const writes = (await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "settings_set");
expect(writes.map((c) => JSON.parse(String(c.args)))).toEqual(
["1440", "0"].map((value) => ({ scope: "global", key: "remoteDevelopment.idleTimeoutMinutes", value })),
);
expect(await ipcCalls(page, "settings_set")).toHaveLength(0);
}
});
}
test("custom idle time preserves 90 minutes across units and accepts only whole-minute durations", async ({
workbench: page,
}) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Idle timeout");
await dialog.getByRole("treeitem", { name: "Remote Development", exact: true }).click();
await enablePolicy(page, null, 90);
const amount = dialog.getByRole("textbox", { name: "Custom duration" });
const unit = dialog.getByRole("button", { name: "Duration unit" });
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
await expect(amount).toHaveValue("90");
await unit.click();
await page.getByRole("option", { name: "Hours", exact: true }).click();
await expect(amount).toHaveValue("1.5");
await expect(apply).toBeDisabled();
await unit.click();
await page.getByRole("option", { name: "Days", exact: true }).click();
await expect(amount).toHaveValue("0.0625");
await expect(apply).toBeDisabled();
for (const invalid of ["0", "0.001", "46"]) {
await amount.fill(invalid);
await expect(amount).toHaveAttribute("aria-invalid", "true");
await expect(apply).toBeDisabled();
}
await amount.fill("1.5");
await apply.click();
await expect(apply).toBeDisabled();
const writes = (await ipcCalls(page, "remote_invoke")).filter((c) => c.cmd === "settings_set");
expect(writes.map((c) => JSON.parse(String(c.args)).value)).toEqual(["2160"]);
const picker = dialog.getByRole("button", { name: "Stop backend when idle" });
await picker.click();
await page.getByRole("option", { name: "After 3 hours (default)", exact: true }).click();
await expect(amount).toHaveCount(0);
await picker.click();
await page.getByRole("option", { name: "Custom…", exact: true }).click();
await expect(amount).toHaveValue("3");
});
test("a same-build takeover notifies the old window and leaves reconnect to the user", async ({ workbench: page }) => {
await enablePolicy(page, null);
await page.clock.install();
await page.evaluate(() => window.__ipc.emit({ type: "remoteConnectionLost", host: "devbox", takenOver: true }));
await expect(page.getByText("Another window took over this remote session", { exact: true })).toBeVisible();
await expect(page.getByText(/This window will not reconnect automatically/)).toBeVisible();
await page.getByRole("button", { name: "Reconnect", exact: true }).click();
const prompt = page.getByRole("dialog", { name: "Reconnect to Remote Host" });
await expect(
prompt.getByText("Reconnecting takes over the remote session and disconnects the other window."),
).toBeVisible();
await prompt.getByRole("button", { name: "Cancel" }).click();
await page.clock.fastForward(25_000);
expect(await ipcCalls(page, "remote_connect")).toHaveLength(0);
await expect(page.getByRole("button", { name: "SSH: devbox (disconnected)" })).toBeVisible();
});
+1 -3
Переглянути файл
@@ -5,10 +5,8 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const todoModule = "/src/features/todo/store.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { useTodos } = await import(/* @vite-ignore */ todoModule);
const { showToolWindow } = await import(/* @vite-ignore */ layoutModule);
const directory = "src/features/checkout/shared/services/with-a-long-directory-name/for-order-processing";
const path = `${useProject.getState().project.root}/${directory}/orders.ts`;
useTodos.setState({
@@ -16,9 +14,9 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
error: null,
scanned: new Map([[path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]]]),
});
showToolWindow("todo", true);
});
await page.getByRole("button", { name: "TODO" }).click();
const pane = page.locator('[data-toolwindow="todo"]');
const toolbar = pane.getByRole("toolbar", { name: "TODO actions" });
await expect(toolbar).toHaveAttribute("aria-orientation", "vertical");
+8 -7
Переглянути файл
@@ -20,18 +20,19 @@ run = "pnpm dev:app"
description = "Typecheck, bundle and verify the frontend"
run = "pnpm build"
[tasks."dogfood:local"]
description = "Build and locally install the dogfood desktop app"
run = "pnpm dogfood:local"
[tasks."dogfood:build"]
description = "Build a local dogfood desktop app bundle"
run = "pnpm dogfood:build"
[tasks."dogfood:install"]
description = "Build and install the local dogfood desktop app"
depends = ["dogfood:build"]
run = "pnpm dogfood:install --no-build"
[tasks."dogfood:remote"]
description = "Build and install a local dogfood openidea-server on a configured SSH remote"
run = "pnpm dogfood:remote"
[tasks."dogfood:all"]
description = "Build and install the local dogfood desktop app and remote openidea-server in parallel"
run = "pnpm dogfood:all"
[tasks.test]
description = "Run the frontend and Rust workspace tests"
run = ["pnpm test", "cargo test --workspace"]
+3 -3
Переглянути файл
@@ -34,9 +34,9 @@
"perf:rust": "node perf/rust.ts",
"eval": "node evals/run.ts",
"release:prepare": "node scripts/release-prepare.ts",
"dogfood:local": "node scripts/dogfood.ts local",
"dogfood:remote": "node scripts/dogfood-remote.ts",
"dogfood:all": "node scripts/dogfood.ts all"
"dogfood:build": "node scripts/dogfood.ts build",
"dogfood:install": "node scripts/dogfood.ts install",
"dogfood:remote": "node scripts/dogfood-remote.ts"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
+10 -36
Переглянути файл
@@ -1058,48 +1058,16 @@ async function handleRunningRemoteServers(
}
}
export interface DogfoodRemoteTarget {
remoteConfig: SshRemoteConfig;
remoteContext: RemoteContext;
sshArgs: string[];
version: string;
rustVersion: string;
localDataDir: string;
}
export function resolveDogfoodRemoteTarget(root: string, parsed: DogfoodRemoteArgs): DogfoodRemoteTarget {
export async function runDogfoodRemote(root: string, cliArgs: readonly string[]) {
const parsed = parseDogfoodRemoteArgs(cliArgs);
const { version, rustVersion } = readWorkspaceMetadata(root);
const { configDir, localDataDir } = resolveAppDirs();
const envOpts = (process.env.DOGFOOD_SSH_OPTS ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const extraSshOpts = [...envOpts, ...parsed.sshOpts];
const configs = loadSshConfigs(configDir, root);
const remoteConfig = resolveSshConfig(configs, parsed.remoteName!);
const remoteContext: RemoteContext = {
name: remoteConfig.name,
endpoint: formatRemoteEndpoint(remoteConfig),
};
const sshArgs = buildSshArgs(remoteConfig, extraSshOpts);
return { remoteConfig, remoteContext, sshArgs, version, rustVersion, localDataDir };
}
export async function finishDogfoodRemoteRestart(root: string, parsed: DogfoodRemoteArgs) {
if (parsed.restart === "never" || !parsed.remoteName) return;
const { remoteContext, sshArgs, version, localDataDir } = resolveDogfoodRemoteTarget(root, parsed);
const { os, arch } = probeRemote(sshArgs, remoteContext);
const markerPath = join(localDataDir, "server", version, `${os}-${arch}`, DOGFOOD_MARKER_FILE);
if (!existsSync(markerPath)) return;
const buildId = readFileSync(markerPath, "utf8").trim();
if (!buildId) return;
await handleRunningRemoteServers(sshArgs, remoteContext, buildId, parsed.restart);
}
export async function runDogfoodRemote(root: string, cliArgs: readonly string[]) {
const parsed = parseDogfoodRemoteArgs(cliArgs);
const { version } = readWorkspaceMetadata(root);
const { localDataDir } = resolveAppDirs();
if (parsed.clean && !parsed.remoteName) {
const cleaned = cleanLocalDogfoodServers(localDataDir, version);
@@ -1115,7 +1083,13 @@ export async function runDogfoodRemote(root: string, cliArgs: readonly string[])
return;
}
const { remoteConfig, remoteContext, sshArgs, rustVersion } = resolveDogfoodRemoteTarget(root, parsed);
const configs = loadSshConfigs(configDir, root);
const remoteConfig = resolveSshConfig(configs, parsed.remoteName!);
const remoteContext: RemoteContext = {
name: remoteConfig.name,
endpoint: formatRemoteEndpoint(remoteConfig),
};
const sshArgs = buildSshArgs(remoteConfig, extraSshOpts);
const probe = probeRemote(sshArgs, remoteContext);
const { os, arch } = probe;
const platformKey = `${os}-${arch}`;
+8 -76
Переглянути файл
@@ -6,7 +6,6 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import {
DEFAULT_DOGFOOD_APP_NAME,
deferRestartArgs,
dogfoodBuildEnv,
dogfoodCliArgs,
dogfoodPaths,
@@ -14,85 +13,18 @@ import {
generateDogfoodIcons,
installDogfood,
parseDogfoodArgs,
runParallelTasks,
} from "./dogfood.ts";
const root = fileURLToPath(new URL("..", import.meta.url));
describe("dogfood local and all", () => {
it("parses local and all arguments, including pnpm separator flags", () => {
expect(parseDogfoodArgs(["local"])).toEqual({ action: "local", buildOnly: false });
expect(parseDogfoodArgs(["local", "--build-only"])).toEqual({ action: "local", buildOnly: true });
expect(parseDogfoodArgs(["local", "--", "--build-only"])).toEqual({ action: "local", buildOnly: true });
expect(parseDogfoodArgs(["all", "--", "my-remote", "--build-only", "--restart", "--ssh-opt", "Port=2222"])).toEqual(
{
action: "all",
buildOnly: true,
remoteArgs: ["my-remote", "--restart", "--ssh-opt", "Port=2222"],
remote: {
remoteName: "my-remote",
clean: false,
installRust: false,
restart: "always",
sshOpts: ["Port=2222"],
},
},
);
expect(deferRestartArgs(["my-remote", "--restart", "--ssh-opt", "Port=2222"])).toEqual([
"my-remote",
"--ssh-opt",
"Port=2222",
"--no-restart",
]);
expect(() => parseDogfoodArgs([])).toThrow(/Expected 'local' or 'all'/);
expect(() => parseDogfoodArgs(["build"])).toThrow(/Expected 'local' or 'all'/);
expect(() => parseDogfoodArgs(["local", "my-remote"])).toThrow(/Unexpected option/);
expect(() => parseDogfoodArgs(["all"])).toThrow(/Usage: dogfood:all <remote_name>/);
expect(() => parseDogfoodArgs(["all", "my-remote", "--clean"])).toThrow(/dogfood:remote <remote_name> --clean/);
});
it("runs parallel tasks concurrently, prefixes lines, and terminates siblings on failure", async () => {
const out: string[] = [];
const err: string[] = [];
await runParallelTasks(
[
{
label: "local",
command: process.execPath,
args: ["-e", 'process.stdout.write("step 1\\nstep "); setTimeout(() => process.stdout.write("2"), 40);'],
},
{
label: "remote",
command: process.execPath,
args: ["-e", 'process.stderr.write("warn line\\n"); process.stdout.write("done\\n");'],
},
],
{ stdout: (line) => out.push(line), stderr: (line) => err.push(line) },
);
expect(out).toContain("[local] step 1\n");
expect(out).toContain("[local] step 2\n");
expect(out).toContain("[remote] done\n");
expect(err).toEqual(["[remote] warn line\n"]);
const started = Date.now();
await expect(
runParallelTasks(
[
{
label: "local",
command: process.execPath,
args: ["-e", "setTimeout(() => {}, 10_000)"],
},
{
label: "remote",
command: process.execPath,
args: ["-e", "setTimeout(() => process.exit(2), 50)"],
},
],
{ stdout: () => {}, stderr: () => {} },
),
).rejects.toThrow(/\[remote\] exited with status 2/);
expect(Date.now() - started).toBeLessThan(3_000);
describe("dogfood build and install", () => {
it("parses build and install arguments, including pnpm separator flags", () => {
expect(parseDogfoodArgs(["build"])).toEqual({ action: "build", skipBuild: false });
expect(parseDogfoodArgs(["install"])).toEqual({ action: "install", skipBuild: false });
expect(parseDogfoodArgs(["install", "--no-build"])).toEqual({ action: "install", skipBuild: true });
expect(parseDogfoodArgs(["install", "--", "--no-build"])).toEqual({ action: "install", skipBuild: true });
expect(() => parseDogfoodArgs([])).toThrow(/Expected 'build' or 'install'/);
expect(() => parseDogfoodArgs(["build", "--no-build"])).toThrow(/Unexpected option/);
});
it("keeps the vanilla app identifier so settings, MCP, Skills and agent sessions are shared, without updates", () => {
+22 -199
Переглянути файл
@@ -1,4 +1,4 @@
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import {
chmodSync,
@@ -16,29 +16,16 @@ import { createRequire } from "node:module";
import { homedir } from "node:os";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import {
finishDogfoodRemoteRestart,
parseDogfoodRemoteArgs,
resolveDogfoodRemoteTarget,
type DogfoodRemoteArgs,
} from "./dogfood-remote.ts";
export const DEFAULT_DOGFOOD_APP_NAME = "openidea_dogfood";
const LSREGISTER_PATH =
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
export type DogfoodCommand =
| {
action: "local";
buildOnly: boolean;
}
| {
action: "all";
buildOnly: boolean;
remoteArgs: string[];
remote: DogfoodRemoteArgs;
};
export interface DogfoodCommand {
action: "build" | "install";
skipBuild: boolean;
}
export interface DogfoodPaths {
bundlePath: string;
@@ -48,39 +35,18 @@ export interface DogfoodPaths {
export function parseDogfoodArgs(args: readonly string[]): DogfoodCommand {
const filtered = args.filter((arg) => arg !== "--");
const action = filtered[0];
if (action !== "local" && action !== "all") {
throw new Error(`Expected 'local' or 'all', got ${action ? `'${action}'` : "no command"}`);
if (action !== "build" && action !== "install") {
throw new Error(`Expected 'build' or 'install', got ${action ? `'${action}'` : "no command"}`);
}
let buildOnly = false;
const rest: string[] = [];
for (const arg of filtered.slice(1)) {
if (arg === "--build-only") {
buildOnly = true;
} else if (action === "local") {
throw new Error(`Unexpected option '${arg}' for 'local'`);
let skipBuild = false;
for (const flag of filtered.slice(1)) {
if (action === "install" && flag === "--no-build") {
skipBuild = true;
} else {
rest.push(arg);
throw new Error(`Unexpected option '${flag}' for '${action}'`);
}
}
if (action === "local") {
return { action: "local", buildOnly };
}
if (rest.includes("--clean")) {
throw new Error("Unexpected option '--clean' for 'all'; use 'dogfood:remote <remote_name> --clean' instead");
}
let remote: DogfoodRemoteArgs;
try {
remote = parseDogfoodRemoteArgs(rest);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
message.startsWith("Usage:")
? "Usage: dogfood:all <remote_name> [--build-only] [--install-rust] [--restart | --no-restart] [--ssh-opt key=value]"
: message,
{ cause: error },
);
}
return { action: "all", buildOnly, remoteArgs: rest, remote };
return { action, skipBuild };
}
/**
@@ -252,7 +218,7 @@ export function buildDogfood(root: string, appName: string) {
const SHARED_DATA_NOTES = [
"The dogfood app shares its single instance with OpenIDEA: quit one before opening the other.",
"It writes OpenIDEA's settings and data; a setting only newer builds know can make an older OpenIDEA ignore your settings file.",
"It never updates itself: run 'pnpm dogfood:local' again to pick up new changes.",
"It never updates itself: run 'pnpm dogfood:install' again to pick up new changes.",
];
export function installDogfood(
@@ -274,7 +240,7 @@ function installBundle(
installPath: string,
) {
if (!existsSync(bundlePath)) {
throw new Error(`Dogfood build output not found at ${bundlePath}; run 'mise run dogfood:local --build-only' first`);
throw new Error(`Dogfood build output not found at ${bundlePath}; run 'mise run dogfood:build' first`);
}
if (platform === "darwin") {
@@ -331,164 +297,21 @@ function installBundle(
console.log(`Installed ${appName} to ${installPath}`);
}
export interface ParallelTaskSpec {
label: string;
command: string;
args: string[];
cwd?: string;
env?: NodeJS.ProcessEnv;
}
function stopProcessTree(child: ChildProcess, signal: NodeJS.Signals) {
if (!child.pid) return;
if (process.platform === "win32") {
spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
} else {
try {
process.kill(-child.pid, signal);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
}
}
}
function pipePrefixedLines(
stream: NodeJS.ReadableStream | null,
prefix: string,
writeLine: (line: string) => void,
): Promise<void> {
if (!stream) return Promise.resolve();
return new Promise((resolve) => {
let remainder = "";
stream.setEncoding("utf8");
stream.on("data", (chunk: string) => {
remainder += chunk;
let newline = remainder.indexOf("\n");
while (newline !== -1) {
const line = remainder.slice(0, newline).replace(/\r$/, "");
writeLine(`[${prefix}] ${line}\n`);
remainder = remainder.slice(newline + 1);
newline = remainder.indexOf("\n");
}
});
stream.on("end", () => {
if (remainder.length > 0) {
writeLine(`[${prefix}] ${remainder.replace(/\r$/, "")}\n`);
}
resolve();
});
stream.on("error", () => resolve());
});
}
export async function runParallelTasks(
specs: readonly ParallelTaskSpec[],
writers: {
stdout?: (text: string) => void;
stderr?: (text: string) => void;
} = {},
): Promise<void> {
const writeOut = writers.stdout ?? ((text: string) => process.stdout.write(text));
const writeErr = writers.stderr ?? ((text: string) => process.stderr.write(text));
const children: ChildProcess[] = [];
let firstError: Error | null = null;
let killTimer: ReturnType<typeof setTimeout> | undefined;
const stopAll = (signal: NodeJS.Signals) => {
for (const child of children) stopProcessTree(child, signal);
if (signal === "SIGTERM") {
killTimer ??= setTimeout(() => {
for (const child of children) stopProcessTree(child, "SIGKILL");
}, 5000);
killTimer.unref();
}
};
const onSigint = () => stopAll("SIGTERM");
const onSigterm = () => stopAll("SIGTERM");
process.on("SIGINT", onSigint);
process.on("SIGTERM", onSigterm);
try {
await Promise.all(
specs.map(
(spec) =>
new Promise<void>((resolve) => {
const child = spawn(spec.command, spec.args, {
cwd: spec.cwd,
env: spec.env,
stdio: ["ignore", "pipe", "pipe"],
detached: process.platform !== "win32",
});
children.push(child);
const outDone = pipePrefixedLines(child.stdout, spec.label, writeOut);
const errDone = pipePrefixedLines(child.stderr, spec.label, writeErr);
child.once("error", (err) => {
if (!firstError) {
firstError = new Error(`[${spec.label}] ${err.message}`);
stopAll("SIGTERM");
}
void Promise.all([outDone, errDone]).then(() => resolve());
});
child.once("close", (code, signal) => {
if (code !== 0 && !firstError) {
firstError = new Error(
`[${spec.label}] exited with ${code !== null ? `status ${code}` : `signal ${signal}`}`,
);
stopAll("SIGTERM");
}
void Promise.all([outDone, errDone]).then(() => resolve());
});
}),
),
);
} finally {
if (killTimer) clearTimeout(killTimer);
process.off("SIGINT", onSigint);
process.off("SIGTERM", onSigterm);
}
if (firstError) throw firstError;
}
export function deferRestartArgs(remoteArgs: readonly string[]): string[] {
return [...remoteArgs.filter((arg) => arg !== "--restart" && arg !== "--no-restart"), "--no-restart"];
}
async function runDogfoodAll(root: string, command: Extract<DogfoodCommand, { action: "all" }>) {
// Validate the SSH remote exists in settings.toml before starting the local Cargo build.
resolveDogfoodRemoteTarget(root, command.remote);
const localArgs = [join(root, "scripts", "dogfood.ts"), "local"];
if (command.buildOnly) localArgs.push("--build-only");
const remoteScriptArgs = [join(root, "scripts", "dogfood-remote.ts"), ...deferRestartArgs(command.remoteArgs)];
await runParallelTasks([
{ label: "local", command: process.execPath, args: localArgs, cwd: root, env: process.env },
{ label: "remote", command: process.execPath, args: remoteScriptArgs, cwd: root, env: process.env },
]);
await finishDogfoodRemoteRestart(root, command.remote);
}
async function main() {
function main() {
const root = realpathSync(fileURLToPath(new URL("..", import.meta.url)));
const parsed = parseDogfoodArgs(process.argv.slice(2));
if (parsed.action === "all") {
await runDogfoodAll(root, parsed);
return;
}
const { action, skipBuild } = parseDogfoodArgs(process.argv.slice(2));
const appName = process.env.DOGFOOD_APP_NAME?.trim() || DEFAULT_DOGFOOD_APP_NAME;
buildDogfood(root, appName);
if (!parsed.buildOnly) {
if (action === "build" || !skipBuild) {
buildDogfood(root, appName);
}
if (action === "install") {
installDogfood(root, appName);
}
}
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
try {
await main();
main();
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
+8 -1
Переглянути файл
@@ -252,10 +252,17 @@ pub fn window_take_settings_init(
let owner = AppState::owner_window(window.label());
let launch = windows.take_launch(window.label());
let (remote, project) = if let Some(c) = state.remote_dev.get(owner) {
let session = crate::remote_dev::RemoteSession {
target: c.target.clone(),
root: c.root.clone(),
host: c.host.clone(),
os: c.os.clone(),
commands: c.commands.clone(),
};
// Leave `project` empty on remote sessions: the Settings page tree renders immediately
// from local client settings, and `projectCurrent()` fills in project-scoped settings
// right after first paint without keeping a shadow cache in sync.
(Some(c.snapshot()), None)
(Some(session), None)
} else {
let project = state.project(owner).ok().filter(|p| !p.light).map(|p| ide_host::ops::project::info(&p));
(None, project)
-1
Переглянути файл
@@ -249,7 +249,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("remote.connect", "Remote Development…"),
act("remote.reopenInContainer", "Reopen in Container"),
act("remote.disconnect", "Disconnect from Remote Host"),
act("remote.stopBackend", "Stop Remote Backend"),
act("remote.reloadEnvironment", "Reload Environment"),
SEP,
act("file.save", "Save All"),
+11 -62
Переглянути файл
@@ -172,7 +172,7 @@ fn server_args(up: &Up, bin: &str) -> Vec<String> {
] {
args.extend(["-e".to_owned(), var]);
}
args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]);
args.extend([up.container.clone(), bin.to_owned(), "--stdio".to_owned()]);
args
}
@@ -253,8 +253,7 @@ mod tests {
"OPENIDEA_LIFECYCLE_DONE=1",
ID,
"/home/vscode/.openidea/server/1/ab/openidea-server",
"--attach",
"/workspaces/my app",
"--stdio",
]
);
}
@@ -333,12 +332,10 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
#[tokio::test]
#[ignore = "requires Docker, the Dev Containers CLI, OPENIDEA_DOCKER_TEST_DIR and OPENIDEA_SERVER_BIN"]
async fn opens_a_real_dev_container() {
use serde_json::{Value, json};
let base = PathBuf::from(std::env::var("OPENIDEA_DOCKER_TEST_DIR").expect("OPENIDEA_DOCKER_TEST_DIR"));
let server = PathBuf::from(std::env::var("OPENIDEA_SERVER_BIN").expect("OPENIDEA_SERVER_BIN"));
let workspace = tempfile::Builder::new().prefix("openidea-devcontainer-").tempdir_in(base).unwrap();
let root = workspace.path();
let root = base.join("devcontainer");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join(".devcontainer")).unwrap();
std::fs::write(
root.join(".devcontainer/devcontainer.json"),
@@ -353,19 +350,10 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
std::fs::write(root.join("main.py"), "print('hello')\n").unwrap();
let docker = ide_docker::docker_executable().expect("docker");
let tail = Tail::default();
let up = up(Path::new("devcontainer"), &docker, root, "", &tail)
let up = up(Path::new("devcontainer"), &docker, &root, "", &tail)
.await
.unwrap_or_else(|e| panic!("{e:?}; the CLI said: {}", tail.text()));
struct RemoveContainer<'a>(&'a Path, &'a str);
impl Drop for RemoveContainer<'_> {
fn drop(&mut self) {
if let Err(e) = std::process::Command::new(self.0).args(["rm", "-f", self.1]).status() {
eprintln!("could not remove dev container {}: {e}", self.1);
}
}
}
let _container = RemoveContainer(&docker, &up.container);
assert_eq!(up.folder, format!("/workspaces/{}", root.file_name().unwrap().to_string_lossy()));
assert_eq!(up.folder, "/workspaces/devcontainer");
assert_eq!(up.user, "root");
let found = probe(&docker, &up, "0.0.0-test").await.unwrap();
assert_eq!(platform_os(&found.uname), "linux");
@@ -386,7 +374,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
.request("invoke", invoke("open_project", serde_json::json!({ "path": up.folder })), None)
.await
.unwrap_or_else(|e| panic!("{e:?}; the server said: {}", tail.text()));
assert_eq!(project["root"], up.folder);
assert_eq!(project["root"], "/workspaces/devcontainer");
assert_eq!(project["trusted"], true, "the trust of the local folder is inherited");
let files: serde_json::Value = peer
.request("invoke", invoke("fs_read_dir", serde_json::json!({ "path": up.folder })), None)
@@ -422,49 +410,10 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
}
assert_eq!(reply, "from the container\n");
drop(tunnel);
let term: Value = peer
.request(
"invoke",
invoke(
"term_spawn",
json!({
"options": {
"cwd": up.folder, "shell": "/bin/sh", "args": ["-c", "exec sleep 300"],
"env": {}, "cols": 80, "rows": 24, "shellIntegration": false
},
"onOutput": { "$channel": 1 }
}),
),
None,
)
.await
.unwrap();
let pid = term["pid"].as_u64().unwrap();
peer.kill();
peer.exited().await;
let live = || docker_sh(&docker, &up.container, &format!("kill -0 {pid} 2>/dev/null && printf live"));
assert_eq!(live(), "live", "the terminal must outlive the window in a dev container");
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &Tail::default()).unwrap();
tokio::time::timeout(Duration::from_secs(30), async {
let project: Value = peer.request("invoke", invoke("project_current", json!({})), None).await.unwrap();
assert_eq!(project["root"], up.folder);
let terms: Value = peer.request("invoke", invoke("term_list", json!({})), None).await.unwrap();
assert_eq!(terms[0]["id"], term["id"]);
peer.request::<_, ()>("shutdown", Value::Null, None).await.unwrap();
peer.closed().await;
})
.await
.expect("dev container backend did not reattach and stop");
assert_eq!(docker_sh(&docker, &up.container, "printf running"), "running", "stopping the IDE keeps Docker up");
for _ in 0..50 {
if live().is_empty() {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("terminal process {pid} outlived backend shutdown");
drop(peer);
let removed = std::process::Command::new(&docker).args(["rm", "-f", &up.container]).output().unwrap();
assert!(removed.status.success());
std::fs::remove_dir_all(&root).unwrap();
}
fn platform_os(uname: &str) -> String {
+24 -131
Переглянути файл
@@ -8,7 +8,7 @@ use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::{EventSink, IdeError, IdeResult};
use ide_host::catalogue::TrustClass;
use ide_host::rpc::{ChannelMessage, EventMessage, Invoke, RemoteIdlePolicy, ServerInfo};
use ide_host::rpc::{ChannelMessage, EventMessage, Invoke, ServerInfo};
use ide_jsonrpc::{Handler, Peer};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
@@ -16,8 +16,6 @@ use serde_json::Value;
use specta::Type;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use tauri::ipc::Channel;
use tauri::{AppHandle, Manager, State, Window};
@@ -57,20 +55,12 @@ pub(crate) const SERVER_DIR: &str = ".openidea/server";
/// File name of the server binary on every host.
pub(crate) const SERVER_BIN: &str = "openidea-server";
/// Canonical window key sent to the per-project `openidea-server` daemon, so
/// reopening the project in another desktop window (`main` vs `project-1`)
/// rebinds to the same open project and live terminal sessions on the server.
const SERVER_WINDOW: &str = "main";
/// Printed before a probe's answer: shell start-up files and `wsl.exe` may print first.
pub(crate) const PROBE_MARK: &str = "__OPENIDEA_PROBE__";
/// One remote window's connection.
pub struct Connection {
peer: Peer,
stopping: AtomicBool,
taken_over: Arc<AtomicBool>,
idle_policy: Option<RemoteIdlePolicy>,
pub target: RemoteTarget,
pub root: String,
pub host: String,
@@ -128,18 +118,6 @@ pub struct Connections {
}
impl Connection {
pub(crate) fn snapshot(&self) -> RemoteSession {
RemoteSession {
target: self.target.clone(),
root: self.root.clone(),
host: self.host.clone(),
os: self.os.clone(),
commands: self.commands.clone(),
idle_policy: self.idle_policy,
taken_over: self.taken_over.load(Ordering::Acquire),
}
}
/// Commands of a remote window that run on this machine follow this machine's decision about the
/// remote project, never the server's: the server only answers for what runs there. A remote
/// window always has a project, so only `Always` runs before it is trusted.
@@ -358,8 +336,6 @@ pub struct RemoteProject {
pub host: String,
pub server_version: String,
pub os: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idle_policy: Option<RemoteIdlePolicy>,
/// Commands routed to the server (the rest run locally).
pub commands: Vec<String>,
pub project: ide_host::ops::project::ProjectInfo,
@@ -370,7 +346,6 @@ struct ClientHandler {
window: String,
channels: Channels,
connection: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>>,
taken_over: Arc<AtomicBool>,
}
impl Handler for ClientHandler {
@@ -419,10 +394,6 @@ impl Handler for ClientHandler {
AUTH_REQUEST, AuthRequest, SECRET_REQUEST, SECRET_WRITE, SecretRequest, SecretWrite,
};
match method {
ide_host::rpc::SESSION_REPLACED => {
self.taken_over.store(true, Ordering::Release);
Ok(Value::Null)
}
// A remote plugin's request header needs a secret from this machine's keychain.
SECRET_REQUEST => {
let r: SecretRequest =
@@ -669,13 +640,11 @@ pub async fn remote_connect(
let attempt = state.remote_dev.begin(&label);
let channels: Channels = Arc::default();
let connection_slot: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>> = Arc::default();
let taken_over = Arc::new(AtomicBool::new(false));
let handler = Arc::new(ClientHandler {
app: window.app_handle().clone(),
window: label.clone(),
channels: channels.clone(),
connection: connection_slot.clone(),
taken_over: taken_over.clone(),
});
let tail = crate::remote_wsl::Tail::default();
let mut exec = None;
@@ -685,29 +654,17 @@ pub async fn remote_connect(
let session = state.ssh.session(id).await?;
let bin = ensure_server(&state, &session, progress.clone()).await?;
progress(RemoteStage::Starting, None);
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
let stream = session
.exec_stream(&format!(
"{} --attach {} 2>&1",
ide_ssh::shell::tilde_quote(&bin),
ide_ssh::shell::quote(attach_arg),
))
.exec_stream(&format!("{} --stdio", ide_ssh::shell::tilde_quote(&bin)))
.await
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
let (reader, writer) = tokio::io::split(stream);
let output = tail.clone();
(
Peer::connect_with_output(reader, writer, handler, move |line| output.push(line)),
Some(session),
config.label(),
config.label(),
)
(Peer::connect(reader, writer, handler), Some(session), config.label(), config.label())
}
RemoteTarget::Wsl { distro } => {
let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?;
progress(RemoteStage::Starting, None);
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?;
let peer = crate::remote_wsl::spawn(distro, &bin, handler, &tail)?;
(peer, None, distro.clone(), format!("WSL: {distro}"))
}
RemoteTarget::DevContainer { folder, config } => {
@@ -754,8 +711,7 @@ pub async fn remote_connect(
path.trim().to_owned()
};
progress(RemoteStage::Opening, None);
let call =
Invoke { window: SERVER_WINDOW.into(), cmd: "open_project".into(), args: serde_json::json!({ "path": root }) };
let call = Invoke { window: label.clone(), cmd: "open_project".into(), args: serde_json::json!({ "path": root }) };
let project: ide_host::ops::project::ProjectInfo =
peer.request("invoke", call, None).await.map_err(ide_host::rpc::error_from_reply)?;
// As the server resolved it (symlinks, a trailing `/`): the frontend compares it with the project's.
@@ -766,9 +722,6 @@ pub async fn remote_connect(
let _ = window.set_title(&format!("{} [{title_tag}]", project.display_name));
let connection = Arc::new(Connection {
peer,
stopping: AtomicBool::new(false),
taken_over: taken_over.clone(),
idle_policy: info.idle_policy,
target: target.clone(),
root: root.clone(),
host: host.clone(),
@@ -801,22 +754,16 @@ pub async fn remote_connect(
let app = window.app_handle().clone();
tauri::async_runtime::spawn(async move {
peer.closed().await;
let current = app.state::<AppState>().remote_dev.get(&auth_window);
if current.is_none() {
auth_plugins.forget_remote_loopbacks(&auth_window);
}
auth_plugins.forget_remote_loopbacks(&auth_window);
let Some(connection) = weak.upgrade() else { return };
connection.forwards.lock().clear();
// Still the window's connection: not a disconnect or a replacement, so the window learns
// its project is unreachable instead of failing every command with "connection closed".
let current = app.state::<AppState>().remote_dev.get(&auth_window);
if current.is_some_and(|c| Arc::ptr_eq(&c, &connection)) {
auth_plugins.forget_remote_loopbacks(&auth_window);
if !connection.stopping.load(Ordering::Acquire) || taken_over.load(Ordering::Acquire) {
let taken_over = taken_over.load(Ordering::Acquire);
tracing::info!(host = connection.host, taken_over, "remote backend disconnected");
TauriSink { app, window: Some(auth_window) }
.emit(ide_core::IdeEvent::RemoteConnectionLost { host: connection.host.clone(), taken_over });
}
tracing::warn!("{}: the connection to openidea-server was lost", connection.host);
TauriSink { app, window: Some(auth_window) }
.emit(ide_core::IdeEvent::RemoteConnectionLost { host: connection.host.clone() });
}
});
let plugins = state.plugins.clone();
@@ -827,25 +774,16 @@ pub async fn remote_connect(
if let Err(error) = crate::window_groups::persist(window.app_handle()).await {
tracing::warn!(%error, "cannot save window session after opening remote project");
}
Ok(RemoteProject {
target,
root,
host,
server_version: info.version,
os: info.os,
idle_policy: info.idle_policy,
commands,
project,
})
Ok(RemoteProject { target, root, host, server_version: info.version, os: info.os, commands, project })
}
/// Sends the desktop's plugin languages, with the programs granted to them, to
/// the window's server: `Workspace` contributions take effect where the project
/// is. A server without the command answers an error, which is logged.
pub async fn sync_plugin_languages(plugins: &ide_host::plugins::PluginHost, c: &Connection, _window: &str) {
pub async fn sync_plugin_languages(plugins: &ide_host::plugins::PluginHost, c: &Connection, window: &str) {
use ide_host::plugins::remote::{SYNC_COMMAND, SyncReport};
let call = Invoke {
window: SERVER_WINDOW.to_owned(),
window: window.to_owned(),
cmd: SYNC_COMMAND.into(),
args: serde_json::json!({ "languages": plugins.remote_languages() }),
};
@@ -865,12 +803,12 @@ pub async fn sync_plugin_languages(plugins: &ide_host::plugins::PluginHost, c: &
/// Sends the desktop's live code plugins to the window's server, which runs
/// them next to the project: digests and grants first,
/// then the files of the packages the server lacks, one per request.
pub async fn sync_plugin_packages(plugins: &Arc<ide_host::plugins::PluginHost>, c: &Connection, _window: &str) {
pub async fn sync_plugin_packages(plugins: &Arc<ide_host::plugins::PluginHost>, c: &Connection, window: &str) {
use ide_host::plugins::remote_host::{PackageSyncReport, SYNC_PACKAGES};
let host = plugins.clone();
let Ok(packages) = tauri::async_runtime::spawn_blocking(move || host.remote_packages()).await else { return };
let sync = |files: serde_json::Value| Invoke {
window: SERVER_WINDOW.to_owned(),
window: window.to_owned(),
cmd: SYNC_PACKAGES.into(),
args: serde_json::json!({ "packages": packages, "files": files }),
};
@@ -916,10 +854,6 @@ pub struct RemoteSession {
/// `linux`, `macos` or `windows`: the OS the project's commands run on.
pub os: String,
pub commands: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idle_policy: Option<RemoteIdlePolicy>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub taken_over: bool,
}
/// The remote session of this window (a settings window: its parent's), if any.
@@ -928,7 +862,13 @@ pub struct RemoteSession {
#[specta::specta]
pub fn remote_current(window: Window, state: State<'_, AppState>) -> Option<RemoteSession> {
let c = state.remote_dev.get(AppState::owner_window(window.label()))?;
Some(c.snapshot())
Some(RemoteSession {
target: c.target.clone(),
root: c.root.clone(),
host: c.host.clone(),
os: c.os.clone(),
commands: c.commands.clone(),
})
}
/// This machine's trust decision for the window's remote project (see [`Connection::authorize`]).
@@ -951,16 +891,7 @@ pub fn remote_trust_status(window: Window, state: State<'_, AppState>) -> IdeRes
#[specta::specta]
pub fn remote_trust_set(window: Window, state: State<'_, AppState>, trusted: bool) -> IdeResult<()> {
let c = connection(&window, &state)?;
state.host.trust.decide_remote(&c.location(), trusted)?;
if trusted {
let plugins = state.plugins.clone();
let label = AppState::owner_window(window.label()).to_owned();
tauri::async_runtime::spawn(async move {
sync_plugin_languages(&plugins, &c, &label).await;
sync_plugin_packages(&plugins, &c, &label).await;
});
}
Ok(())
state.host.trust.decide_remote(&c.location(), trusted)
}
/// A port of the remote host reachable on this machine at `localhost:local_port`.
@@ -1166,40 +1097,6 @@ pub fn remote_disconnect(window: Window, state: State<'_, AppState>) {
state.remote_dev.disconnect(AppState::owner_window(window.label()));
}
/// Stops the persistent `openidea-server` daemon for this window's remote project,
/// terminating its terminals, runs, language servers and agent sessions, then disconnects.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn remote_stop_backend(window: Window, state: State<'_, AppState>) -> IdeResult<()> {
let label = AppState::owner_window(window.label()).to_owned();
let c = connection(&window, &state)?;
if c.stopping.swap(true, Ordering::AcqRel) {
return Err(IdeError::unavailable("The remote backend is already stopping"));
}
let result: IdeResult<()> = async {
tokio::time::timeout(Duration::from_secs(10), c.peer.request::<_, Value>("shutdown", Value::Null, None))
.await
.map_err(|_| IdeError::unavailable("The remote backend did not respond to the shutdown request"))?
.map_err(ide_host::rpc::error_from_reply)?;
tokio::time::timeout(ide_host::rpc::SHUTDOWN_TIMEOUT, c.peer.closed())
.await
.map_err(|_| IdeError::unavailable("Timed out waiting for the remote backend to stop"))?;
Ok(())
}
.await;
if result.is_err() {
c.stopping.store(false, Ordering::Release);
}
result?;
let mut connections = state.remote_dev.windows.lock();
if connections.get(&label).is_some_and(|current| Arc::ptr_eq(current, &c)) {
connections.remove(&label);
state.host.mcp_reports.remove_remote(&label);
}
Ok(())
}
/// Runs a command on the window's remote server; `args` and the result are JSON
/// text. Streaming arguments are `{ "$channel": id }`; their values arrive on
/// `on_channel` tagged with the id.
@@ -1253,7 +1150,7 @@ pub async fn remote_invoke(
None
};
let web_url = cmd == "web_url";
let call = Invoke { window: SERVER_WINDOW.into(), cmd, args };
let call = Invoke { window: label, cmd, args };
let reply = invoke_reply(&c.peer, call, std::time::Duration::from_secs(30)).await;
// These commands finish streaming before their reply. Other commands may retain their channels.
if let Some(id) = finite_channel {
@@ -1509,9 +1406,6 @@ mod tests {
std::mem::forget(Peer::connect(reader, writer, Arc::new(TrustingServer)));
Connection {
peer,
stopping: AtomicBool::new(false),
taken_over: Arc::default(),
idle_policy: None,
target,
root: root.into(),
host: "host".into(),
@@ -1612,7 +1506,6 @@ ide_command::desktop_domain!(
remote_forwarded_ports,
remote_import_local,
remote_invoke,
remote_stop_backend,
remote_stop_forwarding,
remote_trust_set,
remote_trust_status,
+10 -22
Переглянути файл
@@ -182,27 +182,15 @@ impl Tail {
}
}
/// Starts `bin --attach <project_path>` in `distro` and speaks the protocol over its stdio.
pub(crate) fn spawn(
distro: &str,
bin: &str,
project_path: &str,
handler: Arc<dyn Handler>,
tail: &Tail,
) -> IdeResult<Peer> {
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, handler, tail)
/// Starts `bin --stdio` in `distro` and speaks the protocol over its stdio. The process dies
/// with the connection.
pub(crate) fn spawn(distro: &str, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
spawn_with(ide_core::wsl::EXE, distro, bin, handler, tail)
}
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
fn spawn_with(
launcher: &str,
distro: &str,
bin: &str,
project_path: &str,
handler: Arc<dyn Handler>,
tail: &Tail,
) -> IdeResult<Peer> {
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
fn spawn_with(launcher: &str, distro: &str, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--stdio"].map(str::to_owned).into();
let tail = tail.clone();
Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line)))
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))
@@ -286,12 +274,12 @@ mod tests {
#[tokio::test]
async fn speaks_the_protocol_through_the_launcher_after_its_utf16_notice() {
use std::os::unix::fs::PermissionsExt;
let (distro, bin, project) = ("Debian-12", "/home/me/server", "/home/me/proj");
let (distro, bin) = ("Debian-12", "/home/me/server");
let dir = tempfile::tempdir().unwrap();
let launcher = dir.path().join("fake-wsl");
let script = format!(
r#"#!/bin/sh
[ "$*" = "-d {distro} --exec {bin} --attach {project}" ] || {{ echo "unexpected arguments: $*" >&2; exit 2; }}
[ "$*" = "-d {distro} --exec {bin} --stdio" ] || {{ echo "unexpected arguments: $*" >&2; exit 2; }}
printf '\377\376N\000o\000\r\000\n\000'
while read -r line; do
line=${{line%?}}
@@ -305,7 +293,7 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
std::fs::write(&launcher, script).unwrap();
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
let tail = Tail::default();
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, Arc::new(Silent), &tail).unwrap();
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, Arc::new(Silent), &tail).unwrap();
let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| {
panic!("{e:?}; launcher said: {}", tail.text());
});
@@ -314,7 +302,7 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
#[tokio::test]
async fn a_bad_distro_name_never_starts_the_launcher() {
let err = spawn_with("does-not-exist", "-d", "/x", "~", Arc::new(Silent), &Tail::default()).err().unwrap();
let err = spawn_with("does-not-exist", "-d", "/x", Arc::new(Silent), &Tail::default()).err().unwrap();
assert!(err.message.contains("not a valid"), "{}", err.message);
}
}
-5
Переглянути файл
@@ -542,7 +542,6 @@ remote_download_into trusted project_host bin
remote_download_local trusted desktop bindings async
remote_forward_port trusted desktop bindings async
remote_forwarded_ports trusted desktop bindings sync
remote_idle_timeout_minutes always project_host bindings async
remote_import_local trusted desktop bindings async
remote_invoke always desktop bindings async
remote_list always project_host bindings async
@@ -550,7 +549,6 @@ remote_mkdir trusted project_host bin
remote_of always project_host bindings sync
remote_open always project_host bindings async
remote_rename trusted project_host bindings async
remote_stop_backend always desktop bindings async
remote_stop_forwarding trusted desktop bindings async
remote_trust_set always desktop bindings sync
remote_trust_status always desktop bindings sync
@@ -561,7 +559,6 @@ replace_preview trusted project_host bin
run_application_build trusted project_host bindings async
run_application_publish trusted project_host bindings async
run_apply_settings trusted project_host bindings async
run_attach always project_host bindings async
run_close_stdin trusted project_host bindings sync
run_configs trusted project_host bindings async
run_dotnet_resolve trusted project_host bindings async
@@ -652,12 +649,10 @@ syntax_structural_ranges always project_host bin
syntax_support always project_host bindings sync
system_font_families always desktop bindings async
system_probe_hotkeys trusted desktop bindings sync
term_attach always project_host bindings async
term_available_shells always project_host bindings sync
term_default_shell always project_host bindings sync
term_is_busy always project_host bindings async
term_kill always project_host bindings sync
term_list always project_host bindings async
term_resize always project_host bindings sync
term_spawn always project_host bindings async
term_store_image always project_host bindings async
+8 -94
Переглянути файл
@@ -1456,8 +1456,6 @@ export const commands = {
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
os: string,
commands: string[],
idlePolicy?: RemoteIdlePolicy | null,
takenOver?: boolean,
} | null>("remote_current"),
remoteDelete: (connection: FsConnection, path: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_delete", { connection, path })),
remoteDisconnect: () => __TAURI_INVOKE<void>("remote_disconnect"),
@@ -1475,11 +1473,6 @@ export const commands = {
remoteForwardPort: (remotePort: number) => typedError<ForwardedPort, IdeError>(__TAURI_INVOKE("remote_forward_port", { remotePort })),
/** The remote ports this window forwards to this machine. */
remoteForwardedPorts: () => __TAURI_INVOKE<ForwardedPort[]>("remote_forwarded_ports"),
/**
* Read the same host-wide value for the close dialog and the idle timer: another project's
* daemon may have edited the file since this host loaded its settings.
*/
remoteIdleTimeoutMinutes: () => typedError<number, IdeError>(__TAURI_INVOKE("remote_idle_timeout_minutes")),
/** A client OS file belongs to this machine even when its destination is remote. */
remoteImportLocal: (from: string, to: string, request: RequestId) => typedError<string[], IdeError>(__TAURI_INVOKE("remote_import_local", { from, to, request })),
/**
@@ -1493,11 +1486,6 @@ export const commands = {
remoteOf: (path: IpcPath) => __TAURI_INVOKE<[FsConnection, string] | null>("remote_of", { path }),
remoteOpen: (connection: FsConnection, path: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("remote_open", { connection, path })),
remoteRename: (connection: FsConnection, from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_rename", { connection, from, to })),
/**
* Stops the persistent `openidea-server` daemon for this window's remote project,
* terminating its terminals, runs, language servers and agent sessions, then disconnects.
*/
remoteStopBackend: () => typedError<null, IdeError>(__TAURI_INVOKE("remote_stop_backend")),
/** Stops forwarding `remote_port` of `host` (`None`: the remote host itself). */
remoteStopForwarding: (remotePort: number, host: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("remote_stop_forwarding", { remotePort, host })),
/** Records the user's trust decision for the window's remote project on this machine. */
@@ -1526,11 +1514,6 @@ export const commands = {
runApplicationPublish: (config: RunConfig_Deserialize, classPaths: string[], mainClass: string) => typedError<null, IdeError>(__TAURI_INVOKE("run_application_publish", { config, classPaths, mainClass })),
/** Kept temporary configurations with the current settings applied. */
runApplySettings: (configs: RunConfig_Deserialize[]) => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_apply_settings", { configs })),
/**
* Reattaches to a running process `id` on this host, returning its buffered output
* and configuration while streaming subsequent chunks to `on_output`.
*/
runAttach: (id: RunId, onOutput: Channel<OutputChunk>) => typedError<RunAttach_Serialize, IdeError>(__TAURI_INVOKE("run_attach", { id, onOutput })),
runCloseStdin: (id: RunId) => typedError<null, IdeError>(__TAURI_INVOKE("run_close_stdin", { id })),
/** Detected configs followed by user-defined ones (user ids win on conflict). */
runConfigs: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_configs")),
@@ -1870,11 +1853,6 @@ export const commands = {
* already registered to another app. Empty everywhere but Windows.
*/
systemProbeHotkeys: (combos: string[]) => typedError<string[], IdeError>(__TAURI_INVOKE("system_probe_hotkeys", { combos })),
/**
* Reattaches to an existing terminal session `id`, returning its buffered output
* and streaming subsequent chunks to `on_output`.
*/
termAttach: (id: TerminalId, cols: number, rows: number, onOutput: Channel<string>) => typedError<TerminalAttach, IdeError>(__TAURI_INVOKE("term_attach", { id, cols, rows, onOutput })),
/** Installed shells for the Terminal's "New Predefined Session" menu. */
termAvailableShells: () => __TAURI_INVOKE<string[]>("term_available_shells"),
/** Shell used when Settings › Terminal › Shell path is empty. */
@@ -1885,8 +1863,6 @@ export const commands = {
*/
termIsBusy: (id: TerminalId) => typedError<boolean, IdeError>(__TAURI_INVOKE("term_is_busy", { id })),
termKill: (id: TerminalId) => typedError<null, IdeError>(__TAURI_INVOKE("term_kill", { id })),
/** Live terminal sessions of this window, for reattaching after a reconnect. */
termList: () => __TAURI_INVOKE<TerminalSessionInfo[]>("term_list"),
termResize: (id: TerminalId, cols: number, rows: number) => typedError<null, IdeError>(__TAURI_INVOKE("term_resize", { id, cols, rows })),
/**
* Async to stay off the main thread: forking the IDE (its whole address space)
@@ -6056,8 +6032,6 @@ export type DockerConnection = {
id: string,
name: string,
endpoint: DockerEndpoint,
/** Whether the user explicitly disconnected this connection in Services. */
disconnected?: boolean,
};
export type DockerContainer = {
@@ -7991,8 +7965,11 @@ export type IdeEvent =
{ type: "mcpBackgroundProjectsChanged" } |
/** A window entered or left full screen, itself or as a member of a full-screen window group. */
{ type: "windowFullscreenChanged" } |
/** This remote window's connection ended or another window took over the session. */
{ type: "remoteConnectionLost"; host: string; takenOver?: boolean } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } |
/**
* This remote window's connection to its host ended on its own (network loss, the host or
* its server went away); the window's project is unreachable until it reconnects.
*/
{ type: "remoteConnectionLost"; host: string } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } |
/**
* The project's direnv environment (`.envrc`) could not be loaded, or a file it is read
* from changed and it can be reloaded.
@@ -11740,12 +11717,6 @@ export type Remote = {
resolvedUrl?: string | null,
};
/** Tools › Remote Development. This is a user setting on the remote host. */
export type RemoteDevelopmentSettings = {
/** Zero disables idle shutdown. Positive values from older configurations keep their meaning. */
idleTimeoutMinutes?: number,
};
/** Manage Remotes edits. */
export type RemoteEdit = { op: "add"; name: string; url: string } | { op: "remove"; name: string } |
/** Renames `name` to `new_name` (when different) and sets its URL. */
@@ -11765,11 +11736,6 @@ export type RemoteEntry = {
permissions: string,
};
/** Advertised only by a persistent backend with an editable idle timeout. */
export type RemoteIdlePolicy = {
overrideSeconds: number | null,
};
/** A project folder on an SSH host, in a WSL distribution or in a dev container. */
export type RemoteLaunch = {
target: RemoteTarget,
@@ -11822,7 +11788,6 @@ export type RemoteProject_Deserialize = {
host: string,
serverVersion: string,
os: string,
idlePolicy?: RemoteIdlePolicy | null,
/** Commands routed to the server (the rest run locally). */
commands: string[],
project: ProjectInfo_Deserialize,
@@ -11835,34 +11800,18 @@ export type RemoteProject_Serialize = {
host: string,
serverVersion: string,
os: string,
idlePolicy?: RemoteIdlePolicy | null,
/** Commands routed to the server (the rest run locally). */
commands: string[],
project: ProjectInfo_Serialize,
};
export type RemoteSession = RemoteSession_Serialize | RemoteSession_Deserialize;
export type RemoteSession_Deserialize = {
export type RemoteSession = {
target: RemoteTarget,
root: string,
host: string,
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
os: string,
commands: string[],
idlePolicy?: RemoteIdlePolicy | null,
takenOver?: boolean,
};
export type RemoteSession_Serialize = {
target: RemoteTarget,
root: string,
host: string,
/** `linux`, `macos` or `windows`: the OS the project's commands run on. */
os: string,
commands: string[],
idlePolicy?: RemoteIdlePolicy | null,
takenOver?: boolean,
};
export type RemoteSkillBrowseResult = {
@@ -12041,23 +11990,6 @@ export type RubySettings = {
interpreter?: string,
};
/** Snapshot and live output binding returned when reattaching to a running process. */
export type RunAttach = RunAttach_Serialize | RunAttach_Deserialize;
/** Snapshot and live output binding returned when reattaching to a running process. */
export type RunAttach_Deserialize = {
info: RunInfo,
config: RunConfig_Deserialize,
buffered: OutputChunk[],
};
/** Snapshot and live output binding returned when reattaching to a running process. */
export type RunAttach_Serialize = {
info: RunInfo,
config: RunConfig_Serialize,
buffered: OutputChunk[],
};
export type RunConfig = RunConfig_Serialize | RunConfig_Deserialize;
export type RunConfig_Deserialize = {
@@ -12567,7 +12499,7 @@ export type SettingsWindowInit = SettingsWindowInit_Serialize | SettingsWindowIn
export type SettingsWindowInit_Deserialize = {
launch: Launch_Deserialize | null,
remote: RemoteSession_Deserialize | null,
remote: RemoteSession | null,
project: ProjectInfo_Deserialize | null,
globalSettings: Settings_Deserialize,
updates: boolean,
@@ -12575,7 +12507,7 @@ export type SettingsWindowInit_Deserialize = {
export type SettingsWindowInit_Serialize = {
launch: Launch_Serialize | null,
remote: RemoteSession_Serialize | null,
remote: RemoteSession | null,
project: ProjectInfo_Serialize | null,
globalSettings: Settings_Serialize,
updates: boolean,
@@ -12636,7 +12568,6 @@ export type Settings_Deserialize = {
spelling?: SpellingSettings,
/** Tools › SSH Configurations. */
ssh?: SshSettings,
remoteDevelopment?: RemoteDevelopmentSettings,
/** Build, Execution, Deployment › Deployment. */
deployment?: DeploymentSettings,
/** Build, Execution, Deployment › Run Targets. */
@@ -12713,7 +12644,6 @@ export type Settings_Serialize = {
spelling: SpellingSettings,
/** Tools › SSH Configurations. */
ssh: SshSettings,
remoteDevelopment: RemoteDevelopmentSettings,
/** Build, Execution, Deployment › Deployment. */
deployment: DeploymentSettings,
/** Build, Execution, Deployment › Run Targets. */
@@ -13379,12 +13309,6 @@ export type TableSort = {
/** A long-running background task shown in the status bar. */
export type TaskId = number;
/** Snapshot and live binding returned when reattaching to an existing session. */
export type TerminalAttach = {
session: TerminalSessionInfo,
buffered: string,
};
/** TerminalExited data exchanged with the IDE. */
export type TerminalExited = {
id: string,
@@ -13414,16 +13338,6 @@ export type TerminalOptions = {
shellIntegration?: boolean,
};
/** Live terminal session state for reattaching across window reconnects. */
export type TerminalSessionInfo = {
id: TerminalId,
title: string,
pid: number | null,
cwd: string,
appTitle: string | null,
commandRunning: boolean,
};
/** Tools › Terminal. */
export type TerminalSettings = {
/** Empty = project root; relative paths resolve against it. */
+9 -10
Переглянути файл
@@ -55,7 +55,7 @@ import { hoverActionsAt } from "@/platform/hoverActions";
import { chooseSavePath } from "@/platform/choosePath";
import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow, projectLocation } from "@/platform/remote";
import { isRemoteWindow } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
@@ -391,7 +391,7 @@ export class EditorController implements SlotHost {
);
tabOptions.activateOnClose = editorPrefs().tabs.activateOnClose as typeof tabOptions.activateOnClose;
let prevSettings = useProject.getState().settings;
let prevScope = projectLocation(useProject.getState().project?.root);
let prevRoot = useProject.getState().project?.root ?? null;
let prevLight = useProject.getState().lightEdit;
this.disposers.push(
useProject.subscribe((s, previous) => {
@@ -401,10 +401,10 @@ export class EditorController implements SlotHost {
.activateOnClose as typeof tabOptions.activateOnClose;
this.manager.applySettings();
}
const scope = projectLocation(s.project?.root);
const root = s.project?.root ?? null;
// Entering or leaving LightEdit replaces the backend's documents too.
if (scope !== prevScope || s.lightEdit !== prevLight || (s.opening && s.project !== previous.project)) {
prevScope = scope;
if (root !== prevRoot || s.lightEdit !== prevLight || (s.opening && s.project !== previous.project)) {
prevRoot = root;
prevLight = s.lightEdit;
this.saveSession();
this.sessionRoot = null;
@@ -417,7 +417,7 @@ export class EditorController implements SlotHost {
const carriedUntitled: Tab[] = [];
let carriedActive: string | null = null;
const cs = useTabs.getState();
for (const pane of scope || s.lightEdit ? Object.values(cs.panes) : []) {
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
for (const tab of pane.tabs) {
if (isUntitledUri(tab.input.path ?? "")) {
carriedUntitled.push(tab);
@@ -462,7 +462,7 @@ export class EditorController implements SlotHost {
.catch((e) => this.documentError(e))
.then(() => {
if (generation !== this.projectGeneration) return;
if (scope) return this.restoreSession(scope);
if (root) return this.restoreSession(root);
else if (s.lightEdit) return this.restoreSession(LIGHT_EDIT_SESSION);
});
} else if (previous.opening && !s.opening && this.closeCommitted) {
@@ -478,7 +478,7 @@ export class EditorController implements SlotHost {
this.upgradeWrappedImageTabs(wrappers);
}),
);
if (prevScope) this.projectTransition = this.restoreSession(prevScope);
if (prevRoot) this.projectTransition = this.restoreSession(prevRoot);
if (this.manager.backend.onFsChanged)
this.disposers.push(this.manager.backend.onFsChanged((e) => this.onFilesRemoved(e.removed)));
if (this.manager.backend.onDiskConflict)
@@ -671,8 +671,7 @@ export class EditorController implements SlotHost {
private openSessionKey(): string | null {
const s = useProject.getState();
const scope = projectLocation(s.project?.root);
if (scope) return scope;
if (s.project?.root) return s.project.root;
if (s.lightEdit) return LIGHT_EDIT_SESSION;
return null;
}
-1
Переглянути файл
@@ -66,7 +66,6 @@ export function activate(): void | (() => void) {
cancelClose: () => ctrl.cancelClose(),
forgetSavedTabs: () => ctrl.forgetSavedTabs(),
keepSavedTabs: () => ctrl.keepSavedTabs(),
flushSession: () => ctrl.saveSession(),
documentHistory: (command) => ctrl.documentHistory(command),
chooseDeclaration: async (targets, name, anchor) =>
openPopup({
+2 -7
Переглянути файл
@@ -8,7 +8,6 @@
* TabsState with new ids.
*/
import { ipcPath } from "@/platform/paths";
import { parseRemoteLocation } from "@/platform/remote";
import type { EditorInput } from "@/workbench/contributions";
import { initialTabsState, paneIds, type LayoutNode, type Pane, type Tab, type TabsState } from "./tabs";
@@ -199,12 +198,8 @@ export function restoreTabsState(session: EditorSession, fileKey: (path: string)
export function loadSession(root: string): EditorSession | null {
try {
const legacyRemote = parseRemoteLocation(root)?.path;
// Sessions saved under the backslash spelling of a Windows root or bare remote path are picked up too.
const raw =
localStorage.getItem(STORAGE_PREFIX + root) ??
(legacyRemote ? localStorage.getItem(STORAGE_PREFIX + legacyRemote) : null) ??
legacyWindowsSession(root);
// Sessions saved under the backslash spelling of a Windows root are picked up too.
const raw = localStorage.getItem(STORAGE_PREFIX + root) ?? legacyWindowsSession(root);
return raw ? parseSession(JSON.parse(raw)) : null;
} catch {
return null;
+2 -3
Переглянути файл
@@ -44,10 +44,9 @@
line-height: 1.5;
}
/* The minimum height goes on the text itself, not the scroller: clicks below the last line
must land in the editable text, or they focus the bare scroller and no caret appears.
A host sets --composer-min-height rather than overriding the rule, so stylesheet order can't undo it. */
must land in the editable text, or they focus the bare scroller and no caret appears. */
.field :global(.cm-content) {
min-height: var(--composer-min-height, 44px);
min-height: 44px;
padding: 10px 12px 2px;
caret-color: var(--fg-strong);
white-space: pre-wrap;
+2 -2
Переглянути файл
@@ -34,8 +34,8 @@
}
/* A box to write in, not a search bar: room for a few lines before it grows. */
.composer {
--composer-min-height: calc(4.5em + 12px);
.composer :global(.cm-content) {
min-height: calc(4.5em + 12px);
}
/* Under the box: one quiet group, the project, checkout and branch side by side. */
+1 -4
Переглянути файл
@@ -5,7 +5,6 @@
*/
import type { AgentTask } from "@/bindings";
import { tx } from "@/platform/i18n";
import { parseRemoteLocation } from "@/platform/remote";
import { attentionRank } from "./model";
/** A group the user made ("Frontend", "Docs"…). */
@@ -59,9 +58,7 @@ export function parseOrganize(saved: unknown): TaskOrganize {
export function loadOrganize(root: string | null | undefined): TaskOrganize {
if (!root) return EMPTY_ORGANIZE;
try {
const legacy = parseRemoteLocation(root)?.path;
const raw =
globalThis.localStorage?.getItem(key(root)) ?? (legacy ? globalThis.localStorage?.getItem(key(legacy)) : null);
const raw = globalThis.localStorage?.getItem(key(root));
return raw == null ? EMPTY_ORGANIZE : parseOrganize(JSON.parse(raw));
} catch {
return EMPTY_ORGANIZE;
+1 -2
Переглянути файл
@@ -29,7 +29,6 @@ import { clearAgentTaskFontZoom, resetAllAgentFontZoom } from "./fontZoom";
import { clearDismissedAssets } from "./sessionAssetsModel";
import { useSkillsCatalog } from "./skillsModel";
import { basename, useProject } from "@/platform/project";
import { projectLocation } from "@/platform/remote";
import { defaultTaskProject } from "./project";
import { call, commands, isTauri, nextRequestId } from "@/platform/ipc";
import { editorService, notifications, notifyTabTitlesChanged, toolWindowService } from "@/workbench/contributions";
@@ -555,7 +554,7 @@ export async function connect(): Promise<void> {
return;
}
if (gen !== generation) return;
const organizeRoot = projectLocation(useProject.getState().project?.root);
const organizeRoot = useProject.getState().project?.root ?? null;
useAgents.setState({
loaded: true,
error: null,
-51
Переглянути файл
@@ -1,51 +0,0 @@
import { useEffect, useState } from "react";
import { useTx } from "@/platform/i18n";
import { call, commands, type RemoteSession } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { formatIdleDuration } from "@/platform/remoteIdle";
/** Read the host's current setting without blocking any of the close choices on a slow connection. */
export function RemoteCloseMessage({ session }: { session: RemoteSession }) {
const tr = useTx();
const { host, idlePolicy } = session;
const override = idlePolicy?.overrideSeconds;
const [minutes, setMinutes] = useState<number | "unavailable" | null>(null);
const canRead = session.commands.includes("remote_idle_timeout_minutes");
useEffect(() => {
if (!idlePolicy || override != null || !canRead || useRemote.getState().session !== session) return;
let active = true;
void call(commands.remoteIdleTimeoutMinutes()).then(
(n) => {
if (active) setMinutes(n);
},
() => {
if (active) setMinutes("unavailable");
},
);
return () => {
active = false;
};
}, [session, idlePolicy, override, canRead]);
const seconds = override ?? (typeof minutes === "number" ? minutes * 60 : null);
const duration = seconds != null && seconds > 0 ? formatIdleDuration(seconds) : null;
const summary =
seconds === 0
? tr`Idle shutdown is off on ${host}.`
: duration !== null
? tr`If kept running, the backend stops after ${duration} idle.`
: !canRead || minutes === "unavailable"
? tr("The host’s idle timeout is unavailable.")
: tr("Checking the host’s idle timeout…");
return (
<>
{tr`Keep the IDE backend on ${host} running so you can reconnect later, or stop it and end its terminals, runs and agent tasks.`}
{idlePolicy && (
<>
{"\n\n"}
<span role="status">{summary}</span>
</>
)}
</>
);
}
-27
Переглянути файл
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as ipc from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { disableRemote, enableRemote } from "@/platform/remote";
import * as services from "@/workbench/contributions";
import type { MessageRequest as PromptRequest } from "@/workbench/messages";
import { installCloseGuard, quitApp, type CloseDeps } from "../closeGuard";
@@ -30,7 +29,6 @@ let uninstall: (() => void) | undefined;
let deps: CloseDeps;
const forget = vi.fn();
const keep = vi.fn();
const flushSession = vi.fn();
beforeEach(() => {
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
@@ -39,11 +37,9 @@ beforeEach(() => {
vi.spyOn(ipc.commands, "windowGroupCancelClose").mockResolvedValue(undefined);
vi.spyOn(ipc.commands, "appCancelQuit").mockResolvedValue(undefined);
vi.spyOn(ipc.commands, "closeProject").mockResolvedValue(undefined);
vi.spyOn(ipc.commands, "remoteStopBackend").mockResolvedValue({ status: "ok", data: null });
vi.spyOn(services, "maybeEditorService").mockReturnValue({
forgetSavedTabs: forget,
keepSavedTabs: keep,
flushSession,
dirtyDocumentIds: () => [],
cancelClose: vi.fn(),
} as never);
@@ -61,7 +57,6 @@ afterEach(() => {
uninstall?.();
uninstall = undefined;
native.close = undefined;
disableRemote();
useProject.setState(initialProject, true);
vi.restoreAllMocks();
vi.clearAllMocks();
@@ -150,28 +145,6 @@ describe("native window close", () => {
expect(keep).toHaveBeenCalledOnce();
expect(deps.onSaveFailed).toHaveBeenCalledOnce();
});
it("flushes saved editor tabs and leaves remote processes running when closing a remote window", async () => {
enableRemote({
target: { kind: "ssh", config: "devbox" },
root: "/project",
host: "coder@devbox:22",
os: "linux",
commands: [],
});
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });
vi.mocked(deps.ask).mockResolvedValueOnce({ button: "keep", checked: false });
const terminate = vi.fn(async () => {});
deps.runningProcesses = vi.fn(async () => ["docker compose up"]);
deps.terminate = terminate;
const prevented = await close({});
expect(prevented).not.toHaveBeenCalled();
expect(deps.runningProcesses).not.toHaveBeenCalled();
expect(terminate).not.toHaveBeenCalled();
expect(ipc.commands.remoteStopBackend).not.toHaveBeenCalled();
expect(flushSession).toHaveBeenCalledOnce();
});
});
// A quit can start outside the window (Dock, logout, another window): its prompts are drawn
+38 -72
Переглянути файл
@@ -2,7 +2,7 @@
* Window close / quit flow.
*
* Closing a window (traffic light, Quit closing every window) runs
* the remote backend choice, if connected, then `decideClose`: confirm exit when this is the last window and
* `decideClose`: confirm exit when this is the last window and
* `general.confirmExit` is on, then Terminate / Cancel when Run/Debug processes
* still run and `run.confirmTerminate` is on, then Save All / Don't Save / Cancel
* when documents have unsaved changes. Quit confirms once, then the backend
@@ -12,11 +12,9 @@
* `general.closeWithoutWelcome` is on, in which case it closes. When
* `general.closeTabsWithWindow` is on, that close drops the saved editor tabs.
*/
import { createElement } from "react";
import { call, IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
import { t, tx } from "@/platform/i18n";
import { IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
import { t } from "@/platform/i18n";
import { closeProject, provideLeaveProjectGuard, useProject } from "@/platform/project";
import { isRemoteWindow, shutdownRemoteBackend, useRemote } from "@/platform/remote";
import { workflowSettings } from "@/platform/workflowSettings";
import {
maybeEditorService,
@@ -26,17 +24,14 @@ import {
type EditorCloseSession,
} from "@/workbench/contributions";
import { beginTermination, endTermination } from "./termination";
import { RemoteCloseMessage } from "./RemoteCloseMessage";
import { ask, type Ask } from "@/workbench/messages";
import { AUX_CLOSED, auxiliaryWindow, closeDocumentWindows, type AuxCloseResult } from "@/platform/auxWindow";
/** Document ids the backend reports dirty in this window. */
const dirtyDocs = new Set<number>();
const dirtyDocumentIds = () => new Set([...dirtyDocs, ...(maybeEditorService()?.dirtyDocumentIds?.() ?? [])]);
export function dirtyCount(): number {
return dirtyDocumentIds().size;
return new Set([...dirtyDocs, ...(maybeEditorService()?.dirtyDocumentIds?.() ?? [])]).size;
}
export function confirmExitEnabled(settings: Settings | null | undefined): boolean {
@@ -88,8 +83,6 @@ export interface CloseDeps {
onSaveFailed: (e: unknown) => void;
/** Stops custom document edits/execution before reading their final dirty state. */
prepareClose?: () => Promise<EditorCloseSession | undefined>;
/** Applies a Don't Save decision when the document host outlives the window. */
discardChanges?: () => Promise<void>;
}
/** Asks whatever must be asked; resolves true when the window may close. */
@@ -141,10 +134,8 @@ export async function decideClose(input: CloseInput, deps: CloseDeps): Promise<b
icon: "warning",
});
if (r.button === "save") await deps.saveAll();
else if (r.button === "discard") {
await session?.discard();
await deps.discardChanges?.();
} else return false;
else if (r.button === "discard") await session?.discard();
else return false;
}
// IDEA asks, then shows "Terminating 'X'" while the graceful shutdown runs; a Kill button
// there kills the processes and the close finishes once none is left.
@@ -247,11 +238,6 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
if (closing) return false;
closing = true;
let forgot = false;
let quitting = false;
const cancel = async () => {
await (quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
return false;
};
const undoForget = () => {
if (!forgot) return;
forgot = false;
@@ -259,68 +245,53 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
};
try {
const ctx = await commands.windowCloseContext();
quitting = ctx.quitting;
// Each window of a quit asks about its own processes and unsaved changes, if it has any.
if (quitting) deps = raisingBeforeAsk(deps);
if (!(await closeDocumentWindows())) return await cancel();
const s = useProject.getState();
const welcome = returnsToWelcome(quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings);
const remote = useRemote.getState();
let stop = false;
if (remote.session && !remote.lost) {
const r = await deps.ask({
title: tx("Close Remote Development Window"),
body: createElement(RemoteCloseMessage, { session: remote.session }),
buttons: [
{ id: "stop", label: tx("Stop Backend") },
{ id: "keep", label: tx("Keep Backend Running"), primary: true },
],
});
if (r.button !== "keep" && r.button !== "stop") return await cancel();
stop = r.button === "stop";
if (ctx.quitting) deps = raisingBeforeAsk(deps);
if (!(await closeDocumentWindows())) {
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
return false;
}
const confirmTerminate = !remote.session && workflowSettings().run.confirmTerminate;
const s = useProject.getState();
// The last project or LightEdit window can return to Welcome. Otherwise it closes.
if (returnsToWelcome(ctx.quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings)) {
if (await confirmLeave(deps, undefined, false)) {
forgot = forgetTabs();
try {
await closeProject();
// Welcome is showing; keep the tabs dropped.
forgot = false;
} catch (e) {
undoForget();
throw e;
}
}
await commands.windowGroupCancelClose();
return false;
}
const confirmTerminate = workflowSettings().run.confirmTerminate;
const ok = await decideClose(
{
quitting,
quitting: ctx.quitting,
windows: ctx.windows,
confirmExit: !welcome && confirmExitEnabled(s.settings),
confirmExit: confirmExitEnabled(s.settings),
confirmTerminate,
processes: confirmTerminate ? await processNames(deps) : [],
dirty: dirtyCount(),
project: s.project?.displayName || s.project?.name || null,
},
savingUntitled({
...deps,
discardChanges: remote.session && !remote.lost && !stop ? discardRemoteChanges : undefined,
}),
savingUntitled(deps),
);
if (!ok) return await cancel();
if (stop) {
try {
await shutdownRemoteBackend();
} catch (e) {
maybeEditorService()?.cancelClose?.();
notifications().notify({
level: "error",
title: tx("Could not stop the remote backend"),
body: e instanceof Error ? e.message : String(e),
});
return await cancel();
}
}
forgot = forgetTabs();
if (!forgot && (!welcome || remote.session)) maybeEditorService()?.flushSession?.();
if (welcome) {
await closeProject();
forgot = false;
return await cancel();
if (!ok) {
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
return false;
}
// The window is closing. Drop the tabs now so pagehide cannot write them back.
forgetTabs();
return true;
} catch (e) {
undoForget();
maybeEditorService()?.cancelClose?.();
void cancel().catch(() => {});
void commands.windowGroupCancelClose().catch(() => {});
deps.onSaveFailed(e);
return false;
} finally {
@@ -328,11 +299,6 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
}
}
async function discardRemoteChanges() {
// Unlike an unexpected transport loss, Don't Save must not keep these buffers for reattachment.
await Promise.all([...dirtyDocumentIds()].map((doc) => call(commands.docClose(doc))));
}
/** Save asks for each untitled buffer's path; one left unsaved (Save As cancelled) keeps the window open. */
function savingUntitled(deps: CloseDeps): CloseDeps {
return {
@@ -355,7 +321,7 @@ export async function confirmLeave(
keepUntitled = true,
): Promise<boolean> {
if (!(await closeDocumentWindows())) return false;
const confirmTerminate = !isRemoteWindow() && workflowSettings().run.confirmTerminate;
const confirmTerminate = workflowSettings().run.confirmTerminate;
// Untitled buffers follow the window into another project: they are neither counted nor
// saved then (the window keeps them open). Closing to Welcome drops them, so they count.
const untitled = new Set(keepUntitled ? (maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []) : []);
+11 -48
Переглянути файл
@@ -7,7 +7,7 @@
import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { onIdeEvent } from "@/platform/ipc";
import { registerActions, type ActionContext } from "@/platform/actions";
import { activeCellGrid } from "./cellActions";
import {
@@ -81,58 +81,21 @@ function tableTarget(arg: unknown): TableCommandTarget {
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
}
/** The Database window, on the stripe by default only while the project has data sources. */
function registerDatabaseWindow(): () => void {
let withSources: boolean | null = null;
let dispose = () => {};
const sync = (next: boolean) => {
if (next === withSources) return;
withSources = next;
// Registering the same id again replaces the contribution in place.
dispose = registerToolWindow({
id: DB_TOOL_WINDOW,
title: "Database",
icon: "toolwindow-database",
anchor: "right",
order: 20,
...(next ? {} : { stripe: "onUse" as const }),
component: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseView)),
headerMenu: useDatabaseHeaderMenu,
headerActions: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseHeaderActions)),
});
};
// Until the window loads the sources, a quiet probe decides; a failed one leaves it under "…".
let probe = 0;
const check = () => {
const seq = ++probe;
sync(false);
if (!useProject.getState().project) return;
call(commands.dbSources()).then(
(sources) => seq === probe && !useDatabase.getState().loaded && sync(sources.length > 0),
() => {},
);
};
check();
const offSources = useDatabase.subscribe((s) => {
if (s.loaded) sync(s.sources.length > 0);
});
const offProject = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) check();
});
return () => {
probe++;
offSources();
offProject();
dispose();
};
}
export function activate(): () => void {
const disposers = [
onIdeEvent("dbSourcesChanged", () => {
void loadSources();
}),
registerDatabaseWindow(),
registerToolWindow({
id: DB_TOOL_WINDOW,
title: "Database",
icon: "toolwindow-database",
anchor: "right",
order: 20,
component: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseView)),
headerMenu: useDatabaseHeaderMenu,
headerActions: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseHeaderActions)),
}),
registerServiceView({
id: RESULTS_VIEW,
title: "Database",
-56
Переглянути файл
@@ -1,56 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { waitFor } from "@testing-library/react";
import { useContributions } from "@/workbench/contributions";
import { useProject } from "@/platform/project";
import type { DataSource } from "@/platform/ipc";
const mocks = vi.hoisted(() => ({ sources: vi.fn(async (): Promise<unknown> => []) }));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
commands: { ...actual.commands, dbSources: () => "dbSources" },
call: (request: unknown) => (request === "dbSources" ? mocks.sources() : Promise.reject(new Error("unmocked"))),
};
});
import { activate } from "./index";
import { DB_TOOL_WINDOW, useDatabase } from "./store";
const stripe = () => useContributions.getState().toolWindows.get(DB_TOOL_WINDOW)?.stripe;
describe("Database tool window", () => {
let dispose = () => {};
afterEach(() => {
dispose();
dispose = () => {};
useProject.setState({ project: null });
useDatabase.setState({ sources: [], loaded: false });
});
it("is on the stripe by default only while there are data sources", () => {
dispose = activate();
expect(stripe()).toBe("onUse");
useDatabase.setState({ sources: [{ id: "pg" } as DataSource], loaded: true });
expect(stripe()).toBeUndefined();
useDatabase.setState({ sources: [] });
expect(stripe()).toBe("onUse");
dispose();
dispose = () => {};
expect(useContributions.getState().toolWindows.has(DB_TOOL_WINDOW)).toBe(false);
});
it("asks for the sources quietly when a project opens, before the window loads them", async () => {
dispose = activate();
mocks.sources.mockResolvedValueOnce([{ id: "pg" }]);
useProject.setState({ project: { root: "/app" } as never });
await waitFor(() => expect(stripe()).toBeUndefined());
mocks.sources.mockRejectedValueOnce(new Error("no backend"));
useProject.setState({ project: { root: "/other" } as never });
await waitFor(() => expect(mocks.sources).toHaveBeenCalledTimes(2));
expect(stripe()).toBe("onUse");
expect(useDatabase.getState().loaded).toBe(false);
});
});
-10
Переглянути файл
@@ -76,16 +76,6 @@ describe("Flutter DevTools windows", () => {
const dispose = registerDevToolsWindows();
await waitFor(() => expect(ids()).toEqual(expect.arrayContaining(DEVTOOLS_WINDOWS.map((w) => w.id))));
expect(getContext().flutterDevTools).toBe(true);
// One stripe button: the others wait under "…" until first opened.
const stripes = Object.fromEntries(
DEVTOOLS_WINDOWS.map((w) => [w.id, useContributions.getState().toolWindows.get(w.id)?.stripe]),
);
expect(stripes).toEqual({
"flutter-deep-links": "onUse",
"flutter-devtools": "onUse",
"flutter-devtools-extensions": "onUse",
"flutter-inspector": undefined,
});
useProject.setState({ project: { root: "/tool" } as never });
await waitFor(() => expect(ids()).not.toContain("flutter-inspector"));
-2
Переглянути файл
@@ -114,8 +114,6 @@ export function registerDevToolsWindows(): () => void {
icon: w.icon,
anchor: "right",
order: 40 + i,
// Only the Inspector is on the stripe until the others are first opened.
...(w.id === "flutter-inspector" ? {} : { stripe: "onUse" as const }),
component: view("FlutterDevToolsView"),
headerActions: view("FlutterDevToolsRefresh"),
...(w.app === "each" ? { headerContent: view("FlutterDevToolsTabs") } : {}),
-21
Переглянути файл
@@ -30,7 +30,6 @@ function add(pluginId: string, decl: Partial<WindowView> & Pick<WindowView, "id"
}
beforeEach(() => {
localStorage.clear();
useContextKeys.setState({}, true);
show.mockClear();
provideToolWindowService({ show } as never);
@@ -119,26 +118,6 @@ it("reveals the requested grouped tab and never reveals hidden or removed views"
revealWindowView("spring", "beans");
expect(show).not.toHaveBeenCalled();
expect(screen.getByText("routes body")).toBeInTheDocument();
});
it("remembers the selected tab of a grouped plugin tool window across close and reopen", async () => {
const first = add("spring", { id: "routes", title: "Routes", group: "framework" });
const second = add("spring", { id: "beans", title: "Beans", group: "framework" });
const window1 = useContributions.getState().toolWindows.get(id)!;
const { unmount } = render(<window1.component id={id} />);
await userEvent.click(screen.getByRole("tab", { name: "Beans" }));
expect(screen.getByRole("tab", { name: "Beans" })).toHaveAttribute("aria-selected", "true");
unmount();
first.dispose();
second.dispose();
// Re-registering the plugin views in a reopened window restores the "Beans" selection.
add("spring", { id: "routes", title: "Routes", group: "framework" });
add("spring", { id: "beans", title: "Beans", group: "framework" });
const window2 = useContributions.getState().toolWindows.get(id)!;
render(<window2.component id={id} />);
expect(screen.getByRole("tab", { name: "Beans" })).toHaveAttribute("aria-selected", "true");
expect(screen.getByText("beans body")).toBeVisible();
// Avoid disposing the same declaration twice.
disposers.pop();
});
-1
Переглянути файл
@@ -587,7 +587,6 @@ export function startViewUi(openInput: (input: ReturnType<typeof customEditorInp
kind: PLUGIN_CONTENT_EDITOR_KIND,
component: PluginContentEditor,
keepAlive: true,
restorable: true,
title: pluginContentEditorTitle,
icon: pluginContentEditorIcon,
document: pluginContentEditorDocument,
+5 -35
Переглянути файл
@@ -10,7 +10,7 @@ import {
useToolWindowShown,
type ToolWindowAnchor,
} from "@/workbench/contributions";
import { currentViewLocation, pluginToolWindowId, useViewLocation, viewKey } from "./viewStore";
import { pluginToolWindowId, viewKey } from "./viewStore";
import styles from "./PluginView.module.css";
export interface WindowView {
@@ -47,47 +47,21 @@ interface WindowGroup {
const groups = new Map<string, WindowGroup>();
const windowsByView = new Map<string, { window: string; group: WindowGroup }>();
const GROUP_TAB_PREFIX = "openidea.plugins.groupTab.v1:";
function readSelectedView(groupId: string, location: string | null = currentViewLocation()): string | null {
try {
return localStorage.getItem(`${GROUP_TAB_PREFIX}${location ?? ""}:${groupId}`);
} catch {
return null;
}
}
function writeSelectedView(groupId: string, viewId: string, location: string | null = currentViewLocation()) {
try {
localStorage.setItem(`${GROUP_TAB_PREFIX}${location ?? ""}:${groupId}`, viewId);
} catch {
/* storage unavailable */
}
}
function GroupView({ group, id }: { group: WindowGroup; id: string }) {
const { members, selected } = group.state();
const location = useViewLocation();
const saved = readSelectedView(id, location);
const [fallback, setFallback] = useState<{ location: string | null; id: string | undefined }>();
const member = (id: string | null | undefined) => members.find((m) => m.decl.id === id);
const active =
member(selected) ?? member(saved) ?? member(fallback?.location === location ? fallback.id : null) ?? members[0];
const active = members.find((m) => m.decl.id === selected) ?? members[0];
const activeId = active?.decl.id;
const shown = useToolWindowShown();
// Like separate tool windows, opened tabs retain their local state until withdrawn.
const [visited, setVisited] = useState<ReadonlySet<string>>(() => new Set());
useEffect(() => {
setFallback((previous) =>
previous?.location === location && previous.id === activeId ? previous : { location, id: activeId },
);
setVisited((previous) => {
const next = new Set(
members.filter((m) => previous.has(m.decl.id) || m.decl.id === activeId).map((m) => m.decl.id),
);
return next.size === previous.size && [...next].every((id) => previous.has(id)) ? previous : next;
});
}, [members, activeId, location]);
}, [members, activeId]);
if (!active) return null;
return (
<VerbatimTextContext.Provider value={true}>
@@ -97,10 +71,7 @@ function GroupView({ group, id }: { group: WindowGroup; id: string }) {
panelIdPrefix={id}
items={members.map(({ decl }) => ({ id: decl.id, label: decl.title }))}
activeId={active.decl.id}
onSelect={(viewId) => {
writeSelectedView(id, viewId, location);
group.state.setState({ selected: viewId });
}}
onSelect={(id) => group.state.setState({ selected: id })}
/>
{members
.filter((m) => visited.has(m.decl.id) || m.decl.id === activeId)
@@ -134,7 +105,7 @@ function refresh(id: string, group: WindowGroup) {
const selected = group.state.getState().selected;
group.state.setState({
members,
selected: selected && members.some((m) => m.decl.id === selected) ? selected : null,
selected: selected ?? members[0]?.decl.id ?? null,
});
const secondary = first?.decl.secondary === true;
const signature =
@@ -208,7 +179,6 @@ export function registerWindowView(
export function revealWindowView(pluginId: string, view: string) {
const entry = windowsByView.get(viewKey(pluginId, view));
if (!entry?.group.state.getState().members.some((m) => m.decl.id === view)) return;
writeSelectedView(entry.window, view);
entry.group.state.setState({ selected: view });
toolWindowService().show(entry.window, true);
}
+2 -7
Переглянути файл
@@ -16,7 +16,6 @@ import { notifications } from "@/workbench/contributions";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { ipcPath } from "@/platform/paths";
import { projectLocation } from "@/platform/remote";
import {
DEFAULT_TREE_OPTIONS,
GROUP_PREFIX,
@@ -394,11 +393,7 @@ function initialExpanded(root: string | null, mode: ViewMode, members = get().me
// The tree as the user left it, like IDEA: a collapsed project root stays collapsed, and
// nodes outside it (content roots, contributed roots) stay open.
// Keys of nodes that no longer exist are inert. Only a first open expands the roots.
const scope = projectLocation(root) ?? root;
const persisted =
mode === "project" || mode === "unity"
? (readJson<string[]>(expandedKey(scope)) ?? (scope !== root ? readJson<string[]>(expandedKey(root)) : null))
: null;
const persisted = mode === "project" || mode === "unity" ? readJson<string[]>(expandedKey(root)) : null;
if (persisted) return new Set(persisted);
return new Set(members ?? [root]);
}
@@ -409,7 +404,7 @@ function persistExpanded() {
persistTimer = setTimeout(() => {
const { root, expanded, mode } = get();
if (root && (mode === "project" || mode === "unity"))
writeJson(expandedKey(projectLocation(root) ?? root), [...expanded].slice(0, MAX_PERSISTED));
writeJson(expandedKey(root), [...expanded].slice(0, MAX_PERSISTED));
}, 300);
}
+2 -15
Переглянути файл
@@ -2,7 +2,7 @@ import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { RemoteSession } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { BarButton, Icon, showContextMenu, Spinner } from "@/ui";
import { BarButton, Icon, Spinner } from "@/ui";
import styles from "./RemoteDev.module.css";
const BADGE: Record<RemoteSession["target"]["kind"], string> = {
@@ -19,7 +19,6 @@ export function remoteBadge(session: Pick<RemoteSession, "target" | "host">): st
export function RemoteStatus() {
const session = useRemote((s) => s.session);
const lost = useRemote((s) => s.lost !== null);
const takenOver = useRemote((s) => s.takenOver);
const reconnecting = useRemote((s) => s.reconnecting);
if (!session) return null;
const label = remoteBadge(session);
@@ -29,9 +28,7 @@ export function RemoteStatus() {
tooltip={
reconnecting
? tx`Reconnecting to ${session.host}…`
: takenOver
? tx("Another window took over this remote session")
: tx`Lost the connection to ${session.host}. Click to reconnect.`
: tx`Lost the connection to ${session.host}. Click to reconnect.`
}
aria-label={tx`${label} (disconnected)`}
disabled={reconnecting}
@@ -48,16 +45,6 @@ export function RemoteStatus() {
tooltip={tx`Project runs on ${label}`}
aria-label={label}
onClick={() => void executeAction("remote.connect")}
onContextMenu={(e) => {
e.preventDefault();
showContextMenu(e, [
{ kind: "action", action: "remote.connect" },
{ kind: "action", action: "remote.reloadEnvironment" },
{ kind: "separator" },
{ kind: "action", action: "remote.disconnect" },
{ kind: "action", action: "remote.stopBackend" },
]);
}}
>
{label}
</BarButton>
+1 -32
Переглянути файл
@@ -4,11 +4,9 @@
* to it (platform/remote.ts).
*/
import { registerActions } from "@/platform/actions";
import { disconnectRemote, stopRemoteBackend, useRemote } from "@/platform/remote";
import { disconnectRemote, useRemote } from "@/platform/remote";
import { lazyComponent } from "@/ui";
import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { tx } from "@/platform/i18n";
import { confirmLeaveProject } from "@/platform/project";
import { ConnectHost } from "./ConnectDialog";
import { reopenInContainer } from "./container";
@@ -103,35 +101,6 @@ export function activate(): () => void {
}
},
},
{
id: "remote.stopBackend",
title: "Stop Remote Backend",
description:
"Stops the remote IDE backend and its terminals, runs and agent sessions, then closes the project.",
category: "File",
keywords: ["ssh", "remote", "stop", "shutdown", "backend", "server"],
when: "projectRemote && !remoteConnectionLost",
run: async () => {
const host = useRemote.getState().session?.host;
if (!host) return;
if (
!(await confirm({
title: tx("Stop Remote Backend"),
message: tx`Stop the IDE backend on ${host} and terminate its running terminals, runs and agent sessions?`,
ok: tx("Stop Backend"),
icon: "warning",
}))
)
return;
if (!(await confirmLeaveProject(false))) return;
try {
await stopRemoteBackend();
} catch (e) {
maybeEditorService()?.cancelClose?.();
throw e;
}
},
},
{
id: "remote.reopenInContainer",
title: "Reopen in Container",
+5 -38
Переглянути файл
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { RemoteSession } from "@/platform/ipc";
const listeners = vi.hoisted(() => new Map<string, (event: { host: string; takenOver: boolean }) => void>());
const listeners = vi.hoisted(() => new Map<string, (event: { host: string }) => void>());
const reconnectRemote = vi.hoisted(() => vi.fn<() => Promise<void>>());
const notify = vi.hoisted(() => vi.fn());
const dirty = vi.hoisted(() => ({ ids: [] as number[] }));
@@ -9,7 +9,7 @@ const confirm = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
onIdeEvent: (type: string, handler: (event: { host: string; takenOver: boolean }) => void) => {
onIdeEvent: (type: string, handler: (event: { host: string }) => void) => {
listeners.set(type, handler);
return () => listeners.delete(type);
},
@@ -26,7 +26,7 @@ vi.mock("@/workbench/contributions", async (orig) => ({
vi.mock("@/workbench/messages", () => ({ confirm }));
import { getContext } from "@/platform/context";
import { enableRemote, useRemote } from "@/platform/remote";
import { useRemote } from "@/platform/remote";
import { installReconnect, reconnectNow, RETRY_DELAYS_MS } from "./reconnect";
const session: RemoteSession = {
@@ -43,7 +43,7 @@ let uninstall: () => void;
beforeEach(() => {
waits = [];
dirty.ids = [];
useRemote.setState({ session, lost: null, takenOver: false, reconnecting: false });
useRemote.setState({ session, lost: null, reconnecting: false });
uninstall = installReconnect(async (ms) => {
waits.push(ms);
});
@@ -54,7 +54,7 @@ afterEach(() => {
vi.clearAllMocks();
});
const lose = (takenOver = false) => listeners.get("remoteConnectionLost")!({ host: "box", takenOver });
const lose = () => listeners.get("remoteConnectionLost")!({ host: "box" });
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
it("marks the window lost and reconnects in the background", async () => {
@@ -68,39 +68,6 @@ it("marks the window lost and reconnects in the background", async () => {
expect(notify).not.toHaveBeenCalled();
});
it("reports a takeover without automatically disconnecting the other window in return", async () => {
lose(true);
lose(); // A subsequent transport-loss event must not turn a takeover into a retry.
await settle();
expect(waits).toEqual([]);
expect(reconnectRemote).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "warning",
title: "Another window took over this remote session",
body: "Your project is still running on box. This window will not reconnect automatically.",
}),
);
confirm.mockResolvedValueOnce(false);
await reconnectNow();
expect(confirm).toHaveBeenCalledOnce();
expect(reconnectRemote).not.toHaveBeenCalled();
});
it("keeps a restored, displaced window disconnected until an explicit, confirmed reconnect", async () => {
enableRemote({ ...session, takenOver: true });
expect(getContext().remoteConnectionLost).toBe(true);
expect(notify).toHaveBeenCalledOnce();
lose();
await settle();
expect(waits).toEqual([]);
expect(reconnectRemote).not.toHaveBeenCalled();
reconnectRemote.mockResolvedValueOnce();
await reconnectNow();
expect(confirm).toHaveBeenCalledOnce();
expect(reconnectRemote).toHaveBeenCalledOnce();
});
it("offers Reconnect once every attempt failed", async () => {
reconnectRemote.mockRejectedValue(new Error("Connection refused"));
lose();
+14 -29
Переглянути файл
@@ -18,36 +18,27 @@ let generation = 0;
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
const unsaved = () => maybeEditorService()?.dirtyDocumentIds?.().length ?? 0;
function notifyLost(host: string, error?: unknown, takenOver = false) {
function notifyLost(host: string, error?: unknown) {
notifications().notify({
key: KEY,
group: "remote",
level: takenOver ? "warning" : "error",
title: takenOver ? tx("Another window took over this remote session") : tx`Lost the connection to ${host}`,
body:
error !== undefined
? errorText(error)
: takenOver
? tx`Your project is still running on ${host}. This window will not reconnect automatically.`
: undefined,
level: "error",
title: tx`Lost the connection to ${host}`,
body: error === undefined ? undefined : errorText(error),
actions: [{ label: tx("Reconnect"), run: () => void reconnectNow() }],
});
}
/** Reconnect to Remote Host: asks first when reopening the project would drop unsaved edits. */
export async function reconnectNow(): Promise<void> {
const { lost, reconnecting, takenOver } = useRemote.getState();
const { lost, reconnecting } = useRemote.getState();
if (!lost || reconnecting) return;
const count = unsaved();
if (
(takenOver || count > 0) &&
count > 0 &&
!(await confirm({
title: tx("Reconnect to Remote Host"),
message: takenOver
? count > 0
? tx`Reconnecting disconnects the other window. Unsaved edits in ${count} files in this window may be lost.`
: tx("Reconnecting takes over the remote session and disconnects the other window.")
: tx`Reconnecting opens the project again. Unsaved changes in ${count} files can't be saved to ${lost} and will be lost.`,
message: tx`Reconnecting opens the project again. Unsaved changes in ${count} files can't be saved to ${lost} and will be lost.`,
ok: tx("Reconnect"),
icon: "warning",
}))
@@ -58,7 +49,7 @@ export async function reconnectNow(): Promise<void> {
try {
await reconnectRemote();
} catch (e) {
notifyLost(lost, e, takenOver);
notifyLost(lost, e);
}
}
@@ -85,19 +76,13 @@ export function installReconnect(
wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
): () => void {
const offEvent = onIdeEvent("remoteConnectionLost", (e) => {
const state = useRemote.getState();
if (state.session?.host !== e.host || state.takenOver) return;
const takenOver = e.takenOver === true;
++generation;
useRemote.setState({ lost: e.host, takenOver });
if (!takenOver) void retry(e.host, generation, wait);
if (!useRemote.getState().session) return;
useRemote.setState({ lost: e.host });
void retry(e.host, ++generation, wait);
});
const offState = useRemote.subscribe((s, prev) => {
if (s.lost !== prev.lost) setContext("remoteConnectionLost", s.lost !== null);
});
const sync = (s: ReturnType<typeof useRemote.getState>, prev?: ReturnType<typeof useRemote.getState>) => {
if (s.lost !== prev?.lost) setContext("remoteConnectionLost", s.lost !== null);
if (s.lost && s.takenOver && (!prev?.takenOver || s.lost !== prev.lost)) notifyLost(s.lost, undefined, true);
};
sync(useRemote.getState());
const offState = useRemote.subscribe(sync);
return () => {
generation++;
offEvent();
+77
Переглянути файл
@@ -0,0 +1,77 @@
/** The npm tool window: the project's packages and their scripts; activating a script runs it. */
import { useMemo, useState, type ReactNode } from "react";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { Icon, Tree, showContextMenu, type MenuItem, type TreeRowState } from "@/ui";
import { runScriptNode, useNpmScripts, type NpmNode } from "./npmScripts";
import { scriptMenuItems } from "./npmGutter";
import { call, commands } from "@/platform/ipc";
import styles from "./Run.module.css";
function scriptMenuItemsFor(node: NpmNode): Promise<MenuItem[]> {
if (node.kind !== "script") return Promise.resolve([]);
return call(commands.fsReadText(node.path))
.catch(() => "")
.then((content) => scriptMenuItems({ name: node.name, line: 0 }, node.path, content ?? ""));
}
export function NpmScriptsView() {
const packages = useNpmScripts((s) => s.packages);
const loaded = useNpmScripts((s) => s.loaded);
const hasProject = useProject((s) => !!s.project);
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
const roots = useMemo(() => packages, [packages]);
const expanded = useMemo(
() => new Set(roots.filter((n) => n.kind === "package" && !collapsed.has(n.key)).map((n) => n.key)),
[roots, collapsed],
);
if (!loaded || !hasProject || roots.length === 0) return null;
const renderNode = (n: NpmNode, state: TreeRowState): ReactNode => {
if (n.kind === "package") {
return (
<span className={styles.scriptsRow} title={n.label}>
<Icon name="file-npm" size={16} />
<span className={state.selected ? styles.scriptsStrong : undefined}>{n.label}</span>
<span className={styles.scriptsMeta}>{n.scripts.length}</span>
</span>
);
}
return (
<span className={styles.scriptsRow} title={n.name}>
<Icon name="runnable-mark" size={14} />
<span>{n.name}</span>
</span>
);
};
return (
<Tree<NpmNode>
aria-label={tx`npm scripts`}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "package" ? n.label : n.name)}
getChildren={(n) => (n.kind === "package" ? n.scripts : undefined)}
isExpandable={(n) => n.kind === "package"}
expanded={expanded}
onExpandedChange={(_next, node, isOpen) =>
setCollapsed((prev) => {
const s = new Set(prev);
if (isOpen) s.delete(node.key);
else s.add(node.key);
return s;
})
}
onActivate={(n) => {
if (n.kind === "script") void runScriptNode(n, false);
}}
onContextMenu={(n, _sel, e) => {
if (n?.kind !== "script") return;
void scriptMenuItemsFor(n).then((items) => showContextMenu({ clientX: e.clientX, clientY: e.clientY }, items));
}}
renderNode={renderNode}
/>
);
}
+17
Переглянути файл
@@ -6,6 +6,23 @@
min-width: 0;
}
.scriptsRow {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.scriptsStrong {
font-weight: 500;
}
.scriptsMeta {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.tabs {
min-width: 0;
border: 0;
+8 -13
Переглянути файл
@@ -7,7 +7,6 @@ import { executeAction, executeActionOrThrow, getAction, registerActions } from
import { getContext, setContext, useContextKeys } from "@/platform/context";
import { call, commands, onIdeEvent, type RunConfig } from "@/platform/ipc";
import { projectFolder, useProject } from "@/platform/project";
import { parseRemoteLocation, projectLocation } from "@/platform/remote";
import { isSameOrInside } from "@/platform/paths";
import { agentRunSettings, onWorkflowSettingsChange } from "@/platform/workflowSettings";
import { showContextMenu, lazyComponent, lazyWhen, type MenuItem } from "@/ui";
@@ -73,6 +72,7 @@ import { junitType } from "./junitType";
import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate";
import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { npmGutter } from "./npmGutter";
import { startNpmScriptsWatch } from "./npmScripts";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
import { markdownCommandGutter } from "./markdownCommands";
@@ -438,6 +438,7 @@ export function activate(): () => void {
headerContent: lazyComponent(() => import("./RunView").then((m) => m.RunTabs)),
useBadge: useRunningCount,
}),
startNpmScriptsWatch(),
registerTitleItem({ id: "run.widget", title: "Run Widget", align: "right", priority: 0, component: RunWidget }),
registerRunAnythingProvider(runConfigsRunAnything),
registerBuiltinTypes(),
@@ -913,18 +914,12 @@ export function activate(): () => void {
if (s.sessions !== prev.sessions) trimAgentArchive();
}),
onWorkflowSettingsChange(() => agentRunSettings(), trimAgentArchive),
(() => {
let prevLocation = projectLocation(useProject.getState().project?.root);
return useProject.subscribe((s, prev) => {
const nextLocation = projectLocation(s.project?.root);
if (nextLocation === prevLocation && s.project?.trusted === prev.project?.trusted) return;
const wasRemote = !!prevLocation && parseRemoteLocation(prevLocation) !== null;
prevLocation = nextLocation;
resetRuns(!wasRemote);
useStackTraces.setState({ tabs: [], dialog: null });
if (s.project) void loadConfigs();
});
})(),
useProject.subscribe((s, prev) => {
if (s.project?.root === prev.project?.root && s.project?.trusted === prev.project?.trusted) return;
resetRuns();
useStackTraces.setState({ tabs: [], dialog: null });
if (s.project) void loadConfigs();
}),
];
setBeforeLaunchRunner(runBeforeLaunch);
+186
Переглянути файл
@@ -0,0 +1,186 @@
/**
* The npm tool window's data: the project's `package.json` files (root, workspace members and
* detected module roots) read from disk, independent of run configuration detection. Running a
* script goes through `scriptMenuItems`, which reuses a matching configuration or makes a temporary one.
*/
import { create } from "zustand";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectRoots } from "@/platform/projectRoots";
import { lazyComponent } from "@/ui";
import { registerToolWindow } from "@/workbench/contributions";
import { objectEntries, scriptMenuItems, type ScriptEntry } from "./npmGutter";
/** A package (the directory of a `package.json`) or one of its scripts. */
export type NpmNode = { kind: "package"; key: string; label: string; scripts: NpmScript[] } | NpmScript;
export interface NpmScript {
kind: "script";
key: string;
/** Directory relative to the project root ("" for the root package). */
dir: string;
/** Absolute path of the `package.json`. */
path: string;
name: string;
}
interface NpmScriptsState {
loaded: boolean;
packages: NpmNode[];
}
export const useNpmScripts = create<NpmScriptsState>(() => ({ loaded: false, packages: [] }));
const safeJson = (text: string): Record<string, unknown> | null => {
try {
return JSON.parse(text) as Record<string, unknown>;
} catch {
return null;
}
};
/** Member directories (relative to the root) of the root package's `workspaces`: plain paths and one `*` level. */
async function workspaceDirs(pkg: Record<string, unknown>, root: string): Promise<string[]> {
const ws = pkg.workspaces;
const list = Array.isArray(ws)
? (ws as unknown[])
: Array.isArray((ws as { packages?: unknown[] })?.packages)
? (ws as { packages: unknown[] }).packages
: [];
const out: string[] = [];
for (const pattern of list) {
if (typeof pattern !== "string" || !pattern || pattern.includes("..")) continue;
const star = pattern.indexOf("*");
if (star < 0) {
out.push(pattern.replace(/\/+$/, ""));
continue;
}
const parent = pattern.slice(0, star).replace(/\/+$/, "");
const suffix = pattern.slice(star + 1);
const entries = await call(commands.fsReadDir(parent ? `${root}/${parent}` : root)).catch(() => []);
for (const e of entries) {
const isDir = e.kind === "dir" || e.targetKind === "dir";
if (!isDir || e.ignored || e.excluded || e.name === "node_modules") continue;
if (suffix && !e.name.endsWith(suffix)) continue;
out.push(parent ? `${parent}/${e.name}` : e.name);
}
}
return out;
}
let loadGen = 0;
/** Rescans the packages and their scripts. */
export async function loadNpmScripts(): Promise<void> {
const root = useProject.getState().project?.root ?? null;
const gen = ++loadGen;
if (!root || !isTauri()) {
useNpmScripts.setState({ loaded: true, packages: [] });
return;
}
const rootName = useProject.getState().project?.name ?? root;
const dirs = new Set([""]);
const rootText = await call(commands.fsReadText(`${root}/package.json`)).catch(() => null);
const rootPkg = rootText !== null ? safeJson(rootText) : null;
if (rootPkg) for (const dir of await workspaceDirs(rootPkg, root)) dirs.add(dir);
// Detected roots cover a front end in a subdirectory. A node module's own directory only shows
// up in `detectedFrom` ("<dir>/package.json"). Roots outside the project (absolute) are skipped.
for (const r of useProjectRoots.getState().detected) {
const abs = r.path.startsWith(`${root}/`) ? r.path.slice(root.length + 1) : r.path;
const rel = /^[A-Za-z]:[\\/]|^\//.test(abs) ? null : abs;
if (rel === null) continue;
if (r.kind !== "excluded" && rel) dirs.add(rel);
if (r.detectedFrom) {
const moduleDir = r.detectedFrom.replace(/\/[^/]+$/, "");
if (moduleDir && !/^[A-Za-z]:[\\/]|^\//.test(moduleDir)) dirs.add(moduleDir);
}
}
// Any other package.json the index knows, outside node_modules.
const indexed = await call(commands.findFilesNamed("package.json")).catch(() => []);
for (const file of indexed.slice(0, 500)) {
const path = String(file).replace(/\\/g, "/");
if (!path.startsWith(`${root}/`) || path.includes("/node_modules/")) continue;
dirs.add(path.slice(root.length + 1).replace(/\/?package\.json$/, ""));
}
const packages: NpmNode[] = [];
await Promise.all(
[...dirs].map(async (dir) => {
const path = dir ? `${root}/${dir}/package.json` : `${root}/package.json`;
const text = await call(commands.fsReadText(path)).catch(() => null);
if (text === null) return;
const scripts: NpmScript[] = objectEntries(text, "scripts").map((e: ScriptEntry) => ({
kind: "script" as const,
key: `npm:${dir ? `${dir}:` : ""}${e.name}`,
dir,
path,
name: e.name,
}));
if (scripts.length === 0) return;
scripts.sort((a, b) => a.name.localeCompare(b.name));
packages.push({ kind: "package", key: `pkg:${dir}`, label: dir === "" ? rootName : dir, scripts });
}),
);
if (gen !== loadGen) return;
packages.sort((a, b) =>
a.kind === "package" && b.kind === "package"
? a.label === rootName
? -1
: b.label === rootName
? 1
: a.label.localeCompare(b.label)
: 0,
);
useNpmScripts.setState({ loaded: true, packages });
}
/** Runs or debugs a script the way its gutter icon does. */
export async function runScriptNode(node: NpmScript, debug: boolean): Promise<void> {
const content = await call(commands.fsReadText(node.path)).catch(() => "");
const entry: ScriptEntry = { name: node.name, line: 0 };
const items = await scriptMenuItems(entry, node.path, content ?? "");
const item = items[debug ? 1 : 0];
if (item && "run" in item) item.run?.();
}
/** Keeps the scripts current and shows the npm tool window while the project has any. */
export function startNpmScriptsWatch(): () => void {
let unregister: (() => void) | null = null;
let indexing = true;
const syncToolWindow = (has: boolean) => {
if (has && !unregister)
unregister = registerToolWindow({
id: "npm-scripts",
title: "npm",
icon: "file-npm",
anchor: "right",
order: 13,
component: lazyComponent(() => import("./NpmScriptsView").then((m) => m.NpmScriptsView)),
});
else if (!has && unregister) {
unregister();
unregister = null;
}
};
const disposers = [
useNpmScripts.subscribe((s) => syncToolWindow(s.packages.length > 0)),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) void loadNpmScripts();
}),
useProjectRoots.subscribe((s, prev) => {
if (s.detected !== prev.detected || s.root !== prev.root) void loadNpmScripts();
}),
onIdeEvent("indexState", (e) => {
if (indexing && !e.indexing) void loadNpmScripts();
indexing = e.indexing;
}),
onIdeEvent("fsChanged", (e) => {
const changed = [...e.created, ...e.modified, ...e.removed];
if (changed.some((p) => /(^|\/)package\.json$/.test(p) && !p.includes("/node_modules/"))) void loadNpmScripts();
}),
];
void loadNpmScripts();
return () => {
disposers.forEach((d) => d());
syncToolWindow(false);
};
}
+3 -66
Переглянути файл
@@ -31,7 +31,6 @@ import {
import { downloadJdkActions } from "@/platform/jdk";
import { buildToolRecovery } from "@/platform/buildToolRecovery";
import { useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { executeAction } from "@/platform/actions";
import { workflowSettings } from "@/platform/workflowSettings";
import { maybeEditorService, notifications, toolWindowService, useDebugRunSessions } from "@/workbench/contributions";
@@ -281,73 +280,11 @@ export async function loadConfigs(): Promise<void> {
loadError: null,
selectedId,
});
if (isRemoteWindow()) void reattachRemoteRuns(root, configs);
} catch (e) {
useRun.setState({ loaded: true, loadError: e instanceof Error ? e.message : String(e) });
}
}
/** Reattaches running `ProcessManager` sessions (including `docker compose up`, `docker run` and apps) on a persistent remote daemon. */
async function reattachRemoteRuns(root: string, knownConfigs: readonly RunConfig[]): Promise<void> {
let live;
try {
live = await commands.runList();
} catch {
return;
}
if (useProject.getState().project?.root !== root) return;
for (const info of live) {
if (!info.running) continue;
if (useRun.getState().sessions.some((s) => s.runId === info.id)) continue;
const sessionId = `run${++sessionSeq}`;
const channel = new Channel<OutputChunk>();
let generation = 0;
channel.onmessage = (chunk) => {
if (runtimes.get(sessionId)?.generation !== generation) return;
enqueue(sessionId, chunk);
};
try {
const attached = await call(commands.runAttach(info.id, channel));
if (useProject.getState().project?.root !== root) return;
if (useRun.getState().sessions.some((s) => s.runId === info.id)) continue;
const config = knownConfigs.find((c) => c.id === attached.config.id) ?? attached.config;
const rt = newRuntime(config);
generation = rt.generation;
if (attached.info.pty) rt.terminal = new TerminalOutput();
rt.lineListeners.push((line) => {
const port = startedPort(line);
if (
port !== null &&
runtimes.get(sessionId)?.generation === generation &&
getSession(sessionId)?.httpPort !== port
)
patchSession(sessionId, { httpPort: port });
});
runtimes.set(sessionId, rt);
const session: RunSession = {
id: sessionId,
config,
runId: attached.info.id,
status: attached.info.running ? "running" : "finished",
exitCode: null,
startedAt: Date.now(),
endedAt: attached.info.running ? null : Date.now(),
stdinClosed: !!config.stdinFile,
terminal: attached.info.pty,
pinned: workflowSettings().run.pinTabs || undefined,
};
useRun.setState((s) => ({
sessions: [...s.sessions, session],
activeSession: s.activeSession ?? sessionId,
}));
for (const chunk of attached.buffered) enqueue(sessionId, chunk);
flush(sessionId);
} catch {
/* run exited before attach */
}
}
}
/** IDEA picks an application config first; prefer a run/dev/start target over builds and tests. */
export function defaultSelection(configs: readonly RunConfig[]): RunConfig | undefined {
const score = (c: RunConfig) => {
@@ -1814,9 +1751,9 @@ export function runningSessions(): RunSession[] {
return useRun.getState().sessions.filter(isLive);
}
/** Stops everything (unless detaching from a persistent remote backend) and forgets sessions. */
export function resetRuns(stopBackend = true) {
if (stopBackend) for (const s of runningSessions()) void stopSession(s.id);
/** Stops everything and forgets sessions (project closed). */
export function resetRuns() {
for (const s of runningSessions()) void stopSession(s.id);
for (const rt of runtimes.values()) cancelFlush(rt);
runtimes.clear();
pendingExits.clear();
-1
Переглянути файл
@@ -218,7 +218,6 @@ export function activate(): void | (() => void) {
anchor: "left",
secondary: true,
order: 30,
stripe: "onUse",
component: lazyComponent(() => import("./bookmarks/BookmarksView").then((m) => m.BookmarksView)),
headerActions: lazyComponent(() => import("./bookmarks/BookmarksView").then((m) => m.BookmarksActions)),
useBadge: () => null,
+9 -49
Переглянути файл
@@ -51,41 +51,14 @@ beforeEach(() => {
});
describe("Docker connections", () => {
it("skips a saved disconnected connection on startup and during polling", async () => {
vi.resetModules();
const { connectionState, watch } = await import("./store");
const paused = { id: "paused", name: "Paused", endpoint: { kind: "ssh", config: "build" }, disconnected: true };
const active = { id: "active", name: "Active", endpoint: { kind: "tcp", host: "build:2376" } };
backend.settings.mockResolvedValueOnce(ok({ connections: [paused, active], registries: [] }));
backend.snapshot.mockResolvedValue(ok({ availability: { kind: "daemonDown", message: "Offline" }, errors: [] }));
vi.useFakeTimers();
const stop = watch();
try {
await vi.advanceTimersByTimeAsync(0);
expect(backend.snapshot.mock.calls).toEqual([[active.endpoint]]);
expect(connectionState(paused.id)).toMatchObject({ disconnected: true, snapshot: null });
await vi.advanceTimersByTimeAsync(10_000);
expect(backend.snapshot.mock.calls).toEqual([[active.endpoint], [active.endpoint]]);
} finally {
stop();
vi.useRealTimers();
}
});
it("stop talking to the daemon while disconnected, and connect again on Connect", async () => {
const stop = watch();
await vi.waitFor(() => expect(connectionState("box").snapshot).not.toBeNull());
expect(backend.events).toHaveBeenCalledOnce();
await disconnectConnection("box");
disconnectConnection("box");
expect(backend.cancel).toHaveBeenCalledOnce();
expect(connectionState("box")).toMatchObject({ snapshot: null, disconnected: true });
expect(backend.saveSettings).toHaveBeenLastCalledWith({
connections: [expect.objectContaining({ id: "box", disconnected: true })],
registries: [],
});
backend.snapshot.mockClear();
await refresh("box");
expect(backend.snapshot).not.toHaveBeenCalled();
@@ -93,22 +66,9 @@ describe("Docker connections", () => {
await connectConnection("box");
expect(backend.snapshot).toHaveBeenCalledOnce();
expect(connectionState("box")).toMatchObject({ disconnected: false, snapshot: ready });
expect(backend.saveSettings).toHaveBeenLastCalledWith({
connections: [expect.objectContaining({ id: "box", disconnected: false })],
registries: [],
});
stop();
});
it("preserves the saved disconnect when editing the connection concurrently", async () => {
const edited = { id: "box", name: "Edited box", endpoint: { kind: "default" } } as const;
await Promise.all([disconnectConnection("box"), saveConnection(edited)]);
expect(backend.saveSettings).toHaveBeenLastCalledWith({
connections: [{ ...edited, disconnected: true }],
registries: [],
});
});
describe("over SSH", () => {
const box = { id: "box", name: "Box", endpoint: { kind: "ssh", config: "build" } };
const twin = { id: "twin", name: "Box again", endpoint: { kind: "ssh", config: "build" } };
@@ -121,7 +81,7 @@ describe("Docker connections", () => {
let finish!: () => void;
backend.snapshot.mockReturnValueOnce(new Promise((resolve) => (finish = () => resolve(ok(ready)))));
const reading = refresh("box");
await disconnectConnection("box");
disconnectConnection("box");
await Promise.resolve();
expect(backend.disconnect).not.toHaveBeenCalled();
finish();
@@ -135,20 +95,20 @@ describe("Docker connections", () => {
let finish!: () => void;
backend.snapshot.mockReturnValueOnce(new Promise((resolve) => (finish = () => resolve(ok(ready)))));
const reading = refresh("box");
const disconnecting = disconnectConnection("box");
disconnectConnection("box");
const connecting = connectConnection("box");
finish();
await Promise.all([reading, disconnecting, connecting]);
await Promise.all([reading, connecting]);
await vi.waitFor(() => expect(connectionState("box").snapshot).toEqual(ready));
expect(backend.disconnect).not.toHaveBeenCalled();
});
it("keeps a tunnel another connected connection uses, until that one disconnects too", async () => {
connect(box, twin);
await disconnectConnection("box");
disconnectConnection("box");
await new Promise((r) => setTimeout(r, 0));
expect(backend.disconnect).not.toHaveBeenCalled();
await disconnectConnection("twin");
disconnectConnection("twin");
await vi.waitFor(() => expect(backend.disconnect).toHaveBeenCalledExactlyOnceWith(box.endpoint));
});
@@ -161,7 +121,7 @@ describe("Docker connections", () => {
it("leaves other endpoints alone: they keep nothing open", async () => {
connect(local);
await disconnectConnection("local");
disconnectConnection("local");
await removeConnection("local");
await new Promise((r) => setTimeout(r, 0));
expect(backend.disconnect).not.toHaveBeenCalled();
@@ -169,7 +129,7 @@ describe("Docker connections", () => {
it("matches the configuration as the backend does, ignoring surrounding spaces", async () => {
connect(box, { ...twin, endpoint: { kind: "ssh", config: " build " } });
await disconnectConnection("box");
disconnectConnection("box");
await new Promise((r) => setTimeout(r, 0));
expect(backend.disconnect).not.toHaveBeenCalled();
});
@@ -184,7 +144,7 @@ describe("Docker connections", () => {
connect(box);
let closed!: () => void;
backend.disconnect.mockReturnValueOnce(new Promise((resolve) => (closed = () => resolve(ok(null)))));
await disconnectConnection("box");
disconnectConnection("box");
await vi.waitFor(() => expect(backend.disconnect).toHaveBeenCalledOnce());
backend.snapshot.mockClear();
const connecting = connectConnection("box");
+1 -1
Переглянути файл
@@ -256,7 +256,7 @@ function menu(item: ServiceTreeItem): MenuItem[] {
{ kind: "separator" },
connectionState(c.id).disconnected
? { label: "Connect", run: () => void connectConnection(c.id) }
: { label: "Disconnect", run: () => void disconnectConnection(c.id) },
: { label: "Disconnect", run: () => disconnectConnection(c.id) },
{ label: "Edit Connection…", icon: "edit", run: () => openConnectionDialog(c) },
{ label: "Remove Connection", icon: "trash", danger: true, run: () => void removeConnectionPrompt(c) },
);
+1 -1
Переглянути файл
@@ -169,7 +169,7 @@ export function activate(): () => void {
when: PROJECT,
run: () => {
const id = currentConnection();
if (id && !connectionState(id).disconnected) void disconnectConnection(id);
if (id && !connectionState(id).disconnected) disconnectConnection(id);
},
},
{
+35 -72
Переглянути файл
@@ -58,7 +58,7 @@ export interface ConnectionState {
snapshot: DockerSnapshot | null;
loading: boolean;
error: string | null;
/** Explicitly disconnected: no snapshots, events or polling until Connect. */
/** Disconnected for this session: no snapshots, events or polling until Connect. */
disconnected?: boolean;
/** Containers with a start / stop / … / remove in progress, by id: the operation. */
busy?: Record<string, ContainerOp | "remove">;
@@ -128,18 +128,9 @@ export function loadSettings(): Promise<void> {
return Promise.resolve();
}
settingsLoad ??= call(commands.dockerSettings())
.then((s: DockerSettings) => {
const connections = s.connections ?? [];
useServices.setState((state) => ({
settings: { connections, registries: s.registries ?? [] },
conns: {
...state.conns,
...Object.fromEntries(
connections.filter((c) => c.disconnected).map((c) => [c.id, { ...IDLE, disconnected: true }]),
),
},
}));
})
.then((s: DockerSettings) =>
useServices.setState({ settings: { connections: s.connections ?? [], registries: s.registries ?? [] } }),
)
.catch((e) => {
settingsLoad = null;
notifications().notify({
@@ -152,43 +143,32 @@ export function loadSettings(): Promise<void> {
return settingsLoad;
}
let settingsWrite = Promise.resolve(true);
function saveSettings(update: (current: Settings) => Settings): Promise<boolean> {
// Each write replaces the settings file, so derive it after the previous save.
settingsWrite = settingsWrite.then(async () => {
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 });
return true;
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Cannot save Docker settings",
body: errorMessage(e),
});
return false;
}
});
return settingsWrite;
async function saveSettings(settings: Settings): Promise<boolean> {
try {
if (isTauri()) await call(commands.dockerSaveSettings(settings));
useServices.setState({ settings });
return true;
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Cannot save Docker settings",
body: errorMessage(e),
});
return false;
}
}
export const newId = (prefix: string) => `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
/** Adds or replaces (same id) a connection; the tree picks it up right away. */
export async function saveConnection(c: Pick<DockerConnection, "id" | "name" | "endpoint">): Promise<boolean> {
export async function saveConnection(c: DockerConnection): Promise<boolean> {
await loadSettings();
let old: DockerEndpoint | undefined;
const ok = await saveSettings((s) => {
old = s.connections.find((x) => x.id === c.id)?.endpoint;
return {
...s,
connections: old ? s.connections.map((x) => (x.id === c.id ? { ...x, ...c } : x)) : [...s.connections, c],
};
const s = useServices.getState().settings ?? { connections: [], registries: [] };
const old = s.connections.find((x) => x.id === c.id)?.endpoint;
const ok = await saveSettings({
...s,
connections: old ? s.connections.map((x) => (x.id === c.id ? c : x)) : [...s.connections, c],
});
if (ok) {
stopEvents(c.id);
@@ -203,7 +183,7 @@ export async function removeConnection(id: string): Promise<void> {
if (!s) return;
stopEvents(id);
const endpoint = endpointOf(id);
if (await saveSettings((s) => ({ ...s, connections: s.connections.filter((c) => c.id !== id) }))) {
if (await saveSettings({ ...s, connections: s.connections.filter((c) => c.id !== id) })) {
useServices.setState((st) => {
const conns = { ...st.conns };
delete conns[id];
@@ -216,12 +196,11 @@ export async function removeConnection(id: string): Promise<void> {
/** Adds or replaces a registry; `password` undefined keeps the saved one, null forgets it. */
export async function saveRegistry(r: DockerRegistry, password: string | null | undefined): Promise<boolean> {
await loadSettings();
const ok = await saveSettings((s) => {
const exists = s.registries.some((x) => x.id === r.id);
return {
...s,
registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r],
};
const s = useServices.getState().settings ?? { connections: [], registries: [] };
const exists = s.registries.some((x) => x.id === r.id);
const ok = await saveSettings({
...s,
registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r],
});
if (ok && password !== undefined && isTauri()) {
try {
@@ -240,18 +219,7 @@ export async function saveRegistry(r: DockerRegistry, password: string | null |
export async function removeRegistry(id: string): Promise<void> {
const s = useServices.getState().settings;
if (s) await saveSettings((s) => ({ ...s, registries: s.registries.filter((r) => r.id !== id) }));
}
function saveConnectionDisconnected(id: string, disconnected: boolean): Promise<boolean> {
return saveSettings((s) => {
const existing = s.connections.find((c) => c.id === id);
if (!existing || (existing.disconnected ?? false) === disconnected) return s;
return {
...s,
connections: s.connections.map((c) => (c.id === id ? { ...c, disconnected } : c)),
};
});
if (s) await saveSettings({ ...s, registries: s.registries.filter((r) => r.id !== id) });
}
/** Test login; resolves to docker's answer, rejects with its error. */
@@ -343,9 +311,7 @@ export function watch(): () => void {
if (watchers === 1) {
pollTimer = setInterval(() => {
for (const c of connections()) {
const state = connectionState(c.id);
if (state.disconnected) continue;
const ready = state.snapshot?.availability.kind === "ready";
const ready = connectionState(c.id).snapshot?.availability.kind === "ready";
if (!ready || !events.has(c.id)) void refresh(c.id);
}
}, 10_000);
@@ -361,24 +327,21 @@ export function watch(): () => void {
/**
* Disconnect: stops talking to the connection's daemon (its event stream and polling; for an
* SSH connection, its tunnel and SSH connection) until Connect, even across restarts.
* SSH connection, its tunnel and SSH connection) until Connect. Not saved: a new session connects.
*/
export async function disconnectConnection(id: string): Promise<void> {
export function disconnectConnection(id: string): void {
stopEvents(id);
clearTimeout(debounces.get(id));
again.delete(id);
patchConn(id, { snapshot: null, error: null, loading: false, disconnected: true });
closeEndpoint(id, endpointOf(id));
await saveConnectionDisconnected(id, true);
}
export async function connectConnection(id: string): Promise<void> {
patchConn(id, { disconnected: false });
const saving = saveConnectionDisconnected(id, false);
// A tunnel being closed would take this connection's next snapshot down with it.
await closing.get(id);
await refresh(id);
await saving;
return refresh(id);
}
/** The SSH configuration an endpoint tunnels through (as the backend keys its tunnels). */
-6
Переглянути файл
@@ -41,7 +41,6 @@ import {
type NotificationsValid,
} from "./behaviorSchema";
import { isThemeChoiceId, type ThemeChoiceId } from "@/platform/themes";
import { DEFAULT_REMOTE_IDLE_MINUTES, validRemoteIdleMinutes } from "@/platform/remoteIdle";
/** Agents › IDE MCP Server › Port: its default (`ide-core::settings::DEFAULT_MCP_PORT`) and range. */
export const DEFAULT_MCP_PORT = 26371;
@@ -116,7 +115,6 @@ export interface ValidSettings extends WorkflowSettings {
notifications: NotificationsValid;
/** System Settings › HTTP Proxy (global). */
proxy: ProxySettingsValid;
remoteDevelopment: { idleTimeoutMinutes: number };
/** Tools › Download sources: a mirror prefix for the installer's release downloads. */
toolDownloads: { githubMirror: string };
languages: LanguagesValid;
@@ -226,7 +224,6 @@ export const DEFAULT_SETTINGS: ValidSettings = {
customKeymaps: {},
notifications: DEFAULT_NOTIFICATIONS,
proxy: DEFAULT_PROXY,
remoteDevelopment: { idleTimeoutMinutes: DEFAULT_REMOTE_IDLE_MINUTES },
toolDownloads: { githubMirror: "" },
languages: DEFAULT_LANGUAGES,
cmake: {},
@@ -428,9 +425,6 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
customKeymaps,
notifications: validateNotifications(root.notifications),
proxy: validateProxy(root.proxy),
remoteDevelopment: {
idleTimeoutMinutes: validRemoteIdleMinutes(obj(root.remoteDevelopment).idleTimeoutMinutes),
},
toolDownloads: {
githubMirror:
typeof obj(root.toolDownloads).githubMirror === "string"
-5
Переглянути файл
@@ -3,8 +3,3 @@
flex-direction: column;
max-width: 680px;
}
.durationAmount {
width: 12ch;
font-variant-numeric: tabular-nums;
}
-2
Переглянути файл
@@ -10,7 +10,6 @@ import { EXECUTION_PAGES } from "./execution";
import { LANGUAGE_PAGES } from "./languages";
import { preloadBuiltinPage } from "./lazyPage";
import { OptionsPage } from "./OptionsPage";
import { REMOTE_DEVELOPMENT_PAGE } from "./remoteDevelopment";
import { RUN_TARGET_PAGES } from "./runTargets";
import { SCOPE_PAGES } from "./scopes";
import { flattenOptions, specLabels, type PageSpec } from "./spec";
@@ -33,7 +32,6 @@ const BUILTIN_PAGES = [
...RUN_TARGET_PAGES,
...TOOLS_PAGES,
...SSH_PAGES,
REMOTE_DEVELOPMENT_PAGE,
...LANGUAGE_PAGES,
];
const specs = new Map<string, PageSpec>(BUILTIN_PAGES.map((p) => [p.id, p]));
-155
Переглянути файл
@@ -1,155 +0,0 @@
import { useId, useState } from "react";
import { tx, useTx } from "@/platform/i18n";
import { useRemote } from "@/platform/remote";
import { DEFAULT_REMOTE_IDLE_MINUTES, MAX_REMOTE_IDLE_MINUTES, formatIdleDuration } from "@/platform/remoteIdle";
import { Input, Select } from "@/ui";
import { Row } from "../components/Form";
import { useSetting } from "../components/context";
import type { PageSpec } from "./spec";
import { TOOLS_GROUP } from "./tools";
import styles from "./Pages.module.css";
const PRESETS = [30, 60, DEFAULT_REMOTE_IDLE_MINUTES, 480, 1440];
const SCALES = { minutes: 1, hours: 60, days: 1440 };
type Unit = keyof typeof SCALES;
function CustomDuration({ minutes, setMinutes }: { minutes: number; setMinutes: (n: number) => void }) {
const id = useId();
const [unit, setUnit] = useState<Unit>(() =>
minutes % 1440 === 0 ? "days" : minutes % 60 === 0 ? "hours" : "minutes",
);
const [draft, setDraft] = useState<string | null>(null);
const scale = SCALES[unit];
// Changing the unit only changes the display; it must never round or stage a new timeout.
const display = (n: number) => String(Number((n / scale).toFixed(6)));
const parse = (text: string) => {
const decimal = text.trim().replace(",", ".");
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(decimal)) return null;
const value = Number(decimal) * scale;
const rounded = Math.round(value);
if (rounded < 1 || rounded > MAX_REMOTE_IDLE_MINUTES) return null;
if (Number(decimal) === Number(display(minutes))) return minutes;
return Math.abs(value - rounded) <= Number.EPSILON * Math.max(1, value) ? rounded : null;
};
const invalid = draft !== null && parse(draft) === null;
return (
<Row
label="Custom duration"
htmlFor={id}
hint={invalid ? tx("Enter a duration equivalent to 1–65,535 whole minutes.") : undefined}
>
<Input
id={id}
className={styles.durationAmount}
inputMode="decimal"
invalid={invalid}
value={draft ?? display(minutes)}
onChange={(e) => {
setDraft(e.target.value);
const next = parse(e.target.value);
if (next !== null) setMinutes(next);
}}
onBlur={() => setDraft(null)}
/>
<Select<Unit>
aria-label="Duration unit"
value={unit}
options={[
{ value: "minutes", label: "Minutes" },
{ value: "hours", label: "Hours" },
{ value: "days", label: "Days" },
]}
onChange={(next) => {
setUnit(next);
setDraft(null);
}}
/>
</Row>
);
}
function IdleTimeout() {
const tr = useTx();
const session = useRemote((s) => s.session);
const disconnected = useRemote((s) => s.lost !== null);
const [minutes, setMinutes] = useSetting<number>("remoteDevelopment.idleTimeoutMinutes");
const [customAt, setCustomAt] = useState<number | null>(null);
const id = useId();
const host = session?.host;
const seconds = session?.idlePolicy?.overrideSeconds;
if (session && !disconnected && seconds != null) {
return (
<Row label="Stop backend when idle" hint={tr`Set by OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS on ${host}.`}>
{formatIdleDuration(seconds)}
</Row>
);
}
const disabled = !session?.idlePolicy || disconnected;
const value =
minutes === 0 ? "never" : customAt === minutes || !PRESETS.includes(minutes) ? "custom" : String(minutes);
const hint = !session
? tr("Open Settings in a remote project window to change its backend timeout.")
: disconnected
? tr("Reconnect to the remote host to change its backend timeout.")
: !session.idlePolicy
? tr("This backend does not support a configurable idle timeout.")
: minutes === 0
? tr`Idle shutdown is off on ${host}. You can still stop the backend manually.`
: tr`The timer starts when the last window disconnects from ${host} and no terminals, runs, debug sessions, or agent tasks are active.`;
const custom = (next: number) => {
setCustomAt(next);
setMinutes(next);
};
return (
<>
<Row label="Stop backend when idle" htmlFor={id} hint={hint} disabled={disabled}>
<Select
id={id}
aria-label="Stop backend when idle"
disabled={disabled}
value={value}
options={[
...PRESETS.map((n) => {
const duration = formatIdleDuration(n * 60);
return {
value: String(n),
label: n === DEFAULT_REMOTE_IDLE_MINUTES ? tr`After ${duration} (default)` : tr`After ${duration}`,
};
}),
{ value: "custom", label: "Custom…" },
{ value: "never", label: "Never" },
]}
onChange={(next) => {
if (next === "custom") custom(minutes || DEFAULT_REMOTE_IDLE_MINUTES);
else {
setCustomAt(null);
setMinutes(next === "never" ? 0 : Number(next));
}
}}
/>
</Row>
{!disabled && value === "custom" && <CustomDuration minutes={minutes} setMinutes={custom} />}
</>
);
}
export const REMOTE_DEVELOPMENT_PAGE: PageSpec = {
id: "tools.remoteDevelopment",
title: "Remote Development",
group: TOOLS_GROUP,
order: 604,
keywords: ["SSH", "WSL", "dev container", "disconnect", "shutdown", "idle timeout"],
sections: [
{
title: "Remote backend",
options: [
{
kind: "custom",
label: "Stop backend when idle",
keywords: ["Idle timeout", "Custom duration", "Never"],
component: IdleTimeout,
},
],
},
],
};
+2 -10
Переглянути файл
@@ -4,12 +4,11 @@
* its own. The session lives in `cliSessions.ts`; this only attaches its host while the
* tab is the one shown.
*/
import { useEffect, useLayoutEffect, useRef, type FocusEvent } from "react";
import { useLayoutEffect, useRef, type FocusEvent } from "react";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { useEditorShown, type EditorInput } from "@/workbench/contributions";
import { Button, EmptyState, T } from "@/ui";
import { cliData, reattachCliTab, startTab, useClis } from "./cli";
import { cliData, startTab, useClis } from "./cli";
import { cliSession } from "./cliSessions";
import styles from "./Cli.module.css";
// The pane is the terminal tool window's own: same xterm layout, cursor and scrollbar.
@@ -20,15 +19,8 @@ export function CliEditor({ input }: { input: EditorInput }) {
const live = useClis((s) => !!s.sessions[input.key]);
const shown = useEditorShown();
const project = useProject((s) => s.project);
const remote = useRemote((s) => s.session !== null);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!live && remote && project?.root && data?.terminalId) {
void reattachCliTab(input);
}
}, [live, remote, project?.root, data?.terminalId, input]);
// Hidden tabs stay unopened (xterm opened at 0×0 never takes keys); the session keeps running.
useLayoutEffect(() => {
const el = ref.current;
+5 -23
Переглянути файл
@@ -1,7 +1,6 @@
import { Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { useProject } from "@/platform/project";
import { isRemoteWindow, projectLocation, useRemote } from "@/platform/remote";
import { toolWindowService } from "@/workbench/contributions";
import { ToolWindowHeader, useOwnToolWindowHeader } from "@/workbench/toolwindows/ToolWindows";
import { usePlatform } from "@/platform/platformInfo";
@@ -46,7 +45,6 @@ import {
tabTitle,
topRightGroup,
useTerminals,
waitForTerminalRestore,
type GroupLayout,
type TerminalTab,
} from "./store";
@@ -266,8 +264,6 @@ function RenamePopup({ tab, anchor, onClose }: { tab: TerminalTab; anchor: Eleme
export function TerminalView() {
const layout = useTerminals((s) => s.layout);
const root = useProject((s) => s.project?.root);
const remoteSession = useRemote((s) => s.session);
const scope = projectLocation(root);
const rootRef = useRef<HTMLDivElement>(null);
const split = typeof layout !== "string";
// Split, each group shows a header of its own, as in IDEA.
@@ -279,23 +275,12 @@ export function TerminalView() {
useEffect(() => {
const el = rootRef.current;
if (!root || !el) return;
let alive = true;
const ensureTab = () => {
if (!alive || el.clientHeight <= 0) return;
if (el.clientHeight <= 0) return;
// Restore this project's tabs once the pane is actually visible. A project
// switch while the runtime is loaded restores from the project subscription.
syncTerminalProject(root, scope);
if (useTerminals.getState().tabs.length === 0) {
if (isRemoteWindow()) {
void waitForTerminalRestore().then(() => {
if (!alive || el.clientHeight <= 0 || useProject.getState().project?.root !== root) return;
if (useTerminals.getState().tabs.length === 0) newTab(root);
refitSessions();
});
return;
}
newTab(root);
}
syncTerminalProject(root);
if (useTerminals.getState().tabs.length === 0) newTab(root);
// Sessions created while this window was hidden open once it actually has a box.
refitSessions();
};
@@ -303,11 +288,8 @@ export function TerminalView() {
if (typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(ensureTab);
ro.observe(el);
return () => {
alive = false;
ro.disconnect();
};
}, [root, scope, remoteSession]);
return () => ro.disconnect();
}, [root]);
return (
<div
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more