Skip to content

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

wezterm-client: become an adapter over thinkterm-session

RoversX145f73fc4da5
diff --git a/Cargo.lock b/Cargo.lock
index 0b668a99..a8217f53 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7855,7 +7855,6 @@ dependencies = [
"lazy_static",
"libc",
"log",
- "lru",
"metrics",
"mux",
"openssl",
@@ -7863,12 +7862,11 @@ dependencies = [
"portable-pty",
"promise",
"rangeset",
- "ratelim",
"smol",
"tempfile",
"termwiz 0.24.0",
- "textwrap",
"thinkterm-proto",
+ "thinkterm-session",
"thinkterm-update",
"thiserror 1.0.69",
"umask",
diff --git a/thinkterm-tui/src/lib.rs b/thinkterm-tui/src/lib.rs
index 8db0a8cb..0354defd 100644
--- a/thinkterm-tui/src/lib.rs
+++ b/thinkterm-tui/src/lib.rs
@@ -60,7 +60,7 @@ const RESIZE_SETTLE: Duration = Duration::from_millis(150);
/// How often to ask the panes for new content when nothing has asked to draw.
///
/// A remote pane only asks the server from inside `get_changed_since`, and
-/// `RenderableInner::poll` doubles its own interval every time it runs — up to
+/// the session's poll doubles its own interval every time it runs — up to
/// half a minute — resetting only when a response lands. Until now the only
/// caller was `paint_pane`, so a renderer that draws strictly on demand stopped
/// asking, and the screen sat still until something was tapped.
diff --git a/wezterm-client/Cargo.toml b/wezterm-client/Cargo.toml
index f11690cb..6020aac3 100644
--- a/wezterm-client/Cargo.toml
+++ b/wezterm-client/Cargo.toml
@@ -19,7 +19,6 @@ futures.workspace = true
lazy_static.workspace = true
libc.workspace = true
log.workspace = true
-lru.workspace = true
metrics.workspace = true
mux.workspace = true
openssl.workspace = true
@@ -27,11 +26,10 @@ parking_lot.workspace = true
portable-pty = { workspace=true, features = ["serde_support"]}
promise.workspace = true
rangeset.workspace = true
-ratelim.workspace = true
smol.workspace = true
termwiz.workspace = true
-textwrap.workspace = true
thinkterm-proto.workspace = true
+thinkterm-session.workspace = true
thinkterm-update.workspace = true
thiserror.workspace = true
umask.workspace = true
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index e1e8380d..00c2a5fb 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -35,19 +35,22 @@ use std::sync::mpsc::channel;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::Duration;
+use thinkterm_session::connection::{
+ describe_handshake_failure, describe_server_build_mismatch, leads_back_to_this_process,
+ ChannelSendError, RegistrationBarrier,
+};
use thiserror::Error;
use wezterm_uds::UnixStream;
+pub use thinkterm_session::connection::ConnectionPhase as ClientConnectionPhase;
+pub use thinkterm_session::connection::VersionHandshakeStalled;
+
static NEXT_CONNECTION_GENERATION: AtomicU64 = AtomicU64::new(1);
#[derive(Error, Debug)]
#[error("Timeout")]
struct Timeout;
-#[derive(Error, Debug)]
-#[error("ChannelSendError")]
-struct ChannelSendError;
-
enum ReaderMessage {
SendPdu {
pdu: Pdu,
@@ -72,38 +75,6 @@ enum ReaderMessage {
KeepaliveTick,
}
-struct RegistrationBarrier<T> {
- complete: bool,
- deferred: VecDeque<T>,
-}
-
-impl<T> RegistrationBarrier<T> {
- fn new() -> Self {
- Self {
- complete: false,
- deferred: VecDeque::new(),
- }
- }
-
- 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)
- }
- }
-
- fn complete(&mut self) -> VecDeque<T> {
- self.complete = true;
- std::mem::take(&mut self.deferred)
- }
-
- fn drain(&mut self) -> VecDeque<T> {
- std::mem::take(&mut self.deferred)
- }
-}
-
struct PduRegistrationBarrier {
inner: RegistrationBarrier<(Pdu, Sender<anyhow::Result<Pdu>>)>,
}
@@ -128,7 +99,7 @@ impl PduRegistrationBarrier {
}
fn is_complete(&self) -> bool {
- self.inner.complete
+ self.inner.is_complete()
}
fn fail_deferred(&mut self, reason: &str) {
@@ -144,32 +115,6 @@ impl Drop for PduRegistrationBarrier {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-#[repr(u8)]
-pub enum ClientConnectionPhase {
- Connecting = 0,
- Registering = 1,
- Syncing = 2,
- Ready = 3,
- Reconnecting = 4,
- Suspended = 5,
- Detached = 6,
-}
-
-impl ClientConnectionPhase {
- 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,
- }
- }
-}
-
#[derive(Clone)]
pub struct Client {
sender: Sender<ReaderMessage>,
@@ -280,77 +225,6 @@ pub struct IncompatibleVersionError {
pub codec_vers: usize,
}
-/// 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.
-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(crate) 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."
- ))
-}
-
macro_rules! rpc {
($method_name:ident, $request_type:ident, $response_type:ident) => {
pub async fn $method_name(&self, pdu: $request_type) -> anyhow::Result<$response_type> {
@@ -771,11 +645,6 @@ fn process_unilateral(
Ok(())
}
-/// Whether the server answering the handshake is the process asking.
-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)
-}
-
#[derive(Error, Debug, Clone, PartialEq, Eq)]
enum NotReconnectableError {
#[error("Client was destroyed")]
@@ -2469,9 +2338,7 @@ impl Client {
#[cfg(test)]
mod tests {
- use super::{
- describe_server_build_mismatch, is_auth_cancelled, Reconnectable, RegistrationBarrier,
- };
+ use super::{is_auth_cancelled, Reconnectable};
use crate::domain::ClientDomainConfig;
#[test]
@@ -2497,43 +2364,6 @@ mod tests {
assert!(host.is_local_session_host());
}
- #[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"));
- }
-
#[test]
fn auth_cancellation_survives_being_wrapped_in_context() {
// The reconnect loop parks instead of retrying when it sees this, so
@@ -2568,40 +2398,3 @@ mod tests {
assert!(cmd.contains("wezterm cli --prefer-mux proxy"), "{}", cmd);
}
}
-
-#[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/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index 73849e2a..12e02bc0 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -1,16 +1,11 @@
use crate::domain::ClientInner;
-use crate::pane::mousestate;
-use crate::pane::renderable::{
- hydrate_lines, FrontendPreviewPolicy, RenderableInner, RenderableState,
-};
+use crate::pane::events::DesktopHost;
use anyhow::bail;
use async_trait::async_trait;
use codec::*;
use config::configuration;
use config::keyassignment::ScrollbackEraseMode;
-use futures::future::{BoxFuture, FutureExt};
use futures::lock::Mutex as AsyncMutex;
-use futures::stream::{FuturesUnordered, StreamExt};
use mux::domain::DomainId;
use mux::pane::{
alloc_pane_id, CachePolicy, CloseReason, ForEachPaneLogicalLine, LogicalLine, Pane, PaneId,
@@ -18,17 +13,26 @@ use mux::pane::{
};
use mux::renderable::{RenderableDimensions, StableCursorPosition};
use mux::tab::TabId;
-use mux::{Mux, MuxNotification};
+use mux::Mux;
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
use rangeset::RangeSet;
-use ratelim::RateLimiter;
-use std::cell::RefCell;
-use std::collections::{BTreeMap, HashMap, VecDeque};
+use std::collections::{BTreeMap, HashMap};
use std::ops::Range;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
-use termwiz::input::{KeyEvent, KeyboardEncoding};
+use termwiz::input::KeyboardEncoding;
use termwiz::surface::SequenceNo;
+use thinkterm_session::clock::Clock;
+use thinkterm_session::decide::{
+ application_palette_transition, decide_resize_for_viewport, finish_preview_request,
+ next_requested_size, remote_server_identity_matches, PaletteDelivery,
+};
+use thinkterm_session::host::{SessionEvents, SessionHost};
+use thinkterm_session::input::PaneInput;
+use thinkterm_session::lines::FrontendPreviewPolicy;
+use thinkterm_session::mouse;
+use thinkterm_session::pane::PaneSession;
+use thinkterm_session::SessionConfig;
use url::Url;
use wezterm_dynamic::Value;
use wezterm_term::color::ColorPalette;
@@ -37,183 +41,6 @@ use wezterm_term::{
TerminalConfiguration, TerminalSize,
};
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-struct ResizeDecision {
- converge_local_surface: bool,
- send_rpc: bool,
-}
-
-fn render_watchdog_should_run(dead: bool) -> bool {
- !dead
-}
-
-#[derive(Debug, PartialEq)]
-struct ApplicationPaletteTransition {
- palette: ColorPalette,
- application_palette: bool,
- palette_changed: bool,
- provenance_changed: bool,
-}
-
-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,
- }
-}
-
-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
-}
-
-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,
- }
-}
-
-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.
-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)]
-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.
- 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.
- 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
- }
- }
- }
-
- 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.
- 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.
- fn invalidate_delivery(&mut self) {
- self.delivered = None;
- }
-}
-
-pub(crate) fn remote_server_identity_matches(created: Option<&str>, current: Option<&str>) -> bool {
- created == current
-}
-
pub struct ClientPane {
client: Arc<ClientInner>,
/// The mux runtime that allocated `remote_pane_id`.
@@ -226,7 +53,6 @@ pub struct ClientPane {
local_pane_id: PaneId,
pub remote_pane_id: PaneId,
remote_tab_id: Arc<AtomicUsize>,
- pub renderable: Mutex<RenderableState>,
configured_palette: Arc<Mutex<ColorPalette>>,
/// Delivery state for the palette advisory: what we want the server to
/// hold and what it last confirmed. A single worker task drains it; see
@@ -239,18 +65,12 @@ pub struct ClientPane {
palette: Mutex<ColorPalette>,
application_palette: Mutex<bool>,
writer: Mutex<PaneWriter>,
- /// Everything this pane was given and the server has not answered,
- /// in the order it was given; see [`PaneInput`].
- inputs: Arc<Mutex<InputQueue>>,
+ /// This process as the session sees it: the mux, the clocks, the
+ /// connection.
+ host: Arc<DesktopHost>,
+ /// The mirrored pane itself: rows, cursor, geometry, pushes, fetches.
+ session: Arc<PaneSession<DesktopHost>>,
clipboard: Mutex<Option<Arc<dyn Clipboard>>>,
- mouse_grabbed: Mutex<bool>,
- alt_screen: Mutex<bool>,
- /// As last reported by the server. The GUI's key encoders consult it
- /// before every key: a pane left at Xterm never gets kitty-protocol or
- /// win32-input-mode bytes, whatever the remote program asked for.
- keyboard_encoding: Mutex<KeyboardEncoding>,
- /// Render pushes waiting to be applied, in the order they arrived.
- render_deltas: Mutex<RenderDeltaQueue>,
requested_size: Mutex<Option<TerminalSize>>,
ignore_next_kill: Mutex<bool>,
user_vars: Mutex<HashMap<String, String>>,
@@ -370,36 +190,37 @@ impl ClientPane {
) -> Self {
let local_pane_id = alloc_pane_id();
let remote_tab_id = Arc::new(AtomicUsize::new(remote_tab_id));
- let inputs: Arc<Mutex<InputQueue>> = Default::default();
+
+ let session_config = SessionConfig {
+ scrollback_lines: configuration().scrollback_lines,
+ local_echo_threshold_ms: client.local_echo_threshold_ms,
+ overlay_lag_indicator: client.overlay_lag_indicator,
+ };
+ let host = Arc::new(DesktopHost::new(Arc::clone(client)));
+ let session = PaneSession::new(
+ Arc::clone(&host),
+ crate::pane::events::shared_image_store(),
+ session_config,
+ remote_pane_id,
+ Arc::clone(&remote_tab_id),
+ local_pane_id,
+ RenderableDimensions {
+ cols: size.cols as _,
+ viewport_rows: size.rows as _,
+ scrollback_rows: size.rows as _,
+ physical_top: 0,
+ scrollback_top: 0,
+ dpi: size.dpi,
+ pixel_width: size.pixel_width,
+ pixel_height: size.pixel_height,
+ reverse_video: false,
+ },
+ title,
+ alt_screen,
+ );
let writer = PaneWriter {
client: Arc::clone(client),
- remote_pane_id,
- remote_tab_id: Arc::clone(&remote_tab_id),
- inputs: Arc::clone(&inputs),
- };
-
- let fetch_limiter =
- RateLimiter::new(|config| config.ratelimit_mux_line_prefetches_per_second);
-
- let render = RenderableState {
- inner: RefCell::new(RenderableInner::new(
- client,
- remote_pane_id,
- local_pane_id,
- RenderableDimensions {
- cols: size.cols as _,
- viewport_rows: size.rows as _,
- scrollback_rows: size.rows as _,
- physical_top: 0,
- scrollback_top: 0,
- dpi: size.dpi,
- pixel_width: size.pixel_width,
- pixel_height: size.pixel_height,
- reverse_video: false,
- },
- title,
- fetch_limiter,
- )),
+ session: Arc::clone(&session),
};
let config = configuration();
@@ -423,22 +244,18 @@ impl ClientPane {
Self {
client: Arc::clone(client),
remote_server_id: client.client.remote_server_id(),
- inputs,
+ host,
+ session,
remote_pane_id,
local_pane_id,
remote_tab_id,
application_palette: Mutex::new(false),
- renderable: Mutex::new(render),
writer: Mutex::new(writer),
configured_palette: Arc::new(Mutex::new(palette.clone())),
delivered_palette,
palette_rpc_lock,
palette: Mutex::new(palette),
clipboard: Mutex::new(None),
- mouse_grabbed: Mutex::new(false),
- alt_screen: Mutex::new(alt_screen),
- keyboard_encoding: Mutex::new(KeyboardEncoding::Xterm),
- render_deltas: Mutex::new(RenderDeltaQueue::default()),
requested_size: Mutex::new(Some(size)),
ignore_next_kill: Mutex::new(false),
unseen_output: Mutex::new(false),
@@ -453,39 +270,6 @@ impl ClientPane {
}
}
- /// 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,
- mut delta: GetPaneRenderChangesResponse,
- carried: Option<RowsCarried>,
- ) {
- *self.mouse_grabbed.lock() = delta.mouse_grabbed;
- *self.alt_screen.lock() = delta.alt_screen;
- *self.keyboard_encoding.lock() = delta.keyboard_encoding.into();
-
- let bonus_lines = std::mem::take(&mut delta.bonus_lines);
- let client = { Arc::clone(&self.renderable.lock().inner.borrow().client) };
- let (bonus_lines, left_out) =
- hydrate_lines(client, 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);
- }
- }
- }
-
- self.renderable
- .lock()
- .inner
- .borrow_mut()
- .apply_changes_to_surface(delta, bonus_lines);
- }
-
pub async fn process_unilateral(&self, pdu: Pdu) -> anyhow::Result<()> {
match pdu {
Pdu::GetPaneRenderChangesResponse(delta) => {
@@ -496,10 +280,7 @@ impl ClientPane {
// push could land after a newer one and roll the rows back,
// and a program streaming pictures had every push fetching
// a frame that was already stale.
- if self.render_deltas.lock().push(delta) {
- let local_pane_id = self.local_pane_id;
- promise::spawn::spawn(drain_render_deltas(local_pane_id)).detach();
- }
+ self.session.queue_render_delta(delta);
}
Pdu::SetClipboard(SetClipboard {
clipboard,
@@ -534,46 +315,38 @@ impl ClientPane {
*self.application_palette.lock() = transition.application_palette;
if transition.palette_changed {
*self.palette.lock() = transition.palette;
- self.renderable.lock().inner.borrow_mut().make_all_stale();
+ self.session.make_all_stale();
}
// Provenance changes must propagate through chained muxes even
// when the effective colors happen to be identical. Only an
// actual color change invalidates the render surface above.
if transition.palette_changed || transition.provenance_changed {
- let mux = Mux::get();
- mux.notify(MuxNotification::Alert {
- pane_id: self.local_pane_id,
- alert: Alert::PaletteChanged,
- });
+ self.host
+ .events()
+ .alert(self.local_pane_id, Alert::PaletteChanged);
}
}
Pdu::NotifyAlert(NotifyAlert { alert, .. }) => {
- let mux = Mux::get();
match &alert {
Alert::SetUserVar { name, value } => {
self.user_vars.lock().insert(name.clone(), value.clone());
}
Alert::OutputSinceFocusLost => {
*self.unseen_output.lock() = true;
- mux.notify(MuxNotification::Alert {
- pane_id: self.local_pane_id,
- alert: Alert::OutputSinceFocusLost,
- });
+ self.host
+ .events()
+ .alert(self.local_pane_id, Alert::OutputSinceFocusLost);
}
Alert::Progress(progress) => {
*self.progress.lock() = progress.clone();
- mux.notify(MuxNotification::Alert {
- pane_id: self.local_pane_id,
- alert: Alert::Progress(progress.clone()),
- });
+ self.host
+ .events()
+ .alert(self.local_pane_id, Alert::Progress(progress.clone()));
}
_ => {}
}
- mux.notify(MuxNotification::Alert {
- pane_id: self.local_pane_id,
- alert,
- });
+ self.host.events().alert(self.local_pane_id, alert);
}
Pdu::AgentStatusChanged(codec::AgentStatusChanged { status, .. }) => {
// Read-at-send-time coalescing means a backlog of queued
@@ -594,20 +367,17 @@ impl ClientPane {
// process is itself a mux server for further clients,
// its dispatch forwards the status one hop on (same
// reason the Progress alert above re-notifies).
- Mux::get().notify(MuxNotification::AgentStatusChanged(self.local_pane_id));
+ self.host.events().agent_status_changed(self.local_pane_id);
}
}
Pdu::PaneRemoved(PaneRemoved { pane_id }) => {
log::trace!("remote pane {} has been removed", pane_id);
- self.renderable.lock().inner.borrow_mut().dead = true;
+ self.session.set_dead(true);
// The prune below can be deferred (activity in flight, or
// the windows lock contended); the dead mirror must not
// keep reporting an agent to the panel meanwhile.
*self.agent_status.lock() = None;
- let mux = Mux::get();
- mux.prune_dead_windows();
-
- self.client.expire_stale_mappings();
+ self.host.events().pane_removed(self.local_pane_id);
}
Pdu::PaneFocused(PaneFocused { pane_id }) => {
// We get here whenever the pane focus is changed on the
@@ -636,17 +406,7 @@ impl ClientPane {
return Ok(());
}
log::trace!("advised of remote pane focus: {pane_id}");
-
- let mux = Mux::get();
- if let Err(err) = mux.focus_pane_and_containing_tab(self.local_pane_id) {
- log::error!("Error reconciling remote PaneFocused notification: {err:#}");
- } else if let Some((_domain, window_id, _tab)) =
- mux.resolve_pane_id(self.local_pane_id)
- {
- // The reconcile flips tab/stack selection silently (to
- // avoid focus advisory loops); nudge the GUI to repaint.
- mux.notify(MuxNotification::WindowInvalidated(window_id));
- }
+ self.host.events().pane_focused(self.local_pane_id);
}
_ => bail!("unhandled unilateral pdu: {:?}", pdu),
};
@@ -752,12 +512,7 @@ impl ClientPane {
/// poll/fetch) has no pulse of its own; the GUI's watchdog uses this to
/// restart it instead of leaving the pane frozen until user input.
pub fn render_looks_stalled(&self, viewport_top: Option<StableRowIndex>) -> bool {
- let renderable = self.renderable.lock();
- let mut inner = renderable.inner.borrow_mut();
- if !render_watchdog_should_run(inner.dead) {
- return false;
- }
- inner.watchdog_check_displayed_rows(viewport_top)
+ self.session.render_looks_stalled(viewport_top)
}
/// Adopt geometry that is carried by a complete frontend viewport RPC.
@@ -769,11 +524,9 @@ impl ClientPane {
/// following up with a duplicate per-pane Resize RPC.
pub fn adopt_frontend_geometry(&self, size: TerminalSize) -> bool {
*self.requested_size.lock() = Some(size);
- let render = self.renderable.lock();
- let mut inner = render.inner.borrow_mut();
- let changed = inner.apply_local_resize(size);
+ let changed = self.session.apply_local_resize(size);
if changed {
- inner.update_last_send();
+ self.session.update_last_send();
}
changed
}
@@ -799,21 +552,15 @@ impl ClientPane {
policy: FrontendPreviewPolicy,
) -> bool {
*self.requested_size.lock() = Some(size);
- let render = self.renderable.lock();
- let mut inner = render.inner.borrow_mut();
- let changed = inner.begin_frontend_preview(epoch, size, policy);
+ let changed = self.session.begin_frontend_preview(epoch, size, policy);
if changed {
- inner.update_last_send();
+ self.session.update_last_send();
}
changed
}
pub fn server_geometry_matches(&self, size: TerminalSize) -> bool {
- self.renderable
- .lock()
- .inner
- .borrow()
- .server_geometry_matches(size)
+ self.session.server_geometry_matches(size)
}
pub fn finish_frontend_geometry_preview(
@@ -822,19 +569,14 @@ impl ClientPane {
size: TerminalSize,
succeeded: bool,
) -> bool {
- let finished = self
- .renderable
- .lock()
- .inner
- .borrow_mut()
- .end_frontend_preview(epoch, succeeded);
+ let finished = self.session.end_frontend_preview(epoch, succeeded);
let mut requested = self.requested_size.lock();
finish_preview_request(&mut requested, size, succeeded, finished);
finished
}
pub fn is_remote_tardy(&self) -> bool {
- self.renderable.lock().inner.borrow().is_tardy()
+ self.session.is_tardy()
}
/// Forget a geometry adoption when the complete viewport RPC failed.
@@ -852,13 +594,13 @@ impl ClientPane {
/// still present, so a full-screen application cannot expose its old grid
/// or incremental redraw after the ownership RPC completes.
pub fn prime_frontend_geometry(&self, size: TerminalSize) -> bool {
- self.renderable.lock().prime_frontend_geometry(size)
+ self.session.prime_frontend_geometry(size)
}
/// Which geometry fields still block a takeover from settling, or None
/// once the server agrees. Diagnostic only; see `mux::geometrytrace`.
pub fn frontend_geometry_mismatch(&self, size: TerminalSize) -> Option<String> {
- self.renderable.lock().frontend_geometry_mismatch(size)
+ self.session.frontend_geometry_mismatch(size)
}
/// End the remote pane and wait for the mux server to acknowledge it.
@@ -882,28 +624,13 @@ impl ClientPane {
}
}
-fn finish_preview_request(
- requested: &mut Option<TerminalSize>,
- size: TerminalSize,
- succeeded: bool,
- finished: bool,
-) {
- if finished && !succeeded && requested.as_ref() == Some(&size) {
- requested.take();
- }
-}
-
impl ClientPane {
/// Queue `input` behind everything this pane was given before it.
fn queue_input(&self, input: PaneInput) -> anyhow::Result<()> {
- queue_pane_input(
- &self.client,
- self.remote_pane_id,
- &self.remote_tab_id,
- &self.inputs,
- input,
- )?;
- self.renderable.lock().inner.borrow_mut().update_last_send();
+ if self.session.queue_input(input)? {
+ start_input_drain(&self.session);
+ }
+ self.session.update_last_send();
Ok(())
}
}
@@ -915,28 +642,25 @@ impl Pane for ClientPane {
}
fn get_metadata(&self) -> Value {
- let renderable = self.renderable.lock();
- let inner = renderable.inner.borrow();
-
let mut map: BTreeMap<Value, Value> = BTreeMap::new();
map.insert(
Value::String("is_tardy".to_string()),
- Value::Bool(inner.is_tardy()),
+ Value::Bool(self.session.is_tardy()),
);
map.insert(
Value::String("since_last_response_ms".to_string()),
- Value::U64(inner.last_recv_time.elapsed().as_millis() as u64),
+ Value::U64(self.session.since_last_response().as_millis() as u64),
);
Value::Object(map.into())
}
fn get_cursor_position(&self) -> StableCursorPosition {
- self.renderable.lock().get_cursor_position()
+ self.session.cursor_position()
}
fn get_dimensions(&self) -> RenderableDimensions {
- self.renderable.lock().get_dimensions()
+ self.session.dimensions()
}
fn with_lines_mut(&self, lines: Range<StableRowIndex>, with_lines: &mut dyn WithPaneLines) {
@@ -952,7 +676,7 @@ impl Pane for ClientPane {
}
fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {
- self.renderable.lock().get_lines(lines)
+ self.session.get_lines(lines)
}
fn get_logical_lines(&self, lines: Range<StableRowIndex>) -> Vec<LogicalLine> {
@@ -960,7 +684,7 @@ impl Pane for ClientPane {
}
fn get_current_seqno(&self) -> SequenceNo {
- self.renderable.lock().get_current_seqno()
+ self.session.current_seqno()
}
fn get_changed_since(
@@ -968,7 +692,7 @@ impl Pane for ClientPane {
lines: Range<StableRowIndex>,
seqno: SequenceNo,
) -> RangeSet<StableRowIndex> {
- self.renderable.lock().get_changed_since(lines, seqno)
+ self.session.changed_since(lines, seqno)
}
fn set_clipboard(&self, clipboard: &Arc<dyn Clipboard>) {
@@ -976,9 +700,7 @@ impl Pane for ClientPane {
}
fn get_title(&self) -> String {
- let renderable = self.renderable.lock();
- let inner = renderable.inner.borrow();
- inner.title.clone()
+ self.session.title()
}
fn get_progress(&self) -> Progress {
@@ -993,13 +715,11 @@ impl Pane for ClientPane {
if self.client.remote_tab_input_is_blocked() {
return Ok(());
}
- Mux::get().record_input_for_current_identity();
- self.queue_input(PaneInput::Paste(text.to_owned()))?;
- self.renderable
- .lock()
- .inner
- .borrow_mut()
- .predict_from_paste(text);
+ self.host.events().input_recorded();
+ if self.session.paste(text)? {
+ start_input_drain(&self.session);
+ }
+ self.session.update_last_send();
Ok(())
}
@@ -1011,8 +731,8 @@ impl Pane for ClientPane {
// Kitty-protocol and win32-input-mode keys arrive here rather than
// through key_down, so this is where they count as input: for the
// client list's idle time, and for the laggy-link indicator.
- Mux::get().record_input_for_current_identity();
- self.renderable.lock().inner.borrow_mut().update_last_send();
+ self.host.events().input_recorded();
+ self.session.update_last_send();
MutexGuard::map(self.writer.lock(), |writer| {
let w: &mut dyn std::io::Write = writer;
w
@@ -1030,11 +750,9 @@ impl Pane for ClientPane {
);
return;
}
- let render = self.renderable.lock();
- let mut inner = render.inner.borrow_mut();
let client = Arc::clone(&self.client);
// Invalidate any cached rows on a resize
- inner.make_all_stale();
+ self.session.make_all_stale();
promise::spawn::spawn(async move {
// Traced separately from the send below: this await can be a full
// claim round-trip (or refuse outright) while SetClientViewport
@@ -1073,7 +791,7 @@ impl Pane for ClientPane {
Ok::<(), anyhow::Error>(())
})
.detach();
- inner.update_last_send();
+ self.session.update_last_send();
}
fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
@@ -1087,9 +805,7 @@ impl Pane for ClientPane {
// complete Native viewport carrying exact pane frames.
let mut requested = self.requested_size.lock();
let prior_requested = *requested;
- let render = self.renderable.lock();
- let mut inner = render.inner.borrow_mut();
- let advertised = inner.dimensions;
+ let advertised = self.session.dimensions();
let owns_viewport = self.client.owns_remote_viewport(self.remote_tab_id());
let decision =
decide_resize_for_viewport(owns_viewport, prior_requested, advertised, size);
@@ -1100,10 +816,10 @@ impl Pane for ClientPane {
*requested = next_requested_size(owns_viewport, prior_requested, decision, size);
if decision.converge_local_surface {
- inner.apply_local_resize(size);
+ self.session.apply_local_resize(size);
}
if decision.send_rpc {
- inner.update_last_send();
+ self.session.update_last_send();
}
(decision, prior_requested, advertised)
};
@@ -1162,19 +878,12 @@ impl Pane for ClientPane {
if self.client.remote_tab_input_is_blocked() {
return Ok(());
}
- Mux::get().record_input_for_current_identity();
- let input_serial = InputSerial::now();
- self.queue_input(PaneInput::Key {
- event: KeyEvent {
- key,
- modifiers: mods,
- },
- input_serial,
- })?;
- let renderable = self.renderable.lock();
- let mut inner = renderable.inner.borrow_mut();
- inner.input_serial = input_serial;
- inner.predict_from_key_event(key, mods);
+ self.host.events().input_recorded();
+ let input_serial = InputSerial::from_millis(self.host.clock().wall_millis());
+ if self.session.key_down(input_serial, key, mods)? {
+ start_input_drain(&self.session);
+ }
+ self.session.update_last_send();
Ok(())
}
@@ -1258,12 +967,12 @@ impl Pane for ClientPane {
if self.client.remote_tab_input_is_blocked() {
return Ok(());
}
- Mux::get().record_input_for_current_identity();
- self.queue_input(PaneInput::Mouse(mousestate::normalize_wheel(event)))
+ self.host.events().input_recorded();
+ self.queue_input(PaneInput::Mouse(mouse::normalize_wheel(event)))
}
fn is_dead(&self) -> bool {
- self.renderable.lock().inner.borrow().dead
+ self.session.is_dead()
}
fn palette(&self) -> ColorPalette {
@@ -1283,19 +992,19 @@ impl Pane for ClientPane {
}
fn is_mouse_grabbed(&self) -> bool {
- *self.mouse_grabbed.lock()
+ self.session.is_mouse_grabbed()
}
fn is_alt_screen_active(&self) -> bool {
- *self.alt_screen.lock()
+ self.session.is_alt_screen()
}
fn get_keyboard_encoding(&self) -> KeyboardEncoding {
- *self.keyboard_encoding.lock()
+ self.session.keyboard_encoding()
}
fn get_current_working_dir(&self, _policy: CachePolicy) -> Option<Url> {
- self.renderable.lock().inner.borrow().working_dir.clone()
+ self.session.working_dir()
}
fn focus_changed(&self, focused: bool) {
@@ -1316,7 +1025,10 @@ impl Pane for ClientPane {
// In the queue with the keys: the server applies it in arrival
// order, so the client sends it in the order it was asked.
if let Err(err) = self.queue_input(PaneInput::EraseScrollback(erase_mode)) {
- log::warn!("erase scrollback of remote pane {}: {err:#}", self.remote_pane_id);
+ log::warn!(
+ "erase scrollback of remote pane {}: {err:#}",
+ self.remote_pane_id
+ );
}
}
@@ -1381,7 +1093,7 @@ impl Pane for ClientPane {
// defaults. Identical re-sends stay flicker-free because both the
// server and the receiving side de-duplicate them; the skip here
// only avoids per-config-bump RPC noise once delivery is confirmed.
- let send = self.delivered_palette.lock().delivered.as_ref() != Some(&palette);
+ let send = self.delivered_palette.lock().delivered() != Some(&palette);
// If the application running in the pane hasn't changed the
// palette through escape sequences, speculatively adopt the
@@ -1408,418 +1120,15 @@ impl Pane for ClientPane {
}
}
-#[derive(Default)]
-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)]
-struct RowsCarried {
- rows: std::collections::HashSet<StableRowIndex>,
- ranges: Vec<Range<StableRowIndex>>,
-}
-
-impl RowsCarried {
- 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.
- 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.
- 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)))
- }
-}
-
-/// 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(PaneId);
-
-impl Drop for DrainingDeltas {
- fn drop(&mut self) {
- let Some(mux) = Mux::try_get() else {
- return;
- };
- if let Some(pane) = mux.get_pane(self.0) {
- if let Some(pane) = pane.downcast_ref::<ClientPane>() {
- pane.render_deltas.lock().draining = false;
- }
- }
- }
-}
-
-async fn drain_render_deltas(local_pane_id: PaneId) {
- let _draining = DrainingDeltas(local_pane_id);
- loop {
- let Some(pane) = Mux::get().get_pane(local_pane_id) else {
- return;
- };
- let Some(pane) = pane.downcast_ref::<ClientPane>() else {
- return;
- };
- let Some((delta, carried)) = pane.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 = std::time::Instant::now();
- let fetched_pictures = carried.is_none();
- pane.apply_render_delta(delta, carried).await;
- log::debug!(
- "render push for pane {local_pane_id} applied in {:?} (fetched pictures: {})",
- started.elapsed(),
- fetched_pictures
- );
- }
-}
-
struct PaneWriter {
client: Arc<ClientInner>,
- remote_pane_id: PaneId,
- remote_tab_id: Arc<AtomicUsize>,
- inputs: Arc<Mutex<InputQueue>>,
+ session: Arc<PaneSession<DesktopHost>>,
}
-/// 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.
-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.
-const INPUT_ITEM_FLOOR: usize = 64;
-
-impl PaneInput {
- 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
- }
- }
- }
-
- 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.
- 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)) => {
- mousestate::coalesce(last, event).map(PaneInput::Mouse)
- }
- (_, next) => Some(next),
- }
- }
-
- 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)]
-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)]
-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.
- 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.
- 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.
- 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<Mutex<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<Mutex<InputQueue>>,
- weight: usize,
-}
-
-impl Drop for Settling {
- fn drop(&mut self) {
- self.queue.lock().settle(self.weight);
- }
-}
-
-/// Where a drain sends: the connection, or a recorder under test.
-trait InputLink: Send + Sync + '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) -> BoxFuture<'_, anyhow::Result<bool>>;
-
- /// Put the request on the wire now, behind everything sent before it;
- /// the future is its answer.
- fn send(&self, pdu: Pdu) -> BoxFuture<'static, anyhow::Result<Pdu>>;
-}
-
-impl InputLink for ClientInner {
- fn prepare(&self, remote_tab_id: TabId) -> BoxFuture<'_, anyhow::Result<bool>> {
- self.prepare_remote_tab_input(remote_tab_id).boxed()
- }
-
- fn send(&self, pdu: Pdu) -> BoxFuture<'static, anyhow::Result<Pdu>> {
- self.client.send_pdu_pipelined(pdu).boxed()
- }
-}
-
-/// 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.
-async fn drain_pane_inputs<L: InputLink>(
- link: Arc<L>,
- remote_pane_id: PaneId,
- remote_tab_id: Arc<AtomicUsize>,
- queue: Arc<Mutex<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.send(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() {}
-}
-
-fn answered(answer: anyhow::Result<Pdu>) -> anyhow::Result<()> {
- match answer? {
- Pdu::UnitResponse(_) => Ok(()),
- Pdu::ErrorResponse(err) => bail!(err.reason),
- other => bail!("unexpected response {other:?}"),
- }
-}
-
-/// Queue `input` for the remote pane behind everything given before it,
-/// and start the drain when none runs.
-fn queue_pane_input(
- client: &Arc<ClientInner>,
- remote_pane_id: PaneId,
- remote_tab_id: &Arc<AtomicUsize>,
- inputs: &Arc<Mutex<InputQueue>>,
- input: PaneInput,
-) -> Result<(), InputQueueFull> {
- let what = input.describe();
- let start_drain = inputs.lock().push(input).map_err(|full| {
- log::warn!("refusing {what} for remote pane {remote_pane_id}: {full}");
- full
- })?;
- if start_drain {
- promise::spawn::spawn_into_main_thread(drain_pane_inputs(
- Arc::clone(client),
- remote_pane_id,
- Arc::clone(remote_tab_id),
- Arc::clone(inputs),
- ))
- .detach();
- }
- Ok(())
+/// Run the pane's input drain on the main thread executor, which needs a
+/// `Send` future: the desktop link hands out `Send` futures, so it is.
+fn start_input_drain(session: &Arc<PaneSession<DesktopHost>>) {
+ promise::spawn::spawn_into_main_thread(Arc::clone(session).drain_inputs()).detach();
}
impl std::io::Write for PaneWriter {
@@ -1827,14 +1136,13 @@ impl std::io::Write for PaneWriter {
if self.client.remote_tab_input_is_blocked() {
return Ok(data.len());
}
- queue_pane_input(
- &self.client,
- self.remote_pane_id,
- &self.remote_tab_id,
- &self.inputs,
- PaneInput::Bytes(data.to_vec()),
- )
- .map_err(|full| std::io::Error::new(std::io::ErrorKind::WouldBlock, full))?;
+ let start = self
+ .session
+ .write_bytes(data)
+ .map_err(|full| std::io::Error::new(std::io::ErrorKind::WouldBlock, full))?;
+ if start {
+ start_input_drain(&self.session);
+ }
Ok(data.len())
}
@@ -1842,684 +1150,3 @@ impl std::io::Write for PaneWriter {
Ok(())
}
}
-
-#[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);
- }
-
- #[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");
- }
-}
-
-#[cfg(test)]
-mod input_queue_tests {
- use super::*;
- use std::sync::atomic::AtomicBool;
- use wezterm_term::{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: Mutex<Vec<String>>,
- answers: Mutex<Vec<smol::channel::Sender<anyhow::Result<Pdu>>>>,
- refuse: AtomicBool,
- }
-
- impl RecordingLink {
- fn answer_everything(&self) {
- for answer in self.answers.lock().drain(..) {
- answer
- .try_send(Ok(Pdu::UnitResponse(UnitResponse {})))
- .unwrap();
- }
- }
- }
-
- impl InputLink for RecordingLink {
- fn prepare(&self, _remote_tab_id: TabId) -> BoxFuture<'_, anyhow::Result<bool>> {
- let allowed = !self.refuse.load(Ordering::SeqCst);
- async move { Ok(allowed) }.boxed()
- }
-
- fn send(&self, pdu: Pdu) -> BoxFuture<'static, anyhow::Result<Pdu>> {
- self.wire.lock().push(pdu_tag(&pdu));
- let (tx, rx) = smol::channel::bounded(1);
- self.answers.lock().push(tx);
- async move {
- rx.recv()
- .await
- .map_err(|_| anyhow::anyhow!("the answer was dropped"))?
- }
- .boxed()
- }
- }
-
- /// 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<Mutex<InputQueue>> = Default::default();
- let tab = Arc::new(AtomicUsize::new(0));
- let ex = smol::LocalExecutor::new();
- let drain = || {
- ex.spawn(drain_pane_inputs(
- Arc::clone(&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();
- smol::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<Mutex<InputQueue>> = Default::default();
- assert!(queue.lock().push(enter()).unwrap());
- let ex = smol::LocalExecutor::new();
- smol::block_on(ex.run(drain_pane_inputs(
- Arc::clone(&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<Mutex<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<Mutex<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/wezterm-client/src/pane/events.rs b/wezterm-client/src/pane/events.rs
new file mode 100644
index 00000000..b1998639
--- /dev/null
+++ b/wezterm-client/src/pane/events.rs
@@ -0,0 +1,268 @@
+//! The desktop's side of the session crate's host traits: the mux for
+//! notifications, the system clocks, the live configuration, the promise
+//! executor for tasks, and the `ClientInner` connection for the wire.
+use crate::domain::ClientInner;
+use config::configuration;
+use mux::domain::DomainId;
+use mux::{Mux, MuxNotification};
+use promise::BrokenPromise;
+use std::convert::TryInto;
+use std::sync::{Arc, Mutex};
+use std::time::{Instant, SystemTime};
+use thinkterm_proto::TabId;
+use thinkterm_session::clock::{Clock, Timestamp};
+use thinkterm_session::host::{
+ DetachedFuture, HostConfig, HostPaneId, ImageDomainKey, LinkError, PduLink, SessionEvents,
+ SessionHost, Spawner,
+};
+use thinkterm_session::images::ImageStore;
+use thinkterm_session::input::{PaneLink, SendFuture};
+use thinkterm_session::Lock;
+use wezterm_term::Alert;
+
+/// The desktop's clocks. `now` is micros since this process first asked;
+/// `wall_millis` is what `InputSerial::now()` always was.
+pub(crate) struct SystemClock;
+
+impl Clock for SystemClock {
+ fn now(&self) -> Timestamp {
+ static ORIGIN: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
+ Timestamp::from_micros(ORIGIN.get_or_init(Instant::now).elapsed().as_micros() as u64)
+ }
+
+ fn wall_millis(&self) -> u64 {
+ SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .expect("SystemTime before unix epoch?")
+ .as_millis()
+ .try_into()
+ .expect("millisecond count to fit in u64")
+ }
+}
+
+/// The desktop's live settings, read from the current configuration on
+/// every call, as the config-reload-aware code they replace did. The
+/// hyperlink rules are copied once per configuration generation, not per
+/// push: the session asks for them on every delta.
+pub(crate) struct DesktopConfig {
+ rules: Mutex<Option<(usize, Arc<Vec<termwiz::hyperlink::Rule>>)>>,
+}
+
+impl DesktopConfig {
+ pub(crate) fn new() -> Self {
+ Self {
+ rules: Mutex::new(None),
+ }
+ }
+}
+
+impl HostConfig for DesktopConfig {
+ fn hyperlink_rules(&self) -> Arc<Vec<termwiz::hyperlink::Rule>> {
+ let config = configuration();
+ let generation = config.generation();
+ let mut cached = self.rules.lock().unwrap_or_else(|p| p.into_inner());
+ match &*cached {
+ Some((held, rules)) if *held == generation => Arc::clone(rules),
+ _ => {
+ let rules = Arc::new(config.hyperlink_rules.clone());
+ *cached = Some((generation, Arc::clone(&rules)));
+ rules
+ }
+ }
+ }
+
+ fn fetch_rate_per_second(&self) -> u32 {
+ configuration().ratelimit_mux_line_prefetches_per_second
+ }
+}
+
+/// The session's own tasks run on the promise executor, as they did
+/// before the session was a crate: non-`Send`, on this thread.
+pub(crate) struct PromiseSpawner;
+
+impl Spawner for PromiseSpawner {
+ fn spawn_detached(&self, fut: DetachedFuture) {
+ promise::spawn::spawn(fut).detach();
+ }
+}
+
+/// The connection behind a `ClientInner`, as the session's wire. Its
+/// futures are `Send`, so the input drain can run on the main thread
+/// executor, which requires that.
+pub(crate) struct DesktopLink(Arc<ClientInner>);
+
+impl DesktopLink {
+ pub(crate) fn new(client: Arc<ClientInner>) -> Self {
+ Self(client)
+ }
+}
+
+impl PduLink for DesktopLink {
+ type Request = SendFuture<Result<codec::Pdu, LinkError>>;
+
+ fn request(&self, pdu: codec::Pdu) -> Self::Request {
+ // The same metrics the rpc! wrappers record, keyed the same way
+ // (the wrapper names are the snake_case of the PDU names).
+ let method: &'static str = match &pdu {
+ codec::Pdu::GetLines(_) => "get_lines",
+ codec::Pdu::GetPaneRenderChanges(_) => "get_pane_render_changes",
+ codec::Pdu::GetImageCell(_) => "get_image_cell",
+ other => other.pdu_name(),
+ };
+ let start = Instant::now();
+ let answer = self.0.client.send_pdu_pipelined(pdu);
+ Box::pin(async move {
+ let answer = answer.await;
+ metrics::histogram!("rpc", "method" => method).record(start.elapsed());
+ metrics::counter!("rpc.count", "method" => method).increment(1);
+ answer.map_err(|err| LinkError {
+ // A broken promise is the transport between connections;
+ // the request may be answered once it is back.
+ retryable: err.downcast_ref::<BrokenPromise>().is_some(),
+ message: format!("{err:#}"),
+ })
+ })
+ }
+
+ fn is_reconnectable(&self) -> bool {
+ self.0.client.is_reconnectable
+ }
+
+ fn connection_generation(&self) -> u64 {
+ self.0.client.connection_generation()
+ }
+}
+
+impl PaneLink for DesktopLink {
+ type Prepare = SendFuture<anyhow::Result<bool>>;
+
+ fn prepare(&self, remote_tab_id: TabId) -> Self::Prepare {
+ let client = Arc::clone(&self.0);
+ Box::pin(async move { client.prepare_remote_tab_input(remote_tab_id).await })
+ }
+}
+
+pub(crate) struct MuxEvents {
+ client: Arc<ClientInner>,
+}
+
+impl MuxEvents {
+ pub(crate) fn new(client: Arc<ClientInner>) -> Self {
+ Self { client }
+ }
+}
+
+impl SessionEvents for MuxEvents {
+ fn pane_output(&self, pane: HostPaneId) {
+ Mux::get().notify(MuxNotification::PaneOutput(pane));
+ }
+
+ fn alert(&self, pane: HostPaneId, alert: Alert) {
+ Mux::get().notify(MuxNotification::Alert {
+ pane_id: pane,
+ alert,
+ });
+ }
+
+ fn agent_status_changed(&self, pane: HostPaneId) {
+ Mux::get().notify(MuxNotification::AgentStatusChanged(pane));
+ }
+
+ fn pane_removed(&self, _pane: HostPaneId) {
+ let mux = Mux::get();
+ mux.prune_dead_windows();
+ self.client.expire_stale_mappings();
+ }
+
+ fn pane_focused(&self, pane: HostPaneId) {
+ let mux = Mux::get();
+ if let Err(err) = mux.focus_pane_and_containing_tab(pane) {
+ log::error!("Error reconciling remote PaneFocused notification: {err:#}");
+ } else if let Some((_domain, window_id, _tab)) = mux.resolve_pane_id(pane) {
+ // The reconcile flips tab/stack selection silently (to
+ // avoid focus advisory loops); nudge the GUI to repaint.
+ mux.notify(MuxNotification::WindowInvalidated(window_id));
+ }
+ }
+
+ fn input_recorded(&self) {
+ Mux::get().record_input_for_current_identity();
+ }
+}
+
+/// Everything a desktop pane session takes from this process.
+pub(crate) struct DesktopHost {
+ link: DesktopLink,
+ events: MuxEvents,
+ clock: SystemClock,
+ config: DesktopConfig,
+ spawner: PromiseSpawner,
+ image_domain: DomainId,
+}
+
+impl DesktopHost {
+ pub(crate) fn new(client: Arc<ClientInner>) -> Self {
+ Self {
+ image_domain: client.local_domain_id,
+ link: DesktopLink::new(Arc::clone(&client)),
+ events: MuxEvents::new(client),
+ clock: SystemClock,
+ config: DesktopConfig::new(),
+ spawner: PromiseSpawner,
+ }
+ }
+}
+
+impl SessionHost for DesktopHost {
+ type Clock = SystemClock;
+ type Spawner = PromiseSpawner;
+ type Events = MuxEvents;
+ type Link = DesktopLink;
+ type Config = DesktopConfig;
+
+ fn clock(&self) -> &SystemClock {
+ &self.clock
+ }
+
+ fn spawner(&self) -> &PromiseSpawner {
+ &self.spawner
+ }
+
+ fn events(&self) -> &MuxEvents {
+ &self.events
+ }
+
+ fn link(&self) -> &DesktopLink {
+ &self.link
+ }
+
+ fn config(&self) -> &DesktopConfig {
+ &self.config
+ }
+
+ fn image_domain(&self) -> ImageDomainKey {
+ self.image_domain
+ }
+}
+
+/// Images fetched from remote panes, by the domain they came from and
+/// their hash, shared by every pane session in this process.
+fn image_store() -> &'static Arc<Lock<ImageStore>> {
+ static STORE: std::sync::OnceLock<Arc<Lock<ImageStore>>> = std::sync::OnceLock::new();
+ STORE.get_or_init(|| Arc::new(Lock::new(ImageStore::default())))
+}
+
+pub(crate) fn shared_image_store() -> Arc<Lock<ImageStore>> {
+ Arc::clone(image_store())
+}
+
+/// What the store of remote images holds right now: a count and bytes.
+pub fn remote_image_footprint() -> (usize, usize) {
+ image_store().lock().footprint()
+}
+
+/// Drop every image held for `domain_id`: on (re)attach the server may be
+/// a different process, whose generations start over.
+pub(crate) fn forget_images_for_domain(domain_id: DomainId) {
+ image_store().lock().forget_domain(domain_id);
+}
diff --git a/wezterm-client/src/pane/images.rs b/wezterm-client/src/pane/images.rs
deleted file mode 100644
index d0c0c318..00000000
--- a/wezterm-client/src/pane/images.rs
+++ /dev/null
@@ -1,218 +0,0 @@
-//! 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(crate) 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(crate) 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");
- }
-}
diff --git a/wezterm-client/src/pane/mod.rs b/wezterm-client/src/pane/mod.rs
index 5188730b..e229ba42 100644
--- a/wezterm-client/src/pane/mod.rs
+++ b/wezterm-client/src/pane/mod.rs
@@ -1,9 +1,7 @@
-pub(crate) use clientpane::remote_server_identity_matches;
+pub(crate) use thinkterm_session::decide::remote_server_identity_matches;
pub use clientpane::ClientPane;
mod clientpane;
-mod images;
-mod mousestate;
-mod renderable;
-pub(crate) use renderable::forget_images_for_domain;
-pub use renderable::remote_image_footprint;
+mod events;
+pub(crate) use events::forget_images_for_domain;
+pub use events::remote_image_footprint;
diff --git a/wezterm-client/src/pane/mousestate.rs b/wezterm-client/src/pane/mousestate.rs
deleted file mode 100644
index b2d80742..00000000
--- a/wezterm-client/src/pane/mousestate.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-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/wezterm-client/src/pane/renderable.rs b/wezterm-client/src/pane/renderable.rs
deleted file mode 100644
index 07bd5436..00000000
--- a/wezterm-client/src/pane/renderable.rs
+++ /dev/null
@@ -1,2132 +0,0 @@
-use crate::domain::ClientInner;
-use crate::pane::clientpane::ClientPane;
-use anyhow::anyhow;
-use codec::*;
-use config::{configuration, ConfigHandle};
-use lru::LruCache;
-use mux::domain::DomainId;
-use mux::pane::PaneId;
-use mux::renderable::{RenderableDimensions, StableCursorPosition};
-use mux::Mux;
-use promise::BrokenPromise;
-use rangeset::*;
-use ratelim::RateLimiter;
-use std::cell::RefCell;
-use std::collections::HashMap;
-use std::num::NonZeroUsize;
-use std::ops::Range;
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{Arc, Mutex};
-use std::time::{Duration, Instant};
-use termwiz::cell::{Cell, CellAttributes, Underline};
-use termwiz::color::AnsiColor;
-use termwiz::image::{ImageCell, ImageData};
-use termwiz::surface::{SequenceNo, SEQ_ZERO};
-use url::Url;
-use wezterm_term::{KeyCode, KeyModifiers, 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.
-const MAX_POLL_INTERVAL: Duration = Duration::from_secs(30);
-const BASE_POLL_INTERVAL: Duration = Duration::from_millis(20);
-const FETCH_STALL_BASE: Duration = Duration::from_secs(30);
-const POLL_STALL_BASE: Duration = Duration::from_secs(15);
-
-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)]
-struct FetchToken {
- epoch: u64,
- started_at: Instant,
- stall_attempt: u32,
-}
-
-impl FetchToken {
- fn new(epoch: u64, started_at: Instant) -> Self {
- Self {
- epoch,
- started_at,
- stall_attempt: 0,
- }
- }
-
- fn retry(self, started_at: Instant) -> Self {
- Self {
- epoch: self.epoch,
- started_at,
- stall_attempt: self.stall_attempt.saturating_add(1),
- }
- }
-}
-
-fn fetch_should_be_retried(token: FetchToken, now: Instant) -> bool {
- now.saturating_duration_since(token.started_at)
- > stall_timeout(FETCH_STALL_BASE, token.stall_attempt)
-}
-
-fn poll_should_be_retried(started_at: Instant, attempt: u32, now: Instant) -> bool {
- now.saturating_duration_since(started_at) > stall_timeout(POLL_STALL_BASE, attempt)
-}
-
-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)]
-struct FrontendPreviewGeometry {
- epoch: u64,
- size: wezterm_term::TerminalSize,
- 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(crate) enum FrontendPreviewPolicy {
- PreserveRows,
- LiveResize,
-}
-
-#[derive(Debug)]
-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)]
-struct FetchRetryBatch {
- token: FetchToken,
- rows: RangeSet<StableRowIndex>,
-}
-
-#[derive(Debug, Default)]
-struct LineWatchdogDecision {
- repaint: bool,
- retries: Vec<FetchRetryBatch>,
-}
-
-impl LineWatchdogDecision {
- 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 });
- }
-}
-
-fn line_watchdog_decision(
- lines: &mut LruCache<StableRowIndex, LineEntry>,
- range: Range<StableRowIndex>,
- now: Instant,
-) -> 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 {
- 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),
- }
- }
-}
-
-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.
-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;
-}
-
-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
-}
-
-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
-}
-
-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))
-}
-
-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 => {}
- }
- }
- }
-}
-
-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)
- }
-}
-
-fn fetch_token_is_current(token: FetchToken, epoch: u64) -> bool {
- token.epoch == epoch
-}
-
-pub struct RenderableInner {
- pub client: Arc<ClientInner>,
- remote_pane_id: PaneId,
- local_pane_id: PaneId,
- last_poll: Instant,
- pub 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.
- poll_in_flight: Arc<AtomicU64>,
- poll_gen: u64,
- poll_stall_attempt: u32,
- poll_interval: Duration,
-
- 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.
- alt_screen: bool,
- pub 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.
- 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.
- frontend_preview: Option<FrontendPreviewGeometry>,
-
- lines: LruCache<StableRowIndex, LineEntry>,
- 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.
- epoch_discard_notified: u64,
- pub title: String,
- pub working_dir: Option<Url>,
- pub seqno: SequenceNo,
-
- fetch_limiter: RateLimiter,
-
- last_send_time: Instant,
- pub last_recv_time: Instant,
- last_late_dirty: Instant,
- last_input_rtt: u64,
-
- pub input_serial: InputSerial,
-}
-
-pub struct RenderableState {
- pub inner: RefCell<RenderableInner>,
-}
-
-impl RenderableInner {
- pub fn new(
- client: &Arc<ClientInner>,
- remote_pane_id: PaneId,
- local_pane_id: PaneId,
- dimensions: RenderableDimensions,
- title: &str,
- fetch_limiter: RateLimiter,
- ) -> Self {
- let now = Instant::now();
-
- Self {
- client: Arc::clone(client),
- remote_pane_id,
- local_pane_id,
- 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: false,
- server_dimensions: dimensions,
- frontend_preview: None,
- lines: LruCache::new(
- NonZeroUsize::new(configuration().scrollback_lines.max(128)).unwrap(),
- ),
- line_cache_epoch: 0,
- epoch_discard_notified: 0,
- title: title.to_string(),
- working_dir: None,
- fetch_limiter,
- last_send_time: now,
- last_recv_time: now,
- last_late_dirty: now,
- last_input_rtt: 0,
- input_serial: InputSerial::empty(),
- seqno: SEQ_ZERO,
- }
- }
-
- /// 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) -> bool {
- let elapsed = self.last_recv_time.elapsed();
- 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.client
- .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) {
- self.last_send_time = Instant::now();
- self.poll_interval = BASE_POLL_INTERVAL;
- }
-
- pub fn apply_changes_to_surface(
- &mut self,
- delta: GetPaneRenderChangesResponse,
- bonus_lines: Vec<(StableRowIndex, Line)>,
- ) {
- log::trace!(
- "apply_changes_to_surface local={} remote={}",
- self.local_pane_id,
- self.remote_pane_id
- );
- let now = Instant::now();
- self.poll_interval = BASE_POLL_INTERVAL;
- self.last_recv_time = now;
-
- if delta.alt_screen != self.alt_screen {
- self.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.
- self.invalidate_line_cache(true);
- }
-
- let live_preview_accepts_snapshot = self.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 != self.cursor_position {
- dirty.add(self.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 {
- self.last_input_rtt = serial.elapsed_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()) >= self.input_serial)
- {
- self.cursor_position = delta.cursor_position;
- }
- let prior_server_dimensions = self.server_dimensions;
- self.server_dimensions = delta.dimensions;
- let (visible_dimensions, invalidate) = resolve_server_geometry(
- self.dimensions,
- prior_server_dimensions,
- delta.dimensions,
- self.frontend_preview.is_some(),
- );
- self.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.
- self.invalidate_line_cache(preserve_lines);
- }
- self.title = delta.title;
- self.working_dir = delta.working_dir.map(Into::into);
- log::trace!(
- "server says: seqno from {} -> {} for local_pane_id={}",
- self.seqno,
- delta.seqno,
- self.local_pane_id
- );
- self.seqno = delta.seqno;
-
- let config = configuration();
- 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());
- self.put_line(stable_row, line, &config, None);
- dirty.remove(stable_row);
- }
-
- log::trace!(
- "apply_changes_to_surface: Generate PaneOutput event for local={}",
- self.local_pane_id
- );
- Mux::get().notify(mux::MuxNotification::PaneOutput(self.local_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 = self.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);
- self.make_stale(stable_row);
- continue;
- }
- to_fetch.add(stable_row);
- let token = self.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()
- );
- self.lines.put(stable_row, entry);
- }
- }
- if !to_fetch.is_empty() {
- if self.fetch_limiter.non_blocking_admittance_check(1) {
- self.schedule_fetch_lines(to_fetch, self.fetch_token(now));
- } else {
- log::warn!(
- "exceeded fetch throttle, drop {:?} and mark stale",
- to_fetch
- );
- for r in to_fetch.iter() {
- for stable_row in r.clone() {
- self.make_stale(stable_row);
- }
- }
- }
- }
- }
-
- pub fn make_all_stale(&mut self) {
- self.invalidate_line_cache(true);
- }
-
- /// True when a row the GUI is actually displaying is waiting on work
- /// that only a paint performs. `viewport_top` is the GUI's 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(crate) fn watchdog_check_displayed_rows(
- &mut self,
- viewport_top: Option<StableRowIndex>,
- ) -> bool {
- let top = viewport_top.unwrap_or(self.dimensions.physical_top);
- let range = top..top.saturating_add(self.dimensions.viewport_rows as StableRowIndex);
- // Keep the line-table borrow inside the pure decision helper. Only
- // after it ends do we schedule RPCs through `self`, avoiding a
- // renderable/RefCell re-entry while inspecting the cache.
- let decision = line_watchdog_decision(&mut self.lines, range, Instant::now());
- if decision.repaint {
- self.poll_interval = BASE_POLL_INTERVAL;
- }
- for batch in decision.retries {
- self.schedule_fetch_lines(batch.rows, batch.token);
- }
- decision.repaint
- }
-
- fn fetch_token(&self, started_at: Instant) -> FetchToken {
- FetchToken::new(self.line_cache_epoch, started_at)
- }
-
- 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(crate) fn apply_local_resize(&mut self, size: wezterm_term::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(crate) fn begin_frontend_preview(
- &mut self,
- epoch: u64,
- size: wezterm_term::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(crate) fn server_geometry_matches(&self, size: wezterm_term::TerminalSize) -> bool {
- render_dimensions_match_terminal_size(self.server_dimensions, size)
- }
-
- pub(crate) 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
- }
-
- 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 => {}
- }
- }
-
- fn put_line(
- &mut self,
- stable_row: StableRowIndex,
- mut line: Line,
- config: &ConfigHandle,
- fetch_token: Option<FetchToken>,
- ) {
- line.scan_and_create_hyperlinks(&config.hyperlink_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);
- }
-
- fn schedule_fetch_lines(
- &mut self,
- to_fetch: RangeSet<StableRowIndex>,
- fetch_token: FetchToken,
- ) {
- if to_fetch.is_empty() || self.dead {
- return;
- }
-
- let local_pane_id = self.local_pane_id;
- log::trace!(
- "will fetch lines {:?} for remote tab id {} at {:?}",
- to_fetch,
- self.remote_pane_id,
- fetch_token,
- );
-
- let client = Arc::clone(&self.client);
- let remote_pane_id = self.remote_pane_id;
-
- promise::spawn::spawn(async move {
- let result = client
- .client
- .get_lines(GetLines {
- pane_id: remote_pane_id,
- lines: to_fetch.clone().into(),
- })
- .await;
-
- let result = match result {
- Ok(result) => {
- let (lines, _) =
- hydrate_lines(Arc::clone(&client), remote_pane_id, result.lines, true)
- .await;
- Ok(lines)
- }
- Err(err) => Err(err),
- };
- Self::apply_lines(local_pane_id, result, to_fetch, fetch_token)
- })
- .detach();
- }
-
- fn apply_lines(
- local_pane_id: PaneId,
- result: anyhow::Result<Vec<(StableRowIndex, Line)>>,
- to_fetch: RangeSet<StableRowIndex>,
- fetch_token: FetchToken,
- ) -> anyhow::Result<()> {
- let mux = Mux::get();
- let pane = mux
- .get_pane(local_pane_id)
- .ok_or_else(|| anyhow!("no such tab {}", local_pane_id))?;
- let mut notify_pane_output = true;
- if let Some(client_tab) = pane.downcast_ref::<ClientPane>() {
- let renderable = client_tab.renderable.lock();
- let mut inner = renderable.inner.borrow_mut();
-
- if !fetch_token_is_current(fetch_token, inner.line_cache_epoch) {
- log::trace!(
- "discarding line fetch for pane {} from epoch {} because current epoch is {}",
- local_pane_id,
- fetch_token.epoch,
- inner.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 = inner.epoch_discard_notified == inner.line_cache_epoch;
- inner.epoch_discard_notified = inner.line_cache_epoch;
- drop(inner);
- drop(renderable);
- if !already_notified {
- mux.notify(mux::MuxNotification::PaneOutput(local_pane_id));
- }
- return Ok(());
- }
-
- match result {
- Ok(lines) => {
- let config = configuration();
- 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);
- inner.put_line(stable_row, line, &config, 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 inner.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 inner.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 <= inner.seqno, 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,
- };
- inner.lines.put(stable_row, entry);
- }
- }
- }
- }
- }
- if notify_pane_output {
- log::trace!(
- "Generate PaneOutput event for local_pane_id={}",
- local_pane_id
- );
- mux.notify(mux::MuxNotification::PaneOutput(local_pane_id));
- }
- Ok(())
- }
-
- fn poll(&mut self) -> anyhow::Result<()> {
- let now = Instant::now();
- let mut forced_retry = false;
- let in_flight = self.poll_in_flight.load(Ordering::SeqCst);
- if in_flight != 0 {
- let deadline = stall_timeout(POLL_STALL_BASE, self.poll_stall_attempt);
- if poll_should_be_retried(self.last_poll, self.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.local_pane_id,
- in_flight,
- deadline,
- self.poll_stall_attempt,
- );
- if !claim_poll_completion(&self.poll_in_flight, in_flight) {
- return Ok(());
- }
- self.poll_stall_attempt = self.poll_stall_attempt.saturating_add(1);
- forced_retry = true;
- } else {
- // We have a poll in progress
- return Ok(());
- }
- }
-
- if !forced_retry {
- if now.saturating_duration_since(self.last_poll) < self.poll_interval {
- return Ok(());
- }
- self.poll_stall_attempt = 0;
- }
-
- let interval = self.poll_interval;
- let interval = (interval + interval).min(MAX_POLL_INTERVAL);
- self.poll_interval = interval;
-
- self.last_poll = now;
- self.poll_gen = self.poll_gen.wrapping_add(1).max(1);
- let gen = self.poll_gen;
- self.poll_in_flight.store(gen, Ordering::SeqCst);
- let poll_in_flight = Arc::clone(&self.poll_in_flight);
- let remote_pane_id = self.remote_pane_id;
- let local_pane_id = self.local_pane_id;
- let client = Arc::clone(&self.client);
- promise::spawn::spawn(async move {
- let alive = match client
- .client
- .get_pane_render_changes(GetPaneRenderChanges {
- pane_id: remote_pane_id,
- })
- .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(_) => client.client.is_reconnectable,
- };
-
- // Cleared through the shared handle before anything that can
- // bail: if the pane has left the mux (or the downcast fails),
- // 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 Ok(());
- }
-
- let mux = Mux::get();
- let tab = mux
- .get_pane(local_pane_id)
- .ok_or_else(|| anyhow!("no such tab {}", local_pane_id))?;
- if let Some(client_tab) = tab.downcast_ref::<ClientPane>() {
- let renderable = client_tab.renderable.lock();
- let mut inner = renderable.inner.borrow_mut();
-
- inner.dead = !alive;
- inner.last_recv_time = Instant::now();
- inner.poll_stall_attempt = 0;
- }
- Ok::<(), anyhow::Error>(())
- })
- .detach();
- Ok(())
- }
-}
-
-lazy_static::lazy_static! {
- /// Images fetched from remote panes, by the domain they came from and
- /// their hash. The domain is part of the key because the generation an
- /// image carries is a counter private to one server-side object: the
- /// same picture from two servers, or from one server before and after a
- /// restart, must not share a copy or compare generations.
- static ref IMAGE_LRU: Mutex<ImageStore> = Mutex::new(ImageStore::new(MAX_IMAGES, MAX_IMAGE_BYTES));
-}
-
-/// 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.
-const MAX_IMAGES: usize = 128;
-const MAX_IMAGE_BYTES: usize = 64 * 1024 * 1024;
-
-/// The images fetched from remote panes, by domain and hash, with the
-/// size each was last measured at.
-pub(crate) struct ImageStore {
- images: LruCache<(DomainId, [u8; 32]), (Arc<ImageData>, usize)>,
- bytes: usize,
- max_bytes: usize,
-}
-
-impl ImageStore {
- fn new(max_images: usize, max_bytes: usize) -> Self {
- Self {
- images: LruCache::new(NonZeroUsize::new(max_images.max(1)).unwrap()),
- bytes: 0,
- max_bytes,
- }
- }
-
- fn get(&mut self, key: &(DomainId, [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.
- fn put(&mut self, key: (DomainId, [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);
- }
- }
- }
-
- fn forget_domain(&mut self, domain_id: DomainId) {
- let stale: Vec<(DomainId, [u8; 32])> = self
- .images
- .iter()
- .filter(|((domain, _), _)| *domain == domain_id)
- .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(crate) fn footprint(&self) -> (usize, usize) {
- (self.images.len(), self.bytes)
- }
-}
-
-/// What the store of remote images holds right now: a count and bytes.
-pub fn remote_image_footprint() -> (usize, usize) {
- IMAGE_LRU.lock().unwrap().footprint()
-}
-
-/// Drop every image held for `domain_id`: on (re)attach the server may be
-/// a different process, whose generations start over.
-pub(crate) fn forget_images_for_domain(domain_id: DomainId) {
- IMAGE_LRU.lock().unwrap().forget_domain(domain_id);
-}
-
-/// 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(crate) async fn hydrate_lines(
- client: Arc<ClientInner>,
- 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_id = client.local_domain_id;
- for im in &image_cells {
- let held = IMAGE_LRU.lock().unwrap().get(&(domain_id, 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| super::images::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::future::join_all(
- asked
- .iter()
- .map(|(_, held, request)| fetch_image(&client, 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(domain_id, 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)
-}
-
-/// 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.
-fn file_image(domain_id: DomainId, data: Arc<ImageData>) -> Arc<ImageData> {
- let key = (domain_id, data.hash());
- let existing = IMAGE_LRU.lock().unwrap().get(&key);
- let filed = match existing {
- Some(existing) if !Arc::ptr_eq(&existing, &data) => {
- if !super::images::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.
- IMAGE_LRU.lock().unwrap().put(key, Arc::clone(&filed));
- filed
-}
-
-/// 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(
- client: &Arc<ClientInner>,
- held: Option<Arc<ImageData>>,
- request: GetImageCell,
-) -> Option<Arc<ImageData>> {
- let whole = GetImageCell {
- have_frames: 0,
- ..request
- };
- let asked_at = Instant::now();
- let mut response = client.client.get_image_cell(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,
- asked_at.elapsed()
- );
- }
- 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 super::images::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 = client.client.get_image_cell(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;
- }
- }
- }
-}
-
-impl RenderableState {
- pub fn get_cursor_position(&self) -> StableCursorPosition {
- self.inner.borrow().cursor_position
- }
-
- pub fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {
- let mut inner = self.inner.borrow_mut();
- let mut result = vec![];
- let mut to_fetch = RangeSet::new();
- let now = Instant::now();
- let fetch_token = inner.fetch_token(now);
-
- for idx in lines.clone() {
- let entry = match inner.lines.pop(&idx) {
- Some(LineEntry::Line(line)) => {
- result.push(line.clone());
- if line.changed_since(inner.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(inner.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(inner.dimensions.cols, SEQ_ZERO));
- to_fetch.add(idx);
- LineEntry::Fetching(fetch_token)
- }
- };
-
- if inner.client.overlay_lag_indicator && idx == inner.dimensions.physical_top {
- if inner.is_tardy() {
- let status = format!(
- "ThinkTerm: {:.0?}⏳since last response",
- inner.last_recv_time.elapsed()
- );
- // Right align it in the tab
- let col = inner
- .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);
- }
- }
-
- inner.lines.put(idx, entry);
- }
-
- log::trace!(
- "get_lines: {:?}, num result lines={}, will fetch {:?}",
- lines,
- result.len(),
- to_fetch
- );
-
- inner.schedule_fetch_lines(to_fetch, fetch_token);
- (lines.start, result)
- }
-
- pub fn get_current_seqno(&self) -> SequenceNo {
- self.inner.borrow().seqno
- }
-
- pub fn get_changed_since(
- &self,
- lines: Range<StableRowIndex>,
- seqno: SequenceNo,
- ) -> RangeSet<StableRowIndex> {
- let mut inner = self.inner.borrow_mut();
- if let Err(err) = inner.poll() {
- // We allow for BrokenPromise here for now; for a TLS backed
- // session it indicates that we'll retry. For a local unix
- // domain session it is terminal... but we will detect that
- // terminal condition elsewhere
- if let Err(err) = err.downcast::<BrokenPromise>() {
- log::error!("remote tab poll failed: {}, marking as dead", err);
- inner.dead = true;
- }
- }
-
- let mut result = RangeSet::new();
- for r in lines {
- match inner.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
- if inner.is_tardy() {
- // ... but take care to avoid always reporting it as dirty, so
- // that we don't end up busy looping just to repaint it
- if inner.last_late_dirty.elapsed() >= Duration::from_secs(1) {
- result.add(inner.dimensions.physical_top);
- inner.last_late_dirty = Instant::now();
- }
- }
-
- if !result.is_empty() {
- log::trace!("get_changed_since: {} -> {:?}", seqno, result);
- }
-
- result
- }
-
- pub fn get_dimensions(&self) -> RenderableDimensions {
- self.inner.borrow().dimensions
- }
-
- /// Which fields or render rows block a takeover from settling on `size`.
- pub(crate) fn frontend_geometry_mismatch(
- &self,
- size: wezterm_term::TerminalSize,
- ) -> Option<String> {
- let mut inner = self.inner.borrow_mut();
- let dims = inner.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 = inner.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 inner.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(" "),
- inner.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(crate) fn prime_frontend_geometry(&self, size: wezterm_term::TerminalSize) -> bool {
- let mut visible = {
- let mut inner = self.inner.borrow_mut();
- // 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.
- inner.poll_interval = BASE_POLL_INTERVAL;
- if let Err(err) = inner.poll() {
- log::trace!("polling takeover geometry: {err:#}");
- }
- let Some(visible) = confirmed_frontend_visible_range(inner.server_dimensions, size)
- else {
- return false;
- };
- visible
- };
-
- // 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(visible.clone());
-
- let mut inner = self.inner.borrow_mut();
- if confirmed_frontend_visible_range(inner.server_dimensions, size).as_ref()
- != Some(&visible)
- {
- return false;
- }
- visible.all(|row| matches!(inner.lines.get(&row), Some(LineEntry::Line(_))))
- }
-}
-
-#[cfg(test)]
-mod test {
- 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 = super::ImageStore::new(128, 100);
- let frame = |n: u8| {
- Arc::new(ImageData::with_data(
- termwiz::image::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]| termwiz::image::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| super::super::images::frame_count(&image.data());
- let domain = usize::MAX - 7;
-
- let first = Arc::new(ImageData::with_data_and_hash(anim(&[1, 2]), hash));
- let filed = super::file_image(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 = super::file_image(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 = super::file_image(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"
- );
- super::forget_images_for_domain(domain);
- }
-
- 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, Instant::now());
- 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, Instant::now());
- 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, Instant::now());
- 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 = Instant::now();
- 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 = Instant::now();
- 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 = Instant::now();
- 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 = Instant::now();
- 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 = Instant::now();
- 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);
- }
-}