From 46152096e7bd032fe9c65ef023ffa78a38dda9f3 Mon Sep 17 00:00:00 2001 From: felix Date: Mon, 23 Nov 2026 12:34:51 +0000 Subject: [PATCH 1/2] =?UTF-8?q?feat(id):=20kitty=20keyboard=20slices=20E+F?= =?UTF-8?q?=20=E2=80=94=20SSH=20negotiation/framing,=20browser=20opt-in=20?= =?UTF-8?q?(#787)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Slice E: on an opted-in server (SshServeOptions::kitty_keyboard; serve command env ID_WORLD_SSH_KITTY_KEYBOARD), a raw SSH session whose F13.4 probe reported kitty keyboard support pushes kitty-disambiguate-v1, verifies the flags report before admitting keys, frames input with the Slice B assembler (one complete key token per durable Input event), and pops exactly its own push on fallback and on every teardown path. Verification failure or timeout pops and falls back to legacy chunk input with held bytes untouched. Command, explorer and exec sessions never negotiate; defaults are legacy everywhere. The assembler moves from the id facade into id-worlds (the SSH adapter's crate); the facade re-exports it, so id::input_framing is unchanged. Slice F: the web world page selects the Slice C rich encoder per connection via ?keyboard=kitty; legacy remains the default, paste and the manual input form keep their existing paths. Tests: kitty.rs unit tests (filter, verification, fallback byte fidelity, split tokens); world_ssh integration tests (negotiate + split-input framing + Escape/Alt distinction + teardown pop, verify fallback, no-opt-in, unsupported terminal); web opt-in contract tests (DOM to WebSocket, both modes, paste/shortcut exclusions). --- ...-11-02T_reference_kitty_disambiguate_v1.md | 20 +- pkgs/id/crates/id-cli/src/commands/serve.rs | 16 +- .../id-worlds}/src/input_framing.rs | 11 +- pkgs/id/crates/id-worlds/src/lib.rs | 1 + pkgs/id/crates/id-worlds/src/world_ssh.rs | 622 ++++++++++++++++-- .../crates/id-worlds/src/world_ssh/form_io.rs | 6 + .../crates/id-worlds/src/world_ssh/kitty.rs | 336 ++++++++++ pkgs/id/src/lib.rs | 2 +- pkgs/id/web/src/world-keyboard-optin.test.ts | 159 +++++ pkgs/id/web/src/world-keyboard.ts | 10 +- pkgs/id/web/src/world.ts | 14 +- 11 files changed, 1138 insertions(+), 59 deletions(-) rename pkgs/id/{ => crates/id-worlds}/src/input_framing.rs (97%) create mode 100644 pkgs/id/crates/id-worlds/src/world_ssh/kitty.rs create mode 100644 pkgs/id/web/src/world-keyboard-optin.test.ts diff --git a/doc/2026-11-02T_reference_kitty_disambiguate_v1.md b/doc/2026-11-02T_reference_kitty_disambiguate_v1.md index 0942b3a991..f54e75690e 100644 --- a/doc/2026-11-02T_reference_kitty_disambiguate_v1.md +++ b/doc/2026-11-02T_reference_kitty_disambiguate_v1.md @@ -1,16 +1,24 @@ # kitty-disambiguate-v1 profile reference -- Status: **implemented (Slice A)** in `pkgs/id/examples/roc-world/Key.roc` - (`Key.parse_events`, `Key.to_legacy`); no activation. +- Status: **implemented, slices A–F**. The decoder is + `pkgs/id/examples/roc-world/Key.roc` (`Key.parse_events`, `Key.to_legacy`); + the bounded stream assembler is `pkgs/id/crates/id-worlds/src/input_framing.rs`; + the browser encoder is `richTerminalBytesForKey` in + `pkgs/id/web/src/world-keyboard.ts`, selected per connection by + `?keyboard=kitty` in `world.ts`; SSH negotiation (push/verify/pop plus + assembler framing on the raw path) is `world_ssh::kitty`, behind the + server opt-in `SshServeOptions::kitty_keyboard` (serve command: + `ID_WORLD_SSH_KITTY_KEYBOARD=1`). Defaults are legacy everywhere. - Upstream specification: [Comprehensive keyboard handling in terminals](https://sw.kovidgoyal.net/kitty/keyboard-protocol/), verified by direct fetch on **2026-11-02** (sections Quickstart, Key codes, Modifiers, Event types, Progressive enhancement, Disambiguate escape codes, Legacy key event encoding, Functional key definitions). -- Design record: `doc/2026-11-01_design_id787.md` §§4.1–4.2, 5–6 (Slice A). - Activation (negotiation, assembler, browser encoder) is slices B–F and is - **gated on F13.4 detection (#786, still open)**. This profile must only be - selected after an explicit opt-in; the push/pop owner is slice E. +- Design record: `doc/2026-11-01_design_id787.md` §§4.1–4.2, 5–6. + Activation waited for F13.4 detection: the SSH adapter's startup probe + (`world_terminal.rs`) records kitty keyboard support in the connection + profile, and negotiation starts only from that evidence, only after an + explicit opt-in; the push/pop owner is the SSH session (slice E). ## Wire summary (verified against the upstream spec) diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index 4abe578ef6..b604ecc5ed 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -2352,8 +2352,22 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { status!( "world ssh over iroh: `id world ssh-tunnel ` then `ssh -p 2222 @127.0.0.1`" ); + // #787 Slice E: kitty keyboard negotiation is opt-in per server, + // for worlds compiled with the extended Key module; every other + // world keeps the legacy input semantics by default. + let kitty_keyboard = std::env::var("ID_WORLD_SSH_KITTY_KEYBOARD") + .is_ok_and(|value| value == "1" || value.eq_ignore_ascii_case("true")); + if kitty_keyboard { + status!( + "world ssh kitty keyboard: enabled (kitty-disambiguate-v1, negotiated per session)" + ); + } + let options = id_worlds::world_ssh::SshServeOptions { kitty_keyboard }; tokio::spawn(async move { - if let Err(e) = id_worlds::world_ssh::serve(listener, hub, host_key, blobs).await { + if let Err(e) = + id_worlds::world_ssh::serve_with_options(listener, hub, host_key, blobs, options) + .await + { tracing::error!("world ssh server error: {}", e); } }) diff --git a/pkgs/id/src/input_framing.rs b/pkgs/id/crates/id-worlds/src/input_framing.rs similarity index 97% rename from pkgs/id/src/input_framing.rs rename to pkgs/id/crates/id-worlds/src/input_framing.rs index aea0fbb912..c91bc458f9 100644 --- a/pkgs/id/src/input_framing.rs +++ b/pkgs/id/crates/id-worlds/src/input_framing.rs @@ -7,10 +7,13 @@ //! token per complete key, independent of how the transport split the stream. //! Plain text emits one token per Unicode scalar. //! -//! The module is deliberately **inert**: `world_ssh` does not call it, the -//! durable `Input(Vec)` event is unchanged and no transport behaviour moves -//! yet. Slice E owns activation after F13.4 supplies detection and the reply -//! demultiplexer; [`ReplyFilter`] is the interface that demultiplexer plugs into. +//! Activation is Slice E: `world_ssh` runs one assembler per opted-in raw +//! connection whose terminal reported kitty keyboard support to the F13.4 +//! probe, after the push is verified (see `world_ssh::kitty`). Sessions that +//! are not opted in, or whose terminal did not report support, never touch +//! this module and keep the legacy chunk forwarding exactly. The durable +//! `Input(Vec)` event is unchanged either way; [`ReplyFilter`] is the +//! interface the connection-local reply classifier plugs into. //! //! Token bytes are never rewritten: what the assembler emits is exactly the //! bytes the transport received. Framing failures are fatal by design, because diff --git a/pkgs/id/crates/id-worlds/src/lib.rs b/pkgs/id/crates/id-worlds/src/lib.rs index 1abe1a7daf..adf8b48649 100644 --- a/pkgs/id/crates/id-worlds/src/lib.rs +++ b/pkgs/id/crates/id-worlds/src/lib.rs @@ -49,6 +49,7 @@ pub mod blob_gate; pub mod chat_anchor_render; pub mod groups; pub mod guest_burn; +pub mod input_framing; pub mod program_bundle; pub mod program_gallery; pub mod program_gallery_admission; diff --git a/pkgs/id/crates/id-worlds/src/world_ssh.rs b/pkgs/id/crates/id-worlds/src/world_ssh.rs index 3e9b749690..1b21eaba95 100644 --- a/pkgs/id/crates/id-worlds/src/world_ssh.rs +++ b/pkgs/id/crates/id-worlds/src/world_ssh.rs @@ -64,7 +64,9 @@ use crate::world_session::{ use crate::world_session::{ Inbound, SessionConfig, SessionIo, encode_hex, run_session, run_session_with, }; -use crate::world_terminal::{PROBE_QUERIES, PROBE_TIMEOUT, ProbeDemux, TierPresenter}; +use crate::world_terminal::{ + PROBE_QUERIES, PROBE_TIMEOUT, ProbeDemux, ProbeOutcome, TierPresenter, +}; /// File, beside the other server keys, that holds the SSH host key. pub const SSH_HOST_KEY_FILE: &str = ".ssh-host-key"; @@ -172,6 +174,23 @@ const MAX_VIEWPORT_WIDTH: u32 = 500; /// Tallest viewport a `resize` frame may name (shell contract v1). const MAX_VIEWPORT_HEIGHT: u32 = 200; +/// Adapter-local options for the world SSH server. +/// +/// Every option defaults to the legacy behavior; an option is a rollout +/// safeguard for the operator, not a capability claim — a session only +/// changes behavior when its own terminal proves support at runtime. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SshServeOptions { + /// Opt raw sessions into `kitty-disambiguate-v1` negotiation (#787 + /// Slice E): on a session whose terminal reported kitty keyboard + /// support to the F13.4 startup probe, push the disambiguation flag, + /// verify it took effect, and frame input into complete key tokens. + /// The operator opts in only for worlds compiled with the extended + /// Key module (or an equivalent decoder); older compiled guests must + /// stay on the default, where input keeps its legacy chunk semantics. + pub kitty_keyboard: bool, +} + /// Serve SSH connections until the listener fails. pub async fn serve( listener: TcpListener, @@ -179,7 +198,19 @@ pub async fn serve( host_key: PrivateKey, blobs: iroh_blobs::api::Store, ) -> std::io::Result<()> { - serve_limited(listener, hub, host_key, blobs, MAX_CONNECTIONS).await + serve_with_options(listener, hub, host_key, blobs, SshServeOptions::default()).await +} + +/// Serve SSH connections with explicit adapter options, until the +/// listener fails. +pub async fn serve_with_options( + listener: TcpListener, + hub: WorldHub, + host_key: PrivateKey, + blobs: iroh_blobs::api::Store, + options: SshServeOptions, +) -> std::io::Result<()> { + serve_limited(listener, hub, host_key, blobs, MAX_CONNECTIONS, options).await } async fn serve_limited( @@ -188,6 +219,7 @@ async fn serve_limited( host_key: PrivateKey, blobs: iroh_blobs::api::Store, max_connections: usize, + options: SshServeOptions, ) -> std::io::Result<()> { let config = Arc::new(Config { keys: vec![host_key], @@ -200,6 +232,7 @@ async fn serve_limited( hub, blobs, connections: Arc::new(Semaphore::new(max_connections)), + options, }; server.run_on_socket(config, &listener).await } @@ -274,6 +307,7 @@ struct SshServer { hub: WorldHub, blobs: iroh_blobs::api::Store, connections: Arc, + options: SshServeOptions, } impl Server for SshServer { @@ -290,6 +324,7 @@ impl Server for SshServer { dropped_input: Arc::new(AtomicUsize::new(0)), exec: None, exec_backlog: Arc::new(AtomicUsize::new(0)), + options: self.options, } } } @@ -325,6 +360,8 @@ struct SshClient { exec: Option>>, /// Bytes queued on `exec` and not yet read by the session. exec_backlog: Arc, + /// Adapter options the server was started with, handed to each shell. + options: SshServeOptions, } enum SshInputFrame { @@ -572,6 +609,11 @@ impl Handler for SshClient { previous_screen: None, probe_tty, probe: None, + probe_outcome: None, + kitty_opt_in: self.options.kitty_keyboard, + kitty: kitty::KittyKeyboard::new(), + kitty_drop_baseline: 0, + kitty_verify_deadline: None, presenter: None, active_form: None, form_line: Vec::new(), @@ -592,6 +634,7 @@ impl Handler for SshClient { io.enter_alt_screen().await; io.start_terminal_probe().await; run_session_with(&hub, &mut io, config).await; + io.restore_kitty_keyboard().await; if io.errored { tokio::time::sleep(REFUSED_SHELL_DELAY).await; } @@ -832,6 +875,21 @@ struct SshIo { probe_tty: bool, /// Bounded startup probe state while the reply window is open. probe: Option, + /// The probe's outcome, retained when its window closed so the raw + /// input path can act on the detected kitty keyboard support after + /// the held pre-activation bytes have drained (Slice E of #787). + probe_outcome: Option, + /// Server opt-in for kitty keyboard negotiation (#787 Slice E). Raw + /// sessions only; command and explorer sessions never negotiate. + kitty_opt_in: bool, + /// Kitty activation state for this connection (#787 Slice E). + kitty: kitty::KittyKeyboard, + /// Dropped-input counter value when kitty verification began; growth + /// past it while engaged means the transport lost bytes the assembler + /// never saw, which is fatal to the active stream. + kitty_drop_baseline: usize, + /// Absolute deadline for the outstanding kitty flags verification. + kitty_verify_deadline: Option, /// Tier presenter selected when the startup probe closed (F13.4). /// Absent until then, and for callers that never probed: those keep /// the pre-F13.4 rendering path exactly. @@ -856,6 +914,15 @@ struct SshIo { pending_form_answer: Option, } +/// One unit of raw input read while kitty framing is engaged (#787 +/// Slice E): a complete key token (or, just after a fallback, one legacy +/// chunk), a resize, or the end of the stream. +enum KittyRead { + Token(Vec), + Resize(SshInputFrame), + Closed, +} + /// The one startup probe window of a raw SSH session. #[derive(Debug)] struct SshProbe { @@ -907,6 +974,7 @@ fn prepend_dropped_input_notice(counter: &AtomicUsize, out: &mut Vec) -> Opt mod form_io; mod form_prompt; +mod kitty; use form_io::{ FormBytes, FormInputProgress, consume_form_input, discard_form_input_line, discard_form_lf_after_cr, form_closed_aliases, form_retry_alias, form_view_is_unchanged, @@ -935,7 +1003,7 @@ impl SshIo { self.discarding_form_line = false; return None; } - match recv_bytes_through_probe(&mut self.frames, &mut self.probe).await { + match self.recv_form_bytes().await { FormBytes::Bytes(bytes) => self.form_backlog.extend(bytes), FormBytes::Resize(resize) => { self.previous_screen = None; @@ -952,7 +1020,7 @@ impl SshIo { if discard_form_lf_after_cr(&mut self.form_backlog, &mut self.form_after_cr) { return None; } - match recv_bytes_through_probe(&mut self.frames, &mut self.probe).await { + match self.recv_form_bytes().await { FormBytes::Bytes(bytes) => self.form_backlog.extend(bytes), FormBytes::Resize(resize) => { self.previous_screen = None; @@ -982,7 +1050,7 @@ impl SshIo { continue; } if self.form_backlog.is_empty() { - match recv_bytes_through_probe(&mut self.frames, &mut self.probe).await { + match self.recv_form_bytes().await { FormBytes::Bytes(bytes) => self.form_backlog.extend(bytes), FormBytes::Resize(resize) => { self.previous_screen = None; @@ -1133,8 +1201,176 @@ impl SshIo { "terminal capability probe closed; tier presenter selected" ); self.presenter = Some(TierPresenter::from_outcome(&outcome)); + // Retained for the raw input path: kitty activation (Slice E of + // #787) reads the detected support from here once the held + // pre-activation bytes below have drained as legacy input. + self.probe_outcome = Some(outcome); probe.demux.expire() } + + /// Whether kitty activation may begin on this connection: the server + /// opted in, the startup probe has closed with uncontradicted kitty + /// keyboard support, and no held tokens are still draining. + fn kitty_may_activate(&self) -> bool { + self.kitty_opt_in + && !self.kitty.is_engaged() + && !self.kitty.has_held_tokens() + && self.probe.is_none() + && self + .probe_outcome + .as_ref() + .is_some_and(|outcome| outcome.profile.kitty_keyboard && !outcome.conflicted) + } + + /// Begin kitty activation when [`Self::kitty_may_activate`] holds: + /// write the profile push and the flags query as one burst. A failed + /// write retires the opt-in for this session — the terminal never saw + /// a push, so no pop is owed and input stays legacy. + async fn maybe_begin_kitty(&mut self) { + if !self.kitty_may_activate() { + return; + } + let mut burst = Vec::with_capacity(kitty::KITTY_PUSH.len() + kitty::KITTY_QUERY.len()); + burst.extend_from_slice(kitty::KITTY_PUSH); + burst.extend_from_slice(kitty::KITTY_QUERY); + if self.handle.data(self.channel, burst).await.is_err() { + self.kitty_opt_in = false; + return; + } + self.kitty_drop_baseline = self.dropped_input.load(Ordering::Relaxed); + self.kitty_verify_deadline = Some(tokio::time::Instant::now() + kitty::VERIFY_TIMEOUT); + self.kitty.begin_verify(); + } + + /// Pop the owned kitty push, if one is outstanding. Best effort, like + /// every terminal restore: a dead transport cannot guarantee delivery. + async fn pop_kitty(&mut self) { + if !self.kitty.pushed() { + return; + } + let _ = self.handle.data(self.channel, kitty::KITTY_POP).await; + self.kitty.pop_written(); + } + + /// Abandon kitty activation after a failed or unanswered verification: + /// pop the owned push and fall back to legacy input. Held tokens stay + /// queued and drain as legacy frames — their bytes are untouched. + async fn kitty_fallback(&mut self) { + self.kitty_verify_deadline = None; + self.pop_kitty().await; + self.kitty.fallback(); + tracing::debug!("kitty keyboard verification failed; session stays on legacy input"); + } + + /// Session teardown: restore the terminal's keyboard mode by popping + /// exactly the push this session owns, if any (#787 Slice E). Runs on + /// every exit path of the raw session — normal return, refused join, + /// error and cancellation all funnel through the spawn that calls + /// this — before the alternate screen is left. + async fn restore_kitty_keyboard(&mut self) { + self.pop_kitty().await; + self.kitty.reset(); + } + + /// Read the next unit of raw input while kitty is engaged. + /// + /// Verification answers are consumed by the assembler's filter and + /// never surface here; a failed or timed-out verification pops the + /// push and this call continues on the legacy path, so the caller + /// always gets the next input unit (or closure) exactly once. + async fn kitty_next(&mut self) -> KittyRead { + loop { + if let Some(token) = self.kitty.take_token() { + return KittyRead::Token(token); + } + if !self.kitty.is_engaged() { + // A fallback drained its held tokens: read one legacy + // chunk so this call still returns the next input unit. + return match self.frames.recv().await { + Some(SshInputFrame::Bytes(bytes)) => KittyRead::Token(bytes), + Some(resize @ SshInputFrame::Resize(..)) => KittyRead::Resize(resize), + None => KittyRead::Closed, + }; + } + // Queue loss is fatal while engaged: bytes the assembler never + // saw leave a gap no resynchronisation can repair (design + // §4.2). The counter is shared with the russh handler, so only + // growth past the activation baseline is this stream's loss. + if self.dropped_input.load(Ordering::Relaxed) > self.kitty_drop_baseline { + let error = self.kitty.queue_lost(); + tracing::warn!("world ssh kitty input: {error}; ending session"); + return KittyRead::Closed; + } + let verifying = self.kitty.phase() == kitty::KittyPhase::Verifying; + let wake = match (verifying, self.kitty.has_partial_token()) { + (true, _) => self.kitty_verify_deadline, + (false, true) => Some( + tokio::time::Instant::now() + crate::input_framing::INCOMPLETE_TOKEN_DEADLINE, + ), + (false, false) => None, + }; + let received = match wake { + Some(deadline) => tokio::select! { + frame = self.frames.recv() => Some(frame), + () = tokio::time::sleep_until(deadline) => None, + }, + None => Some(self.frames.recv().await), + }; + match received { + Some(Some(SshInputFrame::Bytes(bytes))) => { + if let Err(error) = self.kitty.feed(&bytes, std::time::Instant::now()) { + tracing::warn!("world ssh kitty input: {error}; ending session"); + return KittyRead::Closed; + } + if self.kitty.verify_failed() { + self.kitty_fallback().await; + } + } + Some(Some(resize @ SshInputFrame::Resize(..))) => { + return KittyRead::Resize(resize); + } + Some(None) => { + if let Err(error) = self.kitty.finish() { + tracing::warn!( + "world ssh kitty input: {error}; ending session at end of input" + ); + } + return KittyRead::Closed; + } + None => { + // A wake deadline passed with no new bytes. + if verifying + && self + .kitty_verify_deadline + .is_some_and(|deadline| tokio::time::Instant::now() >= deadline) + { + self.kitty_verify_deadline = None; + self.kitty_fallback().await; + } else if let Err(error) = + self.kitty.check_token_deadline(std::time::Instant::now()) + { + tracing::warn!("world ssh kitty input: {error}; ending session"); + return KittyRead::Closed; + } + } + } + } + } + + /// Fetch the next form-path byte unit: through the kitty assembler + /// while it is engaged (form answers are terminal input too, and the + /// stream must not desynchronise around them), otherwise through the + /// probe-aware legacy fetch. + async fn recv_form_bytes(&mut self) -> FormBytes { + if self.kitty.is_engaged() { + return match self.kitty_next().await { + KittyRead::Token(bytes) => FormBytes::Bytes(bytes), + KittyRead::Resize(resize) => FormBytes::Resize(resize), + KittyRead::Closed => FormBytes::Closed, + }; + } + recv_bytes_through_probe(&mut self.frames, &mut self.probe, &mut self.probe_outcome).await + } } impl SessionIo for SshIo { @@ -1170,43 +1406,66 @@ impl SessionIo for SshIo { return self.recv_form_answer().await; } match self.mode { - ShellMode::Raw => loop { - let Some(deadline) = self.probe.as_ref().map(|probe| probe.deadline) else { - return self - .frames - .recv() - .await - .map_or(Inbound::Closed, |input| Inbound::Text(raw_frame(&input))); - }; - // Cancel-safe: the probe stays in place across the await, and - // bytes received in an earlier call are held in its demux. - let received = tokio::select! { - frame = self.frames.recv() => Some(frame), - () = tokio::time::sleep_until(deadline) => None, - }; - match received { - Some(Some(SshInputFrame::Bytes(bytes))) => { - let input = self - .probe - .as_mut() - .map_or_else(Vec::new, |probe| probe.demux.push(&bytes)); - if !input.is_empty() { - return Inbound::Text(raw_frame(&SshInputFrame::Bytes(input))); + ShellMode::Raw => { + // Kitty activation (#787 Slice E): once the probe has + // closed with detected support on an opted-in server, + // begin negotiation; while engaged, input arrives as + // framed key tokens. Tokens held by a verification + // fallback drain first, as legacy frames, bytes untouched. + self.maybe_begin_kitty().await; + if self.kitty.is_engaged() { + return match self.kitty_next().await { + KittyRead::Token(bytes) => { + Inbound::Text(raw_frame(&SshInputFrame::Bytes(bytes))) } - } - Some(Some(resize @ SshInputFrame::Resize(..))) => { - self.previous_screen = None; - return Inbound::Text(raw_frame(&resize)); - } - Some(None) => return Inbound::Closed, - None => { - let held = self.close_terminal_probe(); - if !held.is_empty() { - return Inbound::Text(raw_frame(&SshInputFrame::Bytes(held))); + KittyRead::Resize(resize) => { + self.previous_screen = None; + Inbound::Text(raw_frame(&resize)) + } + KittyRead::Closed => Inbound::Closed, + }; + } + if let Some(token) = self.kitty.take_token() { + return Inbound::Text(raw_frame(&SshInputFrame::Bytes(token))); + } + loop { + let Some(deadline) = self.probe.as_ref().map(|probe| probe.deadline) else { + return self + .frames + .recv() + .await + .map_or(Inbound::Closed, |input| Inbound::Text(raw_frame(&input))); + }; + // Cancel-safe: the probe stays in place across the await, and + // bytes received in an earlier call are held in its demux. + let received = tokio::select! { + frame = self.frames.recv() => Some(frame), + () = tokio::time::sleep_until(deadline) => None, + }; + match received { + Some(Some(SshInputFrame::Bytes(bytes))) => { + let input = self + .probe + .as_mut() + .map_or_else(Vec::new, |probe| probe.demux.push(&bytes)); + if !input.is_empty() { + return Inbound::Text(raw_frame(&SshInputFrame::Bytes(input))); + } + } + Some(Some(resize @ SshInputFrame::Resize(..))) => { + self.previous_screen = None; + return Inbound::Text(raw_frame(&resize)); + } + Some(None) => return Inbound::Closed, + None => { + let held = self.close_terminal_probe(); + if !held.is_empty() { + return Inbound::Text(raw_frame(&SshInputFrame::Bytes(held))); + } } } } - }, + } ShellMode::Command => loop { if let Some(command) = self.commands.pop_front() { if let Some(frame) = command_frame(&command, &self.capability) { @@ -2503,6 +2762,15 @@ mod tests { hub: WorldHub, blobs: iroh_blobs::api::Store, max_connections: usize, + ) -> (u16, tokio::task::JoinHandle>) { + start_with_options(hub, blobs, max_connections, SshServeOptions::default()).await + } + + async fn start_with_options( + hub: WorldHub, + blobs: iroh_blobs::api::Store, + max_connections: usize, + options: SshServeOptions, ) -> (u16, tokio::task::JoinHandle>) { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); @@ -2515,6 +2783,7 @@ mod tests { host_key, blobs, max_connections, + options, )), ) } @@ -2952,6 +3221,279 @@ mod tests { server.abort(); } + /// A lobby world with an event subscription and a join capability: + /// the kitty tests' stage (#787 Slice E). + async fn kitty_stage( + hub: &WorldHub, + name: &str, + ) -> ( + tokio::sync::broadcast::Receiver, + String, + ) { + let world = hub + .lease(None, Some("admin")) + .await + .unwrap() + .service() + .world() + .clone(); + let events = world.subscribe(); + let invite = hub + .lease(None, Some("admin")) + .await + .unwrap() + .service() + .invite(Some("admin"), name.to_owned(), None, None) + .await + .unwrap(); + let capability = serde_json::to_value(invite).unwrap()["capability"] + .as_str() + .unwrap() + .to_owned(); + (events, capability) + } + + fn count_bytes(bytes: &[u8], needle: &[u8]) -> usize { + bytes + .windows(needle.len()) + .filter(|window| *window == needle) + .count() + } + + /// Read channel output until `needle` appears or the timeout lapses; + /// returns everything read either way. + async fn read_until_bytes( + channel: &mut Channel, + needle: &[u8], + timeout: Duration, + ) -> Vec { + let mut bytes = Vec::new(); + let _ = tokio::time::timeout(timeout, async { + while count_bytes(&bytes, needle) == 0 { + match channel.wait().await { + Some(ChannelMsg::Data { data }) => bytes.extend_from_slice(&data), + Some(_) => {} + None => break, + } + } + }) + .await; + bytes + } + + /// Collect the next `want` world Input events (fewer on timeout). + async fn collect_inputs( + events: &mut tokio::sync::broadcast::Receiver, + want: usize, + ) -> Vec> { + let mut inputs = Vec::new(); + let _ = tokio::time::timeout(Duration::from_secs(10), async { + while inputs.len() < want { + match events.recv().await { + Ok(event) => { + if let crate::world::WorldEventKind::Input(bytes) = event.kind { + inputs.push(bytes); + } + } + Err(_) => break, + } + } + }) + .await; + inputs + } + + #[tokio::test] + async fn kitty_opt_in_negotiates_verifies_and_frames_split_input() { + let hub = lobby_hub(); + let (mut events, capability) = kitty_stage(&hub, "ssh-kitty").await; + let (port, server) = start_with_options( + hub, + test_store(), + MAX_CONNECTIONS, + SshServeOptions { + kitty_keyboard: true, + }, + ) + .await; + let session = connect(port, &capability).await; + let mut channel = shell(&session).await; + + // The F13.4 probe runs first; answer that the terminal speaks the + // kitty keyboard protocol (flags currently 0). + let probed = read_until_bytes(&mut channel, PROBE_QUERIES, Duration::from_secs(10)).await; + assert_eq!(count_bytes(&probed, PROBE_QUERIES), 1); + channel.data(b"\x1b[?0u".as_slice()).await.unwrap(); + + // Detection precedes negotiation: only now may the push + verify + // query burst appear, exactly once. + let burst = + read_until_bytes(&mut channel, kitty::KITTY_PUSH, Duration::from_secs(10)).await; + assert_eq!( + count_bytes(&burst, b"\x1b[>1u\x1b[?u"), + 1, + "one push + verify burst after detection" + ); + // The terminal applies the push and reports the flag back. + channel.data(b"\x1b[?1u".as_slice()).await.unwrap(); + + // A kitty key split across transport chunks, then Escape, Alt+x + // and a plain key: four complete tokens, in order, with the + // verification reply nowhere in world input. + channel.data(b"\x1b[97;".as_slice()).await.unwrap(); + channel.data(b"5u".as_slice()).await.unwrap(); + channel.data(b"\x1b[27u".as_slice()).await.unwrap(); + channel.data(b"\x1b[120;3u".as_slice()).await.unwrap(); + channel.data(b"z".as_slice()).await.unwrap(); + let inputs = collect_inputs(&mut events, 4).await; + assert_eq!( + inputs, + vec![ + b"\x1b[97;5u".to_vec(), + b"\x1b[27u".to_vec(), + b"\x1b[120;3u".to_vec(), + b"z".to_vec(), + ], + "framed tokens, distinct Escape vs Alt, no reply bytes journaled" + ); + + // Teardown pops exactly the owned push before the channel closes. + channel.eof().await.unwrap(); + let mut tail = Vec::new(); + let _ = tokio::time::timeout(Duration::from_secs(10), async { + loop { + match channel.wait().await { + Some(ChannelMsg::Data { data }) => tail.extend_from_slice(&data), + Some(_) => {} + None => break, + } + } + }) + .await; + assert_eq!( + count_bytes(&tail, kitty::KITTY_POP), + 1, + "one pop restores the terminal on exit" + ); + server.abort(); + } + + #[tokio::test] + async fn kitty_opt_in_falls_back_when_the_push_does_not_take() { + let hub = lobby_hub(); + let (mut events, capability) = kitty_stage(&hub, "ssh-kitty-fallback").await; + let (port, server) = start_with_options( + hub, + test_store(), + MAX_CONNECTIONS, + SshServeOptions { + kitty_keyboard: true, + }, + ) + .await; + let session = connect(port, &capability).await; + let mut channel = shell(&session).await; + + read_until_bytes(&mut channel, PROBE_QUERIES, Duration::from_secs(10)).await; + channel.data(b"\x1b[?0u".as_slice()).await.unwrap(); + read_until_bytes(&mut channel, kitty::KITTY_PUSH, Duration::from_secs(10)).await; + + // A key typed during verification is held, then the flags answer + // says the push did not take: the session must pop and fall back. + channel.data(b"q".as_slice()).await.unwrap(); + channel.data(b"\x1b[?0u".as_slice()).await.unwrap(); + let popped = + read_until_bytes(&mut channel, kitty::KITTY_POP, Duration::from_secs(10)).await; + assert_eq!( + count_bytes(&popped, kitty::KITTY_POP), + 1, + "failed push is popped" + ); + + // The held key is delivered with its bytes untouched, and later + // input keeps legacy chunk semantics. + assert_eq!(collect_inputs(&mut events, 1).await, vec![b"q".to_vec()]); + channel.data(b"hi".as_slice()).await.unwrap(); + assert_eq!(collect_inputs(&mut events, 1).await, vec![b"hi".to_vec()]); + server.abort(); + } + + #[tokio::test] + async fn kitty_stays_off_without_the_server_opt_in() { + let hub = lobby_hub(); + let (mut events, capability) = kitty_stage(&hub, "ssh-kitty-default").await; + let (port, server) = start(hub).await; + let session = connect(port, &capability).await; + let mut channel = shell(&session).await; + + read_until_bytes(&mut channel, PROBE_QUERIES, Duration::from_secs(10)).await; + // The terminal would support kitty — but the default is legacy. + channel.data(b"\x1b[?0u".as_slice()).await.unwrap(); + let mut heard = Vec::new(); + let _ = tokio::time::timeout(Duration::from_millis(1200), async { + loop { + match channel.wait().await { + Some(ChannelMsg::Data { data }) => heard.extend_from_slice(&data), + Some(_) => {} + None => break, + } + } + }) + .await; + assert_eq!( + count_bytes(&heard, kitty::KITTY_PUSH), + 0, + "no negotiation without the opt-in" + ); + channel.data(b"\x1b[97;5u".as_slice()).await.unwrap(); + assert_eq!( + collect_inputs(&mut events, 1).await, + vec![b"\x1b[97;5u".to_vec()], + "legacy chunk forwarding is unchanged" + ); + server.abort(); + } + + #[tokio::test] + async fn kitty_stays_off_when_the_terminal_reports_no_support() { + let hub = lobby_hub(); + let (mut events, capability) = kitty_stage(&hub, "ssh-kitty-unsupported").await; + let (port, server) = start_with_options( + hub, + test_store(), + MAX_CONNECTIONS, + SshServeOptions { + kitty_keyboard: true, + }, + ) + .await; + let session = connect(port, &capability).await; + let mut channel = shell(&session).await; + + read_until_bytes(&mut channel, PROBE_QUERIES, Duration::from_secs(10)).await; + // Only a cursor-position reply: no kitty keyboard evidence. + channel.data(b"\x1b[12;40R".as_slice()).await.unwrap(); + let mut heard = Vec::new(); + let _ = tokio::time::timeout(Duration::from_millis(1200), async { + loop { + match channel.wait().await { + Some(ChannelMsg::Data { data }) => heard.extend_from_slice(&data), + Some(_) => {} + None => break, + } + } + }) + .await; + assert_eq!( + count_bytes(&heard, kitty::KITTY_PUSH), + 0, + "no push on an unsupported terminal" + ); + channel.data(b"ab".as_slice()).await.unwrap(); + assert_eq!(collect_inputs(&mut events, 1).await, vec![b"ab".to_vec()]); + server.abort(); + } + #[tokio::test] async fn a_shell_without_a_pty_sends_no_probe_bytes() { let hub = lobby_hub(); @@ -3935,7 +4477,7 @@ mod tests { tx.send(SshInputFrame::Bytes(b"{\"action\":\"submit\"}\n".to_vec())) .await .unwrap(); - match recv_bytes_through_probe(&mut rx, &mut probe).await { + match recv_bytes_through_probe(&mut rx, &mut probe, &mut None).await { FormBytes::Bytes(bytes) => { assert_eq!(bytes, b"{\"action\":\"submit\"}\n".to_vec()) } @@ -3956,7 +4498,7 @@ mod tests { tx2.send(SshInputFrame::Bytes(b"\x1b[".to_vec())) .await .unwrap(); - match recv_bytes_through_probe(&mut rx2, &mut probe2).await { + match recv_bytes_through_probe(&mut rx2, &mut probe2, &mut None).await { FormBytes::Bytes(bytes) => assert_eq!(bytes, b"\x1b[".to_vec()), _ => panic!("expected held bytes at probe expiry"), } diff --git a/pkgs/id/crates/id-worlds/src/world_ssh/form_io.rs b/pkgs/id/crates/id-worlds/src/world_ssh/form_io.rs index 58653a67c5..44bd332c6d 100644 --- a/pkgs/id/crates/id-worlds/src/world_ssh/form_io.rs +++ b/pkgs/id/crates/id-worlds/src/world_ssh/form_io.rs @@ -10,6 +10,7 @@ use tokio::sync::mpsc; use crate::world_presentation::FormSurface; use super::{Inbound, MAX_FORM_RESPONSE_BYTES, SshInputFrame, SshProbe, terminal_text}; +use crate::world_terminal::ProbeOutcome; /// The retry alias recorded for a rejected form answer: /// `(form_id, view_token, current_token)`. @@ -250,6 +251,7 @@ pub(super) enum FormBytes { pub(super) async fn recv_bytes_through_probe( frames: &mut mpsc::Receiver, probe: &mut Option, + probe_outcome: &mut Option, ) -> FormBytes { loop { let Some(deadline) = probe.as_ref().map(|probe| probe.deadline) else { @@ -287,6 +289,10 @@ pub(super) async fn recv_bytes_through_probe( ?tier, "terminal capability probe closed; Tier 3 fallback stays active" ); + // The outcome is retained even on this path, so + // kitty activation (#787 Slice E) can still read + // the detected support once the form closes. + *probe_outcome = Some(probe.demux.outcome()); probe.demux.expire() } None => Vec::new(), diff --git a/pkgs/id/crates/id-worlds/src/world_ssh/kitty.rs b/pkgs/id/crates/id-worlds/src/world_ssh/kitty.rs new file mode 100644 index 0000000000..f61d1a9acd --- /dev/null +++ b/pkgs/id/crates/id-worlds/src/world_ssh/kitty.rs @@ -0,0 +1,336 @@ +//! Kitty keyboard activation state for one raw SSH connection. +//! +//! Slice E of #787 (`doc/2026-11-01_design_id787.md` §4.3 and §6 row E), +//! implementing the `kitty-disambiguate-v1` profile +//! (`doc/2026-11-02T_reference_kitty_disambiguate_v1.md`): push the +//! disambiguation flag, verify with the flags query before admitting any +//! active key, frame the stream with the Slice B assembler, and pop exactly +//! the owned push on teardown or fallback. +//! +//! This state exists only on a raw session whose server opted in AND whose +//! terminal reported kitty keyboard support to the F13.4 startup probe. +//! Every other session keeps the legacy chunk forwarding untouched. Token +//! bytes are never rewritten, and nothing here is journaled: probe, +//! verification and push/pop bytes are control plane only, so the durable +//! `Input(Vec)` event keeps carrying exactly the key bytes it always +//! did — now framed one complete key token per event instead of one +//! transport chunk. + +use std::collections::VecDeque; +use std::time::Duration; + +use crate::input_framing::{AssemblyError, InputAssembler, Limits, ReplyDisposition, ReplyFilter}; + +/// Push the disambiguation flag of `kitty-disambiguate-v1` (`CSI > 1 u`). +pub const KITTY_PUSH: &[u8] = b"\x1b[>1u"; +/// Pop one keyboard-mode stack entry (`CSI < u`): removes exactly the push +/// above, never a mode the terminal or another client owned. +pub const KITTY_POP: &[u8] = b"\x1b[ u`. The F13.4 probe burst already asks this once +/// for support detection; activation asks again after the push, because only +/// the post-push report proves the push took effect. +pub const KITTY_QUERY: &[u8] = b"\x1b[?u"; +/// The one flag this profile requests: disambiguate escape codes. +const DISAMBIGUATE_FLAG: u32 = 1; +/// How long the terminal gets to answer the post-push flags query before +/// the session falls back to legacy input. One round trip, on the scale of +/// the F13.4 probe window (250 ms) with headroom for a loaded terminal. +pub const VERIFY_TIMEOUT: Duration = Duration::from_millis(500); + +/// Where one connection sits in the activation lifecycle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KittyPhase { + /// No push outstanding; input follows the legacy path. + Inactive, + /// Push sent and query outstanding; assembled tokens are held, not + /// admitted, until the flags report proves the push took effect. + Verifying, + /// Verified: tokens are admitted as they complete. + Active, +} + +/// Classifies the one outstanding verification reply. +/// +/// Only the exact `CSI ? u` answer to our own query is consumed, +/// and only while that query is outstanding; every other token — including +/// a flags-shaped token at any other time — is application input, per the +/// design's ban on unrestricted reply filters (§4.3). +#[derive(Debug, Default)] +struct VerifyFilter { + /// A flags query is outstanding and its answer is still due. + outstanding: bool, + /// The answer, once seen: whether it carried the disambiguation flag. + answered: Option, +} + +impl VerifyFilter { + /// Parse a complete token as a kitty flags report, returning its flags. + fn flags_report(token: &[u8]) -> Option { + let body = token.strip_prefix(b"\x1b[?")?.strip_suffix(b"u")?; + if body.is_empty() || !body.iter().all(u8::is_ascii_digit) { + return None; + } + body.iter().try_fold(0_u32, |value, digit| { + value.checked_mul(10)?.checked_add(u32::from(*digit - b'0')) + }) + } +} + +impl ReplyFilter for VerifyFilter { + fn classify(&mut self, token: &[u8]) -> ReplyDisposition { + if self.outstanding + && let Some(flags) = Self::flags_report(token) + { + self.outstanding = false; + self.answered = Some(flags & DISAMBIGUATE_FLAG != 0); + return ReplyDisposition::Consume; + } + ReplyDisposition::Forward + } +} + +/// Per-connection kitty keyboard state: phase, assembler, held tokens. +/// +/// Held tokens are admitted in arrival order. On a verification fallback +/// the held tokens stay queued and the caller drains them as legacy input +/// frames — their bytes are exactly what the terminal sent, so the +/// fallback loses framing, never bytes. +#[derive(Debug)] +pub struct KittyKeyboard { + phase: KittyPhase, + assembler: InputAssembler, + filter: VerifyFilter, + tokens: VecDeque>, + /// Whether our push was written to the terminal. Tracked across + /// fallback and teardown so exactly one pop is owed, and only then. + pushed: bool, +} + +impl Default for KittyKeyboard { + fn default() -> Self { + Self::new() + } +} + +impl KittyKeyboard { + /// A fresh, inactive state. + #[must_use] + pub fn new() -> Self { + Self { + phase: KittyPhase::Inactive, + assembler: InputAssembler::new(Limits::default()), + filter: VerifyFilter::default(), + tokens: VecDeque::new(), + pushed: false, + } + } + + /// The current lifecycle phase. + #[must_use] + pub const fn phase(&self) -> KittyPhase { + self.phase + } + + /// Whether the push/verify machinery is engaged (verifying or active). + /// Inactive sessions never route input through here. + #[must_use] + pub const fn is_engaged(&self) -> bool { + !matches!(self.phase, KittyPhase::Inactive) + } + + /// Whether our push is outstanding and a pop is owed on teardown. + #[must_use] + pub const fn pushed(&self) -> bool { + self.pushed + } + + /// Held tokens are still draining (post-fallback legacy frames). + #[must_use] + pub fn has_held_tokens(&self) -> bool { + !self.tokens.is_empty() + } + + /// Begin verification after the caller has written the push and query. + /// The caller owns the write (and its failure); this records that the + /// push is owed a pop and that one flags answer is due. + pub fn begin_verify(&mut self) { + self.phase = KittyPhase::Verifying; + self.pushed = true; + self.filter.outstanding = true; + self.filter.answered = None; + } + + /// Feed one transport chunk through the assembler and the verification + /// filter, holding every completed token in order. A flags answer that + /// carries the disambiguation flag flips the phase to active at once; + /// one without it is left for the caller to observe via + /// [`Self::verify_failed`] so it can pop and fall back. + /// + /// # Errors + /// + /// Returns the assembler's fatal framing error; the caller must close + /// the active session (a missing prefix cannot be resynchronised). + pub fn feed(&mut self, bytes: &[u8], now: std::time::Instant) -> Result<(), AssemblyError> { + let tokens = self.assembler.push_filtered(bytes, now, &mut self.filter)?; + self.tokens.extend(tokens); + if self.phase == KittyPhase::Verifying && self.filter.answered == Some(true) { + self.phase = KittyPhase::Active; + } + Ok(()) + } + + /// The verification query was answered and the flags do NOT include + /// disambiguation: the push did not take effect. + #[must_use] + pub const fn verify_failed(&self) -> bool { + matches!(self.phase, KittyPhase::Verifying) && matches!(self.filter.answered, Some(false)) + } + + /// Take the next held token, in arrival order. + pub fn take_token(&mut self) -> Option> { + self.tokens.pop_front() + } + + /// Fail if a partial token has outlived the assembler's deadline. + /// + /// # Errors + /// + /// Returns [`AssemblyError::IncompleteToken`] past the deadline; the + /// caller must close the active session. + pub fn check_token_deadline(&mut self, now: std::time::Instant) -> Result<(), AssemblyError> { + self.assembler.check_deadline(now) + } + + /// Whether a partial token is pending (its deadline is worth a timer). + #[must_use] + pub const fn has_partial_token(&self) -> bool { + !self.assembler.is_empty() + } + + /// End of input: fail if a token is still incomplete, so a truncated + /// escape tail never becomes ordinary application text. + /// + /// # Errors + /// + /// Returns [`AssemblyError::IncompleteToken`] when bytes are pending. + pub fn finish(&mut self) -> Result<(), AssemblyError> { + self.assembler.finish() + } + + /// Signal transport queue loss: queued bytes the assembler never saw + /// are a fatal gap in active mode. + pub fn queue_lost(&mut self) -> AssemblyError { + self.assembler.queue_lost() + } + + /// Abandon activation and return to the legacy path: the assembler and + /// filter reset, held tokens stay queued for the caller to drain as + /// legacy frames, and the push (if any) is handed back as still owed — + /// the caller writes the pop. Returns whether a pop is owed. + pub fn fallback(&mut self) -> bool { + self.phase = KittyPhase::Inactive; + self.assembler = InputAssembler::new(Limits::default()); + self.filter = VerifyFilter::default(); + self.pushed + } + + /// Full reset for teardown, after the caller has written any owed pop. + pub fn reset(&mut self) { + *self = Self::new(); + } + + /// Record that the owed pop has been written. + pub fn pop_written(&mut self) { + self.pushed = false; + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn now() -> std::time::Instant { + std::time::Instant::now() + } + + #[test] + fn flags_reports_parse_only_the_exact_shape() { + assert_eq!(VerifyFilter::flags_report(b"\x1b[?0u"), Some(0)); + assert_eq!(VerifyFilter::flags_report(b"\x1b[?1u"), Some(1)); + assert_eq!(VerifyFilter::flags_report(b"\x1b[?15u"), Some(15)); + // Not flags reports: the push form, a key event, a partial token. + assert_eq!(VerifyFilter::flags_report(b"\x1b[>1u"), None); + assert_eq!(VerifyFilter::flags_report(b"\x1b[97;5u"), None); + assert_eq!(VerifyFilter::flags_report(b"\x1b[?u"), None); + assert_eq!(VerifyFilter::flags_report(b"\x1b[?1;2u"), None); + } + + #[test] + fn the_filter_consumes_only_the_outstanding_answer() { + let mut filter = VerifyFilter { + outstanding: true, + answered: None, + }; + // A key coalesced before the answer stays input. + assert_eq!(filter.classify(b"x"), ReplyDisposition::Forward); + assert_eq!(filter.classify(b"\x1b[?1u"), ReplyDisposition::Consume); + assert_eq!(filter.answered, Some(true)); + // Nothing is outstanding now: a later flags-shaped token is input. + assert_eq!(filter.classify(b"\x1b[?1u"), ReplyDisposition::Forward); + } + + #[test] + fn verification_flips_active_only_on_the_disambiguate_flag() { + let mut kitty = KittyKeyboard::new(); + kitty.begin_verify(); + kitty.feed(b"\x1b[?1u", now()).unwrap(); + assert_eq!(kitty.phase(), KittyPhase::Active); + // The answer itself never becomes a held token. + assert!(!kitty.has_held_tokens()); + + let mut refused = KittyKeyboard::new(); + refused.begin_verify(); + refused.feed(b"\x1b[?4u", now()).unwrap(); + assert_eq!(refused.phase(), KittyPhase::Verifying); + assert!(refused.verify_failed()); + } + + #[test] + fn keys_coalesced_with_the_answer_keep_their_order() { + let mut kitty = KittyKeyboard::new(); + kitty.begin_verify(); + kitty.feed(b"a\x1b[?1u\x1b[97;5u", now()).unwrap(); + assert_eq!(kitty.phase(), KittyPhase::Active); + assert_eq!(kitty.take_token().unwrap(), b"a".to_vec()); + assert_eq!(kitty.take_token().unwrap(), b"\x1b[97;5u".to_vec()); + assert_eq!(kitty.take_token(), None); + } + + #[test] + fn fallback_keeps_held_token_bytes_and_the_owed_pop() { + let mut kitty = KittyKeyboard::new(); + kitty.begin_verify(); + kitty.feed(b"q\x1b[9", now()).unwrap(); + assert!(kitty.fallback()); + assert!(!kitty.is_engaged()); + // The complete key survives as a legacy frame; the partial escape + // tail was assembler state and is gone with the reset. + assert_eq!(kitty.take_token().unwrap(), b"q".to_vec()); + kitty.pop_written(); + assert!(!kitty.pushed()); + } + + #[test] + fn split_tokens_complete_across_feeds() { + let mut kitty = KittyKeyboard::new(); + kitty.begin_verify(); + kitty.feed(b"\x1b[?1u", now()).unwrap(); + kitty.feed(b"\x1b[97;", now()).unwrap(); + assert!(!kitty.has_held_tokens()); + assert!(kitty.has_partial_token()); + kitty.feed(b"5u", now()).unwrap(); + assert_eq!(kitty.take_token().unwrap(), b"\x1b[97;5u".to_vec()); + } +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index dce38c2b41..415dafc8d9 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -256,7 +256,7 @@ pub mod hosted_binding; pub mod hosted_export; pub mod hosted_ingest; pub use id_events::idset; -pub mod input_framing; +pub use id_worlds::input_framing; pub use id_directory::invite; pub use id_directory::invites; pub use id_events::local_claims; diff --git a/pkgs/id/web/src/world-keyboard-optin.test.ts b/pkgs/id/web/src/world-keyboard-optin.test.ts new file mode 100644 index 0000000000..850b1c0f3f --- /dev/null +++ b/pkgs/id/web/src/world-keyboard-optin.test.ts @@ -0,0 +1,159 @@ +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, describe, expect, it, vi } from "vitest"; + +/** + * Slice F of #787: the per-connection keyboard opt-in. The page's keydown + * path must send legacy bytes by default and kitty-disambiguate-v1 bytes + * when the connection is opened with `?keyboard=kitty`, over the same + * DOM → WebSocket route the shell contract test exercises. Paste and the + * manual input form stay on their existing paths in both modes. + */ + +const here = dirname(fileURLToPath(import.meta.url)); + +/** The world page markup, read from the Rust template so the test cannot drift from it. */ +function worldPageMarkup(): string { + const source = readFileSync(resolve(here, "../../crates/id-web/src/templates.rs"), "utf8"); + const start = source.indexOf("pub fn render_world_page"); + const open = source.indexOf('r#"', start); + const close = source.indexOf('"#;', open); + if (start < 0 || open < 0 || close < 0) throw new Error("world page template not found in templates.rs"); + return source.slice(open + 3, close); +} + +type Entry = { from: "client" | "server"; frame: unknown }; + +class FakeSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static readonly all: FakeSocket[] = []; + + readyState = FakeSocket.CONNECTING; + bufferedAmount = 0; + onclose: ((event: Event) => void) | null = null; + readonly transcript: Entry[] = []; + + constructor(readonly url: string) { + super(); + FakeSocket.all.push(this); + } + + send(data: string): void { + if (this.readyState !== FakeSocket.OPEN) throw new Error(`send on a socket in state ${this.readyState}`); + this.transcript.push({ from: "client", frame: JSON.parse(data) }); + } + + close(): void { + if (this.readyState === FakeSocket.CLOSED) return; + this.readyState = FakeSocket.CLOSED; + this.dispatchEvent(new Event("close")); + } + + open(): void { + this.readyState = FakeSocket.OPEN; + this.dispatchEvent(new Event("open")); + } + + deliver(frame: Record): void { + this.transcript.push({ from: "server", frame }); + this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(frame) })); + } + + sent(type: string): Array> { + return this.transcript + .filter((entry) => entry.from === "client" && (entry.frame as { type?: string }).type === type) + .map((entry) => entry.frame as Record); + } +} + +class FakeResizeObserver { + static readonly all: FakeResizeObserver[] = []; + constructor(readonly callback: ResizeObserverCallback) { + FakeResizeObserver.all.push(this); + } + observe(): void {} + unobserve(): void {} + disconnect(): void {} + fire(): void { + this.callback([], this as unknown as ResizeObserver); + } +} + +const realWebSocket = globalThis.WebSocket; +const realResizeObserver = globalThis.ResizeObserver; + +async function bootWorld(search: string): Promise<{ root: HTMLElement; session: FakeSocket }> { + vi.resetModules(); + vi.stubGlobal("WebSocket", FakeSocket); + vi.stubGlobal("ResizeObserver", FakeResizeObserver); + sessionStorage.clear(); + window.history.pushState(null, "", `/world${search}`); + document.body.innerHTML = worldPageMarkup(); + await import("./world"); + const root = document.querySelector("[data-world-app]") as HTMLElement; + expect(root.dataset.initialized).toBe("true"); + const capability = root.querySelector("[data-world-capability]"); + if (!capability) throw new Error("missing capability input"); + capability.value = "guest-capability"; + root.querySelector("[data-world-join]")?.click(); + const session = FakeSocket.all.at(-1) as FakeSocket; + session.open(); + expect(session.sent("join")).toHaveLength(1); + return { root, session }; +} + +function keydown(root: HTMLElement, init: KeyboardEventInit): void { + const view = root.querySelector("[data-world-view]"); + if (!view) throw new Error("missing world view"); + view.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init })); +} + +function inputHexes(session: FakeSocket): unknown[] { + return session.sent("input").map((frame) => frame.data_hex); +} + +afterAll(() => { + vi.stubGlobal("WebSocket", realWebSocket); + vi.stubGlobal("ResizeObserver", realResizeObserver); + document.body.innerHTML = ""; +}); + +describe("keyboard opt-in (#787 Slice F)", () => { + it("sends legacy bytes by default: bare Escape, chunked legacy forms", async () => { + const { root, session } = await bootWorld(""); + keydown(root, { key: "Escape" }); + keydown(root, { key: "a" }); + keydown(root, { key: "ArrowUp" }); + // Legacy: Escape is the bare ESC byte — ambiguous with Alt by design + // of the legacy grammar, and unchanged by this slice. + expect(inputHexes(session)).toEqual(["1b", "61", "1b5b41"]); + }); + + it("sends kitty-disambiguate-v1 bytes with ?keyboard=kitty", async () => { + const { root, session } = await bootWorld("?keyboard=kitty"); + keydown(root, { key: "Escape" }); + keydown(root, { key: "i", ctrlKey: true }); + keydown(root, { key: "x", altKey: true }); + keydown(root, { key: "a" }); + // CSI 27 u (Escape, unambiguous), CSI 105;5 u (Ctrl+i, distinct from + // Tab), CSI 120;3 u (Alt+x, distinct from Escape-then-x), plain text. + expect(inputHexes(session)).toEqual(["1b5b323775", "1b5b3130353b3575", "1b5b3132303b3375", "61"]); + }); + + it("keeps paste and shortcut exclusions unchanged under the opt-in", async () => { + const { root, session } = await bootWorld("?keyboard=kitty"); + keydown(root, { key: "s", metaKey: true }); + expect(session.sent("input")).toHaveLength(0); + const view = root.querySelector("[data-world-view]"); + if (!view) throw new Error("missing world view"); + const paste = new Event("paste", { bubbles: true, cancelable: true }); + Object.defineProperty(paste, "clipboardData", { value: { getData: () => "pasted text" } }); + view.dispatchEvent(paste); + expect(session.sent("paste")).toEqual([{ type: "paste", text: "pasted text" }]); + expect(session.sent("input")).toHaveLength(0); + }); +}); diff --git a/pkgs/id/web/src/world-keyboard.ts b/pkgs/id/web/src/world-keyboard.ts index 8e7b31222c..e44af7ef77 100644 --- a/pkgs/id/web/src/world-keyboard.ts +++ b/pkgs/id/web/src/world-keyboard.ts @@ -115,10 +115,10 @@ export function terminalBytesForKey(event: KeyEventLike): Uint8Array | null { * Rich (kitty-disambiguate-v1) terminal encoding for world applications — * Slice C of issue #787, additive alongside the legacy encoder above. * - * This encoder is NOT used by the UI: nothing calls it yet. It exists so a - * future per-connection opt-in (Slice F) can select it, exactly as the - * design requires — `terminalBytesForKey` stays the default legacy path, - * unchanged. Parity with a terminal is equality of the events the Roc + * The UI selects this encoder only for a connection opened with + * `?keyboard=kitty` (Slice F, in world.ts); `terminalBytesForKey` stays + * the default legacy path, unchanged. Parity with a terminal is equality + * of the events the Roc * `Key.parse_events` decoder (Slice A) produces, not identical bytes: * plain UTF-8 text and a CSI-u form of the same scalar are the same event. * @@ -237,7 +237,7 @@ function unshiftedScalar(key: string): string { * anything the profile leaves Unknown (F13+, CapsLock and other * modifier-only or unsupported named keys). Multi-scalar text is not * a physical key: it stays on the text path (design §4.4). - * Unused by the UI in this slice (see the block comment above). + * Selected per connection by world.ts (see the block comment above). */ export function richTerminalBytesForKey(event: KeyEventLike): Uint8Array | null { if (event.metaKey || event.key === "Unidentified" || event.key === "Dead" || event.key === "Process") { diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index b7809269bc..5d01e86b1c 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -2,7 +2,7 @@ import { createFormPresenter, type FormPresenter, type FormSurface } from "./world-form"; import { advanceHostViewCursor, parseWorldHostViewPage, parseWorldInviteResponse } from "./world-http"; -import { terminalBytesForKey } from "./world-keyboard"; +import { richTerminalBytesForKey, terminalBytesForKey } from "./world-keyboard"; import { decodeViewPatch } from "./screen-codec"; import { parseWorldSeed } from "./world-seed"; import { applyScreenPatch, renderWorldSurface, type ScreenPatch, type ScreenSurface } from "./world-surface"; @@ -125,6 +125,16 @@ function initWorld(): void { const worldSocketPath = root.dataset.worldSocket ?? "/ws/world"; // `/world?world=arena` opens the page on that world. worldInput.value = new URLSearchParams(window.location.search).get("world") ?? ""; + // The keyboard encoder for this connection (#787 Slice F): the legacy + // encoder is the default; `?keyboard=kitty` selects the + // kitty-disambiguate-v1 rich encoder for worlds compiled with the + // extended Key module. The choice is fixed for the page's lifetime — + // switching encoders mid-connection would mix two key grammars on one + // input stream. + const encodeKey = + new URLSearchParams(window.location.search).get("keyboard") === "kitty" + ? richTerminalBytesForKey + : terminalBytesForKey; // A program-only surface (#2146 phase 2) pins its world server-side: // the rendered data-world-program wins over the ?world= parameter. if (root.dataset.worldProgram) worldInput.value = root.dataset.worldProgram; @@ -487,7 +497,7 @@ function initWorld(): void { }; view.addEventListener("keydown", (event: KeyboardEvent) => { - const bytes = terminalBytesForKey(event); + const bytes = encodeKey(event); if (!bytes) return; if (sendInputBytes(bytes)) event.preventDefault(); }); From 00520a8a3e0eb724437d2f1510472b95ccc163c7 Mon Sep 17 00:00:00 2001 From: felix Date: Mon, 23 Nov 2026 12:35:41 +0000 Subject: [PATCH 2/2] =?UTF-8?q?fix(id):=20kitty=20fallback=20is=20final=20?= =?UTF-8?q?per=20connection=20=E2=80=94=20no=20renegotiation=20loop=20(#78?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/id/crates/id-worlds/src/world_ssh.rs | 24 ++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/pkgs/id/crates/id-worlds/src/world_ssh.rs b/pkgs/id/crates/id-worlds/src/world_ssh.rs index 1b21eaba95..83fcca45c2 100644 --- a/pkgs/id/crates/id-worlds/src/world_ssh.rs +++ b/pkgs/id/crates/id-worlds/src/world_ssh.rs @@ -1254,8 +1254,12 @@ impl SshIo { /// Abandon kitty activation after a failed or unanswered verification: /// pop the owned push and fall back to legacy input. Held tokens stay - /// queued and drain as legacy frames — their bytes are untouched. + /// queued and drain as legacy frames — their bytes are untouched. The + /// opt-in retires with the fallback: one negotiation attempt per + /// connection, never a push/retry loop against a terminal that has + /// already answered (or refused to). async fn kitty_fallback(&mut self) { + self.kitty_opt_in = false; self.kitty_verify_deadline = None; self.pop_kitty().await; self.kitty.fallback(); @@ -3415,6 +3419,24 @@ mod tests { assert_eq!(collect_inputs(&mut events, 1).await, vec![b"q".to_vec()]); channel.data(b"hi".as_slice()).await.unwrap(); assert_eq!(collect_inputs(&mut events, 1).await, vec![b"hi".to_vec()]); + + // And the fallback is final for this connection: no second push. + let mut heard = Vec::new(); + let _ = tokio::time::timeout(Duration::from_millis(700), async { + loop { + match channel.wait().await { + Some(ChannelMsg::Data { data }) => heard.extend_from_slice(&data), + Some(_) => {} + None => break, + } + } + }) + .await; + assert_eq!( + count_bytes(&heard, kitty::KITTY_PUSH), + 0, + "a refused terminal is not renegotiated" + ); server.abort(); }