A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
thinkterm-session: extract the mux client session layer into a portable crate
RoversXa3826d913c62
diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.ymlindex 603c7004..27bfc685 100644--- a/.github/workflows/wasm.yml+++ b/.github/workflows/wasm.yml@@ -41,10 +41,12 @@ jobs:- uses: Swatinem/rust-cache@v2with:cache-on-failure: true+ # Dev-dependencies are not checked here (cargo check builds none):+ # thinkterm-session's tests run natively and lean on async-executor.- name: Check the portable core for wasm32run: |- cargo check -p thinkterm-proto -p codec -p wezterm-term -p termwiz \- --target wasm32-unknown-unknown+ cargo check -p thinkterm-proto -p codec -p thinkterm-session \+ -p wezterm-term -p termwiz --target wasm32-unknown-unknown- name: Run the terminal core in a wasm VMrun: |cargo build -p wasm-probe --target wasm32-unknown-unknown --releasediff --git a/Cargo.lock b/Cargo.lockindex 356e9a67..0b668a99 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6470,6 +6470,27 @@ dependencies = ["wezterm-term",]+[[package]]+name = "thinkterm-session"+version = "0.1.0"+dependencies = [+ "anyhow",+ "async-channel",+ "async-executor",+ "codec",+ "futures-lite",+ "futures-util",+ "log",+ "lru",+ "rangeset",+ "termwiz 0.24.0",+ "textwrap",+ "thinkterm-proto",+ "thiserror 1.0.69",+ "url",+ "wezterm-term",+]+[[package]]name = "thinkterm-syntax"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex d6ab2ec2..07971ef7 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -8,6 +8,7 @@ members = ["thinkterm-syntax","thinkterm-core","thinkterm-proto",+ "thinkterm-session","thinkterm-tui","thinkterm-update","deps/cairo",@@ -77,6 +78,7 @@ colorgrad = "0.6"config = { path = "config" }thinkterm-core = { path = "thinkterm-core" }thinkterm-proto = { path = "thinkterm-proto" }+thinkterm-session = { path = "thinkterm-session" }thinkterm-update = { path = "thinkterm-update" }core-foundation = "=0.10.0"core-graphics = "=0.24.0"diff --git a/thinkterm-session/Cargo.toml b/thinkterm-session/Cargo.tomlnew file mode 100644index 00000000..1baa255a--- /dev/null+++ b/thinkterm-session/Cargo.toml@@ -0,0 +1,37 @@+[package]+name = "thinkterm-session"+version = "0.1.0"+edition = "2021"+publish = false++# The mux client "session layer": per-pane wire state (deltas by seqno,+# dirty lines, fetch and stall bookkeeping, the line cache, predictive+# echo, input serials), the ordered input queue, the render-delta queue,+# and the transport-neutral half of a connection. Shared by the desktop+# client, the browser client and any later mobile client. This crate must+# always build for wasm32-unknown-unknown; that constraint is what keeps a+# pure client able to mirror a pane. Do not add dependencies that touch+# processes, files, sockets or threads, and never call+# std::time::Instant/SystemTime or std::thread from it: time goes through+# the Clock trait, spawning through Spawner, the wire through PduLink and+# notifications through SessionEvents. Banned by name: mux, config,+# promise, ratelim, smol, async-io, openssl, portable-pty, filedescriptor.++[dependencies]+anyhow.workspace = true+codec.workspace = true+futures-util.workspace = true+log.workspace = true+lru.workspace = true+rangeset.workspace = true+termwiz = { workspace = true, features = ["use_serde"] }+textwrap.workspace = true+thinkterm-proto.workspace = true+thiserror.workspace = true+url.workspace = true+wezterm-term = { workspace = true, features = ["use_serde"] }++[dev-dependencies]+async-channel.workspace = true+async-executor.workspace = true+futures-lite.workspace = truediff --git a/thinkterm-session/src/clock.rs b/thinkterm-session/src/clock.rsnew file mode 100644index 00000000..7437cd82--- /dev/null+++ b/thinkterm-session/src/clock.rs@@ -0,0 +1,129 @@+//! Time as the session layer sees it: a monotonic `Timestamp` the host+//! supplies. The crate never asks the system for the time itself.+use std::ops::Add;+use std::time::Duration;++/// Microseconds since an origin the host chose; only differences matter.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct Timestamp(u64);++impl Timestamp {+ pub const ZERO: Self = Self(0);++ pub const fn from_micros(micros: u64) -> Self {+ Self(micros)+ }++ pub const fn as_micros(self) -> u64 {+ self.0+ }++ /// Zero when `earlier` is not earlier, like `Instant`'s.+ pub fn saturating_duration_since(self, earlier: Self) -> Duration {+ Duration::from_micros(self.0.saturating_sub(earlier.0))+ }++ pub fn saturating_add(self, d: Duration) -> Self {+ Self(+ self.0+ .saturating_add(d.as_micros().min(u64::MAX as u128) as u64),+ )+ }+}++/// The host's clocks: a monotonic one for deadlines and a wall clock for+/// `InputSerial`, which the wire defines as millis since the unix epoch.+pub trait Clock {+ fn now(&self) -> Timestamp;+ fn wall_millis(&self) -> u64;+}++/// A token bucket: `rate` admits a second, at most `rate` at once, full+/// to begin with. Replaces the desktop's governor-backed limiter, whose+/// per-second quota behaves the same way for unit checks.+#[derive(Debug, Clone)]+pub struct RateLimiter {+ rate: u32,+ tokens: f64,+ last: Timestamp,+}++impl RateLimiter {+ pub fn new(rate: u32, now: Timestamp) -> Self {+ Self {+ rate: rate.max(1),+ tokens: rate.max(1) as f64,+ last: now,+ }+ }++ /// Admit `amount` now, or refuse. `rate` is the current setting: a+ /// changed value rebuilds the bucket full (a reload changed the+ /// limit), an unchanged one only refills what time has earned.+ pub fn admit(&mut self, rate: u32, amount: u32, now: Timestamp) -> bool {+ let rate = rate.max(1);+ if rate != self.rate {+ *self = Self::new(rate, now);+ }+ let elapsed = now.saturating_duration_since(self.last).as_secs_f64();+ self.tokens = (self.tokens + elapsed * self.rate as f64).min(self.rate as f64);+ self.last = now;+ if self.tokens >= amount as f64 {+ self.tokens -= amount as f64;+ true+ } else {+ false+ }+ }+}++impl Add<Duration> for Timestamp {+ type Output = Self;+ fn add(self, d: Duration) -> Self {+ self.saturating_add(d)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(ms: u64) -> Timestamp {+ Timestamp::from_micros(ms * 1000)+ }++ #[test]+ fn n_admits_pass_then_the_next_is_denied_at_the_same_instant() {+ let mut limiter = RateLimiter::new(3, at(0));+ assert!(limiter.admit(3, 1, at(0)));+ assert!(limiter.admit(3, 1, at(0)));+ assert!(limiter.admit(3, 1, at(0)), "the burst is the whole rate");+ assert!(!limiter.admit(3, 1, at(0)), "and then it is spent");+ assert!(+ limiter.admit(3, 1, at(334)),+ "a third of a second earns one back"+ );+ }++ #[test]+ fn a_changed_rate_rebuilds_the_bucket_full() {+ let mut limiter = RateLimiter::new(1, at(0));+ assert!(limiter.admit(1, 1, at(0)));+ assert!(!limiter.admit(1, 1, at(0)));+ assert!(+ limiter.admit(5, 1, at(0)),+ "the reload starts a full bucket"+ );+ }++ #[test]+ fn an_unchanged_rate_does_not_reset_the_bucket() {+ let mut limiter = RateLimiter::new(2, at(0));+ assert!(limiter.admit(2, 1, at(0)));+ assert!(limiter.admit(2, 1, at(0)));+ assert!(+ !limiter.admit(2, 1, at(0)),+ "still spent: no rebuild without a change"+ );+ }+}diff --git a/thinkterm-session/src/connection.rs b/thinkterm-session/src/connection.rsnew file mode 100644index 00000000..fdd8370b--- /dev/null+++ b/thinkterm-session/src/connection.rs@@ -0,0 +1,464 @@+//! The transport-neutral half of a connection: what may be sent before+//! the server knows who we are, the phases a connection goes through, how+//! answers find their requests, when a silent link is declared dead, and+//! how a failed version handshake is described. The desktop client drives+//! these from its socket loop; a browser client from a WebSocket.+use crate::clock::Timestamp;+use codec::{CorruptResponse, Pdu, CODEC_VERSION};+use std::collections::{HashMap, VecDeque};+use std::time::Duration;+use thiserror::Error;++#[derive(Error, Debug)]+#[error("ChannelSendError")]+pub struct ChannelSendError;++pub struct RegistrationBarrier<T> {+ complete: bool,+ deferred: VecDeque<T>,+}++impl<T> RegistrationBarrier<T> {+ pub fn new() -> Self {+ Self {+ complete: false,+ deferred: VecDeque::new(),+ }+ }++ pub fn submit(&mut self, item: T, registration_required: bool) -> Option<T> {+ if registration_required && !self.complete {+ self.deferred.push_back(item);+ None+ } else {+ Some(item)+ }+ }++ pub fn complete(&mut self) -> VecDeque<T> {+ self.complete = true;+ std::mem::take(&mut self.deferred)+ }++ pub fn drain(&mut self) -> VecDeque<T> {+ std::mem::take(&mut self.deferred)+ }++ pub fn is_complete(&self) -> bool {+ self.complete+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub enum ConnectionPhase {+ Connecting = 0,+ Registering = 1,+ Syncing = 2,+ Ready = 3,+ Reconnecting = 4,+ Suspended = 5,+ Detached = 6,+}++impl ConnectionPhase {+ pub fn from_u8(value: u8) -> Self {+ match value {+ 0 => Self::Connecting,+ 1 => Self::Registering,+ 2 => Self::Syncing,+ 3 => Self::Ready,+ 4 => Self::Reconnecting,+ 5 => Self::Suspended,+ _ => Self::Detached,+ }+ }+}++/// The server accepted the connection but never answered the version+/// handshake. Unlike [`IncompatibleVersionError`] this is a transient+/// condition — a wedged or overloaded server (e.g. one pane consuming all+/// of its resources) or a stalled link — and retrying can succeed, so it+/// must never be classified as fatal.+#[derive(Error, Debug, Clone, PartialEq, Eq)]+#[error(+ "The server did not answer the version handshake within {timeout_secs} \+ seconds. The server may be overloaded or wedged, or the link may have \+ stalled. This is transient — it is NOT a version mismatch — and \+ reconnecting can succeed."+)]+pub struct VersionHandshakeStalled {+ pub timeout_secs: u64,+}++/// Human-readable description of a failed version handshake, for errors+/// that are not a timeout. The wording deliberately does not claim a+/// version mismatch: a real mismatch is detected from an actual response+/// ([`IncompatibleVersionError`]); landing here means no usable answer+/// arrived at all, which is most often a transport or server-health+/// problem.+pub fn describe_handshake_failure(err: &anyhow::Error) -> String {+ if err.root_cause().is::<CorruptResponse>() {+ "Received an implausible and likely corrupt response from \+ the server. This can happen if the remote host outputs \+ to stdout prior to running commands. \+ Check your shell startup!"+ .to_string()+ } else if err.root_cause().is::<ChannelSendError>() {+ "Internal channel was closed prior to sending request. \+ This may indicate that the remote host output invalid data \+ to stdout prior to running the requested command. \+ Check your shell startup!"+ .to_string()+ } else {+ format!(+ "The version handshake with the server failed: '{err}'. \+ Possible causes: the connection or the server stalled before \+ answering; the remote host printed to stdout during shell \+ startup (check your shell startup files); or the server build \+ is too old to answer at all. An actual version mismatch is \+ reported explicitly, so do not assume one from this message."+ )+ }+}++/// Describe a server whose build differs from ours, or `None` when they match.+///+/// [`CODEC_VERSION`] guards the wire format, not behaviour: two builds that+/// differ only by a behaviour change still carry the same codec version and+/// handshake without complaint. That is how a mux server left running from a+/// days-old build goes on serving live shells while looking healthy to a+/// freshly built client -- the failure this reports is invisible otherwise.+///+/// Reported through the log rather than the connection UI on purpose. A+/// *remote* server legitimately runs its own build, and nagging on every+/// connect would train the warning away before it ever caught the local case+/// it exists for.+pub fn describe_server_build_mismatch(local: &str, remote: &str) -> Option<String> {+ if local == remote {+ return None;+ }+ Some(format!(+ "mux server is running {remote}, this client is {local}. \+ Codec version {CODEC_VERSION} matches, so they interoperate, but the \+ server may be serving behaviour from an older build; restart it if \+ that is not deliberate."+ ))+}++/// Whether the server answering the handshake is the process asking.+pub fn leads_back_to_this_process(own_server_id: Option<&str>, server_id: &str) -> bool {+ own_server_id.is_some_and(|own| own == server_id)+}++/// Answers matched to the requests waiting for them, by serial. Serial 0+/// is the server speaking unasked and never enters the table.+pub struct SerialTable<W> {+ next_serial: u64,+ waiting: HashMap<u64, W>,+}++/// What became of an answer.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Answer {+ /// Handed to the request that waited for it.+ Delivered,+ /// The request stopped waiting (a bootstrap RPC that timed out and+ /// dropped its receiver). That abandons one request, not the+ /// connection: killing it here turned a transient handshake stall into+ /// a permanent detach.+ Discarded,+ /// Nothing ever asked with this serial: the stream is out of step and+ /// the connection cannot be trusted.+ Unmatched,+}++impl<W> Default for SerialTable<W> {+ fn default() -> Self {+ Self::new()+ }+}++impl<W> SerialTable<W> {+ pub fn new() -> Self {+ Self {+ next_serial: 1,+ waiting: HashMap::new(),+ }+ }++ /// The serial the next request goes out with.+ pub fn next_serial(&self) -> u64 {+ self.next_serial+ }++ /// Take a serial for a request; `waiter` gets its answer.+ pub fn register(&mut self, waiter: W) -> u64 {+ let serial = self.next_serial;+ self.next_serial += 1;+ self.waiting.insert(serial, waiter);+ serial+ }++ /// Take a serial for a request nothing waits on (a keepalive ping).+ pub fn allocate(&mut self) -> u64 {+ let serial = self.next_serial;+ self.next_serial += 1;+ serial+ }++ /// Route `pdu`, answered on `serial`. `deliver` hands it to the waiter+ /// and says whether anyone was still listening.+ pub fn answer(+ &mut self,+ serial: u64,+ pdu: Pdu,+ deliver: impl FnOnce(W, Pdu) -> bool,+ ) -> Answer {+ match self.waiting.remove(&serial) {+ Some(waiter) => {+ if deliver(waiter, pdu) {+ Answer::Delivered+ } else {+ Answer::Discarded+ }+ }+ None => Answer::Unmatched,+ }+ }++ /// Every waiter, for failing them all when the connection ends.+ pub fn drain(&mut self) -> Vec<W> {+ self.waiting.drain().map(|(_, waiter)| waiter).collect()+ }++ pub fn is_empty(&self) -> bool {+ self.waiting.is_empty()+ }+}++/// Application-level keepalive: a transport that died without a reset+/// (VPN egress rotation, a sleepy NAT) otherwise hangs silently until the+/// next write. After `interval` without a byte received, ping; the pong+/// must arrive before the following tick.+pub struct Keepalive {+ interval: Duration,+ deadline: Timestamp,+ pending_ping: Option<(u64, Timestamp)>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum KeepaliveAction {+ /// Put a ping with this serial on the wire.+ SendPing(u64),+ /// The ping with this serial went unanswered for `waited`: the+ /// transport is presumed dead.+ DeclareDead { serial: u64, waited: Duration },+}++impl Keepalive {+ pub fn new(interval: Duration, now: Timestamp) -> Self {+ Self {+ interval,+ deadline: now + interval,+ pending_ping: None,+ }+ }++ /// When the next tick is due.+ pub fn deadline(&self) -> Timestamp {+ self.deadline+ }++ /// A byte arrived. Traffic postpones the next ping, but not the+ /// verdict on one already sent: a server that keeps pushing output+ /// while never answering is still one that never answers.+ pub fn received(&mut self, now: Timestamp) {+ if self.pending_ping.is_none() {+ self.deadline = now + self.interval;+ }+ }++ /// An answer arrived on `serial`; true when it was the pending ping's.+ pub fn answered(&mut self, serial: u64, now: Timestamp) -> bool {+ match self.pending_ping {+ Some((pending, _)) if pending == serial => {+ self.pending_ping = None;+ self.deadline = now + self.interval;+ true+ }+ _ => false,+ }+ }++ /// The deadline passed. `serial` allocates the ping's serial when one+ /// is to be sent.+ pub fn tick(&mut self, now: Timestamp, serial: impl FnOnce() -> u64) -> KeepaliveAction {+ if let Some((serial, sent)) = self.pending_ping.take() {+ return KeepaliveAction::DeclareDead {+ serial,+ waited: now.saturating_duration_since(sent),+ };+ }+ let serial = serial();+ self.pending_ping = Some((serial, now));+ self.deadline = now + self.interval;+ KeepaliveAction::SendPing(serial)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn an_identical_build_is_not_worth_warning_about() {+ assert_eq!(+ describe_server_build_mismatch("20260814-011230-aaef9bfb", "20260814-011230-aaef9bfb"),+ None+ );+ }++ #[test]+ fn a_server_from_another_build_names_both_sides() {+ let mismatch =+ describe_server_build_mismatch("20260815-150100-eab2bf7c", "20260813-012155-816da4db")+ .expect("differing builds are reported");+ // Which side is which is the whole point of the message: the same two+ // version strings in the wrong order sends the user to restart the+ // wrong process.+ assert!(mismatch.contains("server is running 20260813-012155-816da4db"));+ assert!(mismatch.contains("client is 20260815-150100-eab2bf7c"));+ }++ #[test]+ fn registration_barrier_sends_bootstrap_before_deferred_rpcs() {+ let mut barrier = RegistrationBarrier::new();+ assert_eq!(barrier.submit("palette", true), None);+ assert_eq!(barrier.submit("viewport", true), None);+ assert_eq!(+ barrier.submit("GetCodecVersion", false),+ Some("GetCodecVersion")+ );+ assert_eq!(barrier.submit("SetClientId", false), Some("SetClientId"));+ assert_eq!(+ barrier.complete().into_iter().collect::<Vec<_>>(),+ vec!["palette", "viewport"]+ );+ assert_eq!(barrier.submit("focus", true), Some("focus"));+ }++ fn pong() -> Pdu {+ Pdu::Pong(codec::Pong {})+ }++ #[test]+ fn an_answer_nobody_waits_for_is_discarded_not_fatal() {+ let mut table: SerialTable<Option<()>> = SerialTable::new();+ let serial = table.register(Some(()));+ // the waiter is gone: delivery finds nobody listening+ assert_eq!(+ table.answer(serial, pong(), |_, _| false),+ Answer::Discarded+ );+ assert!(table.is_empty());+ }++ #[test]+ fn an_answer_for_an_unknown_serial_is_fatal() {+ let mut table: SerialTable<()> = SerialTable::new();+ let serial = table.register(());+ assert_eq!(table.answer(serial, pong(), |_, _| true), Answer::Delivered);+ assert_eq!(table.answer(serial, pong(), |_, _| true), Answer::Unmatched);+ assert_eq!(table.answer(99, pong(), |_, _| true), Answer::Unmatched);+ assert_eq!(+ table.allocate(),+ 2,+ "a ping takes the next serial without waiting"+ );+ assert_eq!(table.next_serial(), 3);+ }++ fn at(secs: u64) -> Timestamp {+ Timestamp::from_micros(secs * 1_000_000)+ }++ #[test]+ fn traffic_postpones_the_next_ping_but_not_the_verdict_on_one_sent() {+ let mut keepalive = Keepalive::new(Duration::from_secs(15), at(0));+ assert_eq!(keepalive.deadline(), at(15));+ keepalive.received(at(10));+ assert_eq!(keepalive.deadline(), at(25), "a byte pushed the tick back");+ let mut serials = 5u64..;+ assert_eq!(+ keepalive.tick(at(25), || serials.next().unwrap()),+ KeepaliveAction::SendPing(5)+ );+ keepalive.received(at(30));+ assert_eq!(+ keepalive.deadline(),+ at(40),+ "output during a pending ping does not postpone its verdict"+ );+ assert!(+ !keepalive.answered(4, at(31)),+ "some other answer is not the pong"+ );+ assert!(keepalive.answered(5, at(31)));+ assert_eq!(+ keepalive.deadline(),+ at(46),+ "the pong restarts the idle clock"+ );+ }++ #[test]+ fn a_missed_pong_declares_the_transport_dead_on_the_next_tick() {+ let mut keepalive = Keepalive::new(Duration::from_secs(15), at(0));+ assert_eq!(keepalive.tick(at(15), || 7), KeepaliveAction::SendPing(7));+ assert_eq!(+ keepalive.tick(at(30), || 8),+ KeepaliveAction::DeclareDead {+ serial: 7,+ waited: Duration::from_secs(15)+ }+ );+ }+}++#[cfg(test)]+mod handshake_classification_tests {+ use super::*;++ #[test]+ fn unknown_failure_does_not_claim_a_version_mismatch() {+ let err = anyhow::anyhow!("Client was destroyed");+ let msg = describe_handshake_failure(&err);+ assert!(!msg.contains("install a compatible"), "{msg}");+ assert!(msg.contains("Client was destroyed"), "{msg}");+ }++ #[test]+ fn channel_send_error_keeps_its_specific_guidance() {+ let err = anyhow::Error::new(ChannelSendError).context("send_pdu");+ let msg = describe_handshake_failure(&err);+ assert!(msg.contains("Internal channel was closed"), "{msg}");+ }++ #[test]+ fn stalled_handshake_reads_as_transient() {+ let msg = VersionHandshakeStalled { timeout_secs: 60 }.to_string();+ assert!(msg.contains("transient"), "{msg}");+ assert!(msg.contains("NOT a version mismatch"), "{msg}");+ }++ #[test]+ fn a_server_with_our_own_id_is_never_attached() {+ assert!(super::leads_back_to_this_process(Some("abc"), "abc"));+ assert!(!super::leads_back_to_this_process(Some("abc"), "def"));+ assert!(+ !super::leads_back_to_this_process(None, "abc"),+ "a process without a mux of its own cannot be the server"+ );+ }+}diff --git a/thinkterm-session/src/decide.rs b/thinkterm-session/src/decide.rsnew file mode 100644index 00000000..992b4980--- /dev/null+++ b/thinkterm-session/src/decide.rs@@ -0,0 +1,543 @@+//! Pure decisions a pane makes about resizing, palettes and its watchdog,+//! off the network so the ordering rules are unit-testable. Moved from the+//! desktop client's `clientpane.rs`; every client makes these the same way.+use thinkterm_proto::RenderableDimensions;+use wezterm_term::color::ColorPalette;+use wezterm_term::TerminalSize;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ResizeDecision {+ pub converge_local_surface: bool,+ pub send_rpc: bool,+}++pub fn render_watchdog_should_run(dead: bool) -> bool {+ !dead+}++#[derive(Debug, PartialEq)]+pub struct ApplicationPaletteTransition {+ pub palette: ColorPalette,+ pub application_palette: bool,+ pub palette_changed: bool,+ pub provenance_changed: bool,+}++pub fn application_palette_transition(+ current: &ColorPalette,+ configured: &ColorPalette,+ was_application_palette: bool,+ update: Option<ColorPalette>,+) -> ApplicationPaletteTransition {+ let (palette, application_palette) = match update {+ Some(palette) => (palette, true),+ None => (configured.clone(), false),+ };+ ApplicationPaletteTransition {+ palette_changed: current != &palette,+ provenance_changed: was_application_palette != application_palette,+ palette,+ application_palette,+ }+}++pub fn render_dimensions_match_size(dimensions: RenderableDimensions, size: TerminalSize) -> bool {+ dimensions.cols == size.cols+ && dimensions.viewport_rows == size.rows+ && dimensions.pixel_width == size.pixel_width+ && dimensions.pixel_height == size.pixel_height+ && dimensions.dpi == size.dpi+}++pub fn decide_resize(+ last_requested: Option<TerminalSize>,+ dimensions: RenderableDimensions,+ target: TerminalSize,+) -> ResizeDecision {+ let converge_local_surface = !render_dimensions_match_size(dimensions, target);+ ResizeDecision {+ converge_local_surface,+ send_rpc: last_requested != Some(target) && converge_local_surface,+ }+}++pub fn decide_resize_for_viewport(+ owns_viewport: Option<bool>,+ last_requested: Option<TerminalSize>,+ dimensions: RenderableDimensions,+ target: TerminalSize,+) -> ResizeDecision {+ if owns_viewport != Some(true) {+ // A passive renderer shows the canonical server grid. Do not first+ // reflow locally and then get snapped back by the next server push.+ // `None` is not permission: it is the attach-time interval before the+ // server has answered the first viewport advertisement.+ return ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ };+ }+ decide_resize(last_requested, dimensions, target)+}++/// What `requested_size` holds after a resize decision. It dedupes the resize+/// RPC, so it may only record a size the server was actually told about: a+/// target latched on the passive branch would dedupe away the corrective RPC+/// for that same size once this renderer becomes the owner.+///+/// A passive renderer clears the latch outright rather than preserving it:+/// whatever it remembers was sent under a previous ownership, and the server+/// may have been driven elsewhere since - a retained key that happens to+/// equal the takeover target would dedupe away the very RPC that reclaims+/// the geometry. Clearing can never produce a spurious RPC, because+/// `send_rpc` still requires the local surface to disagree with the target.+pub fn next_requested_size(+ owns_viewport: Option<bool>,+ prior: Option<TerminalSize>,+ decision: ResizeDecision,+ target: TerminalSize,+) -> Option<TerminalSize> {+ if owns_viewport != Some(true) {+ return None;+ }+ if decision.send_rpc {+ Some(target)+ } else {+ prior+ }+}++/// Delivery state of the palette advisory RPC.+///+/// A single worker task owns all sending for a pane, and it always sends the+/// LATEST desired palette — that serialization is what makes stale overwrites+/// impossible (two concurrent send tasks with retries could land an old color+/// on the server after a newer one). The state transitions live here, off the+/// network, so the ordering rules are unit-testable.+#[derive(Default)]+pub struct PaletteDelivery {+ /// The palette we want the server to hold.+ desired: Option<ColorPalette>,+ /// The palette the server last confirmed receiving. `None` means+ /// unknown: never confirmed, failed, or invalidated by a reconnect.+ delivered: Option<ColorPalette>,+ /// Whether the sender worker is alive. At most one ever runs.+ sender_running: bool,+}++impl PaletteDelivery {+ /// Adopt a new target. Returns true when the caller must start the+ /// worker (none is running); an already-running worker will pick the+ /// new target up on its next loop.+ pub fn adopt_target(&mut self, palette: ColorPalette) -> bool {+ self.desired = Some(palette);+ if self.sender_running {+ false+ } else {+ self.sender_running = true;+ true+ }+ }++ /// What the worker should send next, or `None` when it is done — in+ /// which case the worker slot is released.+ pub fn next_to_send(&mut self) -> Option<ColorPalette> {+ match &self.desired {+ Some(target) if self.delivered.as_ref() != Some(target) => Some(target.clone()),+ _ => {+ self.sender_running = false;+ None+ }+ }+ }++ pub fn record_success(&mut self, sent: ColorPalette) {+ self.delivered = Some(sent);+ }++ /// The worker gave up (repeated RPC failures). `delivered` stays+ /// whatever it was — importantly NOT the desired value — so the next+ /// set_config or resync restarts the worker instead of assuming the+ /// server heard us.+ pub fn give_up_if_still_desired(&mut self, attempted: &ColorPalette) -> bool {+ if self.desired.as_ref() == Some(attempted) {+ self.sender_running = false;+ true+ } else {+ // A newer target arrived during the final failed RPC. Keep the+ // worker slot and let it send that target instead of stranding it+ // until an unrelated config update or resync happens.+ false+ }+ }++ /// A reconnect happened: whatever we previously confirmed, the server+ /// may be a fresh process that knows nothing.+ pub fn invalidate_delivery(&mut self) {+ self.delivered = None;+ }++ /// The palette the server last confirmed, if any.+ pub fn delivered(&self) -> Option<&ColorPalette> {+ self.delivered.as_ref()+ }+}++pub fn remote_server_identity_matches(created: Option<&str>, current: Option<&str>) -> bool {+ created == current+}++pub fn finish_preview_request(+ requested: &mut Option<TerminalSize>,+ size: TerminalSize,+ succeeded: bool,+ finished: bool,+) {+ if finished && !succeeded && requested.as_ref() == Some(&size) {+ requested.take();+ }+}++#[cfg(test)]+mod test {+ use super::*;++ fn size(cols: usize, rows: usize, dpi: u32) -> TerminalSize {+ TerminalSize {+ rows,+ cols,+ pixel_width: cols * 10,+ pixel_height: rows * 20,+ dpi,+ }+ }++ fn dimensions(size: TerminalSize) -> RenderableDimensions {+ RenderableDimensions {+ cols: size.cols,+ viewport_rows: size.rows,+ scrollback_rows: size.rows,+ dpi: size.dpi,+ pixel_width: size.pixel_width,+ pixel_height: size.pixel_height,+ ..RenderableDimensions::default()+ }+ }++ #[test]+ fn remote_pane_ids_are_reusable_only_within_the_same_mux_runtime() {+ assert!(remote_server_identity_matches(+ Some("devbox:100:runtime-a"),+ Some("devbox:100:runtime-a")+ ));+ assert!(!remote_server_identity_matches(+ Some("devbox:100:runtime-a"),+ Some("devbox:200:runtime-b")+ ));+ assert!(!remote_server_identity_matches(+ None,+ Some("devbox:200:runtime-b")+ ));+ }++ #[test]+ fn resize_decision_separates_local_convergence_from_rpc() {+ let target = size(120, 40, 96);+ let old = size(100, 30, 96);++ assert_eq!(+ decide_resize(Some(target), dimensions(target), target),+ ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ }+ );+ assert_eq!(+ decide_resize(Some(target), dimensions(old), target),+ ResizeDecision {+ converge_local_surface: true,+ send_rpc: false,+ },+ "a delayed server surface must be repaired locally without repeating the RPC"+ );+ assert_eq!(+ decide_resize(Some(old), dimensions(target), target),+ ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ },+ "a server that already reached the target needs no RPC"+ );+ assert_eq!(+ decide_resize(Some(old), dimensions(old), target),+ ResizeDecision {+ converge_local_surface: true,+ send_rpc: true,+ },+ "a genuine target change sends exactly one RPC"+ );+ }++ #[test]+ fn resize_decision_includes_dpi() {+ let target = size(120, 40, 144);+ let mut advertised = dimensions(target);+ advertised.dpi = 96;++ assert_eq!(+ decide_resize(Some(target), advertised, target),+ ResizeDecision {+ converge_local_surface: true,+ send_rpc: false,+ }+ );+ }++ #[test]+ fn passive_different_sized_client_keeps_the_canonical_surface_stable() {+ let canonical = size(132, 40, 96);+ let passive_window = size(80, 24, 96);++ assert_eq!(+ decide_resize_for_viewport(+ Some(false),+ Some(passive_window),+ dimensions(canonical),+ passive_window,+ ),+ ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ },+ "a non-owner must neither publish nor locally reflow to its different window size"+ );+ }++ #[test]+ fn unknown_viewport_ownership_waits_for_the_server() {+ let canonical = size(132, 40, 96);+ let attaching_window = size(80, 24, 96);++ assert_eq!(+ decide_resize_for_viewport(None, None, dimensions(canonical), attaching_window,),+ ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ }+ );+ }++ /// The disconnect-takeover regression: a stale dedupe key from the+ /// passive period must never suppress the corrective RPC once the lease+ /// lands here. Both halves matter: a target latched while passive (never+ /// sent), and a key retained from a PREVIOUS ownership that happens to+ /// equal the takeover target - the common case for a renderer whose+ /// window never changed while another device drove the tab.+ #[test]+ fn a_passive_resize_does_not_dedupe_away_the_owners_first_rpc() {+ let canonical = size(132, 40, 96);+ let target = size(120, 40, 96);++ let passive = decide_resize_for_viewport(Some(false), None, dimensions(canonical), target);+ assert_eq!(+ passive,+ ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ }+ );+ let requested = next_requested_size(Some(false), None, passive, target);+ assert_eq!(requested, None, "nothing was sent, so nothing may latch");++ // A key left over from when this renderer last owned the tab is+ // cleared by any passive round, even though it equals the target.+ assert_eq!(+ next_requested_size(Some(false), Some(target), passive, target),+ None,+ "a passive renderer's dedupe key is meaningless and must clear"+ );++ let takeover =+ decide_resize_for_viewport(Some(true), requested, dimensions(canonical), target);+ assert!(takeover.send_rpc, "the corrective RPC must still go out");+ assert_eq!(+ next_requested_size(Some(true), requested, takeover, target),+ Some(target)+ );++ let repeat =+ decide_resize_for_viewport(Some(true), Some(target), dimensions(canonical), target);+ assert!(!repeat.send_rpc, "a sent size still dedupes the next call");+ assert_eq!(+ next_requested_size(Some(true), Some(target), repeat, target),+ Some(target),+ "an owner's deduped call keeps its key"+ );+ }++ #[test]+ fn stale_preview_completion_cannot_clear_a_newer_requested_size() {+ let geometry = size(120, 40, 96);+ let mut requested = Some(geometry);++ finish_preview_request(&mut requested, geometry, false, false);+ assert_eq!(requested, Some(geometry));++ finish_preview_request(&mut requested, geometry, false, true);+ assert_eq!(requested, None);+ }++ #[test]+ fn dead_panes_do_not_run_the_render_watchdog() {+ assert!(render_watchdog_should_run(false));+ assert!(!render_watchdog_should_run(true));+ }+}++#[cfg(test)]+mod palette_delivery_tests {+ use super::{application_palette_transition, PaletteDelivery};+ use wezterm_term::color::ColorPalette;++ fn palette(fg: f32) -> ColorPalette {+ let mut palette = ColorPalette::default();+ palette.foreground = (fg, fg, fg, 1.0).into();+ palette+ }++ #[test]+ fn a_send_is_confirmed_and_the_worker_stops() {+ let mut state = PaletteDelivery::default();+ assert!(+ state.adopt_target(palette(0.5)),+ "first adopt starts a worker"+ );+ let sent = state.next_to_send().expect("something to send");+ state.record_success(sent);+ assert!(state.next_to_send().is_none(), "delivered == desired: done");+ assert!(!state.sender_running, "the worker slot must be released");+ }++ /// The bug this design removes: a retry of an OLD palette must never be+ /// the last thing the server hears. The worker always re-reads the+ /// latest desired value, so a success for A while B is pending simply+ /// leads to sending B next.+ #[test]+ fn a_stale_color_can_never_be_the_last_one_standing() {+ let mut state = PaletteDelivery::default();+ assert!(state.adopt_target(palette(0.1)));+ let first = state.next_to_send().expect("A to send");++ // B arrives while A's RPC is in flight: same worker, no new task.+ assert!(!state.adopt_target(palette(0.9)), "worker already running");++ state.record_success(first);+ let second = state.next_to_send().expect("B still owed to the server");+ assert_eq!(second, palette(0.9), "the newest target wins");+ state.record_success(second);+ assert!(state.next_to_send().is_none());+ }++ /// The retry path of the same bug: a send FAILS, and while the worker+ /// waits to retry, a newer palette arrives. The retry must send the+ /// newer palette — the failed old one is simply abandoned.+ #[test]+ fn a_retry_after_failure_sends_the_newest_target() {+ let mut state = PaletteDelivery::default();+ assert!(state.adopt_target(palette(0.1)));+ let _failed = state.next_to_send().expect("A to send");+ // The RPC for A fails: no record_success. B arrives during the+ // retry backoff.+ assert!(!state.adopt_target(palette(0.9)), "worker still running");+ assert_eq!(+ state.next_to_send(),+ Some(palette(0.9)),+ "the retry must carry the newest target, not replay the old one"+ );+ }++ /// Give-up leaves delivery unconfirmed so the next advisory restarts a+ /// worker rather than assuming the server heard us.+ #[test]+ fn giving_up_allows_a_later_restart_with_the_same_value() {+ let mut state = PaletteDelivery::default();+ assert!(state.adopt_target(palette(0.5)));+ let _ = state.next_to_send().expect("initial send");+ assert!(state.give_up_if_still_desired(&palette(0.5)));+ assert!(+ state.adopt_target(palette(0.5)),+ "same value must restart the worker after a give-up"+ );+ assert_eq!(state.next_to_send(), Some(palette(0.5)));+ }++ /// A newer target arriving during the final failed RPC must keep the+ /// worker alive; otherwise no caller remains to start delivery for it.+ #[test]+ fn giving_up_an_obsolete_target_keeps_the_worker_for_the_newest_value() {+ let mut state = PaletteDelivery::default();+ let old = palette(0.1);+ let new = palette(0.9);+ assert!(state.adopt_target(old.clone()));+ assert_eq!(state.next_to_send(), Some(old.clone()));+ assert!(!state.adopt_target(new.clone()));+ assert!(!state.give_up_if_still_desired(&old));+ assert!(state.sender_running);+ assert_eq!(state.next_to_send(), Some(new));+ }++ /// A reconnect invalidates old confirmations: the server may be a fresh+ /// process that never heard the palette we once delivered.+ #[test]+ fn a_reconnect_invalidates_the_confirmation() {+ let mut state = PaletteDelivery::default();+ assert!(state.adopt_target(palette(0.5)));+ let sent = state.next_to_send().unwrap();+ state.record_success(sent);+ assert!(state.next_to_send().is_none());++ state.invalidate_delivery();+ assert!(+ state.adopt_target(palette(0.5)),+ "resync restarts the worker"+ );+ assert_eq!(state.next_to_send(), Some(palette(0.5)));+ }++ #[test]+ fn explicit_no_override_restores_the_configured_palette() {+ let configured = palette(1.0);+ let transition = application_palette_transition(&palette(0.7), &configured, true, None);+ assert_eq!(transition.palette, configured);+ assert!(!transition.application_palette);+ assert!(transition.palette_changed);+ assert!(transition.provenance_changed);+ }++ #[test]+ fn default_gray_is_honored_when_it_is_explicit_application_state() {+ let configured = palette(1.0);+ let gray = ColorPalette::default();+ let transition =+ application_palette_transition(&configured, &configured, false, Some(gray.clone()));+ assert_eq!(transition.palette, gray);+ assert!(transition.application_palette);+ assert!(transition.palette_changed);+ assert!(transition.provenance_changed);+ }++ #[test]+ fn equal_colors_still_preserve_application_provenance_without_repaint() {+ let configured = palette(1.0);+ let transition = application_palette_transition(+ &configured,+ &configured,+ false,+ Some(configured.clone()),+ );+ assert_eq!(transition.palette, configured);+ assert!(transition.application_palette);+ assert!(!transition.palette_changed);+ assert!(transition.provenance_changed);+ }+}diff --git a/thinkterm-session/src/delta_queue.rs b/thinkterm-session/src/delta_queue.rsnew file mode 100644index 00000000..9ec2897f--- /dev/null+++ b/thinkterm-session/src/delta_queue.rs@@ -0,0 +1,139 @@+//! Render pushes for a pane, applied one at a time in the order they+//! came, and what a push that a newer one has overtaken may skip.+use codec::GetPaneRenderChangesResponse;+use std::ops::Range;+use wezterm_term::StableRowIndex;++#[derive(Default)]+pub struct RenderDeltaQueue {+ pending: std::collections::VecDeque<GetPaneRenderChangesResponse>,+ draining: bool,+}++/// The rows named by the pushes still waiting in the queue: as bonus rows,+/// or as dirty ranges the client will fetch on its own.+#[derive(Default)]+pub struct RowsCarried {+ rows: std::collections::HashSet<StableRowIndex>,+ ranges: Vec<Range<StableRowIndex>>,+}++impl RowsCarried {+ pub fn contains(&self, row: StableRowIndex) -> bool {+ self.rows.contains(&row) || self.ranges.iter().any(|range| range.contains(&row))+ }+}++impl RenderDeltaQueue {+ /// Queue `delta`; true when the caller has to start the drain.+ pub fn push(&mut self, delta: GetPaneRenderChangesResponse) -> bool {+ self.pending.push_back(delta);+ !std::mem::replace(&mut self.draining, true)+ }++ /// The next push to apply, with the rows the pushes behind it carry+ /// when there are any, or None once the drain is over.+ pub fn take(&mut self) -> Option<(GetPaneRenderChangesResponse, Option<RowsCarried>)> {+ let delta = match self.pending.pop_front() {+ Some(delta) => delta,+ None => {+ self.draining = false;+ return None;+ }+ };+ if self.pending.is_empty() {+ return Some((delta, None));+ }+ let mut carried = RowsCarried::default();+ for newer in &self.pending {+ carried.rows.extend(newer.bonus_lines.rows());+ carried.ranges.extend(newer.dirty_lines.iter().cloned());+ }+ Some((delta, Some(carried)))+ }++ /// The drain's task ended without reaching the end of the queue (it+ /// was dropped); the next push must start a new one.+ pub fn end_drain(&mut self) {+ self.draining = false;+ }+}++#[cfg(test)]+mod render_delta_queue_tests {+ #[test]+ fn render_pushes_are_taken_in_order_and_know_when_another_waits() {+ let mut queue = super::RenderDeltaQueue::default();+ let delta = |seqno| codec::GetPaneRenderChangesResponse {+ pane_id: 1,+ mouse_grabbed: false,+ alt_screen: false,+ keyboard_encoding: Default::default(),+ cursor_position: Default::default(),+ dimensions: Default::default(),+ dirty_lines: vec![],+ title: String::new(),+ working_dir: None,+ bonus_lines: Vec::new().into(),+ input_serial: None,+ seqno,+ };+ assert!(queue.push(delta(1)), "the first push starts the drain");+ assert!(!queue.push(delta(2)), "the second rides along");+ let (first, carried) = queue.take().unwrap();+ assert_eq!(first.seqno, 1);+ assert!(+ carried.is_some(),+ "so the first is applied without fetching pictures"+ );+ let (second, carried) = queue.take().unwrap();+ assert_eq!(second.seqno, 2);+ assert!(carried.is_none(), "the latest one fetches");+ assert!(queue.take().is_none(), "and the drain ends");+ }++ /// A push applied without pictures leaves rows out; the rows the+ /// pushes behind it name are the ones something else will bring.+ #[test]+ fn a_push_applied_without_pictures_knows_which_rows_the_newer_ones_carry() {+ use termwiz::surface::Line;+ let mut queue = super::RenderDeltaQueue::default();+ let delta =+ |seqno,+ bonus: Vec<wezterm_term::StableRowIndex>,+ dirty: Vec<std::ops::Range<wezterm_term::StableRowIndex>>| {+ codec::GetPaneRenderChangesResponse {+ pane_id: 1,+ mouse_grabbed: false,+ alt_screen: false,+ keyboard_encoding: Default::default(),+ cursor_position: Default::default(),+ dimensions: Default::default(),+ dirty_lines: dirty,+ title: String::new(),+ working_dir: None,+ bonus_lines: bonus+ .into_iter()+ .map(|row| (row, Line::with_width(1, 0)))+ .collect::<Vec<_>>()+ .into(),+ input_serial: None,+ seqno,+ }+ };+ queue.push(delta(1, vec![3, 4], vec![]));+ queue.push(delta(2, vec![4], vec![10..12]));++ queue.push(delta(3, vec![7], vec![]));+ let (_, carried) = queue.take().unwrap();+ let carried = carried.expect("two pushes wait behind the first");+ assert!(carried.contains(4), "a bonus row of a later push");+ assert!(carried.contains(7));+ assert!(carried.contains(11), "a dirty row of a later push");+ assert!(+ !carried.contains(3),+ "row 3 is only in the push being applied: left out, it must be marked dirty"+ );+ assert!(!carried.contains(12), "ranges are half-open");+ }+}diff --git a/thinkterm-session/src/host.rs b/thinkterm-session/src/host.rsnew file mode 100644index 00000000..34ed1666--- /dev/null+++ b/thinkterm-session/src/host.rs@@ -0,0 +1,123 @@+//! What the session needs from whoever hosts it. The desktop client wires+//! these to the mux; a browser client to its page.+use crate::clock::Clock;+use codec::Pdu;+use std::future::Future;+use std::pin::Pin;+use wezterm_term::Alert;++/// A future the session hands the host to run to completion. Not `Send`:+/// the desktop's executor spawns local futures and a browser has one+/// thread.+pub type DetachedFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;++/// Keys the image store: the connection an image came from. The desktop+/// uses its mux domain id; the generation an image carries is a counter+/// private to one server-side object, so pictures from two servers, or+/// one server before and after a restart, must not share a copy.+pub type ImageDomainKey = usize;++/// The request could not be answered.+#[derive(Debug, Clone)]+pub struct LinkError {+ pub message: String,+ /// The link is between connections and the request may be answered+ /// after it comes back; false when nothing will ever answer.+ pub retryable: bool,+}++impl std::fmt::Display for LinkError {+ fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ fmt.write_str(&self.message)+ }+}++impl std::error::Error for LinkError {}++/// Request and answer over whatever the transport is. Message-level, not+/// a byte stream: a browser has framed messages. The future is an+/// associated type so a desktop link can hand out `Send` futures and a+/// browser link local ones, with no `Send` bound written here.+pub trait PduLink {+ type Request: Future<Output = Result<Pdu, LinkError>> + 'static;++ /// Put `pdu` on the wire now, behind everything sent before it; the+ /// future is its answer.+ fn request(&self, pdu: Pdu) -> Self::Request;++ /// A timeout on a reconnectable link is not a dead pane.+ fn is_reconnectable(&self) -> bool;++ /// Bumped whenever the transport is replaced.+ fn connection_generation(&self) -> u64;+}++/// Send `pdu` and take the answer of the expected type. An+/// `ErrorResponse` becomes the error it carries.+pub async fn request<L: PduLink, T>(+ link: &L,+ pdu: Pdu,+ extract: impl FnOnce(Pdu) -> Result<T, Pdu>,+) -> anyhow::Result<T> {+ match link.request(pdu).await {+ Ok(Pdu::ErrorResponse(err)) => anyhow::bail!(err.reason),+ Ok(pdu) => extract(pdu).map_err(|other| anyhow::anyhow!("unexpected response {other:?}")),+ Err(err) => Err(err.into()),+ }+}++/// Runs the session's own detached tasks (line fetches, polls, the+/// render-delta drain).+pub trait Spawner {+ fn spawn_detached(&self, fut: DetachedFuture);+}++/// Everything a pane session takes from its host, in one place.+pub trait SessionHost: 'static {+ type Clock: Clock;+ type Spawner: Spawner;+ type Events: SessionEvents;+ type Link: crate::input::PaneLink;+ type Config: HostConfig;++ fn clock(&self) -> &Self::Clock;+ fn spawner(&self) -> &Self::Spawner;+ fn events(&self) -> &Self::Events;+ fn link(&self) -> &Self::Link;+ fn config(&self) -> &Self::Config;+ fn image_domain(&self) -> ImageDomainKey;+}++/// The host's identity for a pane: what its notifications name. The+/// desktop uses its local mux pane id; a browser client can use anything.+pub type HostPaneId = usize;++/// Settings the host may change while a session runs, read where they are+/// used rather than snapshotted, so a reload takes effect.+pub trait HostConfig {+ /// The rules that turn text into hyperlinks as rows arrive. Read per+ /// push and per fetch, so a host that reloads its settings hands out+ /// the new rules; shared, so that costs an `Arc` clone.+ fn hyperlink_rules(&self) -> std::sync::Arc<Vec<termwiz::hyperlink::Rule>>;+ /// How many line prefetch batches a second the pane may ask for.+ fn fetch_rate_per_second(&self) -> u32;+}++/// Everything the session tells the host about a pane. Synchronous, and+/// never re-entering the session: several of these are called with the+/// pane's lock held, exactly as the desktop's `Mux::notify` was.+pub trait SessionEvents {+ /// The pane's content changed; a paint is due.+ fn pane_output(&self, pane: HostPaneId);+ /// The remote program raised an alert (bell, progress, user var, ...).+ fn alert(&self, pane: HostPaneId, alert: Alert);+ /// The agent status the server tracks for the pane changed.+ fn agent_status_changed(&self, pane: HostPaneId);+ /// The server removed the pane; its mirror is dead.+ fn pane_removed(&self, pane: HostPaneId);+ /// The server moved focus to the pane.+ fn pane_focused(&self, pane: HostPaneId);+ /// The user gave the pane input; the host's own bookkeeping of "who+ /// is typing" goes here.+ fn input_recorded(&self);+}diff --git a/thinkterm-session/src/hydrate.rs b/thinkterm-session/src/hydrate.rsnew file mode 100644index 00000000..30b7de3d--- /dev/null+++ b/thinkterm-session/src/hydrate.rs@@ -0,0 +1,243 @@+//! Attaching the pictures serialized lines name, fetching the ones not+//! held, and keeping a held copy in step with the original.+use crate::host::{request, SessionHost};+use crate::images::{file_image, frame_count, merge_into, ImageStore};+use crate::Lock;+use codec::{GetImageCell, GetImageCellResponse, Pdu, SerializedLines};+use std::collections::HashMap;+use std::sync::Arc;+use termwiz::image::{ImageCell, ImageData};+use thinkterm_proto::PaneId;+use wezterm_term::{Line, StableRowIndex};++/// Attach the images the serialized lines name. With `fetch_images` off,+/// nothing is asked of the server: images already held are attached, and+/// rows whose pictures would have to be fetched are left out, so the row+/// the cache already shows stays -- the previous frame rather than a+/// blank. Used for a push that a newer push has already overtaken. The+/// rows left out are returned with the lines: the caller has to see that+/// something brings them, or they would stay as they were for good, since+/// the push carried them as bonus rows and nothing marks those dirty.+pub async fn hydrate_lines<H: SessionHost>(+ host: &H,+ images: &Lock<ImageStore>,+ pane_id: PaneId,+ serialized_lines: SerializedLines,+ fetch_images: bool,+) -> (Vec<(StableRowIndex, Line)>, Vec<StableRowIndex>) {+ let (mut lines, image_cells) = serialized_lines.extract_data();++ if image_cells.is_empty() {+ return (lines, vec![]);+ }++ let mut requests = HashMap::new();+ let mut data_by_hash = HashMap::new();+ let domain = host.image_domain();+ for im in &image_cells {+ let held = images.lock().get(&(domain, im.data_hash));+ match held {+ // A copy at or past the generation the cell was sent with is+ // current. An animation grows behind an unchanging hash, so+ // the hash alone would say "have it" forever.+ Some(data) if data.generation() >= im.data_generation => {+ data_by_hash.insert(im.data_hash, data);+ }+ held => {+ requests.entry(im.data_hash).or_insert_with(|| {+ let have_frames = held+ .as_ref()+ .map(|data| frame_count(&data.data()))+ .unwrap_or(0);+ (+ held,+ GetImageCell {+ pane_id,+ line_idx: im.line_idx,+ cell_idx: im.cell_idx,+ data_hash: im.data_hash,+ data_generation: im.data_generation,+ have_frames,+ },+ )+ });+ }+ }+ }++ let mut left_out = vec![];+ if !fetch_images && !requests.is_empty() {+ let unfetched: std::collections::HashSet<StableRowIndex> = image_cells+ .iter()+ .filter(|im| requests.contains_key(&im.data_hash))+ .map(|im| im.line_idx)+ .collect();+ lines.retain(|(idx, _)| !unfetched.contains(idx));+ left_out = unfetched.into_iter().collect();+ requests.clear();+ }++ // Concurrently, not one at a time: these are independent round trips, so+ // awaiting them serially cost a line with N distinct images N times the+ // latency.+ let asked: Vec<([u8; 32], Option<Arc<ImageData>>, GetImageCell)> = requests+ .into_iter()+ .map(|(hash, (held, request))| (hash, held, request))+ .collect();+ let fetched = futures_util::future::join_all(+ asked+ .iter()+ .map(|(_, held, request)| fetch_image(host, held.clone(), request.clone())),+ )+ .await;++ for ((asked_for, _, _), data) in asked.into_iter().zip(fetched) {+ let Some(data) = data else { continue };+ let data = file_image(images, domain, data);+ // Filed under the hash the cell named as well: the server may have+ // answered with the picture now in the cell, whose hash differs.+ data_by_hash.insert(asked_for, Arc::clone(&data));+ data_by_hash.insert(data.hash(), data);+ }++ let mut line_by_idx = HashMap::new();+ for (line_idx, line) in lines {+ line_by_idx.insert(line_idx, line);+ }++ for im in image_cells {+ if let Some(data) = data_by_hash.get(&im.data_hash) {+ if let Some(line) = line_by_idx.get_mut(&im.line_idx) {+ if let Some(cell) = line.cells_mut_for_attr_changes_only().get_mut(im.cell_idx) {+ cell.attrs_mut()+ .attach_image(Box::new(ImageCell::with_z_index(+ im.top_left,+ im.bottom_right,+ Arc::clone(data),+ im.z_index,+ im.padding_left,+ im.padding_top,+ im.padding_right,+ im.padding_bottom,+ im.image_id,+ im.placement_id,+ )));+ }+ }+ }+ }++ (line_by_idx.into_iter().collect(), left_out)+}++async fn get_image_cell<H: SessionHost>(+ host: &H,+ req: GetImageCell,+) -> anyhow::Result<GetImageCellResponse> {+ request(host.link(), Pdu::GetImageCell(req), |pdu| match pdu {+ Pdu::GetImageCellResponse(response) => Ok(response),+ other => Err(other),+ })+ .await+}++/// Fetch the image `request` names and bring `held`, the copy already+/// filed under that hash, up to date in place; the Arc to file is returned.+/// A delta the copy cannot take (its leading frames no longer match) is+/// followed by one fetch of the whole image. A copy is never replaced by+/// a fresh Arc: the glyph cache is keyed by hash and holds the copy, so a+/// second Arc under the same hash would leave the painter on the old one+/// for good. A whole image the copy still will not take (it would shrink+/// under a painter) leaves the copy as it is.+async fn fetch_image<H: SessionHost>(+ host: &H,+ held: Option<Arc<ImageData>>,+ request: GetImageCell,+) -> Option<Arc<ImageData>> {+ use crate::clock::Clock;+ let whole = GetImageCell {+ have_frames: 0,+ ..request+ };+ let asked_at = host.clock().now();+ let mut response = get_image_cell(host, request).await;+ if log::log_enabled!(log::Level::Debug) {+ let bytes = match &response {+ Ok(GetImageCellResponse {+ data: Some(data), ..+ }) => data.len(),+ _ => 0,+ };+ log::debug!(+ "image fetch for pane {} took {:?} ({bytes} bytes)",+ whole.pane_id,+ host.clock().now().saturating_duration_since(asked_at)+ );+ }+ let mut asked_for_whole = false;+ loop {+ match response {+ Ok(GetImageCellResponse {+ data: Some(fresh),+ data_generation,+ frames_from,+ ..+ }) => {+ if fresh.hash() != whole.data_hash {+ // Not the picture asked for but the one now in the cell:+ // a newer frame. Its own copy, never merged into the+ // one held for the old hash. It is always sent whole;+ // a tail of it would be frames counted from a copy of+ // some other picture, and adopting it as the whole+ // would leave a truncated animation under its hash.+ if frames_from != 0 {+ log::warn!(+ "the server answered a fetch for one image with part of another; \+ ignoring it"+ );+ return None;+ }+ fresh.set_generation(data_generation);+ return Some(fresh);+ }+ match &held {+ None if frames_from == 0 => {+ fresh.set_generation(data_generation);+ return Some(fresh);+ }+ Some(held) if merge_into(held, &fresh, frames_from, data_generation) => {+ return Some(Arc::clone(held));+ }+ _ => {}+ }+ if !asked_for_whole {+ asked_for_whole = true;+ log::debug!("image delta did not fit the copy held; fetching the whole image");+ response = get_image_cell(host, GetImageCell { ..whole }).await;+ continue;+ }+ // The copy stays, and is marked as current as the server's:+ // left at its old generation, every later push would find+ // it behind and fetch the whole image again, for good.+ log::debug!("the whole image did not fit the copy held either; keeping the copy");+ if let Some(held) = &held {+ held.set_generation(data_generation);+ }+ return held;+ }+ Ok(GetImageCellResponse { data: None, .. }) => {+ // Not an error: the image has been let go of on the server+ // by the time the request lands, which is the ordinary+ // outcome for a pane streaming frames faster than the round+ // trip. This cell renders without it and the next frame+ // supersedes it.+ log::debug!("image cell no longer holds the requested hash");+ return None;+ }+ Err(err) => {+ log::error!("failed to retrieve image {err:#}");+ return None;+ }+ }+ }+}diff --git a/thinkterm-session/src/images.rs b/thinkterm-session/src/images.rsnew file mode 100644index 00000000..249f1b7f--- /dev/null+++ b/thinkterm-session/src/images.rs@@ -0,0 +1,414 @@+//! Keeping a remote pane's copy of an image in step with the original.+//!+//! The server shares one `Arc<ImageData>` between its terminal and every+//! cell that shows the picture, and an animation grows inside it: frames+//! are appended behind the mutex while the hash, which is the picture's+//! identity and the glyph cache's key, stays put. This side holds a copy+//! made from the wire, which nothing grows. So the copy is grown here: a+//! fetch brings the frames the copy lacks, and they are written into the+//! very Arc the cached lines and the glyph cache already point at. The+//! painter then sees the new frames the way it does for a local pane.++use std::sync::Arc;+use termwiz::image::{ImageData, ImageDataType};++/// The animation frames a copy holds: what to tell the server we have.+pub fn frame_count(data: &ImageDataType) -> u32 {+ match data {+ ImageDataType::AnimRgba8 { frames, .. } => frames.len() as u32,+ ImageDataType::Rgba8 { .. } => 1,+ _ => 0,+ }+}++/// Bring `held` up to date from `fetched`, in place. `frames_from` is 0+/// when `fetched` is the whole image, otherwise the index its frames start+/// at, in which case its durations and hashes cover every frame and the+/// hashes of the frames in front must match the ones held.+///+/// False means `fetched` could not be applied: the frames in front no+/// longer match, or the fetch would leave fewer frames than are held --+/// the painter indexes into the frame list by a cursor it keeps, and the+/// list must never shrink under it. `held` and `fetched` are untouched+/// then; the caller fetches the whole image or adopts `fetched` as is.+pub fn merge_into(+ held: &Arc<ImageData>,+ fetched: &Arc<ImageData>,+ frames_from: u32,+ generation: u64,+) -> bool {+ // Both locks, held first. `fetched` is private to this task, so the+ // order cannot cross anyone else's.+ let mut mine = held.data();+ let mut theirs = fetched.data();++ let merged = if frames_from == 0 {+ if frame_count(&theirs) < frame_count(&mine) {+ return false;+ }+ std::mem::replace(&mut *theirs, ImageDataType::EncodedFile(Vec::new()))+ } else {+ let from = frames_from as usize;+ let matches = match (&*theirs, &*mine) {+ (+ ImageDataType::AnimRgba8 {+ frames: tail,+ hashes,+ ..+ },+ ImageDataType::AnimRgba8 {+ hashes: held_hashes,+ ..+ },+ ) => {+ hashes.len() == from + tail.len()+ && held_hashes.len() == from+ && held_hashes[..] == hashes[..from]+ }+ (+ ImageDataType::AnimRgba8 {+ frames: tail,+ hashes,+ ..+ },+ ImageDataType::Rgba8 { hash, .. },+ ) => from == 1 && hashes.len() == 1 + tail.len() && hashes[0] == *hash,+ _ => false,+ };+ if !matches {+ return false;+ }+ // `theirs` is taken apart first; `mine` is emptied last and for+ // the shortest possible stretch, since every cached line and the+ // glyph cache point at it.+ let taken = std::mem::replace(&mut *theirs, ImageDataType::EncodedFile(Vec::new()));+ let ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames: tail,+ hashes,+ } = taken+ else {+ unreachable!("checked above");+ };+ let mut frames = match std::mem::replace(&mut *mine, ImageDataType::EncodedFile(Vec::new()))+ {+ ImageDataType::AnimRgba8 { frames, .. } => frames,+ ImageDataType::Rgba8 { data, .. } => vec![data],+ other => {+ *mine = other;+ return false;+ }+ };+ frames.extend(tail);+ ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames,+ hashes,+ }+ };++ *mine = merged;+ drop(theirs);+ drop(mine);+ held.set_generation(generation);+ true+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::Duration;++ fn still(pixel: u8) -> Arc<ImageData> {+ Arc::new(ImageData::with_data(+ ImageDataType::new_single_frame_content_hashed(1, 1, vec![pixel; 4]),+ ))+ }++ fn frame_hash(pixel: u8) -> [u8; 32] {+ let image = still(pixel);+ let data = image.data();+ match &*data {+ ImageDataType::Rgba8 { hash, .. } => *hash,+ _ => unreachable!(),+ }+ }++ fn anim(pixels: &[u8]) -> ImageDataType {+ ImageDataType::AnimRgba8 {+ width: 1,+ height: 1,+ durations: vec![Duration::from_millis(40); pixels.len()],+ frames: pixels.iter().map(|p| vec![*p; 4]).collect(),+ hashes: pixels.iter().map(|p| frame_hash(*p)).collect(),+ }+ }++ /// A delta as the server builds it: frames from `from` on, every+ /// duration and hash.+ fn delta(pixels: &[u8], from: usize, hash: [u8; 32]) -> Arc<ImageData> {+ let ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames,+ hashes,+ } = anim(pixels)+ else {+ unreachable!()+ };+ Arc::new(ImageData::with_data_and_hash(+ ImageDataType::AnimRgba8 {+ width,+ height,+ durations,+ frames: frames[from..].to_vec(),+ hashes,+ },+ hash,+ ))+ }++ #[test]+ fn appended_frames_grow_the_held_copy_in_place() {+ let held = still(1);+ let hash = held.hash();+ assert!(merge_into(&held, &delta(&[1, 2, 3], 1, hash), 1, 7));+ assert_eq!(frame_count(&held.data()), 3);+ assert_eq!(held.generation(), 7);+ // Then two more frames on top of the three.+ assert!(merge_into(&held, &delta(&[1, 2, 3, 4, 5], 3, hash), 3, 9));+ assert_eq!(frame_count(&held.data()), 5);+ let data = held.data();+ let ImageDataType::AnimRgba8 { frames, hashes, .. } = &*data else {+ panic!("expected an animation, got {:?}", &*data);+ };+ assert_eq!(frames[4], vec![5; 4]);+ assert_eq!(hashes[4], frame_hash(5));+ }++ #[test]+ fn a_delta_whose_leading_frames_differ_is_refused() {+ // The frame in front was edited in place on the server: what we+ // hold is no longer the prefix, so appending would splice a stale+ // frame into a fresh animation.+ let held = still(1);+ let hash = held.hash();+ assert!(!merge_into(&held, &delta(&[9, 2], 1, hash), 1, 3));+ assert_eq!(frame_count(&held.data()), 1, "left alone");+ assert_eq!(held.generation(), 0, "left alone");+ }++ #[test]+ fn a_whole_image_replaces_the_copy_but_never_shrinks_it() {+ let held = still(1);+ let hash = held.hash();+ let whole = Arc::new(ImageData::with_data_and_hash(anim(&[1, 2]), hash));+ assert!(merge_into(&held, &whole, 0, 2));+ assert_eq!(frame_count(&held.data()), 2);++ let shorter = Arc::new(ImageData::with_data_and_hash(anim(&[1]), hash));+ assert!(!merge_into(&held, &shorter, 0, 3));+ assert_eq!(frame_count(&held.data()), 2, "a painter may be on frame 2");+ }+}++/// How much the images fetched from remote panes may hold: a count, and+/// above all bytes. A program streaming full-window pictures gives every+/// frame a new hash, and with the count alone the store held the last+/// hundred-odd frames of it -- half a gigabyte of pixels nothing would+/// show again. A picture larger than the whole budget is kept on its+/// own.+pub const MAX_IMAGES: usize = 128;+pub const MAX_IMAGE_BYTES: usize = 64 * 1024 * 1024;++/// The images fetched from remote panes, by connection and hash, with the+/// size each was last measured at.+pub struct ImageStore {+ images: lru::LruCache<(crate::host::ImageDomainKey, [u8; 32]), (Arc<ImageData>, usize)>,+ bytes: usize,+ max_bytes: usize,+}++impl Default for ImageStore {+ fn default() -> Self {+ Self::new(MAX_IMAGES, MAX_IMAGE_BYTES)+ }+}++impl ImageStore {+ pub fn new(max_images: usize, max_bytes: usize) -> Self {+ Self {+ images: lru::LruCache::new(std::num::NonZeroUsize::new(max_images.max(1)).unwrap()),+ bytes: 0,+ max_bytes,+ }+ }++ pub fn get(&mut self, key: &(crate::host::ImageDomainKey, [u8; 32])) -> Option<Arc<ImageData>> {+ self.images.get(key).map(|(data, _)| Arc::clone(data))+ }++ /// File `data` under `key`, measured now: the same Arc filed again+ /// after it grew is measured again. The least recently used go while+ /// the total is over budget, though never the one just filed.+ pub fn put(&mut self, key: (crate::host::ImageDomainKey, [u8; 32]), data: Arc<ImageData>) {+ if let Some((_, old)) = self.images.pop(&key) {+ self.bytes = self.bytes.saturating_sub(old);+ }+ let size = data.len();+ if let Some((_, (_, evicted))) = self.images.push(key, (data, size)) {+ self.bytes = self.bytes.saturating_sub(evicted);+ }+ self.bytes += size;+ while self.images.len() > 1 && self.bytes > self.max_bytes {+ if let Some((_, (_, size))) = self.images.pop_lru() {+ self.bytes = self.bytes.saturating_sub(size);+ }+ }+ }++ pub fn forget_domain(&mut self, domain: crate::host::ImageDomainKey) {+ let stale: Vec<(crate::host::ImageDomainKey, [u8; 32])> = self+ .images+ .iter()+ .filter(|((held, _), _)| *held == domain)+ .map(|(key, _)| *key)+ .collect();+ for key in stale {+ if let Some((_, size)) = self.images.pop(&key) {+ self.bytes = self.bytes.saturating_sub(size);+ }+ }+ }++ /// Images held and the bytes they were last measured at.+ pub fn footprint(&self) -> (usize, usize) {+ (self.images.len(), self.bytes)+ }+}++/// File `data` under its hash and return the Arc to attach to cells. When+/// a copy is already filed there, that copy is brought up to date from+/// `data` and is the one returned: the glyph cache is keyed by hash and+/// keeps the first Arc it met, so a second Arc under the same hash would+/// leave the painter on the old one, blind to every frame that grows in+/// the new. Two fetches can miss the same hash at once (a row fetch and a+/// push both naming it), and a fetch answered with the picture now in the+/// cell lands under a hash that may well be filed already.+pub fn file_image(+ store: &crate::Lock<ImageStore>,+ domain: crate::host::ImageDomainKey,+ data: Arc<ImageData>,+) -> Arc<ImageData> {+ let key = (domain, data.hash());+ let existing = store.lock().get(&key);+ let filed = match existing {+ Some(existing) if !Arc::ptr_eq(&existing, &data) => {+ if !merge_into(&existing, &data, 0, data.generation()) {+ // The copy holds more than the fetch brought, and is+ // therefore at least as current as it.+ existing.set_generation(existing.generation().max(data.generation()));+ }+ existing+ }+ _ => data,+ };+ // Filed again whichever way: a copy that just grew, in place or by+ // merge, is measured again here.+ store.lock().put(key, Arc::clone(&filed));+ filed+}++#[cfg(test)]+mod store_tests {+ use super::*;++ /// A stream of full-window frames must not pin its last hundred+ /// frames: the store is bounded in bytes, and the newest stays.+ #[test]+ fn the_image_store_lets_old_frames_go_when_over_its_byte_budget() {+ let mut store = ImageStore::new(128, 100);+ let frame = |n: u8| {+ Arc::new(ImageData::with_data(ImageDataType::AnimRgba8 {+ width: 1,+ height: 1,+ durations: vec![std::time::Duration::from_millis(40)],+ frames: vec![vec![n; 40]],+ hashes: vec![[n; 32]],+ }))+ };+ let frames: Vec<Arc<ImageData>> = (1..=5).map(frame).collect();+ for f in &frames {+ store.put((3, f.hash()), Arc::clone(f));+ }+ assert_eq!(store.footprint(), (2, 80), "two of forty fit in a hundred");+ assert!(+ store.get(&(3, frames[4].hash())).is_some(),+ "the newest stays"+ );+ assert!(+ store.get(&(3, frames[0].hash())).is_none(),+ "the oldest went"+ );++ let big = Arc::new(ImageData::with_raw_data(vec![7; 500]));+ store.put((3, big.hash()), Arc::clone(&big));+ assert_eq!(+ store.footprint(),+ (1, 500),+ "a picture over the budget is kept alone"+ );++ store.forget_domain(3);+ assert_eq!(store.footprint(), (0, 0));+ }++ /// The glyph cache keys on the hash and keeps the first Arc it met:+ /// a hash that is already filed keeps its Arc, brought up to date+ /// from what was fetched, whatever the fetch brought.+ #[test]+ fn a_hash_already_filed_keeps_its_arc_and_grows_it() {+ let hash = [77u8; 32];+ let anim = |pixels: &[u8]| ImageDataType::AnimRgba8 {+ width: 1,+ height: 1,+ durations: vec![std::time::Duration::from_millis(40); pixels.len()],+ frames: pixels.iter().map(|p| vec![*p; 4]).collect(),+ hashes: pixels.iter().map(|p| [*p; 32]).collect(),+ };+ let frames = |image: &ImageData| frame_count(&image.data());+ let store = crate::Lock::new(ImageStore::new(128, 1 << 20));+ let domain = 3;++ let first = Arc::new(ImageData::with_data_and_hash(anim(&[1, 2]), hash));+ let filed = file_image(&store, domain, Arc::clone(&first));+ assert!(+ Arc::ptr_eq(&filed, &first),+ "nothing filed yet: this Arc is the one"+ );++ let longer = Arc::new(ImageData::with_data_and_hash(anim(&[1, 2, 3]), hash));+ longer.set_generation(3);+ let filed = file_image(&store, domain, longer);+ assert!(Arc::ptr_eq(&filed, &first), "the Arc already filed is kept");+ assert_eq!(frames(&first), 3, "and holds what the fetch brought");+ assert_eq!(first.generation(), 3);++ let shorter = Arc::new(ImageData::with_data_and_hash(anim(&[1]), hash));+ shorter.set_generation(7);+ let filed = file_image(&store, domain, shorter);+ assert!(Arc::ptr_eq(&filed, &first));+ assert_eq!(frames(&first), 3, "a copy never shrinks under the painter");+ assert_eq!(+ first.generation(),+ 7,+ "but counts as current, or every push would fetch it again"+ );+ assert_eq!(store.lock().footprint().0, 1);+ }+}diff --git a/thinkterm-session/src/input.rs b/thinkterm-session/src/input.rsnew file mode 100644index 00000000..5d1979bc--- /dev/null+++ b/thinkterm-session/src/input.rs@@ -0,0 +1,595 @@+//! Input for a remote pane: one ordered queue per pane, drained onto the+//! wire in the order the user gave it, each request sent the moment the+//! one before it is on the wire.+use crate::host::{LinkError, PduLink};+use crate::Lock;+use codec::{+ EraseScrollbackRequest, InputSerial, Pdu, SendKeyDown, SendMouseEvent, SendPaste, WriteToPane,+};+use futures_util::stream::{FuturesUnordered, StreamExt};+use std::collections::VecDeque;+use std::future::Future;+use std::pin::Pin;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use termwiz::input::KeyEvent;+use thinkterm_proto::{PaneId, ScrollbackEraseMode, TabId};+use wezterm_term::MouseEvent;++/// A boxed future for a link whose futures are `Send` (the desktop).+pub type SendFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;+/// A boxed future for a link whose futures are not (a browser).+pub type LocalFuture<T> = Pin<Box<dyn Future<Output = T> + 'static>>;++/// One thing the user gave a remote pane.+///+/// Keys, pastes and mouse reports travel as their own requests; the pty+/// bytes the GUI encodes itself (kitty-protocol and win32-input-mode keys,+/// text from the input method, SendString) go as WriteToPane. The four+/// used to leave by separate paths, and the byte path waited for each+/// answer before sending more, so a key pressed while a write was still+/// unanswered overtook the text queued behind that write: Enter before+/// the sentence it was meant to end. Everything now goes through one+/// queue per pane, in the order it was given.+pub enum PaneInput {+ Bytes(Vec<u8>),+ Key {+ event: KeyEvent,+ input_serial: InputSerial,+ },+ Paste(String),+ Mouse(MouseEvent),+ EraseScrollback(ScrollbackEraseMode),+}++/// What an input weighs against `INPUT_QUEUE_LIMIT` when it is all+/// bookkeeping.+pub const INPUT_ITEM_FLOOR: usize = 64;++impl PaneInput {+ pub fn weight(&self) -> usize {+ match self {+ PaneInput::Bytes(data) => data.len().max(INPUT_ITEM_FLOOR),+ PaneInput::Paste(text) => text.len().max(INPUT_ITEM_FLOOR),+ PaneInput::Key { .. } | PaneInput::Mouse(_) | PaneInput::EraseScrollback(_) => {+ INPUT_ITEM_FLOOR+ }+ }+ }++ pub fn describe(&self) -> String {+ match self {+ PaneInput::Bytes(data) => format!("{} bytes", data.len()),+ PaneInput::Key { .. } => "a key".to_string(),+ PaneInput::Paste(text) => format!("a paste of {} bytes", text.len()),+ PaneInput::Mouse(_) => "a mouse report".to_string(),+ PaneInput::EraseScrollback(_) => "a scrollback erase".to_string(),+ }+ }++ /// Fold `next` into this one when the two can travel as a single+ /// request: bytes after bytes, a mouse report over the one before it.+ /// Nothing folds across a key or a paste, so the order the user gave+ /// is the order the pty sees. Hands `next` back when it has to stay+ /// its own request.+ pub fn absorb(&mut self, next: PaneInput) -> Option<PaneInput> {+ match (self, next) {+ (PaneInput::Bytes(data), PaneInput::Bytes(more)) => {+ data.extend_from_slice(&more);+ None+ }+ (PaneInput::Mouse(last), PaneInput::Mouse(event)) => {+ crate::mouse::coalesce(last, event).map(PaneInput::Mouse)+ }+ (_, next) => Some(next),+ }+ }++ pub fn into_pdu(self, pane_id: PaneId) -> Pdu {+ match self {+ PaneInput::Bytes(data) => Pdu::WriteToPane(WriteToPane { pane_id, data }),+ PaneInput::Key {+ event,+ input_serial,+ } => Pdu::SendKeyDown(SendKeyDown {+ pane_id,+ event,+ input_serial,+ }),+ PaneInput::Paste(data) => Pdu::SendPaste(SendPaste { pane_id, data }),+ PaneInput::Mouse(event) => Pdu::SendMouseEvent(SendMouseEvent { pane_id, event }),+ PaneInput::EraseScrollback(erase_mode) => {+ Pdu::EraseScrollbackRequest(EraseScrollbackRequest {+ pane_id,+ erase_mode,+ })+ }+ }+ }+}++/// Input for a remote pane the server has not answered: what waits to be+/// sent, and how much is on the wire.+#[derive(Default)]+pub struct InputQueue {+ pending: VecDeque<PaneInput>,+ /// The weight of `pending`.+ queued: usize,+ /// The weight sent and not yet answered.+ in_flight: usize,+ draining: bool,+}++/// How much input may wait for the link, queued or sent and unanswered,+/// before more is refused: a paste, not a runaway.+const INPUT_QUEUE_LIMIT: usize = 4 * 1024 * 1024;++/// The queue is full: the link has answered nothing for a while and+/// `INPUT_QUEUE_LIMIT` bytes of input already wait for it.+#[derive(Debug)]+pub struct InputQueueFull {+ waiting: usize,+}++impl std::fmt::Display for InputQueueFull {+ fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ fmt,+ "{} bytes of input are already waiting for the link to the remote pane",+ self.waiting+ )+ }+}++impl std::error::Error for InputQueueFull {}++impl InputQueue {+ /// Queue `input` behind what already waits; true when the caller has+ /// to start the drain. Over the limit the input is refused rather than+ /// dropped and reported as sent: the caller is told, and what reaches+ /// the remote pane is either all of an input or none of it.+ pub fn push(&mut self, input: PaneInput) -> Result<bool, InputQueueFull> {+ let waiting = self.queued + self.in_flight;+ if waiting + input.weight() > INPUT_QUEUE_LIMIT {+ return Err(InputQueueFull { waiting });+ }+ let input = match self.pending.back_mut() {+ Some(last) => {+ let before = last.weight();+ let left = last.absorb(input);+ self.queued = self.queued - before + last.weight();+ left+ }+ None => Some(input),+ };+ if let Some(input) = input {+ self.queued += input.weight();+ self.pending.push_back(input);+ }+ Ok(!std::mem::replace(&mut self.draining, true))+ }++ /// The next input to send, counted as in flight from here on, or None+ /// once nothing waits: the drain is over and the next push starts a+ /// new one. The check and the hand-back happen under the one lock, so+ /// no push can slip between them and find the queue neither drained+ /// nor draining.+ pub fn take(&mut self) -> Option<PaneInput> {+ match self.pending.pop_front() {+ Some(input) => {+ let weight = input.weight();+ self.queued -= weight;+ self.in_flight += weight;+ Some(input)+ }+ None => {+ self.draining = false;+ None+ }+ }+ }++ /// `weight` of input was answered, or never went: it no longer waits.+ pub fn settle(&mut self, weight: usize) {+ self.in_flight = self.in_flight.saturating_sub(weight);+ }+}++/// Marks the drain over if its task ends before it reaches the end of the+/// queue (a panic caught by the executor, a scheduler torn down with it+/// queued); every later input would otherwise wait for a drain that never+/// comes. A drain that did reach the end handed the queue back itself and+/// disarms this, so it cannot undo a drain the next push already started.+struct InputDraining {+ queue: Arc<Lock<InputQueue>>,+ done: bool,+}++impl Drop for InputDraining {+ fn drop(&mut self) {+ if !self.done {+ self.queue.lock().draining = false;+ }+ }+}++/// Settles an input's weight when its answer arrives, or when the answer+/// is given up on: dropped with the future, it settles all the same.+struct Settling {+ queue: Arc<Lock<InputQueue>>,+ weight: usize,+}++impl Drop for Settling {+ fn drop(&mut self) {+ self.queue.lock().settle(self.weight);+ }+}++/// The wire as the input drain needs it: `PduLink` plus the per-tab gate.+/// The future is an associated type so a desktop link can hand out `Send`+/// futures and a browser link local ones, with no `Send` bound written+/// here (see `SendFuture` and `LocalFuture`).+pub trait PaneLink: PduLink {+ type Prepare: Future<Output = anyhow::Result<bool>> + 'static;++ /// Whether this client may drive the tab right now; a claim may have+ /// to reach the server first.+ fn prepare(&self, remote_tab_id: TabId) -> Self::Prepare;+}++/// Sends the pane's queued input in order, each request the moment the+/// one before it is on the wire, then waits for the answers. No request+/// waits for an answer before the next is sent: the wire keeps the order,+/// and the server applies one connection's input to a pane in the order+/// it arrives. The answers only settle what counts against+/// `INPUT_QUEUE_LIMIT`, so a stalled link ends in refused input, not in+/// input sent out of order.+pub async fn drain_pane_inputs<L: PaneLink>(+ link: &L,+ remote_pane_id: PaneId,+ remote_tab_id: Arc<AtomicUsize>,+ queue: Arc<Lock<InputQueue>>,+) {+ let mut answers = FuturesUnordered::new();+ let mut draining = InputDraining {+ queue: Arc::clone(&queue),+ done: false,+ };+ loop {+ let Some(input) = queue.lock().take() else {+ draining.done = true;+ break;+ };+ let what = input.describe();+ let settling = Settling {+ queue: Arc::clone(&queue),+ weight: input.weight(),+ };+ let remote_tab_id = remote_tab_id.load(Ordering::Relaxed);+ match link.prepare(remote_tab_id).await {+ Ok(true) => {}+ Ok(false) => {+ log::warn!(+ "dropping {what} for remote pane {remote_pane_id}: this client may \+ not drive the tab right now"+ );+ continue;+ }+ Err(err) => {+ log::error!("dropping {what} for remote pane {remote_pane_id}: {err:#}");+ continue;+ }+ }+ let answer = link.request(input.into_pdu(remote_pane_id));+ answers.push(async move {+ let _settling = settling;+ if let Err(err) = answered(answer.await) {+ log::error!("sending {what} to remote pane {remote_pane_id}: {err:#}");+ }+ });+ }+ drop(draining);+ while answers.next().await.is_some() {}+}++/// Queue `input` behind everything given before it; true when the caller+/// has to start the drain.+pub fn push_input(queue: &Lock<InputQueue>, input: PaneInput) -> Result<bool, InputQueueFull> {+ queue.lock().push(input)+}++fn answered(answer: Result<Pdu, LinkError>) -> anyhow::Result<()> {+ match answer? {+ Pdu::UnitResponse(_) => Ok(()),+ Pdu::ErrorResponse(err) => anyhow::bail!(err.reason),+ other => anyhow::bail!("unexpected response {other:?}"),+ }+}++#[cfg(test)]+mod input_queue_tests {+ use super::*;+ use codec::UnitResponse;+ use std::sync::atomic::AtomicBool;+ use wezterm_term::{KeyCode, KeyModifiers, MouseButton, MouseEventKind};++ fn bytes(text: &str) -> PaneInput {+ PaneInput::Bytes(text.as_bytes().to_vec())+ }++ fn enter() -> PaneInput {+ PaneInput::Key {+ event: KeyEvent {+ key: KeyCode::Enter,+ modifiers: KeyModifiers::NONE,+ },+ input_serial: InputSerial::empty(),+ }+ }++ fn mouse(kind: MouseEventKind, button: MouseButton, x: usize) -> PaneInput {+ PaneInput::Mouse(MouseEvent {+ kind,+ x,+ y: 0,+ x_pixel_offset: 0,+ y_pixel_offset: 0,+ button,+ modifiers: KeyModifiers::NONE,+ })+ }++ fn tag(input: &PaneInput) -> String {+ match input {+ PaneInput::Bytes(data) => format!("bytes:{}", String::from_utf8_lossy(data)),+ PaneInput::Key { .. } => "key".to_string(),+ PaneInput::Paste(text) => format!("paste:{text}"),+ PaneInput::EraseScrollback(_) => "erase".to_string(),+ PaneInput::Mouse(event) => match (&event.kind, &event.button) {+ (MouseEventKind::Move, _) => format!("mouse:move@{}", event.x),+ (_, MouseButton::WheelDown(n)) => format!("mouse:wheeldown{n}"),+ _ => "mouse".to_string(),+ },+ }+ }++ fn pdu_tag(pdu: &Pdu) -> String {+ match pdu {+ Pdu::WriteToPane(write) => {+ format!("bytes:{}", String::from_utf8_lossy(&write.data))+ }+ Pdu::SendKeyDown(_) => "key".to_string(),+ Pdu::SendPaste(paste) => format!("paste:{}", paste.data),+ Pdu::SendMouseEvent(_) => "mouse".to_string(),+ other => format!("{other:?}"),+ }+ }++ /// A link that records what went on the wire and answers only when+ /// the test says so.+ #[derive(Default)]+ struct RecordingLink {+ wire: Lock<Vec<String>>,+ answers: Lock<Vec<async_channel::Sender<Result<Pdu, LinkError>>>>,+ refuse: AtomicBool,+ }++ impl RecordingLink {+ fn answer_everything(&self) {+ for answer in self.answers.lock().drain(..) {+ answer+ .try_send(Ok(Pdu::UnitResponse(UnitResponse {})))+ .unwrap();+ }+ }+ }++ impl PduLink for RecordingLink {+ type Request = LocalFuture<Result<Pdu, LinkError>>;++ fn request(&self, pdu: Pdu) -> Self::Request {+ self.wire.lock().push(pdu_tag(&pdu));+ let (tx, rx) = async_channel::bounded(1);+ self.answers.lock().push(tx);+ Box::pin(async move {+ rx.recv().await.map_err(|_| LinkError {+ message: "the answer was dropped".into(),+ retryable: false,+ })?+ })+ }++ fn is_reconnectable(&self) -> bool {+ false+ }++ fn connection_generation(&self) -> u64 {+ 1+ }+ }++ impl PaneLink for RecordingLink {+ type Prepare = LocalFuture<anyhow::Result<bool>>;++ fn prepare(&self, _remote_tab_id: TabId) -> Self::Prepare {+ let allowed = !self.refuse.load(Ordering::SeqCst);+ Box::pin(async move { Ok(allowed) })+ }+ }++ /// The scenario that was wrong: text from the input method is on the+ /// wire and unanswered, more text arrives, then Enter. Enter must leave+ /// after that text, and nothing may wait for the first answer.+ #[test]+ fn enter_leaves_behind_the_text_queued_before_it_without_waiting_for_an_answer() {+ let link = Arc::new(RecordingLink::default());+ let queue: Arc<Lock<InputQueue>> = Default::default();+ let tab = Arc::new(AtomicUsize::new(0));+ let ex = async_executor::LocalExecutor::new();+ let drain = || {+ ex.spawn(drain_pane_inputs(+ &*link,+ 7,+ Arc::clone(&tab),+ Arc::clone(&queue),+ ))+ };++ assert!(queue.lock().push(bytes("ni")).unwrap());+ let first = drain();+ while ex.try_tick() {}+ assert_eq!(*link.wire.lock(), ["bytes:ni"], "sent at once");+ assert_eq!(queue.lock().in_flight, INPUT_ITEM_FLOOR, "and unanswered");+ assert!(+ !queue.lock().draining,+ "an unanswered request does not hold the drain"+ );++ assert!(+ queue.lock().push(bytes("hao")).unwrap(),+ "a new drain starts"+ );+ assert!(+ !queue.lock().push(enter()).unwrap(),+ "and Enter rides along"+ );+ let second = drain();+ while ex.try_tick() {}+ assert_eq!(+ *link.wire.lock(),+ ["bytes:ni", "bytes:hao", "key"],+ "Enter left after the text, while ni is still unanswered"+ );+ assert_eq!(queue.lock().in_flight, 3 * INPUT_ITEM_FLOOR);++ link.answer_everything();+ futures_lite::future::block_on(ex.run(async {+ first.await;+ second.await;+ }));+ assert_eq!(queue.lock().in_flight, 0, "every answer settled its input");+ }++ #[test]+ fn input_this_client_may_not_send_is_dropped_and_settled() {+ let link = Arc::new(RecordingLink::default());+ link.refuse.store(true, Ordering::SeqCst);+ let queue: Arc<Lock<InputQueue>> = Default::default();+ assert!(queue.lock().push(enter()).unwrap());+ let ex = async_executor::LocalExecutor::new();+ futures_lite::future::block_on(ex.run(drain_pane_inputs(+ &*link,+ 7,+ Arc::new(AtomicUsize::new(0)),+ Arc::clone(&queue),+ )));+ assert!(link.wire.lock().is_empty(), "nothing went");+ let queue = queue.lock();+ assert_eq!(queue.in_flight, 0, "and nothing is counted as waiting");+ assert!(!queue.draining, "the drain is over");+ }++ #[test]+ fn only_neighbours_of_the_same_kind_travel_together() {+ let mut queue = InputQueue::default();+ queue.push(bytes("a")).unwrap();+ queue.push(bytes("b")).unwrap();+ queue.push(enter()).unwrap();+ queue.push(bytes("c")).unwrap();+ queue+ .push(mouse(MouseEventKind::Move, MouseButton::None, 1))+ .unwrap();+ queue+ .push(mouse(MouseEventKind::Move, MouseButton::None, 2))+ .unwrap();+ queue.push(PaneInput::Paste("p".to_string())).unwrap();+ queue+ .push(mouse(MouseEventKind::Press, MouseButton::WheelDown(3), 0))+ .unwrap();+ queue+ .push(mouse(MouseEventKind::Press, MouseButton::WheelDown(1), 0))+ .unwrap();+ assert_eq!(+ queue.queued,+ queue.pending.iter().map(PaneInput::weight).sum::<usize>(),+ "folding keeps the account right"+ );+ let sent: Vec<String> = std::iter::from_fn(|| queue.take())+ .map(|input| tag(&input))+ .collect();+ assert_eq!(+ sent,+ [+ "bytes:ab",+ "key",+ "bytes:c",+ "mouse:move@2",+ "paste:p",+ "mouse:wheeldown4"+ ]+ );+ }++ #[test]+ fn input_on_the_wire_counts_until_it_is_answered() {+ let mut queue = InputQueue::default();+ assert!(+ queue+ .push(PaneInput::Bytes(vec![b'x'; INPUT_QUEUE_LIMIT]))+ .is_ok(),+ "the limit itself fits"+ );+ let refused = queue+ .push(enter())+ .expect_err("a key on top of it does not");+ assert_eq!(refused.waiting, INPUT_QUEUE_LIMIT);+ assert_eq!(+ queue.take().map(|input| input.weight()),+ Some(INPUT_QUEUE_LIMIT),+ "what was queued is intact; the refused key is not in it"+ );+ assert!(+ queue.push(enter()).is_err(),+ "on the wire and unanswered, it still counts"+ );+ queue.settle(INPUT_QUEUE_LIMIT);+ assert!(queue.push(enter()).is_ok(), "answered, it makes room");+ }++ #[test]+ fn a_drain_that_ends_early_gives_the_queue_back() {+ let queue: Arc<Lock<InputQueue>> = Default::default();+ assert!(queue.lock().push(bytes("a")).unwrap());+ drop(InputDraining {+ queue: Arc::clone(&queue),+ done: false,+ });+ assert!(!queue.lock().draining, "the slot is free again");+ assert_eq!(+ tag(&queue.lock().take().unwrap()),+ "bytes:a",+ "and the bytes still wait for the next drain"+ );+ }++ #[test]+ fn a_drain_that_reached_the_end_does_not_undo_the_next_one() {+ let queue: Arc<Lock<InputQueue>> = Default::default();+ assert!(queue.lock().push(bytes("a")).unwrap());+ assert!(queue.lock().take().is_some());+ assert!(queue.lock().take().is_none(), "handed back under the lock");+ assert!(+ queue.lock().push(bytes("b")).unwrap(),+ "the next push starts a new drain"+ );+ drop(InputDraining {+ queue: Arc::clone(&queue),+ done: true,+ });+ assert!(+ queue.lock().draining,+ "the finished drain's guard is disarmed"+ );+ }+}diff --git a/thinkterm-session/src/lib.rs b/thinkterm-session/src/lib.rsnew file mode 100644index 00000000..119ee355--- /dev/null+++ b/thinkterm-session/src/lib.rs@@ -0,0 +1,123 @@+//! The mux client session layer, shared by every ThinkTerm client.+//!+//! Everything here runs on `wasm32-unknown-unknown`: the host supplies time+//! (`Clock`), task spawning (`Spawner`), the wire (`PduLink`) and the event+//! sink (`SessionEvents`); nothing in this crate reaches a process, a file,+//! a socket, a thread or a system clock directly.++pub mod clock;+pub mod connection;+pub mod decide;+pub mod delta_queue;+pub mod host;+pub mod hydrate;+pub mod images;+pub mod input;+pub mod lines;+pub mod mouse;+pub mod pane;+pub mod pane_state;++/// What a pane's session is told once, at construction. Everything a+/// host may change at run time is asked for through `host::HostConfig`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct SessionConfig {+ /// How many rows the line cache holds (at least 128 are kept).+ pub scrollback_lines: usize,+ /// Predict the echo of typed keys once the measured input round trip+ /// reaches this many milliseconds; `None` never predicts.+ pub local_echo_threshold_ms: Option<u64>,+ /// Paint a "since last response" overlay on a tardy pane.+ pub overlay_lag_indicator: bool,+}++/// A mutex that does not poison. The session holds its locks for a few+/// statements and never across an await; a panic inside one must not turn+/// every later lock into a panic too (which `std::sync::Mutex` would).+///+/// Some host callbacks run with a session lock held (a `pane_output` from+/// inside a delta), so a host that re-enters the session from one would+/// deadlock. Debug builds catch that loudly instead: the thread holding+/// the lock is remembered and a second `lock()` from it panics.+#[derive(Default)]+pub struct Lock<T> {+ inner: std::sync::Mutex<T>,+ #[cfg(debug_assertions)]+ holder: std::sync::Mutex<Option<std::thread::ThreadId>>,+}++/// The guard, releasing the re-entrancy record with the lock.+pub struct LockGuard<'a, T> {+ guard: Option<std::sync::MutexGuard<'a, T>>,+ #[cfg(debug_assertions)]+ holder: &'a std::sync::Mutex<Option<std::thread::ThreadId>>,+}++impl<T> Lock<T> {+ pub fn new(value: T) -> Self {+ Self {+ inner: std::sync::Mutex::new(value),+ #[cfg(debug_assertions)]+ holder: std::sync::Mutex::new(None),+ }+ }++ pub fn lock(&self) -> LockGuard<'_, T> {+ #[cfg(debug_assertions)]+ {+ let me = std::thread::current().id();+ let holder = self.holder.lock().unwrap_or_else(|p| p.into_inner());+ if *holder == Some(me) {+ panic!("the session lock was re-entered from a host callback");+ }+ }+ let guard = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ #[cfg(debug_assertions)]+ {+ *self.holder.lock().unwrap_or_else(|p| p.into_inner()) =+ Some(std::thread::current().id());+ }+ LockGuard {+ guard: Some(guard),+ #[cfg(debug_assertions)]+ holder: &self.holder,+ }+ }+}++impl<T> std::ops::Deref for LockGuard<'_, T> {+ type Target = T;+ fn deref(&self) -> &T {+ self.guard.as_ref().expect("guard is held until drop")+ }+}++impl<T> std::ops::DerefMut for LockGuard<'_, T> {+ fn deref_mut(&mut self) -> &mut T {+ self.guard.as_mut().expect("guard is held until drop")+ }+}++impl<T> Drop for LockGuard<'_, T> {+ fn drop(&mut self) {+ #[cfg(debug_assertions)]+ {+ *self.holder.lock().unwrap_or_else(|p| p.into_inner()) = None;+ }+ self.guard.take();+ }+}++impl<T: std::fmt::Debug> std::fmt::Debug for Lock<T> {+ fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ // try_lock, never lock: formatting a lock from under itself must+ // not hang.+ match self.inner.try_lock() {+ Ok(guard) => fmt.debug_tuple("Lock").field(&*guard).finish(),+ Err(_) => fmt.write_str("Lock(<held>)"),+ }+ }+}diff --git a/thinkterm-session/src/lines.rs b/thinkterm-session/src/lines.rsnew file mode 100644index 00000000..f4f922eb--- /dev/null+++ b/thinkterm-session/src/lines.rs@@ -0,0 +1,577 @@+//! The per-pane line cache and its fetch bookkeeping: which rows are+//! current, which are on their way, when a fetch or a poll has stalled,+//! and how a cached row survives a resize. Pure over `Timestamp`.+use crate::clock::Timestamp;+use lru::LruCache;+use rangeset::RangeSet;+use std::ops::Range;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::Duration;+use thinkterm_proto::RenderableDimensions;+use wezterm_term::{Line, StableRowIndex};++// 30s, not shorter: poll is a fallback, and every poll costs the server a+// full-scrollback get_changed_since scan under the terminal lock, per+// painted mirror pane. Stall recovery is the watchdog's job — it resets+// the interval to BASE the moment a pane looks stuck.+pub const MAX_POLL_INTERVAL: Duration = Duration::from_secs(30);+pub const BASE_POLL_INTERVAL: Duration = Duration::from_millis(20);+pub const FETCH_STALL_BASE: Duration = Duration::from_secs(30);+pub const POLL_STALL_BASE: Duration = Duration::from_secs(15);++pub fn stall_timeout(base: Duration, attempt: u32) -> Duration {+ let multiplier = 1u32.checked_shl(attempt).unwrap_or(u32::MAX);+ base.checked_mul(multiplier).unwrap_or(Duration::MAX)+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct FetchToken {+ pub epoch: u64,+ pub started_at: Timestamp,+ pub stall_attempt: u32,+}++impl FetchToken {+ pub fn new(epoch: u64, started_at: Timestamp) -> Self {+ Self {+ epoch,+ started_at,+ stall_attempt: 0,+ }+ }++ pub fn retry(self, started_at: Timestamp) -> Self {+ Self {+ epoch: self.epoch,+ started_at,+ stall_attempt: self.stall_attempt.saturating_add(1),+ }+ }+}++pub fn fetch_should_be_retried(token: FetchToken, now: Timestamp) -> bool {+ now.saturating_duration_since(token.started_at)+ > stall_timeout(FETCH_STALL_BASE, token.stall_attempt)+}++pub fn poll_should_be_retried(started_at: Timestamp, attempt: u32, now: Timestamp) -> bool {+ now.saturating_duration_since(started_at) > stall_timeout(POLL_STALL_BASE, attempt)+}++pub fn claim_poll_completion(in_flight: &AtomicU64, generation: u64) -> bool {+ in_flight+ .compare_exchange(generation, 0, Ordering::SeqCst, Ordering::SeqCst)+ .is_ok()+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct FrontendPreviewGeometry {+ pub epoch: u64,+ pub size: wezterm_term::TerminalSize,+ pub policy: FrontendPreviewPolicy,+}++/// How an optimistic frontend geometry should treat rows that were fetched for+/// the preceding grid. Takeover previews are hidden by an opaque frontend+/// surface, while a live divider resize is visible and must never expose a row+/// whose cell storage still has the old width.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FrontendPreviewPolicy {+ PreserveRows,+ LiveResize,+}++#[derive(Debug)]+pub enum LineEntry {+ // Up to date wrt. server and has been rendered at least once+ Line(Line),+ // Currently being downloaded from the server+ Fetching(FetchToken),+ // We have a version of the line locally and are treating it+ // as needing rendering because we are also in the process of+ // downloading a newer version from the server+ LineAndFetching(Line, FetchToken),+ // We have a local copy but it is stale and will need to be+ // fetched again+ Stale(Line),+}++#[derive(Debug)]+pub struct FetchRetryBatch {+ pub token: FetchToken,+ pub rows: RangeSet<StableRowIndex>,+}++#[derive(Debug, Default)]+pub struct LineWatchdogDecision {+ pub repaint: bool,+ pub retries: Vec<FetchRetryBatch>,+}++impl LineWatchdogDecision {+ pub fn retry(&mut self, row: StableRowIndex, token: FetchToken) {+ self.repaint = true;+ if let Some(batch) = self.retries.iter_mut().find(|batch| batch.token == token) {+ batch.rows.add(row);+ return;+ }+ let mut rows = RangeSet::new();+ rows.add(row);+ self.retries.push(FetchRetryBatch { token, rows });+ }+}++pub fn line_watchdog_decision(+ lines: &mut LruCache<StableRowIndex, LineEntry>,+ range: Range<StableRowIndex>,+ now: Timestamp,+) -> LineWatchdogDecision {+ let mut decision = LineWatchdogDecision::default();+ for row in range {+ let entry = match lines.pop(&row) {+ Some(LineEntry::Stale(line)) => {+ decision.repaint = true;+ LineEntry::Stale(line)+ }+ Some(LineEntry::Fetching(token)) => {+ if fetch_should_be_retried(token, now) {+ let replacement = token.retry(now);+ decision.retry(row, replacement);+ LineEntry::Fetching(replacement)+ } else {+ LineEntry::Fetching(token)+ }+ }+ Some(LineEntry::LineAndFetching(line, token)) => {+ if fetch_should_be_retried(token, now) {+ let replacement = token.retry(now);+ decision.retry(row, replacement);+ LineEntry::LineAndFetching(line, replacement)+ } else {+ LineEntry::LineAndFetching(line, token)+ }+ }+ Some(entry) => entry,+ None => {+ decision.repaint = true;+ continue;+ }+ };+ lines.put(row, entry);+ }+ decision+}++impl LineEntry {+ pub fn kind(&self) -> (&'static str, Option<FetchToken>) {+ match self {+ Self::Line(_) => ("Line", None),+ Self::Fetching(token) => ("Fetching", Some(*token)),+ Self::LineAndFetching(_, token) => ("LineAndFetching", Some(*token)),+ Self::Stale(_) => ("Stale", None),+ }+ }+}++pub fn invalidate_line_entries(+ lines: &mut LruCache<StableRowIndex, LineEntry>,+ preserve_lines: bool,+) {+ if !preserve_lines {+ lines.clear();+ return;+ }++ // Keep the original bound: an unbounded rebuild left the cache free to+ // grow with every fetched line for the rest of the pane's life.+ let mut stale = LruCache::new(lines.cap());+ while let Some((stable_row, entry)) = lines.pop_lru() {+ match entry {+ LineEntry::Stale(line)+ | LineEntry::Line(line)+ | LineEntry::LineAndFetching(line, _) => {+ stale.put(stable_row, LineEntry::Stale(line));+ }+ LineEntry::Fetching(_) => {}+ }+ }+ *lines = stale;+}++/// Keep a stable visual fallback while a visible divider is moving, but make+/// every retained row structurally valid for the new grid before it can be+/// painted. Cropping/padding a prior complete row is preferable to either a+/// blank flash or mixing old-width storage with newly fetched cells.+pub fn resize_stale_line_entries(lines: &mut LruCache<StableRowIndex, LineEntry>, cols: usize) {+ let mut stale = LruCache::new(lines.cap());+ while let Some((stable_row, entry)) = lines.pop_lru() {+ let line = match entry {+ LineEntry::Stale(line)+ | LineEntry::Line(line)+ | LineEntry::LineAndFetching(line, _) => line,+ LineEntry::Fetching(_) => continue,+ };+ let seqno = line.current_seqno();+ let mut line = line;+ line.resize(cols, seqno);+ line.set_last_cell_was_wrapped(false, seqno);+ stale.put(stable_row, LineEntry::Stale(line));+ }+ *lines = stale;+}++pub fn render_geometry_changed(current: RenderableDimensions, next: RenderableDimensions) -> bool {+ current.cols != next.cols+ || current.viewport_rows != next.viewport_rows+ || current.pixel_width != next.pixel_width+ || current.pixel_height != next.pixel_height+ || current.dpi != next.dpi+}++pub fn render_dimensions_match_terminal_size(+ dimensions: RenderableDimensions,+ size: wezterm_term::TerminalSize,+) -> bool {+ dimensions.cols == size.cols+ && dimensions.viewport_rows == size.rows+ && dimensions.pixel_width == size.pixel_width+ && dimensions.pixel_height == size.pixel_height+ && dimensions.dpi == size.dpi+}++pub fn confirmed_frontend_visible_range(+ dimensions: RenderableDimensions,+ size: wezterm_term::TerminalSize,+) -> Option<Range<StableRowIndex>> {+ if !render_dimensions_match_terminal_size(dimensions, size) {+ return None;+ }+ let top = dimensions.physical_top;+ Some(top..top.saturating_add(size.rows as StableRowIndex))+}++pub fn release_unreturned_fetches(+ lines: &mut LruCache<StableRowIndex, LineEntry>,+ requested: &RangeSet<StableRowIndex>,+ returned: &RangeSet<StableRowIndex>,+ fetch_token: FetchToken,+) {+ for range in requested.iter() {+ for row in range.clone() {+ if returned.contains(row) {+ continue;+ }+ match lines.pop(&row) {+ Some(LineEntry::Fetching(token)) if token == fetch_token => {}+ Some(LineEntry::LineAndFetching(line, token)) if token == fetch_token => {+ lines.put(row, LineEntry::Stale(line));+ }+ Some(entry) => {+ lines.put(row, entry);+ }+ None => {}+ }+ }+ }+}++pub fn resolve_server_geometry(+ visible: RenderableDimensions,+ previous_server: RenderableDimensions,+ next_server: RenderableDimensions,+ preview_active: bool,+) -> (RenderableDimensions, Option<bool>) {+ if preview_active {+ let invalidation = render_geometry_changed(previous_server, next_server).then_some(true);+ (visible, invalidation)+ } else if render_geometry_changed(visible, next_server) {+ (next_server, Some(visible.cols == next_server.cols))+ } else {+ (next_server, None)+ }+}++pub fn fetch_token_is_current(token: FetchToken, epoch: u64) -> bool {+ token.epoch == epoch+}++#[cfg(test)]+mod test {+ use super::*;+ use std::num::NonZeroUsize;+ use termwiz::surface::SEQ_ZERO;++ fn line(width: usize) -> Line {+ Line::with_width(width, SEQ_ZERO)+ }++ fn dimensions(cols: usize, rows: usize, dpi: u32) -> RenderableDimensions {+ RenderableDimensions {+ cols,+ viewport_rows: rows,+ scrollback_rows: rows,+ dpi,+ pixel_width: cols * 10,+ pixel_height: rows * 20,+ ..RenderableDimensions::default()+ }+ }++ #[test]+ fn preserving_invalidation_cancels_fetches_and_keeps_stale_lines() {+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ let token = FetchToken::new(7, Timestamp::ZERO);+ lines.put(1, LineEntry::Line(line(80)));+ lines.put(2, LineEntry::LineAndFetching(line(80), token));+ lines.put(3, LineEntry::Fetching(token));++ invalidate_line_entries(&mut lines, true);++ assert!(matches!(lines.get(&1), Some(LineEntry::Stale(_))));+ assert!(matches!(lines.get(&2), Some(LineEntry::Stale(_))));+ assert!(+ lines.get(&3).is_none(),+ "an in-flight fetch without a line must be canceled"+ );+ }++ #[test]+ fn invalidation_and_live_resize_keep_the_cache_bounded() {+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ lines.put(1, LineEntry::Line(line(80)));++ invalidate_line_entries(&mut lines, true);+ assert_eq!(lines.cap().get(), 8);++ resize_stale_line_entries(&mut lines, 37);+ assert_eq!(lines.cap().get(), 8);+ }++ #[test]+ fn width_changing_invalidation_clears_every_cached_line() {+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ lines.put(1, LineEntry::Line(line(80)));+ lines.put(2, LineEntry::Stale(line(80)));++ invalidate_line_entries(&mut lines, false);++ assert!(lines.is_empty());+ }++ #[test]+ fn live_resize_normalizes_retained_rows_to_the_preview_width() {+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ let mut wrapped = line(80);+ wrapped.set_last_cell_was_wrapped(true, SEQ_ZERO);+ lines.put(1, LineEntry::Line(wrapped));+ lines.put(2, LineEntry::Stale(line(80)));++ resize_stale_line_entries(&mut lines, 37);++ for row in [1, 2] {+ let Some(LineEntry::Stale(line)) = lines.get(&row) else {+ panic!("row {} was not retained as stale", row);+ };+ assert_eq!(line.len(), 37);+ assert!(!line.last_cell_was_wrapped());+ }+ }++ #[test]+ fn geometry_epoch_ignores_scrollback_motion_but_detects_render_size() {+ let current = dimensions(80, 24, 96);+ let mut scrollback_only = current;+ scrollback_only.scrollback_rows += 1;+ scrollback_only.physical_top += 1;+ assert!(!render_geometry_changed(current, scrollback_only));++ let mut new_width = current;+ new_width.cols += 1;+ assert!(render_geometry_changed(current, new_width));++ let mut new_dpi = current;+ new_dpi.dpi += 1;+ assert!(render_geometry_changed(current, new_dpi));+ }++ #[test]+ fn server_updates_cannot_replace_a_pinned_preview_grid() {+ let server = dimensions(80, 24, 96);+ let preview = dimensions(140, 42, 96);+ let next_server = dimensions(100, 30, 96);++ let (visible, invalidation) = resolve_server_geometry(preview, server, next_server, true);+ assert_eq!(visible, preview);+ assert_eq!(invalidation, Some(true));++ let (visible, invalidation) = resolve_server_geometry(server, server, next_server, false);+ assert_eq!(visible, next_server);+ assert_eq!(invalidation, Some(false));+ }++ #[test]+ fn server_geometry_confirmation_requires_the_complete_terminal_size() {+ let expected = wezterm_term::TerminalSize {+ rows: 40,+ cols: 120,+ pixel_width: 1200,+ pixel_height: 800,+ dpi: 144,+ };+ let confirmed = dimensions(120, 40, 144);+ assert!(render_dimensions_match_terminal_size(confirmed, expected));++ let mut stale_rows = confirmed;+ stale_rows.viewport_rows = 24;+ assert!(!render_dimensions_match_terminal_size(stale_rows, expected));++ let mut stale_pixels = confirmed;+ stale_pixels.pixel_height = 768;+ assert!(!render_dimensions_match_terminal_size(+ stale_pixels,+ expected+ ));+ }++ #[test]+ fn takeover_fetches_the_authoritative_server_rows_after_bottom_anchored_resize() {+ let size = wezterm_term::TerminalSize {+ rows: 27,+ cols: 120,+ pixel_width: 1200,+ pixel_height: 540,+ dpi: 96,+ };+ let mut server = dimensions(120, 27, 96);+ server.pixel_width = size.pixel_width;+ server.pixel_height = size.pixel_height;+ server.physical_top = 69;++ assert_eq!(+ confirmed_frontend_visible_range(server, size),+ Some(69..96),+ "a preview's stale top row must not shift the request to 70..97"+ );+ }++ #[test]+ fn a_partial_fetch_response_does_not_leave_an_unreturned_row_in_flight_forever() {+ let token = FetchToken::new(9, Timestamp::ZERO);+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ lines.put(70, LineEntry::Fetching(token));+ lines.put(71, LineEntry::LineAndFetching(line(80), token));+ let mut requested = RangeSet::new();+ requested.add_range(70..72);+ let returned = RangeSet::new();++ release_unreturned_fetches(&mut lines, &requested, &returned, token);++ assert!(lines.get(&70).is_none());+ assert!(matches!(lines.get(&71), Some(LineEntry::Stale(_))));+ }++ #[test]+ fn fetch_token_from_prior_epoch_is_not_current() {+ let token = FetchToken::new(4, Timestamp::ZERO);+ assert!(fetch_token_is_current(token, 4));+ assert!(!fetch_token_is_current(token, 5));+ }++ #[test]+ fn healthy_slow_fetch_keeps_its_original_token() {+ let started = Timestamp::ZERO;+ let token = FetchToken::new(7, started);+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ lines.put(10, LineEntry::Fetching(token));++ let decision = line_watchdog_decision(&mut lines, 10..11, started + Duration::from_secs(3));+ assert!(!decision.repaint);+ assert!(decision.retries.is_empty());+ assert!(matches!(lines.get(&10), Some(LineEntry::Fetching(current)) if *current == token));+ }++ #[test]+ fn fetch_stall_deadline_grows_until_a_stable_slow_rtt_can_complete() {+ let started = Timestamp::ZERO;+ let first = FetchToken::new(11, started);+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ lines.put(20, LineEntry::Fetching(first));++ let retry_started = started + Duration::from_secs(31);+ let decision = line_watchdog_decision(&mut lines, 20..21, retry_started);+ assert!(decision.repaint);+ assert_eq!(decision.retries.len(), 1);+ let replacement = decision.retries[0].token;+ assert_eq!(replacement.epoch, first.epoch);+ assert_eq!(replacement.stall_attempt, 1);++ // A stable 40s RTT lost to the first 30s deadline, but the replacement+ // keeps the exact token for its 60s window and can be accepted.+ let decision =+ line_watchdog_decision(&mut lines, 20..21, retry_started + Duration::from_secs(40));+ assert!(!decision.repaint);+ assert!(decision.retries.is_empty());+ assert!(matches!(+ lines.get(&20),+ Some(LineEntry::Fetching(current)) if *current == replacement+ ));+ }++ #[test]+ fn displayed_missing_rows_retry_but_offscreen_pending_rows_do_not_latch() {+ let now = Timestamp::ZERO;+ let mut missing = LruCache::new(NonZeroUsize::new(8).unwrap());+ missing.put(10, LineEntry::Line(line(80)));+ let decision = line_watchdog_decision(&mut missing, 10..12, now);+ assert!(decision.repaint, "displayed row 11 is missing");+ assert!(decision.retries.is_empty());++ let mut offscreen = LruCache::new(NonZeroUsize::new(8).unwrap());+ offscreen.put(5, LineEntry::Stale(line(80)));+ offscreen.put(10, LineEntry::Line(line(80)));+ offscreen.put(11, LineEntry::Line(line(80)));+ let decision = line_watchdog_decision(&mut offscreen, 10..12, now);+ assert!(!decision.repaint);+ assert!(decision.retries.is_empty());+ }++ #[test]+ fn epoch_bump_resets_fetch_stall_attempt() {+ let now = Timestamp::ZERO;+ let old = FetchToken::new(3, now).retry(now).retry(now);+ assert_eq!(old.stall_attempt, 2);++ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());+ lines.put(1, LineEntry::LineAndFetching(line(80), old));+ invalidate_line_entries(&mut lines, true);+ assert!(matches!(lines.get(&1), Some(LineEntry::Stale(_))));++ let next = FetchToken::new(old.epoch + 1, now);+ assert_eq!(next.stall_attempt, 0);+ assert!(!fetch_token_is_current(old, next.epoch));+ assert!(fetch_token_is_current(next, next.epoch));+ }++ #[test]+ fn poll_stall_retry_is_generation_safe_and_uses_a_growing_deadline() {+ let started = Timestamp::ZERO;+ assert!(poll_should_be_retried(+ started,+ 0,+ started + Duration::from_secs(20)+ ));+ assert!(!poll_should_be_retried(+ started,+ 1,+ started + Duration::from_secs(20)+ ));+ assert_eq!(stall_timeout(POLL_STALL_BASE, 2), Duration::from_secs(60));+ assert_eq!(stall_timeout(FETCH_STALL_BASE, 2), Duration::from_secs(120));++ let in_flight = AtomicU64::new(2);+ assert!(!claim_poll_completion(&in_flight, 1));+ assert_eq!(in_flight.load(Ordering::SeqCst), 2);+ assert!(claim_poll_completion(&in_flight, 2));+ assert_eq!(in_flight.load(Ordering::SeqCst), 0);+ }+}diff --git a/thinkterm-session/src/mouse.rs b/thinkterm-session/src/mouse.rsnew file mode 100644index 00000000..b2d80742--- /dev/null+++ b/thinkterm-session/src/mouse.rs@@ -0,0 +1,53 @@+use wezterm_term::{MouseButton, MouseEvent, MouseEventKind};++/// The GUI passes through the raw OS wheel amount (lines per notch), but+/// a local terminal emits exactly one report per wheel event no matter+/// the amount. Normalize each event to a single notch so that coalescing+/// accumulates a notch count; the mux server replays one report per+/// notch, matching local behavior.+pub fn normalize_wheel(mut event: MouseEvent) -> MouseEvent {+ event.button = match event.button {+ MouseButton::WheelUp(n) if n > 1 => MouseButton::WheelUp(1),+ MouseButton::WheelDown(n) if n > 1 => MouseButton::WheelDown(1),+ MouseButton::WheelLeft(n) if n > 1 => MouseButton::WheelLeft(1),+ MouseButton::WheelRight(n) if n > 1 => MouseButton::WheelRight(1),+ b => b,+ };+ event+}++/// Fold `event` into `last`, the mouse event queued right before it, when+/// the two can travel as one: interim moves collapse into the latest,+/// repeated wheel notches add up. Hands `event` back when it has to stay+/// its own report.+pub fn coalesce(last: &mut MouseEvent, event: MouseEvent) -> Option<MouseEvent> {+ if last.modifiers != event.modifiers {+ return Some(event);+ }+ if last.kind == MouseEventKind::Move+ && event.kind == MouseEventKind::Move+ && last.button == event.button+ {+ *last = event;+ return None;+ }+ match (&last.button, &event.button) {+ (MouseButton::WheelUp(a), MouseButton::WheelUp(b)) => {+ last.button = MouseButton::WheelUp(a + b);+ None+ }+ (MouseButton::WheelDown(a), MouseButton::WheelDown(b)) => {+ last.button = MouseButton::WheelDown(a + b);+ None+ }+ (MouseButton::WheelLeft(a), MouseButton::WheelLeft(b)) => {+ last.button = MouseButton::WheelLeft(a + b);+ None+ }+ (MouseButton::WheelRight(a), MouseButton::WheelRight(b)) => {+ last.button = MouseButton::WheelRight(a + b);+ None+ }+ _ => Some(event),+ }+}diff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rsnew file mode 100644index 00000000..ac4a1d9a--- /dev/null+++ b/thinkterm-session/src/pane.rs@@ -0,0 +1,1339 @@+//! One mirrored pane: its state behind one lock, the pushes it applies in+//! order, the rows it fetches and the polls it makes through the host.+//! Detached tasks hold a `Weak` to it; a pane that is gone by the time an+//! answer arrives is simply not updated.+use crate::clock::Clock;+use crate::delta_queue::{RenderDeltaQueue, RowsCarried};+use crate::host::{request, HostConfig, HostPaneId, PduLink, SessionEvents, SessionHost, Spawner};+use crate::hydrate::hydrate_lines;+use crate::images::ImageStore;+use crate::input::{drain_pane_inputs, push_input, InputQueue, InputQueueFull, PaneInput};+use crate::lines::*;+use crate::pane_state::PaneState;+use crate::{Lock, SessionConfig};+use codec::{GetLines, GetPaneRenderChanges, GetPaneRenderChangesResponse, InputSerial, Pdu};+use rangeset::RangeSet;+use std::ops::Range;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::{Arc, Weak};+use std::time::Duration;+use termwiz::cell::CellAttributes;+use termwiz::color::AnsiColor;+use termwiz::input::{KeyEvent, KeyboardEncoding};+use termwiz::surface::{SequenceNo, SEQ_ZERO};+use thinkterm_proto::ScrollbackEraseMode;+use thinkterm_proto::{PaneId, RenderableDimensions, StableCursorPosition};+use url::Url;+use wezterm_term::{KeyCode, KeyModifiers, Line, MouseEvent, StableRowIndex, TerminalSize};++pub struct PaneSession<H: SessionHost> {+ host: Arc<H>,+ images: Arc<Lock<ImageStore>>,+ state: Lock<PaneState>,+ render_deltas: Lock<RenderDeltaQueue>,+ /// Everything this pane was given and the server has not answered,+ /// in the order it was given; see `PaneInput`. Shared with the drain's+ /// guards, which settle it after this pane may be gone.+ inputs: Arc<Lock<InputQueue>>,+ remote_pane_id: PaneId,+ /// The tab the server currently files the pane under; a resync moves+ /// it. Shared with the host so it can update it in place.+ remote_tab_id: Arc<AtomicUsize>,+ host_pane_id: HostPaneId,+}++impl<H: SessionHost> PaneSession<H> {+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ host: Arc<H>,+ images: Arc<Lock<ImageStore>>,+ config: SessionConfig,+ remote_pane_id: PaneId,+ remote_tab_id: Arc<AtomicUsize>,+ host_pane_id: HostPaneId,+ dimensions: RenderableDimensions,+ title: &str,+ alt_screen: bool,+ ) -> Arc<Self> {+ let state = PaneState::new(+ config,+ dimensions,+ title,+ alt_screen,+ host.config().fetch_rate_per_second(),+ host.clock().now(),+ );+ Arc::new(Self {+ host,+ images,+ state: Lock::new(state),+ render_deltas: Lock::new(RenderDeltaQueue::default()),+ inputs: Default::default(),+ remote_pane_id,+ remote_tab_id,+ host_pane_id,+ })+ }++ fn state(&self) -> crate::LockGuard<'_, PaneState> {+ self.state.lock()+ }++ fn now(&self) -> crate::clock::Timestamp {+ self.host.clock().now()+ }++ pub fn remote_pane_id(&self) -> PaneId {+ self.remote_pane_id+ }++ pub fn host_pane_id(&self) -> HostPaneId {+ self.host_pane_id+ }++ // ---- what the renderer reads --------------------------------------++ pub fn dimensions(&self) -> RenderableDimensions {+ self.state().dimensions+ }++ pub fn cursor_position(&self) -> StableCursorPosition {+ self.state().cursor_position+ }++ pub fn current_seqno(&self) -> SequenceNo {+ self.state().seqno+ }++ pub fn title(&self) -> String {+ self.state().title.clone()+ }++ pub fn working_dir(&self) -> Option<Url> {+ self.state().working_dir.clone()+ }++ pub fn is_dead(&self) -> bool {+ self.state().dead+ }++ pub fn set_dead(&self, dead: bool) {+ self.state().dead = dead;+ }++ pub fn is_alt_screen(&self) -> bool {+ self.state().alt_screen+ }++ pub fn is_mouse_grabbed(&self) -> bool {+ self.state().mouse_grabbed+ }++ pub fn keyboard_encoding(&self) -> KeyboardEncoding {+ self.state().keyboard_encoding+ }++ pub fn is_tardy(&self) -> bool {+ let now = self.now();+ self.state().is_tardy(now)+ }++ pub fn since_last_response(&self) -> Duration {+ let now = self.now();+ self.state().since_last_response(now)+ }++ pub fn make_all_stale(&self) {+ self.state().make_all_stale();+ }++ pub fn update_last_send(&self) {+ let now = self.now();+ self.state().update_last_send(now);+ }++ /// A key went out with `serial`: remember it for cursor reconciliation+ /// and predict its echo, in that order.+ pub fn predict_from_key_event(&self, serial: InputSerial, key: KeyCode, mods: KeyModifiers) {+ let mut st = self.state();+ st.input_serial = serial;+ st.predict_from_key_event(key, mods);+ }++ pub fn predict_from_paste(&self, text: &str) {+ self.state().predict_from_paste(text);+ }++ // ---- input ----------------------------------------------------------+ //+ // Everything goes through one queue per pane, in the order it was+ // given; `Ok(true)` means nothing is draining it and the host must+ // spawn `drain_inputs`. Over the limit an input is refused, not+ // dropped: the caller is told, and what reaches the server is either+ // all of an input or none of it.++ /// Queue `input` behind everything given before it.+ pub fn queue_input(&self, input: PaneInput) -> Result<bool, InputQueueFull> {+ let what = input.describe();+ push_input(&self.inputs, input).map_err(|full| {+ log::warn!(+ "refusing {what} for remote pane {}: {full}",+ self.remote_pane_id+ );+ full+ })+ }++ /// A key, sent with `serial` and predicted locally right after it is+ /// queued: the serial first, so the answer to this very key is the+ /// one allowed to move the cursor.+ pub fn key_down(+ &self,+ serial: InputSerial,+ key: KeyCode,+ mods: KeyModifiers,+ ) -> Result<bool, InputQueueFull> {+ let start = self.queue_input(PaneInput::Key {+ event: KeyEvent {+ key,+ modifiers: mods,+ },+ input_serial: serial,+ })?;+ self.predict_from_key_event(serial, key, mods);+ Ok(start)+ }++ /// A paste, predicted locally right after it is queued.+ pub fn paste(&self, text: &str) -> Result<bool, InputQueueFull> {+ let start = self.queue_input(PaneInput::Paste(text.to_owned()))?;+ self.predict_from_paste(text);+ Ok(start)+ }++ /// Bytes the host encoded itself (kitty-protocol keys, IME text).+ pub fn write_bytes(&self, data: &[u8]) -> Result<bool, InputQueueFull> {+ self.queue_input(PaneInput::Bytes(data.to_vec()))+ }++ pub fn mouse_event(&self, event: MouseEvent) -> Result<bool, InputQueueFull> {+ self.queue_input(PaneInput::Mouse(crate::mouse::normalize_wheel(event)))+ }++ pub fn erase_scrollback(&self, mode: ScrollbackEraseMode) -> Result<bool, InputQueueFull> {+ self.queue_input(PaneInput::EraseScrollback(mode))+ }++ /// Send the queued input in order until the queue is empty. The host+ /// spawns this when a queue call returned `Ok(true)`; it is a plain+ /// `async fn` rather than a `Spawner` task so a host whose link hands+ /// out `Send` futures gets a `Send` future here too.+ pub async fn drain_inputs(self: Arc<Self>) {+ drain_pane_inputs(+ self.host.link(),+ self.remote_pane_id,+ Arc::clone(&self.remote_tab_id),+ Arc::clone(&self.inputs),+ )+ .await+ }++ // ---- geometry -------------------------------------------------------++ pub fn apply_local_resize(&self, size: TerminalSize) -> bool {+ self.state().apply_local_resize(size)+ }++ pub fn begin_frontend_preview(+ &self,+ epoch: u64,+ size: TerminalSize,+ policy: FrontendPreviewPolicy,+ ) -> bool {+ self.state().begin_frontend_preview(epoch, size, policy)+ }++ pub fn end_frontend_preview(&self, epoch: u64, succeeded: bool) -> bool {+ self.state().end_frontend_preview(epoch, succeeded)+ }++ pub fn server_geometry_matches(&self, size: TerminalSize) -> bool {+ self.state().server_geometry_matches(size)+ }++ /// Which fields or render rows block a takeover from settling on `size`.+ pub fn frontend_geometry_mismatch(&self, size: TerminalSize) -> Option<String> {+ let mut st = self.state();+ let dims = st.server_dimensions;+ if !render_dimensions_match_terminal_size(dims, size) {+ let mut fields = Vec::new();+ if dims.cols != size.cols {+ fields.push(format!("cols {}!={}", dims.cols, size.cols));+ }+ if dims.viewport_rows != size.rows {+ fields.push(format!("rows {}!={}", dims.viewport_rows, size.rows));+ }+ if dims.pixel_width != size.pixel_width {+ fields.push(format!("px_w {}!={}", dims.pixel_width, size.pixel_width));+ }+ if dims.pixel_height != size.pixel_height {+ fields.push(format!("px_h {}!={}", dims.pixel_height, size.pixel_height));+ }+ if dims.dpi != size.dpi {+ fields.push(format!("dpi {}!={}", dims.dpi, size.dpi));+ }+ return Some(fields.join(","));+ }++ let top = st.server_dimensions.physical_top;+ let end = top.saturating_add(size.rows as StableRowIndex);+ let mut total = 0usize;+ let mut sample = Vec::new();+ for row in top..end {+ let kind = match st.lines.get(&row) {+ Some(LineEntry::Line(_)) => continue,+ Some(LineEntry::Fetching(token)) => format!("Fetching/e{}", token.epoch),+ Some(LineEntry::LineAndFetching(_, token)) => {+ format!("LineAndFetching/e{}", token.epoch)+ }+ Some(LineEntry::Stale(_)) => "Stale".to_string(),+ None => "Missing".to_string(),+ };+ total += 1;+ if sample.len() < 8 {+ sample.push(format!("{row}:{kind}"));+ }+ }+ (total > 0).then(|| {+ format!(+ "render rows {top}..{end} pending {total} [{}], cache_epoch={}",+ sample.join(" "),+ st.line_cache_epoch+ )+ })+ }++ /// Drive a render poll and populate every currently visible line while a+ /// takeover overlay is still opaque. Returns true only after the server+ /// has confirmed `size` and none of those rows is stale or in flight.+ pub fn prime_frontend_geometry(self: &Arc<Self>, size: TerminalSize) -> bool {+ // One lock for the whole call: the row fetch it schedules goes+ // through `get_lines_locked`, never back through the public+ // `get_lines`, so this cannot deadlock on its own lock.+ let mut st = self.state();+ // Cancel any backoff this pane had settled into, but leave+ // `last_poll` alone so `poll` still rate-limits itself. Backdating+ // it forced a fresh render-changes RPC on *every* call, and the+ // reply emits PaneOutput, which marks the frontend dirty, which+ // draws, which calls this again: on a local socket that loop ran+ // thousands of times a second for the whole takeover window+ // instead of the ~50 the base interval allows.+ st.poll_interval = BASE_POLL_INTERVAL;+ self.poll(&mut st);+ let Some(mut visible) = confirmed_frontend_visible_range(st.server_dimensions, size) else {+ return false;+ };++ // This both returns any retained rows and schedules missing/stale+ // rows. Fetch completion emits PaneOutput and drives another overlay+ // frame, where the readiness check below can finally pass.+ let _ = self.get_lines_locked(&mut st, visible.clone());++ if confirmed_frontend_visible_range(st.server_dimensions, size).as_ref() != Some(&visible) {+ return false;+ }+ visible.all(|row| matches!(st.lines.get(&row), Some(LineEntry::Line(_))))+ }++ // ---- the render surface ---------------------------------------------++ pub fn get_lines(+ self: &Arc<Self>,+ lines: Range<StableRowIndex>,+ ) -> (StableRowIndex, Vec<Line>) {+ let mut st = self.state();+ self.get_lines_locked(&mut st, lines)+ }++ fn get_lines_locked(+ self: &Arc<Self>,+ st: &mut PaneState,+ lines: Range<StableRowIndex>,+ ) -> (StableRowIndex, Vec<Line>) {+ let mut result = vec![];+ let mut to_fetch = RangeSet::new();+ let now = self.now();+ let fetch_token = st.fetch_token(now);++ for idx in lines.clone() {+ let entry = match st.lines.pop(&idx) {+ Some(LineEntry::Line(line)) => {+ result.push(line.clone());+ if line.changed_since(st.seqno) {+ to_fetch.add(idx);+ LineEntry::Stale(line)+ } else {+ LineEntry::Line(line)+ }+ }+ Some(LineEntry::LineAndFetching(line, then)) => {+ result.push(line.clone());+ LineEntry::LineAndFetching(line, then)+ }+ Some(LineEntry::Fetching(then)) => {+ result.push(Line::with_width(st.dimensions.cols, SEQ_ZERO));+ LineEntry::Fetching(then)+ }+ Some(LineEntry::Stale(line)) => {+ result.push(line.clone());+ to_fetch.add(idx);+ LineEntry::LineAndFetching(line, fetch_token)+ }+ None => {+ result.push(Line::with_width(st.dimensions.cols, SEQ_ZERO));+ to_fetch.add(idx);+ LineEntry::Fetching(fetch_token)+ }+ };++ if st.config.overlay_lag_indicator && idx == st.dimensions.physical_top {+ if st.is_tardy(now) {+ let status = format!(+ "ThinkTerm: {:.0?}⏳since last response",+ st.since_last_response(now)+ );+ // Right align it in the tab+ let col = st+ .dimensions+ .cols+ .saturating_sub(wezterm_term::unicode_column_width(&status, None));++ let mut attr = CellAttributes::default();+ attr.set_foreground(AnsiColor::White);+ attr.set_background(AnsiColor::Blue);++ result+ .last_mut()+ .unwrap()+ .overlay_text_with_attribute(col, &status, attr, SEQ_ZERO);+ }+ }++ st.lines.put(idx, entry);+ }++ log::trace!(+ "get_lines: {:?}, num result lines={}, will fetch {:?}",+ lines,+ result.len(),+ to_fetch+ );++ self.schedule_fetch_lines(st.dead, to_fetch, fetch_token);+ (lines.start, result)+ }++ pub fn changed_since(+ self: &Arc<Self>,+ lines: Range<StableRowIndex>,+ seqno: SequenceNo,+ ) -> RangeSet<StableRowIndex> {+ let mut st = self.state();+ self.poll(&mut st);++ let mut result = RangeSet::new();+ for r in lines {+ match st.lines.get(&r) {+ None => {+ result.add(r);+ }+ Some(+ LineEntry::Line(line)+ | LineEntry::Stale(line)+ | LineEntry::LineAndFetching(line, _),+ ) if line.changed_since(seqno) => {+ result.add(r);+ }+ _ => {}+ }+ }++ // If we're behind receiving an update, invalidate the top row so+ // that the indicator will update in a more timely fashion+ let now = self.now();+ if st.is_tardy(now) {+ // ... but take care to avoid always reporting it as dirty, so+ // that we don't end up busy looping just to repaint it+ if now.saturating_duration_since(st.last_late_dirty) >= Duration::from_secs(1) {+ result.add(st.dimensions.physical_top);+ st.last_late_dirty = now;+ }+ }++ if !result.is_empty() {+ log::trace!("get_changed_since: {} -> {:?}", seqno, result);+ }++ result+ }++ /// True when a row the host is actually displaying is waiting on work+ /// that only a paint performs. `viewport_top` is the displayed viewport+ /// origin (None = following the tail): scoping to the painted range --+ /// not the live screen -- is what keeps this from latching, and Stale+ /// entries for rows outside it are normal and must not count.+ ///+ /// Checking also repairs a fetch whose detached future may have been+ /// lost. Its retry deadline doubles after every supersession, so a+ /// healthy but consistently slow request eventually gets a window long+ /// enough to complete instead of losing forever to a fixed watchdog.+ pub fn render_looks_stalled(self: &Arc<Self>, viewport_top: Option<StableRowIndex>) -> bool {+ let mut st = self.state();+ if !crate::decide::render_watchdog_should_run(st.dead) {+ return false;+ }+ let top = viewport_top.unwrap_or(st.dimensions.physical_top);+ let range = top..top.saturating_add(st.dimensions.viewport_rows as StableRowIndex);+ let decision = line_watchdog_decision(&mut st.lines, range, self.now());+ if decision.repaint {+ st.poll_interval = BASE_POLL_INTERVAL;+ }+ for batch in decision.retries {+ self.schedule_fetch_lines(st.dead, batch.rows, batch.token);+ }+ decision.repaint+ }++ // ---- pushes ---------------------------------------------------------++ /// Queue a render push; it is applied by the drain, in order.+ pub fn queue_render_delta(self: &Arc<Self>, delta: GetPaneRenderChangesResponse) {+ if self.render_deltas.lock().push(delta) {+ let weak = Arc::downgrade(self);+ self.host+ .spawner()+ .spawn_detached(Box::pin(Self::drain_render_deltas(weak)));+ }+ }++ async fn drain_render_deltas(weak: Weak<Self>) {+ let _draining = DrainingDeltas(weak.clone());+ loop {+ let Some(me) = weak.upgrade() else {+ return;+ };+ let Some((delta, carried)) = me.render_deltas.lock().take() else {+ return;+ };+ // A push with a newer one already behind it is applied without+ // asking for pictures: the newer push names the current ones, and+ // rows whose pictures are missing keep showing the previous frame.+ let started = me.now();+ let fetched_pictures = carried.is_none();+ me.apply_render_delta(delta, carried).await;+ log::debug!(+ "render push for pane {} applied in {:?} (fetched pictures: {})",+ me.host_pane_id,+ me.now().saturating_duration_since(started),+ fetched_pictures+ );+ }+ }++ /// Apply one push. With `carried` given, newer pushes wait behind this+ /// one and it is applied without fetching pictures; a row it then has+ /// to leave out is marked dirty unless one of those pushes brings it,+ /// since the server sent it as a bonus row and nothing else would ever+ /// fetch it again.+ async fn apply_render_delta(+ self: &Arc<Self>,+ mut delta: GetPaneRenderChangesResponse,+ carried: Option<RowsCarried>,+ ) {+ let bonus_lines = std::mem::take(&mut delta.bonus_lines);+ let (bonus_lines, left_out) = hydrate_lines(+ &*self.host,+ &self.images,+ delta.pane_id,+ bonus_lines,+ carried.is_none(),+ )+ .await;+ if let Some(carried) = carried {+ for row in left_out {+ if !carried.contains(row) {+ delta.dirty_lines.push(row..row + 1);+ }+ }+ }++ let mut st = self.state();+ self.apply_changes_to_surface(&mut st, delta, bonus_lines);+ }++ fn apply_changes_to_surface(+ self: &Arc<Self>,+ st: &mut PaneState,+ delta: GetPaneRenderChangesResponse,+ bonus_lines: Vec<(StableRowIndex, Line)>,+ ) {+ log::trace!(+ "apply_changes_to_surface local={} remote={}",+ self.host_pane_id,+ self.remote_pane_id+ );+ let now = self.now();+ st.poll_interval = BASE_POLL_INTERVAL;+ st.last_recv_time = now;++ if delta.alt_screen != st.alt_screen {+ st.alt_screen = delta.alt_screen;+ // Rows cached from the other screen are stamped with seqnos+ // the server will never move past, so nothing else would ever+ // refetch them; the alternate screen's rows in particular sit+ // at the stable indices of the primary's oldest scrollback.+ st.invalidate_line_cache(true);+ }+ st.mouse_grabbed = delta.mouse_grabbed;+ st.keyboard_encoding = delta.keyboard_encoding.into();++ let live_preview_accepts_snapshot = st.frontend_preview.is_none_or(|preview| {+ preview.policy != FrontendPreviewPolicy::LiveResize+ || render_dimensions_match_terminal_size(delta.dimensions, preview.size)+ });++ let mut dirty = RangeSet::new();+ for r in delta.dirty_lines {+ dirty.add_range(r.clone());+ }+ if delta.cursor_position != st.cursor_position {+ dirty.add(st.cursor_position.y);+ // But note that the server may have sent this in bonus_lines;+ // we'll address that below+ dirty.add(delta.cursor_position.y);+ }++ // Keep track of the approximate round trip time by recording how+ // long it took for this response to come back+ if let Some(serial) = delta.input_serial {+ st.last_input_rtt = serial.elapsed_millis_since(self.host.clock().wall_millis());+ }++ // When it comes to updating the cursor position, if the update was tagged+ // with keyboard input, we'll only take the position if the update comes from+ // the most recent key event. This helps to prevent the cursor wiggling if the+ // user is typing more than one character per roundtrip interval--the wiggle+ // manifests because we may have already predicted a local cursor move forwards+ // by one character, and we may receive the response to the prior update after+ // we have rendered that, and then shortly receive the most recent response.+ // The result of that is that the cursor moves right one, left one and then+ // finally right one in quick succession.+ // If the delta was not from an input event then we trust it; this is most+ // like due to a unilateral movement by the application on the other end.+ if live_preview_accepts_snapshot+ && (delta.input_serial.is_none()+ || delta.input_serial.unwrap_or(InputSerial::empty()) >= st.input_serial)+ {+ st.cursor_position = delta.cursor_position;+ }+ let prior_server_dimensions = st.server_dimensions;+ st.server_dimensions = delta.dimensions;+ let (visible_dimensions, invalidate) = resolve_server_geometry(+ st.dimensions,+ prior_server_dimensions,+ delta.dimensions,+ st.frontend_preview.is_some(),+ );+ st.dimensions = visible_dimensions;+ if let Some(preserve_lines) = invalidate {+ // During a preview, retain old rows while marking them stale. This+ // prevents a blank flash as a full-screen application redraws.+ st.invalidate_line_cache(preserve_lines);+ }+ st.title = delta.title;+ st.working_dir = delta.working_dir.map(Into::into);+ log::trace!(+ "server says: seqno from {} -> {} for local_pane_id={}",+ st.seqno,+ delta.seqno,+ self.host_pane_id+ );+ st.seqno = delta.seqno;++ let rules = self.host.config().hyperlink_rules();+ for (stable_row, line) in bonus_lines {+ // A live preview can have several acknowledged server grids in+ // flight over its lifetime. Rows bundled with an intermediate+ // grid are authoritative for that grid only; accepting them into+ // the final-width cache is exactly how old-width fragments survive+ // after the divider stops.+ if !live_preview_accepts_snapshot {+ continue;+ }+ log::trace!("bonus line {} seqno={}", stable_row, line.current_seqno());+ st.put_line(stable_row, line, &rules, None);+ dirty.remove(stable_row);+ }++ log::trace!(+ "apply_changes_to_surface: Generate PaneOutput event for local={}",+ self.host_pane_id+ );+ // Under the lock, as it always was: the host must not re-enter.+ self.host.events().pane_output(self.host_pane_id);++ let mut to_fetch = RangeSet::new();+ log::trace!("dirty as of seq {} -> {:?}", delta.seqno, dirty);+ for r in dirty.iter() {+ for stable_row in r.clone() {+ // If a line is in the (probable) viewport region,+ // then we'll likely want to fetch it.+ // If it is outside that region, remove it from our cache+ // so that we'll fetch it on demand later.+ let fetchable = stable_row >= delta.dimensions.physical_top;+ let prior = st.lines.pop(&stable_row);+ let prior_kind = prior.as_ref().map(|e| e.kind());+ if !fetchable {+ log::trace!("make {} stale bcos not fetchable", stable_row);+ st.make_stale(stable_row);+ continue;+ }+ to_fetch.add(stable_row);+ let token = st.fetch_token(now);+ let entry = match prior {+ Some(LineEntry::Fetching(_)) | None => LineEntry::Fetching(token),+ Some(LineEntry::LineAndFetching(old, ..))+ | Some(LineEntry::Stale(old))+ | Some(LineEntry::Line(old)) => LineEntry::LineAndFetching(old, token),+ };+ log::trace!(+ "row {} {:?} -> {:?} due to dirty and IN viewport",+ stable_row,+ prior_kind,+ entry.kind()+ );+ st.lines.put(stable_row, entry);+ }+ }+ if !to_fetch.is_empty() {+ let rate = self.host.config().fetch_rate_per_second();+ if st.fetch_limiter.admit(rate, 1, now) {+ let token = st.fetch_token(now);+ self.schedule_fetch_lines(st.dead, to_fetch, token);+ } else {+ log::warn!(+ "exceeded fetch throttle, drop {:?} and mark stale",+ to_fetch+ );+ for r in to_fetch.iter() {+ for stable_row in r.clone() {+ st.make_stale(stable_row);+ }+ }+ }+ }+ }++ // ---- fetching and polling -------------------------------------------++ fn schedule_fetch_lines(+ self: &Arc<Self>,+ dead: bool,+ to_fetch: RangeSet<StableRowIndex>,+ fetch_token: FetchToken,+ ) {+ if to_fetch.is_empty() || dead {+ return;+ }++ log::trace!(+ "will fetch lines {:?} for remote tab id {} at {:?}",+ to_fetch,+ self.remote_pane_id,+ fetch_token,+ );++ let host = Arc::clone(&self.host);+ let images = Arc::clone(&self.images);+ let remote_pane_id = self.remote_pane_id;+ let weak = Arc::downgrade(self);++ self.host.spawner().spawn_detached(Box::pin(async move {+ let result = request(+ host.link(),+ Pdu::GetLines(GetLines {+ pane_id: remote_pane_id,+ lines: to_fetch.clone().into(),+ }),+ |pdu| match pdu {+ Pdu::GetLinesResponse(response) => Ok(response),+ other => Err(other),+ },+ )+ .await;++ let result = match result {+ Ok(result) => {+ let (lines, _) =+ hydrate_lines(&*host, &images, remote_pane_id, result.lines, true).await;+ Ok(lines)+ }+ Err(err) => Err(err),+ };+ Self::apply_lines(&weak, result, to_fetch, fetch_token);+ }));+ }++ fn apply_lines(+ weak: &Weak<Self>,+ result: anyhow::Result<Vec<(StableRowIndex, Line)>>,+ to_fetch: RangeSet<StableRowIndex>,+ fetch_token: FetchToken,+ ) {+ // The pane is gone: nothing to update, nobody to tell.+ let Some(me) = weak.upgrade() else {+ return;+ };+ let mut notify_pane_output = true;+ {+ let mut st = me.state();++ if !fetch_token_is_current(fetch_token, st.line_cache_epoch) {+ log::trace!(+ "discarding line fetch for pane {} from epoch {} because current epoch is {}",+ me.host_pane_id,+ fetch_token.epoch,+ st.line_cache_epoch+ );+ // The rows this fetch covered were re-tagged Stale when the+ // epoch moved, and only a paint re-fetches Stale rows. A+ // paint is only scheduled by PaneOutput, so returning+ // without notifying can leave the pane frozen until the+ // user interacts with it. Once per epoch is enough: a live+ // resize discards several in-flight fetches per frame.+ let already_notified = st.epoch_discard_notified == st.line_cache_epoch;+ st.epoch_discard_notified = st.line_cache_epoch;+ drop(st);+ if !already_notified {+ me.host.events().pane_output(me.host_pane_id);+ }+ return;+ }++ match result {+ Ok(lines) => {+ let rules = me.host.config().hyperlink_rules();+ let mut returned = RangeSet::new();++ log::trace!("fetch complete for {:?} with {:?}", to_fetch, fetch_token);+ for (stable_row, line) in lines.into_iter() {+ returned.add(stable_row);+ st.put_line(stable_row, line, &rules, Some(fetch_token));+ }+ // The terminal can scroll or resize while GetLines is in+ // flight, so a successful response is allowed to omit a+ // row that no longer exists in its stable range. Leaving+ // that row tagged Fetching would suppress every future+ // request for it and can hold an opaque takeover mask up+ // forever.+ release_unreturned_fetches(&mut st.lines, &to_fetch, &returned, fetch_token);+ }+ Err(err) => {+ log::error!("get_lines failed: {}", err);+ // No PaneOutput for a failure: notifying would repaint,+ // the repaint would re-fetch the Stale rows, and a+ // persistent error would spin that loop at RPC rate.+ // The rows stay Stale; the next natural paint (input,+ // or the ~1s render watchdog) retries them instead.+ notify_pane_output = false;+ for r in to_fetch.iter() {+ for stable_row in r.clone() {+ let entry = match st.lines.pop(&stable_row) {+ Some(LineEntry::Fetching(then)) if then == fetch_token => {+ // leave it popped+ continue;+ }+ Some(LineEntry::LineAndFetching(line, then))+ if then == fetch_token =>+ {+ // Stale, not Line: the local copy's seqno+ // is already <= the pane's, so a Line+ // would never satisfy changed_since and+ // the row would keep its old content+ // forever. Stale rows are re-fetched by+ // the next paint.+ LineEntry::Stale(line)+ }+ Some(entry) => entry,+ None => continue,+ };+ st.lines.put(stable_row, entry);+ }+ }+ }+ }+ }+ if notify_pane_output {+ log::trace!(+ "Generate PaneOutput event for local_pane_id={}",+ me.host_pane_id+ );+ me.host.events().pane_output(me.host_pane_id);+ }+ }++ fn poll(self: &Arc<Self>, st: &mut PaneState) {+ let now = self.now();+ let mut forced_retry = false;+ let in_flight = st.poll_in_flight.load(Ordering::SeqCst);+ if in_flight != 0 {+ let deadline = stall_timeout(POLL_STALL_BASE, st.poll_stall_attempt);+ if poll_should_be_retried(st.last_poll, st.poll_stall_attempt, now) {+ // A detached completion may have been lost. Increase the+ // next deadline instead of using a fixed threshold: a slow+ // but healthy poll must eventually be allowed to win.+ log::warn!(+ "pane {} poll generation {} exceeded {:?} (attempt {}); replacing it",+ self.host_pane_id,+ in_flight,+ deadline,+ st.poll_stall_attempt,+ );+ if !claim_poll_completion(&st.poll_in_flight, in_flight) {+ return;+ }+ st.poll_stall_attempt = st.poll_stall_attempt.saturating_add(1);+ forced_retry = true;+ } else {+ // We have a poll in progress+ return;+ }+ }++ if !forced_retry {+ if now.saturating_duration_since(st.last_poll) < st.poll_interval {+ return;+ }+ st.poll_stall_attempt = 0;+ }++ let interval = st.poll_interval;+ let interval = (interval + interval).min(MAX_POLL_INTERVAL);+ st.poll_interval = interval;++ st.last_poll = now;+ st.poll_gen = st.poll_gen.wrapping_add(1).max(1);+ let gen = st.poll_gen;+ st.poll_in_flight.store(gen, Ordering::SeqCst);+ let poll_in_flight = Arc::clone(&st.poll_in_flight);+ let remote_pane_id = self.remote_pane_id;+ let host = Arc::clone(&self.host);+ let weak = Arc::downgrade(self);+ self.host.spawner().spawn_detached(Box::pin(async move {+ let alive = match request(+ host.link(),+ Pdu::GetPaneRenderChanges(GetPaneRenderChanges {+ pane_id: remote_pane_id,+ }),+ |pdu| match pdu {+ Pdu::LivenessResponse(response) => Ok(response),+ other => Err(other),+ },+ )+ .await+ {+ Ok(resp) => resp.is_alive,+ // if we got a timeout on a reconnectable, don't+ // consider the tab to be dead; that helps to+ // avoid having a tab get shuffled around+ Err(_) => host.link().is_reconnectable(),+ };++ // Cleared through the shared handle before anything that can+ // bail: if the pane is gone, a flag left set would silence every+ // future poll. Generation checked: a poll the watchdog already+ // superseded must not clear its successor's latch or apply its+ // stale answer.+ if !claim_poll_completion(&poll_in_flight, gen) {+ return;+ }++ let Some(me) = weak.upgrade() else {+ return;+ };+ let mut st = me.state();+ st.dead = !alive;+ st.last_recv_time = host.clock().now();+ st.poll_stall_attempt = 0;+ }));+ }+}++/// Marks the drain over when its task ends, however it ends, so a task+/// dropped without finishing cannot leave every later push waiting.+struct DrainingDeltas<H: SessionHost>(Weak<PaneSession<H>>);++impl<H: SessionHost> Drop for DrainingDeltas<H> {+ fn drop(&mut self) {+ if let Some(pane) = self.0.upgrade() {+ pane.render_deltas.lock().end_drain();+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::host::{DetachedFuture, HostConfig, LinkError};+ use crate::input::{LocalFuture, PaneLink};+ use codec::{GetLinesResponse, UnitResponse};+ use std::cell::{Cell, RefCell};+ use std::future::Future;+ use std::pin::Pin;+ use std::task::{Context, Poll, Waker};+ use termwiz::cell::CellAttributes;+ use thinkterm_proto::TabId;++ /// Poll to completion with a no-op waker: every future here is ready+ /// after a poll or two, nothing waits on the outside.+ fn spin_on<F: Future>(mut fut: F) -> F::Output {+ let mut fut = unsafe { Pin::new_unchecked(&mut fut) };+ let mut cx = Context::from_waker(Waker::noop());+ for _ in 0..1000 {+ if let Poll::Ready(out) = fut.as_mut().poll(&mut cx) {+ return out;+ }+ }+ panic!("a test future never became ready");+ }++ struct TestClock(Cell<u64>);+ impl Clock for TestClock {+ fn now(&self) -> crate::clock::Timestamp {+ crate::clock::Timestamp::from_micros(self.0.get())+ }+ fn wall_millis(&self) -> u64 {+ 5_000+ }+ }++ /// Tasks run when the test says so, so a fetch can be "in flight"+ /// across an epoch bump.+ #[derive(Default)]+ struct TestSpawner(RefCell<Vec<DetachedFuture>>);+ impl Spawner for TestSpawner {+ fn spawn_detached(&self, fut: DetachedFuture) {+ self.0.borrow_mut().push(fut);+ }+ }+ impl TestSpawner {+ fn run_all(&self) {+ for _ in 0..100 {+ let tasks = std::mem::take(&mut *self.0.borrow_mut());+ if tasks.is_empty() {+ return;+ }+ for task in tasks {+ spin_on(task);+ }+ }+ panic!("tasks kept spawning tasks");+ }+ }++ #[derive(Default)]+ struct TestEvents {+ outputs: Cell<u32>,+ }+ impl SessionEvents for TestEvents {+ fn pane_output(&self, _pane: HostPaneId) {+ self.outputs.set(self.outputs.get() + 1);+ }+ fn alert(&self, _pane: HostPaneId, _alert: wezterm_term::Alert) {}+ fn agent_status_changed(&self, _pane: HostPaneId) {}+ fn pane_removed(&self, _pane: HostPaneId) {}+ fn pane_focused(&self, _pane: HostPaneId) {}+ fn input_recorded(&self) {}+ }++ struct TestConfig;+ impl HostConfig for TestConfig {+ fn hyperlink_rules(&self) -> Arc<Vec<termwiz::hyperlink::Rule>> {+ Arc::new(Vec::new())+ }+ fn fetch_rate_per_second(&self) -> u32 {+ 100+ }+ }++ /// Answers GetLines from a table of rows, everything else with+ /// UnitResponse.+ #[derive(Default)]+ struct TestLink {+ rows: RefCell<Vec<(StableRowIndex, String)>>,+ asked: RefCell<Vec<&'static str>>,+ }+ impl PduLink for TestLink {+ type Request = LocalFuture<Result<Pdu, LinkError>>;+ fn request(&self, pdu: Pdu) -> Self::Request {+ self.asked.borrow_mut().push(pdu.pdu_name());+ let answer = match pdu {+ Pdu::GetLines(req) => {+ let table = self.rows.borrow();+ let lines: Vec<(StableRowIndex, Line)> = req+ .lines+ .iter()+ .flat_map(|range| range.clone())+ .filter_map(|row| {+ table.iter().find(|(r, _)| *r == row).map(|(r, text)| {+ (+ *r,+ Line::from_text(+ text,+ &CellAttributes::default(),+ SEQ_ZERO,+ None,+ ),+ )+ })+ })+ .collect();+ Pdu::GetLinesResponse(GetLinesResponse {+ pane_id: req.pane_id,+ lines: lines.into(),+ })+ }+ Pdu::GetPaneRenderChanges(req) => Pdu::LivenessResponse(codec::LivenessResponse {+ pane_id: req.pane_id,+ is_alive: true,+ }),+ _ => Pdu::UnitResponse(UnitResponse {}),+ };+ Box::pin(async move { Ok(answer) })+ }+ fn is_reconnectable(&self) -> bool {+ true+ }+ fn connection_generation(&self) -> u64 {+ 1+ }+ }+ impl PaneLink for TestLink {+ type Prepare = LocalFuture<anyhow::Result<bool>>;+ fn prepare(&self, _remote_tab_id: TabId) -> Self::Prepare {+ Box::pin(async { Ok(true) })+ }+ }++ struct TestHost {+ clock: TestClock,+ spawner: TestSpawner,+ events: TestEvents,+ link: TestLink,+ config: TestConfig,+ }+ impl SessionHost for TestHost {+ type Clock = TestClock;+ type Spawner = TestSpawner;+ type Events = TestEvents;+ type Link = TestLink;+ type Config = TestConfig;+ fn clock(&self) -> &TestClock {+ &self.clock+ }+ fn spawner(&self) -> &TestSpawner {+ &self.spawner+ }+ fn events(&self) -> &TestEvents {+ &self.events+ }+ fn link(&self) -> &TestLink {+ &self.link+ }+ fn config(&self) -> &TestConfig {+ &self.config+ }+ fn image_domain(&self) -> crate::host::ImageDomainKey {+ 1+ }+ }++ fn dims() -> RenderableDimensions {+ RenderableDimensions {+ cols: 80,+ viewport_rows: 24,+ scrollback_rows: 24,+ physical_top: 0,+ scrollback_top: 0,+ dpi: 96,+ pixel_width: 800,+ pixel_height: 480,+ reverse_video: false,+ }+ }++ fn size() -> TerminalSize {+ TerminalSize {+ rows: 24,+ cols: 80,+ pixel_width: 800,+ pixel_height: 480,+ dpi: 96,+ }+ }++ fn session(rows: &[(StableRowIndex, &str)]) -> (Arc<TestHost>, Arc<PaneSession<TestHost>>) {+ let host = Arc::new(TestHost {+ clock: TestClock(Cell::new(0)),+ spawner: TestSpawner::default(),+ events: TestEvents::default(),+ link: TestLink::default(),+ config: TestConfig,+ });+ *host.link.rows.borrow_mut() = rows.iter().map(|(r, t)| (*r, t.to_string())).collect();+ let session = PaneSession::new(+ Arc::clone(&host),+ Arc::new(Lock::new(ImageStore::default())),+ SessionConfig {+ scrollback_lines: 256,+ local_echo_threshold_ms: None,+ overlay_lag_indicator: false,+ },+ 9,+ Arc::new(AtomicUsize::new(0)),+ 1,+ dims(),+ "test",+ false,+ );+ (host, session)+ }++ fn delta(seqno: usize, alt_screen: bool, mouse_grabbed: bool) -> GetPaneRenderChangesResponse {+ GetPaneRenderChangesResponse {+ pane_id: 9,+ mouse_grabbed,+ alt_screen,+ keyboard_encoding: Default::default(),+ cursor_position: Default::default(),+ dimensions: dims(),+ dirty_lines: vec![],+ title: String::new(),+ working_dir: None,+ bonus_lines: Vec::new().into(),+ input_serial: None,+ seqno,+ }+ }++ /// R1: `prime_frontend_geometry` fetches through the same lock it+ /// holds. It must neither deadlock nor report ready before the rows+ /// arrived, and report ready once they have.+ #[test]+ fn priming_an_empty_cache_takes_one_lock_and_settles_after_the_fetch() {+ let (host, session) = session(&(0..24).map(|r| (r, "row")).collect::<Vec<_>>());+ // A server seqno first: rows stamped with SEQ_ZERO always read as+ // changed, exactly as they would before the first push.+ session.queue_render_delta(delta(1, false, false));+ host.spawner.run_all();+ assert!(+ !session.prime_frontend_geometry(size()),+ "nothing fetched yet"+ );+ assert!(!host.spawner.0.borrow().is_empty(), "a fetch was scheduled");+ host.spawner.run_all();+ assert!(host.link.asked.borrow().contains(&"GetLines"));+ assert!(+ session.prime_frontend_geometry(size()),+ "every visible row is a Line now"+ );+ }++ /// R5: a poll completing after the pane is gone still clears the+ /// latch it shares with the task, generation-checked.+ #[test]+ fn a_poll_answered_after_the_pane_is_gone_still_clears_its_latch() {+ let (host, session) = session(&[]);+ // past the poll interval, so changed_since polls; the task is queued, not run+ host.clock.0.set(1_000_000);+ let _ = session.changed_since(0..1, SEQ_ZERO);+ let latch = Arc::clone(&session.state().poll_in_flight);+ assert_ne!(latch.load(Ordering::SeqCst), 0, "a poll is in flight");+ drop(session);+ host.spawner.run_all();+ assert_eq!(+ latch.load(Ordering::SeqCst),+ 0,+ "cleared before the upgrade failed"+ );+ }++ /// R6: fetches discarded because the epoch moved notify once per+ /// epoch, not once per fetch and not never.+ #[test]+ fn discarded_fetches_notify_once_per_epoch() {+ let (host, session) = session(&[(0, "a"), (1, "b")]);+ let mut size = size();+ for epoch in 1..=2u64 {+ // two fetches queued for this epoch, neither run yet+ let _ = session.get_lines(0..1);+ let _ = session.get_lines(1..2);+ // the epoch moves under them+ size.cols += 1;+ assert!(session.apply_local_resize(size));+ assert_eq!(session.state().line_cache_epoch, epoch);+ host.spawner.run_all();+ assert_eq!(+ host.events.outputs.get(),+ epoch as u32,+ "exactly one repaint per epoch of discards"+ );+ }+ }++ /// S12: the screen switch, the mouse grab and the cache flush land in+ /// the same locked update.+ #[test]+ fn a_delta_switching_screens_flushes_the_cache_in_the_same_update() {+ let (host, session) = session(&[(0, "a")]);+ let _ = session.get_lines(0..1);+ host.spawner.run_all();+ let epoch_before = session.state().line_cache_epoch;+ session.queue_render_delta(delta(3, true, true));+ host.spawner.run_all();+ assert!(session.is_alt_screen());+ assert!(session.is_mouse_grabbed());+ assert_eq!(session.current_seqno(), 3);+ assert!(+ session.state().line_cache_epoch > epoch_before,+ "the other screen's rows are stale"+ );+ }++ /// The input path: queue, drain through the link in order, settle.+ #[test]+ fn queued_input_leaves_in_order_and_settles() {+ let (host, session) = session(&[]);+ assert!(+ session.write_bytes(b"ni").unwrap(),+ "the first input starts the drain"+ );+ assert!(+ !session.write_bytes(b"hao").unwrap(),+ "the second rides along"+ );+ assert!(!session+ .key_down(+ InputSerial::from_millis(1),+ KeyCode::Enter,+ KeyModifiers::NONE+ )+ .unwrap());+ spin_on(Arc::clone(&session).drain_inputs());+ assert_eq!(*host.link.asked.borrow(), ["WriteToPane", "SendKeyDown"]);+ assert!(+ session.write_bytes(b"x").unwrap(),+ "drained: the next input starts a new drain"+ );+ }+}diff --git a/thinkterm-session/src/pane_state.rs b/thinkterm-session/src/pane_state.rsnew file mode 100644index 00000000..a8f0fc9e--- /dev/null+++ b/thinkterm-session/src/pane_state.rs@@ -0,0 +1,482 @@+//! What a client knows about one remote pane: the rows it holds and their+//! fetch state, the cursor, the geometry the server confirmed and the+//! geometry being shown, and the timing that drives polls, fetch stalls+//! and predictive echo. Pure over the host's `Timestamp`; the session in+//! `pane.rs` does the talking.+use crate::clock::{RateLimiter, Timestamp};+use crate::lines::*;+use crate::SessionConfig;+use codec::InputSerial;+use lru::LruCache;+use std::num::NonZeroUsize;+use std::sync::atomic::AtomicU64;+use std::sync::Arc;+use std::time::Duration;+use termwiz::cell::{Cell, CellAttributes, Underline};+use termwiz::input::KeyboardEncoding;+use termwiz::surface::{SequenceNo, SEQ_ZERO};+use thinkterm_proto::{RenderableDimensions, StableCursorPosition};+use url::Url;+use wezterm_term::{KeyCode, KeyModifiers, Line, StableRowIndex, TerminalSize};++pub struct PaneState {+ pub(crate) config: SessionConfig,+ pub(crate) last_poll: Timestamp,+ pub(crate) dead: bool,+ /// Generation of the poll currently in flight; 0 means none. Shared+ /// with the poll task so completion can clear it without finding this+ /// pane again (a pane that left the mux must not stay latched), and+ /// generation-checked so a watchdog-superseded poll completing late+ /// can neither clear its successor's latch nor apply a stale answer.+ pub(crate) poll_in_flight: Arc<AtomicU64>,+ pub(crate) poll_gen: u64,+ pub(crate) poll_stall_attempt: u32,+ pub(crate) poll_interval: Duration,++ pub(crate) cursor_position: StableCursorPosition,+ /// Whether the remote pane showed its alternate screen at the last+ /// push. The two screens share one stable-row space on the wire, so a+ /// switch changes what every cached row means without any row being+ /// resent: the cache is cleared on the switch.+ pub(crate) alt_screen: bool,+ pub(crate) mouse_grabbed: bool,+ pub(crate) keyboard_encoding: KeyboardEncoding,+ pub(crate) dimensions: RenderableDimensions,+ /// The dimensions most recently confirmed by the remote pane. A GUI+ /// takeover may resize its local surface optimistically; keeping the+ /// server value separate lets it remain masked until a post-resize render+ /// snapshot has actually arrived.+ pub(crate) server_dimensions: RenderableDimensions,+ /// While a native GUI divider is moving, this is the authoritative render+ /// surface. Remote snapshots continue updating `server_dimensions` and+ /// line contents, but cannot bounce the visible surface back to an older+ /// grid between mouse-move frames.+ pub(crate) frontend_preview: Option<FrontendPreviewGeometry>,++ pub(crate) lines: LruCache<StableRowIndex, LineEntry>,+ pub(crate) line_cache_epoch: u64,+ /// The epoch for which a discarded-fetch PaneOutput has already been+ /// emitted; during a live resize every frame bumps the epoch and can+ /// discard several in-flight fetches, and one repaint per epoch is+ /// enough to re-issue them.+ pub(crate) epoch_discard_notified: u64,+ pub(crate) title: String,+ pub(crate) working_dir: Option<Url>,+ pub(crate) seqno: SequenceNo,++ pub(crate) fetch_limiter: RateLimiter,++ pub(crate) last_send_time: Timestamp,+ pub(crate) last_recv_time: Timestamp,+ pub(crate) last_late_dirty: Timestamp,+ pub(crate) last_input_rtt: u64,++ pub(crate) input_serial: InputSerial,+}++impl PaneState {+ #[allow(clippy::too_many_arguments)]+ pub fn new(+ config: SessionConfig,+ dimensions: RenderableDimensions,+ title: &str,+ alt_screen: bool,+ fetch_rate_per_second: u32,+ now: Timestamp,+ ) -> Self {+ Self {+ config,+ last_poll: now,+ dead: false,+ poll_in_flight: Arc::new(AtomicU64::new(0)),+ poll_gen: 0,+ poll_stall_attempt: 0,+ poll_interval: BASE_POLL_INTERVAL,+ cursor_position: StableCursorPosition::default(),+ dimensions,+ alt_screen,+ mouse_grabbed: false,+ keyboard_encoding: KeyboardEncoding::Xterm,+ server_dimensions: dimensions,+ frontend_preview: None,+ lines: LruCache::new(NonZeroUsize::new(config.scrollback_lines.max(128)).unwrap()),+ line_cache_epoch: 0,+ epoch_discard_notified: 0,+ title: title.to_string(),+ working_dir: None,+ fetch_limiter: RateLimiter::new(fetch_rate_per_second, now),+ last_send_time: now,+ last_recv_time: now,+ last_late_dirty: now,+ last_input_rtt: 0,+ input_serial: InputSerial::empty(),+ seqno: SEQ_ZERO,+ }+ }++ /// How long since the server was last heard from for this pane.+ pub fn since_last_response(&self, now: Timestamp) -> Duration {+ now.saturating_duration_since(self.last_recv_time)+ }++ /// Returns true if we think we should display the laggy connection+ /// indicator. If we're past our poll interval and more recently+ /// tried to send something than receive something, the UI is worth+ /// showing.+ pub fn is_tardy(&self, now: Timestamp) -> bool {+ let elapsed = self.since_last_response(now);+ if elapsed > self.poll_interval.max(Duration::from_secs(3)) {+ self.last_send_time > self.last_recv_time+ } else {+ false+ }+ }++ /// Predictive echo can be noisy when the link is working well,+ /// so we only employ it when it looks like the latency is high.+ fn should_predict(&self) -> bool {+ self.config+ .local_echo_threshold_ms+ .map(|thresh| self.last_input_rtt >= thresh)+ .unwrap_or(false)+ }++ /// Compute a "prediction" and apply it to the line data that we+ /// have available, marking it as dirty so that it gets rendered.+ /// The prediction is basically just local echo.+ /// Open questions:+ /// how do we tell if the intent is to suppress local echo during eg:+ /// * password prompt? One option is to look back and see if the line+ /// looks like a password prompt.+ /// * normal mode in vim: letter presses are typically movement or+ /// other editor commands+ /// There are bound to be a number of other edge cases that we should+ /// handle.+ fn apply_prediction(&mut self, c: KeyCode, line: &mut Line) {+ let text = line.as_str();+ if text.contains("sword") {+ // This line might be a password prompt. Don't force+ // on local echo here, as we don't want to reveal content+ // from their password+ return;+ }++ match c {+ KeyCode::Enter => {+ self.cursor_position.x = 0;+ self.cursor_position.y += 1;+ }+ KeyCode::UpArrow => {+ self.cursor_position.y = self.cursor_position.y.saturating_sub(1);+ }+ KeyCode::DownArrow => {+ self.cursor_position.y += 1;+ }+ KeyCode::RightArrow => {+ self.cursor_position.x += 1;+ }+ KeyCode::LeftArrow => {+ self.cursor_position.x = self.cursor_position.x.saturating_sub(1);+ }+ KeyCode::Delete => {+ line.erase_cell(self.cursor_position.x, SEQ_ZERO);+ }+ KeyCode::Backspace => {+ if self.cursor_position.x > 0 {+ line.erase_cell(self.cursor_position.x - 1, SEQ_ZERO);+ self.cursor_position.x -= 1;+ }+ }+ KeyCode::Char(c) => {+ let cell = Cell::new(+ c,+ CellAttributes::default()+ .set_underline(Underline::Double)+ .clone(),+ );++ let width = cell.width();+ line.set_cell(self.cursor_position.x, cell, SEQ_ZERO);+ // Adjust the cursor to reflect the width of this new cell+ self.cursor_position.x += width;+ }+ _ => {}+ }+ }++ /// Based on a keypress, apply a "prediction" of what the terminal+ /// content will look like once we receive the response from the+ /// remote system. The prediction helps to reduce perceived latency+ /// when a user is typing at any reasonable velocity.+ pub fn predict_from_key_event(&mut self, key: KeyCode, mods: KeyModifiers) {+ if !self.should_predict() {+ return;+ }++ let c = match key {+ KeyCode::LeftArrow+ | KeyCode::RightArrow+ | KeyCode::UpArrow+ | KeyCode::DownArrow+ | KeyCode::Delete+ | KeyCode::Backspace+ | KeyCode::Enter+ | KeyCode::Char(_) => key,+ _ => return,+ };+ if mods != KeyModifiers::NONE && mods != KeyModifiers::SHIFT {+ return;+ }++ let row = self.cursor_position.y;+ match self.lines.pop(&row) {+ // A Stale row stays Stale: promoting it to Line would cancel+ // the pending re-fetch (its seqno can never satisfy+ // changed_since again) and freeze the row on predicted text.+ Some(LineEntry::Stale(mut line)) => {+ self.apply_prediction(c, &mut line);+ self.lines.put(row, LineEntry::Stale(line));+ }+ Some(LineEntry::Line(mut line)) => {+ self.apply_prediction(c, &mut line);+ self.lines.put(row, LineEntry::Line(line));+ }+ Some(LineEntry::LineAndFetching(mut line, instant)) => {+ self.apply_prediction(c, &mut line);+ self.lines+ .put(row, LineEntry::LineAndFetching(line, instant));+ }+ Some(entry) => {+ self.lines.put(row, entry);+ }+ None => {}+ }+ }++ fn apply_paste_prediction(&mut self, row: usize, text: &str, line: &mut Line) {+ let attrs = CellAttributes::default()+ .set_underline(Underline::Double)+ .clone();++ let text_line = Line::from_text(text, &attrs, SEQ_ZERO, None);++ if row == 0 {+ for cell in text_line.visible_cells() {+ line.set_cell(self.cursor_position.x, cell.as_cell(), SEQ_ZERO);+ self.cursor_position.x += cell.width();+ }+ } else {+ // The pasted line replaces the data for the existing line+ line.resize_and_clear(0, SEQ_ZERO, CellAttributes::default());+ line.append_line(text_line, SEQ_ZERO);+ self.cursor_position.x = line.len();+ }+ }++ pub fn predict_from_paste(&mut self, text: &str) {+ if !self.should_predict() {+ return;+ }++ let text = textwrap::fill(text, self.dimensions.cols);+ let lines: Vec<&str> = text.split("\n").collect();++ for (idx, paste_line) in lines.iter().enumerate() {+ let row = self.cursor_position.y + idx as StableRowIndex;++ match self.lines.pop(&row) {+ // Stale stays Stale; see predict_from_key_event.+ Some(LineEntry::Stale(mut line)) => {+ self.apply_paste_prediction(idx, paste_line, &mut line);+ self.lines.put(row, LineEntry::Stale(line));+ }+ Some(LineEntry::Line(mut line)) => {+ self.apply_paste_prediction(idx, paste_line, &mut line);+ self.lines.put(row, LineEntry::Line(line));+ }+ Some(LineEntry::LineAndFetching(mut line, instant)) => {+ self.apply_paste_prediction(idx, paste_line, &mut line);+ self.lines+ .put(row, LineEntry::LineAndFetching(line, instant));+ }+ Some(entry) => {+ self.lines.put(row, entry);+ }+ None => {}+ }+ }+ self.cursor_position.y += lines.len().saturating_sub(1) as StableRowIndex;+ }++ pub fn update_last_send(&mut self, now: Timestamp) {+ self.last_send_time = now;+ self.poll_interval = BASE_POLL_INTERVAL;+ }++ pub fn make_all_stale(&mut self) {+ self.invalidate_line_cache(true);+ }++ pub(crate) fn fetch_token(&self, started_at: Timestamp) -> FetchToken {+ FetchToken::new(self.line_cache_epoch, started_at)+ }++ pub(crate) fn invalidate_line_cache(&mut self, preserve_lines: bool) {+ self.line_cache_epoch = self.line_cache_epoch.wrapping_add(1);+ invalidate_line_entries(&mut self.lines, preserve_lines);+ }++ /// Converge the locally rendered surface to the geometry requested by the+ /// GUI. This is deliberately separate from deciding whether a Resize RPC+ /// is needed: a delayed server update can temporarily restore old+ /// dimensions after the desired size was already requested.+ pub fn apply_local_resize(&mut self, size: TerminalSize) -> bool {+ if self.dimensions.cols == size.cols+ && self.dimensions.viewport_rows == size.rows+ && self.dimensions.pixel_width == size.pixel_width+ && self.dimensions.pixel_height == size.pixel_height+ && self.dimensions.dpi == size.dpi+ {+ return false;+ }++ let width_changed = self.dimensions.cols != size.cols;+ self.dimensions.cols = size.cols;+ self.dimensions.viewport_rows = size.rows;+ self.dimensions.pixel_width = size.pixel_width;+ self.dimensions.pixel_height = size.pixel_height;+ self.dimensions.dpi = size.dpi;+ // Keep showing the old rows while the refetch is in flight, exactly+ // as the LiveResize preview does: dropping them here painted the+ // whole pane blank for a server round trip every time chrome (the+ // sidebars) changed the terminal's width. A width change normalizes+ // the retained cell storage so an old-width row can never be+ // interpreted as already matching the new grid.+ self.line_cache_epoch = self.line_cache_epoch.wrapping_add(1);+ if width_changed {+ resize_stale_line_entries(&mut self.lines, size.cols);+ } else {+ invalidate_line_entries(&mut self.lines, true);+ }+ true+ }++ pub fn begin_frontend_preview(+ &mut self,+ epoch: u64,+ size: TerminalSize,+ policy: FrontendPreviewPolicy,+ ) -> bool {+ if self+ .frontend_preview+ .is_some_and(|preview| preview.epoch > epoch)+ {+ return false;+ }+ self.frontend_preview = Some(FrontendPreviewGeometry {+ epoch,+ size,+ policy,+ });+ if render_dimensions_match_terminal_size(self.dimensions, size) {+ return false;+ }+ let width_changed = self.dimensions.cols != size.cols;+ self.dimensions.cols = size.cols;+ self.dimensions.viewport_rows = size.rows;+ self.dimensions.pixel_width = size.pixel_width;+ self.dimensions.pixel_height = size.pixel_height;+ self.dimensions.dpi = size.dpi;+ if policy == FrontendPreviewPolicy::LiveResize {+ self.line_cache_epoch = self.line_cache_epoch.wrapping_add(1);+ if width_changed {+ resize_stale_line_entries(&mut self.lines, size.cols);+ } else {+ invalidate_line_entries(&mut self.lines, true);+ }+ }+ true+ }++ pub fn server_geometry_matches(&self, size: TerminalSize) -> bool {+ render_dimensions_match_terminal_size(self.server_dimensions, size)+ }++ pub fn end_frontend_preview(&mut self, epoch: u64, succeeded: bool) -> bool {+ let Some(preview) = self.frontend_preview else {+ return false;+ };+ if preview.epoch != epoch {+ return false;+ }+ self.frontend_preview = None;+ if succeeded && self.server_geometry_matches(preview.size) {+ self.dimensions = self.server_dimensions;+ return true;+ }+ if !succeeded && render_geometry_changed(self.dimensions, self.server_dimensions) {+ let preserve_lines = self.dimensions.cols == self.server_dimensions.cols;+ self.dimensions = self.server_dimensions;+ self.invalidate_line_cache(preserve_lines);+ }+ true+ }++ pub(crate) fn make_stale(&mut self, stable_row: StableRowIndex) {+ match self.lines.pop(&stable_row) {+ Some(LineEntry::Stale(old))+ | Some(LineEntry::Line(old))+ | Some(LineEntry::LineAndFetching(old, _)) => {+ self.lines.put(stable_row, LineEntry::Stale(old));+ }+ Some(LineEntry::Fetching(_)) | None => {}+ }+ }++ pub(crate) fn put_line(+ &mut self,+ stable_row: StableRowIndex,+ mut line: Line,+ rules: &[termwiz::hyperlink::Rule],+ fetch_token: Option<FetchToken>,+ ) {+ line.scan_and_create_hyperlinks(rules);++ let entry = if let Some(fetch_token) = fetch_token {+ // If we're completing a fetch, only replace entries that were+ // set to fetching as part of our fetch. If they are now longer+ // tagged that way, then someone came along after us and changed+ // the state, so we should leave it alone++ match self.lines.pop(&stable_row) {+ Some(LineEntry::LineAndFetching(_, then)) | Some(LineEntry::Fetching(then))+ if fetch_token == then =>+ {+ log::trace!(+ "row {} fetch done -> Line seq={} vs self.seq={}",+ stable_row,+ line.current_seqno(),+ self.seqno+ );+ line.update_last_change_seqno(self.seqno);+ LineEntry::Line(line)+ }+ Some(e) => {+ // It changed since we started: leave it alone!+ log::trace!(+ "row {} {:?} changed since fetch started at {:?}, so leave it be",+ stable_row,+ e.kind(),+ fetch_token+ );+ self.lines.put(stable_row, e);+ return;+ }+ None => return,+ }+ } else {+ LineEntry::Line(line)+ };+ self.lines.put(stable_row, entry);+ }+}