Skip to content

Commit 41432d4

Browse files
authored
feat(process): add process.listeningPorts resolution for run sessions (#131)
1 parent 6c84d32 commit 41432d4

9 files changed

Lines changed: 881 additions & 1 deletion

File tree

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,7 @@ or removing a command fails until the table changes in the same commit.
650650
| `processLifecycle.inventory` | Group a process snapshot of one Lithe instance into terminals, Agent tasks and background services |
651651
| `processLifecycle.settle` | Turn confirmation answers into what ends, what is kept and the updated settings |
652652
| `processMemory.summarize` | Sum a process table's memory, compressed memory, graphics memory and processor and graphics use by part of one Lithe instance: the host, language servers, plugin services, system helpers and other child processes |
653+
| `process.listeningPorts` | Filter, normalize, deduplicate, and format listening TCP ports for one run process tree |
653654
| `markdown.render` | Renders and sanitizes shared Markdown |
654655
| `markdown.outline` | Outlines the headings of shared Markdown as a document-symbol tree |
655656
| `markdown.resolveReference` | Decides what a link or an image of a rendered Markdown document points at |
@@ -6295,6 +6296,32 @@ A table without the host or with a repeated process ID, or a `logicalProcessors`
62956296
of 0, is `invalid_request`. Fixtures live in
62966297
`rust/fixtures/process-lifecycle/memory-summary-v1.json`.
62976298

6299+
`process.listeningPorts` accepts `{ rootProcessId, processes, sockets,
6300+
excludePorts?, limit? }` and returns `{ schemaVersion, ports, truncated }` for
6301+
one running session's process tree:
6302+
6303+
- `rootProcessId` must be a positive integer. `processes` is a list of
6304+
`{ processId, parentProcessId, startTime? }`; parent links where
6305+
`parent.startTime > child.startTime` are ignored as PID reuse, and
6306+
`rootProcessId` itself is always included even when `processes` is empty.
6307+
- `sockets` is a list of `{ processId, address, port }`. Addresses are trimmed,
6308+
unwrapped from `[...]`, stripped of IPv6 `%zone` suffixes, mapped from `""` /
6309+
`"*"` to `"0.0.0.0"`, and unwrapped from IPv4-mapped IPv6 `::ffff:a.b.c.d` to
6310+
IPv4; non-IP strings return `invalid_request`.
6311+
- Sockets with `port == 0`, ports listed in `excludePorts` (such as an
6312+
attached debugger port), or `processId` outside the tree are filtered out.
6313+
- Multiple sockets sharing a port (for example dual-stack `0.0.0.0` + `::`)
6314+
collapse deterministically to one entry, preferring loopback/unspecified binds,
6315+
then IPv4 over IPv6, then loopback over unspecified, then lowest `processId`.
6316+
- Loopback and unspecified binds (`127.0.0.0/8`, `0.0.0.0`, `::1`, `::`) format
6317+
`label` as `:<port>` and `url` as `http://localhost:<port>`; specific
6318+
interface binds format `label` as `<ip>:<port>` / `[<ip>]:<port>` and `url`
6319+
as `http://<ip>:<port>` / `http://[<ip>]:<port>`.
6320+
- Results are ordered ascending by `port`; `limit` defaults to 8 and is clamped
6321+
to `1..=32`, with `truncated: true` when more matching ports existed.
6322+
6323+
Fixtures live in `rust/fixtures/process-lifecycle/listening-ports-v1.json`.
6324+
62986325
## Local IDE capability broker
62996326

63006327
`ideHost.control` accepts `{action, arguments}` and delegates to the native

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,9 @@ pub enum CoreCommand {
130130
ProcessLifecycleSettle,
131131
/// Sums a process table's memory by part of the instance (`processMemory.summarize`).
132132
ProcessMemorySummarize,
133+
/// Filters, normalizes, and formats listening TCP ports of one process tree
134+
/// (`process.listeningPorts`).
135+
ProcessListeningPorts,
133136
/// Renders and sanitizes shared Markdown (`markdown.render`).
134137
MarkdownRender,
135138
/// Outlines the headings of shared Markdown as document symbols (`markdown.outline`).
@@ -1336,6 +1339,7 @@ impl CoreCommand {
13361339
"processLifecycle.inventory" => Some(Self::ProcessLifecycleInventory),
13371340
"processLifecycle.settle" => Some(Self::ProcessLifecycleSettle),
13381341
"processMemory.summarize" => Some(Self::ProcessMemorySummarize),
1342+
"process.listeningPorts" => Some(Self::ProcessListeningPorts),
13391343
"markdown.render" => Some(Self::MarkdownRender),
13401344
"markdown.outline" => Some(Self::MarkdownOutline),
13411345
"markdown.resolveReference" => Some(Self::MarkdownResolveReference),
@@ -1820,6 +1824,10 @@ mod tests {
18201824
CoreCommand::parse("processMemory.summarize"),
18211825
Some(CoreCommand::ProcessMemorySummarize)
18221826
));
1827+
assert!(matches!(
1828+
CoreCommand::parse("process.listeningPorts"),
1829+
Some(CoreCommand::ProcessListeningPorts)
1830+
));
18231831
}
18241832

18251833
#[test]

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,25 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
462462
),
463463
}
464464
}
465+
CoreCommand::ProcessListeningPorts => {
466+
match serde_json::from_value::<lithe_process::ports::ListeningPortsRequest>(
467+
parsed.payload,
468+
)
469+
.map_err(|error| error.to_string())
470+
.and_then(|request| {
471+
lithe_process::ports::resolve(&request).map_err(|error| error.to_string())
472+
}) {
473+
Ok(ports) => CoreResponse::success(
474+
id,
475+
serde_json::to_value(ports).expect("listening ports response should encode"),
476+
),
477+
Err(details) => CoreResponse::failure(
478+
id,
479+
CoreError::new(ErrorCode::InvalidRequest, "Invalid listening ports request")
480+
.with_details(details),
481+
),
482+
}
483+
}
465484
CoreCommand::Editor(command) => editor::dispatch(command, id, parsed.payload, document),
466485
CoreCommand::WorkbenchChromeLayoutReduce => {
467486
rules_response(id, "workbench.chromeLayout.reduce", parsed.payload)

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,10 @@ pub(crate) fn is_hot(method: &str) -> bool {
197197
method,
198198
"workspace.filterChanges" | "lsp.workspaceFilesChanged" | "git.classifyMetadataChanges"
199199
)
200-
// The status bar sums the instance's memory every few seconds while it is shown.
200+
// The status bar sums the instance's memory every few seconds while it is shown,
201+
// and active runs probe their process tree's listening ports periodically.
201202
|| method == "processMemory.summarize"
203+
|| method == "process.listeningPorts"
202204
}
203205

204206
/// Explicit host provenance wins; Git provenance covers hosts that send only that.
@@ -275,6 +277,7 @@ mod tests {
275277
"git.classifyMetadataChanges",
276278
"debug.transport.handle",
277279
"processMemory.summarize",
280+
"process.listeningPorts",
278281
] {
279282
assert!(is_hot(method), "{method}");
280283
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ mod plugin_settings_documents;
5454
mod plugin_source_settings;
5555
mod plugin_views;
5656
mod process_memory;
57+
mod process_ports;
5758
mod project;
5859
mod project_generators;
5960
mod project_tree;
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//! `process.listeningPorts` against the shared listening-ports fixture.
2+
3+
use serde_json::{json, Value};
4+
5+
fn run(request: &Value) -> Value {
6+
serde_json::from_str(&crate::execute_json(
7+
&json!({"command": "process.listeningPorts", "payload": request}).to_string(),
8+
))
9+
.unwrap()
10+
}
11+
12+
#[test]
13+
fn shared_listening_ports_fixture_runs_every_case() {
14+
let fixture: Value = serde_json::from_str(include_str!(concat!(
15+
env!("CARGO_MANIFEST_DIR"),
16+
"/../../fixtures/process-lifecycle/listening-ports-v1.json"
17+
)))
18+
.unwrap();
19+
for case in fixture["cases"].as_array().unwrap() {
20+
let response = run(&case["request"]);
21+
assert_eq!(response["ok"], true, "case {}: {response}", case["name"]);
22+
assert_eq!(response["data"], case["expected"], "case {}", case["name"]);
23+
}
24+
for case in fixture["invalid"].as_array().unwrap() {
25+
let response = run(&case["request"]);
26+
assert_eq!(response["ok"], false, "case {}: {response}", case["name"]);
27+
assert_eq!(
28+
response["error"]["code"], "invalid_request",
29+
"case {}",
30+
case["name"]
31+
);
32+
}
33+
}

‎rust/crates/process/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@
44
pub mod inventory;
55
pub mod lifecycle;
66
pub mod memory;
7+
pub mod ports;

0 commit comments

Comments
 (0)