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/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" diff --git a/README.md b/README.md index 81c3bde4..b11c004b 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 named after the config: laio recognizes its rex sessions by the sidecar store, so labels are plain names. ## 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 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`. +- **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..b3b68f75 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 = "Multi-Muxer" +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" diff --git a/docs/content/docs/configuration/lifecycle.md b/docs/content/docs/configuration/lifecycle.md index 0086a144..aa380b7a 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 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 1fa97bbe..d7e32ae2 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 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; 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"` @@ -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 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 @@ -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 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. +- `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..0856f98c 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 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 32c79da0..fac02586 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 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. + +- `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. 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 c30667d0..c8cfaa6e 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 ● only the session laio runs in (`REX_SESSION`); rex exposes no who-displays-what signal, so every other laio-managed session shows ○. + +#### rex (experimental) + +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 ff25136b..d4fc05e0 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, 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 @@ -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 fe1eebc2..108b4ddd 100644 --- a/src/muxer/mod.rs +++ b/src/muxer/mod.rs @@ -3,9 +3,11 @@ use clap::ValueEnum; use miette::{Result, bail}; use std::env; pub(crate) mod herdr; +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; @@ -14,6 +16,7 @@ pub(crate) enum Muxer { Tmux, Zellij, Herdr, + Rex, } pub(crate) fn create_muxer(muxer: &Option) -> Result> { @@ -24,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: '{}'", @@ -39,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/client.rs b/src/muxer/rex/client.rs new file mode 100644 index 00000000..6e31edd9 --- /dev/null +++ b/src/muxer/rex/client.rs @@ -0,0 +1,160 @@ +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::{ + CreateOutput, CreateRequest, FocusOutput, PwdOutput, SessionListOutput, SessionView, +}; + +#[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 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/export.rs b/src/muxer/rex/export.rs new file mode 100644 index 00000000..c57bf12e --- /dev/null +++ b/src/muxer/rex/export.rs @@ -0,0 +1,356 @@ +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}; + +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(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(fallback: Option<&str>) -> Result { + fallback + .map(str::to_string) + .ok_or_else(|| miette!("Cannot determine the rex session name")) +} + +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/layout.rs b/src/muxer/rex/layout.rs new file mode 100644 index 00000000..22594303 --- /dev/null +++ b/src/muxer/rex/layout.rs @@ -0,0 +1,229 @@ +use miette::{Result, bail, 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 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)] +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)> { + if session.windows.is_empty() { + bail!("Session '{}' has no windows", session.name); + } + + 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 { + let layout = 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, + }); + + 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 + ); + } + + 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( + 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 +} + +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/src/muxer/rex/mod.rs b/src/muxer/rex/mod.rs new file mode 100644 index 00000000..028c5371 --- /dev/null +++ b/src/muxer/rex/mod.rs @@ -0,0 +1,51 @@ +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}; + +pub(crate) use mux::Rex; + +#[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; + +#[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; + +#[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/model.rs b/src/muxer/rex/model.rs new file mode 100644 index 00000000..59e53af1 --- /dev/null +++ b/src/muxer/rex/model.rs @@ -0,0 +1,150 @@ +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 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, 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/src/muxer/rex/mux.rs b/src/muxer/rex/mux.rs new file mode 100644 index 00000000..f0236390 --- /dev/null +++ b/src/muxer/rex/mux.rs @@ -0,0 +1,543 @@ +use std::collections::{HashMap, 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}; + +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, local_path, session_from_view, tiled_block_ids, +}; + +use super::client::RexClient; +use super::model::CreateOutput; +use super::store::{RexSessionRecord, RexSessionStore, laio_state_dir}; + +const MAX_LABEL_LEN: usize = 128; +const REX_SESSION_ENV: &str = "REX_SESSION"; + +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 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(), + 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, name: &str) { + if let Err(error) = self.store.delete_by_name(name) { + log::warn!("Failed to delete the rex session record '{name}': {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: &RexSessionRecord, + session: &Option, + ) -> Result<()> { + if let Some(session) = session { + return self.run_shutdown_commands(session); + } + + 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 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_named( + &self, + name: &str, + session: &Option, + skip_cmds: bool, + stop_other: bool, + ) -> Result<()> { + let Some(record) = self.store.read_by_name(name)? else { + log::debug!("Not a laio session: {name}"); + return Ok(()); + }; + + self.stop_resolved( + &record.laio_name, + &record.rex_session_id, + &record, + session, + skip_cmds, + stop_other, + ) + } + + fn stop_current( + &self, + rex_session_id: &str, + session: &Option, + skip_cmds: bool, + stop_other: bool, + ) -> Result<()> { + 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(()); + }; + + self.stop_resolved( + &record.laio_name, + rex_session_id, + &record, + session, + skip_cmds, + stop_other, + ) + } + + fn name_from_session_id(&self, rex_session_id: &str) -> Result> { + Ok(self + .store + .find_by_session_id(rex_session_id)? + .map(|record| record.laio_name)) + } + + fn stop_resolved( + &self, + name: &str, + rex_session_id: &str, + record: &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(name); + + hooks.and(kill) + } + + fn sweep(&self, skip_cmds: bool, current: Option<&str>) -> Result<()> { + log::trace!("Closing all/other laio rex sessions."); + + let live_ids: Vec = self + .client + .session_list()? + .sessions + .into_iter() + .map(|session| session.session_id) + .collect(); + + self.store.prune(&live_ids)?; + + let targets: Vec<(String, String, RexSessionRecord)> = 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(), + record, + ) + }) + .collect(); + + 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, &None) + }; + + let kill = self.kill_session(rex_session_id); + self.delete_record(name); + + hooks.and(kill)?; + } + + Ok(()) + } +} + +impl Multiplexer for Rex { + fn start( + &self, + session: &Session, + env_vars: &[(&str, &str)], + 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); + + let created = self.client.session_create(&request)?; + + self.write_record(&created.session_id, 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 live_ids: HashSet = self + .client + .session_list()? + .sessions + .into_iter() + .map(|session| session.session_id) + .collect(); + + let live: Vec = live_ids.iter().cloned().collect(); + self.store.prune(&live)?; + + let current = current_session(); + + Ok(self + .store + .list()? + .into_iter() + .filter(|record| live_ids.contains(&record.rex_session_id)) + .map(|record| { + let attached = current.as_deref() == Some(record.rex_session_id.as_str()); + SessionInfo::active(record.laio_name, attached) + }) + .collect()) + } + + fn switch(&self, name: &str, skip_attach: bool) -> Result { + 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); + }; + + 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) + } + + fn get_session(&self) -> Result { + 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.name_from_session_id(&rex_session_id)?; + + session_from_view(&view, &pwds, name.as_deref()) + } +} + +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 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 laio_label(name: &str) -> Result { + if name.is_empty() { + bail!("Invalid rex session name '{name}'"); + } + + if name.len() > MAX_LABEL_LEN { + bail!("rex session label '{name}' exceeds {MAX_LABEL_LEN} bytes"); + } + + Ok(name.to_string()) +} + +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/src/muxer/rex/store.rs b/src/muxer/rex/store.rs new file mode 100644 index 00000000..9375fd96 --- /dev/null +++ b/src/muxer/rex/store.rs @@ -0,0 +1,274 @@ +use std::{ + env, fs, + io::ErrorKind, + path::{Path, PathBuf}, +}; + +use miette::{Result, miette}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +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 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) 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 } + } + + /// 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.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}"))?; + + 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> { + 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 + .list()? + .into_iter() + .find(|record| record.rex_session_id == rex_session_id)) + } + + 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_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 + ); + + 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 (path, record) in self.scanned_records()? { + if live_session_ids.contains(&record.rex_session_id) { + continue; + } + + delete_file(&path)?; + pruned.push(record.rex_session_id); + } + + Ok(pruned) + } + + pub(crate) fn list(&self) -> Result> { + Ok(self + .scanned_records()? + .into_iter() + .map(|(_, record)| record) + .collect()) + } + + 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()), + 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).map(|record| self.migrate(path, record))) + .collect()) + } + + 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() +} + +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())), + } +} + +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/client_test.rs b/test/muxer/rex/client_test.rs new file mode 100644 index 00000000..2e056967 --- /dev/null +++ b/test/muxer/rex/client_test.rs @@ -0,0 +1,370 @@ +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 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(()) +} diff --git a/test/muxer/rex/export_test.rs b/test/muxer/rex/export_test.rs new file mode 100644 index 00000000..028bd66d --- /dev/null +++ b/test/muxer/rex/export_test.rs @@ -0,0 +1,360 @@ +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_fails_to_name_the_session() -> TestResult { + let layout = leaf("b1"); + let view = view( + "laio: work", + "w1", + vec![window("w1", "main", None, None, vec![tiled(layout, &[])])], + ); + + let error = session_from_view(&view, &pwds(&[("b1", "/opt/project")]), None) + .err() + .ok_or("a missing record should fail the export")?; + + assert!( + error + .to_string() + .contains("Cannot determine the rex session name"), + "{error}" + ); + 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/layout_test.rs b/test/muxer/rex/layout_test.rs new file mode 100644 index 00000000..6abc3a53 --- /dev/null +++ b/test/muxer/rex/layout_test.rs @@ -0,0 +1,386 @@ +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(()) +} + +#[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(()) +} diff --git a/test/muxer/rex/mux_test.rs b/test/muxer/rex/mux_test.rs new file mode 100644 index 00000000..7b09b3ac --- /dev/null +++ b/test/muxer/rex/mux_test.rs @@ -0,0 +1,301 @@ +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; + +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>>; + +pub(super) const WORK_KEY: &str = "00e13ed7"; + +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(), + 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 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..dd468eab --- /dev/null +++ b/test/muxer/rex/mux_test/session.rs @@ -0,0 +1,182 @@ +use std::env; +use std::sync::MutexGuard; + +use crate::common::muxer::Multiplexer; +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(); + 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_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"))?; + let store = harness.store(); + + let rex = harness + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .build(); + + let sessions = rex.list_sessions()?; + + assert_eq!(rows(&sessions), [("work", SessionStatus::Active)]); + assert!( + store.read_by_name("stale")?.is_none(), + "the stale record file must be deleted" + ); + Ok(()) +} + +#[test] +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(()) +} + +#[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) + .build(); + + let sessions = rex.list_sessions()?; + + assert_eq!( + rows(&sessions), + [ + ("extra", SessionStatus::Active), + ("work", SessionStatus::Active) + ] + ); + 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..2cf6a30a --- /dev/null +++ b/test/muxer/rex/mux_test/start.rs @@ -0,0 +1,495 @@ +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_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(format!("{WORK_KEY}.json")).is_file(), + "the sidecar record must exist before the first send" + ); + }); + + let store = harness.store(); + let rex = harness + .create("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.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_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( + " +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() + .create("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() + .create("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 + .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_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() + .create("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 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"}]}"#, + ) + .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().create("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() + .create("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() + .create("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_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(); + + rex.start( + &session_of("\nname: Über-Foo\npath: /tmp\nwindows:\n - name: main\n - name: logs\n")?, + &[], + true, + true, + )?; + + 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_128_byte_limit_and_rejects_one_over() -> TestResult { + let allowed = "Ü".repeat(64); + 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(); + + rex.start( + &session_of(&format!( + "\nname: {allowed}\npath: /tmp\nwindows:\n - name: main\n" + ))?, + &[], + true, + true, + )?; + + let rejected = "b".repeat(129); + 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_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(); + let blocked = harness.store_dir().to_path_buf(); + fs::write(&blocked, "not a directory")?; + + 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 new file mode 100644 index 00000000..dfc3a709 --- /dev/null +++ b/test/muxer/rex/mux_test/stop.rs @@ -0,0 +1,298 @@ +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":"other"}]}"#; + +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_name("work")?.is_some()); + assert!(store.read_by_name("other")?.is_none()); + Ok(()) +} + +#[test] +fn stop_all_ignores_live_sessions_without_a_record() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new() + .json_args(&["session", "ls", "--json"], SESSION_LIST) + .build(); + + Ok(rex.stop(&None, &None, true, true, false)?) +} + +#[test] +fn stop_other_sweeps_every_other_recorded_session() -> 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: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"); + } + + result?; + assert!(store.list()?.is_empty()); + Ok(()) +} + +#[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_name("work")?.is_none()); + Ok(()) +} + +#[test] +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"))?; + 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_name("work")?.is_none()); + Ok(()) +} + +#[test] +fn stop_without_a_name_refuses_a_recorded_id_that_is_not_current() -> TestResult { + let _guard = env_guard(); + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + let store = harness.store(); + + let rex = harness.build(); + set_current_session("session:9"); + + let result = rex.stop(&None, &None, false, false, false); + unsafe { + env::remove_var("REX_SESSION"); + } + + 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_no_record_matches_the_current_session() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new().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() -> TestResult { + let _guard = env_guard(); + let rex = Harness::new().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_name("work")?.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_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(format!("{WORK_KEY}.json")), + "{ not json", + )?; + + let rex = harness.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(()) +} diff --git a/test/muxer/rex/mux_test/switch.rs b/test/muxer/rex/mux_test/switch.rs new file mode 100644 index 00000000..4bb5ccff --- /dev/null +++ b/test/muxer/rex/mux_test/switch.rs @@ -0,0 +1,70 @@ +use crate::common::muxer::Multiplexer; + +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_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)?); + Ok(()) +} + +#[test] +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(); + + assert!(rex.switch("work", false)?); + Ok(()) +} + +#[test] +fn switch_continues_when_the_attach_fails() -> TestResult { + 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.", + ) + .build(); + + assert!(rex.switch("work", false)?); + Ok(()) +} + +#[test] +fn switch_returns_false_when_the_recorded_session_is_not_live() -> TestResult { + let harness = Harness::new(); + harness.seed(&record("session:1", "work"))?; + + let rex = harness + .json_args(&["session", "ls", "--json"], r#"{"sessions":[]}"#) + .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 new file mode 100644 index 00000000..e8fccae3 --- /dev/null +++ b/test/muxer/rex/session_get_test.rs @@ -0,0 +1,164 @@ +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_fails_without_a_record() -> TestResult { + let _session = RexSession::new("session:1"); + let rex = view_harness().build(); + + let error = rex + .get_session() + .err() + .ok_or("a missing record should fail the export")?; + + 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 new file mode 100644 index 00000000..c5c94866 --- /dev/null +++ b/test/muxer/rex/store_test.rs @@ -0,0 +1,472 @@ +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::{ + 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"; +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 { + 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-store-{}-{nanos}-{suffix}", + std::process::id() + )) +} + +fn record(rex_session_id: &str, laio_name: &str) -> RexSessionRecord { + RexSessionRecord { + rex_session_id: rex_session_id.to_string(), + 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.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!( + 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(()) +} + +#[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_returns_none_for_a_corrupt_record() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(&dir)?; + 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(()) +} + +#[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_name_errors_when_the_record_path_is_unreadable() -> TestResult { + let dir = unique_dir(); + fs::create_dir_all(dir.join(format!("{PROJECT_KEY}.json")))?; + let store = RexSessionStore::new(dir); + + let error = store + .read_by_name("project") + .err() + .ok_or("reading a directory as a record should fail")?; + let message = error.to_string(); + + assert!(message.contains(PROJECT_KEY), "{message}"); + Ok(()) +} + +#[test] +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_name("project")?; + + 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(()) +} + +#[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(format!("{BETA_KEY}.json")).exists(), + "stale record file should be gone" + ); + assert!( + dir.join(format!("{ALPHA_KEY}.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.list()?.is_empty()); + assert!(store.prune(&["session:1".to_string()])?.is_empty()); + 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(()) +} + +#[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(()) +} 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) +} 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(()) +}