Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions rust/contracts/remote-workspace-protocol-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ socket, lock and log under `<dir>` (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
Expand Down Expand Up @@ -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) |
Expand Down Expand Up @@ -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.
Expand Down
60 changes: 51 additions & 9 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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, 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 |
Expand Down Expand Up @@ -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
Expand All @@ -5957,6 +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, 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`,
Expand All @@ -5971,6 +5982,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
Expand All @@ -5992,7 +6005,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`
Expand All @@ -6015,8 +6028,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 <sessionKey>`, with
`--state-dir <installRoot>` 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
Expand Down Expand Up @@ -6045,9 +6076,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`:
Expand All @@ -6064,6 +6104,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, 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
Expand Down
8 changes: 8 additions & 0 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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)),
Expand Down
19 changes: 15 additions & 4 deletions rust/crates/core/src/runtime/dispatcher/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,12 +305,23 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, 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::<lithe_workspace::sessions::DisconnectRequest>(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(
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/core/src/runtime/request_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ mod tests {
"remote.startForward",
"remote.startHostForward",
"remote.startReverseForward",
"remote.runningPrograms",
"remote.endPrograms",
"debug.launch",
] {
assert!(!is_hot(method), "{method}");
Expand Down
123 changes: 123 additions & 0 deletions rust/crates/core/src/tests/remote_sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1678,3 +1678,126 @@ 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}");

// 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.
loop {
match terminal.next_event(STEP).unwrap() {
Some(TerminalEvent::Exit(_)) => break,
Some(TerminalEvent::Output(_)) => {}
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": []})
);
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}");
}
Loading
Loading