From 6759d5ed092fc429449728a827d6c6affcd2641d Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:41:06 +0700 Subject: [PATCH 1/6] fix(record): date, size and TERM the asciicast header from the recording The asciicast header filled three fields from constants or from the clock at export: env.TERM was always xterm-256color, a recording with no frame claimed 80x24, and timestamp was the export time. - env.TERM is the TERM the child was given, the value XTGETTCAP's TN already reports, so the header no longer gives a third answer. - A recording with no frame takes the terminal's size at record(). - timestamp is the second record() was called in. The asciicast v2 spec defines it as the "Unix timestamp of the beginning of the recording session"; #309 chose the export time, which is later by the recording's length, and made two exports of one recording differ (#555). The export-time test now pins the start instead, and the file-equals-string comparison is exact again. Closes #850 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 8 +++ crates/termlens/src/terminal.rs | 78 +++++++++++++++++++++----- crates/termlens/tests/record.rs | 99 +++++++++++++++++++++++---------- skills/termlens/SKILL.md | 2 +- 4 files changed, 142 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c779ded..7e668baa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,14 @@ reads that marker. a payload that long, since deflate output for a picture is far smaller than the picture. A test that decoded such a payload should expect `Malformed`, or the application should send it unpadded. (#810) +- The asciicast header describes the recording it heads. `timestamp` is + the second `Terminal::record` was called in, the "beginning of the + recording session" the asciicast v2 spec defines, rather than the time + of the export, so two exports of one recording are the same document. + `env.TERM` is the `TERM` the child was given, where it was always + `xterm-256color`, and a recording with no frame takes the terminal's + size at `record` rather than 80x24. A test that bounded `timestamp` by + the export should bound it by the call to `record`. (#850) ### Fixed diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index cf953b91..13a22be4 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -893,9 +893,32 @@ impl RecordingState { pub struct Recorder { state: Arc>, shared: Arc>, - /// The command being recorded, for the asciicast `title` (#309). Carried - /// from the terminal because `stop` has no other way back to it. + /// What the asciicast header says about the recording, taken from the + /// terminal at [`Terminal::record`] because `stop` has no other way back + /// to it. + header: CastHeader, +} + +/// The asciicast header fields that are not derived from the frames. +#[derive(Debug, Clone, PartialEq, Eq)] +struct CastHeader { + /// The command being recorded, for the `title` (#309). title: String, + /// The `TERM` the child was given, for `env.TERM`. The v2 spec calls + /// `env` "a map of captured environment variables", and termlens already + /// makes XTGETTCAP's `TN` agree with the child's `TERM`; a constant here + /// gave a third answer that could be neither (#850). + term: String, + /// The grid's (cols, rows) when recording began: the header's size for a + /// recording with no frame, which otherwise described an 80x24 terminal + /// that never existed (#850). + size: (u16, u16), + /// Unix seconds when recording began, `None` for a clock set before the + /// epoch. The v2 spec defines `timestamp` as the "Unix timestamp of the + /// beginning of the recording session"; #309 wrote the export time, + /// which is later by the recording's length and any wait before the + /// export, and made two exports of one recording differ (#555, #850). + started: Option, } impl fmt::Debug for Recorder { @@ -943,7 +966,7 @@ impl Recorder { Ok(Recording { frames: state.frames.iter().cloned().collect(), dropped: state.dropped, - title: self.title.clone(), + header: self.header.clone(), }) } @@ -978,7 +1001,7 @@ impl Drop for Recorder { pub struct Recording { frames: Vec<(Duration, Screen)>, dropped: u64, - title: String, + header: CastHeader, } impl Recording { @@ -1033,13 +1056,20 @@ impl Recording { /// termlens ships no image encoder; this is the file those tools turn /// into a GIF. /// + /// The header's `width` and `height` are the first frame's size, or the + /// terminal's size at [`Terminal::record`] when no frame was recorded; + /// `timestamp` is the second `record` was called in, the "beginning of + /// the recording session" the format defines, so exporting one + /// recording twice writes the same document; `env.TERM` is the `TERM` + /// the child was given; `title` is the command. + /// /// [asciicast v2]: https://docs.asciinema.org/manual/asciicast/v2/ #[must_use] pub fn to_asciicast(&self) -> String { let (cols, rows) = self .frames .first() - .map_or((80, 24), |(_, frame)| frame.size()); + .map_or(self.header.size, |(_, frame)| frame.size()); // The header is one line of JSON, assembled key by key because two of // the four optional keys the v2 spec defines may be absent (#309). // Without them a player shows a recording with no date and no name, @@ -1049,14 +1079,18 @@ impl Recording { // A clock set before the epoch has no honest unix timestamp, so the // key is omitted rather than written as 0 — a reader that meets no // timestamp shows none, where one that meets 1970 shows a wrong date. - if let Ok(since_epoch) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { - let _ = write!(out, ", \"timestamp\": {}", since_epoch.as_secs()); + if let Some(started) = self.header.started { + let _ = write!(out, ", \"timestamp\": {started}"); } let _ = write!(out, ", \"duration\": {:.6}", self.duration().as_secs_f64()); - if !self.title.is_empty() { - let _ = write!(out, ", \"title\": {}", json_string(&self.title)); + if !self.header.title.is_empty() { + let _ = write!(out, ", \"title\": {}", json_string(&self.header.title)); } - out.push_str(", \"env\": {\"TERM\": \"xterm-256color\"}}\n"); + let _ = writeln!( + out, + ", \"env\": {{\"TERM\": {}}}}}", + json_string(&self.header.term) + ); let mut previous_size = self.frames.first().map(|(_, frame)| frame.size()); for (at, frame) in &self.frames { let size = frame.size(); @@ -3184,12 +3218,23 @@ impl Terminal { budget: self.record_budget, dropped: 0, })); - self.shared - .mutate(|shared| shared.recorders.push(Arc::clone(&state))); + let started = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .ok() + .map(|since_epoch| since_epoch.as_secs()); + let (term, size) = self.shared.mutate(|shared| { + shared.recorders.push(Arc::clone(&state)); + (shared.term_name.clone(), shared.snapshot().size()) + }); Recorder { state, shared: Arc::clone(&self.shared), - title: self.command_desc.clone(), + header: CastHeader { + title: self.command_desc.clone(), + term, + size, + started, + }, } } @@ -5918,7 +5963,12 @@ mod tests { }) .collect(), dropped: 0, - title: String::new(), + header: super::CastHeader { + title: String::new(), + term: "xterm-256color".into(), + size: (10, 3), + started: None, + }, }; let cast = recording.to_asciicast(); let events: Vec<&str> = cast.lines().skip(1).collect(); diff --git a/crates/termlens/tests/record.rs b/crates/termlens/tests/record.rs index 5c0546c2..50f1443f 100644 --- a/crates/termlens/tests/record.rs +++ b/crates/termlens/tests/record.rs @@ -19,20 +19,12 @@ fn emit(builder: termlens::TerminalBuilder, steps: &[&str]) -> termlens::Result< common::spawn_emit(builder.size(40, 6).timeout(Duration::from_secs(10)), steps) } -/// The cast with its header's `"timestamp"` key taken out. -/// -/// The key is the wall clock at *export* — `the_header_timestamp_is_the_export_time` -/// pins that — so two exports of one recording are the same document except -/// where a second boundary fell between them, which failed the file-equals- -/// string comparison on a CI runner (#555). What that comparison is about is -/// everything else. -fn without_timestamp(cast: &str) -> String { - let (header, events) = cast.split_once('\n').expect("a header line, then events"); - let Some((before, rest)) = header.split_once(", \"timestamp\": ") else { - return cast.to_owned(); - }; - let digits = rest.bytes().take_while(u8::is_ascii_digit).count(); - format!("{before}{}\n{events}", &rest[digits..]) +/// Unix seconds now. +fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("a clock after 1970") + .as_secs() } #[test] @@ -151,13 +143,11 @@ fn the_asciicast_is_a_v2_header_and_one_full_repaint_per_frame() -> termlens::Re frames.write_asciicast(&path)?; let written = std::fs::read_to_string(&path)?; let _ = std::fs::remove_file(&path); - // The same document, not the same second: `write_asciicast` exports again. - assert_ne!( - without_timestamp(&cast), - cast, - "the helper must remove something, or the comparison below proves nothing" - ); - assert_eq!(without_timestamp(&written), without_timestamp(&cast)); + // The same document, to the byte. While the header's timestamp was the + // export time, a second boundary falling between the two exports made + // them differ, which failed this comparison on a CI runner (#555); it is + // the recording's start now, so the comparison is exact (#850). + assert_eq!(written, cast); t.send(Key::Enter)?; assert!(t.wait_exit()?.success()); Ok(()) @@ -337,28 +327,29 @@ fn the_asciicast_header_dates_and_names_the_recording() -> termlens::Result<()> &["READY", "--wait", "--raw", BURST, " DONE", "--wait"], )?; t.wait_until(|s| s.contains("READY"))?; - let before = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("a clock after 1970") - .as_secs(); + let before = unix_now(); let rec = t.record(); + let after = unix_now(); t.send(Key::Enter)?; t.wait_until(|s| s.contains("DONE"))?; let frames = rec.stop()?; + // Into the next second before exporting, so an export-time timestamp + // cannot pass for the recording's start. + while unix_now() <= after { + std::thread::sleep(Duration::from_millis(50)); + } let cast = frames.to_asciicast(); let header = cast.lines().next().expect("a header line"); let parsed: serde_json::Value = serde_json::from_str(header).expect("the header is still one line of valid JSON"); + // The v2 spec's "beginning of the recording session": the second + // `record()` was called in, not the export (#850). let timestamp = parsed["timestamp"].as_u64().expect("unix seconds"); - let after = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("a clock after 1970") - .as_secs(); assert!( (before..=after).contains(×tamp), - "exported now, not at some other time: {timestamp} outside {before}..={after}" + "dated when recording began: {timestamp} outside {before}..={after}" ); // The title is the command, which here carries the fixture's own @@ -385,6 +376,54 @@ fn the_asciicast_header_dates_and_names_the_recording() -> termlens::Result<()> Ok(()) } +/// The header describes the terminal that was recorded: the `TERM` the +/// child was given, and for a recording with no frame the terminal's own +/// size rather than 80x24 (#850). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY closes a DEC 2026 bracket before the content it wrapped, so a recorded frame never holds what was drawn (#149)" +)] +fn the_asciicast_header_describes_the_recorded_terminal() -> termlens::Result<()> { + let mut t = common::spawn_emit( + Terminal::builder() + .size(30, 4) + .env("TERM", "vt100") + .timeout(Duration::from_secs(10)), + &["READY", "--wait", "--raw", BURST, " DONE", "--wait"], + )?; + t.wait_until(|s| s.contains("READY"))?; + let rec = t.record(); + t.send(Key::Enter)?; + t.wait_until(|s| s.contains("DONE"))?; + let header = |recording: &termlens::Recording| -> serde_json::Value { + let cast = recording.to_asciicast(); + let line = cast.lines().next().expect("a header line"); + serde_json::from_str(line).expect("one line of valid JSON") + }; + let full = header(&rec.stop()?); + assert_eq!(full["env"]["TERM"], "vt100", "{full}"); + assert_eq!( + (full["width"].clone(), full["height"].clone()), + (30.into(), 4.into()) + ); + + // The application has drawn frames, but none since this `record()`. + let empty = t.record().stop()?; + assert!(empty.is_empty()); + let empty = header(&empty); + assert_eq!( + (empty["width"].clone(), empty["height"].clone()), + (30.into(), 4.into()), + "the terminal's size, not 80x24: {empty}" + ); + assert_eq!(empty["env"]["TERM"], "vt100", "{empty}"); + + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + /// Live heap bytes in this test process, for the dropped-recorder test /// below. /// diff --git a/skills/termlens/SKILL.md b/skills/termlens/SKILL.md index 199f0cab..579001cc 100644 --- a/skills/termlens/SKILL.md +++ b/skills/termlens/SKILL.md @@ -477,7 +477,7 @@ included in `X`, and `terminal closed (EOF) while waiting for X` is | `resize_and_wait(cols, rows, \|s\| bool)` | `Screen` | a resize: the predicate is asked only once the app has drawn after it (a printable character, or a changed cell; a cursor hide, a mode or a query alone does not count), so on Linux and macOS the old screen at the new size cannot pass it. On Windows ConPTY repaints the old screen after a resize, so there, and where the app paints on its own, name what only the new layout has | | `wait_exit()` | `ExitStatus` | the child's exit; `success()`, `code() -> Option`, `signal() -> Option<&str>` | | `wait_until_matches(&Regex)` | `Screen` | feature `regex`: a pattern over a row of the screen — the expect-style wait, on the grid | -| `record()` … `.stop()` | `Recording` | every complete DEC 2026 frame with its time; `frames()`, `duration()` (to the last frame), `write_asciicast(path)` for a file `asciinema` plays — its header carries when and what was recorded | +| `record()` … `.stop()` | `Recording` | every complete DEC 2026 frame with its time; `frames()`, `duration()` (to the last frame), `write_asciicast(path)` for a file `asciinema` plays — its header carries when recording began, what was recorded and the child's `TERM` | | `frame_timings()` | `Vec` | not a wait: what each of the last 512 repaints cost, span and size between its DEC 2026 markers, kept apart from the eight frames `wait_frame` retains — measured through a PTY, so a trend to hold a line on, not a render benchmark | **Drive**: `send(Key)`, `send_str("text")` (no Enter — send `Key::Enter` From d12706d3e8a5a8db73dfa4857f53b2a8b9dc33a8 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:42:59 +0700 Subject: [PATCH 2/6] fix(wait): name a DEC 2026 update left open in wait_frame and stop An application stalled inside a synchronized update, on a read or on a query's reply, did emit one. wait_frame's timeout said it never had, or that it had not repainted in response to the input, and pointed at wait_until; Recorder::stop said "never emitted" too. wait_idle on the same terminal named the open update, so the diagnosis depended on which wait timed out. Both now check for an open update first and say the application began one and has not ended it. "Never emitted" stays for a terminal that has seen no Begin. A timeout whose frames were rejected by the predicate says the next one is open, too. Closes #837 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 7 +++ crates/termlens/src/terminal.rs | 78 ++++++++++++++++++++++++++++----- crates/termlens/tests/frames.rs | 70 +++++++++++++++++++++++++++++ crates/termlens/tests/record.rs | 27 ++++++++++++ docs/DESIGN.md | 4 +- skills/termlens/SKILL.md | 1 + 6 files changed, 174 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e668baa..3c636fbc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -150,6 +150,13 @@ reads that marker. first 200 bytes and a hash of the whole, as the library cuts the names it writes to `TERMLENS_ARTIFACT_DIR` (#773). The summary shows it whole. (#808) +- A `wait_frame` timeout and `Recorder::stop` name a DEC 2026 update the + application began and has not ended, as `wait_idle` does. An + application stalled inside one, on a read or on a query's reply, was + described as one that never emitted a synchronized update, or as one + that had not repainted in response to the input, with advice to use + `wait_until`; `wait_frame` is the right wait for it, and returns once + the update ends. (#837) ## [0.11.11] - 2026-11-25 diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index 13a22be4..4929815d 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -936,15 +936,16 @@ impl Recorder { /// /// # Errors /// - /// [`Error::Input`] when the application has never emitted a DEC 2026 + /// [`Error::Input`] when the application has never completed a DEC 2026 /// synchronized update — the diagnosis [`wait_frame`](Terminal::wait_frame) - /// gives. A recording is made of complete frames; sampling the grid on a + /// gives, which names an update begun and not yet ended apart from one + /// never emitted. A recording is made of complete frames; sampling the grid on a /// timer instead would be the torn-frame problem in a new hat. /// [`Error::Emulator`] once the emulation has failed, as every wait /// returns it: no frame after the failure was seen, so the recording /// would end there without saying so. pub fn stop(self) -> Result { - let frames_seen = self.deregister(); + let (frames_seen, open) = self.deregister(); // Ahead of the count, as `resize` puts it ahead of its own refusal // (#702): frames completed after the panic were never seen, so // "never emitted a synchronized update" could be false, and frames @@ -953,6 +954,17 @@ impl Recorder { return Err(failure); } let state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + if frames_seen == 0 && open { + // It emitted one and stalled inside it, which "never emitted" + // misdescribed (#837): the wording wait_frame gives. + return Err(Error::Input( + "nothing to record yet — the application began a DEC 2026 synchronized \ + update and has not ended it (Begin with no End), so no frame has completed. \ + A recording is made of complete frames, as wait_frame is; stop once the \ + application has ended the update." + .to_owned(), + )); + } if frames_seen == 0 { return Err(Error::Input( "nothing to record — the application never emitted a DEC 2026 synchronized \ @@ -971,17 +983,18 @@ impl Recorder { } /// Take this recorder out of the reader thread's delivery list, and - /// report how many complete frames the terminal has seen in total. + /// report how many complete frames the terminal has seen in total and + /// whether an update is open now. /// /// One definition for the two callers — `stop`, and `Drop` when a /// recorder is abandoned before `stop` — so the two cannot deregister /// by different rules. - fn deregister(&self) -> u64 { + fn deregister(&self) -> (u64, bool) { self.shared.mutate(|state| { state .recorders .retain(|recorder| !Arc::ptr_eq(recorder, &self.state)); - state.frames_seen + (state.frames_seen, state.in_open_update()) }) } } @@ -1719,6 +1732,14 @@ impl EmuState { /// The error every screen-based wait returns once the emulator has /// failed. `None` while it is healthy. + /// Whether the application is inside a DEC 2026 update it began and has + /// not ended. False once the emulator has panicked, since it is never + /// asked again (#211), and an emulator failure is reported ahead of + /// anything this decides. + fn in_open_update(&self) -> bool { + self.emu_panic.is_none() && self.emu.in_sync_update() + } + fn emulator_failure(&self) -> Option { self.emu_panic.as_ref().map(|detail| { Error::Emulator { @@ -4461,6 +4482,9 @@ impl Terminal { /// [`Error::Timeout`] at the deadline — with a pointed message when the /// application never emitted a single synchronized update, since /// `wait_frame` can then never succeed; use `wait_until` for such apps. + /// An application that began an update and has not ended it, stalled on + /// a read or on a query's reply, is named as that instead, as + /// [`wait_idle`](Self::wait_idle) names it. /// [`Error::Eof`] as soon as the PTY closes with no matching frame. pub fn wait_frame(&mut self, predicate: impl FnMut(&Screen) -> bool) -> Result { self.wait_frame_deadline(predicate, self.default_timeout) @@ -4558,10 +4582,11 @@ impl Terminal { // picture that claims to be current — and what changed // between that frame and the live grid is shown as a diff, // which is the question a stuck wait actually asks. - let (frames, screen, query) = { + let (frames, screen, query, open) = { let mut guard = self.shared.lock(); let screen = guard.snapshot(); - (guard.frames_seen, screen, guard.query_note()) + let open = guard.in_open_update(); + (guard.frames_seen, screen, guard.query_note(), open) }; let dropped_note = match dropped { 0 => String::new(), @@ -4575,11 +4600,40 @@ impl Terminal { ), }; let note = format!("{query}{}{}", self.unread_note(), history_note(&screen)); + let open_note = if open { + "; the next one is open, begun and not yet ended" + } else { + "" + }; // What put the cursor where it is: the resize that moved it // last, or else a frame an earlier wait returned. The message // names that one, since the other never happened (#705). let resized = self.frame_cursor_resize; - let waiting_for = if frames > 0 && frames == cursor { + // What the application has not repainted since, for the + // messages that name an update left open. + let since = match resized { + Some((cols, rows)) => format!("the resize to {cols}x{rows}"), + None => "the frame this terminal last returned".to_owned(), + }; + let waiting_for = if open && frames == 0 { + // It did emit one, and stalled inside it: on a read, or + // on a query's reply, which the note then names. + // "Never emitted" and the advice to use wait_until sent + // the reader away from the cause, while wait_idle on the + // same terminal named it (#837). + format!( + "a complete frame — the application began a DEC 2026 synchronized \ + update and has not ended it (Begin with no End), so no frame has \ + completed and the screen below is a half-painted one{note}" + ) + } else if open && frames == cursor { + format!( + "{WHAT} — since {since}, the application began a DEC 2026 \ + synchronized update and has not ended it (Begin with no End), so \ + the screen below is a half-painted frame ({} in total){note}", + frames_phrase(frames) + ) + } else if frames > 0 && frames == cursor { // Every frame the application drew is behind the cursor, // handed to an earlier wait or drawn before a resize, so // it has not repainted since. Naming that is the @@ -4614,19 +4668,19 @@ impl Terminal { ) } else if cursor == 0 { format!( - "{WHAT} ({} observed{dropped_note}){note}", + "{WHAT} ({} observed{dropped_note}{open_note}){note}", frames_phrase(frames) ) } else if let Some((cols, rows)) = resized { format!( "{WHAT} ({} since the resize to {cols}x{rows}, {frames} in total\ - {dropped_note}){note}", + {dropped_note}{open_note}){note}", frames_phrase(frames - cursor) ) } else { format!( "{WHAT} ({} since the last one returned, {frames} in total\ - {dropped_note}){note}", + {dropped_note}{open_note}){note}", frames_phrase(frames - cursor) ) }; diff --git a/crates/termlens/tests/frames.rs b/crates/termlens/tests/frames.rs index ee8cf9c1..656d1546 100644 --- a/crates/termlens/tests/frames.rs +++ b/crates/termlens/tests/frames.rs @@ -305,6 +305,76 @@ fn an_unmatched_end_publishes_no_frame() { ); } +/// An application stalled inside a DEC 2026 update, on a read or on a +/// query's reply, did emit one: the timeout names the open update, as +/// `wait_idle`'s does, rather than "never emitted" and advice to use +/// `wait_until` (#837). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY closes a DEC 2026 bracket before the content it wrapped, so no frame holds what was drawn (#149)" +)] +fn a_wait_frame_timeout_names_an_update_left_open_before_any_frame() -> termlens::Result<()> { + let mut t = emit( + Terminal::builder().timeout(Duration::from_secs(10)), + &["--raw", r"\e[?2026hhalf a frame", "--wait"], + )?; + t.wait_until(|s| s.contains("half a frame"))?; + let err = t + .wait_frame_for(|s| s.contains("half"), Duration::from_millis(300)) + .unwrap_err(); + let msg = err.to_string(); + assert!(!msg.contains("never emitted"), "it emitted one: {msg}"); + assert!( + msg.contains("began a DEC 2026 synchronized update and has not ended it"), + "the open update is named: {msg}" + ); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + +/// The same once a frame was returned: the next repaint is open, which is +/// not "has not completed a repaint ... if it does not repaint in response +/// to this input" (#837). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY closes a DEC 2026 bracket before the content it wrapped, so no frame holds what was drawn (#149)" +)] +fn a_wait_frame_timeout_names_an_update_left_open_after_a_frame() -> termlens::Result<()> { + let mut t = emit( + Terminal::builder().timeout(Duration::from_secs(10)), + &[ + "--raw", + r"\e[?2026h\e[Hone\e[?2026l", + "--wait", + "--raw", + r"\e[?2026h\e[Htwo", + "--wait", + ], + )?; + t.wait_frame(|s| s.contains("one"))?; + t.send(Key::Enter)?; + t.wait_until(|s| s.contains("two"))?; + let err = t + .wait_frame_for(|s| s.contains("two"), Duration::from_millis(300)) + .unwrap_err(); + let msg = err.to_string(); + assert!( + msg.contains("began a DEC 2026 synchronized update and has not ended it"), + "the open update is named: {msg}" + ); + assert!(!msg.contains("use wait_until"), "{msg}"); + assert!( + !msg.contains("assert on the screen with wait_until"), + "{msg}" + ); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + #[test] fn a_defensive_mode_reset_keeps_the_never_emitted_diagnosis() { // Verbatim from a real crash handler: applications reset terminal modes diff --git a/crates/termlens/tests/record.rs b/crates/termlens/tests/record.rs index 50f1443f..3ddff7c6 100644 --- a/crates/termlens/tests/record.rs +++ b/crates/termlens/tests/record.rs @@ -316,6 +316,33 @@ fn a_recording_spans_up_to_its_last_frame() -> termlens::Result<()> { /// The asciicast header carries the optional keys a player shows: when the /// recording was taken and what was recorded (#309). Without them a file /// attached to a bug report answers neither question. +/// An application stalled inside its first DEC 2026 update did emit one: +/// `stop` names the open update rather than "never emitted" (#837). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY closes a DEC 2026 bracket before the content it wrapped, so a recorded frame never holds what was drawn (#149)" +)] +fn stop_names_an_update_left_open() -> termlens::Result<()> { + let mut t = emit( + Terminal::builder(), + &["--raw", r"\e[?2026hhalf a frame", "--wait"], + )?; + t.wait_until(|s| s.contains("half a frame"))?; + let rec = t.record(); + let err = rec.stop().expect_err("no frame has completed"); + assert!(matches!(err, termlens::Error::Input(_)), "{err}"); + let msg = err.to_string(); + assert!(!msg.contains("never emitted"), "it emitted one: {msg}"); + assert!( + msg.contains("began a DEC 2026 synchronized update and has not ended it"), + "the open update is named: {msg}" + ); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + #[test] #[cfg_attr( windows, diff --git a/docs/DESIGN.md b/docs/DESIGN.md index af71dd5c..abd69a1f 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -427,7 +427,9 @@ screen dump** — a CI log alone answers "what was the app showing?". repaint — and a Begin/End pair that changed nothing still counts, since the count is of repaints rather than of changes. An app that never emits a synchronized update makes the timeout error say so and point at - `wait_until`. + `wait_until`. An app that began one and has not ended it, stalled on a + read or on a query's reply, is named as that instead, as `wait_idle` + names it (#837); so is `Recorder::stop`'s refusal. - `wait_idle(quiet)` — resolves when **no bytes for `quiet`** AND the stream does not end mid-escape-sequence (or mid-UTF-8-character) AND no synchronized update is open (a begun-but-unfinished DEC 2026 repaint is diff --git a/skills/termlens/SKILL.md b/skills/termlens/SKILL.md index 579001cc..7651784c 100644 --- a/skills/termlens/SKILL.md +++ b/skills/termlens/SKILL.md @@ -439,6 +439,7 @@ included in `X`, and `terminal closed (EOF) while waiting for X` is | ``failed to send … to `…` (the child released the terminal (EOF) before this write of 4096 bytes finished; …)`` | the child exited while the send was blocked on input it had stopped reading | the embedded screen is its last; if the exit is expected, `wait_exit()` instead of typing into it | | `… note: the application left 100 bytes of input unread` (Linux, macOS) | the app has stopped reading: what you sent sits in the terminal's input queue — in canonical mode, complete lines only; `at least 4095 bytes` on Linux means the 4 KiB read buffer is full and more may wait behind it | find why it stopped reading (a blocking call, a stalled read loop: crossterm 0.29 can stall after 1,024 bytes arrive at once, crossterm#1142) rather than lengthening the wait | | `the application never emitted a DEC 2026 synchronized update` | `wait_frame` or `record().stop()` against an app without synchronized output | use `snapshot_after` / `wait_until` (rule 8) | +| `the application began a DEC 2026 synchronized update and has not ended it (Begin with no End)` | `wait_frame` or `record().stop()` while the app is stalled inside a repaint, on a read or on a query's reply (a query note names it) | find what it is blocked on; `wait_frame` returns once the update ends | | `--- last returned frame → live screen ---` under a `wait_frame` timeout | the app repainted, but never into the predicate | the diff shows what did change; the predicate is looking at the wrong thing | | `input not receivable: the application has not enabled mouse tracking` | `click`/`drag`/`scroll` before the app enabled the mouse, or after it reset a tracking mode: `CSI ? 1000 l` ends reporting whichever of `?9`, `?1000`, `?1002`, `?1003` was set, as in xterm | `wait_until(|s| s.mouse_mode() != MouseMode::None)` first; an app that resets one mode to keep another must set that one again | | `input not receivable: mouse at (50, 2) is outside the 20x5 grid` | coordinates swapped or out of range | rule 6 | From 981c3236187107fcf25f1aa42007d7e4ef0d5a24 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:45:23 +0700 Subject: [PATCH 3/6] fix(queries): answer XTGETTCAP keys by cursor-key mode and termcap name XTGETTCAP answered each key capability with its normal-mode bytes, whatever mode the application had set, so one that set DECCKM, as ncurses does through smkx for keypad(), learned \e[A for Up and then received \eOA from send. xterm answers "the string that xterm would send" by running the keysym through its own key input, which picks SS3 under DECCKM. The answers now come from Key::encode_modal with the mode as of the query. The keys were known only by their terminfo names, while Co and TN were answered by their termcap names. The termcap names Vim asks by (kb, ku, kd, kr, kl, kh, @7, kD, kP, kN) are answered now too. Closes #831 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 7 ++ crates/termlens/src/terminal.rs | 57 ++++++++++----- crates/termlens/tests/queries.rs | 115 +++++++++++++++++++++++++++++++ docs/DESIGN.md | 8 ++- 4 files changed, 167 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c636fbc..9369868b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -157,6 +157,13 @@ reads that marker. that had not repainted in response to the input, with advice to use `wait_until`; `wait_frame` is the right wait for it, and returns once the update ends. (#837) +- XTGETTCAP answers a key capability with what `send` writes for the key + in the cursor-key mode the application has set, as xterm does: after + `CSI ? 1 h`, which ncurses sends for `keypad()`, `kcuu1` is `\eOA` + where it was `\e[A`, and `khome` and `kend` likewise. Each key is + answered by its termcap name too (`kb`, `ku`, `kd`, `kr`, `kl`, `kh`, + `@7`, `kD`, `kP`, `kN`), the names Vim asks by, which were declined. + (#831) ## [0.11.11] - 2026-11-25 diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index 4929815d..142aa054 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -1656,7 +1656,11 @@ impl EmuState { format!("\x1b[?{mode};{value}$y").into_bytes() } Query::RequestTermcap { names, shape } => { - match termcap_reply(names, &self.term_name) { + // The mode as of this query: processing stops at each query, + // so a DECCKM ahead of it in the same read is applied and + // one after it is not, as for DECRPM above. + let application_cursor = self.emu.input_modes().application_cursor; + match termcap_reply(names, &self.term_name, application_cursor) { Some(reply) => reply, None => { // Nothing in the request was even readable as a hex @@ -2561,31 +2565,48 @@ const MIN_DIMENSION: u16 = 2; /// /// Every entry is something the crate genuinely implements, checked against /// the code that implements it rather than copied from a terminfo file. The -/// key capabilities are the exact bytes [`Key::encode`](crate::Key::encode) -/// produces in default mode, so an application that reads them and then -/// matches incoming input against them will match what we actually send. +/// key capabilities are the exact bytes [`Terminal::send`] writes for the key +/// in the cursor-key mode the application has set now, so an application +/// that reads them and then matches incoming input against them will match +/// what we actually send. Each is known by its terminfo and its termcap +/// name, as `colors`/`Co` and `name`/`TN` are. /// /// Declining is the default for everything else, and it is not a shrug: a /// guessed capability is worse than an absent one, because the application /// will believe it. -fn termcap_value(name: &str, term_name: &str) -> Option { +fn termcap_value(name: &str, term_name: &str, application_cursor: bool) -> Option { + // Key capabilities: what `send` writes for the key now. xterm answers + // with "the corresponding string that xterm would send" (ctlseqs.txt): + // it runs the capability's keysym through its own key input + // (`misc.c` XTGETTCAP, `input.c` `Input()`), which picks SS3 for the + // cursor keys under DECCKM. Answering the normal-mode bytes taught an + // application that set DECCKM, as ncurses does through `smkx` for + // `keypad()`, `\e[A` for Up while Up sent `\eOA` (#831). The termcap + // names are the ones Vim asks by (`key_names[]` in its `term.c`). + use crate::Key; + let key = match name { + "kbs" | "kb" => Some(Key::Backspace), + "kcuu1" | "ku" => Some(Key::Up), + "kcud1" | "kd" => Some(Key::Down), + "kcuf1" | "kr" => Some(Key::Right), + "kcub1" | "kl" => Some(Key::Left), + "khome" | "kh" => Some(Key::Home), + "kend" | "@7" => Some(Key::End), + "kdch1" | "kD" => Some(Key::Delete), + "kpp" | "kP" => Some(Key::PageUp), + "knp" | "kN" => Some(Key::PageDown), + _ => None, + }; + if let Some(key) = key { + // Every key above encodes to ASCII, so the bytes are a string. + return String::from_utf8(key.encode_modal(application_cursor)).ok(); + } Some(match name { // The terminal name we told the child, so `TN` and `$TERM` agree. "TN" | "name" => term_name.to_owned(), // 256 indexed colours, which is what `xterm-256color` promises and // what the emulator renders. "Co" | "colors" => "256".to_owned(), - // Key capabilities: exactly what `Key::encode` emits. - "kbs" => "\u{7f}".to_owned(), - "kcuu1" => "\u{1b}[A".to_owned(), - "kcud1" => "\u{1b}[B".to_owned(), - "kcuf1" => "\u{1b}[C".to_owned(), - "kcub1" => "\u{1b}[D".to_owned(), - "khome" => "\u{1b}[H".to_owned(), - "kend" => "\u{1b}[F".to_owned(), - "kdch1" => "\u{1b}[3~".to_owned(), - "kpp" => "\u{1b}[5~".to_owned(), - "knp" => "\u{1b}[6~".to_owned(), _ => return None, }) } @@ -2596,7 +2617,7 @@ fn termcap_value(name: &str, term_name: &str) -> Option { /// known, `0` = unsupported), so a mixed request cannot be answered in a /// single frame without lying about one half of it. `None` when nothing in /// the request decoded as a name at all. -fn termcap_reply(names: &str, term_name: &str) -> Option> { +fn termcap_reply(names: &str, term_name: &str, application_cursor: bool) -> Option> { let mut out = Vec::new(); let mut decoded_any = false; for hex_name in names.split(';').filter(|s| !s.is_empty()) { @@ -2604,7 +2625,7 @@ fn termcap_reply(names: &str, term_name: &str) -> Option> { continue; }; decoded_any = true; - match termcap_value(&name, term_name) { + match termcap_value(&name, term_name, application_cursor) { Some(value) => out.extend_from_slice( format!("\x1bP1+r{hex_name}={}\x1b\\", encode_hex(value.as_bytes())).as_bytes(), ), diff --git a/crates/termlens/tests/queries.rs b/crates/termlens/tests/queries.rs index 599fecc8..d08ef18a 100644 --- a/crates/termlens/tests/queries.rs +++ b/crates/termlens/tests/queries.rs @@ -1084,3 +1084,118 @@ fn xtgettcap_key_capabilities_match_what_send_emits() -> termlens::Result<()> { assert!(t.wait_exit()?.success()); Ok(()) } + +/// The key capabilities are what the key sends *now*: after DECCKM +/// (`CSI ? 1 h`, which ncurses sends through `smkx` when a program calls +/// `keypad()`), the cursor keys and Home and End send SS3 forms, and +/// XTGETTCAP answers them, as xterm does by running the capability's keysym +/// through its own key input (#831). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY answers or eats the child's queries itself, so they never reach the responder (#149)" +)] +fn xtgettcap_key_answers_follow_cursor_key_mode() -> termlens::Result<()> { + // kcuu1, khome, kend; each reply is 4 + 10 + 1 + 6 + 2 = about 30 bytes. + let ask = |deckcm: &str| { + common::spawn_emit( + Terminal::builder() + .size(200, 6) + .timeout(Duration::from_secs(10)), + &[ + "--raw-mode", + "--raw", + &format!(r"{deckcm}\eP+q6b63757531;6b686f6d65;6b656e64\e\\"), + "--read-quiet", + "200", + " DONE", + "--read", + "3", + " END", + "--wait", + ], + ) + }; + let mut t = ask(r"\e[?1h")?; + t.wait_until(|s| s.contains("DONE"))?; + let text = t.screen().text(); + for reply in [ + "P1+r6b63757531=1b4f41", + "P1+r6b686f6d65=1b4f48", + "P1+r6b656e64=1b4f46", + ] { + assert!(text.contains(reply), "{reply} in {text}"); + } + // And `send` writes those bytes in this mode (`--read` shows ESC as E). + t.send(Key::Up)?; + t.wait_until(|s| s.contains("DONEEOA END"))?; + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + + // Without DECCKM, the normal-mode bytes, as before. + let mut t = ask("")?; + t.wait_until(|s| s.contains("DONE"))?; + let text = t.screen().text(); + for reply in [ + "P1+r6b63757531=1b5b41", + "P1+r6b686f6d65=1b5b48", + "P1+r6b656e64=1b5b46", + ] { + assert!(text.contains(reply), "{reply} in {text}"); + } + t.send(Key::Up)?; + t.wait_until(|s| s.contains("DONEE[A END"))?; + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + +/// Each key capability is answered by its termcap name as well, as `Co` +/// and `TN` are: ctlseqs.txt names "termcap or terminfo capability names", +/// and Vim asks by the termcap names (`ku`, `kd`, `kr`, `kl`, …) (#831). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY answers or eats the child's queries itself, so they never reach the responder (#149)" +)] +fn xtgettcap_answers_the_termcap_names_of_keys() -> termlens::Result<()> { + // termcap name, then the bytes `Key::encode` gives that key. + let keys: [(&str, Key); 10] = [ + ("kb", Key::Backspace), + ("ku", Key::Up), + ("kd", Key::Down), + ("kr", Key::Right), + ("kl", Key::Left), + ("kh", Key::Home), + ("@7", Key::End), + ("kD", Key::Delete), + ("kP", Key::PageUp), + ("kN", Key::PageDown), + ]; + let hex = |bytes: &[u8]| -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() }; + let request: Vec = keys.iter().map(|(name, _)| hex(name.as_bytes())).collect(); + let mut t = common::spawn_emit( + Terminal::builder() + .size(200, 10) + .timeout(Duration::from_secs(10)), + &[ + "--raw-mode", + "--raw", + &format!(r"\eP+q{}\e\\", request.join(";")), + "--read-quiet", + "400", + " DONE", + "--wait", + ], + )?; + t.wait_until(|s| s.contains("DONE"))?; + // The replies wrap across rows; join them back. + let text: String = t.screen().text().replace('\n', ""); + for (name, key) in keys { + let reply = format!("P1+r{}={}", hex(name.as_bytes()), hex(&key.encode())); + assert!(text.contains(&reply), "{name}: {reply} in {text}"); + } + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} diff --git a/docs/DESIGN.md b/docs/DESIGN.md index abd69a1f..bef90fe2 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -241,8 +241,12 @@ and ConPTY keeps typed input on its own side of the pipe. `XTGETTCAP` is answered from a table of capabilities the crate actually implements, and every entry was checked against the code that implements it rather than copied from a terminfo file — the key capabilities are literally -the bytes `Key::encode` produces, so an application that reads them and then -matches incoming input against them matches what we send. Anything else gets +the bytes `send` writes for the key in the cursor-key mode the application +has set at the query, SS3 forms under DECCKM as xterm answers them, so an +application that reads them and then matches incoming input against them +matches what we send (#831). Each key is known by its terminfo and its +termcap name (`kcuu1` and `ku`, `kend` and `@7`), as `colors`/`Co` and +`name`/`TN` are. Anything else gets the explicit "unsupported" reply, which is the half that matters: a capability we guessed at would be believed, while a refusal lets the application decide instead of wait. From 1850884380f3d26a95fd7fd110c55f809dce376d Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:48:54 +0700 Subject: [PATCH 4/6] fix(wait): skip the frame of an update open across a resize resize moved the frame cursor to the count of completed frames, and an update open at that moment was not counted yet. When the application ended it after the resize, its frame, drawn at the old size, was the first one wait_frame offered, so a predicate the old layout satisfied passed on it: the stale-frame trap the cursor was moved to close. An application with a spinner or a clock is often painting when the resize lands, and finishes that frame before it handles SIGWINCH. resize now notes an update open at the resize. The reader marks the frame that ends it, and wait_frame steps past that frame while no frame has been returned since the resize. The sketch's cursor + 1 would have skipped a real frame when the update never ends: a hard reset closes it without one, so the reader drops the note then and the next frame is offered. A timeout while that update is still open names it as begun before the resize, so the "since the resize" wording stays true. Closes #836 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 7 ++ crates/termlens/src/terminal.rs | 88 ++++++++++++++++++++--- crates/termlens/tests/frames.rs | 124 ++++++++++++++++++++++++++++++++ docs/DESIGN.md | 10 ++- 4 files changed, 219 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9369868b..203e96e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -164,6 +164,13 @@ reads that marker. answered by its termcap name too (`kb`, `ku`, `kd`, `kr`, `kl`, `kh`, `@7`, `kD`, `kP`, `kN`), the names Vim asks by, which were declined. (#831) +- `wait_frame` after a `resize` no longer offers the frame of a DEC 2026 + update that was open when the resize landed. The application finishes + that frame before it handles `SIGWINCH`, so it was drawn at the old + size, and it was the first frame offered: a predicate the old layout + satisfied passed on it. A timeout while that update is still open + names it. An update a hard reset closes without a frame leaves the + next frame offered. (#836) ## [0.11.11] - 2026-11-25 diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index 142aa054..9fe9c2fe 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -1338,6 +1338,14 @@ struct EmuState { snapshot_cache: Option<(u64, Screen)>, /// Completed synchronized updates (DEC 2026) observed so far. frames_seen: u64, + /// A DEC 2026 update was open when the last resize landed and has + /// neither completed nor been abandoned since. It was begun at the old + /// size, so its frame is not the repaint that answers the resize (#836). + open_at_resize: bool, + /// The index of the frame that completed the update open at the last + /// resize, once it has: `wait_frame` steps past it while no frame has + /// been returned since that resize. Cleared by every resize. + stale_frame: Option, /// The most recent completed frames, oldest first, capped at /// [`FRAME_HISTORY`]. Several frames can complete inside one read, so /// keeping only the newest made rapid intermediate states — a @@ -1441,6 +1449,8 @@ impl EmuState { // spawned with is exactly that. snapshot_cache: Some((0, emu_snapshot)), frames_seen: 0, + open_at_resize: false, + stale_frame: None, frames: VecDeque::with_capacity(FRAME_HISTORY), timings: VecDeque::new(), recorders: Vec::new(), @@ -2958,6 +2968,12 @@ fn reader_loop( match processed.stop { Some(Stop::FrameComplete(span)) => { state.frames_seen += 1; + // The update open at the resize ended here, + // and every later one began after it (#836). + if state.open_at_resize { + state.open_at_resize = false; + state.stale_frame = Some(state.frames_seen); + } // Through `build_snapshot`, so a retained // frame carries the repaint count like every // other snapshot. Taking it straight from the @@ -2994,6 +3010,16 @@ fn reader_loop( } None => {} } + // Closed without a frame, by a hard reset: the next + // frame was begun after the resize and is offered + // (#836). Processing stops at each frame's End, so + // an update that ended above was handled there, and + // one closed and another begun inside this call is + // the one case read as still open: it costs that + // frame, never offers a stale one. + if state.open_at_resize && !state.emu.in_sync_update() { + state.open_at_resize = false; + } } })); if let Err(payload) = processing { @@ -3159,7 +3185,9 @@ pub struct Terminal { /// already returned from this terminal. Each call looks only past it, /// so N successive calls observe N distinct frames and a frame cannot /// satisfy two waits. Advanced by a resize too: a frame drawn at the - /// old size is not the repaint that answers the new one. + /// old size is not the repaint that answers the new one. A `wait_frame` + /// after the resize steps it past the frame of an update open at the + /// resize, once that has ended (#836). frame_cursor: u64, /// The size (cols, rows) of the resize that last moved `frame_cursor`, /// while no frame has been returned since. A `wait_frame` timeout says @@ -4436,7 +4464,8 @@ impl Terminal { /// /// A [`resize`](Self::resize) that changes a dimension also advances the /// cursor: a frame drawn at the old size is not the repaint that answers - /// the new one. A resize to the size the grid already has is a true + /// the new one, and neither is the frame of an update open when the + /// resize landed, begun at the old size and ended after it (#836). A resize to the size the grid already has is a true /// no-op — no `SIGWINCH`, no repaint — so it leaves the cursor where it /// was, and the frame the application last drew is still offered. /// @@ -4533,7 +4562,11 @@ impl Terminal { ) -> Result { const WHAT: &str = "a complete frame matching the predicate"; let deadline = deadline_after(timeout); - let cursor = self.frame_cursor; + // Advanced past the frame of an update that was open at the resize + // which last moved the cursor, once the reader has marked it, and + // only while no frame has been returned since that resize (#836). + let mut cursor = self.frame_cursor; + let after_resize = self.frame_cursor_resize.is_some(); let mut seen_frame = None; // Frames past the cursor that left the ring before this wait could // offer them: a burst longer than FRAME_HISTORY drops its oldest @@ -4547,6 +4580,10 @@ impl Terminal { if let Some(failure) = state.emulator_failure() { return Some(Err(failure)); } + if after_resize && state.stale_frame == Some(cursor + 1) { + cursor += 1; + next_unoffered = next_unoffered.max(cursor + 1); + } if state.frames_seen > cursor && seen_frame != Some(state.frames_seen) { seen_frame = Some(state.frames_seen); if let Some((oldest, _)) = state @@ -4586,6 +4623,8 @@ impl Terminal { } None }); + // Kept across calls: the stale frame stays behind the cursor. + self.frame_cursor = cursor; match outcome { Ok(Ok((index, frame))) => { self.frame_cursor = index; @@ -4603,11 +4642,18 @@ impl Terminal { // picture that claims to be current — and what changed // between that frame and the live grid is shown as a diff, // which is the question a stuck wait actually asks. - let (frames, screen, query, open) = { + let (frames, screen, query, open, open_at_resize) = { let mut guard = self.shared.lock(); let screen = guard.snapshot(); let open = guard.in_open_update(); - (guard.frames_seen, screen, guard.query_note(), open) + let open_at_resize = after_resize && guard.open_at_resize; + ( + guard.frames_seen, + screen, + guard.query_note(), + open, + open_at_resize, + ) }; let dropped_note = match dropped { 0 => String::new(), @@ -4636,7 +4682,18 @@ impl Terminal { Some((cols, rows)) => format!("the resize to {cols}x{rows}"), None => "the frame this terminal last returned".to_owned(), }; - let waiting_for = if open && frames == 0 { + let waiting_for = if let (true, Some((cols, rows))) = (open_at_resize, resized) { + // Begun at the old size, so not "since the resize": its + // frame will not be offered, and the repaint for the new + // size is a later one (#836). + format!( + "{WHAT} — the DEC 2026 synchronized update the application began \ + before the resize to {cols}x{rows} has not ended (Begin with no \ + End), and its frame, begun at the old size, will not be offered; \ + the screen below is a half-painted frame ({} in total){note}", + frames_phrase(frames) + ) + } else if open && frames == 0 { // It did emit one, and stalled inside it: on a read, or // on a query's reply, which the note then names. // "Never emitted" and the advice to use wait_until sent @@ -4663,7 +4720,7 @@ impl Terminal { match resized { Some((cols, rows)) => format!( "{WHAT} — the application has not completed a repaint since the \ - resize to {cols}x{rows} ({} in total), and a frame drawn at \ + resize to {cols}x{rows} ({} in total), and a frame begun at \ the old size is not offered. If it does not repaint when \ resized, assert on the screen with wait_until instead{note}", frames_phrase(frames) @@ -5240,8 +5297,13 @@ impl Terminal { /// that needs the new width, a complete status bar on the new bottom /// row — or use [`wait_frame`](Self::wait_frame) where the app emits /// synchronized updates, which is safe here when the size actually - /// changes: the frame cursor advances, so only a frame completed - /// *after* it can satisfy the wait. For any application, + /// changes: the frame cursor advances, so only a frame begun and + /// completed *after* it can satisfy the wait — an update open when the + /// resize lands was begun at the old size, and its frame is not offered + /// however late it ends (#836). An application that repaints for the + /// new size inside the update it had already begun therefore needs one + /// more frame: its repaint cannot be told from one drawn at the old + /// size. For any application, /// [`resize_and_wait`](Self::resize_and_wait) resizes and asks its /// predicate only once the application has drawn something after the /// resize. A resize to the size the grid @@ -5384,6 +5446,14 @@ impl Terminal { return Err(Error::Pty(format!("resize failed: {e}"))); } state.touch(); + // An update open now was begun at the old size; the frame it + // completes is drawn there, however late it ends, so it is not + // offered either. The application finishes such a frame before + // it handles SIGWINCH (#836). Its index is unknown until it + // ends, and it may never end (RIS closes it with no frame), so + // the reader marks it rather than the cursor counting it here. + state.open_at_resize = state.in_open_update(); + state.stale_frame = None; // Built, not stored: the screen an emulator panic freezes is the // last one a test took (#775), and no test has taken this one. let left = keep_left.then(|| state.build_snapshot()); diff --git a/crates/termlens/tests/frames.rs b/crates/termlens/tests/frames.rs index 656d1546..85c0895b 100644 --- a/crates/termlens/tests/frames.rs +++ b/crates/termlens/tests/frames.rs @@ -779,6 +779,130 @@ fn the_repaint_answering_a_resize_is_offered_to_wait_frame() -> termlens::Result Ok(()) } +/// An update open when the resize lands was begun at the old size: the +/// application finishes that frame before it handles `SIGWINCH`, as one +/// with a spinner or a clock does, so its frame is not offered as the +/// repaint answering the resize (#836). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY closes a DEC 2026 bracket before the content it wrapped, so no frame holds what was drawn (#149)" +)] +fn a_resize_inside_an_update_does_not_offer_that_update() -> termlens::Result<()> { + let mut t = emit( + Terminal::builder() + .size(80, 24) + .timeout(Duration::from_secs(10)), + // Opens an update at 80x24 and waits for a line; then closes it, and + // repaints at the size the terminal has by then. + &[ + "--raw-mode", + "--raw", + r"\e[?2026h\e[H\e[2Jlayout ", + "--winsize", + "--wait", + "--raw", + r"\e[?2026l", + "--sleep", + "200ms", + "--raw", + r"\e[?2026h\e[H\e[2Jlayout ", + "--winsize", + "--raw", + r"\e[?2026l", + "--wait", + ], + )?; + t.wait_until(|s| s.contains("layout 80x24"))?; // inside the update + t.resize(100, 30)?; + t.send(Key::Enter)?; + let frame = t.wait_frame(|s| s.contains("layout"))?; + assert!( + frame.row_text(0).starts_with("layout 100x30"), + "the update begun before the resize is not offered:\n{frame}" + ); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + +/// The update open at the resize may never end: a hard reset (RIS) closes +/// it without a frame. The next frame was begun after the resize, so it is +/// the one offered, not skipped in the old update's place (#836). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY closes a DEC 2026 bracket before the content it wrapped, so no frame holds what was drawn (#149)" +)] +fn a_resize_inside_an_update_a_reset_abandons_offers_the_next_frame() -> termlens::Result<()> { + let mut t = emit( + Terminal::builder() + .size(80, 24) + .timeout(Duration::from_secs(10)), + &[ + "--raw-mode", + "--raw", + r"\e[?2026h\e[H\e[2Jstale ", + "--winsize", + "--wait", + // RIS ends the open update with no frame. + "--raw", + r"\ec", + "--sleep", + "200ms", + "--raw", + r"\e[?2026h\e[H\e[2Jlayout ", + "--winsize", + "--raw", + r"\e[?2026l", + "--wait", + ], + )?; + t.wait_until(|s| s.contains("stale 80x24"))?; + t.resize(100, 30)?; + t.send(Key::Enter)?; + let frame = t.wait_frame_for(|s| s.contains("layout"), Duration::from_secs(3))?; + assert!(frame.row_text(0).starts_with("layout 100x30"), "{frame}"); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + +/// An update still open at the timeout, begun before the resize, is named +/// as that: its frame will not be offered (#836). +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY closes a DEC 2026 bracket before the content it wrapped, so no frame holds what was drawn (#149)" +)] +fn a_timeout_names_the_update_open_across_a_resize() -> termlens::Result<()> { + let mut t = emit( + Terminal::builder() + .size(80, 24) + .timeout(Duration::from_secs(10)), + &[ + "--raw", + r"\e[?2026h\e[Hone\e[?2026l", + "--raw", + r"\e[?2026h\e[Htwo", + "--wait", + ], + )?; + t.wait_until(|s| s.repaints() == 1 && s.contains("two"))?; + t.resize(100, 30)?; + let msg = t + .wait_frame_for(|s| s.contains("two"), Duration::from_millis(300)) + .unwrap_err() + .to_string(); + assert!( + msg.contains("began before the resize to 100x30 has not ended"), + "{msg}" + ); + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + /// `screen()` is the live grid even for an application that brackets /// every repaint — the tear is real, documented, and wanted for /// diagnosis. `wait_frame`'s return value is the frame-consistent read. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index bef90fe2..8940a059 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -422,6 +422,14 @@ screen dump** — a CI log alone answers "what was the app showing?". `send(key); wait_frame(old_state)` fail instead of passing on stale content. A `resize` that changes a dimension advances the cursor too: a frame drawn at the old size is not the repaint that answers the new one. + Nor is the frame of an update open when the resize lands: the + application finishes it before it handles `SIGWINCH`, so it was begun + at the old size however late it ends. The reader marks the frame that + ends it, and a `wait_frame` steps past that one; an update a hard reset + closes without a frame leaves the next frame offered (#836). An + application that repaints for the new size inside the update it had + already begun needs one more frame, since termlens cannot tell that + repaint from one drawn at the old size. A resize to the size the grid already has is a no-op — no `SIGWINCH`, no repaint — and leaves the cursor where it was. @@ -595,7 +603,7 @@ post-SIGWINCH frame can show — content that needs the new width, a complete status bar on the new bottom row — or use `wait_frame` where the app emits synchronized updates, which is safe here when the size actually changes: `resize` advances the frame cursor, so only a frame -completed *after* the resize can satisfy the wait. A resize to the size +begun and completed *after* the resize can satisfy the wait. A resize to the size the grid already has is a no-op, and the frame the application last drew is still the current truth. From 55f90c82214ee7efa6bd2cb2a9c8e433121fe68c Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:50:45 +0700 Subject: [PATCH 5/6] fix(record): bound a recording's image data by capture_graphics Every recorded frame is a whole Screen, and every Screen holds an Arc of the graphics log as it stood, with each image's data. RecordingState charged a frame for its cells only, so a running recorder kept every image the application sent while the terminal kept capture_graphics of them: 400 repaints of a 1 MiB image held 400 MiB against a 4 MiB bound. The recording now counts the image data its frames hold, each payload once by the address of its shared data, and drops its oldest frames, reported in dropped(), while that passes capture_graphics, as it does for cells past record_budget. The newest frame is always kept; its images are within the bound already, since the terminal's log is. The test records twenty 1 KiB images against a 4 KiB budget rather than the issue's 200 MiB, so the test of the bound stays bounded itself. Closes #855 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 7 +++ crates/termlens/src/terminal.rs | 104 +++++++++++++++++++++++++++----- crates/termlens/tests/record.rs | 85 ++++++++++++++++++++++++++ docs/DESIGN.md | 4 +- skills/termlens/SKILL.md | 2 +- 5 files changed, 184 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 203e96e3..5ad8fc89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -171,6 +171,13 @@ reads that marker. satisfied passed on it. A timeout while that update is still open names it. An update a hard reset closes without a frame leaves the next frame offered. (#836) +- A running `Recorder` no longer keeps every image the application sent. + Each recorded frame holds the graphics log as it stood, so a recording + of 400 repaints each carrying a 1 MiB image held 400 MiB while the + terminal kept 4. A recording now keeps no more image data than + `capture_graphics` across its frames, each image counted once, and + drops its oldest frames, counted in `Recording::dropped()`, to stay + within it. (#855) ## [0.11.11] - 2026-11-25 diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index 9fe9c2fe..629a7137 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -6,7 +6,7 @@ //! the test thread. Screens are immutable snapshots taken under that lock, //! so no output is ever lost between two waits. -use std::collections::{HashSet, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::ffi::{OsStr, OsString}; use std::fmt; // The asciicast header is assembled key by key because two of its keys @@ -862,20 +862,77 @@ struct RecordingState { frames: VecDeque<(Duration, Screen)>, cells: usize, budget: usize, + /// The image data the frames hold, each payload once: the frames share + /// it through `Arc`s, keyed by the data's address and length, with how + /// many frames hold each. An address cannot be reused while a frame + /// here keeps the allocation alive, and the entry goes with the last. + images: HashMap<(usize, usize), usize>, + image_bytes: usize, + /// [`TerminalBuilder::capture_graphics`]: the recording keeps no more + /// image data than the terminal does (#855). + image_budget: usize, dropped: u64, } impl RecordingState { + fn new(budget: usize, image_budget: usize) -> Self { + Self { + started: Instant::now(), + frames: VecDeque::new(), + cells: 0, + budget, + images: HashMap::new(), + image_bytes: 0, + image_budget, + dropped: 0, + } + } + fn push(&mut self, frame: Screen) { - let cells = usize::from(frame.cols()) * usize::from(frame.rows()); - while !self.frames.is_empty() && self.cells + cells > self.budget { + self.cells += usize::from(frame.cols()) * usize::from(frame.rows()); + self.hold_images(&frame, true); + self.frames.push_back((self.started.elapsed(), frame)); + // Oldest first, on both bounds, and never the frame just pushed: a + // frame larger than the cell budget alone is kept, as it always was, + // and its images are within `capture_graphics` already, since the + // terminal's own log is. + // + // Every frame holds the graphics log as it stood (#855), and with + // it each image's data; cells alone left a recording of an + // image-heavy application holding every image it showed, far past + // the capture bound the terminal keeps. + while self.frames.len() > 1 + && (self.cells > self.budget || self.image_bytes > self.image_budget) + { if let Some((_, gone)) = self.frames.pop_front() { self.cells -= usize::from(gone.cols()) * usize::from(gone.rows()); + self.hold_images(&gone, false); self.dropped += 1; } } - self.cells += cells; - self.frames.push_back((self.started.elapsed(), frame)); + } + + /// Count `frame`'s image data in, or out, once per distinct payload. + fn hold_images(&mut self, frame: &Screen, hold: bool) { + for payload in frame.graphics().payloads() { + let Some(data) = payload.data() else { + continue; + }; + let key = (data.as_ptr() as usize, data.len()); + if hold { + let holders = self.images.entry(key).or_insert(0); + if *holders == 0 { + self.image_bytes += data.len(); + } + *holders += 1; + } else if let Some(holders) = self.images.get_mut(&key) { + *holders -= 1; + if *holders == 0 { + self.images.remove(&key); + self.image_bytes -= data.len(); + } + } + } } } @@ -1037,8 +1094,10 @@ impl Recording { self.frames.is_empty() } - /// Frames dropped to stay within [`TerminalBuilder::record_budget`] — - /// the oldest ones, so the recording is honest about being a tail. + /// Frames dropped to stay within [`TerminalBuilder::record_budget`], or + /// within [`TerminalBuilder::capture_graphics`] for the image data the + /// frames keep — the oldest ones, so the recording is honest about being + /// a tail. #[must_use] pub fn dropped(&self) -> u64 { self.dropped @@ -2140,6 +2199,12 @@ impl TerminalBuilder { /// The default is 4 MiB. `0` keeps no data at all — the counters and /// every declared fact stay exact, which is all a test that only asks /// "did an image go out?" ever reads. + /// + /// The bound holds for a [`record`](Terminal::record)ing too. Every + /// recorded frame keeps the images the terminal held when it completed, + /// so a recording drops its oldest frames, and reports them dropped, to + /// keep no more image data than this across all its frames, each image + /// counted once however many frames share it. #[must_use] pub fn capture_graphics(mut self, bytes: usize) -> Self { self.capture_graphics = bytes; @@ -2151,6 +2216,11 @@ impl TerminalBuilder { /// reported as dropped. The default, two million cells, is about a /// thousand 80x24 frames; an animation test wants a few, a session /// recording wants them all and knows how long it runs. + /// + /// A recorded frame keeps the inline images the terminal held when it + /// completed, as well as its cells. Their data is bounded by + /// [`capture_graphics`](Self::capture_graphics), not by this: the + /// oldest frames are dropped for whichever bound is passed first. #[must_use] pub fn record_budget(mut self, cells: usize) -> Self { self.record_budget = cells; @@ -2535,6 +2605,7 @@ impl TerminalBuilder { frame_cursor_resize: None, last_frame: None, record_budget: self.record_budget, + capture_graphics: self.capture_graphics, cell_size: self.cell_size, mouse_held: Vec::new(), }) @@ -3199,6 +3270,9 @@ pub struct Terminal { last_frame: Option, /// The builder's recording budget, handed to each `record()`. record_budget: usize, + /// The builder's graphics capture budget, which bounds a recording's + /// image data too (#855). + capture_graphics: usize, /// Declared pixels per cell, kept so a resize can recompute the PTY's /// pixel geometry rather than silently dropping it. cell_size: Option<(u16, u16)>, @@ -3275,19 +3349,17 @@ impl Terminal { /// /// The recorder receives what the frame ring receives: complete DEC 2026 /// synchronized updates, and only those. Bounded by - /// [`record_budget`](TerminalBuilder::record_budget), oldest frames - /// dropped and the drop reported. The recorder holds no borrow of the + /// [`record_budget`](TerminalBuilder::record_budget) in cells and by + /// [`capture_graphics`](TerminalBuilder::capture_graphics) in the image + /// data the frames keep, oldest frames dropped and the drop reported. The recorder holds no borrow of the /// terminal; drive the application as usual while it runs, and drop it /// — or [`stop`](Recorder::stop) it — when the recording is over; a /// recorder that goes out of scope stops collecting. pub fn record(&mut self) -> Recorder { - let state = Arc::new(Mutex::new(RecordingState { - started: Instant::now(), - frames: VecDeque::new(), - cells: 0, - budget: self.record_budget, - dropped: 0, - })); + let state = Arc::new(Mutex::new(RecordingState::new( + self.record_budget, + self.capture_graphics, + ))); let started = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .ok() diff --git a/crates/termlens/tests/record.rs b/crates/termlens/tests/record.rs index 3ddff7c6..2e893999 100644 --- a/crates/termlens/tests/record.rs +++ b/crates/termlens/tests/record.rs @@ -451,6 +451,91 @@ fn the_asciicast_header_describes_the_recorded_terminal() -> termlens::Result<() Ok(()) } +/// A recorded frame holds the terminal's graphics log as it stood, and with +/// it every image's data, so a running recorder kept every image the +/// application sent while the terminal kept only `capture_graphics` of +/// them (#855). The recording is bounded by the same budget, counting each +/// image once however many frames share it, and drops its oldest frames, +/// reported, to stay within it. +/// +/// Small by design, as a test of a bound must be: twenty 1 KiB images +/// against a 4 KiB budget, 20 KiB held at worst. +#[test] +#[cfg_attr( + windows, + ignore = "ConPTY does not forward kitty or sixel payloads, and closes a DEC 2026 bracket before the content it wrapped (#149)" +)] +fn a_recording_keeps_no_more_image_data_than_capture_graphics() -> termlens::Result<()> { + const BUDGET: usize = 4096; + const FRAMES: usize = 20; + let image = "A".repeat(1024); + // Each repaint a DEC 2026 update carrying one quiet kitty transmission. + let repaints: Vec = (1..=FRAMES) + .map(|k| format!(r"\e[?2026h\e[1;1Hframe {k}\e_Ga=t,f=100,q=2,i={k};{image}\e\\\e[?2026l")) + .collect(); + let mut steps = vec!["--wait"]; + for repaint in &repaints { + steps.extend(["--raw", repaint]); + } + steps.extend([" END", "--wait"]); + let mut t = emit(Terminal::builder().capture_graphics(BUDGET), &steps)?; + let rec = t.record(); + t.send(Key::Enter)?; + t.wait_until(|s| s.contains("END"))?; + let recording = rec.stop()?; + + let held_by_terminal: usize = t + .screen() + .graphics() + .payloads() + .iter() + .filter_map(|p| p.data()) + .map(<[u8]>::len) + .sum(); + assert!( + held_by_terminal > 0 && held_by_terminal <= BUDGET, + "the terminal keeps images within its budget: {held_by_terminal}" + ); + + // Distinct payloads, by the address of their data, as the frames share + // them through `Arc`s. + let mut held = std::collections::HashSet::new(); + let mut bytes = 0; + for (_, frame) in recording.frames() { + for payload in frame.graphics().payloads() { + if let Some(data) = payload.data() { + if held.insert(data.as_ptr()) { + bytes += data.len(); + } + } + } + } + assert!( + bytes <= BUDGET, + "the recording holds {bytes} bytes of image data in {} images over {} frames, \ + {} dropped; capture_graphics is {BUDGET}", + held.len(), + recording.len(), + recording.dropped() + ); + assert!(recording.dropped() > 0, "the drop is reported"); + assert_eq!( + recording.len() + usize::try_from(recording.dropped()).unwrap(), + FRAMES, + "every frame is kept or counted as dropped" + ); + let last = &recording + .frames() + .last() + .expect("the newest frame is kept") + .1; + assert!(last.contains(&format!("frame {FRAMES}")), "{last}"); + + t.send(Key::Enter)?; + assert!(t.wait_exit()?.success()); + Ok(()) +} + /// Live heap bytes in this test process, for the dropped-recorder test /// below. /// diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 8940a059..3450b6bf 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -956,7 +956,9 @@ Rules: composited onto the grid, so nothing termlens reports about the screen changes because an image was decoded. Retention is bounded like scrollback (4 MiB and 512 payloads by default, `TerminalBuilder::capture_graphics`), - and a payload past the bound reports `None` data and refuses to decode + and a recording keeps no more image data than that across its frames, + each of which holds the log as it stood: it drops its oldest frames, + reported, to stay within it (#855). A payload past the bound reports `None` data and refuses to decode with `DecodeError::NotCaptured` rather than handing back a prefix that would decode into a plausible-looking wrong picture. `f=100` (PNG) is refused for the same reason a guessed query reply is: termlens carries no diff --git a/skills/termlens/SKILL.md b/skills/termlens/SKILL.md index 7651784c..90d0e276 100644 --- a/skills/termlens/SKILL.md +++ b/skills/termlens/SKILL.md @@ -463,7 +463,7 @@ included in `X`, and `terminal closed (EOF) while waiting for X` is | `.current_dir(path)` | default: the test process's directory | | `.scrollback(rows)` | history retained (default 1000, text only) | | `.scrollback_styles(true)` | retain scrolled rows as cells too, so `scrollback_cell` keeps a masked-field assertion alive after it scrolls (measured cost in the rustdoc) | -| `.record_budget(cells)` | how much `record()` retains, in cells (frames × grid size), before dropping the oldest frames; default 2,000,000, about a thousand 80x24 frames — `Recording::dropped()` counts what went | +| `.record_budget(cells)` | how much `record()` retains, in cells (frames × grid size), before dropping the oldest frames; default 2,000,000, about a thousand 80x24 frames — `Recording::dropped()` counts what went. The images the frames keep are bounded by `capture_graphics` too | | `.spawn(program) -> Result` | program is a path or a name on `PATH` | **Wait** (the waits all return `termlens::Result`, all embed the screen on failure, all have a `_for(…, timeout)` twin; the last two rows are about frames over time rather than waits): From 8c0bcfaa172b9615e814a741dcdedad98b5b1cff Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:54:25 +0700 Subject: [PATCH 6/6] fix(drop): stop the jobs of a job-control shell on Linux Drop stopped the process group the child leads. A shell with job control, every interactive one and sh after set -m, starts each job in a process group of its own in the child's session, and the kernel's hang-up as the session leader exits reaches the foreground group only, so a job that ignored SIGHUP ran on after the drop, on a PTY nobody held. #714's group kill never reached it. On Linux the session's other groups are read from /proc//stat before the hang-up and again before the kill, and are hung up and killed with the child's. The session's id is the child's pid, which no process can take while the child is unreaped or a member lives. A scan costs about 2 ms with 500 processes, so the second is skipped when the first found no other group. macOS would list the session through sysctl with KERN_PROC_SESSION. That is not done: it could not be run and checked here, so LIMITATIONS says that off Linux such a job outlives the drop, and the two new tests are ignored there. Closes #835 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 8 +++ crates/termlens/src/terminal.rs | 94 ++++++++++++++++++++++++++++++++ crates/termlens/tests/process.rs | 83 ++++++++++++++++++++++++++++ docs/DESIGN.md | 15 +++++ docs/LIMITATIONS.md | 9 +++ 5 files changed, 209 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ad8fc89..5c4fb63c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -178,6 +178,14 @@ reads that marker. `capture_graphics` across its frames, each image counted once, and drops its oldest frames, counted in `Recording::dropped()`, to stay within it. (#855) +- On Linux, `Drop` stops the jobs a shell with job control started, each + in a process group of its own in the child's session. The kernel's + hang-up as the session leader exits reaches the foreground group only, + so a background job that ignored `SIGHUP`, typed at an interactive + `bash` or started by `sh` after `set -m`, ran on after the drop, on a + PTY nobody held. The session's other groups are now hung up and killed + with the child's. macOS and the other Unixes still stop the child's + group only, as `docs/LIMITATIONS.md` says. (#835) ## [0.11.11] - 2026-11-25 diff --git a/crates/termlens/src/terminal.rs b/crates/termlens/src/terminal.rs index 629a7137..58ed2d89 100644 --- a/crates/termlens/src/terminal.rs +++ b/crates/termlens/src/terminal.rs @@ -5855,8 +5855,19 @@ fn stop_group(child: &mut PtyChild, id: u32, pid: libc::pid_t, deadline: Instant let group = -pid; // `Drop` has not reaped the child, and only this thread reaps it. let mut state = child_state(id); + // The other groups of the child's session, found while the child holds + // the session's id; a child reaped elsewhere before the stop returns + // below without signalling anything, as it did (#630). + let others = if state == ChildState::Gone { + Vec::new() + } else { + session_groups(pid) + }; if state == ChildState::Running { let _ = send_signal(group, libc::SIGHUP); + for &other in &others { + let _ = send_signal(-other, libc::SIGHUP); + } state = settled_by(id, (Instant::now() + HANGUP_GRACE).min(deadline)); if state == ChildState::Gone { // The hang-up ended the child and the kernel reaped it (SIGCHLD @@ -5867,6 +5878,7 @@ fn stop_group(child: &mut PtyChild, id: u32, pid: libc::pid_t, deadline: Instant // the window `send_signal` accepts. Stopping here left that // member running where the default disposition killed it (#774). let _ = send_signal(group, libc::SIGKILL); + kill_session_groups(pid, &others); return; } } @@ -5877,9 +5889,91 @@ fn stop_group(child: &mut PtyChild, id: u32, pid: libc::pid_t, deadline: Instant // group id is still the child's. Whatever in the group ignored the // hangup, the child's or the kernel's, is killed, and the child reaped. let _ = send_signal(group, libc::SIGKILL); + kill_session_groups(pid, &others); reaped_by(child, deadline); } +/// Kill the process groups of the child's session other than its own. +/// +/// A shell with job control, every interactive one and `sh` after `set -m`, +/// starts each job in a process group of its own, in the child's session. +/// The kernel's hang-up as the session leader exits reaches the foreground +/// group only, and a job that ignores `SIGHUP` ran on, on a PTY nobody +/// held: #714's group kill never reached it (#835). +/// +/// The session is scanned again first, so a group that emptied during the +/// hang-up grace is not signalled by a stale id, and a job started during +/// it is not missed. When `first`, the scan before the hang-up, found none, +/// the second is skipped: a scan reads every process's `stat`, about 2 ms +/// with 500 processes, and most drops have no job to find. What that skips +/// is a first job started by the child's own group during the grace, while +/// it is being hung up, which then outlives the drop. +#[cfg(unix)] +fn kill_session_groups(sid: libc::pid_t, first: &[libc::pid_t]) { + if first.is_empty() { + return; + } + for group in session_groups(sid) { + // A group id read from the session a moment ago: it names a group + // while a member lives, and POSIX reuses no group id until then. One + // that emptied between the scan and this call frees its id in a + // window no portable call closes, the window `send_signal` accepts. + let _ = send_signal(-group, libc::SIGKILL); + } +} + +/// The process groups in session `sid` other than the one its leader leads, +/// read from `/proc//stat`, whose fields after the command name are +/// state, ppid, pgrp and session (proc(5)). The session's id is the child's +/// pid, which no other process can take while the child is unreaped or a +/// member of the session lives: Linux frees a pid only once nothing uses it +/// as a process, group or session id. +/// +/// Elsewhere it is empty: macOS lists a session's processes through +/// `sysctl` with `KERN_PROC_SESSION`, which is not done yet, and a job in a +/// group of its own outlives the drop there (docs/LIMITATIONS.md). +#[cfg(target_os = "linux")] +fn session_groups(sid: libc::pid_t) -> Vec { + let mut groups = Vec::new(); + let Ok(entries) = std::fs::read_dir("/proc") else { + return groups; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(pid) = name.to_str().and_then(|n| n.parse::().ok()) else { + continue; + }; + // Gone since the listing, or another user's under hidepid: neither + // is a member this process could signal. + let Ok(stat) = std::fs::read(format!("/proc/{pid}/stat")) else { + continue; + }; + // The command name is parenthesised and may itself hold `)`, so + // the fields start after the last one. + let Some(close) = stat.iter().rposition(|&b| b == b')') else { + continue; + }; + let tail = String::from_utf8_lossy(&stat[close + 1..]); + let mut fields = tail.split_ascii_whitespace().skip(2); + let (Some(pgrp), Some(session)) = (fields.next(), fields.next()) else { + continue; + }; + let (Ok(pgrp), Ok(session)) = (pgrp.parse::(), session.parse::()) + else { + continue; + }; + if session == sid && pgrp > 0 && pgrp != sid && !groups.contains(&pgrp) { + groups.push(pgrp); + } + } + groups +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn session_groups(_sid: libc::pid_t) -> Vec { + Vec::new() +} + /// Poll `id`, our own unreaped child, until it is no longer running or /// `deadline` passes, reaping nothing; where it stands then. #[cfg(unix)] diff --git a/crates/termlens/tests/process.rs b/crates/termlens/tests/process.rs index dff4641d..858bf8bf 100644 --- a/crates/termlens/tests/process.rs +++ b/crates/termlens/tests/process.rs @@ -438,6 +438,89 @@ fn drop_stops_a_hangup_ignoring_helper_in_the_child_s_group() -> termlens::Resul Ok(()) } +/// [`HUP_PROOF_HELPER`]'s body as a script, for a shell with job control +/// to start as a job: `sh job.sh &` puts it in a process group of its own, +/// in the child's session, and `$$` in it is its own pid. +#[cfg(unix)] +const HUP_PROOF_JOB: &str = "trap '' HUP; echo \"helper:$$;\"; \ + while [ ! -e go ]; do sleep 0.02; done; : > seen; exec sleep 120\n"; + +/// A job a shell with job control started is in a process group of its +/// own, which the kernel's hang-up as the session leader exits never +/// reaches: only the foreground group is hung up. One that ignores +/// `SIGHUP` ran on after the drop, on a PTY nobody held (#835). Here the +/// shell is `sh` after `set -m`. +#[cfg(unix)] +#[test] +#[cfg_attr( + not(target_os = "linux"), + ignore = "a job in a group of its own outlives the drop off Linux (docs/LIMITATIONS.md, #835)" +)] +fn drop_stops_a_hangup_ignoring_job_of_a_job_control_shell() -> termlens::Result<()> { + let dir = helper_dir("session-set-m")?; + std::fs::write(dir.join("job.sh"), HUP_PROOF_JOB)?; + let mut t = sh_in(&dir, "set -m; sh job.sh & read _")?; + // Dropped, and so killed, whatever the assertion below decides. + let helper = Helper::armed(&mut t, &dir)?; + assert_ne!( + process_group(&helper.pid), + process_group(&t.pid().expect("a pid").to_string()), + "the job has a process group of its own, or this proves nothing" + ); + drop(t); + assert!( + helper.gone(), + "job {} outlived the drop of a `set -m` shell", + helper.pid + ); + Ok(()) +} + +/// The same with an interactive `bash`, the shell a suite most often +/// drives with job control: the job is typed at its prompt (#835). +#[cfg(unix)] +#[test] +#[cfg_attr( + not(target_os = "linux"), + ignore = "a job in a group of its own outlives the drop off Linux (docs/LIMITATIONS.md, #835)" +)] +fn drop_stops_a_hangup_ignoring_job_an_interactive_shell_started() -> termlens::Result<()> { + let dir = helper_dir("session-bash-i")?; + std::fs::write(dir.join("job.sh"), HUP_PROOF_JOB)?; + let mut t = Terminal::builder() + .timeout(Duration::from_secs(10)) + .current_dir(&dir) + .env("PS1", "ready> ") + .args(["--norc", "--noprofile", "-i"]) + .spawn("bash")?; + t.wait_until(|s| s.contains("ready>"))?; + t.send_str("sh job.sh &")?; + t.send(Key::Enter)?; + let helper = Helper::armed(&mut t, &dir)?; + assert_ne!( + process_group(&helper.pid), + process_group(&t.pid().expect("a pid").to_string()), + "the job has a process group of its own, or this proves nothing" + ); + drop(t); + assert!( + helper.gone(), + "job {} outlived the drop of an interactive bash", + helper.pid + ); + Ok(()) +} + +/// The process group of `pid`, as `ps` reports it. +#[cfg(unix)] +fn process_group(pid: &str) -> String { + let out = std::process::Command::new("ps") + .args(["-o", "pgid=", "-p", pid]) + .output() + .expect("ps runs"); + String::from_utf8_lossy(&out.stdout).trim().to_owned() +} + /// The same once the child has exited, and no wait has reaped it: it is a /// zombie, which holds the group's id, so the group is killed and the /// child reaped. Teardown used to reap such a child first and then signal diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 3450b6bf..9f48c4fd 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -499,6 +499,21 @@ reuses no process group id while a member of the group exists, and a member that ignored the hang-up is what the kill is for (#774). `signal` still reaches the child alone. +On Linux the other process groups of the child's session are hung up and +killed with it (#835). A shell with job control, every interactive one +and `sh` after `set -m`, starts each job in a group of its own, and the +kernel's hang-up as the session leader exits reaches the foreground group +only, so a job that ignores SIGHUP was never a member the group kill +reached. The session's groups are read from `/proc//stat` before the +hang-up and again before the kill, the session's id being the child's +pid, which no other process takes while the child is unreaped or a member +lives. The scan reads every process's `stat`, about 2 ms with 500 +processes, so the second is skipped when the first found no other group: +a first job started during the hang-up grace then outlives the drop. +macOS would list the session through `sysctl` with `KERN_PROC_SESSION`; +that is not done, and elsewhere such a job outlives the drop +(LIMITATIONS). + ### `screen()` is the live grid, frames or no frames `wait_frame` is the only frame-gated observation in the crate. `screen()` diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index e47f5436..ac847ade 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -350,6 +350,15 @@ CHANGELOG entry. drop's hang-up ends it and the kernel reaps it at once, and the group is killed all the same, since a member still running keeps the group's id from being reused (#774). +- **Off Linux, a job in a process group of its own outlives the drop.** A + shell with job control (an interactive one, or `sh` after `set -m`) + starts each job in a group of its own in the program's session. On + Linux `Drop` finds the session's groups in `/proc` and kills them too; + on macOS and the other Unixes it stops the program's own group only, so + such a job that ignores SIGHUP runs on, on a PTY nobody holds. End the + jobs before the drop (`kill %1`, or `exit` twice at a bash prompt), or + start the shell without job control. On Linux, a first job started + while the drop is hanging the program up is missed too (#835). - Exotic grapheme clusters render as the vt100 crate renders them; the unicode-torture fixture pins the current behaviour. - **Needle matching is NFC, then substring, not grapheme matching.**