From 29a41f51be01e9bee80138f5b486d81b49464c43 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 15:56:31 +0000 Subject: [PATCH 01/16] feat(muxer/rex): add rex client and JSON models --- src/muxer/mod.rs | 8 + src/muxer/rex/client.rs | 181 +++++++++++++++ src/muxer/rex/mod.rs | 6 + src/muxer/rex/model.rs | 197 ++++++++++++++++ test/muxer/rex/client_test.rs | 407 ++++++++++++++++++++++++++++++++++ 5 files changed, 799 insertions(+) create mode 100644 src/muxer/rex/client.rs create mode 100644 src/muxer/rex/mod.rs create mode 100644 src/muxer/rex/model.rs create mode 100644 test/muxer/rex/client_test.rs diff --git a/src/muxer/mod.rs b/src/muxer/mod.rs index fe1eebc2..f266b496 100644 --- a/src/muxer/mod.rs +++ b/src/muxer/mod.rs @@ -3,6 +3,14 @@ use clap::ValueEnum; use miette::{Result, bail}; use std::env; pub(crate) mod herdr; +#[cfg_attr( + not(test), + expect( + dead_code, + reason = "unwired until the Muxer enum wiring subtask of parent 4b347a42; remove when wiring lands" + ) +)] +pub(crate) mod rex; pub(crate) mod tmux; pub(crate) mod zellij; pub(crate) use herdr::Herdr; diff --git a/src/muxer/rex/client.rs b/src/muxer/rex/client.rs new file mode 100644 index 00000000..8a50e898 --- /dev/null +++ b/src/muxer/rex/client.rs @@ -0,0 +1,181 @@ +use std::sync::Arc; + +use miette::{Report, Result, miette}; +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::json; + +use crate::cmd_basic; +use crate::common::cmd::{Runner, Type}; +use crate::common::muxer::Client; + +use super::model::{ + ClientListOutput, CreateOutput, CreateRequest, FocusOutput, PwdOutput, SessionListOutput, + SessionView, TargetResolveOutput, +}; + +#[derive(Debug)] +pub(crate) struct RexClient { + cmd_runner: Arc, +} + +impl Client for RexClient { + fn get_runner(&self) -> &R { + &self.cmd_runner + } +} + +impl RexClient { + pub(crate) fn new(cmd_runner: Arc) -> Self { + Self { cmd_runner } + } + + pub(crate) fn session_create(&self, request: &CreateRequest) -> Result { + let payload = to_json(request)?; + + self.run_json( + "session_create", + cmd_basic!("rex", args = ["api", "call", "session.create", payload]), + ) + } + + pub(crate) fn session_view(&self, session_id: &str) -> Result { + let payload = to_json(&json!({"session_id": session_id}))?; + + self.run_json( + "session_view", + cmd_basic!("rex", args = ["api", "call", "session.view", payload]), + ) + } + + pub(crate) fn session_focus_window( + &self, + session_id: &str, + window_id: &str, + ) -> Result { + let payload = to_json(&json!({"session_id": session_id, "window_id": window_id}))?; + + self.run_json( + "session_focus_window", + cmd_basic!( + "rex", + args = ["api", "call", "session.focus_window", payload] + ), + ) + } + + pub(crate) fn session_focus_block( + &self, + session_id: &str, + block_id: &str, + ) -> Result { + let payload = to_json(&json!({"session_id": session_id, "block_id": block_id}))?; + + self.run_json( + "session_focus_block", + cmd_basic!( + "rex", + args = ["api", "call", "session.focus_block", payload] + ), + ) + } + + pub(crate) fn session_list(&self) -> Result { + self.run_json( + "session_list", + cmd_basic!("rex", args = ["session", "ls", "--json"]), + ) + } + + pub(crate) fn target_resolve( + &self, + kinds: &[&str], + queries: &[&str], + ) -> Result { + let payload = to_json(&json!({"kinds": kinds, "queries": queries}))?; + + self.run_json( + "target_resolve", + cmd_basic!("rex", args = ["api", "call", "target.resolve", payload]), + ) + } + + pub(crate) fn client_list(&self) -> Result { + self.run_json( + "client_list", + cmd_basic!("rex", args = ["client", "ls", "--json"]), + ) + } + + pub(crate) fn block_pwd(&self, session: &str, block_id: &str) -> Result { + self.run_json( + "block_pwd", + cmd_basic!( + "rex", + args = ["block", "call", "-s", session, "-b", block_id, "pwd"] + ), + ) + } + + pub(crate) fn zoom(&self, session: &str, block_id: &str, on: bool) -> Result<()> { + let state = if on { "--on" } else { "--off" }; + + self.run_unit( + "zoom", + cmd_basic!("rex", args = ["zoom", "-s", session, block_id, state]), + ) + } + + pub(crate) fn send_commands(&self, session: &str, block_id: &str, text: &str) -> Result<()> { + self.run_unit( + "send_commands", + cmd_basic!( + "rex", + args = ["send", "-s", session, "-b", block_id, "--", text] + ), + ) + } + + fn run_json(&self, method: &str, cmd: Type) -> Result { + let output = self.run_string(method, &cmd)?; + + parse_json(method, &output) + } + + fn run_string(&self, method: &str, cmd: &Type) -> Result { + let output: String = self + .cmd_runner + .run(cmd) + .map_err(|error| rex_error(method, &error))?; + + Ok(output) + } + + fn run_unit(&self, method: &str, cmd: Type) -> Result<()> { + let _: () = self + .cmd_runner + .run(&cmd) + .map_err(|error| rex_error(method, &error))?; + + Ok(()) + } +} + +fn to_json(value: &T) -> Result { + serde_json::to_string(value) + .map_err(|error| miette!("rex request serialisation failed: {error}")) +} + +fn parse_json(method: &str, output: &str) -> Result { + serde_json::from_str(output) + .map_err(|error| miette!("rex {method} returned invalid JSON: {error}: {output}")) +} + +fn rex_error(method: &str, error: &Report) -> Report { + let detail = error + .chain() + .map(ToString::to_string) + .collect::>() + .join(": "); + + miette!("rex {method} failed: {detail}") +} diff --git a/src/muxer/rex/mod.rs b/src/muxer/rex/mod.rs new file mode 100644 index 00000000..e931ce6b --- /dev/null +++ b/src/muxer/rex/mod.rs @@ -0,0 +1,6 @@ +pub(crate) mod client; +pub(crate) mod model; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/client_test.rs"] +mod client_test; diff --git a/src/muxer/rex/model.rs b/src/muxer/rex/model.rs new file mode 100644 index 00000000..20451c2e --- /dev/null +++ b/src/muxer/rex/model.rs @@ -0,0 +1,197 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct SessionListOutput { + #[serde(default)] + pub(crate) sessions: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct SessionListEntry { + pub(crate) session_id: String, + pub(crate) label: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct CreateOutput { + pub(crate) session_id: String, + #[serde(default)] + pub(crate) initial_windows: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct CreateWindowOut { + pub(crate) window_id: String, + #[serde(default)] + pub(crate) block_ids: Vec, + pub(crate) revision: u32, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct SessionView { + pub(crate) revision: u32, + pub(crate) session_id: Option, + pub(crate) label: Option, + pub(crate) active_window_id: Option, + pub(crate) windows: Option>, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct WindowView { + pub(crate) window_id: Option, + pub(crate) label: Option, + pub(crate) focused_block_id: Option, + pub(crate) zoomed_block_id: Option, + pub(crate) layers: Option>, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct LayerView { + pub(crate) layer_id: Option, + pub(crate) kind: String, + pub(crate) bounds: Vec, + pub(crate) layout: Option, + pub(crate) blocks: Option>, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct ViewNode { + pub(crate) rect: Vec, + pub(crate) block_id: Option, + pub(crate) split: Option>, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +pub(crate) struct ViewSplit { + pub(crate) split_id: Option, + pub(crate) direction: String, + pub(crate) ratio: Option, + pub(crate) before: Option, + pub(crate) after: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct BlockRef { + pub(crate) block_id: String, + pub(crate) creator_name: Option, + pub(crate) flavor: Option, + pub(crate) label: Option, + pub(crate) owner: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct TargetResolveOutput { + pub(crate) results: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct ResolveResult { + pub(crate) query: String, + pub(crate) status: String, + pub(crate) target: Option, + pub(crate) candidates: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct Candidate { + pub(crate) kind: String, + pub(crate) label: String, + pub(crate) session_id: Option, + pub(crate) window_id: Option, + pub(crate) block_id: Option, + pub(crate) ordinal: Option, + #[serde(rename = "where")] + pub(crate) r#where: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct PwdOutput { + pub(crate) pwd: String, + pub(crate) owner: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct PwdOwner { + pub(crate) pid: u32, + pub(crate) name: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct ClientListOutput { + pub(crate) clients: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct ClientEntry { + pub(crate) client_id: String, + pub(crate) connection_state: Option, + pub(crate) info: Option, + pub(crate) session_ids: Option>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub(crate) struct ClientInfo { + pub(crate) kind: Option, + pub(crate) platform: Option, + pub(crate) name: Option, + pub(crate) version: Option, + pub(crate) label: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +pub(crate) struct FocusOutput { + pub(crate) revision: u32, +} + +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub(crate) struct CreateRequest { + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) label: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) initial_windows: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub(crate) struct CreateWindow { + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) window_label: Option, + pub(crate) layout: LayoutNode, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub(crate) struct LayoutNode { + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) block: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) split: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub(crate) struct BlockNode { + pub(crate) flavor: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) label: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) options: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub(crate) struct SplitNode { + pub(crate) direction: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) ratio: Option, + pub(crate) before: Box, + pub(crate) after: Box, +} + +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub(crate) struct BlockOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) shell: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) login: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) cwd: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) initial_input: Option, +} diff --git a/test/muxer/rex/client_test.rs b/test/muxer/rex/client_test.rs new file mode 100644 index 00000000..243592b9 --- /dev/null +++ b/test/muxer/rex/client_test.rs @@ -0,0 +1,407 @@ +use std::sync::Arc; + +use miette::{Report, miette}; +use serde_json::{Value, json}; + +use crate::common::cmd::Type; +use crate::common::cmd::test::{MockCmdBoolMock, MockCmdStringMock, MockCmdUnitMock, RunnerMock}; +use crate::muxer::rex::client::RexClient; +use crate::muxer::rex::model::{ + BlockNode, BlockOptions, CreateRequest, CreateWindow, LayoutNode, SplitNode, +}; + +type TestResult = core::result::Result>; + +fn argv(cmd: &Type) -> Option<(String, Vec)> { + match cmd { + Type::Basic(command) => Some(( + command.get_program().to_string_lossy().into_owned(), + command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(), + )), + Type::Verbose(_) | Type::Forget(_) => None, + } +} + +fn exact_argv(cmd: &Type, expected: &[String]) -> bool { + argv(cmd).is_some_and(|(program, args)| program == "rex" && args == expected) +} + +fn api_payload(cmd: &Type, method: &str) -> Option { + let (program, args) = argv(cmd)?; + if program != "rex" + || args.len() != 4 + || args[0] != "api" + || args[1] != "call" + || args[2] != method + { + return None; + } + + serde_json::from_str(&args[3]).ok() +} + +fn expected(args: &[&str]) -> Vec { + args.iter().map(|arg| arg.to_string()).collect() +} + +fn runner(cmd_unit: MockCmdUnitMock, cmd_string: MockCmdStringMock) -> Arc { + Arc::new(RunnerMock { + cmd_unit, + cmd_string, + cmd_bool: MockCmdBoolMock::new(), + }) +} + +fn string_client_with(matcher: F, output: &str) -> TestResult> +where + F: Fn(&Type) -> bool + Send + 'static, +{ + let output = output.to_string(); + let mut cmd_string = MockCmdStringMock::new(); + cmd_string + .expect_run() + .times(1) + .withf(matcher) + .returning(move |_| Ok(output.clone())); + + Ok(RexClient::new(runner(MockCmdUnitMock::new(), cmd_string))) +} + +fn string_client(args: &[&str], output: &str) -> TestResult> { + let expected_args = expected(args); + + string_client_with(move |cmd| exact_argv(cmd, &expected_args), output) +} + +fn api_client( + method: &'static str, + payload: Value, + output: &str, +) -> TestResult> { + string_client_with( + move |cmd| api_payload(cmd, method).is_some_and(|actual| actual == payload), + output, + ) +} + +fn failing_client( + args: &[&str], + stderr: &str, + context: &str, +) -> Result, Report> { + let expected_args = expected(args); + let stderr = stderr.to_string(); + let context = context.to_string(); + let mut cmd_string = MockCmdStringMock::new(); + cmd_string + .expect_run() + .times(1) + .withf(move |cmd| exact_argv(cmd, &expected_args)) + .returning(move |_| Err(miette!(stderr.clone()).wrap_err(context.clone()))); + + Ok(RexClient::new(runner(MockCmdUnitMock::new(), cmd_string))) +} + +fn unit_client(args: &[&str]) -> TestResult> { + let expected_args = expected(args); + let mut cmd_unit = MockCmdUnitMock::new(); + cmd_unit + .expect_run() + .times(1) + .withf(move |cmd| exact_argv(cmd, &expected_args)) + .returning(|_| Ok(())); + + Ok(RexClient::new(runner(cmd_unit, MockCmdStringMock::new()))) +} + +fn terminal(label: Option<&str>, options: Option) -> LayoutNode { + LayoutNode { + block: Some(BlockNode { + flavor: "terminal".to_string(), + label: label.map(str::to_string), + options, + }), + split: None, + } +} + +fn create_request() -> CreateRequest { + let options = BlockOptions { + cwd: Some("/tmp".to_string()), + ..BlockOptions::default() + }; + + CreateRequest { + label: Some("laio-probe".to_string()), + initial_windows: Some(vec![ + CreateWindow { + window_label: Some("w1".to_string()), + layout: terminal(Some("p1"), Some(options)), + }, + CreateWindow { + window_label: None, + layout: LayoutNode { + block: None, + split: Some(SplitNode { + direction: "horizontal".to_string(), + ratio: Some(0.5), + before: Box::new(terminal(None, None)), + after: Box::new(terminal(None, None)), + }), + }, + }, + ]), + } +} + +fn create_payload() -> Value { + json!({ + "label": "laio-probe", + "initial_windows": [ + { + "window_label": "w1", + "layout": { + "block": { + "flavor": "terminal", + "label": "p1", + "options": { "cwd": "/tmp" } + } + } + }, + { + "layout": { + "split": { + "direction": "horizontal", + "ratio": 0.5, + "before": { "block": { "flavor": "terminal" } }, + "after": { "block": { "flavor": "terminal" } } + } + } + } + ] + }) +} + +#[test] +fn session_create_sends_request_json_as_one_argument() -> TestResult { + let client = api_client( + "session.create", + create_payload(), + r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2","block:3"],"revision":7}]}"#, + )?; + + let output = client.session_create(&create_request())?; + + assert_eq!(output.session_id, "session:1"); + let window = output + .initial_windows + .first() + .ok_or("should have one window")?; + assert_eq!(window.window_id, "window:1"); + assert_eq!(window.block_ids, ["block:1", "block:2", "block:3"]); + Ok(()) +} + +#[test] +fn session_view_parses_window_without_focus_zoom_or_block_owner() -> TestResult { + let client = api_client( + "session.view", + json!({"session_id": "session:1"}), + r#"{"revision":12,"session_id":"session:1","label":"laio-probe","active_window_id":"window:1","windows":[{"window_id":"window:1","label":"Window 01a1","layers":[{"layer_id":"layer:1","kind":"tiled","bounds":[0,0,1,1],"layout":{"rect":[0,0,1,1],"block_id":"block:1"},"blocks":[{"block_id":"block:1","creator_name":"rex","flavor":"terminal","label":"shell"}]}]}]}"#, + )?; + + let view = client.session_view("session:1")?; + + assert_eq!(view.revision, 12); + let window = view + .windows + .and_then(|windows| windows.into_iter().next()) + .ok_or("should have one window")?; + assert!(window.focused_block_id.is_none()); + assert!(window.zoomed_block_id.is_none()); + let block = window + .layers + .and_then(|layers| layers.into_iter().next()) + .and_then(|layer| layer.blocks) + .and_then(|blocks| blocks.into_iter().next()) + .ok_or("should have one block")?; + assert_eq!(block.block_id, "block:1"); + assert!(block.owner.is_none()); + Ok(()) +} + +#[test] +fn session_focus_window_sends_session_and_window() -> TestResult { + let client = api_client( + "session.focus_window", + json!({"session_id": "session:1", "window_id": "window:1"}), + r#"{"revision":9}"#, + )?; + + let output = client.session_focus_window("session:1", "window:1")?; + + assert_eq!(output.revision, 9); + Ok(()) +} + +#[test] +fn session_focus_block_sends_session_and_block() -> TestResult { + let client = api_client( + "session.focus_block", + json!({"session_id": "session:1", "block_id": "block:1"}), + r#"{"revision":10}"#, + )?; + + let output = client.session_focus_block("session:1", "block:1")?; + + assert_eq!(output.revision, 10); + Ok(()) +} + +#[test] +fn session_list_reads_cli_json_output() -> TestResult { + let client = string_client( + &["session", "ls", "--json"], + r#"{"sessions":[{"session_id":"session:1","label":"laio-probe"},{"session_id":"session:2","label":"other"}]}"#, + )?; + + let output = client.session_list()?; + + let labels: Vec<&str> = output + .sessions + .iter() + .map(|session| session.label.as_str()) + .collect(); + assert_eq!(labels, ["laio-probe", "other"]); + Ok(()) +} + +#[test] +fn target_resolve_sends_kinds_and_queries() -> TestResult { + let client = api_client( + "target.resolve", + json!({"kinds": ["session"], "queries": ["laio-probe"]}), + r#"{"results":[{"query":"laio-probe","status":"not_found","candidates":[]}]}"#, + )?; + + let output = client.target_resolve(&["session"], &["laio-probe"])?; + + let results = output.results.ok_or("should have results")?; + assert_eq!(results.len(), 1); + assert_eq!(results[0].status, "not_found"); + Ok(()) +} + +#[test] +fn client_list_exposes_session_ids() -> TestResult { + let client = string_client( + &["client", "ls", "--json"], + r#"{"clients":[{"client_id":"client:app","connection_state":"connected","info":{"kind":"app","platform":"macos","name":"Rex Beta","version":"0.1.0 (1758)","label":"Mac"},"session_ids":["session:1","session:2"]},{"client_id":"client:cli","connection_state":"connected","info":{"kind":"cli","platform":"macos","name":"rex","version":"0.0.1"}}]}"#, + )?; + + let output = client.client_list()?; + + let clients = output.clients.ok_or("should have clients")?; + let app = clients.first().ok_or("should have the app client")?; + let session_ids = app + .session_ids + .clone() + .ok_or("app client should carry session ids")?; + assert_eq!(session_ids, ["session:1", "session:2"]); + let cli = clients.get(1).ok_or("should have the cli client")?; + assert!(cli.session_ids.is_none()); + Ok(()) +} + +#[test] +fn block_pwd_passes_session_scope() -> TestResult { + let client = string_client( + &["block", "call", "-s", "session:1", "-b", "block:1", "pwd"], + r#"{"pwd":"file://host/tmp/project","owner":{"pid":42,"name":"zsh"}}"#, + )?; + + let output = client.block_pwd("session:1", "block:1")?; + + assert_eq!(output.pwd, "file://host/tmp/project"); + let owner = output.owner.ok_or("should have an owner")?; + assert_eq!(owner.pid, 42); + Ok(()) +} + +#[test] +fn zoom_on_passes_session_scope() -> TestResult { + let client = unit_client(&["zoom", "-s", "session:1", "block:1", "--on"])?; + + client.zoom("session:1", "block:1", true)?; + Ok(()) +} + +#[test] +fn zoom_off_passes_session_scope() -> TestResult { + let client = unit_client(&["zoom", "-s", "session:1", "block:1", "--off"])?; + + client.zoom("session:1", "block:1", false)?; + Ok(()) +} + +#[test] +fn send_commands_passes_session_scope_and_verbatim_text() -> TestResult { + let client = unit_client(&[ + "send", + "-s", + "session:1", + "-b", + "block:1", + "--", + "echo one\necho two\n", + ])?; + + client.send_commands("session:1", "block:1", "echo one\necho two\n")?; + Ok(()) +} + +#[test] +fn nonzero_exit_error_contains_stderr_detail() -> TestResult { + let client = failing_client( + &["session", "ls", "--json"], + "Error: stream response \"control-1\" failed: block target block:9 not found (status=404 code=not_found)", + "Basic: rex session ls --json", + )?; + + let error = client.session_list().err().ok_or("should fail")?; + + assert!( + error.to_string().contains("block target block:9 not found"), + "{error}" + ); + Ok(()) +} + +#[test] +fn nonzero_exit_error_contains_server_code() -> TestResult { + let client = failing_client( + &["session", "ls", "--json"], + "Error: stream response \"control-2\" failed: session not found (status=404 code=not_found)", + "Basic: rex session ls --json", + )?; + + let error = client.session_list().err().ok_or("should fail")?; + + assert!(error.to_string().contains("not_found"), "{error}"); + Ok(()) +} + +#[test] +fn invalid_json_error_names_method_and_output() -> TestResult { + let client = string_client(&["session", "ls", "--json"], "not json at all")?; + + let error = client.session_list().err().ok_or("should fail")?; + let message = error.to_string(); + + assert!(message.contains("session_list"), "{message}"); + assert!(message.contains("not json at all"), "{message}"); + Ok(()) +} From 273a22d95d557f5605386c6be08dfc9762396e6f Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 16:06:57 +0000 Subject: [PATCH 02/16] feat(muxer/rex): add sidecar session store --- src/muxer/rex/mod.rs | 5 + src/muxer/rex/store.rs | 176 ++++++++++++++++++++++++++ test/muxer/rex/store_test.rs | 239 +++++++++++++++++++++++++++++++++++ 3 files changed, 420 insertions(+) create mode 100644 src/muxer/rex/store.rs create mode 100644 test/muxer/rex/store_test.rs diff --git a/src/muxer/rex/mod.rs b/src/muxer/rex/mod.rs index e931ce6b..e4976221 100644 --- a/src/muxer/rex/mod.rs +++ b/src/muxer/rex/mod.rs @@ -1,6 +1,11 @@ pub(crate) mod client; pub(crate) mod model; +pub(crate) mod store; #[cfg(test)] #[path = "../../../test/muxer/rex/client_test.rs"] mod client_test; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/store_test.rs"] +mod store_test; diff --git a/src/muxer/rex/store.rs b/src/muxer/rex/store.rs new file mode 100644 index 00000000..5ba2c713 --- /dev/null +++ b/src/muxer/rex/store.rs @@ -0,0 +1,176 @@ +use std::{ + env, fs, + io::ErrorKind, + path::{Path, PathBuf}, +}; + +use miette::{Result, miette}; +use serde::{Deserialize, Serialize}; + +use crate::common::path::home_dir; + +const STATE_DIR_ENV: &str = "LAIO_STATE_DIR"; +const XDG_STATE_HOME_ENV: &str = "XDG_STATE_HOME"; +const APP_DIR: &str = "laio"; +const REX_DIR: &str = "rex"; +const SESSION_PREFIX: &str = "session:"; +const RECORD_EXTENSION: &str = "json"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct RexSessionRecord { + pub(crate) rex_session_id: String, + pub(crate) rex_label: String, + pub(crate) laio_name: String, + pub(crate) config_path: String, + pub(crate) variables: String, + pub(crate) created_at: u64, +} + +#[derive(Debug, Clone)] +pub(crate) struct RexSessionStore { + dir: PathBuf, +} + +impl RexSessionStore { + pub(crate) fn new(dir: PathBuf) -> Self { + Self { dir } + } + + pub(crate) fn write_record(&self, record: &RexSessionRecord) -> Result<()> { + fs::create_dir_all(&self.dir) + .map_err(|error| miette!("failed to create '{}': {error}", self.dir.display()))?; + + let path = self.record_path(&record.rex_session_id); + let tmp_path = path.with_extension(format!("{RECORD_EXTENSION}.tmp")); + let json = serde_json::to_string_pretty(record) + .map_err(|error| miette!("failed to serialise rex session record: {error}"))?; + + fs::write(&tmp_path, json) + .map_err(|error| miette!("failed to write '{}': {error}", tmp_path.display()))?; + fs::rename(&tmp_path, &path) + .map_err(|error| miette!("failed to replace '{}': {error}", path.display())) + } + + pub(crate) fn read_by_name(&self, laio_name: &str) -> Result> { + Ok(self + .records()? + .into_iter() + .find(|record| record.laio_name == laio_name)) + } + + pub(crate) fn read_by_session(&self, rex_session_id: &str) -> Result> { + let path = self.record_path(rex_session_id); + + match fs::read_to_string(&path) { + Ok(json) => Ok(parse_record(&path, &json)), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(None), + Err(error) => Err(miette!("failed to read '{}': {error}", path.display())), + } + } + + pub(crate) fn delete_by_session(&self, rex_session_id: &str) -> Result<()> { + let path = self.record_path(rex_session_id); + + match fs::remove_file(&path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(()), + Err(error) => Err(miette!("failed to delete '{}': {error}", path.display())), + } + } + + pub(crate) fn prune(&self, live_session_ids: &[String]) -> Result> { + let mut pruned = Vec::new(); + + for record in self.records()? { + if live_session_ids.contains(&record.rex_session_id) { + continue; + } + + self.delete_by_session(&record.rex_session_id)?; + pruned.push(record.rex_session_id); + } + + Ok(pruned) + } + + pub(crate) fn list(&self) -> Result> { + self.records() + } + + fn records(&self) -> Result> { + let entries = match fs::read_dir(&self.dir) { + Ok(entries) => entries, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => { + return Err(miette!("failed to list '{}': {error}", self.dir.display())); + } + }; + + let mut paths: Vec = entries + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some(RECORD_EXTENSION)) + .collect(); + paths.sort(); + + Ok(paths + .iter() + .filter_map(|path| read_record_file(path)) + .collect()) + } + + fn record_path(&self, rex_session_id: &str) -> PathBuf { + let stem = rex_session_id + .strip_prefix(SESSION_PREFIX) + .unwrap_or(rex_session_id); + + self.dir.join(format!("{stem}.{RECORD_EXTENSION}")) + } +} + +fn read_record_file(path: &Path) -> Option { + match fs::read_to_string(path) { + Ok(json) => parse_record(path, &json), + Err(error) => { + log::warn!( + "Skipping unreadable rex session record '{}': {error}", + path.display() + ); + None + } + } +} + +fn parse_record(path: &Path, json: &str) -> Option { + match serde_json::from_str(json) { + Ok(record) => Some(record), + Err(error) => { + log::warn!("Skipping rex session record '{}': {error}", path.display()); + None + } + } +} + +pub(crate) fn laio_state_dir() -> PathBuf { + let override_dir = env::var(STATE_DIR_ENV).ok(); + let xdg_state_home = env::var(XDG_STATE_HOME_ENV).ok(); + let home = home_dir().unwrap_or_else(|_| "/".to_string()); + + resolve_state_dir(override_dir.as_deref(), xdg_state_home.as_deref(), &home) +} + +pub(crate) fn resolve_state_dir( + override_dir: Option<&str>, + xdg_state_home: Option<&str>, + home: &str, +) -> PathBuf { + match (override_dir, xdg_state_home) { + (Some(dir), _) => PathBuf::from(dir), + (None, Some(xdg)) => PathBuf::from(xdg).join(APP_DIR).join(REX_DIR), + (None, None) => PathBuf::from(home) + .join(".local") + .join("state") + .join(APP_DIR) + .join(REX_DIR), + } +} diff --git a/test/muxer/rex/store_test.rs b/test/muxer/rex/store_test.rs new file mode 100644 index 00000000..d238a99f --- /dev/null +++ b/test/muxer/rex/store_test.rs @@ -0,0 +1,239 @@ +use std::env; +use std::fs; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::common::path::home_dir; +use crate::muxer::rex::store::{ + RexSessionRecord, RexSessionStore, laio_state_dir, resolve_state_dir, +}; + +type TestResult = core::result::Result>; + +static NEXT_DIR: AtomicU64 = AtomicU64::new(0); + +fn unique_dir() -> PathBuf { + let suffix = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + + env::temp_dir().join(format!("laio-rex-store-{}-{suffix}", std::process::id())) +} + +fn record(rex_session_id: &str, laio_name: &str) -> RexSessionRecord { + RexSessionRecord { + rex_session_id: rex_session_id.to_string(), + rex_label: format!("{laio_name}-label"), + laio_name: laio_name.to_string(), + config_path: format!("/tmp/configs/{laio_name}.yaml"), + variables: format!("session_name={laio_name}&path=%2Ftmp"), + created_at: 1_700_000_000, + } +} + +fn store() -> RexSessionStore { + RexSessionStore::new(unique_dir()) +} + +#[test] +fn write_then_read_by_name_round_trips_every_field() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + let expected = record("session:1", "project"); + + store.write_record(&expected)?; + + let actual = store + .read_by_name("project")? + .ok_or("should read back the record")?; + + assert_eq!(actual.rex_session_id, expected.rex_session_id); + assert_eq!(actual.rex_label, expected.rex_label); + assert_eq!(actual.laio_name, expected.laio_name); + assert_eq!(actual.config_path, expected.config_path); + assert_eq!(actual.variables, expected.variables); + assert_eq!(actual.created_at, expected.created_at); + assert!( + dir.join("1.json").is_file(), + "record file is named after the uuid" + ); + Ok(()) +} + +#[test] +fn read_by_name_returns_none_for_an_unknown_name() -> TestResult { + let store = store(); + store.write_record(&record("session:1", "project"))?; + + let found = store.read_by_name("missing")?; + + assert!(found.is_none()); + Ok(()) +} + +#[test] +fn read_by_name_skips_files_that_are_not_valid_json() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + fs::write(dir.join("broken.json"), "{ not json")?; + let store = RexSessionStore::new(dir); + + let found = store.read_by_name("project")?; + + assert!(found.is_none()); + assert!(store.list()?.is_empty()); + Ok(()) +} + +#[test] +fn read_by_name_picks_the_record_with_the_matching_name() -> TestResult { + let store = store(); + store.write_record(&record("session:1", "alpha"))?; + store.write_record(&record("session:2", "beta"))?; + + let alpha = store.read_by_name("alpha")?.ok_or("should read alpha")?; + let beta = store.read_by_name("beta")?.ok_or("should read beta")?; + + assert_eq!(alpha.rex_session_id, "session:1"); + assert_eq!(beta.rex_session_id, "session:2"); + Ok(()) +} + +#[test] +fn read_by_session_reads_the_record_file_directly() -> TestResult { + let store = store(); + store.write_record(&record("session:1", "project"))?; + + let found = store + .read_by_session("session:1")? + .ok_or("should read the session record")?; + + assert_eq!(found.laio_name, "project"); + assert!(store.read_by_session("session:2")?.is_none()); + Ok(()) +} + +#[test] +fn read_by_session_returns_none_for_a_corrupt_record() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + fs::write(dir.join("1.json"), "{ not json")?; + let store = RexSessionStore::new(dir); + + let found = store.read_by_session("session:1")?; + + assert!(found.is_none()); + Ok(()) +} + +#[test] +fn read_by_session_errors_when_the_record_path_is_unreadable() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(dir.join("1.json"))?; + let store = RexSessionStore::new(dir); + + let error = store + .read_by_session("session:1") + .err() + .ok_or("reading a directory as a record should fail")?; + let message = error.to_string(); + + assert!(message.contains("1.json"), "{message}"); + Ok(()) +} + +#[test] +fn delete_by_session_removes_the_record_file() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + store.write_record(&record("session:1", "project"))?; + + store.delete_by_session("session:1")?; + + assert!(!dir.join("1.json").exists(), "record file should be gone"); + assert!(store.read_by_session("session:1")?.is_none()); + store.delete_by_session("session:1")?; + Ok(()) +} + +#[test] +fn prune_deletes_records_absent_from_the_live_ids() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + store.write_record(&record("session:a", "alpha"))?; + store.write_record(&record("session:b", "beta"))?; + + let pruned = store.prune(&["session:a".to_string()])?; + + assert_eq!(pruned, ["session:b"]); + assert!( + !dir.join("b.json").exists(), + "stale record file should be gone" + ); + assert!(dir.join("a.json").is_file(), "live record file should stay"); + Ok(()) +} + +#[test] +fn list_returns_every_readable_record() -> TestResult { + let store = store(); + store.write_record(&record("session:1", "alpha"))?; + store.write_record(&record("session:2", "beta"))?; + + let names: Vec = store + .list()? + .into_iter() + .map(|record| record.laio_name) + .collect(); + + assert_eq!(names, ["alpha", "beta"]); + Ok(()) +} + +#[test] +fn reads_tolerate_a_missing_store_directory() -> TestResult { + let store = store(); + + assert!(store.read_by_name("project")?.is_none()); + assert!(store.read_by_session("session:1")?.is_none()); + assert!(store.list()?.is_empty()); + assert!(store.prune(&["session:1".to_string()])?.is_empty()); + store.delete_by_session("session:1")?; + Ok(()) +} + +#[test] +fn resolve_state_dir_prefers_the_override() -> TestResult { + let resolved = resolve_state_dir(Some("/tmp/laio-state"), Some("/tmp/xdg"), "/tmp/home"); + + assert_eq!(resolved, PathBuf::from("/tmp/laio-state")); + Ok(()) +} + +#[test] +fn resolve_state_dir_uses_xdg_state_home_when_the_override_is_absent() -> TestResult { + let resolved = resolve_state_dir(None, Some("/tmp/xdg"), "/tmp/home"); + + assert_eq!(resolved, PathBuf::from("/tmp/xdg/laio/rex")); + Ok(()) +} + +#[test] +fn resolve_state_dir_falls_back_to_the_home_directory() -> TestResult { + let resolved = resolve_state_dir(None, None, "/tmp/home"); + + assert_eq!(resolved, PathBuf::from("/tmp/home/.local/state/laio/rex")); + Ok(()) +} + +#[test] +fn laio_state_dir_applies_the_real_env_to_the_resolver() -> TestResult { + let override_dir = env::var("LAIO_STATE_DIR").ok(); + let xdg_state_home = env::var("XDG_STATE_HOME").ok(); + let expected = resolve_state_dir( + override_dir.as_deref(), + xdg_state_home.as_deref(), + &home_dir()?, + ); + + assert_eq!(laio_state_dir(), expected); + Ok(()) +} From daf45e31819ee4f2d051cd9d21944bb771a294ee Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 16:15:16 +0000 Subject: [PATCH 03/16] feat(muxer/rex): add layout plan builder --- src/muxer/rex/layout.rs | 201 ++++++++++++++++++++ src/muxer/rex/mod.rs | 14 ++ test/muxer/rex/layout_test.rs | 332 ++++++++++++++++++++++++++++++++++ 3 files changed, 547 insertions(+) create mode 100644 src/muxer/rex/layout.rs create mode 100644 test/muxer/rex/layout_test.rs diff --git a/src/muxer/rex/layout.rs b/src/muxer/rex/layout.rs new file mode 100644 index 00000000..e115aa10 --- /dev/null +++ b/src/muxer/rex/layout.rs @@ -0,0 +1,201 @@ +use miette::{Result, miette}; + +use crate::common::config::{FlexDirection, Pane, Session, Window}; +use crate::common::path::sanitize_path; + +use super::model::{BlockNode, BlockOptions, CreateRequest, CreateWindow, LayoutNode, SplitNode}; + +const MIN_SPLIT_RATIO: f64 = 0.1; +const MAX_SPLIT_RATIO: f64 = 0.9; +const SHELL_FLAVOR: &str = "com.superlogical.terminal.shell"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct LeafPlan { + pub(crate) window_index: usize, + pub(crate) block_index: usize, + pub(crate) name: Option, + pub(crate) cwd: String, + pub(crate) commands: Vec, + pub(crate) zoom: bool, + pub(crate) focus: bool, +} + +struct WindowContext<'a> { + window_index: usize, + window_path: &'a str, + window_name: &'a str, + shell: &'a Option, +} + +pub(crate) fn build_create_request(session: &Session) -> Result<(CreateRequest, Vec)> { + let mut leaves = Vec::new(); + let mut windows = Vec::new(); + + for (window_index, window) in session.windows.iter().enumerate() { + let window_path = window.effective_path(&session.path); + let mut window_leaves = Vec::new(); + let context = WindowContext { + window_index, + window_path: &window_path, + window_name: &window.name, + shell: &session.shell, + }; + + let layout = build_window(window, &context, &mut window_leaves)?; + + windows.push(CreateWindow { + window_label: Some(window.name.clone()), + layout, + }); + leaves.extend(window_leaves); + } + + Ok(( + CreateRequest { + label: None, + initial_windows: Some(windows), + }, + leaves, + )) +} + +fn build_window( + window: &Window, + context: &WindowContext, + leaves: &mut Vec, +) -> Result { + if window.panes.is_empty() { + leaves.push(LeafPlan { + window_index: context.window_index, + block_index: 0, + name: None, + cwd: context.window_path.to_string(), + commands: Vec::new(), + zoom: false, + focus: false, + }); + + return Ok(block_node( + None, + context.window_path.to_string(), + context.shell, + )); + } + + build_siblings(&window.panes, &window.flex_direction, context, leaves) +} + +fn build_siblings( + panes: &[Pane], + direction: &FlexDirection, + context: &WindowContext, + leaves: &mut Vec, +) -> Result { + build_sibling(panes, 0, direction, context, leaves) +} + +fn build_sibling( + panes: &[Pane], + index: usize, + direction: &FlexDirection, + context: &WindowContext, + leaves: &mut Vec, +) -> Result { + let pane = panes.get(index).ok_or_else(|| { + miette!( + "Window '{}' has no pane at index {index}", + context.window_name + ) + })?; + + if index + 1 == panes.len() { + return build_pane(pane, context, leaves); + } + + let remaining: usize = panes[index..].iter().map(|pane| pane.flex).sum(); + let ratio = if remaining == 0 { + 0.0 + } else { + pane.flex as f64 / remaining as f64 + }; + + Ok(LayoutNode { + block: None, + split: Some(SplitNode { + direction: split_direction(direction).to_string(), + ratio: Some(clamp_ratio(ratio, context.window_name, index)), + before: Box::new(build_pane(pane, context, leaves)?), + after: Box::new(build_sibling(panes, index + 1, direction, context, leaves)?), + }), + }) +} + +fn build_pane( + pane: &Pane, + context: &WindowContext, + leaves: &mut Vec, +) -> Result { + if pane.panes.is_empty() { + let cwd = sanitize_path(&pane.path, &context.window_path.to_string()); + + leaves.push(LeafPlan { + window_index: context.window_index, + block_index: leaves.len(), + name: pane.name.clone(), + cwd: cwd.clone(), + commands: pane_commands(pane)?, + zoom: pane.zoom, + focus: pane.focus, + }); + + return Ok(block_node(pane.name.clone(), cwd, context.shell)); + } + + build_siblings(&pane.panes, &pane.flex_direction, context, leaves) +} + +fn block_node(label: Option, cwd: String, shell: &Option) -> LayoutNode { + LayoutNode { + block: Some(BlockNode { + flavor: SHELL_FLAVOR.to_string(), + label, + options: Some(BlockOptions { + shell: shell.clone(), + cwd: Some(cwd), + ..BlockOptions::default() + }), + }), + split: None, + } +} + +fn pane_commands(pane: &Pane) -> Result> { + let mut commands: Vec = pane + .commands + .iter() + .map(|command| command.to_string()) + .collect(); + + if let Some(script) = &pane.script { + commands.push(script.to_cmd()?.to_string()); + } + + Ok(commands) +} + +fn split_direction(direction: &FlexDirection) -> &'static str { + match direction { + FlexDirection::Row => "horizontal", + FlexDirection::Column => "vertical", + } +} + +fn clamp_ratio(ratio: f64, window_name: &str, index: usize) -> f64 { + let clamped = ratio.clamp(MIN_SPLIT_RATIO, MAX_SPLIT_RATIO); + + if (clamped - ratio).abs() > f64::EPSILON { + log::warn!("Window '{window_name}' pane index {index} ratio {ratio} clamped to {clamped}"); + } + + clamped +} diff --git a/src/muxer/rex/mod.rs b/src/muxer/rex/mod.rs index e4976221..c7cf60a8 100644 --- a/src/muxer/rex/mod.rs +++ b/src/muxer/rex/mod.rs @@ -1,11 +1,25 @@ pub(crate) mod client; +pub(crate) mod layout; pub(crate) mod model; pub(crate) mod store; +#[cfg_attr( + not(test), + expect( + unused_imports, + reason = "unwired until the Muxer enum wiring subtask of parent 4b347a42; remove when wiring lands" + ) +)] +pub(crate) use layout::{LeafPlan, build_create_request}; + #[cfg(test)] #[path = "../../../test/muxer/rex/client_test.rs"] mod client_test; +#[cfg(test)] +#[path = "../../../test/muxer/rex/layout_test.rs"] +mod layout_test; + #[cfg(test)] #[path = "../../../test/muxer/rex/store_test.rs"] mod store_test; diff --git a/test/muxer/rex/layout_test.rs b/test/muxer/rex/layout_test.rs new file mode 100644 index 00000000..e970e9a2 --- /dev/null +++ b/test/muxer/rex/layout_test.rs @@ -0,0 +1,332 @@ +use std::collections::HashMap; + +use crate::common::config::{Command, FlexDirection, Pane, Script, Session, Window}; +use crate::muxer::rex::model::{BlockNode, CreateRequest, LayoutNode, SplitNode}; +use crate::muxer::rex::{LeafPlan, build_create_request}; + +type TestResult = core::result::Result>; + +fn test_session(windows: Vec) -> Session { + Session { + name: "test".to_string(), + path: "/tmp/project".to_string(), + startup: Vec::new(), + startup_script: None, + shutdown: Vec::new(), + shutdown_script: None, + env: HashMap::new(), + shell: None, + pane_cmd_delay: None, + windows, + } +} + +fn test_window(name: &str, flex_direction: FlexDirection, panes: Vec) -> Window { + Window { + name: name.to_string(), + path: None, + flex_direction, + panes, + focus: false, + } +} + +fn test_pane(flex: usize, name: Option<&str>, path: &str) -> Pane { + Pane { + flex_direction: FlexDirection::Row, + flex, + name: name.map(str::to_string), + path: path.to_string(), + style: None, + commands: Vec::new(), + script: None, + panes: Vec::new(), + zoom: false, + focus: false, + } +} + +fn split_of<'a>(node: &'a LayoutNode, context: &str) -> TestResult<&'a SplitNode> { + node.split + .as_ref() + .ok_or_else(|| format!("{context} should be a split, got {node:?}").into()) +} + +fn block_of<'a>(node: &'a LayoutNode, context: &str) -> TestResult<&'a BlockNode> { + node.block + .as_ref() + .ok_or_else(|| format!("{context} should be a block, got {node:?}").into()) +} + +fn collect_blocks<'a>(node: &'a LayoutNode, blocks: &mut Vec<&'a BlockNode>) { + if let Some(block) = &node.block { + blocks.push(block); + } + + if let Some(split) = &node.split { + collect_blocks(&split.before, blocks); + collect_blocks(&split.after, blocks); + } +} + +fn first_window(request: &CreateRequest) -> TestResult<&LayoutNode> { + request + .initial_windows + .as_ref() + .and_then(|windows| windows.first()) + .map(|window| &window.layout) + .ok_or_else(|| "request should carry one initial window".into()) +} + +fn positions(leaves: &[LeafPlan]) -> Vec<(usize, usize)> { + leaves + .iter() + .map(|leaf| (leaf.window_index, leaf.block_index)) + .collect() +} + +#[test] +fn build_create_request_splits_flex_two_one_one_into_nested_halves() -> TestResult { + let session = test_session(vec![test_window( + "main", + FlexDirection::Row, + vec![ + test_pane(2, None, "."), + test_pane(1, None, "."), + test_pane(1, None, "."), + ], + )]); + + let (request, leaves) = build_create_request(&session)?; + + assert_eq!(request.label, None); + let window = request + .initial_windows + .as_ref() + .and_then(|windows| windows.first()) + .ok_or("request should carry one initial window")?; + assert_eq!(window.window_label.as_deref(), Some("main")); + + let root = split_of(&window.layout, "window root")?; + assert_eq!(root.direction, "horizontal"); + assert_eq!(root.ratio, Some(0.5)); + + let after = split_of(&root.after, "inner split")?; + assert_eq!(after.direction, "horizontal"); + assert_eq!(after.ratio, Some(0.5)); + + assert_eq!(leaves.len(), 3); + Ok(()) +} + +#[test] +fn build_create_request_numbers_leaves_per_window() -> TestResult { + let session = test_session(vec![ + test_window( + "first", + FlexDirection::Row, + vec![ + test_pane(1, None, "."), + test_pane(1, None, "."), + test_pane(1, None, "."), + ], + ), + test_window( + "second", + FlexDirection::Row, + vec![test_pane(1, None, "."), test_pane(1, None, ".")], + ), + ]); + + let (_, leaves) = build_create_request(&session)?; + + assert_eq!(positions(&leaves), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1)]); + Ok(()) +} + +#[test] +fn build_create_request_maps_column_windows_to_vertical_splits() -> TestResult { + let session = test_session(vec![test_window( + "stack", + FlexDirection::Column, + vec![test_pane(1, None, "."), test_pane(1, None, ".")], + )]); + + let (request, _) = build_create_request(&session)?; + + let root = split_of(first_window(&request)?, "window root")?; + assert_eq!(root.direction, "vertical"); + Ok(()) +} + +#[test] +fn build_create_request_emits_one_block_for_a_window_without_panes() -> TestResult { + let mut window = test_window("empty", FlexDirection::Row, Vec::new()); + window.path = Some("sub".to_string()); + + let (request, leaves) = build_create_request(&test_session(vec![window]))?; + + let block = block_of(first_window(&request)?, "window root")?; + assert_eq!(block.flavor, "com.superlogical.terminal.shell"); + assert_eq!( + block + .options + .as_ref() + .and_then(|options| options.cwd.as_deref()), + Some("/tmp/project/sub") + ); + + assert_eq!(leaves.len(), 1); + assert_eq!(leaves[0].block_index, 0); + assert_eq!(leaves[0].cwd, "/tmp/project/sub"); + Ok(()) +} + +#[test] +fn build_create_request_clamps_ratios_outside_the_valid_range() -> TestResult { + let low = test_session(vec![test_window( + "low", + FlexDirection::Row, + vec![test_pane(1, None, "."), test_pane(10, None, ".")], + )]); + let high = test_session(vec![test_window( + "high", + FlexDirection::Row, + vec![test_pane(10, None, "."), test_pane(1, None, ".")], + )]); + + let (low_request, _) = build_create_request(&low)?; + let (high_request, _) = build_create_request(&high)?; + + let low_root = split_of(first_window(&low_request)?, "low window root")?; + assert_eq!(low_root.ratio, Some(0.1)); + block_of(&low_root.before, "low first child")?; + block_of(&low_root.after, "low second child")?; + + let high_root = split_of(first_window(&high_request)?, "high window root")?; + assert_eq!(high_root.ratio, Some(0.9)); + block_of(&high_root.before, "high first child")?; + block_of(&high_root.after, "high second child")?; + Ok(()) +} + +#[test] +fn build_create_request_sets_shell_on_every_block() -> TestResult { + let mut session = test_session(vec![test_window( + "main", + FlexDirection::Row, + vec![ + test_pane(2, None, "."), + test_pane(1, None, "."), + test_pane(1, None, "."), + ], + )]); + session.shell = Some("/bin/zsh".to_string()); + + let (request, _) = build_create_request(&session)?; + + let mut blocks = Vec::new(); + collect_blocks(first_window(&request)?, &mut blocks); + assert_eq!(blocks.len(), 3); + + for block in blocks { + assert_eq!( + block + .options + .as_ref() + .and_then(|options| options.shell.as_deref()), + Some("/bin/zsh"), + "{block:?}" + ); + } + Ok(()) +} + +#[test] +fn build_create_request_maps_pane_name_to_label_and_leaf_name() -> TestResult { + let session = test_session(vec![test_window( + "main", + FlexDirection::Row, + vec![test_pane(1, Some("build"), ".")], + )]); + + let (request, leaves) = build_create_request(&session)?; + + let block = block_of(first_window(&request)?, "window root")?; + assert_eq!(block.label.as_deref(), Some("build")); + assert_eq!(leaves[0].name.as_deref(), Some("build")); + Ok(()) +} + +#[test] +fn build_create_request_orders_leaf_commands_before_the_script() -> TestResult { + let script: Script = noyalib::compat::serde_yaml::from_str("echo hi")?; + let mut pane = test_pane(1, None, "."); + pane.commands = vec![ + Command::from_string("echo one"), + Command::from_string("echo two"), + ]; + pane.script = Some(script); + + let session = test_session(vec![test_window("main", FlexDirection::Row, vec![pane])]); + let (_, leaves) = build_create_request(&session)?; + + let commands = &leaves[0].commands; + assert_eq!(commands.len(), 3, "{commands:?}"); + assert_eq!(commands[0], "echo one"); + assert_eq!(commands[1], "echo two"); + assert!( + commands[2].contains("laio-"), + "script command should point at the materialized script: {commands:?}" + ); + Ok(()) +} + +#[test] +fn build_create_request_switches_direction_for_a_nested_pane_group() -> TestResult { + let mut group = test_pane(1, None, "."); + group.flex_direction = FlexDirection::Column; + group.panes = vec![test_pane(1, None, "a"), test_pane(1, None, "b")]; + + let session = test_session(vec![test_window( + "main", + FlexDirection::Row, + vec![group, test_pane(1, None, "c")], + )]); + + let (request, leaves) = build_create_request(&session)?; + + let root = split_of(first_window(&request)?, "window root")?; + assert_eq!(root.direction, "horizontal"); + + let group_split = split_of(&root.before, "nested pane group")?; + assert_eq!(group_split.direction, "vertical"); + + let block_indexes: Vec = leaves.iter().map(|leaf| leaf.block_index).collect(); + assert_eq!(block_indexes, [0, 1, 2]); + let cwds: Vec<&str> = leaves.iter().map(|leaf| leaf.cwd.as_str()).collect(); + assert_eq!(cwds, ["/tmp/project/a", "/tmp/project/b", "/tmp/project/c"]); + Ok(()) +} + +#[test] +fn build_create_request_carries_zoom_and_focus() -> TestResult { + let mut zoomed = test_pane(1, None, "."); + zoomed.zoom = true; + let mut focused = test_pane(1, None, "."); + focused.focus = true; + + let session = test_session(vec![test_window( + "main", + FlexDirection::Row, + vec![zoomed, focused], + )]); + + let (_, leaves) = build_create_request(&session)?; + + assert!(leaves[0].zoom); + assert!(!leaves[0].focus); + assert!(!leaves[1].zoom); + assert!(leaves[1].focus); + Ok(()) +} From 944c17d16c04e95898d8bce14044154d92fdb6ff Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 16:41:58 +0000 Subject: [PATCH 04/16] feat(muxer/rex): guard layout builder limits --- src/muxer/rex/layout.rs | 44 ++++++++++++++++++++++------ test/muxer/rex/layout_test.rs | 54 +++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 8 deletions(-) diff --git a/src/muxer/rex/layout.rs b/src/muxer/rex/layout.rs index e115aa10..22594303 100644 --- a/src/muxer/rex/layout.rs +++ b/src/muxer/rex/layout.rs @@ -1,4 +1,4 @@ -use miette::{Result, miette}; +use miette::{Result, bail, miette}; use crate::common::config::{FlexDirection, Pane, Session, Window}; use crate::common::path::sanitize_path; @@ -7,6 +7,8 @@ use super::model::{BlockNode, BlockOptions, CreateRequest, CreateWindow, LayoutN const MIN_SPLIT_RATIO: f64 = 0.1; const MAX_SPLIT_RATIO: f64 = 0.9; +const MAX_BLOCKS_PER_WINDOW: usize = 24; +const MAX_SPLIT_DEPTH: usize = 16; const SHELL_FLAVOR: &str = "com.superlogical.terminal.shell"; #[derive(Debug, Clone, PartialEq, Eq)] @@ -28,6 +30,10 @@ struct WindowContext<'a> { } pub(crate) fn build_create_request(session: &Session) -> Result<(CreateRequest, Vec)> { + if session.windows.is_empty() { + bail!("Session '{}' has no windows", session.name); + } + let mut leaves = Vec::new(); let mut windows = Vec::new(); @@ -64,7 +70,7 @@ fn build_window( context: &WindowContext, leaves: &mut Vec, ) -> Result { - if window.panes.is_empty() { + let layout = if window.panes.is_empty() { leaves.push(LeafPlan { window_index: context.window_index, block_index: 0, @@ -75,14 +81,29 @@ fn build_window( focus: false, }); - return Ok(block_node( - None, - context.window_path.to_string(), - context.shell, - )); + block_node(None, context.window_path.to_string(), context.shell) + } else { + build_siblings(&window.panes, &window.flex_direction, context, leaves)? + }; + + if leaves.len() > MAX_BLOCKS_PER_WINDOW { + bail!( + "Window '{}' has {} blocks, exceeding the {} block limit", + window.name, + leaves.len(), + MAX_BLOCKS_PER_WINDOW + ); } - build_siblings(&window.panes, &window.flex_direction, context, leaves) + let depth = tree_depth(&layout); + if depth > MAX_SPLIT_DEPTH { + bail!( + "Window '{}' has split depth {depth}, exceeding the {MAX_SPLIT_DEPTH} depth limit", + window.name + ); + } + + Ok(layout) } fn build_siblings( @@ -199,3 +220,10 @@ fn clamp_ratio(ratio: f64, window_name: &str, index: usize) -> f64 { clamped } + +fn tree_depth(node: &LayoutNode) -> usize { + match &node.split { + Some(split) => 1 + tree_depth(&split.before).max(tree_depth(&split.after)), + None => 1, + } +} diff --git a/test/muxer/rex/layout_test.rs b/test/muxer/rex/layout_test.rs index e970e9a2..6abc3a53 100644 --- a/test/muxer/rex/layout_test.rs +++ b/test/muxer/rex/layout_test.rs @@ -330,3 +330,57 @@ fn build_create_request_carries_zoom_and_focus() -> TestResult { assert!(leaves[1].focus); Ok(()) } + +#[test] +fn build_create_request_rejects_a_session_without_windows() -> TestResult { + let error = build_create_request(&test_session(Vec::new())) + .err() + .ok_or("a session without windows should fail")?; + let message = error.to_string(); + + assert!(message.contains("test"), "{message}"); + assert!(message.contains("no windows"), "{message}"); + Ok(()) +} + +#[test] +fn build_create_request_rejects_a_window_above_the_block_limit() -> TestResult { + let panes = (0..25).map(|_| test_pane(1, None, ".")).collect(); + let error = build_create_request(&test_session(vec![test_window( + "wide", + FlexDirection::Row, + panes, + )])) + .err() + .ok_or("25 blocks should fail")?; + let message = error.to_string(); + + assert!(message.contains("wide"), "{message}"); + assert!(message.contains("25"), "{message}"); + assert!(message.contains("24"), "{message}"); + Ok(()) +} + +#[test] +fn build_create_request_rejects_a_window_above_the_depth_limit() -> TestResult { + let mut nested = test_pane(1, None, "leaf"); + for _ in 0..15 { + let mut group = test_pane(1, None, "."); + group.panes = vec![test_pane(1, None, "leaf"), nested]; + nested = group; + } + + let error = build_create_request(&test_session(vec![test_window( + "deep", + FlexDirection::Row, + vec![test_pane(1, None, "leaf"), nested], + )])) + .err() + .ok_or("depth 17 should fail")?; + let message = error.to_string(); + + assert!(message.contains("deep"), "{message}"); + assert!(message.contains("depth"), "{message}"); + assert!(message.contains("16"), "{message}"); + Ok(()) +} From 64dbf4f95a8f5f8db3e14fd5ff21e35ca7ba8189 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 17:16:25 +0000 Subject: [PATCH 05/16] feat(muxer/rex): implement Multiplexer lifecycle methods --- src/muxer/rex/mod.rs | 25 +- src/muxer/rex/mux.rs | 595 +++++++++++++++++++++++++++++ test/muxer/rex/mux_test.rs | 347 +++++++++++++++++ test/muxer/rex/mux_test/session.rs | 101 +++++ test/muxer/rex/mux_test/start.rs | 371 ++++++++++++++++++ test/muxer/rex/mux_test/stop.rs | 326 ++++++++++++++++ test/muxer/rex/mux_test/switch.rs | 84 ++++ 7 files changed, 1848 insertions(+), 1 deletion(-) create mode 100644 src/muxer/rex/mux.rs create mode 100644 test/muxer/rex/mux_test.rs create mode 100644 test/muxer/rex/mux_test/session.rs create mode 100644 test/muxer/rex/mux_test/start.rs create mode 100644 test/muxer/rex/mux_test/stop.rs create mode 100644 test/muxer/rex/mux_test/switch.rs diff --git a/src/muxer/rex/mod.rs b/src/muxer/rex/mod.rs index c7cf60a8..3276ded8 100644 --- a/src/muxer/rex/mod.rs +++ b/src/muxer/rex/mod.rs @@ -1,8 +1,11 @@ pub(crate) mod client; pub(crate) mod layout; pub(crate) mod model; +pub(crate) mod mux; pub(crate) mod store; +pub(crate) use layout::{LeafPlan, build_create_request}; + #[cfg_attr( not(test), expect( @@ -10,7 +13,7 @@ pub(crate) mod store; reason = "unwired until the Muxer enum wiring subtask of parent 4b347a42; remove when wiring lands" ) )] -pub(crate) use layout::{LeafPlan, build_create_request}; +pub(crate) use mux::Rex; #[cfg(test)] #[path = "../../../test/muxer/rex/client_test.rs"] @@ -23,3 +26,23 @@ mod layout_test; #[cfg(test)] #[path = "../../../test/muxer/rex/store_test.rs"] mod store_test; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/mux_test.rs"] +mod mux_test; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/mux_test/start.rs"] +mod mux_test_start; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/mux_test/switch.rs"] +mod mux_test_switch; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/mux_test/session.rs"] +mod mux_test_session; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/mux_test/stop.rs"] +mod mux_test_stop; diff --git a/src/muxer/rex/mux.rs b/src/muxer/rex/mux.rs new file mode 100644 index 00000000..ca8ce0c2 --- /dev/null +++ b/src/muxer/rex/mux.rs @@ -0,0 +1,595 @@ +use std::collections::HashSet; +use std::env; +use std::path::PathBuf; +use std::sync::Arc; +use std::thread; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use miette::{Result, bail, miette}; + +use crate::app::manager::session::manager::{LAIO_CONFIG, LAIO_VARS, decode_variables}; +use crate::cmd_basic; +use crate::common::cmd::{Runner, ShellRunner, Type}; +use crate::common::config::Session; +use crate::common::muxer::{Client, Multiplexer}; +use crate::common::path::{resolve_symlink, to_absolute_path}; +use crate::common::session_info::SessionInfo; +use crate::muxer::rex::{LeafPlan, build_create_request}; + +use super::client::RexClient; +use super::model::{ClientListOutput, CreateOutput, ResolveResult}; +use super::store::{RexSessionRecord, RexSessionStore, laio_state_dir}; + +const LABEL_PREFIX: &str = "laio-"; +const MAX_LABEL_LEN: usize = 128; +const SESSION_KIND: &str = "session"; +const REX_SESSION_ENV: &str = "REX_SESSION"; +const RESOLVED: &str = "resolved"; +const AMBIGUOUS: &str = "ambiguous"; + +pub(crate) struct Rex { + client: RexClient, + store: RexSessionStore, +} + +impl Rex { + pub(crate) fn new() -> Self { + Self::new_with_parts(ShellRunner::new(), laio_state_dir()) + } +} + +impl Rex { + pub(crate) fn new_with_parts(runner: R, store_dir: PathBuf) -> Self { + Self { + client: RexClient::new(Arc::new(runner)), + store: RexSessionStore::new(store_dir), + } + } + + fn write_record( + &self, + rex_session_id: &str, + label: &str, + session: &Session, + env_vars: &[(&str, &str)], + ) { + let record = RexSessionRecord { + rex_session_id: rex_session_id.to_string(), + rex_label: label.to_string(), + laio_name: session.name.clone(), + config_path: env_value(env_vars, LAIO_CONFIG).to_string(), + variables: env_value(env_vars, LAIO_VARS).to_string(), + created_at: unix_seconds(), + }; + + if let Err(error) = self.store.write_record(&record) { + log::warn!( + "Failed to write the rex session record for '{}': {error}", + session.name + ); + } + } + + fn delete_record(&self, rex_session_id: &str) { + if let Err(error) = self.store.delete_by_session(rex_session_id) { + log::warn!("Failed to delete the rex session record '{rex_session_id}': {error}"); + } + } + + fn run_startup_hooks(&self, session: &Session) -> Result<()> { + let mut commands = session.startup.clone(); + if let Some(script) = &session.startup_script { + commands.push(script.to_cmd()?); + } + + self.client.run_commands(&commands, &session.path) + } + + fn run_shutdown_hooks( + &self, + name: &str, + record: Option<&RexSessionRecord>, + session: &Option, + ) -> Result<()> { + if let Some(session) = session { + return self.run_shutdown_commands(session); + } + + let Some(record) = record else { + log::warn!("No usable rex session record for '{name}'; skipping shutdown commands"); + return Ok(()); + }; + + let variables = decode_record_variables(name, &record.variables); + let session = Session::from_config( + &resolve_symlink(&to_absolute_path(&record.config_path)?)?, + variables.as_deref(), + )?; + + self.run_shutdown_commands(&session) + } + + fn run_shutdown_commands(&self, session: &Session) -> Result<()> { + let mut commands = session.shutdown.clone(); + if let Some(script) = &session.shutdown_script { + commands.push(script.to_cmd()?); + } + + self.client.run_commands(&commands, &session.path) + } + + fn resolve_session(&self, name: &str) -> Result> { + let label = laio_label(name)?; + let output = self + .client + .target_resolve(&[SESSION_KIND], &[label.as_str()])?; + + let Some(result) = output + .results + .and_then(|results| results.into_iter().next()) + else { + return Ok(None); + }; + + resolution(&label, &result) + } + + fn attach(&self, rex_session_id: &str, skip_attach: bool) { + if skip_attach { + return; + } + + if let Err(error) = self.select_session(rex_session_id) { + log::warn!("Failed to attach to rex session '{rex_session_id}': {error}"); + } + } + + fn select_session(&self, rex_session_id: &str) -> Result<()> { + let _: () = self.client.get_runner().run(&cmd_basic!( + "rex", + args = [ + "do", + "session.select", + format!("session_id={rex_session_id}") + ] + ))?; + + Ok(()) + } + + fn kill_session(&self, rex_session_id: &str) -> Result<()> { + let _: () = self + .client + .get_runner() + .run(&cmd_basic!("rex", args = ["kill", rex_session_id]))?; + + Ok(()) + } + + fn stop_target(&self, name: &str, record: Option<&RexSessionRecord>) -> Result> { + if let Some(record) = record { + return Ok(Some(record.rex_session_id.clone())); + } + + self.resolve_session(name) + } + + fn stop_named( + &self, + name: &str, + session: &Option, + skip_cmds: bool, + stop_other: bool, + ) -> Result<()> { + let record = self.store.read_by_name(name)?; + + let Some(rex_session_id) = self.stop_target(name, record.as_ref())? else { + log::debug!("Not a laio session: {name}"); + return Ok(()); + }; + + self.stop_resolved( + name, + &rex_session_id, + record.as_ref(), + session, + skip_cmds, + stop_other, + ) + } + + fn stop_current( + &self, + rex_session_id: &str, + session: &Option, + skip_cmds: bool, + stop_other: bool, + ) -> Result<()> { + let record = self.store.read_by_session(rex_session_id)?; + + if let Some(record) = &record { + return self.stop_resolved( + &record.laio_name, + rex_session_id, + Some(record), + session, + skip_cmds, + stop_other, + ); + } + + let Some(label) = self.live_label(rex_session_id)? else { + log::debug!("Not a laio session: {rex_session_id}"); + return Ok(()); + }; + + let Some(name) = label.strip_prefix(LABEL_PREFIX) else { + log::debug!("Not a laio session: {label}"); + return Ok(()); + }; + + self.stop_resolved(name, rex_session_id, None, session, skip_cmds, stop_other) + } + + fn live_label(&self, rex_session_id: &str) -> Result> { + Ok(self + .client + .session_list()? + .sessions + .into_iter() + .find(|session| session.session_id == rex_session_id) + .map(|session| session.label)) + } + + fn stop_resolved( + &self, + name: &str, + rex_session_id: &str, + record: Option<&RexSessionRecord>, + session: &Option, + skip_cmds: bool, + stop_other: bool, + ) -> Result<()> { + log::trace!("Closing rex session: {name}"); + + let hooks = if skip_cmds || stop_other { + Ok(()) + } else { + self.run_shutdown_hooks(name, record, session) + }; + + let kill = self.kill_session(rex_session_id); + self.delete_record(rex_session_id); + + hooks.and(kill) + } + + fn sweep(&self, skip_cmds: bool, current: Option<&str>) -> Result<()> { + log::trace!("Closing all/other laio rex sessions."); + + let sessions = self.client.session_list()?.sessions; + let live_ids: Vec = sessions + .iter() + .map(|session| session.session_id.clone()) + .collect(); + + self.store.prune(&live_ids)?; + + let mut targets: Vec<(String, String, Option)> = self + .store + .list()? + .into_iter() + .filter(|record| Some(record.rex_session_id.as_str()) != current) + .map(|record| { + ( + record.laio_name.clone(), + record.rex_session_id.clone(), + Some(record), + ) + }) + .collect(); + + for session in &sessions { + let Some(name) = session.label.strip_prefix(LABEL_PREFIX) else { + continue; + }; + + let recorded = targets + .iter() + .any(|(_, rex_session_id, _)| rex_session_id == &session.session_id); + + if recorded || Some(session.session_id.as_str()) == current { + continue; + } + + targets.push((name.to_string(), session.session_id.clone(), None)); + } + + for (name, rex_session_id, record) in &targets { + log::trace!("Closing rex session: {name}"); + + let hooks = if skip_cmds { + Ok(()) + } else { + self.run_shutdown_hooks(name, record.as_ref(), &None) + }; + + let kill = self.kill_session(rex_session_id); + self.delete_record(rex_session_id); + + hooks.and(kill)?; + } + + Ok(()) + } +} + +impl Multiplexer for Rex { + fn start( + &self, + session: &Session, + env_vars: &[(&str, &str)], + skip_attach: bool, + skip_cmds: bool, + ) -> Result<()> { + if self.switch(&session.name, skip_attach)? { + return Ok(()); + } + + let label = laio_label(&session.name)?; + let (mut request, leaves) = build_create_request(session)?; + request.label = Some(label.clone()); + + let created = self.client.session_create(&request)?; + + self.write_record(&created.session_id, &label, session, env_vars); + + if !skip_cmds { + self.run_startup_hooks(session)?; + } + + if let Some(index) = session.windows.iter().position(|window| window.focus) + && let Some(window) = created.initial_windows.get(index) + { + self.client + .session_focus_window(&created.session_id, &window.window_id)?; + } + + for leaf in leaves.iter().filter(|leaf| leaf.focus) { + if let Some(block_id) = block_id(&created, leaf) { + self.client + .session_focus_block(&created.session_id, block_id)?; + } + } + + for leaf in leaves.iter().filter(|leaf| leaf.zoom) { + if let Some(block_id) = block_id(&created, leaf) { + self.client.zoom(&created.session_id, block_id, true)?; + } + } + + if !skip_cmds { + if let Some(delay_ms) = session.pane_cmd_delay { + thread::sleep(Duration::from_millis(delay_ms)); + } + + for leaf in &leaves { + if leaf.commands.is_empty() { + continue; + } + + let Some(block_id) = block_id(&created, leaf) else { + log::warn!( + "rex session '{}' has no block for window {} index {}", + session.name, + leaf.window_index, + leaf.block_index + ); + continue; + }; + + let text = format!("{}\n", leaf.commands.join("\n")); + + if let Err(error) = self + .client + .send_commands(&created.session_id, block_id, &text) + { + log::warn!("Failed to send commands to rex block '{block_id}': {error}"); + } + } + } + + self.attach(&created.session_id, skip_attach); + + Ok(()) + } + + fn stop( + &self, + name: &Option, + session: &Option, + skip_cmds: bool, + stop_all: bool, + stop_other: bool, + ) -> Result<()> { + let current = current_session(); + log::trace!("Current rex session: {current:?}"); + + if !stop_all && !stop_other && name.is_none() && current.is_none() { + bail!("Specify laio session you want to stop."); + } + + if (stop_all || stop_other) && name.is_some() { + bail!("Stopping all/other and specifying a session name are mutually exclusive."); + } + + if stop_other && current.is_none() { + bail!("Not inside a rex session."); + } + + if stop_all || (stop_other && current.is_some()) { + return self.sweep(skip_cmds, current.as_deref()); + } + + if let Some(name) = name { + return self.stop_named(name, session, skip_cmds, stop_other); + } + + let Some(current) = current else { + return Ok(()); + }; + + self.stop_current(¤t, session, skip_cmds, stop_other) + } + + fn get_session_config_path(&self, name: &str) -> Result> { + Ok(self + .store + .read_by_name(name)? + .map(|record| record.config_path)) + } + + fn get_session_variables(&self, name: &str) -> Result>> { + let Some(record) = self.store.read_by_name(name)? else { + return Ok(None); + }; + + Ok(decode_record_variables(name, &record.variables)) + } + + fn list_sessions(&self) -> Result> { + let sessions = self.client.session_list()?.sessions; + let live_ids: Vec = sessions + .iter() + .map(|session| session.session_id.clone()) + .collect(); + + self.store.prune(&live_ids)?; + + let attached = attached_session_ids(&self.client.client_list()?); + let records = self.store.list()?; + + let mut infos: Vec = records + .iter() + .map(|record| { + SessionInfo::active( + record.laio_name.clone(), + attached.contains(&record.rex_session_id), + ) + }) + .collect(); + + for session in &sessions { + let Some(name) = session.label.strip_prefix(LABEL_PREFIX) else { + continue; + }; + + let recorded = records + .iter() + .any(|record| record.rex_session_id == session.session_id); + + if !recorded { + infos.push(SessionInfo::inactive(name.to_string())); + } + } + + Ok(infos) + } + + fn switch(&self, name: &str, skip_attach: bool) -> Result { + let Some(rex_session_id) = self.resolve_session(name)? else { + return Ok(false); + }; + + self.attach(&rex_session_id, skip_attach); + + Ok(true) + } + + fn get_session(&self) -> Result { + Err(miette!("Exporting a rex session is not supported yet.")) + } +} + +fn block_id<'a>(created: &'a CreateOutput, leaf: &LeafPlan) -> Option<&'a str> { + created + .initial_windows + .get(leaf.window_index) + .and_then(|window| window.block_ids.get(leaf.block_index)) + .map(String::as_str) +} + +fn attached_session_ids(output: &ClientListOutput) -> HashSet { + output + .clients + .iter() + .flatten() + .filter_map(|client| client.session_ids.as_ref()) + .flatten() + .cloned() + .collect() +} + +fn decode_record_variables(name: &str, encoded: &str) -> Option> { + if encoded.is_empty() { + return Some(Vec::new()); + } + + match decode_variables(encoded) { + Ok(variables) => Some(variables), + Err(error) => { + log::warn!("Failed to decode LAIO_VARS for session '{name}': {error:?}"); + None + } + } +} + +fn resolution(label: &str, result: &ResolveResult) -> Result> { + match result.status.as_str() { + AMBIGUOUS => Err(miette!("Multiple rex sessions match the label '{label}'")), + RESOLVED => Ok(result + .target + .as_ref() + .and_then(|target| target.session_id.clone())), + _ => Ok(None), + } +} + +fn laio_label(name: &str) -> Result { + let valid = !name.is_empty() + && name + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-')); + + if !valid { + bail!("Invalid rex session name '{name}'"); + } + + let label = format!("{LABEL_PREFIX}{name}"); + + if label.len() > MAX_LABEL_LEN { + bail!("rex session label '{label}' exceeds {MAX_LABEL_LEN} characters"); + } + + Ok(label) +} + +fn env_value<'a>(env_vars: &'a [(&str, &str)], key: &str) -> &'a str { + env_vars + .iter() + .find(|(env_key, _)| *env_key == key) + .map(|(_, value)| *value) + .unwrap_or_default() +} + +fn current_session() -> Option { + env::var(REX_SESSION_ENV) + .ok() + .filter(|value| !value.is_empty()) +} + +fn unix_seconds() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_secs()) +} diff --git a/test/muxer/rex/mux_test.rs b/test/muxer/rex/mux_test.rs new file mode 100644 index 00000000..872ec6c5 --- /dev/null +++ b/test/muxer/rex/mux_test.rs @@ -0,0 +1,347 @@ +use std::env; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +use serde_json::{Value, json}; + +use crate::common::cmd::{ + Type, + test::{MockCmdBoolMock, MockCmdStringMock, MockCmdUnitMock, RunnerMock}, +}; +use crate::common::config::Session; +use crate::muxer::rex::Rex; +use crate::muxer::rex::store::{RexSessionRecord, RexSessionStore}; + +pub(super) type TestResult = core::result::Result>; +pub(super) type Log = Arc>>; + +static NEXT_DIR: AtomicU64 = AtomicU64::new(0); +static ENV_LOCK: Mutex<()> = Mutex::new(()); + +pub(super) fn unique_dir() -> PathBuf { + let suffix = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.subsec_nanos()); + + env::temp_dir().join(format!( + "laio-rex-mux-{}-{nanos}-{suffix}", + std::process::id() + )) +} + +pub(super) fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +pub(super) fn env_guard() -> MutexGuard<'static, ()> { + let guard = lock(&ENV_LOCK); + + unsafe { + env::remove_var("REX_SESSION"); + } + + guard +} + +pub(super) fn argv(cmd: &Type) -> (String, Vec) { + let command = match cmd { + Type::Basic(command) | Type::Verbose(command) | Type::Forget(command) => command, + }; + + ( + command.get_program().to_string_lossy().into_owned(), + command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(), + ) +} + +pub(super) fn rex_args(cmd: &Type) -> Option> { + let (program, args) = argv(cmd); + + (program == "rex").then_some(args) +} + +pub(super) fn api_payload(cmd: &Type, method: &str) -> Option { + let args = rex_args(cmd)?; + + if args.len() != 4 || args[0] != "api" || args[1] != "call" || args[2] != method { + return None; + } + + serde_json::from_str(&args[3]).ok() +} + +pub(super) fn expected(args: &[&str]) -> Vec { + args.iter().map(|arg| arg.to_string()).collect() +} + +pub(super) fn session_of(yaml: &str) -> TestResult { + Ok(noyalib::compat::serde_yaml::from_str(yaml)?) +} + +pub(super) fn record(rex_session_id: &str, laio_name: &str) -> RexSessionRecord { + RexSessionRecord { + rex_session_id: rex_session_id.to_string(), + rex_label: format!("laio-{laio_name}"), + laio_name: laio_name.to_string(), + config_path: format!("/tmp/{laio_name}.yaml"), + variables: format!("session_name={laio_name}&path=%2Ftmp"), + created_at: 1_700_000_000, + } +} + +pub(super) struct Harness { + cmd_unit: MockCmdUnitMock, + cmd_string: MockCmdStringMock, + store_dir: PathBuf, +} + +impl Harness { + pub(super) fn new() -> Self { + Self { + cmd_unit: MockCmdUnitMock::new(), + cmd_string: MockCmdStringMock::new(), + store_dir: unique_dir(), + } + } + + pub(super) fn build(self) -> Rex { + Rex::new_with_parts( + RunnerMock { + cmd_unit: self.cmd_unit, + cmd_string: self.cmd_string, + cmd_bool: MockCmdBoolMock::new(), + }, + self.store_dir, + ) + } + + pub(super) fn store(&self) -> RexSessionStore { + RexSessionStore::new(self.store_dir.clone()) + } + + pub(super) fn store_dir(&self) -> &Path { + &self.store_dir + } + + pub(super) fn seed(&self, record: &RexSessionRecord) -> TestResult { + self.store().write_record(record)?; + Ok(()) + } + + pub(super) fn resolve(mut self, label: &str, status: &str, rex_session_id: &str) -> Self { + let payload = json!({"kinds": ["session"], "queries": [label]}); + let output = if status == "resolved" { + json!({ + "results": [{ + "query": label, + "status": status, + "target": { + "kind": "session", + "label": label, + "session_id": rex_session_id + } + }] + }) + } else { + json!({ + "results": [{ "query": label, "status": status, "candidates": [] }] + }) + } + .to_string(); + + self.cmd_string + .expect_run() + .times(1) + .withf(move |cmd| { + api_payload(cmd, "target.resolve").is_some_and(|actual| actual == payload) + }) + .returning(move |_| Ok(output.clone())); + + self + } + + pub(super) fn resolve_failing(mut self, label: &str, detail: &str) -> Self { + let payload = json!({"kinds": ["session"], "queries": [label]}); + let detail = detail.to_string(); + + self.cmd_string + .expect_run() + .times(1) + .withf(move |cmd| { + api_payload(cmd, "target.resolve").is_some_and(|actual| actual == payload) + }) + .returning(move |_| Err(miette::miette!(detail.clone()))); + + self + } + + pub(super) fn create(mut self, label: &str, output: &str, windows: usize) -> Self { + let label = label.to_string(); + let output = output.to_string(); + + self.cmd_string + .expect_run() + .times(1) + .withf(|cmd| api_payload(cmd, "session.create").is_some()) + .returning(move |cmd| { + let payload = api_payload(cmd, "session.create").unwrap_or(Value::Null); + + assert_eq!(payload["label"].as_str(), Some(label.as_str())); + assert_eq!( + payload["initial_windows"].as_array().map(Vec::len), + Some(windows) + ); + + Ok(output.clone()) + }); + + self + } + + pub(super) fn create_failing(mut self, detail: &str) -> Self { + let detail = detail.to_string(); + + self.cmd_string + .expect_run() + .times(1) + .withf(|cmd| api_payload(cmd, "session.create").is_some()) + .returning(move |_| Err(miette::miette!(detail.clone()))); + + self + } + + pub(super) fn json_args(mut self, args: &[&str], output: &str) -> Self { + let expected = expected(args); + let output = output.to_string(); + + self.cmd_string + .expect_run() + .times(1) + .withf(move |cmd| rex_args(cmd).is_some_and(|actual| actual == expected)) + .returning(move |_| Ok(output.clone())); + + self + } + + pub(super) fn json_recording( + mut self, + method: &'static str, + payload: Value, + output: &str, + log: Log, + label: &str, + ) -> Self { + let output = output.to_string(); + let label = label.to_string(); + + self.cmd_string + .expect_run() + .times(1) + .withf(move |cmd| api_payload(cmd, method).is_some_and(|actual| actual == payload)) + .returning(move |_| { + lock(&log).push(label.clone()); + Ok(output.clone()) + }); + + self + } + + pub(super) fn hook_recording(mut self, line: &str, log: Log, label: &str) -> Self { + let line = line.to_string(); + let label = label.to_string(); + + self.cmd_string + .expect_run() + .times(1) + .withf(move |cmd| matches!(cmd, Type::Verbose(_)) && cmd.to_string() == line) + .returning(move |_| { + lock(&log).push(label.clone()); + Ok(String::new()) + }); + + self + } + + pub(super) fn unit(mut self, args: &[&str]) -> Self { + let expected = expected(args); + + self.cmd_unit + .expect_run() + .times(1) + .withf(move |cmd| rex_args(cmd).is_some_and(|actual| actual == expected)) + .returning(|_| Ok(())); + + self + } + + pub(super) fn unit_failing(mut self, args: &[&str], detail: &str) -> Self { + let expected = expected(args); + let detail = detail.to_string(); + + self.cmd_unit + .expect_run() + .times(1) + .withf(move |cmd| rex_args(cmd).is_some_and(|actual| actual == expected)) + .returning(move |_| Err(miette::miette!(detail.clone()))); + + self + } + + pub(super) fn unit_recording(mut self, args: &[&str], log: Log, label: &str) -> Self { + let expected = expected(args); + let label = label.to_string(); + + self.cmd_unit + .expect_run() + .times(1) + .withf(move |cmd| rex_args(cmd).is_some_and(|actual| actual == expected)) + .returning(move |_| { + lock(&log).push(label.clone()); + Ok(()) + }); + + self + } + + pub(super) fn unit_asserting( + mut self, + args: &[&str], + check: Arc, + ) -> Self { + let expected = expected(args); + + self.cmd_unit + .expect_run() + .times(1) + .withf(move |cmd| rex_args(cmd).is_some_and(|actual| actual == expected)) + .returning(move |_| { + check(); + Ok(()) + }); + + self + } + + pub(super) fn unit_at(mut self, args: &[&str], slot: Arc>>) -> Self { + let expected = expected(args); + + self.cmd_unit + .expect_run() + .times(1) + .withf(move |cmd| rex_args(cmd).is_some_and(|actual| actual == expected)) + .returning(move |_| { + *lock(&slot) = Some(Instant::now()); + Ok(()) + }); + + self + } +} diff --git a/test/muxer/rex/mux_test/session.rs b/test/muxer/rex/mux_test/session.rs new file mode 100644 index 00000000..447ab96a --- /dev/null +++ b/test/muxer/rex/mux_test/session.rs @@ -0,0 +1,101 @@ +use crate::common::muxer::Multiplexer; +use crate::common::session_info::SessionStatus; + +use super::mux_test::*; + +const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"laio-work"},{"session_id":"session:2","label":"laio-extra"},{"session_id":"session:3","label":"other"}]}"#; + +#[test] +fn get_session_config_path_returns_the_recorded_path() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + let rex = harness.build(); + + assert_eq!( + rex.get_session_config_path("work")?, + Some("/tmp/work.yaml".to_string()) + ); + assert_eq!(rex.get_session_config_path("missing")?, None); + Ok(()) +} + +#[test] +fn get_session_variables_returns_the_decoded_variables() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + let rex = harness.build(); + + assert_eq!( + rex.get_session_variables("work")?, + Some(vec![ + "session_name=work".to_string(), + "path=/tmp".to_string() + ]) + ); + assert_eq!(rex.get_session_variables("missing")?, None); + Ok(()) +} + +#[test] +fn get_session_variables_returns_none_for_undecodable_variables() -> TestResult { + let harness = Harness::new(); + let mut broken = record("session:1", "work"); + broken.variables = "not-a-pair".to_string(); + harness.seed(&broken)?; + + assert_eq!(harness.build().get_session_variables("work")?, None); + Ok(()) +} + +#[test] +fn list_sessions_prunes_dead_records_and_marks_unrecorded_labels_inactive() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + harness.seed(&record("session:9", "stale"))?; + let store = harness.store(); + + let rex = harness + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .json_args(&["client", "ls", "--json"], r#"{"clients":[]}"#) + .build(); + + let sessions = rex.list_sessions()?; + let rows: Vec<(&str, SessionStatus)> = sessions + .iter() + .map(|info| (info.name.as_str(), info.status)) + .collect(); + + assert_eq!( + rows, + [ + ("work", SessionStatus::Active), + ("extra", SessionStatus::Inactive) + ] + ); + assert!( + store.read_by_session("session:9")?.is_none(), + "the stale record file must be deleted" + ); + Ok(()) +} + +#[test] +fn list_sessions_reports_a_client_held_session_as_attached() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let clients = r#"{"clients":[{"client_id":"client:app","info":{"kind":"app"},"session_ids":["session:1"]}]}"#; + + let rex = harness + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .json_args(&["client", "ls", "--json"], clients) + .build(); + + let sessions = rex.list_sessions()?; + + assert_eq!( + sessions.first().map(|info| info.status), + Some(SessionStatus::Attached) + ); + Ok(()) +} diff --git a/test/muxer/rex/mux_test/start.rs b/test/muxer/rex/mux_test/start.rs new file mode 100644 index 00000000..eeab75b2 --- /dev/null +++ b/test/muxer/rex/mux_test/start.rs @@ -0,0 +1,371 @@ +use std::fs; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use serde_json::json; + +use crate::common::muxer::Multiplexer; + +use super::mux_test::*; + +const MULTI_WINDOW: &str = " +name: work +path: /tmp +windows: + - name: main + panes: + - path: . + commands: + - command: echo + args: + - one + - name: logs +"; + +const MULTI_CREATE: &str = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2},{"window_id":"window:2","block_ids":["block:2"],"revision":3}]}"#; + +#[test] +fn start_creates_one_session_with_the_laio_label_and_records_it_before_sending() -> TestResult { + let harness = Harness::new(); + let check_dir = harness.store_dir().to_path_buf(); + let check = Arc::new(move || { + assert!( + check_dir.join("1.json").is_file(), + "the sidecar record must exist before the first send" + ); + }); + + let store = harness.store(); + let rex = harness + .resolve("laio-work", "not_found", "") + .create("laio-work", MULTI_CREATE, 2) + .unit_asserting( + &[ + "send", + "-s", + "session:1", + "-b", + "block:1", + "--", + "echo one\n", + ], + check, + ) + .build(); + + rex.start( + &session_of(MULTI_WINDOW)?, + &[("LAIO_CONFIG", "/tmp/work.yaml"), ("LAIO_VARS", "a=b")], + true, + false, + )?; + + let record = store + .read_by_name("work")? + .ok_or("start should write the sidecar record")?; + + assert_eq!(record.rex_session_id, "session:1"); + assert_eq!(record.rex_label, "laio-work"); + assert_eq!(record.config_path, "/tmp/work.yaml"); + assert_eq!(record.variables, "a=b"); + Ok(()) +} + +#[test] +fn start_returns_ok_without_creating_when_the_session_already_exists() -> TestResult { + let rex = Harness::new() + .resolve("laio-work", "resolved", "session:1") + .build(); + + Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, false)?) +} + +#[test] +fn start_sends_one_batch_per_leaf_with_a_trailing_newline() -> TestResult { + let session = session_of( + " +name: work +path: /tmp +windows: + - name: main + panes: + - commands: + - command: echo + args: + - one + - commands: + - command: echo + args: + - two + - command: ls +", + )?; + + let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2"],"revision":2}]}"#; + + let rex = Harness::new() + .resolve("laio-work", "not_found", "") + .create("laio-work", create, 1) + .unit(&[ + "send", + "-s", + "session:1", + "-b", + "block:1", + "--", + "echo one\n", + ]) + .unit(&[ + "send", + "-s", + "session:1", + "-b", + "block:2", + "--", + "echo two\nls\n", + ]) + .build(); + + Ok(rex.start(&session, &[], true, false)?) +} + +#[test] +fn start_waits_for_the_pane_command_delay_before_sending() -> TestResult { + let session = session_of( + " +name: work +path: /tmp +pane_cmd_delay: 40 +windows: + - name: main + panes: + - commands: + - command: ls +", + )?; + + let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2}]}"#; + let sent_at: Arc>> = Arc::new(Mutex::new(None)); + + let rex = Harness::new() + .resolve("laio-work", "not_found", "") + .create("laio-work", create, 1) + .unit_at( + &["send", "-s", "session:1", "-b", "block:1", "--", "ls\n"], + Arc::clone(&sent_at), + ) + .build(); + + let started = Instant::now(); + rex.start(&session, &[], true, false)?; + + let sent_at = lock(&sent_at).ok_or("the leaf commands should be sent")?; + + assert!( + sent_at.duration_since(started) >= Duration::from_millis(40), + "the send must wait for pane_cmd_delay" + ); + Ok(()) +} + +#[test] +fn start_returns_err_without_a_record_when_session_create_fails() -> TestResult { + let harness = Harness::new(); + let store = harness.store(); + + let rex = harness + .resolve("laio-work", "not_found", "") + .create_failing("rex session_create failed: bad_request") + .build(); + + let result = rex.start(&session_of(MULTI_WINDOW)?, &[], true, false); + + assert!(result.is_err()); + assert!(store.list()?.is_empty()); + Ok(()) +} + +#[test] +fn start_returns_err_when_target_resolve_fails() -> TestResult { + let rex = Harness::new() + .resolve_failing("laio-work", "rex target_resolve failed: not_found") + .build(); + + let result = rex.start(&session_of(MULTI_WINDOW)?, &[], true, true); + + assert!(result.is_err()); + Ok(()) +} + +#[test] +fn start_continues_when_one_send_fails() -> TestResult { + let session = session_of( + " +name: work +path: /tmp +windows: + - name: main + panes: + - commands: + - command: echo + args: + - one + - commands: + - command: ls +", + )?; + + let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2"],"revision":2}]}"#; + + let rex = Harness::new() + .resolve("laio-work", "not_found", "") + .create("laio-work", create, 1) + .unit_failing( + &[ + "send", + "-s", + "session:1", + "-b", + "block:1", + "--", + "echo one\n", + ], + "stream response failed: block target block:1 not found", + ) + .unit(&["send", "-s", "session:1", "-b", "block:2", "--", "ls\n"]) + .build(); + + Ok(rex.start(&session, &[], true, false)?) +} + +#[test] +fn start_continues_when_session_select_fails() -> TestResult { + let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2}]}"#; + + let rex = Harness::new() + .resolve("laio-work", "not_found", "") + .create("laio-work", create, 2) + .unit(&[ + "send", + "-s", + "session:1", + "-b", + "block:1", + "--", + "echo one\n", + ]) + .unit_failing( + &["do", "session.select", "session_id=session:1"], + "Rex.app is not accepting actions. Turn on Remote Control in its Settings under Rex Server.", + ) + .build(); + + Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], false, false)?) +} + +#[test] +fn start_skips_the_hooks_and_the_sends_when_skip_cmds_is_set() -> TestResult { + let rex = Harness::new() + .resolve("laio-work", "not_found", "") + .create("laio-work", MULTI_CREATE, 2) + .build(); + + Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, true)?) +} + +#[test] +fn start_focuses_the_block_before_zooming_it() -> TestResult { + let session = session_of( + " +name: work +path: /tmp +windows: + - name: main + panes: + - zoom: true + - focus: true +", + )?; + + let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2"],"revision":2}]}"#; + let log: Log = Arc::new(Mutex::new(Vec::new())); + + let rex = Harness::new() + .resolve("laio-work", "not_found", "") + .create("laio-work", create, 1) + .json_recording( + "session.focus_block", + json!({"session_id": "session:1", "block_id": "block:2"}), + r#"{"revision":4}"#, + Arc::clone(&log), + "focus_block", + ) + .unit_recording( + &["zoom", "-s", "session:1", "block:1", "--on"], + Arc::clone(&log), + "zoom", + ) + .build(); + + rex.start(&session, &[], true, true)?; + + assert_eq!(lock(&log).as_slice(), ["focus_block", "zoom"]); + Ok(()) +} + +#[test] +fn start_focuses_the_window_that_asks_for_it() -> TestResult { + let session = session_of( + " +name: work +path: /tmp +windows: + - name: main + - name: logs + focus: true +", + )?; + + let rex = Harness::new() + .resolve("laio-work", "not_found", "") + .create("laio-work", MULTI_CREATE, 2) + .json_recording( + "session.focus_window", + json!({"session_id": "session:1", "window_id": "window:2"}), + r#"{"revision":4}"#, + Arc::new(Mutex::new(Vec::new())), + "focus_window", + ) + .build(); + + Ok(rex.start(&session, &[], true, true)?) +} + +#[test] +fn start_rejects_a_name_outside_the_laio_charset() -> TestResult { + let rex = Harness::new().build(); + + let result = rex.start( + &session_of("\nname: bad/name\npath: /tmp\nwindows:\n - name: main\n")?, + &[], + true, + true, + ); + + assert!(result.is_err()); + Ok(()) +} + +#[test] +fn start_continues_when_the_record_cannot_be_written() -> TestResult { + let harness = Harness::new(); + let blocked = harness.store_dir().to_path_buf(); + fs::write(&blocked, "not a directory")?; + + let rex = harness + .resolve("laio-work", "not_found", "") + .create("laio-work", MULTI_CREATE, 2) + .build(); + + Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, true)?) +} diff --git a/test/muxer/rex/mux_test/stop.rs b/test/muxer/rex/mux_test/stop.rs new file mode 100644 index 00000000..b481c086 --- /dev/null +++ b/test/muxer/rex/mux_test/stop.rs @@ -0,0 +1,326 @@ +use std::env; +use std::fs; +use std::sync::{Arc, Mutex}; + +use crate::common::muxer::Multiplexer; + +use super::mux_test::*; + +const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"laio-work"},{"session_id":"session:2","label":"laio-other"},{"session_id":"session:3","label":"not-laio"}]}"#; + +fn set_current_session(value: &str) { + unsafe { + env::set_var("REX_SESSION", value); + } +} + +#[test] +fn stop_all_kills_and_deletes_every_laio_session_except_the_current_one() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + harness.seed(&record("session:2", "other"))?; + let store = harness.store(); + + let rex = harness + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .unit(&["kill", "session:2"]) + .build(); + set_current_session("session:1"); + + let result = rex.stop(&None, &None, true, true, false); + unsafe { + env::remove_var("REX_SESSION"); + } + + result?; + assert!(store.read_by_session("session:1")?.is_some()); + assert!(store.read_by_session("session:2")?.is_none()); + Ok(()) +} + +#[test] +fn stop_all_kills_a_live_laio_label_without_a_record() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let rex = harness + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .unit(&["kill", "session:1"]) + .unit(&["kill", "session:2"]) + .build(); + + Ok(rex.stop(&None, &None, true, true, false)?) +} + +#[test] +fn stop_other_sweeps_every_other_laio_session() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new() + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .unit(&["kill", "session:1"]) + .unit(&["kill", "session:2"]) + .build(); + set_current_session("session:3"); + + let result = rex.stop(&None, &None, true, false, true); + unsafe { + env::remove_var("REX_SESSION"); + } + + Ok(result?) +} + +#[test] +fn stop_kills_a_recorded_session_by_its_full_id() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + let store = harness.store(); + + let rex = harness.unit(&["kill", "session:1"]).build(); + + rex.stop(&Some("work".to_string()), &None, true, false, false)?; + + assert!(store.read_by_session("session:1")?.is_none()); + Ok(()) +} + +#[test] +fn stop_without_a_name_kills_the_current_rex_session() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + let store = harness.store(); + + let rex = harness.unit(&["kill", "session:1"]).build(); + set_current_session("session:1"); + + let result = rex.stop(&None, &None, true, false, false); + unsafe { + env::remove_var("REX_SESSION"); + } + + result?; + assert!(store.read_by_session("session:1")?.is_none()); + Ok(()) +} + +#[test] +fn stop_without_a_name_keeps_a_foreign_live_session_alive() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new() + .json_args( + &["session", "ls", "--json"], + r#"{"sessions":[{"session_id":"session:7","label":"personal"}]}"#, + ) + .build(); + set_current_session("session:7"); + + let result = rex.stop(&None, &None, false, false, false); + unsafe { + env::remove_var("REX_SESSION"); + } + + result?; + Ok(()) +} + +#[test] +fn stop_without_a_name_kills_a_live_laio_label_without_a_record() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new() + .json_args( + &["session", "ls", "--json"], + r#"{"sessions":[{"session_id":"session:1","label":"laio-work"}]}"#, + ) + .unit(&["kill", "session:1"]) + .build(); + set_current_session("session:1"); + + let result = rex.stop(&None, &None, false, false, false); + unsafe { + env::remove_var("REX_SESSION"); + } + + result?; + Ok(()) +} + +#[test] +fn stop_without_a_name_returns_ok_when_the_current_session_is_gone() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new() + .json_args(&["session", "ls", "--json"], r#"{"sessions":[]}"#) + .build(); + set_current_session("session:9"); + + let result = rex.stop(&None, &None, false, false, false); + unsafe { + env::remove_var("REX_SESSION"); + } + + result?; + Ok(()) +} + +#[test] +fn stop_returns_ok_for_a_name_without_a_record_or_a_live_label() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new().resolve("laio-work", "not_found", "").build(); + + Ok(rex.stop(&Some("work".to_string()), &None, false, false, false)?) +} + +#[test] +fn stop_runs_the_recorded_shutdown_hooks_before_the_kill() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + let config_dir = unique_dir(); + fs::create_dir_all(&config_dir)?; + let config_path = config_dir.join("work.yaml"); + fs::write( + &config_path, + "name: work\npath: /tmp\nshutdown:\n - command: echo\n args:\n - bye\nwindows:\n - name: main\n", + )?; + + let mut seeded = record("session:1", "work"); + seeded.config_path = config_path.to_string_lossy().to_string(); + seeded.variables = String::new(); + harness.seed(&seeded)?; + let store = harness.store(); + + let log: Log = Arc::new(Mutex::new(Vec::new())); + let rex = harness + .hook_recording("echo bye", Arc::clone(&log), "hook") + .unit_recording(&["kill", "session:1"], Arc::clone(&log), "kill") + .build(); + + rex.stop(&Some("work".to_string()), &None, false, false, false)?; + + assert_eq!(lock(&log).as_slice(), ["hook", "kill"]); + assert!(store.read_by_session("session:1")?.is_none()); + Ok(()) +} + +#[test] +fn stop_prefers_the_manager_supplied_session_for_the_hooks() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let log: Log = Arc::new(Mutex::new(Vec::new())); + let rex = harness + .hook_recording("echo supplied", Arc::clone(&log), "hook") + .unit(&["kill", "session:1"]) + .build(); + + let session = session_of( + " +name: work +path: /tmp +shutdown: + - command: echo + args: + - supplied +windows: + - name: main +", + )?; + + rex.stop( + &Some("work".to_string()), + &Some(session), + false, + false, + false, + )?; + + assert_eq!(lock(&log).as_slice(), ["hook"]); + Ok(()) +} + +#[test] +fn stop_skips_the_hooks_when_skip_cmds_is_set() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let rex = harness.unit(&["kill", "session:1"]).build(); + + Ok(rex.stop(&Some("work".to_string()), &None, true, false, false)?) +} + +#[test] +fn stop_kills_the_resolved_label_when_the_record_is_corrupt() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + fs::create_dir_all(harness.store_dir())?; + fs::write(harness.store_dir().join("1.json"), "{ not json")?; + + let rex = harness + .resolve("laio-work", "resolved", "session:9") + .unit(&["kill", "session:9"]) + .build(); + + Ok(rex.stop(&Some("work".to_string()), &None, false, false, false)?) +} + +#[test] +fn stop_rejects_a_name_together_with_stop_all() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new().build(); + + let error = rex + .stop(&Some("work".to_string()), &None, false, true, false) + .err() + .ok_or("mutually exclusive arguments should fail")?; + + assert!(error.to_string().contains("mutually exclusive"), "{error}"); + Ok(()) +} + +#[test] +fn stop_requires_a_session_name_outside_a_rex_session() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new().build(); + + let error = rex + .stop(&None, &None, false, false, false) + .err() + .ok_or("a missing session name should fail")?; + + assert!( + error.to_string().contains("Specify laio session"), + "{error}" + ); + Ok(()) +} + +#[test] +fn stop_other_bails_outside_a_rex_session() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new().build(); + + let error = rex + .stop(&None, &None, false, false, true) + .err() + .ok_or("stop_other outside a rex session should fail")?; + + assert!( + error.to_string().contains("Not inside a rex session"), + "{error}" + ); + Ok(()) +} + +#[test] +fn get_session_reports_the_unsupported_export() -> TestResult { + let rex = Harness::new().build(); + + let error = rex.get_session().err().ok_or("export is unsupported")?; + + assert!(error.to_string().contains("not supported"), "{error}"); + Ok(()) +} diff --git a/test/muxer/rex/mux_test/switch.rs b/test/muxer/rex/mux_test/switch.rs new file mode 100644 index 00000000..8eadf8f6 --- /dev/null +++ b/test/muxer/rex/mux_test/switch.rs @@ -0,0 +1,84 @@ +use crate::common::muxer::Multiplexer; +use crate::muxer::rex::Rex; + +use super::mux_test::*; + +#[test] +fn switch_returns_true_and_skips_attach_when_requested() -> TestResult { + let rex = Harness::new() + .resolve("laio-work", "resolved", "session:1") + .build(); + + assert!(rex.switch("work", true)?); + Ok(()) +} + +#[test] +fn switch_attaches_with_the_full_prefixed_session_id() -> TestResult { + let rex = Harness::new() + .resolve("laio-work", "resolved", "session:1") + .unit(&["do", "session.select", "session_id=session:1"]) + .build(); + + assert!(rex.switch("work", false)?); + Ok(()) +} + +#[test] +fn switch_continues_when_the_attach_fails() -> TestResult { + let rex = Harness::new() + .resolve("laio-work", "resolved", "session:1") + .unit_failing( + &["do", "session.select", "session_id=session:1"], + "Rex.app is not accepting actions. Turn on Remote Control in its Settings under Rex Server.", + ) + .build(); + + assert!(rex.switch("work", false)?); + Ok(()) +} + +#[test] +fn switch_rejects_an_ambiguous_target_with_the_label() -> TestResult { + let rex = Harness::new().resolve("laio-work", "ambiguous", "").build(); + + let error = rex + .switch("work", true) + .err() + .ok_or("ambiguity should fail")?; + + assert!(error.to_string().contains("laio-work"), "{error}"); + Ok(()) +} + +#[test] +fn switch_returns_false_when_the_target_is_not_found() -> TestResult { + let rex = Harness::new().resolve("laio-work", "not_found", "").build(); + + assert!(!rex.switch("work", true)?); + Ok(()) +} + +#[test] +fn switch_rejects_names_outside_the_laio_charset() -> TestResult { + let rex = Rex::new(); + + let error = rex.switch("bad/name", true).err().ok_or("invalid name")?; + + assert!(error.to_string().contains("Invalid"), "{error}"); + Ok(()) +} + +#[test] +fn switch_rejects_a_label_over_the_rex_limit() -> TestResult { + let rex = Rex::new(); + let name = "a".repeat(124); + + let error = rex + .switch(&name, true) + .err() + .ok_or("an over-long label should fail")?; + + assert!(error.to_string().contains("128"), "{error}"); + Ok(()) +} From f66e728f67dfa11953847b7180a85e0dff8a5249 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 17:46:57 +0000 Subject: [PATCH 06/16] test(muxer/rex): fix store_test temp-dir pid-collision flake --- test/muxer/rex/store_test.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/test/muxer/rex/store_test.rs b/test/muxer/rex/store_test.rs index d238a99f..32c7204b 100644 --- a/test/muxer/rex/store_test.rs +++ b/test/muxer/rex/store_test.rs @@ -2,6 +2,7 @@ use std::env; use std::fs; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; use crate::common::path::home_dir; use crate::muxer::rex::store::{ @@ -14,8 +15,14 @@ static NEXT_DIR: AtomicU64 = AtomicU64::new(0); fn unique_dir() -> PathBuf { let suffix = NEXT_DIR.fetch_add(1, Ordering::Relaxed); - - env::temp_dir().join(format!("laio-rex-store-{}-{suffix}", std::process::id())) + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.subsec_nanos()); + + env::temp_dir().join(format!( + "laio-rex-store-{}-{nanos}-{suffix}", + std::process::id() + )) } fn record(rex_session_id: &str, laio_name: &str) -> RexSessionRecord { From 2dd11eb2d81cd6c34e0c079d732db64a76479ccd Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 17:57:04 +0000 Subject: [PATCH 07/16] feat(muxer/rex): implement get_session export --- src/muxer/rex/export.rs | 369 +++++++++++++++++++++++++++++ src/muxer/rex/mod.rs | 10 + src/muxer/rex/mux.rs | 35 ++- test/muxer/rex/export_test.rs | 355 +++++++++++++++++++++++++++ test/muxer/rex/mux_test/stop.rs | 10 - test/muxer/rex/session_get_test.rs | 156 ++++++++++++ 6 files changed, 921 insertions(+), 14 deletions(-) create mode 100644 src/muxer/rex/export.rs create mode 100644 test/muxer/rex/export_test.rs create mode 100644 test/muxer/rex/session_get_test.rs diff --git a/src/muxer/rex/export.rs b/src/muxer/rex/export.rs new file mode 100644 index 00000000..a2199585 --- /dev/null +++ b/src/muxer/rex/export.rs @@ -0,0 +1,369 @@ +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use miette::{Result, bail, miette}; + +use crate::common::config::util::gcd_vec; +use crate::common::config::{FlexDirection, Pane, Session, Window}; +use crate::common::path::relative_path; + +use super::model::{LayerView, SessionView, ViewNode, ViewSplit, WindowView}; +use super::mux::LABEL_PREFIX; + +const TILED_KIND: &str = "tiled"; +const HORIZONTAL: &str = "horizontal"; +const VERTICAL: &str = "vertical"; +const DEFAULT_SPLIT_RATIO: f64 = 0.5; +const FLEX_SCALE: f64 = 100.0; +const FLEX_TOTAL: usize = 100; +const FILE_URL_PREFIX: &str = "file://"; + +pub(crate) fn local_path(pwd: &str) -> &str { + let Some(rest) = pwd.strip_prefix(FILE_URL_PREFIX) else { + return pwd; + }; + + rest.find('/').map_or(pwd, |index| &rest[index..]) +} + +pub(crate) fn tiled_block_ids(view: &SessionView) -> Result> { + let mut block_ids = Vec::new(); + + for window in view.windows.as_deref().unwrap_or_default() { + let Some(layout) = tiled_layer(window).and_then(|layer| layer.layout.as_ref()) else { + continue; + }; + + let mut leaves = Vec::new(); + collect_leaves(layout, 1.0, &mut leaves)?; + block_ids.extend(leaves.into_iter().map(|(block_id, _)| block_id)); + } + + Ok(block_ids) +} + +pub(crate) fn session_from_view( + view: &SessionView, + pwds: &HashMap, + fallback_name: Option<&str>, +) -> Result { + let windows = view.windows.as_deref().unwrap_or_default(); + let leaves: Vec> = windows.iter().map(window_leaves).collect::>()?; + + let session_path = session_path(&leaves, pwds)?; + let active_window_id = view.active_window_id.as_deref(); + + let mut exported = Vec::with_capacity(windows.len()); + for (window, leaves) in windows.iter().zip(&leaves) { + exported.push(window_from_view( + window, + leaves, + &session_path, + pwds, + active_window_id, + )?); + } + + Ok(Session { + name: session_name(view, fallback_name)?, + path: session_path, + startup: Vec::new(), + startup_script: None, + shutdown: Vec::new(), + shutdown_script: None, + env: HashMap::new(), + shell: None, + pane_cmd_delay: None, + windows: exported, + }) +} + +fn window_leaves(window: &WindowView) -> Result> { + let Some(layout) = tiled_layer(window).and_then(|layer| layer.layout.as_ref()) else { + return Ok(Vec::new()); + }; + + let mut leaves = Vec::new(); + collect_leaves(layout, 1.0, &mut leaves)?; + + Ok(leaves) +} + +fn tiled_layer(window: &WindowView) -> Option<&LayerView> { + window + .layers + .as_deref() + .unwrap_or_default() + .iter() + .find(|layer| layer.kind == TILED_KIND) +} + +fn collect_leaves<'a>( + node: &'a ViewNode, + fraction: f64, + leaves: &mut Vec<(&'a str, f64)>, +) -> Result<()> { + if let Some(split) = &node.split { + let ratio = split.ratio.unwrap_or(DEFAULT_SPLIT_RATIO); + + collect_leaves(split_node(split, Side::Before)?, fraction * ratio, leaves)?; + + return collect_leaves( + split_node(split, Side::After)?, + fraction * (1.0 - ratio), + leaves, + ); + } + + leaves.push((node_block_id(node)?, fraction)); + + Ok(()) +} + +fn node_block_id(node: &ViewNode) -> Result<&str> { + node.block_id + .as_deref() + .ok_or_else(|| miette!("rex layout node has neither a block nor a split")) +} + +#[derive(Clone, Copy)] +enum Side { + Before, + After, +} + +fn split_node(split: &ViewSplit, side: Side) -> Result<&ViewNode> { + let (node, name) = match side { + Side::Before => (&split.before, "before"), + Side::After => (&split.after, "after"), + }; + + node.as_ref() + .ok_or_else(|| miette!("rex layout split has no {name} node")) +} + +fn session_path(leaves: &[Vec<(&str, f64)>], pwds: &HashMap) -> Result { + let paths: Vec<&str> = leaves + .iter() + .flatten() + .filter_map(|(block_id, _)| pwds.get(*block_id).map(String::as_str)) + .collect(); + + common_path(&paths) +} + +fn common_path(paths: &[&str]) -> Result { + let mut paths = paths.iter(); + let Some(first) = paths.next() else { + bail!("Cannot determine the session path from the rex block working directories"); + }; + + let mut prefix = PathBuf::from(first); + for path in paths { + while !Path::new(path).starts_with(&prefix) { + if !prefix.pop() { + bail!("Cannot determine the session path from the rex block working directories"); + } + } + } + + let prefix = prefix.to_string_lossy().into_owned(); + if prefix.is_empty() || prefix == "/" { + bail!("Cannot determine the session path from the rex block working directories"); + } + + Ok(prefix) +} + +fn session_name(view: &SessionView, fallback: Option<&str>) -> Result { + if let Some(name) = fallback { + return Ok(name.to_string()); + } + + let label = view + .label + .as_deref() + .ok_or_else(|| miette!("Cannot determine the rex session name"))?; + + log::warn!("No laio record for rex session '{label}'; deriving the name from the label"); + + Ok(label + .strip_prefix(LABEL_PREFIX) + .unwrap_or(label) + .to_string()) +} + +fn window_from_view<'a>( + window: &'a WindowView, + leaves: &'a [(&'a str, f64)], + session_path: &'a str, + pwds: &'a HashMap, + active_window_id: Option<&'a str>, +) -> Result { + let mut flex_direction = FlexDirection::Row; + let mut panes = Vec::new(); + + if let Some(layer) = tiled_layer(window) + && let Some(layout) = &layer.layout + { + let direction = root_direction(layout)?; + let context = ExportContext { + session_path, + pwds, + labels: block_labels(layer), + flexes: flexes(leaves), + focused_block_id: window.focused_block_id.as_deref(), + zoomed_block_id: window.zoomed_block_id.as_deref(), + }; + let group = group_from_node(layout, &direction, &context)?; + + flex_direction = direction; + panes = group.panes; + } + + Ok(Window { + name: window.label.clone().unwrap_or_default(), + path: None, + flex_direction, + panes, + focus: window + .window_id + .as_deref() + .is_some_and(|window_id| Some(window_id) == active_window_id), + }) +} + +fn block_labels(layer: &LayerView) -> HashMap<&str, &str> { + layer + .blocks + .as_deref() + .unwrap_or_default() + .iter() + .filter_map(|block| { + block + .label + .as_deref() + .map(|label| (block.block_id.as_str(), label)) + }) + .collect() +} + +fn flexes<'a>(leaves: &[(&'a str, f64)]) -> HashMap<&'a str, usize> { + let mut weights: Vec = leaves + .iter() + .map(|(_, fraction)| (fraction * FLEX_SCALE).round() as usize) + .collect(); + + let count = weights.len(); + if count > 1 { + let others: usize = weights[..count - 1].iter().sum(); + weights[count - 1] = FLEX_TOTAL.saturating_sub(others); + } + + let gcd = gcd_vec(&weights); + + leaves + .iter() + .zip(weights) + .map(|((block_id, _), weight)| (*block_id, (weight / gcd).max(1))) + .collect() +} + +fn root_direction(node: &ViewNode) -> Result { + match &node.split { + Some(split) => split_direction(&split.direction), + None => Ok(FlexDirection::Row), + } +} + +fn split_direction(direction: &str) -> Result { + match direction { + HORIZONTAL => Ok(FlexDirection::Row), + VERTICAL => Ok(FlexDirection::Column), + _ => Err(miette!("Unknown rex split direction '{direction}'")), + } +} + +struct PaneGroup { + panes: Vec, + flex: usize, +} + +struct ExportContext<'a> { + session_path: &'a str, + pwds: &'a HashMap, + labels: HashMap<&'a str, &'a str>, + flexes: HashMap<&'a str, usize>, + focused_block_id: Option<&'a str>, + zoomed_block_id: Option<&'a str>, +} + +impl ExportContext<'_> { + fn flex(&self, block_id: &str) -> usize { + self.flexes.get(block_id).copied().unwrap_or(1) + } + + fn leaf(&self, block_id: &str) -> Pane { + Pane { + flex_direction: FlexDirection::Row, + flex: self.flex(block_id), + name: self.labels.get(block_id).map(|label| (*label).to_string()), + path: self + .pwds + .get(block_id) + .and_then(|pwd| relative_path(pwd, self.session_path)) + .unwrap_or_else(|| ".".to_string()), + style: None, + commands: Vec::new(), + script: None, + panes: Vec::new(), + zoom: self.zoomed_block_id == Some(block_id), + focus: self.focused_block_id == Some(block_id), + } + } +} + +fn group_from_node<'a>( + node: &'a ViewNode, + direction: &FlexDirection, + context: &ExportContext<'a>, +) -> Result { + let Some(split) = &node.split else { + let block_id = node_block_id(node)?; + + return Ok(PaneGroup { + flex: context.flex(block_id), + panes: vec![context.leaf(block_id)], + }); + }; + + let split_direction = split_direction(&split.direction)?; + + if &split_direction == direction { + let before = group_from_node(split_node(split, Side::Before)?, direction, context)?; + let after = group_from_node(split_node(split, Side::After)?, direction, context)?; + let flex = before.flex + after.flex; + let mut panes = before.panes; + panes.extend(after.panes); + + return Ok(PaneGroup { panes, flex }); + } + + let nested = group_from_node(node, &split_direction, context)?; + + Ok(PaneGroup { + flex: nested.flex, + panes: vec![Pane { + flex_direction: split_direction, + flex: nested.flex, + name: None, + path: ".".to_string(), + style: None, + commands: Vec::new(), + script: None, + panes: nested.panes, + zoom: false, + focus: false, + }], + }) +} diff --git a/src/muxer/rex/mod.rs b/src/muxer/rex/mod.rs index 3276ded8..d4a2c35b 100644 --- a/src/muxer/rex/mod.rs +++ b/src/muxer/rex/mod.rs @@ -1,9 +1,11 @@ pub(crate) mod client; +pub(crate) mod export; pub(crate) mod layout; pub(crate) mod model; pub(crate) mod mux; pub(crate) mod store; +pub(crate) use export::{local_path, session_from_view, tiled_block_ids}; pub(crate) use layout::{LeafPlan, build_create_request}; #[cfg_attr( @@ -46,3 +48,11 @@ mod mux_test_session; #[cfg(test)] #[path = "../../../test/muxer/rex/mux_test/stop.rs"] mod mux_test_stop; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/export_test.rs"] +mod export_test; + +#[cfg(test)] +#[path = "../../../test/muxer/rex/session_get_test.rs"] +mod session_get_test; diff --git a/src/muxer/rex/mux.rs b/src/muxer/rex/mux.rs index ca8ce0c2..b01429e7 100644 --- a/src/muxer/rex/mux.rs +++ b/src/muxer/rex/mux.rs @@ -1,4 +1,4 @@ -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::env; use std::path::PathBuf; use std::sync::Arc; @@ -14,13 +14,15 @@ use crate::common::config::Session; use crate::common::muxer::{Client, Multiplexer}; use crate::common::path::{resolve_symlink, to_absolute_path}; use crate::common::session_info::SessionInfo; -use crate::muxer::rex::{LeafPlan, build_create_request}; +use crate::muxer::rex::{ + LeafPlan, build_create_request, local_path, session_from_view, tiled_block_ids, +}; use super::client::RexClient; use super::model::{ClientListOutput, CreateOutput, ResolveResult}; use super::store::{RexSessionRecord, RexSessionStore, laio_state_dir}; -const LABEL_PREFIX: &str = "laio-"; +pub(super) const LABEL_PREFIX: &str = "laio-"; const MAX_LABEL_LEN: usize = 128; const SESSION_KIND: &str = "session"; const REX_SESSION_ENV: &str = "REX_SESSION"; @@ -507,7 +509,32 @@ impl Multiplexer for Rex { } fn get_session(&self) -> Result { - Err(miette!("Exporting a rex session is not supported yet.")) + let Some(rex_session_id) = current_session() else { + bail!("You do not seem to be inside a rex session."); + }; + + let view = self.client.session_view(&rex_session_id)?; + let mut pwds = HashMap::new(); + + for block_id in tiled_block_ids(&view)? { + match self.client.block_pwd(&rex_session_id, block_id) { + Ok(output) => { + pwds.insert(block_id.to_string(), local_path(&output.pwd).to_string()); + } + Err(error) => { + log::warn!( + "Failed to read the working directory of rex block '{block_id}': {error}" + ); + } + } + } + + let name = self + .store + .read_by_session(&rex_session_id)? + .map(|record| record.laio_name); + + session_from_view(&view, &pwds, name.as_deref()) } } diff --git a/test/muxer/rex/export_test.rs b/test/muxer/rex/export_test.rs new file mode 100644 index 00000000..394b919f --- /dev/null +++ b/test/muxer/rex/export_test.rs @@ -0,0 +1,355 @@ +use std::collections::HashMap; + +use crate::common::config::{FlexDirection, Session}; +use crate::muxer::rex::export::{local_path, session_from_view}; +use crate::muxer::rex::model::{BlockRef, LayerView, SessionView, ViewNode, ViewSplit, WindowView}; + +type TestResult = core::result::Result>; + +const TILED: &str = "tiled"; +const FLOATING: &str = "floating"; + +fn leaf(block_id: &str) -> ViewNode { + ViewNode { + rect: Vec::new(), + block_id: Some(block_id.to_string()), + split: None, + } +} + +fn split(direction: &str, ratio: f64, before: ViewNode, after: ViewNode) -> ViewNode { + ViewNode { + rect: Vec::new(), + block_id: None, + split: Some(Box::new(ViewSplit { + split_id: None, + direction: direction.to_string(), + ratio: Some(ratio), + before: Some(before), + after: Some(after), + })), + } +} + +fn layer(kind: &str, layout: ViewNode) -> LayerView { + LayerView { + layer_id: None, + kind: kind.to_string(), + bounds: Vec::new(), + layout: Some(layout), + blocks: None, + } +} + +fn tiled(layout: ViewNode, labels: &[(&str, &str)]) -> LayerView { + LayerView { + layer_id: None, + kind: TILED.to_string(), + bounds: Vec::new(), + layout: Some(layout), + blocks: Some( + labels + .iter() + .map(|(block_id, label)| BlockRef { + block_id: (*block_id).to_string(), + creator_name: None, + flavor: None, + label: Some((*label).to_string()), + owner: None, + }) + .collect(), + ), + } +} + +fn window( + window_id: &str, + label: &str, + focused: Option<&str>, + zoomed: Option<&str>, + layers: Vec, +) -> WindowView { + WindowView { + window_id: Some(window_id.to_string()), + label: Some(label.to_string()), + focused_block_id: focused.map(str::to_string), + zoomed_block_id: zoomed.map(str::to_string), + layers: Some(layers), + } +} + +fn view(label: &str, active: &str, windows: Vec) -> SessionView { + SessionView { + revision: 1, + session_id: Some("session:1".to_string()), + label: Some(label.to_string()), + active_window_id: Some(active.to_string()), + windows: Some(windows), + } +} + +fn pwds(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(block_id, pwd)| ((*block_id).to_string(), (*pwd).to_string())) + .collect() +} + +fn flexes(session: &Session, window_index: usize) -> Vec { + session.windows[window_index] + .panes + .iter() + .map(|pane| pane.flex) + .collect() +} + +#[test] +fn horizontal_ratios_round_trip_to_the_exact_flex_weights() -> TestResult { + let layout = split( + "horizontal", + 0.5, + leaf("b1"), + split("horizontal", 0.5, leaf("b2"), leaf("b3")), + ); + let view = view( + "laio-other", + "w1", + vec![window( + "w1", + "main", + None, + None, + vec![tiled(layout, &[("b1", "editor"), ("b3", "logs")])], + )], + ); + + let session = session_from_view( + &view, + &pwds(&[ + ("b1", "/opt/project/a"), + ("b2", "/opt/project/b"), + ("b3", "/opt/project/c"), + ]), + Some("work"), + )?; + + let window = &session.windows[0]; + assert_eq!(window.flex_direction, FlexDirection::Row); + assert_eq!(flexes(&session, 0), [2, 1, 1]); + assert_eq!(window.panes[0].name.as_deref(), Some("editor")); + assert_eq!(window.panes[1].name, None); + assert_eq!(window.panes[2].name.as_deref(), Some("logs")); + assert_eq!(session.name, "work"); + Ok(()) +} + +#[test] +fn a_vertical_root_split_sets_the_window_direction_to_column() -> TestResult { + let layout = split("vertical", 0.5, leaf("b1"), leaf("b2")); + let view = view( + "laio-work", + "w1", + vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], + ); + + let session = session_from_view( + &view, + &pwds(&[("b1", "/opt/project/a"), ("b2", "/opt/project/b")]), + Some("work"), + )?; + + assert_eq!(session.windows[0].flex_direction, FlexDirection::Column); + assert_eq!(flexes(&session, 0), [1, 1]); + Ok(()) +} + +#[test] +fn a_vertical_split_inside_a_horizontal_window_becomes_a_column_container() -> TestResult { + let layout = split( + "horizontal", + 0.5, + leaf("b1"), + split("vertical", 0.5, leaf("b2"), leaf("b3")), + ); + let view = view( + "laio-work", + "w1", + vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], + ); + + let session = session_from_view( + &view, + &pwds(&[ + ("b1", "/opt/project/a"), + ("b2", "/opt/project/b"), + ("b3", "/opt/project/c"), + ]), + Some("work"), + )?; + + let window = &session.windows[0]; + assert_eq!(window.flex_direction, FlexDirection::Row); + assert_eq!(window.panes.len(), 2); + assert_eq!(window.panes[0].flex, 2); + assert_eq!(window.panes[1].flex, 2); + assert_eq!(window.panes[1].flex_direction, FlexDirection::Column); + assert_eq!(window.panes[1].panes.len(), 2); + assert_eq!(window.panes[1].panes[0].path, "b"); + Ok(()) +} + +#[test] +fn pane_paths_are_relative_to_the_longest_common_prefix() -> TestResult { + assert_eq!(local_path("file://host/Users/x"), "/Users/x"); + assert_eq!(local_path("file:///Users/x"), "/Users/x"); + assert_eq!(local_path("/Users/x"), "/Users/x"); + + let layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); + let view = view( + "laio-work", + "w1", + vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], + ); + let x = local_path("file://host/Users/x"); + let y = local_path("file://host/Users/y"); + + let session = session_from_view(&view, &pwds(&[("b1", x), ("b2", y)]), Some("work"))?; + + assert_eq!(session.path, "/Users"); + assert_eq!(session.windows[0].panes[0].path, "x"); + assert_eq!(session.windows[0].panes[1].path, "y"); + Ok(()) +} + +#[test] +fn focused_and_zoomed_blocks_mark_their_panes() -> TestResult { + let layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); + let view = view( + "laio-work", + "w1", + vec![window( + "w1", + "main", + Some("b2"), + Some("b1"), + vec![tiled(layout, &[])], + )], + ); + + let session = session_from_view( + &view, + &pwds(&[("b1", "/opt/project/a"), ("b2", "/opt/project/b")]), + Some("work"), + )?; + + let panes = &session.windows[0].panes; + assert!(panes[0].zoom); + assert!(!panes[0].focus); + assert!(!panes[1].zoom); + assert!(panes[1].focus); + Ok(()) +} + +#[test] +fn only_the_active_window_is_focused() -> TestResult { + let layout = || split("horizontal", 0.5, leaf("b1"), leaf("b2")); + let view = view( + "laio-work", + "w2", + vec![ + window("w1", "first", None, None, vec![tiled(layout(), &[])]), + window("w2", "second", None, None, vec![tiled(layout(), &[])]), + ], + ); + + let session = session_from_view( + &view, + &pwds(&[("b1", "/opt/project/a"), ("b2", "/opt/project/b")]), + Some("work"), + )?; + + assert_eq!(session.windows.len(), 2); + assert!(!session.windows[0].focus); + assert!(session.windows[1].focus); + Ok(()) +} + +#[test] +fn floating_layers_are_ignored() -> TestResult { + let tiled_layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); + let view = view( + "laio-work", + "w1", + vec![window( + "w1", + "main", + None, + None, + vec![ + tiled(tiled_layout, &[]), + layer(FLOATING, leaf("floating-block")), + ], + )], + ); + + let session = session_from_view( + &view, + &pwds(&[ + ("b1", "/opt/project/a"), + ("b2", "/opt/project/b"), + ("floating-block", "/elsewhere"), + ]), + Some("work"), + )?; + + assert_eq!(session.windows[0].panes.len(), 2); + assert_eq!(session.path, "/opt/project"); + Ok(()) +} + +#[test] +fn a_missing_record_falls_back_to_the_label_without_the_laio_prefix() -> TestResult { + let layout = leaf("b1"); + let view = view( + "laio-work", + "w1", + vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], + ); + + let session = session_from_view(&view, &pwds(&[("b1", "/opt/project")]), None)?; + + assert_eq!(session.name, "work"); + assert_eq!(session.path, "/opt/project"); + assert_eq!(session.windows[0].panes[0].path, "."); + Ok(()) +} + +#[test] +fn the_export_carries_no_unrecoverable_settings() -> TestResult { + let layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); + let view = view( + "laio-work", + "w1", + vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], + ); + + let session = session_from_view( + &view, + &pwds(&[("b1", "/opt/project/a"), ("b2", "/opt/project/b")]), + Some("work"), + )?; + + assert!(session.startup.is_empty()); + assert!(session.startup_script.is_none()); + assert!(session.shutdown.is_empty()); + assert!(session.shutdown_script.is_none()); + assert!(session.env.is_empty()); + assert!(session.shell.is_none()); + assert!(session.pane_cmd_delay.is_none()); + for pane in &session.windows[0].panes { + assert!(pane.commands.is_empty()); + assert!(pane.style.is_none()); + assert!(pane.script.is_none()); + } + Ok(()) +} diff --git a/test/muxer/rex/mux_test/stop.rs b/test/muxer/rex/mux_test/stop.rs index b481c086..d0a81741 100644 --- a/test/muxer/rex/mux_test/stop.rs +++ b/test/muxer/rex/mux_test/stop.rs @@ -314,13 +314,3 @@ fn stop_other_bails_outside_a_rex_session() -> TestResult { ); Ok(()) } - -#[test] -fn get_session_reports_the_unsupported_export() -> TestResult { - let rex = Harness::new().build(); - - let error = rex.get_session().err().ok_or("export is unsupported")?; - - assert!(error.to_string().contains("not supported"), "{error}"); - Ok(()) -} diff --git a/test/muxer/rex/session_get_test.rs b/test/muxer/rex/session_get_test.rs new file mode 100644 index 00000000..fb9fbee7 --- /dev/null +++ b/test/muxer/rex/session_get_test.rs @@ -0,0 +1,156 @@ +use std::env; +use std::ffi::OsString; +use std::sync::MutexGuard; + +use crate::common::config::FlexDirection; +use crate::common::muxer::Multiplexer; + +use super::mux_test::*; + +const VIEW: &str = r#"{ + "revision": 1, + "session_id": "session:1", + "label": "laio-work", + "active_window_id": "w1", + "windows": [ + { + "window_id": "w1", + "label": "main", + "focused_block_id": "block:b2", + "zoomed_block_id": "block:b1", + "layers": [ + { + "layer_id": "layer:tiled", + "kind": "tiled", + "bounds": [0.0, 0.0, 1.0, 1.0], + "layout": { + "rect": [0.0, 0.0, 1.0, 1.0], + "split": { + "direction": "horizontal", + "ratio": 0.5, + "before": {"rect": [0.0, 0.0, 0.5, 1.0], "block_id": "block:b1"}, + "after": {"rect": [0.5, 0.0, 0.5, 1.0], "block_id": "block:b2"} + } + }, + "blocks": [ + {"block_id": "block:b1", "label": "editor"}, + {"block_id": "block:b2"} + ] + } + ] + } + ] +}"#; + +struct RexSession { + _guard: MutexGuard<'static, ()>, + previous: Option, +} + +impl RexSession { + fn new(value: &str) -> Self { + let previous = env::var_os("REX_SESSION"); + let guard = env_guard(); + + unsafe { + env::set_var("REX_SESSION", value); + } + + Self { + _guard: guard, + previous, + } + } +} + +impl Drop for RexSession { + fn drop(&mut self) { + unsafe { + match self.previous.take() { + Some(value) => env::set_var("REX_SESSION", value), + None => env::remove_var("REX_SESSION"), + } + } + } +} + +fn view_harness() -> Harness { + Harness::new() + .json_args( + &[ + "api", + "call", + "session.view", + r#"{"session_id":"session:1"}"#, + ], + VIEW, + ) + .json_args( + &["block", "call", "-s", "session:1", "-b", "block:b1", "pwd"], + r#"{"pwd":"file://host/opt/project/a"}"#, + ) + .json_args( + &["block", "call", "-s", "session:1", "-b", "block:b2", "pwd"], + r#"{"pwd":"file://host/opt/project/b"}"#, + ) +} + +#[test] +fn get_session_bails_outside_a_rex_session() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new().build(); + + let error = rex.get_session().err().ok_or("missing REX_SESSION")?; + + assert_eq!( + error.to_string(), + "You do not seem to be inside a rex session." + ); + Ok(()) +} + +#[test] +fn get_session_exports_the_current_rex_session() -> TestResult { + let _session = RexSession::new("session:1"); + let harness = view_harness(); + harness.seed(&record("session:1", "stored"))?; + let rex = harness.build(); + + let session = rex.get_session()?; + + assert_eq!(session.name, "stored"); + assert_eq!(session.path, "/opt/project"); + assert_eq!(session.windows.len(), 1); + + let window = &session.windows[0]; + assert_eq!(window.name, "main"); + assert_eq!(window.flex_direction, FlexDirection::Row); + assert!(window.focus); + assert_eq!(window.panes.len(), 2); + + assert_eq!(window.panes[0].flex, 1); + assert_eq!(window.panes[0].name.as_deref(), Some("editor")); + assert_eq!(window.panes[0].path, "a"); + assert!(window.panes[0].zoom); + assert!(!window.panes[0].focus); + + assert_eq!(window.panes[1].flex, 1); + assert_eq!(window.panes[1].name, None); + assert_eq!(window.panes[1].path, "b"); + assert!(!window.panes[1].zoom); + assert!(window.panes[1].focus); + + assert!(window.panes[1].commands.is_empty()); + Ok(()) +} + +#[test] +fn get_session_derives_the_name_from_the_label_without_a_record() -> TestResult { + let _session = RexSession::new("session:1"); + let rex = view_harness().build(); + + let session = rex.get_session()?; + + assert_eq!(session.name, "work"); + Ok(()) +} From 937eb1daf7fd31cfa656e4196c26edfc1e3bbba2 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 18:05:31 +0000 Subject: [PATCH 08/16] feat(muxer/rex): wire muxer enum, factory, and docs --- AGENTS.md | 12 +++++++ README.md | 21 ++++++++---- docs/content/_index.md | 8 +++-- docs/content/docs/configuration/lifecycle.md | 8 +++-- .../docs/configuration/yaml-reference.md | 21 ++++++++++-- .../docs/getting-started/quick-start.md | 4 ++- docs/content/docs/reference/cli-commands.md | 34 ++++++++++++++----- .../content/docs/workflow/managing-configs.md | 6 +++- docs/content/docs/workflow/session-export.md | 14 +++++--- src/app/cli/command_line.rs | 6 ++-- src/muxer/mod.rs | 11 +++--- src/muxer/rex/mod.rs | 7 ---- test/muxer/test.rs | 30 +++++++++++++++- 13 files changed, 137 insertions(+), 45 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cec22045..a973c9a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,6 +99,18 @@ src/ test/ responses.rs socket.rs switch_test.rs + rex/ rex/ + mod.rs client_test.rs + export_test.rs + layout_test.rs + mux_test.rs + mux_test/ + session.rs + start.rs + stop.rs + switch.rs + session_get_test.rs + store_test.rs tmux/ tmux/ mod.rs test/ client.rs diff --git a/README.md b/README.md index 81c3bde4..c3264eba 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ [](https://laio.sh) -A simple, flexbox-inspired layout and session manager for tmux, with experimental zellij and herdr support. Define complex multi-window, multi-pane layouts in YAML and manage session lifecycles with startup/shutdown hooks. +A simple, flexbox-inspired layout and session manager for tmux, with experimental zellij, herdr, and rex support. Define complex multi-window, multi-pane layouts in YAML and manage session lifecycles with startup/shutdown hooks. **[Full Documentation](https://laio.sh/docs/getting-started/installing)** @@ -10,10 +10,10 @@ A simple, flexbox-inspired layout and session manager for tmux, with experimenta - **Template variables** - Dynamic configurations with Tera template support and array variables - **Session lifecycle management** - Startup/shutdown commands and embedded scripts - **Dual configuration modes** - Global configs (`~/.config/laio`) or local project configs (`.laio.yaml`) -- **Session serialization** - Export existing tmux, zellij, and herdr sessions to YAML format +- **Session serialization** - Export existing tmux, zellij, herdr, and rex sessions to YAML format - **Focus & zoom control** - Pin focus and zoom states in configuration - **Environment & shell customization** - Per-session env vars and shell overrides -- **Multiplexer support** - tmux native; experimental Zellij and herdr backends, selectable via `--muxer` or `LAIO_MUXER`. On herdr, each laio config runs as a workspace in the dedicated `laio` session. +- **Multiplexer support** - tmux native; experimental Zellij, herdr, and rex backends, selectable via `--muxer` or `LAIO_MUXER`. On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio-`. ## Quick Start @@ -96,6 +96,7 @@ laio start [name] # Start session (interactive picker if name o laio start --file config.yaml # Start from specific file laio start --var key=value # Start with template variables laio start --muxer herdr # Start with herdr (experimental) +laio start --muxer rex # Start with rex (experimental) laio stop [name] # Stop session laio stop --all # Stop all laio-managed sessions laio list # List sessions and configs @@ -104,7 +105,7 @@ laio config create --var key=value # Create from _default.yaml with variables laio config create --copy src # Create from existing config laio config edit # Edit config in $EDITOR laio config link # Symlink .laio.yaml to global config -laio session yaml # Export current tmux, zellij, or herdr session to YAML +laio session yaml # Export current tmux, zellij, herdr, or rex session to YAML laio completion # Generate shell completions ``` @@ -248,13 +249,21 @@ laio config link myproject # symlinks .laio.yaml -> ~/.config/laio/myproject.ya ## Session Serialization -Export existing tmux, zellij, and herdr sessions to YAML: +Export existing tmux, zellij, herdr, and rex sessions to YAML: ```bash -# From within a tmux, zellij, or herdr session +# From within a tmux, zellij, herdr, or rex session laio session yaml > ~/.config/laio/newsession.yaml ``` +## Experimental rex Backend + +Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio-`. + +- **Attach** runs `rex do session.select session_id=session:`. Remote Control must be enabled in Rex.app under Settings > Rex Server. When the attach fails, the start still succeeds and rex's error is logged as a warning. +- **Session records** live in a sidecar store: `LAIO_STATE_DIR` when set (used as-is), otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. +- **Limitations:** `env` and pane `style` are ignored. `laio session yaml` loses pane commands and ignores floating layers. + ## Usage Restrictions Use of this software is strictly prohibited for any organization, company, or government directly or indirectly involved in aiding or abetting the genocide and atrocities committed against the Palestinian people in Gaza. Only individuals and entities unaffiliated with such actions are permitted to use the software. diff --git a/docs/content/_index.md b/docs/content/_index.md index 9c405199..6428960d 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -1,5 +1,5 @@ +++ -title = "laio - a simple, flexbox-inspired layout & session manager for tmux, zellij & herdr." +title = "laio - a simple, flexbox-inspired layout & session manager for tmux, zellij, herdr & rex." description = "Welcome to laio." sort_by = "weight" weight = 1 @@ -34,7 +34,11 @@ content = 'Use global configs (~/.config/laio) or project-local .laio.yaml files [[extra.list]] title = "Session Export" -content = 'Serialize existing tmux, zellij, and herdr sessions to YAML format for sharing and templating.' +content = 'Serialize existing tmux, zellij, herdr, and rex sessions to YAML format for sharing and templating.' + +[[extra.list]] +title = "Experimental rex Backend" +content = 'Select with --muxer rex. Session env and pane style are ignored, export loses pane commands and floating layers, and attach needs Remote Control enabled in Rex.app under Settings > Rex Server. Session records live in LAIO_STATE_DIR when set, otherwise $XDG_STATE_HOME/laio/rex, otherwise ~/.local/state/laio/rex.' [[extra.list]] title = "Supported Platforms" diff --git a/docs/content/docs/configuration/lifecycle.md b/docs/content/docs/configuration/lifecycle.md index 0086a144..ff7d4ebd 100644 --- a/docs/content/docs/configuration/lifecycle.md +++ b/docs/content/docs/configuration/lifecycle.md @@ -142,7 +142,7 @@ Pane scripts run **after** pane commands complete. ## Pane Command Execution -On tmux, pane commands are batched into a single `send-keys` invocation. On zellij, all pane commands plus the pane script run in one shell invocation: the pane node gets `command=""` with a child `args` node containing `-c` and the joined commands (`; `), plus `close_on_exit true` and `start_suspended false`. The wrapper shell resolves from the session `shell`, then the login shell, then `$SHELL`, then `sh`. On herdr, each command is sent to the pane individually. +On tmux, pane commands are batched into a single `send-keys` invocation. On zellij, all pane commands plus the pane script run in one shell invocation: the pane node gets `command=""` with a child `args` node containing `-c` and the joined commands (`; `), plus `close_on_exit true` and `start_suspended false`. The wrapper shell resolves from the session `shell`, then the login shell, then `$SHELL`, then `sh`. On herdr, each command is sent to the pane individually. On rex, each pane's commands and its script are joined and sent to the pane's block in one go. ```yaml windows: @@ -184,7 +184,11 @@ windows: - Only affects pane-level commands (not startup/shutdown commands) - No effect on zellij, which runs all pane commands in one shell invocation (`pane_cmd_delay` is ignored) -**Note:** On tmux the delay is applied once after all panes are created. On herdr it is applied once before the first pane command is sent. On zellij `pane_cmd_delay` is ignored. +**Note:** On tmux the delay is applied once after all panes are created. On herdr it is applied once before the first pane command is sent. On rex it is applied once before the first pane command is sent. On zellij `pane_cmd_delay` is ignored. + +### rex (experimental) + +rex runs the whole session in one rex session labelled `laio-`. Lifecycle hooks run in the session path, without the session `env`: rex has no environment store, so `env` is ignored. Pane `style` is ignored as well. Attach runs bare `rex do session.select session_id=`; Remote Control must be enabled in Rex.app under Settings > Rex Server, and a failing attach only logs a warning, so the start still succeeds. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. `laio session yaml` loses pane commands and ignores floating layers. ## Common Patterns diff --git a/docs/content/docs/configuration/yaml-reference.md b/docs/content/docs/configuration/yaml-reference.md index 1fa97bbe..5fb3287a 100644 --- a/docs/content/docs/configuration/yaml-reference.md +++ b/docs/content/docs/configuration/yaml-reference.md @@ -16,9 +16,10 @@ top = false ### Required Fields **`name`** (string) -- Session name used by the multiplexer (the workspace label on herdr) +- Session name used by the multiplexer (the workspace label on herdr, the `laio-` label suffix on rex) - Must be unique across all sessions - On herdr, the name must be 1-64 bytes of letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid herdr session name" +- On rex, the name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A `laio-` label longer than 128 characters fails as well - tmux and zellij do not apply this restriction - Example: `"myproject"` @@ -40,6 +41,7 @@ top = false - On tmux, laio sets the session's `default-shell` option to this value - On zellij, laio uses the session `shell`, then the login shell, then `$SHELL`, then `sh` - Ignored on herdr, which uses the shell herdr starts +- On rex, laio sets the shell of every block to this value; without it the block uses rex's default shell - Example: `"/bin/zsh"`, `"/bin/bash"` **`pane_cmd_delay`** (number, milliseconds) @@ -51,10 +53,12 @@ top = false - Example: `500` (wait 500ms) - Recommended value for Nushell: `500` - Not applied on zellij, where `pane_cmd_delay` has no effect +- Applied once before the first pane command on rex **`env`** (object) - Environment variables as key-value pairs - Available to all commands in the session +- Ignored on rex, which has no environment store - Example: ```yaml env: @@ -534,9 +538,9 @@ done - Format: comma-separated key=value pairs - Example: `"bg=blue,fg=white"`, `"bg=darkred,fg=default"` - See `man tmux` for available style options -- Ignored on zellij and herdr, which have no pane style equivalent +- Ignored on zellij, herdr, and rex, which have no pane style equivalent -**Note:** On herdr, each laio config runs as a workspace in the dedicated `laio` session. +**Note:** On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio-`. **`flex_direction`** (string: `"row"` or `"column"`) - Layout direction for nested panes @@ -563,6 +567,17 @@ done tail -f app.log ``` +## rex (experimental) + +Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio-`. + +- `env` and pane `style` are ignored. +- A session with no windows fails with `Session '' has no windows`; each window is capped at 24 blocks and a split depth of 16. +- `pane_cmd_delay` is applied once before the first pane command. +- Attach runs `rex do session.select session_id=`. Remote Control must be enabled in Rex.app under Settings > Rex Server. When the attach fails, the start still succeeds and rex's error is logged as a warning. +- Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. +- `laio session yaml` loses pane commands and ignores floating layers. + ## Command Structure Commands can be defined in two formats: diff --git a/docs/content/docs/getting-started/quick-start.md b/docs/content/docs/getting-started/quick-start.md index 8204612a..81b94b73 100644 --- a/docs/content/docs/getting-started/quick-start.md +++ b/docs/content/docs/getting-started/quick-start.md @@ -23,7 +23,9 @@ laio config create myproject laio start myproject ``` -> laio targets **tmux** by default. Experimental `zellij` and `herdr` backends are available via `--muxer zellij|herdr` or `LAIO_MUXER` on any command. +> laio targets **tmux** by default. Experimental `zellij`, `herdr`, and `rex` backends are available via `--muxer zellij|herdr|rex` or `LAIO_MUXER` on any command. +> +> rex runs one `laio-` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. `env` and pane `style` are ignored, and `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. This creates a default configuration with: - An editor window that runs `{% raw %}{{ editor | default(value="nvim") }}{% endraw %}` from the template (override with `--var editor=`) diff --git a/docs/content/docs/reference/cli-commands.md b/docs/content/docs/reference/cli-commands.md index 32c79da0..6128a7be 100644 --- a/docs/content/docs/reference/cli-commands.md +++ b/docs/content/docs/reference/cli-commands.md @@ -46,7 +46,7 @@ laio start [OPTIONS] [NAME] ``` -f, --file Use specific configuration file --m, --muxer Multiplexer to use (tmux, zellij, or herdr) +-m, --muxer Multiplexer to use (tmux, zellij, herdr, or rex) -p, --show-picker Show config picker (skip .laio.yaml) --skip-cmds Skip startup commands/scripts --skip-attach Start session without attaching @@ -143,7 +143,7 @@ laio stop [OPTIONS] [NAME] ### Options ``` --m, --muxer Multiplexer to use (tmux, zellij, or herdr) +-m, --muxer Multiplexer to use (tmux, zellij, herdr, or rex) --skip-cmds Skip shutdown commands/scripts -a, --all Stop all laio-managed sessions -o, --others Stop all sessions except current @@ -205,7 +205,7 @@ Alias: `laio ls` ### Options ``` --m, --muxer Multiplexer to use (tmux, zellij, or herdr) +-m, --muxer Multiplexer to use (tmux, zellij, herdr, or rex) -j, --json Output as JSON ``` @@ -480,7 +480,7 @@ Alias: `laio config ls` #### Options ``` --m, --muxer Multiplexer to use (tmux, zellij, or herdr) +-m, --muxer Multiplexer to use (tmux, zellij, herdr, or rex) -j, --json Output as JSON ``` @@ -516,7 +516,7 @@ Alias: `laio session ls` #### Options ``` --m, --muxer Multiplexer to use (tmux, zellij, or herdr) +-m, --muxer Multiplexer to use (tmux, zellij, herdr, or rex) -j, --json Output as JSON ``` @@ -543,7 +543,7 @@ laio session yaml [OPTIONS] #### Options ``` --m, --muxer Multiplexer to use (tmux, zellij, or herdr) +-m, --muxer Multiplexer to use (tmux, zellij, herdr, or rex) ``` #### Examples @@ -559,7 +559,7 @@ laio session yaml > ~/.config/laio/newsession.yaml laio session yaml > .laio.yaml ``` -**Note:** Must be run from within a tmux, zellij, or herdr session. +**Note:** Must be run from within a tmux, zellij, herdr, or rex session. ## laio completion @@ -610,6 +610,7 @@ Override the default multiplexer. export LAIO_MUXER=tmux # Use tmux (default) export LAIO_MUXER=zellij # Use zellij (experimental) export LAIO_MUXER=herdr # Use herdr (experimental) +export LAIO_MUXER=rex # Use rex (experimental) ``` Equivalent to using `--muxer` flag on every command. @@ -643,7 +644,7 @@ There are practical limits to nesting depth. Very deep nesting (5+ levels) may c ### Multiplexer Limitations -**Zellij and herdr support is experimental** and may have limitations compared to tmux. Use tmux for production workflows. +**Zellij, herdr, and rex support is experimental** and may have limitations compared to tmux. Use tmux for production workflows. #### herdr (experimental) @@ -659,3 +660,20 @@ herdr maps one laio config to one workspace inside the dedicated `laio` session. - `laio session yaml` exports the workspace of the pane laio runs in. It requires `HERDR_WORKSPACE_ID`, which herdr sets in every pane. - laio marks ownership per workspace with the `LAIO_CONFIG` and `LAIO_VARS` metadata tokens. - Pane `style` is ignored on herdr. + +#### rex (experimental) + +rex maps one laio config to one rex session labelled `laio-`. The name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A rendered label longer than 128 characters fails as well. + +**Select rex on every command.** Multiplexer selection is per invocation and defaults to tmux. Pass `--muxer rex` on each laio command, or set `LAIO_MUXER=rex`. Without it, laio targets tmux. + +- `laio start ` builds the whole session in one `session.create` call, then attaches. Starting a config that is already running attaches to it. `--skip-attach` skips the attach. +- Attach runs the bare command `rex do session.select session_id=`. Remote Control must be enabled in Rex.app under Settings > Rex Server. When the attach fails, the start still succeeds and rex's error is logged as a warning. +- A session without windows fails with `Session '' has no windows`. Each window is capped at 24 blocks and a split depth of 16; a larger layout fails before rex is called. +- `pane_cmd_delay` is applied once before the first pane command is sent. +- Session `env` is ignored: rex has no environment store. `laio` keeps the config path and the template variables in a sidecar record per session. +- The sidecar store is `LAIO_STATE_DIR` when set (used as-is), otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. +- `laio stop ` runs the shutdown hooks and kills the rex session. `laio stop --all` and `--others` sweep the laio-managed sessions and prune stale records. +- `laio list` shows the laio-managed sessions, marked ● when a rex app client has them attached. +- `laio session yaml` requires a rex session: it reads `REX_SESSION`. The export reads the tiled layer, so it loses pane commands and ignores floating layers. +- Pane `style` is ignored on rex. diff --git a/docs/content/docs/workflow/managing-configs.md b/docs/content/docs/workflow/managing-configs.md index c30667d0..cef97db6 100644 --- a/docs/content/docs/workflow/managing-configs.md +++ b/docs/content/docs/workflow/managing-configs.md @@ -105,7 +105,11 @@ Useful for scripting and automation. laio session list ``` -On tmux and zellij this lists every session of the multiplexer, including sessions laio does not manage. On herdr it lists only laio-managed workspaces. +On tmux and zellij this lists every session of the multiplexer, including sessions laio does not manage. On herdr it lists only laio-managed workspaces. On rex it lists only laio-managed sessions and marks a session attached when a rex app client has it attached. + +#### rex (experimental) + +rex runs one `laio-` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. Session `env` and pane `style` are ignored. `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. ## Deleting Configurations diff --git a/docs/content/docs/workflow/session-export.md b/docs/content/docs/workflow/session-export.md index ff25136b..18530d3c 100644 --- a/docs/content/docs/workflow/session-export.md +++ b/docs/content/docs/workflow/session-export.md @@ -1,6 +1,6 @@ +++ title = "Session Export" -description = "Export existing tmux, zellij, and herdr sessions to YAML configuration." +description = "Export existing tmux, zellij, herdr, and rex sessions to YAML configuration." draft = false weight = 30 sort_by = "weight" @@ -13,7 +13,7 @@ top = false ## Overview -Laio can serialize existing tmux, zellij, and herdr sessions into YAML configuration format. This is useful for: +Laio can serialize existing tmux, zellij, herdr, and rex sessions into YAML configuration format. This is useful for: - Capturing complex layouts built interactively - Creating configurations from working sessions @@ -23,7 +23,7 @@ Laio can serialize existing tmux, zellij, and herdr sessions into YAML configura ## Basic Export -From within a tmux, zellij, or herdr session, export to YAML: +From within a tmux, zellij, herdr, or rex session, export to YAML: ```bash laio session yaml @@ -49,7 +49,7 @@ laio session yaml > .laio.yaml The export captures: -- **Session name** - On tmux and zellij, the current session name; on herdr, the label of the workspace laio runs in, which equals the laio session name for laio-managed workspaces +- **Session name** - On tmux and zellij, the current session name; on herdr, the label of the workspace laio runs in, which equals the laio session name for laio-managed workspaces; on rex, the laio name from the sidecar record, otherwise the `laio-` label with its prefix stripped - **Window structure** - All windows and their names - **Pane layout** - Splits, sizes, and arrangement - **Working directories** - Current path for each pane @@ -58,6 +58,7 @@ The export captures: - **Zellij command shape** - On zellij the export reads the KDL layout, so a pane with commands exports the shell wrapper as one command: `command: ` with `args: [-c, ""]` - **Focus and zoom state** - On herdr, the export captures the focused pane and the zoomed pane of each window - **Pane names** - On herdr, each pane label exports as the pane `name` +- **rex layer scope** - On rex the export reads the tiled layer only: pane commands are lost and floating layers are ignored ## What Doesn't Get Exported @@ -67,9 +68,14 @@ The following are **not** captured: - Lifecycle hooks (`startup`, `shutdown`, `startup_script`, `shutdown_script`) - Pane styles (`style`) - Focus and zoom states (`focus`, `zoom`) on tmux and zellij exports +- Pane commands on rex exports You'll need to add these manually after export. +### rex (experimental) + +A rex export needs a rex session: it reads `REX_SESSION`. It reads the tiled layer only, so pane commands are lost and floating layers are ignored. Session `env` and pane `style` are never exported. Attaching to a rex session needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. + ## Command Limitations **Important:** Exported commands reflect **actual running processes**, not the wrapper scripts, aliases, or shell functions used to launch them. diff --git a/src/app/cli/command_line.rs b/src/app/cli/command_line.rs index 6c2e0660..f8401c6d 100644 --- a/src/app/cli/command_line.rs +++ b/src/app/cli/command_line.rs @@ -21,7 +21,7 @@ enum Commands { #[clap(short, long)] file: Option, - /// Specify the multiplexer to use. Note: Zellij and herdr support is experimental! + /// Specify the multiplexer to use. Note: Zellij, herdr, and rex support is experimental! #[clap(short, long)] muxer: Option, @@ -48,7 +48,7 @@ enum Commands { /// Name of the session to stop. name: Option, - /// Specify the multiplexer to use. + /// Specify the multiplexer to use. Note: Zellij, herdr, and rex support is experimental! #[clap(short, long)] muxer: Option, @@ -73,7 +73,7 @@ enum Commands { /// List active (*) and available sessions #[clap(alias = "ls")] List { - /// Specify the multiplexer to use. + /// Specify the multiplexer to use. Note: Zellij, herdr, and rex support is experimental! #[clap(short, long)] muxer: Option, diff --git a/src/muxer/mod.rs b/src/muxer/mod.rs index f266b496..108b4ddd 100644 --- a/src/muxer/mod.rs +++ b/src/muxer/mod.rs @@ -3,17 +3,11 @@ use clap::ValueEnum; use miette::{Result, bail}; use std::env; pub(crate) mod herdr; -#[cfg_attr( - not(test), - expect( - dead_code, - reason = "unwired until the Muxer enum wiring subtask of parent 4b347a42; remove when wiring lands" - ) -)] pub(crate) mod rex; pub(crate) mod tmux; pub(crate) mod zellij; pub(crate) use herdr::Herdr; +pub(crate) use rex::Rex; pub(crate) use tmux::Tmux; pub(crate) use zellij::Zellij; @@ -22,6 +16,7 @@ pub(crate) enum Muxer { Tmux, Zellij, Herdr, + Rex, } pub(crate) fn create_muxer(muxer: &Option) -> Result> { @@ -32,6 +27,7 @@ pub(crate) fn create_muxer(muxer: &Option) -> Result "tmux" => Muxer::Tmux, "zellij" => Muxer::Zellij, "herdr" => Muxer::Herdr, + "rex" => Muxer::Rex, _ => { bail!(format!( "Unsupported muxer specified in LAIO_MUXER: '{}'", @@ -47,6 +43,7 @@ pub(crate) fn create_muxer(muxer: &Option) -> Result Muxer::Tmux => Ok(Box::new(Tmux::new())), Muxer::Zellij => Ok(Box::new(Zellij::new())), Muxer::Herdr => Ok(Box::new(Herdr::new())), + Muxer::Rex => Ok(Box::new(Rex::new())), } } diff --git a/src/muxer/rex/mod.rs b/src/muxer/rex/mod.rs index d4a2c35b..028c5371 100644 --- a/src/muxer/rex/mod.rs +++ b/src/muxer/rex/mod.rs @@ -8,13 +8,6 @@ pub(crate) mod store; pub(crate) use export::{local_path, session_from_view, tiled_block_ids}; pub(crate) use layout::{LeafPlan, build_create_request}; -#[cfg_attr( - not(test), - expect( - unused_imports, - reason = "unwired until the Muxer enum wiring subtask of parent 4b347a42; remove when wiring lands" - ) -)] pub(crate) use mux::Rex; #[cfg(test)] diff --git a/test/muxer/test.rs b/test/muxer/test.rs index a95513ad..3e43f8f6 100644 --- a/test/muxer/test.rs +++ b/test/muxer/test.rs @@ -36,7 +36,7 @@ fn restore_laio_muxer(previous: Option) { #[test] fn create_muxer_returns_each_explicit_backend() -> Result<()> { - for muxer in [Muxer::Tmux, Muxer::Zellij, Muxer::Herdr] { + for muxer in [Muxer::Tmux, Muxer::Zellij, Muxer::Herdr, Muxer::Rex] { assert!(create_muxer(&Some(muxer)).is_ok()); } @@ -54,6 +54,28 @@ fn create_muxer_accepts_herdr_from_the_env_var() -> Result<()> { Ok(()) } +#[test] +fn create_muxer_accepts_rex_from_the_env_var() -> Result<()> { + let _guard = env_lock()?; + let previous = set_laio_muxer(Some("rex")); + let result = create_muxer(&None); + restore_laio_muxer(previous); + + assert!(result.is_ok()); + Ok(()) +} + +#[test] +fn create_muxer_matches_the_rex_env_var_case_insensitively() -> Result<()> { + let _guard = env_lock()?; + let previous = set_laio_muxer(Some("reX")); + let result = create_muxer(&None); + restore_laio_muxer(previous); + + assert!(result.is_ok()); + Ok(()) +} + #[test] fn create_muxer_matches_the_env_var_case_insensitively() -> Result<()> { let _guard = env_lock()?; @@ -99,3 +121,9 @@ fn muxer_value_enum_accepts_herdr() -> Result<()> { assert!(matches!(Muxer::from_str("herdr", true), Ok(Muxer::Herdr))); Ok(()) } + +#[test] +fn muxer_value_enum_accepts_rex() -> Result<()> { + assert!(matches!(Muxer::from_str("rex", true), Ok(Muxer::Rex))); + Ok(()) +} From bb4f4a2ab8ea4884da6b5de030632f000325f5ac Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 22:12:36 +0000 Subject: [PATCH 09/16] feat(muxer/rex): change session marker to 'laio: ' --- README.md | 4 +- docs/content/docs/configuration/lifecycle.md | 2 +- .../docs/configuration/yaml-reference.md | 8 +- .../docs/getting-started/quick-start.md | 2 +- docs/content/docs/reference/cli-commands.md | 2 +- .../content/docs/workflow/managing-configs.md | 2 +- docs/content/docs/workflow/session-export.md | 2 +- src/muxer/rex/mux.rs | 2 +- test/muxer/rex/client_test.rs | 16 ++-- test/muxer/rex/export_test.rs | 18 ++--- test/muxer/rex/mux_test.rs | 2 +- test/muxer/rex/mux_test/session.rs | 2 +- test/muxer/rex/mux_test/start.rs | 79 +++++++++++++------ test/muxer/rex/mux_test/stop.rs | 10 ++- test/muxer/rex/mux_test/switch.rs | 16 ++-- test/muxer/rex/session_get_test.rs | 2 +- 16 files changed, 105 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index c3264eba..7aff9643 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ A simple, flexbox-inspired layout and session manager for tmux, with experimenta - **Session serialization** - Export existing tmux, zellij, herdr, and rex sessions to YAML format - **Focus & zoom control** - Pin focus and zoom states in configuration - **Environment & shell customization** - Per-session env vars and shell overrides -- **Multiplexer support** - tmux native; experimental Zellij, herdr, and rex backends, selectable via `--muxer` or `LAIO_MUXER`. On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio-`. +- **Multiplexer support** - tmux native; experimental Zellij, herdr, and rex backends, selectable via `--muxer` or `LAIO_MUXER`. On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio: `. ## Quick Start @@ -258,7 +258,7 @@ laio session yaml > ~/.config/laio/newsession.yaml ## Experimental rex Backend -Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio-`. +Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio: `. - **Attach** runs `rex do session.select session_id=session:`. Remote Control must be enabled in Rex.app under Settings > Rex Server. When the attach fails, the start still succeeds and rex's error is logged as a warning. - **Session records** live in a sidecar store: `LAIO_STATE_DIR` when set (used as-is), otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. diff --git a/docs/content/docs/configuration/lifecycle.md b/docs/content/docs/configuration/lifecycle.md index ff7d4ebd..f3e6ee3c 100644 --- a/docs/content/docs/configuration/lifecycle.md +++ b/docs/content/docs/configuration/lifecycle.md @@ -188,7 +188,7 @@ windows: ### rex (experimental) -rex runs the whole session in one rex session labelled `laio-`. Lifecycle hooks run in the session path, without the session `env`: rex has no environment store, so `env` is ignored. Pane `style` is ignored as well. Attach runs bare `rex do session.select session_id=`; Remote Control must be enabled in Rex.app under Settings > Rex Server, and a failing attach only logs a warning, so the start still succeeds. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. `laio session yaml` loses pane commands and ignores floating layers. +rex runs the whole session in one rex session labelled `laio: `. Lifecycle hooks run in the session path, without the session `env`: rex has no environment store, so `env` is ignored. Pane `style` is ignored as well. Attach runs bare `rex do session.select session_id=`; Remote Control must be enabled in Rex.app under Settings > Rex Server, and a failing attach only logs a warning, so the start still succeeds. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. `laio session yaml` loses pane commands and ignores floating layers. ## Common Patterns diff --git a/docs/content/docs/configuration/yaml-reference.md b/docs/content/docs/configuration/yaml-reference.md index 5fb3287a..1bab3240 100644 --- a/docs/content/docs/configuration/yaml-reference.md +++ b/docs/content/docs/configuration/yaml-reference.md @@ -16,10 +16,10 @@ top = false ### Required Fields **`name`** (string) -- Session name used by the multiplexer (the workspace label on herdr, the `laio-` label suffix on rex) +- Session name used by the multiplexer (the workspace label on herdr, the `laio: ` label prefix on rex) - Must be unique across all sessions - On herdr, the name must be 1-64 bytes of letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid herdr session name" -- On rex, the name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A `laio-` label longer than 128 characters fails as well +- On rex, the name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A `laio: ` label longer than 128 characters fails as well - tmux and zellij do not apply this restriction - Example: `"myproject"` @@ -540,7 +540,7 @@ done - See `man tmux` for available style options - Ignored on zellij, herdr, and rex, which have no pane style equivalent -**Note:** On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio-`. +**Note:** On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio: `. **`flex_direction`** (string: `"row"` or `"column"`) - Layout direction for nested panes @@ -569,7 +569,7 @@ done ## rex (experimental) -Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio-`. +Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio: `. - `env` and pane `style` are ignored. - A session with no windows fails with `Session '' has no windows`; each window is capped at 24 blocks and a split depth of 16. diff --git a/docs/content/docs/getting-started/quick-start.md b/docs/content/docs/getting-started/quick-start.md index 81b94b73..0478a63e 100644 --- a/docs/content/docs/getting-started/quick-start.md +++ b/docs/content/docs/getting-started/quick-start.md @@ -25,7 +25,7 @@ laio start myproject > laio targets **tmux** by default. Experimental `zellij`, `herdr`, and `rex` backends are available via `--muxer zellij|herdr|rex` or `LAIO_MUXER` on any command. > -> rex runs one `laio-` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. `env` and pane `style` are ignored, and `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. +> rex runs one `laio: ` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. `env` and pane `style` are ignored, and `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. This creates a default configuration with: - An editor window that runs `{% raw %}{{ editor | default(value="nvim") }}{% endraw %}` from the template (override with `--var editor=`) diff --git a/docs/content/docs/reference/cli-commands.md b/docs/content/docs/reference/cli-commands.md index 6128a7be..c7f42985 100644 --- a/docs/content/docs/reference/cli-commands.md +++ b/docs/content/docs/reference/cli-commands.md @@ -663,7 +663,7 @@ herdr maps one laio config to one workspace inside the dedicated `laio` session. #### rex (experimental) -rex maps one laio config to one rex session labelled `laio-`. The name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A rendered label longer than 128 characters fails as well. +rex maps one laio config to one rex session labelled `laio: `. The name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A rendered label longer than 128 characters fails as well. **Select rex on every command.** Multiplexer selection is per invocation and defaults to tmux. Pass `--muxer rex` on each laio command, or set `LAIO_MUXER=rex`. Without it, laio targets tmux. diff --git a/docs/content/docs/workflow/managing-configs.md b/docs/content/docs/workflow/managing-configs.md index cef97db6..7e7f1f90 100644 --- a/docs/content/docs/workflow/managing-configs.md +++ b/docs/content/docs/workflow/managing-configs.md @@ -109,7 +109,7 @@ On tmux and zellij this lists every session of the multiplexer, including sessio #### rex (experimental) -rex runs one `laio-` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. Session `env` and pane `style` are ignored. `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. +rex runs one `laio: ` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. Session `env` and pane `style` are ignored. `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. ## Deleting Configurations diff --git a/docs/content/docs/workflow/session-export.md b/docs/content/docs/workflow/session-export.md index 18530d3c..a16f948c 100644 --- a/docs/content/docs/workflow/session-export.md +++ b/docs/content/docs/workflow/session-export.md @@ -49,7 +49,7 @@ laio session yaml > .laio.yaml The export captures: -- **Session name** - On tmux and zellij, the current session name; on herdr, the label of the workspace laio runs in, which equals the laio session name for laio-managed workspaces; on rex, the laio name from the sidecar record, otherwise the `laio-` label with its prefix stripped +- **Session name** - On tmux and zellij, the current session name; on herdr, the label of the workspace laio runs in, which equals the laio session name for laio-managed workspaces; on rex, the laio name from the sidecar record, otherwise the `laio: ` label with its prefix stripped - **Window structure** - All windows and their names - **Pane layout** - Splits, sizes, and arrangement - **Working directories** - Current path for each pane diff --git a/src/muxer/rex/mux.rs b/src/muxer/rex/mux.rs index b01429e7..60c3916f 100644 --- a/src/muxer/rex/mux.rs +++ b/src/muxer/rex/mux.rs @@ -22,7 +22,7 @@ use super::client::RexClient; use super::model::{ClientListOutput, CreateOutput, ResolveResult}; use super::store::{RexSessionRecord, RexSessionStore, laio_state_dir}; -pub(super) const LABEL_PREFIX: &str = "laio-"; +pub(super) const LABEL_PREFIX: &str = "laio: "; const MAX_LABEL_LEN: usize = 128; const SESSION_KIND: &str = "session"; const REX_SESSION_ENV: &str = "REX_SESSION"; diff --git a/test/muxer/rex/client_test.rs b/test/muxer/rex/client_test.rs index 243592b9..a2ccf464 100644 --- a/test/muxer/rex/client_test.rs +++ b/test/muxer/rex/client_test.rs @@ -135,7 +135,7 @@ fn create_request() -> CreateRequest { }; CreateRequest { - label: Some("laio-probe".to_string()), + label: Some("laio: probe".to_string()), initial_windows: Some(vec![ CreateWindow { window_label: Some("w1".to_string()), @@ -159,7 +159,7 @@ fn create_request() -> CreateRequest { fn create_payload() -> Value { json!({ - "label": "laio-probe", + "label": "laio: probe", "initial_windows": [ { "window_label": "w1", @@ -210,7 +210,7 @@ fn session_view_parses_window_without_focus_zoom_or_block_owner() -> TestResult let client = api_client( "session.view", json!({"session_id": "session:1"}), - r#"{"revision":12,"session_id":"session:1","label":"laio-probe","active_window_id":"window:1","windows":[{"window_id":"window:1","label":"Window 01a1","layers":[{"layer_id":"layer:1","kind":"tiled","bounds":[0,0,1,1],"layout":{"rect":[0,0,1,1],"block_id":"block:1"},"blocks":[{"block_id":"block:1","creator_name":"rex","flavor":"terminal","label":"shell"}]}]}]}"#, + r#"{"revision":12,"session_id":"session:1","label":"laio: probe","active_window_id":"window:1","windows":[{"window_id":"window:1","label":"Window 01a1","layers":[{"layer_id":"layer:1","kind":"tiled","bounds":[0,0,1,1],"layout":{"rect":[0,0,1,1],"block_id":"block:1"},"blocks":[{"block_id":"block:1","creator_name":"rex","flavor":"terminal","label":"shell"}]}]}]}"#, )?; let view = client.session_view("session:1")?; @@ -265,7 +265,7 @@ fn session_focus_block_sends_session_and_block() -> TestResult { fn session_list_reads_cli_json_output() -> TestResult { let client = string_client( &["session", "ls", "--json"], - r#"{"sessions":[{"session_id":"session:1","label":"laio-probe"},{"session_id":"session:2","label":"other"}]}"#, + r#"{"sessions":[{"session_id":"session:1","label":"laio: probe"},{"session_id":"session:2","label":"other"}]}"#, )?; let output = client.session_list()?; @@ -275,7 +275,7 @@ fn session_list_reads_cli_json_output() -> TestResult { .iter() .map(|session| session.label.as_str()) .collect(); - assert_eq!(labels, ["laio-probe", "other"]); + assert_eq!(labels, ["laio: probe", "other"]); Ok(()) } @@ -283,11 +283,11 @@ fn session_list_reads_cli_json_output() -> TestResult { fn target_resolve_sends_kinds_and_queries() -> TestResult { let client = api_client( "target.resolve", - json!({"kinds": ["session"], "queries": ["laio-probe"]}), - r#"{"results":[{"query":"laio-probe","status":"not_found","candidates":[]}]}"#, + json!({"kinds": ["session"], "queries": ["laio: probe"]}), + r#"{"results":[{"query":"laio: probe","status":"not_found","candidates":[]}]}"#, )?; - let output = client.target_resolve(&["session"], &["laio-probe"])?; + let output = client.target_resolve(&["session"], &["laio: probe"])?; let results = output.results.ok_or("should have results")?; assert_eq!(results.len(), 1); diff --git a/test/muxer/rex/export_test.rs b/test/muxer/rex/export_test.rs index 394b919f..f7ea9a45 100644 --- a/test/muxer/rex/export_test.rs +++ b/test/muxer/rex/export_test.rs @@ -112,7 +112,7 @@ fn horizontal_ratios_round_trip_to_the_exact_flex_weights() -> TestResult { split("horizontal", 0.5, leaf("b2"), leaf("b3")), ); let view = view( - "laio-other", + "laio: other", "w1", vec![window( "w1", @@ -147,7 +147,7 @@ fn horizontal_ratios_round_trip_to_the_exact_flex_weights() -> TestResult { fn a_vertical_root_split_sets_the_window_direction_to_column() -> TestResult { let layout = split("vertical", 0.5, leaf("b1"), leaf("b2")); let view = view( - "laio-work", + "laio: work", "w1", vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], ); @@ -172,7 +172,7 @@ fn a_vertical_split_inside_a_horizontal_window_becomes_a_column_container() -> T split("vertical", 0.5, leaf("b2"), leaf("b3")), ); let view = view( - "laio-work", + "laio: work", "w1", vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], ); @@ -206,7 +206,7 @@ fn pane_paths_are_relative_to_the_longest_common_prefix() -> TestResult { let layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); let view = view( - "laio-work", + "laio: work", "w1", vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], ); @@ -225,7 +225,7 @@ fn pane_paths_are_relative_to_the_longest_common_prefix() -> TestResult { fn focused_and_zoomed_blocks_mark_their_panes() -> TestResult { let layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); let view = view( - "laio-work", + "laio: work", "w1", vec![window( "w1", @@ -254,7 +254,7 @@ fn focused_and_zoomed_blocks_mark_their_panes() -> TestResult { fn only_the_active_window_is_focused() -> TestResult { let layout = || split("horizontal", 0.5, leaf("b1"), leaf("b2")); let view = view( - "laio-work", + "laio: work", "w2", vec![ window("w1", "first", None, None, vec![tiled(layout(), &[])]), @@ -278,7 +278,7 @@ fn only_the_active_window_is_focused() -> TestResult { fn floating_layers_are_ignored() -> TestResult { let tiled_layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); let view = view( - "laio-work", + "laio: work", "w1", vec![window( "w1", @@ -311,7 +311,7 @@ fn floating_layers_are_ignored() -> TestResult { fn a_missing_record_falls_back_to_the_label_without_the_laio_prefix() -> TestResult { let layout = leaf("b1"); let view = view( - "laio-work", + "laio: work", "w1", vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], ); @@ -328,7 +328,7 @@ fn a_missing_record_falls_back_to_the_label_without_the_laio_prefix() -> TestRes fn the_export_carries_no_unrecoverable_settings() -> TestResult { let layout = split("horizontal", 0.5, leaf("b1"), leaf("b2")); let view = view( - "laio-work", + "laio: work", "w1", vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], ); diff --git a/test/muxer/rex/mux_test.rs b/test/muxer/rex/mux_test.rs index 872ec6c5..ec5985d6 100644 --- a/test/muxer/rex/mux_test.rs +++ b/test/muxer/rex/mux_test.rs @@ -89,7 +89,7 @@ pub(super) fn session_of(yaml: &str) -> TestResult { pub(super) fn record(rex_session_id: &str, laio_name: &str) -> RexSessionRecord { RexSessionRecord { rex_session_id: rex_session_id.to_string(), - rex_label: format!("laio-{laio_name}"), + rex_label: format!("laio: {laio_name}"), laio_name: laio_name.to_string(), config_path: format!("/tmp/{laio_name}.yaml"), variables: format!("session_name={laio_name}&path=%2Ftmp"), diff --git a/test/muxer/rex/mux_test/session.rs b/test/muxer/rex/mux_test/session.rs index 447ab96a..a48b55f6 100644 --- a/test/muxer/rex/mux_test/session.rs +++ b/test/muxer/rex/mux_test/session.rs @@ -3,7 +3,7 @@ use crate::common::session_info::SessionStatus; use super::mux_test::*; -const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"laio-work"},{"session_id":"session:2","label":"laio-extra"},{"session_id":"session:3","label":"other"}]}"#; +const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"laio: work"},{"session_id":"session:2","label":"laio: extra"},{"session_id":"session:3","label":"other"}]}"#; #[test] fn get_session_config_path_returns_the_recorded_path() -> TestResult { diff --git a/test/muxer/rex/mux_test/start.rs b/test/muxer/rex/mux_test/start.rs index eeab75b2..abd0225d 100644 --- a/test/muxer/rex/mux_test/start.rs +++ b/test/muxer/rex/mux_test/start.rs @@ -37,8 +37,8 @@ fn start_creates_one_session_with_the_laio_label_and_records_it_before_sending() let store = harness.store(); let rex = harness - .resolve("laio-work", "not_found", "") - .create("laio-work", MULTI_CREATE, 2) + .resolve("laio: work", "not_found", "") + .create("laio: work", MULTI_CREATE, 2) .unit_asserting( &[ "send", @@ -65,7 +65,7 @@ fn start_creates_one_session_with_the_laio_label_and_records_it_before_sending() .ok_or("start should write the sidecar record")?; assert_eq!(record.rex_session_id, "session:1"); - assert_eq!(record.rex_label, "laio-work"); + assert_eq!(record.rex_label, "laio: work"); assert_eq!(record.config_path, "/tmp/work.yaml"); assert_eq!(record.variables, "a=b"); Ok(()) @@ -74,7 +74,7 @@ fn start_creates_one_session_with_the_laio_label_and_records_it_before_sending() #[test] fn start_returns_ok_without_creating_when_the_session_already_exists() -> TestResult { let rex = Harness::new() - .resolve("laio-work", "resolved", "session:1") + .resolve("laio: work", "resolved", "session:1") .build(); Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, false)?) @@ -104,8 +104,8 @@ windows: let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2"],"revision":2}]}"#; let rex = Harness::new() - .resolve("laio-work", "not_found", "") - .create("laio-work", create, 1) + .resolve("laio: work", "not_found", "") + .create("laio: work", create, 1) .unit(&[ "send", "-s", @@ -148,8 +148,8 @@ windows: let sent_at: Arc>> = Arc::new(Mutex::new(None)); let rex = Harness::new() - .resolve("laio-work", "not_found", "") - .create("laio-work", create, 1) + .resolve("laio: work", "not_found", "") + .create("laio: work", create, 1) .unit_at( &["send", "-s", "session:1", "-b", "block:1", "--", "ls\n"], Arc::clone(&sent_at), @@ -174,7 +174,7 @@ fn start_returns_err_without_a_record_when_session_create_fails() -> TestResult let store = harness.store(); let rex = harness - .resolve("laio-work", "not_found", "") + .resolve("laio: work", "not_found", "") .create_failing("rex session_create failed: bad_request") .build(); @@ -188,7 +188,7 @@ fn start_returns_err_without_a_record_when_session_create_fails() -> TestResult #[test] fn start_returns_err_when_target_resolve_fails() -> TestResult { let rex = Harness::new() - .resolve_failing("laio-work", "rex target_resolve failed: not_found") + .resolve_failing("laio: work", "rex target_resolve failed: not_found") .build(); let result = rex.start(&session_of(MULTI_WINDOW)?, &[], true, true); @@ -218,8 +218,8 @@ windows: let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2"],"revision":2}]}"#; let rex = Harness::new() - .resolve("laio-work", "not_found", "") - .create("laio-work", create, 1) + .resolve("laio: work", "not_found", "") + .create("laio: work", create, 1) .unit_failing( &[ "send", @@ -243,8 +243,8 @@ fn start_continues_when_session_select_fails() -> TestResult { let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2}]}"#; let rex = Harness::new() - .resolve("laio-work", "not_found", "") - .create("laio-work", create, 2) + .resolve("laio: work", "not_found", "") + .create("laio: work", create, 2) .unit(&[ "send", "-s", @@ -266,8 +266,8 @@ fn start_continues_when_session_select_fails() -> TestResult { #[test] fn start_skips_the_hooks_and_the_sends_when_skip_cmds_is_set() -> TestResult { let rex = Harness::new() - .resolve("laio-work", "not_found", "") - .create("laio-work", MULTI_CREATE, 2) + .resolve("laio: work", "not_found", "") + .create("laio: work", MULTI_CREATE, 2) .build(); Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, true)?) @@ -291,8 +291,8 @@ windows: let log: Log = Arc::new(Mutex::new(Vec::new())); let rex = Harness::new() - .resolve("laio-work", "not_found", "") - .create("laio-work", create, 1) + .resolve("laio: work", "not_found", "") + .create("laio: work", create, 1) .json_recording( "session.focus_block", json!({"session_id": "session:1", "block_id": "block:2"}), @@ -327,8 +327,8 @@ windows: )?; let rex = Harness::new() - .resolve("laio-work", "not_found", "") - .create("laio-work", MULTI_CREATE, 2) + .resolve("laio: work", "not_found", "") + .create("laio: work", MULTI_CREATE, 2) .json_recording( "session.focus_window", json!({"session_id": "session:1", "window_id": "window:2"}), @@ -356,6 +356,41 @@ fn start_rejects_a_name_outside_the_laio_charset() -> TestResult { Ok(()) } +#[test] +fn start_accepts_a_name_at_the_label_limit_and_rejects_one_over() -> TestResult { + let allowed = "a".repeat(122); + let label = format!("laio: {allowed}"); + let rex = Harness::new() + .resolve(&label, "resolved", "session:1") + .build(); + + rex.start( + &session_of(&format!( + "\nname: {allowed}\npath: /tmp\nwindows:\n - name: main\n" + ))?, + &[], + true, + true, + )?; + + let rejected = "b".repeat(123); + let rex = Harness::new().build(); + let error = rex + .start( + &session_of(&format!( + "\nname: {rejected}\npath: /tmp\nwindows:\n - name: main\n" + ))?, + &[], + true, + true, + ) + .err() + .ok_or("a name one over the label limit should fail")?; + + assert!(error.to_string().contains("128"), "{error}"); + Ok(()) +} + #[test] fn start_continues_when_the_record_cannot_be_written() -> TestResult { let harness = Harness::new(); @@ -363,8 +398,8 @@ fn start_continues_when_the_record_cannot_be_written() -> TestResult { fs::write(&blocked, "not a directory")?; let rex = harness - .resolve("laio-work", "not_found", "") - .create("laio-work", MULTI_CREATE, 2) + .resolve("laio: work", "not_found", "") + .create("laio: work", MULTI_CREATE, 2) .build(); Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, true)?) diff --git a/test/muxer/rex/mux_test/stop.rs b/test/muxer/rex/mux_test/stop.rs index d0a81741..be4cb191 100644 --- a/test/muxer/rex/mux_test/stop.rs +++ b/test/muxer/rex/mux_test/stop.rs @@ -6,7 +6,7 @@ use crate::common::muxer::Multiplexer; use super::mux_test::*; -const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"laio-work"},{"session_id":"session:2","label":"laio-other"},{"session_id":"session:3","label":"not-laio"}]}"#; +const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"laio: work"},{"session_id":"session:2","label":"laio: other"},{"session_id":"session:3","label":"other"}]}"#; fn set_current_session(value: &str) { unsafe { @@ -133,7 +133,7 @@ fn stop_without_a_name_kills_a_live_laio_label_without_a_record() -> TestResult let rex = Harness::new() .json_args( &["session", "ls", "--json"], - r#"{"sessions":[{"session_id":"session:1","label":"laio-work"}]}"#, + r#"{"sessions":[{"session_id":"session:1","label":"laio: work"}]}"#, ) .unit(&["kill", "session:1"]) .build(); @@ -168,7 +168,9 @@ fn stop_without_a_name_returns_ok_when_the_current_session_is_gone() -> TestResu #[test] fn stop_returns_ok_for_a_name_without_a_record_or_a_live_label() -> TestResult { let _guard = env_guard(); - let rex = Harness::new().resolve("laio-work", "not_found", "").build(); + let rex = Harness::new() + .resolve("laio: work", "not_found", "") + .build(); Ok(rex.stop(&Some("work".to_string()), &None, false, false, false)?) } @@ -260,7 +262,7 @@ fn stop_kills_the_resolved_label_when_the_record_is_corrupt() -> TestResult { fs::write(harness.store_dir().join("1.json"), "{ not json")?; let rex = harness - .resolve("laio-work", "resolved", "session:9") + .resolve("laio: work", "resolved", "session:9") .unit(&["kill", "session:9"]) .build(); diff --git a/test/muxer/rex/mux_test/switch.rs b/test/muxer/rex/mux_test/switch.rs index 8eadf8f6..50f097c9 100644 --- a/test/muxer/rex/mux_test/switch.rs +++ b/test/muxer/rex/mux_test/switch.rs @@ -6,7 +6,7 @@ use super::mux_test::*; #[test] fn switch_returns_true_and_skips_attach_when_requested() -> TestResult { let rex = Harness::new() - .resolve("laio-work", "resolved", "session:1") + .resolve("laio: work", "resolved", "session:1") .build(); assert!(rex.switch("work", true)?); @@ -16,7 +16,7 @@ fn switch_returns_true_and_skips_attach_when_requested() -> TestResult { #[test] fn switch_attaches_with_the_full_prefixed_session_id() -> TestResult { let rex = Harness::new() - .resolve("laio-work", "resolved", "session:1") + .resolve("laio: work", "resolved", "session:1") .unit(&["do", "session.select", "session_id=session:1"]) .build(); @@ -27,7 +27,7 @@ fn switch_attaches_with_the_full_prefixed_session_id() -> TestResult { #[test] fn switch_continues_when_the_attach_fails() -> TestResult { let rex = Harness::new() - .resolve("laio-work", "resolved", "session:1") + .resolve("laio: work", "resolved", "session:1") .unit_failing( &["do", "session.select", "session_id=session:1"], "Rex.app is not accepting actions. Turn on Remote Control in its Settings under Rex Server.", @@ -40,20 +40,24 @@ fn switch_continues_when_the_attach_fails() -> TestResult { #[test] fn switch_rejects_an_ambiguous_target_with_the_label() -> TestResult { - let rex = Harness::new().resolve("laio-work", "ambiguous", "").build(); + let rex = Harness::new() + .resolve("laio: work", "ambiguous", "") + .build(); let error = rex .switch("work", true) .err() .ok_or("ambiguity should fail")?; - assert!(error.to_string().contains("laio-work"), "{error}"); + assert!(error.to_string().contains("laio: work"), "{error}"); Ok(()) } #[test] fn switch_returns_false_when_the_target_is_not_found() -> TestResult { - let rex = Harness::new().resolve("laio-work", "not_found", "").build(); + let rex = Harness::new() + .resolve("laio: work", "not_found", "") + .build(); assert!(!rex.switch("work", true)?); Ok(()) diff --git a/test/muxer/rex/session_get_test.rs b/test/muxer/rex/session_get_test.rs index fb9fbee7..a6da24d6 100644 --- a/test/muxer/rex/session_get_test.rs +++ b/test/muxer/rex/session_get_test.rs @@ -10,7 +10,7 @@ use super::mux_test::*; const VIEW: &str = r#"{ "revision": 1, "session_id": "session:1", - "label": "laio-work", + "label": "laio: work", "active_window_id": "w1", "windows": [ { From 02079c4bf13d22b5bf2f38ca7d811d46d9167aa8 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 23:04:27 +0000 Subject: [PATCH 10/16] feat(muxer/rex): make the sidecar store the sole ownership oracle --- README.md | 4 +- docs/content/docs/configuration/lifecycle.md | 2 +- .../docs/configuration/yaml-reference.md | 8 +- .../docs/getting-started/quick-start.md | 2 +- docs/content/docs/reference/cli-commands.md | 2 +- .../content/docs/workflow/managing-configs.md | 2 +- docs/content/docs/workflow/session-export.md | 2 +- src/muxer/rex/client.rs | 15 +- src/muxer/rex/export.rs | 23 +- src/muxer/rex/model.rs | 25 -- src/muxer/rex/mux.rs | 263 ++++++--------- src/muxer/rex/store.rs | 156 +++++++-- test/muxer/rex/client_test.rs | 16 - test/muxer/rex/export_test.rs | 15 +- test/muxer/rex/mux_test.rs | 52 +-- test/muxer/rex/mux_test/session.rs | 14 +- test/muxer/rex/mux_test/start.rs | 186 +++++++---- test/muxer/rex/mux_test/stop.rs | 96 +++--- test/muxer/rex/mux_test/switch.rs | 82 ++--- test/muxer/rex/session_get_test.rs | 14 +- test/muxer/rex/store_test.rs | 314 +++++++++++++++--- 21 files changed, 730 insertions(+), 563 deletions(-) diff --git a/README.md b/README.md index 7aff9643..b11c004b 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ A simple, flexbox-inspired layout and session manager for tmux, with experimenta - **Session serialization** - Export existing tmux, zellij, herdr, and rex sessions to YAML format - **Focus & zoom control** - Pin focus and zoom states in configuration - **Environment & shell customization** - Per-session env vars and shell overrides -- **Multiplexer support** - tmux native; experimental Zellij, herdr, and rex backends, selectable via `--muxer` or `LAIO_MUXER`. On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio: `. +- **Multiplexer support** - tmux native; experimental Zellij, herdr, and rex backends, selectable via `--muxer` or `LAIO_MUXER`. On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session named after the config: laio recognizes its rex sessions by the sidecar store, so labels are plain names. ## Quick Start @@ -258,7 +258,7 @@ laio session yaml > ~/.config/laio/newsession.yaml ## Experimental rex Backend -Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio: `. +Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session named after the config: laio recognizes its rex sessions by the sidecar store, so labels are plain names. - **Attach** runs `rex do session.select session_id=session:`. Remote Control must be enabled in Rex.app under Settings > Rex Server. When the attach fails, the start still succeeds and rex's error is logged as a warning. - **Session records** live in a sidecar store: `LAIO_STATE_DIR` when set (used as-is), otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. diff --git a/docs/content/docs/configuration/lifecycle.md b/docs/content/docs/configuration/lifecycle.md index f3e6ee3c..aa380b7a 100644 --- a/docs/content/docs/configuration/lifecycle.md +++ b/docs/content/docs/configuration/lifecycle.md @@ -188,7 +188,7 @@ windows: ### rex (experimental) -rex runs the whole session in one rex session labelled `laio: `. Lifecycle hooks run in the session path, without the session `env`: rex has no environment store, so `env` is ignored. Pane `style` is ignored as well. Attach runs bare `rex do session.select session_id=`; Remote Control must be enabled in Rex.app under Settings > Rex Server, and a failing attach only logs a warning, so the start still succeeds. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. `laio session yaml` loses pane commands and ignores floating layers. +rex runs the whole session in one rex session named after the config: laio recognizes its rex sessions by the sidecar store, so labels are plain names. Lifecycle hooks run in the session path, without the session `env`: rex has no environment store, so `env` is ignored. Pane `style` is ignored as well. Attach runs bare `rex do session.select session_id=`; Remote Control must be enabled in Rex.app under Settings > Rex Server, and a failing attach only logs a warning, so the start still succeeds. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. `laio session yaml` loses pane commands and ignores floating layers. ## Common Patterns diff --git a/docs/content/docs/configuration/yaml-reference.md b/docs/content/docs/configuration/yaml-reference.md index 1bab3240..d7e32ae2 100644 --- a/docs/content/docs/configuration/yaml-reference.md +++ b/docs/content/docs/configuration/yaml-reference.md @@ -16,10 +16,10 @@ top = false ### Required Fields **`name`** (string) -- Session name used by the multiplexer (the workspace label on herdr, the `laio: ` label prefix on rex) +- Session name used by the multiplexer (the workspace label on herdr, the session label on rex) - Must be unique across all sessions - On herdr, the name must be 1-64 bytes of letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid herdr session name" -- On rex, the name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A `laio: ` label longer than 128 characters fails as well +- On rex, the name must be non-empty; an empty name fails with "Invalid rex session name". A name longer than 128 bytes fails as well - tmux and zellij do not apply this restriction - Example: `"myproject"` @@ -540,7 +540,7 @@ done - See `man tmux` for available style options - Ignored on zellij, herdr, and rex, which have no pane style equivalent -**Note:** On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session labelled `laio: `. +**Note:** On herdr, each laio config runs as a workspace in the dedicated `laio` session. On rex, each laio config runs as one rex session named after the config: laio recognizes its rex sessions by the sidecar store, so labels are plain names. **`flex_direction`** (string: `"row"` or `"column"`) - Layout direction for nested panes @@ -569,7 +569,7 @@ done ## rex (experimental) -Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session labelled `laio: `. +Select rex with `--muxer rex` or `LAIO_MUXER=rex`. Each laio config runs as one rex session named after the config: laio recognizes its rex sessions by the sidecar store, so labels are plain names. - `env` and pane `style` are ignored. - A session with no windows fails with `Session '' has no windows`; each window is capped at 24 blocks and a split depth of 16. diff --git a/docs/content/docs/getting-started/quick-start.md b/docs/content/docs/getting-started/quick-start.md index 0478a63e..0856f98c 100644 --- a/docs/content/docs/getting-started/quick-start.md +++ b/docs/content/docs/getting-started/quick-start.md @@ -25,7 +25,7 @@ laio start myproject > laio targets **tmux** by default. Experimental `zellij`, `herdr`, and `rex` backends are available via `--muxer zellij|herdr|rex` or `LAIO_MUXER` on any command. > -> rex runs one `laio: ` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. `env` and pane `style` are ignored, and `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. +> rex runs one rex session per config, named after the config; laio recognizes its rex sessions by the sidecar store, so labels are plain names. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. `env` and pane `style` are ignored, and `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. This creates a default configuration with: - An editor window that runs `{% raw %}{{ editor | default(value="nvim") }}{% endraw %}` from the template (override with `--var editor=`) diff --git a/docs/content/docs/reference/cli-commands.md b/docs/content/docs/reference/cli-commands.md index c7f42985..595e1b13 100644 --- a/docs/content/docs/reference/cli-commands.md +++ b/docs/content/docs/reference/cli-commands.md @@ -663,7 +663,7 @@ herdr maps one laio config to one workspace inside the dedicated `laio` session. #### rex (experimental) -rex maps one laio config to one rex session labelled `laio: `. The name must be non-empty and use only letters, digits, `.`, `_`, or `-`; anything else fails with "Invalid rex session name". A rendered label longer than 128 characters fails as well. +rex maps one laio config to one rex session named after the config; laio recognizes its rex sessions by the sidecar store, so labels are plain names. The name must be non-empty; an empty name fails with "Invalid rex session name". A name longer than 128 bytes fails as well. **Select rex on every command.** Multiplexer selection is per invocation and defaults to tmux. Pass `--muxer rex` on each laio command, or set `LAIO_MUXER=rex`. Without it, laio targets tmux. diff --git a/docs/content/docs/workflow/managing-configs.md b/docs/content/docs/workflow/managing-configs.md index 7e7f1f90..9c175330 100644 --- a/docs/content/docs/workflow/managing-configs.md +++ b/docs/content/docs/workflow/managing-configs.md @@ -109,7 +109,7 @@ On tmux and zellij this lists every session of the multiplexer, including sessio #### rex (experimental) -rex runs one `laio: ` session per config. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. Session `env` and pane `style` are ignored. `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. +rex runs one rex session per config, named after the config; laio recognizes its rex sessions by the sidecar store, so labels are plain names. Attach needs Remote Control enabled in Rex.app under Settings > Rex Server; when the attach fails, the start still succeeds and rex's error is logged as a warning. Session `env` and pane `style` are ignored. `laio session yaml` loses pane commands and ignores floating layers. Session records live in `LAIO_STATE_DIR` when set, otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. ## Deleting Configurations diff --git a/docs/content/docs/workflow/session-export.md b/docs/content/docs/workflow/session-export.md index a16f948c..d4fc05e0 100644 --- a/docs/content/docs/workflow/session-export.md +++ b/docs/content/docs/workflow/session-export.md @@ -49,7 +49,7 @@ laio session yaml > .laio.yaml The export captures: -- **Session name** - On tmux and zellij, the current session name; on herdr, the label of the workspace laio runs in, which equals the laio session name for laio-managed workspaces; on rex, the laio name from the sidecar record, otherwise the `laio: ` label with its prefix stripped +- **Session name** - On tmux and zellij, the current session name; on herdr, the label of the workspace laio runs in, which equals the laio session name for laio-managed workspaces; on rex, the laio name from the sidecar record, and the export fails when no record exists - **Window structure** - All windows and their names - **Pane layout** - Splits, sizes, and arrangement - **Working directories** - Current path for each pane diff --git a/src/muxer/rex/client.rs b/src/muxer/rex/client.rs index 8a50e898..630eb9c2 100644 --- a/src/muxer/rex/client.rs +++ b/src/muxer/rex/client.rs @@ -10,7 +10,7 @@ use crate::common::muxer::Client; use super::model::{ ClientListOutput, CreateOutput, CreateRequest, FocusOutput, PwdOutput, SessionListOutput, - SessionView, TargetResolveOutput, + SessionView, }; #[derive(Debug)] @@ -86,19 +86,6 @@ impl RexClient { ) } - pub(crate) fn target_resolve( - &self, - kinds: &[&str], - queries: &[&str], - ) -> Result { - let payload = to_json(&json!({"kinds": kinds, "queries": queries}))?; - - self.run_json( - "target_resolve", - cmd_basic!("rex", args = ["api", "call", "target.resolve", payload]), - ) - } - pub(crate) fn client_list(&self) -> Result { self.run_json( "client_list", diff --git a/src/muxer/rex/export.rs b/src/muxer/rex/export.rs index a2199585..c57bf12e 100644 --- a/src/muxer/rex/export.rs +++ b/src/muxer/rex/export.rs @@ -8,7 +8,6 @@ use crate::common::config::{FlexDirection, Pane, Session, Window}; use crate::common::path::relative_path; use super::model::{LayerView, SessionView, ViewNode, ViewSplit, WindowView}; -use super::mux::LABEL_PREFIX; const TILED_KIND: &str = "tiled"; const HORIZONTAL: &str = "horizontal"; @@ -65,7 +64,7 @@ pub(crate) fn session_from_view( } Ok(Session { - name: session_name(view, fallback_name)?, + name: session_name(fallback_name)?, path: session_path, startup: Vec::new(), startup_script: None, @@ -175,22 +174,10 @@ fn common_path(paths: &[&str]) -> Result { Ok(prefix) } -fn session_name(view: &SessionView, fallback: Option<&str>) -> Result { - if let Some(name) = fallback { - return Ok(name.to_string()); - } - - let label = view - .label - .as_deref() - .ok_or_else(|| miette!("Cannot determine the rex session name"))?; - - log::warn!("No laio record for rex session '{label}'; deriving the name from the label"); - - Ok(label - .strip_prefix(LABEL_PREFIX) - .unwrap_or(label) - .to_string()) +fn session_name(fallback: Option<&str>) -> Result { + fallback + .map(str::to_string) + .ok_or_else(|| miette!("Cannot determine the rex session name")) } fn window_from_view<'a>( diff --git a/src/muxer/rex/model.rs b/src/muxer/rex/model.rs index 20451c2e..d70e7e83 100644 --- a/src/muxer/rex/model.rs +++ b/src/muxer/rex/model.rs @@ -79,31 +79,6 @@ pub(crate) struct BlockRef { pub(crate) owner: Option, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub(crate) struct TargetResolveOutput { - pub(crate) results: Option>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub(crate) struct ResolveResult { - pub(crate) query: String, - pub(crate) status: String, - pub(crate) target: Option, - pub(crate) candidates: Option>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub(crate) struct Candidate { - pub(crate) kind: String, - pub(crate) label: String, - pub(crate) session_id: Option, - pub(crate) window_id: Option, - pub(crate) block_id: Option, - pub(crate) ordinal: Option, - #[serde(rename = "where")] - pub(crate) r#where: Option, -} - #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] pub(crate) struct PwdOutput { pub(crate) pwd: String, diff --git a/src/muxer/rex/mux.rs b/src/muxer/rex/mux.rs index 60c3916f..a317b669 100644 --- a/src/muxer/rex/mux.rs +++ b/src/muxer/rex/mux.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use miette::{Result, bail, miette}; +use miette::{Result, bail}; use crate::app::manager::session::manager::{LAIO_CONFIG, LAIO_VARS, decode_variables}; use crate::cmd_basic; @@ -19,15 +19,11 @@ use crate::muxer::rex::{ }; use super::client::RexClient; -use super::model::{ClientListOutput, CreateOutput, ResolveResult}; +use super::model::{ClientListOutput, CreateOutput}; use super::store::{RexSessionRecord, RexSessionStore, laio_state_dir}; -pub(super) const LABEL_PREFIX: &str = "laio: "; const MAX_LABEL_LEN: usize = 128; -const SESSION_KIND: &str = "session"; const REX_SESSION_ENV: &str = "REX_SESSION"; -const RESOLVED: &str = "resolved"; -const AMBIGUOUS: &str = "ambiguous"; pub(crate) struct Rex { client: RexClient, @@ -48,16 +44,24 @@ impl Rex { } } - fn write_record( - &self, - rex_session_id: &str, - label: &str, - session: &Session, - env_vars: &[(&str, &str)], - ) { + fn ensure_record_key_is_free(&self, name: &str) -> Result<()> { + match self.store.stored_name_at_key(name) { + Ok(Some(stored)) if stored != name => { + bail!( + "Refusing to start '{name}': its rex session record key already belongs to '{stored}'. Rename one of the two sessions." + ); + } + Ok(_) => Ok(()), + Err(error) => { + log::warn!("Failed to check the rex session record for '{name}': {error}"); + Ok(()) + } + } + } + + fn write_record(&self, rex_session_id: &str, session: &Session, env_vars: &[(&str, &str)]) { let record = RexSessionRecord { rex_session_id: rex_session_id.to_string(), - rex_label: label.to_string(), laio_name: session.name.clone(), config_path: env_value(env_vars, LAIO_CONFIG).to_string(), variables: env_value(env_vars, LAIO_VARS).to_string(), @@ -72,9 +76,9 @@ impl Rex { } } - fn delete_record(&self, rex_session_id: &str) { - if let Err(error) = self.store.delete_by_session(rex_session_id) { - log::warn!("Failed to delete the rex session record '{rex_session_id}': {error}"); + fn delete_record(&self, name: &str) { + if let Err(error) = self.store.delete_by_name(name) { + log::warn!("Failed to delete the rex session record '{name}': {error}"); } } @@ -90,18 +94,13 @@ impl Rex { fn run_shutdown_hooks( &self, name: &str, - record: Option<&RexSessionRecord>, + record: &RexSessionRecord, session: &Option, ) -> Result<()> { if let Some(session) = session { return self.run_shutdown_commands(session); } - let Some(record) = record else { - log::warn!("No usable rex session record for '{name}'; skipping shutdown commands"); - return Ok(()); - }; - let variables = decode_record_variables(name, &record.variables); let session = Session::from_config( &resolve_symlink(&to_absolute_path(&record.config_path)?)?, @@ -120,22 +119,6 @@ impl Rex { self.client.run_commands(&commands, &session.path) } - fn resolve_session(&self, name: &str) -> Result> { - let label = laio_label(name)?; - let output = self - .client - .target_resolve(&[SESSION_KIND], &[label.as_str()])?; - - let Some(result) = output - .results - .and_then(|results| results.into_iter().next()) - else { - return Ok(None); - }; - - resolution(&label, &result) - } - fn attach(&self, rex_session_id: &str, skip_attach: bool) { if skip_attach { return; @@ -168,14 +151,6 @@ impl Rex { Ok(()) } - fn stop_target(&self, name: &str, record: Option<&RexSessionRecord>) -> Result> { - if let Some(record) = record { - return Ok(Some(record.rex_session_id.clone())); - } - - self.resolve_session(name) - } - fn stop_named( &self, name: &str, @@ -183,17 +158,15 @@ impl Rex { skip_cmds: bool, stop_other: bool, ) -> Result<()> { - let record = self.store.read_by_name(name)?; - - let Some(rex_session_id) = self.stop_target(name, record.as_ref())? else { + let Some(record) = self.store.read_by_name(name)? else { log::debug!("Not a laio session: {name}"); return Ok(()); }; self.stop_resolved( - name, - &rex_session_id, - record.as_ref(), + &record.laio_name, + &record.rex_session_id, + &record, session, skip_cmds, stop_other, @@ -207,47 +180,33 @@ impl Rex { skip_cmds: bool, stop_other: bool, ) -> Result<()> { - let record = self.store.read_by_session(rex_session_id)?; - - if let Some(record) = &record { - return self.stop_resolved( - &record.laio_name, - rex_session_id, - Some(record), - session, - skip_cmds, - stop_other, - ); - } - - let Some(label) = self.live_label(rex_session_id)? else { - log::debug!("Not a laio session: {rex_session_id}"); + let Some(record) = self.store.find_by_session_id(rex_session_id)? else { + log::debug!("No laio record for the current rex session: {rex_session_id}"); return Ok(()); }; - let Some(name) = label.strip_prefix(LABEL_PREFIX) else { - log::debug!("Not a laio session: {label}"); - return Ok(()); - }; - - self.stop_resolved(name, rex_session_id, None, session, skip_cmds, stop_other) + self.stop_resolved( + &record.laio_name, + rex_session_id, + &record, + session, + skip_cmds, + stop_other, + ) } - fn live_label(&self, rex_session_id: &str) -> Result> { + fn name_from_session_id(&self, rex_session_id: &str) -> Result> { Ok(self - .client - .session_list()? - .sessions - .into_iter() - .find(|session| session.session_id == rex_session_id) - .map(|session| session.label)) + .store + .find_by_session_id(rex_session_id)? + .map(|record| record.laio_name)) } fn stop_resolved( &self, name: &str, rex_session_id: &str, - record: Option<&RexSessionRecord>, + record: &RexSessionRecord, session: &Option, skip_cmds: bool, stop_other: bool, @@ -261,7 +220,7 @@ impl Rex { }; let kill = self.kill_session(rex_session_id); - self.delete_record(rex_session_id); + self.delete_record(name); hooks.and(kill) } @@ -269,15 +228,17 @@ impl Rex { fn sweep(&self, skip_cmds: bool, current: Option<&str>) -> Result<()> { log::trace!("Closing all/other laio rex sessions."); - let sessions = self.client.session_list()?.sessions; - let live_ids: Vec = sessions - .iter() - .map(|session| session.session_id.clone()) + let live_ids: Vec = self + .client + .session_list()? + .sessions + .into_iter() + .map(|session| session.session_id) .collect(); self.store.prune(&live_ids)?; - let mut targets: Vec<(String, String, Option)> = self + let targets: Vec<(String, String, RexSessionRecord)> = self .store .list()? .into_iter() @@ -286,38 +247,22 @@ impl Rex { ( record.laio_name.clone(), record.rex_session_id.clone(), - Some(record), + record, ) }) .collect(); - for session in &sessions { - let Some(name) = session.label.strip_prefix(LABEL_PREFIX) else { - continue; - }; - - let recorded = targets - .iter() - .any(|(_, rex_session_id, _)| rex_session_id == &session.session_id); - - if recorded || Some(session.session_id.as_str()) == current { - continue; - } - - targets.push((name.to_string(), session.session_id.clone(), None)); - } - for (name, rex_session_id, record) in &targets { log::trace!("Closing rex session: {name}"); let hooks = if skip_cmds { Ok(()) } else { - self.run_shutdown_hooks(name, record.as_ref(), &None) + self.run_shutdown_hooks(name, record, &None) }; let kill = self.kill_session(rex_session_id); - self.delete_record(rex_session_id); + self.delete_record(name); hooks.and(kill)?; } @@ -334,17 +279,19 @@ impl Multiplexer for Rex { skip_attach: bool, skip_cmds: bool, ) -> Result<()> { + self.ensure_record_key_is_free(&session.name)?; + if self.switch(&session.name, skip_attach)? { return Ok(()); } let label = laio_label(&session.name)?; let (mut request, leaves) = build_create_request(session)?; - request.label = Some(label.clone()); + request.label = Some(label); let created = self.client.session_create(&request)?; - self.write_record(&created.session_id, &label, session, env_vars); + self.write_record(&created.session_id, session, env_vars); if !skip_cmds { self.run_startup_hooks(session)?; @@ -460,50 +407,55 @@ impl Multiplexer for Rex { } fn list_sessions(&self) -> Result> { - let sessions = self.client.session_list()?.sessions; - let live_ids: Vec = sessions - .iter() - .map(|session| session.session_id.clone()) + let live_ids: HashSet = self + .client + .session_list()? + .sessions + .into_iter() + .map(|session| session.session_id) .collect(); - self.store.prune(&live_ids)?; + let live: Vec = live_ids.iter().cloned().collect(); + self.store.prune(&live)?; let attached = attached_session_ids(&self.client.client_list()?); - let records = self.store.list()?; - let mut infos: Vec = records - .iter() + Ok(self + .store + .list()? + .into_iter() + .filter(|record| live_ids.contains(&record.rex_session_id)) .map(|record| { - SessionInfo::active( - record.laio_name.clone(), - attached.contains(&record.rex_session_id), - ) + SessionInfo::active(record.laio_name, attached.contains(&record.rex_session_id)) }) - .collect(); - - for session in &sessions { - let Some(name) = session.label.strip_prefix(LABEL_PREFIX) else { - continue; - }; - - let recorded = records - .iter() - .any(|record| record.rex_session_id == session.session_id); - - if !recorded { - infos.push(SessionInfo::inactive(name.to_string())); - } - } - - Ok(infos) + .collect()) } fn switch(&self, name: &str, skip_attach: bool) -> Result { - let Some(rex_session_id) = self.resolve_session(name)? else { + let record = match self.store.read_by_name(name) { + Ok(record) => record, + Err(error) => { + log::warn!("Failed to read the rex session record for '{name}': {error}"); + return Ok(false); + } + }; + + let Some(record) = record else { return Ok(false); }; - self.attach(&rex_session_id, skip_attach); + let live = self + .client + .session_list()? + .sessions + .iter() + .any(|session| session.session_id == record.rex_session_id); + + if !live { + return Ok(false); + } + + self.attach(&record.rex_session_id, skip_attach); Ok(true) } @@ -529,10 +481,7 @@ impl Multiplexer for Rex { } } - let name = self - .store - .read_by_session(&rex_session_id)? - .map(|record| record.laio_name); + let name = self.name_from_session_id(&rex_session_id)?; session_from_view(&view, &pwds, name.as_deref()) } @@ -571,34 +520,16 @@ fn decode_record_variables(name: &str, encoded: &str) -> Option> { } } -fn resolution(label: &str, result: &ResolveResult) -> Result> { - match result.status.as_str() { - AMBIGUOUS => Err(miette!("Multiple rex sessions match the label '{label}'")), - RESOLVED => Ok(result - .target - .as_ref() - .and_then(|target| target.session_id.clone())), - _ => Ok(None), - } -} - fn laio_label(name: &str) -> Result { - let valid = !name.is_empty() - && name - .chars() - .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-')); - - if !valid { + if name.is_empty() { bail!("Invalid rex session name '{name}'"); } - let label = format!("{LABEL_PREFIX}{name}"); - - if label.len() > MAX_LABEL_LEN { - bail!("rex session label '{label}' exceeds {MAX_LABEL_LEN} characters"); + if name.len() > MAX_LABEL_LEN { + bail!("rex session label '{name}' exceeds {MAX_LABEL_LEN} bytes"); } - Ok(label) + Ok(name.to_string()) } fn env_value<'a>(env_vars: &'a [(&str, &str)], key: &str) -> &'a str { diff --git a/src/muxer/rex/store.rs b/src/muxer/rex/store.rs index 5ba2c713..9375fd96 100644 --- a/src/muxer/rex/store.rs +++ b/src/muxer/rex/store.rs @@ -6,6 +6,7 @@ use std::{ use miette::{Result, miette}; use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; use crate::common::path::home_dir; @@ -13,13 +14,12 @@ const STATE_DIR_ENV: &str = "LAIO_STATE_DIR"; const XDG_STATE_HOME_ENV: &str = "XDG_STATE_HOME"; const APP_DIR: &str = "laio"; const REX_DIR: &str = "rex"; -const SESSION_PREFIX: &str = "session:"; const RECORD_EXTENSION: &str = "json"; +const KEY_BYTES: usize = 4; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct RexSessionRecord { pub(crate) rex_session_id: String, - pub(crate) rex_label: String, pub(crate) laio_name: String, pub(crate) config_path: String, pub(crate) variables: String, @@ -36,11 +36,32 @@ impl RexSessionStore { Self { dir } } + /// A record lives at `/.json`, where `key` is the first 8 lowercase + /// hex digits of SHA-256 over the verbatim laio session name. + /// + /// Two distinct names can share a key. A collision is never resolved + /// silently: the write refuses to replace a record that belongs to another + /// name. The start path checks the key before it creates the session; a + /// collision that appears in the race window between that check and this + /// write is logged by the caller and the write is skipped, so the stored + /// record keeps its owner. Concurrent writes to the same name are + /// last-writer-wins; the atomic temporary file plus rename keeps every record + /// whole. pub(crate) fn write_record(&self, record: &RexSessionRecord) -> Result<()> { + if let Some(existing) = self.read_key_file(&record_key(&record.laio_name))? + && existing.laio_name != record.laio_name + { + return Err(miette!( + "Refusing to overwrite the rex session record of '{}' with '{}': both names share the record key", + existing.laio_name, + record.laio_name + )); + } + fs::create_dir_all(&self.dir) .map_err(|error| miette!("failed to create '{}': {error}", self.dir.display()))?; - let path = self.record_path(&record.rex_session_id); + let path = self.key_path(&record_key(&record.laio_name)); let tmp_path = path.with_extension(format!("{RECORD_EXTENSION}.tmp")); let json = serde_json::to_string_pretty(record) .map_err(|error| miette!("failed to serialise rex session record: {error}"))?; @@ -52,41 +73,62 @@ impl RexSessionStore { } pub(crate) fn read_by_name(&self, laio_name: &str) -> Result> { + let Some(record) = self.read_key_file(&record_key(laio_name))? else { + return Ok(None); + }; + + if record.laio_name != laio_name { + log::warn!( + "Ignoring the rex session record '{}': it belongs to another laio name", + record.laio_name + ); + + return Ok(None); + } + + Ok(Some(record)) + } + + pub(crate) fn find_by_session_id( + &self, + rex_session_id: &str, + ) -> Result> { Ok(self - .records()? + .list()? .into_iter() - .find(|record| record.laio_name == laio_name)) + .find(|record| record.rex_session_id == rex_session_id)) } - pub(crate) fn read_by_session(&self, rex_session_id: &str) -> Result> { - let path = self.record_path(rex_session_id); - - match fs::read_to_string(&path) { - Ok(json) => Ok(parse_record(&path, &json)), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(None), - Err(error) => Err(miette!("failed to read '{}': {error}", path.display())), - } + pub(crate) fn stored_name_at_key(&self, laio_name: &str) -> Result> { + Ok(self + .read_key_file(&record_key(laio_name))? + .map(|record| record.laio_name)) } - pub(crate) fn delete_by_session(&self, rex_session_id: &str) -> Result<()> { - let path = self.record_path(rex_session_id); + pub(crate) fn delete_by_name(&self, laio_name: &str) -> Result<()> { + if let Some(record) = self.read_key_file(&record_key(laio_name))? + && record.laio_name != laio_name + { + log::warn!( + "Refusing to delete the rex session record '{}': it belongs to another laio name", + record.laio_name + ); - match fs::remove_file(&path) { - Ok(()) => Ok(()), - Err(error) if error.kind() == ErrorKind::NotFound => Ok(()), - Err(error) => Err(miette!("failed to delete '{}': {error}", path.display())), + return Ok(()); } + + delete_file(&self.key_path(&record_key(laio_name))) } pub(crate) fn prune(&self, live_session_ids: &[String]) -> Result> { let mut pruned = Vec::new(); - for record in self.records()? { + for (path, record) in self.scanned_records()? { if live_session_ids.contains(&record.rex_session_id) { continue; } - self.delete_by_session(&record.rex_session_id)?; + delete_file(&path)?; pruned.push(record.rex_session_id); } @@ -94,10 +136,24 @@ impl RexSessionStore { } pub(crate) fn list(&self) -> Result> { - self.records() + Ok(self + .scanned_records()? + .into_iter() + .map(|(_, record)| record) + .collect()) } - fn records(&self) -> Result> { + fn read_key_file(&self, key: &str) -> Result> { + let path = self.key_path(key); + + match fs::read_to_string(&path) { + Ok(json) => Ok(parse_record(&path, &json)), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(None), + Err(error) => Err(miette!("failed to read '{}': {error}", path.display())), + } + } + + fn scanned_records(&self) -> Result> { let entries = match fs::read_dir(&self.dir) { Ok(entries) => entries, Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()), @@ -115,16 +171,58 @@ impl RexSessionStore { Ok(paths .iter() - .filter_map(|path| read_record_file(path)) + .filter_map(|path| read_record_file(path).map(|record| self.migrate(path, record))) .collect()) } - fn record_path(&self, rex_session_id: &str) -> PathBuf { - let stem = rex_session_id - .strip_prefix(SESSION_PREFIX) - .unwrap_or(rex_session_id); + fn migrate(&self, path: &Path, record: RexSessionRecord) -> (PathBuf, RexSessionRecord) { + let key = record_key(&record.laio_name); + + if path.file_stem().and_then(|stem| stem.to_str()) == Some(key.as_str()) { + return (path.to_path_buf(), record); + } + + if let Err(error) = self.write_record(&record) { + log::warn!( + "Failed to migrate the rex session record '{}': {error}", + path.display() + ); + + return (path.to_path_buf(), record); + } + + if let Err(error) = fs::remove_file(path) { + log::warn!( + "Failed to remove the legacy rex session record '{}': {error}", + path.display() + ); + } + + (self.key_path(&key), record) + } + + fn key_path(&self, key: &str) -> PathBuf { + self.dir.join(format!("{key}.{RECORD_EXTENSION}")) + } +} + +fn record_key(laio_name: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(laio_name.as_bytes()); + let digest = hasher.finalize(); + + digest + .iter() + .take(KEY_BYTES) + .map(|byte| format!("{byte:02x}")) + .collect() +} - self.dir.join(format!("{stem}.{RECORD_EXTENSION}")) +fn delete_file(path: &Path) -> Result<()> { + match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(()), + Err(error) => Err(miette!("failed to delete '{}': {error}", path.display())), } } diff --git a/test/muxer/rex/client_test.rs b/test/muxer/rex/client_test.rs index a2ccf464..c4a7e4d5 100644 --- a/test/muxer/rex/client_test.rs +++ b/test/muxer/rex/client_test.rs @@ -279,22 +279,6 @@ fn session_list_reads_cli_json_output() -> TestResult { Ok(()) } -#[test] -fn target_resolve_sends_kinds_and_queries() -> TestResult { - let client = api_client( - "target.resolve", - json!({"kinds": ["session"], "queries": ["laio: probe"]}), - r#"{"results":[{"query":"laio: probe","status":"not_found","candidates":[]}]}"#, - )?; - - let output = client.target_resolve(&["session"], &["laio: probe"])?; - - let results = output.results.ok_or("should have results")?; - assert_eq!(results.len(), 1); - assert_eq!(results[0].status, "not_found"); - Ok(()) -} - #[test] fn client_list_exposes_session_ids() -> TestResult { let client = string_client( diff --git a/test/muxer/rex/export_test.rs b/test/muxer/rex/export_test.rs index f7ea9a45..028bd66d 100644 --- a/test/muxer/rex/export_test.rs +++ b/test/muxer/rex/export_test.rs @@ -308,7 +308,7 @@ fn floating_layers_are_ignored() -> TestResult { } #[test] -fn a_missing_record_falls_back_to_the_label_without_the_laio_prefix() -> TestResult { +fn a_missing_record_fails_to_name_the_session() -> TestResult { let layout = leaf("b1"); let view = view( "laio: work", @@ -316,11 +316,16 @@ fn a_missing_record_falls_back_to_the_label_without_the_laio_prefix() -> TestRes vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], ); - let session = session_from_view(&view, &pwds(&[("b1", "/opt/project")]), None)?; + let error = session_from_view(&view, &pwds(&[("b1", "/opt/project")]), None) + .err() + .ok_or("a missing record should fail the export")?; - assert_eq!(session.name, "work"); - assert_eq!(session.path, "/opt/project"); - assert_eq!(session.windows[0].panes[0].path, "."); + assert!( + error + .to_string() + .contains("Cannot determine the rex session name"), + "{error}" + ); Ok(()) } diff --git a/test/muxer/rex/mux_test.rs b/test/muxer/rex/mux_test.rs index ec5985d6..7b09b3ac 100644 --- a/test/muxer/rex/mux_test.rs +++ b/test/muxer/rex/mux_test.rs @@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; -use serde_json::{Value, json}; +use serde_json::Value; use crate::common::cmd::{ Type, @@ -17,6 +17,8 @@ use crate::muxer::rex::store::{RexSessionRecord, RexSessionStore}; pub(super) type TestResult = core::result::Result>; pub(super) type Log = Arc>>; +pub(super) const WORK_KEY: &str = "00e13ed7"; + static NEXT_DIR: AtomicU64 = AtomicU64::new(0); static ENV_LOCK: Mutex<()> = Mutex::new(()); @@ -89,7 +91,6 @@ pub(super) fn session_of(yaml: &str) -> TestResult { pub(super) fn record(rex_session_id: &str, laio_name: &str) -> RexSessionRecord { RexSessionRecord { rex_session_id: rex_session_id.to_string(), - rex_label: format!("laio: {laio_name}"), laio_name: laio_name.to_string(), config_path: format!("/tmp/{laio_name}.yaml"), variables: format!("session_name={laio_name}&path=%2Ftmp"), @@ -136,53 +137,6 @@ impl Harness { Ok(()) } - pub(super) fn resolve(mut self, label: &str, status: &str, rex_session_id: &str) -> Self { - let payload = json!({"kinds": ["session"], "queries": [label]}); - let output = if status == "resolved" { - json!({ - "results": [{ - "query": label, - "status": status, - "target": { - "kind": "session", - "label": label, - "session_id": rex_session_id - } - }] - }) - } else { - json!({ - "results": [{ "query": label, "status": status, "candidates": [] }] - }) - } - .to_string(); - - self.cmd_string - .expect_run() - .times(1) - .withf(move |cmd| { - api_payload(cmd, "target.resolve").is_some_and(|actual| actual == payload) - }) - .returning(move |_| Ok(output.clone())); - - self - } - - pub(super) fn resolve_failing(mut self, label: &str, detail: &str) -> Self { - let payload = json!({"kinds": ["session"], "queries": [label]}); - let detail = detail.to_string(); - - self.cmd_string - .expect_run() - .times(1) - .withf(move |cmd| { - api_payload(cmd, "target.resolve").is_some_and(|actual| actual == payload) - }) - .returning(move |_| Err(miette::miette!(detail.clone()))); - - self - } - pub(super) fn create(mut self, label: &str, output: &str, windows: usize) -> Self { let label = label.to_string(); let output = output.to_string(); diff --git a/test/muxer/rex/mux_test/session.rs b/test/muxer/rex/mux_test/session.rs index a48b55f6..583d303c 100644 --- a/test/muxer/rex/mux_test/session.rs +++ b/test/muxer/rex/mux_test/session.rs @@ -3,7 +3,7 @@ use crate::common::session_info::SessionStatus; use super::mux_test::*; -const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"laio: work"},{"session_id":"session:2","label":"laio: extra"},{"session_id":"session:3","label":"other"}]}"#; +const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"work"},{"session_id":"session:2","label":"extra"},{"session_id":"session:3","label":"other"}]}"#; #[test] fn get_session_config_path_returns_the_recorded_path() -> TestResult { @@ -48,7 +48,7 @@ fn get_session_variables_returns_none_for_undecodable_variables() -> TestResult } #[test] -fn list_sessions_prunes_dead_records_and_marks_unrecorded_labels_inactive() -> TestResult { +fn list_sessions_reports_only_live_recorded_sessions() -> TestResult { let harness = Harness::new(); harness.seed(&record("session:1", "work"))?; harness.seed(&record("session:9", "stale"))?; @@ -65,15 +65,9 @@ fn list_sessions_prunes_dead_records_and_marks_unrecorded_labels_inactive() -> T .map(|info| (info.name.as_str(), info.status)) .collect(); - assert_eq!( - rows, - [ - ("work", SessionStatus::Active), - ("extra", SessionStatus::Inactive) - ] - ); + assert_eq!(rows, [("work", SessionStatus::Active)]); assert!( - store.read_by_session("session:9")?.is_none(), + store.read_by_name("stale")?.is_none(), "the stale record file must be deleted" ); Ok(()) diff --git a/test/muxer/rex/mux_test/start.rs b/test/muxer/rex/mux_test/start.rs index abd0225d..f3c904f6 100644 --- a/test/muxer/rex/mux_test/start.rs +++ b/test/muxer/rex/mux_test/start.rs @@ -25,20 +25,19 @@ windows: const MULTI_CREATE: &str = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2},{"window_id":"window:2","block_ids":["block:2"],"revision":3}]}"#; #[test] -fn start_creates_one_session_with_the_laio_label_and_records_it_before_sending() -> TestResult { +fn start_creates_one_session_with_the_raw_name_and_records_it_before_sending() -> TestResult { let harness = Harness::new(); let check_dir = harness.store_dir().to_path_buf(); let check = Arc::new(move || { assert!( - check_dir.join("1.json").is_file(), + check_dir.join(format!("{WORK_KEY}.json")).is_file(), "the sidecar record must exist before the first send" ); }); let store = harness.store(); let rex = harness - .resolve("laio: work", "not_found", "") - .create("laio: work", MULTI_CREATE, 2) + .create("work", MULTI_CREATE, 2) .unit_asserting( &[ "send", @@ -65,21 +64,49 @@ fn start_creates_one_session_with_the_laio_label_and_records_it_before_sending() .ok_or("start should write the sidecar record")?; assert_eq!(record.rex_session_id, "session:1"); - assert_eq!(record.rex_label, "laio: work"); + assert_eq!(record.laio_name, "work"); assert_eq!(record.config_path, "/tmp/work.yaml"); assert_eq!(record.variables, "a=b"); Ok(()) } #[test] -fn start_returns_ok_without_creating_when_the_session_already_exists() -> TestResult { - let rex = Harness::new() - .resolve("laio: work", "resolved", "session:1") +fn start_returns_ok_without_creating_when_the_recorded_session_is_live() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let rex = harness + .json_args( + &["session", "ls", "--json"], + r#"{"sessions":[{"session_id":"session:1","label":"work"}]}"#, + ) .build(); Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, false)?) } +#[test] +fn start_creates_a_new_session_when_the_recorded_session_is_dead() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:9", "work"))?; + let store = harness.store(); + + let rex = harness + .json_args(&["session", "ls", "--json"], r#"{"sessions":[]}"#) + .create("work", MULTI_CREATE, 2) + .build(); + + rex.start(&session_of(MULTI_WINDOW)?, &[], true, true)?; + + assert_eq!( + store + .read_by_name("work")? + .map(|record| record.rex_session_id), + Some("session:1".to_string()) + ); + Ok(()) +} + #[test] fn start_sends_one_batch_per_leaf_with_a_trailing_newline() -> TestResult { let session = session_of( @@ -104,8 +131,7 @@ windows: let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2"],"revision":2}]}"#; let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .create("laio: work", create, 1) + .create("work", create, 1) .unit(&[ "send", "-s", @@ -148,8 +174,7 @@ windows: let sent_at: Arc>> = Arc::new(Mutex::new(None)); let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .create("laio: work", create, 1) + .create("work", create, 1) .unit_at( &["send", "-s", "session:1", "-b", "block:1", "--", "ls\n"], Arc::clone(&sent_at), @@ -174,7 +199,6 @@ fn start_returns_err_without_a_record_when_session_create_fails() -> TestResult let store = harness.store(); let rex = harness - .resolve("laio: work", "not_found", "") .create_failing("rex session_create failed: bad_request") .build(); @@ -185,18 +209,6 @@ fn start_returns_err_without_a_record_when_session_create_fails() -> TestResult Ok(()) } -#[test] -fn start_returns_err_when_target_resolve_fails() -> TestResult { - let rex = Harness::new() - .resolve_failing("laio: work", "rex target_resolve failed: not_found") - .build(); - - let result = rex.start(&session_of(MULTI_WINDOW)?, &[], true, true); - - assert!(result.is_err()); - Ok(()) -} - #[test] fn start_continues_when_one_send_fails() -> TestResult { let session = session_of( @@ -218,8 +230,7 @@ windows: let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1","block:2"],"revision":2}]}"#; let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .create("laio: work", create, 1) + .create("work", create, 1) .unit_failing( &[ "send", @@ -240,20 +251,14 @@ windows: #[test] fn start_continues_when_session_select_fails() -> TestResult { - let create = r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2}]}"#; + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; - let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .create("laio: work", create, 2) - .unit(&[ - "send", - "-s", - "session:1", - "-b", - "block:1", - "--", - "echo one\n", - ]) + let rex = harness + .json_args( + &["session", "ls", "--json"], + r#"{"sessions":[{"session_id":"session:1","label":"work"}]}"#, + ) .unit_failing( &["do", "session.select", "session_id=session:1"], "Rex.app is not accepting actions. Turn on Remote Control in its Settings under Rex Server.", @@ -265,10 +270,7 @@ fn start_continues_when_session_select_fails() -> TestResult { #[test] fn start_skips_the_hooks_and_the_sends_when_skip_cmds_is_set() -> TestResult { - let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .create("laio: work", MULTI_CREATE, 2) - .build(); + let rex = Harness::new().create("work", MULTI_CREATE, 2).build(); Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, true)?) } @@ -291,8 +293,7 @@ windows: let log: Log = Arc::new(Mutex::new(Vec::new())); let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .create("laio: work", create, 1) + .create("work", create, 1) .json_recording( "session.focus_block", json!({"session_id": "session:1", "block_id": "block:2"}), @@ -327,8 +328,7 @@ windows: )?; let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .create("laio: work", MULTI_CREATE, 2) + .create("work", MULTI_CREATE, 2) .json_recording( "session.focus_window", json!({"session_id": "session:1", "window_id": "window:2"}), @@ -342,26 +342,56 @@ windows: } #[test] -fn start_rejects_a_name_outside_the_laio_charset() -> TestResult { - let rex = Harness::new().build(); +fn start_accepts_a_unicode_name_and_records_it_verbatim() -> TestResult { + let harness = Harness::new(); + let store = harness.store(); + let rex = harness.create("Über-Foo", MULTI_CREATE, 2).build(); - let result = rex.start( - &session_of("\nname: bad/name\npath: /tmp\nwindows:\n - name: main\n")?, + rex.start( + &session_of("\nname: Über-Foo\npath: /tmp\nwindows:\n - name: main\n - name: logs\n")?, &[], true, true, - ); + )?; - assert!(result.is_err()); + let record = store + .read_by_name("Über-Foo")? + .ok_or("start should record the unicode name")?; + + assert_eq!(record.laio_name, "Über-Foo"); + Ok(()) +} + +#[test] +fn start_rejects_an_empty_name() -> TestResult { + let rex = Harness::new().build(); + + let error = rex + .start( + &session_of("\nname: ''\npath: /tmp\nwindows:\n - name: main\n")?, + &[], + true, + true, + ) + .err() + .ok_or("an empty name should fail")?; + + assert!( + error.to_string().contains("Invalid rex session name"), + "{error}" + ); Ok(()) } #[test] -fn start_accepts_a_name_at_the_label_limit_and_rejects_one_over() -> TestResult { - let allowed = "a".repeat(122); - let label = format!("laio: {allowed}"); +fn start_accepts_a_name_at_the_128_byte_limit_and_rejects_one_over() -> TestResult { + let allowed = "Ü".repeat(64); let rex = Harness::new() - .resolve(&label, "resolved", "session:1") + .create( + &allowed, + r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2}]}"#, + 1, + ) .build(); rex.start( @@ -373,7 +403,7 @@ fn start_accepts_a_name_at_the_label_limit_and_rejects_one_over() -> TestResult true, )?; - let rejected = "b".repeat(123); + let rejected = "b".repeat(129); let rex = Harness::new().build(); let error = rex .start( @@ -397,10 +427,40 @@ fn start_continues_when_the_record_cannot_be_written() -> TestResult { let blocked = harness.store_dir().to_path_buf(); fs::write(&blocked, "not a directory")?; - let rex = harness - .resolve("laio: work", "not_found", "") - .create("laio: work", MULTI_CREATE, 2) - .build(); + let rex = harness.create("work", MULTI_CREATE, 2).build(); Ok(rex.start(&session_of(MULTI_WINDOW)?, &[], true, true)?) } + +#[test] +fn start_bails_before_creating_anything_when_the_record_key_belongs_to_another_name() -> TestResult +{ + let harness = Harness::new(); + harness.seed(&record("session:1", "probe-1803"))?; + let store = harness.store(); + let rex = harness.build(); + + let error = rex + .start( + &session_of("\nname: probe-89065\npath: /tmp\nwindows:\n - name: main\n")?, + &[], + true, + true, + ) + .err() + .ok_or("a record key collision should fail the start")?; + let message = error.to_string(); + + assert!(message.contains("probe-1803"), "{message}"); + assert!(message.contains("probe-89065"), "{message}"); + + let records = store.list()?; + + assert_eq!(records.len(), 1, "no sidecar record is written"); + assert_eq!( + records.first().map(|record| record.rex_session_id.as_str()), + Some("session:1"), + "the stored record keeps its owner" + ); + Ok(()) +} diff --git a/test/muxer/rex/mux_test/stop.rs b/test/muxer/rex/mux_test/stop.rs index be4cb191..dfc3a709 100644 --- a/test/muxer/rex/mux_test/stop.rs +++ b/test/muxer/rex/mux_test/stop.rs @@ -34,30 +34,30 @@ fn stop_all_kills_and_deletes_every_laio_session_except_the_current_one() -> Tes } result?; - assert!(store.read_by_session("session:1")?.is_some()); - assert!(store.read_by_session("session:2")?.is_none()); + assert!(store.read_by_name("work")?.is_some()); + assert!(store.read_by_name("other")?.is_none()); Ok(()) } #[test] -fn stop_all_kills_a_live_laio_label_without_a_record() -> TestResult { +fn stop_all_ignores_live_sessions_without_a_record() -> TestResult { let _guard = env_guard(); - let harness = Harness::new(); - harness.seed(&record("session:1", "work"))?; - - let rex = harness + let rex = Harness::new() .json_args(&["session", "ls", "--json"], SESSION_LIST) - .unit(&["kill", "session:1"]) - .unit(&["kill", "session:2"]) .build(); Ok(rex.stop(&None, &None, true, true, false)?) } #[test] -fn stop_other_sweeps_every_other_laio_session() -> TestResult { +fn stop_other_sweeps_every_other_recorded_session() -> TestResult { let _guard = env_guard(); - let rex = Harness::new() + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + harness.seed(&record("session:2", "other"))?; + let store = harness.store(); + + let rex = harness .json_args(&["session", "ls", "--json"], SESSION_LIST) .unit(&["kill", "session:1"]) .unit(&["kill", "session:2"]) @@ -69,7 +69,9 @@ fn stop_other_sweeps_every_other_laio_session() -> TestResult { env::remove_var("REX_SESSION"); } - Ok(result?) + result?; + assert!(store.list()?.is_empty()); + Ok(()) } #[test] @@ -83,12 +85,12 @@ fn stop_kills_a_recorded_session_by_its_full_id() -> TestResult { rex.stop(&Some("work".to_string()), &None, true, false, false)?; - assert!(store.read_by_session("session:1")?.is_none()); + assert!(store.read_by_name("work")?.is_none()); Ok(()) } #[test] -fn stop_without_a_name_kills_the_current_rex_session() -> TestResult { +fn stop_without_a_name_kills_exactly_the_recorded_id() -> TestResult { let _guard = env_guard(); let harness = Harness::new(); harness.seed(&record("session:1", "work"))?; @@ -103,41 +105,19 @@ fn stop_without_a_name_kills_the_current_rex_session() -> TestResult { } result?; - assert!(store.read_by_session("session:1")?.is_none()); + assert!(store.read_by_name("work")?.is_none()); Ok(()) } #[test] -fn stop_without_a_name_keeps_a_foreign_live_session_alive() -> TestResult { +fn stop_without_a_name_refuses_a_recorded_id_that_is_not_current() -> TestResult { let _guard = env_guard(); - let rex = Harness::new() - .json_args( - &["session", "ls", "--json"], - r#"{"sessions":[{"session_id":"session:7","label":"personal"}]}"#, - ) - .build(); - set_current_session("session:7"); - - let result = rex.stop(&None, &None, false, false, false); - unsafe { - env::remove_var("REX_SESSION"); - } - - result?; - Ok(()) -} + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + let store = harness.store(); -#[test] -fn stop_without_a_name_kills_a_live_laio_label_without_a_record() -> TestResult { - let _guard = env_guard(); - let rex = Harness::new() - .json_args( - &["session", "ls", "--json"], - r#"{"sessions":[{"session_id":"session:1","label":"laio: work"}]}"#, - ) - .unit(&["kill", "session:1"]) - .build(); - set_current_session("session:1"); + let rex = harness.build(); + set_current_session("session:9"); let result = rex.stop(&None, &None, false, false, false); unsafe { @@ -145,15 +125,17 @@ fn stop_without_a_name_kills_a_live_laio_label_without_a_record() -> TestResult } result?; + assert!( + store.read_by_name("work")?.is_some(), + "the record of another session must survive" + ); Ok(()) } #[test] -fn stop_without_a_name_returns_ok_when_the_current_session_is_gone() -> TestResult { +fn stop_without_a_name_returns_ok_when_no_record_matches_the_current_session() -> TestResult { let _guard = env_guard(); - let rex = Harness::new() - .json_args(&["session", "ls", "--json"], r#"{"sessions":[]}"#) - .build(); + let rex = Harness::new().build(); set_current_session("session:9"); let result = rex.stop(&None, &None, false, false, false); @@ -166,11 +148,9 @@ fn stop_without_a_name_returns_ok_when_the_current_session_is_gone() -> TestResu } #[test] -fn stop_returns_ok_for_a_name_without_a_record_or_a_live_label() -> TestResult { +fn stop_returns_ok_for_a_name_without_a_record() -> TestResult { let _guard = env_guard(); - let rex = Harness::new() - .resolve("laio: work", "not_found", "") - .build(); + let rex = Harness::new().build(); Ok(rex.stop(&Some("work".to_string()), &None, false, false, false)?) } @@ -202,7 +182,7 @@ fn stop_runs_the_recorded_shutdown_hooks_before_the_kill() -> TestResult { rex.stop(&Some("work".to_string()), &None, false, false, false)?; assert_eq!(lock(&log).as_slice(), ["hook", "kill"]); - assert!(store.read_by_session("session:1")?.is_none()); + assert!(store.read_by_name("work")?.is_none()); Ok(()) } @@ -255,16 +235,16 @@ fn stop_skips_the_hooks_when_skip_cmds_is_set() -> TestResult { } #[test] -fn stop_kills_the_resolved_label_when_the_record_is_corrupt() -> TestResult { +fn stop_returns_ok_when_the_record_is_corrupt() -> TestResult { let _guard = env_guard(); let harness = Harness::new(); fs::create_dir_all(harness.store_dir())?; - fs::write(harness.store_dir().join("1.json"), "{ not json")?; + fs::write( + harness.store_dir().join(format!("{WORK_KEY}.json")), + "{ not json", + )?; - let rex = harness - .resolve("laio: work", "resolved", "session:9") - .unit(&["kill", "session:9"]) - .build(); + let rex = harness.build(); Ok(rex.stop(&Some("work".to_string()), &None, false, false, false)?) } diff --git a/test/muxer/rex/mux_test/switch.rs b/test/muxer/rex/mux_test/switch.rs index 50f097c9..4bb5ccff 100644 --- a/test/muxer/rex/mux_test/switch.rs +++ b/test/muxer/rex/mux_test/switch.rs @@ -1,12 +1,24 @@ use crate::common::muxer::Multiplexer; -use crate::muxer::rex::Rex; use super::mux_test::*; +const LIVE_WORK: &str = r#"{"sessions":[{"session_id":"session:1","label":"work"}]}"#; + +#[test] +fn switch_returns_false_without_a_record_and_never_asks_the_server() -> TestResult { + let rex = Harness::new().build(); + + assert!(!rex.switch("work", true)?); + Ok(()) +} + #[test] -fn switch_returns_true_and_skips_attach_when_requested() -> TestResult { - let rex = Harness::new() - .resolve("laio: work", "resolved", "session:1") +fn switch_returns_true_and_skips_attach_for_a_live_recorded_session() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let rex = harness + .json_args(&["session", "ls", "--json"], LIVE_WORK) .build(); assert!(rex.switch("work", true)?); @@ -14,9 +26,12 @@ fn switch_returns_true_and_skips_attach_when_requested() -> TestResult { } #[test] -fn switch_attaches_with_the_full_prefixed_session_id() -> TestResult { - let rex = Harness::new() - .resolve("laio: work", "resolved", "session:1") +fn switch_attaches_with_the_recorded_session_id() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let rex = harness + .json_args(&["session", "ls", "--json"], LIVE_WORK) .unit(&["do", "session.select", "session_id=session:1"]) .build(); @@ -26,8 +41,11 @@ fn switch_attaches_with_the_full_prefixed_session_id() -> TestResult { #[test] fn switch_continues_when_the_attach_fails() -> TestResult { - let rex = Harness::new() - .resolve("laio: work", "resolved", "session:1") + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let rex = harness + .json_args(&["session", "ls", "--json"], LIVE_WORK) .unit_failing( &["do", "session.select", "session_id=session:1"], "Rex.app is not accepting actions. Turn on Remote Control in its Settings under Rex Server.", @@ -39,50 +57,14 @@ fn switch_continues_when_the_attach_fails() -> TestResult { } #[test] -fn switch_rejects_an_ambiguous_target_with_the_label() -> TestResult { - let rex = Harness::new() - .resolve("laio: work", "ambiguous", "") - .build(); - - let error = rex - .switch("work", true) - .err() - .ok_or("ambiguity should fail")?; - - assert!(error.to_string().contains("laio: work"), "{error}"); - Ok(()) -} +fn switch_returns_false_when_the_recorded_session_is_not_live() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; -#[test] -fn switch_returns_false_when_the_target_is_not_found() -> TestResult { - let rex = Harness::new() - .resolve("laio: work", "not_found", "") + let rex = harness + .json_args(&["session", "ls", "--json"], r#"{"sessions":[]}"#) .build(); assert!(!rex.switch("work", true)?); Ok(()) } - -#[test] -fn switch_rejects_names_outside_the_laio_charset() -> TestResult { - let rex = Rex::new(); - - let error = rex.switch("bad/name", true).err().ok_or("invalid name")?; - - assert!(error.to_string().contains("Invalid"), "{error}"); - Ok(()) -} - -#[test] -fn switch_rejects_a_label_over_the_rex_limit() -> TestResult { - let rex = Rex::new(); - let name = "a".repeat(124); - - let error = rex - .switch(&name, true) - .err() - .ok_or("an over-long label should fail")?; - - assert!(error.to_string().contains("128"), "{error}"); - Ok(()) -} diff --git a/test/muxer/rex/session_get_test.rs b/test/muxer/rex/session_get_test.rs index a6da24d6..e8fccae3 100644 --- a/test/muxer/rex/session_get_test.rs +++ b/test/muxer/rex/session_get_test.rs @@ -145,12 +145,20 @@ fn get_session_exports_the_current_rex_session() -> TestResult { } #[test] -fn get_session_derives_the_name_from_the_label_without_a_record() -> TestResult { +fn get_session_fails_without_a_record() -> TestResult { let _session = RexSession::new("session:1"); let rex = view_harness().build(); - let session = rex.get_session()?; + let error = rex + .get_session() + .err() + .ok_or("a missing record should fail the export")?; - assert_eq!(session.name, "work"); + assert!( + error + .to_string() + .contains("Cannot determine the rex session name"), + "{error}" + ); Ok(()) } diff --git a/test/muxer/rex/store_test.rs b/test/muxer/rex/store_test.rs index 32c7204b..acd976c7 100644 --- a/test/muxer/rex/store_test.rs +++ b/test/muxer/rex/store_test.rs @@ -11,6 +11,13 @@ use crate::muxer::rex::store::{ type TestResult = core::result::Result>; +const PROJECT_KEY: &str = "244210e4"; +const FOO_BAR_KEY: &str = "55282c18"; +const UEBER_FOO_KEY: &str = "1fb15279"; +const ALPHA_KEY: &str = "8ed3f6ad"; +const BETA_KEY: &str = "f44e64e7"; +const PROBE_1803_KEY: &str = "a22cdbcd"; + static NEXT_DIR: AtomicU64 = AtomicU64::new(0); fn unique_dir() -> PathBuf { @@ -28,7 +35,6 @@ fn unique_dir() -> PathBuf { fn record(rex_session_id: &str, laio_name: &str) -> RexSessionRecord { RexSessionRecord { rex_session_id: rex_session_id.to_string(), - rex_label: format!("{laio_name}-label"), laio_name: laio_name.to_string(), config_path: format!("/tmp/configs/{laio_name}.yaml"), variables: format!("session_name={laio_name}&path=%2Ftmp"), @@ -53,15 +59,24 @@ fn write_then_read_by_name_round_trips_every_field() -> TestResult { .ok_or("should read back the record")?; assert_eq!(actual.rex_session_id, expected.rex_session_id); - assert_eq!(actual.rex_label, expected.rex_label); assert_eq!(actual.laio_name, expected.laio_name); assert_eq!(actual.config_path, expected.config_path); assert_eq!(actual.variables, expected.variables); assert_eq!(actual.created_at, expected.created_at); + + let files: Vec = fs::read_dir(&dir)? + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect(); + + assert_eq!(files, [format!("{PROJECT_KEY}.json")]); assert!( - dir.join("1.json").is_file(), - "record file is named after the uuid" + PROJECT_KEY + .chars() + .all(|ch| matches!(ch, '0'..='9' | 'a'..='f')), + "the record key is 8 lowercase hex digits" ); + assert_eq!(PROJECT_KEY.len(), 8); Ok(()) } @@ -77,15 +92,25 @@ fn read_by_name_returns_none_for_an_unknown_name() -> TestResult { } #[test] -fn read_by_name_skips_files_that_are_not_valid_json() -> TestResult { +fn read_by_name_returns_none_for_a_corrupt_record() -> TestResult { let dir = unique_dir(); fs::create_dir_all(&dir)?; - fs::write(dir.join("broken.json"), "{ not json")?; + fs::write(dir.join(format!("{PROJECT_KEY}.json")), "{ not json")?; let store = RexSessionStore::new(dir); let found = store.read_by_name("project")?; assert!(found.is_none()); + Ok(()) +} + +#[test] +fn the_scan_warns_and_skips_a_corrupt_record_file() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + fs::write(dir.join("broken.json"), "{ not json")?; + let store = RexSessionStore::new(dir); + assert!(store.list()?.is_empty()); Ok(()) } @@ -105,59 +130,35 @@ fn read_by_name_picks_the_record_with_the_matching_name() -> TestResult { } #[test] -fn read_by_session_reads_the_record_file_directly() -> TestResult { - let store = store(); - store.write_record(&record("session:1", "project"))?; - - let found = store - .read_by_session("session:1")? - .ok_or("should read the session record")?; - - assert_eq!(found.laio_name, "project"); - assert!(store.read_by_session("session:2")?.is_none()); - Ok(()) -} - -#[test] -fn read_by_session_returns_none_for_a_corrupt_record() -> TestResult { - let dir = unique_dir(); - fs::create_dir_all(&dir)?; - fs::write(dir.join("1.json"), "{ not json")?; - let store = RexSessionStore::new(dir); - - let found = store.read_by_session("session:1")?; - - assert!(found.is_none()); - Ok(()) -} - -#[test] -fn read_by_session_errors_when_the_record_path_is_unreadable() -> TestResult { +fn read_by_name_errors_when_the_record_path_is_unreadable() -> TestResult { let dir = unique_dir(); - fs::create_dir_all(dir.join("1.json"))?; + fs::create_dir_all(dir.join(format!("{PROJECT_KEY}.json")))?; let store = RexSessionStore::new(dir); let error = store - .read_by_session("session:1") + .read_by_name("project") .err() .ok_or("reading a directory as a record should fail")?; let message = error.to_string(); - assert!(message.contains("1.json"), "{message}"); + assert!(message.contains(PROJECT_KEY), "{message}"); Ok(()) } #[test] -fn delete_by_session_removes_the_record_file() -> TestResult { +fn delete_by_name_removes_the_record_file() -> TestResult { let dir = unique_dir(); let store = RexSessionStore::new(dir.clone()); store.write_record(&record("session:1", "project"))?; - store.delete_by_session("session:1")?; + store.delete_by_name("project")?; - assert!(!dir.join("1.json").exists(), "record file should be gone"); - assert!(store.read_by_session("session:1")?.is_none()); - store.delete_by_session("session:1")?; + assert!( + !dir.join(format!("{PROJECT_KEY}.json")).exists(), + "record file should be gone" + ); + assert!(store.read_by_name("project")?.is_none()); + store.delete_by_name("project")?; Ok(()) } @@ -172,10 +173,13 @@ fn prune_deletes_records_absent_from_the_live_ids() -> TestResult { assert_eq!(pruned, ["session:b"]); assert!( - !dir.join("b.json").exists(), + !dir.join(format!("{BETA_KEY}.json")).exists(), "stale record file should be gone" ); - assert!(dir.join("a.json").is_file(), "live record file should stay"); + assert!( + dir.join(format!("{ALPHA_KEY}.json")).is_file(), + "live record file should stay" + ); Ok(()) } @@ -200,10 +204,228 @@ fn reads_tolerate_a_missing_store_directory() -> TestResult { let store = store(); assert!(store.read_by_name("project")?.is_none()); - assert!(store.read_by_session("session:1")?.is_none()); assert!(store.list()?.is_empty()); assert!(store.prune(&["session:1".to_string()])?.is_empty()); - store.delete_by_session("session:1")?; + store.delete_by_name("project")?; + Ok(()) +} + +#[test] +fn write_record_uses_one_key_for_a_repeated_name_and_the_last_write_wins() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + + store.write_record(&record("session:1", "Foo Bar"))?; + store.write_record(&record("session:2", "Foo Bar"))?; + + let files: Vec = fs::read_dir(&dir)? + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect(); + + assert_eq!(files, [format!("{FOO_BAR_KEY}.json")]); + + let found = store + .read_by_name("Foo Bar")? + .ok_or("should read the record back")?; + + assert_eq!(found.laio_name, "Foo Bar"); + assert_eq!(found.rex_session_id, "session:2"); + Ok(()) +} + +#[test] +fn write_record_keys_a_unicode_name_and_keeps_it_verbatim() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + let written = record("session:1", "Über-Foo"); + + store.write_record(&written)?; + + assert!(dir.join(format!("{UEBER_FOO_KEY}.json")).is_file()); + + let found = store + .read_by_name("Über-Foo")? + .ok_or("should read the unicode record back")?; + + assert_eq!(found, written); + Ok(()) +} + +#[test] +fn write_record_refuses_two_names_that_share_a_key() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + store.write_record(&record("session:1", "probe-1803"))?; + + let error = store + .write_record(&record("session:2", "probe-89065")) + .err() + .ok_or("a record key collision should fail the write")?; + let message = error.to_string(); + + assert!(message.contains("probe-1803"), "{message}"); + assert!(message.contains("probe-89065"), "{message}"); + assert!(dir.join(format!("{PROBE_1803_KEY}.json")).is_file()); + + let stored = store + .read_by_name("probe-1803")? + .ok_or("the stored record should keep its owner")?; + + assert_eq!(stored.rex_session_id, "session:1"); + Ok(()) +} + +#[test] +fn the_scan_rekeys_a_legacy_uuid_record_to_the_sha_file() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + let legacy = record("session:1", "project"); + fs::write(dir.join("1.json"), serde_json::to_string_pretty(&legacy)?)?; + let store = RexSessionStore::new(dir.clone()); + + assert!( + store.read_by_name("project")?.is_none(), + "a direct read does not scan" + ); + assert_eq!(store.list()?, vec![legacy.clone()]); + + assert!(!dir.join("1.json").exists(), "the legacy file is gone"); + assert!(dir.join(format!("{PROJECT_KEY}.json")).is_file()); + assert_eq!(store.read_by_name("project")?, Some(legacy)); + Ok(()) +} + +#[test] +fn the_scan_leaves_a_corrupt_legacy_record_alone() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + fs::write(dir.join("1.json"), "{ not json")?; + let store = RexSessionStore::new(dir.clone()); + + assert!(store.list()?.is_empty()); + assert!( + dir.join("1.json").is_file(), + "an unreadable legacy file is not touched" + ); + Ok(()) +} + +#[test] +fn find_by_session_id_scans_the_records_for_an_exact_id() -> TestResult { + let store = store(); + store.write_record(&record("session:1", "alpha"))?; + store.write_record(&record("session:2", "beta"))?; + + assert_eq!( + store + .find_by_session_id("session:2")? + .map(|record| record.laio_name), + Some("beta".to_string()) + ); + assert!(store.find_by_session_id("session:3")?.is_none()); + Ok(()) +} + +#[test] +fn read_by_name_ignores_a_record_owned_by_another_name() -> TestResult { + let store = store(); + store.write_record(&record("session:1", "probe-1803"))?; + + assert!( + store.read_by_name("probe-89065")?.is_none(), + "a foreign record must not be served" + ); + assert_eq!( + store + .read_by_name("probe-1803")? + .map(|record| record.rex_session_id), + Some("session:1".to_string()) + ); + Ok(()) +} + +#[test] +fn delete_by_name_refuses_a_record_owned_by_another_name() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + store.write_record(&record("session:1", "probe-1803"))?; + + store.delete_by_name("probe-89065")?; + + assert!( + dir.join(format!("{PROBE_1803_KEY}.json")).is_file(), + "the record of another name must survive" + ); + assert!(store.read_by_name("probe-1803")?.is_some()); + Ok(()) +} + +#[test] +fn prune_deletes_only_the_scanned_path_of_a_stale_record() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + let store = RexSessionStore::new(dir.clone()); + store.write_record(&record("session:1", "probe-1803"))?; + fs::write( + dir.join("1.json"), + serde_json::to_string_pretty(&record("session:2", "probe-89065"))?, + )?; + + let pruned = store.prune(&["session:1".to_string()])?; + + assert_eq!(pruned, ["session:2"]); + assert!( + !dir.join("1.json").exists(), + "the scanned legacy path is deleted" + ); + assert!( + dir.join(format!("{PROBE_1803_KEY}.json")).is_file(), + "a re-hash would delete the live record of the other name" + ); + Ok(()) +} + +#[test] +fn the_scan_keeps_a_legacy_record_whose_key_is_occupied() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + let store = RexSessionStore::new(dir.clone()); + store.write_record(&record("session:1", "probe-1803"))?; + fs::write( + dir.join("1.json"), + serde_json::to_string_pretty(&record("session:2", "probe-89065"))?, + )?; + + assert_eq!(store.list()?.len(), 2, "both records stay readable"); + assert!( + dir.join("1.json").is_file(), + "the colliding legacy file is kept" + ); + assert_eq!( + store + .read_by_name("probe-1803")? + .map(|record| record.rex_session_id), + Some("session:1".to_string()) + ); + Ok(()) +} + +#[test] +fn the_scan_rekeys_a_marker_era_record_and_drops_its_label() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + let mut legacy = serde_json::to_value(record("session:1", "project"))?; + legacy["rex_label"] = serde_json::json!("laio: project"); + fs::write(dir.join("1.json"), serde_json::to_string_pretty(&legacy)?)?; + let store = RexSessionStore::new(dir.clone()); + + assert_eq!(store.list()?.len(), 1); + + let text = fs::read_to_string(dir.join(format!("{PROJECT_KEY}.json")))?; + + assert!(!text.contains("rex_label"), "{text}"); + assert!(!text.contains("laio: project"), "{text}"); Ok(()) } From 0a46a6deea6938eb1d0d943b10e0df1881749f3f Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 23:13:39 +0000 Subject: [PATCH 11/16] test(muxer/rex): pin byte-cap and migration idempotence --- test/muxer/rex/mux_test/start.rs | 29 ++++++++++++++++ test/muxer/rex/store_test.rs | 4 +++ test/muxer/rex/store_test/migration.rs | 47 ++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 test/muxer/rex/store_test/migration.rs diff --git a/test/muxer/rex/mux_test/start.rs b/test/muxer/rex/mux_test/start.rs index f3c904f6..2cf6a30a 100644 --- a/test/muxer/rex/mux_test/start.rs +++ b/test/muxer/rex/mux_test/start.rs @@ -421,6 +421,35 @@ fn start_accepts_a_name_at_the_128_byte_limit_and_rejects_one_over() -> TestResu Ok(()) } +#[test] +fn start_bounds_the_label_by_bytes_not_chars() -> TestResult { + let yaml = |name: &str| format!("\nname: {name}\npath: /tmp\nwindows:\n - name: main\n"); + + let over = "Ü".repeat(65); + assert_eq!((over.chars().count(), over.len()), (65, 130)); + + let rex = Harness::new().build(); + let error = rex + .start(&session_of(&yaml(&over))?, &[], true, true) + .err() + .ok_or("a 130-byte label should fail")?; + + assert!(error.to_string().contains("exceeds 128 bytes"), "{error}"); + + let allowed = "Ü".repeat(64); + assert_eq!((allowed.chars().count(), allowed.len()), (64, 128)); + + let rex = Harness::new() + .create( + &allowed, + r#"{"session_id":"session:1","initial_windows":[{"window_id":"window:1","block_ids":["block:1"],"revision":2}]}"#, + 1, + ) + .build(); + + Ok(rex.start(&session_of(&yaml(&allowed))?, &[], true, true)?) +} + #[test] fn start_continues_when_the_record_cannot_be_written() -> TestResult { let harness = Harness::new(); diff --git a/test/muxer/rex/store_test.rs b/test/muxer/rex/store_test.rs index acd976c7..c5c94866 100644 --- a/test/muxer/rex/store_test.rs +++ b/test/muxer/rex/store_test.rs @@ -9,6 +9,10 @@ use crate::muxer::rex::store::{ RexSessionRecord, RexSessionStore, laio_state_dir, resolve_state_dir, }; +#[cfg(test)] +#[path = "store_test/migration.rs"] +mod migration; + type TestResult = core::result::Result>; const PROJECT_KEY: &str = "244210e4"; diff --git a/test/muxer/rex/store_test/migration.rs b/test/muxer/rex/store_test/migration.rs new file mode 100644 index 00000000..9e78c0d0 --- /dev/null +++ b/test/muxer/rex/store_test/migration.rs @@ -0,0 +1,47 @@ +use std::fs; +use std::path::Path; +use std::time::UNIX_EPOCH; + +use crate::muxer::rex::store::{RexSessionRecord, RexSessionStore}; + +use super::{TestResult, record, unique_dir}; + +#[test] +fn the_scan_migrates_once_and_a_second_scan_changes_nothing() -> TestResult { + let dir = unique_dir(); + let store = RexSessionStore::new(dir.clone()); + store.write_record(&record("session:1", "alpha"))?; + let beta = serde_json::to_string_pretty(&record("session:2", "beta"))?; + fs::write(dir.join("1.json"), beta)?; + let mut legacy = serde_json::to_value(record("session:3", "Über-Foo"))?; + legacy["rex_label"] = serde_json::json!("laio: Über-Foo"); + fs::write(dir.join("2.json"), serde_json::to_string_pretty(&legacy)?)?; + + let first = sorted_records(store.list()?); + let migrated = snapshot(&dir)?; + let second = sorted_records(store.list()?); + + assert_eq!(first, second); + assert_eq!(snapshot(&dir)?, migrated); + Ok(()) +} + +fn sorted_records(mut records: Vec) -> Vec { + records.sort_by(|left, right| left.laio_name.cmp(&right.laio_name)); + records +} + +fn snapshot(dir: &Path) -> TestResult> { + let mut files = Vec::new(); + + for entry in fs::read_dir(dir)? { + let entry = entry?; + let name = entry.file_name().to_string_lossy().into_owned(); + let meta = entry.metadata()?; + let mtime = meta.modified()?.duration_since(UNIX_EPOCH)?.as_nanos(); + files.push(format!("{name}@{mtime}")); + } + + files.sort(); + Ok(files) +} From d3a211786ee016fcdfcd0c0058502bfbfdcebce3 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 23:14:09 +0000 Subject: [PATCH 12/16] chore: bump version to 0.19.0 - Update package version in Cargo.toml and Cargo.lock --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 69926676..f2abd5a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -671,7 +671,7 @@ dependencies = [ [[package]] name = "laio" -version = "0.18.0" +version = "0.19.0" dependencies = [ "clap", "clap-verbosity-flag", diff --git a/Cargo.toml b/Cargo.toml index ca678663..a714f108 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "laio" -version = "0.18.0" +version = "0.19.0" edition = "2024" description = "A simple flexbox-like layout manager for tmux." homepage = "https://github.com/ck3mp3r/laio-cli" From 534436cd681a40457e519a5d63c5316ae10b0df6 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Wed, 4 Nov 2026 23:44:24 +0000 Subject: [PATCH 13/16] fix(muxer/rex): attach reflects REX_SESSION, not client session listings --- docs/content/docs/reference/cli-commands.md | 2 +- .../content/docs/workflow/managing-configs.md | 2 +- src/muxer/rex/client.rs | 10 +- src/muxer/rex/model.rs | 22 ---- src/muxer/rex/mux.rs | 18 +-- test/muxer/rex/client_test.rs | 21 ---- test/muxer/rex/mux_test/session.rs | 111 ++++++++++++++++-- 7 files changed, 106 insertions(+), 80 deletions(-) diff --git a/docs/content/docs/reference/cli-commands.md b/docs/content/docs/reference/cli-commands.md index 595e1b13..fac02586 100644 --- a/docs/content/docs/reference/cli-commands.md +++ b/docs/content/docs/reference/cli-commands.md @@ -674,6 +674,6 @@ rex maps one laio config to one rex session named after the config; laio recogni - Session `env` is ignored: rex has no environment store. `laio` keeps the config path and the template variables in a sidecar record per session. - The sidecar store is `LAIO_STATE_DIR` when set (used as-is), otherwise `$XDG_STATE_HOME/laio/rex`, otherwise `~/.local/state/laio/rex`. - `laio stop ` runs the shutdown hooks and kills the rex session. `laio stop --all` and `--others` sweep the laio-managed sessions and prune stale records. -- `laio list` shows the laio-managed sessions, marked ● when a rex app client has them attached. +- `laio list` shows the laio-managed sessions. It marks ● only for the session laio runs in (`REX_SESSION`). rex exposes no who-displays-what signal, so from outside a rex session every row shows ○. - `laio session yaml` requires a rex session: it reads `REX_SESSION`. The export reads the tiled layer, so it loses pane commands and ignores floating layers. - Pane `style` is ignored on rex. diff --git a/docs/content/docs/workflow/managing-configs.md b/docs/content/docs/workflow/managing-configs.md index 9c175330..c8cfaa6e 100644 --- a/docs/content/docs/workflow/managing-configs.md +++ b/docs/content/docs/workflow/managing-configs.md @@ -105,7 +105,7 @@ Useful for scripting and automation. laio session list ``` -On tmux and zellij this lists every session of the multiplexer, including sessions laio does not manage. On herdr it lists only laio-managed workspaces. On rex it lists only laio-managed sessions and marks a session attached when a rex app client has it attached. +On tmux and zellij this lists every session of the multiplexer, including sessions laio does not manage. On herdr it lists only laio-managed workspaces. On rex it lists only laio-managed sessions and marks ● only the session laio runs in (`REX_SESSION`); rex exposes no who-displays-what signal, so every other laio-managed session shows ○. #### rex (experimental) diff --git a/src/muxer/rex/client.rs b/src/muxer/rex/client.rs index 630eb9c2..6e31edd9 100644 --- a/src/muxer/rex/client.rs +++ b/src/muxer/rex/client.rs @@ -9,8 +9,7 @@ use crate::common::cmd::{Runner, Type}; use crate::common::muxer::Client; use super::model::{ - ClientListOutput, CreateOutput, CreateRequest, FocusOutput, PwdOutput, SessionListOutput, - SessionView, + CreateOutput, CreateRequest, FocusOutput, PwdOutput, SessionListOutput, SessionView, }; #[derive(Debug)] @@ -86,13 +85,6 @@ impl RexClient { ) } - pub(crate) fn client_list(&self) -> Result { - self.run_json( - "client_list", - cmd_basic!("rex", args = ["client", "ls", "--json"]), - ) - } - pub(crate) fn block_pwd(&self, session: &str, block_id: &str) -> Result { self.run_json( "block_pwd", diff --git a/src/muxer/rex/model.rs b/src/muxer/rex/model.rs index d70e7e83..59e53af1 100644 --- a/src/muxer/rex/model.rs +++ b/src/muxer/rex/model.rs @@ -91,28 +91,6 @@ pub(crate) struct PwdOwner { pub(crate) name: String, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub(crate) struct ClientListOutput { - pub(crate) clients: Option>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub(crate) struct ClientEntry { - pub(crate) client_id: String, - pub(crate) connection_state: Option, - pub(crate) info: Option, - pub(crate) session_ids: Option>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] -pub(crate) struct ClientInfo { - pub(crate) kind: Option, - pub(crate) platform: Option, - pub(crate) name: Option, - pub(crate) version: Option, - pub(crate) label: Option, -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] pub(crate) struct FocusOutput { pub(crate) revision: u32, diff --git a/src/muxer/rex/mux.rs b/src/muxer/rex/mux.rs index a317b669..f0236390 100644 --- a/src/muxer/rex/mux.rs +++ b/src/muxer/rex/mux.rs @@ -19,7 +19,7 @@ use crate::muxer::rex::{ }; use super::client::RexClient; -use super::model::{ClientListOutput, CreateOutput}; +use super::model::CreateOutput; use super::store::{RexSessionRecord, RexSessionStore, laio_state_dir}; const MAX_LABEL_LEN: usize = 128; @@ -418,7 +418,7 @@ impl Multiplexer for Rex { let live: Vec = live_ids.iter().cloned().collect(); self.store.prune(&live)?; - let attached = attached_session_ids(&self.client.client_list()?); + let current = current_session(); Ok(self .store @@ -426,7 +426,8 @@ impl Multiplexer for Rex { .into_iter() .filter(|record| live_ids.contains(&record.rex_session_id)) .map(|record| { - SessionInfo::active(record.laio_name, attached.contains(&record.rex_session_id)) + let attached = current.as_deref() == Some(record.rex_session_id.as_str()); + SessionInfo::active(record.laio_name, attached) }) .collect()) } @@ -495,17 +496,6 @@ fn block_id<'a>(created: &'a CreateOutput, leaf: &LeafPlan) -> Option<&'a str> { .map(String::as_str) } -fn attached_session_ids(output: &ClientListOutput) -> HashSet { - output - .clients - .iter() - .flatten() - .filter_map(|client| client.session_ids.as_ref()) - .flatten() - .cloned() - .collect() -} - fn decode_record_variables(name: &str, encoded: &str) -> Option> { if encoded.is_empty() { return Some(Vec::new()); diff --git a/test/muxer/rex/client_test.rs b/test/muxer/rex/client_test.rs index c4a7e4d5..2e056967 100644 --- a/test/muxer/rex/client_test.rs +++ b/test/muxer/rex/client_test.rs @@ -279,27 +279,6 @@ fn session_list_reads_cli_json_output() -> TestResult { Ok(()) } -#[test] -fn client_list_exposes_session_ids() -> TestResult { - let client = string_client( - &["client", "ls", "--json"], - r#"{"clients":[{"client_id":"client:app","connection_state":"connected","info":{"kind":"app","platform":"macos","name":"Rex Beta","version":"0.1.0 (1758)","label":"Mac"},"session_ids":["session:1","session:2"]},{"client_id":"client:cli","connection_state":"connected","info":{"kind":"cli","platform":"macos","name":"rex","version":"0.0.1"}}]}"#, - )?; - - let output = client.client_list()?; - - let clients = output.clients.ok_or("should have clients")?; - let app = clients.first().ok_or("should have the app client")?; - let session_ids = app - .session_ids - .clone() - .ok_or("app client should carry session ids")?; - assert_eq!(session_ids, ["session:1", "session:2"]); - let cli = clients.get(1).ok_or("should have the cli client")?; - assert!(cli.session_ids.is_none()); - Ok(()) -} - #[test] fn block_pwd_passes_session_scope() -> TestResult { let client = string_client( diff --git a/test/muxer/rex/mux_test/session.rs b/test/muxer/rex/mux_test/session.rs index 583d303c..dd468eab 100644 --- a/test/muxer/rex/mux_test/session.rs +++ b/test/muxer/rex/mux_test/session.rs @@ -1,10 +1,53 @@ +use std::env; +use std::sync::MutexGuard; + use crate::common::muxer::Multiplexer; -use crate::common::session_info::SessionStatus; +use crate::common::session_info::{SessionInfo, SessionStatus}; use super::mux_test::*; const SESSION_LIST: &str = r#"{"sessions":[{"session_id":"session:1","label":"work"},{"session_id":"session:2","label":"extra"},{"session_id":"session:3","label":"other"}]}"#; +struct RexSessionEnv { + _guard: MutexGuard<'static, ()>, +} + +impl RexSessionEnv { + fn set(value: &str) -> Self { + let guard = env_guard(); + + unsafe { + env::set_var("REX_SESSION", value); + } + + Self { _guard: guard } + } + + fn unset() -> Self { + Self { + _guard: env_guard(), + } + } +} + +impl Drop for RexSessionEnv { + fn drop(&mut self) { + unsafe { + env::remove_var("REX_SESSION"); + } + } +} + +fn rows(sessions: &[SessionInfo]) -> Vec<(&str, SessionStatus)> { + let mut rows: Vec<(&str, SessionStatus)> = sessions + .iter() + .map(|info| (info.name.as_str(), info.status)) + .collect(); + + rows.sort_by_key(|(name, _)| *name); + rows +} + #[test] fn get_session_config_path_returns_the_recorded_path() -> TestResult { let harness = Harness::new(); @@ -49,6 +92,7 @@ fn get_session_variables_returns_none_for_undecodable_variables() -> TestResult #[test] fn list_sessions_reports_only_live_recorded_sessions() -> TestResult { + let _env = RexSessionEnv::unset(); let harness = Harness::new(); harness.seed(&record("session:1", "work"))?; harness.seed(&record("session:9", "stale"))?; @@ -56,16 +100,11 @@ fn list_sessions_reports_only_live_recorded_sessions() -> TestResult { let rex = harness .json_args(&["session", "ls", "--json"], SESSION_LIST) - .json_args(&["client", "ls", "--json"], r#"{"clients":[]}"#) .build(); let sessions = rex.list_sessions()?; - let rows: Vec<(&str, SessionStatus)> = sessions - .iter() - .map(|info| (info.name.as_str(), info.status)) - .collect(); - assert_eq!(rows, [("work", SessionStatus::Active)]); + assert_eq!(rows(&sessions), [("work", SessionStatus::Active)]); assert!( store.read_by_name("stale")?.is_none(), "the stale record file must be deleted" @@ -74,22 +113,70 @@ fn list_sessions_reports_only_live_recorded_sessions() -> TestResult { } #[test] -fn list_sessions_reports_a_client_held_session_as_attached() -> TestResult { +fn list_sessions_marks_the_session_laio_runs_in_as_attached() -> TestResult { + let _env = RexSessionEnv::set("session:1"); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + harness.seed(&record("session:2", "extra"))?; + + let rex = harness + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .build(); + + let sessions = rex.list_sessions()?; + + assert_eq!( + rows(&sessions), + [ + ("extra", SessionStatus::Active), + ("work", SessionStatus::Attached) + ] + ); + Ok(()) +} + +#[test] +fn list_sessions_reports_every_live_session_active_outside_a_rex_session() -> TestResult { + let _env = RexSessionEnv::unset(); let harness = Harness::new(); harness.seed(&record("session:1", "work"))?; + harness.seed(&record("session:2", "extra"))?; + + let rex = harness + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .build(); + + let sessions = rex.list_sessions()?; + + assert_eq!( + rows(&sessions), + [ + ("extra", SessionStatus::Active), + ("work", SessionStatus::Active) + ] + ); + Ok(()) +} - let clients = r#"{"clients":[{"client_id":"client:app","info":{"kind":"app"},"session_ids":["session:1"]}]}"#; +#[test] +fn list_sessions_marks_no_session_attached_for_a_foreign_rex_session() -> TestResult { + let _env = RexSessionEnv::set("session:404"); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + harness.seed(&record("session:2", "extra"))?; let rex = harness .json_args(&["session", "ls", "--json"], SESSION_LIST) - .json_args(&["client", "ls", "--json"], clients) .build(); let sessions = rex.list_sessions()?; assert_eq!( - sessions.first().map(|info| info.status), - Some(SessionStatus::Attached) + rows(&sessions), + [ + ("extra", SessionStatus::Active), + ("work", SessionStatus::Active) + ] ); Ok(()) } From 7c31a9d1b40e78e8965f0d3ef3cc1cb3695ab2a1 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Thu, 5 Nov 2026 19:39:03 +0000 Subject: [PATCH 14/16] docs: replace the rex landing card with a neutral multi-muxer card --- docs/content/_index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/content/_index.md b/docs/content/_index.md index 6428960d..1bde3c32 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -37,8 +37,8 @@ title = "Session Export" content = 'Serialize existing tmux, zellij, herdr, and rex sessions to YAML format for sharing and templating.' [[extra.list]] -title = "Experimental rex Backend" -content = 'Select with --muxer rex. Session env and pane style are ignored, export loses pane commands and floating layers, and attach needs Remote Control enabled in Rex.app under Settings > Rex Server. Session records live in LAIO_STATE_DIR when set, otherwise $XDG_STATE_HOME/laio/rex, otherwise ~/.local/state/laio/rex.' +title = "Multi-Muxer" +content = 'Four backends — tmux, zellij, herdr, and experimental rex — with identical YAML workflows; see the docs for per-backend details.' [[extra.list]] title = "Supported Platforms" From 78431e7d6e8a80455f922eebf93d35ae0114c335 Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Thu, 5 Nov 2026 19:44:06 +0000 Subject: [PATCH 15/16] docs: state tmux stable, zellij/herdr/rex experimental on the landing card --- docs/content/_index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/_index.md b/docs/content/_index.md index 1bde3c32..5c24aeff 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -38,7 +38,7 @@ content = 'Serialize existing tmux, zellij, herdr, and rex sessions to YAML form [[extra.list]] title = "Multi-Muxer" -content = 'Four backends — tmux, zellij, herdr, and experimental rex — with identical YAML workflows; see the docs for per-backend details.' +content = 'Four backends — tmux is stable; zellij, herdr, and rex are experimental — with identical YAML workflows; see the docs for per-backend details.' [[extra.list]] title = "Supported Platforms" From e95030552a90f3fd6a6feef2ed46faa9886039db Mon Sep 17 00:00:00 2001 From: Christian Kemper Date: Thu, 5 Nov 2026 19:48:34 +0000 Subject: [PATCH 16/16] docs: mark experimental backends with asterisks on the landing card --- docs/content/_index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/_index.md b/docs/content/_index.md index 5c24aeff..b3b68f75 100644 --- a/docs/content/_index.md +++ b/docs/content/_index.md @@ -38,7 +38,7 @@ content = 'Serialize existing tmux, zellij, herdr, and rex sessions to YAML form [[extra.list]] title = "Multi-Muxer" -content = 'Four backends — tmux is stable; zellij, herdr, and rex are experimental — with identical YAML workflows; see the docs for per-backend details.' +content = 'Four backends — tmux, zellij*, herdr*, and rex* — with identical YAML workflows; * experimental, see the docs for per-backend details.' [[extra.list]] title = "Supported Platforms"