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