Skip to content

Commit edd0933

Browse files
authored
feat(remote): keep or end host programs when a connection closes (Refs 1lck/Lithe-IDEA#2231) (#160)
* feat(remote): keep or end host programs when a connection closes (Refs 1lck/Lithe-IDEA#2231) - remote.connect starts the persistent server session (--connect <key>, --state-dir <installRoot>) 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. * 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. * 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.
1 parent 62d44ce commit edd0933

24 files changed

Lines changed: 912 additions & 74 deletions

File tree

‎rust/contracts/remote-workspace-protocol-v1.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@ socket, lock and log under `<dir>` (default `$HOME/.lithe-server`) in
1919
directories only the user can access, and rejects peers with another user
2020
id. A session has one client at a time: a new connection that presents the
2121
session token (see below) replaces the current one. The idle timeout runs
22-
only while the session has neither a client nor running processes or open
23-
terminals; it is 10 minutes unless `server.hello` requests another with
22+
while the session has no client, unless its last client sent `server.keep`
23+
and the session still runs processes or open terminals; when it passes, the
24+
session ends with everything it runs. It is 10 minutes unless `server.hello` requests another with
2425
`idleTimeoutSeconds`, at most 24 hours, and the latest request applies. A
2526
connection the daemon cannot set up is closed without ending the session.
2627
The daemon log is created `0600`, never through a symbolic link, and moves to
@@ -119,6 +120,7 @@ subscribe before creating the resource.
119120
| `server.resume` | `afterSeq?` | `truncated`; then every kept event after `afterSeq`, followed by live events |
120121
| `server.ack` | `seq` | `null`; events up to `seq` may be forgotten |
121122
| `server.shutdown` | — | `null`; the session ends |
123+
| `server.keep` | — | `null`; the running processes and terminals outlast this client; `UNSUPPORTED` on a `--stdio` session |
122124
| `server.ping` | — | `{}` |
123125
| `server.state` | — | running `processes` (`processId`, `pid`, `argv`, `label?`, `runningMs`, `leaderExited`), `terminals` (`terminalId`, `pid`, `argv`, `label?`, `runningMs`, `columns`, `rows`), `watches` |
124126
| `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
327329
watches.
328330

329331
While no client is attached, a persistent session keeps processes, terminals
330-
and watches running. Tunnels, walks and listeners belong to the connection
332+
and watches running until the idle timeout. A client whose user chose to
333+
leave them running sends `server.keep` before it goes, without
334+
`server.shutdown`; the session then outlasts the idle timeout while any of
335+
its processes or terminals runs, and ends once none does. Each client that
336+
attaches decides again: attaching clears an earlier `server.keep`. So the
337+
programs of a client that crashed or lost its network end with the session
338+
after the idle timeout, unless the user reconnects before it passes. Tunnels, walks and listeners belong to the connection
331339
that opened them and end with it. After `server.shutdown` a persistent session is no
332340
longer reachable, even while it is still terminating its processes; the next
333341
connection with the same key starts a fresh session.

‎rust/contracts/rust-core-api.md‎

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -804,7 +804,7 @@ or removing a command fails until the table changes in the same commit.
804804
| `remote.authRespond` | Answer or cancel a prompt relayed by `remote.probe` or `remote.connect` once |
805805
| `remote.connect` | Open a connection over SSH or to a local WSL distribution, installing the shipped server when needed |
806806
| `remote.readDir` | List a directory over an open remote connection |
807-
| `remote.disconnect` | Close an open connection and its OpenSSH or `wsl.exe` process tree |
807+
| `remote.disconnect` | Close an open connection and its OpenSSH or `wsl.exe` process tree, ending or keeping the programs it runs on the host |
808808
| `remote.closeAll` | Close every open connection; the host calls it at application exit |
809809
| `remote.readFile` | Read a file over an open remote connection |
810810
| `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.
831831
| `remote.mottyHosts` | List the SSH hosts saved in Motty for an import |
832832
| `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine |
833833
| `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to |
834-
| `remote.editPreferences` | Set the SSH program, the reconnect limit or whether reverse forwards are allowed, or make one automatic again |
834+
| `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 |
835+
| `remote.runningPrograms` | List the processes and terminals a connection's host session still runs |
836+
| `remote.endPrograms` | End every process and terminal a connection's host session runs, or the listed ones |
835837
| `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation |
836838
| `git.remotes` | Return configured fetch remote names and URLs |
837839
| `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations |
@@ -5940,7 +5942,8 @@ and returns `{ preferences, ssh, reconnect, reverseForwarding, storage,
59405942
sshConfig? }`:
59415943

59425944
- `preferences` is `{ sshProgram, reconnectLimitSeconds,
5943-
allowReverseForwarding }`, the stored values; `null` is automatic.
5945+
allowReverseForwarding, closePrograms }`, the stored values; `null` is
5946+
automatic.
59445947
- `ssh` is `{ source, path, status }`, the OpenSSH client every connection
59455948
starts. `source` is `setting` for a stored program and `automatic`
59465949
otherwise, which is the first executable `ssh` (`ssh.exe` on Windows) in an
@@ -5957,6 +5960,14 @@ sshConfig? }`:
59575960
- `reverseForwarding` is `{ source, allowed }`: whether the ports page may
59585961
start reverse forwards (automatic: not allowed), because every user of the
59595962
host can reach the local port one opens.
5963+
- `closing` is `{ source, programs, idleTimeoutSeconds }`: what happens to
5964+
the processes and terminals still running on the host when a window closes
5965+
its connection. `programs` is `ask` (automatic: the client asks every
5966+
time, and may offer to remember the answer), `end` or `keep`. Nothing
5967+
keeps running on a host, or ends, without the user deciding.
5968+
`idleTimeoutSeconds` (600) is how long the host keeps a session whose
5969+
connection was lost and whose programs nobody kept; the server sets it and
5970+
no document changes it.
59605971
- `storage` is `{ relativePath: "remote/preferences.json", maximumBytes:
59615972
16384 }`.
59625973
- `sshConfig` is `{ path, exists }` for `.ssh/config` below `homeDirectory`,
@@ -5971,6 +5982,8 @@ sshConfig? }`:
59715982
makes the limit automatic with `null`.
59725983
- `reverseForwarding: { allowed: boolean|null }` allows or refuses reverse
59735984
forwards, or makes the switch automatic with `null`.
5985+
- `closePrograms: { programs: "ask"|"end"|"keep"|null }` stores the closing
5986+
choice, or makes it automatic with `null`.
59745987

59755988
The result is `{ changed, document: string|null }`; an unchanged edit
59765989
returns a `null` document and must not create a source. No field or more
@@ -5992,7 +6005,7 @@ user-settings resource does not affect code signatures or update deltas.
59926005
#### Remote connections that stay open
59936006

59946007
`remote.connect` takes `{ connection, servers: [{ target, path, sha256 }],
5995-
serverVersion, installRoot? }`. `servers` are the read-only server builds the
6008+
serverVersion, installRoot?, resume? }`. `servers` are the read-only server builds the
59966009
host ships, by Rust target; `sha256` is the build's SHA-256 as 64 hexadecimal
59976010
digits, taken from the manifest the application ships and signs with the
59986011
builds, never computed from the file Core is about to send. `installRoot`
@@ -6015,8 +6028,26 @@ and `{ stage: "installed", uploaded }` once the server is in place, where
60156028
failed attempt stops after the last stage reached, so a host without a
60166029
matching build stops after `platformChecked`. The result is `{ status, session,
60176030
host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName,
6018-
homeDirectory }` and is set only for `connected`. A host without a matching
6019-
build is `unsupportedPlatform` and nothing is uploaded.
6031+
homeDirectory, sessionKey, sessionToken, resumed, keptPrograms }` and is set
6032+
only for `connected`. A host without a matching build is
6033+
`unsupportedPlatform` and nothing is uploaded.
6034+
6035+
The server runs a persistent session (`--connect <sessionKey>`, with
6036+
`--state-dir <installRoot>` when one is given), so what it runs survives the
6037+
connection. `sessionKey` names that session and `sessionToken` is the secret
6038+
that attaches to it again; the client stores the token like a password and
6039+
never logs it. To attach to a session an earlier connection kept, pass
6040+
`resume: { key, token }` with the values it returned. `resumed` tells whether
6041+
this connection attached to it; `keptPrograms` lists the processes and
6042+
terminals it still runs, as `remote.runningPrograms` does, and is empty for
6043+
a new session. When the host refuses the token, because the session ended
6044+
and another took its key, Core connects once more without `resume`, so the
6045+
user authenticates again but is never locked out; that connection reports
6046+
`resumed: false` and a new key and token. A key that is empty, longer than 64
6047+
characters or not made of ASCII letters, digits, `.`, `_` and `-`, or a token
6048+
that is empty, longer than 128 characters or not hexadecimal, is
6049+
`invalid_request` with `{ field: "resume", reason: "invalid" }`, before
6050+
OpenSSH or `wsl.exe` starts.
60206051

60216052
Instead of `connection`, the request may name a WSL distribution on this
60226053
Windows machine as `wsl: { distribution, user? }`, where `distribution` is a
@@ -6045,9 +6076,18 @@ without sending anything; `details` says which of the two happened and, for a
60456076
mismatch, the SHA-256 Core computed, but never the path. Cancellation and the
60466077
five-minute bound are `cancelled` and `timed_out`.
60476078

6048-
Core keeps an open connection until `remote.disconnect` (`{ sessionId }`,
6049-
returning `{ closed }`) or until the host process exits; ending it terminates
6050-
the OpenSSH or `wsl.exe` process tree. `remote.closeAll` (no payload, returning
6079+
Core keeps an open connection until `remote.disconnect` (`{ sessionId,
6080+
programs? }`, returning `{ closed, kept }`) or until the host process exits;
6081+
ending it terminates the OpenSSH or `wsl.exe` process tree. `programs` is
6082+
`end` (the default), which ends the host session with every process and
6083+
terminal it runs, or `keep`, which tells the host to keep them and leaves
6084+
without ending the session; a later `remote.connect` with `resume` finds
6085+
them. `kept` tells whether the host keeps them: it is `false` for `end`, for
6086+
an unknown or closed connection (`closed: false`) and when the host could not
6087+
be told, whose programs then end like those of a client that crashed. A
6088+
session nobody kept, such as one whose client crashed or lost its network,
6089+
ends with its programs once the server's idle timeout (ten minutes) passes
6090+
without a client; one whose programs were kept lasts until they end. `remote.closeAll` (no payload, returning
60516091
`{ closed }` with the number of connections) ends all of them; the host calls
60526092
it while quitting because exiting without it can leave the OpenSSH tree and
60536093
the remote server running. Requests over it take `sessionId`:
@@ -6064,6 +6104,8 @@ the remote server running. Requests over it take `sessionId`:
60646104
| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin?, label? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` |
60656105
| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows, label? } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` |
60666106
| `remote.captureProcess` | `{ sessionId, params, timeoutMilliseconds, maxOutputBytes }` | base64 `stdout`, `stderr`, nullable `exitCode` and `signal` |
6107+
| `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` |
6108+
| `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 |
60676109

60686110
`remote.writeFile` replaces the file atomically on the host. With
60696111
`expected` (`{ size, modifiedMs }` from the read) a changed file is a

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,6 +1051,12 @@ pub enum RemoteCommand {
10511051
Preferences,
10521052
/// Changes one remote workspace preference (`remote.editPreferences`).
10531053
EditPreferences,
1054+
/// Lists the processes and terminals a host session still runs
1055+
/// (`remote.runningPrograms`).
1056+
RunningPrograms,
1057+
/// Ends every process and terminal a host session runs
1058+
/// (`remote.endPrograms`).
1059+
EndPrograms,
10541060
}
10551061

10561062
#[derive(Debug, Clone)]
@@ -1635,6 +1641,8 @@ impl CoreCommand {
16351641
}
16361642
"remote.preferences" => Some(Self::Remote(RemoteCommand::Preferences)),
16371643
"remote.editPreferences" => Some(Self::Remote(RemoteCommand::EditPreferences)),
1644+
"remote.runningPrograms" => Some(Self::Remote(RemoteCommand::RunningPrograms)),
1645+
"remote.endPrograms" => Some(Self::Remote(RemoteCommand::EndPrograms)),
16381646
"git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)),
16391647
"git.remotes" => Some(Self::Git(GitCommand::Remotes)),
16401648
"git.tags" => Some(Self::Git(GitCommand::Tags)),

‎rust/crates/core/src/runtime/dispatcher/remote.rs‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -305,12 +305,23 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, payload: Valu
305305
"Invalid remote preferences request",
306306
lithe_workspace::preferences::edit,
307307
),
308+
RemoteCommand::RunningPrograms => answer(
309+
id,
310+
payload,
311+
"Invalid remote programs request",
312+
lithe_workspace::programs::list,
313+
),
314+
RemoteCommand::EndPrograms => answer(
315+
id,
316+
payload,
317+
"Invalid remote programs request",
318+
lithe_workspace::programs::end,
319+
),
308320
RemoteCommand::Disconnect => {
309321
match serde_json::from_value::<lithe_workspace::sessions::DisconnectRequest>(payload) {
310-
Ok(request) => CoreResponse::success(
311-
id,
312-
json!({ "closed": lithe_workspace::sessions::disconnect(request) }),
313-
),
322+
Ok(request) => {
323+
CoreResponse::success(id, json!(lithe_workspace::sessions::disconnect(request)))
324+
}
314325
Err(error) => CoreResponse::failure(
315326
id,
316327
CoreError::new(

‎rust/crates/core/src/runtime/request_trace.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,8 @@ mod tests {
294294
"remote.startForward",
295295
"remote.startHostForward",
296296
"remote.startReverseForward",
297+
"remote.runningPrograms",
298+
"remote.endPrograms",
297299
"debug.launch",
298300
] {
299301
assert!(!is_hot(method), "{method}");

‎rust/crates/core/src/tests/remote_sessions.rs‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1678,3 +1678,126 @@ fn remote_host_and_reverse_forwards_follow_their_own_rules() {
16781678
true
16791679
);
16801680
}
1681+
1682+
#[test]
1683+
fn remote_programs_are_listed_ended_and_kept_only_by_a_persistent_session() {
1684+
use lithe_remote::client::api::{SpawnSpec, TerminalEvent, TerminalSpec};
1685+
use lithe_remote::protocol::methods::ResourceLabel;
1686+
1687+
let host = HostFixture::new();
1688+
let respond = |command: &str, payload: Value| -> Value {
1689+
serde_json::from_str(&crate::execute_json(
1690+
&json!({"id": test_support::unique_id(), "command": command,
1691+
"timeoutMilliseconds": 30_000, "payload": payload})
1692+
.to_string(),
1693+
))
1694+
.unwrap()
1695+
};
1696+
let call = |command: &str, payload: Value| -> Value {
1697+
let response = respond(command, payload);
1698+
assert_eq!(response["ok"], true, "{command}: {response}");
1699+
response["data"].clone()
1700+
};
1701+
let session = json!({"sessionId": host.id});
1702+
assert_eq!(
1703+
call("remote.runningPrograms", session.clone()),
1704+
json!({"programs": []})
1705+
);
1706+
1707+
let connection = test_support::connection(&host.id);
1708+
let process = connection
1709+
.session
1710+
.spawn(SpawnSpec {
1711+
argv: vec!["sleep".into(), "30".into()],
1712+
label: Some(ResourceLabel {
1713+
kind: "run".into(),
1714+
name: "server".into(),
1715+
}),
1716+
..SpawnSpec::default()
1717+
})
1718+
.unwrap();
1719+
let terminal = connection
1720+
.session
1721+
.open_terminal(TerminalSpec {
1722+
argv: Some(vec!["sleep".into(), "30".into()]),
1723+
cwd: None,
1724+
env: std::collections::BTreeMap::new(),
1725+
columns: 80,
1726+
rows: 24,
1727+
label: None,
1728+
})
1729+
.unwrap();
1730+
let listed = call("remote.runningPrograms", session.clone());
1731+
let programs = listed["programs"].as_array().unwrap();
1732+
let kinds: Vec<&str> = programs
1733+
.iter()
1734+
.map(|program| program["kind"].as_str().unwrap())
1735+
.collect();
1736+
assert_eq!(kinds, ["process", "terminal"], "{listed}");
1737+
assert_eq!(programs[0]["id"], process.id, "{listed}");
1738+
assert_eq!(programs[0]["argv"], json!(["sleep", "30"]), "{listed}");
1739+
assert_eq!(
1740+
programs[0]["label"],
1741+
json!({"kind": "run", "name": "server"}),
1742+
"{listed}"
1743+
);
1744+
assert_eq!(programs[1]["id"], terminal.id, "{listed}");
1745+
assert!(programs[1]["label"].is_null(), "{listed}");
1746+
1747+
// Only the programs named end, and one the session does not run is not
1748+
// counted; a kind other than process or terminal is refused.
1749+
let refused = respond(
1750+
"remote.endPrograms",
1751+
json!({"sessionId": host.id, "programs": [{"kind": "watch", "id": 1}]}),
1752+
);
1753+
assert_eq!(refused["ok"], false, "{refused}");
1754+
let named = json!({"sessionId": host.id, "programs": [
1755+
{"kind": "terminal", "id": terminal.id},
1756+
{"kind": "process", "id": process.id + 1000},
1757+
]});
1758+
assert_eq!(call("remote.endPrograms", named)["ended"], 1);
1759+
// The server forgets an exited program before it reports the exit.
1760+
loop {
1761+
match terminal.next_event(STEP).unwrap() {
1762+
Some(TerminalEvent::Exit(_)) => break,
1763+
Some(TerminalEvent::Output(_)) => {}
1764+
None => panic!("the terminal subscription ended before its exit"),
1765+
}
1766+
}
1767+
let left = call("remote.runningPrograms", session.clone());
1768+
assert_eq!(left["programs"].as_array().unwrap().len(), 1, "{left}");
1769+
assert_eq!(left["programs"][0]["kind"], "process", "{left}");
1770+
assert_eq!(call("remote.endPrograms", session.clone())["ended"], 1);
1771+
assert!(process.wait(STEP).unwrap().exit.is_some());
1772+
assert_eq!(
1773+
call("remote.runningPrograms", session.clone()),
1774+
json!({"programs": []})
1775+
);
1776+
assert_eq!(call("remote.endPrograms", session.clone())["ended"], 0);
1777+
drop((process, terminal));
1778+
drop(connection);
1779+
1780+
let refused = respond(
1781+
"remote.disconnect",
1782+
json!({"sessionId": host.id, "programs": "later"}),
1783+
);
1784+
assert_eq!(refused["ok"], false, "{refused}");
1785+
// An in-process session runs over standard streams and cannot outlive
1786+
// its client, so keeping its programs is refused and they end.
1787+
assert_eq!(
1788+
call(
1789+
"remote.disconnect",
1790+
json!({"sessionId": host.id, "programs": "keep"})
1791+
),
1792+
json!({"closed": true, "kept": false})
1793+
);
1794+
assert_eq!(
1795+
call(
1796+
"remote.disconnect",
1797+
json!({"sessionId": host.id, "programs": "end"})
1798+
),
1799+
json!({"closed": false, "kept": false})
1800+
);
1801+
let gone = respond("remote.runningPrograms", session);
1802+
assert_eq!(gone["ok"], false, "{gone}");
1803+
}

0 commit comments

Comments
 (0)