diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index 532e83e6397..e497b45cfb6 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -1174,6 +1174,11 @@ name = "opencode-drive" version = "0.1.0" dependencies = [ "opentui", + "serde", + "serde_json", + "tempfile", + "tokio-tungstenite", + "url", ] [[package]] diff --git a/packages/cli-rs/crates/drive/Cargo.toml b/packages/cli-rs/crates/drive/Cargo.toml index 86bbfaf050c..d50c4fb25f7 100644 --- a/packages/cli-rs/crates/drive/Cargo.toml +++ b/packages/cli-rs/crates/drive/Cargo.toml @@ -11,3 +11,11 @@ workspace = true [dependencies] opentui.workspace = true +serde.workspace = true +serde_json.workspace = true +# Only for its re-exported synchronous `tungstenite`; the endpoint runs on plain threads. +tokio-tungstenite.workspace = true +url.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/packages/cli-rs/crates/drive/src/capture.rs b/packages/cli-rs/crates/drive/src/capture.rs new file mode 100644 index 00000000000..1ba3e191405 --- /dev/null +++ b/packages/cli-rs/crates/drive/src/capture.rs @@ -0,0 +1,126 @@ +//! `ui.capture` and `ui.matches` from captured cells, as `actions.ts` reads Core's render buffer. + +use opentui::native::Capture; +use serde_json::{Value, json}; + +/// A `Frontend.CapturedFrame`: each row's cells grouped into spans of equal colors and attributes, as Core's +/// `getSpanLines` groups them. A span's width counts its cells, including the trailing cells of wide graphemes. +pub fn frame(capture: &Capture) -> Value { + let width = capture.width as usize; + let lines: Vec = capture + .cells + .chunks(width.max(1)) + .take(capture.height as usize) + .map(|row| { + let mut spans: Vec = Vec::new(); + for cell in row { + let fg = rgba(cell.fg); + let bg = rgba(cell.bg); + let attributes = cell.attributes.bits(); + match spans.last_mut() { + Some(span) + if span.fg == fg && span.bg == bg && span.attributes == attributes => + { + span.text.push_str(&cell.symbol); + span.width += 1; + } + _ => spans.push(Span { + text: cell.symbol.clone(), + fg, + bg, + attributes, + width: 1, + }), + } + } + json!({ "spans": spans.into_iter().map(Span::json).collect::>() }) + }) + .collect(); + json!({ + "cols": capture.width, + "rows": capture.height, + "cursor": [0, 0], + "lines": lines, + "images": [], + }) +} + +/// Whether the frame's text contains `text`. Rows are joined without line breaks, as Core's `getRealCharBytes` +/// returns them, so a match may run across a row's end. +pub fn matches(capture: &Capture, text: &str) -> bool { + capture + .cells + .iter() + .map(|cell| cell.symbol.as_str()) + .collect::() + .contains(text) +} + +struct Span { + text: String, + fg: [u8; 4], + bg: [u8; 4], + attributes: u8, + width: u32, +} + +impl Span { + fn json(self) -> Value { + json!({ "text": self.text, "fg": self.fg, "bg": self.bg, "attributes": self.attributes, "width": self.width }) + } +} + +fn rgba(color: opentui::style::Color) -> [u8; 4] { + [color.r, color.g, color.b, color.a] +} + +#[cfg(test)] +mod tests { + use super::*; + use opentui::native::Cell; + use opentui::style::{Attributes, Color}; + + fn cell(symbol: &str, fg: Color, attributes: Attributes) -> Cell { + Cell { + symbol: symbol.into(), + fg, + bg: Color::rgb(0, 0, 0), + attributes, + } + } + + #[test] + fn rows_group_into_spans() { + let white = Color::rgb(255, 255, 255); + let red = Color::rgb(255, 0, 0); + let capture = Capture { + width: 4, + height: 2, + cells: vec![ + cell("a", white, Attributes::NONE), + cell("b", white, Attributes::NONE), + cell("c", white, Attributes::BOLD), + cell("d", red, Attributes::BOLD), + cell("世", white, Attributes::NONE), + cell("", white, Attributes::NONE), + cell("x", white, Attributes::NONE), + cell(" ", white, Attributes::NONE), + ], + }; + let frame = frame(&capture); + assert_eq!(frame["cols"], 4); + assert_eq!(frame["cursor"], json!([0, 0])); + assert_eq!( + frame["lines"][0]["spans"], + json!([ + { "text": "ab", "fg": [255, 255, 255, 255], "bg": [0, 0, 0, 255], "attributes": 0, "width": 2 }, + { "text": "c", "fg": [255, 255, 255, 255], "bg": [0, 0, 0, 255], "attributes": 1, "width": 1 }, + { "text": "d", "fg": [255, 0, 0, 255], "bg": [0, 0, 0, 255], "attributes": 1, "width": 1 }, + ]) + ); + assert_eq!(frame["lines"][1]["spans"][0]["text"], "世x "); + assert_eq!(frame["lines"][1]["spans"][0]["width"], 4); + assert!(matches(&capture, "abcd世x")); + assert!(!matches(&capture, "abcd\n")); + } +} diff --git a/packages/cli-rs/crates/drive/src/keys.rs b/packages/cli-rs/crates/drive/src/keys.rs new file mode 100644 index 00000000000..e7fccf1ae1a --- /dev/null +++ b/packages/cli-rs/crates/drive/src/keys.rs @@ -0,0 +1,418 @@ +//! The terminal bytes Core's mock input sends for each action (`@opentui/core/testing` `createMockKeys` with +//! `kittyKeyboard: true`, as the TS simulation renderer sets it, and `createMockMouse`). The endpoint feeds them to +//! the app's input parser, so both clients parse the same bytes. + +use serde::Deserialize; + +/// `KeyCodes` in `mock-keys.ts`. +const KEY_CODES: &[(&str, &str)] = &[ + ("RETURN", "\r"), + ("LINEFEED", "\n"), + ("TAB", "\t"), + ("BACKSPACE", "\u{8}"), + ("DELETE", "\x1b[3~"), + ("HOME", "\x1b[H"), + ("END", "\x1b[F"), + ("ESCAPE", "\x1b"), + ("ARROW_UP", "\x1b[A"), + ("ARROW_DOWN", "\x1b[B"), + ("ARROW_RIGHT", "\x1b[C"), + ("ARROW_LEFT", "\x1b[D"), + ("F1", "\x1bOP"), + ("F2", "\x1bOQ"), + ("F3", "\x1bOR"), + ("F4", "\x1bOS"), + ("F5", "\x1b[15~"), + ("F6", "\x1b[17~"), + ("F7", "\x1b[18~"), + ("F8", "\x1b[19~"), + ("F9", "\x1b[20~"), + ("F10", "\x1b[21~"), + ("F11", "\x1b[23~"), + ("F12", "\x1b[24~"), +]; + +/// `kittyKeyCodeMap` in `mock-keys.ts`. +const KITTY_CODES: &[(&str, u32)] = &[ + ("escape", 27), + ("tab", 9), + ("return", 13), + ("backspace", 127), + ("insert", 57348), + ("delete", 57349), + ("left", 57350), + ("right", 57351), + ("up", 57352), + ("down", 57353), + ("pageup", 57354), + ("pagedown", 57355), + ("home", 57356), + ("end", 57357), + ("f1", 57364), + ("f2", 57365), + ("f3", 57366), + ("f4", 57367), + ("f5", 57368), + ("f6", 57369), + ("f7", 57370), + ("f8", 57371), + ("f9", 57372), + ("f10", 57373), + ("f11", 57374), + ("f12", 57375), +]; + +/// `Frontend.KeyModifiers`. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +pub struct KeyModifiers { + #[serde(default)] + pub ctrl: bool, + #[serde(default)] + pub shift: bool, + #[serde(default)] + pub meta: bool, + #[serde(default, rename = "super")] + pub super_: bool, + #[serde(default)] + pub hyper: bool, +} + +/// `ui.press`: the simulation server's `keyInput` (an upper-cased `KeyCodes` name, else the key itself), then +/// `pressKey` in Kitty mode. +pub fn press(key: &str, modifiers: KeyModifiers) -> Vec { + let upper = key.to_uppercase(); + let (value, mut name) = match KEY_CODES.iter().find(|(code, _)| *code == upper) { + Some((code, value)) => (*value, Some(code.to_lowercase())), + None => (key, None), + }; + let mapped = match value { + "\u{8}" => Some("backspace"), + "\r" | "\n" => Some("return"), + "\t" => Some("tab"), + "\x1b" => Some("escape"), + "\x1b[A" => Some("up"), + "\x1b[B" => Some("down"), + "\x1b[C" => Some("right"), + "\x1b[D" => Some("left"), + "\x1b[H" => Some("home"), + "\x1b[F" => Some("end"), + "\x1b[3~" => Some("delete"), + _ => None, + }; + if let Some(mapped) = mapped { + name = Some(mapped.to_owned()); + } + let name = name.map(|name| { + name.strip_prefix("arrow_") + .map(str::to_owned) + .unwrap_or(name) + }); + if let Some(code) = name + .and_then(|name| KITTY_CODES.iter().find(|(kitty, _)| *kitty == name)) + .map(|(_, code)| *code) + { + return kitty(code, modifiers); + } + // A JavaScript string of length one: one UTF-16 unit, so not a character outside the Basic Multilingual Plane. + let mut units = value.encode_utf16(); + if let (Some(unit), None) = (units.next(), units.next()) + && unit != 0 + && unit != 0x1b + { + return kitty(u32::from(unit), modifiers); + } + // Core falls through to legacy encoding, which only prefixes Escape for Meta on a multi-character key. + let prefix = if modifiers.meta && !value.starts_with('\x1b') { + "\x1b" + } else { + "" + }; + format!("{prefix}{value}").into_bytes() +} + +/// `ui.enter`: `pressEnter`, so Return in Kitty mode. +pub fn enter() -> Vec { + press("RETURN", KeyModifiers::default()) +} + +/// `ui.arrow`: `pressArrow`. +pub fn arrow(direction: Direction) -> Vec { + let key = match direction { + Direction::Up => "ARROW_UP", + Direction::Down => "ARROW_DOWN", + Direction::Left => "ARROW_LEFT", + Direction::Right => "ARROW_RIGHT", + }; + press(key, KeyModifiers::default()) +} + +fn kitty(code: u32, modifiers: KeyModifiers) -> Vec { + let mask = u8::from(modifiers.shift) + | u8::from(modifiers.meta) << 1 + | u8::from(modifiers.ctrl) << 2 + | u8::from(modifiers.super_) << 3 + | u8::from(modifiers.hyper) << 4; + match mask { + 0 => format!("\x1b[{code}u"), + mask => format!("\x1b[{code};{}u", mask + 1), + } + .into_bytes() +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum Direction { + Up, + Down, + Left, + Right, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +pub struct MouseModifiers { + #[serde(default)] + pub shift: bool, + #[serde(default)] + pub alt: bool, + #[serde(default)] + pub ctrl: bool, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum Button { + #[default] + Left, + Middle, + Right, +} + +/// `Frontend.MouseParams`. +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(tag = "action", rename_all = "lowercase")] +pub enum Mouse { + Move { + x: u32, + y: u32, + #[serde(default)] + modifiers: MouseModifiers, + }, + Down { + x: u32, + y: u32, + #[serde(default)] + modifiers: MouseModifiers, + #[serde(default)] + button: Button, + }, + Up { + x: u32, + y: u32, + #[serde(default)] + modifiers: MouseModifiers, + #[serde(default)] + button: Button, + }, + Scroll { + x: u32, + y: u32, + #[serde(default)] + modifiers: MouseModifiers, + direction: Direction, + }, +} + +impl Mouse { + pub fn position(&self) -> (u32, u32) { + match *self { + Self::Move { x, y, .. } + | Self::Down { x, y, .. } + | Self::Up { x, y, .. } + | Self::Scroll { x, y, .. } => (x, y), + } + } +} + +/// `createMockMouse`'s state: the buttons held, in press order, so a move while one is held is a drag. +#[derive(Debug, Default)] +pub struct MouseState { + pressed: Vec, +} + +impl MouseState { + /// The SGR report `createMockMouse` emits for an action. + pub fn encode(&mut self, mouse: Mouse) -> Vec { + let (x, y) = mouse.position(); + let (kind, button, modifiers) = match mouse { + Mouse::Move { modifiers, .. } => match self.pressed.first() { + Some(&held) => (Kind::Drag, held, modifiers), + None => (Kind::Move, 0, modifiers), + }, + Mouse::Down { + modifiers, button, .. + } => (Kind::Down, button_code(button), modifiers), + Mouse::Up { + modifiers, button, .. + } => (Kind::Up, button_code(button), modifiers), + Mouse::Scroll { + modifiers, + direction, + .. + } => { + let wheel = match direction { + Direction::Up => 64, + Direction::Down => 65, + Direction::Left => 66, + Direction::Right => 67, + }; + (Kind::Scroll, wheel, modifiers) + } + }; + let modifier_bits = u16::from(modifiers.shift) << 2 + | u16::from(modifiers.alt) << 3 + | u16::from(modifiers.ctrl) << 4; + let code = modifier_bits + | match kind { + Kind::Move => 32 | 3, + Kind::Drag => u16::from(button) | 32, + Kind::Down | Kind::Up | Kind::Scroll => u16::from(button), + }; + let suffix = if matches!(kind, Kind::Up | Kind::Move | Kind::Drag) { + 'm' + } else { + 'M' + }; + match kind { + Kind::Down if button < 64 && !self.pressed.contains(&button) => { + self.pressed.push(button) + } + Kind::Up => self.pressed.retain(|held| *held != button), + _ => {} + } + format!("\x1b[<{code};{};{}{suffix}", x + 1, y + 1).into_bytes() + } +} + +#[derive(Clone, Copy)] +enum Kind { + Move, + Drag, + Down, + Up, + Scroll, +} + +fn button_code(button: Button) -> u8 { + match button { + Button::Left => 0, + Button::Middle => 1, + Button::Right => 2, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn text(bytes: Vec) -> String { + String::from_utf8(bytes).unwrap() + } + + #[test] + fn keys_encode_as_core_mock_keys_in_kitty_mode() { + let none = KeyModifiers::default(); + let ctrl = KeyModifiers { ctrl: true, ..none }; + let all = KeyModifiers { + ctrl: true, + shift: true, + meta: true, + super_: true, + hyper: true, + }; + let cases: &[(&str, KeyModifiers, &str)] = &[ + ("a", none, "\x1b[97u"), + ("A", none, "\x1b[65u"), + ("c", ctrl, "\x1b[99;5u"), + ("x", all, "\x1b[120;32u"), + ("escape", none, "\x1b[27u"), + ("Escape", ctrl, "\x1b[27;5u"), + ("return", none, "\x1b[13u"), + ("linefeed", none, "\x1b[13u"), + ( + "tab", + KeyModifiers { + shift: true, + ..none + }, + "\x1b[9;2u", + ), + ("backspace", none, "\x1b[127u"), + ("delete", none, "\x1b[57349u"), + ("home", none, "\x1b[57356u"), + ("arrow_up", none, "\x1b[57352u"), + ("f5", none, "\x1b[57368u"), + ("é", none, "\x1b[233u"), + ("\r", none, "\x1b[13u"), + ("\t", none, "\x1b[9u"), + // Names outside `KeyCodes` fall through to legacy encoding as text, as in Core. + ("enter", none, "enter"), + ("pageup", none, "pageup"), + ("space", KeyModifiers { meta: true, ..none }, "\x1bspace"), + ("😀", none, "😀"), + ]; + for (key, modifiers, expected) in cases { + assert_eq!( + text(press(key, *modifiers)), + *expected, + "{key:?} {modifiers:?}" + ); + } + assert_eq!(text(enter()), "\x1b[13u"); + assert_eq!(text(arrow(Direction::Up)), "\x1b[57352u"); + assert_eq!(text(arrow(Direction::Down)), "\x1b[57353u"); + assert_eq!(text(arrow(Direction::Left)), "\x1b[57350u"); + assert_eq!(text(arrow(Direction::Right)), "\x1b[57351u"); + } + + #[test] + fn mouse_reports_encode_as_core_mock_mouse() { + let decode = |json: &str| serde_json::from_str::(json).unwrap(); + let mut state = MouseState::default(); + let cases: &[(&str, &str)] = &[ + (r#"{"action":"move","x":0,"y":0}"#, "\x1b[<35;1;1m"), + ( + r#"{"action":"move","x":3,"y":4,"modifiers":{"ctrl":true}}"#, + "\x1b[<51;4;5m", + ), + ( + r#"{"action":"down","x":2,"y":1,"button":"right"}"#, + "\x1b[<2;3;2M", + ), + (r#"{"action":"move","x":5,"y":1}"#, "\x1b[<34;6;2m"), + ( + r#"{"action":"up","x":5,"y":1,"button":"right"}"#, + "\x1b[<2;6;2m", + ), + (r#"{"action":"move","x":6,"y":1}"#, "\x1b[<35;7;2m"), + ( + r#"{"action":"down","x":0,"y":0,"modifiers":{"shift":true,"alt":true}}"#, + "\x1b[<12;1;1M", + ), + (r#"{"action":"up","x":0,"y":0}"#, "\x1b[<0;1;1m"), + ( + r#"{"action":"scroll","x":9,"y":9,"direction":"down"}"#, + "\x1b[<65;10;10M", + ), + ( + r#"{"action":"scroll","x":9,"y":9,"direction":"left","modifiers":{"ctrl":true}}"#, + "\x1b[<82;10;10M", + ), + ]; + for (json, expected) in cases { + assert_eq!(text(state.encode(decode(json))), *expected, "{json}"); + } + assert!(serde_json::from_str::(r#"{"action":"move","x":-1,"y":0}"#).is_err()); + assert!(serde_json::from_str::(r#"{"action":"scroll","x":1,"y":0}"#).is_err()); + assert!(serde_json::from_str::(r#"{"action":"move","x":1.5,"y":0}"#).is_err()); + } +} diff --git a/packages/cli-rs/crates/drive/src/lib.rs b/packages/cli-rs/crates/drive/src/lib.rs index d6e9a4ab2aa..d82e07bcdbd 100644 --- a/packages/cli-rs/crates/drive/src/lib.rs +++ b/packages/cli-rs/crates/drive/src/lib.rs @@ -1 +1,368 @@ -//! The simulation UI endpoint, `OPENCODE_DRIVE` (H.4). +//! The simulation UI endpoint, `OPENCODE_DRIVE` (H.4): a WebSocket server that drives a headless app as +//! `packages/simulation/src/frontend` drives the TS TUI. Requests run on the UI thread, one at a time; each action +//! feeds the bytes Core's mock input would send to the app's input parser, then paints a frame, as `actions.ts` +//! calls `renderOnce`. Mapping: opentui-rust `docs/headless.md`. + +pub mod capture; +pub mod keys; +pub mod manifest; +pub mod protocol; + +use opentui::App; +use opentui::input::{Input, Parser}; +use protocol::{Envelope, Request}; +use serde_json::{Value, json}; +use std::cell::RefCell; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::rc::Rc; +use std::sync::mpsc; +use tokio_tungstenite::tungstenite::{self, Message}; + +pub use manifest::Manifest; + +/// What the endpoint needs from the app it drives. +pub struct Options { + /// The version the handshake reports, as TS reports `app.version`. + pub version: String, + /// Whether an editor has focus, for `Frontend.State.focused.editor`. Runs on the UI thread. + pub editor: Box bool>, +} + +/// A started endpoint. Its threads run until the process ends; requests fail once the app has ended. +#[derive(Debug, Clone)] +pub struct Server { + pub addr: SocketAddr, +} + +impl Server { + /// The endpoint's URL, as TS prints it. + pub fn url(&self) -> String { + format!("ws://{}", self.addr) + } +} + +/// Listens on `addr` and answers requests for `app`, which must be [headless](App::headless). Call it on the UI +/// thread before [`App::run`]. +pub fn start(app: &App, addr: SocketAddr, options: Options) -> std::io::Result { + let listener = TcpListener::bind(addr)?; + let addr = listener.local_addr()?; + let driver = Rc::new(RefCell::new(Driver { + parser: Parser::new(app.session()), + mouse: keys::MouseState::default(), + editor: options.editor, + })); + app.on_message(move |cx, call: &Call| { + let answer = driver.borrow_mut().answer(cx.app(), &call.request); + let _ = call.reply.send(answer); + }); + let proxy = app.proxy(); + let version = options.version; + std::thread::Builder::new() + .name("drive-ui".into()) + .spawn(move || { + for stream in listener.incoming().flatten() { + let proxy = proxy.clone(); + let version = version.clone(); + let _ = std::thread::Builder::new() + .name("drive-ui-socket".into()) + .spawn(move || serve(stream, &proxy, &version)); + } + })?; + Ok(Server { addr }) +} + +/// One request for the UI thread, with where its answer goes. +struct Call { + request: Request, + reply: mpsc::SyncSender>, +} + +fn serve(stream: TcpStream, proxy: &opentui::app::AppProxy, version: &str) { + let Ok(mut socket) = tungstenite::accept(stream) else { + return; + }; + loop { + let input = match socket.read() { + Ok(Message::Text(text)) => text.to_string(), + Ok(Message::Binary(bytes)) => String::from_utf8_lossy(&bytes).into_owned(), + Ok(Message::Close(_)) | Err(_) => return, + Ok(_) => continue, + }; + if let Some(response) = respond(&input, proxy, version) + && socket.send(Message::text(response.to_string())).is_err() + { + return; + } + } +} + +fn respond(input: &str, proxy: &opentui::app::AppProxy, version: &str) -> Option { + let Envelope { id, request } = match protocol::decode(input) { + Ok(envelope) => envelope, + Err(message) => return Some(protocol::failure(None, &message)), + }; + let answer = match request { + Request::Handshake(params) => protocol::handshake(¶ms, version), + Request::Unsupported(method) => Err(protocol::unsupported(method)), + request => ask(proxy, request), + }; + match answer { + Ok(result) => protocol::success(id, result), + Err(message) => Some(protocol::failure(id, &message)), + } +} + +fn ask(proxy: &opentui::app::AppProxy, request: Request) -> Result { + let (reply, answer) = mpsc::sync_channel(1); + proxy + .send(Call { request, reply }) + .map_err(|error| error.to_string())?; + answer + .recv() + .map_err(|_| opentui::app::ProxyError::Closed.to_string())? +} + +/// The endpoint's state on the UI thread. +struct Driver { + parser: Parser, + mouse: keys::MouseState, + editor: Box bool>, +} + +impl Driver { + fn answer(&mut self, app: &App, request: &Request) -> Result { + match request { + Request::Capture => { + return app + .capture() + .map(|frame| capture::frame(&frame)) + .map_err(|error| error.to_string()); + } + Request::Matches { text } => { + // As TS, read the current frame without painting one; only before the first frame is there none. + let frame = app + .last_frame() + .map_or_else(|| app.capture(), Ok) + .map_err(|error| error.to_string())?; + return Ok(json!(capture::matches(&frame, text))); + } + Request::Type { text } => self.feed(app, text.as_bytes())?, + Request::Press { key, modifiers } => self.feed(app, &keys::press(key, *modifiers))?, + Request::Enter => self.feed(app, &keys::enter())?, + Request::Arrow(direction) => self.feed(app, &keys::arrow(*direction))?, + Request::Mouse(mouse) => { + let (width, height) = app.size(); + let (x, y) = mouse.position(); + if x >= u32::from(width) || y >= u32::from(height) { + return Err("mouse position must be within the terminal viewport".into()); + } + let bytes = self.mouse.encode(*mouse); + self.feed(app, &bytes)?; + } + Request::Resize { cols, rows } => { + let size = |value: f64| { + (value.fract() == 0.0 && value >= 1.0 && value <= f64::from(u16::MAX)) + .then_some(value as u16) + }; + let (Some(cols), Some(rows)) = (size(*cols), size(*rows)) else { + return Err("resize cols and rows must be positive integers".into()); + }; + app.resize(cols, rows).map_err(|error| error.to_string())?; + } + Request::Handshake(_) | Request::Unsupported(_) => { + unreachable!("answered off the UI thread") + } + } + app.capture().map_err(|error| error.to_string())?; + Ok(json!({ "focused": { "editor": (self.editor)(app) }, "elements": [] })) + } + + /// Parses bytes as if typed and dispatches the events. A partial sequence at the end ends at once, so a lone + /// Escape is the Escape key instead of waiting for the input timeout. + fn feed(&mut self, app: &App, bytes: &[u8]) -> Result<(), String> { + let mut inputs = Vec::new(); + let parsed = self + .parser + .feed(bytes, app.now(), &mut inputs) + .and_then(|()| { + self.parser + .deadline() + .map_or(Ok(()), |deadline| self.parser.expire(deadline, &mut inputs)) + }); + parsed.map_err(|error| error.to_string())?; + for input in inputs { + if let Input::Event(event) = input { + app.dispatch(event); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opentui::app::HeadlessOptions; + use opentui::prelude::*; + + /// A client on another thread sends each request and collects the responses; the app records the events it got. + #[test] + fn requests_drive_a_headless_app() { + let options = AppOptions { + exit_on_ctrl_c: false, + ..AppOptions::default() + }; + let app = App::headless(HeadlessOptions { + width: 30, + height: 4, + app: options, + }) + .unwrap(); + let input = opentui::widget::Input::new(&app); + let submitted = Text::new(&app, ""); + app.root().add(&input).add(&submitted); + app.focus(&input); + input.on_submit({ + let submitted = submitted.clone(); + move |_cx, text| drop(submitted.set_text(format!("submitted {text}"))) + }); + let events = Rc::new(RefCell::new(Vec::new())); + app.on_key_capture({ + let events = events.clone(); + move |_cx, key| { + events + .borrow_mut() + .push(format!("{:?} {:?}", key.code, key.modifiers)) + } + }); + app.on_mouse({ + let events = events.clone(); + move |_cx, mouse| { + events + .borrow_mut() + .push(format!("{:?} {} {}", mouse.kind, mouse.x, mouse.y)) + } + }); + let focused = input.clone(); + let editor = + Box::new(move |app: &App| app.focused().is_some_and(|widget| widget.is(&focused))); + let server = start( + &app, + SocketAddr::from(([127, 0, 0, 1], 0)), + Options { + version: "1.2.3".into(), + editor, + }, + ) + .unwrap(); + + let requests = [ + r#"{"jsonrpc":"2.0","id":1,"method":"simulation.handshake","params":{"client":{"name":"t","version":"1"},"expectedRole":"ui","offeredVersions":[1],"requiredCapabilities":["ui.capture"],"optionalCapabilities":[]}}"#, + r#"{"jsonrpc":"2.0","id":2,"method":"ui.type","params":{"text":"Adx"}}"#, + r#"{"jsonrpc":"2.0","id":3,"method":"ui.press","params":{"key":"backspace"}}"#, + r#"{"jsonrpc":"2.0","id":4,"method":"ui.press","params":{"key":"a"}}"#, + r#"{"jsonrpc":"2.0","id":5,"method":"ui.press","params":{"key":"c","modifiers":{"ctrl":true}}}"#, + r#"{"jsonrpc":"2.0","id":6,"method":"ui.arrow","params":{"direction":"left"}}"#, + r#"{"jsonrpc":"2.0","id":7,"method":"ui.matches","params":{"text":"Ada"}}"#, + r#"{"jsonrpc":"2.0","id":8,"method":"ui.enter"}"#, + r#"{"jsonrpc":"2.0","id":9,"method":"ui.matches","params":{"text":"submitted Ada"}}"#, + r#"{"jsonrpc":"2.0","id":10,"method":"ui.mouse","params":{"action":"down","x":1,"y":1}}"#, + r#"{"jsonrpc":"2.0","id":11,"method":"ui.mouse","params":{"action":"move","x":2,"y":1}}"#, + r#"{"jsonrpc":"2.0","id":12,"method":"ui.mouse","params":{"action":"up","x":2,"y":1}}"#, + r#"{"jsonrpc":"2.0","id":13,"method":"ui.mouse","params":{"action":"scroll","x":0,"y":0,"direction":"down"}}"#, + r#"{"jsonrpc":"2.0","id":14,"method":"ui.mouse","params":{"action":"move","x":30,"y":0}}"#, + r#"{"jsonrpc":"2.0","id":15,"method":"ui.resize","params":{"cols":0,"rows":3}}"#, + r#"{"jsonrpc":"2.0","id":16,"method":"ui.resize","params":{"cols":20,"rows":3}}"#, + r#"{"jsonrpc":"2.0","id":17,"method":"ui.capture"}"#, + r#"{"jsonrpc":"2.0","id":18,"method":"ui.state"}"#, + r#"{"jsonrpc":"2.0","method":"ui.press","params":{"key":"!"}}"#, + r#"{"jsonrpc":"2.0","id":19,"method":"ui.nope"}"#, + ]; + let proxy = app.proxy(); + let url = server.url(); + let client = std::thread::spawn(move || { + let (mut socket, _) = tungstenite::connect(&url).unwrap(); + let mut responses = Vec::new(); + for request in requests { + socket.send(Message::text(request)).unwrap(); + if request.contains(r#""id""#) { + let text = socket.read().unwrap().into_text().unwrap(); + responses.push(serde_json::from_str::(&text).unwrap()); + } + } + let _ = proxy.quit(); + responses + }); + app.clone().run().unwrap(); + let responses = client.join().unwrap(); + let result = |id: u64| { + let response = responses + .iter() + .find(|response| response["id"] == id) + .unwrap_or_else(|| panic!("no {id}")); + response + .get("result") + .cloned() + .ok_or_else(|| response["error"]["message"].as_str().unwrap().to_owned()) + }; + + assert_eq!(result(1).unwrap()["server"]["version"], "1.2.3"); + assert_eq!( + result(2).unwrap(), + json!({ "focused": { "editor": true }, "elements": [] }) + ); + assert_eq!(result(7), Ok(json!(true))); + assert_eq!(result(9), Ok(json!(true))); + // The input under the pointer takes the wheel step, so no app mouse handler sees it. + assert_eq!(result(13).unwrap()["elements"], json!([])); + assert_eq!( + result(14), + Err("mouse position must be within the terminal viewport".into()) + ); + assert_eq!( + result(15), + Err("resize cols and rows must be positive integers".into()) + ); + let frame = result(17).unwrap(); + assert_eq!( + (frame["cols"].clone(), frame["rows"].clone()), + (json!(20), json!(3)) + ); + let row = |y: usize| -> String { + frame["lines"][y]["spans"] + .as_array() + .unwrap() + .iter() + .map(|span| span["text"].as_str().unwrap()) + .collect() + }; + assert_eq!(row(0).trim_end(), "Ada"); + assert_eq!(row(1).trim_end(), "submitted Ada"); + assert!( + result(18) + .unwrap_err() + .starts_with("ui.state is not supported") + ); + let invalid = responses.last().unwrap(); + assert_eq!(invalid["id"], Value::Null); + assert_eq!(responses.len(), 19); + assert_eq!( + *events.borrow(), + [ + "Char('A') NONE", + "Char('d') NONE", + "Char('x') NONE", + "Backspace NONE", + "Char('a') NONE", + "Char('c') ctrl", + "Left NONE", + "Enter NONE", + "Down(Left) 1 1", + "Drag(Left) 2 1", + "Up(Left) 2 1", + "Char('!') NONE", + ] + .map(str::to_owned) + ); + } +} diff --git a/packages/cli-rs/crates/drive/src/manifest.rs b/packages/cli-rs/crates/drive/src/manifest.rs new file mode 100644 index 00000000000..48ff8aba201 --- /dev/null +++ b/packages/cli-rs/crates/drive/src/manifest.rs @@ -0,0 +1,263 @@ +//! The drive manifest, as `packages/simulation/src/manifest.ts` resolves it from `OPENCODE_DRIVE`. + +use serde::Deserialize; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; + +/// Where the endpoints listen and the screen size, from `OPENCODE_DRIVE`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Manifest { + /// The UI endpoint, `ws://127.0.0.1:`. + pub ui: String, + /// The backend endpoint the simulated server connects to; the TUI does not use it. + pub backend: String, + /// Columns and rows; the TUI then starts at 100 by 40 when absent. + pub viewport: Option<(u16, u16)>, + /// The timeline path TS records into; the Rust endpoint does not record. + pub recording: Option, +} + +impl Manifest { + /// The defaults for `OPENCODE_DRIVE=1` (`manifest.ts` `defaults`). + pub fn defaults() -> Self { + Self { + ui: "ws://127.0.0.1:40900".into(), + backend: "ws://127.0.0.1:40950".into(), + viewport: None, + recording: None, + } + } + + /// The UI endpoint's socket address. [`resolve`] has checked it. + pub fn ui_addr(&self) -> SocketAddr { + endpoint(&self.ui).expect("a checked endpoint") + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl std::fmt::Display for Error { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0) + } +} + +impl std::error::Error for Error {} + +/// Resolves the manifest named by `OPENCODE_DRIVE`, or `None` when it is unset or empty. `env` reads a variable. +pub fn resolve(env: impl Fn(&str) -> Option) -> Option> { + let name = env("OPENCODE_DRIVE").filter(|name| !name.is_empty())?; + Some(resolve_name(&name, env)) +} + +fn resolve_name(name: &str, env: impl Fn(&str) -> Option) -> Result { + if !valid_name(name) { + return Err(Error(format!( + "Invalid Drive configuration: OPENCODE_DRIVE: expected a valid Drive instance name, got {name:?}" + ))); + } + if name == "1" { + return Ok(Manifest::defaults()); + } + let directory = env("DRIVE_REGISTRY_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| { + let state = env("XDG_STATE_HOME").map(PathBuf::from).unwrap_or_else(|| { + Path::new(&env("HOME").unwrap_or_default()) + .join(".local") + .join("state") + }); + state.join("opencode-drive").join("instances") + }); + let file = directory.join(format!("{name}.json")); + let contents = std::fs::read_to_string(&file).map_err(|error| { + Error(match error.kind() { + std::io::ErrorKind::NotFound => format!("Drive manifest not found: {}", file.display()), + _ => format!("Failed to read Drive manifest: {}: {error}", file.display()), + }) + })?; + decode(&contents).map_err(|message| { + Error(format!( + "Invalid Drive manifest: {}: {message}", + file.display() + )) + }) +} + +fn valid_name(name: &str) -> bool { + let mut chars = name.chars(); + chars + .next() + .is_some_and(|first| first.is_ascii_alphanumeric()) + && name.len() <= 64 + && chars.all(|char| char.is_ascii_alphanumeric() || matches!(char, '.' | '_' | '-')) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Raw { + endpoints: Endpoints, + viewport: Option, + recording: Option, +} + +#[derive(Deserialize)] +struct Endpoints { + ui: String, + backend: String, +} + +#[derive(Deserialize)] +struct Viewport { + cols: u64, + rows: u64, +} + +#[derive(Deserialize)] +struct Recording { + timeline: String, +} + +fn decode(contents: &str) -> Result { + let raw: Raw = serde_json::from_str(contents).map_err(|error| error.to_string())?; + for (key, value) in [ + ("endpoints.ui", &raw.endpoints.ui), + ("endpoints.backend", &raw.endpoints.backend), + ] { + if endpoint(value).is_none() { + return Err(format!( + "{key}: expected a loopback WebSocket endpoint with an explicit port, got {value:?}" + )); + } + } + let viewport = raw + .viewport + .map(|viewport| { + let size = |value: u64| u16::try_from(value).ok().filter(|value| *value > 0); + size(viewport.cols) + .zip(size(viewport.rows)) + .ok_or_else(|| "viewport: expected positive columns and rows".to_owned()) + }) + .transpose()?; + let recording = raw + .recording + .map(|recording| { + Path::new(&recording.timeline) + .is_absolute() + .then(|| PathBuf::from(&recording.timeline)) + .ok_or_else(|| "recording.timeline: expected an absolute path".to_owned()) + }) + .transpose()?; + Ok(Manifest { + ui: raw.endpoints.ui, + backend: raw.endpoints.backend, + viewport, + recording, + }) +} + +/// A `ws://127.0.0.1:` endpoint's address, as `manifest.ts` `Endpoint` accepts it. +fn endpoint(value: &str) -> Option { + let url = url::Url::parse(value).ok()?; + let port = url.port().filter(|port| *port >= 1)?; + (url.scheme() == "ws" && url.host_str() == Some("127.0.0.1")) + .then(|| SocketAddr::from(([127, 0, 0, 1], port))) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn env(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let vars: HashMap = vars + .iter() + .map(|(key, value)| ((*key).to_owned(), (*value).to_owned())) + .collect(); + move |key| vars.get(key).cloned() + } + + #[test] + fn unset_and_default() { + assert_eq!(resolve(env(&[])), None); + assert_eq!(resolve(env(&[("OPENCODE_DRIVE", "")])), None); + assert_eq!( + resolve(env(&[("OPENCODE_DRIVE", "1")])), + Some(Ok(Manifest::defaults())) + ); + assert_eq!( + Manifest::defaults().ui_addr(), + SocketAddr::from(([127, 0, 0, 1], 40900)) + ); + } + + #[test] + fn names_are_checked() { + for name in ["-x", "a/b", "a b", &"a".repeat(65)] { + let error = resolve(env(&[("OPENCODE_DRIVE", name)])) + .unwrap() + .unwrap_err(); + assert!( + error.0.starts_with("Invalid Drive configuration"), + "{name}: {error}" + ); + } + } + + #[test] + fn manifests_come_from_the_registry() { + let directory = tempfile::tempdir().unwrap(); + let instances = directory.path().join("opencode-drive").join("instances"); + std::fs::create_dir_all(&instances).unwrap(); + let state = directory.path().to_str().unwrap(); + let write = |name: &str, body: &str| { + std::fs::write(instances.join(format!("{name}.json")), body).unwrap() + }; + write( + "good", + r#"{"endpoints":{"ui":"ws://127.0.0.1:4100","backend":"ws://127.0.0.1:4101"},"viewport":{"cols":80,"rows":24},"recording":{"timeline":"/tmp/t.json"}}"#, + ); + write( + "remote", + r#"{"endpoints":{"ui":"ws://10.0.0.1:4100","backend":"ws://127.0.0.1:4101"}}"#, + ); + write( + "portless", + r#"{"endpoints":{"ui":"ws://127.0.0.1","backend":"ws://127.0.0.1:4101"}}"#, + ); + write( + "zero", + r#"{"endpoints":{"ui":"ws://127.0.0.1:1","backend":"ws://127.0.0.1:2"},"viewport":{"cols":0,"rows":2}}"#, + ); + let get = |name: &str| { + resolve(env(&[("OPENCODE_DRIVE", name), ("XDG_STATE_HOME", state)])).unwrap() + }; + + let good = get("good").unwrap(); + assert_eq!(good.ui_addr(), SocketAddr::from(([127, 0, 0, 1], 4100))); + assert_eq!(good.viewport, Some((80, 24))); + assert_eq!(good.recording, Some(PathBuf::from("/tmp/t.json"))); + for name in ["remote", "portless", "zero"] { + assert!( + get(name) + .unwrap_err() + .0 + .starts_with("Invalid Drive manifest: "), + "{name}" + ); + } + assert!( + get("missing") + .unwrap_err() + .0 + .starts_with("Drive manifest not found: ") + ); + + let registry = resolve(env(&[ + ("OPENCODE_DRIVE", "good"), + ("DRIVE_REGISTRY_DIR", instances.to_str().unwrap()), + ])); + assert_eq!(registry.unwrap().unwrap(), good); + } +} diff --git a/packages/cli-rs/crates/drive/src/protocol.rs b/packages/cli-rs/crates/drive/src/protocol.rs new file mode 100644 index 00000000000..e204a7dea9c --- /dev/null +++ b/packages/cli-rs/crates/drive/src/protocol.rs @@ -0,0 +1,387 @@ +//! The UI half of the simulation protocol (`packages/protocol/src/simulation.ts`): JSON-RPC 2.0 requests over a +//! WebSocket, decoded as `Frontend.Request` decodes them, and the handshake. + +use crate::keys::{Direction, KeyModifiers, Mouse}; +use serde::Deserialize; +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +/// The capabilities this endpoint implements, in `Frontend.Capabilities` order. `ui.focus`, `ui.click`, +/// `ui.state`, and `ui.snapshot` name renderable numbers, which the Rust TUI has none of (plan 7.3), and the endpoint +/// does not record (`ui.recording.*`). +pub const CAPABILITIES: &[&str] = &[ + "ui.type", + "ui.press", + "ui.enter", + "ui.arrow", + "ui.mouse", + "ui.resize", + "ui.matches", + "ui.capture", +]; + +/// One decoded request. `id` is `None` for a notification, which gets a response only when it fails. +#[derive(Debug, Clone, PartialEq)] +pub struct Envelope { + pub id: Option, + pub request: Request, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Request { + Handshake(HandshakeParams), + Type { + text: String, + }, + Press { + key: String, + modifiers: KeyModifiers, + }, + Enter, + Arrow(Direction), + Mouse(Mouse), + Resize { + cols: f64, + rows: f64, + }, + Matches { + text: String, + }, + Capture, + /// A request of the protocol this endpoint does not implement. + Unsupported(&'static str), +} + +/// Decodes a request, or says why it is not one. TS answers a request it cannot decode with a failure whose `id` is +/// null. +pub fn decode(input: &str) -> Result { + let value: Value = + serde_json::from_str(input).map_err(|error| format!("invalid JSON: {error}"))?; + let object = value + .as_object() + .ok_or("expected a JSON-RPC request object")?; + if object.get("jsonrpc") != Some(&json!("2.0")) { + return Err("jsonrpc: expected \"2.0\"".into()); + } + let id = object.get("id").cloned(); + if id + .as_ref() + .is_some_and(|id| !(id.is_string() || id.is_number() || id.is_null())) + { + return Err("id: expected a string, a number, or null".into()); + } + let method = object + .get("method") + .and_then(Value::as_str) + .ok_or("method: expected a string")?; + let params = object.get("params"); + let request = match method { + "simulation.handshake" => Request::Handshake(params_of(method, params)?), + "ui.type" => Request::Type { + text: params_of::(method, params)?.text, + }, + "ui.matches" => Request::Matches { + text: params_of::(method, params)?.text, + }, + "ui.press" => { + let press: Press = params_of(method, params)?; + Request::Press { + key: press.key, + modifiers: press.modifiers.unwrap_or_default(), + } + } + "ui.arrow" => Request::Arrow(params_of::(method, params)?.direction), + "ui.mouse" => Request::Mouse(params_of(method, params)?), + "ui.resize" => { + let resize: Resize = params_of(method, params)?; + Request::Resize { + cols: resize.cols, + rows: resize.rows, + } + } + "ui.enter" => Request::Enter, + "ui.capture" => Request::Capture, + "ui.focus" | "ui.click" => { + params_of::(method, params)?; + Request::Unsupported(if method == "ui.focus" { + "ui.focus" + } else { + "ui.click" + }) + } + "ui.state" => Request::Unsupported("ui.state"), + "ui.snapshot" => Request::Unsupported("ui.snapshot"), + "ui.recording.finish" => Request::Unsupported("ui.recording.finish"), + other => return Err(format!("method: unknown simulation UI method {other:?}")), + }; + Ok(Envelope { id, request }) +} + +fn params_of(method: &str, params: Option<&Value>) -> Result { + let params = params + .filter(|params| params.is_object()) + .ok_or_else(|| format!("{method}: params: expected an object"))?; + serde_json::from_value(params.clone()).map_err(|error| format!("{method}: params: {error}")) +} + +#[derive(Deserialize)] +struct Text { + text: String, +} + +#[derive(Deserialize)] +struct Press { + key: String, + modifiers: Option, +} + +#[derive(Deserialize)] +struct Arrow { + direction: Direction, +} + +#[derive(Deserialize)] +struct Resize { + cols: f64, + rows: f64, +} + +/// The message for a request this endpoint does not implement. +pub fn unsupported(method: &str) -> String { + match method { + "ui.recording.finish" => "UI recording is not available".into(), + _ => format!( + "{method} is not supported by the Rust TUI: it has no renderable numbers; use ui.mouse with coordinates" + ), + } +} + +/// `JsonRpc.success`: nothing for a notification. +pub fn success(id: Option, result: Value) -> Option { + id.map(|id| json!({ "jsonrpc": "2.0", "id": id, "result": result })) +} + +/// `JsonRpc.failure`, with the server's error code. +pub fn failure(id: Option, message: &str) -> Value { + json!({ "jsonrpc": "2.0", "id": id.unwrap_or(Value::Null), "error": { "code": -32000, "message": message } }) +} + +/// `Handshake.Params`. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HandshakeParams { + pub client: Identity, + pub expected_role: Role, + pub offered_versions: Vec, + pub required_capabilities: Vec, + pub optional_capabilities: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct Identity { + pub name: String, + pub version: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + Ui, + Backend, +} + +/// `Handshake.dispatch` for the `ui` role, after the checks `Handshake.Params` makes while decoding. +pub fn handshake(params: &HandshakeParams, version: &str) -> Result { + check(params)?; + if params.expected_role != Role::Ui { + return Err("Expected simulation endpoint role backend, received ui".into()); + } + if !params.offered_versions.contains(&1) { + return Err("No mutually supported simulation protocol version".into()); + } + let missing: Vec<&str> = params + .required_capabilities + .iter() + .map(String::as_str) + .filter(|capability| !CAPABILITIES.contains(capability)) + .collect(); + if !missing.is_empty() { + return Err(format!( + "Simulation endpoint is missing required capabilities: {}", + missing.join(", ") + )); + } + Ok(json!({ + "protocolVersion": 1, + "role": "ui", + "server": { "name": "opencode", "version": version }, + "capabilities": CAPABILITIES, + })) +} + +fn check(params: &HandshakeParams) -> Result<(), String> { + let unique = |items: &[String]| { + items + .iter() + .enumerate() + .all(|(index, item)| !items[..index].contains(item)) + }; + if params.client.name.is_empty() || params.client.version.is_empty() { + return Err( + "simulation.handshake: params.client: expected a non-empty name and version".into(), + ); + } + let versions = ¶ms.offered_versions; + if versions.is_empty() + || versions.contains(&0) + || versions + .iter() + .enumerate() + .any(|(index, version)| versions[..index].contains(version)) + { + return Err( + "simulation.handshake: params.offeredVersions: expected unique positive integers" + .into(), + ); + } + for capabilities in [¶ms.required_capabilities, ¶ms.optional_capabilities] { + if capabilities.iter().any(String::is_empty) || !unique(capabilities) { + return Err( + "simulation.handshake: params: expected unique non-empty capabilities".into(), + ); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn handshake_request(role: &str, versions: &str, required: &str) -> String { + format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"simulation.handshake","params":{{"client":{{"name":"t","version":"1"}},"expectedRole":"{role}","offeredVersions":{versions},"requiredCapabilities":{required},"optionalCapabilities":[]}}}}"# + ) + } + + fn answer(input: &str) -> Result { + let Request::Handshake(params) = decode(input)?.request else { + panic!("not a handshake") + }; + handshake(¶ms, "9.9.9") + } + + #[test] + fn handshakes_match_typescript() { + let ok = answer(&handshake_request("ui", "[2,1]", r#"["ui.capture"]"#)).unwrap(); + assert_eq!(ok["protocolVersion"], 1); + assert_eq!( + ok["server"], + json!({ "name": "opencode", "version": "9.9.9" }) + ); + assert_eq!( + ok["capabilities"].as_array().unwrap().len(), + CAPABILITIES.len() + ); + assert_eq!( + answer(&handshake_request("backend", "[1]", "[]")).unwrap_err(), + "Expected simulation endpoint role backend, received ui" + ); + assert_eq!( + answer(&handshake_request("ui", "[2]", "[]")).unwrap_err(), + "No mutually supported simulation protocol version" + ); + assert_eq!( + answer(&handshake_request( + "ui", + "[1]", + r#"["ui.state","ui.type","ui.click"]"# + )) + .unwrap_err(), + "Simulation endpoint is missing required capabilities: ui.state, ui.click" + ); + assert!(answer(&handshake_request("ui", "[]", "[]")).is_err()); + assert!(answer(&handshake_request("ui", "[1,1]", "[]")).is_err()); + assert!(answer(&handshake_request("ui", "[1]", r#"["a","a"]"#)).is_err()); + } + + #[test] + fn requests_decode_as_the_frontend_schema() { + let decode_request = |input: &str| decode(input).map(|envelope| envelope.request); + assert_eq!( + decode(r#"{"jsonrpc":"2.0","id":"a","method":"ui.type","params":{"text":"hi"}}"#) + .unwrap(), + Envelope { + id: Some(json!("a")), + request: Request::Type { text: "hi".into() } + } + ); + assert_eq!( + decode(r#"{"jsonrpc":"2.0","method":"ui.enter"}"#) + .unwrap() + .id, + None + ); + assert_eq!( + decode_request( + r#"{"jsonrpc":"2.0","id":1,"method":"ui.press","params":{"key":"c","modifiers":{"ctrl":true}}}"# + ), + Ok(Request::Press { + key: "c".into(), + modifiers: KeyModifiers { + ctrl: true, + ..KeyModifiers::default() + } + }) + ); + assert_eq!( + decode_request( + r#"{"jsonrpc":"2.0","id":1,"method":"ui.arrow","params":{"direction":"left"}}"# + ), + Ok(Request::Arrow(Direction::Left)) + ); + assert_eq!( + decode_request( + r#"{"jsonrpc":"2.0","id":1,"method":"ui.resize","params":{"cols":80.5,"rows":24}}"# + ), + Ok(Request::Resize { + cols: 80.5, + rows: 24.0 + }) + ); + assert_eq!( + decode_request(r#"{"jsonrpc":"2.0","id":1,"method":"ui.state"}"#), + Ok(Request::Unsupported("ui.state")) + ); + assert_eq!( + decode_request( + r#"{"jsonrpc":"2.0","id":1,"method":"ui.click","params":{"target":1,"x":0,"y":0}}"# + ), + Ok(Request::Unsupported("ui.click")) + ); + for bad in [ + "nope", + r#"{"jsonrpc":"1.0","id":1,"method":"ui.enter"}"#, + r#"{"jsonrpc":"2.0","id":{},"method":"ui.enter"}"#, + r#"{"jsonrpc":"2.0","id":1,"method":"ui.type"}"#, + r#"{"jsonrpc":"2.0","id":1,"method":"ui.type","params":{"text":1}}"#, + r#"{"jsonrpc":"2.0","id":1,"method":"ui.arrow","params":{"direction":"in"}}"#, + r#"{"jsonrpc":"2.0","id":1,"method":"ui.nope"}"#, + ] { + assert!(decode(bad).is_err(), "{bad}"); + } + } + + #[test] + fn responses_are_json_rpc() { + assert_eq!(success(None, json!(true)), None); + assert_eq!( + success(Some(json!(3)), json!(true)), + Some(json!({ "jsonrpc": "2.0", "id": 3, "result": true })) + ); + assert_eq!( + failure(None, "bad"), + json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32000, "message": "bad" } }) + ); + } +}