дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 21:42:27 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
25f82363a4 | ||
|
|
fec50f3925 | ||
|
|
8b3d9adcfe | ||
|
|
457174a442 | ||
|
|
de868f1677 |
No files matched your search
@@ -155,6 +155,12 @@ 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
|
||||
|
||||
@@ -661,6 +661,15 @@ 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);
|
||||
@@ -2514,6 +2523,8 @@ 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);
|
||||
@@ -2827,11 +2838,8 @@ impl Task {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// Adds the user's message to the conversation and shows the task starting.
|
||||
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt) {
|
||||
let attachments = prompt
|
||||
.files
|
||||
.iter()
|
||||
@@ -2849,6 +2857,13 @@ 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) {
|
||||
|
||||
@@ -40,10 +40,11 @@ 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 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.
|
||||
/// This remote window's connection ended or another window took over the session.
|
||||
RemoteConnectionLost {
|
||||
host: String,
|
||||
#[serde(default)]
|
||||
taken_over: bool,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
|
||||
@@ -4,6 +4,20 @@
|
||||
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")]
|
||||
|
||||
@@ -60,6 +60,7 @@ 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.
|
||||
@@ -578,6 +579,7 @@ 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(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! `openidea-server --stdio`: the IDE backend for remote development, serving
|
||||
//! one desktop client over stdin / stdout (started by the client over SSH).
|
||||
//! `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>`).
|
||||
|
||||
use ide_host::catalogue::TrustClass;
|
||||
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
|
||||
@@ -10,6 +11,12 @@ 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) {
|
||||
@@ -35,18 +42,48 @@ fn main() {
|
||||
};
|
||||
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 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);
|
||||
}
|
||||
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");
|
||||
@@ -55,7 +92,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));
|
||||
let code = runtime.block_on(run(base, mode));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
@@ -64,7 +101,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) -> i32 {
|
||||
async fn run(base: PathBuf, mode: Mode) -> 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) {
|
||||
@@ -82,40 +119,103 @@ async fn run(base: PathBuf) -> 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());
|
||||
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.
|
||||
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) {
|
||||
host.mcp.set_stdio_link(base.join("bin").join("openidea-server"));
|
||||
host.mcp_background.serve_none();
|
||||
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()) {
|
||||
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) {
|
||||
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());
|
||||
}
|
||||
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
|
||||
}
|
||||
|
||||
fn build_dispatcher(plugins: &Option<Arc<RemotePlugins>>, plugin_languages: Arc<RemotePluginLanguages>) -> Dispatcher {
|
||||
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| {
|
||||
@@ -126,14 +226,13 @@ async fn run(base: PathBuf) -> i32 {
|
||||
Ok(report)
|
||||
}
|
||||
});
|
||||
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
|
||||
host.mcp.stop(&host);
|
||||
if let Some(plugins) = &plugins {
|
||||
dispatcher
|
||||
}
|
||||
|
||||
async fn shutdown_all(host: &Host, plugins: Option<&Arc<RemotePlugins>>) {
|
||||
host.mcp.stop(host);
|
||||
if let Some(plugins) = plugins {
|
||||
plugins.host().shutdown();
|
||||
}
|
||||
// `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
|
||||
host.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! 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())
|
||||
}
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
pub mod agent_secrets;
|
||||
pub mod catalogue;
|
||||
#[cfg(unix)]
|
||||
pub mod daemon;
|
||||
pub mod data_dirs;
|
||||
pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
@@ -526,6 +528,25 @@ 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).
|
||||
@@ -533,7 +554,6 @@ 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 {
|
||||
@@ -553,22 +573,33 @@ 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.
|
||||
for project in &projects {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.shutdown().await;
|
||||
let stop_kernels = async {
|
||||
for project in &projects {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.shutdown().await;
|
||||
}
|
||||
project.notebooks.shutdown().await;
|
||||
}
|
||||
project.notebooks.shutdown().await;
|
||||
}
|
||||
};
|
||||
let stop_language_servers = async {
|
||||
for project in &projects {
|
||||
project.lsp.shutdown_all().await;
|
||||
}
|
||||
};
|
||||
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");
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
// ---- cancellable requests: the UI allocates ids, `cancel_request` cancels ----
|
||||
|
||||
@@ -87,6 +87,15 @@ 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.
|
||||
@@ -481,6 +490,7 @@ 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,
|
||||
|
||||
@@ -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, RunConfig, RunInfo, StartOptions};
|
||||
use ide_run::{OutputChunk, RunAttach, RunConfig, RunInfo, StartOptions};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -644,6 +644,19 @@ 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::*;
|
||||
@@ -816,6 +829,7 @@ mod ownership_tests {
|
||||
ide_command::domain!(
|
||||
run:
|
||||
run_apply_settings,
|
||||
run_attach,
|
||||
run_close_stdin,
|
||||
run_configs,
|
||||
run_list,
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::{Channel, Emit};
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeResult, IpcBytes, TerminalId};
|
||||
use ide_terminal::{TerminalInfo, TerminalOptions};
|
||||
use ide_terminal::{TerminalAttach, TerminalInfo, TerminalOptions, TerminalSessionInfo};
|
||||
|
||||
mod images;
|
||||
|
||||
@@ -53,6 +53,7 @@ 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"));
|
||||
@@ -160,6 +161,36 @@ 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)]
|
||||
@@ -202,10 +233,12 @@ 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,
|
||||
|
||||
@@ -20,17 +20,16 @@
|
||||
|
||||
use super::{Consent, HostWorkspace, PluginEvent, PluginHost, PluginSource, SecretStore};
|
||||
use crate::catalogue::TrustClass;
|
||||
use crate::rpc::Dispatcher;
|
||||
use crate::rpc::{Dispatcher, PeerHandle};
|
||||
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, OnceLock, Weak};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
/// The server command the desktop calls with its packages.
|
||||
@@ -246,13 +245,13 @@ pub struct RemotePlugins {
|
||||
|
||||
/// Secrets from the desktop's keychain, asked for when used.
|
||||
struct ClientSecrets {
|
||||
peer: Arc<OnceLock<Peer>>,
|
||||
peer: Arc<dyn PeerHandle>,
|
||||
runtime: tokio::runtime::Handle,
|
||||
}
|
||||
|
||||
impl SecretStore for ClientSecrets {
|
||||
fn get(&self, plugin: &str, name: &str) -> Option<String> {
|
||||
let peer = self.peer.get()?.clone();
|
||||
let peer = self.peer.current()?;
|
||||
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
|
||||
@@ -275,7 +274,7 @@ impl SecretStore for ClientSecrets {
|
||||
}
|
||||
|
||||
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
|
||||
let peer = self.peer.get().ok_or("desktop disconnected")?.clone();
|
||||
let peer = self.peer.current().ok_or("desktop disconnected")?;
|
||||
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))
|
||||
@@ -293,11 +292,12 @@ 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(data_dir: &Path, projects: &Arc<crate::Host>, peer: Arc<OnceLock<Peer>>) -> IdeResult<Arc<Self>> {
|
||||
pub fn start<P: PeerHandle>(data_dir: &Path, projects: &Arc<crate::Host>, peer: Arc<P>) -> IdeResult<Arc<Self>> {
|
||||
let peer: Arc<dyn PeerHandle> = peer;
|
||||
let sink_peer = peer.clone();
|
||||
let sink = move |client: Option<&str>, event: PluginEvent| {
|
||||
if forwarded(&event)
|
||||
&& let Some(p) = sink_peer.get()
|
||||
&& let Some(p) = sink_peer.current()
|
||||
{
|
||||
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<OnceLock<Peer>>,
|
||||
peer: Arc<dyn PeerHandle>,
|
||||
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.get().ok_or(ide_plugin::HostError::Cancelled)?.clone();
|
||||
let peer = self.peer.current().ok_or(ide_plugin::HostError::Cancelled)?;
|
||||
let timeout = match &operation {
|
||||
AuthOperation::Wait { timeout_ms, .. } => Duration::from_millis(u64::from(*timeout_ms)) + SECRET_TIMEOUT,
|
||||
_ => SECRET_TIMEOUT,
|
||||
|
||||
@@ -16,7 +16,6 @@ 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;
|
||||
@@ -169,7 +168,7 @@ impl PluginHost {
|
||||
plugin_id: &str,
|
||||
window: &str,
|
||||
output: crate::ops::Emit<String>,
|
||||
completion: Option<Arc<dyn Fn(Option<i32>) + Send + Sync>>,
|
||||
completion: Option<ide_terminal::TerminalExitHook>,
|
||||
options: impl FnOnce() -> IdeResult<ide_terminal::TerminalOptions>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
@@ -184,20 +183,12 @@ 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(),
|
||||
sink,
|
||||
host.window_sink(window),
|
||||
Box::new(move |data| output(data)),
|
||||
completion,
|
||||
)?;
|
||||
if !self
|
||||
.shared
|
||||
|
||||
@@ -76,6 +76,8 @@ 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,
|
||||
@@ -106,6 +108,14 @@ 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
|
||||
@@ -377,6 +387,10 @@ 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());
|
||||
@@ -390,6 +404,7 @@ 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();
|
||||
@@ -513,6 +528,7 @@ impl Host {
|
||||
scan_repositories(
|
||||
&root,
|
||||
&repos,
|
||||
git_metadata.as_deref(),
|
||||
&settings,
|
||||
&sink,
|
||||
&build_cache,
|
||||
@@ -603,11 +619,11 @@ impl Host {
|
||||
mark("watcher");
|
||||
{
|
||||
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
|
||||
let build_cache = build_cache.clone();
|
||||
let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone());
|
||||
let trusted = trusted.load(Ordering::Acquire);
|
||||
std::thread::Builder::new()
|
||||
.name("openidea-vcs-roots".into())
|
||||
.spawn(move || scan_repositories(&root, &repos, &settings, &sink, &build_cache, trusted))?;
|
||||
std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || {
|
||||
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted)
|
||||
})?;
|
||||
}
|
||||
mark("git");
|
||||
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
|
||||
@@ -656,6 +672,7 @@ 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,
|
||||
@@ -903,6 +920,7 @@ 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,
|
||||
@@ -1006,6 +1024,7 @@ fn light_watcher(
|
||||
fn scan_repositories(
|
||||
root: &Path,
|
||||
repos: &RwLock<Repos>,
|
||||
git_metadata: Option<&ide_vcs::MetadataWatch>,
|
||||
settings: &SettingsStore,
|
||||
sink: &SharedSink,
|
||||
build_cache: &Path,
|
||||
@@ -1014,6 +1033,9 @@ 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() });
|
||||
}
|
||||
@@ -1067,6 +1089,7 @@ impl Project {
|
||||
scan_repositories(
|
||||
&self.root,
|
||||
&self.repos,
|
||||
self.git_metadata.as_deref(),
|
||||
&self.settings,
|
||||
&self.sink,
|
||||
&self.build_cache_dir(),
|
||||
@@ -2321,6 +2344,20 @@ 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)
|
||||
}
|
||||
@@ -2605,3 +2642,77 @@ 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,15 @@ 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")]
|
||||
@@ -38,6 +47,8 @@ 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)]
|
||||
@@ -60,12 +71,71 @@ 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<OnceLock<Peer>>,
|
||||
peer: Arc<dyn PeerHandle>,
|
||||
}
|
||||
|
||||
impl Call {
|
||||
@@ -91,7 +161,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.get() else { return };
|
||||
let Some(peer) = peer.current() else { return };
|
||||
match serde_json::to_value(&data) {
|
||||
Ok(data) => {
|
||||
let _ = peer.notify("channel", ChannelMessage { id, data });
|
||||
@@ -151,23 +221,56 @@ 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>(host: Arc<Host>, dispatcher: Dispatcher, peer: Arc<OnceLock<Peer>>, reader: R, writer: W)
|
||||
pub async fn serve<R, W, P>(host: Arc<Host>, dispatcher: Dispatcher, peer: Arc<P>, 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 p = Peer::connect(reader, writer, handler);
|
||||
let (generation, previous) = slot.install(p.clone());
|
||||
if let Some(old) = previous {
|
||||
old.kill();
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
{
|
||||
let handler = Arc::new(ServerHandler { host: host.clone(), dispatcher, peer: peer.clone() });
|
||||
// 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 _ = peer.set(p.clone());
|
||||
p.closed().await;
|
||||
// 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);
|
||||
}
|
||||
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(peer: Arc<OnceLock<Peer>>, window: Option<String>) -> ide_core::SharedSink {
|
||||
pub fn event_sink<P: PeerHandle>(peer: Arc<P>, window: Option<String>) -> ide_core::SharedSink {
|
||||
Arc::new(PeerSink { peer, window })
|
||||
}
|
||||
|
||||
@@ -218,13 +321,13 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
|
||||
}
|
||||
|
||||
struct PeerSink {
|
||||
peer: Arc<OnceLock<Peer>>,
|
||||
peer: Arc<dyn PeerHandle>,
|
||||
window: Option<String>,
|
||||
}
|
||||
|
||||
impl ide_core::EventSink for PeerSink {
|
||||
fn emit(&self, event: IdeEvent) {
|
||||
if let Some(peer) = self.peer.get() {
|
||||
if let Some(peer) = self.peer.current() {
|
||||
let _ = peer.notify("event", EventMessage { window: self.window.clone(), event });
|
||||
}
|
||||
}
|
||||
@@ -233,16 +336,18 @@ impl ide_core::EventSink for PeerSink {
|
||||
struct ServerHandler {
|
||||
host: Arc<Host>,
|
||||
dispatcher: Dispatcher,
|
||||
peer: Arc<OnceLock<Peer>>,
|
||||
peer: Arc<dyn PeerHandle>,
|
||||
daemon: Option<(ide_core::CancellationToken, RemoteIdlePolicy)>,
|
||||
}
|
||||
|
||||
pub fn server_info() -> ServerInfo {
|
||||
fn server_info(idle_policy: Option<RemoteIdlePolicy>) -> 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,10 +355,16 @@ 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()).map_err(internal),
|
||||
"initialize" => {
|
||||
serde_json::to_value(server_info(self.daemon.as_ref().map(|(_, policy)| *policy))).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()))?;
|
||||
@@ -268,6 +379,14 @@ 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.
|
||||
|
||||
@@ -0,0 +1,877 @@
|
||||
//! 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");
|
||||
}
|
||||
@@ -720,6 +720,14 @@ 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",
|
||||
@@ -729,16 +737,23 @@ 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;
|
||||
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}),
|
||||
)
|
||||
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;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let received: Value = serde_json::from_str(received.as_str().unwrap()).unwrap();
|
||||
.expect("plugin terminal completion after reattach");
|
||||
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();
|
||||
|
||||
@@ -30,6 +30,7 @@ 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"] {
|
||||
|
||||
@@ -250,8 +250,13 @@ 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<Vec<u8>>,
|
||||
out: mpsc::UnboundedSender<Outgoing>,
|
||||
pending: Mutex<Pending>,
|
||||
next_id: AtomicI64,
|
||||
/// Set once the transport is gone; new requests fail fast.
|
||||
@@ -275,7 +280,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(body).map_err(|_| RpcError::Closed)
|
||||
self.out.send(Outgoing::Message(body)).map_err(|_| RpcError::Closed)
|
||||
}
|
||||
|
||||
/// Fails every in-flight request and refuses new ones.
|
||||
@@ -479,6 +484,20 @@ 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
|
||||
@@ -520,7 +539,7 @@ impl Peer {
|
||||
R: AsyncRead + Unpin + Send + 'static,
|
||||
W: AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
|
||||
let (out_tx, mut out_rx) = mpsc::unbounded_channel();
|
||||
let (closed, _) = watch::channel(None);
|
||||
let inner = Arc::new(Inner {
|
||||
out: out_tx,
|
||||
@@ -547,7 +566,14 @@ impl Peer {
|
||||
body = out_rx.recv() => body,
|
||||
_ = kill.cancelled() => None,
|
||||
};
|
||||
let Some(body) = body else { break };
|
||||
let body = match body {
|
||||
Some(Outgoing::Message(body)) => body,
|
||||
Some(Outgoing::Flush(done)) => {
|
||||
let _ = done.send(());
|
||||
continue;
|
||||
}
|
||||
None => break,
|
||||
};
|
||||
if let Err(e) = framing.write(&mut writer, &body).await {
|
||||
tracing::debug!("jsonrpc write failed: {e}");
|
||||
if let Some(inner) = weak.upgrade() {
|
||||
@@ -706,6 +732,13 @@ 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();
|
||||
|
||||
@@ -242,6 +242,15 @@ 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),
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
//! for "Emulate terminal in output console"), stream output, stdin, stop.
|
||||
|
||||
use crate::utf8::OutputDecoder;
|
||||
use crate::{OutputChunk, RunConfig, RunInfo};
|
||||
use crate::{OutputChunk, RunAttach, 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;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
@@ -32,11 +32,43 @@ 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 {
|
||||
@@ -54,6 +86,7 @@ struct StopCommand {
|
||||
struct Entry {
|
||||
project_root: PathBuf,
|
||||
id: RunId,
|
||||
config: RunConfig,
|
||||
config_id: String,
|
||||
name: String,
|
||||
pid: Mutex<Option<u32>>,
|
||||
@@ -67,13 +100,18 @@ struct Entry {
|
||||
#[cfg(windows)]
|
||||
job: Option<ide_core::process::Job>,
|
||||
stop: Option<StopCommand>,
|
||||
output: OutputFn,
|
||||
output: Mutex<RunOutputState>,
|
||||
sink: Mutex<SharedSink>,
|
||||
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,
|
||||
@@ -479,6 +517,7 @@ 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())),
|
||||
@@ -487,14 +526,15 @@ impl ProcessManager {
|
||||
#[cfg(windows)]
|
||||
job,
|
||||
stop,
|
||||
output: on_output.clone(),
|
||||
output: Mutex::new(RunOutputState::new(on_output)),
|
||||
sink: Mutex::new(sink),
|
||||
exited: AtomicBool::new(false),
|
||||
code: Mutex::new(None),
|
||||
stopping: AtomicBool::new(false),
|
||||
});
|
||||
self.register(entry.clone());
|
||||
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = output_queue();
|
||||
let stdout = child.stdout.take();
|
||||
@@ -521,7 +561,7 @@ impl ProcessManager {
|
||||
)?;
|
||||
}
|
||||
let decoder = || OutputDecoder::for_pipes(options.encoding.as_deref());
|
||||
spawn_pump(rx, on_output.clone(), entry.clone(), sink, [decoder(), decoder()], notice)?;
|
||||
spawn_pump(rx, entry.clone(), [decoder(), decoder()], notice)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
@@ -626,6 +666,7 @@ 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()),
|
||||
@@ -635,13 +676,14 @@ impl ProcessManager {
|
||||
#[cfg(windows)]
|
||||
job: child.process_id().and_then(ide_core::process::Job::for_pid),
|
||||
stop,
|
||||
output: on_output.clone(),
|
||||
output: Mutex::new(RunOutputState::new(on_output)),
|
||||
sink: Mutex::new(sink),
|
||||
exited: AtomicBool::new(false),
|
||||
code: Mutex::new(None),
|
||||
stopping: AtomicBool::new(false),
|
||||
});
|
||||
self.register(entry.clone());
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
entry.emit_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = output_queue();
|
||||
let result = spawn_reader(
|
||||
@@ -654,7 +696,7 @@ impl ProcessManager {
|
||||
)
|
||||
.and_then(|_| {
|
||||
let decoder = || OutputDecoder::for_label(options.encoding.as_deref());
|
||||
spawn_pump(rx, on_output, entry.clone(), sink, [decoder(), decoder()], None)
|
||||
spawn_pump(rx, entry.clone(), [decoder(), decoder()], None)
|
||||
});
|
||||
if let Err(e) = result {
|
||||
let _ = child.kill();
|
||||
@@ -763,7 +805,7 @@ impl ProcessManager {
|
||||
!group_alive(pid, &entry)
|
||||
};
|
||||
if let Some(stop) = &entry.stop {
|
||||
run_stop_command(stop, &entry.output);
|
||||
run_stop_command(stop, &entry);
|
||||
if exits_within(grace) {
|
||||
return;
|
||||
}
|
||||
@@ -800,6 +842,40 @@ 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) {
|
||||
@@ -821,6 +897,34 @@ 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 {
|
||||
@@ -865,7 +969,7 @@ fn run_followup(
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x0000_0200 | ide_core::process::CREATE_NO_WINDOW);
|
||||
}
|
||||
(entry.output)(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
entry.emit_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.
|
||||
@@ -997,11 +1101,12 @@ 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, output: &OutputFn) {
|
||||
output(OutputChunk::System { text: format!("{}\n", stop.line) });
|
||||
fn run_stop_command(stop: &StopCommand, entry: &Entry) {
|
||||
entry.emit_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 {
|
||||
@@ -1012,16 +1117,18 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
output(OutputChunk::Stderr { text: format!("Cannot run the stop command: {e}\n") });
|
||||
entry.emit_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);
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
})
|
||||
let _ = send.send(String::from_utf8_lossy(&buf).into_owned());
|
||||
});
|
||||
receive
|
||||
});
|
||||
let deadline = Instant::now() + STOP_COMMAND_TIMEOUT;
|
||||
let status = loop {
|
||||
@@ -1029,15 +1136,17 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
|
||||
Ok(Some(status)) => break Some(status),
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
}
|
||||
};
|
||||
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()) });
|
||||
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}") });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1193,9 +1302,7 @@ 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<()> {
|
||||
@@ -1216,7 +1323,7 @@ fn spawn_pump(
|
||||
|
||||
let flush = |pending: &mut String, stream: Stream, started: &mut Option<Instant>| {
|
||||
if !pending.is_empty() {
|
||||
on_output(chunk(stream, std::mem::take(pending)));
|
||||
entry.emit_output(chunk(stream, std::mem::take(pending)));
|
||||
}
|
||||
*started = None;
|
||||
};
|
||||
@@ -1296,12 +1403,12 @@ fn spawn_pump(
|
||||
rest.push_str(&filter.finish());
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
on_output(chunk(stream, rest));
|
||||
entry.emit_output(chunk(stream, rest));
|
||||
}
|
||||
}
|
||||
|
||||
let (code, message) = describe_exit(status);
|
||||
on_output(OutputChunk::System { text: format!("\n{message}\n") });
|
||||
entry.emit_output(OutputChunk::System { text: format!("\n{message}\n") });
|
||||
entry.stdin.lock().take();
|
||||
if let Some(pty) = &entry.pty {
|
||||
pty.lock().take();
|
||||
@@ -1333,7 +1440,8 @@ fn spawn_pump(
|
||||
*entry.code.lock() = code;
|
||||
entry.exited.store(true, Ordering::Release);
|
||||
tracing::debug!(id = %entry.id, ?code, "run exited");
|
||||
sink.emit(IdeEvent::RunExited { run: entry.id, code });
|
||||
let target_sink = entry.sink.lock().clone();
|
||||
target_sink.emit(IdeEvent::RunExited { run: entry.id, code });
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! An in-process SSH server for tests (feature `testing`): password `dev` /
|
||||
//! `secret`, commands answered by a closure, SFTP served from a local
|
||||
//! `secret`, commands answered by a closure or an explicitly allowed process, 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,15 +10,34 @@ 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),
|
||||
@@ -37,7 +56,7 @@ pub async fn sshd(root: PathBuf, exec: ExecFn) -> u16 {
|
||||
#[derive(Clone)]
|
||||
struct Sshd {
|
||||
root: PathBuf,
|
||||
exec: ExecFn,
|
||||
exec: Exec,
|
||||
}
|
||||
|
||||
impl server::Server for Sshd {
|
||||
@@ -49,7 +68,7 @@ impl server::Server for Sshd {
|
||||
|
||||
struct Conn {
|
||||
root: PathBuf,
|
||||
exec: ExecFn,
|
||||
exec: Exec,
|
||||
channels: Arc<Mutex<HashMap<ChannelId, Channel<Msg>>>>,
|
||||
shells: std::collections::HashSet<ChannelId>,
|
||||
}
|
||||
@@ -99,7 +118,44 @@ impl server::Handler for Conn {
|
||||
data: &[u8],
|
||||
session: &mut Session,
|
||||
) -> Result<(), Self::Error> {
|
||||
let (out, code) = (self.exec)(&String::from_utf8_lossy(data));
|
||||
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);
|
||||
session.channel_success(channel)?;
|
||||
session.data(channel, out.into_bytes())?;
|
||||
session.exit_status_request(channel, code)?;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! 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};
|
||||
@@ -130,6 +131,26 @@ 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 {
|
||||
@@ -207,11 +228,18 @@ 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`).
|
||||
@@ -230,6 +258,9 @@ 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()
|
||||
@@ -237,15 +268,16 @@ 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.
|
||||
/// Emits `IdeEvent::TerminalExited` to `sink` (the starter's) only.
|
||||
/// Calls `on_exit` if supplied and emits `IdeEvent::TerminalExited` to the current sink.
|
||||
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, false)
|
||||
self.spawn_impl(options, key, sink, on_output, on_exit, false)
|
||||
}
|
||||
|
||||
/// Runs an approved absolute executable with exact arguments and cwd.
|
||||
@@ -256,6 +288,7 @@ 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()
|
||||
@@ -263,7 +296,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, true)
|
||||
self.spawn_impl(options, key, sink, on_output, on_exit, true)
|
||||
}
|
||||
|
||||
fn spawn_impl(
|
||||
@@ -272,6 +305,7 @@ 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);
|
||||
@@ -351,10 +385,17 @@ 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),
|
||||
@@ -363,7 +404,7 @@ impl TerminalManager {
|
||||
|
||||
let (tx, rx) = mpsc::channel::<Msg>();
|
||||
let budget = ByteBudget::default();
|
||||
let out = OutputSender { tx: tx.clone(), budget: budget.clone() };
|
||||
let out = OutputSender { tx, budget: budget.clone() };
|
||||
let spawned = spawn_reader(
|
||||
id,
|
||||
reader,
|
||||
@@ -375,15 +416,16 @@ impl TerminalManager {
|
||||
.and_then(|_| {
|
||||
spawn_pump(
|
||||
id,
|
||||
OutputReceiver { rx, budget },
|
||||
on_output,
|
||||
OutputReceiver { rx, budget: budget.clone() },
|
||||
output,
|
||||
exited,
|
||||
self.sessions.clone(),
|
||||
sink,
|
||||
Instant::now(),
|
||||
on_exit,
|
||||
)
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
budget.close();
|
||||
if let Some(s) = self.sessions.lock().remove(&id) {
|
||||
terminate(&s);
|
||||
}
|
||||
@@ -411,18 +453,23 @@ 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 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()) {
|
||||
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) {
|
||||
budget.close();
|
||||
if let Some(s) = self.sessions.lock().remove(&id) {
|
||||
terminate(&s);
|
||||
@@ -500,6 +547,85 @@ 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)?;
|
||||
@@ -711,25 +837,44 @@ 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,
|
||||
output: OutputReceiver,
|
||||
on_output: Box<dyn Fn(String) + Send>,
|
||||
receiver: OutputReceiver,
|
||||
output: Arc<Mutex<OutputState>>,
|
||||
exited: Arc<AtomicBool>,
|
||||
sessions: Sessions,
|
||||
sink: SharedSink,
|
||||
started: Instant,
|
||||
sink: Arc<Mutex<SharedSink>>,
|
||||
on_exit: Option<TerminalExitHook>,
|
||||
) -> 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 on_output = move |text: String| {
|
||||
let emit_output = |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");
|
||||
}
|
||||
on_output(text)
|
||||
let mut out = output.lock();
|
||||
out.scrollback.push(&text);
|
||||
(out.on_output)(text);
|
||||
};
|
||||
let mut decoder = Utf8Decoder::new();
|
||||
let mut pending = String::new();
|
||||
@@ -739,7 +884,7 @@ fn spawn_pump(
|
||||
|
||||
let flush = |pending: &mut String, batch_started: &mut Option<Instant>| {
|
||||
if !pending.is_empty() {
|
||||
on_output(std::mem::take(pending));
|
||||
emit_output(std::mem::take(pending));
|
||||
}
|
||||
*batch_started = None;
|
||||
};
|
||||
@@ -753,10 +898,10 @@ fn spawn_pump(
|
||||
(Some(a), None) | (None, Some(a)) => a,
|
||||
(None, None) => Duration::from_secs(3600),
|
||||
};
|
||||
match output.rx.recv_timeout(wait) {
|
||||
match receiver.rx.recv_timeout(wait) {
|
||||
Ok(Msg::Data(bytes)) => {
|
||||
// The pump owns these bytes now; wake any producer waiting on the cap.
|
||||
output.budget.release(bytes.len());
|
||||
receiver.budget.release(bytes.len());
|
||||
decoder.decode_into(&bytes, &mut pending);
|
||||
if !pending.is_empty() && batch_started.is_none() {
|
||||
batch_started = Some(Instant::now());
|
||||
@@ -783,11 +928,15 @@ fn spawn_pump(
|
||||
pending.push_str(&decoder.finish());
|
||||
flush(&mut pending, &mut batch_started);
|
||||
exited.store(true, Ordering::Release);
|
||||
output.budget.close();
|
||||
receiver.budget.close();
|
||||
sessions.lock().remove(&id);
|
||||
let code = exit.flatten();
|
||||
tracing::debug!(%id, ?code, "terminal exited");
|
||||
sink.emit(IdeEvent::TerminalExited { terminal: id, code });
|
||||
let target_sink = sink.lock().clone();
|
||||
if let Some(on_exit) = on_exit {
|
||||
on_exit(code);
|
||||
}
|
||||
target_sink.emit(IdeEvent::TerminalExited { terminal: id, code });
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1126,6 +1275,7 @@ mod tests {
|
||||
Box::new(move |s| {
|
||||
let _ = tx.send(s);
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.expect("spawn");
|
||||
(info, rx)
|
||||
@@ -1192,14 +1342,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(|_| {})).is_err());
|
||||
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).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(|_| {})).is_err());
|
||||
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).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(|_| {})).is_err());
|
||||
assert!(h.manager.spawn_program(options, "test".into(), h.sink.clone(), Box::new(|_| {}), None).is_err());
|
||||
assert!(h.manager.list().is_empty());
|
||||
}
|
||||
|
||||
@@ -1329,7 +1479,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(|_| {})).expect("spawn");
|
||||
let theirs = h.manager.spawn(sh("exit 2"), "other".into(), other_sink, Box::new(|_| {}), None).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:?}"),
|
||||
@@ -1342,6 +1492,34 @@ 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");
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
//! 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$ ");
|
||||
}
|
||||
}
|
||||
@@ -933,6 +933,8 @@ mod ignore;
|
||||
mod index_writes;
|
||||
mod log_index;
|
||||
mod manage;
|
||||
mod metadata_watch;
|
||||
pub use metadata_watch::MetadataWatch;
|
||||
mod ops;
|
||||
mod patch;
|
||||
mod preserve;
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -668,6 +668,44 @@ 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;
|
||||
@@ -941,6 +979,10 @@ 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();
|
||||
|
||||
@@ -66,8 +66,9 @@ 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]; 6] = [
|
||||
const USER_ONLY: &[&[&str]] = &[
|
||||
&["mcpServer"],
|
||||
&["remoteDevelopment"],
|
||||
&["editor", "customSchemes"],
|
||||
&["agentSecurity", "allowedCommands"],
|
||||
&["agents", "defaults"],
|
||||
@@ -91,7 +92,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)
|
||||
{
|
||||
|
||||
@@ -28,6 +28,7 @@ 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` |
|
||||
@@ -38,10 +39,11 @@ flowchart LR
|
||||
## The server
|
||||
|
||||
```text
|
||||
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
|
||||
openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
|
||||
```
|
||||
|
||||
- `--stdio` serves one desktop client over stdin/stdout. stdout carries the protocol, so logs go to stderr (filter with `OPENIDEA_LOG`).
|
||||
- `--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`).
|
||||
- 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.
|
||||
|
||||
@@ -9,9 +9,27 @@ 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, 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.
|
||||
[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.
|
||||
|
||||
## Supported hosts
|
||||
|
||||
@@ -35,8 +53,10 @@ 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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Files on the host
|
||||
|
||||
@@ -45,6 +65,12 @@ new server next to the old one.
|
||||
| `~/.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.
|
||||
@@ -95,7 +121,8 @@ 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. |
|
||||
| `--stdio` | Serve one desktop client over stdin / stdout. Logs go to stderr. |
|
||||
| `--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. |
|
||||
| `--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. |
|
||||
|
||||
|
||||
@@ -96,7 +96,8 @@ 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.
|
||||
- **File › Disconnect from Remote Host** closes the project and ends the connection.
|
||||
- **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.
|
||||
|
||||
### Forward ports
|
||||
|
||||
|
||||
@@ -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). After a restart each tab starts a **new** session in its directory. Scrollback and running commands are not restored.
|
||||
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.
|
||||
|
||||
## Keys in the terminal
|
||||
|
||||
|
||||
@@ -25,23 +25,25 @@ flowchart LR
|
||||
S1 --> H["ide-host: Host<br/>项目、LSP、索引、git、<br/>终端、运行、调试器、插件"]
|
||||
```
|
||||
|
||||
| 部分 | 位置 |
|
||||
| ------------------------- | ------------------------------------------------------------------------- |
|
||||
| 服务端二进制 | `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/` |
|
||||
| 部分 | 位置 |
|
||||
| ------------------------- | -------------------------------------------------------------------------- |
|
||||
| 服务端二进制 | `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/` |
|
||||
|
||||
## 服务端
|
||||
|
||||
```text
|
||||
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
|
||||
openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
|
||||
```
|
||||
|
||||
- `--stdio` 通过 stdin/stdout 为一个桌面客户端提供服务。stdout 承载协议,所以日志写到 stderr(用 `OPENIDEA_LOG` 过滤)。
|
||||
- `--attach <project-path>` 将 stdin/stdout 桥接到独立守护进程,套接字权限为 `0600`,目录权限为 `0700`。套接字键不随构建变化;连接前会核对构建,只有在没有连接的窗口、活动任务或未保存的文档时才替换旧后端。空闲退出或主动关闭时会保留套接字,直到清理完成。
|
||||
- `--stdio` 直接通过 stdin/stdout 为单个桌面客户端提供服务并在断开时退出。stdout 承载协议,所以日志写到 stderr(用 `OPENIDEA_LOG` 过滤)。
|
||||
- 状态保存在 `OPENIDEA_SERVER_HOME`(默认 `~/.openidea`)下的 `config/` 和 `data/` 中。可以在 `config/languages/` 里追加语言定义。
|
||||
- SSH exec channel 只给最小的环境变量,所以服务端每次启动都会读取登录 shell 的环境,并把 IDE 托管的工具目录加入 `PATH`。
|
||||
- `--version` 打印应用版本和协议版本。
|
||||
|
||||
@@ -7,8 +7,19 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
|
||||
承担桌面端在本地时要做的工作:文件系统、索引、语言服务器、终端、运行、调试、构建工具和 Git。桌面窗口只负责显示界面,并把命令发给它。
|
||||
|
||||
你不需要手动启动它。打开远程项目时([SSH](/zh/guide/remote/ssh)、[容器](/zh/guide/remote/containers)),桌面端会按需在主机上安装服务端,
|
||||
通过 SSH 连接(或 `wsl.exe` / `docker exec`)以 `openidea-server --stdio` 启动,并经由标准输入输出与它通信。一个服务端进程只服务一个桌面窗口,
|
||||
窗口断开后即退出。
|
||||
通过 SSH 连接(或 `wsl.exe` / `docker exec`)运行 `openidea-server --attach <project>`,连接到按项目隔离的后台守护进程(经由私有 Unix 套接字),
|
||||
并经由标准输入输出与它通信。
|
||||
|
||||
## 关闭窗口或停止远程后端
|
||||
|
||||
- 关闭窗口时默认选择**保持后端运行**。窗口断开连接,但终端、运行配置、索引和智能体任务不受影响。重新打开同一项目即可接回。网络中断也不会停止后端。
|
||||
- 关闭时选择**停止后端**,或使用**文件 › 停止远程后端**,会关闭 IDE 后端及其任务。正在运行且配置了停止命令的运行配置会先执行该命令,例如 `docker compose down`。
|
||||
停止开发容器里的 IDE 后端不会关闭开发容器本身。
|
||||
- 默认情况下,没有窗口连接,且没有活动的终端、运行配置、调试会话或智能体任务时,后端闲置**三小时**后自动退出。
|
||||
在已连接的窗口中,打开**设置 › 工具 › 远程开发 › 空闲时停止后端**。选择预设时长、通过**自定义…**输入分钟、小时或天数,或选择**从不**让空闲项目保持运行。
|
||||
点击**应用**后,设置保存在远程主机的用户设置中;后端下次进入空闲时即生效,无需重启。选择**从不**后仍可手动**停止后端**;从未打开项目的后端仍会自动退出。
|
||||
- 关闭窗口的对话框会说明在当前主机上**保持后端运行**的效果。启动环境中的 `OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS` 如为正整数秒数,会优先于所有用户选择(包括**从不**),并在设置页以只读形式显示。重新连接会重置计时。
|
||||
请在项目闲置前保存修改:网络中断后,未保存的文档仅保留在后端内存里。
|
||||
|
||||
## 支持的主机
|
||||
|
||||
@@ -30,7 +41,9 @@ description: "运行在远程主机上的 IDE 后端:桌面端如何安装和
|
||||
校验 SHA-256 后缓存到本机本地数据目录的 `server/<version>/<os>-<arch>/` 下。
|
||||
3. 把二进制上传到主机,并删除同一版本的旧构建。
|
||||
|
||||
桌面端和服务端始终是同一版本。升级 OpenIDEA 后,下一次连接会在旧版本旁边安装新的服务端。
|
||||
升级 OpenIDEA 后,若旧后端没有窗口连接、活动任务或未保存的文档,下一次连接会替换该项目的旧后端。
|
||||
否则,OpenIDEA 会提示你用旧版本结束任务或保存文档,再停止旧后端并升级。同一版本的两个窗口可以轮流连接同一项目;
|
||||
原窗口会提示会话已被另一个窗口接管,不会自动重新连接。
|
||||
|
||||
## 主机上的文件
|
||||
|
||||
@@ -39,6 +52,11 @@ 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 会在需要时重新安装工具。
|
||||
|
||||
@@ -82,7 +100,8 @@ cargo build --release -p ide-host --bin openidea-server
|
||||
| 参数 | 含义 |
|
||||
| ------------------------------- | -------------------------------------------------------------------------------- |
|
||||
| `--version` | 输出服务端版本和协议版本后退出。 |
|
||||
| `--stdio` | 通过标准输入输出服务一个桌面客户端,日志写到 stderr。 |
|
||||
| `--attach <project>` | 启动或连接到该项目的持久化后台守护进程,并将标准输入输出桥接到其 Unix 套接字。 |
|
||||
| `--stdio` | 直接通过标准输入输出服务单个桌面客户端并在断开时退出,日志写到 stderr。 |
|
||||
| `--mcp-stdio [--project <dir>]` | 将标准输入输出上的 MCP 消息转发给当前主机正在运行的 `openidea-server` MCP 服务。 |
|
||||
| `--connect <host> <port>` | 通过标准输入输出中转一个到 `<host>:<port>` 的 TCP 连接,用于开发容器的端口转发。 |
|
||||
|
||||
|
||||
@@ -74,7 +74,8 @@ SSH 代理使用 `IdentityAgent` 指定的那个,未指定时使用登录 shel
|
||||
- OpenIDEA 安装的语言服务器、调试器等工具都装在远程主机的 `~/.openidea/data` 下。
|
||||
- 快捷键、外观、编辑器字体和配色方案保留在本机;项目和工具相关的设置保存在主机上。
|
||||
- 你的代码插件会同步到服务端,在项目所在的机器上运行。
|
||||
- **文件 › 断开与远程主机的连接**会关闭项目并断开连接。
|
||||
- 关闭窗口时选择**保持后端运行**,或使用**文件 › 断开与远程主机的连接**,会保留远程 IDE 后端及其任务。重新打开项目即可接回。
|
||||
- 关闭窗口时选择**停止后端**,或使用**文件 › 停止远程后端**,会关闭后端及其任务。有关空闲超时和手动清理,请参阅[关闭窗口或停止远程后端](/zh/guide/remote/server#关闭窗口或停止远程后端)。
|
||||
|
||||
### 端口转发
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
|
||||
|
||||
### 重启 IDE 之后
|
||||
|
||||
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令。
|
||||
OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称、使用的 Shell 以及拆分布局(最多 32 个标签页)。对于本地项目,重启后每个标签页都会在原目录**重新**启动一个会话,不会恢复滚动缓冲区和正在运行的命令;对于远程项目,关闭并重新打开窗口会重新连接到 `openidea-server` 上仍在运行的终端会话,并恢复最近的终端输出与正在执行的命令。
|
||||
|
||||
## 终端中的按键
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ 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 {
|
||||
@@ -71,8 +72,12 @@ export async function stubDesktop(page: Page) {
|
||||
callbacks.get(id)?.({ index, message });
|
||||
},
|
||||
emit(event) {
|
||||
for (const l of listeners)
|
||||
if (l.event === "ide://event") callbacks.get(l.handler)?.({ event: l.event, id: 0, payload: 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 });
|
||||
}
|
||||
},
|
||||
};
|
||||
window.__ipc = ipc;
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
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();
|
||||
});
|
||||
@@ -5,8 +5,10 @@ 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({
|
||||
@@ -14,9 +16,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");
|
||||
|
||||
@@ -252,17 +252,10 @@ 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(session), None)
|
||||
(Some(c.snapshot()), None)
|
||||
} else {
|
||||
let project = state.project(owner).ok().filter(|p| !p.light).map(|p| ide_host::ops::project::info(&p));
|
||||
(None, project)
|
||||
|
||||
@@ -249,6 +249,7 @@ 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"),
|
||||
|
||||
@@ -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(), "--stdio".to_owned()]);
|
||||
args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]);
|
||||
args
|
||||
}
|
||||
|
||||
@@ -253,7 +253,8 @@ mod tests {
|
||||
"OPENIDEA_LIFECYCLE_DONE=1",
|
||||
ID,
|
||||
"/home/vscode/.openidea/server/1/ab/openidea-server",
|
||||
"--stdio",
|
||||
"--attach",
|
||||
"/workspaces/my app",
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -332,10 +333,12 @@ 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 root = base.join("devcontainer");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let workspace = tempfile::Builder::new().prefix("openidea-devcontainer-").tempdir_in(base).unwrap();
|
||||
let root = workspace.path();
|
||||
std::fs::create_dir_all(root.join(".devcontainer")).unwrap();
|
||||
std::fs::write(
|
||||
root.join(".devcontainer/devcontainer.json"),
|
||||
@@ -350,10 +353,19 @@ 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()));
|
||||
assert_eq!(up.folder, "/workspaces/devcontainer");
|
||||
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.user, "root");
|
||||
let found = probe(&docker, &up, "0.0.0-test").await.unwrap();
|
||||
assert_eq!(platform_os(&found.uname), "linux");
|
||||
@@ -374,7 +386,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"], "/workspaces/devcontainer");
|
||||
assert_eq!(project["root"], up.folder);
|
||||
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)
|
||||
@@ -410,10 +422,49 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
|
||||
}
|
||||
assert_eq!(reply, "from the container\n");
|
||||
drop(tunnel);
|
||||
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();
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
fn platform_os(uname: &str) -> String {
|
||||
|
||||
@@ -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, ServerInfo};
|
||||
use ide_host::rpc::{ChannelMessage, EventMessage, Invoke, RemoteIdlePolicy, ServerInfo};
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -16,6 +16,8 @@ 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};
|
||||
|
||||
@@ -55,12 +57,20 @@ 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,
|
||||
@@ -118,6 +128,18 @@ 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.
|
||||
@@ -336,6 +358,8 @@ 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,
|
||||
@@ -346,6 +370,7 @@ struct ClientHandler {
|
||||
window: String,
|
||||
channels: Channels,
|
||||
connection: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>>,
|
||||
taken_over: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Handler for ClientHandler {
|
||||
@@ -394,6 +419,10 @@ 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 =
|
||||
@@ -640,11 +669,13 @@ 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;
|
||||
@@ -654,17 +685,29 @@ 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!("{} --stdio", ide_ssh::shell::tilde_quote(&bin)))
|
||||
.exec_stream(&format!(
|
||||
"{} --attach {} 2>&1",
|
||||
ide_ssh::shell::tilde_quote(&bin),
|
||||
ide_ssh::shell::quote(attach_arg),
|
||||
))
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
|
||||
let (reader, writer) = tokio::io::split(stream);
|
||||
(Peer::connect(reader, writer, handler), Some(session), config.label(), config.label())
|
||||
let output = tail.clone();
|
||||
(
|
||||
Peer::connect_with_output(reader, writer, handler, move |line| output.push(line)),
|
||||
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 peer = crate::remote_wsl::spawn(distro, &bin, handler, &tail)?;
|
||||
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?;
|
||||
(peer, None, distro.clone(), format!("WSL: {distro}"))
|
||||
}
|
||||
RemoteTarget::DevContainer { folder, config } => {
|
||||
@@ -711,7 +754,8 @@ pub async fn remote_connect(
|
||||
path.trim().to_owned()
|
||||
};
|
||||
progress(RemoteStage::Opening, None);
|
||||
let call = Invoke { window: label.clone(), cmd: "open_project".into(), args: serde_json::json!({ "path": root }) };
|
||||
let call =
|
||||
Invoke { window: SERVER_WINDOW.into(), 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.
|
||||
@@ -722,6 +766,9 @@ 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(),
|
||||
@@ -754,16 +801,22 @@ pub async fn remote_connect(
|
||||
let app = window.app_handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
peer.closed().await;
|
||||
auth_plugins.forget_remote_loopbacks(&auth_window);
|
||||
let current = app.state::<AppState>().remote_dev.get(&auth_window);
|
||||
if current.is_none() {
|
||||
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)) {
|
||||
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() });
|
||||
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 });
|
||||
}
|
||||
}
|
||||
});
|
||||
let plugins = state.plugins.clone();
|
||||
@@ -774,16 +827,25 @@ 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, commands, project })
|
||||
Ok(RemoteProject {
|
||||
target,
|
||||
root,
|
||||
host,
|
||||
server_version: info.version,
|
||||
os: info.os,
|
||||
idle_policy: info.idle_policy,
|
||||
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: window.to_owned(),
|
||||
window: SERVER_WINDOW.to_owned(),
|
||||
cmd: SYNC_COMMAND.into(),
|
||||
args: serde_json::json!({ "languages": plugins.remote_languages() }),
|
||||
};
|
||||
@@ -803,12 +865,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: window.to_owned(),
|
||||
window: SERVER_WINDOW.to_owned(),
|
||||
cmd: SYNC_PACKAGES.into(),
|
||||
args: serde_json::json!({ "packages": packages, "files": files }),
|
||||
};
|
||||
@@ -854,6 +916,10 @@ 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.
|
||||
@@ -862,13 +928,7 @@ 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(RemoteSession {
|
||||
target: c.target.clone(),
|
||||
root: c.root.clone(),
|
||||
host: c.host.clone(),
|
||||
os: c.os.clone(),
|
||||
commands: c.commands.clone(),
|
||||
})
|
||||
Some(c.snapshot())
|
||||
}
|
||||
|
||||
/// This machine's trust decision for the window's remote project (see [`Connection::authorize`]).
|
||||
@@ -891,7 +951,16 @@ 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)
|
||||
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(())
|
||||
}
|
||||
|
||||
/// A port of the remote host reachable on this machine at `localhost:local_port`.
|
||||
@@ -1097,6 +1166,40 @@ 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.
|
||||
@@ -1150,7 +1253,7 @@ pub async fn remote_invoke(
|
||||
None
|
||||
};
|
||||
let web_url = cmd == "web_url";
|
||||
let call = Invoke { window: label, cmd, args };
|
||||
let call = Invoke { window: SERVER_WINDOW.into(), 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 {
|
||||
@@ -1406,6 +1509,9 @@ 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(),
|
||||
@@ -1506,6 +1612,7 @@ ide_command::desktop_domain!(
|
||||
remote_forwarded_ports,
|
||||
remote_import_local,
|
||||
remote_invoke,
|
||||
remote_stop_backend,
|
||||
remote_stop_forwarding,
|
||||
remote_trust_set,
|
||||
remote_trust_status,
|
||||
|
||||
@@ -182,15 +182,27 @@ impl 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)
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
|
||||
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();
|
||||
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();
|
||||
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}")))
|
||||
@@ -274,12 +286,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) = ("Debian-12", "/home/me/server");
|
||||
let (distro, bin, project) = ("Debian-12", "/home/me/server", "/home/me/proj");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let launcher = dir.path().join("fake-wsl");
|
||||
let script = format!(
|
||||
r#"#!/bin/sh
|
||||
[ "$*" = "-d {distro} --exec {bin} --stdio" ] || {{ echo "unexpected arguments: $*" >&2; exit 2; }}
|
||||
[ "$*" = "-d {distro} --exec {bin} --attach {project}" ] || {{ echo "unexpected arguments: $*" >&2; exit 2; }}
|
||||
printf '\377\376N\000o\000\r\000\n\000'
|
||||
while read -r line; do
|
||||
line=${{line%?}}
|
||||
@@ -293,7 +305,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, Arc::new(Silent), &tail).unwrap();
|
||||
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, 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());
|
||||
});
|
||||
@@ -302,7 +314,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);
|
||||
}
|
||||
}
|
||||
@@ -542,6 +542,7 @@ 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
|
||||
@@ -549,6 +550,7 @@ 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
|
||||
@@ -559,6 +561,7 @@ 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
|
||||
@@ -649,10 +652,12 @@ 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
|
||||
|
||||
+92
-8
@@ -1456,6 +1456,8 @@ 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"),
|
||||
@@ -1473,6 +1475,11 @@ 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 })),
|
||||
/**
|
||||
@@ -1486,6 +1493,11 @@ 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. */
|
||||
@@ -1514,6 +1526,11 @@ 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")),
|
||||
@@ -1853,6 +1870,11 @@ 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. */
|
||||
@@ -1863,6 +1885,8 @@ 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)
|
||||
@@ -7967,11 +7991,8 @@ 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 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 } |
|
||||
/** 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 } |
|
||||
/**
|
||||
* The project's direnv environment (`.envrc`) could not be loaded, or a file it is read
|
||||
* from changed and it can be reloaded.
|
||||
@@ -11719,6 +11740,12 @@ 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. */
|
||||
@@ -11738,6 +11765,11 @@ 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,
|
||||
@@ -11790,6 +11822,7 @@ 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,
|
||||
@@ -11802,18 +11835,34 @@ 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 = {
|
||||
export type RemoteSession = RemoteSession_Serialize | RemoteSession_Deserialize;
|
||||
|
||||
export type RemoteSession_Deserialize = {
|
||||
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 = {
|
||||
@@ -11992,6 +12041,23 @@ 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 = {
|
||||
@@ -12501,7 +12567,7 @@ export type SettingsWindowInit = SettingsWindowInit_Serialize | SettingsWindowIn
|
||||
|
||||
export type SettingsWindowInit_Deserialize = {
|
||||
launch: Launch_Deserialize | null,
|
||||
remote: RemoteSession | null,
|
||||
remote: RemoteSession_Deserialize | null,
|
||||
project: ProjectInfo_Deserialize | null,
|
||||
globalSettings: Settings_Deserialize,
|
||||
updates: boolean,
|
||||
@@ -12509,7 +12575,7 @@ export type SettingsWindowInit_Deserialize = {
|
||||
|
||||
export type SettingsWindowInit_Serialize = {
|
||||
launch: Launch_Serialize | null,
|
||||
remote: RemoteSession | null,
|
||||
remote: RemoteSession_Serialize | null,
|
||||
project: ProjectInfo_Serialize | null,
|
||||
globalSettings: Settings_Serialize,
|
||||
updates: boolean,
|
||||
@@ -12570,6 +12636,7 @@ export type Settings_Deserialize = {
|
||||
spelling?: SpellingSettings,
|
||||
/** Tools › SSH Configurations. */
|
||||
ssh?: SshSettings,
|
||||
remoteDevelopment?: RemoteDevelopmentSettings,
|
||||
/** Build, Execution, Deployment › Deployment. */
|
||||
deployment?: DeploymentSettings,
|
||||
/** Build, Execution, Deployment › Run Targets. */
|
||||
@@ -12646,6 +12713,7 @@ export type Settings_Serialize = {
|
||||
spelling: SpellingSettings,
|
||||
/** Tools › SSH Configurations. */
|
||||
ssh: SshSettings,
|
||||
remoteDevelopment: RemoteDevelopmentSettings,
|
||||
/** Build, Execution, Deployment › Deployment. */
|
||||
deployment: DeploymentSettings,
|
||||
/** Build, Execution, Deployment › Run Targets. */
|
||||
@@ -13311,6 +13379,12 @@ 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,
|
||||
@@ -13340,6 +13414,16 @@ 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. */
|
||||
|
||||
@@ -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 } from "@/platform/remote";
|
||||
import { isRemoteWindow, projectLocation } 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 prevRoot = useProject.getState().project?.root ?? null;
|
||||
let prevScope = projectLocation(useProject.getState().project?.root);
|
||||
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 root = s.project?.root ?? null;
|
||||
const scope = projectLocation(s.project?.root);
|
||||
// Entering or leaving LightEdit replaces the backend's documents too.
|
||||
if (root !== prevRoot || s.lightEdit !== prevLight || (s.opening && s.project !== previous.project)) {
|
||||
prevRoot = root;
|
||||
if (scope !== prevScope || s.lightEdit !== prevLight || (s.opening && s.project !== previous.project)) {
|
||||
prevScope = scope;
|
||||
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 root || s.lightEdit ? Object.values(cs.panes) : []) {
|
||||
for (const pane of scope || 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 (root) return this.restoreSession(root);
|
||||
if (scope) return this.restoreSession(scope);
|
||||
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 (prevRoot) this.projectTransition = this.restoreSession(prevRoot);
|
||||
if (prevScope) this.projectTransition = this.restoreSession(prevScope);
|
||||
if (this.manager.backend.onFsChanged)
|
||||
this.disposers.push(this.manager.backend.onFsChanged((e) => this.onFilesRemoved(e.removed)));
|
||||
if (this.manager.backend.onDiskConflict)
|
||||
@@ -671,7 +671,8 @@ export class EditorController implements SlotHost {
|
||||
|
||||
private openSessionKey(): string | null {
|
||||
const s = useProject.getState();
|
||||
if (s.project?.root) return s.project.root;
|
||||
const scope = projectLocation(s.project?.root);
|
||||
if (scope) return scope;
|
||||
if (s.lightEdit) return LIGHT_EDIT_SESSION;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ 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({
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* 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";
|
||||
|
||||
@@ -198,8 +199,12 @@ export function restoreTabsState(session: EditorSession, fileKey: (path: string)
|
||||
|
||||
export function loadSession(root: string): EditorSession | null {
|
||||
try {
|
||||
// Sessions saved under the backslash spelling of a Windows root are picked up too.
|
||||
const raw = localStorage.getItem(STORAGE_PREFIX + root) ?? legacyWindowsSession(root);
|
||||
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);
|
||||
return raw ? parseSession(JSON.parse(raw)) : null;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -44,9 +44,10 @@
|
||||
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. */
|
||||
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. */
|
||||
.field :global(.cm-content) {
|
||||
min-height: 44px;
|
||||
min-height: var(--composer-min-height, 44px);
|
||||
padding: 10px 12px 2px;
|
||||
caret-color: var(--fg-strong);
|
||||
white-space: pre-wrap;
|
||||
|
||||
@@ -34,8 +34,8 @@
|
||||
}
|
||||
|
||||
/* A box to write in, not a search bar: room for a few lines before it grows. */
|
||||
.composer :global(.cm-content) {
|
||||
min-height: calc(4.5em + 12px);
|
||||
.composer {
|
||||
--composer-min-height: calc(4.5em + 12px);
|
||||
}
|
||||
|
||||
/* Under the box: one quiet group, the project, checkout and branch side by side. */
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
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"…). */
|
||||
@@ -58,7 +59,9 @@ export function parseOrganize(saved: unknown): TaskOrganize {
|
||||
export function loadOrganize(root: string | null | undefined): TaskOrganize {
|
||||
if (!root) return EMPTY_ORGANIZE;
|
||||
try {
|
||||
const raw = globalThis.localStorage?.getItem(key(root));
|
||||
const legacy = parseRemoteLocation(root)?.path;
|
||||
const raw =
|
||||
globalThis.localStorage?.getItem(key(root)) ?? (legacy ? globalThis.localStorage?.getItem(key(legacy)) : null);
|
||||
return raw == null ? EMPTY_ORGANIZE : parseOrganize(JSON.parse(raw));
|
||||
} catch {
|
||||
return EMPTY_ORGANIZE;
|
||||
|
||||
@@ -29,6 +29,7 @@ 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";
|
||||
@@ -554,7 +555,7 @@ export async function connect(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (gen !== generation) return;
|
||||
const organizeRoot = useProject.getState().project?.root ?? null;
|
||||
const organizeRoot = projectLocation(useProject.getState().project?.root);
|
||||
useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
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>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -29,6 +30,7 @@ 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);
|
||||
@@ -37,9 +39,11 @@ 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);
|
||||
@@ -57,6 +61,7 @@ afterEach(() => {
|
||||
uninstall?.();
|
||||
uninstall = undefined;
|
||||
native.close = undefined;
|
||||
disableRemote();
|
||||
useProject.setState(initialProject, true);
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
@@ -145,6 +150,28 @@ 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
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Window close / quit flow.
|
||||
*
|
||||
* Closing a window (traffic light, Quit closing every window) runs
|
||||
* `decideClose`: confirm exit when this is the last window and
|
||||
* the remote backend choice, if connected, then `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,9 +12,11 @@
|
||||
* `general.closeWithoutWelcome` is on, in which case it closes. When
|
||||
* `general.closeTabsWithWindow` is on, that close drops the saved editor tabs.
|
||||
*/
|
||||
import { IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { createElement } from "react";
|
||||
import { call, IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { t, tx } from "@/platform/i18n";
|
||||
import { closeProject, provideLeaveProjectGuard, useProject } from "@/platform/project";
|
||||
import { isRemoteWindow, shutdownRemoteBackend, useRemote } from "@/platform/remote";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import {
|
||||
maybeEditorService,
|
||||
@@ -24,14 +26,17 @@ 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 new Set([...dirtyDocs, ...(maybeEditorService()?.dirtyDocumentIds?.() ?? [])]).size;
|
||||
return dirtyDocumentIds().size;
|
||||
}
|
||||
|
||||
export function confirmExitEnabled(settings: Settings | null | undefined): boolean {
|
||||
@@ -83,6 +88,8 @@ 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. */
|
||||
@@ -134,8 +141,10 @@ 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();
|
||||
else return false;
|
||||
else if (r.button === "discard") {
|
||||
await session?.discard();
|
||||
await deps.discardChanges?.();
|
||||
} 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.
|
||||
@@ -238,6 +247,11 @@ 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;
|
||||
@@ -245,53 +259,68 @@ 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 (ctx.quitting) deps = raisingBeforeAsk(deps);
|
||||
if (!(await closeDocumentWindows())) {
|
||||
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
|
||||
return false;
|
||||
}
|
||||
if (quitting) deps = raisingBeforeAsk(deps);
|
||||
if (!(await closeDocumentWindows())) return await cancel();
|
||||
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 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";
|
||||
}
|
||||
const confirmTerminate = workflowSettings().run.confirmTerminate;
|
||||
const confirmTerminate = !remote.session && workflowSettings().run.confirmTerminate;
|
||||
const ok = await decideClose(
|
||||
{
|
||||
quitting: ctx.quitting,
|
||||
quitting,
|
||||
windows: ctx.windows,
|
||||
confirmExit: confirmExitEnabled(s.settings),
|
||||
confirmExit: !welcome && confirmExitEnabled(s.settings),
|
||||
confirmTerminate,
|
||||
processes: confirmTerminate ? await processNames(deps) : [],
|
||||
dirty: dirtyCount(),
|
||||
project: s.project?.displayName || s.project?.name || null,
|
||||
},
|
||||
savingUntitled(deps),
|
||||
savingUntitled({
|
||||
...deps,
|
||||
discardChanges: remote.session && !remote.lost && !stop ? discardRemoteChanges : undefined,
|
||||
}),
|
||||
);
|
||||
if (!ok) {
|
||||
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
|
||||
return false;
|
||||
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();
|
||||
}
|
||||
// The window is closing. Drop the tabs now so pagehide cannot write them back.
|
||||
forgetTabs();
|
||||
return true;
|
||||
} catch (e) {
|
||||
undoForget();
|
||||
maybeEditorService()?.cancelClose?.();
|
||||
void commands.windowGroupCancelClose().catch(() => {});
|
||||
void cancel().catch(() => {});
|
||||
deps.onSaveFailed(e);
|
||||
return false;
|
||||
} finally {
|
||||
@@ -299,6 +328,11 @@ 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 {
|
||||
@@ -321,7 +355,7 @@ export async function confirmLeave(
|
||||
keepUntitled = true,
|
||||
): Promise<boolean> {
|
||||
if (!(await closeDocumentWindows())) return false;
|
||||
const confirmTerminate = workflowSettings().run.confirmTerminate;
|
||||
const confirmTerminate = !isRemoteWindow() && 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?.() ?? []) : []);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
|
||||
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { registerActions, type ActionContext } from "@/platform/actions";
|
||||
import { activeCellGrid } from "./cellActions";
|
||||
import {
|
||||
@@ -81,21 +81,58 @@ function tableTarget(arg: unknown): TableCommandTarget {
|
||||
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
onIdeEvent("dbSourcesChanged", () => {
|
||||
void loadSources();
|
||||
}),
|
||||
registerToolWindow({
|
||||
/** 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(),
|
||||
registerServiceView({
|
||||
id: RESULTS_VIEW,
|
||||
title: "Database",
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -76,6 +76,16 @@ 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"));
|
||||
|
||||
@@ -114,6 +114,8 @@ 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") } : {}),
|
||||
|
||||
@@ -30,6 +30,7 @@ function add(pluginId: string, decl: Partial<WindowView> & Pick<WindowView, "id"
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useContextKeys.setState({}, true);
|
||||
show.mockClear();
|
||||
provideToolWindowService({ show } as never);
|
||||
@@ -118,6 +119,26 @@ 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();
|
||||
});
|
||||
|
||||
@@ -587,6 +587,7 @@ 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,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
useToolWindowShown,
|
||||
type ToolWindowAnchor,
|
||||
} from "@/workbench/contributions";
|
||||
import { pluginToolWindowId, viewKey } from "./viewStore";
|
||||
import { currentViewLocation, pluginToolWindowId, useViewLocation, viewKey } from "./viewStore";
|
||||
import styles from "./PluginView.module.css";
|
||||
|
||||
export interface WindowView {
|
||||
@@ -47,21 +47,47 @@ 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 active = members.find((m) => m.decl.id === selected) ?? members[0];
|
||||
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 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]);
|
||||
}, [members, activeId, location]);
|
||||
if (!active) return null;
|
||||
return (
|
||||
<VerbatimTextContext.Provider value={true}>
|
||||
@@ -71,7 +97,10 @@ 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={(id) => group.state.setState({ selected: id })}
|
||||
onSelect={(viewId) => {
|
||||
writeSelectedView(id, viewId, location);
|
||||
group.state.setState({ selected: viewId });
|
||||
}}
|
||||
/>
|
||||
{members
|
||||
.filter((m) => visited.has(m.decl.id) || m.decl.id === activeId)
|
||||
@@ -105,7 +134,7 @@ function refresh(id: string, group: WindowGroup) {
|
||||
const selected = group.state.getState().selected;
|
||||
group.state.setState({
|
||||
members,
|
||||
selected: selected ?? members[0]?.decl.id ?? null,
|
||||
selected: selected && members.some((m) => m.decl.id === selected) ? selected : null,
|
||||
});
|
||||
const secondary = first?.decl.secondary === true;
|
||||
const signature =
|
||||
@@ -179,6 +208,7 @@ 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);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ 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,
|
||||
@@ -393,7 +394,11 @@ 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 persisted = mode === "project" || mode === "unity" ? readJson<string[]>(expandedKey(root)) : null;
|
||||
const scope = projectLocation(root) ?? root;
|
||||
const persisted =
|
||||
mode === "project" || mode === "unity"
|
||||
? (readJson<string[]>(expandedKey(scope)) ?? (scope !== root ? readJson<string[]>(expandedKey(root)) : null))
|
||||
: null;
|
||||
if (persisted) return new Set(persisted);
|
||||
return new Set(members ?? [root]);
|
||||
}
|
||||
@@ -404,7 +409,7 @@ function persistExpanded() {
|
||||
persistTimer = setTimeout(() => {
|
||||
const { root, expanded, mode } = get();
|
||||
if (root && (mode === "project" || mode === "unity"))
|
||||
writeJson(expandedKey(root), [...expanded].slice(0, MAX_PERSISTED));
|
||||
writeJson(expandedKey(projectLocation(root) ?? root), [...expanded].slice(0, MAX_PERSISTED));
|
||||
}, 300);
|
||||
}
|
||||
|
||||
|
||||
@@ -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, Spinner } from "@/ui";
|
||||
import { BarButton, Icon, showContextMenu, Spinner } from "@/ui";
|
||||
import styles from "./RemoteDev.module.css";
|
||||
|
||||
const BADGE: Record<RemoteSession["target"]["kind"], string> = {
|
||||
@@ -19,6 +19,7 @@ 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);
|
||||
@@ -28,7 +29,9 @@ export function RemoteStatus() {
|
||||
tooltip={
|
||||
reconnecting
|
||||
? tx`Reconnecting to ${session.host}…`
|
||||
: tx`Lost the connection to ${session.host}. Click to reconnect.`
|
||||
: takenOver
|
||||
? tx("Another window took over this remote session")
|
||||
: tx`Lost the connection to ${session.host}. Click to reconnect.`
|
||||
}
|
||||
aria-label={tx`${label} (disconnected)`}
|
||||
disabled={reconnecting}
|
||||
@@ -45,6 +48,16 @@ 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>
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
* to it (platform/remote.ts).
|
||||
*/
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { disconnectRemote, useRemote } from "@/platform/remote";
|
||||
import { disconnectRemote, stopRemoteBackend, 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";
|
||||
@@ -101,6 +103,35 @@ 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",
|
||||
|
||||
@@ -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 }) => void>());
|
||||
const listeners = vi.hoisted(() => new Map<string, (event: { host: string; takenOver: boolean }) => 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 }) => void) => {
|
||||
onIdeEvent: (type: string, handler: (event: { host: string; takenOver: boolean }) => 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 { useRemote } from "@/platform/remote";
|
||||
import { enableRemote, 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, reconnecting: false });
|
||||
useRemote.setState({ session, lost: null, takenOver: false, reconnecting: false });
|
||||
uninstall = installReconnect(async (ms) => {
|
||||
waits.push(ms);
|
||||
});
|
||||
@@ -54,7 +54,7 @@ afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const lose = () => listeners.get("remoteConnectionLost")!({ host: "box" });
|
||||
const lose = (takenOver = false) => listeners.get("remoteConnectionLost")!({ host: "box", takenOver });
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
it("marks the window lost and reconnects in the background", async () => {
|
||||
@@ -68,6 +68,39 @@ 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();
|
||||
|
||||
@@ -18,27 +18,36 @@ 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) {
|
||||
function notifyLost(host: string, error?: unknown, takenOver = false) {
|
||||
notifications().notify({
|
||||
key: KEY,
|
||||
group: "remote",
|
||||
level: "error",
|
||||
title: tx`Lost the connection to ${host}`,
|
||||
body: error === undefined ? undefined : errorText(error),
|
||||
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,
|
||||
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 } = useRemote.getState();
|
||||
const { lost, reconnecting, takenOver } = useRemote.getState();
|
||||
if (!lost || reconnecting) return;
|
||||
const count = unsaved();
|
||||
if (
|
||||
count > 0 &&
|
||||
(takenOver || count > 0) &&
|
||||
!(await confirm({
|
||||
title: tx("Reconnect to Remote Host"),
|
||||
message: tx`Reconnecting opens the project again. Unsaved changes in ${count} files can't be saved to ${lost} and will be lost.`,
|
||||
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.`,
|
||||
ok: tx("Reconnect"),
|
||||
icon: "warning",
|
||||
}))
|
||||
@@ -49,7 +58,7 @@ export async function reconnectNow(): Promise<void> {
|
||||
try {
|
||||
await reconnectRemote();
|
||||
} catch (e) {
|
||||
notifyLost(lost, e);
|
||||
notifyLost(lost, e, takenOver);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,13 +85,19 @@ export function installReconnect(
|
||||
wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
||||
): () => void {
|
||||
const offEvent = onIdeEvent("remoteConnectionLost", (e) => {
|
||||
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 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);
|
||||
});
|
||||
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();
|
||||
|
||||
@@ -7,6 +7,7 @@ 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";
|
||||
@@ -912,12 +913,18 @@ export function activate(): () => void {
|
||||
if (s.sessions !== prev.sessions) trimAgentArchive();
|
||||
}),
|
||||
onWorkflowSettingsChange(() => agentRunSettings(), trimAgentArchive),
|
||||
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();
|
||||
}),
|
||||
(() => {
|
||||
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();
|
||||
});
|
||||
})(),
|
||||
];
|
||||
|
||||
setBeforeLaunchRunner(runBeforeLaunch);
|
||||
|
||||
@@ -31,6 +31,7 @@ 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";
|
||||
@@ -280,11 +281,73 @@ 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) => {
|
||||
@@ -1751,9 +1814,9 @@ export function runningSessions(): RunSession[] {
|
||||
return useRun.getState().sessions.filter(isLive);
|
||||
}
|
||||
|
||||
/** Stops everything and forgets sessions (project closed). */
|
||||
export function resetRuns() {
|
||||
for (const s of runningSessions()) void stopSession(s.id);
|
||||
/** 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);
|
||||
for (const rt of runtimes.values()) cancelFlush(rt);
|
||||
runtimes.clear();
|
||||
pendingExits.clear();
|
||||
|
||||
@@ -218,6 +218,7 @@ 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,
|
||||
|
||||
@@ -41,6 +41,7 @@ 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;
|
||||
@@ -115,6 +116,7 @@ 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;
|
||||
@@ -224,6 +226,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
customKeymaps: {},
|
||||
notifications: DEFAULT_NOTIFICATIONS,
|
||||
proxy: DEFAULT_PROXY,
|
||||
remoteDevelopment: { idleTimeoutMinutes: DEFAULT_REMOTE_IDLE_MINUTES },
|
||||
toolDownloads: { githubMirror: "" },
|
||||
languages: DEFAULT_LANGUAGES,
|
||||
cmake: {},
|
||||
@@ -425,6 +428,9 @@ 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"
|
||||
|
||||
@@ -3,3 +3,8 @@
|
||||
flex-direction: column;
|
||||
max-width: 680px;
|
||||
}
|
||||
|
||||
.durationAmount {
|
||||
width: 12ch;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
@@ -10,6 +10,7 @@ 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";
|
||||
@@ -32,6 +33,7 @@ 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]));
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
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,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -4,11 +4,12 @@
|
||||
* its own. The session lives in `cliSessions.ts`; this only attaches its host while the
|
||||
* tab is the one shown.
|
||||
*/
|
||||
import { useLayoutEffect, useRef, type FocusEvent } from "react";
|
||||
import { useEffect, 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, startTab, useClis } from "./cli";
|
||||
import { cliData, reattachCliTab, 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.
|
||||
@@ -19,8 +20,15 @@ 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;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -45,6 +46,7 @@ import {
|
||||
tabTitle,
|
||||
topRightGroup,
|
||||
useTerminals,
|
||||
waitForTerminalRestore,
|
||||
type GroupLayout,
|
||||
type TerminalTab,
|
||||
} from "./store";
|
||||
@@ -264,6 +266,8 @@ 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.
|
||||
@@ -275,12 +279,23 @@ export function TerminalView() {
|
||||
useEffect(() => {
|
||||
const el = rootRef.current;
|
||||
if (!root || !el) return;
|
||||
let alive = true;
|
||||
const ensureTab = () => {
|
||||
if (el.clientHeight <= 0) return;
|
||||
if (!alive || 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);
|
||||
if (useTerminals.getState().tabs.length === 0) newTab(root);
|
||||
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);
|
||||
}
|
||||
// Sessions created while this window was hidden open once it actually has a box.
|
||||
refitSessions();
|
||||
};
|
||||
@@ -288,8 +303,11 @@ export function TerminalView() {
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const ro = new ResizeObserver(ensureTab);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [root]);
|
||||
return () => {
|
||||
alive = false;
|
||||
ro.disconnect();
|
||||
};
|
||||
}, [root, scope, remoteSession]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -10,6 +10,7 @@ import { create } from "zustand";
|
||||
import { editorService, toolWindowService, type EditorInput } from "@/workbench/contributions";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { Badge } from "@/ui";
|
||||
import { loadTerminalRuntime } from "./loader";
|
||||
import type { SessionSnapshot } from "./session";
|
||||
@@ -24,6 +25,8 @@ export interface CliData {
|
||||
command: string;
|
||||
/** The session's directory when it was saved; a restored tab starts there. */
|
||||
cwd?: string;
|
||||
/** Live backend PTY id in a persistent remote session. */
|
||||
terminalId?: number;
|
||||
}
|
||||
|
||||
/** `data` arrives from the saved editor session: treat it as untrusted JSON. */
|
||||
@@ -31,20 +34,28 @@ export function cliData(input: EditorInput): CliData | null {
|
||||
if (input.kind !== CLI_KIND) return null;
|
||||
const d = input.data as Partial<CliData> | undefined;
|
||||
if (!d || typeof d.name !== "string" || !d.name.trim()) return null;
|
||||
const terminalId =
|
||||
typeof d.terminalId === "number" && Number.isInteger(d.terminalId) && d.terminalId > 0 ? d.terminalId : undefined;
|
||||
return {
|
||||
name: d.name.trim(),
|
||||
command: typeof d.command === "string" ? d.command.trim() : "",
|
||||
...(typeof d.cwd === "string" && d.cwd ? { cwd: d.cwd } : {}),
|
||||
...(terminalId !== undefined ? { terminalId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
/** A fresh input for one session; keys never repeat, so a restored tab is its own. */
|
||||
export function cliInput(name: string, command: string, cwd?: string): EditorInput {
|
||||
export function cliInput(name: string, command: string, cwd?: string, terminalId?: number): EditorInput {
|
||||
return {
|
||||
kind: CLI_KIND,
|
||||
key: `cli:r${++seq}-${Date.now().toString(36)}`,
|
||||
data: { name, command, ...(cwd ? { cwd } : {}) },
|
||||
data: {
|
||||
name,
|
||||
command,
|
||||
...(cwd ? { cwd } : {}),
|
||||
...(terminalId !== undefined ? { terminalId } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,6 +70,23 @@ export function CliDoneMark({ inputKey }: { inputKey: string }) {
|
||||
return createElement(Badge, { dot: true, tone: "accent", children: tx("Finished") });
|
||||
}
|
||||
|
||||
/** Keeps `input.data.terminalId` in sync once the session's PTY spawns, so saved editor sessions can reattach. */
|
||||
function trackCliTerminalId(input: EditorInput) {
|
||||
if (!input.data || typeof input.data !== "object") return;
|
||||
const apply = (tid: number | null | undefined) => {
|
||||
if (tid != null) {
|
||||
(input.data as CliData).terminalId = tid;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
if (apply(useClis.getState().sessions[input.key]?.terminalId)) return;
|
||||
const off = useClis.subscribe((s) => {
|
||||
const snap = s.sessions[input.key];
|
||||
if (apply(snap?.terminalId) || snap?.status === "exited" || snap?.status === "error") off();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Move to Editor: tab `id` of the Terminal tool window (the active one when omitted)
|
||||
* leaves the tool window and opens as an editor tab, its session still running.
|
||||
@@ -71,8 +99,10 @@ export async function moveTerminalToEditor(id?: string) {
|
||||
const name = rt.tabTitle(tab, state.sessions);
|
||||
const session = rt.detachTab(tab.id);
|
||||
if (!session) return;
|
||||
const input = cliInput(name, "", session.state.cwd ?? undefined);
|
||||
const tid = session.persistedTerminalId ?? session.state.terminalId ?? undefined;
|
||||
const input = cliInput(name, "", session.state.cwd ?? undefined, tid);
|
||||
rt.adoptCli(input.key, session);
|
||||
trackCliTerminalId(input);
|
||||
if (rt.useTerminals.getState().tabs.length === 0) toolWindowService().hide("terminal");
|
||||
await editorService().openInput(input, { focus: true });
|
||||
}
|
||||
@@ -84,4 +114,18 @@ export async function startTab(input: EditorInput) {
|
||||
if (!data || !root) return;
|
||||
const rt = await loadTerminalRuntime();
|
||||
rt.startCli(input.key, data.cwd ?? root, data.command, root);
|
||||
trackCliTerminalId(input);
|
||||
}
|
||||
|
||||
/** Reattaches a restored CLI editor tab to its live remote PTY, when still running. */
|
||||
export async function reattachCliTab(input: EditorInput) {
|
||||
if (!isRemoteWindow()) return;
|
||||
const data = cliData(input);
|
||||
const root = useProject.getState().project?.root;
|
||||
if (!data?.terminalId || !root) return;
|
||||
const rt = await loadTerminalRuntime();
|
||||
const ok = await rt.reattachCli(input.key, data.terminalId, data.cwd ?? root, root);
|
||||
if (!ok && input.data && typeof input.data === "object") {
|
||||
delete (input.data as CliData).terminalId;
|
||||
}
|
||||
}
|
||||
@@ -99,9 +99,37 @@ export function startCli(key: string, cwd: string, command: string, fallbackRoot
|
||||
return session;
|
||||
}
|
||||
|
||||
/** Reattaches a restored CLI editor tab to `terminalId` if it is still running on the remote server. */
|
||||
export async function reattachCli(
|
||||
key: string,
|
||||
terminalId: number,
|
||||
cwd: string,
|
||||
fallbackRoot?: string,
|
||||
): Promise<boolean> {
|
||||
if (sessions.has(key)) return true;
|
||||
const session = new TerminalSession({
|
||||
key,
|
||||
cwd,
|
||||
fallbackRoot,
|
||||
attachTerminalId: terminalId,
|
||||
onlyAttach: true,
|
||||
onChange,
|
||||
onFocus() {},
|
||||
onCompletion: (_, info) => noteCliCompletion(key, info),
|
||||
});
|
||||
sessions.set(key, session);
|
||||
useClis.setState((s) => ({ sessions: { ...s.sessions, [key]: session.state } }));
|
||||
await session.start();
|
||||
if (session.state.status !== "running") {
|
||||
disposeCli(key, false);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ends the session of a closed tab. */
|
||||
export function disposeCli(key: string) {
|
||||
sessions.get(key)?.dispose();
|
||||
export function disposeCli(key: string, kill = true) {
|
||||
sessions.get(key)?.dispose(kill);
|
||||
sessions.delete(key);
|
||||
useClis.setState((s) => {
|
||||
const sessions = { ...s.sessions };
|
||||
@@ -111,8 +139,8 @@ export function disposeCli(key: string) {
|
||||
}
|
||||
|
||||
/** The project switched: the tabs are closed by the editor without `onClose`, so end the sessions here. */
|
||||
export function disposeAllClis() {
|
||||
for (const session of sessions.values()) session.dispose();
|
||||
export function disposeAllClis(kill = true) {
|
||||
for (const session of sessions.values()) session.dispose(kill);
|
||||
sessions.clear();
|
||||
useClis.setState({ sessions: {} });
|
||||
}
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
*/
|
||||
import { createElement } from "react";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isRemoteWindow, parseRemoteLocation, projectLocation } from "@/platform/remote";
|
||||
import { useSystemFontStore } from "@/platform/systemFonts";
|
||||
import { onWorkflowSettingsChange } from "@/platform/workflowSettings";
|
||||
import {
|
||||
@@ -367,15 +368,43 @@ export function activate(): () => void {
|
||||
return () => document.removeEventListener("visibilitychange", onVisibility);
|
||||
})(),
|
||||
// Sessions belong to the project. Remember this project's tabs, then open the next one's.
|
||||
useProject.subscribe((s, prev) => {
|
||||
const rt = terminalRuntime();
|
||||
if (rt && s.project?.root !== prev.project?.root) {
|
||||
if (rt.useTerminalFind.getState().open) rt.closeTerminalFind();
|
||||
rt.syncTerminalProject(s.project?.root ?? null);
|
||||
// The editor drops the old project's tabs without `onClose`; their CLIs end with it.
|
||||
rt.disposeAllClis();
|
||||
}
|
||||
}),
|
||||
(() => {
|
||||
let prevLocation = projectLocation(useProject.getState().project?.root);
|
||||
return useProject.subscribe((s) => {
|
||||
const nextLocation = projectLocation(s.project?.root);
|
||||
if (nextLocation === prevLocation) return;
|
||||
const wasRemote = !!prevLocation && parseRemoteLocation(prevLocation) !== null;
|
||||
prevLocation = nextLocation;
|
||||
const rt = terminalRuntime();
|
||||
if (rt) {
|
||||
if (rt.useTerminalFind.getState().open) rt.closeTerminalFind();
|
||||
rt.syncTerminalProject(s.project?.root ?? null, nextLocation);
|
||||
// The editor drops the old project's tabs without `onClose`; their CLIs end with it locally,
|
||||
// or detach without killing the remote daemon's PTYs.
|
||||
rt.disposeAllClis(!wasRemote);
|
||||
} else if (s.project?.root && isRemoteWindow() && isTauri()) {
|
||||
const root = s.project.root;
|
||||
void commands
|
||||
.termList()
|
||||
.then(async (list) => {
|
||||
if (list.length > 0 && useProject.getState().project?.root === root) {
|
||||
await loadTerminalRuntime();
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
});
|
||||
})(),
|
||||
(() => {
|
||||
if (typeof window === "undefined") return () => {};
|
||||
const flush = () => terminalRuntime()?.rememberTerminals();
|
||||
window.addEventListener("pagehide", flush);
|
||||
window.addEventListener("beforeunload", flush);
|
||||
return () => {
|
||||
window.removeEventListener("pagehide", flush);
|
||||
window.removeEventListener("beforeunload", flush);
|
||||
};
|
||||
})(),
|
||||
];
|
||||
|
||||
if (typeof MutationObserver !== "undefined" && typeof document !== "undefined") {
|
||||
|
||||
@@ -16,11 +16,13 @@ import {
|
||||
vi.mock("./session", () => ({
|
||||
TerminalSession: class {
|
||||
key: string;
|
||||
state: { cwd: string; status: string };
|
||||
state: { cwd: string; status: string; terminalId?: number | null };
|
||||
command:
|
||||
| { program: string; args: string[]; shell?: boolean; onExit?: (code: number | null, closed: boolean) => void }
|
||||
| undefined;
|
||||
fallbackRoot: string | undefined;
|
||||
attachTerminalId: number | null | undefined;
|
||||
disposedWithKill: boolean | undefined;
|
||||
constructor(opts: {
|
||||
key: string;
|
||||
cwd: string;
|
||||
@@ -31,17 +33,23 @@ vi.mock("./session", () => ({
|
||||
onExit?: (code: number | null, closed: boolean) => void;
|
||||
};
|
||||
fallbackRoot?: string;
|
||||
attachTerminalId?: number | null;
|
||||
}) {
|
||||
this.key = opts.key;
|
||||
this.state = { cwd: opts.cwd, status: "idle" };
|
||||
this.state = { cwd: opts.cwd, status: "idle", terminalId: opts.attachTerminalId ?? null };
|
||||
this.command = opts.command;
|
||||
this.fallbackRoot = opts.fallbackRoot;
|
||||
this.attachTerminalId = opts.attachTerminalId;
|
||||
}
|
||||
get persistedTerminalId() {
|
||||
return this.state.terminalId ?? this.attachTerminalId ?? null;
|
||||
}
|
||||
async start() {
|
||||
this.state.status = "running";
|
||||
}
|
||||
dispose() {
|
||||
this.command?.onExit?.(null, true);
|
||||
dispose(kill = true) {
|
||||
this.disposedWithKill = kill;
|
||||
if (kill) this.command?.onExit?.(null, true);
|
||||
}
|
||||
},
|
||||
}));
|
||||
@@ -179,4 +187,41 @@ describe("terminal tab memory", () => {
|
||||
expect(restored.state.cwd).toBe("/repo/gone");
|
||||
expect(restored.fallbackRoot).toBe("/repo");
|
||||
});
|
||||
|
||||
it("reattaches live remote terminal ids without killing them on unbind and keeps two remote hosts apart", () => {
|
||||
const scopeA = "ssh://devbox-a/home/coder/repo";
|
||||
const scopeB = "ssh://devbox-b/home/coder/repo";
|
||||
|
||||
syncTerminalProject("/home/coder/repo", scopeA);
|
||||
const tabA = newTab("/home/coder/repo");
|
||||
renameTab(tabA.id, "watch date");
|
||||
const sessionA = getSession(tabA.session) as unknown as {
|
||||
state: { cwd: string; terminalId: number | null };
|
||||
disposedWithKill?: boolean;
|
||||
};
|
||||
sessionA.state.terminalId = 41;
|
||||
useTerminals.setState((s) => ({
|
||||
sessions: { ...s.sessions, [tabA.session]: { ...s.sessions[tabA.session]!, terminalId: 41 } },
|
||||
}));
|
||||
|
||||
// Leaving a remote project detaches without killing the remote PTY.
|
||||
unbindTerminals();
|
||||
expect(sessionA.disposedWithKill).toBe(false);
|
||||
|
||||
// Another remote host with the same `/home/coder/repo` path has its own tab layout.
|
||||
syncTerminalProject("/home/coder/repo", scopeB);
|
||||
expect(state().tabs).toEqual([]);
|
||||
const tabB = newTab("/home/coder/repo");
|
||||
renameTab(tabB.id, "docker compose");
|
||||
|
||||
// Reopening `devbox-a` restores `watch date` and reattaches to PTY 41.
|
||||
syncTerminalProject("/home/coder/repo", scopeA);
|
||||
expect(names()).toEqual(["watch date"]);
|
||||
const restoredA = getSession(state().tabs[0]!.session) as unknown as {
|
||||
attachTerminalId?: number | null;
|
||||
state: { status: string };
|
||||
};
|
||||
expect(restoredA.attachTerminalId).toBe(41);
|
||||
expect(restoredA.state.status).toBe("running");
|
||||
});
|
||||
});
|
||||
@@ -3,11 +3,12 @@
|
||||
* working directory and rename, and how the tab groups were split. Shell
|
||||
* scrollback is not kept; a tab comes back as a new session in that directory.
|
||||
*/
|
||||
import { parseRemoteLocation } from "@/platform/remote";
|
||||
import type { GroupLayout, SplitOrientation } from "./store";
|
||||
|
||||
const STORAGE_PREFIX = "openidea.terminal.tabs.v1:";
|
||||
|
||||
interface StoredTab {
|
||||
export interface StoredTab {
|
||||
id: string;
|
||||
name: string;
|
||||
customName: string | null;
|
||||
@@ -15,6 +16,8 @@ interface StoredTab {
|
||||
group: string;
|
||||
/** Predefined shell program. A one-shot command is not replayed. */
|
||||
shell: string | null;
|
||||
/** Backend PTY id for reattaching across persistent remote sessions. */
|
||||
terminalId?: number | null;
|
||||
}
|
||||
|
||||
export interface StoredTerminals {
|
||||
@@ -33,7 +36,10 @@ export function storageKey(root: string): string {
|
||||
|
||||
export function readStored(root: string): StoredTerminals | null {
|
||||
try {
|
||||
return decode(JSON.parse(localStorage.getItem(storageKey(root)) ?? "null"));
|
||||
const raw =
|
||||
localStorage.getItem(storageKey(root)) ??
|
||||
(parseRemoteLocation(root) ? localStorage.getItem(storageKey(parseRemoteLocation(root)!.path)) : null);
|
||||
return decode(JSON.parse(raw ?? "null"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -83,7 +89,17 @@ function decodeTab(item: unknown, groups: Set<string>, fallback: string): Stored
|
||||
const group = typeof t.group === "string" && groups.has(t.group) ? t.group : fallback;
|
||||
const customName = typeof t.customName === "string" && t.customName.trim() ? t.customName.trim() : null;
|
||||
const shell = typeof t.shell === "string" && t.shell ? t.shell : null;
|
||||
return { id: t.id, name: t.name.trim(), customName, cwd: t.cwd, group, shell };
|
||||
const terminalId =
|
||||
typeof t.terminalId === "number" && Number.isInteger(t.terminalId) && t.terminalId > 0 ? t.terminalId : null;
|
||||
return {
|
||||
id: t.id,
|
||||
name: t.name.trim(),
|
||||
customName,
|
||||
cwd: t.cwd,
|
||||
group,
|
||||
shell,
|
||||
...(terminalId !== null ? { terminalId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeLayout(raw: unknown): GroupLayout | null {
|
||||
|
||||
@@ -8,6 +8,7 @@ export {
|
||||
newTab,
|
||||
newTabRunning,
|
||||
pluginSession,
|
||||
rememberTerminals,
|
||||
syncTerminalProject,
|
||||
tabTitle,
|
||||
unbindTerminals,
|
||||
@@ -31,6 +32,7 @@ export {
|
||||
disposeAllClis,
|
||||
disposeCli,
|
||||
isCliSession,
|
||||
reattachCli,
|
||||
startCli,
|
||||
} from "./cliSessions";
|
||||
export { CliEditor } from "./CliEditor";
|
||||
|
||||
@@ -65,6 +65,8 @@ export type SessionStatus = "idle" | "starting" | "running" | "exited" | "error"
|
||||
export interface SessionSnapshot {
|
||||
status: SessionStatus;
|
||||
exitCode: number | null;
|
||||
/** Live or pending backend PTY id, when one exists. */
|
||||
terminalId?: TerminalId | null;
|
||||
/** Shell name reported by the backend (`zsh`). */
|
||||
title: string;
|
||||
/** Window title set by the running program (OSC 0/2), null when unset or blank. */
|
||||
@@ -123,6 +125,10 @@ export interface SessionOptions {
|
||||
* (deleted since the last run, see `resolveStartCwd`).
|
||||
*/
|
||||
fallbackRoot?: string;
|
||||
/** Existing backend PTY id to reattach to before falling back to spawning a fresh shell. */
|
||||
attachTerminalId?: TerminalId | null;
|
||||
/** Do not spawn a fresh shell if `attachTerminalId` is no longer running (CLI editor tabs). */
|
||||
onlyAttach?: boolean;
|
||||
}
|
||||
|
||||
/** Mouse-tracking DEC private modes (X10, normal, button, any-event, encodings). */
|
||||
@@ -260,6 +266,7 @@ export class TerminalSession {
|
||||
/** Bounds retries when the pane has no box yet, or xterm cannot measure a cell. */
|
||||
private fitAttempts = 0;
|
||||
private disposed = false;
|
||||
private killOnDispose = true;
|
||||
private disposables: IDisposable[] = [];
|
||||
private resizeObserver: ResizeObserver | null = null;
|
||||
private readonly fitter = fitScheduler(() => this.doFit());
|
||||
@@ -305,6 +312,7 @@ export class TerminalSession {
|
||||
this.snapshot = {
|
||||
status: "idle",
|
||||
exitCode: null,
|
||||
terminalId: opts.attachTerminalId ?? null,
|
||||
title: "Local",
|
||||
appTitle: null,
|
||||
commandRunning: false,
|
||||
@@ -824,11 +832,45 @@ export class TerminalSession {
|
||||
}
|
||||
const cols = Math.max(2, this.term.cols);
|
||||
const rows = Math.max(1, this.term.rows);
|
||||
this.lastSize = { cols, rows };
|
||||
this.lastSize = this.opened ? { cols, rows } : { cols: 0, rows: 0 };
|
||||
const channel = new Channel<string>();
|
||||
channel.onmessage = (chunk) => {
|
||||
if (generation === this.generation && !this.disposed) this.writePtyOutput(chunk);
|
||||
};
|
||||
const attachId = this.opts.attachTerminalId ?? null;
|
||||
if (attachId !== null) {
|
||||
this.opts.attachTerminalId = null;
|
||||
try {
|
||||
const attachCols = this.opened ? cols : 0;
|
||||
const attachRows = this.opened ? rows : 0;
|
||||
const attached = await call(commands.termAttach(attachId, attachCols, attachRows, channel));
|
||||
if (this.disposed || generation !== this.generation) {
|
||||
if (this.disposed && this.killOnDispose && !this.opts.command?.onExit) void commands.termKill(attachId);
|
||||
return;
|
||||
}
|
||||
this.ptyId = attached.session.id;
|
||||
if (attached.buffered) this.writePtyOutput(attached.buffered);
|
||||
this.update({
|
||||
terminalId: attached.session.id,
|
||||
status: "running",
|
||||
title: attached.session.title || "Local",
|
||||
cwd: attached.session.cwd || this.snapshot.cwd,
|
||||
appTitle: attached.session.appTitle ?? this.snapshot.appTitle,
|
||||
commandRunning: attached.session.commandRunning,
|
||||
});
|
||||
if (this.opened && (attachCols === 0 || this.term.cols !== attachCols || this.term.rows !== attachRows)) {
|
||||
this.resizePty(Math.max(2, this.term.cols), Math.max(1, this.term.rows));
|
||||
}
|
||||
this.flushPendingInput();
|
||||
return;
|
||||
} catch {
|
||||
if (this.disposed || generation !== this.generation) return;
|
||||
if (this.opts.onlyAttach) {
|
||||
this.update({ terminalId: null, status: "exited", commandRunning: false, progress: null });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
const t = workflowSettings().terminal;
|
||||
const [shellPath, ...shellArgs] = parseShellCommand(t.shellPath, hostOs() === "windows");
|
||||
@@ -853,11 +895,11 @@ export class TerminalSession {
|
||||
),
|
||||
);
|
||||
if (this.disposed || generation !== this.generation) {
|
||||
void commands.termKill(info.id);
|
||||
if (!this.disposed || this.killOnDispose) void commands.termKill(info.id);
|
||||
return;
|
||||
}
|
||||
this.ptyId = info.id;
|
||||
this.update({ status: "running", title: info.title || "Local" });
|
||||
this.update({ terminalId: info.id, status: "running", title: info.title || "Local" });
|
||||
// Send the new size if it changed while the program was starting.
|
||||
if (this.term.cols !== cols || this.term.rows !== rows) this.resizePty(this.term.cols, this.term.rows);
|
||||
this.flushPendingInput();
|
||||
@@ -866,7 +908,7 @@ export class TerminalSession {
|
||||
this.term.writeln(`\x1b[31mFailed to start terminal: ${e instanceof Error ? e.message : String(e)}\x1b[0m`);
|
||||
if (!custom?.onExit) this.term.writeln(RESTART_HINT);
|
||||
// Nothing runs: a non-shell command tab must not keep its running marker.
|
||||
this.update({ status: "error", commandRunning: false, progress: null });
|
||||
this.update({ terminalId: null, status: "error", commandRunning: false, progress: null });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -874,6 +916,11 @@ export class TerminalSession {
|
||||
return this.ptyId;
|
||||
}
|
||||
|
||||
/** Backend PTY id for session persistence, including tabs waiting to attach. */
|
||||
get persistedTerminalId(): TerminalId | null {
|
||||
return this.ptyId ?? this.opts.attachTerminalId ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether ending the session would kill something the user started (as IDEA
|
||||
* judges it): a program run instead of a shell always counts;
|
||||
@@ -898,7 +945,7 @@ export class TerminalSession {
|
||||
this.pendingInput = "";
|
||||
// The process is gone: a non-shell command tab never sees OSC 133's D, so
|
||||
// the running marker stops here rather than spinning over the dead tab.
|
||||
this.update({ status: "exited", exitCode: code, commandRunning: false, progress: null });
|
||||
this.update({ terminalId: null, status: "exited", exitCode: code, commandRunning: false, progress: null });
|
||||
// Let output still in flight on the channel land first.
|
||||
setTimeout(() => {
|
||||
if (this.disposed || this.snapshot.status !== "exited") return;
|
||||
@@ -1063,10 +1110,11 @@ export class TerminalSession {
|
||||
return () => this.searchListeners.delete(listener);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
dispose(kill = true) {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
if (this.snapshot.status === "running" || this.snapshot.status === "starting")
|
||||
this.killOnDispose = kill;
|
||||
if (kill && (this.snapshot.status === "running" || this.snapshot.status === "starting"))
|
||||
this.opts.command?.onExit?.(null, true);
|
||||
this.fitter.cancel();
|
||||
this.ptyResize.cancel();
|
||||
@@ -1077,7 +1125,7 @@ export class TerminalSession {
|
||||
this.host.removeEventListener("mousedown", this.onMiddleClick);
|
||||
this.host.removeEventListener("wheel", this.onWheelZoom, { capture: true });
|
||||
// A session with an owner (`onExit`) is ended by that owner.
|
||||
if (this.ptyId !== null && !this.opts.command?.onExit) void commands.termKill(this.ptyId);
|
||||
if (kill && this.ptyId !== null && !this.opts.command?.onExit) void commands.termKill(this.ptyId);
|
||||
this.ptyId = null;
|
||||
this.disposables.forEach((d) => d.dispose());
|
||||
this.term.dispose();
|
||||
|
||||
@@ -6,10 +6,13 @@
|
||||
import { create } from "zustand";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { commands, isTauri, type TerminalSessionInfo } from "@/platform/ipc";
|
||||
import { basename } from "@/platform/project";
|
||||
import { isRemoteWindow, parseRemoteLocation, projectLocation } from "@/platform/remote";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { toolWindowService } from "@/workbench/contributions";
|
||||
import { maybeEditorService, toolWindowService } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { CLI_KIND, cliData } from "./cli";
|
||||
import { completionAlert, completionPrefs, raiseCompletionNotification, type CompletionInfo } from "./completion";
|
||||
import { readStored, writeStored, type StoredTerminals } from "./persist";
|
||||
import { TerminalSession, type SessionOptions, type SessionSnapshot } from "./session";
|
||||
@@ -112,13 +115,19 @@ function notifyCompletion(key: string, info: CompletionInfo) {
|
||||
});
|
||||
}
|
||||
|
||||
function createSession(cwd: string, command?: SessionOptions["command"], fallbackRoot?: string): TerminalSession {
|
||||
function createSession(
|
||||
cwd: string,
|
||||
command?: SessionOptions["command"],
|
||||
fallbackRoot?: string,
|
||||
attachTerminalId?: number | null,
|
||||
): TerminalSession {
|
||||
const key = `s${++seq}`;
|
||||
const session = new TerminalSession({
|
||||
key,
|
||||
cwd,
|
||||
command,
|
||||
fallbackRoot,
|
||||
attachTerminalId,
|
||||
onChange: (k, snapshot) => useTerminals.setState((s) => ({ sessions: { ...s.sessions, [k]: snapshot } })),
|
||||
onFocus: (k) => {
|
||||
const tab = tabOfSession(k);
|
||||
@@ -143,13 +152,13 @@ function createSession(cwd: string, command?: SessionOptions["command"], fallbac
|
||||
return session;
|
||||
}
|
||||
|
||||
function disposeSession(key: string) {
|
||||
function disposeSession(key: string, kill = true) {
|
||||
const session = sessions.get(key);
|
||||
const focus = document.activeElement;
|
||||
// Removing the focused pane fires no blur, so `terminalFocus` would stay set (⌘T would keep
|
||||
// opening terminal tabs). Another pane taking the caret sets it again.
|
||||
if (focus && session?.host?.contains(focus)) publishFocus(false);
|
||||
session?.dispose();
|
||||
session?.dispose(kill);
|
||||
sessions.delete(key);
|
||||
useTerminals.setState((s) => {
|
||||
const next = { ...s.sessions };
|
||||
@@ -344,8 +353,8 @@ export function requestCloseSession(key: string): Promise<boolean> {
|
||||
return tab ? requestCloseTab(tab.id) : Promise.resolve(false);
|
||||
}
|
||||
|
||||
export function closeAll() {
|
||||
for (const t of useTerminals.getState().tabs) disposeSession(t.session);
|
||||
export function closeAll(kill = true) {
|
||||
for (const t of useTerminals.getState().tabs) disposeSession(t.session, kill);
|
||||
useTerminals.setState({ tabs: [], layout: newGroupId(), selected: {}, activeTab: null, sessions: {} });
|
||||
}
|
||||
|
||||
@@ -585,7 +594,12 @@ export function publishFocus(focused: boolean) {
|
||||
}
|
||||
|
||||
/** Project whose tabs `useTerminals` currently holds. Null before the first bind and after unbind. */
|
||||
/** Project root directory whose tabs `useTerminals` currently holds. */
|
||||
let boundProject: string | null = null;
|
||||
/** Storage scope (`projectLocation(root)`) of the bound project. */
|
||||
let boundScope: string | null = null;
|
||||
/** Whether the bound project runs on a persistent remote server. */
|
||||
let boundRemote = false;
|
||||
/** Set while swapping projects, so closing the old tabs is not saved as the new project's layout. */
|
||||
let restoring = false;
|
||||
|
||||
@@ -593,36 +607,59 @@ function sessionCwd(key: string): string {
|
||||
return sessions.get(key)?.state.cwd ?? "";
|
||||
}
|
||||
|
||||
function sessionTerminalId(key: string): number | null {
|
||||
const s = sessions.get(key);
|
||||
return s?.persistedTerminalId ?? s?.state.terminalId ?? null;
|
||||
}
|
||||
|
||||
function capture(): StoredTerminals {
|
||||
const s = useTerminals.getState();
|
||||
const tabs = s.tabs.flatMap((t) => {
|
||||
const cwd = sessionCwd(t.session);
|
||||
return cwd ? [{ id: t.id, name: t.name, customName: t.customName, cwd, group: t.group, shell: t.shell }] : [];
|
||||
const terminalId = sessionTerminalId(t.session);
|
||||
return cwd
|
||||
? [
|
||||
{
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
customName: t.customName,
|
||||
cwd,
|
||||
group: t.group,
|
||||
shell: t.shell,
|
||||
...(terminalId !== null ? { terminalId } : {}),
|
||||
},
|
||||
]
|
||||
: [];
|
||||
});
|
||||
return { v: 1, tabs, layout: s.layout, selected: s.selected, activeTab: s.activeTab };
|
||||
}
|
||||
|
||||
function remember() {
|
||||
if (restoring || !boundProject) return;
|
||||
writeStored(boundProject, capture());
|
||||
export function rememberTerminals() {
|
||||
if (restoring || !boundScope) return;
|
||||
writeStored(boundScope, capture());
|
||||
}
|
||||
|
||||
function cwdSignature(s: TerminalState): string {
|
||||
return s.tabs.map((t) => s.sessions[t.session]?.cwd ?? "").join("\n");
|
||||
function sessionSignature(s: TerminalState): string {
|
||||
return s.tabs
|
||||
.map((t) => {
|
||||
const snap = s.sessions[t.session];
|
||||
return `${snap?.cwd ?? ""}\t${snap?.terminalId ?? ""}`;
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
useTerminals.subscribe((s, prev) => {
|
||||
if (restoring || !boundProject) return;
|
||||
if (restoring || !boundScope) return;
|
||||
if (
|
||||
s.tabs === prev.tabs &&
|
||||
s.layout === prev.layout &&
|
||||
s.selected === prev.selected &&
|
||||
s.activeTab === prev.activeTab &&
|
||||
cwdSignature(s) === cwdSignature(prev)
|
||||
sessionSignature(s) === sessionSignature(prev)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
remember();
|
||||
rememberTerminals();
|
||||
});
|
||||
|
||||
function remapLayout(node: GroupLayout, mapGroup: (group: string) => string): GroupLayout {
|
||||
@@ -634,8 +671,8 @@ function remapLayout(node: GroupLayout, mapGroup: (group: string) => string): Gr
|
||||
};
|
||||
}
|
||||
|
||||
/** Opens the saved tabs in fresh sessions. Group ids are new, so they don't collide with ones minted later. */
|
||||
function restore(saved: StoredTerminals, root: string) {
|
||||
/** Opens the saved tabs in fresh sessions (or reattaches live remote PTYs). Group ids are new. */
|
||||
function restore(saved: StoredTerminals, root: string, remote: boolean) {
|
||||
const groupOf = new Map<string, string>();
|
||||
const mapGroup = (group: string) => {
|
||||
let mapped = groupOf.get(group);
|
||||
@@ -645,13 +682,17 @@ function restore(saved: StoredTerminals, root: string) {
|
||||
const layout = remapLayout(saved.layout, mapGroup);
|
||||
const idOf = new Map<string, string>();
|
||||
const tabs: TerminalTab[] = [];
|
||||
const toAttach: TerminalSession[] = [];
|
||||
for (const savedTab of saved.tabs) {
|
||||
const attachId = remote ? (savedTab.terminalId ?? null) : null;
|
||||
const session = createSession(
|
||||
savedTab.cwd,
|
||||
savedTab.shell ? { program: savedTab.shell, args: [], shell: true } : undefined,
|
||||
// A saved directory may have been deleted since the last run: start in the project root then.
|
||||
root,
|
||||
attachId,
|
||||
);
|
||||
if (attachId !== null) toAttach.push(session);
|
||||
const id = `t${seq}`;
|
||||
idOf.set(savedTab.id, id);
|
||||
tabs.push({
|
||||
@@ -673,34 +714,98 @@ function restore(saved: StoredTerminals, root: string) {
|
||||
}
|
||||
const activeTab = (saved.activeTab && idOf.get(saved.activeTab)) || tabs[0]?.id || null;
|
||||
useTerminals.setState({ tabs, layout, selected, activeTab });
|
||||
for (const session of toAttach) void session.start();
|
||||
}
|
||||
|
||||
/** Adopts any live PTYs on a remote daemon that were not already claimed by a saved tab or CLI editor tab. */
|
||||
async function reconcileRemoteTerminals(scope: string, root: string) {
|
||||
if (!isTauri()) return;
|
||||
let live: TerminalSessionInfo[];
|
||||
try {
|
||||
live = await commands.termList();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (boundScope !== scope || !live.length) return;
|
||||
const claimed = new Set<number>();
|
||||
for (const s of sessions.values()) {
|
||||
const id = s.persistedTerminalId ?? s.state.terminalId;
|
||||
if (id != null) claimed.add(id);
|
||||
}
|
||||
for (const tab of maybeEditorService()?.openTabs?.() ?? []) {
|
||||
if (tab.input.kind === CLI_KIND) {
|
||||
const tid = cliData(tab.input)?.terminalId;
|
||||
if (tid != null) claimed.add(tid);
|
||||
}
|
||||
}
|
||||
const unclaimed = live.filter((info) => !claimed.has(info.id));
|
||||
if (!unclaimed.length) return;
|
||||
for (const info of unclaimed) {
|
||||
const session = createSession(info.cwd || root, undefined, root, info.id);
|
||||
const { tabs, layout, activeTab } = useTerminals.getState();
|
||||
const tab: TerminalTab = {
|
||||
id: `t${seq}`,
|
||||
name: defaultTabName(info.title || undefined),
|
||||
customName: null,
|
||||
shell: null,
|
||||
session: session.key,
|
||||
group: tabs.find((t) => t.id === activeTab)?.group ?? layoutGroups(layout)[0]!,
|
||||
};
|
||||
useTerminals.setState((s) => ({
|
||||
tabs: [...s.tabs, tab],
|
||||
selected: { ...s.selected, [tab.group]: s.selected[tab.group] ?? tab.id },
|
||||
activeTab: s.activeTab ?? tab.id,
|
||||
}));
|
||||
void session.start();
|
||||
}
|
||||
}
|
||||
|
||||
let pendingRemoteRestore: Promise<void> | null = null;
|
||||
|
||||
export function waitForTerminalRestore(): Promise<void> {
|
||||
return pendingRemoteRestore ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* Points the terminal at `root`, remembering the project it was bound to.
|
||||
* The same root again is a no-op, so a tool window re-render doesn't reopen tabs.
|
||||
* The same project location again is a no-op, so a tool window re-render doesn't reopen tabs.
|
||||
*/
|
||||
export function syncTerminalProject(root: string | null) {
|
||||
if (root === boundProject) return;
|
||||
if (boundProject) writeStored(boundProject, capture());
|
||||
export function syncTerminalProject(root: string | null, scope: string | null = projectLocation(root)) {
|
||||
if (scope === boundScope) return;
|
||||
if (boundScope) writeStored(boundScope, capture());
|
||||
const wasRemote = boundRemote;
|
||||
const nextRemote = !!scope && (isRemoteWindow() || parseRemoteLocation(scope) !== null);
|
||||
restoring = true;
|
||||
boundProject = root;
|
||||
boundScope = scope;
|
||||
boundRemote = nextRemote;
|
||||
pendingRemoteRestore = null;
|
||||
try {
|
||||
closeAll();
|
||||
if (!root) return;
|
||||
const saved = readStored(root);
|
||||
if (saved?.tabs.length) restore(saved, root);
|
||||
closeAll(!wasRemote);
|
||||
if (!root || !scope) return;
|
||||
const saved = readStored(scope);
|
||||
if (saved?.tabs.length) restore(saved, root, nextRemote);
|
||||
} finally {
|
||||
restoring = false;
|
||||
}
|
||||
if (nextRemote && scope && root) {
|
||||
const p = reconcileRemoteTerminals(scope, root).finally(() => {
|
||||
if (pendingRemoteRestore === p) pendingRemoteRestore = null;
|
||||
});
|
||||
pendingRemoteRestore = p;
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the in-memory sessions without writing the empty layout over the project that owned them. */
|
||||
export function unbindTerminals() {
|
||||
if (boundProject) writeStored(boundProject, capture());
|
||||
if (boundScope) writeStored(boundScope, capture());
|
||||
const wasRemote = boundRemote;
|
||||
restoring = true;
|
||||
boundProject = null;
|
||||
boundScope = null;
|
||||
boundRemote = false;
|
||||
try {
|
||||
closeAll();
|
||||
closeAll(!wasRemote);
|
||||
} finally {
|
||||
restoring = false;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ export function activate(): () => void {
|
||||
icon: hasIcon("toolwindow-todo") ? "toolwindow-todo" : "list",
|
||||
anchor: "bottom",
|
||||
order: 40,
|
||||
stripe: "onUse",
|
||||
component: TodoView,
|
||||
headerContent: TodoTabs,
|
||||
headerMenu: useTodoHeaderMenu,
|
||||
|
||||
@@ -49,4 +49,16 @@ describe("openRecent", () => {
|
||||
expect(openProject).toHaveBeenCalledWith("/p/local");
|
||||
expect(openRemoteProject).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("joins a remote open that is still connecting instead of connecting twice", async () => {
|
||||
let finish!: (ok: boolean) => void;
|
||||
openRemoteProject.mockReturnValue(new Promise<boolean>((resolve) => (finish = resolve)));
|
||||
const first = openRecent({ path: UNC, name: "app" });
|
||||
const second = openRecent({ path: UNC, name: "app" });
|
||||
finish(true);
|
||||
expect(await Promise.all([first, second])).toEqual([true, true]);
|
||||
expect(openRemoteProject).toHaveBeenCalledTimes(1);
|
||||
await openRecent({ path: UNC, name: "app" });
|
||||
expect(openRemoteProject).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -125,7 +125,18 @@ function failure(e: unknown): { kind?: unknown; message: string } {
|
||||
}
|
||||
|
||||
/** Opens a project from the recent list; offers to remove entries whose folder is gone. */
|
||||
export async function openRecent(project: Pick<RecentProject, "path" | "name">): Promise<boolean> {
|
||||
const openingRecent = new Map<string, Promise<boolean>>();
|
||||
|
||||
/** A second click (or double click) while the same project is still opening joins that attempt instead of connecting again. */
|
||||
export function openRecent(project: Pick<RecentProject, "path" | "name">): Promise<boolean> {
|
||||
const pending = openingRecent.get(project.path);
|
||||
if (pending) return pending;
|
||||
const attempt = openRecentNow(project).finally(() => openingRecent.delete(project.path));
|
||||
openingRecent.set(project.path, attempt);
|
||||
return attempt;
|
||||
}
|
||||
|
||||
async function openRecentNow(project: Pick<RecentProject, "path" | "name">): Promise<boolean> {
|
||||
if (!isTauri()) {
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
|
||||
@@ -211,6 +211,7 @@
|
||||
"menu.file.openFile": "Open File…",
|
||||
"menu.remote.connect": "Remote Development…",
|
||||
"menu.remote.disconnect": "Disconnect from Remote Host",
|
||||
"menu.remote.stopBackend": "Stop Remote Backend",
|
||||
"menu.navigationBar": "Navigation Bar",
|
||||
"menu.run.updateApplication": "Update Application",
|
||||
"menu.ssh.startSession": "Start SSH Session…",
|
||||
|
||||
@@ -2924,6 +2924,41 @@
|
||||
"Lost the connection to {host}": "Lost the connection to {host}",
|
||||
"Reconnect": "Reconnect",
|
||||
"Reconnect to Remote Host": "Reconnect to Remote Host",
|
||||
"Stop Remote Backend": "Stop Remote Backend",
|
||||
"Stop Backend": "Stop Backend",
|
||||
"Close Remote Development Window": "Close Remote Development Window",
|
||||
"Keep Backend Running": "Keep Backend Running",
|
||||
"Keep the IDE backend on {host} running so you can reconnect later, or stop it and end its terminals, runs and agent tasks.": "Keep the IDE backend on {host} running so you can reconnect later, or stop it and end its terminals, runs and agent tasks.",
|
||||
"Could not stop the remote backend": "Could not stop the remote backend",
|
||||
"Another window took over this remote session": "Another window took over this remote session",
|
||||
"Remote Development": "Remote Development",
|
||||
"Remote backend": "Remote backend",
|
||||
"Idle timeout": "Idle timeout",
|
||||
"Open Settings in a remote project window to change its backend timeout.": "Open Settings in a remote project window to change its backend timeout.",
|
||||
"Reconnect to the remote host to change its backend timeout.": "Reconnect to the remote host to change its backend timeout.",
|
||||
"This backend does not support a configurable idle timeout.": "This backend does not support a configurable idle timeout.",
|
||||
"Stop backend when idle": "Stop backend when idle",
|
||||
"Custom duration": "Custom duration",
|
||||
"Duration unit": "Duration unit",
|
||||
"Minutes": "Minutes",
|
||||
"Hours": "Hours",
|
||||
"Days": "Days",
|
||||
"Custom…": "Custom…",
|
||||
"After {duration} (default)": "After {duration} (default)",
|
||||
"After {duration}": "After {duration}",
|
||||
"Enter a duration equivalent to 1–65,535 whole minutes.": "Enter a duration equivalent to 1–65,535 whole minutes.",
|
||||
"The timer starts when the last window disconnects from {host} and no terminals, runs, debug sessions, or agent tasks are active.": "The timer starts when the last window disconnects from {host} and no terminals, runs, debug sessions, or agent tasks are active.",
|
||||
"Idle shutdown is off on {host}. You can still stop the backend manually.": "Idle shutdown is off on {host}. You can still stop the backend manually.",
|
||||
"Idle shutdown is off on {host}.": "Idle shutdown is off on {host}.",
|
||||
"If kept running, the backend stops after {duration} idle.": "If kept running, the backend stops after {duration} idle.",
|
||||
"The host’s idle timeout is unavailable.": "The host’s idle timeout is unavailable.",
|
||||
"Checking the host’s idle timeout…": "Checking the host’s idle timeout…",
|
||||
"Set by OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS on {host}.": "Set by OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS on {host}.",
|
||||
"Your project is still running on {host}. This window will not reconnect automatically.": "Your project is still running on {host}. This window will not reconnect automatically.",
|
||||
"Reconnecting takes over the remote session and disconnects the other window.": "Reconnecting takes over the remote session and disconnects the other window.",
|
||||
"Reconnecting disconnects the other window. Unsaved edits in {count} files in this window may be lost.": "Reconnecting disconnects the other window. Unsaved edits in {count} files in this window may be lost.",
|
||||
"Stops the remote IDE backend and its terminals, runs and agent sessions, then closes the project.": "Stops the remote IDE backend and its terminals, runs and agent sessions, then closes the project.",
|
||||
"Stop the IDE backend on {host} and terminate its running terminals, runs and agent sessions?": "Stop the IDE backend on {host} and terminate its running terminals, runs and agent sessions?",
|
||||
"Connects this window to its remote project again after the connection was lost.": "Connects this window to its remote project again after the connection was lost.",
|
||||
"Reconnecting opens the project again. Unsaved changes in {count} files can't be saved to {host} and will be lost.": "Reconnecting opens the project again. Unsaved changes in {count} files can't be saved to {host} and will be lost.",
|
||||
"Reconnecting to {host}…": "Reconnecting to {host}…",
|
||||
|
||||
@@ -9284,6 +9284,40 @@
|
||||
"Lost the connection to {host}": "与 {host} 的连接已断开",
|
||||
"Reconnect": "重新连接",
|
||||
"Reconnect to Remote Host": "重新连接远程主机",
|
||||
"Stop Remote Backend": "停止远程后端",
|
||||
"Stop Backend": "停止后端",
|
||||
"Close Remote Development Window": "关闭远程开发窗口",
|
||||
"Keep Backend Running": "保持后端运行",
|
||||
"Keep the IDE backend on {host} running so you can reconnect later, or stop it and end its terminals, runs and agent tasks.": "保持 {host} 上的 IDE 后端运行以便稍后重新连接,或停止后端并结束其终端、运行配置和智能体任务。",
|
||||
"Could not stop the remote backend": "无法停止远程后端",
|
||||
"Another window took over this remote session": "另一个窗口已接管此远程会话",
|
||||
"Remote backend": "远程后端",
|
||||
"Idle timeout": "空闲超时",
|
||||
"Open Settings in a remote project window to change its backend timeout.": "请在远程项目窗口中打开设置,修改后端的空闲超时。",
|
||||
"Reconnect to the remote host to change its backend timeout.": "请先重新连接远程主机,再修改后端的空闲超时。",
|
||||
"This backend does not support a configurable idle timeout.": "此后端不支持设置空闲超时。",
|
||||
"Stop backend when idle": "空闲时停止后端",
|
||||
"Custom duration": "自定义时长",
|
||||
"Duration unit": "时长单位",
|
||||
"Minutes": "分钟",
|
||||
"Hours": "小时",
|
||||
"Days": "天",
|
||||
"Custom…": "自定义…",
|
||||
"After {duration} (default)": "{duration}后(默认)",
|
||||
"After {duration}": "{duration}后",
|
||||
"Enter a duration equivalent to 1–65,535 whole minutes.": "请输入相当于 1 至 65,535 个整分钟的时长。",
|
||||
"The timer starts when the last window disconnects from {host} and no terminals, runs, debug sessions, or agent tasks are active.": "当最后一个窗口断开与 {host} 的连接,且没有活动的终端、运行配置、调试会话或智能体任务时,开始计时。",
|
||||
"Idle shutdown is off on {host}. You can still stop the backend manually.": "{host} 上已关闭空闲自动停止。你仍可手动停止后端。",
|
||||
"Idle shutdown is off on {host}.": "{host} 上已关闭空闲自动停止。",
|
||||
"If kept running, the backend stops after {duration} idle.": "如果保持运行,后端将在空闲{duration}后停止。",
|
||||
"The host’s idle timeout is unavailable.": "无法获取主机的空闲超时。",
|
||||
"Checking the host’s idle timeout…": "正在获取主机的空闲超时…",
|
||||
"Set by OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS on {host}.": "此值由 {host} 上的 OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS 指定。",
|
||||
"Your project is still running on {host}. This window will not reconnect automatically.": "项目仍在 {host} 上运行。此窗口不会自动重新连接。",
|
||||
"Reconnecting takes over the remote session and disconnects the other window.": "重新连接会接管远程会话并断开另一个窗口的连接。",
|
||||
"Reconnecting disconnects the other window. Unsaved edits in {count} files in this window may be lost.": "重新连接会断开另一个窗口的连接。此窗口中 {count} 个文件的未保存修改可能会丢失。",
|
||||
"Stops the remote IDE backend and its terminals, runs and agent sessions, then closes the project.": "停止远程 IDE 后端及其终端、运行和智能体会话,然后关闭项目。",
|
||||
"Stop the IDE backend on {host} and terminate its running terminals, runs and agent sessions?": "要停止 {host} 上的 IDE 后端并终止其正在运行的终端、运行和智能体会话吗?",
|
||||
"Connects this window to its remote project again after the connection was lost.": "连接断开后,让此窗口重新连接到其远程项目。",
|
||||
"Reconnecting opens the project again. Unsaved changes in {count} files can't be saved to {host} and will be lost.": "重新连接会重新打开项目。{count} 个文件中未保存的更改无法保存到 {host},将会丢失。",
|
||||
"Reconnecting to {host}…": "正在重新连接到 {host}…",
|
||||
|
||||
@@ -211,6 +211,7 @@
|
||||
"menu.file.openFile": "打开文件…",
|
||||
"menu.remote.connect": "远程开发…",
|
||||
"menu.remote.disconnect": "断开与远程主机的连接",
|
||||
"menu.remote.stopBackend": "停止远程后端",
|
||||
"menu.navigationBar": "导航栏",
|
||||
"menu.run.updateApplication": "更新应用",
|
||||
"menu.ssh.startSession": "启动 SSH 会话…",
|
||||
|
||||
@@ -28,11 +28,17 @@ interface RemoteState {
|
||||
session: RemoteSession | null;
|
||||
/** The host the connection was lost to (the window's project is unreachable), else null. */
|
||||
lost: string | null;
|
||||
takenOver: boolean;
|
||||
/** A reconnection to the lost host is in progress. */
|
||||
reconnecting: boolean;
|
||||
}
|
||||
|
||||
export const useRemote = create<RemoteState>(() => ({ session: null, lost: null, reconnecting: false }));
|
||||
export const useRemote = create<RemoteState>(() => ({
|
||||
session: null,
|
||||
lost: null,
|
||||
takenOver: false,
|
||||
reconnecting: false,
|
||||
}));
|
||||
|
||||
let routed = new Set<string>();
|
||||
let nextChannel = 1;
|
||||
@@ -84,22 +90,24 @@ async function remoteInvoke(cmd: string, args?: InvokeArgs, options?: InvokeOpti
|
||||
return value;
|
||||
}
|
||||
|
||||
function isRemoteHostOnlySetting(key: string): boolean {
|
||||
function isMcpServerSetting(key: string): boolean {
|
||||
return key === "mcpServer" || key.startsWith("mcpServer.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a command of a remote window runs. Local always: opening a project (a
|
||||
* local folder; leaving the remote one) and closing it (that drops the
|
||||
* connection, which ends the server's session). Client UI settings stay local.
|
||||
* Host-specific service settings (`mcpServer.*`) apply to the remote host only;
|
||||
* connection, not the backend). Client UI settings stay local.
|
||||
* Host-specific service settings apply to the remote host only;
|
||||
* other global tooling settings apply on both sides.
|
||||
*/
|
||||
export function remoteRouting(cmd: string, args: InvokeArgs | undefined, served: ReadonlySet<string>) {
|
||||
const key = (args as { key?: string } | undefined)?.key ?? "";
|
||||
if (cmd === "settings_set" && (key === "remoteDevelopment" || key.startsWith("remoteDevelopment."))) return "remote";
|
||||
if (cmd === "system_font_families") return "local";
|
||||
if (cmd === "settings_set" && isClientSetting((args as { key?: string } | undefined)?.key ?? "")) return "local";
|
||||
if (cmd === "settings_set" && isClientSetting(key)) return "local";
|
||||
if (!served.has(cmd) || cmd === "open_project" || cmd === "close_project") return "local";
|
||||
if (cmd === "settings_set" && isRemoteHostOnlySetting((args as { key?: string } | undefined)?.key ?? "")) {
|
||||
if (cmd === "settings_set" && isMcpServerSetting(key)) {
|
||||
return served.has("mcp_server_status") ? "remote" : "local";
|
||||
}
|
||||
if (cmd === "settings_set" && (args as { scope?: string } | undefined)?.scope === "global") return "both";
|
||||
@@ -153,14 +161,15 @@ const route: InvokeRoute = (cmd, args, options) => {
|
||||
*/
|
||||
export function enableRemote(session: RemoteSession) {
|
||||
routed = new Set(session.commands);
|
||||
const takenOver = session.takenOver === true;
|
||||
setInvokeRoute(route);
|
||||
useRemote.setState({ session, lost: null, reconnecting: false });
|
||||
useRemote.setState({ session, lost: takenOver ? session.host : null, takenOver, reconnecting: false });
|
||||
}
|
||||
|
||||
export function disableRemote() {
|
||||
routed = new Set();
|
||||
setInvokeRoute(null);
|
||||
useRemote.setState({ session: null, lost: null, reconnecting: false });
|
||||
useRemote.setState({ session: null, lost: null, takenOver: false, reconnecting: false });
|
||||
}
|
||||
|
||||
export function isRemoteWindow(): boolean {
|
||||
@@ -193,7 +202,14 @@ export const useRemoteProgress = create<{ progress: RemoteProgress | null; locat
|
||||
|
||||
/** Routes this window to the server `remoteConnect` answered with and shows its project. */
|
||||
async function attachRemote(r: RemoteProject, path: string): Promise<void> {
|
||||
enableRemote({ target: r.target, root: r.root, host: r.host, os: r.os, commands: r.commands });
|
||||
enableRemote({
|
||||
target: r.target,
|
||||
root: r.root,
|
||||
host: r.host,
|
||||
os: r.os,
|
||||
commands: r.commands,
|
||||
idlePolicy: r.idlePolicy,
|
||||
});
|
||||
if (takeLegacyRemoteTrust(r.target, path, r.host)) {
|
||||
const status = await call(commands.projectTrustStatus(r.root));
|
||||
if (!status.decided) await call(commands.projectTrustSet(r.root, true, false));
|
||||
@@ -254,9 +270,7 @@ export async function connectRemote(target: RemoteTarget, path: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects this window to its remote project again after the connection was lost. The new server
|
||||
* has none of the old one's documents, terminals or sessions, so the window opens its project
|
||||
* again (editors come back from their saved tabs), as reopening the remote project would.
|
||||
* Opens the project again, reattaching to its existing backend if it is still running.
|
||||
*/
|
||||
export async function reconnectRemote(): Promise<void> {
|
||||
const session = useRemote.getState().session;
|
||||
@@ -278,6 +292,18 @@ export async function disconnectRemote() {
|
||||
useProject.setState({ project: null });
|
||||
}
|
||||
|
||||
/** Shuts down the remote `openidea-server` daemon and its processes, then closes the window's project. */
|
||||
export async function stopRemoteBackend() {
|
||||
if (!isRemoteWindow()) return;
|
||||
await shutdownRemoteBackend();
|
||||
await disconnectRemote();
|
||||
}
|
||||
|
||||
/** Stops the backend without deciding what to do with the desktop window. */
|
||||
export async function shutdownRemoteBackend() {
|
||||
await call(commands.remoteStopBackend());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Remote project locations: `ssh://<configuration id>/<absolute path>`,
|
||||
// `wsl://<distribution>/<absolute path>` or `devcontainer://<local folder>[:<config>]/<container path>`,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useI18n } from "./i18n";
|
||||
|
||||
export const DEFAULT_REMOTE_IDLE_MINUTES = 180;
|
||||
export const MAX_REMOTE_IDLE_MINUTES = 65535;
|
||||
|
||||
/** Zero is an explicit Never, not the fallback for malformed or missing settings. */
|
||||
export function validRemoteIdleMinutes(value: unknown): number {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_REMOTE_IDLE_MINUTES
|
||||
? value
|
||||
: DEFAULT_REMOTE_IDLE_MINUTES;
|
||||
}
|
||||
|
||||
/** Use the largest whole unit so neither a saved minute nor a host-enforced second gets rounded. */
|
||||
export function formatIdleDuration(seconds: number): string {
|
||||
const [unit, scale] =
|
||||
seconds % 86400 === 0
|
||||
? (["day", 86400] as const)
|
||||
: seconds % 3600 === 0
|
||||
? (["hour", 3600] as const)
|
||||
: seconds % 60 === 0
|
||||
? (["minute", 60] as const)
|
||||
: (["second", 1] as const);
|
||||
return new Intl.NumberFormat(useI18n.getState().locale, { style: "unit", unit, unitDisplay: "long" }).format(
|
||||
seconds / scale,
|
||||
);
|
||||
}
|
||||
@@ -162,6 +162,17 @@ describe("remote client settings", () => {
|
||||
expect(remoteRouting("settings_set", { scope: "project", key }, served)).toBe("remote");
|
||||
expect(remoteRouting("settings_set", { scope: "global", key }, served)).toBe("both");
|
||||
});
|
||||
it("writes the backend idle timeout only on the remote host, regardless of MCP support", async () => {
|
||||
const args = { scope: "global", key: "remoteDevelopment.idleTimeoutMinutes", value: "45" };
|
||||
await call(commands.settingsSet("global", args.key, args.value));
|
||||
const writes = invoke.mock.calls.filter(
|
||||
([cmd, params]) =>
|
||||
cmd === "settings_set" || (cmd === "remote_invoke" && (params as { cmd: string }).cmd === "settings_set"),
|
||||
);
|
||||
expect(writes.map(([cmd, params]) => [cmd, params])).toEqual([
|
||||
["remote_invoke", expect.objectContaining({ cmd: "settings_set", args: JSON.stringify(args) })],
|
||||
]);
|
||||
});
|
||||
it("routes mcpServer settings and MCP commands to the remote host without mutating local MCP settings", async () => {
|
||||
const withMcp = new Set([...served, "settings_get_global", "mcp_server_status", "mcp_ui_ready", "mcp_respond"]);
|
||||
enableRemote({
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { openPolicy } from "./projectWindow";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { isRemoteWindow, useRemote } from "@/platform/remote";
|
||||
import { isRemoteWindow, projectLocation, useRemote } from "@/platform/remote";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
provideNotificationService,
|
||||
@@ -42,25 +42,29 @@ export function activateWorkbench(): () => void {
|
||||
const syncProjectContext = () => {
|
||||
const project = useProject.getState().project;
|
||||
setContext("projectLocal", !!project && !isRemoteWindow() && !useProject.getState().lightEdit);
|
||||
setContext("projectRemote", !!project && isRemoteWindow());
|
||||
setContext("workspaceOpen", !!project?.workspace);
|
||||
setContext("projectAttached", !!project?.workspace && project.workspace.projects[0] === project.root);
|
||||
setContext("workspaceContainer", !!project?.workspace && project.workspace.projects[0] !== project.root);
|
||||
setContext("projectOpenAsk", openPolicy() === "ask");
|
||||
};
|
||||
// Synchronous so the frame's first render after opening already has the project's layout.
|
||||
const onProject = (root: string | null) => {
|
||||
setContext("projectOpen", root !== null);
|
||||
let prevLocation = projectLocation(useProject.getState().project?.root);
|
||||
const onProject = (scope: string | null) => {
|
||||
setContext("projectOpen", scope !== null);
|
||||
syncProjectContext();
|
||||
setContext("lightEdit", useProject.getState().lightEdit);
|
||||
if (root !== null) loadToolWindowLayout(root);
|
||||
if (scope !== null) loadToolWindowLayout(scope);
|
||||
};
|
||||
onProject(useProject.getState().project?.root ?? null);
|
||||
onProject(prevLocation);
|
||||
const unsubProject = useProject.subscribe((s, prev) => {
|
||||
syncProjectContext();
|
||||
if (s.project?.root === prev.project?.root && s.lightEdit === prev.lightEdit) return;
|
||||
const nextLocation = projectLocation(s.project?.root);
|
||||
if (nextLocation === prevLocation && s.lightEdit === prev.lightEdit) return;
|
||||
prevLocation = nextLocation;
|
||||
// The previous project's notifications (and their actions) no longer apply.
|
||||
if (prev.project) clearProjectNotifications();
|
||||
onProject(s.project?.root ?? null);
|
||||
onProject(nextLocation);
|
||||
});
|
||||
|
||||
const disposers = [
|
||||
|
||||
@@ -795,6 +795,8 @@ export interface EditorService {
|
||||
forgetSavedTabs?(): void;
|
||||
/** Writes them again when a close is cancelled after {@link forgetSavedTabs}. */
|
||||
keepSavedTabs?(): void;
|
||||
/** Flushes the open editor tabs, splits and caret positions to storage immediately. */
|
||||
flushSession?(): void;
|
||||
/** Edit › Undo / Redo for a focused custom editor that has its own history; false when none takes it. */
|
||||
documentHistory?(command: "undo" | "redo"): boolean;
|
||||
/** Go to Declaration's chooser ("Choose Declaration of `name`") over `targets`, below `anchor`. */
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import { create } from "zustand";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { parseRemoteLocation } from "@/platform/remote";
|
||||
import {
|
||||
useContributions,
|
||||
type ToolWindowAnchor,
|
||||
@@ -241,7 +242,8 @@ function storageKey(scope: string) {
|
||||
|
||||
function readStorage(scope: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(storageKey(scope));
|
||||
const legacy = parseRemoteLocation(scope)?.path;
|
||||
const raw = localStorage.getItem(storageKey(scope)) ?? (legacy ? localStorage.getItem(storageKey(legacy)) : null);
|
||||
const v: unknown = raw ? JSON.parse(raw) : null;
|
||||
return v && typeof v === "object" ? (v as Record<string, unknown>) : null;
|
||||
} catch {
|
||||
|
||||
Reference in new issue
Заблокувати користувача