Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat: add persistent Driver and Lume release channels

Francesco Bonacci0813659ac237
diff --git a/.github/releases/README.md b/.github/releases/README.md
index 94dec75b35..f06e7c6e29 100644
--- a/.github/releases/README.md
+++ b/.github/releases/README.md
@@ -22,3 +22,26 @@ Nightly release notes reuse the repository's PR-first attribution collector.
The first nightly is bounded by the component's current stable tag; later
nightlies are bounded by the previous published nightly. A component therefore
needs a reachable stable tag before its nightly channel is enabled.
+
+## Persistent consumer selection
+
+Components that let users follow a channel should reuse the same consumer
+contract while keeping product-specific installers and updaters:
+
+- `stable` is the default when no preference exists;
+- `channel set stable|nightly` persists intent without replacing the binary;
+- installer `--channel stable|nightly` persists intent and installs that channel;
+- exact immutable pins outrank saved state, are one-shot, and cannot be combined
+ with an explicit channel;
+- stable and nightly discovery use disjoint prefixes and strict version grammars;
+- update caches include the selected channel, and structured status reports both
+ the selected and current channel; and
+- a channel mismatch is offered as an explicit transition even when ordinary
+ SemVer ordering would point the other way.
+
+Store the preference as a validated one-line `release-channel` file in the
+component's existing product home. A missing file means stable; invalid or
+unreadable state fails closed with a repair command. Product-home overrides must
+relocate the file so installer and updater tests remain isolated. Cua Driver and
+Lume are the reference implementations; [RFC 3101](../../rfcs/3101-persistent-release-channel-selection.md)
+records the full rationale and acceptance matrix.
diff --git a/.github/scripts/tests/test_release_channel_installers.py b/.github/scripts/tests/test_release_channel_installers.py
index 3b1b5376d5..f64bbab9e6 100644
--- a/.github/scripts/tests/test_release_channel_installers.py
+++ b/.github/scripts/tests/test_release_channel_installers.py
@@ -38,6 +38,8 @@ def run_lume_resolver(tmp_path: Path, version: str, baked: str = "") -> subproce
GITHUB_REPO="trycua/cua"
LUME_VERSION="{version}"
LUME_BAKED_VERSION="{baked}"
+ LUME_CHANNEL="stable"
+ LUME_TAG_PREFIX="lume-v"
{shell_function(source, "get_latest_lume_tag")}
get_latest_lume_tag
"""
@@ -86,11 +88,37 @@ def test_lume_exact_pin_rejects_cross_component_and_malformed_tags(
assert "exact x.y.z stable version or canonical nightly tag" in result.stderr
-def test_lume_stable_api_filter_is_exact_draft_aware_and_nightly_blind():
+def test_lume_api_filter_is_exact_draft_aware_and_channel_scoped():
body = shell_function(LUME_INSTALLER.read_text(), "get_latest_lume_tag")
- assert "tag ~ /^lume-v[0-9]+\\.[0-9]+\\.[0-9]+$/" in body
+ assert 'awk -v prefix="$LUME_TAG_PREFIX" -v channel="$LUME_CHANNEL"' in body
+ assert 'channel == "stable"' in body
+ assert 'channel == "nightly"' in body
assert '"draft"[[:space:]]*:[[:space:]]*false' in body
- assert "nightly-lume" not in body.split('if [ -n "$LUME_BAKED_VERSION" ]', 1)[1]
+
+
+def test_installers_make_channel_persistent_but_keep_exact_pins_one_shot():
+ lume = LUME_INSTALLER.read_text()
+ driver = (ROOT / "libs/cua-driver/scripts/_install-rust.sh").read_text()
+ windows = (ROOT / "libs/cua-driver/scripts/install.ps1").read_text(encoding="utf-8-sig")
+
+ assert 'RELEASE_CHANNEL_PATH="$LUME_HOME/release-channel"' in lume
+ assert 'if [ "$LUME_CHANNEL_EXPLICIT" = true ]' in lume
+ assert "--channel cannot be combined with LUME_VERSION" in lume
+ assert 'if [ -n "$LUME_VERSION" ]; then' in lume
+ assert lume.index('if [ -n "$LUME_VERSION" ]; then') < lume.index(
+ 'elif [ -f "$RELEASE_CHANNEL_PATH" ]; then'
+ )
+ assert 'CHANNEL_STATE_FILE="$HOME_DIR/release-channel"' in driver
+ assert 'if [[ "$CHANNEL_EXPLICIT" == "1" ]]' in driver
+ assert "--channel cannot be combined with CUA_DRIVER_RS_VERSION" in driver
+ assert 'elif [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; then' in driver
+ assert '$ReleaseChannelPath = Join-Path $HomeDir "release-channel"' in windows
+ assert "if ($ChannelWasExplicit)" in windows
+ assert "-Channel cannot be combined with an exact release pin" in windows
+ pin_precedence = "if ($env:CUA_DRIVER_RS_VERSION -or $Release -ne 'latest')"
+ assert windows.index(pin_precedence) < windows.index(
+ "if (Test-Path -LiteralPath $ReleaseChannelPath)"
+ )
def test_driver_download_uses_the_resolved_tag_not_the_stable_prefix():
diff --git a/docs/content/docs/how-to-guides/driver/install.mdx b/docs/content/docs/how-to-guides/driver/install.mdx
index a83d8589fd..9b9b74841e 100644
--- a/docs/content/docs/how-to-guides/driver/install.mdx
+++ b/docs/content/docs/how-to-guides/driver/install.mdx
@@ -92,10 +92,40 @@ cua-driver doctor
`doctor` checks the version, install layout, and telemetry setup on every platform. It also runs platform probes for TCC on macOS, the interactive session on Windows, and AT-SPI plus the display server on Linux.
+## Follow the nightly channel
+
+Stable is the default. To install the newest nightly and save that preference:
+
+<Tabs items={['macOS and Linux', 'Windows']}>
+ <Tab value="macOS and Linux">
+
+```bash
+curl -fsSL https://cua.ai/driver/install.sh | bash -s -- --channel nightly
+```
+
+ </Tab>
+ <Tab value="Windows">
+
+```powershell
+& ([scriptblock]::Create((irm https://cua.ai/driver/install.ps1))) -Channel nightly
+```
+
+ </Tab>
+</Tabs>
+
+Later `cua-driver check-update` and `cua-driver update --apply` stay on nightly.
+Switch back without reinstalling immediately with:
+
+```bash
+cua-driver channel set stable
+cua-driver update --apply
+```
+
+`channel set` saves intent only; `update --apply` performs the binary change.
+
## Install an exact nightly
-Nightlies are immutable builds of exact `main` commits. They are opt-in and do
-not replace stable update discovery. Copy the full
+Nightlies are immutable builds of exact `main` commits. Copy the full
`nightly-cua-driver-rs-v…` tag from the component's GitHub release, then pin
that tag during installation:
@@ -119,9 +149,10 @@ Remove-Item Env:CUA_DRIVER_RS_VERSION
</Tab>
</Tabs>
-The pin is one-shot: later runs of the ordinary installer return to the baked
-stable release. Exact pins never fall back to another release when an asset is
-missing.
+The pin is one-shot: it does not change the saved update channel. A machine
+without a saved preference therefore remains on stable; a machine following
+nightly keeps following nightly. Exact pins never fall back to another release
+when an asset is missing, and cannot be combined with `--channel`.
## Choose a permission mode
diff --git a/docs/content/docs/how-to-guides/driver/update.mdx b/docs/content/docs/how-to-guides/driver/update.mdx
index c3201a6ee2..e74f98bd5d 100644
--- a/docs/content/docs/how-to-guides/driver/update.mdx
+++ b/docs/content/docs/how-to-guides/driver/update.mdx
@@ -35,6 +35,19 @@ restarting a long-running daemon or worker.
## Check for updates
+Checks use the saved channel. Existing installations default to `stable`.
+Inspect or change it with:
+
+```bash
+cua-driver channel status
+cua-driver channel set nightly
+cua-driver update --apply
+```
+
+Changing the channel does not install by itself. A stable/nightly transition is
+reported as available even when the target version would not compare as newer
+under ordinary SemVer ordering.
+
```bash
cua-driver check-update
```
@@ -99,6 +112,8 @@ cua-driver check-update --json
```json
{
"current_version": "0.12.6",
+ "current_channel": "stable",
+ "selected_channel": "stable",
"latest_version": "0.13.0",
"update_available": true,
"source": "github_releases",
@@ -133,7 +148,10 @@ Every `cua-driver mcp`, `serve`, and `doctor` invocation starts a background ver
Release notes: https://github.com/trycua/cua/releases/tag/cua-driver-rs-v0.13.0
```
-The check uses a 20-hour cache and never blocks startup. One-shot commands such as `--version`, `call`, and `list-tools` skip it so piped output remains clean.
+The check uses a channel-keyed 20-hour cache and never blocks startup. A cached
+stable result can never satisfy a nightly check, or vice versa. One-shot
+commands such as `--version`, `call`, and `list-tools` skip it so piped output
+remains clean.
Disable the check for one invocation:
diff --git a/docs/content/docs/how-to-guides/lume/install-lume.mdx b/docs/content/docs/how-to-guides/lume/install-lume.mdx
index bfbb3977db..4ced5ad5e8 100644
--- a/docs/content/docs/how-to-guides/lume/install-lume.mdx
+++ b/docs/content/docs/how-to-guides/lume/install-lume.mdx
@@ -43,7 +43,26 @@ lume update --apply
The installer no longer creates scheduled auto-updaters. Older `lume-update` cron jobs and
LaunchAgents are removed the next time the installer runs.
-## Install an exact nightly
+## Choose a release channel
+
+To select nightlies for future checks and explicit updates, install the newest
+nightly and persist the channel in one command:
+
+```bash
+curl -fsSL https://cua.ai/lume/install.sh | bash -s -- --channel nightly
+```
+
+Later checks and explicit updates stay on nightly. Switch back with:
+
+```bash
+lume channel set stable
+lume update --apply
+```
+
+`channel set` never replaces the running binary by itself. Stable remains the
+default on machines without saved channel state.
+
+### Pin one exact nightly
Nightlies are immutable builds of exact `main` commits. Copy the full
`nightly-lume-v…` tag from the component's GitHub release and pass it as an
@@ -54,9 +73,9 @@ curl -fsSL https://cua.ai/lume/install.sh | \
LUME_VERSION=nightly-lume-v0.5.4-nightly.20260812.123456789 bash
```
-Nightlies do not participate in `lume check-update` or stable installer
-discovery. Run the ordinary installer again to return to the baked stable
-release.
+The pin does not change the saved channel and cannot be combined with
+`--channel`. Stable discovery remains blind to nightly tags, and nightly
+discovery remains blind to stable tags.
## Manual installation
diff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdx
index a996530424..aeef9605cd 100644
--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx
@@ -362,6 +362,38 @@ The distinct ID is replaced with a redacted placeholder.
| ---- | ----------- |
| `--json` | Emit JSON. |
+### `cua-driver channel`
+
+Inspect or change the stable/nightly update channel.
+
+Selection is persistent but never installs by itself; use cua-driver update --apply after changing it.
+
+#### `cua-driver channel status`
+
+Show selected and current release channels.
+
+**Flags:**
+
+| Name | Description |
+| ---- | ----------- |
+| `--json` | Emit machine-readable channel state. |
+
+#### `cua-driver channel set`
+
+Save stable or nightly as the update channel.
+
+**Arguments:**
+
+| Name | Type | Required | Description |
+| ---- | ---- | -------- | ----------- |
+| `<channel>` | String | Yes | stable or nightly |
+
+**Flags:**
+
+| Name | Description |
+| ---- | ----------- |
+| `--json` | Emit machine-readable channel state. |
+
### `cua-driver autostart`
Manage platform-native daemon autostart.
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 37641828c0..7fef799920 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -795,7 +795,7 @@ Stability: schema_version="1" is the contract. Future breaking changes will be `
### `check_for_update`
-Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Mirror of `cua-driver check-update --json`.
+Check the saved stable/nightly Cua Driver channel for a release on GitHub. Returns current and selected channels, current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Mirror of `cua-driver check-update --json`.
**Arguments:** none.
diff --git a/docs/content/docs/reference/lume/cli-reference.mdx b/docs/content/docs/reference/lume/cli-reference.mdx
index d8404f7b14..e47ad00d15 100644
--- a/docs/content/docs/reference/lume/cli-reference.mdx
+++ b/docs/content/docs/reference/lume/cli-reference.mdx
@@ -495,6 +495,16 @@ Check for a Lume update and optionally apply it
| `--apply` | false | Apply the update by re-running the official installer |
| `--json` | false | Emit the structured update-state payload as JSON |
+### lume channel
+
+Inspect or change the stable/nightly update channel; selection does not install
+
+**Subcommands:**
+
+- `lume channel status` - Show selected and current release channels
+- `lume channel set` - Save stable or nightly as the update channel
+ - `<channel>` - Release channel: stable or nightly
+
## Developer Tools
### lume dump-docs
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rs b/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rs
index aac7aad163..bc150cef6d 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rs
@@ -30,8 +30,8 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
fn def() -> &'static ToolDef {
DEF.get_or_init(|| ToolDef {
name: "check_for_update".into(),
- description: "Check whether a newer cua-driver-rs release is available on GitHub. \
- Returns the current and latest versions, an `update_available` boolean, \
+ description: "Check the saved stable/nightly Cua Driver channel for a release on GitHub. \
+ Returns current and selected channels, current and latest versions, an `update_available` boolean, \
the install one-liner, and the release notes URL. Read-only — never \
installs. Mirror of `cua-driver check-update --json`."
.into(),
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 665c42d176..fa59231cae 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -115,6 +115,12 @@ pub enum Command {
json: bool,
no_cache: bool,
},
+ /// Persist or inspect the stable/nightly release preference.
+ Channel {
+ subcommand: String,
+ value: Option<String>,
+ json: bool,
+ },
Doctor {
json: bool,
},
@@ -308,6 +314,7 @@ fn finite_command_name_from_args(args: &[String]) -> Option<&'static str> {
Some("dump-docs") => Some("dump_docs"),
Some("update") => Some("update"),
Some("check-update") => Some("check_update"),
+ Some("channel") => Some("channel"),
Some("doctor") => Some("doctor"),
Some("diagnose") => Some("diagnose"),
Some("permissions") => Some("permissions"),
@@ -402,6 +409,11 @@ fn finite_operation_from_args(args: &[String]) -> &'static str {
},
Some("update") if args.iter().any(|arg| arg == "--apply") => "apply",
Some("update") => "check_only",
+ Some("channel") => match subcommand.unwrap_or("status") {
+ "status" => "status",
+ "set" => "set",
+ _ => "other",
+ },
_ => "not_applicable",
}
}
@@ -471,7 +483,7 @@ pub fn parse_command() -> Command {
env!("CARGO_PKG_VERSION")
);
println!("Usage: cua-driver [SUBCOMMAND] [OPTIONS]");
- println!("Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, browser-approve, manifest, cursor-theme, sessions");
+ println!("Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, browser-approve, manifest, channel, cursor-theme, sessions");
println!();
println!("permissions options (macOS):");
println!(" cua-driver permissions status Report Accessibility + Screen Recording status. Read-only (no prompt).");
@@ -492,6 +504,9 @@ pub fn parse_command() -> Command {
println!(" cua-driver update Same check as above, then suggest --apply if outdated.");
println!(" --apply Download + install the latest release via the canonical installer.");
println!(" --json Emit the structured check payload (does not change --apply behaviour).");
+ println!(" cua-driver channel status Show the saved stable/nightly update channel.");
+ println!(" cua-driver channel set <name> Save stable or nightly; run update --apply to switch binaries.");
+ println!(" --json Emit machine-readable channel state.");
println!();
println!("autostart options (Windows-only today):");
println!(" cua-driver autostart enable Register a logon Scheduled Task so serve starts at every interactive logon.");
@@ -812,6 +827,23 @@ pub fn parse_command() -> Command {
let no_cache = args.iter().any(|a| a == "--no-cache");
Command::CheckUpdate { json, no_cache }
}
+ Some("channel") => {
+ let subcommand = pos.next().unwrap_or("status").to_owned();
+ let value = pos.next().map(str::to_owned);
+ if !matches!(subcommand.as_str(), "status" | "set") {
+ eprintln!("Unknown channel subcommand '{subcommand}'. Valid: status, set");
+ process::exit(64);
+ }
+ if subcommand == "set" && value.is_none() {
+ eprintln!("Usage: cua-driver channel set <stable|nightly>");
+ process::exit(64);
+ }
+ Command::Channel {
+ subcommand,
+ value,
+ json: args.iter().any(|arg| arg == "--json"),
+ }
+ }
Some("doctor") => {
// `--json` switches to machine-readable output for scripting.
// Bare flag — no value, position-independent.
@@ -1631,6 +1663,13 @@ pub fn build_manifest() -> serde_json::Value {
{ "name": "--json", "type": "flag", "description": "Emit the structured check payload." },
{ "name": "--no-cache", "type": "flag", "description": "Force a fresh GitHub round-trip." }
] },
+ { "name": "channel",
+ "description": "Inspect or persist the stable/nightly release channel.",
+ "args": [
+ { "name": "subcommand", "type": "positional-string", "description": "status | set. Default: status." },
+ { "name": "channel", "type": "positional-string", "description": "stable | nightly (required for set)." },
+ { "name": "--json", "type": "flag", "description": "Emit machine-readable channel state." }
+ ] },
{ "name": "doctor",
"description": "Self-diagnose probes for runtime prerequisites (permissions, accessibility, capture, etc.).",
"args": [ { "name": "--json", "type": "flag", "description": "Machine-readable doctor report." } ] },
@@ -2412,6 +2451,14 @@ pub fn run_update_cmd(apply: bool, json: bool) {
}
let current = env!("CARGO_PKG_VERSION");
+ let selected_channel = crate::release_channel::selected().unwrap_or_else(|error| {
+ eprintln!("Cannot read release channel: {error}");
+ eprintln!(
+ "Repair it with `cua-driver channel set stable` or `cua-driver channel set nightly`."
+ );
+ process::exit(1);
+ });
+ let current_channel = crate::release_channel::ReleaseChannel::from_version(current);
if !json {
println!("Current version: {current}");
println!("Checking for updates…");
@@ -2444,7 +2491,14 @@ pub fn run_update_cmd(apply: bool, json: bool) {
}
process::exit(1);
}
- Ok(v) if !crate::version_check::is_newer(&v, current) => {
+ Ok(v)
+ if !crate::version_check::update_is_available(
+ &v,
+ current,
+ current_channel,
+ selected_channel,
+ ) =>
+ {
crate::telemetry::capture_update_checked(
crate::telemetry::UpdateCheckSource::Cli,
crate::telemetry::UpdateCheckOutcome::UpToDate,
@@ -3092,6 +3146,58 @@ pub fn run_check_update_cmd(json: bool, no_cache: bool) {
}
}
+/// Inspect or persist the release channel. Selection never installs by itself;
+/// replacement remains explicit through `cua-driver update --apply`.
+pub fn run_channel_cmd(subcommand: &str, value: Option<&str>, json: bool) {
+ let result = match subcommand {
+ "status" => crate::release_channel::selected(),
+ "set" => {
+ let channel = value
+ .unwrap_or_default()
+ .parse::<crate::release_channel::ReleaseChannel>()
+ .unwrap_or_else(|error| {
+ eprintln!("{error}");
+ process::exit(64);
+ });
+ if let Err(error) = crate::release_channel::set(channel) {
+ eprintln!("Failed to save release channel: {error}");
+ process::exit(1);
+ }
+ Ok(channel)
+ }
+ _ => unreachable!("validated by parse_command"),
+ };
+
+ let selected = result.unwrap_or_else(|error| {
+ eprintln!("Failed to read release channel: {error}");
+ eprintln!(
+ "Repair it with `cua-driver channel set stable` or `cua-driver channel set nightly`."
+ );
+ process::exit(1);
+ });
+ let current = crate::release_channel::ReleaseChannel::from_version(env!("CARGO_PKG_VERSION"));
+
+ if json {
+ println!(
+ "{}",
+ serde_json::json!({
+ "selected_channel": selected.as_str(),
+ "current_channel": current.map(|channel| channel.as_str()),
+ "current_version": env!("CARGO_PKG_VERSION"),
+ })
+ );
+ } else {
+ println!("Selected channel: {selected}");
+ match current {
+ Some(channel) => println!("Current channel: {channel}"),
+ None => println!("Current channel: development"),
+ }
+ if subcommand == "set" && current != Some(selected) {
+ println!("Run `cua-driver update --apply` to install the latest {selected} release.");
+ }
+ }
+}
+
fn cli_docs_json() -> serde_json::Value {
let no_args: Vec<serde_json::Value> = Vec::new();
let no_options: Vec<serde_json::Value> = Vec::new();
@@ -3326,6 +3432,18 @@ fn cli_docs_json() -> serde_json::Value {
],
"subcommands": no_subcommands
},
+ {
+ "name": "channel",
+ "abstract": "Inspect or change the stable/nightly update channel.",
+ "discussion": "Selection is persistent but never installs by itself; use cua-driver update --apply after changing it.",
+ "arguments": no_args,
+ "options": no_options,
+ "flags": no_flags,
+ "subcommands": [
+ {"name":"status","abstract":"Show selected and current release channels.","discussion":"","arguments":[],"options":[],"flags":[{"name":"json","short_name":null,"help":"Emit machine-readable channel state.","default_value":false}],"subcommands":[]},
+ {"name":"set","abstract":"Save stable or nightly as the update channel.","discussion":"","arguments":[{"name":"channel","help":"stable or nightly","type":"String","is_optional":false}],"options":[],"flags":[{"name":"json","short_name":null,"help":"Emit machine-readable channel state.","default_value":false}],"subcommands":[]}
+ ]
+ },
{
"name": "doctor",
"abstract": "Run platform-aware diagnostic probes.",
@@ -4075,6 +4193,11 @@ mod tests {
"apply"
);
assert_eq!(finite_operation_from_args(&args(&["update"])), "check_only");
+ assert_eq!(finite_operation_from_args(&args(&["channel"])), "status");
+ assert_eq!(
+ finite_operation_from_args(&args(&["channel", "set", "private-value"])),
+ "set"
+ );
assert_eq!(
finite_operation_from_args(&args(&["doctor", "private-value"])),
"not_applicable"
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index d62fdb19b1..91ced04596 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -25,6 +25,7 @@ mod doctor;
mod mcp_http;
mod private_worker;
mod proxy;
+mod release_channel;
mod responsibility;
mod sdk_adapter;
mod serve;
@@ -725,6 +726,13 @@ fn main() {
cli::Command::CheckUpdate { json, no_cache } => {
cli::run_check_update_cmd(json, no_cache);
}
+ cli::Command::Channel {
+ subcommand,
+ value,
+ json,
+ } => {
+ cli::run_channel_cmd(&subcommand, value.as_deref(), json);
+ }
cli::Command::Doctor { json } => {
// Long-running interactive entry point — kick off the
// background "new version available?" check so the banner
@@ -988,6 +996,14 @@ fn main() -> anyhow::Result<()> {
cli::run_check_update_cmd(json, no_cache);
return Ok(());
}
+ cli::Command::Channel {
+ subcommand,
+ value,
+ json,
+ } => {
+ cli::run_channel_cmd(&subcommand, value.as_deref(), json);
+ return Ok(());
+ }
cli::Command::Doctor { json } => {
// Long-running interactive entry point — kick off the
// background update check so the banner can land on stderr.
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/release_channel.rs b/libs/cua-driver/rust/crates/cua-driver/src/release_channel.rs
new file mode 100644
index 0000000000..35a922e281
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/src/release_channel.rs
@@ -0,0 +1,178 @@
+//! Persistent stable/nightly update-channel preference.
+
+use std::fmt;
+use std::path::PathBuf;
+use std::str::FromStr;
+
+pub const FILE_NAME: &str = "release-channel";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ReleaseChannel {
+ Stable,
+ Nightly,
+}
+
+impl ReleaseChannel {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Stable => "stable",
+ Self::Nightly => "nightly",
+ }
+ }
+
+ pub fn from_version(version: &str) -> Option<Self> {
+ let parsed = semver::Version::parse(version).ok()?;
+ if parsed.build.is_empty() && parsed.pre.is_empty() && parsed.to_string() == version {
+ Some(Self::Stable)
+ } else if parsed.build.is_empty()
+ && parsed.to_string() == version
+ && is_canonical_nightly_prerelease(parsed.pre.as_str())
+ {
+ Some(Self::Nightly)
+ } else {
+ None
+ }
+ }
+}
+
+fn is_canonical_nightly_prerelease(value: &str) -> bool {
+ let Some(suffix) = value.strip_prefix("nightly.") else {
+ return false;
+ };
+ let Some((date, run)) = suffix.split_once('.') else {
+ return false;
+ };
+ date.len() == 8
+ && date.bytes().all(|byte| byte.is_ascii_digit())
+ && !run.is_empty()
+ && run.bytes().all(|byte| byte.is_ascii_digit())
+ && !run.starts_with('0')
+}
+
+impl Default for ReleaseChannel {
+ fn default() -> Self {
+ Self::Stable
+ }
+}
+
+impl fmt::Display for ReleaseChannel {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+impl FromStr for ReleaseChannel {
+ type Err = String;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ match value.trim() {
+ "stable" => Ok(Self::Stable),
+ "nightly" => Ok(Self::Nightly),
+ other => Err(format!(
+ "invalid release channel {other:?}; expected `stable` or `nightly`"
+ )),
+ }
+ }
+}
+
+pub fn selected() -> Result<ReleaseChannel, String> {
+ let path = state_path()?;
+ selected_at(&path)
+}
+
+fn selected_at(path: &std::path::Path) -> Result<ReleaseChannel, String> {
+ match std::fs::read_to_string(path) {
+ Ok(raw) => raw.parse(),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(ReleaseChannel::Stable),
+ Err(error) => Err(format!(
+ "cannot read release channel at {}: {error}",
+ path.display()
+ )),
+ }
+}
+
+pub fn set(channel: ReleaseChannel) -> Result<(), String> {
+ let path = state_path()?;
+ set_at(&path, channel)
+}
+
+fn set_at(path: &std::path::Path, channel: ReleaseChannel) -> Result<(), String> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| "release-channel path has no parent".to_owned())?;
+ std::fs::create_dir_all(parent)
+ .map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
+
+ let temporary = parent.join(format!(".{FILE_NAME}.tmp-{}", std::process::id()));
+ std::fs::write(&temporary, format!("{}\n", channel.as_str()))
+ .map_err(|error| format!("cannot write {}: {error}", temporary.display()))?;
+ if let Err(error) = std::fs::rename(&temporary, &path) {
+ // std::fs::rename cannot replace an existing destination on Windows.
+ // Keep partial contents out of the canonical path on all platforms.
+ if path.exists() {
+ std::fs::remove_file(&path)
+ .map_err(|remove| format!("cannot replace {}: {remove}", path.display()))?;
+ std::fs::rename(&temporary, &path)
+ .map_err(|move_error| format!("cannot replace {}: {move_error}", path.display()))?;
+ } else {
+ return Err(format!("cannot persist {}: {error}", path.display()));
+ }
+ }
+ Ok(())
+}
+
+pub fn state_path() -> Result<PathBuf, String> {
+ if let Some(home) = std::env::var_os("CUA_DRIVER_RS_HOME") {
+ return Ok(PathBuf::from(home).join(FILE_NAME));
+ }
+ let root = std::env::var_os("HOME")
+ .or_else(|| std::env::var_os("USERPROFILE"))
+ .ok_or_else(|| "neither HOME nor USERPROFILE is set".to_owned())?;
+ Ok(PathBuf::from(root)
+ .join(crate::bundle::user_home_subdirectory())
+ .join(FILE_NAME))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn strict_channel_vocabulary() {
+ assert_eq!("stable".parse(), Ok(ReleaseChannel::Stable));
+ assert_eq!("nightly\n".parse(), Ok(ReleaseChannel::Nightly));
+ assert!("beta".parse::<ReleaseChannel>().is_err());
+ assert!("".parse::<ReleaseChannel>().is_err());
+ }
+
+ #[test]
+ fn current_channel_uses_strict_version_shape() {
+ assert_eq!(
+ ReleaseChannel::from_version("0.19.3"),
+ Some(ReleaseChannel::Stable)
+ );
+ assert_eq!(
+ ReleaseChannel::from_version("0.19.4-nightly.20260812.42"),
+ Some(ReleaseChannel::Nightly)
+ );
+ assert_eq!(ReleaseChannel::from_version("0.19.4-dev"), None);
+ assert_eq!(ReleaseChannel::from_version("0.19.4-nightly.foo"), None);
+ assert_eq!(ReleaseChannel::from_version("0.19.4+build"), None);
+ assert_eq!(
+ ReleaseChannel::from_version("0.19.4-nightly.20260812.0"),
+ None
+ );
+ }
+
+ #[test]
+ fn missing_state_defaults_stable_and_valid_state_round_trips() {
+ let root = tempfile::tempdir().expect("tempdir");
+ let path = root.path().join(FILE_NAME);
+ assert_eq!(selected_at(&path), Ok(ReleaseChannel::Stable));
+ set_at(&path, ReleaseChannel::Nightly).expect("persist nightly");
+ assert_eq!(selected_at(&path), Ok(ReleaseChannel::Nightly));
+ set_at(&path, ReleaseChannel::Stable).expect("persist stable");
+ assert_eq!(selected_at(&path), Ok(ReleaseChannel::Stable));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs
index fa14a8f3e0..80af2396e9 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs
@@ -61,6 +61,7 @@ const HTTP_TIMEOUT_SECONDS: u64 = 4;
/// Releases tagged with anything else (e.g. the Swift port's
/// `cua-driver-v*`) are filtered out so we never recommend the wrong binary.
pub const RELEASE_TAG_PREFIX: &str = "cua-driver-rs-v";
+pub const NIGHTLY_RELEASE_TAG_PREFIX: &str = "nightly-cua-driver-rs-v";
/// GitHub releases API endpoint. Paginates newest-first; 40 entries is
/// plenty of headroom past the most recent stable release even when
@@ -116,6 +117,8 @@ pub fn maybe_announce_update() {
#[derive(serde::Serialize, Debug, Clone)]
pub struct UpdateState {
pub current_version: String,
+ pub current_channel: Option<&'static str>,
+ pub selected_channel: Option<&'static str>,
/// `None` when the network fetch failed and no usable cache existed —
/// the `error` field carries the human-readable reason.
pub latest_version: Option<String>,
@@ -194,6 +197,28 @@ pub fn check_update_state(no_cache: bool) -> UpdateState {
let now = unix_now();
let checked_at = iso8601(now);
+ let current_channel = crate::release_channel::ReleaseChannel::from_version(&current);
+ let selected_channel = match crate::release_channel::selected() {
+ Ok(channel) => channel,
+ Err(error) => {
+ return UpdateState {
+ current_version: current,
+ current_channel: current_channel.map(|channel| channel.as_str()),
+ selected_channel: None,
+ latest_version: None,
+ update_available: false,
+ source: "github_releases",
+ checked_at,
+ cache_hit: false,
+ install_command: None,
+ release_notes_url: None,
+ error: Some(format!(
+ "{error}; run `cua-driver channel set stable` or `cua-driver channel set nightly` to repair it"
+ )),
+ };
+ }
+ };
+
let cached = read_cache().unwrap_or_default();
let cache_fresh = cached
.last_checked_unix
@@ -202,18 +227,22 @@ pub fn check_update_state(no_cache: bool) -> UpdateState {
// Honour the cache unless caller explicitly asked us to bypass it.
// Mirrors `npm outdated --no-cache` / `brew update --force` semantics.
- let use_cache = !no_cache && cache_fresh && cached.latest_version.is_some();
+ let cache_channel_matches =
+ cached.channel.as_deref().unwrap_or("stable") == selected_channel.as_str();
+ let use_cache =
+ !no_cache && cache_fresh && cache_channel_matches && cached.latest_version.is_some();
let (latest, cache_hit, fetch_error) = if use_cache {
(cached.latest_version.clone(), true, None)
} else {
- match fetch_latest_version() {
+ match fetch_latest_version_for(selected_channel) {
Ok(v) => {
// Persist on success so the next launch can reuse the answer.
let new_cache = VersionCache {
last_checked_unix: Some(now),
last_checked_at: Some(checked_at.clone()),
latest_version: Some(v.clone()),
+ channel: Some(selected_channel.as_str().to_owned()),
dismissed_versions: cached.dismissed_versions.clone(),
};
if let Err(e) = write_cache(&new_cache) {
@@ -228,7 +257,11 @@ pub fn check_update_state(no_cache: bool) -> UpdateState {
// surfaces only when no cache is available.
tracing::debug!(target: "cua_driver::version_check",
"fetch failed: {e}");
- match cached.latest_version.clone() {
+ match cached
+ .latest_version
+ .clone()
+ .filter(|_| cache_channel_matches)
+ {
Some(v) => (Some(v), true, None),
None => (None, false, Some(e)),
}
@@ -238,7 +271,7 @@ pub fn check_update_state(no_cache: bool) -> UpdateState {
let update_available = latest
.as_deref()
- .map(|l| is_newer(l, &current))
+ .map(|latest| update_is_available(latest, &current, current_channel, selected_channel))
.unwrap_or(false);
let (install_command, release_notes_url) = if update_available {
@@ -246,7 +279,8 @@ pub fn check_update_state(no_cache: bool) -> UpdateState {
(
Some(install_one_liner()),
Some(format!(
- "https://github.com/trycua/cua/releases/tag/{RELEASE_TAG_PREFIX}{l}"
+ "https://github.com/trycua/cua/releases/tag/{}{l}",
+ tag_prefix(selected_channel)
)),
)
} else {
@@ -255,6 +289,8 @@ pub fn check_update_state(no_cache: bool) -> UpdateState {
UpdateState {
current_version: current,
+ current_channel: current_channel.map(|channel| channel.as_str()),
+ selected_channel: Some(selected_channel.as_str()),
latest_version: latest,
update_available,
source: "github_releases",
@@ -303,13 +339,19 @@ where
W: std::io::Write,
{
let now = unix_now();
+ let Ok(selected_channel) = crate::release_channel::selected() else {
+ return;
+ };
// Decide whether the cache is still fresh enough to skip the network.
let cached = read_cache().unwrap_or_default();
+ let cache_channel_matches =
+ cached.channel.as_deref().unwrap_or("stable") == selected_channel.as_str();
let needs_refresh = cached
.last_checked_unix
.map(|t| now.saturating_sub(t) >= CACHE_REFRESH_SECONDS)
- .unwrap_or(true);
+ .unwrap_or(true)
+ || !cache_channel_matches;
let (latest, cache_hit) = if needs_refresh {
match fetch() {
@@ -319,6 +361,7 @@ where
last_checked_unix: Some(now),
last_checked_at: Some(iso8601(now)),
latest_version: Some(v.clone()),
+ channel: Some(selected_channel.as_str().to_owned()),
dismissed_versions: cached.dismissed_versions.clone(),
};
if let Err(e) = write_cache(&new_cache) {
@@ -332,14 +375,22 @@ where
"fetch failed: {e}");
// Fall back to the cached value if any — better an old
// banner than none on a brief network blip.
- match cached.latest_version.clone() {
+ match cached
+ .latest_version
+ .clone()
+ .filter(|_| cache_channel_matches)
+ {
Some(v) => (v, true),
None => return,
}
}
}
} else {
- match cached.latest_version.clone() {
+ match cached
+ .latest_version
+ .clone()
+ .filter(|_| cache_channel_matches)
+ {
Some(v) => (v, true),
None => return,
}
@@ -351,7 +402,8 @@ where
.map(|c| c.dismissed_versions)
.unwrap_or(cached.dismissed_versions);
- if !is_newer(&latest, current) {
+ let current_channel = crate::release_channel::ReleaseChannel::from_version(current);
+ if !update_is_available(&latest, current, current_channel, selected_channel) {
return;
}
if dismissed.iter().any(|v| v == &latest) {
@@ -371,7 +423,7 @@ where
);
}
- let banner = format_banner(&latest, current);
+ let banner = format_banner(&latest, current, selected_channel);
if let Err(e) = writer.write_all(banner.as_bytes()) {
tracing::debug!(target: "cua_driver::version_check",
"failed to print banner: {e}");
@@ -381,12 +433,16 @@ where
/// Format the two-line banner. Plain text, no ANSI colours — terminals
/// without UTF-8 still see the `✨` byte sequence but the text is
/// readable either way.
-fn format_banner(latest: &str, current: &str) -> String {
+fn format_banner(
+ latest: &str,
+ current: &str,
+ channel: crate::release_channel::ReleaseChannel,
+) -> String {
format!(
"\n\u{2728} cua-driver v{latest} is available (you have v{current}).\n \
Update with: cua-driver update\n \
Release notes: https://github.com/trycua/cua/releases/tag/{prefix}{latest}\n\n",
- prefix = RELEASE_TAG_PREFIX,
+ prefix = tag_prefix(channel),
)
}
@@ -405,7 +461,10 @@ fn is_enabled() -> bool {
if let Some(false) = read_config_flag() {
return false;
}
- if is_prerelease(env!("CARGO_PKG_VERSION")) {
+ if is_prerelease(env!("CARGO_PKG_VERSION"))
+ && crate::release_channel::ReleaseChannel::from_version(env!("CARGO_PKG_VERSION"))
+ != Some(crate::release_channel::ReleaseChannel::Nightly)
+ {
return false;
}
true
@@ -462,6 +521,18 @@ pub fn is_newer(latest: &str, current: &str) -> bool {
l > c
}
+pub fn update_is_available(
+ latest: &str,
+ current: &str,
+ current_channel: Option<crate::release_channel::ReleaseChannel>,
+ selected_channel: crate::release_channel::ReleaseChannel,
+) -> bool {
+ current_channel
+ .map(|channel| channel != selected_channel)
+ .unwrap_or(false)
+ || is_newer(latest, current)
+}
+
// ── On-disk cache ────────────────────────────────────────────────────────
/// Serialised shape of `~/.cua-driver-rs/version_check.json`.
@@ -478,6 +549,8 @@ pub(crate) struct VersionCache {
pub last_checked_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latest_version: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub channel: Option<String>,
#[serde(default)]
pub dismissed_versions: Vec<String>,
}
@@ -540,6 +613,13 @@ fn cache_path() -> Option<PathBuf> {
/// human-readable error string on failure. The caller is expected to
/// downgrade errors to `tracing::debug!`.
pub fn fetch_latest_version() -> Result<String, String> {
+ let channel = crate::release_channel::selected()?;
+ fetch_latest_version_for(channel)
+}
+
+pub fn fetch_latest_version_for(
+ channel: crate::release_channel::ReleaseChannel,
+) -> Result<String, String> {
let agent = ureq::Agent::config_builder()
.timeout_global(Some(std::time::Duration::from_secs(HTTP_TIMEOUT_SECONDS)))
.build()
@@ -560,27 +640,40 @@ pub fn fetch_latest_version() -> Result<String, String> {
.read_json()
.map_err(|e| format!("JSON parse error: {e}"))?;
- pick_latest_release(&body)
- .ok_or_else(|| "no matching cua-driver-rs-v* release in response".to_owned())
+ pick_latest_release(&body, channel)
+ .ok_or_else(|| format!("no matching {}* release in response", tag_prefix(channel)))
}
/// Pull the highest non-draft `cua-driver-rs-v*` tag out of the parsed
/// releases response. Split out so unit tests can feed in canned JSON
/// without hitting the network. Pre-release flag is intentionally
/// ignored — see `fetch_latest_version` doc-comment.
-pub(crate) fn pick_latest_release(body: &serde_json::Value) -> Option<String> {
+pub(crate) fn pick_latest_release(
+ body: &serde_json::Value,
+ channel: crate::release_channel::ReleaseChannel,
+) -> Option<String> {
let releases = body.as_array()?;
let mut versions: Vec<semver::Version> = releases
.iter()
.filter_map(|r| {
let tag = r.get("tag_name")?.as_str()?;
- let bare = tag.strip_prefix(RELEASE_TAG_PREFIX)?;
+ let bare = tag.strip_prefix(tag_prefix(channel))?;
if r.get("draft").and_then(|d| d.as_bool()).unwrap_or(false) {
return None;
}
let version = semver::Version::parse(bare).ok()?;
- if !version.pre.is_empty() || !version.build.is_empty() {
- return None;
+ match channel {
+ crate::release_channel::ReleaseChannel::Stable
+ if !version.pre.is_empty() || !version.build.is_empty() =>
+ {
+ return None
+ }
+ crate::release_channel::ReleaseChannel::Nightly
+ if !is_canonical_nightly(&version) =>
+ {
+ return None
+ }
+ _ => {}
}
Some(version)
})
@@ -589,6 +682,23 @@ pub(crate) fn pick_latest_release(body: &serde_json::Value) -> Option<String> {
versions.last().map(|v| v.to_string())
}
+fn tag_prefix(channel: crate::release_channel::ReleaseChannel) -> &'static str {
+ match channel {
+ crate::release_channel::ReleaseChannel::Stable => RELEASE_TAG_PREFIX,
+ crate::release_channel::ReleaseChannel::Nightly => NIGHTLY_RELEASE_TAG_PREFIX,
+ }
+}
+
+fn is_canonical_nightly(version: &semver::Version) -> bool {
+ let parts: Vec<&str> = version.pre.as_str().split('.').collect();
+ parts.len() == 3
+ && parts[0] == "nightly"
+ && parts[1].len() == 8
+ && parts[1].bytes().all(|byte| byte.is_ascii_digit())
+ && parts[2].parse::<u64>().map(|run| run > 0).unwrap_or(false)
+ && version.build.is_empty()
+}
+
// ── Time helpers ─────────────────────────────────────────────────────────
fn unix_now() -> u64 {
@@ -693,6 +803,23 @@ mod tests {
assert!(is_newer("0.1.3", "0.1.3-dev"));
}
+ #[test]
+ fn channel_mismatch_is_available_even_when_target_version_is_lower() {
+ use crate::release_channel::ReleaseChannel::{Nightly, Stable};
+ assert!(update_is_available(
+ "0.19.3",
+ "0.19.4-nightly.20260812.42",
+ Some(Nightly),
+ Stable,
+ ));
+ assert!(!update_is_available(
+ "0.19.3",
+ "0.19.4",
+ Some(Stable),
+ Stable,
+ ));
+ }
+
#[test]
fn is_newer_returns_false_for_equal_versions() {
assert!(!is_newer("0.1.3", "0.1.3"));
@@ -745,6 +872,7 @@ mod tests {
last_checked_unix: Some(1_700_000_000),
last_checked_at: Some("2023-11-14T22:13:20Z".into()),
latest_version: Some("0.1.4".into()),
+ channel: Some("stable".into()),
dismissed_versions: vec!["0.1.3".into()],
};
write_cache(&original).expect("write_cache");
@@ -794,6 +922,7 @@ mod tests {
last_checked_unix: Some(now.saturating_sub(21 * 60 * 60)),
last_checked_at: Some(iso8601(now.saturating_sub(21 * 60 * 60))),
latest_version: Some("0.1.3".into()), // stale data
+ channel: Some("stable".into()),
dismissed_versions: vec![],
};
write_cache(&stale).unwrap();
@@ -831,6 +960,7 @@ mod tests {
last_checked_unix: Some(now.saturating_sub(60 * 60)),
last_checked_at: Some(iso8601(now.saturating_sub(60 * 60))),
latest_version: Some("0.1.4".into()),
+ channel: Some("stable".into()),
dismissed_versions: vec![],
};
write_cache(&fresh).unwrap();
@@ -869,6 +999,7 @@ mod tests {
last_checked_unix: Some(now),
last_checked_at: Some(iso8601(now)),
latest_version: Some("0.1.4".into()),
+ channel: Some("stable".into()),
dismissed_versions: vec!["0.1.4".into()],
};
write_cache(&cache).unwrap();
@@ -1001,7 +1132,11 @@ mod tests {
#[test]
fn banner_contains_required_lines() {
- let banner = format_banner("0.1.4", "0.1.3");
+ let banner = format_banner(
+ "0.1.4",
+ "0.1.3",
+ crate::release_channel::ReleaseChannel::Stable,
+ );
// Headline.
assert!(
banner.contains("cua-driver v0.1.4 is available"),
@@ -1032,7 +1167,10 @@ mod tests {
{"tag_name": "cua-driver-rs-v0.1.3", "draft": false, "prerelease": false},
{"tag_name": "cua-driver-v9.9.9", "draft": false, "prerelease": false},
]);
- assert_eq!(pick_latest_release(&body).as_deref(), Some("0.1.4"));
+ assert_eq!(
+ pick_latest_release(&body, crate::release_channel::ReleaseChannel::Stable).as_deref(),
+ Some("0.1.4")
+ );
}
#[test]
@@ -1046,7 +1184,10 @@ mod tests {
{"tag_name": "cua-driver-rs-v0.1.5", "draft": false, "prerelease": true},
{"tag_name": "cua-driver-rs-v0.1.4", "draft": false, "prerelease": false},
]);
- assert_eq!(pick_latest_release(&body).as_deref(), Some("0.1.5"));
+ assert_eq!(
+ pick_latest_release(&body, crate::release_channel::ReleaseChannel::Stable).as_deref(),
+ Some("0.1.5")
+ );
}
#[test]
@@ -1064,12 +1205,35 @@ mod tests {
},
{"tag_name": "cua-driver-rs-v0.2.0", "draft": false, "prerelease": true},
]);
- assert_eq!(pick_latest_release(&body).as_deref(), Some("0.2.0"));
+ assert_eq!(
+ pick_latest_release(&body, crate::release_channel::ReleaseChannel::Stable).as_deref(),
+ Some("0.2.0")
+ );
+ }
+
+ #[test]
+ fn nightly_discovery_rejects_stable_and_wrong_prefix_tags() {
+ let body = serde_json::json!([
+ {"tag_name": "cua-driver-rs-v9.9.9", "draft": false},
+ {"tag_name": "cua-driver-rs-v0.20.0-nightly.20260812.99", "draft": false},
+ {"tag_name": "nightly-cua-driver-rs-v0.20.0-nightly.20260812.42", "draft": false},
+ {"tag_name": "nightly-cua-driver-rs-v0.20.0-nightly.20260812.7", "draft": false}
+ ]);
+ assert_eq!(
+ pick_latest_release(&body, crate::release_channel::ReleaseChannel::Nightly).as_deref(),
+ Some("0.20.0-nightly.20260812.42")
+ );
}
#[test]
fn pick_latest_release_returns_none_for_empty_array() {
- assert_eq!(pick_latest_release(&serde_json::json!([])), None);
+ assert_eq!(
+ pick_latest_release(
+ &serde_json::json!([]),
+ crate::release_channel::ReleaseChannel::Stable
+ ),
+ None
+ );
}
#[test]
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/release_channel_cli_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/release_channel_cli_test.rs
new file mode 100644
index 0000000000..94375c7f21
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/release_channel_cli_test.rs
@@ -0,0 +1,59 @@
+use std::process::Command;
+
+fn run(home: &std::path::Path, args: &[&str]) -> std::process::Output {
+ Command::new(env!("CARGO_BIN_EXE_cua-driver"))
+ .args(args)
+ .env("CUA_DRIVER_RS_HOME", home)
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "0")
+ .output()
+ .expect("run cua-driver")
+}
+
+#[test]
+fn channel_cli_persists_and_reports_the_selected_channel() {
+ let home = tempfile::tempdir().expect("temp home");
+
+ let initial = run(home.path(), &["channel", "status", "--json"]);
+ assert!(
+ initial.status.success(),
+ "{}",
+ String::from_utf8_lossy(&initial.stderr)
+ );
+ let initial: serde_json::Value = serde_json::from_slice(&initial.stdout).expect("initial json");
+ assert_eq!(initial["selected_channel"], "stable");
+
+ let changed = run(home.path(), &["channel", "set", "nightly", "--json"]);
+ assert!(
+ changed.status.success(),
+ "{}",
+ String::from_utf8_lossy(&changed.stderr)
+ );
+ assert_eq!(
+ std::fs::read_to_string(home.path().join("release-channel")).expect("saved preference"),
+ "nightly\n"
+ );
+
+ let status = run(home.path(), &["channel", "status", "--json"]);
+ assert!(
+ status.status.success(),
+ "{}",
+ String::from_utf8_lossy(&status.stderr)
+ );
+ let status: serde_json::Value = serde_json::from_slice(&status.stdout).expect("status json");
+ assert_eq!(status["selected_channel"], "nightly");
+}
+
+#[test]
+fn channel_cli_fails_closed_on_invalid_saved_state() {
+ let home = tempfile::tempdir().expect("temp home");
+ std::fs::write(home.path().join("release-channel"), "broken\n").expect("invalid state");
+
+ let output = run(home.path(), &["channel", "status", "--json"]);
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("expected `stable` or `nightly`"),
+ "{stderr}"
+ );
+ assert!(stderr.contains("channel set stable"), "{stderr}");
+}
diff --git a/libs/cua-driver/scripts/_install-rust.sh b/libs/cua-driver/scripts/_install-rust.sh
index 4853d8f143..8b11b9f408 100644
--- a/libs/cua-driver/scripts/_install-rust.sh
+++ b/libs/cua-driver/scripts/_install-rust.sh
@@ -21,6 +21,7 @@
# --bin-dir <path> install the visible binary/symlink to <path>
# instead of ~/.local/bin
# --no-modify-path skip auto-appending an `export PATH=...` line
+# --channel <name> persist and install the latest stable or nightly release
#
# Env overrides:
# CUA_DRIVER_RS_VERSION=0.1.2 pin a stable release
@@ -135,6 +136,8 @@ NO_MODIFY_PATH="${CUA_DRIVER_RS_NO_MODIFY_PATH:-0}"
# `current` resolves to is always preserved regardless of cutoff.
KEEP_VERSIONS_DEFAULT=5
KEEP_VERSIONS="${CUA_DRIVER_RS_KEEP_VERSIONS:-$KEEP_VERSIONS_DEFAULT}"
+CHANNEL_ARG=""
+CHANNEL_EXPLICIT=0
# macOS-only: name and install location of the .app bundle that wraps
# the bare binary so the TCC auto-relaunch path in `cua-driver mcp` has
@@ -152,6 +155,10 @@ while [[ $# -gt 0 ]]; do
--bin-dir) BIN_DIR="$2"; shift 2 ;;
--bin-dir=*) BIN_DIR="${1#*=}"; shift ;;
--no-modify-path) NO_MODIFY_PATH=1; shift ;;
+ --channel)
+ [[ -n "${2:-}" ]] || { printf 'error: --channel requires stable or nightly\n' >&2; exit 2; }
+ CHANNEL_ARG="$2"; CHANNEL_EXPLICIT=1; shift 2 ;;
+ --channel=*) CHANNEL_ARG="${1#*=}"; CHANNEL_EXPLICIT=1; shift ;;
*) shift ;;
esac
done
@@ -538,7 +545,11 @@ github_api_curl() {
# considering it. GitHub's REST response renders those top-level fields on
# separate lines in that order; nested author/assets objects have no tag_name.
extract_published_release_versions() {
- awk -v prefix="$TAG_PREFIX" '
+ # Keep this helper usable by stable-only callers and extracted test
+ # harnesses that predate persistent channel selection.
+ local selected_channel="${SELECTED_CHANNEL:-stable}"
+ local selected_tag_prefix="${SELECTED_TAG_PREFIX:-$TAG_PREFIX}"
+ awk -v prefix="$selected_tag_prefix" -v channel="$selected_channel" '
/"tag_name"[[:space:]]*:/ {
tag = $0
sub(/^.*"tag_name"[[:space:]]*:[[:space:]]*"/, "", tag)
@@ -550,7 +561,8 @@ extract_published_release_versions() {
version = tag
if (index(version, prefix) == 1) {
version = substr(version, length(prefix) + 1)
- if (version ~ /^[0-9]+\.[0-9]+\.[0-9]+$/) {
+ if ((channel == "stable" && version ~ /^[0-9]+\.[0-9]+\.[0-9]+$/) ||
+ (channel == "nightly" && version ~ /^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[1-9][0-9]*$/)) {
print version
}
}
@@ -575,9 +587,9 @@ resolve_latest_version_from_api() {
page_json="$(github_api_curl -fsSL \
"https://api.github.com/repos/$REPO/releases?per_page=100&page=$page")" || return 1
- # Extract only published exact stable x.y.z tags. Cua Driver's stable
- # tags are marked prerelease in GitHub metadata, so the tag syntax —
- # not the prerelease flag — decides semantic stability.
+ # Extract only published tags matching the selected channel's strict
+ # grammar. Cua Driver's stable tags are marked prerelease in GitHub
+ # metadata, so tag syntax—not the prerelease flag—defines the channel.
page_versions="$(printf '%s' "$page_json" | extract_published_release_versions)" || true
if [[ -n "$page_versions" ]]; then
versions="${versions}${versions:+$'\n'}${page_versions}"
@@ -597,7 +609,7 @@ resolve_latest_version_from_api() {
version="$(
printf '%s\n' "$versions" \
| sed '/^$/d' \
- | sort -t. -k1,1nr -k2,2nr -k3,3nr \
+ | sort -t. -k1,1nr -k2,2nr -k3,3nr -k4,4nr -k5,5nr \
| head -n 1
)"
[[ -n "$version" ]] || return 1
@@ -629,6 +641,32 @@ resolve_explicit_release_tag() {
return 1
}
+CHANNEL_STATE_FILE="$HOME_DIR/release-channel"
+if [[ "$CHANNEL_EXPLICIT" == "1" && -n "${CUA_DRIVER_RS_VERSION:-}" ]]; then
+ err "--channel cannot be combined with CUA_DRIVER_RS_VERSION; exact pins do not change saved channel state"
+ exit 2
+fi
+if [[ "$CHANNEL_EXPLICIT" == "1" ]]; then
+ SELECTED_CHANNEL="$CHANNEL_ARG"
+elif [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; then
+ # Exact pins are one-shot and outrank persisted preference. In particular,
+ # a damaged preference file must not make a deliberate recovery pin unusable.
+ SELECTED_CHANNEL="stable"
+elif [[ -f "$CHANNEL_STATE_FILE" ]]; then
+ SELECTED_CHANNEL="$(tr -d '[:space:]' < "$CHANNEL_STATE_FILE")"
+else
+ SELECTED_CHANNEL="stable"
+fi
+case "$SELECTED_CHANNEL" in
+ stable) SELECTED_TAG_PREFIX="$TAG_PREFIX" ;;
+ nightly) SELECTED_TAG_PREFIX="$NIGHTLY_TAG_PREFIX" ;;
+ *)
+ err "invalid release channel '$SELECTED_CHANNEL' in $CHANNEL_STATE_FILE; expected stable or nightly"
+ err " repair with: cua-driver channel set stable"
+ exit 1
+ ;;
+esac
+
if [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; then
VERSION_SOURCE="pin"
if ! TAG="$(resolve_explicit_release_tag "$CUA_DRIVER_RS_VERSION")"; then
@@ -636,7 +674,7 @@ if [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; then
exit 1
fi
log "using version from CUA_DRIVER_RS_VERSION: $TAG"
-elif [[ -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]]; then
+elif [[ "$SELECTED_CHANNEL" == "stable" && -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]]; then
VERSION_SOURCE="baked"
if ! [[ "$CUA_DRIVER_RS_BAKED_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
err "baked Cua Driver version must be an exact stable x.y.z version"
@@ -646,13 +684,13 @@ elif [[ -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]]; then
log "using baked release: $TAG"
else
VERSION_SOURCE="api"
- log "resolving latest $TAG_PREFIX* release via GitHub API"
+ log "resolving latest $SELECTED_CHANNEL release via GitHub API"
if ! API_VERSION="$(resolve_latest_version_from_api)"; then
- err "no release matching ${TAG_PREFIX}* found on $REPO"
+ err "no release matching ${SELECTED_TAG_PREFIX}* found on $REPO"
err " (cua-driver-rs is a BETA-stage cross-platform port; releases may not be published yet.)"
exit 1
fi
- TAG="${TAG_PREFIX}${API_VERSION}"
+ TAG="${SELECTED_TAG_PREFIX}${API_VERSION}"
log "latest release: $TAG"
fi
@@ -829,6 +867,14 @@ if [[ "$THEME_AVAILABLE" == "0" ]]; then
"$VERSION" >&2
fi
+if [[ "$CHANNEL_EXPLICIT" == "1" ]]; then
+ mkdir -p "$HOME_DIR"
+ CHANNEL_TMP="$HOME_DIR/.release-channel.$$"
+ printf '%s\n' "$SELECTED_CHANNEL" > "$CHANNEL_TMP"
+ mv -f "$CHANNEL_TMP" "$CHANNEL_STATE_FILE"
+ log "saved release channel: $SELECTED_CHANNEL"
+fi
+
# --- Install ------------------------------------------------------------
# Before staging the new release, sweep any prior install-local build that
diff --git a/libs/cua-driver/scripts/install.ps1 b/libs/cua-driver/scripts/install.ps1
index f8723ecc6d..776a709155 100644
--- a/libs/cua-driver/scripts/install.ps1
+++ b/libs/cua-driver/scripts/install.ps1
@@ -55,6 +55,8 @@
# -Release release to install ("latest", a bare stable version, or a
# canonical nightly-cua-driver-rs-v* tag).
# Overridden by $env:CUA_DRIVER_RS_VERSION when set.
+# -Channel persist and install the latest "stable" or "nightly" release.
+# Cannot be combined with an exact release pin.
# -AutoStart register a Scheduled Task that runs `cua-driver serve` at
# every logon (Windows-native equivalent of macOS LaunchAgent).
# The task runs with LogonType=Interactive so it lands in
@@ -77,6 +79,8 @@
[CmdletBinding()]
param(
[string]$Release = "latest",
+ [ValidateSet("stable", "nightly")]
+ [string]$Channel,
# Default-on: cua-driver-serve is what makes the agent flow work
# across logon / reboot. Without the scheduled task the user has
# to remember to run `cua-driver autostart kick` every time, and
@@ -154,6 +158,8 @@ $LegacyHomeDir = Join-Path $env:USERPROFILE ".cua-driver-rs"
$PackagesDir = Join-Path $HomeDir "packages"
$ReleasesDir = Join-Path $PackagesDir "releases"
$CurrentDir = Join-Path $PackagesDir "current"
+$ReleaseChannelPath = Join-Path $HomeDir "release-channel"
+$ChannelWasExplicit = $PSBoundParameters.ContainsKey('Channel')
# Post-install GC: how many per-version release dirs to retain. Validated
# in Resolve-KeepVersions below; 0 means "never GC".
@@ -908,7 +914,8 @@ function Get-LatestVersionFromApi {
# the API is unreachable or has no matching tag. Never exits: callers
# decide whether a miss is fatal, because this runs both as the primary
# resolver (fatal) and as a recovery step (advisory).
- Write-Step "resolving latest $TagPrefix* release via GitHub API"
+ $selectedPrefix = if ($Script:CuaDriverRsSelectedChannel -eq 'nightly') { $NightlyTagPrefix } else { $TagPrefix }
+ Write-Step "resolving latest $($Script:CuaDriverRsSelectedChannel) release via GitHub API"
# Paginate the /releases endpoint until we've seen every release or
# collected enough $TagPrefix* matches to be confident the latest is
# in hand. A single page (even at per_page=100) is not guaranteed to
@@ -931,8 +938,11 @@ function Get-LatestVersionFromApi {
$batch = Invoke-RestMethod -Uri $uri -Headers (Get-GitHubApiHeaders) -UseBasicParsing
if (-not $batch -or $batch.Count -eq 0) { break }
$releaseMatches += @($batch | Where-Object {
- (-not $_.draft) -and
- ($_.tag_name -match "^$([regex]::Escape($TagPrefix))([0-9]+\.[0-9]+\.[0-9]+)$")
+ if ($_.draft) { return $false }
+ if ($Script:CuaDriverRsSelectedChannel -eq 'nightly') {
+ return $_.tag_name -match "^$([regex]::Escape($selectedPrefix))([0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[1-9][0-9]*)$"
+ }
+ return $_.tag_name -match "^$([regex]::Escape($selectedPrefix))([0-9]+\.[0-9]+\.[0-9]+)$"
})
if ($batch.Count -lt 100) { break }
}
@@ -944,13 +954,51 @@ function Get-LatestVersionFromApi {
if (-not $releaseMatches -or $releaseMatches.Count -eq 0) {
return $null
}
- # Sort by SemVer descending. [version] correctly orders dotted triples.
- $latest = $releaseMatches | Sort-Object {
- $v = $_.tag_name.Substring($TagPrefix.Length)
- try { [version]$v } catch { [version]"0.0.0" }
- } -Descending | Select-Object -First 1
+ if ($Script:CuaDriverRsSelectedChannel -eq 'nightly') {
+ $latest = $releaseMatches | Sort-Object {
+ $v = $_.tag_name.Substring($selectedPrefix.Length)
+ if ($v -match '^([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.([1-9][0-9]*)$') {
+ $base = [version]$Matches[1]
+ return '{0:D10}.{1:D10}.{2:D10}.{3:D10}.{4:D20}' -f $base.Major, $base.Minor, $base.Build, [long]$Matches[2], [long]$Matches[3]
+ }
+ return '0'
+ } -Descending | Select-Object -First 1
+ }
+ else {
+ $latest = $releaseMatches | Sort-Object {
+ $v = $_.tag_name.Substring($selectedPrefix.Length)
+ try { [version]$v } catch { [version]'0.0.0' }
+ } -Descending | Select-Object -First 1
+ }
Write-Step "latest release: $($latest.tag_name)"
- return $latest.tag_name.Substring($TagPrefix.Length)
+ return $latest.tag_name.Substring($selectedPrefix.Length)
+}
+
+function Resolve-SelectedChannel {
+ if ($ChannelWasExplicit -and ($env:CUA_DRIVER_RS_VERSION -or $Release -ne 'latest')) {
+ Write-ErrorStep "-Channel cannot be combined with an exact release pin; pins do not change saved channel state"
+ exit 2
+ }
+ if ($ChannelWasExplicit) { return $Channel }
+ if ($env:CUA_DRIVER_RS_VERSION -or $Release -ne 'latest') {
+ # Exact pins are one-shot and outrank persisted preference. This also
+ # preserves a recovery path when the preference file is malformed.
+ return 'stable'
+ }
+ if (Test-Path -LiteralPath $ReleaseChannelPath) {
+ try { $saved = (Get-Content -LiteralPath $ReleaseChannelPath -Raw).Trim() }
+ catch {
+ Write-ErrorStep "cannot read release channel at ${ReleaseChannelPath}: $($_.Exception.Message)"
+ exit 1
+ }
+ if ($saved -notin @('stable', 'nightly')) {
+ Write-ErrorStep "invalid release channel '$saved' in $ReleaseChannelPath; expected stable or nightly"
+ Write-ErrorStep " repair with: cua-driver channel set stable"
+ exit 1
+ }
+ return $saved
+ }
+ return 'stable'
}
function Resolve-Version {
@@ -973,7 +1021,7 @@ function Resolve-Version {
# Baked-version fallback — set by the CD workflow after each release
# so the default `irm | iex` install path doesn't hit the GitHub API.
# See the BAKED_VERSION sentinel-block near the top of this file.
- if ($Script:CuaDriverRsBakedVersion) {
+ if ($Script:CuaDriverRsSelectedChannel -eq 'stable' -and $Script:CuaDriverRsBakedVersion) {
$v = $Script:CuaDriverRsBakedVersion -replace '^v', ''
Assert-StableVersion $v 'baked release'
Write-Step "using baked release: $TagPrefix$v"
@@ -983,11 +1031,13 @@ function Resolve-Version {
}
$v = Get-LatestVersionFromApi
if (-not $v) {
- Write-ErrorStep "no release matching $TagPrefix* found on $Repo"
+ $selectedPrefix = if ($Script:CuaDriverRsSelectedChannel -eq 'nightly') { $NightlyTagPrefix } else { $TagPrefix }
+ Write-ErrorStep "no release matching $selectedPrefix* found on $Repo"
exit 1
}
$Script:CuaDriverRsVersionSource = 'api'
- $Script:CuaDriverRsReleaseTag = "$TagPrefix$v"
+ $selectedPrefix = if ($Script:CuaDriverRsSelectedChannel -eq 'nightly') { $NightlyTagPrefix } else { $TagPrefix }
+ $Script:CuaDriverRsReleaseTag = "$selectedPrefix$v"
return $v
}
@@ -1076,10 +1126,10 @@ function Get-ReleaseAsset([string]$version, [string]$archLabel, [string]$destDir
if ($download.ErrorMessage) {
if (Test-TransientDownloadFailure $download.StatusCode) {
- Write-ErrorStep "download failed after $($download.Attempts) attempts for $TagPrefix$resolvedVersion ($archLabel): $($download.ErrorMessage)"
+ Write-ErrorStep "download failed after $($download.Attempts) attempts for $Script:CuaDriverRsReleaseTag ($archLabel): $($download.ErrorMessage)"
}
else {
- Write-ErrorStep "download failed for $TagPrefix$resolvedVersion ($archLabel) with HTTP $($download.StatusCode): $($download.ErrorMessage)"
+ Write-ErrorStep "download failed for $Script:CuaDriverRsReleaseTag ($archLabel) with HTTP $($download.StatusCode): $($download.ErrorMessage)"
}
Write-ErrorStep " The requested version was not changed. Check network access and GitHub credentials, then retry."
exit 1
@@ -1117,7 +1167,7 @@ function Get-ReleaseAsset([string]$version, [string]$archLabel, [string]$destDir
}
if ($download.Missing) {
- $message = "release asset for $TagPrefix$resolvedVersion ($archLabel) was not found (HTTP 404)"
+ $message = "release asset for $Script:CuaDriverRsReleaseTag ($archLabel) was not found (HTTP 404)"
if ($missingDetail) { $message += "; $missingDetail" }
Write-ErrorStep "$message."
if ($Script:CuaDriverRsVersionSource -in @('env', 'release-arg')) {
@@ -1329,6 +1379,7 @@ $target = Get-TargetTriple
$archLabel = Get-AssetArchLabel $target
Write-Step " target : $target"
+$Script:CuaDriverRsSelectedChannel = Resolve-SelectedChannel
$version = Resolve-Version
$versionedDir = Join-Path $ReleasesDir "$version-$target"
@@ -1449,6 +1500,13 @@ else {
# Wire up the junction chain. The inner junction (current → releases\<v>)
# is what makes the upgrade atomic; the outer junction (bin → current)
# is what gives users a stable PATH entry.
+if ($ChannelWasExplicit) {
+ New-Item -ItemType Directory -Force -Path $HomeDir | Out-Null
+ $channelTempPath = Join-Path $HomeDir (".release-channel." + $PID)
+ Set-Content -LiteralPath $channelTempPath -Value $Script:CuaDriverRsSelectedChannel -Encoding Ascii -NoNewline
+ Move-Item -LiteralPath $channelTempPath -Destination $ReleaseChannelPath -Force
+ Write-Step "saved release channel: $($Script:CuaDriverRsSelectedChannel)"
+}
Ensure-Junction $CurrentDir $versionedDir
Ensure-Junction $VisibleBinDir $CurrentDir
diff --git a/libs/cua-driver/scripts/install.sh b/libs/cua-driver/scripts/install.sh
index 9a15ade601..d22dd81e5f 100755
--- a/libs/cua-driver/scripts/install.sh
+++ b/libs/cua-driver/scripts/install.sh
@@ -10,6 +10,7 @@
# ~/.local/bin (e.g. /usr/local/bin — that target needs sudo)
# --no-modify-path skip auto-appending an `export PATH=...` line to your
# shell rc when ~/.local/bin is missing from PATH
+# --channel <name> persist and install the latest stable or nightly release
# --backend=rust explicit Rust backend (no-op; Rust is the only option)
# --experimental-rust legacy alias for --backend=rust (no-op)
# --backend=swift retired Swift backend (no-op; accepted for compat)
@@ -20,6 +21,7 @@
# CUA_DRIVER_RS_INSTALL_DIR=PATH same as --bin-dir
# CUA_DRIVER_BIN_DIR=PATH legacy alias for --bin-dir
# CUA_DRIVER_NO_MODIFY_PATH=1 same as --no-modify-path
+# CUA_DRIVER_RS_HOME=PATH package and release-channel state home
#
# Uninstall:
# /bin/bash -c "$(curl -fsSL https://cua.ai/driver/uninstall.sh)"
diff --git a/libs/cua-driver/scripts/tests/test_install_version_fallback.py b/libs/cua-driver/scripts/tests/test_install_version_fallback.py
index 98bdda2d18..4f7418eaaf 100644
--- a/libs/cua-driver/scripts/tests/test_install_version_fallback.py
+++ b/libs/cua-driver/scripts/tests/test_install_version_fallback.py
@@ -215,7 +215,7 @@ def test_windows_api_resolver_accepts_published_stable_tags_marked_prerelease()
"function Resolve-Version"
)
]
- assert "(-not $_.draft)" in body
+ assert "if ($_.draft) { return $false }" in body
assert "(-not $_.prerelease)" not in body
assert "[0-9]+\\.[0-9]+\\.[0-9]+" in body
diff --git a/libs/lume/scripts/install.sh b/libs/lume/scripts/install.sh
index e918736eef..d60a1107c4 100755
--- a/libs/lume/scripts/install.sh
+++ b/libs/lume/scripts/install.sh
@@ -49,6 +49,9 @@ UPDATE_ON_LOGIN=false
# LUME_BAKED_VERSION is updated in the release PR so the default
# installer path does not need a GitHub API call.
LUME_VERSION="${LUME_VERSION:-}"
+LUME_HOME="${LUME_HOME:-$HOME/.lume}"
+LUME_CHANNEL=""
+LUME_CHANNEL_EXPLICIT=false
# ~~~ BAKED_VERSION: auto-updated in the release PR — do not edit ~~~
LUME_BAKED_VERSION="0.5.3" # x-release-please-version
# ~~~ END_BAKED_VERSION ~~~
@@ -70,6 +73,16 @@ while [ "$#" -gt 0 ]; do
--no-background-service)
INSTALL_BACKGROUND_SERVICE=false
;;
+ --channel)
+ [ -n "${2:-}" ] || { echo "${RED}Error: --channel requires stable or nightly.${NORMAL}" >&2; exit 2; }
+ LUME_CHANNEL="$2"
+ LUME_CHANNEL_EXPLICIT=true
+ shift
+ ;;
+ --channel=*)
+ LUME_CHANNEL="${1#*=}"
+ LUME_CHANNEL_EXPLICIT=true
+ ;;
--no-auto-updater)
echo "${YELLOW}Warning: --no-auto-updater is deprecated; scheduled auto-updates are no longer installed.${NORMAL}"
INSTALL_AUTO_UPDATER=false
@@ -86,6 +99,7 @@ while [ "$#" -gt 0 ]; do
echo " --install-dir DIR Install to the specified directory (default: $DEFAULT_INSTALL_DIR)"
echo " --port PORT Specify the port for lume serve (default: 7777)"
echo " --no-background-service Do not setup the Lume background service (LaunchAgent)"
+ echo " --channel CHANNEL Persist and install the latest stable or nightly release"
echo " --no-auto-updater Deprecated no-op; scheduled auto-updates are no longer installed"
echo " --update-on-login Deprecated no-op; use 'lume update --apply'"
echo " --help Display this help message"
@@ -107,6 +121,32 @@ while [ "$#" -gt 0 ]; do
shift
done
+RELEASE_CHANNEL_PATH="$LUME_HOME/release-channel"
+if [ "$LUME_CHANNEL_EXPLICIT" = true ] && [ -n "$LUME_VERSION" ]; then
+ echo "${RED}Error: --channel cannot be combined with LUME_VERSION; exact pins do not change saved channel state.${NORMAL}" >&2
+ exit 2
+fi
+if [ "$LUME_CHANNEL_EXPLICIT" != true ]; then
+ if [ -n "$LUME_VERSION" ]; then
+ # Exact pins are one-shot and outrank persisted preference. Keep them
+ # usable as a recovery path even if the preference file is malformed.
+ LUME_CHANNEL="stable"
+ elif [ -f "$RELEASE_CHANNEL_PATH" ]; then
+ LUME_CHANNEL=$(tr -d '[:space:]' < "$RELEASE_CHANNEL_PATH")
+ else
+ LUME_CHANNEL="stable"
+ fi
+fi
+case "$LUME_CHANNEL" in
+ stable) LUME_TAG_PREFIX="lume-v" ;;
+ nightly) LUME_TAG_PREFIX="nightly-lume-v" ;;
+ *)
+ echo "${RED}Error: invalid release channel '$LUME_CHANNEL' in $RELEASE_CHANNEL_PATH; expected stable or nightly.${NORMAL}" >&2
+ echo "Repair with: lume channel set stable" >&2
+ exit 1
+ ;;
+esac
+
echo "${BOLD}${BLUE}"
echo " ⠀⣀⣀⡀⠀⠀⠀⠀⢀⣀⣀⣀⡀⠘⠋⢉⠙⣷⠀⠀ ⠀"
echo " ⠀⠀⢀⣴⣿⡿⠋⣉⠁⣠⣾⣿⣿⣿⣿⡿⠿⣦⡈⠀⣿⡇⠃⠀"
@@ -194,7 +234,7 @@ get_latest_lume_tag() {
return 0
fi
- if [ -n "$LUME_BAKED_VERSION" ]; then
+ if [ "$LUME_CHANNEL" = "stable" ] && [ -n "$LUME_BAKED_VERSION" ]; then
local baked="${LUME_BAKED_VERSION#v}"
if ! [[ "$baked" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "${RED}Error: baked Lume version must be an exact stable x.y.z version.${NORMAL}" >&2
@@ -229,7 +269,7 @@ get_latest_lume_tag() {
fi
local page_versions
- page_versions=$(printf '%s' "$response" | awk '
+ page_versions=$(printf '%s' "$response" | awk -v prefix="$LUME_TAG_PREFIX" -v channel="$LUME_CHANNEL" '
/"tag_name"[[:space:]]*:/ {
tag = $0
sub(/^.*"tag_name"[[:space:]]*:[[:space:]]*"/, "", tag)
@@ -238,9 +278,12 @@ get_latest_lume_tag() {
}
tag != "" && /"draft"[[:space:]]*:/ {
if ($0 ~ /"draft"[[:space:]]*:[[:space:]]*false/ &&
- tag ~ /^lume-v[0-9]+\.[0-9]+\.[0-9]+$/) {
- sub(/^lume-v/, "", tag)
- print tag
+ index(tag, prefix) == 1) {
+ version = substr(tag, length(prefix) + 1)
+ if ((channel == "stable" && version ~ /^[0-9]+\.[0-9]+\.[0-9]+$/) ||
+ (channel == "nightly" && version ~ /^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[1-9][0-9]*$/)) {
+ print version
+ }
}
tag = ""
}
@@ -259,12 +302,12 @@ get_latest_lume_tag() {
done
local latest
- latest=$(printf '%s\n' "$versions" | sed '/^$/d' | sort -t. -k1,1nr -k2,2nr -k3,3nr | head -n 1)
+ latest=$(printf '%s\n' "$versions" | sed '/^$/d' | sort -t. -k1,1nr -k2,2nr -k3,3nr -k4,4nr -k5,5nr | head -n 1)
if [ -z "$latest" ]; then
- echo "${RED}Error: Could not find any published stable lume tags after checking $max_pages pages.${NORMAL}" >&2
+ echo "${RED}Error: Could not find any published $LUME_CHANNEL Lume tags after checking $max_pages pages.${NORMAL}" >&2
return 1
fi
- LUME_TAG="lume-v$latest"
+ LUME_TAG="$LUME_TAG_PREFIX$latest"
echo "Found latest Lume release: ${BOLD}$LUME_TAG${NORMAL}" >&2
echo "$LUME_TAG"
}
@@ -318,6 +361,16 @@ download_release() {
fi
}
+persist_release_channel() {
+ if [ "$LUME_CHANNEL_EXPLICIT" = true ]; then
+ mkdir -p "$LUME_HOME"
+ channel_tmp="$LUME_HOME/.release-channel.$$"
+ printf '%s\n' "$LUME_CHANNEL" > "$channel_tmp"
+ mv -f "$channel_tmp" "$RELEASE_CHANNEL_PATH"
+ echo "Saved release channel: ${BOLD}$LUME_CHANNEL${NORMAL}"
+ fi
+}
+
# Extract and install
install_binary() {
echo "Extracting archive..."
@@ -462,6 +515,7 @@ main() {
detect_platform
create_temp_dir
download_release
+ persist_release_channel
install_binary
record_installation_telemetry
diff --git a/libs/lume/src/Commands/Channel.swift b/libs/lume/src/Commands/Channel.swift
new file mode 100644
index 0000000000..40e9d8645b
--- /dev/null
+++ b/libs/lume/src/Commands/Channel.swift
@@ -0,0 +1,63 @@
+import ArgumentParser
+import Foundation
+
+struct ReleaseChannelCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "channel",
+ abstract: "Inspect or change the stable/nightly update channel; selection does not install",
+ subcommands: [ChannelStatus.self, ChannelSet.self],
+ defaultSubcommand: ChannelStatus.self
+ )
+}
+
+struct ChannelStatus: ParsableCommand {
+ static let configuration = CommandConfiguration(commandName: "status")
+
+ @Flag(help: "Emit machine-readable channel state as JSON")
+ var json = false
+
+ func run() throws {
+ try printChannelState(selected: LumeReleaseChannel.selected(), json: json, changed: false)
+ }
+}
+
+struct ChannelSet: ParsableCommand {
+ static let configuration = CommandConfiguration(commandName: "set")
+
+ @Argument(help: "Release channel: stable or nightly")
+ var channel: String
+
+ @Flag(help: "Emit machine-readable channel state as JSON")
+ var json = false
+
+ func run() throws {
+ guard let selected = LumeReleaseChannel(rawValue: channel) else {
+ throw ValidationError("release channel must be stable or nightly")
+ }
+ try LumeReleaseChannel.set(selected)
+ try printChannelState(selected: selected, json: json, changed: true)
+ }
+}
+
+private func printChannelState(
+ selected: LumeReleaseChannel,
+ json: Bool,
+ changed: Bool
+) throws {
+ let current = LumeReleaseChannel.current(for: Lume.Version.current)
+ if json {
+ let payload: [String: Any] = [
+ "selected_channel": selected.rawValue,
+ "current_channel": current?.rawValue ?? NSNull(),
+ "current_version": Lume.Version.current,
+ ]
+ let data = try JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys])
+ print(String(decoding: data, as: UTF8.self))
+ return
+ }
+ print("Selected channel: \(selected.rawValue)")
+ print("Current channel: \(current?.rawValue ?? "development")")
+ if changed && current != selected {
+ print("Run `lume update --apply` to install the latest \(selected.rawValue) release.")
+ }
+}
diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swift
index 72ac08d3e0..a46c1c5773 100644
--- a/libs/lume/src/Server/MCPServer.swift
+++ b/libs/lume/src/Server/MCPServer.swift
@@ -319,7 +319,7 @@ final class LumeMCPServer {
[
Tool(
name: "check_for_update",
- description: "Check whether a newer Lume release is available on GitHub. Read-only; never installs. Mirrors `lume check-update --json`.",
+ description: "Check the saved stable/nightly Lume channel for a release on GitHub. Returns current and selected channels. Read-only; never installs. Mirrors `lume check-update --json`.",
inputSchema: .object([
"type": .string("object"),
"properties": .object([:])
diff --git a/libs/lume/src/Telemetry/TelemetryClient.swift b/libs/lume/src/Telemetry/TelemetryClient.swift
index 536e7b7f47..085d608b99 100644
--- a/libs/lume/src/Telemetry/TelemetryClient.swift
+++ b/libs/lume/src/Telemetry/TelemetryClient.swift
@@ -402,7 +402,7 @@ final class TelemetryClient: @unchecked Sendable {
switch raw {
case "create", "pull", "push", "convert", "images", "clone", "get", "set", "run",
"stop", "ssh", "sip", "ipsw", "serve", "delete", "prune", "config", "logs",
- "update", "setup":
+ "update", "setup", "channel":
return raw
case "ls": return "list"
case "check-update": return "check_update"
diff --git a/libs/lume/src/Update/ReleaseChannel.swift b/libs/lume/src/Update/ReleaseChannel.swift
new file mode 100644
index 0000000000..a7df3718d3
--- /dev/null
+++ b/libs/lume/src/Update/ReleaseChannel.swift
@@ -0,0 +1,85 @@
+import Foundation
+
+enum LumeReleaseChannel: String, Codable, CaseIterable {
+ case stable
+ case nightly
+
+ static let fileName = "release-channel"
+
+ static func current(for version: String) -> LumeReleaseChannel? {
+ if plainVersion(version) != nil { return .stable }
+ if nightlyVersion(version) != nil { return .nightly }
+ return nil
+ }
+
+ static func selected() throws -> LumeReleaseChannel {
+ try selected(at: stateFileURL())
+ }
+
+ static func selected(at url: URL) throws -> LumeReleaseChannel {
+ guard FileManager.default.fileExists(atPath: url.path) else { return .stable }
+ let value = try String(contentsOf: url, encoding: .utf8)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard let channel = LumeReleaseChannel(rawValue: value) else {
+ throw LumeReleaseChannelError.invalid(value: value, path: url.path)
+ }
+ return channel
+ }
+
+ static func set(_ channel: LumeReleaseChannel) throws {
+ try set(channel, at: stateFileURL())
+ }
+
+ static func set(_ channel: LumeReleaseChannel, at url: URL) throws {
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try Data("\(channel.rawValue)\n".utf8).write(to: url, options: .atomic)
+ }
+
+ static func stateFileURL() -> URL {
+ if let override = ProcessInfo.processInfo.environment["LUME_HOME"], !override.isEmpty {
+ return URL(fileURLWithPath: override).appendingPathComponent(fileName)
+ }
+ return FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".lume")
+ .appendingPathComponent(fileName)
+ }
+
+ static func plainVersion(_ version: String) -> [Int]? {
+ let parts = version.split(separator: ".", omittingEmptySubsequences: false)
+ guard parts.count == 3,
+ parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }),
+ parts.allSatisfy({ $0 == "0" || !$0.hasPrefix("0") })
+ else { return nil }
+ let numbers = parts.compactMap { Int($0) }
+ return numbers.count == 3 ? numbers : nil
+ }
+
+ static func nightlyVersion(_ version: String) -> [Int]? {
+ let pieces = version.components(separatedBy: "-nightly.")
+ guard pieces.count == 2, let base = plainVersion(pieces[0]) else { return nil }
+ let suffix = pieces[1].split(separator: ".", omittingEmptySubsequences: false)
+ guard suffix.count == 2,
+ suffix[0].count == 8,
+ suffix[0].allSatisfy(\.isNumber),
+ let date = Int(suffix[0]),
+ let run = Int(suffix[1]),
+ !suffix[1].hasPrefix("0"),
+ run > 0
+ else { return nil }
+ return base + [date, run]
+ }
+}
+
+enum LumeReleaseChannelError: LocalizedError {
+ case invalid(value: String, path: String)
+
+ var errorDescription: String? {
+ switch self {
+ case .invalid(let value, let path):
+ return "Invalid release channel '\(value)' in \(path); run `lume channel set stable` or `lume channel set nightly` to repair it."
+ }
+ }
+}
diff --git a/libs/lume/src/Update/VersionCheck.swift b/libs/lume/src/Update/VersionCheck.swift
index 6f3157cc9b..8c0ddcfd6d 100644
--- a/libs/lume/src/Update/VersionCheck.swift
+++ b/libs/lume/src/Update/VersionCheck.swift
@@ -2,6 +2,7 @@ import Foundation
enum LumeVersionCheck {
static let releaseTagPrefix = "lume-v"
+ static let nightlyReleaseTagPrefix = "nightly-lume-v"
static let releasesURL = URL(string: "https://api.github.com/repos/trycua/cua/releases?per_page=40")!
static let defaultInstallScriptURL =
"https://cua.ai/lume/install.sh"
@@ -12,6 +13,8 @@ enum LumeVersionCheck {
struct State: Codable {
let currentVersion: String
+ let currentChannel: String?
+ let selectedChannel: String?
let latestVersion: String?
let updateAvailable: Bool
let source: String
@@ -23,6 +26,8 @@ enum LumeVersionCheck {
enum CodingKeys: String, CodingKey {
case currentVersion
+ case currentChannel
+ case selectedChannel
case latestVersion
case updateAvailable
case source
@@ -36,6 +41,8 @@ enum LumeVersionCheck {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(currentVersion, forKey: .currentVersion)
+ try encodeOptional(currentChannel, into: &container, forKey: .currentChannel)
+ try encodeOptional(selectedChannel, into: &container, forKey: .selectedChannel)
try encodeOptional(latestVersion, into: &container, forKey: .latestVersion)
try container.encode(updateAvailable, forKey: .updateAvailable)
try container.encode(source, forKey: .source)
@@ -62,6 +69,7 @@ enum LumeVersionCheck {
struct Cache: Codable {
var lastCheckedUnix: TimeInterval?
var latestVersion: String?
+ var channel: String?
}
static func checkUpdateState(noCache: Bool = false) async -> State {
@@ -72,11 +80,31 @@ enum LumeVersionCheck {
let current = Lume.Version.current
let now = Date()
let checkedAt = ISO8601DateFormatter().string(from: now)
- let cached = (try? readCache()) ?? Cache(lastCheckedUnix: nil, latestVersion: nil)
+ let currentChannel = LumeReleaseChannel.current(for: current)
+ let selectedChannel: LumeReleaseChannel
+ do {
+ selectedChannel = try LumeReleaseChannel.selected()
+ } catch {
+ return State(
+ currentVersion: current,
+ currentChannel: currentChannel?.rawValue,
+ selectedChannel: nil,
+ latestVersion: nil,
+ updateAvailable: false,
+ source: "github_releases",
+ checkedAt: checkedAt,
+ cacheHit: false,
+ installCommand: nil,
+ releaseNotesURL: nil,
+ error: error.localizedDescription
+ )
+ }
+ let cached = (try? readCache()) ?? Cache(lastCheckedUnix: nil, latestVersion: nil, channel: nil)
let cacheFresh =
cached.lastCheckedUnix
.map { now.timeIntervalSince1970 - $0 < cacheRefreshSeconds } ?? false
- let useCache = !noCache && cacheFresh && cached.latestVersion != nil
+ let cacheChannelMatches = (cached.channel ?? "stable") == selectedChannel.rawValue
+ let useCache = !noCache && cacheFresh && cacheChannelMatches && cached.latestVersion != nil
let latest: String?
let cacheHit: Bool
@@ -88,13 +116,17 @@ enum LumeVersionCheck {
fetchError = nil
} else {
do {
- let fetched = try await fetchLatestVersion()
+ let fetched = try await fetchLatestVersion(channel: selectedChannel)
latest = fetched
cacheHit = false
fetchError = nil
- try? writeCache(Cache(lastCheckedUnix: now.timeIntervalSince1970, latestVersion: fetched))
+ try? writeCache(Cache(
+ lastCheckedUnix: now.timeIntervalSince1970,
+ latestVersion: fetched,
+ channel: selectedChannel.rawValue
+ ))
} catch {
- if let cachedLatest = cached.latestVersion {
+ if cacheChannelMatches, let cachedLatest = cached.latestVersion {
latest = cachedLatest
cacheHit = true
fetchError = nil
@@ -106,14 +138,24 @@ enum LumeVersionCheck {
}
}
- let updateAvailable = latest.map { isNewer($0, than: current) } ?? false
+ let updateAvailable = latest.map {
+ updateIsAvailable(
+ latest: $0,
+ current: current,
+ currentChannel: currentChannel,
+ selectedChannel: selectedChannel
+ )
+ } ?? false
+ let prefix = selectedChannel == .nightly ? nightlyReleaseTagPrefix : releaseTagPrefix
let releaseNotesURL =
updateAvailable
- ? "https://github.com/trycua/cua/releases/tag/\(releaseTagPrefix)\(latest ?? "")"
+ ? "https://github.com/trycua/cua/releases/tag/\(prefix)\(latest ?? "")"
: nil
return State(
currentVersion: current,
+ currentChannel: currentChannel?.rawValue,
+ selectedChannel: selectedChannel.rawValue,
latestVersion: latest,
updateAvailable: updateAvailable,
source: "github_releases",
@@ -135,6 +177,8 @@ enum LumeVersionCheck {
static func disabledState() -> State {
State(
currentVersion: Lume.Version.current,
+ currentChannel: LumeReleaseChannel.current(for: Lume.Version.current)?.rawValue,
+ selectedChannel: (try? LumeReleaseChannel.selected())?.rawValue,
latestVersion: nil,
updateAvailable: false,
source: "github_releases",
@@ -180,6 +224,15 @@ enum LumeVersionCheck {
compare(lhs, rhs) == .orderedDescending
}
+ static func updateIsAvailable(
+ latest: String,
+ current: String,
+ currentChannel: LumeReleaseChannel?,
+ selectedChannel: LumeReleaseChannel
+ ) -> Bool {
+ currentChannel.map { $0 != selectedChannel } ?? false || isNewer(latest, than: current)
+ }
+
static func compare(_ lhs: String, _ rhs: String) -> ComparisonResult {
let left = parseVersion(lhs)
let right = parseVersion(rhs)
@@ -192,7 +245,7 @@ enum LumeVersionCheck {
return .orderedSame
}
- private static func fetchLatestVersion() async throws -> String {
+ private static func fetchLatestVersion(channel: LumeReleaseChannel) async throws -> String {
var versions: [String] = []
for page in 1...5 {
@@ -220,7 +273,7 @@ enum LumeVersionCheck {
throw VersionCheckError.invalidResponse
}
- versions.append(contentsOf: publishedStableVersions(from: releases))
+ versions.append(contentsOf: publishedVersions(from: releases, channel: channel))
if releases.count < 100 {
break
@@ -236,30 +289,35 @@ enum LumeVersionCheck {
}
private static func parseVersion(_ version: String) -> [Int] {
- version
- .split(separator: "-", maxSplits: 1, omittingEmptySubsequences: true)
- .first?
- .split(separator: ".")
- .map { Int($0) ?? 0 } ?? []
+ LumeReleaseChannel.plainVersion(version)
+ ?? LumeReleaseChannel.nightlyVersion(version)
+ ?? []
}
static func publishedStableVersions(from releases: [[String: Any]]) -> [String] {
- releases.compactMap { release in
+ publishedVersions(from: releases, channel: .stable)
+ }
+
+ static func publishedVersions(
+ from releases: [[String: Any]],
+ channel: LumeReleaseChannel
+ ) -> [String] {
+ let prefix = channel == .nightly ? nightlyReleaseTagPrefix : releaseTagPrefix
+ return releases.compactMap { release -> String? in
if release["draft"] as? Bool == true { return nil }
guard let tag = release["tag_name"] as? String,
- tag.hasPrefix(releaseTagPrefix)
+ tag.hasPrefix(prefix)
else { return nil }
- let version = String(tag.dropFirst(releaseTagPrefix.count))
- return isPlainSemver(version) ? version : nil
+ let version = String(tag.dropFirst(prefix.count))
+ switch channel {
+ case .stable:
+ return LumeReleaseChannel.plainVersion(version) != nil ? version : nil
+ case .nightly:
+ return LumeReleaseChannel.nightlyVersion(version) != nil ? version : nil
+ }
}
}
- private static func isPlainSemver(_ version: String) -> Bool {
- let parts = version.split(separator: ".")
- guard parts.count == 3 else { return false }
- return parts.allSatisfy { Int($0) != nil }
- }
-
private static func cacheFileURL() -> URL {
let env = ProcessInfo.processInfo.environment
let cacheRoot =
diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swift
index 01b3da35bb..41838c984a 100644
--- a/libs/lume/src/Utils/CommandDocExtractor.swift
+++ b/libs/lume/src/Utils/CommandDocExtractor.swift
@@ -99,6 +99,7 @@ enum CommandDocExtractor {
logsDoc,
checkUpdateDoc,
updateDoc,
+ channelDoc,
setupDoc,
dumpDocsDoc,
]
@@ -706,6 +707,36 @@ enum CommandDocExtractor {
)
}
+ private static var channelDoc: CommandDoc {
+ CommandDoc(
+ name: "channel",
+ abstract: "Inspect or change the stable/nightly update channel; selection does not install",
+ discussion: "Selection is persistent but never installs by itself; use lume update --apply after changing it.",
+ arguments: [],
+ options: [],
+ flags: [],
+ subcommands: [
+ CommandDoc(
+ name: "status",
+ abstract: "Show selected and current release channels",
+ discussion: nil,
+ arguments: [], options: [],
+ flags: [FlagDoc(name: "json", shortName: nil, help: "Emit machine-readable channel state as JSON", defaultValue: false)],
+ subcommands: []
+ ),
+ CommandDoc(
+ name: "set",
+ abstract: "Save stable or nightly as the update channel",
+ discussion: nil,
+ arguments: [ArgumentDoc(name: "channel", help: "Release channel: stable or nightly", type: "String", isOptional: false)],
+ options: [],
+ flags: [FlagDoc(name: "json", shortName: nil, help: "Emit machine-readable channel state as JSON", defaultValue: false)],
+ subcommands: []
+ ),
+ ]
+ )
+ }
+
// MARK: - Setup
private static var setupDoc: CommandDoc {
diff --git a/libs/lume/src/Utils/CommandRegistry.swift b/libs/lume/src/Utils/CommandRegistry.swift
index 85d1d1f828..8d8b79ab76 100644
--- a/libs/lume/src/Utils/CommandRegistry.swift
+++ b/libs/lume/src/Utils/CommandRegistry.swift
@@ -27,6 +27,7 @@ enum CommandRegistry {
Logs.self,
CheckUpdate.self,
Update.self,
+ ReleaseChannelCommand.self,
Setup.self,
DumpDocs.self,
]
diff --git a/libs/lume/tests/TelemetryClientTests.swift b/libs/lume/tests/TelemetryClientTests.swift
index 98e8c8b919..8117690b0f 100644
--- a/libs/lume/tests/TelemetryClientTests.swift
+++ b/libs/lume/tests/TelemetryClientTests.swift
@@ -302,6 +302,7 @@ func telemetryMappingsAreBounded() {
"run": "run", "stop": "stop", "ssh": "ssh", "sip": "sip", "ipsw": "ipsw",
"serve": "serve", "delete": "delete", "prune": "prune", "config": "config",
"logs": "logs", "check-update": "check_update", "update": "update", "setup": "setup",
+ "channel": "channel",
"dump-docs": "dump_docs",
]
for (command, operation) in commands {
diff --git a/libs/lume/tests/VersionCheckTests.swift b/libs/lume/tests/VersionCheckTests.swift
index e3d88bdd16..9943d54807 100644
--- a/libs/lume/tests/VersionCheckTests.swift
+++ b/libs/lume/tests/VersionCheckTests.swift
@@ -1,4 +1,5 @@
import Darwin
+import Foundation
import Testing
@testable import lume
@@ -30,4 +31,56 @@ struct VersionCheckTests {
]
#expect(LumeVersionCheck.publishedStableVersions(from: releases) == ["0.5.3"])
}
+
+ @Test func nightlyDiscoveryRejectsStableAndWrongPrefixTags() {
+ let releases: [[String: Any]] = [
+ ["tag_name": "lume-v9.9.9", "draft": false],
+ ["tag_name": "lume-v0.5.4-nightly.20260812.99", "draft": false],
+ ["tag_name": "nightly-lume-v0.5.4-nightly.20260812.7", "draft": false],
+ ["tag_name": "nightly-lume-v0.5.4-nightly.20260812.42", "draft": false],
+ ["tag_name": "nightly-lume-v0.5.4-nightly.20260812.99", "draft": true],
+ ]
+ let versions = LumeVersionCheck.publishedVersions(from: releases, channel: .nightly)
+ #expect(
+ versions.sorted { LumeVersionCheck.compare($0, $1) == .orderedDescending }
+ == ["0.5.4-nightly.20260812.42", "0.5.4-nightly.20260812.7"]
+ )
+ }
+
+ @Test func releaseChannelVersionGrammarIsStrict() {
+ #expect(LumeReleaseChannel.current(for: "0.5.3") == .stable)
+ #expect(LumeReleaseChannel.current(for: "0.5.4-nightly.20260812.42") == .nightly)
+ #expect(LumeReleaseChannel.current(for: "0.5.4-rc.1") == nil)
+ #expect(LumeReleaseChannel.nightlyVersion("0.5.4-nightly.20260812.0") == nil)
+ #expect(LumeReleaseChannel.nightlyVersion("0.5.4-nightly.20260812.01") == nil)
+ }
+
+ @Test func releaseChannelStateRoundTripsAndFailsClosed() throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let path = root.appendingPathComponent(LumeReleaseChannel.fileName)
+ #expect(try LumeReleaseChannel.selected(at: path) == .stable)
+ try LumeReleaseChannel.set(.nightly, at: path)
+ #expect(try LumeReleaseChannel.selected(at: path) == .nightly)
+ try Data("broken\n".utf8).write(to: path)
+ #expect(throws: LumeReleaseChannelError.self) {
+ try LumeReleaseChannel.selected(at: path)
+ }
+ }
+
+ @Test func channelMismatchIsAnUpdateEvenWhenTheTargetVersionIsLower() {
+ #expect(LumeVersionCheck.updateIsAvailable(
+ latest: "0.5.3",
+ current: "0.5.4-nightly.20260812.42",
+ currentChannel: .nightly,
+ selectedChannel: .stable
+ ))
+ #expect(!LumeVersionCheck.updateIsAvailable(
+ latest: "0.5.3",
+ current: "0.5.4",
+ currentChannel: .stable,
+ selectedChannel: .stable
+ ))
+ }
}
diff --git a/rfcs/3101-persistent-release-channel-selection.md b/rfcs/3101-persistent-release-channel-selection.md
new file mode 100644
index 0000000000..8c62a9f978
--- /dev/null
+++ b/rfcs/3101-persistent-release-channel-selection.md
@@ -0,0 +1,220 @@
+---
+title: Persistent release-channel selection for Cua Driver and Lume
+authors:
+ - f-trycua
+created: 2026-08-12
+last_updated: 2026-08-12
+status: accepted
+discussion: https://github.com/trycua/cua/issues/3101
+rfc_pr: https://github.com/trycua/cua/pull/3102
+implementation:
+ - https://github.com/trycua/cua/pull/3102
+supersedes:
+superseded_by:
+---
+
+# RFC: Persistent release-channel selection for Cua Driver and Lume
+
+## Summary
+
+Cua Driver and Lume will expose the same persistent `stable`/`nightly`
+selection contract. Stable remains the default. An explicit installer flag or
+CLI command saves the channel, and later checks and explicit update applies
+stay inside it. Exact version pins remain one-shot reproduction and rollback
+controls and never mutate the saved preference.
+
+## Motivation
+
+[RFC #3096](3096-immutable-nightly-release-channels.md) established immutable,
+disjoint nightly namespaces and exact nightly installation. It deliberately
+deferred newest-nightly resolution and persisted channel state. Users can
+reproduce one nightly, but cannot opt a machine into following later nightlies
+without discovering and pinning every tag themselves.
+
+The follow-up must not weaken the original isolation invariant: stable clients
+must never discover a nightly unless the user explicitly selected nightly.
+
+## Goals
+
+- Give both products matching `channel status` and
+ `channel set stable|nightly` commands.
+- Add `--channel stable|nightly` to both canonical installers.
+- Keep missing state equivalent to stable for existing installs.
+- Make checks, banners, structured update state, and explicit apply honor the
+ saved channel.
+- Preserve exact pins without changing future update intent.
+- Treat a channel transition as available even when SemVer ordering alone
+ would call the selected-channel target older.
+- Document a small pattern future Cua components can reuse.
+
+## Non-goals
+
+- Background or unattended update application.
+- Mutable nightly tags or assets.
+- Registry channels, retention, or object-store pointers.
+- Replacing Release Please as the stable version authority.
+- Inferring a user's preference from the currently installed version.
+
+## Terminology
+
+**Selected channel** is the validated persisted preference, either `stable` or
+`nightly`. A missing preference means `stable`.
+
+**Current channel** is derived only from the running artifact's strict release
+version grammar. It is status, not future intent.
+
+**Exact pin** is a full stable version or canonical immutable nightly identity
+provided through the existing product environment variable.
+
+## Current state
+
+Cua Driver and Lume stable resolvers accept only their stable tag prefixes.
+Nightlies use separate `nightly-` prefixes and can be installed only through an
+exact tag. Driver's Rust updater and Lume's Swift updater search stable releases
+only. Installers prefer an exact pin, then a baked stable version, then a stable
+API fallback.
+
+## Proposal
+
+### Persistence
+
+Each product owns a one-line UTF-8 `release-channel` file beside its existing
+package/update state. The only valid contents are `stable` and `nightly`.
+Writers create the parent directory and replace the file atomically. A missing
+file reads as stable. Invalid or unreadable explicit state fails closed with a
+recovery instruction; it is never interpreted as nightly.
+
+The file is a user preference, not an authorization artifact. Product-home
+overrides used by installers and tests also relocate it, preserving isolated
+and portable installations.
+
+### CLI
+
+Both products expose:
+
+```text
+<product> channel status [--json]
+<product> channel set stable|nightly [--json]
+```
+
+`set` persists intent only. It prints the selected channel and tells the user
+to run `update --apply`; it does not replace a running binary as a side effect.
+Update status includes `selected_channel` and `current_channel` so a caller can
+distinguish version upgrades from channel transitions.
+
+### Installers
+
+Both canonical installers accept `--channel stable|nightly`. The flag persists
+the selection and installs the highest published release visible in that
+channel. Without a flag or exact pin, the installer reads saved state. Missing
+state uses the baked stable release without an API call. Nightly selection
+always resolves through the releases API because nightly tags are immutable and
+no mutable pointer is introduced.
+
+Selection precedence is:
+
+1. exact version environment variable;
+2. explicit `--channel` argument;
+3. saved channel;
+4. stable default.
+
+An exact pin does not write channel state. Combining a pin with `--channel` is
+rejected to avoid ambiguous persistence. Existing baked stable versions remain
+authoritative only for the stable channel.
+
+### Discovery and apply
+
+Resolvers select exactly one prefix and strict grammar. Stable never considers
+nightly tags and nightly never considers stable tags. Caches are keyed by
+channel so a stable result cannot satisfy a nightly check or the reverse.
+
+Within one channel, ordinary SemVer ordering determines whether a newer release
+exists. When current and selected channels differ, the newest selected-channel
+release is offered as an explicit transition regardless of relative SemVer
+ordering. `update --apply` pins that resolved immutable target while preserving
+the selected channel.
+
+### Reusable component contract
+
+Future components reuse the two-value vocabulary, strict namespace selection,
+one-line product-owned state, precedence rules, structured status fields, and
+test matrix. Component-specific code retains its own home path, installer,
+packaging, signing, and platform updater implementation.
+
+## Alternatives considered
+
+Environment-only selection was rejected because it is not durable. Inferring
+intent from the installed artifact was rejected because a rollback would
+silently rewrite future behavior. GitHub's `prerelease` or `latest` metadata
+was rejected as a channel boundary by RFC #3096. A central cross-product JSON
+file was rejected because shell and PowerShell installers cannot safely update
+unrelated product keys without adding another parser and lock protocol.
+
+## Compatibility and migration
+
+Existing machines have no state file and stay stable. Existing exact stable and
+nightly pins keep their meaning. `channel set nightly` followed by
+`update --apply` opts in; the corresponding stable commands opt out. A single
+installer call with `--channel` performs both operations. Exact pins remain the
+supported rollback and reproduction path.
+
+No stable tag, nightly tag, manifest, signing, permission, or session contract
+changes.
+
+## Security, privacy, and telemetry
+
+Channel choice is explicit local user intent. The state file contains no token,
+credential, identity, path, or session data and grants no authority. GitHub
+metadata cannot select a channel. Existing signature, notarization, digest,
+approval, and explicit-apply boundaries remain independently binding.
+
+Telemetry may record only the normalized channel vocabulary and existing
+bounded update outcomes. It must not record the preference path or use channel
+state as an identifier.
+
+## Implementation plan
+
+1. Add validated channel state and channel-aware discovery to Driver.
+2. Wire Unix and Windows Driver installers, CLI, updater, cache, MCP state, and
+ generated docs.
+3. Add the same contract to Lume's installer, Swift updater, CLI, MCP state,
+ and generated docs.
+4. Add focused cross-platform resolver, persistence, installer, and contract
+ tests while preserving stable visibility tests.
+5. Merge only after ordinary CI is green, then publish exact-main nightlies and
+ prove stable to nightly to stable behavior through public assets.
+
+## Test and acceptance plan
+
+- Missing state resolves stable; valid state round-trips; invalid state fails
+ closed with a recovery instruction.
+- Stable discovery rejects all nightly shapes and nightly discovery rejects all
+ stable shapes for both products.
+- Explicit pin precedence and pin-plus-channel rejection are covered on Bash
+ and PowerShell.
+- Baked stable versions are used only on stable; nightly always resolves an
+ immutable public tag.
+- Update caches cannot cross channels.
+- Structured CLI and MCP update state exposes selected and current channels.
+- Stable to nightly and nightly to stable transitions are offered and applied
+ even across SemVer precedence boundaries.
+- Focused Rust, Swift, installer, generated-contract, and repository release
+ tests pass, followed by ordinary PR CI.
+- Fresh Driver and Lume nightlies publish from the merged main SHA with signed
+ artifacts, manifests, checksums, and attributed release notes.
+- Public installer/updater smoke tests prove stable to nightly to stable and an
+ exact pin that leaves saved state unchanged.
+
+## Unresolved questions
+
+None for this increment. Background apply, registries, retention, and
+object-store pointers remain separate follow-ups.
+
+## Decision record
+
+The maintainer selected persistent, product-owned state after the exact-pin
+nightly foundation shipped. The accepted contract keeps stable as the default,
+uses an explicit two-value vocabulary, makes pins non-persistent, separates
+selection from apply in the CLI, and keeps disjoint tag grammars as the actual
+channel boundary. It rejects inference from installed versions and GitHub
+release metadata. Disposition: accepted for implementation.
diff --git a/scripts/docs-generators/lume.ts b/scripts/docs-generators/lume.ts
index 48b3e69457..48e675fe4c 100644
--- a/scripts/docs-generators/lume.ts
+++ b/scripts/docs-generators/lume.ts
@@ -342,7 +342,7 @@ export function generateCLIReferenceMDX(docs: CLIDocumentation): string {
{ title: 'Guest Access and Security', commands: ['ssh', 'setup', 'sip'] },
{
title: 'Configuration and Server',
- commands: ['config', 'serve', 'logs', 'check-update', 'update'],
+ commands: ['config', 'serve', 'logs', 'check-update', 'update', 'channel'],
},
{ title: 'Developer Tools', commands: ['dump-docs'] },
];