Lutra/crates/control/src/protocol.rs
danny 9b278099cf M3.7: lutra CLI and single instance
- crates/control: rendezvous file (<data_dir>/instance.json, port + random
  token, atomic write, 0600 on Unix, stale detection), token-protected
  listener (start_with_token, app.auth first, constant-time compare,
  10 s auth timeout), app.focus, and a blocking client (connect_live,
  request/execute/subscribe/next_event, open_folder/open_file/reveal)
- lutra-desktop: a normal start forwards its path to a running instance
  and exits, otherwise claims the rendezvous; --control instances skip it
  unless LUTRA_RENDEZVOUS_DIR is set; non-Unicode args are usage errors
- lutra-cli (binary lutra, now L6): path[:line[:column]] targets, folder ->
  project.open, file -> file.open (parent opened without a project, outside
  the project refused), editor.reveal, starts the desktop if needed,
  --wait until bufferClosed, --version/--help, exit codes 0/1/2
- tests: proptest target parsing, rendezvous read/write/stale, token check
  over TCP, forwarding against a test backend, --wait end to end
- docs: architecture, G7, ROADMAP (agent automation 18% est.), roadmap,
  README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 00:23:09 +02:00

370 lines
12 KiB
Rust

//! The line protocol: one JSON request in, one JSON response out.
//!
//! Requests are `{"id": <number|string>, "method": "...", "params": {...}}`.
//! Responses are `{"id": ..., "result": ...}` or
//! `{"id": ..., "error": {"code": "...", "message": "..."}}`. Every input
//! line is untrusted; [`handle_line`] answers anything, including garbage,
//! with a well-formed response and never panics.
use std::path::PathBuf;
use lutra_engine::{EngineError, guard};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::Backend;
use crate::methods::{
APP_AUTH, APP_FOCUS, APP_PING, ENGINE_EXECUTE, ENGINE_LIST_COMMANDS, EVENTS_SUBSCRIBE,
UI_SCREENSHOT,
};
/// Largest accepted request line in bytes, newline excluded.
pub const MAX_LINE_BYTES: usize = 16 * 1024 * 1024;
/// Error codes of the protocol itself; engine errors use
/// [`EngineError::code`].
pub mod codes {
/// The line is not valid JSON or not UTF-8.
pub const PARSE_ERROR: &str = "parse_error";
/// The JSON is not a request object.
pub const INVALID_REQUEST: &str = "invalid_request";
/// No such method.
pub const METHOD_NOT_FOUND: &str = "method_not_found";
/// The method's params are wrong.
pub const INVALID_PARAMS: &str = "invalid_params";
/// The line exceeds [`super::MAX_LINE_BYTES`].
pub const LINE_TOO_LONG: &str = "line_too_long";
/// The screenshot could not be taken.
pub const SCREENSHOT_FAILED: &str = "screenshot_failed";
/// The connection has not authenticated with the right token.
pub const UNAUTHORIZED: &str = "unauthorized";
/// The window could not be brought to the front.
pub const FOCUS_FAILED: &str = "focus_failed";
}
/// A parsed request.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
/// Caller-chosen id, echoed in the response: a number or a string.
pub id: Value,
/// Method name, e.g. `engine.execute`.
pub method: String,
/// Method params; defaults to null.
#[serde(default)]
pub params: Value,
}
/// Error object of a response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorObject {
/// Stable code.
pub code: String,
/// Human-readable message.
pub message: String,
}
/// A response line.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Response {
/// The request id, or null if it could not be read.
pub id: Value,
/// The result on success.
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
/// The error on failure.
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorObject>,
}
impl Response {
/// A success response.
pub fn ok(id: Value, result: Value) -> Self {
Self {
id,
result: Some(result),
error: None,
}
}
/// An error response.
pub fn err(id: Value, code: &str, message: impl Into<String>) -> Self {
Self {
id,
result: None,
error: Some(ErrorObject {
code: code.to_string(),
message: message.into(),
}),
}
}
/// The response as one JSON line without the trailing newline.
pub fn to_line(&self) -> String {
serde_json::to_string(self).unwrap_or_else(|e| {
format!(r#"{{"id":null,"error":{{"code":"internal","message":"cannot encode response: {e}"}}}}"#)
})
}
}
/// Params of `engine.execute`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ExecuteParams {
/// Command id.
command: String,
/// Command params.
#[serde(default)]
params: Value,
}
/// Params of `ui.screenshot`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ScreenshotParams {
/// Where to write the PNG.
path: PathBuf,
}
/// Parses a request line.
///
/// # Errors
/// An error response for invalid JSON, a non-object, a missing or
/// non-scalar id, or unknown fields.
pub fn parse_request(line: &str) -> Result<Request, Response> {
let value: Value = serde_json::from_str(line)
.map_err(|e| Response::err(Value::Null, codes::PARSE_ERROR, e.to_string()))?;
let id = value.get("id").cloned().unwrap_or(Value::Null);
let id_ok = matches!(id, Value::Number(_) | Value::String(_));
let echo = if id_ok { id } else { Value::Null };
if !id_ok {
return Err(Response::err(
echo,
codes::INVALID_REQUEST,
"request needs an id (number or string)",
));
}
serde_json::from_value(value)
.map_err(|e| Response::err(echo, codes::INVALID_REQUEST, e.to_string()))
}
/// Params of `app.auth`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuthParams {
/// The token from the rendezvous file.
pub token: String,
}
/// Answers one request line. Never panics: a panic in the backend becomes an
/// `internal` error response.
pub fn handle_line(line: &str, backend: &dyn Backend) -> Response {
let request = match parse_request(line) {
Ok(request) => request,
Err(response) => return response,
};
let id = request.id.clone();
match guard::run(|| Ok(dispatch(request, backend))) {
Ok(response) => response,
Err(e) => engine_error(id, &e),
}
}
/// Runs a parsed request.
fn dispatch(request: Request, backend: &dyn Backend) -> Response {
let Request { id, method, params } = request;
match method.as_str() {
APP_PING => Response::ok(
id,
json!({ "pong": true, "version": env!("CARGO_PKG_VERSION") }),
),
ENGINE_EXECUTE => match serde_json::from_value::<ExecuteParams>(params) {
Ok(p) => match backend.execute(&p.command, p.params) {
Ok(value) => Response::ok(id, value),
Err(e) => engine_error(id, &e),
},
Err(e) => Response::err(id, codes::INVALID_PARAMS, e.to_string()),
},
ENGINE_LIST_COMMANDS => match serde_json::to_value(backend.list_commands()) {
Ok(list) => Response::ok(id, list),
Err(e) => Response::err(id, "internal", e.to_string()),
},
UI_SCREENSHOT => match serde_json::from_value::<ScreenshotParams>(params) {
Ok(p) => match backend.screenshot(&p.path) {
Ok(()) => Response::ok(id, json!({ "path": p.path })),
Err(message) => Response::err(id, codes::SCREENSHOT_FAILED, message),
},
Err(e) => Response::err(id, codes::INVALID_PARAMS, e.to_string()),
},
APP_AUTH => Response::ok(id, json!({ "authenticated": true })),
APP_FOCUS => match backend.focus() {
Ok(()) => Response::ok(id, json!({ "focused": true })),
Err(message) => Response::err(id, codes::FOCUS_FAILED, message),
},
EVENTS_SUBSCRIBE => Response::err(
id,
codes::INVALID_REQUEST,
"events.subscribe needs a connection to stream on",
),
other => Response::err(
id,
codes::METHOD_NOT_FOUND,
format!("unknown method: {other}"),
),
}
}
/// An error response for an engine error.
fn engine_error(id: Value, error: &EngineError) -> Response {
Response::err(id, error.code(), error.to_string())
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::Mutex;
use lutra_engine::{CommandInfo, Effect, Engine};
use proptest::prelude::*;
use super::*;
struct TestBackend {
engine: Mutex<Engine>,
effects: Mutex<Vec<Effect>>,
}
impl TestBackend {
fn new() -> Self {
Self {
engine: Mutex::new(Engine::new().unwrap()),
effects: Mutex::new(Vec::new()),
}
}
}
impl Backend for TestBackend {
fn execute(&self, command: &str, params: Value) -> Result<Value, EngineError> {
let out = self.engine.lock().unwrap().execute(command, params)?;
self.effects.lock().unwrap().extend(out.effects);
Ok(out.value)
}
fn list_commands(&self) -> Vec<CommandInfo> {
self.engine.lock().unwrap().list_commands()
}
fn screenshot(&self, path: &Path) -> Result<(), String> {
if path.as_os_str() == "panic" {
panic!("screenshot exploded");
}
Err("no window".into())
}
fn subscribe(&self, _sink: crate::EventSink) {}
}
fn call(line: &str) -> Response {
handle_line(line, &TestBackend::new())
}
#[test]
fn subscribe_needs_a_connection() {
let r = call(r#"{"id":1,"method":"events.subscribe"}"#);
assert_eq!(r.error.unwrap().code, "invalid_request");
}
#[test]
fn auth_and_focus_on_an_open_channel() {
let r = call(r#"{"id":1,"method":"app.auth","params":{"token":"x"}}"#);
assert_eq!(r.result.unwrap()["authenticated"], true);
let r = call(r#"{"id":2,"method":"app.focus"}"#);
assert_eq!(r.error.unwrap().code, "focus_failed");
}
#[test]
fn ping() {
let r = call(r#"{"id":1,"method":"app.ping"}"#);
assert_eq!(r.id, json!(1));
assert_eq!(r.result.unwrap()["pong"], true);
}
#[test]
fn execute_runs_commands_and_collects_effects() {
let backend = TestBackend::new();
let r = handle_line(
r#"{"id":"a","method":"engine.execute","params":{"command":"app.about"}}"#,
&backend,
);
assert_eq!(r.result.unwrap()["name"], "Lutra");
let r = handle_line(
r#"{"id":2,"method":"engine.execute","params":{"command":"app.quit","params":{}}}"#,
&backend,
);
assert_eq!(r.result, Some(Value::Null));
assert_eq!(*backend.effects.lock().unwrap(), vec![Effect::Quit]);
}
#[test]
fn errors_carry_stable_codes() {
let code = |line: &str| call(line).error.unwrap().code;
assert_eq!(code("not json"), "parse_error");
assert_eq!(code("[1,2]"), "invalid_request");
assert_eq!(code(r#"{"method":"app.ping"}"#), "invalid_request");
assert_eq!(code(r#"{"id":{},"method":"app.ping"}"#), "invalid_request");
assert_eq!(
code(r#"{"id":1,"method":"app.ping","x":1}"#),
"invalid_request"
);
assert_eq!(code(r#"{"id":1,"method":"nope"}"#), "method_not_found");
assert_eq!(
code(r#"{"id":1,"method":"engine.execute"}"#),
"invalid_params"
);
assert_eq!(
code(r#"{"id":1,"method":"engine.execute","params":{"command":"x.y"}}"#),
"unknown_command"
);
assert_eq!(
code(r#"{"id":1,"method":"ui.screenshot","params":{"path":"a.png"}}"#),
"screenshot_failed"
);
}
#[test]
fn backend_panics_become_internal_errors() {
let r = call(r#"{"id":9,"method":"ui.screenshot","params":{"path":"panic"}}"#);
assert_eq!(r.id, json!(9));
let e = r.error.unwrap();
assert_eq!(e.code, "internal");
assert!(e.message.contains("screenshot exploded"));
}
#[test]
fn lists_commands() {
let r = call(r#"{"id":1,"method":"engine.listCommands"}"#);
let list = r.result.unwrap();
assert_eq!(list[0]["id"], "app.about");
}
proptest! {
#[test]
fn any_line_gets_a_well_formed_response(line in ".{0,200}") {
let r = call(&line);
prop_assert!(r.result.is_some() != r.error.is_some());
let back: Response = serde_json::from_str(&r.to_line()).unwrap();
prop_assert_eq!(back, r);
}
#[test]
fn json_shaped_lines_get_a_well_formed_response(
id in prop_oneof![Just(json!(1)), Just(json!("x")), Just(Value::Null), Just(json!([1]))],
method in prop_oneof![Just("app.ping".to_string()), Just("engine.execute".to_string()), Just("ui.screenshot".to_string()), "[a-z.]{0,20}"],
params in prop_oneof![Just(Value::Null), Just(json!({"command": "app.about"})), Just(json!({"path": 3})), Just(json!("s"))],
) {
let line = json!({"id": id, "method": method, "params": params}).to_string();
let r = call(&line);
prop_assert!(r.result.is_some() != r.error.is_some());
}
}
}