From 654a6b14a8e1683d2a04c27ddaf77bfd64df1bae Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 11 Nov 2026 19:43:26 +0800 Subject: [PATCH] feat(git): mark reported queries and fold their output in the console Started events carry query: true for an internal query reported through reportQueries and false for a visible command. A console record passes the flag back, and git.consolePresentation folds a successful query's whole output into one query fragment labelled by its line count, the way IDEA keeps silent handlers out of sight. Failed queries and single-line output stay visible; search still locates every folded line. --- rust/lithe-core/src/git/console/output.rs | 17 +++++++- rust/lithe-core/src/git/console/tests.rs | 35 ++++++++++++++++ rust/lithe-core/src/git/console/types.rs | 7 +++- rust/lithe-core/src/git/execution_events.rs | 42 +++++++++++++++++++- shared/contracts/rust-core-api.md | 12 ++++-- shared/fixtures/git/execution-events-v1.json | 3 +- 6 files changed, 109 insertions(+), 7 deletions(-) diff --git a/rust/lithe-core/src/git/console/output.rs b/rust/lithe-core/src/git/console/output.rs index f2a76de4..ba9f12cb 100644 --- a/rust/lithe-core/src/git/console/output.rs +++ b/rust/lithe-core/src/git/console/output.rs @@ -1,9 +1,24 @@ -//! IDEA-style progress folding; ordinary command output remains continuous text. +//! IDEA-style progress and query folding; ordinary command output remains continuous text. use super::types::{OutputFragment, Record}; use regex::Regex; use std::sync::OnceLock; pub(super) fn project(record: &Record) -> Vec { + // A query's output answers the workflow, not the user: like IDEA's silent handlers it + // stays out of sight, folded whole, unless the query failed or wrote a single line. + if record.query && record.lines.len() > 1 && !record.failed() { + return vec![OutputFragment { + id: "output-0".into(), + start: 0, + end: record.lines.len(), + kind: "query".into(), + count: record.lines.len(), + added: 0, + updated: 0, + deleted: 0, + matches: 0, + }]; + } let mut result = Vec::new(); let mut start = 0; while start < record.lines.len() { diff --git a/rust/lithe-core/src/git/console/tests.rs b/rust/lithe-core/src/git/console/tests.rs index e0d2ce97..c3bfaa1b 100644 --- a/rust/lithe-core/src/git/console/tests.rs +++ b/rust/lithe-core/src/git/console/tests.rs @@ -200,3 +200,38 @@ fn expected_nonzero_queries_are_distinct_from_real_failures_and_limits_are_expli ) .is_err()); } + +#[test] +fn query_output_folds_whole_unless_the_query_failed_or_wrote_one_line() { + let make = |count: usize, query: bool, state: &str, exit: Option| -> Request { + serde_json::from_value(json!({"search":"line 7", "records":[{ + "id":"log", "root":"/repo", "arguments":["log","--max-count=50"], "state":state, + "exitCode":exit, "query":query, + "lines":(0..count).map(|i| json!({"stream":"stdout","text":format!("line {i}")})).collect::>() + }]})).unwrap() + }; + for state in ["running", "completed"] { + let folded = present(make(40, true, state, (state == "completed").then_some(0))).unwrap(); + let output = &folded.entries[0].output; + assert_eq!(output.len(), 1, "{state}"); + assert_eq!( + ( + output[0].kind.as_str(), + output[0].start, + output[0].end, + output[0].count + ), + ("query", 0, 40, 40) + ); + // Search still reaches every folded line, so a host can open the fold on a hit. + assert_eq!(folded.matches[0].line_index, Some(7)); + assert_eq!(output[0].matches, 1); + } + let failed = present(make(40, true, "completed", Some(128))).unwrap(); + assert!(failed.entries[0].failed); + assert!(failed.entries[0].output.iter().all(|f| f.kind == "text")); + let single = present(make(1, true, "completed", Some(0))).unwrap(); + assert_eq!(single.entries[0].output[0].kind, "text"); + let visible = present(make(40, false, "completed", Some(0))).unwrap(); + assert!(visible.entries[0].output.iter().all(|f| f.kind == "text")); +} diff --git a/rust/lithe-core/src/git/console/types.rs b/rust/lithe-core/src/git/console/types.rs index 5f9afbd3..594e4740 100644 --- a/rust/lithe-core/src/git/console/types.rs +++ b/rust/lithe-core/src/git/console/types.rs @@ -57,6 +57,10 @@ pub struct Record { pub remote_result: Option, #[serde(default)] pub truncated: bool, + /// The `query` of the record's `started` event: an internal query the workflow reported + /// only because the request asked for queries. Its output is folded unless it failed. + #[serde(default)] + pub query: bool, } #[derive(Debug, Deserialize)] @@ -137,7 +141,8 @@ pub struct OutputFragment { pub id: String, pub start: usize, pub end: usize, - /// text or progress; a folded progress range uses its last original line as its label. + /// text, progress or query; a folded progress range uses its last original line as its + /// label, and a query range, which folds a query's whole output, is labelled by `count`. pub kind: String, /// Number of original lines in the range. pub count: usize, diff --git a/rust/lithe-core/src/git/execution_events.rs b/rust/lithe-core/src/git/execution_events.rs index 8d699793..fafbb7f5 100644 --- a/rust/lithe-core/src/git/execution_events.rs +++ b/rust/lithe-core/src/git/execution_events.rs @@ -83,6 +83,9 @@ enum Kind<'a> { /// Native presentation folds global options without rewriting actual argv. display_arguments: Vec, global_arguments: Vec, + /// An internal query reported through `reportQueries`, as opposed to a command the + /// workflow runs visibly; consoles fold a query's output by default. + query: bool, }, Output { invocation_id: u64, @@ -240,6 +243,8 @@ pub(super) struct Invocation { /// stays visible while stdout is replaced with one explicit redaction marker. redact_configuration: Cell, configuration_marker_sent: bool, + /// The child is an internal query reported only because the request asked for queries. + query: bool, } impl Invocation { /// The invocation that reports a child: visible commands always report, and internal @@ -250,7 +255,9 @@ impl Invocation { execution_policy::current().report_queries && execution_policy::source() != Source::Background }; - (visible || query()).then(Self::current).flatten() + let mut invocation = (visible || query()).then(Self::current).flatten()?; + invocation.query = !visible; + Some(invocation) } /// Whether an internal query's nonzero exit answered its question, such as a missing /// config key or an absent ref. A visible command's nonzero exit is always Git's failure. @@ -278,6 +285,7 @@ impl Invocation { pending_progress: None, redact_configuration: Cell::new(false), configuration_marker_sent: false, + query: false, }) }) } @@ -361,6 +369,7 @@ impl Invocation { invocation_id: self.id, working_directory: root, arguments: &arguments, + query: self.query, }, ); } @@ -860,6 +869,37 @@ mod tests { assert_eq!(records, [true, false]); } + #[test] + fn reported_queries_are_marked_apart_from_visible_commands() { + let options = crate::git::execution_policy::GitExecutionOptions { + report_queries: true, + ..Default::default() + }; + let _policy = crate::git::execution_policy::Scope::begin(Some(options)).unwrap(); + let events = capture_request(|| { + request_started(Some("marked")); + let query = Invocation::reported(false).unwrap(); + query.started("/workspace", &["log".into()]); + query.finished(Some(0), None); + let command = Invocation::reported(true).unwrap(); + command.started("/workspace", &["commit".into()]); + command.finished(Some(0), None); + request_finished(r#"{"ok":true,"data":{}}"#); + }); + let marks: Vec<_> = events + .iter() + .filter(|event| event["type"] == "started") + .map(|event| (event["arguments"][0].clone(), event["query"].clone())) + .collect(); + assert_eq!( + marks, + [ + (serde_json::json!("log"), serde_json::json!(true)), + (serde_json::json!("commit"), serde_json::json!(false)) + ] + ); + } + #[test] fn request_finished_names_unconfirmed_records_and_early_failures() { let events = capture_request(|| { diff --git a/shared/contracts/rust-core-api.md b/shared/contracts/rust-core-api.md index 2256ec52..6c596023 100644 --- a/shared/contracts/rust-core-api.md +++ b/shared/contracts/rust-core-api.md @@ -1503,7 +1503,7 @@ package manager owns the download and Lithe does not infer bytes from logs. | `git.resolveFileContext` | Resolve a file to its owning Git checkout and relative path | | `git.write` | Validate and execute shared Git mutations such as stage, commit, branch, checkout, remote sync, clone, and stash | | `git.fetchPlan` | Validate Fetch choices; optionally inspect a repository to expand enabled per-remote commands | -| `git.consolePresentation` | Pure IDEA-style configuration/progress folds, empty-output notices and search ranges over retained diagnostic snapshots | +| `git.consolePresentation` | Pure IDEA-style configuration/progress/query folds, empty-output notices and search ranges over retained diagnostic snapshots | | `git.remoteUrl` | Read a configured remote URL silently; a missing remote returns a null URL | | `git.executionInspect` | Inspect executable capabilities, configuration provenance and effective Fetch preferences | | `git.executionConfigure` | Explicitly save or clear one allowlisted value in a selected config scope | @@ -2059,7 +2059,7 @@ Each event has `operationId` and `type`: | Type | Additional fields | | --- | --- | | `requestStarted` | none; cancellation is registered before delivery | -| `started` | `invocationId`, `workingDirectory`, `arguments`, nullable resolved `executable`, `temporaryConfig` key/value pairs, `displayArguments`, `globalArguments`, `source` | +| `started` | `invocationId`, `workingDirectory`, `arguments`, nullable resolved `executable`, `temporaryConfig` key/value pairs, `displayArguments`, `globalArguments`, `source`, `query` | | `output` | `invocationId`, `stream` (`stdout`/`stderr`), `text`, `progress`, `truncated`, optional `progressDetails` (`stage`, nullable `percent`, `completed`, `total`) | | `finished` | `invocationId`, nullable `exitCode`, monotonic `durationMilliseconds`, nullable `error`, `expectedExit` | | `requestFinished` | nullable `error`, including failures before a child started; `unconfirmedInvocations`, the started records without `finished`; `failureRecord`, true when `error` is set, is not a cancellation, and no record of the request failed or is unconfirmed, so the host shows the error as its own record | @@ -2102,7 +2102,13 @@ events. Internal read-only queries remain silent in the console while retaining normal workflow capture and result semantics, unless the request sets `gitExecution.reportQueries`: then each query produces the same `started`, `output` and `finished` events as a visible command, so the console records what the -workbench read. Queries of a request whose provenance is `background` (an +workbench read. Their `started` event carries `query: true`; every visible command +carries `query: false`. A host passes the flag back as the console record's +`query`, and `git.consolePresentation` then folds a query's whole output into one +`query` output fragment whose `count` labels it, the way IDEA keeps silent +handlers out of sight. A failed query and a query that wrote a single line keep +their output visible. Search still counts and locates every folded line, so a +host opens the fold on a hit. Queries of a request whose provenance is `background` (an automatic refresh or watcher, which runs too often to record) stay silent even then; provenance is `gitExecution.source`, or the envelope origin when that is unknown. Reported queries never authenticate or prompt; a query that needs diff --git a/shared/fixtures/git/execution-events-v1.json b/shared/fixtures/git/execution-events-v1.json index fb1b8d4d..cd8fcb69 100644 --- a/shared/fixtures/git/execution-events-v1.json +++ b/shared/fixtures/git/execution-events-v1.json @@ -47,7 +47,8 @@ "-c", "log.showSignature=false" ], - "source": "unknown" + "source": "unknown", + "query": false }, { "operationId": "fixture",