Trace reconnect mouse input handling
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled

This commit is contained in:
DuProcess
2026-07-12 00:40:28 -04:00
parent 1dcb33550e
commit 80e922957e
7 changed files with 537 additions and 19 deletions
+281 -17
View File
@@ -4878,7 +4878,12 @@ async fn run_terminal(
stdin_msg = stdin_rx.recv() => {
match stdin_msg {
Some(mut bytes) => {
dosh::trace::event(
"client.stdin",
&[("bytes", dosh::trace::bytes_summary(&bytes))],
);
if input_matches_escape(&bytes, escape_key.as_deref()) {
dosh::trace::event("client.escape", &[]);
break;
}
let saw_focus_in = input_contains_focus_in(&bytes);
@@ -4886,6 +4891,10 @@ async fn run_terminal(
&& saw_focus_in
&& last_focus_repaint_at.elapsed() >= FOCUS_REPAINT_COOLDOWN
{
dosh::trace::event(
"client.focus_reconnect_start",
&[("silent_ms", last_packet_at.elapsed().as_millis().to_string())],
);
last_focus_repaint_at = Instant::now();
if let Some(frame) = reconnect(
&socket,
@@ -4897,6 +4906,13 @@ async fn run_terminal(
)
.await?
{
dosh::trace::event(
"client.focus_reconnect_ok",
&[
("output_seq", frame.output_seq.to_string()),
("bytes", frame.bytes.len().to_string()),
],
);
refresh_live_addr(&mut addr, &cred)?;
arm_stale_terminal_input_suppression(
&mut stale_terminal_input_suppress_until,
@@ -4917,15 +4933,60 @@ async fn run_terminal(
.await?;
}
}
let before_focus_strip = bytes.len();
bytes = strip_terminal_focus_reports(&bytes);
if before_focus_strip != bytes.len() {
dosh::trace::event(
"client.focus_stripped",
&[
("before", before_focus_strip.to_string()),
("after", bytes.len().to_string()),
],
);
}
if bytes.is_empty() {
continue;
}
if should_strip_unowned_terminal_reports(
predictor.alternate_screen,
predictor.mouse_tracking,
) {
let before_mouse_strip = bytes.len();
bytes = strip_stale_mouse_reports(&bytes);
if before_mouse_strip != bytes.len() {
dosh::trace::event(
"client.unowned_mouse_stripped",
&[
("before", before_mouse_strip.to_string()),
("after", bytes.len().to_string()),
("summary", dosh::trace::bytes_summary(&bytes)),
],
);
}
if bytes.is_empty() {
continue;
}
}
if should_strip_stale_terminal_reports(
last_packet_at.elapsed(),
stale_terminal_input_suppress_until,
) {
let before_mouse_strip = bytes.len();
bytes = strip_stale_mouse_reports(&bytes);
dosh::trace::event(
"client.stale_strip",
&[
("before", before_mouse_strip.to_string()),
("after", bytes.len().to_string()),
("silent_ms", last_packet_at.elapsed().as_millis().to_string()),
(
"grace",
stale_terminal_input_suppress_until
.is_some_and(|deadline| Instant::now() < deadline)
.to_string(),
),
],
);
if bytes.is_empty() {
continue;
}
@@ -4940,6 +5001,13 @@ async fn run_terminal(
&bytes,
)
{
dosh::trace::event(
"client.queue_startup_gate",
&[
("bytes", dosh::trace::bytes_summary(&bytes)),
("pending", pending_user_input.len().to_string()),
],
);
queue_pending_user_input(
&mut pending_user_input,
&mut pending_user_input_bytes,
@@ -4967,6 +5035,10 @@ async fn run_terminal(
if send_input(&socket, addr, &cred, &mut send_seq, send_now.clone()).await? {
predictor.observe_input(&send_now)?;
} else {
dosh::trace::event(
"client.queue_send_now_stale",
&[("bytes", dosh::trace::bytes_summary(&send_now))],
);
queue_stale_pending_user_input(
&mut pending_user_input,
&mut pending_user_input_bytes,
@@ -4984,6 +5056,16 @@ async fn run_terminal(
StartupGateMode::HoldAll
};
if should_hold_post_submit_input(&hold_for_later) {
dosh::trace::event(
"client.queue_post_submit_control",
&[
(
"bytes",
dosh::trace::bytes_summary(&hold_for_later),
),
("pending", pending_user_input.len().to_string()),
],
);
queue_pending_user_input(
&mut pending_user_input,
&mut pending_user_input_bytes,
@@ -5002,6 +5084,13 @@ async fn run_terminal(
if sent {
predictor.observe_input(&hold_for_later)?;
} else {
dosh::trace::event(
"client.queue_post_submit_stale",
&[(
"bytes",
dosh::trace::bytes_summary(&hold_for_later),
)],
);
queue_stale_pending_user_input(
&mut pending_user_input,
&mut pending_user_input_bytes,
@@ -5012,6 +5101,13 @@ async fn run_terminal(
continue;
}
if last_packet_at.elapsed() >= Duration::from_secs(2) {
dosh::trace::event(
"client.queue_disconnected",
&[
("bytes", dosh::trace::bytes_summary(&bytes)),
("silent_ms", last_packet_at.elapsed().as_millis().to_string()),
],
);
queue_stale_pending_user_input(
&mut pending_user_input,
&mut pending_user_input_bytes,
@@ -5027,6 +5123,13 @@ async fn run_terminal(
)
.await?
{
dosh::trace::event(
"client.disconnected_reconnect_ok",
&[
("output_seq", frame.output_seq.to_string()),
("bytes", frame.bytes.len().to_string()),
],
);
refresh_live_addr(&mut addr, &cred)?;
arm_stale_terminal_input_suppression(
&mut stale_terminal_input_suppress_until,
@@ -5052,6 +5155,10 @@ async fn run_terminal(
if send_input(&socket, addr, &cred, &mut send_seq, bytes.clone()).await? {
predictor.observe_input(&bytes)?;
} else {
dosh::trace::event(
"client.queue_transient_send",
&[("bytes", dosh::trace::bytes_summary(&bytes))],
);
queue_stale_pending_user_input(
&mut pending_user_input,
&mut pending_user_input_bytes,
@@ -6014,6 +6121,14 @@ async fn reconnect(
frame_buffer: &mut FrameBuffer,
predictor: &mut Predictor,
) -> Result<Option<Frame>> {
dosh::trace::event(
"client.reconnect_start",
&[
("session", cred.session.clone()),
("mode", cred.mode.clone()),
("last_rendered_seq", cred.last_rendered_seq.to_string()),
],
);
if let Ok((frame, next)) = try_live_resume(socket, cred, send_seq, size.0, size.1).await {
*cred = next;
frame_buffer.clear();
@@ -6026,11 +6141,19 @@ async fn reconnect(
send_seq,
)
.await?;
dosh::trace::event(
"client.reconnect_live_ok",
&[
("output_seq", frame.output_seq.to_string()),
("bytes", frame.bytes.len().to_string()),
],
);
return Ok(Some(frame));
}
let Ok((frame, next)) = try_ticket_attach(socket, cred, size.0, size.1, Vec::new()).await
else {
dosh::trace::event("client.reconnect_none", &[]);
return Ok(None);
};
*cred = next;
@@ -6045,6 +6168,13 @@ async fn reconnect(
send_seq,
)
.await?;
dosh::trace::event(
"client.reconnect_ticket_ok",
&[
("output_seq", frame.output_seq.to_string()),
("bytes", frame.bytes.len().to_string()),
],
);
Ok(Some(frame))
}
@@ -6162,6 +6292,10 @@ fn should_strip_stale_terminal_reports(
|| suppress_until.is_some_and(|deadline| Instant::now() < deadline)
}
fn should_strip_unowned_terminal_reports(alternate_screen: bool, mouse_tracking: bool) -> bool {
!alternate_screen && !mouse_tracking
}
fn input_contains_focus_in(bytes: &[u8]) -> bool {
contains_bytes(bytes, b"\x1b[I") || contains_bytes(bytes, b"\x9bI")
}
@@ -6210,23 +6344,44 @@ async fn flush_pending_user_input(
pending: &mut VecDeque<PendingUserInput>,
pending_bytes: &mut usize,
) -> Result<()> {
dosh::trace::event(
"client.pending_flush_start",
&[
("items", pending.len().to_string()),
("bytes", pending_bytes.to_string()),
],
);
while let Some(input) = pending.pop_front() {
let PendingUserInput {
bytes,
strip_mouse_reports,
} = input;
*pending_bytes = pending_bytes.saturating_sub(bytes.len());
let before_filter_len = bytes.len();
let bytes = if strip_mouse_reports {
strip_stale_mouse_reports(&bytes)
} else {
bytes
};
dosh::trace::event(
"client.pending_flush_item",
&[
("before", before_filter_len.to_string()),
("after", bytes.len().to_string()),
("strip_mouse", strip_mouse_reports.to_string()),
("summary", dosh::trace::bytes_summary(&bytes)),
],
);
if bytes.is_empty() {
continue;
}
if send_input(socket, addr, cred, send_seq, bytes.clone()).await? {
predictor.observe_input(&bytes)?;
} else {
dosh::trace::event(
"client.pending_flush_requeue",
&[("bytes", dosh::trace::bytes_summary(&bytes))],
);
requeue_pending_user_input_front(
pending,
pending_bytes,
@@ -6397,6 +6552,8 @@ async fn send_input(
send_seq: &mut u64,
bytes: Vec<u8>,
) -> Result<bool> {
let seq = *send_seq;
let bytes_summary = dosh::trace::bytes_summary(&bytes);
let body = protocol::to_body(&Input { bytes })?;
let packet = protocol::encode_encrypted(
PacketKind::Input,
@@ -6408,7 +6565,17 @@ async fn send_input(
&body,
)?;
*send_seq += 1;
send_terminal_udp(socket, &packet, addr).await
let sent = send_terminal_udp(socket, &packet, addr).await?;
dosh::trace::event(
"client.input_send",
&[
("seq", seq.to_string()),
("ack", cred.last_rendered_seq.to_string()),
("sent", sent.to_string()),
("summary", bytes_summary),
],
);
Ok(sent)
}
async fn send_stream_open(
@@ -6923,22 +7090,44 @@ const GLITCH_FORCE_MS: u128 = 250;
/// without retaining arbitrary terminal output.
const TERMINAL_OUTPUT_PARSE_TAIL: usize = 64;
fn alternate_screen_after_output(mut active: bool, bytes: &[u8]) -> bool {
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct TerminalModeChanges {
alternate_screen: Option<bool>,
mouse_tracking: Option<bool>,
}
fn terminal_modes_after_output(
mut alternate_screen: bool,
mut mouse_tracking: bool,
bytes: &[u8],
) -> (bool, bool) {
let mut offset = 0usize;
while offset < bytes.len() {
let Some((next, transition)) = terminal_private_mode_transition(bytes, offset) else {
let Some((next, changes)) = terminal_private_mode_changes(bytes, offset) else {
offset += 1;
continue;
};
if let Some(enable) = transition {
active = enable;
if let Some(enable) = changes.alternate_screen {
alternate_screen = enable;
}
if let Some(enable) = changes.mouse_tracking {
mouse_tracking = enable;
}
offset = next.max(offset + 1);
}
active
(alternate_screen, mouse_tracking)
}
#[cfg(test)]
fn terminal_private_mode_transition(bytes: &[u8], offset: usize) -> Option<(usize, Option<bool>)> {
terminal_private_mode_changes(bytes, offset)
.map(|(next, changes)| (next, changes.alternate_screen))
}
fn terminal_private_mode_changes(
bytes: &[u8],
offset: usize,
) -> Option<(usize, TerminalModeChanges)> {
let mut cursor = offset;
match bytes.get(cursor).copied()? {
0x1b if bytes.get(cursor + 1) == Some(&b'[') => cursor += 2,
@@ -6957,10 +7146,18 @@ fn terminal_private_mode_transition(bytes: &[u8], offset: usize) -> Option<(usiz
b'0'..=b'9' | b';' | b':' => cursor += 1,
b'h' | b'l' => {
let params = &bytes[params_start..cursor];
let touches_alt = terminal_private_params_include_alt_screen(params);
return Some((cursor + 1, touches_alt.then_some(byte == b'h')));
let enable = byte == b'h';
return Some((
cursor + 1,
TerminalModeChanges {
alternate_screen: terminal_private_params_include_alt_screen(params)
.then_some(enable),
mouse_tracking: terminal_private_params_include_mouse_tracking(params)
.then_some(enable),
},
));
}
0x40..=0x7e => return Some((cursor + 1, None)),
0x40..=0x7e => return Some((cursor + 1, TerminalModeChanges::default())),
_ => return None,
}
}
@@ -6973,6 +7170,17 @@ fn terminal_private_params_include_alt_screen(params: &[u8]) -> bool {
.any(|param| matches!(param, b"47" | b"1047" | b"1049"))
}
fn terminal_private_params_include_mouse_tracking(params: &[u8]) -> bool {
params
.split(|byte| matches!(byte, b';' | b':'))
.any(|param| {
matches!(
param,
b"1000" | b"1001" | b"1002" | b"1003" | b"1005" | b"1006" | b"1015"
)
})
}
/// One speculatively-echoed character on the current line.
#[derive(Clone, Debug)]
struct PredictedCell {
@@ -6990,6 +7198,10 @@ struct Predictor {
/// as vim/htop); we never speculate there because we cannot model arbitrary
/// cursor addressing safely.
alternate_screen: bool,
/// True while the server-side program has requested terminal mouse reports.
/// When false, SGR mouse bytes from the local terminal are stale UI noise and
/// must not be forwarded into the shell prompt.
mouse_tracking: bool,
/// Tail of recent terminal output, retained so alternate-screen transitions
/// split across UDP frames are still detected.
output_parse_tail: Vec<u8>,
@@ -7039,6 +7251,7 @@ impl Predictor {
mode,
enabled: enabled && mode != PredictMode::Off,
alternate_screen: false,
mouse_tracking: false,
output_parse_tail: Vec::new(),
cells: Vec::new(),
cursor: 0,
@@ -7062,6 +7275,7 @@ impl Predictor {
self.epoch += 1;
self.confirmed_epoch = self.epoch - 1;
self.alternate_screen = false;
self.mouse_tracking = false;
self.output_parse_tail.clear();
self.oldest_pending_at = None;
}
@@ -7223,11 +7437,27 @@ impl Predictor {
parse.extend_from_slice(&self.output_parse_tail);
parse.extend_from_slice(bytes);
let before = self.alternate_screen;
self.alternate_screen = alternate_screen_after_output(self.alternate_screen, &parse);
if self.alternate_screen != before {
let before_alternate_screen = self.alternate_screen;
let before_mouse_tracking = self.mouse_tracking;
let (alternate_screen, mouse_tracking) =
terminal_modes_after_output(self.alternate_screen, self.mouse_tracking, &parse);
self.alternate_screen = alternate_screen;
self.mouse_tracking = mouse_tracking;
if self.alternate_screen != before_alternate_screen {
let _ = self.discard_all();
}
if self.alternate_screen != before_alternate_screen
|| self.mouse_tracking != before_mouse_tracking
{
dosh::trace::event(
"client.terminal_modes",
&[
("alt", self.alternate_screen.to_string()),
("mouse", self.mouse_tracking.to_string()),
("bytes", dosh::trace::bytes_summary(bytes)),
],
);
}
self.output_parse_tail.clear();
let keep = parse.len().min(TERMINAL_OUTPUT_PARSE_TAIL);
@@ -8058,11 +8288,12 @@ mod tests {
selected_predict_mode, selected_udp_host, server_version_mismatch,
should_flush_terminal_input_after_contact, should_hold_during_startup_gate,
should_hold_post_submit_input, should_repaint_idle_alternate_screen,
split_after_command_submit, ssh_command_target, ssh_config_uses_proxy,
ssh_destination_host, ssh_username, ssh_with_user, startup_command, status_ssh_target,
strip_stale_mouse_reports, strip_terminal_focus_reports, terminal_private_mode_transition,
toml_bare_key_or_quoted, unix_update_script, update_installer_url, update_version_status,
upsert_managed_block, valid_forward_host, vscode_safe_alias, windows_update_script,
should_strip_unowned_terminal_reports, split_after_command_submit, ssh_command_target,
ssh_config_uses_proxy, ssh_destination_host, ssh_username, ssh_with_user, startup_command,
status_ssh_target, strip_stale_mouse_reports, strip_terminal_focus_reports,
terminal_private_mode_transition, toml_bare_key_or_quoted, unix_update_script,
update_installer_url, update_version_status, upsert_managed_block, valid_forward_host,
vscode_safe_alias, windows_update_script,
};
use dosh::config::{ClientConfig, CommandExtension, HostConfig};
use dosh::native::EnvVar;
@@ -8832,6 +9063,33 @@ mod tests {
assert!(!predictor.alternate_screen);
}
#[test]
fn predictor_tracks_mouse_tracking_modes_separately_from_alternate_screen() {
let mut predictor = Predictor::new(true);
predictor.observe_output(b"\x1b[?1000;1006h");
assert!(!predictor.alternate_screen);
assert!(predictor.mouse_tracking);
predictor.observe_output(b"\x1b[?1006;1000l");
assert!(!predictor.mouse_tracking);
predictor.observe_output(b"\x1b[?1000;1049h");
assert!(predictor.alternate_screen);
assert!(predictor.mouse_tracking);
predictor.observe_output(b"\x1b[?1049l");
assert!(!predictor.alternate_screen);
assert!(predictor.mouse_tracking);
}
#[test]
fn unowned_mouse_reports_are_stripped_only_outside_terminal_mouse_mode() {
assert!(should_strip_unowned_terminal_reports(false, false));
assert!(!should_strip_unowned_terminal_reports(false, true));
assert!(!should_strip_unowned_terminal_reports(true, false));
}
#[test]
fn predictor_tracks_alternate_screen_split_across_frames() {
let mut predictor = Predictor::new(true);
@@ -9740,6 +9998,12 @@ mod tests {
assert_eq!(strip_stale_mouse_reports(b"152;1Mls\r"), b"ls\r");
}
#[test]
fn long_orphan_mouse_spam_is_stripped_from_pending_input() {
let input = b"35;152;1M35;149;1M35;147;1M35;144;2M35;141;3M0;107;10m35;106;10Mtm\r";
assert_eq!(strip_stale_mouse_reports(input), b"tm\r");
}
#[test]
fn split_stale_mouse_suffixes_are_stripped_from_pending_input() {
assert_eq!(strip_stale_mouse_reports(b"1M35;149;1Mls\r"), b"ls\r");