From e7ae3f5516dee169aed4598cd8f4c9c89725c785 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 11:47:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(remote):=20server.state=20=E6=8A=A5?= =?UTF-8?q?=E5=91=8A=E8=B5=84=E6=BA=90=E6=A0=87=E7=AD=BE=E3=80=81=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E6=97=B6=E9=95=BF=E5=92=8C=E7=BB=88=E7=AB=AF=E5=AE=9E?= =?UTF-8?q?=E9=99=85=E5=91=BD=E4=BB=A4=EF=BC=88#2231=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 关闭窗口时要逐项确认远端还在运行的进程和终端(#2231 §9.1:类型、名称、命令原样、运行时长),下次连接要列出上次留下的进程(§9.2)。这些信息必须由服务端保存:换一台机器、重启客户端或客户端崩溃后,本地记录都会丢失。 协议:process.spawn 和 terminal.open 新增可选 label(kind ≤ 64 字符、name ≤ 256 字符、不含控制字符),服务端原样保存、不解释,违反规则返回 INVALID_REQUEST 且不启动任何程序;server.state 的进程和终端条目新增 label 和 runningMs(服务端单调时钟,不受客户端重启和两台机器时钟差的影响,同一次回复用同一时刻计算),终端条目新增 argv(请求的 argv,或默认登录 shell 的路径)。旧客户端不传 label 时照常工作。 客户端:SpawnSpec 和 TerminalSpec 新增 label。workspace 的 remote.hostRequest 允许 server.state(只读,不创建资源),桌面端才能在关闭前读取。 crates/remote 之外只有两处改动:lsp-transport 和 git 的 SpawnParams 字面量补 label: None;workspace host 允许列表加一行。 测试:标签字数上限(按字符计)与控制字符规则、运行时长取整与时钟回退;集成测试覆盖带标签和不带标签的进程、runningMs 不超过测试自己测得的时长、三种无效标签都返回 INVALID_REQUEST 且命令没有执行、终端报告实际命令和标签。 --- .../contracts/remote-workspace-protocol-v1.md | 16 +++- rust/contracts/rust-core-api.md | 8 +- rust/crates/git/src/remote_process.rs | 2 + .../lsp-transport/src/remote_process.rs | 1 + rust/crates/remote/src/client/api.rs | 18 ++-- rust/crates/remote/src/protocol/methods.rs | 46 ++++++++++ rust/crates/remote/src/server/process.rs | 57 ++++++++++-- rust/crates/remote/src/server/resources.rs | 67 +++++++++++++- rust/crates/remote/src/server/session.rs | 9 +- rust/crates/remote/src/server/terminal.rs | 25 ++++-- rust/crates/remote/tests/persistence.rs | 2 + rust/crates/remote/tests/processes.rs | 87 ++++++++++++++++++- rust/crates/remote/tests/terminals.rs | 29 +++++++ rust/crates/workspace/src/host.rs | 2 + 14 files changed, 340 insertions(+), 29 deletions(-) diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index 02008d0c..1c64939e 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -108,7 +108,7 @@ subscribe before creating the resource. | `server.ack` | `seq` | `null`; events up to `seq` may be forgotten | | `server.shutdown` | — | `null`; the session ends | | `server.ping` | — | `{}` | -| `server.state` | — | running `processes`, `terminals`, `watches` | +| `server.state` | — | running `processes` (`processId`, `pid`, `argv`, `label?`, `runningMs`, `leaderExited`), `terminals` (`terminalId`, `pid`, `argv`, `label?`, `runningMs`, `columns`, `rows`), `watches` | | `fs.stat` | `path` | metadata of the path itself (links not followed) | | `fs.readDir` | `path` | `entries` sorted by name byte order, `skippedNonUtf8` | | `fs.readFile` | `path`, `offset`, `length` (≤ 8 MiB) | `data`, `eof`, `metadata` | @@ -131,11 +131,11 @@ subscribe before creating the resource. | `walk.cancel` | `walkId` | `null` | | `watch.start` | `watchId`, `root`, `excludeNames` | `watchedDirectories` (per-directory backends) | | `watch.stop` | `watchId` | `null` | -| `process.spawn` | `processId`, `argv`, `cwd?`, `environment` (`server` / `login`), `env`, `pipeStdin` | `pid` | +| `process.spawn` | `processId`, `argv`, `cwd?`, `environment` (`server` / `login`), `env`, `pipeStdin`, `label?` | `pid` | | `process.writeStdin` | `processId`, `data` | `null`; `BUSY` when the process stops reading | | `process.closeStdin` | `processId` | `null` | | `process.kill` | `processId`, `force` | `null`; signals every process of its session, also after `process.exit` while members run; `UNKNOWN_RESOURCE` once the session is empty | -| `terminal.open` | `terminalId`, `argv?`, `cwd?`, `env`, `columns`, `rows` | `pid`; default program is the login shell | +| `terminal.open` | `terminalId`, `argv?`, `cwd?`, `env`, `columns`, `rows`, `label?` | `pid`; default program is the login shell | | `terminal.write` | `terminalId`, `data` | `null`; `BUSY` when not read | | `terminal.resize` | `terminalId`, `columns`, `rows` | `null` | | `terminal.close` | `terminalId` | `null`; `SIGHUP` to its session, `SIGKILL` after 2 s | @@ -215,6 +215,16 @@ its session until no member is left, so members that outlive the leader can still be killed and are cleaned up when the session ends; `server.state` marks such processes with `leaderExited`. +`server.state` lets a client list what still runs before it closes a window, +and lets a later client list what an earlier one left running. `label` +(`kind` ≤ 64 characters, `name` ≤ 256 characters, no control characters) +is what the client shows for the resource; the server stores it unchanged, +never interprets it, and refuses a label that breaks a rule with +`INVALID_REQUEST` before starting anything. `runningMs` counts from the +start on the server's monotonic clock, so it is right after a client +restart and whatever the clients' clocks say. A terminal's `argv` is the +program actually started: the requested `argv`, or the login shell's path. + When a session ends, the server terminates everything it still owns (`SIGTERM` or `SIGHUP`, then `SIGKILL` after 2 seconds to sessions that still have members), lets running requests finish for up to 5 seconds, and exits. diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c7043843..6ec2bab1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5727,8 +5727,8 @@ the remote server running. Requests over it take `sessionId`: | `remote.hostInfo` | `{ sessionId }` | the original connection's handshake `host`, including OS, architecture, home and features | | `remote.uploadFile` | `{ sessionId, sourcePath, path, sha256, mode }` | verified `{ size, sha256 }` | | `remote.runWatch` | `{ sessionId, params: { root, excludeNames? } }` | waits until root removal or cancellation; relays `watch.started`, `watch.changed`, `watch.error` | -| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` | -| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` | +| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin?, label? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` | +| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows, label? } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` | | `remote.captureProcess` | `{ sessionId, params, timeoutMilliseconds, maxOutputBytes }` | base64 `stdout`, `stderr`, nullable `exitCode` and `signal` | `remote.writeFile` replaces the file atomically on the host. With @@ -5739,7 +5739,9 @@ fails with `connection_closed` and is forgotten, so the host reconnects; an unknown or closed `sessionId` is also `connection_closed`. `remote.hostRequest` accepts finite filesystem, environment and port queries, -plus controls of existing processes and terminals. Creating a watch, process, +`server.state` (what still runs, with the `label` given at start, so the host +can ask before closing a window), plus controls of existing processes and +terminals. Creating a watch, process, terminal, walk or tunnel through that command is `invalid_request`; creation requires an owner that subscribes before sending the start request. Streamed Core events use `{ type: "remote", event, params }`. Resource IDs are allocated diff --git a/rust/crates/git/src/remote_process.rs b/rust/crates/git/src/remote_process.rs index 15460c2a..b307507f 100644 --- a/rust/crates/git/src/remote_process.rs +++ b/rust/crates/git/src/remote_process.rs @@ -212,6 +212,7 @@ pub(super) fn parameters( environment: EnvironmentSource::Login, env, pipe_stdin, + label: None, }) } @@ -278,6 +279,7 @@ fn remote_git_executable( environment: EnvironmentSource::Login, env: BTreeMap::new(), pipe_stdin: false, + label: None, }, None, &mut |event| { diff --git a/rust/crates/lsp-transport/src/remote_process.rs b/rust/crates/lsp-transport/src/remote_process.rs index 1d45a6fe..77a27fde 100644 --- a/rust/crates/lsp-transport/src/remote_process.rs +++ b/rust/crates/lsp-transport/src/remote_process.rs @@ -474,6 +474,7 @@ pub(crate) fn launch(host: Host, spec: LspProcessSpec) -> Result, /// Keep standard input open for [`ProcessHandle::write_stdin`]. pub pipe_stdin: bool, + /// What [`RemoteSession::state`] reports for the process. + pub label: Option, } /// What to open in [`RemoteSession::open_terminal`]. @@ -80,6 +82,8 @@ pub struct TerminalSpec { pub columns: u16, /// Initial height in character cells. pub rows: u16, + /// What [`RemoteSession::state`] reports for the terminal. + pub label: Option, } /// A finished process's collected output. @@ -386,6 +390,7 @@ impl RemoteSession { environment: spec.environment, env: spec.env, pipe_stdin: spec.pipe_stdin, + label: spec.label, }, ); match result { @@ -415,6 +420,7 @@ impl RemoteSession { env: spec.env, columns: spec.columns, rows: spec.rows, + label: spec.label, }, ); match result { diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 572e3be7..b3ba4efa 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -476,6 +476,13 @@ pub struct ProcessState { pub pid: u32, /// Program and arguments the process was spawned with. pub argv: Vec, + /// The label the process was spawned with. + #[serde(default)] + pub label: Option, + /// Milliseconds since the server started the process, on the server's + /// monotonic clock, so it stays right across client restarts and clock + /// differences between the machines. + pub running_ms: u64, /// The process itself exited, but members of its session still run; /// `process.kill` still reaches them. pub leader_exited: bool, @@ -489,12 +496,45 @@ pub struct TerminalState { pub terminal_id: u64, /// Operating-system pid of the terminal's program, for diagnostics only. pub pid: u32, + /// Program and arguments the terminal runs: those it was opened with, + /// or the path of the login shell it started by default. + pub argv: Vec, + /// The label the terminal was opened with. + #[serde(default)] + pub label: Option, + /// Milliseconds since the server started the terminal's program, on the + /// server's monotonic clock. + pub running_ms: u64, /// Current width in character cells. pub columns: u16, /// Current height in character cells. pub rows: u16, } +/// Longest [`ResourceLabel::kind`], in characters. +pub const MAX_LABEL_KIND_CHARS: usize = 64; +/// Longest [`ResourceLabel::name`], in characters. +pub const MAX_LABEL_NAME_CHARS: usize = 256; + +/// What a client shows for a process or terminal when it lists the session's +/// resources: when a window closes while they still run, or after a new +/// client reconnects to a persistent session and no longer knows what it +/// started. The server keeps it unchanged with the resource and returns it in +/// `server.state`; it never interprets it. +/// +/// Neither field may contain control characters; a label that breaks a rule +/// fails the request with `INVALID_REQUEST`. +#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ResourceLabel { + /// Client-defined category, such as `run`, `task` or `debug`; at most + /// [`MAX_LABEL_KIND_CHARS`]. + pub kind: String, + /// Name shown to the user, such as a run configuration's name; at most + /// [`MAX_LABEL_NAME_CHARS`]. + pub name: String, +} + /// An active watch. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -945,6 +985,9 @@ pub struct SpawnParams { /// process reads end-of-file immediately. #[serde(default)] pub pipe_stdin: bool, + /// What `server.state` reports for the process. + #[serde(default)] + pub label: Option, } /// Result of `process.spawn`. @@ -1046,6 +1089,9 @@ pub struct TerminalOpenParams { pub columns: u16, /// Initial height in character cells. pub rows: u16, + /// What `server.state` reports for the terminal. + #[serde(default)] + pub label: Option, } /// Result of `terminal.open`. diff --git a/rust/crates/remote/src/server/process.rs b/rust/crates/remote/src/server/process.rs index d764c595..ddf05f3c 100644 --- a/rust/crates/remote/src/server/process.rs +++ b/rust/crates/remote/src/server/process.rs @@ -11,14 +11,14 @@ use crate::protocol::methods::{ self, decode_bytes, encode_bytes, EnvironmentSource, KillParams, OutputStream, - ProcessExitEvent, ProcessOutputEvent, ProcessParams, ProcessState, SpawnParams, SpawnResult, - WriteStdinParams, + ProcessExitEvent, ProcessOutputEvent, ProcessParams, ProcessState, ResourceLabel, SpawnParams, + SpawnResult, WriteStdinParams, }; use crate::protocol::{ErrorCode, RemoteError}; use crate::server::connection::Context; use crate::server::fs::{host_path, io_error}; use crate::server::platform::{self, ChildKind}; -use crate::server::resources::Registry; +use crate::server::resources::{validate_label, Registry}; use crate::server::session::Session; use crate::server::threads::Parked; use crate::server::{parse, to_value}; @@ -56,11 +56,23 @@ pub(crate) struct Leader { pub(crate) pid: u32, /// Set when the leader exited and its exit event was sent. pub(crate) exited: bool, + /// When the server started the leader. + started: Instant, } impl Leader { pub(crate) fn new(pid: u32) -> Self { - Self { pid, exited: false } + Self { + pid, + exited: false, + started: Instant::now(), + } + } + + /// Whole milliseconds from the leader's start to `now`, the moment + /// `server.state` reads every entry at. + pub(crate) fn running_ms(&self, now: Instant) -> u64 { + u64::try_from(now.saturating_duration_since(self.started).as_millis()).unwrap_or(u64::MAX) } } @@ -100,6 +112,7 @@ pub(crate) struct ProcessTable { struct RunningProcess { leader: Leader, argv: Vec, + label: Option, /// `None` when standard input was not piped or has been closed. stdin: Option>>, } @@ -129,7 +142,7 @@ impl ProcessTable { } } - pub(crate) fn states(&self) -> Vec { + pub(crate) fn states(&self, now: Instant) -> Vec { self.registry .lock() .iter() @@ -137,6 +150,8 @@ impl ProcessTable { process_id: *process_id, pid: process.leader.pid, argv: process.argv.clone(), + label: process.label.clone(), + running_ms: process.leader.running_ms(now), leader_exited: process.leader.exited, }) .collect() @@ -153,6 +168,7 @@ impl ProcessTable { let Some((program, arguments)) = params.argv.split_first() else { return Err(RemoteError::new(ErrorCode::InvalidRequest, "argv is empty")); }; + validate_label(params.label.as_ref())?; let mut command = Command::new(program); command .args(arguments) @@ -192,6 +208,7 @@ impl ProcessTable { let entry = RunningProcess { leader: Leader::new(pid), argv: params.argv.clone(), + label: params.label, stdin, }; if let Err(error) = self.registry.insert(params.process_id, entry) { @@ -545,3 +562,33 @@ impl OutputGate { exit(); } } + +#[cfg(test)] +mod tests { + use super::Leader; + use std::time::{Duration, Instant}; + + fn started_at(started: Instant) -> Leader { + Leader { + pid: 1, + exited: false, + started, + } + } + + #[test] + fn running_time_counts_whole_milliseconds_since_the_start() { + let started = Instant::now(); + let leader = started_at(started); + assert_eq!(leader.running_ms(started), 0); + assert_eq!(leader.running_ms(started + Duration::from_micros(1_999)), 1); + assert_eq!(leader.running_ms(started + Duration::from_secs(90)), 90_000); + } + + #[test] + fn running_time_is_never_negative() { + let started = Instant::now(); + let leader = started_at(started + Duration::from_secs(1)); + assert_eq!(leader.running_ms(started), 0); + } +} diff --git a/rust/crates/remote/src/server/resources.rs b/rust/crates/remote/src/server/resources.rs index 68b98d30..b5934565 100644 --- a/rust/crates/remote/src/server/resources.rs +++ b/rust/crates/remote/src/server/resources.rs @@ -1,5 +1,6 @@ //! Shared bookkeeping for client-identified resources. +use crate::protocol::methods::{ResourceLabel, MAX_LABEL_KIND_CHARS, MAX_LABEL_NAME_CHARS}; use crate::protocol::{ErrorCode, RemoteError}; use serde_json::Value; use std::collections::BTreeMap; @@ -289,11 +290,75 @@ impl InFlight { } } +/// Checks a client's label against the protocol's limits before the resource +/// starts. The error names the field that broke a rule, never its content. +pub(crate) fn validate_label(label: Option<&ResourceLabel>) -> Result<(), RemoteError> { + let Some(label) = label else { + return Ok(()); + }; + for (field, value, limit) in [ + ("kind", &label.kind, MAX_LABEL_KIND_CHARS), + ("name", &label.name, MAX_LABEL_NAME_CHARS), + ] { + if value.chars().count() > limit { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + format!("label {field} is longer than {limit} characters"), + )); + } + if value.chars().any(char::is_control) { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + format!("label {field} contains a control character"), + )); + } + } + Ok(()) +} + #[cfg(test)] mod tests { - use super::Registry; + use super::{validate_label, Registry}; + use crate::protocol::methods::{ResourceLabel, MAX_LABEL_KIND_CHARS, MAX_LABEL_NAME_CHARS}; use crate::protocol::ErrorCode; + fn label(kind: &str, name: &str) -> ResourceLabel { + ResourceLabel { + kind: kind.into(), + name: name.into(), + } + } + + #[test] + fn labels_within_the_limits_are_accepted() { + validate_label(None).unwrap(); + validate_label(Some(&label("run", "Server"))).unwrap(); + // The limits count characters, so a name in Chinese may use three + // times as many bytes. + validate_label(Some(&label( + &"k".repeat(MAX_LABEL_KIND_CHARS), + &"运".repeat(MAX_LABEL_NAME_CHARS), + ))) + .unwrap(); + } + + #[test] + fn labels_that_break_a_rule_are_invalid_requests() { + let long_kind = "k".repeat(MAX_LABEL_KIND_CHARS + 1); + let long_name = "运".repeat(MAX_LABEL_NAME_CHARS + 1); + for (rejected, field) in [ + (label(&long_kind, "Server"), "kind"), + (label("run", &long_name), "name"), + (label("run\n", "Server"), "kind"), + (label("run", "\u{1b}[31mServer"), "name"), + ] { + let error = validate_label(Some(&rejected)).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert!(error.message.contains(field), "{}", error.message); + assert!(!error.message.contains("Server"), "{}", error.message); + } + } + #[test] fn bounded_registries_refuse_starts_until_an_entry_ends() { let registry = Registry::bounded("tunnel", 2); diff --git a/rust/crates/remote/src/server/session.rs b/rust/crates/remote/src/server/session.rs index 9fb532f3..dd7d6e0d 100644 --- a/rust/crates/remote/src/server/session.rs +++ b/rust/crates/remote/src/server/session.rs @@ -14,7 +14,7 @@ use crate::server::watch::WatchTable; use std::io::Read; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; -use std::time::Duration; +use std::time::{Duration, Instant}; /// Default time a persistent session without a client and without running /// programs survives. @@ -213,10 +213,13 @@ impl Session { *crate::server::lock(&self.idle_timeout) } + /// Running times are measured to one moment, so entries of one reply + /// compare correctly. pub(crate) fn state(&self) -> ServerState { + let now = Instant::now(); ServerState { - processes: self.processes.states(), - terminals: self.terminals.states(), + processes: self.processes.states(now), + terminals: self.terminals.states(now), watches: self.watches.states(), } } diff --git a/rust/crates/remote/src/server/terminal.rs b/rust/crates/remote/src/server/terminal.rs index 39ed63f1..9969cb47 100644 --- a/rust/crates/remote/src/server/terminal.rs +++ b/rust/crates/remote/src/server/terminal.rs @@ -6,8 +6,9 @@ //! therefore behave as users expect. use crate::protocol::methods::{ - self, decode_bytes, encode_bytes, TerminalExitEvent, TerminalOpenParams, TerminalOpenResult, - TerminalOutputEvent, TerminalParams, TerminalResizeParams, TerminalState, TerminalWriteParams, + self, decode_bytes, encode_bytes, ResourceLabel, TerminalExitEvent, TerminalOpenParams, + TerminalOpenResult, TerminalOutputEvent, TerminalParams, TerminalResizeParams, TerminalState, + TerminalWriteParams, }; use crate::protocol::{ErrorCode, RemoteError}; use crate::server::connection::Context; @@ -17,7 +18,7 @@ use crate::server::process::{ exit_parts, has_exited_leaders, prune, queue_input, spawn_error, terminate_groups, Forward, InputWriter, Leader, Monitor, }; -use crate::server::resources::Registry; +use crate::server::resources::{validate_label, Registry}; use crate::server::session::{Session, TERMINATION_GRACE}; use crate::server::threads::Parked; use crate::server::{parse, to_value}; @@ -29,6 +30,7 @@ use std::path::Path; use std::process::{Command, Stdio}; use std::sync::mpsc::SyncSender; use std::sync::Arc; +use std::time::Instant; const DEFAULT_TERM: &str = "xterm-256color"; @@ -43,6 +45,9 @@ struct RunningTerminal { /// Kept after the shell exits while jobs it started still run, so that /// closing the terminal or ending the session still reaches them. leader: Leader, + /// The program actually started, including the default login shell. + argv: Vec, + label: Option, columns: u16, rows: u16, master: Arc, @@ -77,7 +82,7 @@ impl TerminalTable { } } - pub(crate) fn states(&self) -> Vec { + pub(crate) fn states(&self, now: Instant) -> Vec { self.registry .lock() .iter() @@ -85,6 +90,9 @@ impl TerminalTable { .map(|(terminal_id, terminal)| TerminalState { terminal_id: *terminal_id, pid: terminal.leader.pid, + argv: terminal.argv.clone(), + label: terminal.label.clone(), + running_ms: terminal.leader.running_ms(now), columns: terminal.columns, rows: terminal.rows, }) @@ -98,15 +106,16 @@ impl TerminalTable { ) -> Result { session.ids.observe(params.terminal_id); self.registry.ensure_free(params.terminal_id)?; + validate_label(params.label.as_ref())?; let account = platform::current_account(); - let mut command = match ¶ms.argv { + let (mut command, argv) = match ¶ms.argv { Some(argv) => { let Some((program, arguments)) = argv.split_first() else { return Err(RemoteError::new(ErrorCode::InvalidRequest, "argv is empty")); }; let mut command = Command::new(program); command.args(arguments); - command + (command, argv.clone()) } None => { let shell = account @@ -121,7 +130,7 @@ impl TerminalTable { .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| "sh".into()); command.arg0(format!("-{name}")); - command + (command, vec![shell]) } }; let directory = match ¶ms.cwd { @@ -166,6 +175,8 @@ impl TerminalTable { let pid = child.id(); let entry = RunningTerminal { leader: Leader::new(pid), + argv, + label: params.label, columns: params.columns, rows: params.rows, master, diff --git a/rust/crates/remote/tests/persistence.rs b/rust/crates/remote/tests/persistence.rs index cc5f068f..0d426526 100644 --- a/rust/crates/remote/tests/persistence.rs +++ b/rust/crates/remote/tests/persistence.rs @@ -103,6 +103,7 @@ fn terminals_can_be_reattached_after_reconnecting() { ]), columns: 80, rows: 24, + label: None, }) .unwrap(); // The answer is printed only after the test creates the gate file while @@ -334,6 +335,7 @@ fn open_terminals_keep_an_idle_session_alive() { env: BTreeMap::new(), columns: 80, rows: 24, + label: None, }) .unwrap(); let terminal_id = terminal.id; diff --git a/rust/crates/remote/tests/processes.rs b/rust/crates/remote/tests/processes.rs index f0f0ff22..40a0face 100644 --- a/rust/crates/remote/tests/processes.rs +++ b/rust/crates/remote/tests/processes.rs @@ -6,11 +6,12 @@ use lithe_remote::client::api::ProcessEvent; use lithe_remote::client::session::ClientError; use lithe_remote::client::SpawnSpec; use lithe_remote::protocol::methods::{ - self, EnvironmentSource, OutputStream, ResolvedEnvironmentSource, + self, EnvironmentSource, OutputStream, ResolvedEnvironmentSource, ResourceLabel, }; use lithe_remote::protocol::ErrorCode; use serde_json::json; use std::collections::BTreeMap; +use std::time::Instant; use support::{connect, connect_with_environment, wait_until_gone, TempDir, STEP_TIMEOUT}; fn argv(values: &[&str]) -> Vec { @@ -115,6 +116,90 @@ fn a_live_resource_id_cannot_be_reused() { session.shutdown(STEP_TIMEOUT); } +// Closing a window lists what still runs by the label its client gave and +// the time it has been running, also to a client that did not start it. +#[test] +fn state_reports_labels_and_running_time() { + let (session, _events) = connect(); + let label = ResourceLabel { + kind: "run".into(), + name: "Server".into(), + }; + let started = Instant::now(); + let labeled = session + .spawn(SpawnSpec { + argv: argv(&["sleep", "60"]), + label: Some(label.clone()), + ..SpawnSpec::default() + }) + .unwrap(); + let unlabeled = session + .spawn(SpawnSpec { + argv: argv(&["sleep", "60"]), + ..SpawnSpec::default() + }) + .unwrap(); + let state = session.state().unwrap(); + // The server started both after `started` and measured before this. + let elapsed = started.elapsed().as_millis(); + let find = |process_id| { + state + .processes + .iter() + .find(|running| running.process_id == process_id) + .unwrap() + }; + assert_eq!(find(labeled.id).label.as_ref(), Some(&label)); + assert_eq!(find(unlabeled.id).label, None); + for running in &state.processes { + assert!(u128::from(running.running_ms) <= elapsed); + } + for process in [labeled, unlabeled] { + process.kill(true).unwrap(); + process.wait(STEP_TIMEOUT).unwrap(); + } + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn a_label_that_breaks_a_rule_starts_nothing() { + let (session, _events) = connect(); + let directory = TempDir::new("rejected-label"); + let started = directory.join("started"); + let invalid = [ + ResourceLabel { + kind: "k".repeat(methods::MAX_LABEL_KIND_CHARS + 1), + name: "Server".into(), + }, + ResourceLabel { + kind: "run".into(), + name: "n".repeat(methods::MAX_LABEL_NAME_CHARS + 1), + }, + ResourceLabel { + kind: "run".into(), + name: "Server\n".into(), + }, + ]; + for label in invalid { + let result = session.spawn(SpawnSpec { + argv: argv(&["touch", &started]), + label: Some(label), + ..SpawnSpec::default() + }); + match result { + Err(ClientError::Remote(error)) => assert_eq!(error.code, ErrorCode::InvalidRequest), + Err(other) => panic!("expected INVALID_REQUEST, got {other:?}"), + Ok(_) => panic!("a process with an invalid label started"), + } + } + assert!(session.state().unwrap().processes.is_empty()); + assert!( + !std::path::Path::new(&started).exists(), + "the rejected command ran" + ); + session.shutdown(STEP_TIMEOUT); +} + #[test] fn disconnecting_a_stdio_session_terminates_its_processes() { let (session, events) = connect(); diff --git a/rust/crates/remote/tests/terminals.rs b/rust/crates/remote/tests/terminals.rs index aeffe44e..ed4cbae7 100644 --- a/rust/crates/remote/tests/terminals.rs +++ b/rust/crates/remote/tests/terminals.rs @@ -4,6 +4,7 @@ mod support; use lithe_remote::client::api::{TerminalEvent, TerminalHandle}; use lithe_remote::client::TerminalSpec; +use lithe_remote::protocol::methods::ResourceLabel; use std::collections::BTreeMap; use std::time::Instant; use support::{connect, wait_until_gone, STEP_TIMEOUT}; @@ -22,6 +23,7 @@ fn plain_shell() -> TerminalSpec { ]), columns: 100, rows: 40, + label: None, } } @@ -91,6 +93,33 @@ fn resizing_changes_the_size_programs_see() { session.shutdown(STEP_TIMEOUT); } +#[test] +fn state_reports_the_terminal_command_and_label() { + let (session, _events) = connect(); + let label = ResourceLabel { + kind: "terminal".into(), + name: "Local".into(), + }; + let terminal = session + .open_terminal(TerminalSpec { + label: Some(label.clone()), + ..plain_shell() + }) + .unwrap(); + let state = session.state().unwrap(); + let running = state + .terminals + .iter() + .find(|running| running.terminal_id == terminal.id) + .unwrap(); + assert_eq!(running.argv, ["/bin/sh"]); + assert_eq!(running.label.as_ref(), Some(&label)); + terminal.close().unwrap(); + read_until_exit(&terminal); + drop(terminal); + session.shutdown(STEP_TIMEOUT); +} + // Closing a terminal window hangs up the shell and its jobs. #[test] fn closing_hangs_up_the_shell_and_its_jobs() { diff --git a/rust/crates/workspace/src/host.rs b/rust/crates/workspace/src/host.rs index 2d7065c9..73534199 100644 --- a/rust/crates/workspace/src/host.rs +++ b/rust/crates/workspace/src/host.rs @@ -107,6 +107,7 @@ fn allowed_method(method: &str) -> bool { | methods::TERMINAL_RESIZE | methods::TERMINAL_CLOSE | methods::PORTS_LISTENING + | methods::SERVER_STATE ) } @@ -567,6 +568,7 @@ mod request_tests { methods::PROCESS_KILL, methods::TERMINAL_RESIZE, methods::TERMINAL_CLOSE, + methods::SERVER_STATE, ] { assert!(allowed_method(method), "{method}"); }