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
16 changes: 13 additions & 3 deletions rust/contracts/remote-workspace-protocol-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ subscribe before creating the resource.
| `server.ack` | `seq` | `null`; events up to `seq` may be forgotten |
| `server.shutdown` | — | `null`; the session ends |
| `server.ping` | — | `{}` |
| `server.state` | — | running `processes`, `terminals`, `watches` |
| `server.state` | — | running `processes` (`processId`, `pid`, `argv`, `label?`, `runningMs`, `leaderExited`), `terminals` (`terminalId`, `pid`, `argv`, `label?`, `runningMs`, `columns`, `rows`), `watches` |
| `fs.stat` | `path` | metadata of the path itself (links not followed) |
| `fs.readDir` | `path` | `entries` sorted by name byte order, `skippedNonUtf8` |
| `fs.readFile` | `path`, `offset`, `length` (≤ 8 MiB) | `data`, `eof`, `metadata` |
Expand All @@ -131,11 +131,11 @@ subscribe before creating the resource.
| `walk.cancel` | `walkId` | `null` |
| `watch.start` | `watchId`, `root`, `excludeNames` | `watchedDirectories` (per-directory backends) |
| `watch.stop` | `watchId` | `null` |
| `process.spawn` | `processId`, `argv`, `cwd?`, `environment` (`server` / `login`), `env`, `pipeStdin` | `pid` |
| `process.spawn` | `processId`, `argv`, `cwd?`, `environment` (`server` / `login`), `env`, `pipeStdin`, `label?` | `pid` |
| `process.writeStdin` | `processId`, `data` | `null`; `BUSY` when the process stops reading |
| `process.closeStdin` | `processId` | `null` |
| `process.kill` | `processId`, `force` | `null`; signals every process of its session, also after `process.exit` while members run; `UNKNOWN_RESOURCE` once the session is empty |
| `terminal.open` | `terminalId`, `argv?`, `cwd?`, `env`, `columns`, `rows` | `pid`; default program is the login shell |
| `terminal.open` | `terminalId`, `argv?`, `cwd?`, `env`, `columns`, `rows`, `label?` | `pid`; default program is the login shell |
| `terminal.write` | `terminalId`, `data` | `null`; `BUSY` when not read |
| `terminal.resize` | `terminalId`, `columns`, `rows` | `null` |
| `terminal.close` | `terminalId` | `null`; `SIGHUP` to its session, `SIGKILL` after 2 s |
Expand Down Expand Up @@ -215,6 +215,16 @@ its session until no member is left, so members that outlive the leader can
still be killed and are cleaned up when the session ends; `server.state`
marks such processes with `leaderExited`.

`server.state` lets a client list what still runs before it closes a window,
and lets a later client list what an earlier one left running. `label`
(`kind` ≤ 64 characters, `name` ≤ 256 characters, no control characters)
is what the client shows for the resource; the server stores it unchanged,
never interprets it, and refuses a label that breaks a rule with
`INVALID_REQUEST` before starting anything. `runningMs` counts from the
start on the server's monotonic clock, so it is right after a client
restart and whatever the clients' clocks say. A terminal's `argv` is the
program actually started: the requested `argv`, or the login shell's path.

When a session ends, the server terminates everything it still owns
(`SIGTERM` or `SIGHUP`, then `SIGKILL` after 2 seconds to sessions that still
have members), lets running requests finish for up to 5 seconds, and exits.
Expand Down
8 changes: 5 additions & 3 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5727,8 +5727,8 @@ the remote server running. Requests over it take `sessionId`:
| `remote.hostInfo` | `{ sessionId }` | the original connection's handshake `host`, including OS, architecture, home and features |
| `remote.uploadFile` | `{ sessionId, sourcePath, path, sha256, mode }` | verified `{ size, sha256 }` |
| `remote.runWatch` | `{ sessionId, params: { root, excludeNames? } }` | waits until root removal or cancellation; relays `watch.started`, `watch.changed`, `watch.error` |
| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` |
| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` |
| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin?, label? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` |
| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows, label? } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` |
| `remote.captureProcess` | `{ sessionId, params, timeoutMilliseconds, maxOutputBytes }` | base64 `stdout`, `stderr`, nullable `exitCode` and `signal` |

`remote.writeFile` replaces the file atomically on the host. With
Expand All @@ -5739,7 +5739,9 @@ fails with `connection_closed` and is forgotten, so the host reconnects; an
unknown or closed `sessionId` is also `connection_closed`.

`remote.hostRequest` accepts finite filesystem, environment and port queries,
plus controls of existing processes and terminals. Creating a watch, process,
`server.state` (what still runs, with the `label` given at start, so the host
can ask before closing a window), plus controls of existing processes and
terminals. Creating a watch, process,
terminal, walk or tunnel through that command is `invalid_request`; creation
requires an owner that subscribes before sending the start request. Streamed
Core events use `{ type: "remote", event, params }`. Resource IDs are allocated
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/git/src/remote_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ pub(super) fn parameters(
environment: EnvironmentSource::Login,
env,
pipe_stdin,
label: None,
})
}

Expand Down Expand Up @@ -278,6 +279,7 @@ fn remote_git_executable(
environment: EnvironmentSource::Login,
env: BTreeMap::new(),
pipe_stdin: false,
label: None,
},
None,
&mut |event| {
Expand Down
1 change: 1 addition & 0 deletions rust/crates/lsp-transport/src/remote_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ pub(crate) fn launch(host: Host, spec: LspProcessSpec) -> Result<LspProcessStrea
environment: EnvironmentSource::Login,
env: spec.environment,
pipe_stdin: true,
label: None,
};
let pending = process
.connection
Expand Down
18 changes: 12 additions & 6 deletions rust/crates/remote/src/client/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ use crate::protocol::methods::{
EnvironmentResolveParams, EnvironmentResolveResult, EnvironmentSource, FileMetadata,
FileVersion, KillParams, ListeningPort, ListeningPortsResult, OutputStream, PathParams,
ProcessExitEvent, ProcessOutputEvent, ProcessParams, ReadDirResult, ReadFileParams,
ReadFileResult, RealPathResult, RemoveParams, RenameParams, ServerState, SetPermissionsParams,
SpawnParams, SpawnResult, TerminalExitEvent, TerminalOpenParams, TerminalOpenResult,
TerminalOutputEvent, TerminalParams, TerminalResizeParams, TerminalWriteParams,
TunnelClosedEvent, TunnelDataEvent, TunnelOpenParams, TunnelParams, TunnelTarget,
TunnelWriteParams, VolumeInfo, WalkDoneEvent, WalkEntriesEvent, WalkEntry, WalkParams,
WalkStartParams, WatchChangedEvent, WatchErrorEvent, WatchParams, WatchStartParams,
ReadFileResult, RealPathResult, RemoveParams, RenameParams, ResourceLabel, ServerState,
SetPermissionsParams, SpawnParams, SpawnResult, TerminalExitEvent, TerminalOpenParams,
TerminalOpenResult, TerminalOutputEvent, TerminalParams, TerminalResizeParams,
TerminalWriteParams, TunnelClosedEvent, TunnelDataEvent, TunnelOpenParams, TunnelParams,
TunnelTarget, TunnelWriteParams, VolumeInfo, WalkDoneEvent, WalkEntriesEvent, WalkEntry,
WalkParams, WalkStartParams, WatchChangedEvent, WatchErrorEvent, WatchParams, WatchStartParams,
WatchStartResult, WriteFileParams, MAX_TRANSFER_BYTES,
};
use crate::protocol::{ErrorCode, RemoteError};
Expand Down Expand Up @@ -64,6 +64,8 @@ pub struct SpawnSpec {
pub env: BTreeMap<String, String>,
/// Keep standard input open for [`ProcessHandle::write_stdin`].
pub pipe_stdin: bool,
/// What [`RemoteSession::state`] reports for the process.
pub label: Option<ResourceLabel>,
}

/// What to open in [`RemoteSession::open_terminal`].
Expand All @@ -80,6 +82,8 @@ pub struct TerminalSpec {
pub columns: u16,
/// Initial height in character cells.
pub rows: u16,
/// What [`RemoteSession::state`] reports for the terminal.
pub label: Option<ResourceLabel>,
}

/// A finished process's collected output.
Expand Down Expand Up @@ -386,6 +390,7 @@ impl RemoteSession {
environment: spec.environment,
env: spec.env,
pipe_stdin: spec.pipe_stdin,
label: spec.label,
},
);
match result {
Expand Down Expand Up @@ -415,6 +420,7 @@ impl RemoteSession {
env: spec.env,
columns: spec.columns,
rows: spec.rows,
label: spec.label,
},
);
match result {
Expand Down
46 changes: 46 additions & 0 deletions rust/crates/remote/src/protocol/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,13 @@ pub struct ProcessState {
pub pid: u32,
/// Program and arguments the process was spawned with.
pub argv: Vec<String>,
/// The label the process was spawned with.
#[serde(default)]
pub label: Option<ResourceLabel>,
/// Milliseconds since the server started the process, on the server's
/// monotonic clock, so it stays right across client restarts and clock
/// differences between the machines.
pub running_ms: u64,
/// The process itself exited, but members of its session still run;
/// `process.kill` still reaches them.
pub leader_exited: bool,
Expand All @@ -489,12 +496,45 @@ pub struct TerminalState {
pub terminal_id: u64,
/// Operating-system pid of the terminal's program, for diagnostics only.
pub pid: u32,
/// Program and arguments the terminal runs: those it was opened with,
/// or the path of the login shell it started by default.
pub argv: Vec<String>,
/// The label the terminal was opened with.
#[serde(default)]
pub label: Option<ResourceLabel>,
/// Milliseconds since the server started the terminal's program, on the
/// server's monotonic clock.
pub running_ms: u64,
/// Current width in character cells.
pub columns: u16,
/// Current height in character cells.
pub rows: u16,
}

/// Longest [`ResourceLabel::kind`], in characters.
pub const MAX_LABEL_KIND_CHARS: usize = 64;
/// Longest [`ResourceLabel::name`], in characters.
pub const MAX_LABEL_NAME_CHARS: usize = 256;

/// What a client shows for a process or terminal when it lists the session's
/// resources: when a window closes while they still run, or after a new
/// client reconnects to a persistent session and no longer knows what it
/// started. The server keeps it unchanged with the resource and returns it in
/// `server.state`; it never interprets it.
///
/// Neither field may contain control characters; a label that breaks a rule
/// fails the request with `INVALID_REQUEST`.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ResourceLabel {
/// Client-defined category, such as `run`, `task` or `debug`; at most
/// [`MAX_LABEL_KIND_CHARS`].
pub kind: String,
/// Name shown to the user, such as a run configuration's name; at most
/// [`MAX_LABEL_NAME_CHARS`].
pub name: String,
}

/// An active watch.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -945,6 +985,9 @@ pub struct SpawnParams {
/// process reads end-of-file immediately.
#[serde(default)]
pub pipe_stdin: bool,
/// What `server.state` reports for the process.
#[serde(default)]
pub label: Option<ResourceLabel>,
}

/// Result of `process.spawn`.
Expand Down Expand Up @@ -1046,6 +1089,9 @@ pub struct TerminalOpenParams {
pub columns: u16,
/// Initial height in character cells.
pub rows: u16,
/// What `server.state` reports for the terminal.
#[serde(default)]
pub label: Option<ResourceLabel>,
}

/// Result of `terminal.open`.
Expand Down
57 changes: 52 additions & 5 deletions rust/crates/remote/src/server/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@

use crate::protocol::methods::{
self, decode_bytes, encode_bytes, EnvironmentSource, KillParams, OutputStream,
ProcessExitEvent, ProcessOutputEvent, ProcessParams, ProcessState, SpawnParams, SpawnResult,
WriteStdinParams,
ProcessExitEvent, ProcessOutputEvent, ProcessParams, ProcessState, ResourceLabel, SpawnParams,
SpawnResult, WriteStdinParams,
};
use crate::protocol::{ErrorCode, RemoteError};
use crate::server::connection::Context;
use crate::server::fs::{host_path, io_error};
use crate::server::platform::{self, ChildKind};
use crate::server::resources::Registry;
use crate::server::resources::{validate_label, Registry};
use crate::server::session::Session;
use crate::server::threads::Parked;
use crate::server::{parse, to_value};
Expand Down Expand Up @@ -56,11 +56,23 @@ pub(crate) struct Leader {
pub(crate) pid: u32,
/// Set when the leader exited and its exit event was sent.
pub(crate) exited: bool,
/// When the server started the leader.
started: Instant,
}

impl Leader {
pub(crate) fn new(pid: u32) -> Self {
Self { pid, exited: false }
Self {
pid,
exited: false,
started: Instant::now(),
}
}

/// Whole milliseconds from the leader's start to `now`, the moment
/// `server.state` reads every entry at.
pub(crate) fn running_ms(&self, now: Instant) -> u64 {
u64::try_from(now.saturating_duration_since(self.started).as_millis()).unwrap_or(u64::MAX)
}
}

Expand Down Expand Up @@ -100,6 +112,7 @@ pub(crate) struct ProcessTable {
struct RunningProcess {
leader: Leader,
argv: Vec<String>,
label: Option<ResourceLabel>,
/// `None` when standard input was not piped or has been closed.
stdin: Option<SyncSender<Vec<u8>>>,
}
Expand Down Expand Up @@ -129,14 +142,16 @@ impl ProcessTable {
}
}

pub(crate) fn states(&self) -> Vec<ProcessState> {
pub(crate) fn states(&self, now: Instant) -> Vec<ProcessState> {
self.registry
.lock()
.iter()
.map(|(process_id, process)| ProcessState {
process_id: *process_id,
pid: process.leader.pid,
argv: process.argv.clone(),
label: process.label.clone(),
running_ms: process.leader.running_ms(now),
leader_exited: process.leader.exited,
})
.collect()
Expand All @@ -153,6 +168,7 @@ impl ProcessTable {
let Some((program, arguments)) = params.argv.split_first() else {
return Err(RemoteError::new(ErrorCode::InvalidRequest, "argv is empty"));
};
validate_label(params.label.as_ref())?;
let mut command = Command::new(program);
command
.args(arguments)
Expand Down Expand Up @@ -192,6 +208,7 @@ impl ProcessTable {
let entry = RunningProcess {
leader: Leader::new(pid),
argv: params.argv.clone(),
label: params.label,
stdin,
};
if let Err(error) = self.registry.insert(params.process_id, entry) {
Expand Down Expand Up @@ -545,3 +562,33 @@ impl OutputGate {
exit();
}
}

#[cfg(test)]
mod tests {
use super::Leader;
use std::time::{Duration, Instant};

fn started_at(started: Instant) -> Leader {
Leader {
pid: 1,
exited: false,
started,
}
}

#[test]
fn running_time_counts_whole_milliseconds_since_the_start() {
let started = Instant::now();
let leader = started_at(started);
assert_eq!(leader.running_ms(started), 0);
assert_eq!(leader.running_ms(started + Duration::from_micros(1_999)), 1);
assert_eq!(leader.running_ms(started + Duration::from_secs(90)), 90_000);
}

#[test]
fn running_time_is_never_negative() {
let started = Instant::now();
let leader = started_at(started + Duration::from_secs(1));
assert_eq!(leader.running_ms(started), 0);
}
}
Loading
Loading