Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

feat(term): parse program status reports and keep them per terminal

RoversX3c1b08da99dc
diff --git a/term/src/lib.rs b/term/src/lib.rs
index d4798c5c..b1968b78 100644
--- a/term/src/lib.rs
+++ b/term/src/lib.rs
@@ -33,6 +33,7 @@ pub mod kitty_animation;
pub mod kitty_placeholder;
pub mod kitty_relative;
pub mod kitty_virtual;
+pub mod program_status;
/// Graphics state carried alongside the unchanged legacy terminal snapshot.
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/term/src/program_status.rs b/term/src/program_status.rs
new file mode 100644
index 00000000..a33133c2
--- /dev/null
+++ b/term/src/program_status.rs
@@ -0,0 +1,396 @@
+//! What programs have told the terminal about themselves with OSC 7501.
+//!
+//! A program files records under ids of its choosing: the root record
+//! (no id) for itself, `/`-separated paths for parts of its work such as
+//! sub-tasks. The terminal keeps them until they are replaced, cleared, or
+//! outlived by the program they describe, and answers questions about them;
+//! deciding what they mean for the interface is the mux's business.
+
+use std::collections::HashMap;
+pub use wezterm_escape_parser::osc::{ProgramBlockedKind, ProgramState, ProgramStatusReport};
+
+/// One record, as a program last reported it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ProgramStatusRecord {
+ /// Local receipt identity; even identical reports are new emissions.
+ pub serial: u64,
+ /// Foreground process group observed when this report was received.
+ pub process_group: Option<u32>,
+ /// `None` for the root record.
+ pub id: Option<String>,
+ /// Never [`ProgramState::Clear`], which removes records instead.
+ pub state: ProgramState,
+ pub kind: Option<ProgramBlockedKind>,
+ pub progress: Option<u8>,
+ /// As reported. [`ProgramStatusRecords::snapshot`] fills it in from the
+ /// nearest ancestor for a record that names none.
+ pub app: Option<String>,
+ pub title: Option<String>,
+ pub msg: Option<String>,
+ /// Kept after the program that filed it went away: a result nobody has
+ /// seen yet, describing nothing that is running now.
+ pub orphaned: bool,
+}
+
+/// The records as a consumer sees them: the root, and every other record
+/// in id order with its `app` inherited.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ProgramStatusSnapshot {
+ pub root: Option<ProgramStatusRecord>,
+ pub children: Vec<ProgramStatusRecord>,
+ /// The receipt serial of the last report taken in by then: what a
+ /// decision made on this snapshot may act on, and nothing filed after.
+ pub latest_serial: u64,
+}
+
+/// The records a terminal keeps, least recently updated first.
+#[derive(Clone, Debug, Default)]
+pub struct ProgramStatusRecords {
+ records: Vec<ProgramStatusRecord>,
+ serial: u64,
+}
+
+impl ProgramStatusRecords {
+ /// The protocol's floor for how many records a terminal keeps. Past it,
+ /// the record updated longest ago makes room.
+ pub const MAX_RECORDS: usize = 256;
+
+ /// File a report: it replaces its record whole, or for `clear` removes
+ /// the record and everything under it -- every record, without an id.
+ pub fn apply(&mut self, report: ProgramStatusReport) {
+ self.apply_from(report, None);
+ }
+
+ /// File a report with the process group observed at receipt, if available.
+ pub fn apply_from(&mut self, report: ProgramStatusReport, process_group: Option<u32>) {
+ self.serial = self.serial.wrapping_add(1);
+ if report.state == ProgramState::Clear {
+ match report.id {
+ Some(id) => self.records.retain(|record| !is_within(record, &id)),
+ None => self.records.clear(),
+ }
+ return;
+ }
+ if report.id.is_none()
+ && self.find(None).is_some_and(|root| {
+ matches!((root.process_group, process_group), (Some(old), Some(new)) if old != new)
+ })
+ {
+ // Children keep the app of the root they were filed under,
+ // even if a later command replaces it before a shell prompt.
+ let apps = self.apps();
+ let inherited: Vec<_> = self.records
+ .iter()
+ .map(|record| {
+ record.id.as_deref().filter(|_| record.app.is_none())
+ .and_then(|id| inherited_app(&apps, id))
+ })
+ .collect();
+ for (record, app) in self.records.iter_mut().zip(inherited) {
+ if app.is_some() {
+ record.app = app;
+ }
+ }
+ }
+ self.records.retain(|record| record.id != report.id);
+ if self.records.len() >= Self::MAX_RECORDS {
+ self.records.remove(0);
+ }
+ self.records.push(ProgramStatusRecord {
+ serial: self.serial,
+ process_group,
+ id: report.id,
+ state: report.state,
+ kind: report.kind,
+ progress: report.progress,
+ app: report.app,
+ title: report.title,
+ msg: report.msg,
+ orphaned: false,
+ });
+ }
+
+ /// The program is gone, or a shell has put up a new prompt: nothing it
+ /// was in the middle of is still going on. Only results nobody has seen
+ /// yet -- `done` and `error` -- outlive it, marked as left behind.
+ /// Returns whether anything changed.
+ pub fn end_of_program(&mut self) -> bool {
+ self.end_of_program_through(u64::MAX)
+ }
+
+ /// [`end_of_program`](Self::end_of_program) for the records received up
+ /// to serial `through` only: a decision taken on a snapshot must not
+ /// sweep away a report that arrived after it.
+ pub fn end_of_program_through(&mut self, through: u64) -> bool {
+ // A survivor keeps the name it had from a parent that is about to
+ // go: it is still that program's result.
+ let inherited: Vec<Option<String>> = {
+ let apps = self.apps();
+ self.records
+ .iter()
+ .map(|record| match (&record.app, &record.id) {
+ (None, Some(id)) if record.serial <= through => inherited_app(&apps, id),
+ _ => None,
+ })
+ .collect()
+ };
+ for (record, app) in self.records.iter_mut().zip(inherited) {
+ if app.is_some() {
+ record.app = app;
+ }
+ }
+ let before = self.records.len();
+ self.records.retain(|record| {
+ record.serial > through
+ || matches!(record.state, ProgramState::Done | ProgramState::Error)
+ });
+ let mut changed = self.records.len() != before;
+ for record in self.records.iter_mut().filter(|record| record.serial <= through) {
+ changed |= !record.orphaned;
+ record.orphaned = true;
+ }
+ changed
+ }
+
+ /// Someone has looked: a `done` or `error` result has been seen and
+ /// need not be announced any longer. Returns whether anything changed.
+ pub fn seen(&mut self) -> bool {
+ let before = self.records.len();
+ self.records.retain(|record| {
+ !matches!(record.state, ProgramState::Done | ProgramState::Error)
+ });
+ self.records.len() != before
+ }
+
+ pub fn clear(&mut self) {
+ self.records.clear();
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.records.is_empty()
+ }
+
+ /// The root and, of the other records, the first `max_children` in id
+ /// order. Taken under the terminal's lock, so every record is looked at
+ /// once and only the ones handed out are copied.
+ pub fn snapshot(&self, max_children: usize) -> ProgramStatusSnapshot {
+ if self.records.is_empty() {
+ return ProgramStatusSnapshot::default();
+ }
+ let apps = self.apps();
+ let app_of = |id: &str| inherited_app(&apps, id);
+ let mut children: Vec<&ProgramStatusRecord> =
+ self.records.iter().filter(|record| record.id.is_some()).collect();
+ children.sort_by(|a, b| a.id.cmp(&b.id));
+ let children = children
+ .into_iter()
+ .take(max_children)
+ .map(|record| {
+ let mut record = record.clone();
+ if record.app.is_none() {
+ record.app = app_of(record.id.as_deref().unwrap_or_default());
+ }
+ record
+ })
+ .collect();
+ ProgramStatusSnapshot {
+ root: self.find(None).cloned(),
+ children,
+ latest_serial: self.serial,
+ }
+ }
+
+ /// Each record that names its program, by id.
+ fn apps(&self) -> HashMap<Option<&str>, &str> {
+ self.records
+ .iter()
+ .filter_map(|record| Some((record.id.as_deref(), record.app.as_deref()?)))
+ .collect()
+ }
+
+ /// The `app` the nearest ancestor of `id` names.
+ fn find(&self, id: Option<&str>) -> Option<&ProgramStatusRecord> {
+ self.records.iter().find(|record| record.id.as_deref() == id)
+ }
+}
+
+/// The `app` the nearest ancestor of `id` names, from [`ProgramStatusRecords::apps`].
+fn inherited_app(apps: &HashMap<Option<&str>, &str>, id: &str) -> Option<String> {
+ let mut path = id;
+ while let Some((parent, _)) = path.rsplit_once('/') {
+ path = parent;
+ if let Some(app) = apps.get(&Some(path)) {
+ return Some(app.to_string());
+ }
+ }
+ apps.get(&None).map(|app| app.to_string())
+}
+
+/// Whether `record` is `id` itself or somewhere under it.
+fn is_within(record: &ProgramStatusRecord, id: &str) -> bool {
+ record.id.as_deref().is_some_and(|own| {
+ own == id || (own.starts_with(id) && own.as_bytes().get(id.len()) == Some(&b'/'))
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn report(state: ProgramState, id: Option<&str>, app: Option<&str>) -> ProgramStatusReport {
+ ProgramStatusReport {
+ state,
+ id: id.map(str::to_string),
+ kind: None,
+ progress: None,
+ app: app.map(str::to_string),
+ title: None,
+ msg: None,
+ }
+ }
+
+ #[test]
+ fn a_report_replaces_its_record_whole() {
+ let mut records = ProgramStatusRecords::default();
+ let mut first = report(ProgramState::Working, None, Some("claude-code"));
+ first.msg = Some("Running tests".to_string());
+ first.progress = Some(40);
+ records.apply(first);
+ records.apply(report(ProgramState::Idle, None, None));
+ let root = records.snapshot(usize::MAX).root.unwrap();
+ assert_eq!(root.state, ProgramState::Idle);
+ assert_eq!((root.msg, root.progress, root.app), (None, None, None));
+ }
+
+ #[test]
+ fn identical_emissions_keep_distinct_receipts_even_after_a_clear() {
+ let mut records = ProgramStatusRecords::default();
+ let working = report(ProgramState::Working, None, Some("example"));
+ records.apply_from(working.clone(), Some(9101));
+ let first = records.snapshot(0).root.unwrap();
+ records.apply_from(working.clone(), Some(9102));
+ let second = records.snapshot(0).root.unwrap();
+ assert_eq!(first.process_group, Some(9101));
+ assert_eq!(second.process_group, Some(9102));
+ assert_ne!(second.serial, first.serial);
+ records.clear();
+ records.apply_from(working, Some(9102));
+ assert_ne!(records.snapshot(0).root.unwrap().serial, second.serial);
+ }
+
+ #[test]
+ fn children_inherit_the_nearest_app_and_clear_with_their_parent() {
+ let mut records = ProgramStatusRecords::default();
+ records.apply(report(ProgramState::Working, None, Some("claude-code")));
+ records.apply(report(ProgramState::Working, Some("task"), Some("tool")));
+ records.apply(report(ProgramState::Blocked, Some("task/sub"), None));
+ records.apply(report(ProgramState::Working, Some("taskforce"), None));
+ let snapshot = records.snapshot(usize::MAX);
+ let apps: Vec<_> = snapshot
+ .children
+ .iter()
+ .map(|child| (child.id.clone().unwrap(), child.app.clone().unwrap()))
+ .collect();
+ assert_eq!(
+ apps,
+ [
+ ("task".to_string(), "tool".to_string()),
+ ("task/sub".to_string(), "tool".to_string()),
+ ("taskforce".to_string(), "claude-code".to_string()),
+ ]
+ );
+
+ // `taskforce` only shares a prefix with `task`; it is not under it.
+ records.apply(report(ProgramState::Clear, Some("task"), None));
+ let ids: Vec<_> = records
+ .snapshot(usize::MAX)
+ .children
+ .into_iter()
+ .map(|child| child.id.unwrap())
+ .collect();
+ assert_eq!(ids, ["taskforce"]);
+
+ records.apply(report(ProgramState::Clear, None, None));
+ assert!(records.is_empty());
+ }
+
+ #[test]
+ fn only_unseen_results_outlive_their_program() {
+ let mut records = ProgramStatusRecords::default();
+ records.apply(report(ProgramState::Working, None, None));
+ records.apply(report(ProgramState::Blocked, Some("a"), None));
+ records.apply(report(ProgramState::Idle, Some("b"), None));
+ records.apply(report(ProgramState::Done, Some("c"), None));
+ records.apply(report(ProgramState::Error, Some("d"), None));
+ assert!(records.end_of_program());
+ let left: Vec<_> = records
+ .snapshot(usize::MAX)
+ .children
+ .into_iter()
+ .map(|child| (child.state, child.orphaned))
+ .collect();
+ assert_eq!(left, [(ProgramState::Done, true), (ProgramState::Error, true)]);
+ assert!(!records.end_of_program());
+
+ // A program reporting again files a record of its own, not one left
+ // behind.
+ records.apply(report(ProgramState::Done, Some("c"), None));
+ assert!(!records.snapshot(usize::MAX).children[0].orphaned);
+ assert!(records.seen());
+ assert!(records.is_empty());
+ }
+
+ #[test]
+ fn ending_a_program_spares_what_arrived_after_the_decision() {
+ let mut records = ProgramStatusRecords::default();
+ records.apply(report(ProgramState::Working, None, Some("old")));
+ let decided_on = records.snapshot(0).latest_serial;
+ // The next command reports before the decision is acted on.
+ records.apply(report(ProgramState::Working, Some("next"), Some("new")));
+ assert!(records.end_of_program_through(decided_on));
+ let snapshot = records.snapshot(usize::MAX);
+ assert_eq!(snapshot.root, None);
+ assert_eq!(snapshot.children.len(), 1);
+ assert!(!snapshot.children[0].orphaned);
+ }
+
+ #[test]
+ fn children_keep_their_app_when_another_process_replaces_the_root() {
+ let mut records = ProgramStatusRecords::default();
+ records.apply_from(report(ProgramState::Working, None, Some("tool")), Some(9801));
+ records.apply_from(report(ProgramState::Error, Some("fetch"), None), Some(9801));
+ records.apply_from(report(ProgramState::Working, None, Some("example")), Some(9802));
+ let snapshot = records.snapshot(usize::MAX);
+ assert_eq!(snapshot.children[0].app.as_deref(), Some("tool"));
+ records.end_of_program();
+ assert_eq!(records.snapshot(usize::MAX).children[0].app.as_deref(), Some("tool"));
+ }
+
+ #[test]
+ fn a_snapshot_hands_out_the_first_children_only() {
+ let mut records = ProgramStatusRecords::default();
+ records.apply(report(ProgramState::Working, None, Some("tool")));
+ for id in ["c", "a", "b"] {
+ records.apply(report(ProgramState::Working, Some(id), None));
+ }
+ let snapshot = records.snapshot(2);
+ let ids: Vec<_> = snapshot.children.iter().map(|c| c.id.clone().unwrap()).collect();
+ assert_eq!(ids, ["a", "b"]);
+ assert!(snapshot.children.iter().all(|c| c.app.as_deref() == Some("tool")));
+ }
+
+ #[test]
+ fn the_least_recently_updated_record_makes_room() {
+ let mut records = ProgramStatusRecords::default();
+ for n in 0..ProgramStatusRecords::MAX_RECORDS {
+ records.apply(report(ProgramState::Working, Some(&n.to_string()), None));
+ }
+ // Updating "0" makes "1" the oldest.
+ records.apply(report(ProgramState::Idle, Some("0"), None));
+ records.apply(report(ProgramState::Working, Some("new"), None));
+ let snapshot = records.snapshot(usize::MAX);
+ assert_eq!(snapshot.children.len(), ProgramStatusRecords::MAX_RECORDS);
+ assert!(snapshot.children.iter().all(|c| c.id.as_deref() != Some("1")));
+ assert!(snapshot.children.iter().any(|c| c.id.as_deref() == Some("0")));
+ }
+}
diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs
index 31547603..1a7ba817 100644
--- a/term/src/terminalstate/mod.rs
+++ b/term/src/terminalstate/mod.rs
@@ -408,6 +408,9 @@ pub struct TerminalState {
/// before any display flattening (Paused stays distinct). `None`
/// means the app has not spoken.
agent_osc_progress: Option<String>,
+ /// What programs have reported about themselves with OSC 7501.
+ program_status: crate::program_status::ProgramStatusRecords,
+ program_status_process_group: Option<Box<dyn Fn() -> Option<u32> + Send + Sync>>,
palette: Option<ColorPalette>,
@@ -697,6 +700,8 @@ impl TerminalState {
progress: Progress::default(),
agent_osc_title: None,
agent_osc_progress: None,
+ program_status: Default::default(),
+ program_status_process_group: None,
}
}
@@ -822,6 +827,36 @@ impl TerminalState {
self.agent_osc_progress = None;
}
+ /// The records programs have filed with OSC 7501, with at most
+ /// `max_children` besides the root.
+ pub fn program_status(
+ &self,
+ max_children: usize,
+ ) -> crate::program_status::ProgramStatusSnapshot {
+ self.program_status.snapshot(max_children)
+ }
+
+ /// Someone has looked at the pane: a finished or failed program's
+ /// result has been seen. Returns whether anything changed.
+ pub fn program_status_seen(&mut self) -> bool {
+ self.program_status.seen()
+ }
+
+ /// Resolve the foreground only when an OSC 7501 report is received.
+ pub fn set_program_status_process_group(
+ &mut self,
+ source: Box<dyn Fn() -> Option<u32> + Send + Sync>,
+ ) {
+ self.program_status_process_group = Some(source);
+ }
+
+ /// The program that filed OSC 7501 records has gone: drop all but the
+ /// results nobody has seen, among the records received up to serial
+ /// `through`. Returns whether anything changed.
+ pub fn end_program_status(&mut self, through: u64) -> bool {
+ self.program_status.end_of_program_through(through)
+ }
+
/// Returns the current working directory associated with the
/// terminal session. The working directory can be changed by
/// the applicaiton using the OSC 7 escape sequence.
diff --git a/term/src/terminalstate/performer.rs b/term/src/terminalstate/performer.rs
index ad807496..93e71e6d 100644
--- a/term/src/terminalstate/performer.rs
+++ b/term/src/terminalstate/performer.rs
@@ -22,7 +22,7 @@ use wezterm_escape_parser::csi::{
};
use wezterm_escape_parser::osc::{
ChangeColorPair, ColorOrQuery, FinalTermSemanticPrompt, ITermProprietary,
- ITermUnicodeVersionOp, Selection,
+ ITermUnicodeVersionOp, ProgramStatus, Selection,
};
use wezterm_escape_parser::{
Action, ControlCode, DeviceControlMode, Esc, EscCode, OperatingSystemCommand, CSI,
@@ -884,6 +884,7 @@ impl<'a> Performer<'a> {
self.progress = Progress::default();
self.agent_osc_title = None;
self.agent_osc_progress = None;
+ self.program_status.clear();
// Before the screen is torn down, while the placement rows
// still refer to real lines. The soft reset (DECSTR) already
@@ -1060,6 +1061,9 @@ impl<'a> Performer<'a> {
) => {
self.fresh_line();
self.pen.set_semantic_type(SemanticType::Prompt);
+ // A new shell prompt: whatever filed OSC 7501 records has
+ // finished, and only its unseen results remain.
+ self.program_status.end_of_program();
}
OperatingSystemCommand::FinalTermSemanticPrompt(
FinalTermSemanticPrompt::StartPrompt(_),
@@ -1267,6 +1271,24 @@ impl<'a> Performer<'a> {
self.implicit_palette_reset_if_same_as_configured();
self.palette_did_change();
}
+ OperatingSystemCommand::ProgramStatus(ProgramStatus::Query) => {
+ // The same body back is the whole answer: nothing about the
+ // records is ever echoed.
+ write!(
+ self.writer,
+ "{}",
+ OperatingSystemCommand::ProgramStatus(ProgramStatus::Query)
+ )
+ .ok();
+ self.writer.flush().ok();
+ }
+ OperatingSystemCommand::ProgramStatus(ProgramStatus::Report(report)) => {
+ let group = self
+ .program_status_process_group
+ .as_ref()
+ .and_then(|source| source());
+ self.program_status.apply_from(report, group);
+ }
OperatingSystemCommand::ConEmuProgress(prog) => {
use wezterm_escape_parser::osc::Progress as TProg;
// Retained before the display flattening below (which folds
diff --git a/term/src/test/mod.rs b/term/src/test/mod.rs
index 18513bad..1ee57932 100644
--- a/term/src/test/mod.rs
+++ b/term/src/test/mod.rs
@@ -258,6 +258,81 @@ fn agent_osc_evidence_tracks_only_real_emissions() {
assert_eq!(term.agent_osc_evidence(), Default::default());
}
+/// OSC 7501: the query is answered, reports are kept, and each of the
+/// protocol's ends for a record -- a new prompt, being seen, a hard reset
+/// -- does what it should.
+#[cfg(not(target_family = "wasm"))]
+#[test]
+fn program_status_reports_are_answered_kept_and_retired() {
+ use crate::program_status::ProgramState;
+
+ #[derive(Clone, Default)]
+ struct Sink(Arc<Mutex<Vec<u8>>>);
+
+ impl std::io::Write for Sink {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ let sink = Sink::default();
+ let mut term = Terminal::new(
+ TerminalSize {
+ rows: 4,
+ cols: 20,
+ pixel_width: 160,
+ pixel_height: 64,
+ dpi: 0,
+ },
+ Arc::new(TestTermConfig { scrollback: 0 }),
+ "ThinkTerm",
+ "O_o",
+ Box::new(sink.clone()),
+ );
+
+ term.advance_bytes("\x1b]7501;?\x07");
+ let reply = b"\x1b]7501;?\x1b\\";
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ while sink.0.lock().unwrap().len() < reply.len() && std::time::Instant::now() < deadline {
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert_eq!(sink.0.lock().unwrap().as_slice(), reply);
+
+ // "Running tests"
+ term.advance_bytes(
+ "\x1b]7501;state=working:app=claude-code:progress=60:msg=UnVubmluZyB0ZXN0cw\x1b\\\
+ \x1b]7501;state=blocked:id=plan:kind=question\x1b\\\
+ \x1b]7501;state=done:id=explore\x1b\\",
+ );
+ let snapshot = term.program_status(usize::MAX);
+ let root = snapshot.root.unwrap();
+ assert_eq!(root.state, ProgramState::Working);
+ assert_eq!(root.progress, Some(60));
+ assert_eq!(root.msg.as_deref(), Some("Running tests"));
+ assert_eq!(snapshot.children.len(), 2);
+ assert_eq!(snapshot.children[1].app.as_deref(), Some("claude-code"));
+
+ // The shell's next prompt: only the unseen result is left.
+ term.advance_bytes("\x1b]133;A\x07");
+ let snapshot = term.program_status(usize::MAX);
+ assert_eq!(snapshot.root, None);
+ assert_eq!(snapshot.children.len(), 1);
+ assert_eq!(snapshot.children[0].state, ProgramState::Done);
+ assert!(snapshot.children[0].orphaned);
+
+ assert!(term.program_status_seen());
+ assert_eq!(term.program_status(usize::MAX), Default::default());
+
+ term.advance_bytes("\x1b]7501;state=error\x1b\\");
+ assert!(term.program_status(usize::MAX).root.is_some());
+ term.advance_bytes("\x1bc");
+ assert_eq!(term.program_status(usize::MAX), Default::default());
+}
+
#[test]
fn application_palette_override_tracks_osc_set_query_and_reset() {
let mut term = TestTerm::new(4, 8, 0);
diff --git a/wezterm-escape-parser/src/osc.rs b/wezterm-escape-parser/src/osc.rs
index 1060214d..e2113c58 100644
--- a/wezterm-escape-parser/src/osc.rs
+++ b/wezterm-escape-parser/src/osc.rs
@@ -50,6 +50,7 @@ pub enum OperatingSystemCommand {
ResetColors(Vec<u8>),
RxvtExtension(Vec<String>),
ConEmuProgress(Progress),
+ ProgramStatus(ProgramStatus),
Unspecified(Vec<Vec<u8>>),
}
@@ -361,6 +362,9 @@ impl OperatingSystemCommand {
}
FinalTermSemanticPrompt => self::FinalTermSemanticPrompt::parse(osc)
.map(OperatingSystemCommand::FinalTermSemanticPrompt),
+ ProgramStatus => {
+ self::ProgramStatus::parse(osc).map(OperatingSystemCommand::ProgramStatus)
+ }
ChangeColorNumber => Self::parse_change_color_number(osc),
ResetColors => Self::parse_reset_colors(osc),
@@ -497,6 +501,8 @@ osc_entries!(
RxvtProprietary = "777",
FinalTermSemanticPrompt = "133",
ITermProprietary = "1337",
+ /// A program reporting its own state; see [`ProgramStatus`].
+ ProgramStatus = "7501",
/// Here the "Sun" suffix comes from the table in
/// <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Miscellaneous>
/// that lays out various window related escape sequences.
@@ -610,6 +616,7 @@ impl Display for OperatingSystemCommand {
ConEmuProgress(Progress::SetError(pct)) => write!(f, "9;4;2;{pct}")?,
ConEmuProgress(Progress::SetIndeterminate) => write!(f, "9;4;3")?,
ConEmuProgress(Progress::Paused) => write!(f, "9;4;4")?,
+ ProgramStatus(status) => status.fmt(f)?,
};
// Use the longer form ST as neovim doesn't like the BEL version
write!(f, "\x1b\\")?;
@@ -887,6 +894,247 @@ pub enum Progress {
Paused,
}
+/// OSC 7501: a program telling the terminal what state it is in.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ProgramStatus {
+ /// `OSC 7501 ; ? ST`: does the terminal speak the protocol? One that
+ /// does answers with the same sequence.
+ Query,
+ Report(ProgramStatusReport),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ProgramState {
+ /// At rest, waiting to be told what to do.
+ Idle,
+ Working,
+ /// Finished, with a result nobody has looked at yet.
+ Done,
+ /// Cannot go on until someone does something.
+ Blocked,
+ /// Failed and stopped.
+ Error,
+ /// Removes the record the report addresses, and everything under it.
+ Clear,
+}
+
+impl ProgramState {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Idle => "idle",
+ Self::Working => "working",
+ Self::Done => "done",
+ Self::Blocked => "blocked",
+ Self::Error => "error",
+ Self::Clear => "clear",
+ }
+ }
+}
+
+/// What a blocked program is waiting for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ProgramBlockedKind {
+ Permission,
+ Question,
+ Auth,
+}
+
+impl ProgramBlockedKind {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Permission => "permission",
+ Self::Question => "question",
+ Self::Auth => "auth",
+ }
+ }
+}
+
+/// One report. It replaces its record whole: a key left out is a key
+/// removed, not one kept from before.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ProgramStatusReport {
+ pub state: ProgramState,
+ /// The record addressed, a `/`-separated path such as `build/test`.
+ /// `None` is the root record.
+ pub id: Option<String>,
+ /// Only with `Blocked`.
+ pub kind: Option<ProgramBlockedKind>,
+ /// 0 to 100, only with `Working` or `Blocked`; `None` is indeterminate.
+ pub progress: Option<u8>,
+ /// Machine-readable program name, such as `claude-code`.
+ pub app: Option<String>,
+ /// Decoded from base64; never contains a control character.
+ pub title: Option<String>,
+ /// One line on what the program is doing or did; decoded, never
+ /// contains a control character.
+ pub msg: Option<String>,
+}
+
+impl ProgramStatus {
+ /// The whole sequence, introducer to terminator, may be no longer.
+ const MAX_SEQUENCE: usize = 4096;
+ const MAX_KEY: usize = 16;
+ const MAX_NAME: usize = 32;
+ const MAX_ID: usize = 128;
+ const MAX_ID_DEPTH: usize = 8;
+ /// Encoded and decoded limits for `title`, then `msg`.
+ const MAX_TITLE: (usize, usize) = (256, 192);
+ const MAX_MSG: (usize, usize) = (2732, 2048);
+
+ fn parse(osc: &[&[u8]]) -> Result<Self> {
+ ensure!(osc.len() >= 2, "program status without a body");
+ // No value may contain `;`, so a body the parser split on one is
+ // put back together and its broken pair skipped like any other.
+ let body = osc[1..].join(&b';');
+ // `ESC ] 7501 ;` before the body and `ESC \` after it.
+ ensure!(
+ body.len() + 9 <= Self::MAX_SEQUENCE,
+ "program status longer than {} bytes",
+ Self::MAX_SEQUENCE
+ );
+ let body = str::from_utf8(&body)?;
+ if body.trim() == "?" {
+ return Ok(Self::Query);
+ }
+
+ let (mut state, mut id, mut kind, mut progress) = (None, None, None, None);
+ let (mut app, mut title, mut msg) = (None, None, None);
+ for pair in body.split(':') {
+ // A pair without `=` is malformed and skipped; the rest of the
+ // report still counts.
+ let Some((key, value)) = pair.split_once('=') else {
+ continue;
+ };
+ let (key, value) = (key.trim(), value.trim());
+ ensure!(key.len() <= Self::MAX_KEY, "program status key too long");
+ // A repeated key: the last one wins.
+ match key {
+ "state" => state = Some(value),
+ "id" => id = Some(value),
+ "kind" => kind = Some(value),
+ "progress" => progress = Some(value),
+ "app" => app = Some(value),
+ "title" => title = Some(value),
+ "msg" => msg = Some(value),
+ // Unknown keys are how the protocol grows.
+ _ => {}
+ }
+ }
+
+ let state = match state {
+ Some("idle") => ProgramState::Idle,
+ Some("working") => ProgramState::Working,
+ Some("done") => ProgramState::Done,
+ Some("blocked") => ProgramState::Blocked,
+ Some("error") => ProgramState::Error,
+ Some("clear") => ProgramState::Clear,
+ other => bail!("program status state {:?}", other),
+ };
+ let id = match id.filter(|id| !id.is_empty()) {
+ Some(id) => {
+ ensure!(
+ id.len() <= Self::MAX_ID
+ && id.split('/').count() <= Self::MAX_ID_DEPTH
+ && id.split('/').all(Self::is_name),
+ "program status id {:?}",
+ id
+ );
+ Some(id.to_string())
+ }
+ None => None,
+ };
+ let app = match app.filter(|app| !app.is_empty()) {
+ Some(app) => {
+ ensure!(Self::is_name(app), "program status app {:?}", app);
+ Some(app.to_string())
+ }
+ None => None,
+ };
+ let kind = match (state, kind) {
+ (ProgramState::Blocked, Some("permission")) => Some(ProgramBlockedKind::Permission),
+ (ProgramState::Blocked, Some("question")) => Some(ProgramBlockedKind::Question),
+ (ProgramState::Blocked, Some("auth")) => Some(ProgramBlockedKind::Auth),
+ _ => None,
+ };
+ let progress = match state {
+ ProgramState::Working | ProgramState::Blocked => progress
+ .and_then(|value| value.parse::<u8>().ok())
+ .filter(|pct| *pct <= 100),
+ _ => None,
+ };
+ Ok(Self::Report(ProgramStatusReport {
+ state,
+ id,
+ kind,
+ progress,
+ app,
+ title: Self::decode_text(title, Self::MAX_TITLE)?,
+ msg: Self::decode_text(msg, Self::MAX_MSG)?,
+ }))
+ }
+
+ /// An `id` segment or an `app`: `[A-Za-z0-9_.+-]{1,32}`.
+ fn is_name(name: &str) -> bool {
+ !name.is_empty()
+ && name.len() <= Self::MAX_NAME
+ && name
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'+' | b'-'))
+ }
+
+ /// Standard base64 with optional padding, holding UTF-8 without a
+ /// single control character. Anything else costs the whole report.
+ fn decode_text(value: Option<&str>, limits: (usize, usize)) -> Result<Option<String>> {
+ use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
+ let Some(value) = value.filter(|value| !value.is_empty()) else {
+ return Ok(None);
+ };
+ ensure!(value.len() <= limits.0, "program status text too long");
+ let bytes = GeneralPurpose::new(
+ &base64::alphabet::STANDARD,
+ GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),
+ )
+ .decode(value)
+ .map_err(|err| format_err!("program status base64: {:#}", err))?;
+ ensure!(bytes.len() <= limits.1, "program status text too long");
+ let text = String::from_utf8(bytes)?;
+ ensure!(
+ !text.chars().any(char::is_control),
+ "program status text with a control character"
+ );
+ Ok((!text.is_empty()).then_some(text))
+ }
+}
+
+impl Display for ProgramStatus {
+ fn fmt(&self, f: &mut Formatter) -> FmtResult {
+ let report = match self {
+ Self::Query => return write!(f, "7501;?"),
+ Self::Report(report) => report,
+ };
+ write!(f, "7501;state={}", report.state.as_str())?;
+ if let Some(id) = &report.id {
+ write!(f, ":id={id}")?;
+ }
+ if let Some(kind) = report.kind {
+ write!(f, ":kind={}", kind.as_str())?;
+ }
+ if let Some(progress) = report.progress {
+ write!(f, ":progress={progress}")?;
+ }
+ if let Some(app) = &report.app {
+ write!(f, ":app={app}")?;
+ }
+ if let Some(title) = &report.title {
+ write!(f, ":title={}", base64_encode(title))?;
+ }
+ if let Some(msg) = &report.msg {
+ write!(f, ":msg={}", base64_encode(msg))?;
+ }
+ Ok(())
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ITermProprietary {
/// The "Set Mark" command allows you to record a location and then jump back to it later
@@ -1722,6 +1970,88 @@ mod test {
);
}
+ #[test]
+ fn program_status() {
+ assert_eq!(
+ parse(&["7501", "?"], "\x1b]7501;?\x1b\\"),
+ OperatingSystemCommand::ProgramStatus(ProgramStatus::Query)
+ );
+ // "Bash: npm test" and "Fix it", the latter without padding.
+ assert_eq!(
+ parse(
+ &[
+ "7501",
+ " state = blocked :kind=permission:progress=40:app=claude-code:id=build/test:msg=QmFzaDogbnBtIHRlc3Q=:title=Rml4IGl0:future=1:stray"
+ ],
+ "\x1b]7501;state=blocked:id=build/test:kind=permission:progress=40:app=claude-code:title=Rml4IGl0:msg=QmFzaDogbnBtIHRlc3Q=\x1b\\"
+ ),
+ OperatingSystemCommand::ProgramStatus(ProgramStatus::Report(ProgramStatusReport {
+ state: ProgramState::Blocked,
+ id: Some("build/test".to_string()),
+ kind: Some(ProgramBlockedKind::Permission),
+ progress: Some(40),
+ app: Some("claude-code".to_string()),
+ title: Some("Fix it".to_string()),
+ msg: Some("Bash: npm test".to_string()),
+ }))
+ );
+ // `kind` belongs to blocked and `progress` to working and blocked;
+ // anywhere else they are dropped, as is a progress out of range.
+ assert_eq!(
+ parse(
+ &["7501", "state=done:kind=auth:progress=50"],
+ "\x1b]7501;state=done\x1b\\"
+ ),
+ OperatingSystemCommand::ProgramStatus(ProgramStatus::Report(ProgramStatusReport {
+ state: ProgramState::Done,
+ id: None,
+ kind: None,
+ progress: None,
+ app: None,
+ title: None,
+ msg: None,
+ }))
+ );
+ assert_eq!(
+ parse(&["7501", "state=working:progress=101"], "\x1b]7501;state=working\x1b\\"),
+ OperatingSystemCommand::ProgramStatus(ProgramStatus::Report(ProgramStatusReport {
+ state: ProgramState::Working,
+ id: None,
+ kind: None,
+ progress: None,
+ app: None,
+ title: None,
+ msg: None,
+ }))
+ );
+
+ // Each of these costs the whole report.
+ let msg = base64_encode("x".repeat(2049));
+ let control = base64_encode("line\nbreak");
+ for body in [
+ "".to_string(),
+ "kind=permission".to_string(),
+ "state=sleeping".to_string(),
+ "state=idle:id=a b".to_string(),
+ "state=idle:id=a//b".to_string(),
+ "state=idle:id=1/2/3/4/5/6/7/8/9".to_string(),
+ "state=idle:app=claude code".to_string(),
+ "state=idle:msg=not*base64".to_string(),
+ format!("state=idle:msg={control}"),
+ format!("state=idle:msg={msg}"),
+ format!("state=idle:{}=1", "k".repeat(17)),
+ format!("state=idle:future={}", "x".repeat(4096)),
+ ] {
+ assert!(
+ matches!(
+ OperatingSystemCommand::parse(&[b"7501", body.as_bytes()]),
+ OperatingSystemCommand::Unspecified(_)
+ ),
+ "{body:?} was accepted"
+ );
+ }
+ }
+
#[test]
fn iterm() {
assert_eq!(