From 1f18c7a042a4ad0d9c324ac7928c7379b4e77265 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 02:20:38 +0800 Subject: [PATCH 1/3] feat(remote): keep or end host programs when a connection closes (Refs 1lck/Lithe-IDEA#2231) - remote.connect starts the persistent server session (--connect , --state-dir ) and returns sessionKey, sessionToken, resumed and keptPrograms; resume { key, token } attaches to a kept session, and a refused token connects once more with a new session. - server.keep: only programs the user chose to keep outlast the idle timeout; attaching clears an earlier keep, so a crashed client's programs end after ten minutes. - remote.disconnect takes programs: end|keep and returns { closed, kept }. - remote.runningPrograms and remote.endPrograms list and end what a host session still runs. - closePrograms preference (ask|end|keep, automatic asks) with closing in remote.preferences. - remote.session.state_failed log event; protocol and Core API docs. --- .../contracts/remote-workspace-protocol-v1.md | 14 +- rust/contracts/rust-core-api.md | 57 ++++- rust/crates/core/src/protocol/command.rs | 8 + .../core/src/runtime/dispatcher/remote.rs | 19 +- rust/crates/core/src/runtime/request_trace.rs | 2 + rust/crates/core/src/tests/remote_sessions.rs | 108 ++++++++ .../diagnostics/src/catalog_generated.rs | 15 +- rust/crates/remote/src/client/api.rs | 9 + rust/crates/remote/src/client/preferences.rs | 60 ++++- .../remote/src/client/preferences/tests.rs | 29 +++ rust/crates/remote/src/client/session.rs | 4 +- rust/crates/remote/src/protocol/methods.rs | 8 + rust/crates/remote/src/server/connection.rs | 5 + rust/crates/remote/src/server/daemon.rs | 9 +- rust/crates/remote/src/server/session.rs | 41 +++- rust/crates/remote/tests/persistence.rs | 65 ++++- rust/crates/workspace/src/lib.rs | 1 + rust/crates/workspace/src/preferences.rs | 26 +- .../crates/workspace/src/preferences/tests.rs | 34 +++ rust/crates/workspace/src/probe/tests.rs | 41 +++- rust/crates/workspace/src/programs.rs | 104 ++++++++ rust/crates/workspace/src/sessions.rs | 230 ++++++++++++++++-- rust/logging/events/remote.json | 22 +- 23 files changed, 841 insertions(+), 70 deletions(-) create mode 100644 rust/crates/workspace/src/programs.rs diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index 06681617..360eae2d 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -19,8 +19,9 @@ socket, lock and log under `` (default `$HOME/.lithe-server`) in directories only the user can access, and rejects peers with another user id. A session has one client at a time: a new connection that presents the session token (see below) replaces the current one. The idle timeout runs -only while the session has neither a client nor running processes or open -terminals; it is 10 minutes unless `server.hello` requests another with +while the session has no client, unless its last client sent `server.keep` +and the session still runs processes or open terminals; when it passes, the +session ends with everything it runs. It is 10 minutes unless `server.hello` requests another with `idleTimeoutSeconds`, at most 24 hours, and the latest request applies. A connection the daemon cannot set up is closed without ending the session. The daemon log is created `0600`, never through a symbolic link, and moves to @@ -119,6 +120,7 @@ subscribe before creating the resource. | `server.resume` | `afterSeq?` | `truncated`; then every kept event after `afterSeq`, followed by live events | | `server.ack` | `seq` | `null`; events up to `seq` may be forgotten | | `server.shutdown` | — | `null`; the session ends | +| `server.keep` | — | `null`; the running processes and terminals outlast this client; `UNSUPPORTED` on a `--stdio` session | | `server.ping` | — | `{}` | | `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) | @@ -327,7 +329,13 @@ events after `afterSeq` were dropped; the client re-reads state and rescans watches. While no client is attached, a persistent session keeps processes, terminals -and watches running. Tunnels, walks and listeners belong to the connection +and watches running until the idle timeout. A client whose user chose to +leave them running sends `server.keep` before it goes, without +`server.shutdown`; the session then outlasts the idle timeout while any of +its processes or terminals runs, and ends once none does. Each client that +attaches decides again: attaching clears an earlier `server.keep`. So the +programs of a client that crashed or lost its network end with the session +after the idle timeout, unless the user reconnects before it passes. Tunnels, walks and listeners belong to the connection that opened them and end with it. After `server.shutdown` a persistent session is no longer reachable, even while it is still terminating its processes; the next connection with the same key starts a fresh session. diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2a5454bc..c37c54c4 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -804,7 +804,7 @@ or removing a command fails until the table changes in the same commit. | `remote.authRespond` | Answer or cancel a prompt relayed by `remote.probe` or `remote.connect` once | | `remote.connect` | Open a connection over SSH or to a local WSL distribution, installing the shipped server when needed | | `remote.readDir` | List a directory over an open remote connection | -| `remote.disconnect` | Close an open connection and its OpenSSH or `wsl.exe` process tree | +| `remote.disconnect` | Close an open connection and its OpenSSH or `wsl.exe` process tree, ending or keeping the programs it runs on the host | | `remote.closeAll` | Close every open connection; the host calls it at application exit | | `remote.readFile` | Read a file over an open remote connection | | `remote.writeFile` | Save a file over an open remote connection | @@ -831,7 +831,9 @@ or removing a command fails until the table changes in the same commit. | `remote.mottyHosts` | List the SSH hosts saved in Motty for an import | | `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine | | `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to | -| `remote.editPreferences` | Set the SSH program, the reconnect limit or whether reverse forwards are allowed, or make one automatic again | +| `remote.editPreferences` | Set the SSH program, the reconnect limit, whether reverse forwards are allowed or what closing a connection does to its programs, or make one automatic again | +| `remote.runningPrograms` | List the processes and terminals a connection's host session still runs | +| `remote.endPrograms` | End every process and terminal a connection's host session runs | | `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation | | `git.remotes` | Return configured fetch remote names and URLs | | `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations | @@ -5940,7 +5942,8 @@ and returns `{ preferences, ssh, reconnect, reverseForwarding, storage, sshConfig? }`: - `preferences` is `{ sshProgram, reconnectLimitSeconds, - allowReverseForwarding }`, the stored values; `null` is automatic. + allowReverseForwarding, closePrograms }`, the stored values; `null` is + automatic. - `ssh` is `{ source, path, status }`, the OpenSSH client every connection starts. `source` is `setting` for a stored program and `automatic` otherwise, which is the first executable `ssh` (`ssh.exe` on Windows) in an @@ -5957,6 +5960,11 @@ sshConfig? }`: - `reverseForwarding` is `{ source, allowed }`: whether the ports page may start reverse forwards (automatic: not allowed), because every user of the host can reach the local port one opens. +- `closing` is `{ source, programs }`: what happens to the processes and + terminals still running on the host when a window closes its connection. + `programs` is `ask` (automatic: the client asks every time, and may offer + to remember the answer), `end` or `keep`. Nothing keeps running on a host, + or ends, without the user deciding. - `storage` is `{ relativePath: "remote/preferences.json", maximumBytes: 16384 }`. - `sshConfig` is `{ path, exists }` for `.ssh/config` below `homeDirectory`, @@ -5971,6 +5979,8 @@ sshConfig? }`: makes the limit automatic with `null`. - `reverseForwarding: { allowed: boolean|null }` allows or refuses reverse forwards, or makes the switch automatic with `null`. +- `closePrograms: { programs: "ask"|"end"|"keep"|null }` stores the closing + choice, or makes it automatic with `null`. The result is `{ changed, document: string|null }`; an unchanged edit returns a `null` document and must not create a source. No field or more @@ -5992,7 +6002,7 @@ user-settings resource does not affect code signatures or update deltas. #### Remote connections that stay open `remote.connect` takes `{ connection, servers: [{ target, path, sha256 }], -serverVersion, installRoot? }`. `servers` are the read-only server builds the +serverVersion, installRoot?, resume? }`. `servers` are the read-only server builds the host ships, by Rust target; `sha256` is the build's SHA-256 as 64 hexadecimal digits, taken from the manifest the application ships and signs with the builds, never computed from the file Core is about to send. `installRoot` @@ -6015,8 +6025,26 @@ and `{ stage: "installed", uploaded }` once the server is in place, where failed attempt stops after the last stage reached, so a host without a matching build stops after `platformChecked`. The result is `{ status, session, host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName, -homeDirectory }` and is set only for `connected`. A host without a matching -build is `unsupportedPlatform` and nothing is uploaded. +homeDirectory, sessionKey, sessionToken, resumed, keptPrograms }` and is set +only for `connected`. A host without a matching build is +`unsupportedPlatform` and nothing is uploaded. + +The server runs a persistent session (`--connect `, with +`--state-dir ` when one is given), so what it runs survives the +connection. `sessionKey` names that session and `sessionToken` is the secret +that attaches to it again; the client stores the token like a password and +never logs it. To attach to a session an earlier connection kept, pass +`resume: { key, token }` with the values it returned. `resumed` tells whether +this connection attached to it; `keptPrograms` lists the processes and +terminals it still runs, as `remote.runningPrograms` does, and is empty for +a new session. When the host refuses the token, because the session ended +and another took its key, Core connects once more without `resume`, so the +user authenticates again but is never locked out; that connection reports +`resumed: false` and a new key and token. A key that is empty, longer than 64 +characters or not made of ASCII letters, digits, `.`, `_` and `-`, or a token +that is empty, longer than 128 characters or not hexadecimal, is +`invalid_request` with `{ field: "resume", reason: "invalid" }`, before +OpenSSH or `wsl.exe` starts. Instead of `connection`, the request may name a WSL distribution on this Windows machine as `wsl: { distribution, user? }`, where `distribution` is a @@ -6045,9 +6073,18 @@ without sending anything; `details` says which of the two happened and, for a mismatch, the SHA-256 Core computed, but never the path. Cancellation and the five-minute bound are `cancelled` and `timed_out`. -Core keeps an open connection until `remote.disconnect` (`{ sessionId }`, -returning `{ closed }`) or until the host process exits; ending it terminates -the OpenSSH or `wsl.exe` process tree. `remote.closeAll` (no payload, returning +Core keeps an open connection until `remote.disconnect` (`{ sessionId, +programs? }`, returning `{ closed, kept }`) or until the host process exits; +ending it terminates the OpenSSH or `wsl.exe` process tree. `programs` is +`end` (the default), which ends the host session with every process and +terminal it runs, or `keep`, which tells the host to keep them and leaves +without ending the session; a later `remote.connect` with `resume` finds +them. `kept` tells whether the host keeps them: it is `false` for `end`, for +an unknown or closed connection (`closed: false`) and when the host could not +be told, whose programs then end like those of a client that crashed. A +session nobody kept, such as one whose client crashed or lost its network, +ends with its programs once the server's idle timeout (ten minutes) passes +without a client; one whose programs were kept lasts until they end. `remote.closeAll` (no payload, returning `{ closed }` with the number of connections) ends all of them; the host calls it while quitting because exiting without it can leave the OpenSSH tree and the remote server running. Requests over it take `sessionId`: @@ -6064,6 +6101,8 @@ the remote server running. Requests over it take `sessionId`: | `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.runningPrograms` | `{ sessionId }` | `{ programs: [{ kind, id, argv, label, runningMs }] }`, processes first; `kind` is `process` or `terminal`, `label` the one the program started with or `null` | +| `remote.endPrograms` | `{ sessionId }` | `{ ended }`: every listed process gets `SIGTERM` for its process session and every terminal hangs up; one that ended in the meantime is not counted, one that ignores the signal is still listed | `remote.writeFile` replaces the file atomically on the host. With `expected` (`{ size, modifiedMs }` from the read) a changed file is a diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 0b1a9b0d..2c1c5149 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1051,6 +1051,12 @@ pub enum RemoteCommand { Preferences, /// Changes one remote workspace preference (`remote.editPreferences`). EditPreferences, + /// Lists the processes and terminals a host session still runs + /// (`remote.runningPrograms`). + RunningPrograms, + /// Ends every process and terminal a host session runs + /// (`remote.endPrograms`). + EndPrograms, } #[derive(Debug, Clone)] @@ -1635,6 +1641,8 @@ impl CoreCommand { } "remote.preferences" => Some(Self::Remote(RemoteCommand::Preferences)), "remote.editPreferences" => Some(Self::Remote(RemoteCommand::EditPreferences)), + "remote.runningPrograms" => Some(Self::Remote(RemoteCommand::RunningPrograms)), + "remote.endPrograms" => Some(Self::Remote(RemoteCommand::EndPrograms)), "git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)), "git.remotes" => Some(Self::Git(GitCommand::Remotes)), "git.tags" => Some(Self::Git(GitCommand::Tags)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index 208afe01..e304d066 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -305,12 +305,23 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu "Invalid remote preferences request", lithe_workspace::preferences::edit, ), + RemoteCommand::RunningPrograms => answer( + id, + payload, + "Invalid remote programs request", + lithe_workspace::programs::list, + ), + RemoteCommand::EndPrograms => answer( + id, + payload, + "Invalid remote programs request", + lithe_workspace::programs::end, + ), RemoteCommand::Disconnect => { match serde_json::from_value::(payload) { - Ok(request) => CoreResponse::success( - id, - json!({ "closed": lithe_workspace::sessions::disconnect(request) }), - ), + Ok(request) => { + CoreResponse::success(id, json!(lithe_workspace::sessions::disconnect(request))) + } Err(error) => CoreResponse::failure( id, CoreError::new( diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index d31e5c07..59213152 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -294,6 +294,8 @@ mod tests { "remote.startForward", "remote.startHostForward", "remote.startReverseForward", + "remote.runningPrograms", + "remote.endPrograms", "debug.launch", ] { assert!(!is_hot(method), "{method}"); diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 8b2e82d6..05f8da53 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1678,3 +1678,111 @@ fn remote_host_and_reverse_forwards_follow_their_own_rules() { true ); } + +#[test] +fn remote_programs_are_listed_ended_and_kept_only_by_a_persistent_session() { + use lithe_remote::client::api::{SpawnSpec, TerminalEvent, TerminalSpec}; + use lithe_remote::protocol::methods::ResourceLabel; + + let host = HostFixture::new(); + let respond = |command: &str, payload: Value| -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"id": test_support::unique_id(), "command": command, + "timeoutMilliseconds": 30_000, "payload": payload}) + .to_string(), + )) + .unwrap() + }; + let call = |command: &str, payload: Value| -> Value { + let response = respond(command, payload); + assert_eq!(response["ok"], true, "{command}: {response}"); + response["data"].clone() + }; + let session = json!({"sessionId": host.id}); + assert_eq!( + call("remote.runningPrograms", session.clone()), + json!({"programs": []}) + ); + + let connection = test_support::connection(&host.id); + let process = connection + .session + .spawn(SpawnSpec { + argv: vec!["sleep".into(), "30".into()], + label: Some(ResourceLabel { + kind: "run".into(), + name: "server".into(), + }), + ..SpawnSpec::default() + }) + .unwrap(); + let terminal = connection + .session + .open_terminal(TerminalSpec { + argv: Some(vec!["sleep".into(), "30".into()]), + cwd: None, + env: std::collections::BTreeMap::new(), + columns: 80, + rows: 24, + label: None, + }) + .unwrap(); + let listed = call("remote.runningPrograms", session.clone()); + let programs = listed["programs"].as_array().unwrap(); + let kinds: Vec<&str> = programs + .iter() + .map(|program| program["kind"].as_str().unwrap()) + .collect(); + assert_eq!(kinds, ["process", "terminal"], "{listed}"); + assert_eq!(programs[0]["id"], process.id, "{listed}"); + assert_eq!(programs[0]["argv"], json!(["sleep", "30"]), "{listed}"); + assert_eq!( + programs[0]["label"], + json!({"kind": "run", "name": "server"}), + "{listed}" + ); + assert_eq!(programs[1]["id"], terminal.id, "{listed}"); + assert!(programs[1]["label"].is_null(), "{listed}"); + + assert_eq!(call("remote.endPrograms", session.clone())["ended"], 2); + // The server forgets an exited program before it reports the exit. + assert!(process.wait(STEP).unwrap().exit.is_some()); + loop { + match terminal.next_event(STEP).unwrap() { + Some(TerminalEvent::Exit(_)) => break, + Some(TerminalEvent::Output(_)) => {} + None => panic!("the terminal subscription ended before its exit"), + } + } + assert_eq!( + call("remote.runningPrograms", session.clone()), + json!({"programs": []}) + ); + assert_eq!(call("remote.endPrograms", session.clone())["ended"], 0); + drop((process, terminal)); + drop(connection); + + let refused = respond( + "remote.disconnect", + json!({"sessionId": host.id, "programs": "later"}), + ); + assert_eq!(refused["ok"], false, "{refused}"); + // An in-process session runs over standard streams and cannot outlive + // its client, so keeping its programs is refused and they end. + assert_eq!( + call( + "remote.disconnect", + json!({"sessionId": host.id, "programs": "keep"}) + ), + json!({"closed": true, "kept": false}) + ); + assert_eq!( + call( + "remote.disconnect", + json!({"sessionId": host.id, "programs": "end"}) + ), + json!({"closed": false, "kept": false}) + ); + let gone = respond("remote.runningPrograms", session); + assert_eq!(gone["ok"], false, "{gone}"); +} diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index c252769f..844812fb 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1523,7 +1523,7 @@ pub static EVENTS: &[EventMetadata] = &[ message: "Remote session cleanup failed", fields: &[ FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Stable native, thread, or remote category from ending an owned ssh or wsl.exe connection", reason: None }, - FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Connection cleanup stage of the owned ssh or wsl.exe process, e.g. shutdown, tree-kill, wait, or closer", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Connection cleanup stage of the owned ssh or wsl.exe process, e.g. shutdown, keep, tree-kill, wait, or closer", reason: None }, ], span: None, rate: 60, @@ -1542,6 +1542,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "lithe-core", }, + EventMetadata { + id: "remote.session.state_failed", + channel: "remote", + level: LogLevel::Warn, + message: "Remote session state could not be listed", + fields: &[ + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Remote protocol category returned by server.state on the resumed session", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "What the state was listed for after a connection opened, e.g. kept_programs", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "remote.upload.abort_failed", channel: "remote", diff --git a/rust/crates/remote/src/client/api.rs b/rust/crates/remote/src/client/api.rs index 32c02133..7b121eb7 100644 --- a/rust/crates/remote/src/client/api.rs +++ b/rust/crates/remote/src/client/api.rs @@ -187,6 +187,15 @@ impl RemoteSession { self.call(methods::SERVER_STATE, &json!({})) } + /// Sends `server.keep`: the user chose to leave the running programs on + /// the host after this client goes. Drop the session afterwards, instead + /// of shutting it down, to leave them running; the next client that + /// attaches decides again. A `--stdio` session refuses with + /// `UNSUPPORTED`. + pub fn keep(&self) -> Result<(), ClientError> { + self.call_unit(methods::SERVER_KEEP, &json!({})) + } + /// Metadata of `path` itself, without following a final link. pub fn stat(&self, path: &str) -> Result { self.call(methods::FS_STAT, &PathParams { path: path.into() }) diff --git a/rust/crates/remote/src/client/preferences.rs b/rust/crates/remote/src/client/preferences.rs index e387158d..a44eb5be 100644 --- a/rust/crates/remote/src/client/preferences.rs +++ b/rust/crates/remote/src/client/preferences.rs @@ -18,6 +18,11 @@ //! machine's loopback interface. [`Preferences::reverse_forwarding`] is off //! unless the user turned it on, because every user of the host can then //! reach that local port. +//! - `closePrograms` says what happens to the processes and terminals still +//! running on the host when a window closes its connection: `ask` every +//! time, `end` them, or `keep` them running for the next connection. +//! [`Preferences::closing`] is `ask` unless the user chose otherwise, so +//! nothing keeps running on a host, or ends, without the user deciding. //! - The document lives at [`STORAGE_PATH`] below the platform's //! user-preference directory, never on a host or in a workspace. It holds //! no secret. This module validates and edits it; the platform adapter @@ -58,11 +63,28 @@ const SSH_NAME: &str = "ssh"; /// Whether reverse forwards are offered when the document sets nothing. pub const DEFAULT_ALLOW_REVERSE_FORWARDING: bool = false; +/// What happens to programs still running on the host when a window closes +/// its connection. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ClosePrograms { + /// Ask every time. + Ask, + /// End every process and terminal of the session. + End, + /// Leave them running; the next connection to the host finds them. + Keep, +} + +/// The choice when the document sets nothing. +pub const DEFAULT_CLOSE_PROGRAMS: ClosePrograms = ClosePrograms::Ask; + /// Why a document or an edit was refused. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct PreferenceError { - /// `document`, `version`, `sshProgram` or `reconnectLimitSeconds`. + /// `document`, `version`, `sshProgram`, `reconnectLimitSeconds` or + /// `closePrograms`. pub field: &'static str, /// Why the field was refused. pub reason: PreferenceReason, @@ -118,6 +140,9 @@ pub struct Preferences { /// `None` uses [`DEFAULT_ALLOW_REVERSE_FORWARDING`]. #[serde(default, skip_serializing_if = "Option::is_none")] allow_reverse_forwarding: Option, + /// `None` uses [`DEFAULT_CLOSE_PROGRAMS`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + close_programs: Option, } impl Default for Preferences { @@ -127,6 +152,7 @@ impl Default for Preferences { ssh_program: None, reconnect_limit_seconds: None, allow_reverse_forwarding: None, + close_programs: None, } } } @@ -181,6 +207,15 @@ pub struct ReverseForwarding { pub allowed: bool, } +/// What happens to running programs when a window closes its connection. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Closing { + pub source: Source, + /// The choice that takes effect. + pub programs: ClosePrograms, +} + /// How long a lost session is reconnected automatically. #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -277,6 +312,29 @@ impl Preferences { self.allow_reverse_forwarding = allowed; } + /// The stored closing choice, `None` when automatic. + pub fn close_programs(&self) -> Option { + self.close_programs + } + + /// Sets what happens to running programs on close, or makes it + /// automatic with `None`. + pub fn set_close_programs(&mut self, programs: Option) { + self.close_programs = programs; + } + + /// What happens to running programs on close, and whether the user + /// decided. + pub fn closing(&self) -> Closing { + Closing { + source: match self.close_programs { + Some(_) => Source::Setting, + None => Source::Automatic, + }, + programs: self.close_programs.unwrap_or(DEFAULT_CLOSE_PROGRAMS), + } + } + /// Whether reverse forwards are offered, and whether the user decided. pub fn reverse_forwarding(&self) -> ReverseForwarding { ReverseForwarding { diff --git a/rust/crates/remote/src/client/preferences/tests.rs b/rust/crates/remote/src/client/preferences/tests.rs index 3806ff35..30627e01 100644 --- a/rust/crates/remote/src/client/preferences/tests.rs +++ b/rust/crates/remote/src/client/preferences/tests.rs @@ -87,6 +87,35 @@ fn reverse_forwarding_is_off_until_the_user_turns_it_on() { ); } +#[test] +fn closing_asks_until_the_user_chooses() { + let mut preferences = Preferences::default(); + let closing = preferences.closing(); + assert_eq!( + (closing.source, closing.programs), + (Source::Automatic, ClosePrograms::Ask) + ); + for programs in [ClosePrograms::Keep, ClosePrograms::End, ClosePrograms::Ask] { + preferences.set_close_programs(Some(programs)); + let read = Preferences::parse(Some(&preferences.text().unwrap())).unwrap(); + assert_eq!(read.close_programs(), Some(programs)); + let closing = read.closing(); + assert_eq!( + (closing.source, closing.programs), + (Source::Setting, programs) + ); + } + preferences.set_close_programs(None); + assert_eq!(preferences, Preferences::default()); + assert_eq!( + refusal("{\"version\":1,\"closePrograms\":\"later\"}"), + PreferenceError { + field: "document", + reason: PreferenceReason::Invalid + } + ); +} + #[test] fn the_document_refuses_other_versions_unknown_fields_and_bad_values() { let at = |field, reason| PreferenceError { field, reason }; diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index afa256b1..a6ad0375 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -186,8 +186,8 @@ pub struct ConnectOptions { pub client_name: String, /// Bounds transport start-up, the preamble and `server.hello` together. pub handshake_timeout: Duration, - /// How long a persistent session without a client and without running - /// processes or terminals stays alive. + /// How long a persistent session without a client stays alive, unless + /// its last client kept its running programs with `server.keep`. pub idle_timeout: Option, /// Token from an earlier connection's [`HelloResult`], required to /// reattach to a persistent session that already had a client. A wrong diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 8a17a88b..1621b5de 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -29,6 +29,14 @@ pub const SERVER_STATE: &str = "server.state"; pub const SERVER_RESUME: &str = "server.resume"; /// Acknowledges received events, see [`AckParams`]. pub const SERVER_ACK: &str = "server.ack"; +/// The user chose to keep the session's programs running after this client +/// leaves. Until the next client attaches, running processes and terminals +/// keep the persistent session past its idle timeout; without it, a session +/// that lost its client ends after the idle timeout even while programs run, +/// so a crashed or vanished client does not leave them behind for good. +/// A `--stdio` session ends with its connection and refuses it with +/// `UNSUPPORTED`. Returns `null`. +pub const SERVER_KEEP: &str = "server.keep"; /// Returns the [`FileMetadata`] of a path without following a final link. pub const FS_STAT: &str = "fs.stat"; diff --git a/rust/crates/remote/src/server/connection.rs b/rust/crates/remote/src/server/connection.rs index 4408723d..b9e6993f 100644 --- a/rust/crates/remote/src/server/connection.rs +++ b/rust/crates/remote/src/server/connection.rs @@ -247,6 +247,7 @@ fn is_inline(method: &str) -> bool { methods::SERVER_PING | methods::SERVER_STATE | methods::SERVER_ACK + | methods::SERVER_KEEP | methods::PROCESS_WRITE_STDIN | methods::PROCESS_CLOSE_STDIN | methods::TERMINAL_WRITE @@ -268,6 +269,10 @@ fn handle(context: &Context, method: &str, params: Value) -> Result { + session.keep()?; + Ok(Value::Null) + } method if method.starts_with("fs.upload") => { session.uploads.handle(context, method, params) } diff --git a/rust/crates/remote/src/server/daemon.rs b/rust/crates/remote/src/server/daemon.rs index 50d9631f..dcea8d4f 100644 --- a/rust/crates/remote/src/server/daemon.rs +++ b/rust/crates/remote/src/server/daemon.rs @@ -5,10 +5,11 @@ //! the daemon first if none runs, and then copies bytes between its standard //! streams and the socket. When SSH drops, only the proxy dies: the daemon //! keeps terminals and builds running, buffers their events, and hands them -//! to the next connection. A daemon whose session has no client and no -//! running process or terminal ends it after the idle timeout the client -//! requested; running programs end only through `server.shutdown` or the -//! user stopping them. +//! to the next connection. A daemon whose session has no client ends it +//! after the idle timeout the client requested, together with whatever it +//! still runs, unless the last client sent `server.keep`: programs the user +//! chose to keep run, and keep the session, until they end, a client stops +//! them, or `server.shutdown`. //! //! The socket lives in a directory only the user can access, and the daemon //! also verifies the peer's user id, so other users on a shared host cannot diff --git a/rust/crates/remote/src/server/session.rs b/rust/crates/remote/src/server/session.rs index e79ec348..2fe9689e 100644 --- a/rust/crates/remote/src/server/session.rs +++ b/rust/crates/remote/src/server/session.rs @@ -17,13 +17,13 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -/// Default time a persistent session without a client and without running +/// Default time a persistent session without a client and without kept /// programs survives. pub(crate) const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60); /// Upper bound clients may request, so an idle daemon that nobody comes back -/// to does not linger on a shared host for days. Running processes and -/// terminals keep a session regardless; see [`Session::keeps_programs`]. +/// to does not linger on a shared host for days. Programs the user kept +/// keep a session regardless; see [`Session::keeps_programs`]. const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60); /// Random bytes in a persistent session's token: 128 bits cannot be guessed @@ -101,6 +101,9 @@ pub(crate) struct Session { /// Whether any client completed a handshake before, which makes the /// next one a resumption. had_client: AtomicBool, + /// Set by `server.keep` and cleared when a client is admitted: the user + /// chose to leave the running programs on the host. + kept: AtomicBool, /// Secret later clients of a persistent session must present; `None` /// for a `--stdio` session, which has exactly one connection. token: Option, @@ -133,6 +136,7 @@ impl Session { starts: Arc::default(), ending: AtomicBool::new(false), had_client: AtomicBool::new(false), + kept: AtomicBool::new(false), token: if persistent { Some(generate_token()?) } else { @@ -170,6 +174,9 @@ impl Session { /// attached before. The first client of a persistent session is admitted /// whatever it presents, since a fresh session cannot know any token; /// every later one must present this session's token. + /// + /// An admitted client decides again what happens to the programs when it + /// leaves, so admission clears an earlier `server.keep`. pub(crate) fn admit(&self, presented: Option<&SessionToken>) -> Result { let Some(token) = &self.token else { return Ok(self.had_client.swap(true, Ordering::AcqRel)); @@ -185,6 +192,7 @@ impl Session { Some(presented) if same_secret(presented.as_str().as_bytes(), token.as_str().as_bytes()) => { + self.kept.store(false, Ordering::Release); Ok(true) } _ => Err(RemoteError::new( @@ -199,12 +207,29 @@ impl Session { self.token.as_ref() } - /// Whether processes or terminals still run. A persistent session keeps - /// them however long it has no client: ending it would kill a build or a - /// shell the user expects to find again. Only `server.shutdown`, or the - /// user stopping them, ends them. + /// `server.keep`: the user chose to leave the running programs on the + /// host after this client goes. Refused by a `--stdio` session, which + /// ends with its only connection. + pub(crate) fn keep(&self) -> Result<(), RemoteError> { + if !self.persistent { + return Err(RemoteError::new( + ErrorCode::Unsupported, + "only a persistent session keeps programs without a client", + )); + } + self.kept.store(true, Ordering::Release); + Ok(()) + } + + /// Whether programs the user kept still run. A kept session outlives its + /// idle timeout however long it has no client, so a build or a shell the + /// user left running is there to find again; only `server.shutdown`, or + /// the programs ending, ends it. Programs nobody kept, such as those of a + /// client that crashed or lost its network, end with the session once + /// the idle timeout passes without a client. pub(crate) fn keeps_programs(&self) -> bool { - !self.processes.is_empty() || !self.terminals.is_empty() + self.kept.load(Ordering::Acquire) + && (!self.processes.is_empty() || !self.terminals.is_empty()) } pub(crate) fn set_idle_timeout(&self, seconds: u64) { diff --git a/rust/crates/remote/tests/persistence.rs b/rust/crates/remote/tests/persistence.rs index 0d426526..8455a0c8 100644 --- a/rust/crates/remote/tests/persistence.rs +++ b/rust/crates/remote/tests/persistence.rs @@ -274,10 +274,10 @@ fn wait_for_file(path: &str) -> bool { false } -// The idle timeout applies only while nothing runs: a build left running -// keeps its session past the timeout, and the session ends after it. +// A build the user chose to keep keeps its session past the idle timeout, +// and the session ends after the build does. #[test] -fn running_processes_keep_an_idle_session_alive() { +fn kept_processes_keep_an_idle_session_alive() { let daemon = Daemon::new("kept-process"); let gate = TempDir::new("kept-process-gate"); let (marker, release) = (gate.join("marker"), gate.join("release")); @@ -290,6 +290,7 @@ fn running_processes_keep_an_idle_session_alive() { .unwrap(); let process_id = process.id; drop(process); + session.keep().unwrap(); drop(session); assert!( wait_for_file(&marker), @@ -316,10 +317,10 @@ fn running_processes_keep_an_idle_session_alive() { ); } -// An open terminal counts as running, so a shell left open with no output +// A kept terminal counts as running, so a shell left open with no output // keeps its session past the idle timeout too. #[test] -fn open_terminals_keep_an_idle_session_alive() { +fn kept_terminals_keep_an_idle_session_alive() { let daemon = Daemon::new("kept-terminal"); let gate = TempDir::new("kept-terminal-gate"); let (marker, release) = (gate.join("marker"), gate.join("release")); @@ -340,6 +341,7 @@ fn open_terminals_keep_an_idle_session_alive() { .unwrap(); let terminal_id = terminal.id; drop(terminal); + session.keep().unwrap(); drop(session); assert!( wait_for_file(&marker), @@ -364,6 +366,59 @@ fn open_terminals_keep_an_idle_session_alive() { ); } +// Programs nobody kept, such as those of a client that crashed or lost its +// network, end with the session once the idle timeout passes. +#[test] +fn programs_nobody_kept_end_with_an_idle_session() { + let daemon = Daemon::new("unkept-process"); + let gate = TempDir::new("unkept-process-gate"); + let (marker, release) = (gate.join("marker"), gate.join("release")); + let (session, _events) = daemon.connect(Some(Duration::from_secs(1))); + let process = session + .spawn(SpawnSpec { + argv: argv(&["sh", "-c", &outlast_idle_timeout(&marker, &release)]), + ..SpawnSpec::default() + }) + .unwrap(); + drop(process); + drop(session); + assert!( + daemon.wait_until_stopped(), + "the session outlived its idle timeout with a program nobody kept\n{}", + daemon.log() + ); + std::fs::write(&release, b"").unwrap(); +} + +// A client that attaches to a kept session decides again: when it leaves +// without keeping, the programs end after the idle timeout. +#[test] +fn attaching_clears_an_earlier_keep() { + let daemon = Daemon::new("rekept-process"); + let gate = TempDir::new("rekept-process-gate"); + let (marker, release) = (gate.join("marker"), gate.join("release")); + let (session, _events) = daemon.connect(Some(Duration::from_secs(1))); + let process = session + .spawn(SpawnSpec { + argv: argv(&["sh", "-c", &outlast_idle_timeout(&marker, &release)]), + ..SpawnSpec::default() + }) + .unwrap(); + drop(process); + session.keep().unwrap(); + drop(session); + + let (session, _events) = daemon.connect_deferred(); + assert!(session.hello().session.resumed); + drop(session); + assert!( + daemon.wait_until_stopped(), + "an earlier keep outlived the next client\n{}", + daemon.log() + ); + std::fs::write(&release, b"").unwrap(); +} + // Within the account, only the session's own client may reattach: another // program cannot take over a session, and its attempt does not disconnect // the attached client. The token never reaches the log, which stays diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index 30ad89c9..cb5295a5 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -29,6 +29,7 @@ pub mod host; pub mod motty; pub mod preferences; pub mod probe; +pub mod programs; mod scope; pub mod sessions; pub mod ssh_configuration; diff --git a/rust/crates/workspace/src/preferences.rs b/rust/crates/workspace/src/preferences.rs index 194d44fd..d66aad0d 100644 --- a/rust/crates/workspace/src/preferences.rs +++ b/rust/crates/workspace/src/preferences.rs @@ -8,7 +8,7 @@ //! `lithe_remote::client::preferences`. use lithe_protocol::{CoreError, ErrorCode}; -use lithe_remote::client::preferences::{self, PreferenceError, Preferences}; +use lithe_remote::client::preferences::{self, ClosePrograms, PreferenceError, Preferences}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::path::PathBuf; @@ -25,8 +25,8 @@ pub struct ReadRequest { home_directory: Option, } -/// `remote.editPreferences`: exactly one of `sshProgram`, `reconnectLimit` -/// and `reverseForwarding`. +/// `remote.editPreferences`: exactly one of `sshProgram`, `reconnectLimit`, +/// `reverseForwarding` and `closePrograms`. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EditRequest { @@ -38,6 +38,8 @@ pub struct EditRequest { reconnect_limit: Option, #[serde(default)] reverse_forwarding: Option, + #[serde(default)] + close_programs: Option, } /// The SSH program to use; `path: null` makes it automatic. @@ -61,6 +63,14 @@ struct SwitchEdit { allowed: Option, } +/// What happens to running programs on close; `programs: null` makes it +/// automatic, which asks. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct CloseEdit { + programs: Option, +} + /// Where the native client keeps the document. #[derive(Serialize)] #[serde(rename_all = "camelCase")] @@ -84,10 +94,12 @@ pub fn read(request: ReadRequest) -> Result { "sshProgram": preferences.ssh_program(), "reconnectLimitSeconds": preferences.reconnect_limit_seconds(), "allowReverseForwarding": preferences.allow_reverse_forwarding(), + "closePrograms": preferences.close_programs(), }, "ssh": ssh, "reconnect": preferences.reconnect(), "reverseForwarding": preferences.reverse_forwarding(), + "closing": preferences.closing(), "storage": STORAGE, }); if let Some(home) = request.home_directory { @@ -117,14 +129,16 @@ pub fn edit(request: EditRequest) -> Result { request.ssh_program, request.reconnect_limit, request.reverse_forwarding, + request.close_programs, ) { - (Some(program), None, None) => after + (Some(program), None, None, None) => after .set_ssh_program(program.path.as_deref()) .map_err(invalid_request)?, - (None, Some(limit), None) => after + (None, Some(limit), None, None) => after .set_reconnect_limit(limit.seconds) .map_err(invalid_request)?, - (None, None, Some(switch)) => after.set_allow_reverse_forwarding(switch.allowed), + (None, None, Some(switch), None) => after.set_allow_reverse_forwarding(switch.allowed), + (None, None, None, Some(close)) => after.set_close_programs(close.programs), _ => { return Err(CoreError::new( ErrorCode::InvalidRequest, diff --git a/rust/crates/workspace/src/preferences/tests.rs b/rust/crates/workspace/src/preferences/tests.rs index 3c0eeb69..adfe4f08 100644 --- a/rust/crates/workspace/src/preferences/tests.rs +++ b/rust/crates/workspace/src/preferences/tests.rs @@ -22,8 +22,13 @@ fn reading_no_document_reports_automatic_values_and_the_storage() { "sshProgram": null, "reconnectLimitSeconds": null, "allowReverseForwarding": null, + "closePrograms": null, }) ); + assert_eq!( + result["closing"], + json!({ "source": "automatic", "programs": "ask" }) + ); assert_eq!(result["ssh"]["source"], "automatic"); assert_eq!(result["reconnect"]["source"], "automatic"); assert_eq!(result["reconnect"]["limitSeconds"], 60); @@ -120,6 +125,30 @@ fn reverse_forwards_stay_refused_until_the_switch_allows_them() { assert!(matches!(error.code, ErrorCode::ParseFailed)); } +#[test] +fn the_closing_choice_is_edited_and_read_back() { + let edited = edit(request(json!({ + "document": null, + "closePrograms": { "programs": "keep" }, + }))) + .unwrap(); + assert_eq!(edited["changed"], true); + let document = edited["document"].as_str().unwrap().to_owned(); + let state = read(request(json!({ "document": document }))).unwrap(); + assert_eq!(state["preferences"]["closePrograms"], "keep"); + assert_eq!( + state["closing"], + json!({ "source": "setting", "programs": "keep" }) + ); + let restored = edit(request(json!({ + "document": document, + "closePrograms": { "programs": null }, + }))) + .unwrap(); + let state = read(request(json!({ "document": restored["document"] }))).unwrap(); + assert_eq!(state["closing"]["source"], "automatic"); +} + #[test] fn an_edit_names_exactly_one_value_and_refuses_bad_programs_by_field() { for both_or_neither in [ @@ -134,6 +163,11 @@ fn an_edit_names_exactly_one_value_and_refuses_bad_programs_by_field() { "reconnectLimit": { "seconds": null }, "reverseForwarding": { "allowed": true }, }), + json!({ + "document": null, + "reverseForwarding": { "allowed": true }, + "closePrograms": { "programs": "end" }, + }), ] { let error = edit(request(both_or_neither)).unwrap_err(); assert!(matches!(error.code, ErrorCode::InvalidRequest)); diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index 79557617..56497b62 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -470,6 +470,42 @@ fn connections_name_exactly_one_client() { assert!(!wsl.program.with_extension("ran").exists()); } +// A session key reaches the remote command line, so one the server would +// refuse, or a token it never issues, is refused before anything runs. +#[cfg(unix)] +#[test] +fn a_malformed_resume_is_refused_before_the_client_runs() { + let ssh = FakeSsh::new("remote-connect-resume-refused", "touch \"$0.ran\""); + let token = "0123456789abcdef".repeat(2); + for (key, token) in [ + (String::new(), token.clone()), + ("a b".to_owned(), token.clone()), + ("$(id)".to_owned(), token.clone()), + ("k".repeat(65), token.clone()), + ("window-1".to_owned(), String::new()), + ("window-1".to_owned(), "not hex".to_owned()), + ("window-1".to_owned(), "a".repeat(129)), + ] { + let mut request = serde_json::to_value(json!({ + "connection": { "host": "devbox", "user": "dev" }, + "servers": [], + "serverVersion": "0.1.0", + })) + .unwrap(); + request["resume"] = json!({ "key": key, "token": token }); + let request: sessions::ConnectRequest = serde_json::from_value(request).unwrap(); + let error = sessions::connect_with(request, Some(ssh.path())).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest), "{error:?}"); + assert_eq!( + serde_json::from_str::(error.details.as_deref().unwrap()).unwrap(), + json!({ "field": "resume", "reason": "invalid" }), + "key of {} chars", + key.chars().count() + ); + } + assert!(!ssh.program.with_extension("ran").exists()); +} + // The connection log keeps one category per failed status, so a log line // tells authentication, host key and network failures apart. #[test] @@ -565,7 +601,10 @@ fn closed_connections_cannot_be_used() { )); let request: sessions::DisconnectRequest = serde_json::from_value(json!({ "sessionId": "missing" })).unwrap(); - assert!(!sessions::disconnect(request)); + assert_eq!( + sessions::disconnect(request), + sessions::DisconnectResult::default() + ); } // Application exit closes whatever is open and must be safe with nothing open. diff --git a/rust/crates/workspace/src/programs.rs b/rust/crates/workspace/src/programs.rs new file mode 100644 index 00000000..329fee15 --- /dev/null +++ b/rust/crates/workspace/src/programs.rs @@ -0,0 +1,104 @@ +//! `remote.runningPrograms` and `remote.endPrograms`: the processes and +//! terminals a host session still runs (design §9). +//! +//! A client lists them when a window closes its connection, to ask whether +//! they end or keep running, and after reconnecting to a session an earlier +//! connection kept, which it no longer knows the programs of. Ending them +//! is the "End" of that list; keeping them needs nothing. + +use crate::sessions::{lookup, request_error}; +use lithe_protocol::CoreError; +use lithe_remote::client::{ClientError, RemoteSession}; +use lithe_remote::protocol::message::ErrorCode as RemoteErrorCode; +use lithe_remote::protocol::methods::{self, ResourceLabel}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::time::Duration; + +/// Deadline for one request that lists or ends a program. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +/// Whether a program is a process or a terminal. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ProgramKind { + Process, + Terminal, +} + +/// One process or terminal the session still runs. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RunningProgram { + pub kind: ProgramKind, + /// The id the program was started with; unique per kind. + pub id: u64, + /// Program and arguments, user content the client shows unchanged. + pub argv: Vec, + /// The label the program was started with, if any. + pub label: Option, + /// Milliseconds the program has run, on the host's clock. + pub running_ms: u64, +} + +/// The processes and terminals `session` still runs, processes first. +pub(crate) fn running(session: &RemoteSession) -> Result, ClientError> { + let state = session.state()?; + let processes = state.processes.into_iter().map(|process| RunningProgram { + kind: ProgramKind::Process, + id: process.process_id, + argv: process.argv, + label: process.label, + running_ms: process.running_ms, + }); + let terminals = state.terminals.into_iter().map(|terminal| RunningProgram { + kind: ProgramKind::Terminal, + id: terminal.terminal_id, + argv: terminal.argv, + label: terminal.label, + running_ms: terminal.running_ms, + }); + Ok(processes.chain(terminals).collect()) +} + +/// `remote.runningPrograms` and `remote.endPrograms`: the session. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProgramsRequest { + session_id: String, +} + +/// Lists the processes and terminals the session still runs. +pub fn list(request: ProgramsRequest) -> Result { + let connection = lookup(&request.session_id)?; + let programs = + running(&connection.session).map_err(|error| request_error(&request.session_id, error))?; + Ok(json!({ "programs": programs })) +} + +/// Ends every process and terminal the session still runs: processes get +/// `SIGTERM` for their whole process session, terminals hang up. Returns +/// how many were signalled; a program that ended in the meantime is not +/// counted. A program that ignores the signal is still listed afterwards. +pub fn end(request: ProgramsRequest) -> Result { + let connection = lookup(&request.session_id)?; + let session = &connection.session; + let failed = |error| request_error(&request.session_id, error); + let mut ended = 0_usize; + for program in running(session).map_err(failed)? { + let (method, params) = match program.kind { + ProgramKind::Process => ( + methods::PROCESS_KILL, + json!({ "processId": program.id, "force": false }), + ), + ProgramKind::Terminal => (methods::TERMINAL_CLOSE, json!({ "terminalId": program.id })), + }; + match session.request_value(method, params, REQUEST_TIMEOUT) { + Ok(_) => ended += 1, + // log-exempt: The program ended between listing and signalling, which is what the caller asked for. + Err(ClientError::Remote(error)) if error.code == RemoteErrorCode::UnknownResource => {} + Err(error) => return Err(failed(error)), + } + } + Ok(json!({ "ended": ended })) +} diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index a2f4a3f6..08266f16 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -8,10 +8,19 @@ //! requests such as `remote.readDir` use it by id. The client runs in its own //! process tree, which closing a connection ends, together with the //! connection's port forwards. +//! +//! The server runs a persistent session under a key (`--connect`), so the +//! processes and terminals it runs survive the connection. Closing a +//! connection ends them unless the client chose to keep them +//! (`remote.disconnect` with `programs: keep`); a later `remote.connect` that +//! presents the key and the session's token attaches to them again. A +//! session nobody kept, such as one whose client crashed, ends with its +//! programs once the server's idle timeout passes without a client. use crate::probe::{ classify, classify_wsl, diagnostics, relay_challenge, ssh_hop, ProbeStatus, ProbedHost, }; +use crate::programs::RunningProgram; use lithe_git_host::ProcessTree; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::connections::{ConnectionError, Reason, SshConnection}; @@ -22,7 +31,8 @@ use lithe_remote::client::{ wsl, ArtifactError, ConnectionKind, ConnectionLog, ForwardSet, Hop, RemoteSession, ServerArtifact, ServerTarget, TransportChain, WslConnection, }; -use lithe_remote::protocol::methods; +use lithe_remote::protocol::message::ErrorCode as RemoteErrorCode; +use lithe_remote::protocol::methods::{self, SessionToken}; use lithe_request_context::events as execution_events; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, VecDeque}; @@ -84,9 +94,55 @@ pub struct ConnectRequest { preferences: Option, servers: Vec, server_version: String, - /// Install root on the remote; `None` is `$HOME/.lithe-server`. + /// Install root on the remote; `None` is `$HOME/.lithe-server`. The + /// server keeps its persistent sessions' state below it too. #[serde(default)] install_root: Option, + /// The persistent session an earlier connection to this host kept, to + /// attach to again; `None` starts a new session. + #[serde(default)] + resume: Option, +} + +/// A persistent session `remote.connect` returned earlier. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ResumeInput { + /// [`OpenedSession::session_key`]. + key: String, + /// [`OpenedSession::session_token`]; a secret. + token: SessionToken, +} + +/// Longest session key, which the server limits too. +const MAX_SESSION_KEY_CHARS: usize = 64; + +/// Longest session token accepted from a client; the server issues 32 hex +/// digits. +const MAX_SESSION_TOKEN_CHARS: usize = 128; + +impl ResumeInput { + /// Refuses a key the server would refuse, so it never reaches a remote + /// command line, and a token that is not one the server issues. + fn check(&self) -> Result<(), CoreError> { + let key_valid = !self.key.is_empty() + && self.key.chars().count() <= MAX_SESSION_KEY_CHARS + && self + .key + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')); + let token = self.token.as_str(); + let token_valid = !token.is_empty() + && token.len() <= MAX_SESSION_TOKEN_CHARS + && token.chars().all(|c| c.is_ascii_hexdigit()); + if key_valid && token_valid { + return Ok(()); + } + Err(crate::connections::invalid_request(ConnectionError { + field: "resume", + reason: Reason::Invalid, + })) + } } /// The session `remote.connect` opened. @@ -99,6 +155,18 @@ pub struct OpenedSession { host_name: String, user_name: Option, home_directory: Option, + /// Names the persistent session on the host, for a later `resume`. + session_key: String, + /// Secret a later `resume` presents; the client stores it like a + /// password and never logs it. + session_token: Option, + /// Whether this connection attached to the session `resume` named. + /// `false` after a `resume` means that session had ended, or belonged + /// to another client, and a new one started. + resumed: bool, + /// Processes and terminals the resumed session still runs, which an + /// earlier connection kept; empty for a new session. + kept_programs: Vec, } /// `remote.connect` result. Connection failures are results, not errors. @@ -156,25 +224,53 @@ impl Connection { } } + /// Ends the session together with every program it runs. pub(crate) fn close(&self) { // Local ports close first, so nothing new is accepted into a tunnel // the shutdown below is about to end. self.forwards.close(); - if let Err(error) = self.session.request_value( - methods::SERVER_SHUTDOWN, - serde_json::Value::Null, - EXIT_GRACE, - ) { - // A peer that already closed needs no shutdown; other failures use WARN. - if !matches!(error, ClientError::Disconnected { .. }) { - lithe_diagnostics::core_events::recovery_failed( - "remote.session.cleanup_failed", - "shutdown", - &error.failure_category(), - "remote", - ); + self.request_quietly(methods::SERVER_SHUTDOWN, "shutdown"); + self.end_transport(); + } + + /// Leaves the session's programs running on the host for a later + /// connection: `server.keep`, then the connection ends without + /// `server.shutdown`. Returns whether the host keeps them. A session + /// that refused, or whose connection was already lost, ends them once + /// its idle timeout passes. + pub(crate) fn detach(&self) -> bool { + self.forwards.close(); + let kept = self.request_quietly(methods::SERVER_KEEP, "keep"); + self.end_transport(); + kept + } + + /// Sends `method` with the exit grace as its deadline, recording a + /// failure other than a peer that already closed at WARN. + fn request_quietly(&self, method: &str, stage: &str) -> bool { + match self + .session + .request_value(method, serde_json::Value::Null, EXIT_GRACE) + { + Ok(_) => true, + Err(error) => { + // A peer that already closed needs no request; other failures use WARN. + if !matches!(error, ClientError::Disconnected { .. }) { + lithe_diagnostics::core_events::recovery_failed( + "remote.session.cleanup_failed", + stage, + &error.failure_category(), + "remote", + ); + } + false } } + } + + /// Ends the client process and its tree. A persistent session on the + /// host outlives it. + fn end_transport(&self) { match &self.transport { ConnectionTransport::Process { child, tree } => { let mut child = child @@ -280,7 +376,9 @@ pub(crate) fn forget(id: &str) { } } -/// Opens a connection and registers it. +/// Opens a connection and registers it. A `resume` whose token the host +/// refuses starts a new session instead, so a stale or foreign token never +/// locks the user out of the host. pub fn connect(request: ConnectRequest) -> Result { connect_with(request, None) } @@ -389,7 +487,20 @@ pub(crate) fn connect_with( ) -> Result { let client = Client::of(&request); let log = ConnectionLog::begin(client.log_kind()); - let result = connect_logged(request, client, program, &log); + let mut refused = false; + let mut result = connect_logged( + &request, + request.resume.as_ref(), + client, + program, + &log, + &mut refused, + ); + if refused { + // The session under that key belongs to another client, or replaced + // the one the token was issued for. + result = connect_logged(&request, None, client, program, &log, &mut refused); + } match &result { Ok(result) => { if let Some((stage, code)) = failure_of(result.status) { @@ -418,12 +529,24 @@ pub(crate) fn failure_of(status: ProbeStatus) -> Option<(&'static str, &'static } } +/// One connection attempt. Sets `refused` when the host refused the token +/// of `resume`. fn connect_logged( - request: ConnectRequest, + request: &ConnectRequest, + resume: Option<&ResumeInput>, client: Client, program: Option<&str>, log: &ConnectionLog, + refused: &mut bool, ) -> Result { + if let Some(resume) = resume { + resume.check()?; + } + let session_key = resume.map_or_else(nonce, |resume| resume.key.clone()); + let mut server_arguments = vec!["--connect", session_key.as_str()]; + if let Some(root) = request.install_root.as_deref() { + server_arguments.extend(["--state-dir", root]); + } // Only the build for the host's platform is read and checked, once the // probe reports it; here the targets and hashes are just validated. let servers = request @@ -449,11 +572,11 @@ fn connect_logged( let rejected_in_launch = Arc::clone(&rejected); let _connecting = ConnectingGuard::enter(); - let chain = TransportChain::new(vec![first_hop(&request, program)?]); + let chain = TransportChain::new(vec![first_hop(request, program)?]); let argv = chain .command(&launch_command( request.install_root.as_deref(), - &["--stdio"], + &server_arguments, )) .map_err(|error| { CoreError::new(ErrorCode::InvalidRequest, client.invalid()) @@ -697,12 +820,19 @@ fn connect_logged( }; let options = ConnectOptions { handshake_timeout: HANDSHAKE_TIMEOUT, + session_token: resume.map(|resume| resume.token.clone()), log: Some(log.clone()), ..ConnectOptions::default() }; let (session, events) = match RemoteSession::from_streams(output, input, &options) { Ok(value) => value, Err(error) => { + *refused = resume.is_some() + && matches!( + &error, + ClientError::Remote(remote) + if remote.code == RemoteErrorCode::InvalidSessionToken + ); // Grace expiry is advisory: the following checked kill/wait owns the final cleanup result. wait_for_exit(&mut child, EXIT_GRACE); reap(&tree, &mut child); @@ -718,6 +848,21 @@ fn connect_logged( // from blocking on a full channel. std::thread::spawn(move || for _ in events {}); let capabilities = session.hello().host.clone(); + let info = session.hello().session.clone(); + let kept_programs = if info.resumed { + crate::programs::running(&session).unwrap_or_else(|error| { + // The connection works without the list; the client can ask again. + lithe_diagnostics::core_events::recovery_failed( + "remote.session.state_failed", + "kept_programs", + &error.failure_category(), + "remote", + ); + Vec::new() + }) + } else { + Vec::new() + }; let id = nonce(); registry() .lock() @@ -741,6 +886,10 @@ fn connect_logged( host_name: capabilities.host_name, user_name: capabilities.user_name, home_directory: capabilities.home_directory, + session_key, + session_token: info.session_token, + resumed: info.resumed, + kept_programs, }), host: Some(host), diagnostics: String::new(), @@ -887,24 +1036,55 @@ pub fn write_file(request: WriteFileRequest) -> Result bool { +pub fn disconnect(request: DisconnectRequest) -> DisconnectResult { let connection = registry() .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .remove(&request.session_id); let Some(connection) = connection else { - return false; + return DisconnectResult::default(); + }; + let kept = match request.programs { + ProgramsOnClose::End => { + connection.close(); + false + } + ProgramsOnClose::Keep => connection.detach(), }; - connection.close(); - true + DisconnectResult { closed: true, kept } } /// Closes every open connection, for application exit. Connections close in diff --git a/rust/logging/events/remote.json b/rust/logging/events/remote.json index 481c53d6..f26c6a4d 100644 --- a/rust/logging/events/remote.json +++ b/rust/logging/events/remote.json @@ -61,7 +61,7 @@ "stage": { "type": "token", "required": true, - "description": "Connection cleanup stage of the owned ssh or wsl.exe process, e.g. shutdown, tree-kill, wait, or closer" + "description": "Connection cleanup stage of the owned ssh or wsl.exe process, e.g. shutdown, keep, tree-kill, wait, or closer" }, "error": { "type": "error", @@ -72,6 +72,26 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "remote.session.state_failed", + "channel": "remote", + "level": "warn", + "message": "Remote session state could not be listed", + "fields": { + "stage": { + "type": "token", + "required": true, + "description": "What the state was listed for after a connection opened, e.g. kept_programs" + }, + "error": { + "type": "error", + "required": true, + "description": "Remote protocol category returned by server.state on the resumed session" + } + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "remote.session.diagnostics_failed", "channel": "remote", From 658910abd8ae572dbb25b3bababb47960c17bfb5 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 02:45:49 +0800 Subject: [PATCH 2/3] feat(remote): end only the listed programs; a closed connection's cleanup is expected (Refs 1lck/Lithe-IDEA#2231) remote.endPrograms takes an optional programs list ([{kind, id}] as remote.runningPrograms listed them), so a client that reconnected to a kept session ends what it listed without hanging up a terminal it started meanwhile. Resource cleanup that finds the connection already closed (after server.keep or a loss) no longer logs WARN, as the session's own cleanup already treats it. --- rust/contracts/rust-core-api.md | 4 +- rust/crates/core/src/tests/remote_sessions.rs | 19 +++++++- rust/crates/workspace/src/host.rs | 11 +++-- rust/crates/workspace/src/programs.rs | 48 +++++++++++++++---- 4 files changed, 66 insertions(+), 16 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c37c54c4..1136edd3 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -833,7 +833,7 @@ or removing a command fails until the table changes in the same commit. | `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to | | `remote.editPreferences` | Set the SSH program, the reconnect limit, whether reverse forwards are allowed or what closing a connection does to its programs, or make one automatic again | | `remote.runningPrograms` | List the processes and terminals a connection's host session still runs | -| `remote.endPrograms` | End every process and terminal a connection's host session runs | +| `remote.endPrograms` | End every process and terminal a connection's host session runs, or the listed ones | | `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation | | `git.remotes` | Return configured fetch remote names and URLs | | `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations | @@ -6102,7 +6102,7 @@ the remote server running. Requests over it take `sessionId`: | `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.runningPrograms` | `{ sessionId }` | `{ programs: [{ kind, id, argv, label, runningMs }] }`, processes first; `kind` is `process` or `terminal`, `label` the one the program started with or `null` | -| `remote.endPrograms` | `{ sessionId }` | `{ ended }`: every listed process gets `SIGTERM` for its process session and every terminal hangs up; one that ended in the meantime is not counted, one that ignores the signal is still listed | +| `remote.endPrograms` | `{ sessionId, programs? }` | `{ ended }`: every running process gets `SIGTERM` for its process session and every terminal hangs up, or only those `programs` (`[{ kind, id }]` as `remote.runningPrograms` listed them) names; one that ended in the meantime or is not running is not counted, one that ignores the signal is still listed | `remote.writeFile` replaces the file atomically on the host. With `expected` (`{ size, modifiedMs }` from the read) a changed file is a diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 05f8da53..e1e6fdd4 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1744,9 +1744,19 @@ fn remote_programs_are_listed_ended_and_kept_only_by_a_persistent_session() { assert_eq!(programs[1]["id"], terminal.id, "{listed}"); assert!(programs[1]["label"].is_null(), "{listed}"); - assert_eq!(call("remote.endPrograms", session.clone())["ended"], 2); + // Only the programs named end, and one the session does not run is not + // counted; a kind other than process or terminal is refused. + let refused = respond( + "remote.endPrograms", + json!({"sessionId": host.id, "programs": [{"kind": "watch", "id": 1}]}), + ); + assert_eq!(refused["ok"], false, "{refused}"); + let named = json!({"sessionId": host.id, "programs": [ + {"kind": "terminal", "id": terminal.id}, + {"kind": "process", "id": process.id + 1000}, + ]}); + assert_eq!(call("remote.endPrograms", named)["ended"], 1); // The server forgets an exited program before it reports the exit. - assert!(process.wait(STEP).unwrap().exit.is_some()); loop { match terminal.next_event(STEP).unwrap() { Some(TerminalEvent::Exit(_)) => break, @@ -1754,6 +1764,11 @@ fn remote_programs_are_listed_ended_and_kept_only_by_a_persistent_session() { None => panic!("the terminal subscription ended before its exit"), } } + let left = call("remote.runningPrograms", session.clone()); + assert_eq!(left["programs"].as_array().unwrap().len(), 1, "{left}"); + assert_eq!(left["programs"][0]["kind"], "process", "{left}"); + assert_eq!(call("remote.endPrograms", session.clone())["ended"], 1); + assert!(process.wait(STEP).unwrap().exit.is_some()); assert_eq!( call("remote.runningPrograms", session.clone()), json!({"programs": []}) diff --git a/rust/crates/workspace/src/host.rs b/rust/crates/workspace/src/host.rs index 73534199..01fb10a9 100644 --- a/rust/crates/workspace/src/host.rs +++ b/rust/crates/workspace/src/host.rs @@ -216,9 +216,14 @@ impl Drop for Resource<'_> { }; if let Err(error) = self.session.request_value(method, params, CLEANUP_TIMEOUT) { // An exited process, stopped watch or closed terminal is already gone - // on the host: expected missing. The resource owner keeps the primary - // result; WARN reports any other failed cleanup. - if !error.is_resource_already_gone() { + // on the host: expected missing. So is a connection that already + // closed: the host then ended the session, keeps it as the user chose + // or ends it after its idle timeout, and this side can do nothing + // more. The resource owner keeps the primary result; WARN reports any + // other failed cleanup. + if !error.is_resource_already_gone() + && !matches!(error, ClientError::Disconnected { .. }) + { lithe_diagnostics::core_events::recovery_failed( "remote.resource.cleanup_failed", self.family, diff --git a/rust/crates/workspace/src/programs.rs b/rust/crates/workspace/src/programs.rs index 329fee15..9a268cd8 100644 --- a/rust/crates/workspace/src/programs.rs +++ b/rust/crates/workspace/src/programs.rs @@ -4,7 +4,9 @@ //! A client lists them when a window closes its connection, to ask whether //! they end or keep running, and after reconnecting to a session an earlier //! connection kept, which it no longer knows the programs of. Ending them -//! is the "End" of that list; keeping them needs nothing. +//! is the "End" of that list; keeping them needs nothing. After a +//! reconnection the client may already have started programs of its own, +//! so it can end only the ones it listed. use crate::sessions::{lookup, request_error}; use lithe_protocol::CoreError; @@ -19,7 +21,7 @@ use std::time::Duration; const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); /// Whether a program is a process or a terminal. -#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum ProgramKind { Process, @@ -61,13 +63,31 @@ pub(crate) fn running(session: &RemoteSession) -> Result, Cl Ok(processes.chain(terminals).collect()) } -/// `remote.runningPrograms` and `remote.endPrograms`: the session. +/// `remote.runningPrograms`: the session. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ProgramsRequest { session_id: String, } +/// `remote.endPrograms`: the session, and the programs to end, as +/// `remote.runningPrograms` listed them; none ends every program. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EndRequest { + session_id: String, + #[serde(default)] + programs: Option>, +} + +/// A program of `remote.endPrograms`: its kind and id. +#[derive(Clone, Copy, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProgramRef { + kind: ProgramKind, + id: u64, +} + /// Lists the processes and terminals the session still runs. pub fn list(request: ProgramsRequest) -> Result { let connection = lookup(&request.session_id)?; @@ -76,16 +96,26 @@ pub fn list(request: ProgramsRequest) -> Result { Ok(json!({ "programs": programs })) } -/// Ends every process and terminal the session still runs: processes get -/// `SIGTERM` for their whole process session, terminals hang up. Returns -/// how many were signalled; a program that ended in the meantime is not -/// counted. A program that ignores the signal is still listed afterwards. -pub fn end(request: ProgramsRequest) -> Result { +/// Ends the processes and terminals the session still runs, every one or +/// those `programs` names: processes get `SIGTERM` for their whole process +/// session, terminals hang up. Returns how many were signalled; a program +/// that ended in the meantime, or that `programs` names but the session does +/// not run, is not counted. A program that ignores the signal is still +/// listed afterwards. +pub fn end(request: EndRequest) -> Result { let connection = lookup(&request.session_id)?; let session = &connection.session; let failed = |error| request_error(&request.session_id, error); + let chosen = |program: &RunningProgram| { + request.programs.as_ref().is_none_or(|programs| { + programs.contains(&ProgramRef { + kind: program.kind, + id: program.id, + }) + }) + }; let mut ended = 0_usize; - for program in running(session).map_err(failed)? { + for program in running(session).map_err(failed)?.into_iter().filter(chosen) { let (method, params) = match program.kind { ProgramKind::Process => ( methods::PROCESS_KILL, From a81ad08c436dd53e3dea0343bde7bc7310b9e928 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 22 Nov 2026 03:09:51 +0800 Subject: [PATCH 3/3] feat(remote): report the host session's idle timeout with the closing choice (Refs 1lck/Lithe-IDEA#2231) remote.preferences now reports closing.idleTimeoutSeconds, the server's default idle timeout, so the Remote Workspace settings page shows the value the host applies instead of a copy. The constant moves to protocol::methods so the client and the server share it. --- rust/contracts/rust-core-api.md | 13 ++++++++----- rust/crates/remote/src/client/preferences.rs | 5 +++++ rust/crates/remote/src/client/preferences/tests.rs | 2 ++ rust/crates/remote/src/protocol/methods.rs | 6 ++++++ rust/crates/remote/src/server/session.rs | 3 ++- rust/crates/workspace/src/preferences/tests.rs | 4 ++-- 6 files changed, 25 insertions(+), 8 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 1136edd3..2bbeaac1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5960,11 +5960,14 @@ sshConfig? }`: - `reverseForwarding` is `{ source, allowed }`: whether the ports page may start reverse forwards (automatic: not allowed), because every user of the host can reach the local port one opens. -- `closing` is `{ source, programs }`: what happens to the processes and - terminals still running on the host when a window closes its connection. - `programs` is `ask` (automatic: the client asks every time, and may offer - to remember the answer), `end` or `keep`. Nothing keeps running on a host, - or ends, without the user deciding. +- `closing` is `{ source, programs, idleTimeoutSeconds }`: what happens to + the processes and terminals still running on the host when a window closes + its connection. `programs` is `ask` (automatic: the client asks every + time, and may offer to remember the answer), `end` or `keep`. Nothing + keeps running on a host, or ends, without the user deciding. + `idleTimeoutSeconds` (600) is how long the host keeps a session whose + connection was lost and whose programs nobody kept; the server sets it and + no document changes it. - `storage` is `{ relativePath: "remote/preferences.json", maximumBytes: 16384 }`. - `sshConfig` is `{ path, exists }` for `.ssh/config` below `homeDirectory`, diff --git a/rust/crates/remote/src/client/preferences.rs b/rust/crates/remote/src/client/preferences.rs index a44eb5be..a6df648c 100644 --- a/rust/crates/remote/src/client/preferences.rs +++ b/rust/crates/remote/src/client/preferences.rs @@ -214,6 +214,10 @@ pub struct Closing { pub source: Source, /// The choice that takes effect. pub programs: ClosePrograms, + /// Seconds the host keeps a session whose connection was lost, and + /// whose programs nobody kept, before ending it. The server sets it, + /// so no document changes it; clients show it beside the choice. + pub idle_timeout_seconds: u64, } /// How long a lost session is reconnected automatically. @@ -332,6 +336,7 @@ impl Preferences { None => Source::Automatic, }, programs: self.close_programs.unwrap_or(DEFAULT_CLOSE_PROGRAMS), + idle_timeout_seconds: crate::protocol::methods::DEFAULT_IDLE_TIMEOUT_SECONDS, } } diff --git a/rust/crates/remote/src/client/preferences/tests.rs b/rust/crates/remote/src/client/preferences/tests.rs index 30627e01..dd04cbec 100644 --- a/rust/crates/remote/src/client/preferences/tests.rs +++ b/rust/crates/remote/src/client/preferences/tests.rs @@ -95,6 +95,8 @@ fn closing_asks_until_the_user_chooses() { (closing.source, closing.programs), (Source::Automatic, ClosePrograms::Ask) ); + // The server's idle timeout, which no document changes. + assert_eq!(closing.idle_timeout_seconds, 10 * 60); for programs in [ClosePrograms::Keep, ClosePrograms::End, ClosePrograms::Ask] { preferences.set_close_programs(Some(programs)); let read = Preferences::parse(Some(&preferences.text().unwrap())).unwrap(); diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 1621b5de..7b855fb2 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -247,6 +247,12 @@ pub fn is_sha256_hex(value: &str) -> bool { // Server and session // --------------------------------------------------------------------------- +/// Seconds a persistent session waits without a client and without kept +/// programs before it ends, when no client set +/// [`HelloParams::idle_timeout_seconds`]. Clients show it next to the +/// closing choice, so it lives here rather than in the server. +pub const DEFAULT_IDLE_TIMEOUT_SECONDS: u64 = 10 * 60; + /// Parameters of `server.hello`. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] diff --git a/rust/crates/remote/src/server/session.rs b/rust/crates/remote/src/server/session.rs index 2fe9689e..31b7937d 100644 --- a/rust/crates/remote/src/server/session.rs +++ b/rust/crates/remote/src/server/session.rs @@ -19,7 +19,8 @@ use std::time::{Duration, Instant}; /// Default time a persistent session without a client and without kept /// programs survives. -pub(crate) const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60); +pub(crate) const DEFAULT_IDLE_TIMEOUT: Duration = + Duration::from_secs(crate::protocol::methods::DEFAULT_IDLE_TIMEOUT_SECONDS); /// Upper bound clients may request, so an idle daemon that nobody comes back /// to does not linger on a shared host for days. Programs the user kept diff --git a/rust/crates/workspace/src/preferences/tests.rs b/rust/crates/workspace/src/preferences/tests.rs index adfe4f08..20aeda26 100644 --- a/rust/crates/workspace/src/preferences/tests.rs +++ b/rust/crates/workspace/src/preferences/tests.rs @@ -27,7 +27,7 @@ fn reading_no_document_reports_automatic_values_and_the_storage() { ); assert_eq!( result["closing"], - json!({ "source": "automatic", "programs": "ask" }) + json!({ "source": "automatic", "programs": "ask", "idleTimeoutSeconds": 600 }) ); assert_eq!(result["ssh"]["source"], "automatic"); assert_eq!(result["reconnect"]["source"], "automatic"); @@ -138,7 +138,7 @@ fn the_closing_choice_is_edited_and_read_back() { assert_eq!(state["preferences"]["closePrograms"], "keep"); assert_eq!( state["closing"], - json!({ "source": "setting", "programs": "keep" }) + json!({ "source": "setting", "programs": "keep", "idleTimeoutSeconds": 600 }) ); let restored = edit(request(json!({ "document": document,