Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-home): CuaChannel, the names that keep Cua Spaces Local apart from stable (CUA-1776) (#5800)
Francesco Bonaccie89696750138
diff --git a/.github/workflows/ci-cua-spaces-macos.yml b/.github/workflows/ci-cua-spaces-macos.ymlindex dbe408e644..20da07eba6 100644--- a/.github/workflows/ci-cua-spaces-macos.yml+++ b/.github/workflows/ci-cua-spaces-macos.yml@@ -32,6 +32,8 @@ on:- "libs/cua/crates/cua-teleport/**"- "libs/cua/crates/cua-keyvault/**"- "libs/cua/crates/cua-sdk/**"+ # The channel names the Local bundle is stamped from (CuaChannel).+ - "libs/cua/crates/cua-home/**"- "libs/cua/scripts/generate-app-core-ffi.py"- "libs/cua/swift/**"- "libs/spaces-sdk-swift/**"@@ -56,6 +58,8 @@ on:- "libs/cua/crates/cua-teleport/**"- "libs/cua/crates/cua-keyvault/**"- "libs/cua/crates/cua-sdk/**"+ # The channel names the Local bundle is stamped from (CuaChannel).+ - "libs/cua/crates/cua-home/**"- "libs/cua/scripts/generate-app-core-ffi.py"- "libs/cua/swift/**"- "libs/spaces-sdk-swift/**"@@ -184,6 +188,12 @@ jobs:- name: Swift tests (view models, parity, snapshots)working-directory: apps/cua-spaces-macosrun: scripts/test.sh+ # install-local.sh and uninstall-local.sh against a fake HOME and a fake+ # build: a Stable install stays byte-identical, a wrong bundle id is+ # refused. Needs no build, certificate or network.+ - name: install-local and uninstall-local (fake HOME)+ working-directory: apps/cua-spaces-macos+ run: scripts/tests/install-local-test.sh# BridgeContractTests (above) checked every answer against# apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json; its# answers then go through the web UI's webkit adapter.@@ -274,6 +284,29 @@ jobs:- name: Build the app bundle (and its launch check)working-directory: apps/cua-spaces-macosrun: scripts/build-app.sh release+ # Cua Spaces Local (--channel local) runs beside an installed Cua+ # Spaces and must not be able to touch it (CUA-1776): the Local bundle+ # id, helper, URL scheme and home, staging, and no Sparkle feed. The+ # build ends with scripts/check-local-bundle.sh; the second step proves+ # the check fails on the production bundle (its id, its feed, its+ # `cua` scheme).+ - name: Build the Local bundle (Cua Spaces Local) and check it+ working-directory: apps/cua-spaces-macos+ run: |+ scripts/build-app.sh --channel local release "$RUNNER_TEMP/local-app"+ scripts/check-local-bundle.sh "$RUNNER_TEMP/local-app/Cua Spaces Local.app"+ - name: The Local check rejects the production bundle+ working-directory: apps/cua-spaces-macos+ run: |+ if scripts/check-local-bundle.sh ".build/app/Cua Spaces.app" 2>"$RUNNER_TEMP/local-check.log"; then+ echo "check-local-bundle.sh accepted the production bundle" >&2+ exit 1+ fi+ cat "$RUNNER_TEMP/local-check.log"+ for want in "production one" "SUFeedURL is set" "'cua' URL scheme is registered"; do+ grep -F "$want" "$RUNNER_TEMP/local-check.log" >/dev/null ||+ { echo "the check did not report: $want" >&2; exit 1; }+ done# With the release key only (it is absent on forks): two fake releases# through make-appcast.sh, checked with Sparkle's sign_update and the# public key the app ships (catches a secret that does not match it).diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.tsindex 24fb0e540d..711b431c08 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts@@ -24331,7 +24331,8 @@ export interface AgentSetupLike {/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/configureMcp(agents: Array<string>, server: AgentMcpServer | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<AgentSetupOutcome>>;/**@@ -24411,7 +24412,8 @@ private constructor(pointer: UniffiHandle) {/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/async configureMcp(agents: Array<string>, server: AgentMcpServer | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Array<AgentSetupOutcome>> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;@@ -44131,7 +44133,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_agentrun_wait() !== 14426) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentrun_wait");}- if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() !== 62628) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() !== 53713) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp");}if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_detect() !== 59369) {diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.tsindex b5615c1ea8..e77594b1dc 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts@@ -13212,7 +13212,8 @@ export type AppCliInstallPlan = {*/bundledVersion?: string,/**- * Another `cua` found earlier on PATH (it would shadow `target`).+ * Another CLI of the same name found earlier on PATH (it would shadow+ * `target`).*/shadowedBy?: string,/**@@ -13228,9 +13229,10 @@ export type AppCliInstallPlan = {*/pathLine?: string,/**- * A working `cua` CLI already on this machine: `target`, else the- * first in the usual install folders or on PATH (a Finder-launched+ * A working CLI of this channel already on this machine: `target`, else+ * the first in the usual install folders or on PATH (a Finder-launched* app's PATH lacks `~/.local/bin`, so the folders are searched too).+ * Local looks for `cua-local` only: a Stable `cua` is not its CLI.*/found?: string}diff --git a/apps/cua-spaces-macos/README.md b/apps/cua-spaces-macos/README.mdindex f29e4458f4..9eeec2d2d9 100644--- a/apps/cua-spaces-macos/README.md+++ b/apps/cua-spaces-macos/README.md@@ -53,8 +53,39 @@ cd ../../apps/cua-spaces-macosswift build # the packagescripts/test.sh # unit, parity and snapshot tests (swift-testing)scripts/build-app.sh release # .build/app/Cua Spaces.app, ad hoc signed+scripts/build-app.sh --channel local release # .build/app/Cua Spaces Local.app (below)```+### Cua Spaces Local, beside the installed app++`scripts/build-app.sh --channel local` builds **Cua Spaces Local**, which runs+at the same time as an installed Cua Spaces and cannot touch it (CUA-1776).+Without `--channel` the build is Stable, the app the release scripts ship.+Every Local name comes from `CuaChannel`+(`libs/cua/crates/cua-home/src/channel.rs`; `scripts/channel-names.sh local`+prints them), so nothing here hard-codes one.++| | Stable | Local |+|---|---|---|+| App | `Cua Spaces.app` | `Cua Spaces Local.app` |+| Bundle id | `com.trycua.spaces.macos` | `com.trycua.spaces.local` |+| Info.plist | no channel keys | `CuaChannel=local`, `CuaEnv=staging`, `CuaHome=~/.cua-local`, `CuaHelperLabel`, `CuaUrlScheme` |+| Cua deployment | prod (`CUA_ENV` picks another) | staging (`CUA_ENV=prod` opts in) |+| Cua home | `~/.cua` (`~/.cua/envs/staging` on staging) | `~/.cua-local` on staging; `~/.cua-local/envs/prod` under the `CUA_ENV=prod` opt-in |+| Sign-in Keychain service | `ai.cua.session` (`.staging` on staging) | `ai.cua.session.local` (`.staging` on staging) |+| Helper login item | `com.trycua.spaces.helper` | `com.trycua.spaces.local.helper` (plist file and `AssociatedBundleIdentifiers` stamped to match) |+| URL scheme | `cua://` | `cua-local://` |+| Updater | Sparkle feed and key | none (`SUFeedURL`, `SUPublicEDKey` removed): it never offers or installs an update |++The app reads `CuaChannel`, `CuaEnv` and `CuaHome` at start and sets+`CUA_CHANNEL`, `CUA_ENV` and `CUA_HOME` before anything else runs (the login+item included), so `cua-spacesd` and every other child inherit them+(`TargetEnvironment`). A variable that is already set wins. The build ends with+`scripts/check-local-bundle.sh`, which fails if a Local bundle has the+production id, a Sparkle feed or the `cua` scheme; CI runs it too. Run a Local+build from the build directory: installing it beside Stable (with its CLI,+Volume and Lume) is the install-local work of CUA-1776.+`SNAPSHOT_RECORD=1 scripts/test.sh` re-records the snapshot references.UI tests (XCUITest) need Xcode: `xcodegen generate` (project.yml), then`xcodebuild test -scheme CuaSpacesMacUITests`.@@ -188,9 +219,13 @@ team `YCK386LBJ7`, identifier in `CUA_IDENTIFIERS`, hardened runtime.The saved sign-in (`cua auth login`, shared by the app, its `cua` daemonand the `cua` CLI) is a generic password in the login keychain: service-`run.cua.ai`, account `cua-cli`, plus `cua-cli.<name>` for named secrets-such as the device key (`cua-auth`). Only Cua-signed builds use the-keychain; ad hoc and unsigned builds keep it in `~/.cua/credentials.json`.+`ai.cua.session` (`ai.cua.session.staging` on staging), account `cua-cli`,+plus `cua-cli.<name>` for named secrets such as the device key (`cua-auth`).+Items older builds kept under `run.cua.ai` move to it once. Cua Spaces Local+has its own services, `ai.cua.session.local` and `ai.cua.session.local.staging`+(`CuaChannel::keychain_service`), and nothing to move, so it never reads,+replaces or signs out the released app's sign-in. Only Cua-signed builds use+the keychain; ad hoc and unsigned builds keep it in `<cua home>/credentials.json`.**The launch never waits on it.** The window (or New UI's) opens first,on stand-ins for the live services (`Models/AppStartup.swift`). Then, off@@ -288,6 +323,113 @@ app for Windows and Linux.This app is the macOS release; the Electron app (`apps/cua-spaces-desktop`)ships for Windows and Linux.+## Run a Local build next to the stable app++`scripts/install-local.sh` builds this checkout and installs it as **Cua Spaces+Local**, beside the released Cua Spaces, so you can use Spaces to build Spaces:+the released app on your production account, your build on staging, both+signed in and both hosting this Mac.++```sh+scripts/install-local.sh # debug build, then opens the app+scripts/install-local.sh --release # release configuration+scripts/install-local.sh --no-launch # install without opening it+scripts/install-local.sh --with-lume-local # also install lume-local+scripts/install-local.sh --prefix DIR # app in DIR/Applications, cua-local in DIR/.local/bin+scripts/install-local.sh --skip-web-build # use the web UI already built in apps/cua-spaces-web/dist+scripts/install-local.sh --setup-signing # do the one-time signing setup on a new Keychain without asking+```++It first checks what the build needs and lists everything that is missing in+one message, with what to run: the Xcode command line tools, `cmake`, Rust+(rustup), and for the web UI Node 22 or later, `pnpm`, the `wasm32` Rust target+and `wasm-bindgen-cli` (the versions the release build pins). Nothing is built+before they are all there.++`--prefix` is resolved first (`..` and symlinks included) and refused when the+app or `cua-local` would land on, or inside, anything the released Cua Spaces+owns: `/Applications`, `~/.cua`, `~/.local/bin/cua`, `~/.lume`, `~/Cua Volume`.++The Local build shares nothing with the released app. Every name comes from+`CuaChannel::Local` (`libs/cua/crates/cua-home/src/channel.rs`):++| | Cua Spaces | Cua Spaces Local |+|---|---|---|+| App | `/Applications/Cua Spaces.app` | `~/Applications/Cua Spaces Local.app` |+| Bundle id | `com.trycua.spaces.macos` | `com.trycua.spaces.local` |+| CLI | `~/.local/bin/cua` | `~/.local/bin/cua-local` |+| Home | `~/.cua` | `~/.cua-local` |+| Backend | production | staging (`CUA_ENV=prod` opts in) |+| URL scheme | `cua://` | `cua-local://` |+| Updates | Sparkle | none |++The script builds the web UI as the release build does (`pnpm install+--ignore-workspace --frozen-lockfile`, `pnpm build` in `apps/cua-spaces-web`;+`--skip-web-build` or `CUA_WEBUI_DIST` use a build that is already there) and+stops, with a message, when there is none: without it the app says "The new UI+is not in this build". Then it builds the library, the `cua` CLI and+`cua-spacesd` from this checkout (`--skip-rust-build` reuses the last build) and runs+`scripts/build-app.sh --channel local` with `CUA_SPACESD_BIN` set to that+`cua-spacesd`. Without it build-app.sh bundles the pinned release of the host+service, which does not know the Local ports; the script compares the bundled+daemon's machine code with the one it built and refuses the app if they differ.+It copies the app to a staging folder, signs it, checks the signature, the bundle id, the URL scheme+and that there is no update feed, and only then swaps it in. If the copy does+not verify it puts the previous Local app back. It refuses to replace anything+at the Local path that is not a Cua Spaces Local bundle, and it never writes to+`/Applications/Cua Spaces.app`, `~/.local/bin/cua`, `~/.cua` or `~/.lume`.+`cua-local` is a link to the `cua` inside the app; no shell profile is edited,+so put `~/.local/bin` on your PATH.++**Permissions survive a rebuild** when the app is signed with the stable local+certificate that Cua Driver's local install uses+(`libs/cua-driver/scripts/_local-signing.sh`; setup in+`libs/cua-driver/scripts/README.md`, "Stable macOS local signing"). Without it+the app is signed ad hoc and macOS asks for Screen Recording and Accessibility+again after every rebuild; the script says so, and clears the stale rows for the+Local bundle id only. `--require-stable-signing` stops instead of signing ad hoc.++On a new Keychain the certificate is created but codesign cannot use it until+macOS trusts it for code signing, its Keychain is in your search list and+codesign may use its key. The script checks that with a real signing. When it+does not work it says so and, once you agree at a terminal (or with+`--setup-signing`), sets it up: macOS asks for your password once to trust the+certificate, and the Keychain password is asked once (not stored) if codesign+still needs the key, which is opened for that certificate's key only (`-t+private -l <its name>`; never every signing key in your Keychain). Without a terminal or a screen (SSH, a VM) it prints the+exact commands, `sudo` variant included, and does nothing. It never trusts+anything unasked, never changes a certificate you chose with+`CUA_DRIVER_LOCAL_SIGNING_IDENTITY`, and still requires a certificate-backed+signature before it counts as stable.++**Coding agents.** The Local app's agent setup ("Continue" on the welcome+screen) registers its own MCP server as `cua-local` (it launches Local's `cua`)+and installs its own skill copies as `<name>-local` (`cua-spaces-local`, ...;+`SKILL.md` carries that name and a note to run `cua-local`), in the same agent+configs and skills folders as the released app, and keeps its record under+`~/.cua-local`. The released app's `cua` entry and skills are left as they are,+and removing Local's setup removes only Local's. The names come from+`CuaChannel` (`mcp_server_name`, `skill_install_name`).++Rebuilding is the same command. To remove it:++```sh+scripts/uninstall-local.sh # asks first; --yes to skip, --with-lume-local to include lume-local+```++It unregisters the Local helper login item and removes the app, `cua-local`,+`~/.cua-local`, the Local app support folder and the Local Keychain items+(`ai.cua.session.local*`). It keeps `~/Cua Volume Local` and the permissions+macOS granted.++There is one Local slot per Mac: an Internal build from CI uses the same+identity, so it and a build from source replace each other.++`scripts/tests/install-local-test.sh` checks all of this against a fake `HOME`+and a fake build: a Stable install is byte-identical before and after install,+rebuild and uninstall, a wrong bundle id is refused, a failed copy is rolled+back. `CUA_TEST_SIGNING_KEYCHAIN=<keychain>` adds the certificate-signing checks.+## Release`.github/workflows/cd-cua-spaces.yml` (tags `cua-spaces-v*`) runsdiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swiftindex cdc00df4dd..33ff8d2f27 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/ServiceLauncher.swift@@ -7,11 +7,14 @@//// CuaSpacesMac --service-helper run the login item (SMAppService.agent,// Contents/Library/LaunchAgents/+// <CuaHelperLabel>.plist, by default// com.trycua.spaces.helper.plist):-// reads ~/.cua/helper/service.json-// (written by cua-host: args, env,-// log, working directory) and runs-// Contents/MacOS/cua-spacesd with it+// reads <CuaHome>/helper/service.json+// (by default ~/.cua/helper/+// service.json; written by cua-host:+// args, env, log, working directory)+// and runs Contents/MacOS/cua-spacesd+// with it// CuaSpacesMac check-permissions `cua-spacesd check-permissions` with// this terminal's stdio: the app's own// permission state (cua-host's@@ -30,16 +33,20 @@import ApplicationServicesimport CoreGraphics+import CuaSpacesMacKitimport Darwinimport Foundation-/// The spec file cua-host writes (`cua_host::service::helper_spec_path`).-private func specPath() -> String {+/// The spec file cua-host writes (`cua_host::service::helper_spec_path`):+/// below the `CuaHome` this bundle was stamped with (Cua Spaces Local:+/// `~/.cua-local`), else `~/.cua`. `nil` when a bundle of another channel+/// has no usable home: it must not read the released app's spec.+private func specPath() -> String? {var home = ProcessInfo.processInfo.environment["HOME"] ?? ""if home.isEmpty, let pw = getpwuid(getuid()), let dir = pw.pointee.pw_dir {home = String(cString: dir)}- return home + "/.cua/helper/service.json"+ return HelperService.specPath(info: Bundle.main.infoDictionary, home: home)}/// `cua-spacesd` next to this executable (never a path from the spec: only@@ -145,12 +152,16 @@ enum ServiceLauncher {/// `CuaSpacesMac --service-helper run`: the host service.static func serve() -> Never {- guard let spec = Spec.load(specPath()) else {- log("no host service set up (\(specPath())); nothing to run")+ guard let specFile = specPath() else {+ log("this app's CuaHome is not usable; nothing to run")+ exit(0)+ }+ guard let spec = Spec.load(specFile) else {+ log("no host service set up (\(specFile)); nothing to run")exit(0)}guard !spec.args.isEmpty else {- log("\(specPath()) has no arguments; nothing to run")+ log("\(specFile) has no arguments; nothing to run")exit(0)}for sig in [SIGTERM, SIGINT, SIGHUP] {@@ -176,7 +187,6 @@ enum ServiceLauncher {// the host was removed: the files are gone while this process still// runs from them. Stop, so the service that replaced it can take the// port; launchd does not start a program that is gone.- let specFile = specPath()let daemonFile = daemonPath()Thread.detachNewThread {var misses = 0diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swiftindex 35c5560ce5..9205c1df8e 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift@@ -18,6 +18,12 @@ if CommandLine.arguments.dropFirst().first == "--check-launch-only" {exit(0)}+// A Local build ("Cua Spaces Local", Info.plist CuaChannel=local) settles+// CUA_CHANNEL, CUA_ENV and CUA_HOME first, before anything else starts, so the+// helper below, cua-spacesd and every other child inherit them. A Stable+// build changes nothing here.+TargetEnvironment.pinChannel()+// The host service, run by this same executable so every permission is the// app's ("Cua Spaces"; ServiceLauncher.swift), before anything else:// * `--service-helper run`: the service itself (the login item launchd@@ -25,7 +31,8 @@ if CommandLine.arguments.dropFirst().first == "--check-launch-only" {// * `check-permissions`: cua-spacesd's permission check, answered for the// app;// * `--service-helper register|unregister|status`: the login item-// (Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist) through+// (Contents/Library/LaunchAgents/<CuaHelperLabel>.plist, by default+// com.trycua.spaces.helper.plist) through// SMAppService, which only this bundle's own code may register. cua-host's// app-helper runner runs it (from the app's SDK and from the `cua` CLI);// prints `{"status": ...}` (and `"error"`).@@ -38,7 +45,8 @@ if launchArgs.first == "check-permissions" {ServiceLauncher.passthrough(launchArgs)}-// `CUA_ENV=staging`: this process and the daemon use the staging home.+// `CUA_ENV=staging`: this process and the daemon use the staging home (a+// Local build already settled its three variables above).TargetEnvironment.pin()// Teleport, the Cua Volume, persistent agents and the Keyvault for everydiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swiftindex 1431ecbbdb..66d22c5fed 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift@@ -11,9 +11,17 @@ import Foundation/// views captures and UI tests use.@MainActorpublic enum AppEnvironment {+ /// Whether this is a Local build ("Cua Spaces Local", Info.plist+ /// `CuaChannel` = `local`, stamped by `scripts/build-app.sh --channel+ /// local`). Tests and every other build are Stable.+ static let isLocalChannel =+ ((Bundle.main.object(forInfoDictionaryKey: "CuaChannel") as? String) ?? "")+ .trimmingCharacters(in: .whitespaces).lowercased() == "local"+/// The bundle identity (the Keyvault's trusted-caller requirement names- /// it; see README "Keyvault identity").- public static let bundleIdentifier = "com.trycua.spaces.macos"+ /// it; see README "Keyvault identity"). A Local build keeps its settings+ /// in its own folder, `com.trycua.spaces.local`, never Stable's.+ public static let bundleIdentifier = isLocalChannel ? "com.trycua.spaces.local" : "com.trycua.spaces.macos"/// `$HOME`, so a temp HOME (tests, captures) keeps every file away from/// the account's real Library (`FileManager` ignores `$HOME`).@@ -83,7 +91,7 @@ public enum AppEnvironment {// Icons: caches survive restarts; fixtures never resolve apps or// touch the network.let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?- .appendingPathComponent("com.trycua.cua-spaces/icons")+ .appendingPathComponent(isLocalChannel ? "com.trycua.cua-spaces.local/icons" : "com.trycua.cua-spaces/icons")keyvault.appIcons = AppIconCache(dir: caches?.appendingPathComponent("apps"))keyvault.siteIconStore = SiteIconStore(dir: caches?.appendingPathComponent("sites"))keyvault.iconScale = Int(NSScreen.main?.backingScaleFactor ?? 2)diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swiftindex 4d336a10c0..8257f4c2e8 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift@@ -29,14 +29,17 @@ public protocol AgentSetupRunning: AnyObject, Sendable {}/// The SDK's `AgentSetup`, registering the app's own `cua` as the MCP-/// server when the bundle carries one.+/// server when the bundle carries one. The server has no name here: the+/// SDK names it for the app's channel (`cua`, `cua-local` for Cua Spaces+/// Local), so the Local app never writes over the released app's entry, and+/// it installs the channel's skill copies (`cua-spaces-local`).public final class LiveAgentSetup: AgentSetupRunning, @unchecked Sendable {let inner: CuaSDK.AgentSetuplet server: AgentMcpServer?public init(inner: CuaSDK.AgentSetup, cuaBinary: String?) {self.inner = inner- self.server = cuaBinary.map { AgentMcpServer(name: "cua", command: $0, args: ["mcp"], env: [:]) }+ self.server = cuaBinary.map { AgentMcpServer(name: "", command: $0, args: ["mcp"], env: [:]) }}public func statuses() async -> [AppAgentSetupStatus] { inner.detect().map { appAgentSetupStatus(info: $0) } }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppURLScheme.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppURLScheme.swiftnew file mode 100644index 0000000000..258fd0c6aa--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppURLScheme.swift@@ -0,0 +1,28 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation++/// The URL scheme this app answers to: `cua` for the released app, `cua-local`+/// for Cua Spaces Local. `scripts/build-app.sh --channel local` stamps it as+/// Info.plist `CuaUrlScheme` (`CuaChannel::url_scheme` in cua-home) and+/// registers it in `CFBundleURLTypes`, in place of `cua`; a bundle without the+/// key is the released app. The two apps run side by side, so each must+/// handle only its own links: `cua://add/<code>` belongs to Stable and+/// `cua-local://add/<code>` to Local (CUA-1776).+public enum AppURLScheme {+ /// The released app's scheme, and the default when the bundle has no+ /// `CuaUrlScheme`.+ public static let stable = "cua"++ /// The scheme `info` (an Info.plist) names: `CuaUrlScheme` (trimmed,+ /// lower case; a URL's scheme is case-insensitive), else `cua`.+ public static func resolve(info: [String: Any]?) -> String {+ let value = ((info?["CuaUrlScheme"] as? String) ?? "")+ .trimmingCharacters(in: .whitespaces).lowercased()+ return value.isEmpty ? stable : value+ }++ /// This app's scheme.+ public static var current: String { resolve(info: Bundle.main.infoDictionary) }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swiftindex 5d8033a5db..7e06bff19a 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LoginItem.swift@@ -87,15 +87,71 @@ public enum LoginLaunch {/// The host service's login item: this app's own executable/// (`CuaSpacesMac --service-helper run`, so its permissions are the app's) run by-/// `SMAppService.agent` from Contents/Library/LaunchAgents/-/// com.trycua.spaces.helper.plist. cua-host (the `app-helper` runner, in-/// this app's SDK and in the `cua` CLI) drives it through-/// `CuaSpacesMac --service-helper register|unregister|status`, because only-/// this bundle's code may register it; it writes what the helper runs-/// (~/.cua/helper/service.json) and starts it with launchctl.+/// `SMAppService.agent` from Contents/Library/LaunchAgents/<label>.plist+/// (com.trycua.spaces.helper.plist for the released app). cua-host (the+/// `app-helper` runner, in this app's SDK and in the `cua` CLI) drives it+/// through `CuaSpacesMac --service-helper register|unregister|status`,+/// because only this bundle's code may register it; it writes what the+/// helper runs (<CuaHome>/helper/service.json, ~/.cua/helper/service.json+/// for the released app) and starts it with launchctl.+///+/// Each channel has its own helper, so Cua Spaces Local runs beside the+/// released app without sharing its login item, launchd label or spec:+/// `scripts/build-app.sh` stamps `CuaHelperLabel` and `CuaHome` (and names+/// the plist after the label) into the bundle, and this reads them. A bundle+/// without them is the released app and keeps the names it always had.public enum HelperService {- public static let plistName = "com.trycua.spaces.helper.plist"- public static let label = "com.trycua.spaces.helper"+ /// The released app's launchd label, and the default when the bundle+ /// has no `CuaHelperLabel` (`CuaChannel::helper_label` in cua-home).+ static let defaultLabel = "com.trycua.spaces.helper"+ /// The default Cua home, below the user's home, when the bundle has no+ /// `CuaHome` (`CuaChannel::home_dir` in cua-home).+ static let defaultHome = ".cua"++ /// The launchd label of this bundle's helper: `CuaHelperLabel`, else the+ /// released app's.+ public static func label(info: [String: Any]?) -> String {+ stamped(info, "CuaHelperLabel") ?? defaultLabel+ }++ /// The plist in Contents/Library/LaunchAgents: `<label>.plist`.+ public static func plistName(info: [String: Any]?) -> String {+ label(info: info) + ".plist"+ }++ /// Where cua-host writes what the helper runs: `<CuaHome>/helper/+ /// service.json` (`CuaHome` is `~/...` or absolute), else+ /// `~/.cua/helper/service.json`. `nil` for a bundle that names another+ /// channel (`CuaChannel` other than `stable`) without a usable home: it+ /// must never fall back to the released app's file, so it runs nothing.+ public static func specPath(info: [String: Any]?, home: String) -> String? {+ let base: String+ if let stampedHome = stamped(info, "CuaHome") {+ if stampedHome == "~" {+ base = home+ } else if stampedHome.hasPrefix("~/") {+ base = home + "/" + String(stampedHome.dropFirst(2))+ } else if stampedHome.hasPrefix("/") {+ base = stampedHome+ } else {+ return nil+ }+ } else if let channel = stamped(info, "CuaChannel"), channel.lowercased() != "stable" {+ return nil+ } else {+ base = home + "/" + defaultHome+ }+ return (base as NSString).appendingPathComponent("helper/service.json")+ }++ private static func stamped(_ info: [String: Any]?, _ key: String) -> String? {+ guard let value = (info?[key] as? String)?.trimmingCharacters(in: .whitespaces),+ !value.isEmpty else { return nil }+ return value+ }++ public static var label: String { label(info: Bundle.main.infoDictionary) }+ public static var plistName: String { plistName(info: Bundle.main.infoDictionary) }static var service: SMAppService { SMAppService.agent(plistName: plistName) }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TargetEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TargetEnvironment.swiftindex 3acf06b0a9..008eef7098 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TargetEnvironment.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TargetEnvironment.swift@@ -3,25 +3,103 @@import Foundation-/// Which Cua deployment the app talks to: `CUA_ENV` (`prod`, the default, or-/// `staging`). The SDK resolves every endpoint from it. The app only settles-/// it before anything starts:+/// Which Cua channel and deployment the app runs as: `CUA_CHANNEL` (`stable`,+/// the default, or `local`, "Cua Spaces Local") and `CUA_ENV` (`prod`, the+/// default, or `staging`). The SDK resolves every endpoint and name from+/// them (`cua-home`'s `CuaChannel` and `CuaEnv`). The app only settles them+/// before anything starts, so the daemon, the helper and every other child+/// inherit the same values:///-/// - `CUA_ENV` unset: the bundle's `CuaEnv` Info.plist value, which a-/// development build can set to `staging`; release builds, betas included,-/// have none (`scripts/build-release.sh` removes it), so they use production;-/// - `CUA_HOME` unset under staging: `~/.cua/envs/staging`, so the daemon it-/// supervises and every file it reads use the same home as the SDK.+/// - `CUA_CHANNEL` unset: the bundle's `CuaChannel` Info.plist value, which+/// `scripts/build-app.sh --channel local` sets to `local`; Stable builds+/// have none. A Local app then also settles:+/// - `CUA_ENV` unset: the bundle's `CuaEnv` (`staging`), else `staging`:+/// Local never talks to production unless `CUA_ENV=prod` says so;+/// - `CUA_HOME` unset: the bundle's `CuaHome` (`~/.cua-local`), else+/// `~/.cua-local`, for its default environment (staging), and+/// `<that>/envs/prod` under the `CUA_ENV=prod` opt-in, as Stable keeps+/// `~/.cua/envs/staging`, so it never shares Stable's home, daemon or+/// sockets, and its production state never shares its staging home+/// (`CuaChannel::env_home_dir` in cua-home);+/// - on Stable, `CUA_ENV` unset: the bundle's `CuaEnv` Info.plist value, which+/// a development build can set to `staging`; release builds, betas+/// included, have none (`scripts/build-release.sh` removes it), so they use+/// production;+/// - on Stable, `CUA_HOME` unset under staging: `~/.cua/envs/staging`, so the+/// daemon it supervises and every file it reads use the same home as the+/// SDK.+///+/// A variable that is already set always wins (a blank one counts as unset+/// for a Local app), as in `cua-home`.public enum TargetEnvironment {- /// The variables to set for `env` and the bundle's `CuaEnv` value.- public static func pinned(env: [String: String], bundleEnv: String?, home: String) -> [String: String] {+ /// The channel a value names: `stable` or `local` (any case), else nil.+ private static func channel(_ value: String?) -> String? {+ let name = (value ?? "").trimmingCharacters(in: .whitespaces).lowercased()+ return name == "stable" || name == "local" ? name : nil+ }++ private static func trimmed(_ value: String?) -> String {+ (value ?? "").trimmingCharacters(in: .whitespaces)+ }++ private static func isBlank(_ value: String?) -> Bool {+ trimmed(value).isEmpty+ }++ /// Whether a `CUA_ENV` value names production (`prod` or `production`,+ /// any case), as `CuaEnv::parse` does.+ private static func isProduction(_ value: String) -> Bool {+ let name = value.trimmingCharacters(in: .whitespaces).lowercased()+ return name == "prod" || name == "production"+ }++ /// `path` with a leading `~/` replaced by `home`.+ private static func expand(_ path: String, home: String) -> String {+ path.hasPrefix("~/")+ ? URL(fileURLWithPath: home, isDirectory: true)+ .appendingPathComponent(String(path.dropFirst(2)), isDirectory: true).path+ : path+ }++ /// The variables to set for `env` and the bundle's `CuaChannel`, `CuaEnv`+ /// and `CuaHome` values.+ public static func pinned(+ env: [String: String], bundleEnv: String?, home: String,+ bundleChannel: String? = nil, bundleHome: String? = nil+ ) -> [String: String] {var out: [String: String] = [:]- var name = env["CUA_ENV"]- if name == nil, let bundleEnv, !bundleEnv.isEmpty {- name = bundleEnv+ var name = channel(env["CUA_CHANNEL"])+ if name == nil, let bundle = channel(bundleChannel) {+ name = bundle+ // Only a Local bundle sets it: Stable builds never did.+ if bundle == "local" { out["CUA_CHANNEL"] = bundle }+ }+ if name == "local" {+ // The deployment this Local app runs against, as cua-home reads+ // it: `CUA_ENV` when set, else the bundle's, else staging.+ let envValue: String+ if isBlank(env["CUA_ENV"]) {+ envValue = isBlank(bundleEnv) ? "staging" : trimmed(bundleEnv)+ out["CUA_ENV"] = envValue+ } else {+ envValue = trimmed(env["CUA_ENV"])+ }+ if isBlank(env["CUA_HOME"]) {+ let base = expand(isBlank(bundleHome) ? "~/.cua-local" : trimmed(bundleHome), home: home)+ // An unknown value is staging on Local, never production.+ out["CUA_HOME"] = isProduction(envValue)+ ? URL(fileURLWithPath: base, isDirectory: true)+ .appendingPathComponent("envs/prod", isDirectory: true).path+ : base+ }+ return out+ }+ var envName = env["CUA_ENV"]+ if envName == nil, let bundleEnv, !bundleEnv.isEmpty {+ envName = bundleEnvout["CUA_ENV"] = bundleEnv}- let normalized = (name ?? "").trimmingCharacters(in: .whitespaces).lowercased()+ let normalized = (envName ?? "").trimmingCharacters(in: .whitespaces).lowercased()if normalized == "staging", (env["CUA_HOME"] ?? "").isEmpty {out["CUA_HOME"] = URL(fileURLWithPath: home, isDirectory: true).appendingPathComponent(".cua/envs/staging", isDirectory: true).path@@ -31,10 +109,29 @@ public enum TargetEnvironment {/// Applies [`pinned`] to this process. Call first in `main`.public static func pin(bundle: Bundle = .main) {+ apply(pinned(bundle: bundle))+ }++ /// Applies [`pinned`] to this process only when the bundle is a Local+ /// build: `CUA_CHANNEL`, `CUA_ENV` and `CUA_HOME`. For the entry points+ /// that run before [`pin`] (the login item, which starts `cua-spacesd`+ /// with this process's environment). A Stable bundle changes nothing.+ public static func pinChannel(bundle: Bundle = .main) {+ guard channel(bundle.object(forInfoDictionaryKey: "CuaChannel") as? String) == "local" else { return }+ apply(pinned(bundle: bundle))+ }++ private static func pinned(bundle: Bundle) -> [String: String] {let env = ProcessInfo.processInfo.environment- let bundleEnv = bundle.object(forInfoDictionaryKey: "CuaEnv") as? String- for (key, value) in pinned(env: env, bundleEnv: bundleEnv, home: env["HOME"] ?? NSHomeDirectory()) {- setenv(key, value, 1)- }+ return pinned(+ env: env,+ bundleEnv: bundle.object(forInfoDictionaryKey: "CuaEnv") as? String,+ home: env["HOME"] ?? NSHomeDirectory(),+ bundleChannel: bundle.object(forInfoDictionaryKey: "CuaChannel") as? String,+ bundleHome: bundle.object(forInfoDictionaryKey: "CuaHome") as? String)+ }++ private static func apply(_ vars: [String: String]) {+ for (key, value) in vars { setenv(key, value, 1) }}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swiftindex 4ba44c999b..410ffa956e 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/CuaSpacesMacApp.swift@@ -313,8 +313,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {return false}- /// `cua://add/<CODE>` links: the page's Machines at the code, which it- /// confirms before joining. Never joins by itself.+ /// `cua://add/<CODE>` links (`cua-local://` in Cua Spaces Local, which+ /// answers to its own scheme only): the page's Machines at the code,+ /// which it confirms before joining. Never joins by itself.func application(_ application: NSApplication, open urls: [URL]) {guard let route = urls.lazy.compactMap(JoinWithCode.route(for:)).first else { return }NSApp.activate()diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/JoinWithCode.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/JoinWithCode.swiftindex b72caf58c0..cf82fb09cd 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/JoinWithCode.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/JoinWithCode.swift@@ -4,7 +4,9 @@import Foundation/// "Join with a code": the pairing code a machine joins with, as the-/// `host.joinWithCode` bridge method and the `cua://add/<CODE>` link carry it.+/// `host.joinWithCode` bridge method and the `cua://add/<CODE>` link carry it+/// (`cua-local://add/<CODE>` in Cua Spaces Local: the app answers only to its+/// own scheme, `AppURLScheme`)./// Pure parts only; the Process runs in `WebUIBridge+Pages.swift`.enum JoinWithCode {/// Crockford base32, the pairing code's alphabet.@@ -60,10 +62,17 @@ enum JoinWithCode {}/// What `cua://add/<CODE>`, `cua://add/<CODE>?relay=<url>` and- /// `cua://add?code=<CODE>` ask for: the page's route, or `nil` for any- /// other link or a code that is not well formed.+ /// `cua://add?code=<CODE>` ask for, in this app's scheme (`cua`, or+ /// `cua-local` in Cua Spaces Local): the page's route, or `nil` for any+ /// other link (another app's scheme included) or a code that is not well+ /// formed.static func route(for url: URL) -> String? {- guard url.scheme?.lowercased() == "cua",+ route(for: url, scheme: AppURLScheme.current)+ }++ /// [`route(for:)`] for the app whose scheme is `scheme`.+ static func route(for url: URL, scheme: String) -> String? {+ guard url.scheme?.lowercased() == scheme,let parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return nil }let segments = ([parts.host] + parts.path.split(separator: "/").map(String.init)).compactMap { $0 }.filter { !$0.isEmpty }diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperServiceTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperServiceTests.swiftnew file mode 100644index 0000000000..ffb21e675a--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HelperServiceTests.swift@@ -0,0 +1,51 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++@testable import CuaSpacesMacKit+import Foundation+import Testing++/// The host service's login item, per channel: the released app keeps the+/// label, plist and spec it always had (a bundle with no stamped keys), and+/// Cua Spaces Local reads its own from the bundle.+@Suite("Helper service names")+struct HelperServiceTests {+ let home = "/Users/ada"++ @Test func aBundleWithoutKeysIsTheReleasedApp() {+ for info in [nil, [:], ["CuaChannel": "stable"], ["CuaHelperLabel": " ", "CuaHome": ""]] as [[String: Any]?] {+ #expect(HelperService.label(info: info) == "com.trycua.spaces.helper")+ #expect(HelperService.plistName(info: info) == "com.trycua.spaces.helper.plist")+ #expect(HelperService.specPath(info: info, home: home) == "/Users/ada/.cua/helper/service.json")+ }+ }++ @Test func theReleasedAppStampedWithItsOwnNamesKeepsThem() {+ let info: [String: Any] = ["CuaChannel": "stable", "CuaHelperLabel": "com.trycua.spaces.helper", "CuaHome": "~/.cua"]+ #expect(HelperService.label(info: info) == "com.trycua.spaces.helper")+ #expect(HelperService.plistName(info: info) == "com.trycua.spaces.helper.plist")+ #expect(HelperService.specPath(info: info, home: home) == "/Users/ada/.cua/helper/service.json")+ }++ @Test func localReadsItsOwnHelperFromTheBundle() {+ let info: [String: Any] = [+ "CuaChannel": "local", "CuaHelperLabel": "com.trycua.spaces.local.helper", "CuaHome": "~/.cua-local",+ ]+ #expect(HelperService.label(info: info) == "com.trycua.spaces.local.helper")+ #expect(HelperService.plistName(info: info) == "com.trycua.spaces.local.helper.plist")+ #expect(HelperService.specPath(info: info, home: home) == "/Users/ada/.cua-local/helper/service.json")+ }++ @Test func anAbsoluteHomeIsUsedAsIs() {+ #expect(HelperService.specPath(info: ["CuaHome": "/tmp/h"], home: home) == "/tmp/h/helper/service.json")+ #expect(HelperService.specPath(info: ["CuaHome": "~"], home: home) == "/Users/ada/helper/service.json")+ }++ @Test func aBundleOfAnotherChannelNeverReadsTheReleasedAppsSpec() {+ // No home, or one that is not a path: run nothing rather than the+ // released app's helper.+ #expect(HelperService.specPath(info: ["CuaChannel": "local"], home: home) == nil)+ #expect(HelperService.specPath(info: ["CuaChannel": "local", "CuaHome": "cua-local"], home: home) == nil)+ #expect(HelperService.specPath(info: ["CuaHome": "cua-local"], home: home) == nil)+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/JoinWithCodeTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/JoinWithCodeTests.swiftindex dc27847674..620ecf46f2 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/JoinWithCodeTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/JoinWithCodeTests.swift@@ -53,6 +53,43 @@ struct JoinWithCodeTests {#expect(route("https://cua.ai/add/ABCDEFGHJKMN") == nil)}+ /// Each app answers to its own scheme only: `cua://` is Stable's and+ /// `cua-local://` Local's, and the two run on one Mac (CUA-1776).+ @Test func localPairingLinks() {+ func route(_ s: String, scheme: String) -> String? {+ URL(string: s).flatMap { JoinWithCode.route(for: $0, scheme: scheme) }+ }+ // Local takes every form of its own link.+ #expect(route("cua-local://add/abcd-efgh-jkmn", scheme: "cua-local") == "/machines?join=ABCD-EFGH-JKMN")+ #expect(route("cua-local://add/ABCDEFGHJKMN?relay=https%3A%2F%2Fr.example.com%2Fx", scheme: "cua-local")+ == "/machines?join=ABCD-EFGH-JKMN&relay=https%3A%2F%2Fr.example.com%2Fx")+ #expect(route("cua-local://add?code=abcdefghjkmn", scheme: "cua-local") == "/machines?join=ABCD-EFGH-JKMN")+ #expect(route("CUA-LOCAL://add/ABCDEFGHJKMN", scheme: "cua-local") == "/machines?join=ABCD-EFGH-JKMN")+ // ... and judges it as strictly as Stable judges `cua://`.+ #expect(route("cua-local://add/ABCDEFGHJKMN/extra", scheme: "cua-local") == nil)+ #expect(route("cua-local://add/ABCD-EFGH-JKMI", scheme: "cua-local") == nil)+ #expect(route("cua-local://open/ABCDEFGHJKMN", scheme: "cua-local") == nil)+ // A Local build rejects `cua://`: that link belongs to the released app.+ #expect(route("cua://add/ABCDEFGHJKMN", scheme: "cua-local") == nil)+ // A Stable build still rejects `cua-local://`.+ #expect(route("cua-local://add/ABCDEFGHJKMN", scheme: "cua") == nil)+ #expect(route("cua://add/ABCDEFGHJKMN", scheme: "cua") == "/machines?join=ABCD-EFGH-JKMN")+ // This test process is Stable (no `CuaUrlScheme` in its bundle).+ #expect(JoinWithCode.route(for: URL(string: "cua-local://add/ABCDEFGHJKMN")!) == nil)+ #expect(JoinWithCode.route(for: URL(string: "cua://add/ABCDEFGHJKMN")!) == "/machines?join=ABCD-EFGH-JKMN")+ }++ @Test func theSchemeComesFromTheBundle() {+ #expect(AppURLScheme.resolve(info: nil) == "cua")+ #expect(AppURLScheme.resolve(info: [:]) == "cua")+ #expect(AppURLScheme.resolve(info: ["CuaUrlScheme": " "]) == "cua")+ #expect(AppURLScheme.resolve(info: ["CuaUrlScheme": 5]) == "cua")+ #expect(AppURLScheme.resolve(info: ["CuaUrlScheme": "cua-local"]) == "cua-local")+ #expect(AppURLScheme.resolve(info: ["CuaUrlScheme": " Cua-Local "]) == "cua-local")+ // The test bundle is no Local build.+ #expect(AppURLScheme.current == "cua")+ }+@Test func linkRouteIsThePath() {#expect(MainUIRoute.path("/machines?join=ABCD-EFGH-JKMN").webPath == "/machines?join=ABCD-EFGH-JKMN")}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TargetEnvironmentTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TargetEnvironmentTests.swiftindex 6e231fd3e5..1b12ddde36 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TargetEnvironmentTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TargetEnvironmentTests.swift@@ -27,3 +27,126 @@ struct TargetEnvironmentTests {== ["CUA_ENV": "staging", "CUA_HOME": "/Users/ada/.cua/envs/staging"])}}++/// `CUA_CHANNEL=local` (Cua Spaces Local): its own home, staging by default+/// (and `envs/prod` below it under the production opt-in), the same three+/// variables for every child; Stable is untouched.+@Suite("Target environment, Local channel")+struct LocalChannelTargetEnvironmentTests {++ private func pinned(+ env: [String: String] = [:], bundleChannel: String? = "local",+ bundleEnv: String? = "staging", bundleHome: String? = "~/.cua-local"+ ) -> [String: String] {+ TargetEnvironment.pinned(+ env: env, bundleEnv: bundleEnv, home: "/Users/ada",+ bundleChannel: bundleChannel, bundleHome: bundleHome)+ }++ @Test func localBundleSetsChannelStagingAndItsOwnHome() {+ #expect(pinned() == [+ "CUA_CHANNEL": "local", "CUA_ENV": "staging", "CUA_HOME": "/Users/ada/.cua-local",+ ])+ }++ @Test func localHomeHasNoEnvironmentBelowItOnStaging() {+ let home = pinned()["CUA_HOME"] ?? ""+ #expect(home == "/Users/ada/.cua-local")+ #expect(!home.contains("envs"))+ }++ @Test func localDefaultsToStagingEvenWithoutTheBundleKeys() {+ #expect(pinned(bundleEnv: nil, bundleHome: nil) == [+ "CUA_CHANNEL": "local", "CUA_ENV": "staging", "CUA_HOME": "/Users/ada/.cua-local",+ ])+ #expect(pinned(bundleEnv: "", bundleHome: "")["CUA_ENV"] == "staging")+ }++ @Test func productionIsAnExplicitOptInWithAHomeOfItsOwnBelowLocal() {+ let out = pinned(env: ["CUA_ENV": "prod"])+ #expect(out["CUA_ENV"] == nil)+ #expect(out["CUA_HOME"] == "/Users/ada/.cua-local/envs/prod")+ #expect(out["CUA_CHANNEL"] == "local")+ // Spelled any way cua-home accepts.+ #expect(pinned(env: ["CUA_ENV": " Production "])["CUA_HOME"] == "/Users/ada/.cua-local/envs/prod")+ // From the bundle, when `CUA_ENV` is unset.+ let bundle = pinned(bundleEnv: "prod")+ #expect(bundle["CUA_ENV"] == "prod")+ #expect(bundle["CUA_HOME"] == "/Users/ada/.cua-local/envs/prod")+ // An absolute bundle home gets the same folder below it.+ #expect(pinned(env: ["CUA_ENV": "prod"], bundleHome: "/Volumes/x/.cua-local")["CUA_HOME"]+ == "/Volumes/x/.cua-local/envs/prod")+ }++ @Test func aMistypedEnvironmentIsStagingNotProduction() {+ // As in cua-home: Local never falls back to production.+ #expect(pinned(env: ["CUA_ENV": "prd"])["CUA_HOME"] == "/Users/ada/.cua-local")+ }++ @Test func explicitStagingKeepsTheLocalHome() {+ #expect(pinned(env: ["CUA_ENV": "staging"])["CUA_HOME"] == "/Users/ada/.cua-local")+ }++ /// The four (channel, environment) pairs, each with a home of its own+ /// (`CuaChannel::env_home_dir`), and no Local home inside Stable's.+ @Test func everyChannelAndEnvironmentHasItsOwnHome() {+ func home(_ env: [String: String], channel: String?) -> String {+ let out = TargetEnvironment.pinned(+ env: env, bundleEnv: nil, home: "/Users/ada",+ bundleChannel: channel, bundleHome: channel == "local" ? "~/.cua-local" : nil)+ // Stable production pins nothing: its home is `~/.cua`.+ return out["CUA_HOME"] ?? "/Users/ada/.cua"+ }+ let homes = [+ home([:], channel: nil),+ home(["CUA_ENV": "staging"], channel: nil),+ home(["CUA_ENV": "staging"], channel: "local"),+ home(["CUA_ENV": "prod"], channel: "local"),+ ]+ #expect(homes == [+ "/Users/ada/.cua",+ "/Users/ada/.cua/envs/staging",+ "/Users/ada/.cua-local",+ "/Users/ada/.cua-local/envs/prod",+ ])+ #expect(Set(homes).count == 4)+ for stable in homes[0..<2] {+ for local in homes[2..<4] {+ #expect(!stable.hasPrefix(local + "/") && !local.hasPrefix(stable + "/"))+ }+ }+ }++ @Test func setVariablesWin() {+ #expect(pinned(env: ["CUA_CHANNEL": "local", "CUA_ENV": "staging", "CUA_HOME": "/tmp/h"]).isEmpty)+ #expect(pinned(env: ["CUA_HOME": "/tmp/h"])["CUA_HOME"] == nil)+ }++ @Test func aBlankVariableCountsAsUnset() {+ let out = pinned(env: ["CUA_CHANNEL": " ", "CUA_ENV": "", "CUA_HOME": " "])+ #expect(out == ["CUA_CHANNEL": "local", "CUA_ENV": "staging", "CUA_HOME": "/Users/ada/.cua-local"])+ }++ @Test func anAbsoluteBundleHomeIsKept() {+ #expect(pinned(bundleHome: "/Volumes/x/.cua-local")["CUA_HOME"] == "/Volumes/x/.cua-local")+ }++ @Test func theChannelVariableOverridesTheBundle() {+ // `CUA_CHANNEL=stable` on a Local bundle is Stable's rule, as in cua-home.+ let out = pinned(env: ["CUA_CHANNEL": "stable"], bundleEnv: nil)+ #expect(out.isEmpty)+ // An unknown value is not a channel: the bundle decides.+ #expect(pinned(env: ["CUA_CHANNEL": "dev"])["CUA_CHANNEL"] == "local")+ }++ @Test func stableIsUnchanged() {+ // No bundle channel (every Stable build), or an explicit `stable`.+ #expect(pinned(bundleChannel: nil, bundleEnv: nil, bundleHome: nil).isEmpty)+ #expect(pinned(bundleChannel: "stable", bundleEnv: nil, bundleHome: nil).isEmpty)+ #expect(pinned(env: ["CUA_ENV": "staging"], bundleChannel: nil, bundleEnv: nil, bundleHome: nil)+ == ["CUA_HOME": "/Users/ada/.cua/envs/staging"])+ // A bundle with a staging default (a development build): the existing behaviour.+ #expect(pinned(bundleChannel: nil, bundleHome: nil)+ == ["CUA_ENV": "staging", "CUA_HOME": "/Users/ada/.cua/envs/staging"])+ }+}diff --git a/apps/cua-spaces-macos/scripts/_local-common.sh b/apps/cua-spaces-macos/scripts/_local-common.shnew file mode 100644index 0000000000..b0d3d64b10--- /dev/null+++ b/apps/cua-spaces-macos/scripts/_local-common.sh@@ -0,0 +1,237 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Names and checks shared by install-local.sh and uninstall-local.sh (Cua+# Spaces Local, CUA-1776). Sourced; no side effects besides the definitions.+#+# THE NAMES BELOW MIRROR `CuaChannel::Local` in+# libs/cua/crates/cua-home/src/channel.rs, which owns them. A shell script+# cannot call that module, so they are written once, here, and+# scripts/tests/install-local-test.sh fails when one stops matching it.+# Nothing else in these scripts spells a Local or a Stable name.++# shellcheck disable=SC2034 # each script uses some of these names++# --- Local (what these scripts install and remove) ---------------------------+LOCAL_BUNDLE_ID="com.trycua.spaces.local" # CuaChannel::bundle_id+LOCAL_APP_DIR_NAME="Cua Spaces Local.app" # CuaChannel::app_path+LOCAL_CLI_NAME="cua-local" # CuaChannel::cli_name+LOCAL_URL_SCHEME="cua-local" # CuaChannel::url_scheme+LOCAL_HOME_DIR_NAME=".cua-local" # CuaChannel::home_dir+LOCAL_APP_SUPPORT_DIR_NAME="com.trycua.spaces.local" # CuaChannel::app_support_dir_name+LOCAL_HELPER_LABEL="com.trycua.spaces.local.helper" # CuaChannel::helper_label+LOCAL_HOST_LABEL="com.trycua.spacesd.host.local" # CuaChannel::host_label+LOCAL_VOLUME_NAME="Cua Volume Local" # CuaChannel::volume_name+LOCAL_LUME_BIN_NAME="lume-local" # CuaChannel::lume_bin_name+LOCAL_LUME_DIR_NAME=".lume-local" # CuaChannel::lume_dir+# CuaChannel::keychain_service(Prod) and (Staging). The sign-in and the device+# key live under these services, one item per account.+LOCAL_KEYCHAIN_SERVICES=("ai.cua.session.local" "ai.cua.session.local.staging")++# --- Stable (what these scripts must never create, replace or remove) --------+# Only used to refuse a bundle that carries a Stable identity.+STABLE_BUNDLE_ID="com.trycua.spaces.macos" # also its app support folder name+STABLE_URL_SCHEME="cua"+STABLE_HELPER_LABEL="com.trycua.spaces.helper"+STABLE_APP_PARENT="/Applications" # CuaChannel::app_path+STABLE_APP_DIR_NAME="Cua Spaces.app"+STABLE_HOME_DIR_NAME=".cua" # CuaChannel::home_dir+STABLE_CLI_NAME="cua" # CuaChannel::cli_name+STABLE_LUME_DIR_NAME=".lume" # CuaChannel::lume_dir+STABLE_VOLUME_NAME="Cua Volume" # CuaChannel::volume_name++PLISTBUDDY=/usr/libexec/PlistBuddy+LSREGISTER="${CUA_LSREGISTER:-/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister}"++BOLD=$(tput bold 2>/dev/null || true)+NORMAL=$(tput sgr0 2>/dev/null || true)+RED=$(tput setaf 1 2>/dev/null || true)+GREEN=$(tput setaf 2 2>/dev/null || true)+BLUE=$(tput setaf 4 2>/dev/null || true)+YELLOW=$(tput setaf 3 2>/dev/null || true)++log() { printf '%s==>%s %s\n' "$BLUE" "$NORMAL" "$*"; }+ok() { printf '%s%s%s\n' "$GREEN" "$*" "$NORMAL"; }+warn() { printf '%swarning: %s%s\n' "$YELLOW" "$*" "$NORMAL" >&2; }+err() { printf '%serror: %s%s\n' "$RED" "$*" "$NORMAL" >&2; }++# A value of a bundle's Info.plist (a key path like CFBundleIdentifier); empty+# and failing when it is not there.+plist_get() { "$PLISTBUDDY" -c "Print :$2" "$1" 2>/dev/null; }++# The bundle identifier of an app bundle, empty when it has none.+bundle_id_of() { plist_get "$1/Contents/Info.plist" CFBundleIdentifier || true; }++# Every URL scheme the bundle registers, one per line.+plist_url_schemes() {+ local plist="$1" i=0 j value+ while plist_get "$plist" "CFBundleURLTypes:$i" >/dev/null; do+ j=0+ while value="$(plist_get "$plist" "CFBundleURLTypes:$i:CFBundleURLSchemes:$j")"; do+ printf '%s\n' "$value"+ j=$((j + 1))+ done+ i=$((i + 1))+ done+}++# Succeeds when `path` is absent or a Cua Spaces Local bundle, the only thing+# these scripts may replace or remove. Anything else, a Stable app included, is+# refused with the reason.+require_local_bundle_or_absent() {+ local app="$1" id+ if [ ! -e "$app" ] && [ ! -L "$app" ]; then+ return 0+ fi+ if [ -L "$app" ]; then+ err "refusing to touch $app: it is a symlink, not a Cua Spaces Local bundle"+ return 1+ fi+ if [ ! -f "$app/Contents/Info.plist" ]; then+ err "refusing to touch $app: it is not an app bundle (no Contents/Info.plist)"+ return 1+ fi+ id="$(bundle_id_of "$app")"+ if [ "$id" != "$LOCAL_BUNDLE_ID" ]; then+ err "refusing to touch $app: its bundle id is '${id:-none}', not $LOCAL_BUNDLE_ID"+ return 1+ fi+ return 0+}++# Stops the running Local app, its helper included, and nothing else: only+# processes started from inside this bundle are matched.+quit_local_app() {+ local app="$1" pattern pids waited=0+ command -v pgrep >/dev/null 2>&1 || return 0+ pattern="^$(printf '%s' "$app" | sed 's/[][\.*^$+?(){}|]/\\&/g')/Contents/"+ pids="$(pgrep -f "$pattern" 2>/dev/null || true)"+ [ -n "$pids" ] || return 0+ log "stopping the running $LOCAL_APP_DIR_NAME"+ # shellcheck disable=SC2086 # one pid per word+ kill $pids 2>/dev/null || true+ while [ "$waited" -lt 10 ] && pgrep -f "$pattern" >/dev/null 2>&1; do+ sleep 0.5+ waited=$((waited + 1))+ done+ pids="$(pgrep -f "$pattern" 2>/dev/null || true)"+ if [ -n "$pids" ]; then+ # shellcheck disable=SC2086+ kill -9 $pids 2>/dev/null || true+ fi+}++# --- Where Local may write -----------------------------------------------------++# The absolute path with `.`, `..` and every symlink resolved, whether or not+# it exists yet (what is missing is taken as written: it cannot be a link).+# Fails on a symlink loop. This is the path an install or removal acts on, so+# a `..` or a link in --prefix cannot hide where it lands.+canonicalize_path() {+ local rest="$1" cur="/" comp next target links=0+ case "$rest" in+ /*) ;;+ *) rest="$PWD/$rest" ;;+ esac+ while :; do+ while [ "${rest#/}" != "$rest" ]; do rest="${rest#/}"; done+ [ -n "$rest" ] || break+ comp="${rest%%/*}"+ if [ "$comp" = "$rest" ]; then rest=""; else rest="${rest#*/}"; fi+ case "$comp" in+ .) continue ;;+ ..) cur="$(dirname "$cur")"; continue ;;+ esac+ next="${cur%/}/$comp"+ if [ -L "$next" ]; then+ links=$((links + 1))+ [ "$links" -le 40 ] || return 1+ target="$(readlink "$next")" || return 1+ case "$target" in+ /*) cur="/" ;;+ esac+ rest="$target/$rest"+ continue+ fi+ cur="$next"+ done+ printf '%s' "$cur"+}++# A path as compared: lower case (the usual macOS volume ignores case) and+# without the firmlink prefix that makes /System/Volumes/Data/Applications the+# same folder as /Applications.+path_key() {+ local key+ key="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"+ case "$key" in+ /system/volumes/data/*) key="${key#/system/volumes/data}" ;;+ esac+ printf '%s' "$key"+}++# Succeeds when `candidate`, or a folder above it, is the very file system+# object `container` (same device and inode): it is `container` or inside it,+# however the path is spelled.+is_inside_by_identity() {+ local container="$1" candidate="$2" want have+ want="$(stat -f '%d:%i' "$container" 2>/dev/null || true)"+ [ -n "$want" ] || return 1+ while :; do+ have="$(stat -f '%d:%i' "$candidate" 2>/dev/null || true)"+ [ "$have" != "$want" ] || return 0+ [ "$candidate" != "/" ] || return 1+ candidate="$(dirname "$candidate")"+ done+}++# Succeeds when one path is the other or inside it (both given canonical).+paths_overlap() {+ local a b+ a="$(path_key "$1")/"+ b="$(path_key "$2")/"+ case "$a" in "$b"*) return 0 ;; esac+ case "$b" in "$a"*) return 0 ;; esac+ is_inside_by_identity "$1" "$2" && return 0+ is_inside_by_identity "$2" "$1" && return 0+ return 1+}++# What belongs to the released Cua Spaces, one path per line, for the home+# `$1` (canonical): the app, the home, the CLI, Lume's folder, Cua Volume and+# the app's support folder.+stable_owned_paths() {+ local home="$1"+ printf '%s\n' \+ "$STABLE_APP_PARENT/$STABLE_APP_DIR_NAME" \+ "$home/$STABLE_HOME_DIR_NAME" \+ "$home/.local/bin/$STABLE_CLI_NAME" \+ "$home/$STABLE_LUME_DIR_NAME" \+ "$home/$STABLE_VOLUME_NAME" \+ "$home/Library/Application Support/$STABLE_BUNDLE_ID"+}++# Fails, saying why, when `path` (canonical; `label` names it) is or is inside+# anything the released Cua Spaces owns, or inside /Applications, where+# Cua Spaces Local never goes. Each owned path is resolved the same way as+# `path` before they are compared, and checked as written too: ~/.lume may be a+# symlink to /Volumes/VMs, and then /Volumes/VMs is the Stable Lume folder.+# (The identity check below uses lstat, so it cannot see through a link itself.)+reject_stable_overlap() {+ local label="$1" path="$2" home owned resolved+ home="$(canonicalize_path "$HOME")" || { err "cannot resolve HOME ($HOME)"; return 1; }+ while IFS= read -r owned; do+ resolved="$(canonicalize_path "$owned")" || { err "refusing: cannot resolve $owned (a symlink loop?), which belongs to the released Cua Spaces."; return 1; }+ if paths_overlap "$path" "$owned" || paths_overlap "$path" "$resolved"; then+ if [ "$resolved" != "$owned" ]; then owned="$owned (a link to $resolved)"; fi+ err "refusing: the $label path $path is, or is inside, $owned, which belongs to the released Cua Spaces. Pick another --prefix."+ return 1+ fi+ done < <(stable_owned_paths "$home")+ resolved="$(canonicalize_path "$STABLE_APP_PARENT")" || resolved="$STABLE_APP_PARENT"+ if paths_overlap "$path" "$STABLE_APP_PARENT" || paths_overlap "$path" "$resolved"; then+ err "refusing: the $label path $path is inside $STABLE_APP_PARENT, where the released Cua Spaces lives. Cua Spaces Local goes under ~/Applications; pick another --prefix."+ return 1+ fi+}diff --git a/apps/cua-spaces-macos/scripts/build-app.sh b/apps/cua-spaces-macos/scripts/build-app.shindex 6553575500..b60797722d 100755--- a/apps/cua-spaces-macos/scripts/build-app.sh+++ b/apps/cua-spaces-macos/scripts/build-app.sh@@ -23,7 +23,19 @@# dylib, all but the dynamic ones from the executables) after writing their# dSYMs to <out-dir>/dSYMs, which crash reports symbolicate against.#-# scripts/build-app.sh [debug|release] [out-dir]+# scripts/build-app.sh [--channel stable|local] [debug|release] [out-dir]+#+# --channel local builds "Cua Spaces Local.app", which runs beside an+# installed Cua Spaces and cannot touch it (CUA-1776): the Local bundle id+# (com.trycua.spaces.local), name, helper login item (label and plist file+# name), URL scheme (cua-local, not cua) and cua home (~/.cua-local), staging+# by default (CuaEnv), and no Sparkle feed or key, so it never offers or+# installs an update. Every name comes from CuaChannel (scripts/channel-names.sh,+# libs/cua/crates/cua-home/src/channel.rs); the Info.plist keys CuaChannel,+# CuaHome, CuaHelperLabel, CuaUrlScheme and CuaEnv tell the app and its+# helpers which channel they are. scripts/check-local-bundle.sh proves it, and+# runs at the end of this script. Without --channel (the default, stable) the+# bundle is exactly the one the release scripts sign and ship.## CUA_APP_ARCHS="arm64 x86_64" builds each architecture and joins them with# lipo (a universal app; the SDK dylib and the `cua` CLI must then be@@ -34,8 +46,43 @@# development and CI builds.set -euo pipefailhere="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+channel=stable+args=()+while [ $# -gt 0 ]; do+ case "$1" in+ --channel) [ $# -ge 2 ] || { echo "--channel needs stable or local" >&2; exit 2; }; channel="$2"; shift 2 ;;+ --channel=*) channel="${1#--channel=}"; shift ;;+ *) args+=("$1"); shift ;;+ esac+done+case "$channel" in+ stable | local) ;;+ *) echo "--channel must be stable or local (got '$channel')" >&2; exit 2 ;;+esac+set -- ${args[@]+"${args[@]}"}config="${1:-debug}"out="${2:-$here/.build/app}"+# The names this bundle carries. Stable's are the ones the release scripts+# and the updater know; Local's come from CuaChannel, never from here.+app_name="Cua Spaces"+bundle_id=com.trycua.spaces.macos+helper_label=com.trycua.spaces.helper+if [ "$channel" = local ]; then+ names="$("$here/scripts/channel-names.sh" local)"+ while IFS='=' read -r key value; do+ case "$key" in+ app_name) app_name="$value" ;;+ bundle_id) bundle_id="$value" ;;+ helper_label) helper_label="$value" ;;+ url_scheme) url_scheme="$value" ;;+ home) cua_home="$value" ;;+ env) cua_env="$value" ;;+ esac+ done <<<"$names"+ for v in app_name bundle_id helper_label url_scheme cua_home cua_env; do+ [ -n "${!v:-}" ] || { echo "scripts/channel-names.sh local printed no $v" >&2; exit 1; }+ done+fiicons="$here/../cua-spaces/src-tauri/icons"# CUA_VZ_BIN, CUA_MICROVM_INIT_BIN: the microVM monitor (cua-vz) and the# static aarch64 guest init to bundle (build-release.sh builds both).@@ -71,10 +118,31 @@ fi# Resource bundles are the same for every architecture.bin="${bins[0]}"-app="$out/Cua Spaces.app"+app="$out/$app_name.app"rm -rf "$app"mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" "$app/Contents/Frameworks"cp "$here/Support/Info.plist" "$app/Contents/Info.plist"+if [ "$channel" = local ]; then+ # Another identity, no updater, staging, its own home, helper and URL+ # scheme. Nothing here may reach an installed Cua Spaces: see+ # scripts/check-local-bundle.sh.+ plist="$app/Contents/Info.plist"+ pb=/usr/libexec/PlistBuddy+ $pb -c "Set :CFBundleIdentifier $bundle_id" "$plist"+ $pb -c "Set :CFBundleName $app_name" "$plist"+ $pb -c "Set :CFBundleDisplayName $app_name" "$plist"+ for key in SUFeedURL SUPublicEDKey SUEnableAutomaticChecks SUAutomaticallyUpdate SUVerifyUpdateBeforeExtraction; do+ $pb -c "Delete :$key" "$plist"+ done+ # The `cua` scheme is Stable's (cua://add/<code>): Local answers cua-local://.+ $pb -c "Set :CFBundleURLTypes:0:CFBundleURLName $bundle_id" "$plist"+ $pb -c "Set :CFBundleURLTypes:0:CFBundleURLSchemes:0 $url_scheme" "$plist"+ for kv in "CuaChannel:local" "CuaEnv:$cua_env" "CuaHome:$cua_home" "CuaHelperLabel:$helper_label" "CuaUrlScheme:$url_scheme"; do+ $pb -c "Delete :${kv%%:*}" "$plist" 2>/dev/null || true+ $pb -c "Add :${kv%%:*} string ${kv#*:}" "$plist"+ done+ plutil -lint "$plist" >/dev/null+fiif [ ${#bins[@]} -gt 1 ]; thenslices=()for b in "${bins[@]}"; do slices+=("$b/CuaSpacesMac"); done@@ -132,7 +200,15 @@ mkdir -p "$app/Contents/Library/LaunchAgents"spacesd="$("$here/scripts/fetch-spacesd.sh" ${archs:-$(uname -m)})"cp "$spacesd" "$app/Contents/MacOS/cua-spacesd"chmod 0755 "$app/Contents/MacOS/cua-spacesd"-cp "$here/Support/Helper/com.trycua.spaces.helper.plist" "$app/Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist"+helper_plist="$app/Contents/Library/LaunchAgents/$helper_label.plist"+cp "$here/Support/Helper/com.trycua.spaces.helper.plist" "$helper_plist"+if [ "$channel" = local ]; then+ # The login item's own label and the app it belongs to: its own launchd+ # job and its own entry in System Settings, never Stable's.+ /usr/libexec/PlistBuddy -c "Set :Label $helper_label" "$helper_plist"+ /usr/libexec/PlistBuddy -c "Set :AssociatedBundleIdentifiers:0 $bundle_id" "$helper_plist"+ plutil -lint "$helper_plist" >/dev/null+fi[ -x "$cli" ] && cp "$cli" "$app/Contents/MacOS/cua"# Release: symbols go to dSYMs, not into the download (about 40% of each@@ -182,10 +258,10 @@ if [ -n "${CUA_SPACESD_STATIC_DIR:-}" ]; thendone[ "$found" = 1 ] || { echo "no cua-spacesd-linux-* in $CUA_SPACESD_STATIC_DIR" >&2; exit 1; }fi-codesign -s - -f -i com.trycua.spaces.macos "$app/Contents/Frameworks/libcua_sdk.dylib"+codesign -s - -f -i "$bundle_id" "$app/Contents/Frameworks/libcua_sdk.dylib"# Sparkle keeps its upstream ad hoc signatures here (build-release.sh signs# each piece with the release identity).-codesign -s - -f -i com.trycua.spaces.macos "$app"+codesign -s - -f -i "$bundle_id" "$app"codesign --verify --deep --strict "$app"# The app must run on a Mac without this build directory: the resource@@ -220,4 +296,7 @@ fi# It launches (scripts/check-launch.sh: libraries resolve and load; the app# starts and exits before any window)."$here/scripts/check-launch.sh" "$app" >&2+if [ "$channel" = local ]; then+ "$here/scripts/check-local-bundle.sh" "$app" >&2+fiecho "$app"diff --git a/apps/cua-spaces-macos/scripts/channel-names.sh b/apps/cua-spaces-macos/scripts/channel-names.shnew file mode 100755index 0000000000..1e6563eddd--- /dev/null+++ b/apps/cua-spaces-macos/scripts/channel-names.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Prints the names of a Cua Spaces channel as key=value lines (channel,+# app_name, bundle_id, helper_label, url_scheme, home, env), from `CuaChannel`+# (libs/cua/crates/cua-home/src/channel.rs), the one place that owns them+# (CUA-1776). Build and check scripts read these instead of hard-coding a+# name, so the bundle and the Rust code cannot drift apart.+#+# scripts/channel-names.sh stable|local+# eval-free use: names="$(scripts/channel-names.sh local)"+set -euo pipefail+here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+channel="${1:?usage: channel-names.sh <stable|local>}"+# From libs/cua, so its rust-toolchain.toml applies.+cd "$here/../../libs/cua"+exec cargo run --quiet --locked -p cua-home --example channel_names -- "$channel"diff --git a/apps/cua-spaces-macos/scripts/check-local-bundle.sh b/apps/cua-spaces-macos/scripts/check-local-bundle.shnew file mode 100755index 0000000000..0ccaf1f888--- /dev/null+++ b/apps/cua-spaces-macos/scripts/check-local-bundle.sh@@ -0,0 +1,126 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Proves a Local build, "Cua Spaces Local.app" (scripts/build-app.sh --channel+# local), cannot touch an installed Cua Spaces (CUA-1776). It fails when the+# bundle has:+#+# - the production bundle id, or any bundle id, name or app folder that is+# not the Local one (the names come from CuaChannel, through+# scripts/channel-names.sh);+# - a Sparkle feed or key, or automatic checks (a Local build must never+# update itself into the production app, or be offered one);+# - the `cua` URL scheme (cua://add/<code> belongs to Stable), or anything+# but `cua-local`;+# - Info.plist keys that do not say Local: CuaChannel, CuaEnv (staging),+# CuaHome, CuaHelperLabel, CuaUrlScheme;+# - a helper login item that is not the Local one: its plist file name,+# its Label and its AssociatedBundleIdentifiers, or Stable's helper plist+# next to it;+# - a signature under another identifier than the Local bundle id.+#+# scripts/check-local-bundle.sh "path/Cua Spaces Local.app"+set -euo pipefail+here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+app="${1:?usage: check-local-bundle.sh <path/Cua Spaces Local.app>}"+app="${app%/}"+plist="$app/Contents/Info.plist"+[ -f "$plist" ] || { echo "$app has no Contents/Info.plist" >&2; exit 1; }++# The Stable names a Local bundle must never carry. They are the invariant+# this check exists for, so they are written out here and not read from the+# code under test.+prod_id=com.trycua.spaces.macos+prod_scheme=cua+prod_helper=com.trycua.spaces.helper++# The Local names, from CuaChannel.+names="$("$here/scripts/channel-names.sh" local)"+name() { printf '%s\n' "$names" | sed -n "s/^$1=//p"; }+want_app_name="$(name app_name)"+want_id="$(name bundle_id)"+want_helper="$(name helper_label)"+want_scheme="$(name url_scheme)"+want_home="$(name home)"+want_env="$(name env)"+for v in want_app_name want_id want_helper want_scheme want_home want_env; do+ [ -n "${!v}" ] || { echo "scripts/channel-names.sh local printed no ${v#want_}" >&2; exit 1; }+done++fail=0+bad() { echo "local bundle check: $1" >&2; fail=1; }+pb=/usr/libexec/PlistBuddy+key() { $pb -c "Print :$1" "$plist" 2>/dev/null || true; }+expect() { # expect KEY VALUE+ [ "$(key "$1")" = "$2" ] || bad "$1 is '$(key "$1")', want '$2'"+}++# Identity.+id="$(key CFBundleIdentifier)"+[ "$id" != "$prod_id" ] || bad "bundle id is the production one ($prod_id)"+expect CFBundleIdentifier "$want_id"+expect CFBundleName "$want_app_name"+expect CFBundleDisplayName "$want_app_name"+[ "$(basename "$app")" = "$want_app_name.app" ] || bad "app folder is '$(basename "$app")', want '$want_app_name.app'"++# No updater: no feed, no key, no automatic checks.+for k in SUFeedURL SUPublicEDKey SUEnableAutomaticChecks SUAutomaticallyUpdate SUVerifyUpdateBeforeExtraction; do+ [ -z "$(key "$k")" ] || bad "$k is set: a Local build could update itself into production"+done++# URL schemes: cua-local only, never cua.+schemes=()+i=0+while $pb -c "Print :CFBundleURLTypes:$i" "$plist" >/dev/null 2>&1; do+ j=0+ while s="$($pb -c "Print :CFBundleURLTypes:$i:CFBundleURLSchemes:$j" "$plist" 2>/dev/null)"; do+ schemes+=("$s")+ j=$((j + 1))+ done+ urlname="$(key "CFBundleURLTypes:$i:CFBundleURLName")"+ [ "$urlname" != "$prod_id" ] || bad "URL type $i is named for the production bundle id"+ i=$((i + 1))+done+for s in ${schemes[@]+"${schemes[@]}"}; do+ [ "$s" != "$prod_scheme" ] || bad "the '$prod_scheme' URL scheme is registered: cua:// belongs to Stable"+ [ "$s" = "$want_scheme" ] || bad "unexpected URL scheme '$s' (only '$want_scheme')"+done+case " ${schemes[*]-} " in+ *" $want_scheme "*) ;;+ *) bad "the '$want_scheme' URL scheme is not registered" ;;+esac++# What the app and its helpers read to know they are Local.+expect CuaChannel local+expect CuaEnv "$want_env"+expect CuaHome "$want_home"+expect CuaHelperLabel "$want_helper"+expect CuaUrlScheme "$want_scheme"++# The helper login item: its own plist, label and owner.+agents="$app/Contents/Library/LaunchAgents"+[ ! -e "$agents/$prod_helper.plist" ] || bad "Stable's helper plist ($prod_helper.plist) is in the bundle"+helper="$agents/$want_helper.plist"+if [ -f "$helper" ]; then+ label="$($pb -c "Print :Label" "$helper" 2>/dev/null || true)"+ [ "$label" = "$want_helper" ] || bad "helper plist Label is '$label', want '$want_helper'"+ [ "$label" != "$prod_helper" ] || bad "helper plist Label is the production one"+ owner="$($pb -c "Print :AssociatedBundleIdentifiers:0" "$helper" 2>/dev/null || true)"+ [ "$owner" = "$want_id" ] || bad "helper AssociatedBundleIdentifiers is '$owner', want '$want_id'"+ if $pb -c "Print :AssociatedBundleIdentifiers:1" "$helper" >/dev/null 2>&1; then+ bad "helper has more than one AssociatedBundleIdentifiers entry"+ fi+else+ bad "no helper plist $want_helper.plist in Contents/Library/LaunchAgents"+fi+others="$(find "$agents" -maxdepth 1 -name '*.plist' ! -name "$want_helper.plist" 2>/dev/null || true)"+[ -z "$others" ] || bad "other launch agents in the bundle: $(printf '%s' "$others" | tr '\n' ' ')"++# The signature (build-app.sh signs ad hoc under the bundle id; install-local+# re-signs with the stable local certificate, under the same identifier).+signed="$(codesign -dv "$app" 2>&1 | sed -n 's/^Identifier=//p')"+[ "$signed" = "$want_id" ] || bad "signed as '$signed', want '$want_id'"++[ "$fail" = 0 ] || exit 1+echo "local bundle ok: $id"diff --git a/apps/cua-spaces-macos/scripts/install-local.sh b/apps/cua-spaces-macos/scripts/install-local.shnew file mode 100755index 0000000000..a709024e6a--- /dev/null+++ b/apps/cua-spaces-macos/scripts/install-local.sh@@ -0,0 +1,832 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Builds Cua Spaces from this checkout and installs it as "Cua Spaces Local",+# next to the released Cua Spaces: another bundle id, app, CLI, home, launchd+# labels, ports, URL scheme, Keychain items and no update feed. (CUA-1776. Same+# pattern as Cua Driver's libs/cua-driver/scripts/install-local.sh, which+# installs cua-driver-local.)+#+# scripts/install-local.sh [--release] [--no-launch] [--prefix DIR]+# [--with-lume-local] [--skip-rust-build]+# [--skip-web-build] [--setup-signing]+# [--require-stable-signing]+#+# --release build the release configuration (default: debug)+# --no-launch do not open the app when it is installed+# --prefix DIR install under DIR instead of $HOME: the app in+# DIR/Applications, `cua-local` in DIR/.local/bin+# (the state, ~/.cua-local, stays in $HOME). DIR is+# resolved (`..`, symlinks) and refused when the app or+# the link would be, or be inside, anything the released+# Cua Spaces owns (/Applications, ~/.cua,+# ~/.local/bin/cua, ~/.lume, ~/Cua Volume)+# --with-lume-local also install lume-local (libs/lume/scripts/install-local.sh)+# --skip-rust-build do not run cargo and stage the library: use the library,+# `cua` and cua-spacesd already built+# --skip-web-build do not build the web UI (apps/cua-spaces-web): use the+# build already there (dist/), or the one $CUA_WEBUI_DIST+# names. The script stops when there is none: without it+# the app says "The new UI is not in this build".+# --setup-signing when the stable local certificate exists but macOS does+# not let codesign use it yet (a fresh Keychain), do the+# one-time setup without asking first (see "Signing")+# --require-stable-signing+# stop unless the app can be signed with the stable+# local certificate (no ad hoc fallback)+#+# Needs (checked first; one message says what to install): the Xcode command+# line tools, cmake, Rust (rustup) and, for the web UI, Node 22 or later, pnpm,+# the wasm32 Rust target and wasm-bindgen-cli (the versions the release build+# uses).+#+# The bundled host service (cua-spacesd) is built from this checkout, not the+# pinned release: the pinned one does not know the Local ports.+#+# What it installs, and nothing else:+# ~/Applications/Cua Spaces Local.app+# ~/.local/bin/cua-local -> the app's bundled `cua`+#+# What it never touches: /Applications/Cua Spaces.app, ~/.local/bin/cua, ~/.cua,+# ~/.lume, their launchd jobs, and any bundle at the Local path whose id is not+# the Local one (it refuses). The build is staged, signed and verified first;+# the live copy is swapped only then, and put back if the copy fails to verify.+#+# Signing: the stable local certificate shared with Cua Driver's local install+# (libs/cua-driver/scripts/_local-signing.sh), so the Screen Recording and+# Accessibility grants of Cua Spaces Local survive a rebuild. Without it the+# bundle is signed ad hoc and the grants reset on every rebuild (reported).+# On a fresh Keychain the certificate is created, but codesign cannot use it+# until it is trusted for code signing, its Keychain is in the search list and+# codesign may use its key. When that is the case the script says so and, once+# you agree (or with --setup-signing), does it: macOS asks for your password+# once to trust the certificate, and the Keychain password is asked here once+# (not stored) if codesign still needs the key, which is opened for that one+# key only (never every signing key in the Keychain). Where it cannot ask (no+# terminal, no screen) it prints the exact commands instead. It never trusts+# anything without that, never changes which certificate is used, and a+# certificate-backed signature is still what it checks for.+#+# Uninstall: scripts/uninstall-local.sh.+set -euo pipefail++SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"+APP_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd)"+REPO_ROOT="$(cd -- "$APP_DIR/../.." && pwd)"++# shellcheck source=_local-common.sh+# shellcheck source-path=SCRIPTDIR+. "$SCRIPT_DIR/_local-common.sh"++die() { err "$*"; exit 1; }++# --- Arguments ----------------------------------------------------------------++CONFIG=debug+LAUNCH=1+PREFIX=""+WITH_LUME_LOCAL=0+SKIP_RUST_BUILD=0+SKIP_WEB_BUILD=0+SETUP_SIGNING=0+REQUIRE_STABLE_SIGNING=0++usage() { sed -n '/^# Builds Cua Spaces/,/^# Uninstall:/p' "$0" | sed 's/^# \{0,1\}//'; }++while [ "$#" -gt 0 ]; do+ case "$1" in+ --release) CONFIG=release ;;+ --no-launch) LAUNCH=0 ;;+ --prefix)+ [ "$#" -ge 2 ] || die "--prefix needs a directory"+ PREFIX="$2"+ shift+ ;;+ --prefix=*) PREFIX="${1#*=}" ;;+ --with-lume-local) WITH_LUME_LOCAL=1 ;;+ --skip-rust-build) SKIP_RUST_BUILD=1 ;;+ --skip-web-build) SKIP_WEB_BUILD=1 ;;+ --setup-signing) SETUP_SIGNING=1 ;;+ --require-stable-signing) REQUIRE_STABLE_SIGNING=1 ;;+ --help|-h) usage; exit 0 ;;+ *) err "unknown option: $1 (see --help)"; exit 2 ;;+ esac+ shift+done++if [ "$(id -u)" -eq 0 ] || [ -n "${SUDO_USER:-}" ]; then+ die "do not run this script with sudo or as root."+fi+[ "$(uname -s)" = Darwin ] || die "Cua Spaces Local is a macOS app: run this on a Mac."+[ -n "${HOME:-}" ] || die "HOME is not set."++# --- Where it goes -------------------------------------------------------------++if [ -z "$PREFIX" ]; then+ PREFIX="$HOME"+fi+case "$PREFIX" in+ /*) ;;+ *) die "--prefix must be an absolute path (got: $PREFIX)" ;;+esac+PREFIX="${PREFIX%/}"+# Every destination is resolved first (`.`, `..`, symlinks) and the resolved+# paths are the ones written, so nothing in --prefix can hide where they land.+# The links are resolved on the folders the files go into; `cua-local` itself+# may already be a link, which is replaced, never followed.+APP_PARENT="$(canonicalize_path "$PREFIX/Applications")" || die "cannot resolve $PREFIX/Applications (a symlink loop?)"+BIN_DIR="$(canonicalize_path "$PREFIX/.local/bin")" || die "cannot resolve $PREFIX/.local/bin (a symlink loop?)"+APP_DEST="$APP_PARENT/$LOCAL_APP_DIR_NAME"+CLI_LINK="$BIN_DIR/$LOCAL_CLI_NAME"++# The two paths this script writes outside the build tree have the Local names,+# and neither is, or is inside, anything the released Cua Spaces owns+# (/Applications, ~/.cua, ~/.local/bin/cua, ~/.lume, ~/Cua Volume).+[ "$(basename "$APP_DEST")" = "$LOCAL_APP_DIR_NAME" ] || die "internal error: app path $APP_DEST"+[ "$(basename "$CLI_LINK")" = "$LOCAL_CLI_NAME" ] || die "internal error: CLI path $CLI_LINK"+reject_stable_overlap "app" "$APP_DEST" || exit 1+reject_stable_overlap "$LOCAL_CLI_NAME link" "$CLI_LINK" || exit 1+if [ "$WITH_LUME_LOCAL" = 1 ] && [ "$(canonicalize_path "$PREFIX")" != "$(canonicalize_path "$HOME")" ]; then+ die "--with-lume-local installs under \$HOME and cannot be combined with --prefix."+fi++BUILD_SCRIPT="$SCRIPT_DIR/build-app.sh"+SIGNING_LIB="$REPO_ROOT/libs/cua-driver/scripts/_local-signing.sh"+LUME_INSTALL="$REPO_ROOT/libs/lume/scripts/install-local.sh"+BUILD_OUT="$APP_DIR/.build/local-app"+STAGE_ROOT="$APP_DIR/.build/local-stage"+STAGE_APP="$STAGE_ROOT/$LOCAL_APP_DIR_NAME"+# The host service the app bundles. build-app.sh bundles the pinned release+# (libs/cua-spacesd/VERSION) unless $CUA_SPACESD_BIN names another, and the+# pinned one does not know this checkout's Local ports. So this build bundles+# the cua-spacesd of this checkout.+SPACESD_DIR="$REPO_ROOT/libs/cua-spacesd"+# The web UI the app bundles (New UI): apps/cua-spaces-web, built as the+# release build does (cd-cua-spaces.yml "Build the web UI"). build-app.sh reads+# $CUA_WEBUI_DIST, else apps/cua-spaces-web/dist. A $CUA_WEBUI_DIST is a build+# somebody made: it is used as it is, not built.+WEBUI_APP="$REPO_ROOT/apps/cua-spaces-web"+if [ -n "${CUA_WEBUI_DIST:-}" ]; then+ WEBUI_DIST="$CUA_WEBUI_DIST"+ BUILD_WEB=0+else+ WEBUI_DIST="$WEBUI_APP/dist"+ BUILD_WEB=$((1 - SKIP_WEB_BUILD))+fi+WASM_TOOLCHAIN_FILE="$APP_DIR/../cua-spaces/rust-toolchain.toml"+WASM_SCRIPT="$WEBUI_APP/scripts/build-core-wasm.mjs"+case "${CARGO_TARGET_DIR:-/}" in+ /*) ;;+ *) die "CARGO_TARGET_DIR must be an absolute path (got: $CARGO_TARGET_DIR)." ;;+esac+SPACESD_BIN="${CARGO_TARGET_DIR:-$SPACESD_DIR/target}/release/cua-spacesd"++[ -x "$BUILD_SCRIPT" ] || die "missing $BUILD_SCRIPT"+[ -f "$SIGNING_LIB" ] || die "missing $SIGNING_LIB (the stable local signing shared with Cua Driver)"++# The signing helpers (ensure_local_signing_identity, codesign_bounded,+# designated_requirement, ...) are Cua Driver's, shared rather than copied.+# They read $OS and the colour variables.+# shellcheck disable=SC2034 # read by _local-signing.sh+OS="$(uname -s)"+# shellcheck source=../../../libs/cua-driver/scripts/_local-signing.sh+# shellcheck source-path=SCRIPTDIR+. "$SIGNING_LIB"++# --- Preflight: nothing is built or changed when the Local path holds something else --++require_local_bundle_or_absent "$APP_DEST" || exit 1+if [ -d "$CLI_LINK" ] && [ ! -L "$CLI_LINK" ]; then+ die "refusing to replace $CLI_LINK: it is a directory"+fi+if [ "$SKIP_RUST_BUILD" = 1 ] && [ ! -x "$SPACESD_BIN" ]; then+ die "--skip-rust-build: there is no cua-spacesd build at $SPACESD_BIN. Build it ((cd libs/cua-spacesd && cargo build --locked --release -p cua-spacesd --bin cua-spacesd)) or leave out --skip-rust-build."+fi+if [ "$WITH_LUME_LOCAL" = 1 ]; then+ [ -f "$LUME_INSTALL" ] || die "--with-lume-local: missing $LUME_INSTALL"+ # Without lume-local, that script installs over the Stable lume (the same+ # binary, LaunchAgent, port and VMs).+ if ! grep -q "$LOCAL_LUME_BIN_NAME" "$LUME_INSTALL"; then+ die "--with-lume-local: $LUME_INSTALL in this checkout still installs over the Stable lume (it does not know lume-local). Update to a checkout where lume-local has landed."+ fi+fi++# --- Preflight: the tools the build needs ---------------------------------------------+# Everything that is missing is listed once, with what to run, before anything+# is built or changed.++have() { command -v "$1" >/dev/null 2>&1; }++MISSING=()+missing() { MISSING+=("$1"); }++check_prerequisites() {+ local toolchain wasm_bindgen_version major++ # A shell that did not source ~/.cargo/env still has rustup and cargo here.+ if ! have cargo && [ -f "$HOME/.cargo/env" ]; then+ # shellcheck disable=SC1091+ . "$HOME/.cargo/env"+ fi+ case ":$PATH:" in+ *":$HOME/.cargo/bin:"*) ;;+ *) [ ! -d "$HOME/.cargo/bin" ] || PATH="$HOME/.cargo/bin:$PATH" ;;+ esac++ if ! xcode-select -p >/dev/null 2>&1 || ! have swift; then+ missing "the Xcode command line tools (swift, clang): xcode-select --install"+ fi+ if [ "$SKIP_RUST_BUILD" = 0 ]; then+ have cmake || missing "cmake (the audio codec build needs it): brew install cmake"+ fi+ if [ "$SKIP_RUST_BUILD" = 0 ] || [ "$BUILD_WEB" = 1 ]; then+ have cargo || missing "Rust (cargo and rustup): curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh (then open a new terminal)"+ fi++ [ "$BUILD_WEB" = 1 ] || return 0+ if ! have node; then+ missing "Node 22 or later (the web UI): brew install node"+ else+ major="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"+ [ "$major" -ge 22 ] 2>/dev/null || missing "Node 22 or later, this Mac has $(node --version 2>/dev/null || echo none) (the web UI): brew install node"+ fi+ have pnpm || missing "pnpm (the web UI): brew install pnpm (or: corepack enable)"+ # The web UI's app core is Rust built for the browser (WebAssembly), with+ # the toolchain and the wasm-bindgen the release build pins.+ toolchain="$(sed -n 's/^channel *= *"\(.*\)"/\1/p' "$WASM_TOOLCHAIN_FILE" 2>/dev/null | head -n 1)"+ wasm_bindgen_version="$(sed -n 's/^const WASM_BINDGEN = "\(.*\)"/\1/p' "$WASM_SCRIPT" 2>/dev/null | head -n 1)"+ if [ -n "$toolchain" ]; then+ { have rustup && rustup target list --installed --toolchain "$toolchain" 2>/dev/null | grep -qx wasm32-unknown-unknown; } \+ || missing "the wasm32 Rust target for Rust $toolchain (the web UI; after Rust is installed): rustup toolchain install $toolchain --profile minimal --target wasm32-unknown-unknown"+ fi+ if [ -n "$wasm_bindgen_version" ]; then+ { have wasm-bindgen && wasm-bindgen --version 2>/dev/null | grep -qF "$wasm_bindgen_version"; } \+ || missing "wasm-bindgen-cli $wasm_bindgen_version (the web UI): cargo install wasm-bindgen-cli --version $wasm_bindgen_version --locked"+ fi+}++check_prerequisites+if [ "${#MISSING[@]}" -gt 0 ]; then+ err "Cua Spaces Local cannot be built yet: ${#MISSING[@]} thing(s) to install first. Nothing was built or changed."+ for item in "${MISSING[@]}"; do printf ' - %s\n' "$item" >&2; done+ have brew || echo "Homebrew (https://brew.sh) installs the brew ones." >&2+ echo "Install them, then run this script again." >&2+ exit 1+fi++# The web UI the app bundles: built below, or one that is already there. The+# app without it says "The new UI is not in this build".+web_ui_missing() {+ err "there is no web UI build at $WEBUI_DIST/index.html, and without it Cua Spaces Local shows \"The new UI is not in this build\"."+ err "Build it: (cd apps/cua-spaces-web && pnpm install --ignore-workspace --frozen-lockfile && pnpm build), or leave out --skip-web-build. Nothing was installed."+}+if [ "$BUILD_WEB" = 1 ]; then+ [ -d "$WEBUI_APP" ] || die "missing $WEBUI_APP (the web UI)"+elif [ ! -f "$WEBUI_DIST/index.html" ]; then+ web_ui_missing+ exit 1+fi++printf '%sCua Spaces Local installer%s\n' "$BOLD$BLUE" "$NORMAL"+echo " source: $REPO_ROOT"+echo " config: $CONFIG"+echo " app: $APP_DEST"+echo " cli: $CLI_LINK"+echo ""++# --- Build -----------------------------------------------------------------------++# The web UI first (as the release build does: pnpm install --frozen-lockfile,+# pnpm build, which builds the app core's WebAssembly and then the pages): it+# is the quick one to fail. CI=true keeps pnpm from asking questions.+if [ "$BUILD_WEB" = 1 ]; then+ log "building the web UI (apps/cua-spaces-web: pnpm install, pnpm build)"+ if ! (cd "$WEBUI_APP" && CI=true pnpm install --ignore-workspace --frozen-lockfile && pnpm build); then+ die "the web UI build failed (see above). Nothing was installed."+ fi+fi+if [ ! -f "$WEBUI_DIST/index.html" ]; then+ web_ui_missing+ exit 1+fi++if [ "$SKIP_RUST_BUILD" = 0 ]; then+ if ! command -v cargo >/dev/null 2>&1 && [ -f "$HOME/.cargo/env" ]; then+ # shellcheck disable=SC1091+ . "$HOME/.cargo/env"+ fi+ command -v cargo >/dev/null 2>&1 || die "cargo is required (https://rustup.rs), or build the libraries yourself and pass --skip-rust-build."+ log "building the Cua Spaces library and CLI (cargo, release)"+ # The SDK dylib the app links, and the `cua` that goes into the bundle+ # (build-app.sh's defaults).+ (cd "$REPO_ROOT/libs/cua" && cargo build --locked --release -p cua-spaces-ffi -p cua-spaces-cli)+ "$REPO_ROOT/libs/spaces-app-swift/scripts/stage-library.sh"+ log "building cua-spacesd from this checkout (cargo, release)"+ (cd "$SPACESD_DIR" && cargo build --locked --release -p cua-spacesd --bin cua-spacesd)+fi+[ -x "$SPACESD_BIN" ] || die "cargo did not produce $SPACESD_BIN"++# What the bundled daemon must be: this one. Compared by its machine code (the+# __text section), which the signature build-app.sh adds does not change.+code_hash() {+ local hash+ hash="$(otool -X -s __TEXT __text "$1" 2>/dev/null | shasum -a 256 | cut -d' ' -f1)"+ # The hash of nothing: otool found no code.+ [ -n "$hash" ] && [ "$hash" != e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ] || return 1+ printf '%s' "$hash"+}+SPACESD_CODE_HASH="$(code_hash "$SPACESD_BIN")" || die "cannot read the machine code of $SPACESD_BIN (otool)"++log "building the app (build-app.sh --channel local $CONFIG)"+mkdir -p "$BUILD_OUT"+# build-app.sh prints the bundle path as its last line.+if ! BUILT_APP="$(CUA_SPACESD_BIN="$SPACESD_BIN" CUA_WEBUI_DIST="$WEBUI_DIST" "$BUILD_SCRIPT" --channel local "$CONFIG" "$BUILD_OUT" | tee /dev/stderr | tail -n 1)"; then+ die "build-app.sh failed"+fi+[ -d "$BUILT_APP" ] || BUILT_APP="$BUILD_OUT/$LOCAL_APP_DIR_NAME"+[ -d "$BUILT_APP" ] || die "build-app.sh did not produce an app bundle in $BUILD_OUT"+if [ "$(basename "$BUILT_APP")" != "$LOCAL_APP_DIR_NAME" ]; then+ die "build-app.sh --channel local produced '$(basename "$BUILT_APP")', not '$LOCAL_APP_DIR_NAME': it did not build the Local channel, so nothing was installed."+fi++# --- Stage, sign, verify ---------------------------------------------------------++cleanup() { rm -rf "$STAGE_ROOT"; }+trap cleanup EXIT++rm -rf "$STAGE_ROOT"+mkdir -p "$STAGE_ROOT"+# No extended attributes, resource forks or quarantine flag: codesign refuses+# "resource fork, Finder information, or similar detritus" in a bundle, and a+# copy of a downloaded or Finder-touched app has them.+ditto --noextattr --noqtn "$BUILT_APP" "$STAGE_APP"+xattr -cr "$STAGE_APP" 2>/dev/null || true++# Mach-O file or not: the first four bytes.+is_macho() {+ case "$(head -c 4 "$1" 2>/dev/null | od -An -tx1 | tr -d ' \n')" in+ cffaedfe|cefaedfe|feedfacf|feedface|cafebabe|bebafeca|cafebabf|bfbafeca) return 0 ;;+ *) return 1 ;;+ esac+}++sort_deepest_first() { awk -F/ '{ print NF "\t" $0 }' | sort -rn | cut -f2-; }++# The bundle's code that is not its main executable: loose Mach-O files in the+# places code lives (the bundled `cua`, `cua-spacesd`, the SDK dylib, Sparkle's+# helpers), deepest first. Resources are data and stay sealed, not signed.+nested_code_files() {+ local app="$1" main dir f+ main="$app/Contents/MacOS/$(plist_get "$app/Contents/Info.plist" CFBundleExecutable || true)"+ for dir in MacOS Frameworks PlugIns XPCServices Library Helpers; do+ [ -d "$app/Contents/$dir" ] || continue+ find "$app/Contents/$dir" -type f+ done | while IFS= read -r f; do+ [ "$f" != "$main" ] || continue+ if is_macho "$f"; then printf '%s\n' "$f"; fi+ done | sort_deepest_first+}++# Nested bundles (Sparkle.framework, its XPC services and Updater.app), deepest first.+nested_bundles() {+ find "$1/Contents" -type d \( -name '*.app' -o -name '*.xpc' -o -name '*.framework' \) | sort_deepest_first+}++# One codesign call, with its output kept for the failure message. Each piece+# keeps the identifier (and entitlements) build-app.sh gave it, such as+# com.trycua.cua-env-driver for cua-spacesd; only the identity changes. The+# call is bounded (a Keychain prompt nobody answers would wait forever), and a+# Mac that stalls for that long (a full disk, a busy trustd) gets a second try.+sign_piece() {+ local identity="$1" target="$2" preserve="$3" out="" status=0+ local args=(--force --sign "$identity")+ [ -z "$preserve" ] || args+=("--preserve-metadata=$preserve")+ for _ in 1 2; do+ out="$(codesign_bounded 20 "${args[@]}" "$target" 2>&1)" && return 0+ status=$?+ done+ err "codesign failed for $target"+ case "$status" in+ 124|137|142) err "it did not finish in 20 s, twice (a Keychain prompt waiting for you, or a Mac too busy or too full to sign)" ;;+ esac+ [ -z "$out" ] || printf '%s\n' "$out" >&2+ return 1+}++# Signs the staged app with `identity`, inside out: the nested code, the nested+# bundles, then the app (whose identifier is its bundle id). Not `--deep`: that+# would give everything inside the app's options and a derived identifier.+sign_bundle_with() {+ local identity="$1" app="$2" f+ while IFS= read -r f; do+ [ -z "$f" ] || sign_piece "$identity" "$f" identifier,entitlements || return 1+ done < <(nested_code_files "$app")+ while IFS= read -r f; do+ [ -z "$f" ] || sign_piece "$identity" "$f" identifier,entitlements || return 1+ done < <(nested_bundles "$app")+ sign_piece "$identity" "$app" "" || return 1+ codesign --verify --deep --strict "$app" 2>/dev/null+}++# Lets codesign use the private key of the stable local certificate without a+# prompt. `-l` limits it to the key labelled with the certificate's name+# ($CUA_LOCAL_SIGN_CN; the label the helper gives it when it imports the+# identity), and `-t private` to private keys: without them `-s` would change+# the access rules of every signing key in the Keychain, the login Keychain's+# other keys included. When no key has that label the tool fails and changes+# nothing. Prints nothing and takes the Keychain password as $2.+open_key_to_codesign() {+ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l "$CUA_LOCAL_SIGN_CN" -k "$2" "$1" >/dev/null 2>&1+}++# Whether `keychain` is in the user's Keychain search list.+keychain_listed() {+ security list-keychains -d user 2>/dev/null | tr -d ' "' | grep -qxF "$1"+}++# Whether the Keychain holds `identity` as a code-signing identity macOS+# trusts (the `-v` list leaves out one that is not trusted yet).+identity_trusted() {+ security find-identity -v -p codesigning "$2" 2>/dev/null | grep -qF "$1"+}++# The one-time setup, as the commands to type, for a Mac where the script+# could not (or was not allowed to) do it.+SIGNING_HELP_SHOWN=0+print_signing_bootstrap() {+ local kc pem="/tmp/cua-local-signing.pem"+ # Once per run, whichever step needed to say it first.+ [ "$SIGNING_HELP_SHOWN" = 0 ] || return 0+ SIGNING_HELP_SHOWN=1+ kc="$(local_signing_keychain)"+ echo "Cua Spaces Local is signed with the stable local certificate \"$CUA_LOCAL_SIGN_CN\"" >&2+ echo "(the one Cua Driver's local install uses), so its Screen Recording and" >&2+ echo "Accessibility permissions survive rebuilds. On a new Keychain that needs a" >&2+ echo "one-time setup, in Terminal on this Mac:" >&2+ echo " security find-certificate -c \"$CUA_LOCAL_SIGN_CN\" -p \"$kc\" > $pem" >&2+ echo " security add-trusted-cert -r trustRoot -p codeSign -k \"$kc\" $pem" >&2+ echo " (macOS asks for your password once. In an SSH session or a VM without a" >&2+ echo " screen, use: sudo security add-trusted-cert -d -r trustRoot -p codeSign -k \"$kc\" $pem)" >&2+ if ! keychain_listed "$kc"; then+ echo " security list-keychains -d user -s \"$kc\" \"$HOME/Library/Keychains/login.keychain-db\"" >&2+ fi+ echo " read -r -s -p 'Keychain password: ' KCPW; echo" >&2+ echo " security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l \"$CUA_LOCAL_SIGN_CN\" -k \"\$KCPW\" \"$kc\" >/dev/null; unset KCPW" >&2+ echo " (-l limits it to that certificate's key; do not drop it: without it every signing key in the Keychain is changed)" >&2+ echo "then run this script again, or run it with --setup-signing and it does this for you." >&2+}++# Whether codesign can sign with `identity` now, with no prompt: a throwaway+# copy of a Mach-O file of the bundle, signed. (That the signature is+# certificate-backed is checked by sign_staged_app, as before.)+signing_probe() {+ local identity="$1" macho="$2" dir probe status=0+ dir="$(mktemp -d "${TMPDIR:-/tmp}/cua-local-sign-probe.XXXXXX")" || return 1+ probe="$dir/probe"+ if cp "$macho" "$probe"; then+ codesign_bounded 20 --force --sign "$identity" "$probe" >/dev/null 2>&1 || status=$?+ else+ status=1+ fi+ rm -rf "$dir"+ [ "$status" = 0 ]+}++# The certificate `identity` (its SHA-1) as a PEM file at `out`.+export_signing_certificate() {+ security find-certificate -a -Z -p -c "$CUA_LOCAL_SIGN_CN" "$2" 2>/dev/null | awk -v want="$1" '+ /^SHA-1 hash:/ { found = (toupper($3) == toupper(want)); next }+ /^-----BEGIN CERTIFICATE-----/ { if (found) pem = 1 }+ pem { print }+ /^-----END CERTIFICATE-----/ { pem = 0; found = 0 }+ ' > "$3"+ grep -q 'BEGIN CERTIFICATE' "$3"+}++# A new Keychain: the certificate is there (the shared helper creates it) but+# codesign cannot use it until macOS trusts it for code signing, its Keychain+# is in the search list and codesign may use its key. This checks that with a+# real signing, and when it does not work says so and, with consent+# (--setup-signing, or "y" at a terminal), does the setup. It never picks+# another certificate, never touches one chosen with+# CUA_DRIVER_LOCAL_SIGNING_IDENTITY, and never trusts anything unasked.+# Fails (and has printed why and what to type) when the identity is still not+# usable; sign_staged_app then decides as it always did (required: stop;+# otherwise ad hoc, reported).+make_signing_identity_usable() {+ local identity="$1" app_stage="$2" macho kc answer pem pw line+ local current=()+ macho="$app_stage/Contents/MacOS/$(plist_get "$app_stage/Contents/Info.plist" CFBundleExecutable || true)"+ [ -f "$macho" ] || macho="$app_stage/Contents/MacOS/cua"+ [ -f "$macho" ] || return 0+ signing_probe "$identity" "$macho" && return 0++ if [ -n "${CUA_DRIVER_LOCAL_SIGNING_IDENTITY:-}" ]; then+ warn "codesign cannot use the identity you chose ($CUA_DRIVER_LOCAL_SIGNING_IDENTITY) yet: trust it for code signing and let codesign use its key. The script does not change a certificate you picked."+ return 1+ fi+ kc="$(local_signing_keychain)"+ warn "codesign cannot use the stable local certificate yet (a new Keychain: it is not trusted for code signing, or codesign may not use its key)."++ answer=n+ if [ "$SETUP_SIGNING" = 1 ]; then+ answer=y+ elif [ -t 0 ] && [ -t 1 ]; then+ printf 'Set it up now? macOS asks for your password once to trust the certificate. [Y/n] '+ read -r answer || answer=n+ case "$answer" in ""|y|Y|yes|YES|Yes) answer=y ;; *) answer=n ;; esac+ fi+ if [ "$answer" != y ]; then+ print_signing_bootstrap+ return 1+ fi++ # 1. The Keychain in the search list (the trust check looks there).+ if ! keychain_listed "$kc"; then+ while IFS= read -r line; do+ line="${line#"${line%%[![:space:]]*}"}"+ line="${line#\"}"+ line="${line%\"}"+ [ -z "$line" ] || current+=("$line")+ done < <(security list-keychains -d user 2>/dev/null)+ security list-keychains -d user -s "$kc" ${current[@]+"${current[@]}"} \+ || { err "could not add $kc to the Keychain search list"; print_signing_bootstrap; return 1; }+ ok "added $kc to the Keychain search list"+ fi+ # 2. Trusted for code signing: one macOS prompt (user trust settings).+ if ! identity_trusted "$identity" "$kc"; then+ pem="$(mktemp "${TMPDIR:-/tmp}/cua-local-signing.XXXXXX")" || return 1+ if ! export_signing_certificate "$identity" "$kc" "$pem"; then+ rm -f "$pem"+ err "could not read the certificate $identity from $kc"+ print_signing_bootstrap+ return 1+ fi+ log "trusting the certificate for code signing (macOS asks for your password)"+ if ! security add-trusted-cert -r trustRoot -p codeSign -k "$kc" "$pem"; then+ rm -f "$pem"+ err "macOS did not trust the certificate (it asks in a window on this Mac's screen)."+ print_signing_bootstrap+ return 1+ fi+ rm -f "$pem"+ ok "the certificate is trusted for code signing"+ fi+ if signing_probe "$identity" "$macho"; then+ ok "codesign can use the stable local certificate"+ return 0+ fi+ # 3. codesign may use the key without a prompt. Needs the Keychain's+ # password: asked here, used once, not stored.+ if [ -t 0 ]; then+ printf 'Password of the Keychain %s (used once, not stored): ' "$kc"+ read -r -s pw || pw=""+ echo+ if [ -n "$pw" ] && open_key_to_codesign "$kc" "$pw"; then+ pw=""+ if signing_probe "$identity" "$macho"; then+ ok "codesign can use the stable local certificate"+ return 0+ fi+ fi+ pw=""+ err "codesign still cannot use the certificate."+ else+ err "codesign may not use the certificate's key yet, and the Keychain password is asked at a terminal."+ fi+ print_signing_bootstrap+ return 1+}++# Signs the staged app without touching the live one. The stable local+# certificate first; failing that, an ad hoc signature (the permissions then+# reset on the next rebuild), unless one is required or the live app already+# has the certificate (never swap a working signature for an ad hoc one).+sign_staged_app() {+ local app_stage="$1" app_dest="$2" sign_id requirement+ sign_id="$(ensure_local_signing_identity)"+ if [ "$sign_id" != "-" ]; then+ make_signing_identity_usable "$sign_id" "$app_stage" || true+ fi++ if [ "$sign_id" != "-" ]; then+ if sign_bundle_with "$sign_id" "$app_stage"; then+ requirement="$(designated_requirement "$app_stage")"+ if [ "$(classify_designated_requirement "$requirement")" = "certificate-backed" ]; then+ ok "signed the staged app with the stable local certificate: its permissions survive rebuilds"+ return 0+ fi+ warn "the stable identity produced a signature that is not certificate-backed"+ else+ warn "signing with the stable local identity failed"+ fi+ fi++ if [ "$REQUIRE_STABLE_SIGNING" = 1 ]; then+ clean_partial_bundle_signature "$app_stage"+ err "stable signing is required, but no usable certificate-backed identity was available. The installed app was not changed."+ print_signing_bootstrap+ return 1+ fi++ if [ -d "$app_dest" ]; then+ requirement="$(designated_requirement "$app_dest")"+ if [ "$(classify_designated_requirement "$requirement")" = "certificate-backed" ]; then+ clean_partial_bundle_signature "$app_stage"+ err "stable signing failed; keeping the installed certificate-signed $app_dest and its permissions."+ print_signing_bootstrap+ return 1+ fi+ fi++ clean_partial_bundle_signature "$app_stage"+ if ! sign_bundle_with - "$app_stage"; then+ clean_partial_bundle_signature "$app_stage"+ err "could not sign the staged app; the installed app was not changed."+ return 1+ fi+ requirement="$(designated_requirement "$app_stage")"+ if [ "$(classify_designated_requirement "$requirement")" != "ad-hoc" ]; then+ err "could not verify the staged app's ad hoc requirement; the installed app was not changed."+ return 1+ fi+ warn "$LOCAL_APP_DIR_NAME is signed ad hoc: its Screen Recording and Accessibility grants reset on the next rebuild."+ print_signing_bootstrap+}++# Only when an ad hoc cdhash changed, and only for the Local bundle id (the+# stale TCC rows would otherwise keep the old hash and the app never prompts).+reset_spaces_local_tcc() {+ local previous="$1" installed="$2" service failed=""+ ad_hoc_requirement_changed "$previous" "$installed" || return 0+ if ! command -v tccutil >/dev/null 2>&1; then+ warn "tccutil is missing: reset the Screen Recording and Accessibility rows of $LOCAL_BUNDLE_ID in System Settings."+ return 0+ fi+ for service in Accessibility ScreenCapture; do+ tccutil reset "$service" "$LOCAL_BUNDLE_ID" >/dev/null 2>&1 || failed="$failed $service"+ done+ if [ -n "$failed" ]; then+ warn "could not reset these permissions for $LOCAL_BUNDLE_ID:$failed (tccutil reset <service> $LOCAL_BUNDLE_ID)."+ else+ warn "the ad hoc signature changed: cleared the old Accessibility and Screen Recording rows of $LOCAL_BUNDLE_ID. Grant them again when asked."+ fi+}++# What the Local bundle must be, whether it is staged or installed: signed, the+# Local identity and scheme, and none of the Stable ones (bundle id, scheme,+# helper label), no update feed. Prints every problem; fails on any.+verify_local_bundle() {+ local app="$1" plist="$1/Contents/Info.plist" failures=0 id channel label schemes scheme+ local has_local_scheme=0 helper_plist associated++ bad() { err "$app: $*"; failures=$((failures + 1)); }++ if ! codesign --verify --deep --strict "$app" 2>/dev/null; then+ bad "the code signature does not verify"+ fi+ [ -f "$plist" ] || { bad "no Contents/Info.plist"; return 1; }++ id="$(plist_get "$plist" CFBundleIdentifier || true)"+ [ "$id" = "$LOCAL_BUNDLE_ID" ] || bad "bundle id is '${id:-none}', expected $LOCAL_BUNDLE_ID"++ if plist_get "$plist" SUFeedURL >/dev/null; then bad "it has an update feed (SUFeedURL)"; fi+ if plist_get "$plist" SUPublicEDKey >/dev/null; then bad "it has an update key (SUPublicEDKey)"; fi++ schemes="$(plist_url_schemes "$plist")"+ while IFS= read -r scheme; do+ [ -n "$scheme" ] || continue+ [ "$scheme" != "$LOCAL_URL_SCHEME" ] || has_local_scheme=1+ [ "$scheme" != "$STABLE_URL_SCHEME" ] || bad "it registers the Stable URL scheme $STABLE_URL_SCHEME://"+ done <<EOF+$schemes+EOF+ [ "$has_local_scheme" = 1 ] || bad "it does not register the URL scheme $LOCAL_URL_SCHEME://"++ # The host service is this checkout's build, not the pinned release (which+ # would ignore the Local ports and take the released app's).+ if [ ! -x "$app/Contents/MacOS/cua-spacesd" ]; then+ bad "it has no Contents/MacOS/cua-spacesd"+ elif [ "$(code_hash "$app/Contents/MacOS/cua-spacesd" || true)" != "$SPACESD_CODE_HASH" ]; then+ bad "the bundled cua-spacesd is not the build of this checkout ($SPACESD_BIN), probably the pinned release, which ignores the Local ports. build-app.sh must bundle \$CUA_SPACESD_BIN."+ fi++ # The New UI the app shows: build-app.sh copies the web build in, and the+ # app says "The new UI is not in this build" without it.+ [ -f "$app/Contents/Resources/WebUI/index.html" ] \+ || bad "it has no web UI (Contents/Resources/WebUI/index.html): the app would say \"The new UI is not in this build\""++ channel="$(plist_get "$plist" CuaChannel || true)"+ [ "$channel" = local ] || bad "CuaChannel is '${channel:-none}', expected local"+ if label="$(plist_get "$plist" CuaHelperLabel)" && [ "$label" != "$LOCAL_HELPER_LABEL" ]; then+ bad "CuaHelperLabel is '$label', expected $LOCAL_HELPER_LABEL"+ fi++ # The login item helper: its launchd label and the app it belongs to.+ for helper_plist in "$app"/Contents/Library/LaunchAgents/*.plist; do+ [ -f "$helper_plist" ] || continue+ label="$(plist_get "$helper_plist" Label || true)"+ [ "$label" != "$STABLE_HELPER_LABEL" ] || bad "$(basename "$helper_plist") has the Stable helper label $STABLE_HELPER_LABEL"+ associated="$(plist_get "$helper_plist" AssociatedBundleIdentifiers || true)"+ case "$associated" in+ *"$STABLE_BUNDLE_ID"*) bad "$(basename "$helper_plist") is associated with the Stable app $STABLE_BUNDLE_ID" ;;+ esac+ done++ [ "$failures" = 0 ]+}++log "signing"+PREVIOUS_REQUIREMENT=""+if [ -d "$APP_DEST" ]; then+ PREVIOUS_REQUIREMENT="$(designated_requirement "$APP_DEST" || true)"+fi+sign_staged_app "$STAGE_APP" "$APP_DEST" || exit 1+STAGED_REQUIREMENT="$(designated_requirement "$STAGE_APP")"+STAGED_CLASS="$(classify_designated_requirement "$STAGED_REQUIREMENT")"++log "verifying the staged app"+if ! verify_local_bundle "$STAGE_APP"; then+ die "the staged app is not a valid Cua Spaces Local bundle; the installed app was not changed."+fi++# --- Swap ------------------------------------------------------------------------++log "installing $APP_DEST"+# The path may have been taken since the preflight.+require_local_bundle_or_absent "$APP_DEST" || exit 1+quit_local_app "$APP_DEST"+mkdir -p "$APP_PARENT"+APP_BACKUP="$APP_DEST.install-backup.$$"+rm -rf "$APP_BACKUP"+if [ -d "$APP_DEST" ]; then+ mv "$APP_DEST" "$APP_BACKUP"+fi+install_valid=false+INSTALLED_REQUIREMENT=""+INSTALLED_CLASS=""+if ditto "$STAGE_APP" "$APP_DEST" && verify_local_bundle "$APP_DEST"; then+ INSTALLED_REQUIREMENT="$(designated_requirement "$APP_DEST")"+ INSTALLED_CLASS="$(classify_designated_requirement "$INSTALLED_REQUIREMENT")"+ if [ "$INSTALLED_REQUIREMENT" = "$STAGED_REQUIREMENT" ] \+ && [ "$INSTALLED_CLASS" = "$STAGED_CLASS" ] \+ && [ "$INSTALLED_CLASS" != unknown ]; then+ install_valid=true+ fi+fi+if [ "$install_valid" = true ]; then+ rm -rf "$APP_BACKUP"+else+ rm -rf "$APP_DEST"+ if [ -d "$APP_BACKUP" ]; then+ mv "$APP_BACKUP" "$APP_DEST"+ die "the installed copy did not verify; restored the previous $LOCAL_APP_DIR_NAME."+ fi+ die "the installed copy did not verify and was removed."+fi+ok "installed $APP_DEST"+if [ "$INSTALLED_CLASS" = certificate-backed ]; then+ ok "signature: certificate-backed, the same on every rebuild"+fi++# Register the new bundle with LaunchServices now (it does it late otherwise):+# opening it and the cua-local:// scheme resolve to this copy.+if [ -x "$LSREGISTER" ]; then+ "$LSREGISTER" -f "$APP_DEST" >/dev/null 2>&1 || true+fi+reset_spaces_local_tcc "$PREVIOUS_REQUIREMENT" "$INSTALLED_REQUIREMENT"++# --- The CLI -----------------------------------------------------------------------++BUNDLED_CLI="$APP_DEST/Contents/MacOS/cua"+if [ -x "$BUNDLED_CLI" ]; then+ mkdir -p "$BIN_DIR"+ # -n: replace the link itself, never write through it.+ ln -sfn "$BUNDLED_CLI" "$CLI_LINK"+ ok "$CLI_LINK -> $BUNDLED_CLI"+else+ warn "the bundle has no cua CLI (cargo build --release -p cua-spaces-cli, then run this again): $LOCAL_CLI_NAME was not linked."+fi++# --- lume-local ----------------------------------------------------------------------++if [ "$WITH_LUME_LOCAL" = 1 ]; then+ log "installing lume-local"+ lume_args=()+ [ "$CONFIG" != release ] || lume_args+=(--release)+ /bin/bash "$LUME_INSTALL" ${lume_args[@]+"${lume_args[@]}"}+fi++# --- Done ------------------------------------------------------------------------------++echo ""+ok "Cua Spaces Local is installed. The released Cua Spaces, ~/.cua and ~/.local/bin/cua were not touched."+case ":$PATH:" in+ *":$BIN_DIR:"*) ;;+ *) echo " $BIN_DIR is not on your PATH: add it to use $LOCAL_CLI_NAME (no shell profile was edited)." ;;+esac+if [ "$LAUNCH" = 1 ]; then+ log "opening $APP_DEST"+ open "$APP_DEST" || warn "could not open the app"+fidiff --git a/apps/cua-spaces-macos/scripts/tests/install-local-test.sh b/apps/cua-spaces-macos/scripts/tests/install-local-test.shnew file mode 100755index 0000000000..e1a8f5932f--- /dev/null+++ b/apps/cua-spaces-macos/scripts/tests/install-local-test.sh@@ -0,0 +1,1140 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Tests scripts/install-local.sh and scripts/uninstall-local.sh (CUA-1776)+# against a fake HOME and a fake build. Nothing here builds Cua Spaces, touches+# the real HOME, the real Keychain, launchd, LaunchServices or TCC (the tools+# that would are replaced by logging shims). Signing is ad hoc unless you opt in+# to the certificate checks (see "signing" below). It checks, in one place, that:+#+# - a Stable install (~/.cua, ~/.lume, ~/.local/bin/cua, the Stable app and+# its support folder, launchd jobs, Cua Volume) is byte-identical before+# and after install-local.sh, a rebuild and uninstall-local.sh;+# - install-local.sh adds only the Local app and `cua-local`;+# - a bundle at the Local path with another id is refused, and so is a build+# that carries a Stable identity, a feed or the `cua` scheme;+# - a copy that fails to verify is rolled back to the previous app;+# - the web UI is built as the release build does (and the script stops, with+# a clear message, when it is missing), and the tools the build needs are+# checked first, in one message;+# - on a fresh Keychain (a certificate codesign cannot use yet) it says so and+# sets it up only when asked (--setup-signing), or prints the exact steps;+# - uninstall-local.sh removes the Local pieces and only those;+# - the names in scripts/_local-common.sh are the ones CuaChannel::Local has.+#+# scripts/tests/install-local-test.sh+#+# Each check prints PASS or FAIL; the exit status is the number of FAILs.+# The checks are strings for eval, and the shims are written from strings: the+# variables they read are assigned here, and shellcheck cannot see that.+# shellcheck disable=SC2034,SC2016,SC2030,SC2031,SC2119,SC2120,SC2329+set -uo pipefail++[ "$(uname -s)" = Darwin ] || { echo "SKIP: macOS only"; exit 0; }+command -v cc >/dev/null 2>&1 || { echo "SKIP: needs a C compiler (Xcode command line tools)"; exit 0; }++TESTS_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"+SCRIPTS_DIR="$(cd -- "$TESTS_DIR/.." && pwd)"+REPO_ROOT="$(cd -- "$SCRIPTS_DIR/../../.." && pwd)"+CHANNEL_RS="$REPO_ROOT/libs/cua/crates/cua-home/src/channel.rs"+SIGNING_LIB="$REPO_ROOT/libs/cua-driver/scripts/_local-signing.sh"++fails=0+pass() { printf 'PASS %s\n' "$*"; }+fail() { printf 'FAIL %s\n' "$*"; fails=$((fails + 1)); }+check() { if eval "$2"; then pass "$1"; else fail "$1"; fi; }+note() { printf ' %s\n' "$*"; }++WORK="$(mktemp -d "${TMPDIR:-/tmp}/cua-install-local-test.XXXXXX")"+WORK="$(cd "$WORK" && pwd -P)"+trap 'rm -rf "$WORK"' EXIT++# --- The fixture: a repo tree with the real scripts and a fake build -------------++FAKE_REPO="$WORK/repo"+FAKE_SCRIPTS="$FAKE_REPO/apps/cua-spaces-macos/scripts"+FAKE_HOME="$WORK/home"+SHIMS="$WORK/shims"+SHIM_STATE="$WORK/shim-state"+SHIM_LOG="$WORK/shim.log"+STUB_LOG="$WORK/stub.log"+BUILD_LOG="$WORK/build.log"+LUME_LOG="$WORK/lume.log"+STUB_BIN="$WORK/stub"+STUB_DYLIB="$WORK/libfake.dylib"+CARGO_LOG="$WORK/cargo.log"+# The cua-spacesd this checkout builds, and the pinned release build-app.sh+# bundles unless it is told otherwise: two programs with different code.+DAEMON_CHECKOUT="$WORK/daemon-checkout"+DAEMON_PINNED="$WORK/daemon-pinned"+FAKE_DAEMON_BUILT="$FAKE_REPO/libs/cua-spacesd/target/release/cua-spacesd"++mkdir -p "$FAKE_SCRIPTS" "$FAKE_REPO/libs/cua-driver/scripts" "$FAKE_REPO/libs/lume/scripts" \+ "$FAKE_REPO/libs/cua" "$FAKE_REPO/libs/cua-spacesd" "$FAKE_REPO/libs/spaces-app-swift/scripts" \+ "$FAKE_REPO/apps/cua-spaces-web/scripts" "$FAKE_REPO/apps/cua-spaces" \+ "$SHIMS" "$SHIM_STATE" "$FAKE_HOME"+cp "$SCRIPTS_DIR/install-local.sh" "$SCRIPTS_DIR/uninstall-local.sh" "$SCRIPTS_DIR/_local-common.sh" "$FAKE_SCRIPTS/"+cp "$SIGNING_LIB" "$FAKE_REPO/libs/cua-driver/scripts/"+# The pins the script reads (the wasm-bindgen version and the Rust toolchain of+# the web UI's app core), from the real files so they cannot drift from it.+cp "$REPO_ROOT/apps/cua-spaces-web/scripts/build-core-wasm.mjs" "$FAKE_REPO/apps/cua-spaces-web/scripts/"+cp "$REPO_ROOT/apps/cua-spaces/rust-toolchain.toml" "$FAKE_REPO/apps/cua-spaces/"+WEB_LOG="$WORK/web.log"++# A real Mach-O (codesign needs one) that logs how it was called.+cat > "$WORK/stub.c" <<'EOF'+#include <stdio.h>+#include <stdlib.h>+int main(int argc, char **argv) {+ const char *log = getenv("STUB_LOG");+ FILE *f = log ? fopen(log, "a") : NULL;+ if (f) {+ const char *channel = getenv("CUA_CHANNEL");+ fprintf(f, "%s", argv[0]);+ for (int i = 1; i < argc; i++) fprintf(f, " %s", argv[i]);+ fprintf(f, " [CUA_CHANNEL=%s]\n", channel ? channel : "");+ fclose(f);+ }+ return 0;+}+EOF+printf 'int fake_symbol(void) { return 1; }\n' > "$WORK/dylib.c"+# The daemon stubs differ in code, not only in data: the constant is an operand.+printf '#include <stdio.h>\nint main(void) { printf("%%d\\n", DAEMON_VARIANT * 7919); return 0; }\n' > "$WORK/daemon.c"+cc -DDAEMON_VARIANT=1 -o "$DAEMON_CHECKOUT" "$WORK/daemon.c" || { echo "could not compile the checkout daemon stub"; exit 1; }+cc -DDAEMON_VARIANT=2 -o "$DAEMON_PINNED" "$WORK/daemon.c" || { echo "could not compile the pinned daemon stub"; exit 1; }+cc -o "$STUB_BIN" "$WORK/stub.c" || { echo "could not compile the stub"; exit 1; }+cc -dynamiclib -o "$STUB_DYLIB" "$WORK/dylib.c" || { echo "could not compile the stub library"; exit 1; }++# A build-app.sh that writes a Cua Spaces Local bundle shaped like the real one:+# the app, the bundled cua and cua-spacesd, a loose dylib, a versioned framework+# (like Sparkle), the login item helper plist. FAKE_BUILD_* change what it makes.+cat > "$FAKE_SCRIPTS/build-app.sh" <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+echo "$*" >> "$FAKE_BUILD_LOG"+[ "$1" = --channel ] && [ "$2" = local ] || { echo "fake build-app.sh: expected --channel local" >&2; exit 2; }+out="$4"+id="${FAKE_BUILD_ID:-com.trycua.spaces.local}"+name="${FAKE_BUILD_APP_NAME:-Cua Spaces Local}"+scheme="${FAKE_BUILD_SCHEME:-cua-local}"+helper="${FAKE_BUILD_HELPER_LABEL:-com.trycua.spaces.local.helper}"+associated="${FAKE_BUILD_ASSOCIATED:-$id}"+app="$out/$name.app"+rm -rf "$app"+mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" "$app/Contents/Frameworks" "$app/Contents/Library/LaunchAgents"+for b in CuaSpacesMac cua; do cp "$FAKE_STUB" "$app/Contents/MacOS/$b"; done+# The host service, as the real build-app.sh gets it: from fetch-spacesd.sh,+# which prints $CUA_SPACESD_BIN when set and the pinned release otherwise.+# FAKE_BUILD_IGNORE_SPACESD_BIN stands for a build-app.sh that does not honour it.+if [ "${FAKE_BUILD_IGNORE_SPACESD_BIN:-0}" = 1 ]; then unset CUA_SPACESD_BIN; fi+spacesd="$("$(dirname "$0")/fetch-spacesd.sh")"+cp "$spacesd" "$app/Contents/MacOS/cua-spacesd"+chmod 0755 "$app/Contents/MacOS/cua-spacesd"+cp "$FAKE_DYLIB" "$app/Contents/Frameworks/libfake.dylib"+fw="$app/Contents/Frameworks/Fake.framework"+mkdir -p "$fw/Versions/A/Resources"+cp "$FAKE_DYLIB" "$fw/Versions/A/Fake"+install_name_tool -id @rpath/Fake.framework/Versions/A/Fake "$fw/Versions/A/Fake"+cat > "$fw/Versions/A/Resources/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict>+<key>CFBundleExecutable</key><string>Fake</string>+<key>CFBundleIdentifier</key><string>com.example.fake</string>+<key>CFBundlePackageType</key><string>FMWK</string>+<key>CFBundleVersion</key><string>1</string>+</dict></plist>+PLIST+ln -s A "$fw/Versions/Current"+ln -s Versions/Current/Fake "$fw/Fake"+ln -s Versions/Current/Resources "$fw/Resources"+echo "${FAKE_BUILD_SALT:-1}" > "$app/Contents/Resources/salt.txt"+# The web UI, as the real build-app.sh copies it ($CUA_WEBUI_DIST, else+# apps/cua-spaces-web/dist next to the app's folder).+webui="${CUA_WEBUI_DIST:-$(dirname "$0")/../../cua-spaces-web/dist}"+echo "webui=$webui" >> "$FAKE_BUILD_LOG"+if [ "${FAKE_BUILD_NO_WEBUI:-0}" != 1 ] && [ -f "$webui/index.html" ]; then cp -R "$webui" "$app/Contents/Resources/WebUI"; fi+feed=""+if [ "${FAKE_BUILD_FEED:-0}" = 1 ]; then+ feed="<key>SUFeedURL</key><string>https://example.invalid/appcast.xml</string><key>SUPublicEDKey</key><string>key</string>"+fi+cat > "$app/Contents/Info.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict>+<key>CFBundleExecutable</key><string>CuaSpacesMac</string>+<key>CFBundleIdentifier</key><string>$id</string>+<key>CFBundleName</key><string>$name</string>+<key>CFBundlePackageType</key><string>APPL</string>+<key>CFBundleShortVersionString</key><string>0.0.0</string>+<key>CFBundleVersion</key><string>1</string>+<key>CFBundleURLTypes</key><array><dict>+ <key>CFBundleURLName</key><string>$id</string>+ <key>CFBundleURLSchemes</key><array><string>$scheme</string></array>+</dict></array>+<key>CuaChannel</key><string>${FAKE_BUILD_CHANNEL:-local}</string>+<key>CuaHelperLabel</key><string>$helper</string>+$feed+</dict></plist>+PLIST+cat > "$app/Contents/Library/LaunchAgents/$helper.plist" <<PLIST+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict>+<key>Label</key><string>$helper</string>+<key>BundleProgram</key><string>Contents/MacOS/CuaSpacesMac</string>+<key>AssociatedBundleIdentifiers</key><array><string>$associated</string></array>+</dict></plist>+PLIST+/usr/bin/codesign -s - -f -i "$id" "$app/Contents/MacOS/cua-spacesd" >/dev/null 2>&1+/usr/bin/codesign -s - -f -i "$id" "$app" >/dev/null 2>&1+echo "$app"+EOF+chmod +x "$FAKE_SCRIPTS/build-app.sh"++# fetch-spacesd.sh's contract: $CUA_SPACESD_BIN when set, else the pinned release.+cat > "$FAKE_SCRIPTS/fetch-spacesd.sh" <<'FETCH_EOF'+#!/usr/bin/env bash+if [ -n "${CUA_SPACESD_BIN:-}" ]; then echo "$CUA_SPACESD_BIN"; else echo "$FAKE_PINNED_DAEMON"; fi+FETCH_EOF+chmod +x "$FAKE_SCRIPTS/fetch-spacesd.sh"+cat > "$FAKE_REPO/libs/spaces-app-swift/scripts/stage-library.sh" <<'STAGE_EOF'+#!/usr/bin/env bash+echo "stage-library" >> "$CARGO_LOG"+STAGE_EOF+chmod +x "$FAKE_REPO/libs/spaces-app-swift/scripts/stage-library.sh"++# lume scripts: one that knows lume-local, one that does not (the old one that+# installs over the Stable lume).+write_lume_scripts() {+ local knows="$1"+ if [ "$knows" = yes ]; then+ cat > "$FAKE_REPO/libs/lume/scripts/install-local.sh" <<'EOF'+#!/bin/bash+# installs lume-local+echo "install-local $*" >> "$LUME_LOG"+mkdir -p "$HOME/.local/bin" && : > "$HOME/.local/bin/lume-local"+EOF+ cat > "$FAKE_REPO/libs/lume/scripts/uninstall-local.sh" <<'EOF'+#!/bin/bash+# removes lume-local; accepts --yes+echo "uninstall-local $*" >> "$LUME_LOG"+rm -f "$HOME/.local/bin/lume-local"+EOF+ else+ cat > "$FAKE_REPO/libs/lume/scripts/install-local.sh" <<'EOF'+#!/bin/bash+echo "OLD install-local $*" >> "$LUME_LOG"+: > "$HOME/.local/bin/lume"+EOF+ rm -f "$FAKE_REPO/libs/lume/scripts/uninstall-local.sh"+ fi+}++# Shims for everything that would reach outside the fake HOME. Each logs its+# arguments to shim.log.+write_shim() { printf '#!/bin/bash\n%s\n' "$2" > "$SHIMS/$1"; chmod +x "$SHIMS/$1"; }+write_shim launchctl 'echo "launchctl $*" >> "$SHIM_LOG"'+write_shim tccutil 'echo "tccutil $*" >> "$SHIM_LOG"'+write_shim open 'echo "open $*" >> "$SHIM_LOG"'+write_shim lsregister 'echo "lsregister $*" >> "$SHIM_LOG"'+# security: a Keychain with one item per service until it is deleted; or the+# real tool, for the signing test's throwaway keychain.+write_shim security 'if [ "${SHIM_SECURITY_PASSTHROUGH:-0}" = 1 ]; then exec /usr/bin/security "$@"; fi+echo "security $*" >> "$SHIM_LOG"+if [ "$1" = delete-generic-password ] && [ "$2" = -s ]; then+ marker="$SHIM_STATE/deleted-$3"+ if [ -e "$marker" ]; then exit 44; fi+ : > "$marker"; exit 0+fi+# A fresh Keychain (SHIM_FRESH_KEYCHAIN=1): the certificate is there, but it is+# trusted for code signing only after `add-trusted-cert`, and the Keychain is+# in the search list only after `list-keychains -s` (SHIM_KEYCHAIN_LISTED=0).+if [ "${SHIM_FRESH_KEYCHAIN:-0}" = 1 ]; then+ fake=00112233445566778899AABBCCDDEEFF00112233+ case "$1" in+ find-identity)+ verified=0; for a in "$@"; do [ "$a" = -v ] && verified=1; done+ if [ "$verified" = 0 ] || [ -e "$SHIM_STATE/trusted" ]; then echo " 1) $fake \"CuaDriver Local Signing (cua-driver-rs)\""; fi+ echo " 1 valid identities found"; exit 0 ;;+ find-certificate)+ echo "SHA-1 hash: $fake"; echo "-----BEGIN CERTIFICATE-----"; echo "MIIBfake"; echo "-----END CERTIFICATE-----"; exit 0 ;;+ list-keychains)+ if [ "$3" = -s ]; then : > "$SHIM_STATE/listed"; exit 0; fi+ if [ "${SHIM_KEYCHAIN_LISTED:-1}" = 1 ] || [ -e "$SHIM_STATE/listed" ]; then echo " \"$HOME/Library/Keychains/login.keychain-db\""; fi+ echo " \"/Library/Keychains/System.keychain\""; exit 0 ;;+ add-trusted-cert)+ if [ "${SHIM_TRUST_FAILS:-0}" = 1 ]; then echo "SecTrustSettingsSetTrustSettings: no user interaction was possible" >&2; exit 1; fi+ : > "$SHIM_STATE/trusted"; exit 0 ;;+ set-key-partition-list)+ # SHIM_PARTITION_FAILS=1: no key matched the filter (the tool says so and changes nothing).+ if [ "${SHIM_PARTITION_FAILS:-0}" = 1 ]; then echo "security: SecItemCopyMatching: The specified item could not be found in the keychain." >&2; exit 1; fi+ : > "$SHIM_STATE/partition"; exit 0 ;;+ esac+fi+exit 0'+# codesign: the real one, except that it can be made to fail verifying one+# path, to stall (exit like a killed-by-alarm process, no output) on its first+# signing call only (CODESIGN_STALL_ONCE=1) or on every one (CODESIGN_STALL=1).+write_shim codesign 'if [ "${SHIM_FRESH_KEYCHAIN:-0}" = 1 ]; then+ # Signing with the fresh Keychain'"'"'s certificate works once it is trusted (and+ # its key opened to codesign, SHIM_NEED_PARTITION=1); then it signs ad hoc, as+ # a unit test has no real certificate.+ args=(); prev=""; fake=0+ for a in "$@"; do+ if [ "$prev" = --sign ] && [ "$a" = 00112233445566778899AABBCCDDEEFF00112233 ]; then fake=1; args+=(-); else args+=("$a"); fi+ prev="$a"+ done+ if [ "$fake" = 1 ]; then+ if [ ! -e "$SHIM_STATE/trusted" ] || { [ "${SHIM_NEED_PARTITION:-0}" = 1 ] && [ ! -e "$SHIM_STATE/partition" ]; }; then+ echo "no identity found" >&2; exit 1+ fi+ exec /usr/bin/codesign "${args[@]}"+ fi+fi+if [ -n "${FAIL_VERIFY_PATH:-}" ]; then+ verifying=0; for a in "$@"; do [ "$a" = --verify ] && verifying=1; done+ for a in "$@"; do if [ "$verifying" = 1 ] && [ "$a" = "$FAIL_VERIFY_PATH" ]; then echo "shim: verify failed" >&2; exit 1; fi; done+fi+signing=0; for a in "$@"; do [ "$a" = --sign ] && signing=1; done+if [ "$signing" = 1 ]; then+ if [ "${CODESIGN_STALL:-0}" = 1 ]; then exit 142; fi+ if [ "${CODESIGN_STALL_ONCE:-0}" = 1 ] && [ ! -e "$SHIM_STATE/stalled" ]; then : > "$SHIM_STATE/stalled"; exit 142; fi+fi+exec /usr/bin/codesign "$@"'++# The tools the build needs (the script checks for them first). Each can be+# made to look missing or wrong: SHIM_NO_XCODE=1, SHIM_NODE_MAJOR=20,+# SHIM_WASM_TARGET= (none), SHIM_WASM_BINDGEN=0.2.1, SHIM_PNPM_BUILD_FAILS=1.+write_shim xcode-select 'if [ "${SHIM_NO_XCODE:-0}" = 1 ]; then exit 2; fi+echo /Library/Developer/CommandLineTools'+write_shim swift 'echo swift'+write_shim cmake 'echo "cmake version 3.30.0"'+write_shim node 'case "$*" in *versions.node*) echo "${SHIM_NODE_MAJOR:-22}" ;; *) echo "v${SHIM_NODE_MAJOR:-22}.1.0" ;; esac'+write_shim rustup 'case "$*" in "target list --installed --toolchain"*) echo "${SHIM_WASM_TARGET-wasm32-unknown-unknown}" ;; esac'+write_shim wasm-bindgen 'echo "wasm-bindgen ${SHIM_WASM_BINDGEN:-0.2.126}"'+# pnpm: logs where and how it ran; `pnpm build` makes dist/index.html, as the+# web UI's build does.+write_shim pnpm 'echo "pnpm $* [in ${PWD##*/}] CI=${CI:-}" >> "$WEB_LOG"+if [ "$1" = build ]; then+ if [ "${SHIM_PNPM_BUILD_FAILS:-0}" = 1 ]; then echo "vite: build failed" >&2; exit 1; fi+ mkdir -p dist && echo "<!doctype html>" > dist/index.html+fi+exit 0'++# cargo: logs where and how it ran, and makes what the build would make. In+# libs/cua-spacesd it makes this checkout's daemon (FAKE_CARGO_NO_DAEMON=1:+# a build that succeeds and makes nothing).+write_shim cargo 'echo "cargo $* [in ${PWD##*/}]" >> "$CARGO_LOG"+case "$PWD" in+ */libs/cua-spacesd)+ if [ "${FAKE_CARGO_NO_DAEMON:-0}" != 1 ]; then+ mkdir -p target/release && cp "$FAKE_CHECKOUT_DAEMON" target/release/cua-spacesd+ fi ;;+ */libs/cua)+ mkdir -p target/release && : > target/release/cua-spaces-cli && : > target/release/libcua_spaces_ffi.dylib ;;+esac+exit 0'++# --- Running a script ---------------------------------------------------------------++STDIN_FILE=/dev/null+OUT=""+RC=0+# run <command...>: the command with the fake HOME and shims; output in $OUT,+# status in $RC.+run() {+ OUT="$(+ export HOME="$FAKE_HOME" PATH="$SHIMS:$PATH" CUA_LSREGISTER="$SHIMS/lsregister" \+ SHIM_LOG SHIM_STATE STUB_LOG FAKE_BUILD_LOG="$BUILD_LOG" FAKE_STUB="$STUB_BIN" \+ FAKE_DYLIB="$STUB_DYLIB" LUME_LOG CARGO_LOG WEB_LOG FAKE_CHECKOUT_DAEMON="$DAEMON_CHECKOUT" FAKE_PINNED_DAEMON="$DAEMON_PINNED"+ # CI is set on a CI runner and not on a Mac. The web UI check expects+ # CI=true only where install-local.sh sets it (pnpm install), so drop it.+ unset SUDO_USER CUA_DRIVER_LOCAL_SIGNING_KEYCHAIN CUA_DRIVER_LOCAL_SIGNING_IDENTITY CUA_CHANNEL CUA_HOME CUA_ENV \+ CARGO_TARGET_DIR CUA_SPACESD_BIN CUA_WEBUI_DIST CI+ "$@" < "$STDIN_FILE" 2>&1+ )"+ RC=$?+}+# The whole path: the cargo shim builds the library, the CLI and the daemon.+install() { run "$FAKE_SCRIPTS/install-local.sh" --no-launch "$@"; }+uninstall() { run "$FAKE_SCRIPTS/uninstall-local.sh" "$@"; }++# --- Snapshots ------------------------------------------------------------------------++# snap <path relative to the fake HOME>...: every file and symlink below each+# as "path<TAB>mode<TAB>link target", then "path<TAB>sha256" per file, sorted.+# A path that is not there is "absent".+snap() {+ (+ cd "$FAKE_HOME" || exit 1+ for p in "$@"; do+ if [ ! -e "$p" ] && [ ! -L "$p" ]; then+ printf '%s\tabsent\n' "$p"+ continue+ fi+ find "$p" \( -type f -o -type l \) -print0 | LC_ALL=C sort -z | xargs -0 stat -f $'%N\t%Lp\t%Y'+ find "$p" -type f -print0 | LC_ALL=C sort -z | xargs -0 shasum -a 256 | sed 's/^\([0-9a-f]*\) \(.*\)$/\2\t\1/'+ done+ ) | sed 's#^\./##'+}+snap_all() { snap . | LC_ALL=C sort; }++STABLE_PATHS=(+ ".cua" ".lume" ".local/bin/cua" ".local/bin/lume"+ "Library/Application Support/com.trycua.spaces.macos"+ "Library/LaunchAgents/com.trycua.spacesd.host.plist"+ "Library/LaunchAgents/com.trycua.lume_daemon.plist"+ "Cua Volume" "Applications/Cua Spaces.app"+)+snap_stable() { snap "${STABLE_PATHS[@]}"; }++# The real Stable app, when this Mac has one: read, never written (a listing+# with sizes and modification times: it changes if anything is written).+snap_real_stable_app() {+ local app="/Applications/Cua Spaces.app"+ [ -d "$app" ] || { echo "absent"; return; }+ find "$app" -type f -print0 2>/dev/null | LC_ALL=C sort -z | xargs -0 stat -f $'%N\t%z\t%m' | shasum -a 256+}+REAL_HOME="$HOME"+REAL_STABLE_BEFORE="$(snap_real_stable_app)"+REAL_LOCAL_CLI_BEFORE="$(ls -l "$HOME/.local/bin/cua-local" 2>&1)"++# A Stable install in the fake HOME, with a Stable app next to where the Local+# one goes.+make_stable_install() {+ local d+ mkdir -p "$FAKE_HOME/.cua/helper" "$FAKE_HOME/.lume/vm1" "$FAKE_HOME/.local/bin" \+ "$FAKE_HOME/Library/Application Support/com.trycua.spaces.macos" \+ "$FAKE_HOME/Library/LaunchAgents" "$FAKE_HOME/Cua Volume" \+ "$FAKE_HOME/Applications/Cua Spaces.app/Contents/MacOS"+ echo '{"session":"stable"}' > "$FAKE_HOME/.cua/credentials.json"+ echo '{"label":"com.trycua.spaces.helper"}' > "$FAKE_HOME/.cua/helper/service.json"+ echo 'port = 3211' > "$FAKE_HOME/.cua/config.toml"+ echo '{"name":"vm1"}' > "$FAKE_HOME/.lume/vm1/config.json"+ cp "$STUB_BIN" "$FAKE_HOME/.local/bin/cua"+ cp "$STUB_BIN" "$FAKE_HOME/.local/bin/lume"+ echo '{}' > "$FAKE_HOME/Library/Application Support/com.trycua.spaces.macos/settings.json"+ echo '<plist/>' > "$FAKE_HOME/Library/LaunchAgents/com.trycua.spacesd.host.plist"+ echo '<plist/>' > "$FAKE_HOME/Library/LaunchAgents/com.trycua.lume_daemon.plist"+ echo 'my files' > "$FAKE_HOME/Cua Volume/note.txt"+ d="$FAKE_HOME/Applications/Cua Spaces.app/Contents"+ cp "$STUB_BIN" "$d/MacOS/CuaSpacesMac"+ printf '<plist version="1.0"><dict><key>CFBundleIdentifier</key><string>com.trycua.spaces.macos</string></dict></plist>\n' > "$d/Info.plist"+}++reset_fixture() {+ rm -rf "$FAKE_HOME" "$FAKE_REPO/apps/cua-spaces-macos/.build" "$SHIM_STATE" \+ "$FAKE_REPO/libs/cua-spacesd/target" "$FAKE_REPO/libs/cua/target" "$FAKE_REPO/apps/cua-spaces-web/dist"+ mkdir -p "$FAKE_HOME" "$SHIM_STATE"+ : > "$SHIM_LOG"; : > "$STUB_LOG"; : > "$BUILD_LOG"; : > "$LUME_LOG"; : > "$CARGO_LOG"; : > "$WEB_LOG"+ STDIN_FILE=/dev/null+ write_lume_scripts yes+ make_stable_install+}++LOCAL_APP="$FAKE_HOME/Applications/Cua Spaces Local.app"+LOCAL_CLI="$FAKE_HOME/.local/bin/cua-local"+installed_id() { /usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$1/Contents/Info.plist" 2>/dev/null; }++# Every added path must be inside the Local app or be `cua-local`; nothing may+# be removed or changed. Compares two snap_all outputs.+only_local_additions() {+ local before="$1" after="$2" removed added bad+ removed="$(comm -23 <(printf '%s\n' "$before") <(printf '%s\n' "$after"))"+ [ -z "$removed" ] || { note "removed or changed: $removed"; return 1; }+ added="$(comm -13 <(printf '%s\n' "$before") <(printf '%s\n' "$after") | cut -f1)"+ bad="$(printf '%s\n' "$added" | grep -v -e '^Applications/Cua Spaces Local\.app/' -e '^\.local/bin/cua-local$' | grep -v '^$' || true)"+ [ -z "$bad" ] || { note "unexpected new paths: $bad"; return 1; }+}++# --- 0. The names are CuaChannel::Local's ---------------------------------------------++echo "== names =="+if [ -f "$CHANNEL_RS" ]; then+ names_ok=1+ while IFS= read -r value; do+ grep -F >/dev/null "\"$value\"" "$CHANNEL_RS" || { fail "scripts/_local-common.sh has \"$value\", which channel.rs does not"; names_ok=0; }+ done < <(+ # shellcheck disable=SC1091+ . "$SCRIPTS_DIR/_local-common.sh"+ printf '%s\n' "$LOCAL_BUNDLE_ID" "$LOCAL_APP_DIR_NAME" "$LOCAL_CLI_NAME" "$LOCAL_URL_SCHEME" \+ "$LOCAL_HOME_DIR_NAME" "$LOCAL_APP_SUPPORT_DIR_NAME" "$LOCAL_HELPER_LABEL" "$LOCAL_HOST_LABEL" \+ "$LOCAL_VOLUME_NAME" "$LOCAL_LUME_BIN_NAME" "$LOCAL_LUME_DIR_NAME" "${LOCAL_KEYCHAIN_SERVICES[@]}" \+ "$STABLE_BUNDLE_ID" "$STABLE_URL_SCHEME" "$STABLE_HELPER_LABEL" "$STABLE_APP_PARENT" \+ "$STABLE_APP_DIR_NAME" "$STABLE_HOME_DIR_NAME" "$STABLE_CLI_NAME" "$STABLE_LUME_DIR_NAME" "$STABLE_VOLUME_NAME"+ )+ [ "$names_ok" = 1 ] && pass "every name in _local-common.sh is in CuaChannel (channel.rs)"+else+ note "SKIP: no $CHANNEL_RS"+fi++# --- 1. First install ------------------------------------------------------------------++echo "== install =="+reset_fixture+STABLE_BEFORE="$(snap_stable)"+ALL_BEFORE="$(snap_all)"+install+check "install-local.sh succeeds (status $RC)" '[ "$RC" = 0 ]'+[ "$RC" = 0 ] || note "$OUT"+check "builds with --channel local debug <out>" 'grep >/dev/null -- "^--channel local debug " "$BUILD_LOG"'+check "the app is ~/Applications/Cua Spaces Local.app with the Local bundle id" '[ "$(installed_id "$LOCAL_APP")" = com.trycua.spaces.local ]'+check "the signature verifies (deep, strict)" '/usr/bin/codesign --verify --deep --strict "$LOCAL_APP" 2>/dev/null'+check "nested code was re-signed with the app's identity (cua-spacesd keeps its identifier)" \+ '/usr/bin/codesign -dv "$LOCAL_APP/Contents/MacOS/cua-spacesd" 2>&1 | grep >/dev/null "^Identifier=com.trycua.spaces.local$"'+check "the nested framework is signed and sealed" '/usr/bin/codesign --verify --strict "$LOCAL_APP/Contents/Frameworks/Fake.framework" 2>/dev/null'+check "cua-local links to the bundled cua" '[ "$(readlink "$LOCAL_CLI")" = "$LOCAL_APP/Contents/MacOS/cua" ]'+check "cua-local runs the bundled cua" 'STUB_LOG="$STUB_LOG" "$LOCAL_CLI" status && grep >/dev/null "cua-local status" "$STUB_LOG"'+check "no staging files are left in the build tree" '[ ! -e "$FAKE_REPO/apps/cua-spaces-macos/.build/local-stage" ]'+check "nothing is opened with --no-launch" '! grep >/dev/null "^open " "$SHIM_LOG"'+check "the app is registered with LaunchServices" 'grep >/dev/null "^lsregister -f $LOCAL_APP\$" "$SHIM_LOG"'+check "Stable files are byte-identical after install" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'+check "the only new paths are the Local app and cua-local" 'only_local_additions "$ALL_BEFORE" "$(snap_all)"'+check "no home or Local state was created" '[ ! -e "$FAKE_HOME/.cua-local" ]'++# --- 2. Rebuild ---------------------------------------------------------------------------++echo "== rebuild =="+ALL_BEFORE="$(snap_all)"+: > "$SHIM_LOG"+FAKE_BUILD_SALT=2 install+check "a rebuild installs over the Local app (status $RC)" '[ "$RC" = 0 ]'+check "it is the new build" '[ "$(cat "$LOCAL_APP/Contents/Resources/salt.txt")" = 2 ]'+check "no backup is left behind" '! ls "$FAKE_HOME"/Applications/*.install-backup.* >/dev/null 2>&1'+check "an ad hoc cdhash change resets the Local TCC rows, and only those" \+ 'grep >/dev/null "^tccutil reset ScreenCapture com.trycua.spaces.local\$" "$SHIM_LOG" && ! grep "^tccutil" "$SHIM_LOG" | grep -v "com.trycua.spaces.local"'+check "Stable files are byte-identical after a rebuild" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'+check "nothing but the Local app changed" '[ "$(snap_all | grep -v "Cua Spaces Local.app")" = "$(printf "%s\n" "$ALL_BEFORE" | grep -v "Cua Spaces Local.app")" ]'++# --- 3. Launch and --prefix ----------------------------------------------------------------++echo "== launch, prefix =="+: > "$SHIM_LOG"+run "$FAKE_SCRIPTS/install-local.sh"+check "without --no-launch the app is opened by its exact path" 'grep >/dev/null "^open $LOCAL_APP\$" "$SHIM_LOG"'++reset_fixture+ALL_BEFORE="$(snap_all)"+install --prefix "$WORK/prefix"+check "--prefix installs under the prefix (status $RC)" '[ "$RC" = 0 ] && [ "$(installed_id "$WORK/prefix/Applications/Cua Spaces Local.app")" = com.trycua.spaces.local ] && [ -L "$WORK/prefix/.local/bin/cua-local" ]'+check "--prefix leaves the whole HOME untouched" '[ "$(snap_all)" = "$ALL_BEFORE" ]'+install --prefix /+check "a prefix that would put the app in /Applications is refused" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "/Applications"'+install --prefix relative/dir+check "a relative prefix is refused" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "absolute"'++# --- 3b. The host service ------------------------------------------------------------------++# The machine code of a program, which a signature does not change.+text_hash() { otool -X -s __TEXT __text "$1" 2>/dev/null | shasum -a 256 | cut -d' ' -f1; }++echo "== the host service (cua-spacesd) =="+reset_fixture+install+check "the library and CLI are built and staged" \+ 'grep >/dev/null "^cargo build --locked --release -p cua-spaces-ffi -p cua-spaces-cli \[in cua\]$" "$CARGO_LOG" && grep >/dev/null "^stage-library" "$CARGO_LOG"'+check "cua-spacesd is built from this checkout's libs/cua-spacesd" \+ 'grep >/dev/null "^cargo build --locked --release -p cua-spacesd --bin cua-spacesd \[in cua-spacesd\]$" "$CARGO_LOG"'+check "(the checkout's and the pinned daemon of this fixture differ in code)" '[ "$(text_hash "$DAEMON_CHECKOUT")" != "$(text_hash "$DAEMON_PINNED")" ]'+check "the bundled cua-spacesd is this checkout's build" '[ "$(text_hash "$LOCAL_APP/Contents/MacOS/cua-spacesd")" = "$(text_hash "$DAEMON_CHECKOUT")" ]'+check "and not the pinned release" '[ "$(text_hash "$LOCAL_APP/Contents/MacOS/cua-spacesd")" != "$(text_hash "$DAEMON_PINNED")" ]'++ALL_BEFORE="$(snap_all)"+FAKE_BUILD_SALT=pinned FAKE_BUILD_IGNORE_SPACESD_BIN=1 install+check "a build-app.sh that bundles the pinned cua-spacesd is refused, and the installed app is unchanged" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "not the build of this checkout" && [ "$(snap_all)" = "$ALL_BEFORE" ]'+reset_fixture+FAKE_BUILD_IGNORE_SPACESD_BIN=1 install+check "the same on a first install: nothing is installed" '[ "$RC" != 0 ] && [ ! -e "$LOCAL_APP" ] && [ ! -L "$LOCAL_CLI" ]'++reset_fixture+FAKE_CARGO_NO_DAEMON=1 install+check "a cargo run that leaves no cua-spacesd stops the install before the app is built" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "cargo did not produce" && [ ! -s "$BUILD_LOG" ] && [ ! -e "$LOCAL_APP" ]'++reset_fixture+install --skip-rust-build+check "--skip-rust-build with no cua-spacesd build is refused before anything is built" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "no cua-spacesd build" && [ ! -s "$BUILD_LOG" ] && [ ! -s "$CARGO_LOG" ]'+install+: > "$CARGO_LOG"+FAKE_BUILD_SALT=skip install --skip-rust-build+check "--skip-rust-build uses the existing build: no cargo, the same daemon bundled (status $RC)" \+ '[ "$RC" = 0 ] && [ ! -s "$CARGO_LOG" ] && [ "$(cat "$LOCAL_APP/Contents/Resources/salt.txt")" = skip ] && [ "$(text_hash "$LOCAL_APP/Contents/MacOS/cua-spacesd")" = "$(text_hash "$DAEMON_CHECKOUT")" ]'+reset_fixture+run env CARGO_TARGET_DIR=relative/target "$FAKE_SCRIPTS/install-local.sh" --no-launch+check "a relative CARGO_TARGET_DIR is refused (the daemon could not be found)" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "CARGO_TARGET_DIR must be an absolute path"'++# --- 3c. --prefix is resolved before anything is built ------------------------------------------++echo "== --prefix resolves .., symlinks and case, and refuses what the released app owns =="+reset_fixture+LINKS="$WORK/links"+rm -rf "$LINKS" "$WORK/p-apps" "$WORK/p-bin" "$WORK/p-sys" "$WORK/ok" "$WORK/a"+mkdir -p "$LINKS" "$WORK/p-apps" "$WORK/p-bin/.local" "$WORK/p-sys" "$WORK/ok"+ln -s "$FAKE_HOME/.cua" "$LINKS/to-cua"+ln -s "$LINKS/to-cua" "$LINKS/chain"+ln -s "$LINKS/loop" "$LINKS/loop"+ln -s "$FAKE_HOME/.lume" "$WORK/p-apps/Applications"+ln -s "$FAKE_HOME/.cua" "$WORK/p-bin/.local/bin"+ln -s /Applications "$WORK/p-sys/Applications"+ln -s "$WORK/ok" "$LINKS/to-ok"+ALL_BEFORE="$(snap_all)"+for entry in \+ "$FAKE_HOME/.cua|inside the Stable home" \+ "$FAKE_HOME/.cua/deeper/still|nested in the Stable home" \+ "$FAKE_HOME/.lume|Lume's folder" \+ "$FAKE_HOME/Cua Volume|Cua Volume" \+ "$FAKE_HOME/Library/Application Support/com.trycua.spaces.macos|the Stable app's support folder" \+ "$FAKE_HOME/x/../.cua|a .. into the Stable home" \+ "$FAKE_HOME/.cua/sub/..|a trailing .. in the Stable home" \+ "$FAKE_HOME/.CUA|the Stable home in another case" \+ "$LINKS/to-cua|a symlink to the Stable home" \+ "$LINKS/chain|a chain of symlinks to the Stable home" \+ "$WORK/p-apps|an Applications folder that is a symlink into Lume's folder" \+ "$WORK/p-bin|a .local/bin that is a symlink into the Stable home" \+ "$WORK/p-sys|an Applications folder that is a symlink to /Applications" \+ "/Applications/Cua Spaces.app|inside the Stable app" \+ "/System/Volumes/Data/Applications|/Applications by its firmlink path"; do+ prefix="${entry%%|*}"+ what="${entry#*|}"+ : > "$BUILD_LOG"; : > "$CARGO_LOG"+ install --prefix "$prefix"+ check "install refuses --prefix $what" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "refusing" && [ ! -s "$BUILD_LOG" ] && [ ! -s "$CARGO_LOG" ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'+ : > "$SHIM_LOG"+ uninstall --yes --prefix "$prefix"+ check "uninstall refuses --prefix $what" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "refusing" && [ ! -s "$SHIM_LOG" ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'+done+unset entry prefix what+install --prefix "$LINKS/loop"+check "a symlink loop in --prefix is refused" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "cannot resolve"'+install --prefix "$FAKE_HOME/.cua/.."+check "a .. that leads out of the Stable home to a safe place is accepted: the default HOME (status $RC)" '[ "$RC" = 0 ] && [ -d "$LOCAL_APP" ]'+reset_fixture+install --prefix "$WORK/a/b/../c"+check "a nested --prefix with .. is installed where it resolves ($WORK/a/c)" '[ "$RC" = 0 ] && [ -d "$WORK/a/c/Applications/Cua Spaces Local.app" ] && [ ! -e "$WORK/a/b" ]'+install --prefix "$LINKS/to-ok"+check "a symlinked --prefix is installed where it leads ($WORK/ok)" '[ "$RC" = 0 ] && [ -d "$WORK/ok/Applications/Cua Spaces Local.app" ] && [ -L "$WORK/ok/.local/bin/cua-local" ]'+check "and the link target is the resolved app" '[ "$(readlink "$WORK/ok/.local/bin/cua-local")" = "$WORK/ok/Applications/Cua Spaces Local.app/Contents/MacOS/cua" ]'+uninstall --yes --prefix "$LINKS/to-ok"+check "uninstall with the same symlinked --prefix removes it" '[ "$RC" = 0 ] && [ ! -e "$WORK/ok/Applications/Cua Spaces Local.app" ] && [ ! -L "$WORK/ok/.local/bin/cua-local" ]'++# --- 3d. A Stable folder that is itself a symlink ------------------------------------------------++# ~/.lume may be a link to another volume (/Volumes/VMs): that volume is the+# Stable Lume folder, and a --prefix there must be refused. The same for every+# Stable-owned path, and for the Stable CLI, a link to the real binary.+echo "== a Stable-owned path that is a symlink: its target is Stable's too =="+for owned in ".lume" ".cua" "Cua Volume" "Library/Application Support/com.trycua.spaces.macos"; do+ reset_fixture+ target="$WORK/elsewhere/$(printf '%s' "$owned" | tr ' /' '__')"+ rm -rf "$WORK/elsewhere"+ mkdir -p "$target"+ cp -R "$FAKE_HOME/$owned/." "$target/"+ rm -rf "${FAKE_HOME:?}/$owned"+ ln -s "$target" "$FAKE_HOME/$owned"+ ALL_BEFORE="$(snap_all)"+ TARGET_BEFORE="$(find "$target" | LC_ALL=C sort)"+ for prefix in "$target" "$target/deeper/still" "$target/x/.."; do+ : > "$BUILD_LOG"; : > "$CARGO_LOG"+ install --prefix "$prefix"+ check "install refuses --prefix $prefix: ~/$owned is a symlink to it" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "refusing" && [ ! -s "$BUILD_LOG" ] && [ ! -s "$CARGO_LOG" ] && [ "$(snap_all)" = "$ALL_BEFORE" ] && [ "$(find "$target" | LC_ALL=C sort)" = "$TARGET_BEFORE" ]'+ : > "$SHIM_LOG"+ uninstall --yes --prefix "$prefix"+ check "uninstall refuses --prefix $prefix too" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "refusing" && [ ! -s "$SHIM_LOG" ] && [ "$(find "$target" | LC_ALL=C sort)" = "$TARGET_BEFORE" ]'+ done+done+unset owned target prefix++reset_fixture+cp "$FAKE_HOME/.local/bin/cua" "$WORK/cua-real"+rm "$FAKE_HOME/.local/bin/cua"+ln -s "$WORK/cua-real" "$FAKE_HOME/.local/bin/cua"+ALL_BEFORE="$(snap_all)"+install+check "a Stable cua that is a symlink does not stop an install (cua-local is another name)" '[ "$RC" = 0 ] && [ -d "$LOCAL_APP" ] && [ "$(readlink "$FAKE_HOME/.local/bin/cua")" = "$WORK/cua-real" ]'+install --prefix "$WORK/cua-real"+check "but the file it links to is Stable's: --prefix there is refused" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "refusing"'+reset_fixture+mkdir -p "$WORK/safe-vms"+ln -s "$WORK/safe-vms" "$WORK/safe-link"+install --prefix "$WORK/safe-link"+check "a symlinked --prefix that Stable does not own is still fine (status $RC)" '[ "$RC" = 0 ] && [ -d "$WORK/safe-vms/Applications/Cua Spaces Local.app" ]'++# --- 4. Refusals ------------------------------------------------------------------------------++echo "== refusals =="+reset_fixture+mkdir -p "$FAKE_HOME/Applications"+cp -R "$FAKE_HOME/Applications/Cua Spaces.app" "$LOCAL_APP"+ALL_BEFORE="$(snap_all)"+install+check "a bundle with the Stable id at the Local path is refused" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "refusing to touch" && printf "%s" "$OUT" | grep >/dev/null "com.trycua.spaces.macos"'+check "it was refused before anything was built" '[ ! -s "$BUILD_LOG" ]'+check "and nothing changed" '[ "$(snap_all)" = "$ALL_BEFORE" ]'+uninstall --yes+check "uninstall-local.sh refuses the same bundle too" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "refusing to touch"'+check "and removes nothing" '[ "$(snap_all)" = "$ALL_BEFORE" ] && [ -z "$(cat "$SHIM_LOG")" ]'++reset_fixture+mkdir -p "$FAKE_HOME/Applications/Cua Spaces Local.app/Contents"+ALL_BEFORE="$(snap_all)"+install+check "a folder with no Info.plist at the Local path is refused" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "not an app bundle"'++reset_fixture+ln -s "$FAKE_HOME/Applications/Cua Spaces.app" "$LOCAL_APP"+ALL_BEFORE="$(snap_all)"+install+check "a symlink at the Local path (here to the Stable app) is refused and left alone" '[ "$RC" != 0 ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'++echo "== a bad build is never installed =="+for variant in "FAKE_BUILD_ID=com.trycua.spaces.macos|bundle id" \+ "FAKE_BUILD_FEED=1|update feed" \+ "FAKE_BUILD_SCHEME=cua|URL scheme" \+ "FAKE_BUILD_CHANNEL=stable|CuaChannel" \+ "FAKE_BUILD_HELPER_LABEL=com.trycua.spaces.helper|Stable helper label" \+ "FAKE_BUILD_ASSOCIATED=com.trycua.spaces.macos|associated with the Stable app"; do+ var="${variant%%|*}"+ what="${variant#*|}"+ reset_fixture+ install+ ALL_BEFORE="$(snap_all)"+ eval "$var FAKE_BUILD_SALT=bad install"+ check "$var: refused ($what), and the installed Local app is unchanged" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep -i >/dev/null "$what" && [ "$(snap_all)" = "$ALL_BEFORE" ]'+done+reset_fixture+ALL_BEFORE="$(snap_all)"+FAKE_BUILD_APP_NAME="Cua Spaces" install+check "a build-app.sh that ignored --channel local (made Cua Spaces.app) is refused" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "did not build the Local channel" && [ "$(snap_all)" = "$ALL_BEFORE" ]'++# --- 4b. The web UI ----------------------------------------------------------------------------------++echo "== the web UI =="+reset_fixture+install+WEB_DIST="$FAKE_REPO/apps/cua-spaces-web/dist"+check "the web UI is built as the release build does: pnpm install --ignore-workspace --frozen-lockfile, then pnpm build, in apps/cua-spaces-web" \+ '[ "$(cat "$WEB_LOG")" = "pnpm install --ignore-workspace --frozen-lockfile [in cua-spaces-web] CI=true+pnpm build [in cua-spaces-web] CI=" ]'+check "it is built before the Rust build (the quick one fails first)" '[ -s "$WEB_LOG" ] && [ -s "$CARGO_LOG" ]'+check "the build is told where the web UI is, and the installed app has it" \+ 'grep >/dev/null "^webui=$WEB_DIST\$" "$BUILD_LOG" && [ -f "$LOCAL_APP/Contents/Resources/WebUI/index.html" ]'+check "the signature covers the web UI (it verifies, deep and strict)" '/usr/bin/codesign --verify --deep --strict "$LOCAL_APP" 2>/dev/null'++reset_fixture+ALL_BEFORE="$(snap_all)"+install --skip-web-build+check "--skip-web-build with no web UI build stops with a clear message, before anything is built" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "The new UI is not in this build" && printf "%s" "$OUT" | grep >/dev/null "pnpm install --ignore-workspace" && [ ! -s "$BUILD_LOG" ] && [ ! -s "$CARGO_LOG" ] && [ ! -s "$WEB_LOG" ]'+check "and nothing is installed" '[ ! -e "$LOCAL_APP" ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'+mkdir -p "$WEB_DIST" && echo "<!doctype html>" > "$WEB_DIST/index.html"+install --skip-web-build+check "--skip-web-build with a web UI build already there installs it, and runs no pnpm" \+ '[ "$RC" = 0 ] && [ ! -s "$WEB_LOG" ] && [ -f "$LOCAL_APP/Contents/Resources/WebUI/index.html" ]'++reset_fixture+mkdir -p "$WORK/other-webui" && echo "<!doctype html>" > "$WORK/other-webui/index.html"+run env CUA_WEBUI_DIST="$WORK/other-webui" "$FAKE_SCRIPTS/install-local.sh" --no-launch+check "CUA_WEBUI_DIST is used as it is: no pnpm, and the build gets it" \+ '[ "$RC" = 0 ] && [ ! -s "$WEB_LOG" ] && grep >/dev/null "^webui=$WORK/other-webui\$" "$BUILD_LOG" && [ -f "$LOCAL_APP/Contents/Resources/WebUI/index.html" ]'+reset_fixture+run env CUA_WEBUI_DIST="$WORK/nowhere" "$FAKE_SCRIPTS/install-local.sh" --no-launch+check "a CUA_WEBUI_DIST without an index.html stops with the same message" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "no web UI build at $WORK/nowhere/index.html" && [ ! -e "$LOCAL_APP" ]'++reset_fixture+ALL_BEFORE="$(snap_all)"+run env SHIM_PNPM_BUILD_FAILS=1 "$FAKE_SCRIPTS/install-local.sh" --no-launch+check "a failing web UI build stops the install, and nothing is built after it or installed" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "the web UI build failed" && [ ! -s "$BUILD_LOG" ] && [ ! -s "$CARGO_LOG" ] && [ ! -e "$LOCAL_APP" ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'++reset_fixture+install+ALL_BEFORE="$(snap_all)"+FAKE_BUILD_NO_WEBUI=1 FAKE_BUILD_SALT=nowebui install+check "an app build that left the web UI out is never installed: the previous Local app stays" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "no web UI" && [ "$(snap_all)" = "$ALL_BEFORE" ]'++# --- 4c. The tools the build needs -------------------------------------------------------------------++echo "== prerequisites =="+# A PATH that has the logging shims but none of the build tools, so what the+# script finds is what the test puts back.+MINIMAL_SHIMS="$WORK/shims-minimal"+reset_minimal_shims() {+ rm -rf "$MINIMAL_SHIMS"; mkdir -p "$MINIMAL_SHIMS"+ for f in "$SHIMS"/*; do+ case "$(basename "$f")" in+ cmake|node|pnpm|rustup|wasm-bindgen|cargo) ;;+ *) cp "$f" "$MINIMAL_SHIMS/" ;;+ esac+ done+}+reset_minimal_shims+MINIMAL_PATH="$MINIMAL_SHIMS:/usr/bin:/bin:/usr/sbin:/sbin"+no_tools_install() { run env PATH="$MINIMAL_PATH" "$FAKE_SCRIPTS/install-local.sh" --no-launch "$@"; }++reset_fixture+ALL_BEFORE="$(snap_all)"+no_tools_install+check "with no build tools it stops before building anything (status $RC)" '[ "$RC" != 0 ] && [ ! -s "$BUILD_LOG" ] && [ ! -s "$CARGO_LOG" ] && [ ! -s "$WEB_LOG" ] && [ ! -e "$LOCAL_APP" ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'+for want in "cmake" "brew install cmake" "rustup.rs" "Node 22 or later" "pnpm" "brew install pnpm" \+ "wasm32 Rust target" "rustup toolchain install 1.97.1 --profile minimal --target wasm32-unknown-unknown" \+ "wasm-bindgen-cli 0.2.126" "cargo install wasm-bindgen-cli --version 0.2.126 --locked"; do+ check "the one message says: $want" 'printf "%s" "$OUT" | grep -F >/dev/null -- "$want"'+done+check "it is one message (one error line), and says nothing was built or changed" \+ '[ "$(printf "%s\n" "$OUT" | grep -c "error:")" = 1 ] && printf "%s" "$OUT" | grep >/dev/null "Nothing was built or changed"'++reset_fixture+# Rust and the web UI already built: the only thing left to ask for is Xcode.+mkdir -p "$FAKE_REPO/libs/cua-spacesd/target/release" "$FAKE_REPO/apps/cua-spaces-web/dist"+cp "$DAEMON_CHECKOUT" "$FAKE_REPO/libs/cua-spacesd/target/release/cua-spacesd"+echo "<!doctype html>" > "$FAKE_REPO/apps/cua-spaces-web/dist/index.html"+SHIM_NO_XCODE=1 no_tools_install --skip-rust-build --skip-web-build+check "without the Xcode command line tools it says to run xcode-select --install" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep -F >/dev/null "xcode-select --install"'+check "--skip-rust-build --skip-web-build ask for nothing else (no cmake, Rust, Node, pnpm or wasm line)" \+ '! printf "%s" "$OUT" | grep -E >/dev/null "cmake|rustup.rs|Node 22|pnpm|wasm"'+no_tools_install --skip-rust-build --skip-web-build+check "and with Xcode in place those flags need none of the other tools (status $RC)" '[ "$RC" = 0 ] && [ -d "$LOCAL_APP" ] && [ ! -s "$CARGO_LOG" ] && [ ! -s "$WEB_LOG" ]'++reset_fixture+run env SHIM_NODE_MAJOR=20 "$FAKE_SCRIPTS/install-local.sh" --no-launch+check "an old Node is named, with what it has" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep -F >/dev/null "Node 22 or later, this Mac has v20" && [ ! -s "$BUILD_LOG" ]'+reset_fixture+run env SHIM_WASM_TARGET= SHIM_WASM_BINDGEN=0.2.100 "$FAKE_SCRIPTS/install-local.sh" --no-launch+check "a missing wasm32 target and a wrong wasm-bindgen are listed, and only those" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep -F >/dev/null "wasm32 Rust target" && printf "%s" "$OUT" | grep -F >/dev/null "wasm-bindgen-cli 0.2.126" && ! printf "%s" "$OUT" | grep -E >/dev/null "cmake|pnpm|Node 22"'+reset_fixture+install+check "with every tool in place the install goes ahead (status $RC)" '[ "$RC" = 0 ] && [ -d "$LOCAL_APP" ]'++# --- 5. Rollback ---------------------------------------------------------------------------------++echo "== rollback =="+reset_fixture+install+OLD_APP="$(snap "Applications/Cua Spaces Local.app")"+FAKE_BUILD_SALT=3 FAIL_VERIFY_PATH="$LOCAL_APP" install+check "a copy that does not verify fails the install (status $RC)" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "restored the previous"'+check "the previous Local app is back, byte for byte" '[ "$(snap "Applications/Cua Spaces Local.app")" = "$OLD_APP" ]'+check "no backup is left behind" '! ls "$FAKE_HOME"/Applications/*.install-backup.* >/dev/null 2>&1'+check "Stable files are byte-identical after the rollback" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'++# --- 5b. A stalled codesign -----------------------------------------------------------------------++echo "== a codesign that stalls =="+reset_fixture+ALL_BEFORE="$(snap_all)"+CODESIGN_STALL_ONCE=1 install+check "a codesign that stalls once is tried again, and the install succeeds (status $RC)" '[ "$RC" = 0 ] && [ -d "$LOCAL_APP" ] && [ -e "$SHIM_STATE/stalled" ]'+reset_fixture+ALL_BEFORE="$(snap_all)"+CODESIGN_STALL=1 install+check "a codesign that always stalls fails the install with a clear message, and nothing is installed" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "did not finish in 20 s" && [ "$(snap_all)" = "$ALL_BEFORE" ]'++# --- 6. Signing --------------------------------------------------------------------------------------++echo "== signing =="+reset_fixture+install --require-stable-signing+check "--require-stable-signing without a certificate stops, and installs nothing" '[ "$RC" != 0 ] && [ ! -e "$LOCAL_APP" ] && printf "%s" "$OUT" | grep >/dev/null "stable signing is required"'++# A fresh Keychain: the certificate exists, but codesign cannot use it until it+# is trusted for code signing, its Keychain is in the search list and codesign+# may use its key. The Keychain tools are shims here (a unit test must not+# change trust settings), so what is checked is what the script asks of them+# and what it tells the person, not macOS.+echo "== a fresh Keychain =="+FAKE_KEYCHAIN="$FAKE_HOME/Library/Keychains/login.keychain-db"+fresh_fixture() {+ reset_fixture+ mkdir -p "$FAKE_HOME/Library/Keychains" && : > "$FAKE_KEYCHAIN"+}+fresh_install() { run env SHIM_FRESH_KEYCHAIN=1 "$@" "$FAKE_SCRIPTS/install-local.sh" --no-launch $FRESH_ARGS; }+security_calls() { grep "^security " "$SHIM_LOG" | grep -v "find-identity\|find-certificate"; }++fresh_fixture+FRESH_ARGS=""+fresh_install+check "without consent it changes no trust setting and no search list" '! security_calls | grep >/dev/null -e "add-trusted-cert" -e "list-keychains .*-s " -e "set-key-partition-list"'+check "it says codesign cannot use the certificate yet, and prints the exact steps (trust, sudo variant, key access)" \+ 'printf "%s" "$OUT" | grep -F >/dev/null "codesign cannot use the stable local certificate yet" && printf "%s" "$OUT" | grep -F >/dev/null "security add-trusted-cert -r trustRoot -p codeSign -k \"$FAKE_KEYCHAIN\"" && printf "%s" "$OUT" | grep -F >/dev/null "sudo security add-trusted-cert -d -r trustRoot -p codeSign" && printf "%s" "$OUT" | grep -F >/dev/null "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l \"CuaDriver Local Signing (cua-driver-rs)\" -k"'+check "the steps are printed once" '[ "$(printf "%s\n" "$OUT" | grep -c "one-time setup")" = 1 ]'+check "the install is ad hoc, reported, as before (status $RC)" '[ "$RC" = 0 ] && printf "%s" "$OUT" | grep -F >/dev/null "signed ad hoc"'++fresh_fixture+FRESH_ARGS="--require-stable-signing"+fresh_install+check "--require-stable-signing still stops, installs nothing, and prints the steps once" \+ '[ "$RC" != 0 ] && [ ! -e "$LOCAL_APP" ] && printf "%s" "$OUT" | grep -F >/dev/null "stable signing is required" && [ "$(printf "%s\n" "$OUT" | grep -c "one-time setup")" = 1 ]'++fresh_fixture+FRESH_ARGS="--setup-signing"+fresh_install+check "--setup-signing trusts the certificate for code signing: security add-trusted-cert -r trustRoot -p codeSign -k <keychain> <certificate>" \+ 'grep -E >/dev/null "^security add-trusted-cert -r trustRoot -p codeSign -k $FAKE_KEYCHAIN [^ ]+\$" "$SHIM_LOG"'+check "the trust is user-level (no -d; the script never runs sudo)" '! grep >/dev/null "^security add-trusted-cert .* -d " "$SHIM_LOG" && ! grep >/dev/null "^sudo " "$SHIM_LOG"'+check "the Keychain was already in the search list: it is not rewritten" '! grep >/dev/null "^security list-keychains -d user -s" "$SHIM_LOG"'+check "it asks for no key access when codesign works after the trust" '! grep >/dev/null "set-key-partition-list" "$SHIM_LOG"'+check "it tells the person it worked, and the install goes on (status $RC)" '[ "$RC" = 0 ] && printf "%s" "$OUT" | grep -F >/dev/null "codesign can use the stable local certificate"'+check "the certificate the trust was given for is the one that signs: its PEM is the one that was exported" '! ls "${TMPDIR:-/tmp}"/cua-local-signing.* >/dev/null 2>&1'++fresh_fixture+FRESH_ARGS="--setup-signing"+fresh_install SHIM_KEYCHAIN_LISTED=0+check "a Keychain missing from the search list is added to it, before the trust" \+ 'grep -n -e "^security list-keychains -d user -s $FAKE_KEYCHAIN" -e "^security add-trusted-cert" "$SHIM_LOG" | sed -n 1p | grep >/dev/null "list-keychains" && grep >/dev/null "^security add-trusted-cert" "$SHIM_LOG"'++fresh_fixture+FRESH_ARGS="--setup-signing"+fresh_install SHIM_TRUST_FAILS=1+check "when macOS does not take the trust, it says so and prints the steps, and the install is ad hoc (status $RC)" \+ '[ "$RC" = 0 ] && printf "%s" "$OUT" | grep -F >/dev/null "macOS did not trust the certificate" && printf "%s" "$OUT" | grep -F >/dev/null "sudo security add-trusted-cert -d" && printf "%s" "$OUT" | grep -F >/dev/null "signed ad hoc"'++fresh_fixture+FRESH_ARGS="--setup-signing"+fresh_install SHIM_NEED_PARTITION=1+check "when codesign still cannot use the key and there is no terminal, it prints the key-access command rather than asking" \+ '! grep >/dev/null "set-key-partition-list" "$SHIM_LOG" && printf "%s" "$OUT" | grep -F >/dev/null "asked at a terminal" && printf "%s" "$OUT" | grep -F >/dev/null "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l \"CuaDriver Local Signing (cua-driver-rs)\" -k"'++# The key access is opened for the Local certificate's key only. `-s` alone+# changes every signing key in the Keychain (the login Keychain's other keys+# included), so the call carries `-t private -l <the certificate's name>`. The+# password is asked at a terminal, so these run under a pty that answers it.+cat > "$WORK/pty-run.py" <<'EOF'+import os, pty, select, sys+answer, prompt = os.environ.pop("PTY_ANSWER", ""), os.environ.pop("PTY_PROMPT", "")+pid, fd = pty.fork()+if pid == 0:+ os.execvp(sys.argv[1], sys.argv[1:])+out, sent = b"", False+while True:+ try:+ ready, _, _ = select.select([fd], [], [], 60)+ if not ready:+ os.kill(pid, 9)+ break+ data = os.read(fd, 4096)+ except OSError:+ break+ if not data:+ break+ out += data+ if not sent and prompt.encode() in out:+ os.write(fd, (answer + "\n").encode())+ sent = True+_, status = os.waitpid(pid, 0)+sys.stdout.write(out.decode(errors="replace").replace("\r\n", "\n"))+sys.exit(os.waitstatus_to_exitcode(status))+EOF+tty_install() { run env PTY_ANSWER=kc-secret PTY_PROMPT="Password of the Keychain" /usr/bin/python3 -I "$WORK/pty-run.py" env SHIM_FRESH_KEYCHAIN=1 "$@" "$FAKE_SCRIPTS/install-local.sh" --no-launch --setup-signing; }+KEY_CN="CuaDriver Local Signing (cua-driver-rs)"++fresh_fixture+tty_install SHIM_NEED_PARTITION=1+check "at a terminal it asks for the Keychain password and opens the key for the Local certificate only: -s -t private -l <its name>, once" \+ '[ "$(grep -c "^security set-key-partition-list" "$SHIM_LOG")" = 1 ] && grep -F >/dev/null "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l $KEY_CN -k kc-secret $FAKE_KEYCHAIN" "$SHIM_LOG"'+check "after that codesign works and it says so (status $RC)" '[ "$RC" = 0 ] && printf "%s" "$OUT" | grep -F >/dev/null "codesign can use the stable local certificate"'++fresh_fixture+tty_install SHIM_NEED_PARTITION=1 SHIM_PARTITION_FAILS=1+check "when no key matches the label it does not widen the filter: one call, then the exact steps" \+ '[ "$(grep -c "^security set-key-partition-list" "$SHIM_LOG")" = 1 ] && ! grep -v -e "-l $KEY_CN" "$SHIM_LOG" | grep >/dev/null "set-key-partition-list" && printf "%s" "$OUT" | grep -F >/dev/null "codesign still cannot use the certificate"'++fresh_fixture+tty_install+check "with the key already usable after the trust it asks for no password and calls no set-key-partition-list" '! grep >/dev/null "set-key-partition-list" "$SHIM_LOG" && ! printf "%s" "$OUT" | grep -F >/dev/null "Password of the Keychain"'++# The real `security`, on a throwaway Keychain (not in the search list, no trust+# change): the function the script runs matches the Local certificate's key and+# no other signing key, and changes nothing when there is no such key.+echo "== the key access, on a real throwaway Keychain =="+if command -v openssl >/dev/null 2>&1; then+ KCDIR="$WORK/kc"; mkdir -p "$KCDIR"+ KCFILE="$KCDIR/test.keychain-db"+ /usr/bin/security create-keychain -p kc-secret "$KCFILE" >/dev/null 2>&1 && /usr/bin/security unlock-keychain -p kc-secret "$KCFILE" >/dev/null 2>&1+ add_signing_key() {+ printf '[req]\ndistinguished_name=dn\nx509_extensions=ext\nprompt=no\n[dn]\nCN=%s\n[ext]\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=critical,codeSigning\n' "$1" > "$KCDIR/req.cnf"+ openssl req -x509 -newkey rsa:2048 -keyout "$KCDIR/k.pem" -out "$KCDIR/c.pem" -days 2 -nodes -config "$KCDIR/req.cnf" >/dev/null 2>&1 || return 1+ { openssl pkcs12 -export -legacy -inkey "$KCDIR/k.pem" -in "$KCDIR/c.pem" -out "$KCDIR/id.p12" -passout pass:x -name "$1" >/dev/null 2>&1 \+ || openssl pkcs12 -export -inkey "$KCDIR/k.pem" -in "$KCDIR/c.pem" -out "$KCDIR/id.p12" -passout pass:x -name "$1" >/dev/null 2>&1; } || return 1+ /usr/bin/security import "$KCDIR/id.p12" -k "$KCFILE" -P x -A -T /usr/bin/codesign >/dev/null 2>&1+ }+ if add_signing_key "Somebody Else's Signing Key" && add_signing_key "$KEY_CN"; then+ # The script's own function; `security` is a wrapper that keeps the keys+ # the tool says it matched (it prints each) in a file.+ MATCHED="$WORK/matched.txt"+ key_access() (+ CUA_LOCAL_SIGN_CN="$1"+ security() { /usr/bin/security "$@" > "$MATCHED" 2>&1; }+ eval "$(sed -n '/^open_key_to_codesign()/,/^}/p' "$SCRIPTS_DIR/install-local.sh")"+ open_key_to_codesign "$KCFILE" kc-secret+ )+ key_access "$KEY_CN"+ check "the function opens the Local certificate's key (status $?)" '[ -s "$MATCHED" ] && grep -F >/dev/null "\"$KEY_CN\"" "$MATCHED"'+ check "and that is the only key it matched: not the other signing key in the same Keychain" '! grep -F >/dev/null "Somebody Else" "$MATCHED" && [ "$(grep -c "^class: 0x00000010" "$MATCHED")" = 1 ]'+ key_access "No such certificate"+ check "with no key of that name it fails and matches nothing" '[ $? != 0 ] || ! grep >/dev/null "^class:" "$MATCHED"'+ # The unscoped call it replaced, to show the test would catch it.+ /usr/bin/security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k kc-secret "$KCFILE" > "$MATCHED" 2>&1+ check "(for reference) the unscoped -s call matches both keys, which is what the scoping prevents" '[ "$(grep -c "^class: 0x00000010" "$MATCHED")" = 2 ]'+ else+ note "SKIP: could not make test keys in a throwaway Keychain"+ fi+ /usr/bin/security delete-keychain "$KCFILE" >/dev/null 2>&1 || true+else+ note "SKIP: no openssl for the throwaway Keychain checks"+fi++fresh_fixture+FRESH_ARGS="--setup-signing"+fresh_install CUA_DRIVER_LOCAL_SIGNING_IDENTITY=00112233445566778899AABBCCDDEEFF00112233+check "an identity the person picked is never trusted or changed for them" \+ '! security_calls | grep >/dev/null -e "add-trusted-cert" -e "list-keychains .*-s " -e "set-key-partition-list" && printf "%s" "$OUT" | grep -F >/dev/null "does not change a certificate you picked"'++fresh_fixture+: > "$SHIM_STATE/trusted"+FRESH_ARGS="--setup-signing"+fresh_install+check "a certificate codesign can already use: no warning and no setup" \+ '! printf "%s" "$OUT" | grep -F >/dev/null "codesign cannot use" && ! security_calls | grep >/dev/null -e "add-trusted-cert" -e "set-key-partition-list"'+check "the Stable files are untouched by all of this" '[ "$(snap_stable)" = "$(snap_stable)" ] && [ ! -e "$FAKE_HOME/.cua-local" ]'++# The stable local certificate itself (shared with Cua Driver's local install)+# needs a code-signing identity that codesign can use without a prompt, from a+# keychain in the real search list (which a fake HOME hides). Only a Mac set up+# for it has one, and a unit test must not create one in a real keychain. So+# these checks are opt-in: point CUA_TEST_SIGNING_KEYCHAIN at the keychain that+# holds (or may get) "CuaDriver Local Signing (cua-driver-rs)", as in+# libs/cua-driver/scripts/README.md "Stable macOS local signing":+# CUA_TEST_SIGNING_KEYCHAIN=~/Library/Keychains/cua-driver-signing.keychain-db \+# scripts/tests/install-local-test.sh+# They run as your real user but install under --prefix in the work directory,+# so nothing of yours is written.+if [ -n "${CUA_TEST_SIGNING_KEYCHAIN:-}" ]; then+ reset_fixture+ SIGNED_PREFIX="$WORK/prefix-signed"+ SIGNED_APP="$SIGNED_PREFIX/Applications/Cua Spaces Local.app"+ ALL_BEFORE="$(snap_all)"+ signed_install() {+ run env HOME="$REAL_HOME" CUA_DRIVER_LOCAL_SIGNING_KEYCHAIN="$CUA_TEST_SIGNING_KEYCHAIN" SHIM_SECURITY_PASSTHROUGH=1 \+ "$FAKE_SCRIPTS/install-local.sh" --no-launch --require-stable-signing --prefix "$SIGNED_PREFIX" "$@"+ }+ signed_install+ if [ "$RC" = 0 ]; then+ REQ1="$(/usr/bin/codesign -d -r- "$SIGNED_APP" 2>&1 | sed -n 's/^designated => //p')"+ : > "$SHIM_LOG"+ FAKE_BUILD_SALT=rebuilt signed_install+ REQ2="$(/usr/bin/codesign -d -r- "$SIGNED_APP" 2>&1 | sed -n 's/^designated => //p')"+ check "with the local certificate the designated requirement is the certificate's" 'printf "%s" "$REQ1" | grep >/dev/null "certificate leaf"'+ check "a rebuild keeps the same designated requirement, so TCC grants survive" '[ -n "$REQ1" ] && [ "$REQ1" = "$REQ2" ] && [ "$(cat "$SIGNED_APP/Contents/Resources/salt.txt")" = rebuilt ]'+ check "a rebuild signed with the certificate resets no TCC rows" '! grep >/dev/null "^tccutil" "$SHIM_LOG"'+ check "every nested piece is signed with the same certificate" \+ 'for f in Contents/MacOS/cua Contents/MacOS/cua-spacesd Contents/Frameworks/libfake.dylib Contents/Frameworks/Fake.framework; do /usr/bin/codesign -d -r- "$SIGNED_APP/$f" 2>&1 | grep >/dev/null "certificate leaf" || exit 1; done'+ check "the fake HOME was not written" '[ "$(snap_all)" = "$ALL_BEFORE" ]'+ else+ fail "install with the signing keychain $CUA_TEST_SIGNING_KEYCHAIN failed (status $RC)"+ note "$OUT"+ fi+else+ note "SKIP: certificate-signing checks (set CUA_TEST_SIGNING_KEYCHAIN to run them)"+fi++# --- 7. lume-local ----------------------------------------------------------------------------------------++echo "== lume-local =="+reset_fixture+write_lume_scripts no+ALL_BEFORE="$(snap_all)"+install --with-lume-local+check "--with-lume-local refuses a checkout whose Lume script still installs over Stable, before building" \+ '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "still installs over the Stable lume" && [ ! -s "$BUILD_LOG" ] && [ ! -s "$LUME_LOG" ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'+write_lume_scripts yes+install --with-lume-local --prefix "$WORK/p2"+check "--with-lume-local cannot be combined with --prefix" '[ "$RC" != 0 ] && printf "%s" "$OUT" | grep >/dev/null "cannot be combined"'+install --with-lume-local+check "--with-lume-local runs the Lume script (status $RC)" '[ "$RC" = 0 ] && grep >/dev/null "^install-local" "$LUME_LOG" && [ -e "$FAKE_HOME/.local/bin/lume-local" ]'+check "and Stable files, lume included, are byte-identical" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'++# --- 8. Uninstall --------------------------------------------------------------------------------------------------++echo "== uninstall =="+reset_fixture+ALL_BEFORE="$(snap_all)"+STABLE_BEFORE="$(snap_stable)"+install+mkdir -p "$FAKE_HOME/.cua-local/helper" "$FAKE_HOME/Library/Application Support/com.trycua.spaces.local" "$FAKE_HOME/Cua Volume Local"+echo '{}' > "$FAKE_HOME/.cua-local/helper/service.json"+echo '{}' > "$FAKE_HOME/.cua-local/credentials.json"+echo '{}' > "$FAKE_HOME/Library/Application Support/com.trycua.spaces.local/settings.json"+echo '<plist/>' > "$FAKE_HOME/Library/LaunchAgents/com.trycua.spacesd.host.local.plist"+echo 'mine' > "$FAKE_HOME/Cua Volume Local/keep.txt"+BEFORE_UNINSTALL="$(snap_all)"+: > "$SHIM_LOG"; : > "$STUB_LOG"++STDIN_FILE="$WORK/answer-n"; echo n > "$STDIN_FILE"+uninstall+check "answering n removes nothing" '[ "$RC" = 0 ] && [ "$(snap_all)" = "$BEFORE_UNINSTALL" ] && printf "%s" "$OUT" | grep >/dev/null cancelled'+STDIN_FILE=/dev/null+uninstall+check "no answer (no terminal) removes nothing" '[ "$(snap_all)" = "$BEFORE_UNINSTALL" ]'++STDIN_FILE="$WORK/answer-y"; echo y > "$STDIN_FILE"+uninstall+check "answering y removes Local (status $RC)" '[ "$RC" = 0 ] && [ ! -e "$LOCAL_APP" ] && [ ! -e "$LOCAL_CLI" ] && [ ! -L "$LOCAL_CLI" ]'+STDIN_FILE=/dev/null+check "the Local home and its app support folder are gone" '[ ! -e "$FAKE_HOME/.cua-local" ] && [ ! -e "$FAKE_HOME/Library/Application Support/com.trycua.spaces.local" ]'+check "the Local host runner job file is gone" '[ ! -e "$FAKE_HOME/Library/LaunchAgents/com.trycua.spacesd.host.local.plist" ]'+check "the helper login item was unregistered by the Local app itself" 'grep >/dev/null -- "--service-helper unregister \[CUA_CHANNEL=local\]" "$STUB_LOG"'+check "launchctl was asked about the two Local labels only" \+ 'grep >/dev/null "bootout gui/[0-9]*/com.trycua.spaces.local.helper$" "$SHIM_LOG" && grep >/dev/null "bootout gui/[0-9]*/com.trycua.spacesd.host.local$" "$SHIM_LOG" && [ "$(grep -c "^launchctl" "$SHIM_LOG")" = 2 ]'+check "only the Local Keychain services were deleted (both of them)" \+ 'grep >/dev/null "^security delete-generic-password -s ai.cua.session.local\$" "$SHIM_LOG" && grep >/dev/null "^security delete-generic-password -s ai.cua.session.local.staging\$" "$SHIM_LOG" && ! grep "^security" "$SHIM_LOG" | grep -v -e "-s ai.cua.session.local\$" -e "-s ai.cua.session.local.staging\$"'+check "the Local volume folder is kept" '[ "$(cat "$FAKE_HOME/Cua Volume Local/keep.txt")" = mine ]'+check "Stable files are byte-identical after uninstall" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'++echo "== install, then uninstall, leaves the HOME as it was =="+reset_fixture+ALL_BEFORE="$(snap_all)"+install+uninstall --yes+check "uninstall --yes after install: the files are exactly the Stable fixture's again" '[ "$RC" = 0 ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'+uninstall --yes+check "uninstall with nothing installed succeeds and changes nothing" '[ "$RC" = 0 ] && [ "$(snap_all)" = "$ALL_BEFORE" ]'++echo "== uninstall and lume-local =="+reset_fixture+install --with-lume-local+: > "$LUME_LOG"+uninstall --yes+check "--yes alone keeps lume-local" '[ -e "$FAKE_HOME/.local/bin/lume-local" ] && [ ! -s "$LUME_LOG" ]'+uninstall --yes --with-lume-local+check "--with-lume-local runs the Lume uninstaller without asking again" '[ "$RC" = 0 ] && grep >/dev/null "^uninstall-local --yes$" "$LUME_LOG" && [ ! -e "$FAKE_HOME/.local/bin/lume-local" ]'+check "Stable files are byte-identical after both" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'+reset_fixture+install --with-lume-local+STDIN_FILE="$WORK/answer-yn"; printf 'y\nn\n' > "$STDIN_FILE"+: > "$LUME_LOG"+uninstall+check "asked, it offers lume-local, and n keeps it" '[ -e "$FAKE_HOME/.local/bin/lume-local" ] && [ ! -s "$LUME_LOG" ] && printf "%s" "$OUT" | grep >/dev/null "lume-local"'+STDIN_FILE=/dev/null++echo "== this Mac =="+check "the real /Applications/Cua Spaces.app was not touched by any of this" '[ "$(snap_real_stable_app)" = "$REAL_STABLE_BEFORE" ]'+check "this Mac's own ~/.local/bin/cua-local was not touched" '[ "$(ls -l "$HOME/.local/bin/cua-local" 2>&1)" = "$REAL_LOCAL_CLI_BEFORE" ]'++echo+if [ "$fails" = 0 ]; then+ echo "all checks passed"+else+ echo "$fails check(s) FAILED"+fi+exit "$fails"diff --git a/apps/cua-spaces-macos/scripts/uninstall-local.sh b/apps/cua-spaces-macos/scripts/uninstall-local.shnew file mode 100755index 0000000000..52976cc7a7--- /dev/null+++ b/apps/cua-spaces-macos/scripts/uninstall-local.sh@@ -0,0 +1,214 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Removes Cua Spaces Local (CUA-1776), the build scripts/install-local.sh+# installs, and only that. The released Cua Spaces, ~/.cua, ~/.local/bin/cua,+# ~/.lume and their launchd jobs and Keychain items have other names and are+# never reached.+#+# scripts/uninstall-local.sh [--yes] [--with-lume-local] [--prefix DIR]+#+# --yes, -y do not ask first+# --with-lume-local also remove lume-local (without it, it asks, and with+# --yes it stays); its VMs in ~/.lume-local go with it+# --prefix DIR where install-local.sh put the app and `cua-local`+# (default $HOME); the state is always removed from $HOME+#+# It removes, after asking:+# - the Local helper login item (unregistered) and the Local host runner job+# - ~/Applications/Cua Spaces Local.app+# - ~/.local/bin/cua-local+# - ~/.cua-local (the Local sign-in, host and Spaces state)+# and ~/Library/Application Support/com.trycua.spaces.local+# - the Local Keychain items (ai.cua.session.local, ai.cua.session.local.staging)+# - optionally lume-local (libs/lume/scripts/uninstall-local.sh)+# It keeps the Cua Volume Local folder and the permissions macOS granted the+# app. It refuses, changing nothing, when the app at the Local path is not a+# Cua Spaces Local bundle.+set -euo pipefail++SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd -- "$SCRIPT_DIR/../../.." && pwd)"++# shellcheck source=_local-common.sh+# shellcheck source-path=SCRIPTDIR+. "$SCRIPT_DIR/_local-common.sh"++die() { err "$*"; exit 1; }++YES=0+PREFIX=""+WITH_LUME_LOCAL=0++usage() { sed -n '/^# Removes Cua Spaces Local/,/^# Cua Spaces Local bundle\./p' "$0" | sed 's/^# \{0,1\}//'; }++while [ "$#" -gt 0 ]; do+ case "$1" in+ --yes|-y) YES=1 ;;+ --with-lume-local) WITH_LUME_LOCAL=1 ;;+ --prefix)+ [ "$#" -ge 2 ] || die "--prefix needs a directory"+ PREFIX="$2"+ shift+ ;;+ --prefix=*) PREFIX="${1#*=}" ;;+ --help|-h) usage; exit 0 ;;+ *) err "unknown option: $1 (see --help)"; exit 2 ;;+ esac+ shift+done++[ "$(uname -s)" = Darwin ] || die "Cua Spaces Local is a macOS app: run this on a Mac."+[ -n "${HOME:-}" ] && [ "$HOME" != / ] || die "HOME is not set to a user home."++if [ -z "$PREFIX" ]; then+ PREFIX="$HOME"+fi+case "$PREFIX" in+ /*) ;;+ *) die "--prefix must be an absolute path (got: $PREFIX)" ;;+esac+PREFIX="${PREFIX%/}"+# Resolved like install-local.sh does (`..`, symlinks), so what is removed is+# what was installed and never anything of the released Cua Spaces.+APP_PARENT="$(canonicalize_path "$PREFIX/Applications")" || die "cannot resolve $PREFIX/Applications (a symlink loop?)"+BIN_DIR="$(canonicalize_path "$PREFIX/.local/bin")" || die "cannot resolve $PREFIX/.local/bin (a symlink loop?)"+APP_DEST="$APP_PARENT/$LOCAL_APP_DIR_NAME"+CLI_LINK="$BIN_DIR/$LOCAL_CLI_NAME"+LOCAL_HOME="$HOME/$LOCAL_HOME_DIR_NAME"+LOCAL_APP_SUPPORT="$HOME/Library/Application Support/$LOCAL_APP_SUPPORT_DIR_NAME"+HOST_JOB_PLIST="$HOME/Library/LaunchAgents/$LOCAL_HOST_LABEL.plist"+LUME_UNINSTALL="$REPO_ROOT/libs/lume/scripts/uninstall-local.sh"+GUI_DOMAIN="gui/$(id -u)"++# Every path this script removes has a Local name; these are the checks that+# keep a bad prefix or HOME from aiming it elsewhere.+[ "$(basename "$APP_DEST")" = "$LOCAL_APP_DIR_NAME" ] || die "internal error: app path $APP_DEST"+[ "$(basename "$CLI_LINK")" = "$LOCAL_CLI_NAME" ] || die "internal error: CLI path $CLI_LINK"+[ "$(basename "$LOCAL_HOME")" = "$LOCAL_HOME_DIR_NAME" ] || die "internal error: home $LOCAL_HOME"+reject_stable_overlap "app" "$APP_DEST" || exit 1+reject_stable_overlap "$LOCAL_CLI_NAME link" "$CLI_LINK" || exit 1++# Refuse before changing anything.+require_local_bundle_or_absent "$APP_DEST" || exit 1++# Is lume-local present, and may its uninstaller be called?+lume_local_present() {+ [ -e "$PREFIX/.local/bin/$LOCAL_LUME_BIN_NAME" ] || [ -L "$PREFIX/.local/bin/$LOCAL_LUME_BIN_NAME" ] \+ || [ -d "$HOME/$LOCAL_LUME_DIR_NAME" ]+}++confirm() {+ local reply+ printf '%s [y/N] ' "$1"+ read -r reply || reply=""+ case "$reply" in y|Y|yes|YES) return 0 ;; *) return 1 ;; esac+}++echo "This removes Cua Spaces Local. The released Cua Spaces, ~/.cua, ~/.local/bin/cua and ~/.lume are not touched."+echo " helper login item: $LOCAL_HELPER_LABEL"+echo " app: $APP_DEST"+echo " CLI: $CLI_LINK"+echo " state: $LOCAL_HOME and $LOCAL_APP_SUPPORT"+echo " Keychain items: ${LOCAL_KEYCHAIN_SERVICES[*]}"+if [ "$YES" != 1 ]; then+ confirm "Remove them?" || { log "cancelled, nothing was removed"; exit 0; }+fi++REMOVE_LUME=0+if [ "$WITH_LUME_LOCAL" = 1 ]; then+ REMOVE_LUME=1+elif [ "$YES" != 1 ] && lume_local_present; then+ confirm "Also remove $LOCAL_LUME_BIN_NAME and its VMs in ~/$LOCAL_LUME_DIR_NAME?" && REMOVE_LUME=1+fi++# --- The helper login item and the host runner ------------------------------------++# Only this bundle's own code may unregister its login item, so ask the app+# (the same call the host setup makes). Without the app, stop the job.+if [ -x "$APP_DEST/Contents/MacOS/CuaSpacesMac" ]; then+ log "unregistering the helper login item"+ CUA_CHANNEL=local "$APP_DEST/Contents/MacOS/CuaSpacesMac" --service-helper unregister >/dev/null 2>&1 \+ || warn "the app could not unregister its helper; remove $LOCAL_APP_DIR_NAME from System Settings > Login Items if it stays."+fi+quit_local_app "$APP_DEST"+launchctl bootout "$GUI_DOMAIN/$LOCAL_HELPER_LABEL" >/dev/null 2>&1 || true+# The plain runner (`cua host setup` without the app) has its own Local label.+launchctl bootout "$GUI_DOMAIN/$LOCAL_HOST_LABEL" >/dev/null 2>&1 || true+if [ -f "$HOST_JOB_PLIST" ]; then+ rm -f "$HOST_JOB_PLIST"+ log "removed $HOST_JOB_PLIST"+fi++# --- The app and the CLI ---------------------------------------------------------------++if [ -d "$APP_DEST" ]; then+ if [ -x "$LSREGISTER" ]; then+ "$LSREGISTER" -u "$APP_DEST" >/dev/null 2>&1 || true+ fi+ rm -rf "$APP_DEST"+ log "removed $APP_DEST"+fi+# A backup left by an interrupted install of the Local app.+for backup in "$APP_DEST".install-backup.*; do+ [ -d "$backup" ] || continue+ rm -rf "$backup"+ log "removed $backup"+done++# `cua-local` is the Local CLI by name: the install links it into the bundle,+# the app's first run may copy it. Either way the name is Local's.+if [ -d "$CLI_LINK" ] && [ ! -L "$CLI_LINK" ]; then+ warn "$CLI_LINK is a directory; leaving it"+elif [ -e "$CLI_LINK" ] || [ -L "$CLI_LINK" ]; then+ rm -f "$CLI_LINK"+ log "removed $CLI_LINK"+fi++# --- State -------------------------------------------------------------------------------++if [ -d "$LOCAL_HOME" ] || [ -L "$LOCAL_HOME" ]; then+ rm -rf "$LOCAL_HOME"+ log "removed $LOCAL_HOME"+fi+if [ -d "$LOCAL_APP_SUPPORT" ]; then+ rm -rf "$LOCAL_APP_SUPPORT"+ log "removed $LOCAL_APP_SUPPORT"+fi++# The Keychain tool deletes one item per call and has no wildcard: repeat per+# service (one item per account) until none is left. Local services only.+if command -v security >/dev/null 2>&1; then+ for service in "${LOCAL_KEYCHAIN_SERVICES[@]}"; do+ removed=0+ while [ "$removed" -lt 50 ] && security delete-generic-password -s "$service" >/dev/null 2>&1; do+ removed=$((removed + 1))+ done+ [ "$removed" = 0 ] || log "removed $removed Keychain item(s) of $service"+ done+fi++# --- lume-local ----------------------------------------------------------------------------++if [ "$REMOVE_LUME" = 1 ]; then+ if [ ! -f "$LUME_UNINSTALL" ]; then+ warn "lume-local was not removed: this checkout has no libs/lume/scripts/uninstall-local.sh."+ elif ! grep -q "$LOCAL_LUME_BIN_NAME" "$LUME_UNINSTALL"; then+ warn "$LOCAL_LUME_BIN_NAME was not removed: $LUME_UNINSTALL does not know it."+ else+ log "removing lume-local"+ lume_args=()+ # Not asking twice: it was confirmed above.+ if grep -q -- '--yes' "$LUME_UNINSTALL"; then+ lume_args+=(--yes)+ elif grep -q -- '--force' "$LUME_UNINSTALL"; then+ lume_args+=(--force)+ fi+ /bin/bash "$LUME_UNINSTALL" ${lume_args[@]+"${lume_args[@]}"}+ fi+fi++echo ""+ok "Cua Spaces Local was removed; the released Cua Spaces was left untouched."+echo "Kept: ~/$LOCAL_VOLUME_NAME (your files) and the permissions macOS granted $LOCAL_BUNDLE_ID."diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lockindex 846c30d375..cd6857d3b9 100644--- a/apps/cua-spaces/src-tauri/Cargo.lock+++ b/apps/cua-spaces/src-tauri/Cargo.lock@@ -1710,6 +1710,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",diff --git a/apps/cua-spaces/src-tauri/src/installer.rs b/apps/cua-spaces/src-tauri/src/installer.rsindex 2a5395f54e..a4549428c0 100644--- a/apps/cua-spaces/src-tauri/src/installer.rs+++ b/apps/cua-spaces/src-tauri/src/installer.rs@@ -449,7 +449,7 @@ impl InstallerCommands {} else {cli.bundled.clone()- .or_else(|| first_on_path(&cli.path_env, cli_file_name()))+ .or_else(|| first_on_path(&cli.path_env, &cli.installed_name()))};let agents: Arc<dyn AgentSetupBackend> = Arc::new(SdkAgentSetup::new(cua_agent_setup::AgentSetup::from_env(),diff --git a/apps/cua-spaces/src-tauri/tests/installer_commands.rs b/apps/cua-spaces/src-tauri/tests/installer_commands.rsindex a924c8a8f1..0dbeebb50c 100644--- a/apps/cua-spaces/src-tauri/tests/installer_commands.rs+++ b/apps/cua-spaces/src-tauri/tests/installer_commands.rs@@ -12,11 +12,12 @@ use std::sync::{Arc, Mutex};use async_trait::async_trait;use cua_spaces_lib::installer::{AgentDetectReport, AgentInfo, AgentSetupBackend, AgentSetupReport, AgentSetupRequest,- CliAgentSetup, CliInstallRequest, CliInstaller, InstallMethod, InstallerCommands,+ CliAgentSetup, CliInstallRequest, CliInstaller, CuaChannel, InstallMethod, InstallerCommands,};fn installer(dir: &Path, bundled: Option<PathBuf>, path_env: &str, symlink: bool) -> CliInstaller {CliInstaller {+ channel: CuaChannel::Stable,bundled,bin_dir: dir.join("home/.local/bin"),path_env: path_env.to_string(),diff --git a/docs/content/docs/cua-sdk/guides/spacesd.mdx b/docs/content/docs/cua-sdk/guides/spacesd.mdxindex ff9e4ae3b3..d353daba6b 100644--- a/docs/content/docs/cua-sdk/guides/spacesd.mdx+++ b/docs/content/docs/cua-sdk/guides/spacesd.mdx@@ -59,6 +59,7 @@ cua-spacesd --print-config # effective config, never the token| `--listen` | `CUA_ENV_LISTEN` | `0.0.0.0:<port>` with a token, `127.0.0.1:<port>` without || `--port` | `CUA_ENV_PORT` | `3211` (gRPC, gRPC-Web and HTTP routes) || `--quic-port` | `CUA_ENV_QUIC_PORT` | `3212` (QUIC media; `0` disables it) |+| `--mesh-udp-port` | `CUA_ENV_MESH_UDP_PORT` | `3212` (the mesh port that reaches QUIC media; peers dial the same number) || `--token-file` | `CUA_ENV_TOKEN_FILE` | `/run/cua/env-token` || `--data-dir` | `CUA_ENV_DATA_DIR` | `~/.cua/spacesd` || `--downloads-dir` | `CUA_ENV_DOWNLOADS_DIR` | `~/Downloads` (teleport destination) |diff --git a/docs/content/docs/cua-sdk/reference/agent-setup.mdx b/docs/content/docs/cua-sdk/reference/agent-setup.mdxindex f286e9b372..9bcbae910c 100644--- a/docs/content/docs/cua-sdk/reference/agent-setup.mdx+++ b/docs/content/docs/cua-sdk/reference/agent-setup.mdx@@ -22,7 +22,7 @@ Returned by [`Cua.agent_setup`](/cua-sdk/reference/cua#cua).| Method | Description || --- | --- |-| [`configure_mcp`](#agentsetupconfigure_mcp) | Configures the MCP server (default: `cua mcp`, `cua` resolved on PATH) for `agents`. |+| [`configure_mcp`](#agentsetupconfigure_mcp) | Configures the MCP server (default: `cua mcp`, `cua` resolved on PATH; `cua-local mcp` named `cua-local` for the Local app) for `agents`. || [`install_skills`](#agentsetupinstall_skills) | Installs `skills` (empty: all bundled) for `agents`. || [`remove`](#agentsetupremove) | Removes what cua added for `agents` (skills and/or MCP). || [`select`](#agentsetupselect) | Resolves `all` (installed agents), `none` or `claude,codex` to ids. |@@ -41,7 +41,8 @@ Returned by [`Cua.agent_setup`](/cua-sdk/reference/cua#cua).### `AgentSetup.configure_mcp`Configures the MCP server (default: `cua mcp`, `cua` resolved on-PATH) for `agents`.+PATH; `cua-local mcp` named `cua-local` for the Local app) for+`agents`. A server without a name gets the channel's.<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist><Tab value="Python">diff --git a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lockindex f4ee80e6e0..3dc576b513 100644--- a/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock+++ b/examples/openkoalabot-example-tauri/src-tauri/Cargo.lock@@ -1701,6 +1701,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lockindex 914f78e7ed..1fe685db73 100644--- a/examples/streaming/rust/Cargo.lock+++ b/examples/streaming/rust/Cargo.lock@@ -1305,6 +1305,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",diff --git a/libs/cua-spacesd/README.md b/libs/cua-spacesd/README.mdindex 22dfb99b5f..229f1e9068 100644--- a/libs/cua-spacesd/README.md+++ b/libs/cua-spacesd/README.md@@ -38,6 +38,7 @@ cua-spacesd --help| Listen address | `--listen` / `CUA_ENV_LISTEN` | `0.0.0.0:3211` with a token, `127.0.0.1:3211` without || Port | `--port` / `CUA_ENV_PORT` | `3211` || QUIC media port | `--quic-port` / `CUA_ENV_QUIC_PORT` | `3212` (`0` disables QUIC) |+| Mesh media port | `--mesh-udp-port` / `CUA_ENV_MESH_UDP_PORT` | `3212` (the port of the mesh's own network that reaches the QUIC media port; peers dial the same number) || Token | `CUA_ENV_TOKEN`, `--token-file` / `CUA_ENV_TOKEN_FILE`, `--token` | `/run/cua/env-token` || Data directory | `--data-dir` / `CUA_ENV_DATA_DIR` | per-user state directory || Teleport destination | `--downloads-dir` / `CUA_ENV_DOWNLOADS_DIR` | `~/Downloads` |diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.mdindex 050f1b43d7..a49ea5a34a 100644--- a/libs/cua-spacesd/crates/cua-relay/README.md+++ b/libs/cua-spacesd/crates/cua-relay/README.md@@ -100,7 +100,9 @@ signed with an in-process key it trusts next to the relay's (only onrequests carrying the per-forward session key the dialer chose), so thespacesd host policy decides as for relayed calls; a static machine splicesstreams unchanged (the env token rides inside WireGuard). Mesh UDP 3212-reaches the local QUIC media port.+(`--mesh-udp-port`) reaches the local QUIC media port; it is a port of the+mesh's own network, so another cua-spacesd on the same computer does not+compete for it.## Hosted-machine proxy transportdiff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/config.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/config.rsindex 2ba3b0561a..6455324fb4 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/config.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/config.rs@@ -12,6 +12,10 @@ use serde::Serialize;/// Default path of the token file.pub const DEFAULT_TOKEN_FILE: &str = "/run/cua/env-token";+/// Default mesh UDP port of the QUIC media listener+/// ([`cua_mesh::MEDIA_UDP_PORT`]).+pub const DEFAULT_MESH_UDP_PORT: u16 = cua_mesh::MEDIA_UDP_PORT;+/// Largest `bytes` payload accepted in one chunk message.pub const MAX_CHUNK_BYTES: u32 = 4 * 1024 * 1024;/// Largest encoded gRPC message accepted or sent.@@ -65,6 +69,12 @@ pub struct ServerConfig {/// UDP port of the direct QUIC media listener (0 = disabled). Reported in/// `SideChannels`; the listener itself belongs to the desktop provider.pub media_quic_port: u16,+ /// The mesh UDP port that reaches the QUIC media listener over the+ /// mesh ([`cua_mesh::MEDIA_UDP_PORT`], 3212 for every build, unless+ /// `--mesh-udp-port` overrides it). A port of the mesh's own network,+ /// not of the operating system; clients dial the same number+ /// (`cua_mesh::MeshConfig::media_udp_port`).+ pub mesh_udp_port: u16,/// Teleport destination root (default `~/Downloads`).pub downloads_dir: Option<PathBuf>,/// Home directory app-session imports land in (default `$HOME`).@@ -142,6 +152,7 @@ impl Default for ServerConfig {runtime_override: None,os_override: None,media_quic_port: 0,+ mesh_udp_port: DEFAULT_MESH_UDP_PORT,downloads_dir: None,teleport_home: None,teleport_ledger_dir: None,diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rsindex e9b4405d45..416cfa452d 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs@@ -654,6 +654,7 @@ impl ServerContext {dir: self.config().data_dir.join("mesh"),local: std::net::SocketAddr::new(ip, local.port()),quic: (quic_port != 0).then(|| std::net::SocketAddr::new(ip, quic_port)),+ media_udp_port: self.config().mesh_udp_port,account,env_token: Arc::new(move || auth.token().map(|t| t.to_string())),name: cua_mesh::node::hostname(),@@ -741,6 +742,32 @@ mod tests {assert!(!off.cursor_probe());}+ #[test]+ fn the_mesh_media_port_follows_the_config() {+ let host = |ctx: &ServerContext| {+ ctx.mesh_host_config(+ "https://relay.example",+ "token",+ None,+ "machine-1",+ Arc::default(),+ "127.0.0.1:3211".parse().unwrap(),+ )+ };+ // Unset: the port every release has used.+ let ctx = ServerContext::new(ServerConfig::default(), None);+ assert_eq!(host(&ctx).media_udp_port, 3212);+ // An override (`--mesh-udp-port`) reaches the mesh node.+ let local = ServerContext::new(+ ServerConfig {+ mesh_udp_port: 3222,+ ..ServerConfig::default()+ },+ None,+ );+ assert_eq!(host(&local).media_udp_port, 3222);+ }+#[test]fn audio_uplink_policy_follows_init() {let ctx = ServerContext::new(ServerConfig::default(), None);diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/mesh_host.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/mesh_host.rsindex e24b8afbba..eca064e380 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/mesh_host.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/mesh_host.rs@@ -22,8 +22,11 @@//! remembers them, and filters the relay's map to its own approvals.//! Streams are spliced to spacesd unchanged: the env token still travels//! in each request, now inside WireGuard.-//! - **QUIC media.** Mesh UDP [`cua_mesh::MEDIA_UDP_PORT`] reaches the-//! local QUIC media port, so QUIC streaming works over the mesh.+//! - **QUIC media.** Mesh UDP [`MeshHostConfig::media_udp_port`]+//! ([`cua_mesh::MEDIA_UDP_PORT`], 3212, unless `--mesh-udp-port` says+//! otherwise) reaches the local QUIC media port, so QUIC streaming works+//! over the mesh. It is a port of the mesh's own network, not of the+//! operating system.//! - **Metering (account machines).** The relay meters sessions on its//! HTTPS path itself; mesh traffic never passes it in the clear, so this//! node tells it which peers hold streams open (requests in flight,@@ -239,6 +242,9 @@ pub struct MeshHostConfig {pub local: SocketAddr,/// The local QUIC media port, if QUIC runs.pub quic: Option<SocketAddr>,+ /// The mesh UDP port that reaches [`Self::quic`]+ /// ([`cua_mesh::MEDIA_UDP_PORT`] by default).+ pub media_udp_port: u16,/// Account details learned on the relay handshake.pub account: Arc<AccountLink>,/// The env token, for static-mode pairing proofs.@@ -462,7 +468,7 @@ async fn start(cfg: &MeshHostConfig) -> cua_mesh::Result<Mesh> {}));let mesh = Mesh::start(mc).await?;if let Some(quic) = cfg.quic {- mesh.serve_udp(cua_mesh::MEDIA_UDP_PORT, quic)?;+ mesh.serve_udp(cfg.media_udp_port, quic)?;}Ok(mesh)}diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/gang_mesh_e2e.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/gang_mesh_e2e.rsindex ac25548e91..45a8e8062a 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/gang_mesh_e2e.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/gang_mesh_e2e.rs@@ -149,6 +149,7 @@ impl World {dir: home.join("spacesd").join("mesh"),local,quic: None,+ media_udp_port: cua_mesh::MEDIA_UDP_PORT,account,env_token: Arc::new(|| None),name: id.to_owned(),diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gang.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gang.rsindex 12bbb21cea..e873269862 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gang.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gang.rs@@ -114,6 +114,7 @@ impl World {dir: home.join("spacesd").join("mesh"),local,quic: None,+ media_udp_port: cua_mesh::MEDIA_UDP_PORT,account,env_token: Arc::new(|| None),name: id.to_owned(),diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gate.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gate.rsindex 13367e19cb..21282cb7fb 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gate.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gate.rs@@ -53,6 +53,7 @@ fn config(relay: &str, dir: &std::path::Path, on: Arc<AtomicBool>) -> MeshHostCodir: dir.join("mesh"),local: "127.0.0.1:9".parse().unwrap(),quic: None,+ media_udp_port: cua_mesh::MEDIA_UDP_PORT,account: Arc::default(),env_token: Arc::new(|| None),name: "test".into(),diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_metering.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_metering.rsindex 0e91af3eeb..e3c92928d4 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_metering.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_metering.rs@@ -140,6 +140,7 @@ impl World {dir: dir.path().to_owned(),local,quic: Some(media),+ media_udp_port: cua_mesh::MEDIA_UDP_PORT,account,env_token: Arc::new(|| None),name: id.to_owned(),diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs b/libs/cua-spacesd/crates/cua-spacesd/src/main.rsindex 746fba642a..07b146a00d 100644--- a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs+++ b/libs/cua-spacesd/crates/cua-spacesd/src/main.rs@@ -189,6 +189,13 @@ struct ServeArgs {/// address (0 = no QUIC; media stays on the /media WebSocket).#[arg(long, env = "CUA_ENV_QUIC_PORT", default_value_t = cua_proto::SPACESD_DEFAULT_QUIC_PORT)]quic_port: u16,+ /// Mesh UDP port that reaches the QUIC media listener over the mesh+ /// (`join`, when the relay coordinates a mesh). Peers dial the same+ /// number, so leave it at the default unless every peer is told too.+ /// A port of the mesh's own network, not of the operating system, so+ /// two hosts on one machine do not compete for it.+ #[arg(long, env = "CUA_ENV_MESH_UDP_PORT", default_value_t = config::DEFAULT_MESH_UDP_PORT)]+ mesh_udp_port: u16,/// Default per-process scrollback in bytes.#[arg(long, env = "CUA_ENV_SCROLLBACK_BYTES", default_value_t = config::DEFAULT_SCROLLBACK_BYTES)]scrollback_bytes: u64,@@ -610,6 +617,7 @@ fn build_config(allow_guest_power: args.allow_guest_power,runtime_override: args.runtime.clone(),media_quic_port: args.quic_port,+ mesh_udp_port: args.mesh_udp_port,downloads_dir: args.downloads_dir.clone(),force_poll_watcher: args.poll_watcher,cursor_probe: args.cursor_probe,@@ -670,6 +678,7 @@ fn build_await_config(allow_guest_power: args.allow_guest_power,runtime_override: args.runtime.clone(),media_quic_port: args.quic_port,+ mesh_udp_port: args.mesh_udp_port,downloads_dir: args.downloads_dir.clone(),force_poll_watcher: args.poll_watcher,cursor_probe: args.cursor_probe,@@ -1303,6 +1312,72 @@ mod tests {assert!(cli.serve.print_config);}+ /// Cua Spaces Local runs its host next to a Stable one: its ports come+ /// from flags, and the defaults stay what every release has used.+ #[test]+ fn the_ports_follow_the_flags_and_default_to_3211_3212_3212() {+ let dir = tempfile::tempdir().unwrap();+ let token_file = dir.path().join("env-token");+ let token_file = token_file.to_str().unwrap();+ let (config, _) =+ build_config(&parse(&["--token-file", token_file]).serve, false, None).unwrap();+ assert_eq!(config.listen.port(), 3211);+ assert_eq!(config.media_quic_port, 3212);+ assert_eq!(config.mesh_udp_port, 3212);+ assert_eq!(+ serde_json::to_value(&config).unwrap()["mesh_udp_port"],+ 3212,+ "--print-config shows it"+ );++ let local = parse(&[+ "--token-file",+ token_file,+ "--port",+ "3221",+ "--quic-port",+ "3222",+ "--mesh-udp-port",+ "3222",+ ]);+ assert_eq!(local.serve.mesh_udp_port, 3222);+ let (config, _) = build_config(&local.serve, false, None).unwrap();+ assert_eq!(config.listen.port(), 3221);+ assert_eq!(config.media_quic_port, 3222);+ assert_eq!(config.mesh_udp_port, 3222);++ // The same flags on `join` (what the host service runs), and in+ // await-token-file mode.+ let cli = parse(&[+ "join",+ "--relay",+ "wss://relay.example",+ "--relay-token",+ "r",+ "--token-file",+ token_file,+ "--mesh-udp-port",+ "3222",+ ]);+ let Some(Command::Join(join)) = cli.command else {+ panic!("not join")+ };+ let (config, _) = build_config(&join.serve, true, None).unwrap();+ assert_eq!(config.mesh_udp_port, 3222);+ let args = parse(&[+ "--await-token-file",+ "--token-file",+ token_file,+ "--mesh-udp-port",+ "3222",+ ])+ .serve;+ let (config, _) = build_await_config(&args, false, None).unwrap();+ assert_eq!(config.mesh_udp_port, 3222);++ assert!(Cli::try_parse_from(["cua-spacesd", "--mesh-udp-port", "no"]).is_err());+ }+#[test]fn join_binds_loopback_with_a_token() {let dir = tempfile::tempdir().unwrap();diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lockindex a97c55d5fa..240b7d1743 100644--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock@@ -2056,6 +2056,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lockindex f8417fa7f9..864a95140b 100644--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock@@ -1335,6 +1335,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex 854c61b01c..7272da22a3 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2299,6 +2299,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",@@ -3520,6 +3521,7 @@ dependencies = ["reqwest 0.12.28","serde","serde_json",+ "serde_yaml_ng","sha2 0.10.9","tar","tempfile",diff --git a/libs/cua/crates/cua-agent-setup/Cargo.toml b/libs/cua/crates/cua-agent-setup/Cargo.tomlindex 40e427e7b4..a7d7c0da15 100644--- a/libs/cua/crates/cua-agent-setup/Cargo.toml+++ b/libs/cua/crates/cua-agent-setup/Cargo.toml@@ -9,6 +9,8 @@ license.workspace = truerepository.workspace = true[dependencies]+# The channel (Stable, Local) names the MCP server, the skills and the state folder.+cua-home.workspace = trueserde.workspace = trueserde_json.workspace = truethiserror.workspace = truediff --git a/libs/cua/crates/cua-agent-setup/src/lib.rs b/libs/cua/crates/cua-agent-setup/src/lib.rsindex 2aa0aaa806..a7fde08100 100644--- a/libs/cua/crates/cua-agent-setup/src/lib.rs+++ b/libs/cua/crates/cua-agent-setup/src/lib.rs@@ -22,6 +22,7 @@ pub mod registry;pub mod skills;mod state;+pub use cua_home::channel::CuaChannel;pub use edit::Format;pub use fsutil::hash_dir;pub use registry::{AGENTS, AgentSpec};@@ -135,6 +136,11 @@ pub struct HostEnv {/// Whether an agent's own CLI may be run to write its config/// ([`registry::OwnerCli`]). Off for isolated environments.pub run_agent_clis: bool,+ /// Which Cua Spaces build this runs for. It names what is written into+ /// the agents' configs (the MCP server `cua` or `cua-local`, the skills+ /// `cua-spaces` or `cua-spaces-local`) and the folder of the state+ /// (`~/.cua` or `~/.cua-local`), so Local never replaces Stable's.+ pub channel: CuaChannel,}const VARS: &[&str] = &[@@ -215,6 +221,7 @@ impl HostEnv {app_dirs,os,run_agent_clis: true,+ channel: CuaChannel::current(),};// A GUI app (Cua Spaces from the Dock) runs without the user's// shell PATH, so an agent installed under a user bin dir would look@@ -249,9 +256,16 @@ impl HostEnv {path: vec![],os: Os::current(),run_agent_clis: false,+ channel: CuaChannel::Stable,}}+ /// This environment for `channel` (a Local app's, in tests).+ pub fn with_channel(mut self, channel: CuaChannel) -> Self {+ self.channel = channel;+ self+ }+/// A non-empty variable.pub fn var(&self, k: &str) -> Option<&str> {self.vars@@ -278,11 +292,12 @@ impl HostEnv {None}- /// `~/.cua` (or `$CUA_HOME`).+ /// `$CUA_HOME`, else the channel's home: `~/.cua`, or `~/.cua-local` for+ /// Local ([`CuaChannel::home_dir_name`]).pub fn cua_home(&self) -> PathBuf {self.var("CUA_HOME").map(PathBuf::from)- .unwrap_or_else(|| self.home.join(".cua"))+ .unwrap_or_else(|| self.home.join(self.channel.home_dir_name()))}}@@ -345,14 +360,25 @@ impl McpServer {self}- /// `cua mcp`, with `cua` resolved to an absolute path on `env`'s PATH- /// (GUI agents often run without the user's shell PATH), else `cua`.+ /// `command mcp` under the name the channel registers: `cua`, or+ /// `cua-local` for Local ([`CuaChannel::mcp_server_name`]).+ pub fn for_channel(channel: CuaChannel, command: impl Into<String>) -> Self {+ McpServer {+ name: channel.mcp_server_name().into(),+ ..McpServer::new(command)+ }+ }++ /// `cua mcp` (`cua-local mcp` for Local), with the channel's CLI+ /// resolved to an absolute path on `env`'s PATH (GUI agents often run+ /// without the user's shell PATH), else its bare name.pub fn default_for(env: &HostEnv) -> Self {+ let cli = env.channel.cli_name();let cmd = env- .which("cua")+ .which(cli).map(|p| p.display().to_string())- .unwrap_or_else(|| "cua".into());- McpServer::new(cmd)+ .unwrap_or_else(|| cli.into());+ McpServer::for_channel(env.channel, cmd)}}@@ -387,11 +413,20 @@ impl McpServer {}}-/// Whether a launch command is a cua binary (`cua`, `/x/bin/cua`,-/// `cua.exe`).-fn is_cua_command(cmd: &str) -> bool {+/// Whether a launch command is the channel's cua binary: for Stable `cua`,+/// `/x/bin/cua`, `cua.exe`; for Local `cua-local` (`cua-local.exe`), or the+/// `cua` inside `Cua Spaces Local.app`. A Stable `cua` is not Local's, and+/// the reverse.+fn is_cua_command(cmd: &str, channel: CuaChannel) -> bool {let base = cmd.rsplit(['/', '\\']).next().unwrap_or(cmd);- base == "cua" || base == "cua.exe"+ match channel {+ CuaChannel::Stable => base == "cua" || base == "cua.exe",+ CuaChannel::Local => {+ base == "cua-local"+ || base == "cua-local.exe"+ || CuaChannel::path_is_local(Path::new(cmd))+ }+ }}/// Detection result for one agent.@@ -532,9 +567,10 @@ impl AgentSetup {&self.state_path}- /// The bundled default skills.+ /// The bundled default skills, as this channel installs them (Local's+ /// carry `-local` names: [`CuaChannel::skill_install_name`]).pub fn bundled_skills(&self) -> Vec<Skill> {- skills::bundled()+ skills::bundled_for(self.env.channel)}/// Resolves an agent selection: `all` (installed agents), `none`, or a@@ -588,7 +624,7 @@ impl AgentSetup {/// Detects every registry agent (read-only).pub fn detect(&self) -> Vec<AgentStatus> {let state = State::load(&self.state_path).unwrap_or_default();- let bundled = skills::bundled();+ let bundled = self.bundled_skills();AGENTS.iter().map(|a| self.detect_one(a, &state, &bundled))@@ -725,15 +761,16 @@ impl AgentSetup {if let Some(m) = &a.mcp {let file = self.mcp_file(m);status.mcp_format = Some(m.format);- match read_text(&file)- .and_then(|t| edit::get(m.format, &file, &t, m.key_path, MCP_SERVER_NAME))- {+ // The channel's own entry (`cua`, or `cua-local`): Local never+ // reads Stable's as its own.+ let name = self.env.channel.mcp_server_name();+ match read_text(&file).and_then(|t| edit::get(m.format, &file, &t, m.key_path, name)) {Ok(Some(v)) => {status.cua_configured = m.shape.command_of(&v)- .is_some_and(|(c, _)| is_cua_command(&c));- status.cua_managed = state.mcp.get(&file).is_some_and(|r| r.value == v);+ .is_some_and(|(c, _)| is_cua_command(&c, self.env.channel));+ status.cua_managed = state.record(name, &file).is_some_and(|r| r.value == v);}Ok(None) => {}Err(e) => status.error = Some(e.to_string()),@@ -757,16 +794,18 @@ impl AgentSetup {force: bool,) -> Result<Vec<Outcome>> {let specs = self.specs(agents)?;- let bundled = skills::bundled();+ let bundled = self.bundled_skills();let wanted: Vec<&Skill> = if skill_names.is_empty() {bundled.iter().collect()} else {skill_names.iter().map(|n| {+ // By the bundled name (`cua-spaces`) or the name this+ // channel installs it under (`cua-spaces-local`).bundled.iter()- .find(|s| &s.name == n)+ .find(|s| &s.name == n || &s.source == n).ok_or_else(|| Error::InvalidArgument(format!("unknown skill {n:?}")))}).collect::<Result<_>>()?@@ -873,7 +912,7 @@ impl AgentSetup {}o.backup = Some(bak);}- if let Err(e) = skills::write_to(&s.name, dest) {+ if let Err(e) = skills::write_for(self.env.channel, &s.source, dest) {o.change = Change::Failed;o.detail = e.to_string();return o;@@ -937,7 +976,10 @@ impl AgentSetup {o.detail = e.to_string();}out.push(o);- if server.name != LEGACY_SPACES_MCP_NAME {+ // The old entry is the released app's to clean up. Local never+ // wrote it, and removing it would break a Stable setup that+ // still has it.+ if server.name != LEGACY_SPACES_MCP_NAME && self.env.channel == CuaChannel::Stable {out.extend(self.drop_legacy_spaces_mcp(&mut state, a, m, &file));}}@@ -1041,7 +1083,7 @@ impl AgentSetup {None => existing.clone().filter(|v| {!m.shape.command_of(v)- .is_some_and(|(c, _)| is_cua_command(&c))+ .is_some_and(|(c, _)| is_cua_command(&c, self.env.channel))}),};if existing.as_ref() == Some(&want) {@@ -1116,11 +1158,13 @@ impl AgentSetup {for a in &specs {let Some(m) = &a.mcp else { continue };let file = self.mcp_file(m);- // `cua` always gets a row; other servers (`cua-driver`) only- // when cua registered them there.+ // The channel's server (`cua`, or `cua-local`) always gets a+ // row; other servers (`cua-driver`) only when cua registered+ // them there.let mut names = state.names_in(&file);- if !state.mcp.contains_key(&file) {- names.insert(0, MCP_SERVER_NAME.to_string());+ let own = self.env.channel.mcp_server_name();+ if state.record(own, &file).is_none() {+ names.insert(0, own.to_string());}for name in names {let mut o = Outcome {@@ -1327,9 +1371,10 @@ impl AgentSetup {.into_iter().filter(|a| registry::find(a).is_some()).collect();+ let bundled = self.bundled_skills();let names: Vec<String> = names.into_iter()- .filter(|n| skills::get(n).is_some())+ .filter(|n| bundled.iter().any(|s| &s.name == n)).collect();if known.is_empty() || names.is_empty() {continue;@@ -1338,8 +1383,9 @@ impl AgentSetup {}if let Some(server) = server {let agents: Vec<String> = state- .mcp- .values()+ .records(&server.name)+ .into_iter()+ .flat_map(|r| r.values()).flat_map(|r| r.agents.iter().cloned()).filter(|a| registry::find(a).is_some()).collect::<BTreeSet<_>>()@@ -1353,7 +1399,7 @@ impl AgentSetup {let current = edit::get(m.format, &file, &text, m.key_path, &server.name).ok().flatten();- let recorded = state.mcp.get(&file).map(|r| r.value.clone());+ let recorded = state.record(&server.name, &file).map(|r| r.value.clone());if current.is_some() && current == recorded {out.extend(self.configure_mcp(&[a], server)?);}diff --git a/libs/cua/crates/cua-agent-setup/src/skills.rs b/libs/cua/crates/cua-agent-setup/src/skills.rsindex 35c2cc2c1e..d17334f36c 100644--- a/libs/cua/crates/cua-agent-setup/src/skills.rs+++ b/libs/cua/crates/cua-agent-setup/src/skills.rs@@ -3,6 +3,7 @@//! `description` front matter, plus optional reference files).use crate::{Error, Result, fsutil};+use cua_home::channel::CuaChannel;use include_dir::{Dir, include_dir};use sha2::{Digest, Sha256};use std::path::Path;@@ -12,8 +13,14 @@ static BUNDLED: Dir<'_> = include_dir!("$OUT_DIR/skills");/// One bundled skill.#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]pub struct Skill {- /// Folder name (and front matter `name`).+ /// Folder name (and front matter `name`) it is installed under: the+ /// bundled name for Stable (`cua-spaces`), the channel's for Local+ /// (`cua-spaces-local`, [`CuaChannel::skill_install_name`]).pub name: String,+ /// The bundled folder it comes from (`cua-spaces`): [`write_for`] and+ /// [`files`] take this name, whatever the channel installs it as.+ #[serde(skip)]+ pub source: String,/// Front matter `description`.pub description: String,/// Front matter `version`, or the cua version.@@ -37,6 +44,7 @@ pub fn bundled() -> Vec<Skill> {}let files = files_of(d);Some(Skill {+ source: name.clone(),name,description,version: version.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string()),@@ -54,6 +62,132 @@ pub fn get(name: &str) -> Option<Skill> {bundled().into_iter().find(|s| s.name == name)}+/// The note Local's copy of a skill opens with.+const LOCAL_NOTE: &str = "> This is the Cua Spaces Local copy of this skill. Where it says to run `cua`, run `cua-local` instead, and the MCP server is `cua-local`. The released Cua Spaces and its skills are not touched.";++/// Every bundled skill as `channel` installs it, sorted by name. Stable's+/// are the bundled ones. Local's sit beside them under `-local` names, with+/// that name in their `SKILL.md`, a note that says to use `cua-local`, and+/// the hash of that content: installing them never replaces Stable's.+pub fn bundled_for(channel: CuaChannel) -> Vec<Skill> {+ let mut out = bundled();+ if channel == CuaChannel::Stable {+ return out;+ }+ for s in &mut out {+ let d = BUNDLED.get_dir(&s.source).expect("a bundled skill");+ let name = channel.skill_install_name(&s.source);+ s.hash = hash_of(&rendered(channel, &s.source, d));+ s.name = name;+ }+ out.sort_by(|a, b| a.name.cmp(&b.name));+ out+}++/// A skill's files as `channel` installs them: (relative path, contents).+/// For Stable the bundled bytes; for Local `SKILL.md` carries the Local name+/// and note ([`localize`]).+fn rendered(channel: CuaChannel, source: &str, d: &Dir<'_>) -> Vec<(String, Vec<u8>)> {+ files_of(d)+ .into_iter()+ .map(|f| {+ let rel = rel_path(d, f);+ let bytes = if channel != CuaChannel::Stable && rel == "SKILL.md" {+ match f.contents_utf8() {+ Some(md) => localize(md, &channel.skill_install_name(source)).into_bytes(),+ None => f.contents().to_vec(),+ }+ } else {+ f.contents().to_vec()+ };+ (rel, bytes)+ })+ .collect()+}++/// `md` (a `SKILL.md`) for Local: the front matter's `name` becomes+/// `install_name` and the note follows the front matter.+fn localize(md: &str, install_name: &str) -> String {+ let Some(rest) = md+ .strip_prefix("---\n")+ .or_else(|| md.strip_prefix("---\r\n"))+ else {+ return md.to_string();+ };+ let open = &md[..md.len() - rest.len()];+ let Some(end) = rest.find("\n---") else {+ return md.to_string();+ };+ let (fm, closing) = rest.split_at(end);+ let mut renamed = false;+ let fm: Vec<String> = fm+ .split('\n')+ .map(|line| {+ let bare = line.trim_end_matches('\r');+ if !renamed && bare.starts_with("name:") {+ renamed = true;+ let cr = &line[bare.len()..];+ format!("name: {install_name}{cr}")+ } else {+ line.to_string()+ }+ })+ .collect();+ // `closing` is "\n---" and the rest of that line; the body follows it.+ let line_end = closing[1..]+ .find('\n')+ .map(|i| i + 2)+ .unwrap_or(closing.len());+ let (closing, body) = closing.split_at(line_end);+ format!("{open}{}{closing}\n{LOCAL_NOTE}\n\n{body}", fm.join("\n"))+}++/// The tree hash of `files` (the scheme of `fsutil::hash_dir`).+fn hash_of(files: &[(String, Vec<u8>)]) -> String {+ let mut entries: Vec<(String, String)> = files+ .iter()+ .map(|(rel, bytes)| (rel.clone(), fsutil::sha256(bytes)))+ .collect();+ entries.sort();+ let mut h = Sha256::new();+ for (rel, sum) in entries {+ h.update(rel.as_bytes());+ h.update([0]);+ h.update(sum.as_bytes());+ h.update([0]);+ }+ hex::encode(h.finalize())+}++fn rel_path(d: &Dir<'_>, f: &include_dir::File<'_>) -> String {+ f.path()+ .strip_prefix(d.path())+ .unwrap_or(f.path())+ .components()+ .map(|c| c.as_os_str().to_string_lossy().to_string())+ .collect::<Vec<_>>()+ .join("/")+}++/// Writes the bundled skill `source` into `dest` as `channel` installs it+/// (see [`bundled_for`]); otherwise as [`write_to`].+pub fn write_for(channel: CuaChannel, source: &str, dest: &Path) -> Result<()> {+ let d = BUNDLED+ .get_dir(source)+ .ok_or_else(|| Error::InvalidArgument(format!("unknown skill {source:?}")))?;+ if dest.exists() {+ std::fs::remove_dir_all(dest).map_err(|e| Error::io(dest, e))?;+ }+ for (rel, bytes) in rendered(channel, source, d) {+ let p = dest.join(&rel);+ if let Some(parent) = p.parent() {+ std::fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;+ }+ std::fs::write(&p, bytes).map_err(|e| Error::io(&p, e))?;+ }+ Ok(())+}+/// Writes skill `name` into `dest` (created; files cua does not ship are/// removed first so an update never leaves stale references behind).pub fn write_to(name: &str, dest: &Path) -> Result<()> {@@ -243,6 +377,53 @@ mod tests {assert!(write_to("nope", &d.path().join("nope")).is_err());}+ #[test]+ fn local_copies_have_names_of_their_own_and_hash_like_what_is_written() {+ let stable = bundled_for(CuaChannel::Stable);+ assert_eq!(stable, bundled());+ let local = bundled_for(CuaChannel::Local);+ assert_eq!(local.len(), stable.len());+ let d = tempfile::tempdir().unwrap();+ for (l, s) in local.iter().zip(&stable) {+ assert_eq!(l.name, format!("{}-local", s.name));+ assert_eq!(l.source, s.name);+ assert_ne!(l.hash, s.hash, "{}", l.name);+ // Written under the Local name, with that name in SKILL.md, and+ // the tree hashes like the skill says (so it is "not edited").+ let dest = d.path().join(&l.name);+ write_for(CuaChannel::Local, &l.source, &dest).unwrap();+ assert_eq!(fsutil::hash_dir(&dest).unwrap(), l.hash, "{}", l.name);+ let md = std::fs::read_to_string(dest.join("SKILL.md")).unwrap();+ let (name, description, _) = front_matter(&md).unwrap();+ assert_eq!(name, l.name);+ assert_eq!(description, l.description);+ assert!(md.contains(LOCAL_NOTE) && !md.contains('\u{2014}'), "{md}");+ // Stable's copy is the bundled bytes, untouched.+ let stable_dest = d.path().join(&s.name);+ write_for(CuaChannel::Stable, &s.source, &stable_dest).unwrap();+ assert_eq!(fsutil::hash_dir(&stable_dest).unwrap(), s.hash);+ // Every other file is shared byte for byte.+ assert_eq!(l.files, s.files);+ }+ }++ #[test]+ fn localize_keeps_line_endings_and_the_rest_of_the_front_matter() {+ let md = "---\r\nname: a\r\ndescription: x\r\n---\r\n# A\r\n";+ let out = localize(md, "a-local");+ assert!(+ out.starts_with("---\r\nname: a-local\r\ndescription: x\r\n---\r\n"),+ "{out:?}"+ );+ assert!(+ out.ends_with("# A\r\n") && out.contains(LOCAL_NOTE),+ "{out:?}"+ );+ assert_eq!(front_matter(&out).unwrap().0, "a-local");+ // No front matter: left as it is.+ assert_eq!(localize("# plain", "x"), "# plain");+ }+#[test]fn front_matter_handles_folded_descriptions_and_comments() {let md = "---\nname: a\ndescription: >-\n one\n two\nversion: 1.2.3 # x-release\nmetadata:\n k: v\n---\nbody";diff --git a/libs/cua/crates/cua-agent-setup/tests/local_channel.rs b/libs/cua/crates/cua-agent-setup/tests/local_channel.rsnew file mode 100644index 0000000000..868af591b2--- /dev/null+++ b/libs/cua/crates/cua-agent-setup/tests/local_channel.rs@@ -0,0 +1,416 @@+//! Cua Spaces Local's agent setup beside Stable's, in one fake HOME (CUA-1776).+//!+//! The Local app's "Continue" on the welcome screen runs this engine. It must+//! register its own MCP server (`cua-local`, launching `cua-local`) and install+//! its own skill folders (`<name>-local`), keep its own state under+//! `~/.cua-local`, and leave everything Stable wrote byte for byte as it was.+//! Always in a temporary HOME, never the real one.++use cua_agent_setup::{+ AgentSetup, Change, CuaChannel, HostEnv, McpServer, Outcome, Parts, Target, hash_dir,+};+use serde_json::Value;+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++const STABLE_CUA: &str = "/Applications/Cua Spaces.app/Contents/MacOS/cua";+const AGENTS: [&str; 3] = ["claude-code", "codex", "cursor"];++struct Fixture {+ _dir: tempfile::TempDir,+ home: PathBuf,+}++impl Fixture {+ fn new() -> Self {+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path().join("home");+ std::fs::create_dir_all(&home).unwrap();+ // The user's own configs, with a server of theirs in each.+ write(+ &home,+ ".claude.json",+ "{\n \"numStartups\": 12,\n \"mcpServers\": {\n \"other\": {\"type\": \"stdio\", \"command\": \"other-mcp\", \"args\": []}\n }\n}\n",+ );+ write(+ &home,+ ".codex/config.toml",+ "# my codex config\n[mcp_servers.other]\ncommand = \"other-mcp\"\nargs = []\n",+ );+ write(+ &home,+ ".cursor/mcp.json",+ "{\n \"mcpServers\": {\n \"other\": {\"command\": \"other-mcp\"}\n }\n}\n",+ );+ Fixture { _dir: dir, home }+ }++ fn env(&self, channel: CuaChannel) -> HostEnv {+ HostEnv::isolated(&self.home).with_channel(channel)+ }++ fn setup(&self, channel: CuaChannel) -> AgentSetup {+ AgentSetup::new(self.env(channel))+ }++ fn read(&self, rel: &str) -> String {+ std::fs::read_to_string(self.home.join(rel)).unwrap()+ }++ /// What only Stable owns after its setup: its state file and its skill+ /// folders (as hashes). The agents' configs are shared by both channels,+ /// each with its own entry, so they are checked entry by entry.+ fn stable_files(&self) -> BTreeMap<String, String> {+ let mut out = BTreeMap::new();+ out.insert(+ ".cua/agent-setup.json".to_string(),+ self.read(".cua/agent-setup.json"),+ );+ for dir in [".claude/skills", ".agents/skills"] {+ let Ok(entries) = std::fs::read_dir(self.home.join(dir)) else {+ continue;+ };+ for e in entries.flatten() {+ let name = e.file_name().to_string_lossy().into_owned();+ if name.ends_with("-local") {+ continue;+ }+ out.insert(+ format!("{dir}/{name}"),+ hash_dir(&e.path()).unwrap_or_default(),+ );+ }+ }+ out+ }+}++fn write(home: &Path, rel: &str, text: &str) {+ let p = home.join(rel);+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(p, text).unwrap();+}++fn ids(v: &[&str]) -> Vec<String> {+ v.iter().map(|s| s.to_string()).collect()+}++fn items(out: &[Outcome], target: Target) -> Vec<String> {+ let mut v: Vec<String> = out+ .iter()+ .filter(|o| o.target == target)+ .map(|o| o.item.clone())+ .collect();+ v.sort();+ v.dedup();+ v+}++fn json(text: &str) -> Value {+ serde_json::from_str(text).unwrap()+}++/// A `cua-local` the way install-local.sh and the first run leave it:+/// executable, in `~/.local/bin`.+fn install_cua_local(home: &Path) -> PathBuf {+ let p = home.join(".local/bin/cua-local");+ write(home, ".local/bin/cua-local", "#!/bin/sh\n");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ p+}++#[test]+fn local_registers_cua_local_and_skills_of_its_own_and_leaves_stable_untouched() {+ let f = Fixture::new();+ let stable = f.setup(CuaChannel::Stable);+ stable+ .configure_mcp(&ids(&AGENTS), &McpServer::new(STABLE_CUA))+ .unwrap();+ stable.install_skills(&ids(&AGENTS), &[], false).unwrap();+ let before = f.stable_files();+ assert!(+ before.contains_key(".claude/skills/cua-spaces"),+ "{before:?}"+ );++ // Local, with the same agents and the same configs.+ let cua_local = install_cua_local(&f.home);+ let mut env = f.env(CuaChannel::Local);+ env.path.push(f.home.join(".local/bin"));+ let local = AgentSetup::new(env.clone());++ // Stable's `cua` entry is not Local's: nothing reads as configured yet.+ for a in local+ .detect()+ .iter()+ .filter(|a| AGENTS.contains(&a.id.as_str()))+ {+ assert!(!a.cua_configured && !a.cua_managed, "{}: {a:?}", a.id);+ assert!(a.skills_installed.is_empty(), "{}: {a:?}", a.id);+ }++ let server = McpServer::default_for(&env);+ assert_eq!(server.name, "cua-local");+ assert_eq!(server.command, cua_local.display().to_string());+ assert_eq!(server.args, ["mcp"]);++ let mcp = local.configure_mcp(&ids(&AGENTS), &server).unwrap();+ assert!(+ mcp.iter()+ .all(|o| o.item == "cua-local" && o.change == Change::Created),+ "{mcp:#?}"+ );+ let skills = local.install_skills(&ids(&AGENTS), &[], false).unwrap();+ assert!(+ skills.iter().all(|o| o.change == Change::Created),+ "{skills:#?}"+ );+ let installed = items(&skills, Target::Skill);+ assert!(!installed.is_empty());+ assert!(+ installed.iter().all(|n| n.ends_with("-local")),+ "{installed:?}"+ );+ assert_eq!(+ installed,+ local+ .bundled_skills()+ .into_iter()+ .map(|s| s.name)+ .collect::<Vec<_>>()+ );++ // The configs hold both entries, each launching its own binary.+ let claude = json(&f.read(".claude.json"));+ assert_eq!(claude["mcpServers"]["cua"]["command"], STABLE_CUA);+ assert_eq!(+ claude["mcpServers"]["cua-local"]["command"],+ cua_local.display().to_string()+ );+ assert_eq!(claude["mcpServers"]["cua-local"]["args"][0], "mcp");+ assert_eq!(claude["mcpServers"]["other"]["command"], "other-mcp");+ let codex = f.read(".codex/config.toml");+ assert!(codex.contains("[mcp_servers.cua]") && codex.contains(STABLE_CUA));+ assert!(codex.contains("[mcp_servers.cua-local]"), "{codex}");+ assert!(codex.contains("# my codex config"));+ let cursor = json(&f.read(".cursor/mcp.json"));+ assert_eq!(cursor["mcpServers"]["cua"]["command"], STABLE_CUA);+ assert!(cursor["mcpServers"]["cua-local"].is_object());++ // Local's skills have their own folder and name in SKILL.md; Stable's+ // folders are what they were.+ let md = f.read(".claude/skills/cua-spaces-local/SKILL.md");+ assert!(md.contains("name: cua-spaces-local"), "{md}");+ assert!(md.contains("cua-local"));+ assert!(f.home.join(".claude/skills/cua-spaces/SKILL.md").is_file());+ assert_eq!(f.stable_files(), before, "Stable's files changed");++ // Local's state is its own; Stable's file was not written.+ assert!(f.home.join(".cua-local/agent-setup.json").is_file());+ let state = json(&f.read(".cua-local/agent-setup.json"));+ assert!(state["servers"]["cua-local"].is_object(), "{state}");+ assert!(state["mcp"].as_object().is_none_or(|m| m.is_empty()));++ // Both read as configured, each by its own entry and skills.+ for a in local+ .detect()+ .iter()+ .filter(|a| AGENTS.contains(&a.id.as_str()))+ {+ assert!(a.cua_configured && a.cua_managed, "{}: {a:?}", a.id);+ assert_eq!(a.skills_installed.len(), local.bundled_skills().len());+ assert!(a.skills_outdated.is_empty(), "{}: {a:?}", a.id);+ }+ for a in stable+ .detect()+ .iter()+ .filter(|a| AGENTS.contains(&a.id.as_str()))+ {+ assert!(a.cua_configured && a.cua_managed, "{}: {a:?}", a.id);+ assert!(+ a.skills_installed.iter().all(|n| !n.ends_with("-local")),+ "{}: {a:?}",+ a.id+ );+ }++ // Idempotent, and an update keeps to Local's own copies.+ let again = local.configure_mcp(&ids(&AGENTS), &server).unwrap();+ assert!(+ again.iter().all(|o| o.change == Change::Unchanged),+ "{again:#?}"+ );+ let again = local.install_skills(&ids(&AGENTS), &[], false).unwrap();+ assert!(again.iter().all(|o| o.change == Change::Unchanged));+ let updated = local.update(Some(&server)).unwrap();+ assert!(+ updated.iter().all(|o| o.change == Change::Unchanged),+ "{updated:#?}"+ );+ assert_eq!(f.stable_files(), before);++ // Removing Local's setup removes Local's pieces and only those.+ let removed = local.remove(&ids(&AGENTS), Parts::ALL).unwrap();+ let gone = |t: Target| items(&removed, t);+ assert_eq!(gone(Target::Mcp), ["cua-local"], "{removed:#?}");+ assert!(+ removed+ .iter()+ .filter(|o| o.target == Target::Mcp)+ .all(|o| o.change == Change::Removed),+ "{removed:#?}"+ );+ assert!(!f.home.join(".claude/skills/cua-spaces-local").exists());+ let claude = json(&f.read(".claude.json"));+ assert!(claude["mcpServers"]["cua-local"].is_null());+ assert_eq!(claude["mcpServers"]["cua"]["command"], STABLE_CUA);+ assert_eq!(f.stable_files(), before, "removing Local changed Stable");++ // And Stable still removes its own.+ let out = stable.remove(&ids(&AGENTS), Parts::ALL).unwrap();+ assert!(+ out.iter()+ .filter(|o| o.target == Target::Mcp)+ .all(|o| o.item == "cua" && o.change == Change::Removed),+ "{out:#?}"+ );+ assert!(json(&f.read(".claude.json"))["mcpServers"]["cua"].is_null());+}++#[test]+fn a_stable_cua_entry_is_not_taken_over_or_removed_by_local() {+ let f = Fixture::new();+ // Stable's setup has run, then Local's state is asked to remove: it never+ // wrote anything, so it removes nothing.+ f.setup(CuaChannel::Stable)+ .configure_mcp(&ids(&["claude-code"]), &McpServer::new(STABLE_CUA))+ .unwrap();+ let before = f.read(".claude.json");+ let out = f+ .setup(CuaChannel::Local)+ .remove(&ids(&["claude-code"]), Parts::ALL)+ .unwrap();+ assert!(out.iter().all(|o| o.change != Change::Removed), "{out:#?}");+ assert_eq!(f.read(".claude.json"), before);+}++#[test]+fn local_without_a_cua_local_on_the_path_names_the_bare_command() {+ let f = Fixture::new();+ let env = f.env(CuaChannel::Local);+ let server = McpServer::default_for(&env);+ assert_eq!(+ (server.name.as_str(), server.command.as_str()),+ ("cua-local", "cua-local")+ );+ // A Stable environment is unchanged: `cua mcp`, named `cua`.+ let server = McpServer::default_for(&f.env(CuaChannel::Stable));+ assert_eq!(+ (server.name.as_str(), server.command.as_str()),+ ("cua", "cua")+ );+}++#[test]+fn local_recognises_its_own_binary_in_the_app_bundle_and_not_stables() {+ let f = Fixture::new();+ let local = f.setup(CuaChannel::Local);+ let bundled = "/Users/a/Applications/Cua Spaces Local.app/Contents/MacOS/cua";+ local+ .configure_mcp(+ &ids(&["claude-code"]),+ &McpServer::for_channel(CuaChannel::Local, bundled),+ )+ .unwrap();+ let a = local+ .detect()+ .into_iter()+ .find(|a| a.id == "claude-code")+ .unwrap();+ assert!(a.cua_configured && a.cua_managed, "{a:?}");++ // A `cua-local` entry that launches Stable's binary is not Local's.+ let f = Fixture::new();+ let local = f.setup(CuaChannel::Local);+ local+ .configure_mcp(+ &ids(&["claude-code"]),+ &McpServer::for_channel(CuaChannel::Local, STABLE_CUA),+ )+ .unwrap();+ let a = local+ .detect()+ .into_iter()+ .find(|a| a.id == "claude-code")+ .unwrap();+ assert!(!a.cua_configured, "{a:?}");+}++#[test]+fn the_state_folder_follows_the_channel_unless_cua_home_is_set() {+ let f = Fixture::new();+ assert_eq!(f.env(CuaChannel::Stable).cua_home(), f.home.join(".cua"));+ assert_eq!(+ f.env(CuaChannel::Local).cua_home(),+ f.home.join(".cua-local")+ );+ let mut env = f.env(CuaChannel::Local);+ env.vars.insert(+ "CUA_HOME".into(),+ f.home.join("pinned").display().to_string(),+ );+ assert_eq!(env.cua_home(), f.home.join("pinned"));+}++/// Stable's setup removes a stale `cua-spaces` entry that still launches the+/// retired `spaces_mcp.py`; that is the released app's cleanup. Local's setup+/// must leave it (and a user's own `cua-spaces`) exactly as it is.+#[test]+fn local_setup_leaves_stables_legacy_cua_spaces_entry_alone() {+ let f = Fixture::new();+ let legacy = r#"{"mcpServers": {"cua-spaces": {"command": "python3", "args": ["/x/apps/cua-spaces/mcp/spaces_mcp.py"]}, "other": {"command": "o"}}}"#;+ write(&f.home, ".cursor/mcp.json", legacy);++ let local = f.setup(CuaChannel::Local);+ let out = local+ .configure_mcp(+ &ids(&["cursor"]),+ &McpServer::for_channel(CuaChannel::Local, "cua-local"),+ )+ .unwrap();+ assert!(+ out.iter().all(|o| o.item != "cua-spaces"),+ "Local touched the legacy entry: {out:#?}"+ );+ let cursor = json(&f.read(".cursor/mcp.json"));+ assert_eq!(+ cursor["mcpServers"]["cua-spaces"]["args"][0],+ "/x/apps/cua-spaces/mcp/spaces_mcp.py"+ );+ assert!(cursor["mcpServers"]["cua-local"].is_object());+ // Local's remove and update leave it too.+ local.remove(&ids(&["cursor"]), Parts::ALL).unwrap();+ local+ .update(Some(&McpServer::for_channel(+ CuaChannel::Local,+ "cua-local",+ )))+ .unwrap();+ let cursor = json(&f.read(".cursor/mcp.json"));+ assert!(cursor["mcpServers"]["cua-spaces"].is_object(), "{cursor}");+ assert!(cursor["mcpServers"]["cua-local"].is_null());++ // Stable's setup still removes it, as before.+ let out = f+ .setup(CuaChannel::Stable)+ .configure_mcp(&ids(&["cursor"]), &McpServer::new(STABLE_CUA))+ .unwrap();+ let removed: Vec<&Outcome> = out.iter().filter(|o| o.item == "cua-spaces").collect();+ assert_eq!(removed.len(), 1, "{out:#?}");+ assert_eq!(removed[0].change, Change::Removed);+ assert!(json(&f.read(".cursor/mcp.json"))["mcpServers"]["cua-spaces"].is_null());+}diff --git a/libs/cua/crates/cua-agents/src/runs.rs b/libs/cua/crates/cua-agents/src/runs.rsindex 090122ce5c..4d8f5060c1 100644--- a/libs/cua/crates/cua-agents/src/runs.rs+++ b/libs/cua/crates/cua-agents/src/runs.rs@@ -637,6 +637,8 @@ impl Agents {app_dirs: vec![],os: cua_agent_setup::Os::Linux,run_agent_clis: false,+ // The guest's own cua: the bundled names, whatever the host is.+ channel: cua_agent_setup::CuaChannel::Stable,};let dir = loc.resolve(&env).to_string_lossy().replace('\\', "/");let mut done = vec![];diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rsindex 1035bbc582..06792b42f6 100644--- a/libs/cua/crates/cua-auth/src/lib.rs+++ b/libs/cua/crates/cua-auth/src/lib.rs@@ -8,7 +8,10 @@//! it works before and after that client change lands.//! - **Store**: the OS credential vault on Windows and on macOS for builds//! signed by Cua (service `ai.cua.session`, `ai.cua.session.staging` for-//! `CUA_ENV=staging`; account `cua-cli`), a 0600+//! `CUA_ENV=staging`; the Local channel's own, `ai.cua.session.local`+//! and `ai.cua.session.local.staging`, see `CuaChannel::keychain_service`,+//! so a locally built Cua Spaces never shares a sign-in with the released+//! one; account `cua-cli`), a 0600//! `~/.cua/credentials.json` elsewhere (Linux, and unsigned or ad-hoc//! macOS builds, which macOS treats as a new app on every rebuild so//! "Always Allow" never sticks) or with `CUA_CREDENTIAL_STORE=file`.@@ -23,14 +26,16 @@//! waits on a macOS keychain prompt: see [`KEYCHAIN_NONINTERACTIVE_ENV`].//! Items that older builds stored under the service `run.cua.ai`//! (`staging.run.cua.ai`) move to the current service on first read, and-//! sign-out removes both: see `legacy_vault`.+//! sign-out removes both: see `legacy_vault`. The Local channel has no+//! legacy items and skips that move.//! - **Session**: a refreshing access token. Every call reads the store, so//! a sign-out or a token another process rotated is seen at once instead//! of being refreshed twice.//!//! Configuration: `CUA_ENV` (`prod` or `staging`: the default issuer, the//! vault service and the cua home, so each environment keeps its own-//! session), `CUA_OIDC_ISSUER` (wins over `CUA_ENV`), `CUA_OIDC_CLIENT_ID`; test hooks+//! session; `CUA_CHANNEL=local` keeps Local's apart from Stable's),+//! `CUA_OIDC_ISSUER` (wins over `CUA_ENV`), `CUA_OIDC_CLIENT_ID`; test hooks//! `CUA_OIDC_POLL_UNIT_MS`, `CUA_OIDC_REDIRECT_PORT`,//! `CUA_OIDC_LOGIN_TIMEOUT_SECS`.@@ -52,17 +57,23 @@ const DEFAULT_SCOPE: &str = "openid profile offline_access organization:*";const DEVICE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";/// Refresh this long before expiry.const REFRESH_SKEW_SECS: i64 = 60;-/// The OS vault service of the session: `ai.cua.session` in production,-/// another one per `CUA_ENV`, so environments never share a session.+/// The OS vault service of the session and the named secrets, from the+/// channel and `CUA_ENV` (`CuaChannel::keychain_service`): `ai.cua.session`+/// for Stable in production, `.staging` on staging, and `ai.cua.session.local`+/// (`.staging`) for the Local channel. One per (channel, environment), so+/// neither two environments nor a Local build and the released app share a+/// session.#[cfg(any(target_os = "macos", target_os = "windows"))]fn keyring_service() -> &'static str {- cua_home::env::CuaEnv::current().keyring_service()+ cua_home::channel::CuaChannel::current_keychain_service()}/// The service older builds used (`run.cua.ai`, `staging.run.cua.ai`): read/// once to move its items to [`keyring_service`], and cleared on sign-out.+/// `None` for the Local channel: it has no legacy items, so it never reads,+/// moves or deletes anything under a name the released app owns.#[cfg(any(target_os = "macos", target_os = "windows"))]-fn legacy_keyring_service() -> &'static str {- cua_home::env::CuaEnv::current().legacy_keyring_service()+fn legacy_keyring_service() -> Option<&'static str> {+ cua_home::channel::CuaChannel::current_legacy_keychain_service()}#[cfg(any(target_os = "macos", target_os = "windows"))]const KEYRING_ACCOUNT: &str = "cua-cli";@@ -523,14 +534,18 @@ impl Store {let wanted = is_cua_account;// Items still under the legacy service name move first (a// read that needs a prompt is not asked unless `prompt`).- let moved = macos_keychain::migrate_legacy(- macos_keychain::Keychain::Default,- legacy_keyring_service(),- keyring_service(),- &wanted,- prompt,- signed_by_cua(),- );+ let moved = legacy_keyring_service()+ .map(|legacy| {+ macos_keychain::migrate_legacy(+ macos_keychain::Keychain::Default,+ legacy,+ keyring_service(),+ &wanted,+ prompt,+ signed_by_cua(),+ )+ })+ .unwrap_or_default();let items = macos_keychain::check_items(macos_keychain::Keychain::Default,keyring_service(),@@ -559,7 +574,7 @@ impl Store {self.clear()?;#[cfg(target_os = "macos")]if matches!(self, Store::Keyring) {- for service in [keyring_service(), legacy_keyring_service()] {+ for service in std::iter::once(keyring_service()).chain(legacy_keyring_service()) {// Not `check_keychain`: that would move a readable legacy// item over, and this is a sign-out.let items = macos_keychain::check_items(@@ -859,7 +874,8 @@ impl Store {// legacy name. This build only reads it, as it always does.vault_get(secret_entry(name).ok()?).ok().or_else(|| {let account = format!("{KEYRING_ACCOUNT}.{name}");- vault_get(VaultEntry::new(legacy_keyring_service(), &account).ok()?).ok()+ let legacy = legacy_keyring_service()?;+ vault_get(VaultEntry::new(legacy, &account).ok()?).ok()})}#[cfg(not(target_os = "macos"))]@@ -1558,20 +1574,15 @@ impl legacy_vault::Vault for NativeVault {/// stays as it is and fails with the usual hint ([`KEYCHAIN_NEEDS_ACCESS`]).#[cfg(any(target_os = "macos", target_os = "windows"))]fn move_legacy_item(account: &str) -> Result<Option<String>> {+ // The Local channel has no legacy items: nothing to move.+ let Some(legacy) = legacy_keyring_service() else {+ return Ok(None);+ };// A legacy recreate interrupted before its rename left the item under its// staging name: take it back first.#[cfg(target_os = "macos")]- let _ = macos_keychain::recover_staged(- macos_keychain::Keychain::Default,- legacy_keyring_service(),- account,- );- match legacy_vault::move_item(- &NativeVault,- legacy_keyring_service(),- keyring_service(),- account,- ) {+ let _ = macos_keychain::recover_staged(macos_keychain::Keychain::Default, legacy, account);+ match legacy_vault::move_item(&NativeVault, legacy, keyring_service(), account) {Ok(text) => Ok(text),Err(legacy_vault::Failure::Read(e) | legacy_vault::Failure::Write(e)) => Err(e),Err(legacy_vault::Failure::Unverified) => Err(Error::Store(@@ -1586,10 +1597,13 @@ fn move_legacy_item(account: &str) -> Result<Option<String>> {/// deleting the current item.#[cfg(any(target_os = "macos", target_os = "windows"))]fn drop_legacy_item(account: &str) -> bool {+ // The Local channel has none.+ let Some(legacy) = legacy_keyring_service() else {+ return false;+ };#[cfg(target_os = "macos")]let _quiet = macos_keychain::Quiet::new();- VaultEntry::new(legacy_keyring_service(), account)- .is_ok_and(|entry| vault_delete(entry).is_ok())+ VaultEntry::new(legacy, account).is_ok_and(|entry| vault_delete(entry).is_ok())}/// Whether a file store at `path` reads missing secrets from the OS@@ -2956,17 +2970,56 @@ mod tests {#[cfg(any(target_os = "macos", target_os = "windows"))]#[test]fn the_session_lives_under_a_neutral_service_per_environment() {+ use cua_home::channel::CuaChannel;use cua_home::env::CuaEnv;+ // Stable keeps the names it always had.+ let stable = CuaChannel::Stable;assert_eq!(CuaEnv::Prod.keyring_service(), "ai.cua.session");assert_eq!(CuaEnv::Staging.keyring_service(), "ai.cua.session.staging");- // The names older builds used are only ever read to move an item.+ for env in [CuaEnv::Prod, CuaEnv::Staging] {+ assert_eq!(stable.keychain_service(env), env.keyring_service());+ // The names older builds used are only ever read to move an item.+ assert_eq!(+ stable.legacy_keychain_service(env),+ Some(env.legacy_keyring_service())+ );+ assert_ne!(env.keyring_service(), env.legacy_keyring_service());+ }assert_eq!(CuaEnv::Prod.legacy_keyring_service(), "run.cua.ai");assert_eq!(CuaEnv::Staging.legacy_keyring_service(),"staging.run.cua.ai");+ }++ /// The Local channel has its own services, and no legacy one to move+ /// from or to delete: it never touches a name Stable owns.+ #[cfg(any(target_os = "macos", target_os = "windows"))]+ #[test]+ fn the_local_channel_has_its_own_services_and_no_legacy_one() {+ use cua_home::channel::CuaChannel;+ use cua_home::env::CuaEnv;+ let local = CuaChannel::Local;+ assert_eq!(local.keychain_service(CuaEnv::Prod), "ai.cua.session.local");+ assert_eq!(+ local.keychain_service(CuaEnv::Staging),+ "ai.cua.session.local.staging"+ );for env in [CuaEnv::Prod, CuaEnv::Staging] {- assert_ne!(env.keyring_service(), env.legacy_keyring_service());+ assert_eq!(local.legacy_keychain_service(env), None);+ let owned_by_stable = [+ CuaChannel::Stable.keychain_service(env),+ env.legacy_keyring_service(),+ ];+ assert!(!owned_by_stable.contains(&local.keychain_service(env)));+ }+ // This test process is Stable, so the glue reads Stable's names.+ if std::env::var_os("CUA_CHANNEL").is_none() && CuaChannel::build_default().is_none() {+ assert_eq!(keyring_service(), CuaEnv::current().keyring_service());+ assert_eq!(+ legacy_keyring_service(),+ Some(CuaEnv::current().legacy_keyring_service())+ );}}diff --git a/libs/cua/crates/cua-cli/src/agents.rs b/libs/cua/crates/cua-cli/src/agents.rsindex 93dc7cb063..0df602e7f5 100644--- a/libs/cua/crates/cua-cli/src/agents.rs+++ b/libs/cua/crates/cua-cli/src/agents.rs@@ -236,18 +236,21 @@ fn discard_typeahead() {/// The MCP server agents should launch.pub fn mcp_server(setup: &AgentSetup, command: Option<&str>) -> McpServer {+ // The channel's own server (`cua`, or `cua-local` when this is the Local+ // CLI), launching the channel's own binary.+ let channel = setup.env().channel;if let Some(c) = command {- return McpServer::new(c);+ return McpServer::for_channel(channel, c);}- if setup.env().which("cua").is_some() {+ if setup.env().which(channel.cli_name()).is_some() {return McpServer::default_for(setup.env());}let exe = std::env::current_exe().ok().and_then(|p| p.canonicalize().ok()).map(|p| p.display().to_string())- .unwrap_or_else(|| "cua".into());- McpServer::new(exe)+ .unwrap_or_else(|| channel.cli_name().into());+ McpServer::for_channel(channel, exe)}fn print_agents(setup: &AgentSetup, statuses: &[AgentStatus], out: &mut dyn Write) {diff --git a/libs/cua/crates/cua-cli/src/do_cmd.rs b/libs/cua/crates/cua-cli/src/do_cmd.rsindex e838f0a2cd..c437820a42 100644--- a/libs/cua/crates/cua-cli/src/do_cmd.rs+++ b/libs/cua/crates/cua-cli/src/do_cmd.rs@@ -6,7 +6,8 @@//!//! Targets are SDK sandboxes (local or direct) and relay Spaces//! (`relay:<machine-id>`). `host` is a direct sandbox pointing at a-//! cua-spacesd on this machine (default `http://127.0.0.1:3211`), gated+//! cua-spacesd on this machine (default `http://127.0.0.1:3211`, or 3221 for+//! `cua-local`), gated//! behind `cua do-host-consent`.use crate::{@@ -30,8 +31,15 @@ const LEGACY_PROVIDERS: &[&str] = &["direct","sandbox",];-/// Default host spacesd (`CUA_HOST_ENV_URL`).-pub const DEFAULT_HOST_ENV_URL: &str = "http://127.0.0.1:3211";+/// Default host spacesd (`CUA_HOST_ENV_URL`): this machine, on the+/// channel's port (3211, or 3221 for `cua-local`).+pub fn default_host_env_url() -> String {+ host_env_url_on(cua_home::channel::CuaChannel::current())+}++fn host_env_url_on(channel: cua_home::channel::CuaChannel) -> String {+ format!("http://127.0.0.1:{}", channel.ports().tcp)+}#[derive(Args, Debug)]pub struct DoArgs {@@ -616,7 +624,7 @@ impl Run<'_> {}let url = name.or_else(|| std::env::var("CUA_HOST_ENV_URL").ok())- .unwrap_or_else(|| DEFAULT_HOST_ENV_URL.into());+ .unwrap_or_else(default_host_env_url);let token = token.or_else(|| std::env::var("CUA_HOST_ENV_TOKEN").ok());self.register_direct("host", &url, token).await?;("host".to_string(), "host".to_string())@@ -1274,3 +1282,28 @@ async fn snapshot_summary(}Ok(s)}++#[cfg(test)]+mod tests {+ use super::*;+ use cua_home::channel::CuaChannel;++ /// `cua do switch host` reaches this machine's spacesd on the channel's+ /// port: `cua-local`'s is not Stable's 3211.+ #[test]+ fn the_host_target_is_this_machines_spacesd_on_the_channels_port() {+ assert_eq!(host_env_url_on(CuaChannel::Stable), "http://127.0.0.1:3211");+ assert_eq!(host_env_url_on(CuaChannel::Local), "http://127.0.0.1:3221");+ }++ /// Stable's ports are the ones cua-spacesd binds with no flag, so a+ /// Stable host service passes none (`Host::service_spec`) and `cua`+ /// reaches it without being told.+ #[test]+ fn the_stable_ports_are_spacesds_own_defaults() {+ let p = CuaChannel::Stable.ports();+ assert_eq!(p.tcp, cua_proto::SPACESD_DEFAULT_PORT);+ assert_eq!(p.quic, cua_proto::SPACESD_DEFAULT_QUIC_PORT);+ assert_eq!(p.mesh_udp, 3212, "cua_mesh::MEDIA_UDP_PORT");+ }+}diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex d7079611b7..d60da0b425 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -1851,7 +1851,7 @@ pub async fn run_host(})?;Some(cua_host::direct::authority(ip,- cua_proto::SPACESD_DEFAULT_PORT,+ cua_home::channel::CuaChannel::current().ports().tcp,))}(None, false) => None,diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex d37094ae0c..2058b3a041 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -2657,6 +2657,61 @@ Examples:cua host setup --direct 100.101.102.103:3211 --profile spare";+/// The command `cua` parses with, named for `channel`. Stable's is `cli`+/// untouched. A Local build ("Cua Spaces Local", CUA-1776) installs its CLI as+/// `cua-local`, so its help says so: usage lines print `cua-local` (the+/// bundled copy is a file named `cua` inside the app, which clap would name+/// `cua`), and an example that starts with `cua` starts with `cua-local`, so+/// pasting it does not run the Stable CLI.+fn channel_command(cli: clap::Command, channel: cua_home::channel::CuaChannel) -> clap::Command {+ if !channel.is_local() {+ return cli;+ }+ let name = channel.cli_name();+ localize_help(cli.bin_name(name), name)+}++/// `cmd` and its subcommands with the examples in their after-help run as+/// `name` (see [`localize_examples`]).+fn localize_help(cmd: clap::Command, name: &str) -> clap::Command {+ let after = cmd+ .get_after_help()+ .map(|h| localize_examples(&h.to_string(), name));+ let after_long = cmd+ .get_after_long_help()+ .map(|h| localize_examples(&h.to_string(), name));+ let mut cmd = cmd;+ if let Some(h) = after {+ cmd = cmd.after_help(h);+ }+ if let Some(h) = after_long {+ cmd = cmd.after_long_help(h);+ }+ cmd.mut_subcommands(|sub| localize_help(sub, name))+}++/// `text` with every line that is a `cua ...` example (it starts with `cua `+/// once indented) starting with `name` instead.+fn localize_examples(text: &str, name: &str) -> String {+ let mut out = String::with_capacity(text.len() + 16);+ for (i, line) in text.split('\n').enumerate() {+ if i > 0 {+ out.push('\n');+ }+ let body = line.trim_start();+ match body.strip_prefix("cua ") {+ Some(rest) => {+ out.push_str(&line[..line.len() - body.len()]);+ out.push_str(name);+ out.push(' ');+ out.push_str(rest);+ }+ None => out.push_str(line),+ }+ }+ out+}+/// `cua help advanced`, answered before clap: it is a help topic, not a/// command.fn is_advanced_help(args: &[std::ffi::OsString]) -> bool {@@ -2672,22 +2727,33 @@ fn fallback_notice(n: &cua_spaces::mesh::FallbackNotice) {pub fn main() {#[cfg(windows)]keep_stdio_out_of_children();+ let channel = cua_home::channel::CuaChannel::current();if is_advanced_help(&std::env::args_os().skip(1).collect::<Vec<_>>()) {- print!("{ADVANCED_HELP}");+ if channel.is_local() {+ print!("{}", localize_examples(ADVANCED_HELP, channel.cli_name()));+ } else {+ print!("{ADVANCED_HELP}");+ }return;}promote_spacesd_env_vars();- // `CUA_ENV` picks every endpoint and the cua home: a typo must not fall- // back to production silently.+ // `CUA_CHANNEL` and `CUA_ENV` pick every endpoint and the cua home (Local+ // is `cua-local`: staging and `~/.cua-local` unless told otherwise): a+ // typo must not fall back to production silently.if let Err(e) = cua_home::env::CuaEnv::try_current() {eprintln!("error: {e}");std::process::exit(2);}// SAFETY: still first in `main`, before any other thread exists. Pins- // `CUA_HOME` for a non-production `CUA_ENV` so every component and- // child process (the daemon) uses that environment's home.+ // `CUA_HOME` for the Local channel or a non-production `CUA_ENV` (and+ // `CUA_CHANNEL` and `CUA_ENV` for Local) so every component and child+ // process (the daemon) uses that channel's and environment's home.unsafe { cua_home::env::pin_home() };- let matches = cli_command(cua_home::experimental::teams_enabled()).get_matches();+ let matches = channel_command(+ cli_command(cua_home::experimental::teams_enabled()),+ channel,+ )+ .get_matches();let command = command_path(&matches);let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());let daemon_process = matches!(cli.command, Command::Daemon(DaemonCmd::Start { .. }));@@ -3577,6 +3643,81 @@ mod tests {}}+ /// Every command of the tree with its rendered long help.+ fn all_help(cmd: &mut clap::Command) -> Vec<(String, String)> {+ let mut out = vec![(+ cmd.get_bin_name().unwrap_or(cmd.get_name()).to_string(),+ cmd.render_long_help().to_string(),+ )];+ for name in cmd+ .get_subcommands()+ .map(|c| c.get_name().to_string())+ .collect::<Vec<_>>()+ {+ let sub = cmd.find_subcommand_mut(&name).unwrap();+ out.extend(all_help(sub));+ }+ out+ }++ /// CUA-1776: the Local CLI (`cua-local`) says `cua-local` in its usage+ /// and examples, so nothing it prints sends the user to Stable's `cua`.+ #[test]+ fn local_help_says_cua_local() {+ use cua_home::channel::CuaChannel;+ let mut local = channel_command(cli_command(true), CuaChannel::Local);+ local.build();+ let help = all_help(&mut local);+ assert!(help.len() > 20, "the whole tree is rendered");+ assert!(help[0].1.contains("Usage: cua-local "), "{}", help[0].1);+ for (name, text) in &help {+ assert!(name.starts_with("cua-local"), "{name}");+ for line in text.lines() {+ let l = line.trim_start();+ assert!(+ !l.starts_with("cua ") && !l.starts_with("Usage: cua "),+ "{name}: {line}"+ );+ }+ }+ // The examples are still there, renamed.+ assert!(+ help.iter().any(|(_, t)| t+ .lines()+ .any(|l| l.trim_start().starts_with("cua-local host setup"))),+ "host setup example"+ );+ // The version line is still `cua <version>`: the app checks it to+ // recognise its CLI.+ assert_eq!(+ local.render_version().trim(),+ format!("cua {}", cua_sdk::VERSION)+ );+ }++ /// Stable's command and its help are exactly what they were.+ #[test]+ fn stable_help_is_unchanged() {+ use cua_home::channel::CuaChannel;+ for teams in [true, false] {+ let mut plain = cli_command(teams);+ let mut stable = channel_command(cli_command(teams), CuaChannel::Stable);+ plain.build();+ stable.build();+ assert_eq!(all_help(&mut plain), all_help(&mut stable));+ }+ }++ #[test]+ fn examples_are_renamed_line_by_line() {+ let text = "Examples:\n cua host setup\n # cua is a comment\nthe cua daemon\n cua sb ls # list\ncua\n";+ assert_eq!(+ localize_examples(text, "cua-local"),+ "Examples:\n cua-local host setup\n # cua is a comment\nthe cua daemon\n cua-local sb ls # list\ncua\n"+ );+ assert_eq!(localize_examples("", "cua-local"), "");+ }+#[tokio::test]#[ignore = "host: probes the developer's lume, qemu and Docker; run with --ignored"]async fn runtime_doctor_is_read_only_and_reports_backends() {diff --git a/libs/cua/crates/cua-cli/src/teleport_session.rs b/libs/cua/crates/cua-cli/src/teleport_session.rsindex 9d79ff940b..8a0e46bfc0 100644--- a/libs/cua/crates/cua-cli/src/teleport_session.rs+++ b/libs/cua/crates/cua-cli/src/teleport_session.rs@@ -143,12 +143,17 @@ impl Broker for Unwired {}}-/// The error when no Keyvault is reachable: install or open the Cua app.+/// The error when no Keyvault is reachable: install or open the Cua app+/// (this process's channel's: `cua://`, or `cua-local://` for Local).pub fn requires_cua_app() -> BrokerError {+ requires_cua_app_for(cua_home::channel::CuaChannel::current())+}++fn requires_cua_app_for(channel: cua_home::channel::CuaChannel) -> BrokerError {BrokerError::RequiresCuaApp {installed: false,install_url: "https://cua.ai/download".into(),- open_url: "cua://keyvault".into(),+ open_url: channel.keyvault_url(),}}@@ -517,4 +522,14 @@ mod tests {assert_eq!(e.kind(), "requires_cua_app");assert!(e.message().contains("https://cua.ai/download"));}++ #[test]+ fn the_open_link_is_the_channels() {+ use cua_home::channel::CuaChannel;+ let message = |c| requires_cua_app_for(c).message();+ assert!(message(CuaChannel::Stable).contains("open cua://keyvault,"));+ // Local opens Cua Spaces Local, never the released app.+ assert!(message(CuaChannel::Local).contains("open cua-local://keyvault,"));+ assert!(!message(CuaChannel::Local).contains("cua://"));+ }}diff --git a/libs/cua/crates/cua-cli/tests/agents_login.rs b/libs/cua/crates/cua-cli/tests/agents_login.rsindex b58b883602..411f7e09b9 100644--- a/libs/cua/crates/cua-cli/tests/agents_login.rs+++ b/libs/cua/crates/cua-cli/tests/agents_login.rs@@ -385,6 +385,110 @@ async fn agents_commands_round_trip_and_protect_malformed_files() {assert_eq!(o.code, 2, "{o:?}");}+/// The Local CLI (`CUA_CHANNEL=local`, its own home) registers `cua-local`+/// beside the Stable `cua` in the same agent config, installs `-local` skill+/// copies beside Stable's, and removes only its own (CUA-1776).+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_local_cli_registers_cua_local_beside_stables_cua() {+ let mut h = home();+ mkdirs(&h, &[".cursor"]);+ let cursor = h.dir.path().join(".cursor/mcp.json");+ let stable_skill = h.dir.path().join(".agents/skills/cua-spaces");+ let local_skill = h.dir.path().join(".agents/skills/cua-spaces-local");++ // Stable first: `cua`.+ let o = h+ .run(&[+ "agents",+ "setup",+ "--agents",+ "cursor",+ "--yes",+ "--mcp-command",+ "/opt/cua/bin/cua",+ ])+ .await;+ o.ok();+ let before = std::fs::read_to_string(&cursor).unwrap();+ assert!(+ before.contains("\"cua\"") && !before.contains("cua-local"),+ "{before}"+ );+ assert!(stable_skill.join("SKILL.md").is_file());++ // Then the Local CLI, in its own home.+ let local_home = h.dir.path().join(".cua-local");+ h.set("CUA_CHANNEL", "local")+ .set("CUA_HOME", local_home.display().to_string());+ let o = h+ .run(&[+ "--json",+ "agents",+ "setup",+ "--agents",+ "cursor",+ "--yes",+ "--mcp-command",+ "/opt/cua-local/bin/cua-local",+ ])+ .await;+ o.ok();+ let v = o.json();+ let mcp: Vec<&str> = v["outcomes"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|m| m["target"] == "mcp")+ .map(|m| m["item"].as_str().unwrap())+ .collect();+ assert_eq!(mcp, ["cua-local"], "{v}");+ let both: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&cursor).unwrap()).unwrap();+ assert_eq!(both["mcpServers"]["cua"]["command"], "/opt/cua/bin/cua");+ assert_eq!(+ both["mcpServers"]["cua-local"]["command"],+ "/opt/cua-local/bin/cua-local"+ );+ assert!(local_skill.join("SKILL.md").is_file());+ assert!(+ std::fs::read_to_string(local_skill.join("SKILL.md"))+ .unwrap()+ .contains("name: cua-spaces-local")+ );+ assert!(local_home.join("agent-setup.json").is_file());++ let o = h.run(&["--json", "agents", "status"]).await;+ o.ok();+ let v = o.json();+ let c = v["agents"]+ .as_array()+ .unwrap()+ .iter()+ .find(|a| a["id"] == "cursor")+ .unwrap();+ assert_eq!(+ (c["cua_configured"].clone(), c["cua_managed"].clone()),+ (true.into(), true.into()),+ "{c}"+ );+ assert!(+ v["skills"]+ .as_array()+ .unwrap()+ .iter()+ .all(|s| s["name"].as_str().unwrap().ends_with("-local")),+ "{v}"+ );++ // Removing Local's setup leaves Stable's entry and skills.+ h.run(&["agents", "remove", "--yes"]).await.ok();+ let left: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&cursor).unwrap()).unwrap();+ assert_eq!(left["mcpServers"]["cua"]["command"], "/opt/cua/bin/cua");+ assert!(left["mcpServers"]["cua-local"].is_null(), "{left}");+ assert!(stable_skill.join("SKILL.md").is_file() && !local_skill.exists());+}+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn agents_setup_cua_driver_adds_the_driver_skill_and_server() {let h = home();diff --git a/libs/cua/crates/cua-cli/tests/channel_name.rs b/libs/cua/crates/cua-cli/tests/channel_name.rsnew file mode 100644index 0000000000..c7f6dc977c--- /dev/null+++ b/libs/cua/crates/cua-cli/tests/channel_name.rs@@ -0,0 +1,293 @@+//! CUA-1776: the CLI named `cua-local` is the Local channel's, and says so:+//! its usage lines and the examples in its help print `cua-local`, so a+//! copied example does not run Stable's `cua`. Stable's help is unchanged.+//!+//! The Local binary is a hard link of the built `cua` named `cua-local`+//! (the first run installs the bundled CLI under that name).+//!+//! It is Local at startup too, not only in its help: with no `CUA_CHANNEL`,+//! `CUA_ENV` or `CUA_HOME` (a plain shell) `cua-local` uses staging and+//! `~/.cua-local`, and never reads or writes Stable's `~/.cua`.++#![cfg(unix)]++use std::os::unix::process::CommandExt;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::sync::Once;++/// A directory with the built `cua` linked as `cua` and as `cua-local`.+struct Rig {+ dir: tempfile::TempDir,+}++/// The first start of a freshly built `cua` can take seconds on macOS (the+/// system checks the new 400 MB executable), and a dozen starting at once+/// on a busy machine can be killed while they wait. Start it once, alone,+/// before any test links or runs it.+fn warm_up() {+ static WARM: Once = Once::new();+ WARM.call_once(|| {+ let _ = Command::new(env!("CARGO_BIN_EXE_cua"))+ .arg("--version")+ .env("CUA_TELEMETRY", "0")+ .stdin(Stdio::null())+ .output();+ });+}++impl Rig {+ fn new() -> Self {+ warm_up();+ let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();+ for name in ["cua", "cua-local"] {+ let to = dir.path().join(name);+ let from = Path::new(env!("CARGO_BIN_EXE_cua"));+ std::fs::hard_link(from, &to)+ .or_else(|_| std::fs::copy(from, &to).map(|_| ()))+ .unwrap();+ }+ Rig { dir }+ }++ fn bin(&self, name: &str) -> PathBuf {+ self.dir.path().join(name)+ }++ /// Runs `program` as `arg0` with `CUA_CHANNEL` set to `channel`.+ fn run(+ &self,+ program: &str,+ arg0: Option<&str>,+ channel: Option<&str>,+ args: &[&str],+ ) -> String {+ let mut cmd = Command::new(self.bin(program));+ if let Some(a) = arg0 {+ cmd.arg0(a);+ }+ cmd.args(args)+ .env("HOME", self.dir.path())+ .env("CUA_HOME", self.dir.path().join(".cua"))+ .env("CUA_TELEMETRY", "0")+ .env("CUA_RELAY_URL", "http://127.0.0.1:9")+ // An empty PATH: a bare `argv[0]` is not looked up in the+ // developer's own `~/.local/bin`.+ .env("PATH", "")+ .env_remove("CUA_ENV")+ .env_remove("CUA_API_KEY")+ .env_remove("CUA_EXPERIMENTAL_TEAMS")+ .stdin(Stdio::null());+ match channel {+ Some(c) => cmd.env("CUA_CHANNEL", c),+ None => cmd.env_remove("CUA_CHANNEL"),+ };+ let out = cmd.output().expect("run cua");+ assert!(out.status.success(), "{out:?}");+ String::from_utf8(out.stdout).unwrap()+ }+}++/// The help of `cua host setup`, which has `cua ...` examples.+const HELP: &[&str] = &["host", "setup", "--help"];++fn says_local(text: &str) {+ assert!(text.contains("Usage: cua-local host setup"), "{text}");+ assert!(+ text.lines()+ .any(|l| l.trim_start().starts_with("cua-local host setup")),+ "{text}"+ );+ assert!(+ !text.lines().any(|l| l.trim_start().starts_with("cua ")),+ "{text}"+ );+}++fn says_stable(text: &str) {+ assert!(text.contains("Usage: cua host setup"), "{text}");+ assert!(+ text.lines()+ .any(|l| l.trim_start().starts_with("cua host setup")),+ "{text}"+ );+ assert!(!text.contains("cua-local"), "{text}");+}++#[test]+fn stable_cua_is_unchanged() {+ let rig = Rig::new();+ says_stable(&rig.run("cua", None, None, HELP));+ says_stable(&rig.run("cua", None, Some("stable"), HELP));+}++#[test]+fn the_file_named_cua_local_is_the_local_cli() {+ let rig = Rig::new();+ says_local(&rig.run("cua-local", None, None, HELP));+ // Run as `cua` (argv[0] says one thing, the file another): the file+ // path alone says Local.+ says_local(&rig.run("cua-local", Some("cua"), None, HELP));+}++#[test]+fn the_name_it_was_started_under_says_local_too() {+ let rig = Rig::new();+ // A `cua` file started as `cua-local` (a link made later, a shell alias):+ // argv[0] alone says Local.+ says_local(&rig.run("cua", Some("cua-local"), None, HELP));+}++#[test]+fn cua_channel_wins_over_the_name() {+ let rig = Rig::new();+ says_local(&rig.run("cua", None, Some("local"), HELP));+ says_local(&rig.run("cua", Some("cua"), Some("LOCAL"), HELP));+ says_stable(&rig.run("cua-local", Some("cua"), Some("stable"), HELP));+}++#[test]+fn the_version_line_is_cua_in_both_channels() {+ let rig = Rig::new();+ let want = format!("cua {}", cua_sdk::VERSION);+ for (program, arg0, channel) in [+ ("cua", None, None),+ ("cua-local", None, None),+ ("cua-local", Some("cua"), None),+ ("cua", None, Some("local")),+ ] {+ let v = rig.run(program, arg0, channel, &["--version"]);+ assert_eq!(v.trim(), want, "{program} {arg0:?} {channel:?}");+ }+}++#[test]+fn help_advanced_follows_the_channel() {+ let rig = Rig::new();+ let stable = rig.run("cua", None, None, &["help", "advanced"]);+ assert!(stable.contains("cua host setup --relay"), "{stable}");+ assert!(!stable.contains("cua-local"), "{stable}");+ let local = rig.run("cua-local", None, None, &["help", "advanced"]);+ assert!(local.contains("cua-local host setup --relay"), "{local}");+ assert!(+ !local.lines().any(|l| l.trim_start().starts_with("cua ")),+ "{local}"+ );+}++// ---- Startup: the environment and the home -----------------------------------++/// `cua auth status --json` of `program` in a fresh fake `HOME`, with the+/// whole environment cleared but `HOME`, `extra` and what keeps the run+/// hermetic (no `CUA_CHANNEL`, `CUA_ENV` or `CUA_HOME` unless `extra` sets+/// one). Returns the fake home and what the CLI reported.+fn status(+ rig: &Rig,+ program: &str,+ arg0: Option<&str>,+ extra: &[(&str, &str)],+) -> (PathBuf, serde_json::Value, String) {+ let home = tempfile::tempdir_in(rig.dir.path()).unwrap().keep();+ let mut cmd = Command::new(rig.bin(program));+ if let Some(a) = arg0 {+ cmd.arg0(a);+ }+ cmd.args(["auth", "status"])+ .env_clear()+ .env("HOME", &home)+ .env("PATH", "")+ .env("CUA_TELEMETRY", "0")+ // The file store: never the developer's Keychain.+ .env("CUA_CREDENTIAL_STORE", "file")+ .envs(extra.iter().copied())+ .stdin(Stdio::null());+ let text = cmd.output().expect("run cua auth status");+ // Not logged in: exit 1, still reports.+ assert_eq!(text.status.code(), Some(1), "{text:?}");+ let text = String::from_utf8(text.stdout).unwrap();+ let json = cmd+ .arg("--json")+ .output()+ .expect("run cua auth status --json");+ assert_eq!(json.status.code(), Some(1), "{json:?}");+ let json = serde_json::from_slice(&json.stdout).expect("json");+ (home, json, text)+}++/// The home the status line names (`home <path>).`), if it names one.+fn home_in(text: &str) -> Option<&str> {+ let rest = text.split("home ").nth(1)?;+ rest.split(").").next()+}++#[test]+fn a_plain_shell_cua_local_is_staging_with_its_own_home() {+ let rig = Rig::new();+ // No CUA_CHANNEL, CUA_ENV or CUA_HOME at all: the name alone decides.+ for arg0 in [None, Some("cua")] {+ let (home, json, text) = status(&rig, "cua-local", arg0, &[]);+ assert_eq!(json["env"], "staging", "{json}");+ assert!(+ json["issuer"].as_str().unwrap().contains("staging"),+ "{json}"+ );+ assert!(+ json["relay"].as_str().unwrap().contains("staging"),+ "{json}"+ );+ let want = home.join(".cua-local");+ assert_eq!(+ json["store"],+ format!("file {}", want.join("credentials.json").display()),+ "{json}"+ );+ assert!(text.contains("Environment: staging"), "{text}");+ assert_eq!(home_in(&text), want.to_str(), "{text}");+ // Stable's home is never created or read.+ assert!(!home.join(".cua").exists(), "{:?}", home.join(".cua"));+ }+}++#[test]+fn cua_local_with_the_prod_opt_in_keeps_its_own_home() {+ let rig = Rig::new();+ let (home, json, text) = status(&rig, "cua-local", None, &[("CUA_ENV", "prod")]);+ assert_eq!(json["env"], "prod", "{json}");+ assert_eq!(+ json["store"],+ format!(+ "file {}",+ home.join(".cua-local/envs/prod/credentials.json").display()+ ),+ "{json}"+ );+ // Production prints no "Environment:" line.+ assert!(!text.contains("Environment:"), "{text}");+ assert!(!home.join(".cua").exists());+}++#[test]+fn a_plain_shell_cua_is_still_prod_with_the_stable_home() {+ let rig = Rig::new();+ let (home, json, text) = status(&rig, "cua", None, &[]);+ assert_eq!(json["env"], "prod", "{json}");+ assert_eq!(+ json["store"],+ format!("file {}", home.join(".cua/credentials.json").display()),+ "{json}"+ );+ assert!(!text.contains("Environment:"), "{text}");+ assert!(!home.join(".cua-local").exists());+ // And staging on Stable keeps `~/.cua/envs/staging`, as before.+ let (home, json, _) = status(&rig, "cua", None, &[("CUA_ENV", "staging")]);+ assert_eq!(json["env"], "staging", "{json}");+ assert_eq!(+ json["store"],+ format!(+ "file {}",+ home.join(".cua/envs/staging/credentials.json").display()+ ),+ "{json}"+ );+ assert!(!home.join(".cua-local").exists());+}diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rsindex 6118421634..eb9e144b30 100644--- a/libs/cua/crates/cua-daemon/src/local.rs+++ b/libs/cua/crates/cua-daemon/src/local.rs@@ -2360,8 +2360,11 @@ impl LocalRuntime for VmmLocal {via: "vnc".into(),// `lume attach` opens the VM's own display (VNC as its fallback)// and handles the password.- open_command: cua_vmm::lume::lume_bin()- .map(|b| vec![b.display().to_string(), "attach".into(), name.to_string()]),+ // Run with the channel's Lume environment, so a Local Lume+ // attaches to a Local VM.+ open_command: cua_vmm::lume::lume_cmd()+ .map_err(rt_err)?+ .map(|l| l.argv(["attach", name])),})}}diff --git a/libs/cua/crates/cua-home/examples/channel_names.rs b/libs/cua/crates/cua-home/examples/channel_names.rsnew file mode 100644index 0000000000..9ece4f307b--- /dev/null+++ b/libs/cua/crates/cua-home/examples/channel_names.rs@@ -0,0 +1,39 @@+//! Prints the names of a Cua Spaces channel as `key=value` lines, for the+//! scripts that build and check an app bundle+//! (`apps/cua-spaces-macos/scripts/channel-names.sh`), so none of them+//! hard-codes a name: [`CuaChannel`] owns every one (CUA-1776).+//!+//! ```text+//! cargo run -q -p cua-home --example channel_names -- local+//! ```++use cua_home::channel::CuaChannel;++fn main() {+ let arg = std::env::args().nth(1).unwrap_or_default();+ let Some(channel) = CuaChannel::parse(&arg) else {+ eprintln!("usage: channel_names <stable|local>");+ std::process::exit(2);+ };+ // The cua home as the bundle stamps it (`~/.cua-local`), not the path on+ // this machine.+ let home = channel.home_dir();+ let home = format!(+ "~/{}",+ home.file_name()+ .map(|n| n.to_string_lossy())+ .unwrap_or_default()+ );+ let lines = [+ ("channel", channel.name().to_string()),+ ("app_name", channel.app_name().to_string()),+ ("bundle_id", channel.bundle_id().to_string()),+ ("helper_label", channel.helper_label().to_string()),+ ("url_scheme", channel.url_scheme().to_string()),+ ("home", home),+ ("env", channel.default_env().name().to_string()),+ ];+ for (key, value) in lines {+ println!("{key}={value}");+ }+}diff --git a/libs/cua/crates/cua-home/src/channel.rs b/libs/cua/crates/cua-home/src/channel.rsnew file mode 100644index 0000000000..64d1f7d4c8--- /dev/null+++ b/libs/cua/crates/cua-home/src/channel.rs@@ -0,0 +1,1154 @@+//! Which Cua Spaces build this is: the released app (`stable`) or a locally+//! built one (`local`, "Cua Spaces Local"). CUA-1776.+//!+//! The two run on one Mac at the same time, so nothing the Local build+//! writes, registers, listens on or stores may be shared with the Stable+//! install. [`CuaChannel`] is the one place that owns every name that has to+//! differ; nothing else hard-codes one. (Same idea as `bundle.rs` in Cua+//! Driver, which keeps `cua-driver` and `cua-driver-local` apart.)+//!+//! | Name | Stable | Local |+//! |-----------------------|-----------------------------------------------|--------------------------------------------------|+//! | Bundle id | `com.trycua.spaces.macos` (see below) | `com.trycua.spaces.local` |+//! | App | `/Applications/Cua Spaces.app` | `~/Applications/Cua Spaces Local.app` |+//! | CLI | `~/.local/bin/cua` | `~/.local/bin/cua-local` |+//! | Cua home | `~/.cua` (`envs/staging` below it on staging) | `~/.cua-local` (`envs/prod` below it on prod) |+//! | Default environment | prod | staging (`CUA_ENV=prod` opts in) |+//! | Sign-in Keychain | `ai.cua.session` (`.staging`) | `ai.cua.session.local` (`.staging`) |+//! | Legacy Keychain | `run.cua.ai` (`staging.run.cua.ai`), moved once | none: Local never had one, nothing is moved |+//! | App helper | `com.trycua.spaces.helper` | `com.trycua.spaces.local.helper` |+//! | Helper spec | `~/.cua/helper/service.json` | `~/.cua-local/helper/service.json` |+//! | Plain host runner | `com.trycua.spacesd.host` | `com.trycua.spacesd.host.local` |+//! | spacesd ports | 3211 TCP, 3212 QUIC, mesh UDP 3212 | 3221 TCP, 3222 QUIC, mesh UDP 3212 (shared) |+//! | URL scheme | `cua://` | `cua-local://` |+//! | Cua Volume | `~/Cua Volume` | `~/Cua Volume Local` |+//! | Lume | `lume`, `com.trycua.lume_daemon`, `:7777`, `~/.lume` | `lume-local`, `com.trycua.lume_daemon.local`, `:7787`, `~/.lume-local` |+//! | App data | `~/Library/Application Support/com.trycua.spaces.macos` | `.../com.trycua.spaces.local` |+//! | Agent MCP server | `cua` (launches `cua mcp`) | `cua-local` (launches `cua-local mcp`) |+//! | Agent skills | `cua-spaces`, `cua-volume`, ... | `cua-spaces-local`, `cua-volume-local`, ... |+//!+//! **Stable bundle id.** Stable is `com.trycua.spaces.macos` today. The+//! rename to `com.trycua.spaces` is a later, separate change (CUA-1776,+//! "PR 5": it needs a first-launch migration and makes macOS ask for the+//! permission grants again). When it lands, [`CuaChannel::bundle_id`] and+//! [`CuaChannel::app_support_dir_name`] change for Stable here and nowhere+//! else.+//!+//! # Resolution+//!+//! [`CuaChannel::current`] picks the channel in this order:+//!+//! 1. the `CUA_CHANNEL` environment variable (`stable` or `local`);+//! 2. the value compiled in with `CUA_DEFAULT_CHANNEL` (a Local build is+//! compiled with `local`), like `CUA_DEFAULT_ENV` for [`CuaEnv`];+//! 3. the executable path: inside `Cua Spaces Local.app`, or an executable+//! named `cua-local`, means Local;+//! 4. otherwise Stable.+//!+//! The app sets `CUA_CHANNEL` before anything starts, so the helper,+//! spacesd, the daemon and the bundled `cua` all inherit it and agree.+//!+//! # Environment+//!+//! Local defaults to the staging deployment, so a Local build never signs+//! in to, or registers a host with, production by accident. `CUA_ENV=prod`+//! is an explicit opt-in. See [`CuaChannel::default_env`] and+//! [`CuaChannel::current_env`].+//!+//! The environment follows the channel everywhere: [`CuaEnv::build_default`],+//! [`CuaEnv::current`], `Endpoints::from_lookup` (which reads `CUA_CHANNEL`+//! from its lookup, so tests stay hermetic) and [`crate::cua_home`] all go+//! through this module. The home follows both:+//!+//! | Channel | Environment | Home |+//! |---------|-------------|---------------------------|+//! | Stable | prod | `~/.cua` |+//! | Stable | staging | `~/.cua/envs/staging` |+//! | Local | staging | `~/.cua-local` |+//! | Local | prod | `~/.cua-local/envs/prod` |+//!+//! Each channel keeps its own folder for the environment it is made for+//! (Stable for prod, Local for staging) and puts the other one below it+//! (Stable's staging, Local's prod), so a Local build that opts in to+//! production never shares a session, registry or socket with its staging+//! state, or with Stable. The app pins `CUA_HOME` to it. Each of the four+//! also has its own Keychain service ([`CuaChannel::keychain_service`]).++use std::ffi::OsStr;+use std::path::{Path, PathBuf};++use crate::env::{CUA_ENV_VAR, CuaEnv};++/// The environment variable that selects the channel.+pub const CUA_CHANNEL_VAR: &str = "CUA_CHANNEL";++/// The file name of the Local CLI.+const LOCAL_CLI_NAME: &str = "cua-local";++/// The directory name of the Local app bundle.+const LOCAL_APP_DIR_NAME: &str = "Cua Spaces Local.app";++/// The name Local registers the cua MCP server under in coding agents.+const LOCAL_MCP_SERVER_NAME: &str = "cua-local";++/// What Local adds to a bundled skill's name in coding agents' skills folders.+const LOCAL_SKILL_SUFFIX: &str = "-local";++/// The fixed TCP and UDP ports of a channel's `cua-spacesd`.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct Ports {+ /// The spacesd HTTP/WebSocket port (`--port`).+ pub tcp: u16,+ /// The spacesd QUIC port (`--quic-port`, UDP).+ pub quic: u16,+ /// The mesh media UDP port (`cua-mesh`'s `MEDIA_UDP_PORT`), 3212 for+ /// every channel, by design. It is a port of the mesh's own in-process+ /// network, not a socket of the operating system, so a Stable and a+ /// Local host on one Mac never compete for it; and it must match what+ /// the peers dial, which guest Spaces and older cua-spacesd builds+ /// fix at 3212. (`--mesh-udp-port` stays an optional override.)+ pub mesh_udp: u16,+}++/// A Cua Spaces build channel: the released app or a local build.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub enum CuaChannel {+ /// The released app and its CLI (the default).+ #[default]+ Stable,+ /// A locally built "Cua Spaces Local", beside the Stable install.+ Local,+}++impl CuaChannel {+ /// Both channels.+ pub const ALL: [CuaChannel; 2] = [Self::Stable, Self::Local];++ // ----- parsing and resolution ------------------------------------------++ /// Parses a `CUA_CHANNEL` value: `stable` or `local` (any case,+ /// surrounding space ignored). Anything else, empty included, is `None`.+ pub fn parse(value: &str) -> Option<Self> {+ match value.trim().to_ascii_lowercase().as_str() {+ "stable" => Some(Self::Stable),+ "local" => Some(Self::Local),+ _ => None,+ }+ }++ /// The value compiled in with `CUA_DEFAULT_CHANNEL` (a Local build is+ /// compiled with `local`); `None` when the build set none or an unknown+ /// value.+ pub fn build_default() -> Option<Self> {+ option_env!("CUA_DEFAULT_CHANNEL").and_then(Self::parse)+ }++ /// Whether `path` is a Local executable: it is named `cua-local`+ /// (`cua-local.exe`), or it sits inside `Cua Spaces Local.app`. File+ /// names are compared case-insensitively on Windows, where+ /// `CUA-LOCAL.EXE` is the same file.+ pub fn path_is_local(path: &Path) -> bool {+ Self::path_is_local_with(path, cfg!(windows))+ }++ /// [`CuaChannel::path_is_local`], with the case rule given (for tests).+ fn path_is_local_with(path: &Path, ignore_case: bool) -> bool {+ let fold = |s: &str| {+ if ignore_case {+ s.to_ascii_lowercase()+ } else {+ s.to_string()+ }+ };+ let name = fold(+ path.file_name()+ .and_then(|n| n.to_str())+ .unwrap_or_default(),+ );+ let cli = fold(LOCAL_CLI_NAME);+ let app = fold(LOCAL_APP_DIR_NAME);+ name == cli+ || name == format!("{cli}.exe")+ || path+ .components()+ .any(|c| c.as_os_str().to_str().is_some_and(|c| fold(c) == app))+ }++ /// The resolution order, with its three inputs given (for tests and for+ /// callers that carry their own environment):+ ///+ /// 1. `env_value`, the `CUA_CHANNEL` value: when set (not blank) it+ /// decides, and an unknown value is an error naming the accepted+ /// ones;+ /// 2. `build_default`, the compile-time `CUA_DEFAULT_CHANNEL` value+ /// (an unknown value is ignored);+ /// 3. `exe_paths`, the paths the running executable is known by+ /// (`current_exe()`, that with symlinks resolved, and the invocation+ /// path `argv[0]`): Local if any is [`CuaChannel::path_is_local`];+ /// 4. else Stable.+ pub fn resolve(+ env_value: Option<&str>,+ build_default: Option<&str>,+ exe_paths: &[PathBuf],+ ) -> Result<Self, String> {+ if let Some(v) = env_value.filter(|v| !v.trim().is_empty()) {+ return Self::parse(v).ok_or_else(|| {+ format!("{CUA_CHANNEL_VAR}={v:?} is not a Cua channel (stable or local)")+ });+ }+ if let Some(c) = build_default.and_then(Self::parse) {+ return Ok(c);+ }+ if exe_paths.iter().any(|p| Self::path_is_local(p)) {+ return Ok(Self::Local);+ }+ Ok(Self::Stable)+ }++ /// The channel of this process, or an error for an unknown+ /// `CUA_CHANNEL` value. See [`CuaChannel::resolve`].+ pub fn try_current() -> Result<Self, String> {+ Self::resolve(+ std::env::var(CUA_CHANNEL_VAR).ok().as_deref(),+ option_env!("CUA_DEFAULT_CHANNEL"),+ ¤t_exe_paths(),+ )+ }++ /// The channel of this process for a given `CUA_CHANNEL` value (`None`:+ /// unset), the compile-time default and this executable's path. An+ /// unknown value is ignored, as in [`CuaChannel::current`]. For callers+ /// that read their variables through a lookup (`Endpoints::from_lookup`).+ pub fn from_env_value(env_value: Option<&str>) -> Self {+ let build_default = option_env!("CUA_DEFAULT_CHANNEL");+ let exe_paths = current_exe_paths();+ Self::resolve(env_value, build_default, &exe_paths)+ .or_else(|_| Self::resolve(None, build_default, &exe_paths))+ .unwrap_or_default()+ }++ /// The channel of this process. An unknown `CUA_CHANNEL` value is+ /// ignored, so the compile-time default and the executable path still+ /// apply: a typo never moves a Local build onto Stable's names.+ pub fn current() -> Self {+ Self::from_env_value(std::env::var(CUA_CHANNEL_VAR).ok().as_deref())+ }++ /// `stable` or `local`: the value of `CUA_CHANNEL`.+ pub fn name(self) -> &'static str {+ match self {+ Self::Stable => "stable",+ Self::Local => "local",+ }+ }++ /// The `channel` telemetry property: `prod` or `local`. Telemetry only,+ /// never a gate (clients are open source and can claim anything).+ pub fn telemetry_channel(self) -> &'static str {+ match self {+ Self::Stable => "prod",+ Self::Local => "local",+ }+ }++ /// Whether this is the Local channel.+ pub fn is_local(self) -> bool {+ self == Self::Local+ }++ // ----- environment -----------------------------------------------------++ /// The deployment when `CUA_ENV` is not set: Stable keeps+ /// [`CuaEnv::compiled_default`] (prod, or staging for a beta build);+ /// Local is always staging.+ pub fn default_env(self) -> CuaEnv {+ match self {+ Self::Stable => CuaEnv::compiled_default(),+ Self::Local => CuaEnv::Staging,+ }+ }++ /// The deployment for a `CUA_ENV` value (`None`: unset).+ ///+ /// Stable is the rule `CuaEnv::try_from_value` always had: unset is+ /// [`CuaEnv::compiled_default`], blank is prod. Local treats unset and+ /// blank as the default (staging); anything else must be a known+ /// environment, so `prod` is an explicit opt-in and a typo is an error+ /// rather than production.+ pub fn env_from_value(self, value: Option<&str>) -> Result<CuaEnv, String> {+ match self {+ Self::Stable => CuaEnv::stable_from_value(value),+ Self::Local => match value.filter(|v| !v.trim().is_empty()) {+ None => Ok(self.default_env()),+ Some(v) => CuaEnv::parse(v).ok_or_else(|| {+ format!("{CUA_ENV_VAR}={v:?} is not a Cua environment (prod or staging)")+ }),+ },+ }+ }++ /// [`CuaChannel::env_from_value`] with an unknown value answered rather+ /// than refused: production for Stable (what `CuaEnv::current` always+ /// did), staging for Local, so a typo never reaches production.+ pub fn env_or_fallback(self, value: Option<&str>) -> CuaEnv {+ self.env_from_value(value).unwrap_or(match self {+ Self::Stable => CuaEnv::Prod,+ Self::Local => CuaEnv::Staging,+ })+ }++ /// The deployment of this process: [`CuaChannel::current`] and `CUA_ENV`,+ /// or an error for an unknown `CUA_ENV` value.+ pub fn try_current_env() -> Result<CuaEnv, String> {+ Self::current().env_from_value(std::env::var(CUA_ENV_VAR).ok().as_deref())+ }++ /// The deployment of this process. An unknown `CUA_ENV` value falls back+ /// as [`CuaChannel::env_or_fallback`] says (never to production for+ /// Local).+ pub fn current_env() -> CuaEnv {+ Self::current().env_or_fallback(std::env::var(CUA_ENV_VAR).ok().as_deref())+ }++ // ----- the app ---------------------------------------------------------++ /// The bundle identifier, which TCC grants and the app's data are keyed+ /// to. Stable is `com.trycua.spaces.macos` for now; it becomes+ /// `com.trycua.spaces` in a later PR (CUA-1776 "PR 5", with a first-launch+ /// migration), so nothing may hard-code it.+ pub fn bundle_id(self) -> &'static str {+ match self {+ Self::Stable => "com.trycua.spaces.macos",+ Self::Local => "com.trycua.spaces.local",+ }+ }++ /// The app's display name (without `.app`).+ pub fn app_name(self) -> &'static str {+ match self {+ Self::Stable => "Cua Spaces",+ Self::Local => "Cua Spaces Local",+ }+ }++ /// Where the app is installed: `/Applications/Cua Spaces.app`, or+ /// `~/Applications/Cua Spaces Local.app` (never `/Applications`).+ pub fn app_path(self) -> PathBuf {+ match self {+ Self::Stable => PathBuf::from("/Applications").join("Cua Spaces.app"),+ Self::Local => user_home().join("Applications").join(LOCAL_APP_DIR_NAME),+ }+ }++ /// The app's folder name below `~/Library/Application Support`.+ pub fn app_support_dir_name(self) -> &'static str {+ // The same as the bundle id today (macOS convention), but a+ // separate name: the rename migration moves this folder.+ match self {+ Self::Stable => "com.trycua.spaces.macos",+ Self::Local => "com.trycua.spaces.local",+ }+ }++ /// `~/Library/Application Support/<app_support_dir_name>` (settings,+ /// onboarding state).+ pub fn app_support_dir(self) -> PathBuf {+ user_home()+ .join("Library")+ .join("Application Support")+ .join(self.app_support_dir_name())+ }++ /// The URL scheme the app registers (`cua`, `cua-local`), without `://`.+ pub fn url_scheme(self) -> &'static str {+ match self {+ Self::Stable => "cua",+ Self::Local => "cua-local",+ }+ }++ /// The link that opens the Keyvault page of this channel's app:+ /// `cua://keyvault`, or `cua-local://keyvault` for Local. Every link a+ /// Rust crate hands out to the app goes through [`CuaChannel::url_scheme`],+ /// so a Local build never opens the released app.+ pub fn keyvault_url(self) -> String {+ format!("{}://keyvault", self.url_scheme())+ }++ /// [`CuaChannel::keyvault_url`] for this process's channel.+ pub fn current_keyvault_url() -> String {+ Self::current().keyvault_url()+ }++ // ----- the cua home, sign-in and the CLI -------------------------------++ /// The channel's cua home: `~/.cua` or `~/.cua-local`. This is the base:+ /// `CUA_HOME` overrides it, and the environment that is not the+ /// channel's own moves the default below it ([`CuaChannel::env_home_dir`]).+ pub fn home_dir(self) -> PathBuf {+ user_home().join(self.home_dir_name())+ }++ /// The folder name of the channel's cua home below the user's home:+ /// `.cua` or `.cua-local`.+ pub fn home_dir_name(self) -> &'static str {+ match self {+ Self::Stable => ".cua",+ Self::Local => ".cua-local",+ }+ }++ /// The folder below [`CuaChannel::home_dir`] that `env` uses, or `None`+ /// for the home itself. Stable keeps `~/.cua` for production and puts+ /// staging in `envs/staging` ([`CuaEnv::home_subdir`], as it always+ /// has); Local keeps `~/.cua-local` for staging, its default, and puts+ /// production in `envs/prod`. So the four (channel, environment) pairs+ /// never share a home, and no Local home is inside Stable's.+ pub fn home_subdir(self, env: CuaEnv) -> Option<&'static str> {+ match (self, env) {+ (Self::Stable, env) => env.home_subdir(),+ (Self::Local, CuaEnv::Staging) => None,+ (Self::Local, CuaEnv::Prod) => Some("envs/prod"),+ }+ }++ /// The cua home of this channel for `env` when `CUA_HOME` is not set:+ /// [`CuaChannel::home_dir`] plus [`CuaChannel::home_subdir`]+ /// (`~/.cua`, `~/.cua/envs/staging`, `~/.cua-local`,+ /// `~/.cua-local/envs/prod`).+ pub fn env_home_dir(self, env: CuaEnv) -> PathBuf {+ let base = self.home_dir();+ match self.home_subdir(env) {+ Some(sub) => base.join(sub),+ None => base,+ }+ }++ /// The OS credential vault service the session and the device key are+ /// stored under, for `env`. Stable's are [`CuaEnv::keyring_service`];+ /// Local adds `.local` before the `.staging` suffix. One service per+ /// (channel, environment) pair, so a Local build on staging never reads+ /// or replaces the sign-in of a Stable app on staging.+ pub fn keychain_service(self, env: CuaEnv) -> &'static str {+ match (self, env) {+ (Self::Stable, CuaEnv::Prod) => "ai.cua.session",+ (Self::Stable, CuaEnv::Staging) => "ai.cua.session.staging",+ (Self::Local, CuaEnv::Prod) => "ai.cua.session.local",+ (Self::Local, CuaEnv::Staging) => "ai.cua.session.local.staging",+ }+ }++ /// The service older builds stored the Stable session under, which a+ /// build moves an item out of once ([`CuaEnv::legacy_keyring_service`]).+ /// `None` for Local: it is new, has no legacy items, and must never+ /// read, move or delete anything under a name Stable owns.+ pub fn legacy_keychain_service(self, env: CuaEnv) -> Option<&'static str> {+ match self {+ Self::Stable => Some(env.legacy_keyring_service()),+ Self::Local => None,+ }+ }++ /// The channel and deployment of this process, resolved together (one+ /// look at the executable path): [`CuaChannel::current`] and+ /// [`CuaChannel::current_env`].+ pub fn current_with_env() -> (Self, CuaEnv) {+ let channel = Self::current();+ let env = channel.env_or_fallback(std::env::var(CUA_ENV_VAR).ok().as_deref());+ (channel, env)+ }++ /// The Keychain service of this process: [`CuaChannel::keychain_service`]+ /// for [`CuaChannel::current_with_env`].+ pub fn current_keychain_service() -> &'static str {+ let (channel, env) = Self::current_with_env();+ channel.keychain_service(env)+ }++ /// The legacy Keychain service of this process, if its channel has one:+ /// [`CuaChannel::legacy_keychain_service`] for+ /// [`CuaChannel::current_with_env`].+ pub fn current_legacy_keychain_service() -> Option<&'static str> {+ let (channel, env) = Self::current_with_env();+ channel.legacy_keychain_service(env)+ }++ /// The CLI's file name: `cua` or `cua-local`.+ pub fn cli_name(self) -> &'static str {+ match self {+ Self::Stable => "cua",+ Self::Local => LOCAL_CLI_NAME,+ }+ }++ /// Where the first run installs the CLI: `~/.local/bin/<cli_name>`.+ pub fn cli_path(self) -> PathBuf {+ user_home().join(".local").join("bin").join(self.cli_name())+ }++ // ----- coding agents: the MCP server and the skills --------------------++ /// The name the cua MCP server is registered under in a coding agent's+ /// config (Claude Code, Codex, ...): `cua`, or `cua-local` for Local, so+ /// the two channels never write the same entry. It launches+ /// [`CuaChannel::cli_name`] (`cua mcp`, `cua-local mcp`).+ pub fn mcp_server_name(self) -> &'static str {+ match self {+ Self::Stable => "cua",+ Self::Local => LOCAL_MCP_SERVER_NAME,+ }+ }++ /// The suffix a bundled skill's name takes in a coding agent's skills+ /// folder: none for Stable, `-local` for Local.+ pub fn skill_suffix(self) -> &'static str {+ match self {+ Self::Stable => "",+ Self::Local => LOCAL_SKILL_SUFFIX,+ }+ }++ /// The name the bundled skill `bundled` (`cua-spaces`) is installed+ /// under, as its folder and its `name`: `cua-spaces` for Stable,+ /// `cua-spaces-local` for Local. Local's copies sit beside Stable's and+ /// never replace them.+ pub fn skill_install_name(self, bundled: &str) -> String {+ format!("{bundled}{}", self.skill_suffix())+ }++ // ----- host: helper, runner, ports -------------------------------------++ /// The launchd label of the app helper (the login item that runs+ /// spacesd in the user's session).+ pub fn helper_label(self) -> &'static str {+ match self {+ Self::Stable => "com.trycua.spaces.helper",+ Self::Local => "com.trycua.spaces.local.helper",+ }+ }++ /// What the app helper runs: `<home_dir>/helper/service.json`.+ pub fn helper_spec_path(self) -> PathBuf {+ self.home_dir().join("helper").join("service.json")+ }++ /// The launchd label of the plain host runner (`cua host setup` without+ /// the app).+ pub fn host_label(self) -> &'static str {+ match self {+ Self::Stable => "com.trycua.spacesd.host",+ Self::Local => "com.trycua.spacesd.host.local",+ }+ }++ /// The spacesd TCP and QUIC ports, and the mesh media UDP port (the+ /// same for both channels, see [`Ports::mesh_udp`]).+ pub fn ports(self) -> Ports {+ match self {+ Self::Stable => Ports {+ tcp: 3211,+ quic: 3212,+ mesh_udp: 3212,+ },+ Self::Local => Ports {+ tcp: 3221,+ quic: 3222,+ mesh_udp: 3212,+ },+ }+ }++ // ----- Cua Volume ------------------------------------------------------++ /// The Cua Volume's name (and its macOS folder name).+ pub fn volume_name(self) -> &'static str {+ match self {+ Self::Stable => "Cua Volume",+ Self::Local => "Cua Volume Local",+ }+ }++ /// Where the Cua Volume mounts on macOS: `~/<volume_name>`.+ pub fn volume_mount_path(self) -> PathBuf {+ user_home().join(self.volume_name())+ }++ // ----- Lume ------------------------------------------------------------++ /// The Lume server's port.+ pub fn lume_port(self) -> u16 {+ match self {+ Self::Stable => 7777,+ Self::Local => 7787,+ }+ }++ /// The Lume server's URL (`LUME_API`'s default).+ pub fn lume_api(self) -> &'static str {+ match self {+ Self::Stable => "http://127.0.0.1:7777",+ Self::Local => "http://127.0.0.1:7787",+ }+ }++ /// Where Lume keeps its VMs: `~/.lume` or `~/.lume-local`.+ pub fn lume_dir(self) -> PathBuf {+ user_home().join(match self {+ Self::Stable => ".lume",+ Self::Local => ".lume-local",+ })+ }++ /// The launchd label of the Lume daemon.+ pub fn lume_daemon_label(self) -> &'static str {+ match self {+ Self::Stable => "com.trycua.lume_daemon",+ Self::Local => "com.trycua.lume_daemon.local",+ }+ }++ /// The Lume binary's file name: `lume` or `lume-local`.+ pub fn lume_bin_name(self) -> &'static str {+ match self {+ Self::Stable => "lume",+ Self::Local => "lume-local",+ }+ }+}++/// The paths this executable is known by, for [`CuaChannel::resolve`]:+///+/// - `current_exe()`, which is the file itself on Linux (the kernel resolves+/// symlinks), so a `cua-local` link to `target/debug/cua` loses its name;+/// - that path with symlinks resolved (`~/.local/bin/cua-local` may link+/// into the app bundle);+/// - the invocation path, `argv[0]` (a bare name resolved through `PATH`),+/// which keeps the name the process was started under, links included.+fn current_exe_paths() -> Vec<PathBuf> {+ let argv0 = std::env::args_os().next();+ let invoked = invocation_path(argv0.as_deref(), std::env::var_os("PATH").as_deref());+ let exe = std::env::current_exe().ok();+ let real = exe.as_ref().and_then(|e| e.canonicalize().ok());+ collect_exe_paths(exe, real, invoked)+}++/// The distinct paths among the three (see [`current_exe_paths`]).+fn collect_exe_paths(+ exe: Option<PathBuf>,+ real: Option<PathBuf>,+ invoked: Option<PathBuf>,+) -> Vec<PathBuf> {+ let mut paths: Vec<PathBuf> = Vec::new();+ for p in [exe, real, invoked].into_iter().flatten() {+ if !paths.contains(&p) {+ paths.push(p);+ }+ }+ paths+}++/// Where the process was started from: `argv[0]` when it has a directory+/// part; a bare name is looked up in `path_var` like a shell does (the first+/// directory with a file of that name), and stays as the bare name when none+/// has one. `None` for an empty `argv[0]`.+fn invocation_path(argv0: Option<&OsStr>, path_var: Option<&OsStr>) -> Option<PathBuf> {+ let argv0 = argv0.filter(|a| !a.is_empty())?;+ let arg = Path::new(argv0);+ if arg.components().count() > 1 {+ return Some(arg.to_path_buf());+ }+ let names: &[&str] = if cfg!(windows) { &["", ".exe"] } else { &[""] };+ let found = path_var+ .into_iter()+ .flat_map(std::env::split_paths)+ .find_map(|dir| {+ names.iter().find_map(|ext| {+ let mut file = argv0.to_os_string();+ file.push(ext);+ Some(dir.join(file)).filter(|p| p.is_file())+ })+ });+ Some(found.unwrap_or_else(|| arg.to_path_buf()))+}++/// The user's home directory (`$HOME`, else `%USERPROFILE%`), the same+/// lookup [`crate::cua_home`] uses.+fn user_home() -> PathBuf {+ std::env::var_os("HOME")+ .filter(|v| !v.is_empty())+ .or_else(|| std::env::var_os("USERPROFILE"))+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from("."))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn paths(p: &[&str]) -> Vec<PathBuf> {+ p.iter().map(PathBuf::from).collect()+ }++ const LOCAL_EXE: &str = "/Users/ada/Applications/Cua Spaces Local.app/Contents/MacOS/cua";+ const STABLE_EXE: &str = "/Applications/Cua Spaces.app/Contents/MacOS/cua";++ #[test]+ fn parses_channel_names() {+ assert_eq!(CuaChannel::parse("stable"), Some(CuaChannel::Stable));+ assert_eq!(CuaChannel::parse(" LOCAL "), Some(CuaChannel::Local));+ assert_eq!(CuaChannel::parse(""), None);+ assert_eq!(CuaChannel::parse("prod"), None);+ assert_eq!(CuaChannel::parse("dev"), None);+ for c in CuaChannel::ALL {+ assert_eq!(CuaChannel::parse(c.name()), Some(c));+ }+ }++ #[test]+ fn executable_path_selects_local() {+ for p in [+ LOCAL_EXE,+ "/Users/ada/Applications/Cua Spaces Local.app/Contents/MacOS/cua-spacesd",+ "/Users/ada/.local/bin/cua-local",+ "C:/tools/cua-local.exe",+ "cua-local",+ ] {+ assert!(CuaChannel::path_is_local(Path::new(p)), "{p}");+ }+ for p in [+ STABLE_EXE,+ "/Users/ada/.local/bin/cua",+ "/usr/local/bin/cua-spacesd",+ // Only a whole path component or file name counts.+ "/Users/ada/Cua Spaces Local.app.zip/cua",+ "/Users/ada/my-cua-local/cua",+ "/Users/ada/.local/bin/cua-local-old",+ "/Users/ada/repo/target/debug/deps/cua_home-1a2b3c",+ ] {+ assert!(!CuaChannel::path_is_local(Path::new(p)), "{p}");+ }+ }++ #[test]+ fn windows_names_are_case_insensitive() {+ // Windows compares file names without case: `CUA-LOCAL.EXE` is+ // `cua-local.exe`.+ for p in [+ "C:/tools/CUA-LOCAL.EXE",+ "C:/tools/Cua-Local.Exe",+ "C:/tools/cua-local.exe",+ "C:/tools/CUA-LOCAL",+ "C:/Users/ada/Applications/CUA SPACES LOCAL.APP/cua.exe",+ ] {+ assert!(CuaChannel::path_is_local_with(Path::new(p), true), "{p}");+ }+ for p in [+ "C:/tools/CUA.EXE",+ "C:/tools/CUA-LOCAL-OLD.EXE",+ "C:/tools/cua-local.exe.bak",+ "C:/Users/ada/Cua Spaces.app/cua.exe",+ ] {+ assert!(!CuaChannel::path_is_local_with(Path::new(p), true), "{p}");+ }+ // Elsewhere file names are case-sensitive.+ assert!(CuaChannel::path_is_local_with(+ Path::new("/bin/cua-local"),+ false+ ));+ for p in [+ "/bin/CUA-LOCAL",+ "/bin/Cua-Local.exe",+ "/x/CUA SPACES LOCAL.APP/cua",+ ] {+ assert!(!CuaChannel::path_is_local_with(Path::new(p), false), "{p}");+ }+ // This platform's rule is the one `path_is_local` applies.+ assert_eq!(+ CuaChannel::path_is_local(Path::new("/bin/CUA-LOCAL")),+ cfg!(windows)+ );+ }++ #[test]+ fn a_link_named_cua_local_stays_local_when_current_exe_resolves_it() {+ // Linux: `current_exe()` is the file, `target/debug/cua`, not the+ // `cua-local` link the process was started through.+ let real = PathBuf::from("/work/target/debug/cua");+ let link = PathBuf::from("/home/ada/.local/bin/cua-local");+ let known = collect_exe_paths(Some(real.clone()), Some(real.clone()), Some(link.clone()));+ assert_eq!(known, vec![real.clone(), link.clone()]);+ assert_eq!(+ CuaChannel::resolve(None, None, &known),+ Ok(CuaChannel::Local)+ );+ // Without the invocation path the name is lost.+ let lost = collect_exe_paths(Some(real.clone()), Some(real.clone()), None);+ assert_eq!(lost, vec![real.clone()]);+ assert_eq!(+ CuaChannel::resolve(None, None, &lost),+ Ok(CuaChannel::Stable)+ );+ // A Stable binary started as `cua` stays Stable.+ let stable = collect_exe_paths(Some(real.clone()), None, Some(PathBuf::from("cua")));+ assert_eq!(+ CuaChannel::resolve(None, None, &stable),+ Ok(CuaChannel::Stable)+ );+ }++ #[test]+ fn the_invocation_path_is_argv0_and_a_bare_name_is_looked_up_in_path() {+ let dir = tempfile::tempdir().unwrap();+ let other = tempfile::tempdir().unwrap();+ let bin = dir.path().join(if cfg!(windows) {+ "cua-local.exe"+ } else {+ "cua-local"+ });+ std::fs::write(&bin, b"").unwrap();+ let path = std::env::join_paths([other.path(), dir.path()]).unwrap();++ // A bare name: the first PATH directory that has the file.+ let found = invocation_path(Some(OsStr::new("cua-local")), Some(path.as_os_str()));+ assert_eq!(found, Some(bin.clone()));+ // Not on PATH, or no PATH: the bare name stays (its file name still+ // says Local).+ let lost = invocation_path(+ Some(OsStr::new("cua-local")),+ Some(other.path().as_os_str()),+ );+ assert_eq!(lost, Some(PathBuf::from("cua-local")));+ assert_eq!(+ invocation_path(Some(OsStr::new("cua-local")), None),+ Some(PathBuf::from("cua-local"))+ );+ // A name with a directory part is used as it is, PATH or not.+ assert_eq!(+ invocation_path(Some(OsStr::new("./bin/cua-local")), Some(path.as_os_str())),+ Some(PathBuf::from("./bin/cua-local"))+ );+ assert_eq!(+ invocation_path(Some(bin.as_os_str()), None),+ Some(bin.clone())+ );+ // Nothing to go on.+ assert_eq!(+ invocation_path(Some(OsStr::new("")), Some(path.as_os_str())),+ None+ );+ assert_eq!(invocation_path(None, Some(path.as_os_str())), None);+ }++ #[test]+ fn nothing_set_is_stable() {+ let r = |env: Option<&str>, build: Option<&str>, exe: &[&str]| {+ CuaChannel::resolve(env, build, &paths(exe))+ };+ assert_eq!(r(None, None, &[]), Ok(CuaChannel::Stable));+ assert_eq!(r(None, None, &[STABLE_EXE]), Ok(CuaChannel::Stable));+ assert_eq!(r(Some(""), Some(""), &[STABLE_EXE]), Ok(CuaChannel::Stable));+ }++ #[test]+ fn resolution_order_is_env_then_build_default_then_path() {+ let r = |env: Option<&str>, build: Option<&str>, exe: &[&str]| {+ CuaChannel::resolve(env, build, &paths(exe))+ };+ use CuaChannel::{Local, Stable};++ // 3. The path alone.+ assert_eq!(r(None, None, &[LOCAL_EXE]), Ok(Local));+ // Either known path of the executable counts (a symlink's name, or+ // the file it resolves to).+ assert_eq!(+ r(None, None, &["/x/target/debug/cua", "/x/bin/cua-local"]),+ Ok(Local)+ );++ // 2. The compile-time default beats the path, both ways.+ assert_eq!(r(None, Some("local"), &[STABLE_EXE]), Ok(Local));+ assert_eq!(r(None, Some("stable"), &[LOCAL_EXE]), Ok(Stable));+ // An unknown compile-time value is ignored, the path decides.+ assert_eq!(r(None, Some("dev"), &[LOCAL_EXE]), Ok(Local));+ assert_eq!(r(None, Some("dev"), &[STABLE_EXE]), Ok(Stable));++ // 1. CUA_CHANNEL beats the compile-time default and the path.+ assert_eq!(r(Some("stable"), Some("local"), &[LOCAL_EXE]), Ok(Stable));+ assert_eq!(r(Some("local"), Some("stable"), &[STABLE_EXE]), Ok(Local));+ assert_eq!(r(Some(" Local "), None, &[STABLE_EXE]), Ok(Local));+ // Blank means unset.+ assert_eq!(r(Some(" "), Some("local"), &[]), Ok(Local));+ assert_eq!(r(Some(""), None, &[LOCAL_EXE]), Ok(Local));+ }++ #[test]+ fn unknown_channel_value_is_an_error_not_stable() {+ let err =+ CuaChannel::resolve(Some("dev"), Some("local"), &paths(&[LOCAL_EXE])).unwrap_err();+ assert!(+ err.contains("CUA_CHANNEL") && err.contains("stable") && err.contains("local"),+ "{err}"+ );+ }++ #[test]+ fn this_test_binary_is_stable() {+ // A cargo test binary is not a Local executable, and the test+ // environment does not set CUA_CHANNEL.+ if std::env::var_os(CUA_CHANNEL_VAR).is_none() && CuaChannel::build_default().is_none() {+ assert_eq!(CuaChannel::current(), CuaChannel::Stable);+ }+ }++ #[test]+ fn local_defaults_to_staging_and_prod_is_an_opt_in() {+ use CuaChannel::Local;+ // Unset and blank: staging.+ assert_eq!(Local.default_env(), CuaEnv::Staging);+ assert_eq!(Local.env_from_value(None), Ok(CuaEnv::Staging));+ assert_eq!(Local.env_from_value(Some("")), Ok(CuaEnv::Staging));+ assert_eq!(Local.env_from_value(Some(" ")), Ok(CuaEnv::Staging));+ // CUA_ENV set: it wins, prod included.+ assert_eq!(Local.env_from_value(Some("prod")), Ok(CuaEnv::Prod));+ assert_eq!(Local.env_from_value(Some("Production")), Ok(CuaEnv::Prod));+ assert_eq!(Local.env_from_value(Some("staging")), Ok(CuaEnv::Staging));+ // A typo is an error, never production.+ let err = Local.env_from_value(Some("prd")).unwrap_err();+ assert!(err.contains("CUA_ENV") && err.contains("staging"), "{err}");+ }++ #[test]+ fn an_unknown_environment_is_answered_by_channel() {+ use CuaChannel::{Local, Stable};+ for v in [Some("prd"), Some("stagign"), Some("dev")] {+ assert_eq!(Stable.env_or_fallback(v), CuaEnv::Prod, "{v:?}");+ assert_eq!(Local.env_or_fallback(v), CuaEnv::Staging, "{v:?}");+ }+ // A known or unset value is exactly `env_from_value`.+ for v in [None, Some(""), Some("prod"), Some("staging")] {+ assert_eq!(Local.env_or_fallback(v), Local.env_from_value(v).unwrap());+ assert_eq!(Stable.env_or_fallback(v), Stable.env_from_value(v).unwrap());+ }+ }++ #[test]+ fn stable_environment_is_unchanged() {+ use CuaChannel::Stable;+ assert_eq!(Stable.default_env(), CuaEnv::compiled_default());+ for v in [None, Some(""), Some("prod"), Some("staging"), Some("dev")] {+ assert_eq!(+ Stable.env_from_value(v),+ CuaEnv::stable_from_value(v),+ "{v:?}"+ );+ }+ }++ #[test]+ fn stable_names_are_todays_names() {+ let s = CuaChannel::Stable;+ // The Stable bundle id is renamed to com.trycua.spaces in a later PR.+ assert_eq!(s.bundle_id(), "com.trycua.spaces.macos");+ assert_eq!(s.app_name(), "Cua Spaces");+ assert_eq!(s.app_path(), Path::new("/Applications/Cua Spaces.app"));+ assert_eq!(s.app_support_dir_name(), "com.trycua.spaces.macos");+ assert_eq!(s.cli_name(), "cua");+ assert_eq!(s.cli_path(), user_home().join(".local/bin/cua"));+ assert_eq!(s.home_dir(), user_home().join(".cua"));+ assert_eq!(+ s.helper_spec_path(),+ user_home().join(".cua/helper/service.json")+ );+ assert_eq!(s.helper_label(), "com.trycua.spaces.helper");+ assert_eq!(s.host_label(), "com.trycua.spacesd.host");+ assert_eq!(+ s.ports(),+ Ports {+ tcp: 3211,+ quic: 3212,+ mesh_udp: 3212+ }+ );+ assert_eq!(s.url_scheme(), "cua");+ assert_eq!(s.volume_name(), "Cua Volume");+ assert_eq!(s.volume_mount_path(), user_home().join("Cua Volume"));+ assert_eq!(s.lume_api(), "http://127.0.0.1:7777");+ assert_eq!(s.lume_dir(), user_home().join(".lume"));+ assert_eq!(s.lume_daemon_label(), "com.trycua.lume_daemon");+ assert_eq!(s.lume_bin_name(), "lume");+ assert_eq!(s.telemetry_channel(), "prod");+ for env in [CuaEnv::Prod, CuaEnv::Staging] {+ assert_eq!(s.keychain_service(env), env.keyring_service());+ assert_eq!(+ s.legacy_keychain_service(env),+ Some(env.legacy_keyring_service())+ );+ assert_eq!(s.home_subdir(env), env.home_subdir());+ }+ assert_eq!(s.home_dir_name(), ".cua");+ assert_eq!(s.env_home_dir(CuaEnv::Prod), user_home().join(".cua"));+ assert_eq!(+ s.env_home_dir(CuaEnv::Staging),+ user_home().join(".cua/envs/staging")+ );+ }++ #[test]+ fn local_names_are_the_designed_names() {+ let l = CuaChannel::Local;+ assert_eq!(l.bundle_id(), "com.trycua.spaces.local");+ assert_eq!(l.app_name(), "Cua Spaces Local");+ assert_eq!(+ l.app_path(),+ user_home().join("Applications/Cua Spaces Local.app")+ );+ assert_eq!(l.app_support_dir_name(), "com.trycua.spaces.local");+ assert_eq!(+ l.app_support_dir(),+ user_home().join("Library/Application Support/com.trycua.spaces.local")+ );+ assert_eq!(l.cli_name(), "cua-local");+ assert_eq!(l.cli_path(), user_home().join(".local/bin/cua-local"));+ assert_eq!(l.home_dir(), user_home().join(".cua-local"));+ assert_eq!(+ l.helper_spec_path(),+ user_home().join(".cua-local/helper/service.json")+ );+ assert_eq!(l.helper_label(), "com.trycua.spaces.local.helper");+ assert_eq!(l.host_label(), "com.trycua.spacesd.host.local");+ assert_eq!(+ l.ports(),+ Ports {+ tcp: 3221,+ quic: 3222,+ mesh_udp: 3212+ }+ );+ assert_eq!(l.url_scheme(), "cua-local");+ assert_eq!(l.volume_name(), "Cua Volume Local");+ assert_eq!(l.volume_mount_path(), user_home().join("Cua Volume Local"));+ assert_eq!(l.lume_api(), "http://127.0.0.1:7787");+ assert_eq!(l.lume_dir(), user_home().join(".lume-local"));+ assert_eq!(l.lume_daemon_label(), "com.trycua.lume_daemon.local");+ assert_eq!(l.lume_bin_name(), "lume-local");+ assert_eq!(l.telemetry_channel(), "local");+ assert_eq!(l.keychain_service(CuaEnv::Prod), "ai.cua.session.local");+ assert_eq!(+ l.keychain_service(CuaEnv::Staging),+ "ai.cua.session.local.staging"+ );+ // Local is new: no legacy Keychain service to move from.+ for env in [CuaEnv::Prod, CuaEnv::Staging] {+ assert_eq!(l.legacy_keychain_service(env), None);+ }+ }++ #[test]+ fn the_keyvault_link_follows_the_channel_scheme() {+ assert_eq!(CuaChannel::Stable.keyvault_url(), "cua://keyvault");+ assert_eq!(CuaChannel::Local.keyvault_url(), "cua-local://keyvault");+ for c in CuaChannel::ALL {+ assert!(+ c.keyvault_url()+ .starts_with(&format!("{}://", c.url_scheme()))+ );+ }+ // This test binary is Stable unless the environment says otherwise.+ if std::env::var_os(CUA_CHANNEL_VAR).is_none() && CuaChannel::build_default().is_none() {+ assert_eq!(CuaChannel::current_keyvault_url(), "cua://keyvault");+ }+ }++ #[test]+ fn local_prod_has_a_home_of_its_own_below_local() {+ let l = CuaChannel::Local;+ assert_eq!(l.home_dir_name(), ".cua-local");+ // Local's default environment is staging: the home itself.+ assert_eq!(l.home_subdir(CuaEnv::Staging), None);+ assert_eq!(+ l.env_home_dir(CuaEnv::Staging),+ user_home().join(".cua-local")+ );+ // Production is the opt-in, one level down, as Stable's staging is.+ assert_eq!(l.home_subdir(CuaEnv::Prod), Some("envs/prod"));+ assert_eq!(+ l.env_home_dir(CuaEnv::Prod),+ user_home().join(".cua-local/envs/prod")+ );+ // The channel base is unchanged by the environment (the helper's+ // spec lives there).+ assert_eq!(l.home_dir(), user_home().join(".cua-local"));+ }++ #[test]+ fn no_channel_and_environment_pair_shares_a_home_or_a_keychain_service() {+ let pairs: Vec<(CuaChannel, CuaEnv)> = CuaChannel::ALL+ .into_iter()+ .flat_map(|c| [CuaEnv::Prod, CuaEnv::Staging].map(|e| (c, e)))+ .collect();+ assert_eq!(pairs.len(), 4);+ for (i, (c1, e1)) in pairs.iter().enumerate() {+ for (c2, e2) in &pairs[i + 1..] {+ let what = format!("{c1:?}/{e1:?} and {c2:?}/{e2:?}");+ assert_ne!(c1.env_home_dir(*e1), c2.env_home_dir(*e2), "{what}");+ assert_ne!(c1.keychain_service(*e1), c2.keychain_service(*e2), "{what}");+ // Across channels no home is inside the other's.+ if c1 != c2 {+ let (h1, h2) = (c1.env_home_dir(*e1), c2.env_home_dir(*e2));+ assert!(!h1.starts_with(&h2) && !h2.starts_with(&h1), "{what}");+ }+ }+ }+ }++ #[test]+ fn coding_agents_get_names_of_the_channel() {+ assert_eq!(CuaChannel::Stable.mcp_server_name(), "cua");+ assert_eq!(CuaChannel::Local.mcp_server_name(), "cua-local");+ assert_eq!(+ CuaChannel::Stable.skill_install_name("cua-spaces"),+ "cua-spaces"+ );+ assert_eq!(+ CuaChannel::Local.skill_install_name("cua-spaces"),+ "cua-spaces-local"+ );+ // The server is the channel's CLI, so the entry launches its own.+ for c in CuaChannel::ALL {+ assert_eq!(c.mcp_server_name(), c.cli_name());+ }+ // Nothing the two channels register in a coding agent is shared.+ for skill in ["cua-spaces", "cua-driver", "gui-automation"] {+ assert_ne!(+ CuaChannel::Stable.skill_install_name(skill),+ CuaChannel::Local.skill_install_name(skill)+ );+ }+ assert_ne!(+ CuaChannel::Stable.mcp_server_name(),+ CuaChannel::Local.mcp_server_name()+ );+ }++ #[test]+ fn lume_api_names_its_port() {+ for c in CuaChannel::ALL {+ assert_eq!(c.lume_api(), format!("http://127.0.0.1:{}", c.lume_port()));+ }+ }++ #[test]+ fn local_executable_resolves_to_local_names() {+ // The CLI name and the Local app path agree with path detection.+ let l = CuaChannel::Local;+ assert!(CuaChannel::path_is_local(&l.cli_path()));+ assert!(CuaChannel::path_is_local(+ &l.app_path().join("Contents/MacOS/cua")+ ));+ let s = CuaChannel::Stable;+ assert!(!CuaChannel::path_is_local(&s.cli_path()));+ assert!(!CuaChannel::path_is_local(+ &s.app_path().join("Contents/MacOS/cua")+ ));+ }+}diff --git a/libs/cua/crates/cua-home/src/env.rs b/libs/cua/crates/cua-home/src/env.rsindex 89f94b1a63..48bc2648d6 100644--- a/libs/cua/crates/cua-home/src/env.rs+++ b/libs/cua/crates/cua-home/src/env.rs@@ -14,12 +14,26 @@//! | Spaces site | `CUA_SPACES_SITE_URL` | `https://cua.ai` | `https://spaces.staging.cua.ai` |//! | cua home | `CUA_HOME` | `~/.cua` | `~/.cua/envs/staging` |//!+//! (The cua home and the Keychain service in the table are Stable's; Local+//! has its own, see [`crate::channel`].)+//!//! A per-setting override always wins over `CUA_ENV`. With `CUA_ENV` unset,//! the build's default applies: production, or staging for a beta channel//! build (compiled with `CUA_DEFAULT_ENV=staging`).+//!+//! The Local channel (`CUA_CHANNEL=local`, "Cua Spaces Local",+//! [`crate::channel`]) is a different default: with `CUA_ENV` unset it is+//! staging, so a Local build never signs in to production by accident, and+//! its home is `~/.cua-local` itself. `CUA_ENV=prod` is an explicit opt-in,+//! and it gets its own home below that, `~/.cua-local/envs/prod`, so Local's+//! production state never mixes with its staging state or with Stable's.+//! Stable is unchanged. The Keychain service follows the channel too+//! ([`CuaChannel::keychain_service`]).use std::path::PathBuf;+use crate::channel::{CUA_CHANNEL_VAR, CuaChannel};+/// The environment variable that selects the deployment.pub const CUA_ENV_VAR: &str = "CUA_ENV";@@ -44,34 +58,52 @@ impl CuaEnv {}}- /// `CUA_ENV`, or an error naming the accepted values.+ /// `CUA_ENV`, or an error naming the accepted values (or the accepted+ /// channels, for an unknown `CUA_CHANNEL`). The channel decides what an+ /// unset `CUA_ENV` means ([`CuaEnv::build_default`]).pub fn try_current() -> Result<Self, String> {- Self::try_from_value(std::env::var(CUA_ENV_VAR).ok().as_deref())+ CuaChannel::try_current()?.env_from_value(std::env::var(CUA_ENV_VAR).ok().as_deref())}- /// The default when `CUA_ENV` is unset: the build's `CUA_DEFAULT_ENV`- /// (beta channel builds are compiled with `staging`), else production.+ /// The default when `CUA_ENV` is unset: the channel's+ /// ([`CuaChannel::default_env`]). Local is staging; Stable is the+ /// build's `CUA_DEFAULT_ENV` (beta channel builds are compiled with+ /// `staging`), else production ([`CuaEnv::compiled_default`]).pub fn build_default() -> Self {+ CuaChannel::current().default_env()+ }++ /// The Stable channel's default: the build's `CUA_DEFAULT_ENV` (beta+ /// channel builds are compiled with `staging`), else production.+ pub fn compiled_default() -> Self {option_env!("CUA_DEFAULT_ENV").and_then(Self::parse).unwrap_or_default()}/// [`CuaEnv::try_current`] for a given value (`None`: unset, the- /// [`CuaEnv::build_default`]).+ /// [`CuaEnv::build_default`]) in this process's channel.pub fn try_from_value(value: Option<&str>) -> Result<Self, String> {+ CuaChannel::current().env_from_value(value)+ }++ /// The Stable channel's rule for a `CUA_ENV` value (`None`: unset, the+ /// [`CuaEnv::compiled_default`]): what [`CuaEnv::try_from_value`] was+ /// before channels, and what [`CuaChannel::env_from_value`] is for Stable.+ pub(crate) fn stable_from_value(value: Option<&str>) -> Result<Self, String> {match value {- None => Ok(Self::build_default()),+ None => Ok(Self::compiled_default()),Some(v) => Self::parse(v).ok_or_else(|| {format!("{CUA_ENV_VAR}={v:?} is not a Cua environment (prod or staging)")}),}}- /// `CUA_ENV`; an unknown value is production (the `cua` CLI refuses- /// one at startup instead, see [`CuaEnv::try_current`]).+ /// `CUA_ENV`; an unknown value is production for Stable and staging for+ /// Local (the `cua` CLI refuses one at startup instead, see+ /// [`CuaEnv::try_current`]).pub fn current() -> Self {- Self::try_current().unwrap_or_default()+ CuaChannel::current_env()}/// `prod` or `staging`.@@ -130,8 +162,9 @@ impl CuaEnv {}}- /// The OS credential vault service the session, the device key and the- /// other named secrets are stored under. The name is neutral on purpose:+ /// The OS credential vault service Stable stores the session, the device+ /// key and the other named secrets under (Local's are+ /// [`CuaChannel::keychain_service`]). The name is neutral on purpose:/// it used to be the retired Cloud API host (see/// [`CuaEnv::legacy_keyring_service`]).pub fn keyring_service(self) -> &'static str {@@ -153,7 +186,8 @@ impl CuaEnv {}}- /// The cua home below the default `~/.cua` (`None`: `~/.cua` itself).+ /// Stable's cua home below the default `~/.cua` (`None`: `~/.cua`+ /// itself). Use [`CuaChannel::home_subdir`] for the process's channel.pub fn home_subdir(self) -> Option<&'static str> {match self {Self::Prod => None,@@ -181,14 +215,21 @@ pub struct Endpoints {}impl Endpoints {- /// From the process environment (an unknown `CUA_ENV` is production).+ /// From the process environment (an unknown `CUA_ENV` is production on+ /// Stable and staging on Local).pub fn current() -> Self {Self::from_lookup(|k| std::env::var(k).ok())}/// From `get` (a variable lookup; for tests).pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Self {- let env = CuaEnv::try_from_value(get(CUA_ENV_VAR).as_deref()).unwrap_or_default();+ // The channel comes from `get` as well (`CUA_CHANNEL`), so a test's+ // lookup is hermetic; the compile-time default and this process's+ // executable path still apply, as in `CuaChannel::current`. An+ // unknown `CUA_ENV` is production for Stable, as it always was, and+ // never production for Local.+ let channel = CuaChannel::from_env_value(get(CUA_CHANNEL_VAR).as_deref());+ let env = channel.env_or_fallback(get(CUA_ENV_VAR).as_deref());let setting = |var: &str, default: &str| {get(var).map(|v| v.trim().trim_end_matches('/').to_string())@@ -232,26 +273,50 @@ pub fn account_app_url() -> String {Endpoints::current().account_app_url}-/// The cua home a non-production environment uses when `CUA_HOME` is not-/// set: `None` for production or when `CUA_HOME` is set.+/// The cua home a Local channel or a non-default environment uses when+/// `CUA_HOME` is not set: `None` for Stable production or when `CUA_HOME`+/// is set.pub fn env_home() -> Option<PathBuf> {if std::env::var_os("CUA_HOME").is_some_and(|v| !v.is_empty()) {return None;}- CuaEnv::current().home_subdir()?;- Some(crate::cua_home())+ // Local always has a home of its own (`~/.cua-local`, or its `envs/prod`+ // below it); Stable has one only below `~/.cua`.+ let (channel, env) = CuaChannel::current_with_env();+ if !channel.is_local() {+ channel.home_subdir(env)?;+ }+ Some(channel.env_home_dir(env))}-/// Sets `CUA_HOME` to the environment's home when `CUA_ENV` selects a-/// non-production deployment and `CUA_HOME` is unset, so every component-/// (and every child process) that reads `CUA_HOME` directly agrees with-/// [`crate::cua_home`]. Returns the home it set.+/// Sets `CUA_HOME` to the channel's or environment's home when the Local+/// channel, or a non-production `CUA_ENV`, applies and `CUA_HOME` is unset,+/// so every component (and every child process) that reads `CUA_HOME`+/// directly agrees with [`crate::cua_home`]. Returns the home it set.+///+/// A Local process also sets `CUA_CHANNEL=local` and, when `CUA_ENV` is+/// unset or blank, `CUA_ENV` to its default (staging), so every child agrees+/// with it even when it could not tell it is Local from its own path.+/// Stable sets neither.////// # Safety////// Changes the process environment: call it first in `main`, before any/// other thread exists.pub unsafe fn pin_home() -> Option<PathBuf> {+ let channel = CuaChannel::current();+ if channel.is_local() {+ // SAFETY: the caller guarantees no other thread exists.+ unsafe { std::env::set_var(CUA_CHANNEL_VAR, channel.name()) };+ let env_unset = match std::env::var(CUA_ENV_VAR) {+ Ok(v) => v.trim().is_empty(),+ Err(_) => std::env::var_os(CUA_ENV_VAR).is_none(),+ };+ if env_unset {+ // SAFETY: as above.+ unsafe { std::env::set_var(CUA_ENV_VAR, channel.default_env().name()) };+ }+ }let home = env_home()?;// SAFETY: the caller guarantees no other thread exists.unsafe { std::env::set_var("CUA_HOME", &home) };@@ -278,11 +343,64 @@ mod tests {assert_eq!(CuaEnv::parse(" Production "), Some(CuaEnv::Prod));assert_eq!(CuaEnv::parse("STAGING"), Some(CuaEnv::Staging));assert_eq!(CuaEnv::parse("stage"), None);- assert_eq!(CuaEnv::try_from_value(None), Ok(CuaEnv::Prod));- let err = CuaEnv::try_from_value(Some("dev")).unwrap_err();+ // The Stable rule (a test process is Stable unless it says otherwise).+ assert_eq!(+ CuaEnv::stable_from_value(None),+ Ok(CuaEnv::compiled_default())+ );+ assert_eq!(CuaEnv::stable_from_value(Some("")), Ok(CuaEnv::Prod));+ let err = CuaEnv::stable_from_value(Some("dev")).unwrap_err();assert!(err.contains("CUA_ENV") && err.contains("staging"), "{err}");}+ #[test]+ fn local_channel_defaults_to_staging_and_prod_is_an_opt_in() {+ let local = |vars: &[(&str, &str)]| {+ let mut v = vec![("CUA_CHANNEL", "local")];+ v.extend_from_slice(vars);+ endpoints(&v)+ };+ let staging = endpoints(&[("CUA_ENV", "staging"), ("CUA_CHANNEL", "stable")]);+ let prod = endpoints(&[("CUA_ENV", "prod"), ("CUA_CHANNEL", "stable")]);++ // CUA_ENV unset, blank or mistyped: staging, never production.+ for e in [+ local(&[]),+ local(&[("CUA_ENV", "")]),+ local(&[("CUA_ENV", " ")]),+ local(&[("CUA_ENV", "stagign")]),+ local(&[("CUA_ENV", "staging")]),+ ] {+ assert_eq!(e, staging);+ }+ // CUA_ENV=prod is the explicit opt-in.+ assert_eq!(local(&[("CUA_ENV", "prod")]), prod);+ assert_eq!(local(&[("CUA_ENV", "Production")]), prod);+ // A per-setting override still wins.+ assert_eq!(+ local(&[("CUA_RELAY_URL", "http://127.0.0.1:9000")]).relay_url,+ "http://127.0.0.1:9000"+ );+ }++ #[test]+ fn stable_channel_in_a_lookup_is_unchanged() {+ let unset = endpoints(&[("CUA_CHANNEL", "stable")]);+ assert_eq!(unset.env, CuaEnv::compiled_default());+ assert_eq!(unset, endpoints(&[]));+ assert_eq!(+ endpoints(&[("CUA_CHANNEL", "stable"), ("CUA_ENV", "")]).env,+ CuaEnv::Prod+ );+ assert_eq!(+ endpoints(&[("CUA_CHANNEL", "stable"), ("CUA_ENV", "stagign")]).env,+ CuaEnv::Prod,+ "an unknown CUA_ENV is still production on Stable"+ );+ // An unknown channel is ignored: this test binary is Stable.+ assert_eq!(endpoints(&[("CUA_CHANNEL", "dev")]), endpoints(&[]));+ }+#[test]fn unset_is_production_with_todays_endpoints() {let e = endpoints(&[]);diff --git a/libs/cua/crates/cua-home/src/lib.rs b/libs/cua/crates/cua-home/src/lib.rsindex b8987b231d..d9676e7fb3 100644--- a/libs/cua/crates/cua-home/src/lib.rs+++ b/libs/cua/crates/cua-home/src/lib.rs@@ -3,7 +3,10 @@//! [`cua_home`] is `$CUA_HOME`, else `$HOME/.cua` (`%USERPROFILE%\.cua` on//! Windows): the directory that holds the Spaces registry, sandbox state,//! env tokens and credentials. A non-production `CUA_ENV` (see [`env`])-//! moves the default below it (`~/.cua/envs/staging`).+//! moves the default below it (`~/.cua/envs/staging`). The Local channel+//! (see [`channel`]) has a home of its own, `~/.cua-local` (its default+//! environment is staging), with production below it+//! (`~/.cua-local/envs/prod`).//!//! [`guard_write`] refuses a write under the user's *real* `~/.cua` (the//! passwd home, or on Windows the account's profile directory; never@@ -25,6 +28,7 @@use std::io;use std::path::{Path, PathBuf};+pub mod channel;pub mod env;pub mod experimental;pub mod filetable;@@ -81,22 +85,17 @@ pub fn bundled_cua_of(exe: &Path) -> Option<PathBuf> {file(dir.join("resources/native").join(CUA_FILE))}-/// The cua home: `$CUA_HOME`, else `~/.cua` (production) or-/// `~/.cua/envs/<env>` (another `CUA_ENV`).+/// The cua home: `$CUA_HOME`, else the channel's home for the environment+/// ([`channel::CuaChannel::env_home_dir`]): `~/.cua` (Stable, production),+/// `~/.cua/envs/staging` (Stable, staging), `~/.cua-local` (Local, staging)+/// or `~/.cua-local/envs/prod` (Local, with the `CUA_ENV=prod` opt-in, which+/// is an opt-in to the production deployment, not to Stable's home).pub fn cua_home() -> PathBuf {if let Some(h) = std::env::var_os("CUA_HOME").filter(|v| !v.is_empty()) {return PathBuf::from(h);}- let home = std::env::var_os("HOME")- .filter(|v| !v.is_empty())- .or_else(|| std::env::var_os("USERPROFILE"))- .map(PathBuf::from)- .unwrap_or_else(|| PathBuf::from("."));- let base = home.join(".cua");- match env::CuaEnv::current().home_subdir() {- Some(sub) => base.join(sub),- None => base,- }+ let (channel, env) = channel::CuaChannel::current_with_env();+ channel.env_home_dir(env)}/// The user's real `~/.cua`, from the account database rather than `$HOME`diff --git a/libs/cua/crates/cua-home/tests/channel_invocation_test.rs b/libs/cua/crates/cua-home/tests/channel_invocation_test.rsnew file mode 100644index 0000000000..1a629fd6bb--- /dev/null+++ b/libs/cua/crates/cua-home/tests/channel_invocation_test.rs@@ -0,0 +1,78 @@+//! A `cua-local` symlink is Local even where `current_exe()` resolves+//! symlinks (Linux), so the link's name is lost (CUA-1776).+//!+//! The test re-runs its own binary as a child, through a real symlink named+//! `cua-local`, and has the child report the channel it resolves. Nothing is+//! set but the executable path: `CUA_CHANNEL` is removed.++#![cfg(unix)]++use std::path::Path;+use std::process::Command;++use cua_home::channel::{CUA_CHANNEL_VAR, CuaChannel};++const PROBE_VAR: &str = "CUA_CHANNEL_PROBE";++/// The child: prints the channel this process resolves. A no-op when the+/// test suite runs it as an ordinary test.+#[test]+fn probe() {+ if std::env::var_os(PROBE_VAR).is_some() {+ println!("resolved channel={}", CuaChannel::current().name());+ }+}++/// Runs this test binary as `program` (a path, or a bare name looked up in+/// `path`) and returns the channel it printed.+fn channel_of(program: impl AsRef<std::ffi::OsStr>, path: Option<&Path>) -> String {+ let mut cmd = Command::new(program);+ cmd.args(["--exact", "probe", "--nocapture", "--test-threads=1"])+ .env(PROBE_VAR, "1")+ .env_remove(CUA_CHANNEL_VAR);+ if let Some(path) = path {+ cmd.env("PATH", path);+ }+ let out = cmd.output().expect("run the probe");+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(+ out.status.success(),+ "probe failed: {stdout} {}",+ String::from_utf8_lossy(&out.stderr)+ );+ stdout+ .lines()+ // libtest prints `test probe ... ` before the test's own output.+ .find_map(|l| l.split("resolved channel=").nth(1))+ .unwrap_or_else(|| panic!("the probe printed no channel: {stdout}"))+ .trim()+ .to_string()+}++#[test]+fn a_symlink_named_cua_local_resolves_local() {+ if CuaChannel::build_default().is_some() {+ // A build with CUA_DEFAULT_CHANNEL decides before the path does.+ return;+ }+ let exe = std::env::current_exe().expect("test binary");+ // The control: the binary under its own name is Stable.+ assert_eq!(channel_of(&exe, None), "stable");++ let dir = tempfile::Builder::new()+ .prefix("cua-local-link-")+ .tempdir()+ .expect("temp dir");+ let link = dir.path().join("cua-local");+ std::os::unix::fs::symlink(&exe, &link).expect("symlink");++ // Started by path through the link.+ assert_eq!(channel_of(&link, None), "local");+ // Started by bare name, found on PATH (argv[0] is just `cua-local`).+ assert_eq!(channel_of("cua-local", Some(dir.path())), "local");++ // A link under another name is Stable.+ let other = dir.path().join("cua");+ std::os::unix::fs::symlink(&exe, &other).expect("symlink");+ assert_eq!(channel_of(&other, None), "stable");+}diff --git a/libs/cua/crates/cua-home/tests/channel_isolation_test.rs b/libs/cua/crates/cua-home/tests/channel_isolation_test.rsnew file mode 100644index 0000000000..f7dab7735b--- /dev/null+++ b/libs/cua/crates/cua-home/tests/channel_isolation_test.rs@@ -0,0 +1,390 @@+//! The Stable and Local channels must not share a name (CUA-1776).+//!+//! A locally built "Cua Spaces Local" runs beside the released app on one+//! Mac. If any path, launchd label, bundle id, port, URL scheme or Keychain+//! service were the same, the two would overwrite each other's files, take+//! each other's sockets, answer each other's `cua://` links or read each+//! other's sign-in. This collects every name `CuaChannel` owns, for both+//! channels, and asserts that the two sets do not intersect.+//!+//! Modelled on Cua Driver's `testkit_host_state_isolation_test.rs`, which+//! guards the same idea for `cua-driver` and `cua-driver-local`.++use std::collections::BTreeSet;+use std::path::PathBuf;++use cua_home::channel::CuaChannel;+use cua_home::env::CuaEnv;++const ENVS: [CuaEnv; 2] = [CuaEnv::Prod, CuaEnv::Staging];++/// The four (channel, environment) pairs a Mac can run: Stable and Local,+/// each on prod and on staging.+fn pairs() -> Vec<(CuaChannel, CuaEnv)> {+ CuaChannel::ALL+ .into_iter()+ .flat_map(|c| ENVS.map(|e| (c, e)))+ .collect()+}++/// What a cua home holds that two processes must never share: the daemon's+/// socket and files, the credentials file, the Keyvault, the host's tokens+/// and spacesd's data.+const HOME_ENTRIES: [&str; 7] = [+ "cua.sock",+ "daemon.json",+ "credentials.json",+ "keyvault.sock",+ "keyvault",+ "host",+ "spacesd",+];++/// Every file-system location the channel owns.+fn paths(c: CuaChannel) -> Vec<(&'static str, PathBuf)> {+ vec![+ ("app", c.app_path()),+ ("app support", c.app_support_dir()),+ ("cli", c.cli_path()),+ ("cua home", c.home_dir()),+ ("cua home (prod)", c.env_home_dir(CuaEnv::Prod)),+ ("cua home (staging)", c.env_home_dir(CuaEnv::Staging)),+ ("helper spec", c.helper_spec_path()),+ ("volume mount", c.volume_mount_path()),+ ("lume vms", c.lume_dir()),+ ]+}++/// Every launchd label.+fn labels(c: CuaChannel) -> Vec<(&'static str, String)> {+ vec![+ ("app helper", c.helper_label().to_string()),+ ("host runner", c.host_label().to_string()),+ ("lume daemon", c.lume_daemon_label().to_string()),+ ]+}++/// Every other name another program could look a thing up by: bundle id+/// (TCC grants), URL scheme, Keychain services, binary and volume names.+fn identifiers(c: CuaChannel) -> Vec<(String, String)> {+ let mut ids = vec![+ ("bundle id".to_string(), c.bundle_id().to_string()),+ ("app name".to_string(), c.app_name().to_string()),+ (+ "app support dir".to_string(),+ c.app_support_dir_name().to_string(),+ ),+ ("url scheme".to_string(), c.url_scheme().to_string()),+ ("cli name".to_string(), c.cli_name().to_string()),+ ("volume name".to_string(), c.volume_name().to_string()),+ ("lume binary".to_string(), c.lume_bin_name().to_string()),+ ("lume api".to_string(), c.lume_api().to_string()),+ ("telemetry".to_string(), c.telemetry_channel().to_string()),+ // What the Spaces app writes into a coding agent's config (Claude+ // Code, Codex, ...): the MCP server entry and the skill folders.+ (+ "agent mcp server".to_string(),+ c.mcp_server_name().to_string(),+ ),+ ];+ for skill in [+ "cua-spaces",+ "cua-volume",+ "cua-sandboxes",+ "cua-driver",+ "gui-automation",+ ] {+ ids.push((format!("agent skill {skill}"), c.skill_install_name(skill)));+ }+ for env in ENVS {+ ids.push((+ format!("keychain service ({})", env.name()),+ c.keychain_service(env).to_string(),+ ));+ // The service an older build used, which this channel moves from.+ if let Some(legacy) = c.legacy_keychain_service(env) {+ ids.push((+ format!("legacy keychain service ({})", env.name()),+ legacy.to_string(),+ ));+ }+ }+ ids+}++/// Every Keychain service a process of the channel reads, writes, moves from+/// or deletes, for either environment.+fn keychain_services_touched(c: CuaChannel) -> BTreeSet<&'static str> {+ ENVS.iter()+ .flat_map(|e| [Some(c.keychain_service(*e)), c.legacy_keychain_service(*e)])+ .flatten()+ .collect()+}++/// Every port a channel listens on, as `proto:port`. The mesh media port+/// is left out: it is a port of the mesh's own in-process network, not a+/// socket of the operating system, so two channels cannot collide on it,+/// and it is 3212 for both by design (guest Spaces and older cua-spacesd+/// builds fix it there; see `Ports::mesh_udp`).+fn ports(c: CuaChannel) -> BTreeSet<String> {+ let p = c.ports();+ [+ format!("tcp:{}", p.tcp),+ format!("udp:{}", p.quic),+ format!("tcp:{}", c.lume_port()),+ ]+ .into_iter()+ .collect()+}++fn values<K, V: Ord + Clone>(items: &[(K, V)]) -> BTreeSet<V> {+ items.iter().map(|(_, v)| v.clone()).collect()+}++#[test]+fn stable_and_local_paths_never_overlap() {+ let stable = paths(CuaChannel::Stable);+ let local = paths(CuaChannel::Local);+ for (sk, s) in &stable {+ for (lk, l) in &local {+ // Not equal, and neither inside the other: a Local home under+ // `~/.cua` would be wiped or scanned by Stable.+ assert!(+ !s.starts_with(l) && !l.starts_with(s),+ "Stable {sk} {s:?} and Local {lk} {l:?} overlap"+ );+ }+ }+}++#[test]+fn local_paths_stay_out_of_the_system_applications_folder() {+ let app = CuaChannel::Local.app_path();+ assert!(+ !app.starts_with("/Applications"),+ "Local installs to ~/Applications, never over /Applications: {app:?}"+ );+}++#[test]+fn stable_and_local_launchd_labels_never_overlap() {+ let stable = values(&labels(CuaChannel::Stable));+ let local = values(&labels(CuaChannel::Local));+ let both: Vec<_> = stable.intersection(&local).collect();+ assert!(both.is_empty(), "shared launchd labels: {both:?}");+ // Each channel's own labels are distinct from one another.+ assert_eq!(stable.len(), 3);+ assert_eq!(local.len(), 3);+}++/// The one port the channels do share, on purpose: the mesh media UDP port+/// lives on the mesh's own network (not the OS), and the peers dial 3212.+#[test]+fn the_mesh_media_port_is_shared_by_design() {+ let (s, l) = (CuaChannel::Stable.ports(), CuaChannel::Local.ports());+ assert_eq!((s.mesh_udp, l.mesh_udp), (3212, 3212));+ assert!(s.tcp != l.tcp && s.quic != l.quic, "the OS ports differ");+}++#[test]+fn stable_and_local_ports_never_overlap() {+ let stable = ports(CuaChannel::Stable);+ let local = ports(CuaChannel::Local);+ let both: Vec<_> = stable.intersection(&local).collect();+ assert!(both.is_empty(), "shared ports: {both:?}");+}++#[test]+fn stable_and_local_schemes_and_keychain_services_never_overlap() {+ let stable = identifiers(CuaChannel::Stable);+ let local = identifiers(CuaChannel::Local);+ // Kind by kind, so a failure names what is shared.+ for (sk, s) in &stable {+ for (lk, l) in &local {+ assert!(+ s != l,+ "Stable {sk} and Local {lk} are both {s:?}: the two builds would share it"+ );+ }+ }+ // The URL scheme and every Keychain service, spelled out.+ assert_ne!(+ CuaChannel::Stable.url_scheme(),+ CuaChannel::Local.url_scheme()+ );+ let keychain = |c: CuaChannel| -> BTreeSet<&'static str> {+ ENVS.iter().map(|e| c.keychain_service(*e)).collect()+ };+ let (ks, kl) = (keychain(CuaChannel::Stable), keychain(CuaChannel::Local));+ assert_eq!(ks.len(), ENVS.len(), "one Keychain service per environment");+ assert_eq!(kl.len(), ENVS.len(), "one Keychain service per environment");+ assert!(+ ks.is_disjoint(&kl),+ "shared Keychain services: {ks:?} {kl:?}"+ );+}++#[test]+fn every_channel_and_environment_has_a_keychain_service_of_its_own() {+ // The session and the device key live under it: a Local build on+ // staging must not read, replace or sign out a Stable app on staging.+ let services: BTreeSet<&str> = pairs()+ .into_iter()+ .map(|(c, e)| c.keychain_service(e))+ .collect();+ assert_eq!(+ services.len(),+ 4,+ "a Keychain service is shared: {services:?}"+ );++ // Nothing Stable touches (its own services and the legacy ones it moves+ // from and deletes) is a Local service, in either environment.+ let stable = keychain_services_touched(CuaChannel::Stable);+ let local = keychain_services_touched(CuaChannel::Local);+ assert!(+ stable.is_disjoint(&local),+ "Keychain services both channels touch: {stable:?} {local:?}"+ );+ // Local has no legacy items, so it touches exactly its own two.+ assert_eq!(local.len(), ENVS.len());+ assert_eq!(+ local,+ BTreeSet::from(["ai.cua.session.local", "ai.cua.session.local.staging"])+ );+ // Stable's are what its sign-in has always used, plus the legacy pair.+ assert_eq!(+ stable,+ BTreeSet::from([+ "ai.cua.session",+ "ai.cua.session.staging",+ "run.cua.ai",+ "staging.run.cua.ai",+ ])+ );+}++#[test]+fn every_channel_and_environment_has_a_home_of_its_own() {+ // The home holds the daemon, its sockets, the registry, the Keyvault,+ // the credentials file and spacesd's data: two builds on one home would+ // take each other's daemon and read each other's sign-in.+ let mut seen: Vec<(String, PathBuf)> = Vec::new();+ for (c, e) in pairs() {+ let home = c.env_home_dir(e);+ let what = format!("{} on {}", c.name(), e.name());+ seen.push((format!("{what}: the home"), home.clone()));+ for entry in HOME_ENTRIES {+ seen.push((format!("{what}: {entry}"), home.join(entry)));+ }+ }+ let unique: BTreeSet<&PathBuf> = seen.iter().map(|(_, p)| p).collect();+ assert_eq!(+ unique.len(),+ seen.len(),+ "two pairs share a path: {seen:#?}"+ );++ // Across channels, no home or file in it is inside the other's: a Local+ // home under `~/.cua` would be wiped or scanned by Stable, and the other+ // way round. (Within a channel the second environment sits below the+ // first, as Stable's staging always has.)+ for (sc, se) in pairs()+ .into_iter()+ .filter(|(c, _)| *c == CuaChannel::Stable)+ {+ for (lc, le) in pairs().into_iter().filter(|(c, _)| *c == CuaChannel::Local) {+ let (s, l) = (sc.env_home_dir(se), lc.env_home_dir(le));+ assert!(+ !s.starts_with(&l) && !l.starts_with(&s),+ "stable on {} {s:?} and local on {} {l:?} overlap",+ se.name(),+ le.name()+ );+ }+ }+}++#[test]+fn local_prod_never_uses_the_stable_or_the_local_staging_home() {+ let local_prod = CuaChannel::Local.env_home_dir(CuaEnv::Prod);+ for (c, e) in pairs() {+ if (c, e) == (CuaChannel::Local, CuaEnv::Prod) {+ continue;+ }+ assert_ne!(+ c.env_home_dir(e),+ local_prod,+ "{} on {}",+ c.name(),+ e.name()+ );+ }+ // It is the opt-in's own folder below Local's, mirroring how Stable+ // keeps its staging below `~/.cua`.+ assert_eq!(+ local_prod,+ CuaChannel::Local.home_dir().join("envs").join("prod")+ );+ assert_eq!(+ CuaChannel::Stable.env_home_dir(CuaEnv::Staging),+ CuaChannel::Stable.home_dir().join("envs").join("staging")+ );+}++#[test]+fn no_name_is_shared_across_kinds_either() {+ // A Local label equal to a Stable path, or a Stable scheme equal to a+ // Local volume name, would be a bug of the same kind. Compare every+ // string either channel owns against every string of the other.+ let all = |c: CuaChannel| -> BTreeSet<String> {+ let mut set: BTreeSet<String> = paths(c)+ .into_iter()+ .map(|(_, p)| p.to_string_lossy().into_owned())+ .collect();+ set.extend(values(&labels(c)));+ set.extend(values(&identifiers(c)));+ set.extend(ports(c));+ set+ };+ let (s, l) = (all(CuaChannel::Stable), all(CuaChannel::Local));+ let both: Vec<_> = s.intersection(&l).collect();+ assert!(both.is_empty(), "names both channels use: {both:?}");+}++#[test]+fn local_builds_never_use_production_by_default() {+ assert_eq!(CuaChannel::Local.default_env(), CuaEnv::Staging);+ assert_eq!(CuaChannel::Local.env_from_value(None), Ok(CuaEnv::Staging));+}++#[test]+fn every_local_name_says_local() {+ // A cheap guard that a new Local name was derived, not copied from+ // Stable: every non-numeric Local identifier and label contains+ // "local" (any case). Ports are checked by the overlap test above.+ let l = CuaChannel::Local;+ for (kind, name) in labels(l)+ .into_iter()+ .map(|(k, v)| (k.to_string(), v))+ .chain(+ identifiers(l)+ .into_iter()+ // The Lume API is a URL of 127.0.0.1 and a port.+ .filter(|(k, _)| k != "lume api"),+ )+ {+ assert!(+ name.to_ascii_lowercase().contains("local"),+ "Local {kind} {name:?} does not say local"+ );+ }+ for (kind, path) in paths(l) {+ assert!(+ path.to_string_lossy()+ .to_ascii_lowercase()+ .contains("local"),+ "Local {kind} {path:?} does not say local"+ );+ }+}diff --git a/libs/cua/crates/cua-home/tests/local_home_test.rs b/libs/cua/crates/cua-home/tests/local_home_test.rsnew file mode 100644index 0000000000..940dcf6721--- /dev/null+++ b/libs/cua/crates/cua-home/tests/local_home_test.rs@@ -0,0 +1,336 @@+//! The cua home, environment and Keychain service of every channel and+//! environment (CUA-1776): Stable and Local, each on prod and staging.+//!+//! `cua_home()`, `CuaEnv::current()` and `pin_home()` read the process+//! environment, which a test in this process cannot change safely, so each+//! case re-runs this test binary as a child with the environment it needs+//! (a temporary `HOME`, no `CUA_*` variable but the ones given) and has the+//! child report what it resolves.++use std::path::Path;+use std::process::Command;++use cua_home::channel::CuaChannel;+use cua_home::env::{CuaEnv, pin_home};++const PROBE_VAR: &str = "CUA_HOME_PROBE";+const CUA_VARS: [&str; 3] = ["CUA_CHANNEL", "CUA_ENV", "CUA_HOME"];++/// The child: prints what this process resolves, then what `pin_home`+/// leaves in the environment. A no-op as an ordinary test.+#[test]+fn probe() {+ if std::env::var_os(PROBE_VAR).is_none() {+ return;+ }+ let show = |name: &str, v: String| println!("probe {name}={v}");+ show("channel", CuaChannel::current().name().to_string());+ show("env", CuaEnv::current().name().to_string());+ show(+ "try_current",+ match CuaEnv::try_current() {+ Ok(e) => e.name().to_string(),+ Err(e) => format!("error: {e}"),+ },+ );+ show("home", cua_home::cua_home().display().to_string());+ show(+ "keychain",+ CuaChannel::current_keychain_service().to_string(),+ );+ show(+ "legacy keychain",+ CuaChannel::current_legacy_keychain_service()+ .unwrap_or("none")+ .to_string(),+ );+ // SAFETY: the probe is its own process and runs one test, on the main+ // thread (`--test-threads=1`).+ let pinned = unsafe { pin_home() };+ show(+ "pinned",+ pinned.map_or("none".to_string(), |p| p.display().to_string()),+ );+ for var in CUA_VARS {+ show(+ &format!("after {var}"),+ std::env::var(var).unwrap_or_else(|_| "unset".into()),+ );+ }+}++/// What the child resolved, by name.+struct Probe(Vec<(String, String)>);++impl Probe {+ fn get(&self, name: &str) -> &str {+ self.0+ .iter()+ .find(|(k, _)| k == name)+ .map(|(_, v)| v.as_str())+ .unwrap_or_else(|| panic!("the probe printed no {name}: {:?}", self.0))+ }+}++/// Runs the probe with `home` as `$HOME` and `vars` as the only `CUA_*`+/// variables.+fn run(home: &Path, vars: &[(&str, &str)]) -> Probe {+ let exe = std::env::current_exe().expect("test binary");+ let mut cmd = Command::new(exe);+ cmd.args(["--exact", "probe", "--nocapture", "--test-threads=1"])+ .env(PROBE_VAR, "1")+ .env("HOME", home);+ for var in CUA_VARS {+ cmd.env_remove(var);+ }+ for (k, v) in vars {+ cmd.env(k, v);+ }+ let out = cmd.output().expect("run the probe");+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(+ out.status.success(),+ "probe failed: {stdout} {}",+ String::from_utf8_lossy(&out.stderr)+ );+ Probe(+ stdout+ .lines()+ // libtest prints `test probe ... ` before the first line.+ .filter_map(|l| l.rsplit_once("probe ").map(|(_, rest)| rest))+ .filter_map(|l| l.split_once('='))+ .map(|(k, v)| (k.to_string(), v.trim().to_string()))+ .collect(),+ )+}++/// A build with a compiled-in default decides before the variables do.+fn built_with_defaults() -> bool {+ CuaChannel::build_default().is_some() || option_env!("CUA_DEFAULT_ENV").is_some()+}++fn display(home: &Path, rest: &str) -> String {+ home.join(rest).display().to_string()+}++#[test]+fn local_home_is_cua_local_on_staging_and_envs_prod_below_it_on_prod() {+ if built_with_defaults() {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path();+ let local_home = display(home, ".cua-local");+ let local_prod_home = display(home, ".cua-local/envs/prod");++ // Local, `CUA_ENV` unset: staging, and `~/.cua-local` itself.+ let p = run(home, &[("CUA_CHANNEL", "local")]);+ assert_eq!(p.get("channel"), "local");+ assert_eq!(p.get("env"), "staging");+ assert_eq!(p.get("try_current"), "staging");+ assert_eq!(p.get("home"), local_home);+ assert!(!p.get("home").contains("envs"));++ // `CUA_ENV=staging` spelled out is the same.+ let p = run(home, &[("CUA_CHANNEL", "local"), ("CUA_ENV", "staging")]);+ assert_eq!(p.get("env"), "staging");+ assert_eq!(p.get("home"), local_home);++ // Blank `CUA_ENV` means unset.+ let p = run(home, &[("CUA_CHANNEL", "local"), ("CUA_ENV", " ")]);+ assert_eq!(p.get("env"), "staging");+ assert_eq!(p.get("home"), local_home);++ // `CUA_ENV=prod` is the explicit opt-in, and it has a home of its own+ // below Local's, so it never shares one with Local's staging state.+ for prod in ["prod", "Production"] {+ let p = run(home, &[("CUA_CHANNEL", "local"), ("CUA_ENV", prod)]);+ assert_eq!(p.get("env"), "prod");+ assert_eq!(p.get("home"), local_prod_home, "CUA_ENV={prod}");+ }++ // A mistyped `CUA_ENV` is an error at startup and staging, not prod,+ // anywhere that has to answer anyway.+ let p = run(home, &[("CUA_CHANNEL", "local"), ("CUA_ENV", "prd")]);+ assert_eq!(p.get("env"), "staging");+ assert_eq!(p.get("home"), local_home);+ assert!(p.get("try_current").contains("CUA_ENV"), "{:?}", p.0);++ // `CUA_HOME` still wins, on both environments.+ let elsewhere = display(home, "elsewhere");+ for env in ["staging", "prod"] {+ let p = run(+ home,+ &[+ ("CUA_CHANNEL", "local"),+ ("CUA_ENV", env),+ ("CUA_HOME", &elsewhere),+ ],+ );+ assert_eq!(p.get("home"), elsewhere);+ }+}++/// All four (channel, environment) pairs, as one process sees them: each+/// has a home and a Keychain service of its own, and none is shared.+#[test]+fn every_channel_and_environment_has_its_own_home_and_keychain_service() {+ if built_with_defaults() {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path();++ // (CUA_CHANNEL, CUA_ENV, resolved env, home below $HOME, Keychain+ // service, legacy Keychain service).+ let cases: [(&str, &str, &str, &str, &str, &str); 4] = [+ (+ "stable",+ "prod",+ "prod",+ ".cua",+ "ai.cua.session",+ "run.cua.ai",+ ),+ (+ "stable",+ "staging",+ "staging",+ ".cua/envs/staging",+ "ai.cua.session.staging",+ "staging.run.cua.ai",+ ),+ (+ "local",+ "staging",+ "staging",+ ".cua-local",+ "ai.cua.session.local.staging",+ "none",+ ),+ (+ "local",+ "prod",+ "prod",+ ".cua-local/envs/prod",+ "ai.cua.session.local",+ "none",+ ),+ ];+ let mut homes = Vec::new();+ let mut services = Vec::new();+ for (channel, env, want_env, want_home, want_service, want_legacy) in cases {+ let p = run(home, &[("CUA_CHANNEL", channel), ("CUA_ENV", env)]);+ let what = format!("{channel} on {env}");+ assert_eq!(p.get("channel"), channel, "{what}");+ assert_eq!(p.get("env"), want_env, "{what}");+ assert_eq!(p.get("home"), display(home, want_home), "{what}");+ assert_eq!(p.get("keychain"), want_service, "{what}");+ assert_eq!(p.get("legacy keychain"), want_legacy, "{what}");+ homes.push(p.get("home").to_string());+ services.push(p.get("keychain").to_string());+ }+ // Local on staging is also what Local with nothing set resolves to, and+ // Stable with nothing set is Stable on prod.+ let p = run(home, &[("CUA_CHANNEL", "local")]);+ assert_eq!(p.get("keychain"), "ai.cua.session.local.staging");+ assert_eq!(p.get("legacy keychain"), "none");+ let p = run(home, &[]);+ assert_eq!(p.get("keychain"), "ai.cua.session");+ assert_eq!(p.get("legacy keychain"), "run.cua.ai");++ for list in [&homes, &services] {+ let mut sorted = list.clone();+ sorted.sort();+ sorted.dedup();+ assert_eq!(sorted.len(), 4, "a home or service is shared: {list:?}");+ }+ // No Local home is inside a Stable home, or the other way round.+ let (stable_homes, local_homes) = homes.split_at(2);+ for s in stable_homes {+ for l in local_homes {+ let (s, l) = (Path::new(s), Path::new(l));+ assert!(+ !s.starts_with(l) && !l.starts_with(s),+ "{s:?} and {l:?} overlap"+ );+ }+ }+}++#[test]+fn stable_homes_are_unchanged() {+ if built_with_defaults() {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path();++ let p = run(home, &[]);+ assert_eq!(p.get("channel"), "stable");+ assert_eq!(p.get("env"), "prod");+ assert_eq!(p.get("home"), display(home, ".cua"));++ let p = run(home, &[("CUA_CHANNEL", "stable")]);+ assert_eq!(p.get("home"), display(home, ".cua"));++ let p = run(home, &[("CUA_ENV", "staging")]);+ assert_eq!(p.get("env"), "staging");+ assert_eq!(p.get("home"), display(home, ".cua/envs/staging"));++ // A blank `CUA_ENV` and a mistyped one are production, as before.+ let p = run(home, &[("CUA_ENV", "")]);+ assert_eq!(p.get("env"), "prod");+ let p = run(home, &[("CUA_ENV", "prd")]);+ assert_eq!(p.get("env"), "prod");+ assert!(p.get("try_current").contains("CUA_ENV"), "{:?}", p.0);++ // An unknown channel is an error at startup, and Stable elsewhere.+ let p = run(home, &[("CUA_CHANNEL", "dev")]);+ assert_eq!(p.get("channel"), "stable");+ assert!(p.get("try_current").contains("CUA_CHANNEL"), "{:?}", p.0);+}++#[test]+fn pin_home_pins_local_for_every_child_and_leaves_stable_alone() {+ if built_with_defaults() {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let home = dir.path();+ let local_home = display(home, ".cua-local");++ // Local: channel, environment and home, all pinned.+ let p = run(home, &[("CUA_CHANNEL", "local")]);+ assert_eq!(p.get("pinned"), local_home);+ assert_eq!(p.get("after CUA_CHANNEL"), "local");+ assert_eq!(p.get("after CUA_ENV"), "staging");+ assert_eq!(p.get("after CUA_HOME"), local_home);++ // Local with the production opt-in: the opt-in is kept, and the home+ // pinned is Local's production one (Stable production would not pin one).+ let p = run(home, &[("CUA_CHANNEL", "local"), ("CUA_ENV", "prod")]);+ assert_eq!(p.get("pinned"), display(home, ".cua-local/envs/prod"));+ assert_eq!(p.get("after CUA_ENV"), "prod");+ assert_eq!(+ p.get("after CUA_HOME"),+ display(home, ".cua-local/envs/prod")+ );++ // A `CUA_HOME` that is set is never replaced.+ let elsewhere = display(home, "elsewhere");+ let p = run(home, &[("CUA_CHANNEL", "local"), ("CUA_HOME", &elsewhere)]);+ assert_eq!(p.get("pinned"), "none");+ assert_eq!(p.get("after CUA_HOME"), elsewhere);+ assert_eq!(p.get("after CUA_CHANNEL"), "local");++ // Stable production pins nothing; Stable staging pins its home only.+ let p = run(home, &[]);+ assert_eq!(p.get("pinned"), "none");+ assert_eq!(p.get("after CUA_CHANNEL"), "unset");+ assert_eq!(p.get("after CUA_ENV"), "unset");+ assert_eq!(p.get("after CUA_HOME"), "unset");+ let p = run(home, &[("CUA_ENV", "staging")]);+ assert_eq!(p.get("pinned"), display(home, ".cua/envs/staging"));+ assert_eq!(p.get("after CUA_CHANNEL"), "unset");+}diff --git a/libs/cua/crates/cua-home/tests/swift_app_names_test.rs b/libs/cua/crates/cua-home/tests/swift_app_names_test.rsnew file mode 100644index 0000000000..aa7b7e3808--- /dev/null+++ b/libs/cua/crates/cua-home/tests/swift_app_names_test.rs@@ -0,0 +1,56 @@+//! The Swift app names its Application Support folder (where the first-run+//! state, `onboarding.json`, and the settings live) from the bundle's+//! `CuaChannel`; the names must be `CuaChannel`'s (CUA-1776). A Local app+//! that read Stable's folder would show the first run again at every launch+//! in the one case, and share Stable's settings in the other.+//!+//! The Swift source is read straight from the repository; the check is+//! skipped where the app is not there (the crate published on crates.io).++use cua_home::channel::CuaChannel;+use std::path::PathBuf;++fn source() -> Option<String> {+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(+ "../../../../apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift",+ );+ std::fs::read_to_string(path).ok()+}++#[test]+fn the_swift_app_support_folder_is_the_channels() {+ let Some(swift) = source() else {+ eprintln!("SKIP: no apps/cua-spaces-macos in this checkout");+ return;+ };+ // `bundleIdentifier = isLocalChannel ? "<local>" : "<stable>"`, and+ // the support folder is that identifier below Application Support.+ let want = format!(+ "isLocalChannel ? \"{}\" : \"{}\"",+ CuaChannel::Local.app_support_dir_name(),+ CuaChannel::Stable.app_support_dir_name()+ );+ assert!(+ swift.contains(&want),+ "AppEnvironment.bundleIdentifier no longer reads `{want}`: the Swift app's support \+ folder (onboarding.json, settings.json) must be CuaChannel::app_support_dir_name"+ );+ assert!(+ swift.contains(".appendingPathComponent(bundleIdentifier, isDirectory: true)"),+ "AppEnvironment.supportDirectory is not built from bundleIdentifier"+ );+ // The first-run state and the settings sit in that folder, nowhere else.+ for file in ["settings.json", "onboarding.json"] {+ assert!(+ swift.contains(&format!(+ "supportDirectory.appendingPathComponent(\"{file}\")"+ )),+ "{file} is not read from the support folder"+ );+ }+ // Both channels' folders differ, and Local's is not inside Stable's.+ assert_ne!(+ CuaChannel::Stable.app_support_dir(),+ CuaChannel::Local.app_support_dir()+ );+}diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex 134c512aca..d74b13b489 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -9,6 +9,7 @@ use crate::preflight::{self, SessionProbe};use crate::relay::{AccountTokens, ConnectedClient, MachinePatch, RegisterRequest, RelayClient};use crate::service::{self, RunnerKind, ServiceManager, ServiceSpec, ServiceState};use crate::{Error, Result};+use cua_home::channel::{CUA_CHANNEL_VAR, CuaChannel};use serde::{Deserialize, Serialize};use std::net::SocketAddr;use std::path::{Path, PathBuf};@@ -429,7 +430,7 @@ pub fn permission_hints(os: &str, driver: &Path) -> Vec<PermissionHint> {/// runs it, else "cua-spacesd (<path>)".fn service_name(driver: &Path) -> String {if crate::service::is_app_helper_launcher(driver) {- crate::service::APP_HELPER_NAME.to_string()+ crate::service::app_helper_name().to_string()} else {format!("cua-spacesd ({})", driver.display())}@@ -452,7 +453,7 @@ pub fn local_network_hint(os: &str, provide_spaces: bool, driver: &Path) -> Opti}let d = service_name(driver);let short = if crate::service::is_app_helper_launcher(driver) {- crate::service::APP_HELPER_NAME+ crate::service::app_helper_name()} else {"cua-spacesd"};@@ -775,6 +776,10 @@ fn valid_machine_id(id: &str) -> bool {&& !id.ends_with('-')}+/// The environment variables of cua-spacesd's `--port` and `--quic-port`.+const PORT_ENV: &str = "CUA_ENV_PORT";+const QUIC_PORT_ENV: &str = "CUA_ENV_QUIC_PORT";+/// The environment variable with this machine's cost per hour (US/// dollars), passed on to the host service.pub const HOST_USD_PER_HOUR: &str = "CUA_HOST_USD_PER_HOUR";@@ -1050,6 +1055,13 @@ impl Host {/// The command line the service runs.pub fn service_spec(&self, config: &HostConfig) -> ServiceSpec {+ self.service_spec_for(config, CuaChannel::current())+ }++ /// [`Host::service_spec`] for a build of `channel`: the ports it+ /// serves on are the channel's, so Cua Spaces Local's host runs beside+ /// the Stable one.+ pub(crate) fn service_spec_for(&self, config: &HostConfig, channel: CuaChannel) -> ServiceSpec {let p = &self.paths;let s = |p: PathBuf| p.to_string_lossy().into_owned();let mut args: Vec<String> = match config.mode.as_str() {@@ -1131,6 +1143,31 @@ impl Host {]);}let mut env = vec![("CUA_ENV_LOG".into(), "info".into())];+ // A Local build's host service is told its channel and ports, so it+ // runs beside a Stable one (3211 TCP, 3212 QUIC). Nothing is passed+ // for Stable: its service is the one it has always been, on+ // cua-spacesd's own defaults.+ //+ // The ports go twice. `--port` (the listener of a joined host;+ // `--listen` names a direct one) and `--quic-port` are on the+ // command line, where they show in `ps` and win; the environment+ // carries the same for everything the service starts, which reads+ // `CUA_ENV_PORT` and `CUA_CHANNEL`. The mesh media port is not+ // passed: it is 3212 for every channel, by design (a port of the+ // mesh's own network that guest Spaces and older cua-spacesd builds+ // fix, so two hosts on one Mac do not compete for it).+ let (ports, stable) = (channel.ports(), CuaChannel::Stable.ports());+ if ports.tcp != stable.tcp {+ args.extend(["--port".to_string(), ports.tcp.to_string()]);+ env.push((PORT_ENV.into(), ports.tcp.to_string()));+ }+ if ports.quic != stable.quic {+ args.extend(["--quic-port".to_string(), ports.quic.to_string()]);+ env.push((QUIC_PORT_ENV.into(), ports.quic.to_string()));+ }+ if channel != CuaChannel::Stable {+ env.push((CUA_CHANNEL_VAR.into(), channel.name().into()));+ }if let Some(mesh) = &config.mesh {env.push(("CUA_MESH".into(), mesh.clone()));}diff --git a/libs/cua/crates/cua-host/src/service.rs b/libs/cua/crates/cua-host/src/service.rsindex 912faa8e8b..5d6d398edc 100644--- a/libs/cua/crates/cua-host/src/service.rs+++ b/libs/cua/crates/cua-host/src/service.rs@@ -24,6 +24,7 @@//! input, so the task (not a service) runs the driver in the user session.use crate::{Error, Result};+use cua_home::channel::CuaChannel;use serde::{Deserialize, Serialize};use std::path::{Path, PathBuf};use std::process::Command;@@ -31,8 +32,6 @@ use std::sync::Mutex;/// Service name / label used everywhere.pub const SERVICE_NAME: &str = "cua-spacesd-host";-/// launchd label.-pub const LAUNCHD_LABEL: &str = "com.trycua.spacesd.host";/// Windows task name.pub const WINDOWS_TASK_NAME: &str = "Cua\\SpacesdHost";@@ -42,17 +41,25 @@ pub const WINDOWS_TASK_NAME: &str = "Cua\\SpacesdHost";/// test home) never replaces the first one's service.pub fn instance_suffix() -> String {suffix_for(+ CuaChannel::Stable,std::env::var_os("CUA_HOME").as_deref(),std::env::var_os("HOME").as_deref(),)}-fn suffix_for(cua_home: Option<&std::ffi::OsStr>, user_home: Option<&std::ffi::OsStr>) -> String {+/// [`instance_suffix`] for `channel`: a home is "separate" when it is not+/// that channel's own (`~/.cua`, or `~/.cua-local` for Local), so Local's+/// own home adds nothing to its label.+fn suffix_for(+ channel: CuaChannel,+ cua_home: Option<&std::ffi::OsStr>,+ user_home: Option<&std::ffi::OsStr>,+) -> String {use sha2::{Digest, Sha256};let Some(home) = cua_home.filter(|h| !h.is_empty()).map(PathBuf::from) else {return String::new();};- let default = user_home.map(|h| PathBuf::from(h).join(".cua"));+ let default = user_home.map(|h| channel_home_in(channel, Path::new(h)));if Some(&home) == default.as_ref() {return String::new();}@@ -60,25 +67,62 @@ fn suffix_for(cua_home: Option<&std::ffi::OsStr>, user_home: Option<&std::ffi::Oformat!("-{}", &hex::encode(digest)[..8])}+/// `channel`'s cua home below `user_home`: `<user_home>/.cua`, or+/// `<user_home>/.cua-local`. The directory name is [`CuaChannel::home_dir`]'s+/// (the one place that owns it); only the user home is the caller's.+fn channel_home_in(channel: CuaChannel, user_home: &Path) -> PathBuf {+ match channel.home_dir().file_name() {+ Some(name) => user_home.join(name),+ None => channel.home_dir(),+ }+}+/// The systemd unit name of this home's host service.pub fn service_name() -> String {format!("{SERVICE_NAME}{}", instance_suffix())}-/// The launchd label of this home's host service.+/// The launchd label of this home's host service: the channel's+/// [`CuaChannel::host_label`] (`com.trycua.spacesd.host`, or+/// `com.trycua.spacesd.host.local` for Local) plus [`suffix_for`].pub fn launchd_label() -> String {- format!("{LAUNCHD_LABEL}{}", instance_suffix())+ launchd_label_for(+ CuaChannel::current(),+ std::env::var_os("CUA_HOME").as_deref(),+ std::env::var_os("HOME").as_deref(),+ )+}++fn launchd_label_for(+ channel: CuaChannel,+ cua_home: Option<&std::ffi::OsStr>,+ user_home: Option<&std::ffi::OsStr>,+) -> String {+ format!(+ "{}{}",+ channel.host_label(),+ suffix_for(channel, cua_home, user_home)+ )+}++/// What macOS shows for the app's login item (System Settings: Privacy &+/// Security, Login Items): the app's own name, since the app's executable+/// runs it. "Cua Spaces", or "Cua Spaces Local" for the Local build.+pub fn app_helper_name() -> &'static str {+ CuaChannel::current().app_name()}-/// launchd label of the Cua Spaces app's login item ([`AppHelper`]).-pub const APP_HELPER_LABEL: &str = "com.trycua.spaces.helper";-/// What macOS shows for it (System Settings: Privacy & Security, Login-/// Items): the app's own name, since the app's executable runs it.-pub const APP_HELPER_NAME: &str = "Cua Spaces";/// The cua-spacesd the app ships, inside the app (the service runs only/// this one).pub const APP_HELPER_DAEMON: &str = "Contents/MacOS/cua-spacesd";-/// The `SMAppService.agent` plist, inside the app.-pub const APP_HELPER_PLIST: &str = "Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist";+/// The `SMAppService.agent` plist of `channel`'s app, inside the app:+/// `Contents/Library/LaunchAgents/<helper label>.plist` (the label is+/// [`CuaChannel::helper_label`]; `build-app.sh` stamps it per channel).+pub fn app_helper_plist(channel: CuaChannel) -> String {+ format!(+ "Contents/Library/LaunchAgents/{}.plist",+ channel.helper_label()+ )+}/// The app's own executable (which registers the helper), inside the app.pub const APP_EXECUTABLE: &str = "Contents/MacOS/CuaSpacesMac";@@ -1258,11 +1302,22 @@ impl ServiceManager for ProcessRunner {// ------------------------------------------------------------- app helper-/// `~/.cua/helper/service.json`: what the Cua Spaces app's helper runs (a-/// [`ServiceSpec`] as JSON, 0600). A fixed path under the user's home: the-/// helper's launchd plist is sealed in the app and cannot name a cua home.+/// `~/.cua/helper/service.json` (Local: `~/.cua-local/helper/service.json`):+/// what the Cua Spaces app's helper runs (a [`ServiceSpec`] as JSON, 0600).+/// A fixed path under the user's home, per channel: the helper's launchd+/// plist is sealed in the app and cannot name a cua home, so the app's+/// `CuaHome` Info.plist key (stamped per channel) says where it is. Read by+/// `ServiceLauncher.swift`.pub fn helper_spec_path(user_home: &Path) -> PathBuf {- user_home.join(".cua").join("helper").join("service.json")+ helper_spec_path_for(CuaChannel::current(), user_home)+}++/// [`helper_spec_path`] for `channel`: [`CuaChannel::helper_spec_path`]+/// below `user_home`.+pub fn helper_spec_path_for(channel: CuaChannel, user_home: &Path) -> PathBuf {+ channel_home_in(channel, user_home)+ .join("helper")+ .join("service.json")}/// The service's launcher inside `app`: the app's own executable (what@@ -1272,9 +1327,16 @@ pub fn app_helper_launcher(app: &Path) -> PathBuf {app.join(APP_EXECUTABLE)}-/// Whether `app` is a Cua Spaces app that carries the helper.-pub fn has_app_helper(app: &Path) -> bool {- app.join(APP_HELPER_PLIST).is_file()+/// Whether `app` is a Cua Spaces app of `channel` that carries the helper.+///+/// The channel is told by the helper's plist, which is named after the+/// channel's launchd label ([`app_helper_plist`]): a Stable app has only+/// `com.trycua.spaces.helper.plist`, a Local app only+/// `com.trycua.spaces.local.helper.plist`. So an app of the other channel+/// never matches, and one channel never registers, starts or writes the spec+/// of the other's helper.+pub fn has_app_helper(app: &Path, channel: CuaChannel) -> bool {+ app.join(app_helper_plist(channel)).is_file()&& app.join(APP_HELPER_DAEMON).is_file()&& app.join(APP_EXECUTABLE).is_file()}@@ -1290,32 +1352,81 @@ pub fn is_app_helper_launcher(launcher: &Path) -> bool {.is_some_and(|app| app.extension().is_some_and(|e| e == "app"))}-/// The installed Cua Spaces app that carries the helper, if any (macOS):-/// `CUA_SPACES_APP` when set (empty or `none`: no app), else the app this-/// process runs from (the app itself, or the `cua` it links onto PATH),-/// else `/Applications/Cua Spaces.app`, else `~/Applications/Cua Spaces.app`.+/// The installed Cua Spaces app that carries the helper, if any (macOS), of+/// this process's channel ([`CuaChannel::current`]); see+/// [`find_app_helper_for`].pub fn find_app_helper() -> Option<PathBuf> {+ find_app_helper_for(CuaChannel::current())+}++/// The installed Cua Spaces app of `channel` that carries the helper, if+/// any (macOS): `CUA_SPACES_APP` when set (empty or `none`: no app), else+/// the app this process runs from (the app itself, or the `cua` it links+/// onto PATH), else where the channel installs its app+/// ([`CuaChannel::app_path`]: `/Applications/Cua Spaces.app`, or+/// `~/Applications/Cua Spaces Local.app`), else `~/Applications` under the+/// channel's app name.+///+/// An app of the other channel is never picked, whichever way it was named+/// ([`has_app_helper`]): a Local CLI must never drive Stable's helper, nor+/// the Stable CLI the Local one.+pub fn find_app_helper_for(channel: CuaChannel) -> Option<PathBuf> {if !cfg!(target_os = "macos") {return None;}- if let Some(v) = std::env::var_os("CUA_SPACES_APP") {- let p = PathBuf::from(&v);- return (!v.is_empty() && v != "none" && has_app_helper(&p)).then_some(p);- }- let mut candidates = vec![];- if let Ok(exe) = std::env::current_exe().and_then(|e| e.canonicalize()) {- // .../X.app/Contents/MacOS/<exe>- if let Some(app) = exe.parent().and_then(Path::parent).and_then(Path::parent)- && app.extension().is_some_and(|e| e == "app")- {- candidates.push(app.to_path_buf());- }- }- candidates.push(PathBuf::from("/Applications/Cua Spaces.app"));- if let Some(home) = std::env::var_os("HOME") {- candidates.push(PathBuf::from(home).join("Applications/Cua Spaces.app"));+ let spaces_app = std::env::var_os("CUA_SPACES_APP");+ let exe_app = std::env::current_exe()+ .and_then(|e| e.canonicalize())+ .ok()+ .and_then(|exe| app_containing(&exe));+ let candidates = app_helper_candidates(channel, exe_app, std::env::var_os("HOME").as_deref());+ pick_app_helper(channel, spaces_app.as_deref(), candidates)+}++/// `X.app` for `.../X.app/Contents/MacOS/<exe>`.+fn app_containing(exe: &Path) -> Option<PathBuf> {+ exe.parent()+ .and_then(Path::parent)+ .and_then(Path::parent)+ .filter(|app| app.extension().is_some_and(|e| e == "app"))+ .map(Path::to_path_buf)+}++/// The places to look for `channel`'s app, best first: the app this process+/// runs from, where the channel installs its app, then `~/Applications`+/// under the channel's app name. Never the other channel's.+fn app_helper_candidates(+ channel: CuaChannel,+ exe_app: Option<PathBuf>,+ home: Option<&std::ffi::OsStr>,+) -> Vec<PathBuf> {+ let mut candidates: Vec<PathBuf> = exe_app.into_iter().collect();+ candidates.push(channel.app_path());+ if let Some(home) = home {+ candidates.push(+ PathBuf::from(home)+ .join("Applications")+ .join(format!("{}.app", channel.app_name())),+ );}- candidates.into_iter().find(|a| has_app_helper(a))+ candidates+}++/// The app of `channel` with the helper among `candidates`, or the one+/// `CUA_SPACES_APP` names (`spaces_app`; empty or `none`: no app, and the+/// candidates are not consulted).+fn pick_app_helper(+ channel: CuaChannel,+ spaces_app: Option<&std::ffi::OsStr>,+ candidates: Vec<PathBuf>,+) -> Option<PathBuf> {+ if let Some(v) = spaces_app {+ let p = PathBuf::from(v);+ return (!v.is_empty() && v != "none" && has_app_helper(&p, channel)).then_some(p);+ }+ candidates+ .into_iter()+ .find(|app| has_app_helper(app, channel))}/// What `CuaSpacesMac --service-helper <command>` reports: the@@ -1337,20 +1448,31 @@ pub struct HelperRegistration {/// macOS holds the app responsible for it, so Screen Recording and/// Accessibility are granted to "Cua Spaces" (bundle id/// `com.trycua.spaces.macos`, the Cua team), once, and survive app updates.+/// The Local app's helper is its own (launchd label+/// `com.trycua.spaces.local.helper`, spec in `~/.cua-local`), beside+/// Stable's./// (A separate helper bundle got two names in System Settings: macOS lists/// a login item's Screen Recording under the app that contains it.)pub struct AppHelper {/// The app (`/Applications/Cua Spaces.app`).pub app: PathBuf,- /// [`helper_spec_path`].+ /// [`helper_spec_path_for`] the app's channel.pub spec_path: PathBuf,/// The user id (`gui/<uid>`).pub uid: u32,+ /// The channel of `app`: names its launchd label and the app in+ /// messages.+ pub channel: CuaChannel,}impl AppHelper {- /// The helper of `app` for the current user.+ /// The helper of `app` (of this process's channel) for the current user.pub fn for_current_user(app: PathBuf, user_home: &Path) -> Self {+ Self::for_channel(CuaChannel::current(), app, user_home)+ }++ /// The helper of `app`, the app of `channel`, for the current user.+ pub fn for_channel(channel: CuaChannel, app: PathBuf, user_home: &Path) -> Self {#[cfg(unix)]// SAFETY: getuid has no preconditions.let uid = unsafe { libc::getuid() };@@ -1358,13 +1480,14 @@ impl AppHelper {let uid = 0;Self {app,- spec_path: helper_spec_path(user_home),+ spec_path: helper_spec_path_for(channel, user_home),uid,+ channel,}}fn target(&self) -> String {- format!("gui/{}/{APP_HELPER_LABEL}", self.uid)+ format!("gui/{}/{}", self.uid, self.channel.helper_label())}/// `CuaSpacesMac --service-helper <command>`.@@ -1426,7 +1549,7 @@ impl ServiceManager for AppHelper {let _ = self.registration("unregister");}let reg = self.registration("register")?;- helper_registered(®)+ helper_registered(®, self.channel.app_name())}fn start(&self) -> Result<()> {// A fresh registration can take a moment to reach launchd.@@ -1443,14 +1566,15 @@ impl ServiceManager for AppHelper {std::thread::sleep(std::time::Duration::from_secs(2));if result.is_ok() && !self.state().running && self.spawn_failed() {let _ = self.registration("unregister");- helper_registered(&self.registration("register")?)?;+ helper_registered(&self.registration("register")?, self.channel.app_name())?;std::thread::sleep(std::time::Duration::from_millis(500));result = kick();}result.map(drop).map_err(|e| {+ let name = self.channel.app_name();Error::Service(format!(- "macOS did not start {APP_HELPER_NAME} ({e}); if it keeps failing, turn on \- Cua Spaces in System Settings > General > Login Items & Extensions"+ "macOS did not start {name} ({e}); if it keeps failing, turn on \+ {name} in System Settings > General > Login Items & Extensions"))})}@@ -1482,24 +1606,24 @@ impl ServiceManager for AppHelper {.as_deref().is_some_and(|p| p.contains("state = running")),kind: RunnerKind::AppHelper.as_str().into(),- detail: format!("{APP_HELPER_NAME} in {}", self.app.display()),+ detail: format!("{} in {}", self.channel.app_name(), self.app.display()),}}}/// A registration that did not leave the helper allowed to run, in words.-fn helper_registered(reg: &HelperRegistration) -> Result<()> {+fn helper_registered(reg: &HelperRegistration, name: &str) -> Result<()> {match (reg.status.as_str(), ®.error) {("enabled", _) => Ok(()),("requires-approval", _) => Err(Error::Service(format!(- "macOS needs you to allow {APP_HELPER_NAME}: turn on Cua Spaces in System Settings > \+ "macOS needs you to allow {name}: turn on {name} in System Settings > \General > Login Items & Extensions, then try again"))),(status, Some(e)) => Err(Error::Service(format!(- "Cua Spaces could not register {APP_HELPER_NAME} ({status}): {e}"+ "{name} could not register {name} ({status}): {e}"))),(status, None) => Err(Error::Service(format!(- "Cua Spaces could not register {APP_HELPER_NAME} ({status})"+ "{name} could not register {name} ({status})"))),}}@@ -1529,15 +1653,16 @@ impl ServiceManager for MissingAppHelper {installed: false,running: false,kind: RunnerKind::AppHelper.as_str().into(),- detail: format!("{APP_HELPER_NAME}: the Cua Spaces app is not installed"),+ detail: format!("{}: the Cua Spaces app is not installed", app_helper_name()),}}}fn missing_app() -> Error {Error::Service(format!(- "{APP_HELPER_NAME} lives in the Cua Spaces app, which is not installed; install it \- again, or run `cua host setup --runner launchd`"+ "{name} lives in the Cua Spaces app, which is not installed; install it \+ again, or run `cua host setup --runner launchd`",+ name = app_helper_name()))}@@ -1928,17 +2053,18 @@ mod tests {fn the_app_helper_is_found_by_its_bundle_layout() {let dir = tempfile::tempdir().unwrap();let app = dir.path().join("Cua Spaces.app");- assert!(!has_app_helper(&app));- for f in [APP_HELPER_PLIST, APP_EXECUTABLE] {+ let stable = CuaChannel::Stable;+ assert!(!has_app_helper(&app, stable));+ for f in [app_helper_plist(stable).as_str(), APP_EXECUTABLE] {std::fs::create_dir_all(app.join(f).parent().unwrap()).unwrap();std::fs::write(app.join(f), "").unwrap();}assert!(- !has_app_helper(&app),+ !has_app_helper(&app, stable),"an app without its own cua-spacesd (0.9.4)");std::fs::write(app.join(APP_HELPER_DAEMON), "").unwrap();- assert!(has_app_helper(&app));+ assert!(has_app_helper(&app, stable));let launcher = app_helper_launcher(&app);assert_eq!(launcher, app.join(APP_EXECUTABLE));assert!(is_app_helper_launcher(&launcher));@@ -1949,23 +2075,245 @@ mod tests {"/Users/ada/.cua/host/bin/cua-spacesd")));assert_eq!(- helper_spec_path(Path::new("/Users/ada")),+ helper_spec_path_for(stable, Path::new("/Users/ada")),Path::new("/Users/ada/.cua/helper/service.json"));}+ /// A Cua Spaces app of `channel` with the helper, in `parent`.+ fn fake_app(parent: &Path, channel: CuaChannel) -> PathBuf {+ let app = parent.join(format!("{}.app", channel.app_name()));+ for f in [+ app_helper_plist(channel).as_str(),+ APP_HELPER_DAEMON,+ APP_EXECUTABLE,+ ] {+ std::fs::create_dir_all(app.join(f).parent().unwrap()).unwrap();+ std::fs::write(app.join(f), "").unwrap();+ }+ app+ }++ #[test]+ fn stable_keeps_its_helper_names() {+ let stable = CuaChannel::Stable;+ assert_eq!(stable.helper_label(), "com.trycua.spaces.helper");+ assert_eq!(+ app_helper_plist(stable),+ "Contents/Library/LaunchAgents/com.trycua.spaces.helper.plist"+ );+ assert_eq!(+ helper_spec_path_for(stable, Path::new("/Users/ada")),+ Path::new("/Users/ada/.cua/helper/service.json")+ );+ assert_eq!(stable.host_label(), "com.trycua.spacesd.host");+ let user = Some(std::ffi::OsStr::new("/Users/ada"));+ assert_eq!(+ launchd_label_for(stable, None, user),+ "com.trycua.spacesd.host"+ );+ assert_eq!(+ launchd_label_for(stable, Some(std::ffi::OsStr::new("/Users/ada/.cua")), user),+ "com.trycua.spacesd.host"+ );+ let helper = AppHelper::for_channel(+ stable,+ PathBuf::from("/Applications/Cua Spaces.app"),+ Path::new("/Users/ada"),+ );+ assert_eq!(+ helper.target(),+ format!("gui/{}/com.trycua.spaces.helper", helper.uid)+ );+ assert_eq!(+ helper.spec_path,+ Path::new("/Users/ada/.cua/helper/service.json")+ );+ }++ #[test]+ fn local_has_its_own_helper_names() {+ let local = CuaChannel::Local;+ assert_eq!(local.helper_label(), "com.trycua.spaces.local.helper");+ assert_eq!(+ app_helper_plist(local),+ "Contents/Library/LaunchAgents/com.trycua.spaces.local.helper.plist"+ );+ assert_eq!(+ helper_spec_path_for(local, Path::new("/Users/ada")),+ Path::new("/Users/ada/.cua-local/helper/service.json")+ );+ // The plain runner: Local's own home adds no suffix; another home+ // still gets one, so two Local test homes stay apart.+ let user = Some(std::ffi::OsStr::new("/Users/ada"));+ assert_eq!(+ launchd_label_for(local, None, user),+ "com.trycua.spacesd.host.local"+ );+ assert_eq!(+ launchd_label_for(+ local,+ Some(std::ffi::OsStr::new("/Users/ada/.cua-local")),+ user+ ),+ "com.trycua.spacesd.host.local"+ );+ let other = launchd_label_for(local, Some(std::ffi::OsStr::new("/tmp/h")), user);+ assert!(+ other.starts_with("com.trycua.spacesd.host.local-"),+ "{other}"+ );+ // Stable's home is not Local's: it is a separate home to Local.+ assert!(+ launchd_label_for(local, Some(std::ffi::OsStr::new("/Users/ada/.cua")), user)+ .starts_with("com.trycua.spacesd.host.local-")+ );+ let helper = AppHelper::for_channel(+ local,+ PathBuf::from("/Users/ada/Applications/Cua Spaces Local.app"),+ Path::new("/Users/ada"),+ );+ assert_eq!(+ helper.target(),+ format!("gui/{}/com.trycua.spaces.local.helper", helper.uid)+ );+ assert_eq!(+ helper.spec_path,+ Path::new("/Users/ada/.cua-local/helper/service.json")+ );+ // Nothing of Local's is Stable's.+ for (l, s) in [+ (local.helper_label(), CuaChannel::Stable.helper_label()),+ (local.host_label(), CuaChannel::Stable.host_label()),+ ] {+ assert_ne!(l, s);+ }+ assert_ne!(+ helper_spec_path_for(local, Path::new("/Users/ada")),+ helper_spec_path_for(CuaChannel::Stable, Path::new("/Users/ada"))+ );+ }++ #[test]+ fn an_app_of_the_other_channel_is_never_the_helper() {+ let dir = tempfile::tempdir().unwrap();+ let stable_app = fake_app(dir.path(), CuaChannel::Stable);+ let local_app = fake_app(dir.path(), CuaChannel::Local);+ assert_ne!(stable_app, local_app);++ // Each app is the helper of its own channel only.+ assert!(has_app_helper(&stable_app, CuaChannel::Stable));+ assert!(has_app_helper(&local_app, CuaChannel::Local));+ assert!(!has_app_helper(&stable_app, CuaChannel::Local));+ assert!(!has_app_helper(&local_app, CuaChannel::Stable));++ // Both installed: each channel finds its own, whatever the order.+ let both = vec![stable_app.clone(), local_app.clone()];+ let both_rev = vec![local_app.clone(), stable_app.clone()];+ for found in [both, both_rev] {+ assert_eq!(+ pick_app_helper(CuaChannel::Stable, None, found.clone()),+ Some(stable_app.clone())+ );+ assert_eq!(+ pick_app_helper(CuaChannel::Local, None, found),+ Some(local_app.clone())+ );+ }+ // Only the other channel's app installed: no helper.+ assert_eq!(+ pick_app_helper(CuaChannel::Local, None, vec![stable_app.clone()]),+ None+ );+ assert_eq!(+ pick_app_helper(CuaChannel::Stable, None, vec![local_app.clone()]),+ None+ );++ // `CUA_SPACES_APP` cannot point a channel at the other one's app.+ let spaces_app = |p: &Path| Some(p.as_os_str().to_owned());+ assert_eq!(+ pick_app_helper(+ CuaChannel::Local,+ spaces_app(&stable_app).as_deref(),+ vec![]+ ),+ None+ );+ assert_eq!(+ pick_app_helper(+ CuaChannel::Stable,+ spaces_app(&local_app).as_deref(),+ vec![]+ ),+ None+ );+ assert_eq!(+ pick_app_helper(CuaChannel::Local, spaces_app(&local_app).as_deref(), vec![]),+ Some(local_app.clone())+ );+ // `none` and empty still mean no app, whatever is installed.+ for off in ["none", ""] {+ assert_eq!(+ pick_app_helper(+ CuaChannel::Stable,+ Some(std::ffi::OsStr::new(off)),+ vec![stable_app.clone()]+ ),+ None+ );+ }+ }++ #[test]+ fn each_channel_looks_only_for_its_own_app() {+ let home = Some(std::ffi::OsStr::new("/Users/ada"));+ let names = |channel| -> Vec<String> {+ app_helper_candidates(channel, None, home)+ .iter()+ .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())+ .collect()+ };+ assert!(+ names(CuaChannel::Stable)+ .iter()+ .all(|n| n == "Cua Spaces.app")+ );+ assert!(+ names(CuaChannel::Local)+ .iter()+ .all(|n| n == "Cua Spaces Local.app")+ );+ assert_eq!(+ app_helper_candidates(CuaChannel::Stable, None, home)[0],+ Path::new("/Applications/Cua Spaces.app")+ );+ // The app this process runs from comes first.+ let exe = Path::new("/Users/ada/Applications/Cua Spaces Local.app/Contents/MacOS/cua");+ let from = app_containing(exe);+ assert_eq!(+ from.as_deref(),+ Some(Path::new("/Users/ada/Applications/Cua Spaces Local.app"))+ );+ assert_eq!(+ app_helper_candidates(CuaChannel::Local, from.clone(), home)[0],+ from.unwrap()+ );+ assert_eq!(app_containing(Path::new("/usr/local/bin/cua")), None);+ }+#[test]fn a_helper_registration_says_what_to_do_in_words() {let reg = |status: &str, error: Option<&str>| HelperRegistration {status: status.into(),error: error.map(Into::into),};- assert!(helper_registered(®("enabled", None)).is_ok());- let e = helper_registered(®("requires-approval", None))+ assert!(helper_registered(®("enabled", None), "Cua Spaces").is_ok());+ let e = helper_registered(®("requires-approval", None), "Cua Spaces").unwrap_err().to_string();assert!(e.contains("Login Items"), "{e}");- let e = helper_registered(®("not-found", Some("Invalid argument")))+ let e = helper_registered(®("not-found", Some("Invalid argument")), "Cua Spaces").unwrap_err().to_string();assert!(@@ -2081,19 +2429,44 @@ mod tests {#[cfg(test)]mod instance_tests {use super::suffix_for;+ use cua_home::channel::CuaChannel::{Local, Stable};use std::ffi::OsStr;#[test]fn a_separate_cua_home_gets_its_own_service_names() {let user = Some(OsStr::new("/home/ada"));- assert_eq!(suffix_for(None, user), "");- assert_eq!(suffix_for(Some(OsStr::new("")), user), "");- assert_eq!(suffix_for(Some(OsStr::new("/home/ada/.cua")), user), "");- let a = suffix_for(Some(OsStr::new("/home/ada/fb/home")), user);- let b = suffix_for(Some(OsStr::new("/home/ada/other")), user);+ assert_eq!(suffix_for(Stable, None, user), "");+ assert_eq!(suffix_for(Stable, Some(OsStr::new("")), user), "");+ assert_eq!(+ suffix_for(Stable, Some(OsStr::new("/home/ada/.cua")), user),+ ""+ );+ let a = suffix_for(Stable, Some(OsStr::new("/home/ada/fb/home")), user);+ let b = suffix_for(Stable, Some(OsStr::new("/home/ada/other")), user);assert_eq!(a.len(), 9);assert!(a.starts_with('-'));assert_ne!(a, b);- assert_eq!(a, suffix_for(Some(OsStr::new("/home/ada/fb/home")), user));+ assert_eq!(+ a,+ suffix_for(Stable, Some(OsStr::new("/home/ada/fb/home")), user)+ );+ }++ #[test]+ fn a_channel_own_home_is_not_a_separate_home() {+ let user = Some(OsStr::new("/home/ada"));+ assert_eq!(+ suffix_for(Local, Some(OsStr::new("/home/ada/.cua-local")), user),+ ""+ );+ // Each channel's home is a separate home to the other.+ assert_eq!(+ suffix_for(Local, Some(OsStr::new("/home/ada/.cua")), user).len(),+ 9+ );+ assert_eq!(+ suffix_for(Stable, Some(OsStr::new("/home/ada/.cua-local")), user).len(),+ 9+ );}}diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex 5b97afadf9..ed17bd161f 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -1809,6 +1809,241 @@ fn the_service_gets_the_hosts_price_only_when_setup_was_given_it() {assert_eq!(back.usd_per_hour.as_deref(), Some("0.8048"));}+/// The ports are the channel's: a Stable host service is the one it has+/// always been (nothing passed, so a service installed before this still+/// matches), and a Local one asks for 3221 and 3222, on the command line+/// and in the environment, so it runs beside the Stable one. Neither passes+/// a mesh media port: it is 3212 for both, by design.+#[test]+fn the_service_serves_on_the_channels_ports() {+ use cua_home::channel::CuaChannel;+ let home = tempfile::tempdir().unwrap();+ let host = Host::new(home.path());+ let relay = crate::HostConfig {+ mode: "relay".into(),+ relay_url: Some("https://relay.example".into()),+ machine_id: Some("machine-0001".into()),+ ..Default::default()+ };+ let direct = crate::HostConfig {+ mode: "direct".into(),+ listen: Some("0.0.0.0:3221".into()),+ ..Default::default()+ };+ for config in [&relay, &direct] {+ let stable = host.service_spec_for(config, CuaChannel::Stable);+ assert!(+ !stable+ .args+ .iter()+ .any(|a| a == "--port" || a == "--quic-port"),+ "{:?}",+ stable.args+ );+ assert_eq!(+ stable.env,+ vec![("CUA_ENV_LOG".to_string(), "info".to_string())],+ "Stable passes no ports and no channel"+ );++ // Local is Stable's command line plus its two ports.+ let local = host.service_spec_for(config, CuaChannel::Local);+ let mut expected = stable.args.clone();+ expected.extend(["--port", "3221", "--quic-port", "3222"].map(String::from));+ assert_eq!(local.args, expected);+ // The same ports in the environment, for what the service starts,+ // and the channel, so those agree on whose they are.+ let var = |k: &str, v: &str| (k.to_string(), v.to_string());+ assert_eq!(+ local.env,+ vec![+ var("CUA_ENV_LOG", "info"),+ var("CUA_ENV_PORT", "3221"),+ var("CUA_ENV_QUIC_PORT", "3222"),+ var("CUA_CHANNEL", "local"),+ ]+ );+ // Nothing else differs.+ assert_eq!(local.program, stable.program);+ assert_eq!(local.log_path, stable.log_path);+ }++ // What a Stable relay host runs, in full: unchanged by the ports.+ let p = host.paths();+ let s = |p: std::path::PathBuf| p.to_string_lossy().into_owned();+ let mut expected: Vec<String> = [+ "join",+ "--relay",+ "https://relay.example",+ "--relay-token-file",+ ]+ .map(String::from)+ .into();+ expected.extend([+ s(p.machine_token()),+ "--host-policy".into(),+ s(p.policy()),+ "--machine-id-file".into(),+ s(p.machine_id.clone()),+ "--token-file".into(),+ s(p.env_token()),+ "--data-dir".into(),+ s(p.driver_data.clone()),+ ]);+ let stable = host.service_spec_for(&relay, CuaChannel::Stable);+ assert_eq!(+ stable.args[..expected.len()],+ expected[..],+ "{:?}",+ stable.args+ );++ // The service of this process is the channel's: no CUA_CHANNEL and a+ // test executable is Stable, so `service_spec` is the Stable one.+ if !CuaChannel::current().is_local() {+ assert_eq!(host.service_spec(&relay).args, stable.args);+ }+}++/// What a host service asks the machine for: the TCP port of its listener,+/// the UDP port of its QUIC media, and its mesh UDP port, from the command+/// line and environment of `spec`, else cua-spacesd's own defaults (3211,+/// 3212, 3212). A flag beats the environment, as in cua-spacesd. (The mesh+/// port is only ever the default here: no channel overrides it.)+fn requested_ports(spec: &crate::service::ServiceSpec) -> (u16, u16, u16) {+ let flag = |name: &str| {+ spec.args+ .iter()+ .position(|a| a == name)+ .map(|i| spec.args[i + 1].clone())+ };+ let env = |name: &str| {+ spec.env+ .iter()+ .find(|(k, _)| k == name)+ .map(|(_, v)| v.clone())+ };+ let listen_port = flag("--listen").map(|l| {+ l.rsplit(':')+ .next()+ .expect("an address has a port")+ .to_string()+ });+ let port = |value: Option<String>, default: u16| {+ value.map_or(default, |v| v.parse().expect("a port number"))+ };+ (+ port(+ listen_port+ .or_else(|| flag("--port"))+ .or_else(|| env("CUA_ENV_PORT")),+ 3211,+ ),+ port(+ flag("--quic-port").or_else(|| env("CUA_ENV_QUIC_PORT")),+ 3212,+ ),+ port(env("CUA_ENV_MESH_UDP_PORT"), 3212),+ )+}++/// A Stable and a Local host run on one Mac at the same time (CUA-1776):+/// the two services share no listener, in any mode, and both are told the+/// same ports on the command line and in the environment.+#[tokio::test]+async fn a_stable_and_a_local_host_service_share_no_listener() {+ use cua_home::channel::CuaChannel;+ let home = tempfile::tempdir().unwrap();+ let host = Host::new(home.path());+ fn direct(channel: CuaChannel) -> crate::HostConfig {+ crate::HostConfig {+ mode: "direct".into(),+ listen: Some(format!("0.0.0.0:{}", channel.ports().tcp)),+ ..Default::default()+ }+ }+ fn relay(_: CuaChannel) -> crate::HostConfig {+ crate::HostConfig {+ mode: "relay".into(),+ relay_url: Some("https://relay.example".into()),+ machine_id: Some("machine-0001".into()),+ ..Default::default()+ }+ }+ fn direct_and_relay(channel: CuaChannel) -> crate::HostConfig {+ crate::HostConfig {+ static_relay: Some("http://relay.lan:8080".into()),+ ..direct(channel)+ }+ }+ type ConfigFor = fn(CuaChannel) -> crate::HostConfig;+ let configs: [(&str, ConfigFor); 3] = [+ ("relay", relay),+ ("direct", direct),+ ("direct and relay", direct_and_relay),+ ];+ let mut bound = Vec::new();+ for (mode, config) in &configs {+ let stable = host.service_spec_for(&config(CuaChannel::Stable), CuaChannel::Stable);+ let local = host.service_spec_for(&config(CuaChannel::Local), CuaChannel::Local);+ let (s, l) = (requested_ports(&stable), requested_ports(&local));+ assert_eq!(s, (3211, 3212, 3212), "{mode}: Stable keeps its ports");+ assert_eq!(l, (3221, 3222, 3212), "{mode}: Local has its own");+ // The OS listeners differ. The mesh media port (.2) is the same on+ // purpose: it is a port of the mesh's own in-process network, not a+ // socket on the Mac, so the two cannot collide on it, and it must+ // stay 3212 where guest Spaces and older cua-spacesd serve it.+ assert!(s.0 != l.0 && s.1 != l.1, "{mode}");+ assert_eq!(s.2, l.2, "{mode}: the mesh media port is shared");+ assert!(+ local.env.iter().all(|(k, _)| k != "CUA_ENV_MESH_UDP_PORT"),+ "{mode}: Local does not move the mesh port"+ );+ // The environment agrees with the command line.+ let env = |spec: &crate::service::ServiceSpec, k: &str| {+ spec.env+ .iter()+ .find(|(n, _)| n == k)+ .map(|(_, v)| v.clone())+ };+ assert_eq!(env(&local, "CUA_ENV_PORT"), Some("3221".into()), "{mode}");+ assert_eq!(+ env(&local, "CUA_ENV_QUIC_PORT"),+ Some("3222".into()),+ "{mode}"+ );+ assert_eq!(env(&local, "CUA_CHANNEL"), Some("local".into()), "{mode}");+ assert_eq!(env(&stable, "CUA_CHANNEL"), None, "{mode}");+ bound.push((mode, s, l));+ }++ // Start both configurations at once, on this machine's loopback: every+ // listener either asks for binds. A set that something else on this+ // computer already holds (a Stable host that is running now, say) is+ // left to that: Local's binding next to it is the proof.+ let (_, stable, local) = bound[0];+ let mut held = Vec::new();+ let mut taken = Vec::new();+ for (name, (tcp, udp)) in [+ ("Stable", (stable.0, stable.1)),+ ("Local", (local.0, local.1)),+ ] {+ match (+ std::net::TcpListener::bind(("127.0.0.1", tcp)),+ std::net::UdpSocket::bind(("127.0.0.1", udp)),+ ) {+ (Ok(t), Ok(u)) => held.push((t, u)),+ (Err(e), _) | (_, Err(e)) if e.kind() == std::io::ErrorKind::AddrInUse => {+ eprintln!("{name}'s ports {tcp}/{udp} are in use on this machine");+ taken.push(name);+ }+ (Err(e), _) | (_, Err(e)) => panic!("{name}: binding {tcp}/{udp}: {e}"),+ }+ }+ // Whichever set was free is up beside the other, and none failed.+ assert_eq!(held.len() + taken.len(), 2);+}+/// A machine renamed on the relay from an enrolled device: this machine's/// host setup takes the name when it is this machine, and only then.#[tokio::test]diff --git a/libs/cua/crates/cua-keyvault/src/embedded.rs b/libs/cua/crates/cua-keyvault/src/embedded.rsindex 4e557bfe44..0f00e7f829 100644--- a/libs/cua/crates/cua-keyvault/src/embedded.rs+++ b/libs/cua/crates/cua-keyvault/src/embedded.rs@@ -23,7 +23,8 @@ use crate::ipc::{ConnectError, KeyvaultClient, ServerCheck};/// Where users get Cua.pub const INSTALL_URL: &str = "https://cua.ai/download";-/// Opens the Keyvault page of the installed Cua app.+/// Opens the Keyvault page of the released Cua app. A Local build links+/// `cua-local://keyvault` instead (`CuaChannel::keyvault_url`).pub const OPEN_URL: &str = "cua://keyvault";/// Teleport needs the installed Cua app (or CLI daemon).@@ -43,9 +44,20 @@ pub struct RequiresCuaApp {impl RequiresCuaApp {/// The error for "not installed" or "installed, not running".pub fn new(installed: bool, detail: &str) -> Self {+ Self::for_channel(cua_home::channel::CuaChannel::current(), installed, detail)+ }++ /// [`RequiresCuaApp::new`] for `channel`: the open link is that+ /// channel's (`cua://keyvault`, `cua-local://keyvault`).+ pub fn for_channel(+ channel: cua_home::channel::CuaChannel,+ installed: bool,+ detail: &str,+ ) -> Self {+ let open_url = channel.keyvault_url();let message = if installed {format!(- "Teleport needs the Cua app running: open Cua ({OPEN_URL}) and try again. {detail}"+ "Teleport needs the Cua app running: open Cua ({open_url}) and try again. {detail}")} else {format!(@@ -55,7 +67,7 @@ impl RequiresCuaApp {Self {installed,install_url: INSTALL_URL.into(),- open_url: OPEN_URL.into(),+ open_url,message: message.trim().to_string(),}}@@ -342,6 +354,19 @@ mod tests {assert!(e.installed && e.message.contains(OPEN_URL));}+ #[test]+ fn the_open_link_is_the_channels() {+ use cua_home::channel::CuaChannel;+ let stable = RequiresCuaApp::for_channel(CuaChannel::Stable, true, "");+ assert_eq!(stable.open_url, "cua://keyvault");+ assert!(stable.message.contains("(cua://keyvault)"));+ // Local opens Cua Spaces Local, never the released app.+ let local = RequiresCuaApp::for_channel(CuaChannel::Local, true, "");+ assert_eq!(local.open_url, "cua-local://keyvault");+ assert!(local.message.contains("(cua-local://keyvault)"));+ assert!(!local.message.contains("(cua://"));+ }+#[cfg(unix)]#[tokio::test]async fn no_socket_means_requires_cua_app() {diff --git a/libs/cua/crates/cua-keyvault/src/lib.rs b/libs/cua/crates/cua-keyvault/src/lib.rsindex 88346ab281..67656cd4c5 100644--- a/libs/cua/crates/cua-keyvault/src/lib.rs+++ b/libs/cua/crates/cua-keyvault/src/lib.rs@@ -197,11 +197,13 @@ fn cua_home() -> Option<std::path::PathBuf> {}return Some(h.into());}- // Like `cua_home::cua_home()`: another `CUA_ENV` has its own home- // (`~/.cua/envs/staging`), where its daemon serves the Keyvault.+ // Like `cua_home::cua_home()`: the channel's home for the environment+ // (`~/.cua-local` for Local, `~/.cua/envs/staging` for another+ // `CUA_ENV`), where that daemon serves the Keyvault.home_dir().map(|h| {- let base = std::path::PathBuf::from(h).join(".cua");- match cua_home::env::CuaEnv::current().home_subdir() {+ let (channel, env) = cua_home::channel::CuaChannel::current_with_env();+ let base = std::path::PathBuf::from(h).join(channel.home_dir_name());+ match channel.home_subdir(env) {Some(sub) => base.join(sub),None => base,}diff --git a/libs/cua/crates/cua-mesh/src/dialer.rs b/libs/cua/crates/cua-mesh/src/dialer.rsindex d96f992b2b..1228003191 100644--- a/libs/cua/crates/cua-mesh/src/dialer.rs+++ b/libs/cua/crates/cua-mesh/src/dialer.rs@@ -17,7 +17,7 @@ use std::path::PathBuf;use std::sync::Arc;use std::time::Duration;-use crate::{AuthProvider, Error, Forward, Mesh, MeshConfig, NodeKind, Result};+use crate::{AuthProvider, Error, Forward, MEDIA_UDP_PORT, Mesh, MeshConfig, NodeKind, Result};/// The spacesd service on a machine.pub const SPACESD_SERVICE: &str = "spacesd";@@ -70,7 +70,21 @@ impl Dialer {identity: Option<PathBuf>,timeout: Duration,) -> Result<Self> {- let cfg = MeshConfig::new(relay.to_owned(), NodeKind::Client, identity, auth);+ Self::start_with_media_port(relay, auth, identity, timeout, MEDIA_UDP_PORT).await+ }++ /// [`Dialer::start`] for machines that serve their QUIC media on mesh+ /// UDP port `media_udp_port` (`--mesh-udp-port` of their cua-spacesd)+ /// instead of [`MEDIA_UDP_PORT`].+ pub async fn start_with_media_port(+ relay: &str,+ auth: AuthProvider,+ identity: Option<PathBuf>,+ timeout: Duration,+ media_udp_port: u16,+ ) -> Result<Self> {+ let mut cfg = MeshConfig::new(relay.to_owned(), NodeKind::Client, identity, auth);+ cfg.media_udp_port = media_udp_port;let mesh = Mesh::start(cfg).await?;if let Err(e) = mesh.wait_ready(timeout).await {mesh.shutdown();diff --git a/libs/cua/crates/cua-mesh/src/node.rs b/libs/cua/crates/cua-mesh/src/node.rsindex b7fc5e316b..b0ed5fae30 100644--- a/libs/cua/crates/cua-mesh/src/node.rs+++ b/libs/cua/crates/cua-mesh/src/node.rs@@ -22,7 +22,16 @@ use crate::quic::{self, MeshStream, StreamHeader};use crate::vnet::VSocket;use crate::{Error, Result};-/// The mesh UDP port a machine forwards to its local QUIC media port.+/// The default mesh UDP port a machine forwards to its local QUIC media+/// port, and the one a client forward sends media datagrams to.+///+/// It is a port of the mesh's own overlay network (an in-process socket of+/// the node's own mesh address), not a port of the operating system, so two+/// nodes on one computer never compete for it. A host and the clients that+/// dial it must agree, so both take it from [`MeshConfig::media_udp_port`].+/// Every Cua build leaves it at 3212 (guest Spaces and older cua-spacesd+/// fix it there); the setting is an override for a deployment that must+/// move it.pub const MEDIA_UDP_PORT: u16 = 3212;/// How a node is set up.@@ -50,6 +59,11 @@ pub struct MeshConfig {pub stun: Vec<String>,/// Never use direct paths (tests; `CUA_MESH_RELAY_ONLY=1`).pub relay_only: bool,+ /// The mesh UDP port of the peers' QUIC media service: client forwards+ /// send media datagrams to it, and a machine serves it with+ /// [`Mesh::serve_udp`] on the same number. Default+ /// [`MEDIA_UDP_PORT`].+ pub media_udp_port: u16,}impl std::fmt::Debug for MeshConfig {@@ -81,6 +95,7 @@ impl MeshConfig {approved_path: None,stun: Vec::new(),relay_only: std::env::var("CUA_MESH_RELAY_ONLY").is_ok_and(|v| v == "1"),+ media_udp_port: MEDIA_UDP_PORT,}}}@@ -240,6 +255,8 @@ struct Inner {stun: Vec<String>,shutdown: coord::tokio_util_cancel::Token,approved: Option<Arc<Approved>>,+ /// [`MeshConfig::media_udp_port`].+ media_udp_port: u16,udp_services: Mutex<Vec<tokio::task::JoinHandle<()>>>,/// The peer flows of every [`Mesh::serve_udp`] service.udp_flows: Mutex<Vec<UdpFlows>>,@@ -296,6 +313,7 @@ impl Mesh {stun: cfg.stun.clone(),shutdown: shutdown.clone(),approved: approved.clone(),+ media_udp_port: cfg.media_udp_port,udp_services: Mutex::new(Vec::new()),udp_flows: Mutex::new(Vec::new()),endpoints: Mutex::new(Vec::new()),@@ -380,6 +398,12 @@ impl Mesh {self.inner.identity.addr()}+ /// The mesh UDP port client forwards of this node send media datagrams+ /// to ([`MeshConfig::media_udp_port`]).+ pub fn media_udp_port(&self) -> u16 {+ self.inner.media_udp_port+ }+/// Current peers.pub fn peers(&self) -> Vec<PeerInfo> {self.inner@@ -604,7 +628,8 @@ impl Mesh {/// Forwards a loopback port to `service` on `peer`: every TCP/// connection to the returned address becomes one mesh stream, and/// datagrams to the same port number on UDP go to the peer's- /// [`MEDIA_UDP_PORT`]. Dropping the [`Forward`] stops it.+ /// [`MeshConfig::media_udp_port`] (default [`MEDIA_UDP_PORT`]). Dropping+ /// the [`Forward`] stops it.pub async fn forward(&self,peer: PublicKey,@@ -1091,7 +1116,7 @@ async fn udp_client_forward(mesh: Mesh, local: Arc<UdpSocket>, peer: PublicKey)continue;};mesh.inner.engine.want(&peer);- let dst = SocketAddrV6::new(info.addr(), MEDIA_UDP_PORT, 0, 0);+ let dst = SocketAddrV6::new(info.addr(), mesh.inner.media_udp_port, 0, 0);let sock = {let mut f = flows.lock().expect("flows");f.retain(|_, (_, at)| at.elapsed() < Duration::from_secs(180));diff --git a/libs/cua/crates/cua-mesh/tests/mesh.rs b/libs/cua/crates/cua-mesh/tests/mesh.rsindex 3152f5faac..20d43647dd 100644--- a/libs/cua/crates/cua-mesh/tests/mesh.rs+++ b/libs/cua/crates/cua-mesh/tests/mesh.rs@@ -20,6 +20,17 @@ async fn node(dir: &std::path::Path,name: &str,relay_only: bool,+) -> Mesh {+ node_on_media_port(coord, kind, dir, name, relay_only, cua_mesh::MEDIA_UDP_PORT).await+}++async fn node_on_media_port(+ coord: &FakeCoordinator,+ kind: NodeKind,+ dir: &std::path::Path,+ name: &str,+ relay_only: bool,+ media_udp_port: u16,) -> Mesh {let mut headers = Vec::new();if kind == NodeKind::Machine {@@ -34,6 +45,7 @@ async fn node(cfg.name = name.to_owned();cfg.stun = vec![coord.stun.to_string()];cfg.relay_only = relay_only;+ cfg.media_udp_port = media_udp_port;cfg.approved_path = Some(dir.join(format!("{name}-approved.json")));let m = Mesh::start(cfg).await.expect("start");m.wait_ready(READY).await.expect("ready");@@ -361,6 +373,77 @@ async fn loopback_forwards_carry_tcp_and_udp() {assert!(ok, "udp echo over the mesh");}+/// Whether a datagram sent to the forward's UDP side comes back echoed+/// within `tries` half-seconds.+async fn udp_echoes(to: std::net::SocketAddr, tries: usize) -> bool {+ let udp = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();+ for _ in 0..tries {+ udp.send_to(b"media", to).await.unwrap();+ let mut buf = [0u8; 64];+ if let Ok(Ok((n, _))) =+ tokio::time::timeout(Duration::from_millis(500), udp.recv_from(&mut buf)).await+ {+ assert_eq!(&buf[..n], b"media");+ return true;+ }+ }+ false+}++/// A machine that serves its media on another mesh UDP port (a Cua Spaces+/// Local host) is reached by a client that dials that port, and by no one+/// that dials the default.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn the_media_udp_port_is_configurable() {+ const LOCAL_PORT: u16 = 3222;+ let dir = tempfile::tempdir().unwrap();+ let coord = FakeCoordinator::start(Mode::Account).await;+ let machine = node_on_media_port(+ &coord,+ NodeKind::Machine,+ dir.path(),+ "m",+ false,+ LOCAL_PORT,+ )+ .await;+ assert_eq!(machine.media_udp_port(), LOCAL_PORT);+ let default_client = node(&coord, NodeKind::Client, dir.path(), "d", false).await;+ assert_eq!(default_client.media_udp_port(), cua_mesh::MEDIA_UDP_PORT);+ let local_client =+ node_on_media_port(&coord, NodeKind::Client, dir.path(), "l", false, LOCAL_PORT).await;+ serve_echo(&machine);+ let udp_echo = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();+ let echo_addr = udp_echo.local_addr().unwrap();+ tokio::spawn(async move {+ let mut buf = [0u8; 2048];+ loop {+ let (n, src) = udp_echo.recv_from(&mut buf).await.unwrap();+ udp_echo.send_to(&buf[..n], src).await.unwrap();+ }+ });+ machine.serve_udp(LOCAL_PORT, echo_addr).unwrap();+ wait_peer(&local_client, &machine.node_key()).await;+ wait_peer(&default_client, &machine.node_key()).await;++ let to_local = local_client+ .forward(machine.node_key(), "echo", None)+ .await+ .unwrap();+ assert!(+ udp_echoes(to_local.local, 20).await,+ "a client on the host's port reaches its media"+ );+ let to_default = default_client+ .forward(machine.node_key(), "echo", None)+ .await+ .unwrap();+ assert!(+ !udp_echoes(to_default.local, 4).await,+ "a client on the default port does not"+ );+}+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn removed_peers_are_cut() {let dir = tempfile::tempdir().unwrap();diff --git a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs b/libs/cua/crates/cua-sdk/src/native/agent_setup.rsindex 7df43ec572..98cd06dc7e 100644--- a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs+++ b/libs/cua/crates/cua-sdk/src/native/agent_setup.rs@@ -204,8 +204,10 @@ impl AgentSetup {fn server(&self, s: Option<AgentMcpServer>) -> cua_agent_setup::McpServer {match s {Some(s) => cua_agent_setup::McpServer {+ // No name: the channel's (`cua`, or `cua-local` for the+ // Local app), so the Local app never writes Stable's entry.name: if s.name.trim().is_empty() {- cua_agent_setup::MCP_SERVER_NAME.into()+ self.inner.env().channel.mcp_server_name().into()} else {s.name},@@ -291,7 +293,8 @@ impl AgentSetup {}/// Configures the MCP server (default: `cua mcp`, `cua` resolved on- /// PATH) for `agents`.+ /// PATH; `cua-local mcp` named `cua-local` for the Local app) for+ /// `agents`. A server without a name gets the channel's.pub async fn configure_mcp(&self,agents: Vec<String>,@@ -417,6 +420,63 @@ mod tests {assert!(s.onboarding_declined());}+ #[tokio::test]+ async fn sdk_local_agent_setup_registers_cua_local_beside_stables_cua() {+ let d = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(d.path().join(".codex")).unwrap();+ let env = cua_agent_setup::HostEnv::isolated(d.path());+ let stable = AgentSetup::with_env(env.clone());+ let local = AgentSetup::with_env(env.with_channel(cua_agent_setup::CuaChannel::Local));+ let server = |command: &str| AgentMcpServer {+ // No name: each channel registers its own.+ name: String::new(),+ command: command.into(),+ args: vec!["mcp".into()],+ env: HashMap::new(),+ };+ let out = stable+ .configure_mcp(+ vec!["codex".into()],+ Some(server("/Applications/Cua Spaces.app/Contents/MacOS/cua")),+ )+ .await+ .unwrap();+ assert_eq!(+ (out[0].item.as_str(), out[0].change),+ ("cua", AgentSetupChange::Created)+ );+ let local_cua = "/Users/a/Applications/Cua Spaces Local.app/Contents/MacOS/cua";+ let out = local+ .configure_mcp(vec!["codex".into()], Some(server(local_cua)))+ .await+ .unwrap();+ assert_eq!(+ (out[0].item.as_str(), out[0].change),+ ("cua-local", AgentSetupChange::Created)+ );+ let toml = std::fs::read_to_string(d.path().join(".codex/config.toml")).unwrap();+ assert!(toml.contains("[mcp_servers.cua]"), "{toml}");+ assert!(toml.contains("[mcp_servers.cua-local]"), "{toml}");+ assert!(toml.contains("/Applications/Cua Spaces.app/Contents/MacOS/cua"));+ assert!(toml.contains(local_cua));+ // Each reads its own entry as its own.+ let st = |s: &Arc<AgentSetup>| s.status().into_iter().find(|a| a.id == "codex").unwrap();+ assert!(st(&stable).cua_configured && st(&local).cua_configured);+ // Local's skills are `-local` copies beside Stable's.+ let skills: Vec<String> = local.skills().into_iter().map(|s| s.name).collect();+ assert!(skills.iter().all(|n| n.ends_with("-local")), "{skills:?}");+ local+ .install_skills(vec!["codex".into()], vec![], false)+ .await+ .unwrap();+ assert!(+ d.path()+ .join(".agents/skills/cua-spaces-local/SKILL.md")+ .is_file()+ );+ assert!(!d.path().join(".agents/skills/cua-spaces").exists());+ }+#[tokio::test]async fn sdk_cua_driver_setup_in_a_temp_home() {let d = tempfile::tempdir().unwrap();diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex 10edac4c7f..f21de4200f 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -619,6 +619,13 @@ pub(crate) fn setup_token_state(mode: &str, token: Option<&str>) -> &'static str}}+/// Where a direct host listens when the caller gives no address: every+/// interface, on the channel's spacesd port (3211, or 3221 for Cua Spaces+/// Local, so it runs beside a Stable host).+fn direct_listen_default(channel: cua_home::channel::CuaChannel) -> String {+ format!("0.0.0.0:{}", channel.ports().tcp)+}+/// Converts binding options to cua-host options.pub(crate) fn setup_options(o: HostSetupOptions) -> Result<cua_host::SetupOptions> {let mut opts = match o.mode.as_deref().unwrap_or("relay") {@@ -628,7 +635,8 @@ pub(crate) fn setup_options(o: HostSetupOptions) -> Result<cua_host::SetupOption.unwrap_or_else(cua_host::relay_url_from_env),),"direct" => {- let listen = o.direct.as_deref().unwrap_or("0.0.0.0:3211");+ let default = direct_listen_default(cua_home::channel::CuaChannel::current());+ let listen = o.direct.as_deref().unwrap_or(&default);cua_host::SetupOptions::direct(listen.parse().map_err(|_| {CuaError::InvalidArgument(format!("direct address {listen:?} is not ip:port"))})?)@@ -1234,6 +1242,22 @@ impl Devices {mod tests {use super::*;+ /// A direct host the caller gives no address listens on the channel's+ /// spacesd port: Cua Spaces Local's is not Stable's 3211.+ #[test]+ fn a_direct_host_listens_on_the_channels_port_by_default() {+ use cua_home::channel::CuaChannel;+ assert_eq!(direct_listen_default(CuaChannel::Stable), "0.0.0.0:3211");+ assert_eq!(direct_listen_default(CuaChannel::Local), "0.0.0.0:3221");+ for channel in CuaChannel::ALL {+ assert!(+ direct_listen_default(channel)+ .parse::<std::net::SocketAddr>()+ .is_ok()+ );+ }+ }+/// The Machines page groups team machines and says whether a machine/// provides Spaces from what the relay recorded at registration.#[test]diff --git a/libs/cua/crates/cua-sdk/src/native/telemetry.rs b/libs/cua/crates/cua-sdk/src/native/telemetry.rsindex 7ea758eb83..106b9f67e6 100644--- a/libs/cua/crates/cua-sdk/src/native/telemetry.rs+++ b/libs/cua/crates/cua-sdk/src/native/telemetry.rs@@ -504,16 +504,18 @@ pub(crate) fn teleport_outcome(e: &CuaError) -> events::TeleportOutcome {}/// Whether an error message is the Keyvault's `RequiresCuaApp` (its-/// install and open links are fixed constants).+/// install link is fixed, and its open link is the app's own: `cua://` for+/// the released app, `cua-local://` for Cua Spaces Local).pub(crate) fn requires_cua_app(message: &str) -> bool {message.contains(cua_keyvault_links::INSTALL_URL)- || message.contains(cua_keyvault_links::OPEN_URL)+ || cua_home::channel::CuaChannel::ALL+ .iter()+ .any(|c| message.contains(&c.keyvault_url()))}-/// The fixed links `RequiresCuaApp` carries (cua-keyvault `embedded`).+/// The fixed link `RequiresCuaApp` carries (cua-keyvault `embedded`).mod cua_keyvault_links {pub const INSTALL_URL: &str = "https://cua.ai/download";- pub const OPEN_URL: &str = "cua://keyvault";}#[cfg(test)]@@ -595,6 +597,18 @@ mod tests {);}+ #[test]+ fn requires_cua_app_knows_each_channels_open_link() {+ // "Installed, not running" carries the app's open link: the released+ // app's `cua://`, or Cua Spaces Local's `cua-local://`.+ for link in ["cua://keyvault", "cua-local://keyvault"] {+ let m = format!("Teleport needs the Cua app running: open Cua ({link}) and try again.");+ assert!(requires_cua_app(&m), "{link}");+ }+ assert!(!requires_cua_app("no display"));+ assert!(!requires_cua_app("open cua-other://keyvault"));+ }+fn summary() -> StreamSummary {StreamSummary {transport: "websocket",diff --git a/libs/cua/crates/cua-spaces-app-core/src/host.rs b/libs/cua/crates/cua-spaces-app-core/src/host.rsindex 50555271be..ed3fbe56af 100644--- a/libs/cua/crates/cua-spaces-app-core/src/host.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/host.rs@@ -324,8 +324,16 @@ pub fn default_relay_url() -> String {cua_home::env::relay_url()}-/// The direct mode's default listen address.-pub const DEFAULT_LISTEN: &str = "0.0.0.0:3211";+/// The direct mode's default listen address: every interface, on the+/// channel's spacesd port (3211, or 3221 for Cua Spaces Local, so its host+/// runs beside a Stable one).+pub fn default_listen() -> String {+ listen_on(cua_home::channel::CuaChannel::current())+}++fn listen_on(channel: cua_home::channel::CuaChannel) -> String {+ format!("0.0.0.0:{}", channel.ports().tcp)+}/// Adds the "This machine" entry to a roster, first (it is always present/// in the live app; `status` is `None` until the host answers).@@ -1496,7 +1504,7 @@ impl Default for HostFormState {allow: String::new(),advanced: false,direct: false,- listen: DEFAULT_LISTEN.into(),+ listen: default_listen(),// Empty: the form leaves the relay to the host, which resolves it// from its own `CUA_RELAY_URL` / `CUA_ENV`. This core also runs// in the page (wasm), which has no environment and would name@@ -1769,7 +1777,7 @@ pub fn form_view(s: &HostFormState, identity: Option<&str>) -> HostFormView {fields.push(text("listen","Listen on",- DEFAULT_LISTEN,+ &default_listen(),&s.listen,bad,true,@@ -1836,6 +1844,18 @@ pub fn form_view(s: &HostFormState, identity: Option<&str>) -> HostFormView {mod tests {use super::*;+ /// The "Listen on" default is the channel's spacesd port: Cua Spaces+ /// Local's host does not take Stable's 3211.+ #[test]+ fn the_default_listen_address_follows_the_channel() {+ use cua_home::channel::CuaChannel;+ assert_eq!(listen_on(CuaChannel::Stable), "0.0.0.0:3211");+ assert_eq!(listen_on(CuaChannel::Local), "0.0.0.0:3221");+ for channel in CuaChannel::ALL {+ assert!(looks_like_listen(&listen_on(channel)));+ }+ }+#[test]fn listen_needs_a_port() {assert!(looks_like_listen("10.0.0.5:3211"));diff --git a/libs/cua/crates/cua-spaces-app-core/src/installer.rs b/libs/cua/crates/cua-spaces-app-core/src/installer.rsindex 90aedb603b..175c112a4b 100644--- a/libs/cua/crates/cua-spaces-app-core/src/installer.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/installer.rs@@ -7,6 +7,13 @@//! `AppCliInstaller`), so the plan they show and the files they write are//! the same.//!+//! What the CLI is installed as depends on the build's [`CuaChannel`]:+//! Stable installs `~/.local/bin/cua`; Local ("Cua Spaces Local", CUA-1776)+//! installs `~/.local/bin/cua-local` and never touches `cua`, so the two+//! apps keep their own commands. The bundled file is `cua` in both. Local+//! adds `~/.local/bin` to PATH the way Stable does, only when it is not on+//! PATH already and its line is not in the profile yet.+//!//! [`CliInstaller::plan`] shows the exact target path before anything is//! written; [`CliInstaller::install`] writes only after the user consents.//! Paths and environment are injected, so tests run against temp dirs and@@ -18,6 +25,9 @@ use std::process::Stdio;#[cfg(feature = "installer")]use std::time::Duration;+/// The build channel that names the installed CLI (re-exported for the+/// shells that build a [`CliInstaller`]).+pub use cua_home::channel::CuaChannel;use serde::{Deserialize, Serialize};/// Marker line written above a PATH edit (same text as install.sh).@@ -26,11 +36,23 @@ pub const PATH_MARKER: &str = "# Added by the cua installer";#[cfg(feature = "installer")]const VERSION_TIMEOUT: Duration = Duration::from_secs(5);-/// File name of the CLI on this OS.+/// File name of the CLI the app bundles (its sidecar) on this OS. Every app+/// ships it as `cua`; what it is installed as depends on the channel+/// ([`installed_cli_file_name`]).pub fn cli_file_name() -> &'static str {if cfg!(windows) { "cua.exe" } else { "cua" }}+/// File name the CLI is installed under on this OS: `cua` for Stable,+/// `cua-local` for Local (`.exe` on Windows).+pub fn installed_cli_file_name(channel: CuaChannel) -> String {+ format!(+ "{}{}",+ channel.cli_name(),+ if cfg!(windows) { ".exe" } else { "" }+ )+}+/// The sidecar `cua` next to the app executable, when the bundle has one.pub fn bundled_cli(exe: &Path) -> Option<PathBuf> {let candidate = exe.parent()?.join(cli_file_name());@@ -39,6 +61,7 @@ pub fn bundled_cli(exe: &Path) -> Option<PathBuf> {/// Where the GUI installs the CLI: `~/.local/bin` on macOS/Linux (the same/// place install.sh uses), `%LOCALAPPDATA%\Programs\cua\bin` on Windows.+/// Both channels share the folder (the file name tells them apart).pub fn default_bin_dir(home: &Path, local_app_data: Option<&Path>) -> PathBuf {if cfg!(windows) {local_app_data@@ -112,7 +135,8 @@ pub struct CliInstallPlan {pub installed_version: Option<String>,/// `cua --version` of the bundled CLI.pub bundled_version: Option<String>,- /// Another `cua` found earlier on PATH (it would shadow `target`).+ /// Another CLI of the same name found earlier on PATH (it would shadow+ /// `target`).pub shadowed_by: Option<String>,/// `bin_dir` is already on PATH.pub on_path: bool,@@ -120,9 +144,10 @@ pub struct CliInstallPlan {pub path_profile: Option<String>,/// The line that would be added to `path_profile`.pub path_line: Option<String>,- /// A working `cua` CLI already on this machine: `target`, else the- /// first in the usual install folders or on PATH (a Finder-launched+ /// A working CLI of this channel already on this machine: `target`, else+ /// the first in the usual install folders or on PATH (a Finder-launched/// app's PATH lacks `~/.local/bin`, so the folders are searched too).+ /// Local looks for `cua-local` only: a Stable `cua` is not its CLI.#[serde(default)]pub found: Option<String>,}@@ -140,6 +165,8 @@ pub struct CliInstallRequest {#[derive(Clone, Debug)]#[cfg(feature = "installer")]pub struct CliInstaller {+ /// The build channel: names the installed CLI (`cua` or `cua-local`).+ pub channel: CuaChannel,pub bundled: Option<PathBuf>,pub bin_dir: PathBuf,/// Value of PATH used for the on-path / shadow checks.@@ -155,7 +182,10 @@ pub struct CliInstaller {#[cfg(feature = "installer")]impl CliInstaller {- /// The real machine: sidecar next to `exe`, `$HOME`, `$PATH`, `$SHELL`.+ /// The real machine: sidecar next to `exe`, `$HOME`, `$PATH`, `$SHELL`,+ /// and the channel of this process ([`CuaChannel::current`]; the app+ /// sets `CUA_CHANNEL` before anything starts, and a Local app's own path+ /// says Local too).pub fn from_env(exe: &Path) -> Self {let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))@@ -166,6 +196,7 @@ impl CliInstaller {let shell = std::env::var("SHELL").ok();let bundled = bundled_cli(exe);Self {+ channel: CuaChannel::current(),prefer_symlink: bundled.as_deref().is_some_and(stable_app_location),bundled,bin_dir: default_bin_dir(&home, local.as_deref()),@@ -193,7 +224,7 @@ impl CliInstaller {.cloned().chain(std::env::split_paths(&self.path_env));for dir in dirs {- let cli = dir.join(cli_file_name());+ let cli = dir.join(self.installed_name());if seen.contains(&cli) || !cli.is_file() {continue;}@@ -205,9 +236,14 @@ impl CliInstaller {None}+ /// The file name the CLI is installed under: `cua` or `cua-local`.+ pub fn installed_name(&self) -> String {+ installed_cli_file_name(self.channel)+ }+/// The file the CLI is written to.pub fn target(&self) -> PathBuf {- self.bin_dir.join(cli_file_name())+ self.bin_dir.join(self.installed_name())}fn method(&self) -> InstallMethod {@@ -245,11 +281,11 @@ impl CliInstaller {_ => false,};let on_path = path_contains(&self.path_env, &self.bin_dir);- let shadowed_by = first_on_path(&self.path_env, cli_file_name())+ let shadowed_by = first_on_path(&self.path_env, &self.installed_name()).filter(|found| {found != &target && !self.bundled.as_ref().is_some_and(|b| same_file(b, found))})- .filter(|_| on_path_before(&self.path_env, &self.bin_dir))+ .filter(|_| on_path_before(&self.path_env, &self.bin_dir, &self.installed_name())).map(|p| p.display().to_string());let (path_profile, line) = if on_path {(None, None)@@ -299,7 +335,9 @@ impl CliInstaller {}std::fs::create_dir_all(&self.bin_dir).map_err(|e| format!("cannot create {}: {e}", self.bin_dir.display()))?;- let staging = self.bin_dir.join(format!(".{}.cua-new", cli_file_name()));+ let staging = self+ .bin_dir+ .join(format!(".{}.cua-new", self.installed_name()));let _ = std::fs::remove_file(&staging);match self.method() {InstallMethod::Symlink => {@@ -463,15 +501,15 @@ pub fn first_on_path(path_env: &str, name: &str) -> Option<PathBuf> {.find(|p| p.is_file())}-/// Whether some *other* PATH entry with a `cua` comes before `bin_dir`-/// (or `bin_dir` is not on PATH at all).+/// Whether some *other* PATH entry with a CLI file `name` comes before+/// `bin_dir` (or `bin_dir` is not on PATH at all).#[cfg(feature = "installer")]-fn on_path_before(path_env: &str, bin_dir: &Path) -> bool {+fn on_path_before(path_env: &str, bin_dir: &Path, name: &str) -> bool {for dir in std::env::split_paths(path_env) {if dir == bin_dir {return false;}- if dir.join(cli_file_name()).is_file() {+ if dir.join(name).is_file() {return true;}}@@ -622,6 +660,7 @@ mod tests {std::fs::set_permissions(&cua, std::fs::Permissions::from_mode(0o755)).unwrap();let home = tmp.path().join("home");let cli = CliInstaller {+ channel: CuaChannel::Stable,bundled: bundled_cli(&exe),bin_dir: default_bin_dir(&home, None),path_env: "/usr/bin:/bin".into(),@@ -729,6 +768,7 @@ mod tests {script(&bundled, "cua 0.6.0");let home = tmp.path().join("home");let cli = CliInstaller {+ channel: CuaChannel::Stable,bundled: bundled_cli(&exe),bin_dir: default_bin_dir(&home, None),path_env: "/usr/bin:/bin".into(),@@ -793,6 +833,228 @@ mod tests {);}+ #[test]+ fn the_installed_name_follows_the_channel() {+ let ext = if cfg!(windows) { ".exe" } else { "" };+ assert_eq!(+ installed_cli_file_name(CuaChannel::Stable),+ format!("cua{ext}")+ );+ assert_eq!(+ installed_cli_file_name(CuaChannel::Local),+ format!("cua-local{ext}")+ );+ // Stable installs the sidecar's own name.+ assert_eq!(installed_cli_file_name(CuaChannel::Stable), cli_file_name());+ assert_ne!(+ installed_cli_file_name(CuaChannel::Stable),+ installed_cli_file_name(CuaChannel::Local)+ );+ }++ /// The Local app (a `Cua Spaces Local.app` bundling `cua`) beside a+ /// Stable `cua` in the same `~/.local/bin`.+ #[cfg(unix)]+ struct LocalRig {+ _tmp: tempfile::TempDir,+ home: PathBuf,+ bin: PathBuf,+ local: CliInstaller,+ stable_cua: PathBuf,+ stable_before: Vec<u8>,+ }++ #[cfg(unix)]+ fn local_rig() -> LocalRig {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ let app = home.join("Applications/Cua Spaces Local.app/Contents/MacOS");+ std::fs::create_dir_all(&app).unwrap();+ let exe = app.join("CuaSpacesMac");+ std::fs::write(&exe, "").unwrap();+ // Every bundle ships its CLI as `cua`.+ script(&app.join(cli_file_name()), "cua 1.2.3");+ let bin = default_bin_dir(&home, None);+ std::fs::create_dir_all(&bin).unwrap();+ let stable_cua = bin.join("cua");+ script(&stable_cua, "cua 0.4.4");+ let stable_before = std::fs::read(&stable_cua).unwrap();+ let local = CliInstaller {+ channel: CuaChannel::Local,+ bundled: bundled_cli(&exe),+ bin_dir: bin.clone(),+ path_env: "/usr/bin:/bin".into(),+ profile: profile_for_shell(&home, Some("/bin/zsh"), None),+ prefer_symlink: false,+ search_dirs: vec![bin.clone()],+ };+ LocalRig {+ _tmp: tmp,+ home,+ bin,+ local,+ stable_cua,+ stable_before,+ }+ }++ /// CUA-1776: Local installs `cua-local` and never touches `cua`.+ #[cfg(unix)]+ #[tokio::test]+ async fn local_installs_cua_local_and_leaves_cua_alone() {+ let r = local_rig();+ let plan = r.local.plan().await;+ assert_eq!(plan.target, r.bin.join("cua-local").display().to_string());+ assert_eq!(plan.bundled_version.as_deref(), Some("cua 1.2.3"));+ assert!(!plan.installed && !plan.up_to_date, "{plan:?}");+ // Stable's `cua` is not Local's CLI, even in the folder searched.+ assert_eq!(plan.found, None, "{plan:?}");++ let done = r+ .local+ .install(&CliInstallRequest { modify_path: false })+ .await+ .unwrap();+ assert_eq!(done.target, r.bin.join("cua-local").display().to_string());+ assert!(done.installed && done.up_to_date, "{done:?}");+ assert_eq!(done.installed_version.as_deref(), Some("cua 1.2.3"));+ assert_eq!(+ done.found.as_deref(),+ Some(r.bin.join("cua-local").to_str().unwrap())+ );+ assert!(r.bin.join("cua-local").is_file());+ assert_eq!(+ std::fs::read(&r.stable_cua).unwrap(),+ r.stable_before,+ "Stable's cua is untouched"+ );+ // Nothing but the CLI was written: no profile, no staging file.+ assert!(!r.home.join(".zshrc").exists());+ let names: Vec<_> = std::fs::read_dir(&r.bin)+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ assert_eq!(names.len(), 2, "{names:?}");++ // Stable's own installer still sees only its `cua` as its CLI.+ let stable = CliInstaller {+ channel: CuaChannel::Stable,+ ..r.local.clone()+ };+ let plan = stable.plan().await;+ assert_eq!(plan.target, r.stable_cua.display().to_string());+ assert_eq!(plan.installed_version.as_deref(), Some("cua 0.4.4"));+ }++ /// A Local app's CLI symlinks into its own app, like Stable's.+ #[cfg(unix)]+ #[tokio::test]+ async fn local_links_its_cli_into_its_app() {+ let r = local_rig();+ let local = CliInstaller {+ prefer_symlink: true,+ ..r.local.clone()+ };+ let done = local.install(&CliInstallRequest::default()).await.unwrap();+ let target = r.bin.join("cua-local");+ assert!(target.symlink_metadata().unwrap().file_type().is_symlink());+ assert_eq!(done.method, Some(InstallMethod::Symlink));+ assert!(+ std::fs::read_link(&target)+ .unwrap()+ .starts_with(r.home.join("Applications/Cua Spaces Local.app")),+ );+ assert_eq!(std::fs::read(&r.stable_cua).unwrap(), r.stable_before);+ }++ /// Local adds `~/.local/bin` to PATH the way Stable does: once, and not+ /// at all when it is on PATH already or its line is in the profile.+ #[cfg(unix)]+ #[tokio::test]+ async fn local_edits_the_shell_profile_once_and_only_when_needed() {+ let r = local_rig();+ let want = CliInstallRequest { modify_path: true };+ let line = path_line(&r.bin, &r.local.profile);+ let count = |profile: &Path, text: &str| {+ std::fs::read_to_string(profile)+ .unwrap()+ .matches(text)+ .count()+ };++ // Not on PATH: the profile gets the marker and the line.+ let plan = r.local.plan().await;+ assert!(!plan.on_path);+ assert_eq!(plan.path_line.as_deref(), Some(line.as_str()));+ let done = r.local.install(&want).await.unwrap();+ assert!(done.on_path && done.path_line.is_none(), "{done:?}");+ assert_eq!(count(&r.local.profile, PATH_MARKER), 1);+ assert_eq!(count(&r.local.profile, &line), 1);++ // Installing again (the PATH of this process is unchanged) adds no+ // second line.+ std::fs::remove_file(r.bin.join("cua-local")).unwrap();+ r.local.install(&want).await.unwrap();+ assert_eq!(count(&r.local.profile, PATH_MARKER), 1);+ assert_eq!(count(&r.local.profile, &line), 1);++ // Already on PATH: the profile is not touched, not even created.+ std::fs::remove_file(r.bin.join("cua-local")).unwrap();+ let on_path = CliInstaller {+ path_env: format!("/usr/bin:{}", r.bin.display()),+ profile: r.home.join(".profile-never-written"),+ ..r.local.clone()+ };+ let plan = on_path.plan().await;+ assert!(plan.on_path && plan.path_profile.is_none() && plan.path_line.is_none());+ on_path.install(&want).await.unwrap();+ assert!(!on_path.profile.exists());++ // Stable's app (or install.sh) already put the line in the profile:+ // Local leaves the file as it is.+ std::fs::remove_file(r.bin.join("cua-local")).unwrap();+ let shared = r.home.join(".zprofile");+ let body = format!("{PATH_MARKER}\n{line}\n");+ std::fs::write(&shared, &body).unwrap();+ let reuses = CliInstaller {+ profile: shared.clone(),+ ..r.local.clone()+ };+ reuses.install(&want).await.unwrap();+ assert_eq!(std::fs::read_to_string(&shared).unwrap(), body);+ }++ /// A `cua` ahead on PATH shadows Stable's CLI, not Local's; another+ /// `cua-local` ahead shadows Local's.+ #[cfg(unix)]+ #[tokio::test]+ async fn only_a_cli_of_the_same_name_shadows_the_target() {+ let r = local_rig();+ let other = r._tmp.path().join("brew/bin");+ std::fs::create_dir_all(&other).unwrap();+ script(&other.join("cua"), "cua 0.3.0");+ let path_env = format!("{}:{}", other.display(), r.bin.display());+ let local = CliInstaller {+ path_env: path_env.clone(),+ ..r.local.clone()+ };+ let stable = CliInstaller {+ channel: CuaChannel::Stable,+ path_env,+ ..r.local.clone()+ };+ assert_eq!(local.plan().await.shadowed_by, None);+ assert_eq!(+ stable.plan().await.shadowed_by.as_deref(),+ Some(other.join("cua").to_str().unwrap())+ );+ script(&other.join("cua-local"), "cua 0.3.0");+ assert_eq!(+ local.plan().await.shadowed_by.as_deref(),+ Some(other.join("cua-local").to_str().unwrap())+ );+ }+#[test]fn keeps_installed_decides_by_version() {assert!(keeps_installed(Some("cua 0.7.99"), Some("cua 0.6.0")));diff --git a/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rs b/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rsindex af5e5f867c..0b1663aaa6 100644--- a/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/teleport/flow.rs@@ -347,11 +347,24 @@ pub struct InstallCuaPrompt {/// Where people install Cua.pub const CUA_INSTALL_URL: &str = "https://cua.ai/install";-/// Opens the Keyvault page of an installed Cua app.-pub const CUA_OPEN_URL: &str = "cua://keyvault";+// The "Open Cua" button opens the Keyvault page of this process's channel's+// app, `cua://keyvault` or `cua-local://keyvault` (`CuaChannel::keyvault_url`)./// The prompt when `texts` carry the Keyvault's `requires_cua_app` refusal.pub fn requires_cua_app(texts: &[String], installed_flag: bool) -> Option<InstallCuaPrompt> {+ requires_cua_app_for(+ cua_home::channel::CuaChannel::current(),+ texts,+ installed_flag,+ )+}++/// [`requires_cua_app`] for `channel`'s app.+fn requires_cua_app_for(+ channel: cua_home::channel::CuaChannel,+ texts: &[String],+ installed_flag: bool,+) -> Option<InstallCuaPrompt> {if !texts.iter().any(|t| contains_word(t, "requires_cua_app") || contains_word(t, "RequiresCuaApp"))@@ -369,7 +382,7 @@ pub fn requires_cua_app(texts: &[String], installed_flag: bool) -> Option<Instaltitle: "Open Cua to teleport your session".into(),message: "The Cua app keeps your logins in its Keyvault and asks you before sharing them. Open it, then try again.".into(),action_label: "Open Cua".into(),- url: CUA_OPEN_URL.into(),+ url: channel.keyvault_url(),}} else {InstallCuaPrompt {@@ -1772,10 +1785,27 @@ mod tests {).unwrap();assert!(p.installed);- assert_eq!(p.url, CUA_OPEN_URL);+ assert_eq!(p.url, cua_home::channel::CuaChannel::current_keyvault_url());assert!(requires_cua_app(&["xrequires_cua_app".into()], false).is_none());}+ #[test]+ fn the_open_cua_button_opens_the_channels_app() {+ use cua_home::channel::CuaChannel;+ let texts = ["requires_cua_app: installed but not running".to_string()];+ let url = |c| requires_cua_app_for(c, &texts, false).unwrap().url;+ assert_eq!(url(CuaChannel::Stable), "cua://keyvault");+ // Local opens Cua Spaces Local, never the released app.+ assert_eq!(url(CuaChannel::Local), "cua-local://keyvault");+ // Not installed: the install link, whichever channel.+ let texts = ["requires_cua_app".to_string()];+ for c in CuaChannel::ALL {+ let p = requires_cua_app_for(c, &texts, false).unwrap();+ assert!(!p.installed);+ assert_eq!(p.url, CUA_INSTALL_URL);+ }+ }+fn chrome_entry() -> CatalogEntry {serde_json::from_value(serde_json::json!({"id": "com.google.Chrome", "name": "Google Chrome", "capability": "full",diff --git a/libs/cua/crates/cua-spaces-cli/src/lib.rs b/libs/cua/crates/cua-spaces-cli/src/lib.rsindex 45b9587b7b..59ca1be4b8 100644--- a/libs/cua/crates/cua-spaces-cli/src/lib.rs+++ b/libs/cua/crates/cua-spaces-cli/src/lib.rs@@ -16,6 +16,8 @@//!//! The Spaces apps ship this binary as their `cua`.+#![recursion_limit = "256"]+use std::io::Write;use std::sync::Arc;diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rsindex a1a9396061..10b1a4ae48 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs@@ -1824,18 +1824,23 @@ fn default_cua_home(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> PathBufif let Some(h) = set("CUA_HOME") {return PathBuf::from(h);}+ // The channel and environment come from the lookup too (`CUA_CHANNEL`,+ // `CUA_ENV`): each has its own home, where its daemon serves the+ // Keyvault (`~/.cua/envs/staging`, `~/.cua-local`,+ // `~/.cua-local/envs/prod`).+ let channel = cua_home::channel::CuaChannel::from_env_value(+ var("CUA_CHANNEL")+ .and_then(|v| v.into_string().ok())+ .as_deref(),+ );+ let env_value = var("CUA_ENV").and_then(|v| v.into_string().ok());+ let env = channel.env_or_fallback(env_value.as_deref());let base = set("HOME").or_else(|| set("USERPROFILE")).map(PathBuf::from).unwrap_or_default()- .join(".cua");- // A non-production `CUA_ENV` has its own home, where its daemon serves- // the Keyvault (`~/.cua/envs/staging`).- let env = var("CUA_ENV").and_then(|v| v.into_string().ok());- match cua_home::env::CuaEnv::try_from_value(env.as_deref())- .unwrap_or_default()- .home_subdir()- {+ .join(channel.home_dir_name());+ match channel.home_subdir(env) {Some(sub) => base.join(sub),None => base,}@@ -2544,6 +2549,7 @@ impl AppCliInstaller {) -> Arc<Self> {Arc::new(Self {inner: core::installer::CliInstaller {+ channel: cua_home::channel::CuaChannel::Stable,bundled: bundled.map(PathBuf::from),bin_dir: bin_dir.into(),path_env,@@ -3034,6 +3040,41 @@ mod keyvault_home_tests {PathBuf::from("/srv/cua"));}++ /// The Local channel's daemon (and so its Keyvault) lives in+ /// `~/.cua-local` on staging and `~/.cua-local/envs/prod` on prod+ /// (CUA-1776); `CUA_HOME` still wins.+ #[test]+ fn the_keyvault_follows_the_local_channel() {+ let local = |vars: &[(&str, &str)]| {+ let mut all = vec![("HOME", "/home/ada"), ("CUA_CHANNEL", "local")];+ all.extend_from_slice(vars);+ home(&all)+ };+ assert_eq!(local(&[]), PathBuf::from("/home/ada/.cua-local"));+ assert_eq!(+ local(&[("CUA_ENV", "staging")]),+ PathBuf::from("/home/ada/.cua-local")+ );+ assert_eq!(+ local(&[("CUA_ENV", "prod")]),+ PathBuf::from("/home/ada/.cua-local/envs/prod")+ );+ // A mistyped environment is staging on Local, never production.+ assert_eq!(+ local(&[("CUA_ENV", "prd")]),+ PathBuf::from("/home/ada/.cua-local")+ );+ assert_eq!(+ local(&[("CUA_HOME", "/srv/cua"), ("CUA_ENV", "prod")]),+ PathBuf::from("/srv/cua")+ );+ // Stable is untouched by a Local variable elsewhere.+ assert_eq!(+ home(&[("HOME", "/home/ada"), ("CUA_CHANNEL", "stable")]),+ PathBuf::from("/home/ada/.cua")+ );+ }}#[cfg(test)]diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rsindex a8fd1a33cb..8466ebc2ba 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs@@ -7865,7 +7865,8 @@ pub struct AppCliInstallPlan {pub installed_version: Option<String>,/// `cua --version` of the bundled CLI.pub bundled_version: Option<String>,- /// Another `cua` found earlier on PATH (it would shadow `target`).+ /// Another CLI of the same name found earlier on PATH (it would shadow+ /// `target`).pub shadowed_by: Option<String>,/// `bin_dir` is already on PATH.pub on_path: bool,@@ -7873,9 +7874,10 @@ pub struct AppCliInstallPlan {pub path_profile: Option<String>,/// The line that would be added to `path_profile`.pub path_line: Option<String>,- /// A working `cua` CLI already on this machine: `target`, else the- /// first in the usual install folders or on PATH (a Finder-launched+ /// A working CLI of this channel already on this machine: `target`, else+ /// the first in the usual install folders or on PATH (a Finder-launched/// app's PATH lacks `~/.local/bin`, so the folders are searched too).+ /// Local looks for `cua-local` only: a Stable `cua` is not its CLI.pub found: Option<String>,}diff --git a/libs/cua/crates/cua-spaces/src/agents/keys.rs b/libs/cua/crates/cua-spaces/src/agents/keys.rsindex 17b8c908a2..9be87bd044 100644--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs@@ -3,7 +3,8 @@//!//! The keys live in the OS credential vault through cua-auth's secret store//! ([`cua_auth::Store::save_secret`]): one item, `agent-keys`, next to the-//! session (service `ai.cua.session`), with the same access list, so the app,+//! session (service `ai.cua.session`, or the channel's own,+//! `CuaChannel::keychain_service`), with the same access list, so the app,//! the daemon and the CLI read it without a prompt. A build whose store is//! a file (an unsigned macOS build, Linux) refuses to save them: keys are//! never written to a plain file. Set the key in the daemon's environmentdiff --git a/libs/cua/crates/cua-spaces/src/host_jobs.rs b/libs/cua/crates/cua-spaces/src/host_jobs.rsindex 75d48c65c8..24c6989d52 100644--- a/libs/cua/crates/cua-spaces/src/host_jobs.rs+++ b/libs/cua/crates/cua-spaces/src/host_jobs.rs@@ -712,8 +712,8 @@ async fn machine_services(/// macOS VMs Lume runs on this Mac that are not job members (Apple's/// license allows two per Mac, and Apple Virtualization refuses a third).async fn macos_vms_running() -> u32 {- let base = std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into());- let client = cua_vmm::lume::LumeClient::new(base);+ // `$LUME_API`, else this channel's own Lume (Local's is not on :7777).+ let client = cua_vmm::lume::LumeClient::new(cua_vmm::lume::LumeConfig::default().url);match tokio::time::timeout(Duration::from_secs(4), client.list()).await {Ok(Ok(vms)) => vms.iter()diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rsindex 42dbe944cf..81c86f80d0 100644--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs@@ -2369,8 +2369,16 @@ fn stopped_sharing_reason(e: &Error) -> Option<String> {/// local Space (2 vCPUs, 4 GiB)./// How this machine's daemon reaches the machine's own cua-spacesd (the/// host service): where it listens (the direct listener, `CUA_ENV_LISTEN`,-/// else loopback on `CUA_ENV_PORT` or 3211) and its local env token.+/// else loopback on `CUA_ENV_PORT` or the channel's port, 3211 or 3221 for+/// Cua Spaces Local) and its local env token.fn host_spacesd(host: &Host) -> std::result::Result<cua_cluster::machine::HostSpacesd, String> {+ host_spacesd_on(host, cua_home::channel::CuaChannel::current())+}++fn host_spacesd_on(+ host: &Host,+ channel: cua_home::channel::CuaChannel,+) -> std::result::Result<cua_cluster::machine::HostSpacesd, String> {let listen = host.config().ok()@@ -2386,7 +2394,7 @@ fn host_spacesd(host: &Host) -> std::result::Result<cua_cluster::machine::HostSplet port = std::env::var("CUA_ENV_PORT").ok().and_then(|p| p.trim().parse::<u16>().ok())- .unwrap_or(cua_proto::SPACESD_DEFAULT_PORT);+ .unwrap_or(channel.ports().tcp);format!("127.0.0.1:{port}")});// A listener on every interface is reached on loopback.@@ -4360,6 +4368,31 @@ mod tests {use super::*;+ /// The daemon reaches its own host service on the channel's port:+ /// Cua Spaces Local's is not Stable's 3211.+ #[test]+ fn the_daemon_reaches_its_host_spacesd_on_the_channels_port() {+ use cua_home::channel::CuaChannel;+ if std::env::var_os("CUA_ENV_LISTEN").is_some()+ || std::env::var_os("CUA_ENV_PORT").is_some()+ {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let host = Host::new(dir.path());+ std::fs::create_dir_all(host.paths().env_token().parent().unwrap()).unwrap();+ std::fs::write(host.paths().env_token(), "secret\n").unwrap();+ let on = |channel| host_spacesd_on(&host, channel).unwrap();+ assert_eq!(on(CuaChannel::Stable).url, "http://127.0.0.1:3211");+ assert_eq!(on(CuaChannel::Local).url, "http://127.0.0.1:3221");+ assert_eq!(on(CuaChannel::Local).token, "secret");+ // The mesh media port is every channel's, by design: guest Spaces+ // and older cua-spacesd serve it there, and it is not an OS port.+ for channel in CuaChannel::ALL {+ assert_eq!(channel.ports().mesh_udp, cua_mesh::MEDIA_UDP_PORT);+ }+ }+/// What a create on a host reports to its caller, by elapsed minute,/// when the host call takes `call` and the host answers `ask`.async fn reports_while_following(diff --git a/libs/cua/crates/cua-vmm/Cargo.toml b/libs/cua/crates/cua-vmm/Cargo.tomlindex a0f82fe42d..a8e3d9c1fa 100644--- a/libs/cua/crates/cua-vmm/Cargo.toml+++ b/libs/cua/crates/cua-vmm/Cargo.toml@@ -80,3 +80,5 @@ windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storagecua-spacesd-client.workspace = truetempfile = "3"tokio = { version = "1", features = ["full"] }+# Reads Local's `config.yaml` back with a real YAML parser (same version as cua-agent-setup).+serde_yaml_ng = "0.10"diff --git a/libs/cua/crates/cua-vmm/examples/lume_warm.rs b/libs/cua/crates/cua-vmm/examples/lume_warm.rsindex e469892e14..e989277ee2 100644--- a/libs/cua/crates/cua-vmm/examples/lume_warm.rs+++ b/libs/cua/crates/cua-vmm/examples/lume_warm.rs@@ -6,7 +6,8 @@//!//! cargo run -p cua-vmm --example lume_warm -- REF [--cpus N] [--memory-mb M] [--settle-secs S]//!-//! Uses the `lume serve` of `LUME_API` (default `http://127.0.0.1:7777`) and+//! Uses the `lume serve` of `LUME_API` (default `http://127.0.0.1:7777`, or+//! `http://127.0.0.1:7787` on the Local channel) and//! the `CUA_HOME` the daemon uses. Prints one JSON line with the states made//! and how long it took.diff --git a/libs/cua/crates/cua-vmm/src/auto.rs b/libs/cua/crates/cua-vmm/src/auto.rsindex 7745f9b66b..3a27d6c8eb 100644--- a/libs/cua/crates/cua-vmm/src/auto.rs+++ b/libs/cua/crates/cua-vmm/src/auto.rs@@ -413,18 +413,21 @@ pub async fn doctor() -> DoctorReport {let mut lume = LumeReport {supported_host: host_os == HostOs::Macos && host_arch == Arch::Aarch64,binary: lume_binary(),- url: std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into()),+ url: crate::local_network::lume_base(),..Default::default()};#[cfg(feature = "lume")]if lume.supported_host {let c = crate::lume::LumeClient::new(lume.url.clone());lume.serving = c.reachable().await;- if let Some(b) = &lume.binary {- lume.version = host::run(b, &["--version"])- .await- .ok()- .map(|s| s.trim().to_string());+ if lume.binary.is_some() {+ // Run as Lume runs for this channel: a bare `lume --version`+ // initialises the pinned Lume's settings and telemetry under+ // Stable's `~/.config/lume` and `~/.lume`. (For Local this+ // writes only its own config under its home.)+ if let Ok(Some(l)) = crate::lume::lume_cmd() {+ lume.version = crate::lume::version_text(&l).await;+ }}}// Without any Lume, the built-in one is set up on first use unless the@@ -948,7 +951,7 @@ fn lume_binary() -> Option<PathBuf> {}#[cfg(not(feature = "lume"))]{- host::which("lume")+ host::which(cua_home::channel::CuaChannel::current().lume_bin_name())}}diff --git a/libs/cua/crates/cua-vmm/src/host.rs b/libs/cua/crates/cua-vmm/src/host.rsindex a7e782ae4c..b7debdd444 100644--- a/libs/cua/crates/cua-vmm/src/host.rs+++ b/libs/cua/crates/cua-vmm/src/host.rs@@ -4,6 +4,7 @@ use std::net::TcpListener;use std::path::{Path, PathBuf};use std::process::Stdio;+use cua_home::channel::CuaChannel;use serde::{Deserialize, Serialize};use crate::error::{Result, VmmError};@@ -30,12 +31,32 @@ impl HostOs {}}-/// `~/.cua` (or `$CUA_HOME`).+/// `$CUA_HOME`, else this process's channel's cua home: `~/.cua`+/// (Stable) or `~/.cua-local` (Local, so a standalone `cua-local` never+/// shares Stable's state, runtimes or config when `CUA_HOME` is unset).pub fn cua_home() -> PathBuf {- if let Some(h) = std::env::var_os("CUA_HOME").filter(|h| !h.is_empty()) {+ cua_home_with(+ CuaChannel::current(),+ std::env::var_os("CUA_HOME").as_deref(),+ &home_dir(),+ )+}++/// [`cua_home`] for `channel`, with `$CUA_HOME` and the user's home given.+/// Local's home is `~/.cua-local` itself, as the app pins it, not below+/// `envs/<env>`.+pub fn cua_home_with(+ channel: CuaChannel,+ cua_home_env: Option<&std::ffi::OsStr>,+ home: &Path,+) -> PathBuf {+ if let Some(h) = cua_home_env.filter(|h| !h.is_empty()) {return PathBuf::from(h);}- home_dir().join(".cua")+ match channel.home_dir().file_name() {+ Some(name) => home.join(name),+ None => home.join(".cua"),+ }}pub fn home_dir() -> PathBuf {@@ -434,6 +455,8 @@ pub fn signal(pid: u32, sig: &str) {#[cfg(test)]mod tests {+ use super::*;+#[test]fn ports_handed_out_concurrently_never_repeat() {let all: Vec<u16> = std::thread::scope(|sc| {@@ -459,7 +482,61 @@ mod tests {assert_eq!(uniq.len(), 8, "{ds:?}");}- use super::*;+ #[test]+ fn the_cua_home_follows_the_channel_and_cua_home_overrides_it() {+ use std::ffi::OsStr;+ let home = Path::new("/Users/a");+ // Stable's default is unchanged.+ assert_eq!(+ cua_home_with(CuaChannel::Stable, None, home),+ PathBuf::from("/Users/a/.cua")+ );+ assert_eq!(+ cua_home_with(CuaChannel::Local, None, home),+ PathBuf::from("/Users/a/.cua-local")+ );+ for c in CuaChannel::ALL {+ assert_eq!(+ cua_home_with(c, Some(OsStr::new("/tmp/h")), home),+ PathBuf::from("/tmp/h")+ );+ // Blank says nothing.+ assert_eq!(+ cua_home_with(c, Some(OsStr::new("")), home),+ cua_home_with(c, None, home)+ );+ }+ }++ /// A standalone `cua-local` (no app, so no `CUA_HOME` pinned) is Local+ /// by its name and keeps everything under `~/.cua-local`.+ #[test]+ fn a_standalone_cua_local_without_cua_home_uses_the_local_home() {+ let home = Path::new("/Users/a");+ let exe = PathBuf::from("/Users/a/.local/bin/cua-local");+ let channel = CuaChannel::resolve(None, None, &[exe]).unwrap();+ assert_eq!(channel, CuaChannel::Local);+ let cua = cua_home_with(channel, None, home);+ assert_eq!(cua, PathBuf::from("/Users/a/.cua-local"));+ #[cfg(feature = "lume")]+ {+ assert_eq!(+ crate::lume::root_in(&cua),+ PathBuf::from("/Users/a/.cua-local/vmm/lume")+ );+ assert_eq!(+ crate::lume::builtin::root_in(&cua),+ PathBuf::from("/Users/a/.cua-local/runtimes/lume")+ );+ }+ // ... and the same name for Stable is still `~/.cua`.+ let stable =+ CuaChannel::resolve(None, None, &[PathBuf::from("/Users/a/.local/bin/cua")]).unwrap();+ assert_eq!(+ cua_home_with(stable, None, home),+ PathBuf::from("/Users/a/.cua")+ );+ }/// Binds `port`, waiting out another thread's momentary probe of it (a/// probe is dropped at once; this is the window `launch` retries over).diff --git a/libs/cua/crates/cua-vmm/src/local_network.rs b/libs/cua/crates/cua-vmm/src/local_network.rsindex 7192444219..b0261bb921 100644--- a/libs/cua/crates/cua-vmm/src/local_network.rs+++ b/libs/cua/crates/cua-vmm/src/local_network.rs@@ -271,9 +271,18 @@ fn subnet_host(ip: u32, mask: u32) -> Option<String> {Some(std::net::Ipv4Addr::from(target).to_string())}-/// The `lume serve` this host's runtimes talk to.+/// The `lume serve` this host's runtimes talk to: `$LUME_API`, else the+/// default of this process's channel (Stable's `:7777`, Local's `:7787`).pub fn lume_base() -> String {- std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into())+ lume_base_with(+ cua_home::channel::CuaChannel::current(),+ std::env::var("LUME_API").ok().as_deref(),+ )+}++/// [`lume_base`] for `channel`, with `$LUME_API`'s value given (pure).+pub fn lume_base_with(channel: cua_home::channel::CuaChannel, lume_api: Option<&str>) -> String {+ lume_api.map_or_else(|| channel.lume_api().to_string(), str::to_string)}impl ResponsibleApp {@@ -451,6 +460,25 @@ mod tests {assert_eq!(back, r);}+ #[test]+ fn the_lume_server_comes_from_the_channel_unless_lume_api_says_otherwise() {+ use cua_home::channel::CuaChannel;+ assert_eq!(+ lume_base_with(CuaChannel::Stable, None),+ "http://127.0.0.1:7777"+ );+ assert_eq!(+ lume_base_with(CuaChannel::Local, None),+ "http://127.0.0.1:7787"+ );+ for c in CuaChannel::ALL {+ assert_eq!(+ lume_base_with(c, Some("http://10.0.0.5:9000")),+ "http://10.0.0.5:9000"+ );+ }+ }+#[cfg(target_os = "macos")]#[test]fn this_process_has_a_responsible_app() {diff --git a/libs/cua/crates/cua-vmm/src/lume/builtin.rs b/libs/cua/crates/cua-vmm/src/lume/builtin.rsindex 9730b1c50f..8fd5166466 100644--- a/libs/cua/crates/cua-vmm/src/lume/builtin.rs+++ b/libs/cua/crates/cua-vmm/src/lume/builtin.rs@@ -23,6 +23,8 @@use std::path::{Path, PathBuf};+use cua_home::channel::CuaChannel;+use crate::error::{Result, VmmError};use crate::host;@@ -114,7 +116,12 @@ pub fn dir() -> PathBuf {/// `$CUA_HOME/runtimes/lume`: every built-in Lume version.pub fn root() -> PathBuf {- host::cua_home().join("runtimes").join("lume")+ root_in(&host::cua_home())+}++/// [`root`] under the cua home `home`.+pub fn root_in(home: &Path) -> PathBuf {+ home.join("runtimes").join("lume")}/// The built-in Lume's executable, when it is installed and was verified.@@ -127,20 +134,41 @@ pub fn installed() -> Option<PathBuf> {/// Written last, once the unpacked Lume passed every check.const VERIFIED: &str = ".verified";-/// The Lume to run for `source`: this Mac's own (`system`, or `auto` when-/// it has one at least [`MIN_VERSION`]), else the built-in one when-/// installed.+/// The Lume to run for `source` on this process's channel+/// ([`resolve_for`]).pub fn resolve(source: LumeSource) -> Option<PathBuf> {- let system = || host::which("lume").filter(|p| !p.starts_with(root()));+ resolve_for(CuaChannel::current(), source)+}++/// The Lume to run for `source` on `channel`: this Mac's own (`system`, or+/// `auto` when it has one at least [`MIN_VERSION`]), else the built-in one+/// when installed.+///+/// This Mac's own Lume is the one the channel names+/// ([`CuaChannel::lume_bin_name`]): Stable's `lume`, Local's `lume-local`.+/// Local never picks up Stable's `lume`, which keeps its VMs in `~/.lume`+/// and its server on port 7777.+pub fn resolve_for(channel: CuaChannel, source: LumeSource) -> Option<PathBuf> {+ let system = || system_lume(channel, host::which, &root());match source {LumeSource::System => system(),LumeSource::Builtin => installed(),LumeSource::Auto => system()- .filter(|p| system_binary_usable(source, binary_version(p).as_deref()))+ .filter(|p| system_binary_usable(source, binary_version_for(channel, p).as_deref())).or_else(installed),}}+/// This Mac's own Lume for `channel`, looked up with `which` by the name+/// the channel gives it; never the built-in one under `builtin_root`.+fn system_lume(+ channel: CuaChannel,+ which: impl Fn(&str) -> Option<PathBuf>,+ builtin_root: &Path,+) -> Option<PathBuf> {+ which(channel.lume_bin_name()).filter(|p| !p.starts_with(builtin_root))+}+/// The oldest Lume cua runs macOS Spaces on. Lume 0.6.0 is the first/// release with what cua's client relies on (forced and bounded stop for/// detached VMs, running without a VNC listener, GPU passthrough), and a@@ -211,9 +239,33 @@ pub fn system_binary_usable(source: LumeSource, version: Option<&str>) -> bool {/// The ports tried, in order, for a current Lume when the configured one/// is taken by an old server: the next nine. Fixed, so every cua process-/// on this Mac finds the same one.+/// on this Mac finds the same one. Stable's walk (`fallback_ports_for`).pub fn fallback_ports(port: u16) -> impl Iterator<Item = u16> {- (1..=9u16).filter_map(move |d| port.checked_add(d))+ fallback_ports_for(CuaChannel::Stable, port)+}++/// How many ports after its own one a channel's Lume may move to.+pub const FALLBACK_SPAN: u16 = 9;++/// The ports a channel's Lume may use: its own and the nine after it+/// (Stable's `7777..=7786`, Local's `7787..=7796`).+pub fn port_range(channel: CuaChannel) -> std::ops::RangeInclusive<u16> {+ let p = channel.lume_port();+ p..=p.saturating_add(FALLBACK_SPAN)+}++/// [`fallback_ports`] for `channel`: the next nine ports after `port`,+/// except any in another channel's range, so a Local Lume never walks into+/// Stable's ports (and Stable's never into Local's).+pub fn fallback_ports_for(channel: CuaChannel, port: u16) -> impl Iterator<Item = u16> {+ let others: Vec<_> = CuaChannel::ALL+ .into_iter()+ .filter(move |c| *c != channel)+ .map(port_range)+ .collect();+ (1..=FALLBACK_SPAN)+ .filter_map(move |d| port.checked_add(d))+ .filter(move |p| !others.iter().any(|r| r.contains(p)))}/// `url` with its port replaced by `port`.@@ -238,9 +290,32 @@ pub fn is_loopback(url: &str) -> bool {matches!(host, "127.0.0.1" | "localhost" | "::1")}-/// `bin --version` (cached per binary and modification time; bounded to-/// five seconds).-pub fn binary_version(bin: &Path) -> Option<String> {+/// `lume --version`, run as `lume` runs (its channel's environment: the+/// pinned Lume initialises its settings and telemetry before it parses+/// `--version`, so a bare run would touch Stable's `~/.config/lume` and+/// `~/.lume`). Cached per binary and modification time; bounded to five+/// seconds.+pub fn binary_version(lume: &LumeCmd) -> Option<String> {+ cached_version(lume.bin(), || run_version(lume))+}++/// [`binary_version`] of `bin` for `channel`, preparing the channel's+/// environment under `config_root` only when the version is not cached.+pub fn binary_version_in(channel: CuaChannel, config_root: &Path, bin: &Path) -> Option<String> {+ cached_version(bin, || {+ let lume = LumeCmd::new(channel, config_root, bin)+ .inspect_err(|e| tracing::warn!(error = %e, "could not prepare the Lume environment"))+ .ok()?;+ run_version(&lume)+ })+}++/// [`binary_version_in`] under the default Lume state directory.+pub fn binary_version_for(channel: CuaChannel, bin: &Path) -> Option<String> {+ binary_version_in(channel, &super::default_root(), bin)+}++fn cached_version(bin: &Path, run: impl FnOnce() -> Option<String>) -> Option<String> {use std::collections::HashMap;use std::sync::Mutex;/// Binary -> (its modification time, its version).@@ -257,7 +332,7 @@ pub fn binary_version(bin: &Path) -> Option<String> {{return v.clone();}- let v = run_version(&bin);+ let v = run();SEEN.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)@@ -265,10 +340,11 @@ pub fn binary_version(bin: &Path) -> Option<String> {v}-fn run_version(bin: &Path) -> Option<String> {+fn run_version(lume: &LumeCmd) -> Option<String> {use std::io::Read as _;- use std::process::{Command, Stdio};- let mut child = Command::new(bin)+ use std::process::Stdio;+ let mut child = lume+ .command().arg("--version").stdin(Stdio::null()).stdout(Stdio::piped())@@ -334,6 +410,212 @@ pub fn remove() -> Result<()> {}}+/// Lume's switch for its product telemetry (`false` turns it off for the+/// process; it wins over the config file).+const TELEMETRY_VAR: &str = "LUME_TELEMETRY_ENABLED";++/// A Lume to run for a channel: its binary and the environment every+/// process started from it needs. **Every** Lume subprocess goes through+/// one of these (`serve`, `pull`, `get`, `run`, `ssh`, `attach`), so none of+/// them can fall back to Stable's VM directory.+///+/// Stable's has no environment: its Lume runs as it always did.+///+/// Local's Lume keeps its VMs in `~/.lume-local`+/// ([`crate::storage::lume_dir_for`]) whichever Lume runs it, so it gets:+///+/// * `XDG_CONFIG_HOME`: a config directory of its own under `config_root`,+/// with a `lume/config.yaml` that makes the VM directory the default+/// location. **This is the isolation for any Lume named `lume`**, the+/// bundled one included, so it never reads or writes Stable's `~/.lume` or+/// `~/.config/lume`;+/// * `LUME_HOME`: the VM directory. **Contract with Lume (#5804):** a Lume+/// named `lume-local` relocates its VMs, cache and settings through+/// `LUME_HOME`; one named `lume` (Stable's, and the bundled one, on 0.6.0+/// and on newer releases alike) uses `LUME_HOME` only for its+/// release-channel file. So `LUME_HOME` alone does not isolate the+/// bundled `lume`: never drop the config above. It is set for+/// `lume-local`, and so the release-channel file is Local's own;+/// * `TMPDIR`: a private temp directory under `config_root`, where Lume+/// pulls images (`lume_vm_*`), so Local's start-up sweep and Stable's+/// never see each other's half-made pulls;+/// * `LUME_TELEMETRY_ENABLED=false` (and `telemetryEnabled: false` in the+/// config): the pinned Lume writes its telemetry identity, locks and+/// markers under `~/.lume` whatever `LUME_HOME` says, which is Stable's.+/// Local's Lume has none until the pin supports an isolated home.+#[derive(Clone, Debug)]+pub struct LumeCmd {+ bin: PathBuf,+ env: Vec<(&'static str, std::ffi::OsString)>,+ /// The private temp directory its `TMPDIR` names (Local's).+ temp: Option<PathBuf>,+}++impl LumeCmd {+ /// `bin` with no extra environment (Stable's, and tests').+ pub fn plain(bin: impl Into<PathBuf>) -> Self {+ Self {+ bin: bin.into(),+ env: Vec::new(),+ temp: None,+ }+ }++ /// `bin` for `channel`; Local's writes its config under `config_root`.+ pub fn new(+ channel: CuaChannel,+ config_root: &Path,+ bin: impl Into<PathBuf>,+ ) -> std::io::Result<Self> {+ Self::with_vm_dir(+ channel,+ config_root,+ bin,+ &crate::storage::lume_dir_for(channel),+ )+ }++ /// [`LumeCmd::new`] with the VM directory given.+ pub fn with_vm_dir(+ channel: CuaChannel,+ config_root: &Path,+ bin: impl Into<PathBuf>,+ vm_dir: &Path,+ ) -> std::io::Result<Self> {+ let bin = bin.into();+ if !channel.is_local() {+ return Ok(Self::plain(bin));+ }+ let xdg = config_root.join("xdg");+ seed_config(&xdg.join("lume").join("config.yaml"), vm_dir)?;+ let temp = config_root.join("tmp");+ std::fs::create_dir_all(&temp)?;+ Ok(Self {+ bin,+ env: vec![+ (crate::storage::LUME_HOME_VAR, vm_dir.as_os_str().to_owned()),+ ("XDG_CONFIG_HOME", xdg.into_os_string()),+ ("TMPDIR", temp.as_os_str().to_owned()),+ (TELEMETRY_VAR, "false".into()),+ ],+ temp: Some(temp),+ })+ }++ /// The temp directory this Lume pulls into, when it has a private one+ /// (Local's). Stable's is the user's shared temp directory.+ pub fn temp_dir(&self) -> Option<&Path> {+ self.temp.as_deref()+ }++ /// The Lume binary.+ pub fn bin(&self) -> &Path {+ &self.bin+ }++ /// The environment it runs with (empty for Stable).+ pub fn env(&self) -> &[(&'static str, std::ffi::OsString)] {+ &self.env+ }++ /// A command for it, with the environment set.+ pub fn command(&self) -> std::process::Command {+ let mut cmd = std::process::Command::new(&self.bin);+ cmd.envs(self.env.iter().map(|(k, v)| (k, v)));+ cmd+ }++ /// [`LumeCmd::command`] for `tokio`.+ pub fn tokio_command(&self) -> tokio::process::Command {+ tokio::process::Command::from(self.command())+ }++ /// The program and leading arguments that run it with its environment+ /// when only a program and arguments can be given (`PrefixExec`,+ /// [`super::LumeSshExec`], a command for another process to run): the+ /// binary itself for Stable, `env K=V... <bin>` for Local.+ pub fn wrapped(&self) -> (String, Vec<String>) {+ if self.env.is_empty() {+ return (self.bin.display().to_string(), Vec::new());+ }+ let mut lead: Vec<String> = self+ .env+ .iter()+ .map(|(k, v)| format!("{k}={}", v.to_string_lossy()))+ .collect();+ lead.push(self.bin.display().to_string());+ ("/usr/bin/env".into(), lead)+ }++ /// [`LumeCmd::wrapped`] followed by `args`, as one argv.+ pub fn argv<I, S>(&self, args: I) -> Vec<String>+ where+ I: IntoIterator<Item = S>,+ S: Into<String>,+ {+ let (program, lead) = self.wrapped();+ let mut argv = vec![program];+ argv.extend(lead);+ argv.extend(args.into_iter().map(Into::into));+ argv+ }+}++/// `s` as a YAML scalar. A JSON string is a double-quoted YAML scalar+/// (YAML 1.2 is a superset of JSON, and Lume's parser reads the escapes+/// JSON writes), so `serde_json` escapes `\`, `"` and control characters+/// instead of them being pasted into the quotes.+fn yaml_string(s: &str) -> String {+ serde_json::to_string(s).expect("a string always serializes")+}++/// Lume's `config.yaml` that makes `vm_dir` the one VM location. The paths+/// are escaped ([`yaml_string`]): a `LUME_HOME` with a backslash or a quote+/// in it still reads back as the same directory.+pub fn config_yaml(vm_dir: &str) -> String {+ let dir = yaml_string(vm_dir);+ let cache = yaml_string(&format!("{vm_dir}/cache"));+ format!(+ "# Written by Cua Spaces Local: its Lume keeps VMs apart from the released Cua Spaces.\n\+ defaultLocationName: \"home\"\n\+ cacheDirectory: {cache}\n\+ cachingEnabled: false\n\+ telemetryEnabled: false\n\+ \n\+ vmLocations:\n\+ \x20 - name: \"home\"\n\+ \x20 path: {dir}\n"+ )+}++/// Writes the Local Lume's `config.yaml` at `file` unless it already makes+/// `vm_dir` the default location with telemetry off.+fn seed_config(file: &Path, vm_dir: &Path) -> std::io::Result<()> {+ let dir = vm_dir.to_str().ok_or_else(|| {+ std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ format!("{} cannot be a Lume VM directory", vm_dir.display()),+ )+ })?;+ let current = std::fs::read_to_string(file).ok();+ if current.as_deref().is_some_and(|y| {+ crate::storage::lume_default_location(y).is_some_and(|p| p == dir)+ && y.lines().any(|l| l.trim() == "telemetryEnabled: false")+ }) {+ return Ok(());+ }+ let parent = file.parent().unwrap_or(Path::new("."));+ std::fs::create_dir_all(parent)?;+ // Written whole to a temp file beside it and renamed over it: a Lume+ // started meanwhile reads the old config or the new one, never an+ // empty or partial file (which the pinned Lume answers with `~/.lume`).+ let mut tmp = tempfile::NamedTempFile::new_in(parent)?;+ std::io::Write::write_all(&mut tmp, config_yaml(dir).as_bytes())?;+ tmp.as_file().sync_all()?;+ tmp.persist(file).map_err(|e| e.error)?;+ Ok(())+}+/// One install at a time in this process (a second create waits for it).static INSTALL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());@@ -569,6 +851,400 @@ mod tests {assert!(!is_loopback("http://10.0.0.5:7777"));}+ #[test]+ fn stable_keeps_its_ports_and_local_has_a_range_of_its_own() {+ use CuaChannel::{Local, Stable};+ assert_eq!(Stable.lume_port(), 7777);+ assert_eq!(Local.lume_port(), 7787);+ assert_eq!(port_range(Stable), 7777..=7786);+ assert_eq!(port_range(Local), 7787..=7796);+ // Stable is unchanged.+ let stable: Vec<u16> = fallback_ports_for(Stable, 7777).collect();+ assert_eq!(stable, (7778..=7786).collect::<Vec<_>>());+ assert_eq!(fallback_ports(7777).collect::<Vec<_>>(), stable);+ // Local walks 7788-7796 from its own port.+ assert_eq!(+ fallback_ports_for(Local, 7787).collect::<Vec<_>>(),+ (7788..=7796).collect::<Vec<_>>()+ );+ // Neither walks into the other's range, even from an overridden port.+ for from in 7770..7800 {+ assert!(+ fallback_ports_for(Local, from).all(|p| !port_range(Stable).contains(&p)),+ "Local from {from}"+ );+ assert!(+ fallback_ports_for(Stable, from).all(|p| !port_range(Local).contains(&p)),+ "Stable from {from}"+ );+ }+ assert_eq!(fallback_ports_for(Local, u16::MAX).count(), 0);+ }++ #[test]+ fn each_channel_looks_for_its_own_lume_binary() {+ use CuaChannel::{Local, Stable};+ let root = Path::new("/h/.cua/runtimes/lume");+ let on_path = |names: &'static [&'static str]| {+ move |n: &str| {+ names+ .contains(&n)+ .then(|| PathBuf::from("/Users/a/.local/bin").join(n))+ }+ };+ // Local prefers an installed `lume-local`, and never takes `lume`.+ assert_eq!(+ system_lume(Local, on_path(&["lume", "lume-local"]), root),+ Some(PathBuf::from("/Users/a/.local/bin/lume-local"))+ );+ assert_eq!(system_lume(Local, on_path(&["lume"]), root), None);+ // Stable is unchanged: `lume`.+ assert_eq!(+ system_lume(Stable, on_path(&["lume", "lume-local"]), root),+ Some(PathBuf::from("/Users/a/.local/bin/lume"))+ );+ assert_eq!(system_lume(Stable, on_path(&["lume-local"]), root), None);+ // The built-in one is not "this Mac's own".+ assert_eq!(+ system_lume(Local, |_| Some(root.join("0.6.0/lume-local")), root),+ None+ );+ }++ fn lume_for(channel: CuaChannel, root: &Path, vms: &Path) -> std::io::Result<LumeCmd> {+ LumeCmd::with_vm_dir(channel, root, "/opt/lume", vms)+ }++ #[test]+ fn stable_s_lume_is_started_as_it_always_was() {+ let dir = tempfile::tempdir().unwrap();+ let cmd = lume_for(CuaChannel::Stable, dir.path(), Path::new("/h/.lume")).unwrap();+ assert!(cmd.env().is_empty(), "no telemetry or temp dir overrides");+ assert_eq!(cmd.temp_dir(), None);+ assert_eq!(cmd.wrapped(), ("/opt/lume".to_string(), Vec::new()));+ assert_eq!(cmd.argv(["get", "vm"]), ["/opt/lume", "get", "vm"]);+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);+ }++ #[test]+ fn local_s_lume_is_started_on_its_own_vm_directory_and_config() {+ let dir = tempfile::tempdir().unwrap();+ let vms = Path::new("/Users/a/.lume-local");+ let cmd = lume_for(CuaChannel::Local, dir.path(), vms).unwrap();+ let get = |k: &str| {+ cmd.env()+ .iter()+ .find(|(n, _)| *n == k)+ .map(|(_, v)| v.clone())+ };+ assert_eq!(get("LUME_HOME"), Some(vms.into()));+ let xdg = PathBuf::from(get("XDG_CONFIG_HOME").unwrap());+ assert!(xdg.starts_with(dir.path()));+ // A Lume that does not read LUME_HOME yet reads this config instead.+ let yaml = std::fs::read_to_string(xdg.join("lume/config.yaml")).unwrap();+ assert_eq!(+ crate::storage::lume_default_location(&yaml).as_deref(),+ Some("/Users/a/.lume-local")+ );+ assert!(yaml.contains("cacheDirectory: \"/Users/a/.lume-local/cache\""));+ assert!(+ !yaml.contains("\"~/.lume\""),+ "never Stable's default location"+ );+ // The pinned Lume writes its telemetry identity under ~/.lume+ // whatever LUME_HOME says: Local's has telemetry off, by the+ // environment (which wins) and in its config.+ assert!(yaml.contains("telemetryEnabled: false"));+ assert_eq!(get("LUME_TELEMETRY_ENABLED"), Some("false".into()));+ assert_eq!(get("TMPDIR"), Some(dir.path().join("tmp").into()));+ // Where only a program and arguments can be given, the same+ // environment goes through `env`.+ let argv = cmd.argv(["attach", "vm"]);+ assert_eq!(argv[0], "/usr/bin/env");+ assert!(argv.contains(&"LUME_HOME=/Users/a/.lume-local".to_string()));+ assert!(argv.iter().any(|a| a.starts_with("XDG_CONFIG_HOME=")));+ assert_eq!(&argv[argv.len() - 3..], ["/opt/lume", "attach", "vm"]);+ }++ #[test]+ fn the_local_config_is_kept_while_it_is_right_and_fixed_when_it_is_not() {+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("xdg/lume/config.yaml");+ let vms = Path::new("/Users/a/.lume-local");+ lume_for(CuaChannel::Local, dir.path(), vms).unwrap();+ // Right: left alone (Lume may have added its own settings).+ let kept = format!(+ "{}# added by Lume\n",+ std::fs::read_to_string(&file).unwrap()+ );+ std::fs::write(&file, &kept).unwrap();+ lume_for(CuaChannel::Local, dir.path(), vms).unwrap();+ assert_eq!(std::fs::read_to_string(&file).unwrap(), kept);+ // Wrong (say it still names Stable's directory): rewritten.+ std::fs::write(+ &file,+ "defaultLocationName: \"home\"\nvmLocations:\n - name: \"home\"\n path: \"~/.lume\"\n",+ )+ .unwrap();+ lume_for(CuaChannel::Local, dir.path(), vms).unwrap();+ assert_eq!(+ crate::storage::lume_default_location(&std::fs::read_to_string(&file).unwrap())+ .as_deref(),+ Some("/Users/a/.lume-local")+ );+ // An older config of Local's that left telemetry on: rewritten.+ std::fs::write(+ &file,+ format!(+ "defaultLocationName: \"home\"\ntelemetryEnabled: true\nvmLocations:\n - name: \"home\"\n path: \"{}\"\n",+ vms.display()+ ),+ )+ .unwrap();+ lume_for(CuaChannel::Local, dir.path(), vms).unwrap();+ assert!(+ std::fs::read_to_string(&file)+ .unwrap()+ .contains("telemetryEnabled: false")+ );+ // A directory with a quote or a backslash in it is escaped, not+ // refused: it reads back as the same directory.+ for odd in ["/a\"b", r"/a\b"] {+ lume_for(CuaChannel::Local, dir.path(), Path::new(odd)).unwrap();+ let text = std::fs::read_to_string(&file).unwrap();+ assert_eq!(+ crate::storage::lume_default_location(&text).as_deref(),+ Some(odd)+ );+ }+ }++ /// A stand-in `lume` that prints a version and records the environment+ /// it was run with (the pinned Lume initialises settings and telemetry+ /// before it parses `--version`).+ #[cfg(unix)]+ fn recording_lume(dir: &Path) -> (PathBuf, PathBuf) {+ use std::os::unix::fs::PermissionsExt;+ std::fs::create_dir_all(dir).unwrap();+ let bin = dir.join("lume");+ let seen = dir.join("seen");+ std::fs::write(+ &bin,+ format!(+ "#!/bin/sh\n[ \"$1\" = --version ] || exit 64\n\+ printf '%s\\n' \"xdg=$XDG_CONFIG_HOME\" \"telemetry=$LUME_TELEMETRY_ENABLED\" \"tmp=$TMPDIR\" \"home=$LUME_HOME\" > '{}'\n\+ echo 0.6.0\n",+ seen.display()+ ),+ )+ .unwrap();+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();+ (bin, seen)+ }++ /// The version probes (the doctor's and the one that picks a Lume) run+ /// Lume with its channel's environment, so Local's never touches+ /// Stable's `~/.config/lume` or `~/.lume`; Stable's run as they did.+ #[cfg(unix)]+ #[tokio::test]+ async fn version_probes_run_with_the_channel_s_environment() {+ let t = tempfile::tempdir().unwrap();+ let root = t.path().join("cua-local/vmm/lume");+ let (local_bin, local_seen) = recording_lume(&t.path().join("local-bin"));+ let (stable_bin, stable_seen) = recording_lume(&t.path().join("stable-bin"));+ let (text_bin, text_seen) = recording_lume(&t.path().join("text-bin"));++ // `builtin::binary_version_in` (server and system-Lume probes).+ assert_eq!(+ binary_version_in(CuaChannel::Local, &root, &local_bin).as_deref(),+ Some("0.6.0")+ );+ let seen = std::fs::read_to_string(&local_seen).unwrap();+ assert!(+ seen.contains(&format!("xdg={}", root.join("xdg").display())),+ "{seen}"+ );+ assert!(seen.contains("telemetry=false"), "{seen}");+ assert!(+ seen.contains(&format!("tmp={}", root.join("tmp").display())),+ "{seen}"+ );+ assert!(seen.contains("home="), "{seen}");+ assert!(!seen.contains("home=\n"), "LUME_HOME unset: {seen}");++ // Stable's probe has no overrides.+ assert_eq!(+ binary_version_in(CuaChannel::Stable, &root, &stable_bin).as_deref(),+ Some("0.6.0")+ );+ let seen = std::fs::read_to_string(&stable_seen).unwrap();+ assert!(+ !seen.contains(&root.display().to_string()) && !seen.contains("telemetry=false"),+ "Stable's probe got Local's environment: {seen}"+ );++ // The doctor's probe (`crate::lume::version_text`).+ let cmd = LumeCmd::with_vm_dir(+ CuaChannel::Local,+ &root,+ &text_bin,+ Path::new("/Users/a/.lume-local"),+ )+ .unwrap();+ assert_eq!(+ crate::lume::version_text(&cmd).await.as_deref(),+ Some("0.6.0")+ );+ let seen = std::fs::read_to_string(&text_seen).unwrap();+ assert!(+ seen.contains("telemetry=false") && seen.contains("xdg="),+ "{seen}"+ );+ assert!(!seen.contains("xdg=\n"), "{seen}");+ }++ /// Local's `config.yaml` is replaced atomically: a Lume started while it+ /// is rewritten reads the old config or the new one, never an empty or+ /// cut-off file (the pinned Lume answers one with `~/.lume`).+ #[test]+ fn a_reader_never_sees_a_partial_local_config() {+ use std::sync::atomic::{AtomicBool, Ordering};+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("xdg/lume/config.yaml");+ let a = Path::new("/Users/a/.lume-local");+ let b = Path::new("/Users/b/.lume-local");+ seed_config(&file, a).unwrap();+ let done = AtomicBool::new(false);+ let reads = std::sync::atomic::AtomicUsize::new(0);+ std::thread::scope(|s| {+ let readers: Vec<_> = (0..3)+ .map(|_| {+ s.spawn(|| {+ while !done.load(Ordering::Relaxed) {+ let yaml = std::fs::read_to_string(&file).expect("always there");+ let at = crate::storage::lume_default_location(&yaml);+ assert!(+ matches!(+ at.as_deref(),+ Some("/Users/a/.lume-local" | "/Users/b/.lume-local")+ ),+ "a partial config: {yaml:?}"+ );+ reads.fetch_add(1, Ordering::Relaxed);+ }+ })+ })+ .collect();+ // Each writer finds the other's directory in the file, so every+ // call rewrites it.+ let writers: Vec<_> = [a, b]+ .into_iter()+ .map(|vm| {+ let file = &file;+ s.spawn(move || {+ for _ in 0..1500 {+ seed_config(file, vm).unwrap();+ }+ })+ })+ .collect();+ for w in writers {+ w.join().unwrap();+ }+ done.store(true, Ordering::Relaxed);+ for r in readers {+ r.join().unwrap();+ }+ });+ assert!(reads.load(Ordering::Relaxed) > 0);+ // No temp files left beside it.+ let left: Vec<_> = std::fs::read_dir(file.parent().unwrap())+ .unwrap()+ .flatten()+ .map(|e| e.file_name())+ .collect();+ assert_eq!(left, [std::ffi::OsString::from("config.yaml")]);+ }++ /// A VM directory with a backslash, a quote or a newline in it is+ /// escaped, so a real YAML parser (Lume's) reads the same directory+ /// back: it is not decoded as `\t` or `\U`, and it ends where it ends.+ #[test]+ fn the_config_reads_back_the_directory_it_was_written_for() {+ #[derive(serde::Deserialize)]+ struct Location {+ name: String,+ path: String,+ }+ #[derive(serde::Deserialize)]+ #[serde(rename_all = "camelCase")]+ struct Config {+ default_location_name: String,+ cache_directory: String,+ telemetry_enabled: bool,+ vm_locations: Vec<Location>,+ }+ for dir in [+ "/Users/a/.lume-local",+ r"/Volumes/Fast\tmp\Users\new",+ r"C:\Users\a\.lume-local",+ r#"/Users/a/it's "quoted""#,+ "/Users/a/two\nlines",+ "/Users/a/ünïcode #not a comment: x",+ ] {+ let parsed: Config = serde_yaml_ng::from_str(&config_yaml(dir))+ .unwrap_or_else(|e| panic!("{dir:?}: {e}"));+ assert_eq!(parsed.default_location_name, "home", "{dir:?}");+ assert_eq!(parsed.vm_locations.len(), 1, "{dir:?}");+ assert_eq!(parsed.vm_locations[0].name, "home", "{dir:?}");+ assert_eq!(parsed.vm_locations[0].path, dir);+ assert_eq!(parsed.cache_directory, format!("{dir}/cache"));+ assert!(!parsed.telemetry_enabled);+ // Cua's own reader agrees with the parser.+ assert_eq!(+ crate::storage::lume_default_location(&config_yaml(dir)).as_deref(),+ Some(dir),+ "{dir:?}"+ );+ }+ }++ /// Seeding writes that config and is then a no-op for the same directory+ /// (the file is read back through the escapes), and replaces it atomically+ /// for another.+ #[test]+ fn seeding_a_backslash_directory_is_stable() {+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("xdg/lume/config.yaml");+ let vm = Path::new(r"/Volumes/Fast\tmp\Users\new");+ seed_config(&file, vm).unwrap();+ let first = std::fs::read_to_string(&file).unwrap();+ let parsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&first).unwrap();+ assert_eq!(+ parsed["vmLocations"][0]["path"].as_str(),+ vm.to_str(),+ "{first}"+ );+ let before = std::fs::metadata(&file).unwrap().modified().unwrap();+ std::thread::sleep(std::time::Duration::from_millis(20));+ seed_config(&file, vm).unwrap();+ assert_eq!(+ std::fs::metadata(&file).unwrap().modified().unwrap(),+ before+ );+ let other = Path::new(r"C:\other");+ seed_config(&file, other).unwrap();+ let parsed: serde_yaml_ng::Value =+ serde_yaml_ng::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();+ assert_eq!(parsed["vmLocations"][0]["path"].as_str(), other.to_str());+ let left: Vec<_> = std::fs::read_dir(file.parent().unwrap())+ .unwrap()+ .flatten()+ .map(|e| e.file_name())+ .collect();+ assert_eq!(left, [std::ffi::OsString::from("config.yaml")]);+ }+#[test]fn only_cua_s_team_is_accepted() {assert!(team_matches(diff --git a/libs/cua/crates/cua-vmm/src/lume/client.rs b/libs/cua/crates/cua-vmm/src/lume/client.rsindex 31aa9499d0..79cd76068b 100644--- a/libs/cua/crates/cua-vmm/src/lume/client.rs+++ b/libs/cua/crates/cua-vmm/src/lume/client.rs@@ -1,4 +1,5 @@-//! Typed HTTP client for `lume serve` (default `http://127.0.0.1:7777`).+//! Typed HTTP client for `lume serve` (default `http://127.0.0.1:7777`, Local's+//! `http://127.0.0.1:7787`).//!//! Routes mirror `libs/lume/src/Server/Server.swift`.diff --git a/libs/cua/crates/cua-vmm/src/lume/lease.rs b/libs/cua/crates/cua-vmm/src/lume/lease.rsindex ad10a3dbeb..ba7170871b 100644--- a/libs/cua/crates/cua-vmm/src/lume/lease.rs+++ b/libs/cua/crates/cua-vmm/src/lume/lease.rs@@ -25,6 +25,8 @@use std::path::Path;+use cua_home::channel::CuaChannel;+/// One `bootpd` lease.#[derive(Clone, Debug, PartialEq, Eq)]pub struct Lease {@@ -170,10 +172,28 @@ pub async fn lookup(arp_ip(&String::from_utf8_lossy(&out.stdout), mac).map(|ip| (ip, "arp"))}-/// Directories Lume keeps VMs in: `~/.lume` plus every `path:` under-/// `vmLocations` in `~/.config/lume/config.yaml`.+/// Directories this process's Lume keeps VMs in ([`vm_dirs_for`]).pub fn vm_dirs(home: &Path) -> Vec<std::path::PathBuf> {- let mut out = vec![home.join(".lume")];+ vm_dirs_for(+ CuaChannel::current(),+ home,+ crate::storage::lume_home_env().as_deref(),+ )+}++/// Directories `channel`'s Lume keeps VMs in: its default one (`~/.lume`, or+/// Local's `~/.lume-local`, which `lume_home` moves), plus, for Stable, every `path:` under+/// `vmLocations` in `~/.config/lume/config.yaml`. Local's Lume has its own+/// config, so Stable's is not read: its VMs are never Local's.+pub fn vm_dirs_for(+ channel: CuaChannel,+ home: &Path,+ lume_home: Option<&str>,+) -> Vec<std::path::PathBuf> {+ let mut out = vec![crate::storage::default_lume_dir(channel, home, lume_home)];+ if channel.is_local() {+ return out;+ }if let Ok(cfg) = std::fs::read_to_string(home.join(".config/lume/config.yaml")) {for l in cfg.lines() {if let Some(p) = l.trim().strip_prefix("path:") {@@ -196,10 +216,15 @@ pub fn vm_dirs(home: &Path) -> Vec<std::path::PathBuf> {/// VM directory. Only `name`'s, and only while no VM of that name exists/// there; a guard with content is not Lume's and stays.pub fn remove_resize_guards(home: &Path, name: &str) {+ remove_resize_guards_in(&vm_dirs(home), name);+}++/// [`remove_resize_guards`] in `dirs`.+pub fn remove_resize_guards_in(dirs: &[std::path::PathBuf], name: &str) {if name.is_empty() || name.contains('/') || name.starts_with('.') {return;}- for dir in vm_dirs(home) {+ for dir in dirs {let guard = dir.join(format!(".{name}.resize.guard"));let empty = std::fs::symlink_metadata(&guard).is_ok_and(|m| m.is_file() && m.len() == 0);if empty@@ -214,7 +239,12 @@ pub fn remove_resize_guards(home: &Path, name: &str) {/// The VM's MAC from its Lume `config.json` (read-only). `lume serve`/// releases before 0.6 do not report `macAddress` over the API.pub fn config_mac(home: &Path, name: &str) -> Option<String> {- vm_dirs(home).into_iter().find_map(|d| {+ config_mac_in(&vm_dirs(home), name)+}++/// [`config_mac`] in `dirs`.+pub fn config_mac_in(dirs: &[std::path::PathBuf], name: &str) -> Option<String> {+ dirs.iter().find_map(|d| {let raw = std::fs::read(d.join(name).join("config.json")).ok()?;let v: serde_json::Value = serde_json::from_slice(&raw).ok()?;v.get("macAddress")?.as_str().and_then(normalize_mac)@@ -234,10 +264,11 @@ mod tests {std::fs::write(lume.join(format!(".{f}.resize.guard")), b"").unwrap();}std::fs::write(lume.join(".full.resize.guard"), b"x").unwrap();- remove_resize_guards(home.path(), "gone");- remove_resize_guards(home.path(), "kept");- remove_resize_guards(home.path(), "full");- remove_resize_guards(home.path(), "../escape");+ let dirs = vm_dirs_for(CuaChannel::Stable, home.path(), None);+ remove_resize_guards_in(&dirs, "gone");+ remove_resize_guards_in(&dirs, "kept");+ remove_resize_guards_in(&dirs, "full");+ remove_resize_guards_in(&dirs, "../escape");assert!(!lume.join(".gone.resize.guard").exists());assert!(lume.join(".kept.resize.guard").exists(),@@ -322,11 +353,39 @@ mod tests {r#"{"macAddress":"E2:2D:52:4:4E:BB","os":"linux"}"#,).unwrap();+ let dirs = vm_dirs_for(CuaChannel::Stable, home.path(), None);assert_eq!(- config_mac(home.path(), "vm1").as_deref(),+ config_mac_in(&dirs, "vm1").as_deref(),Some("e2:2d:52:04:4e:bb"));- assert_eq!(config_mac(home.path(), "nope"), None);+ assert_eq!(config_mac_in(&dirs, "nope"), None);+ }++ #[test]+ fn local_reads_its_own_vm_dir_and_never_stable_s() {+ let home = tempfile::tempdir().unwrap();+ // Stable's config points somewhere; Local must not follow it.+ let other = home.path().join("vms");+ std::fs::create_dir_all(home.path().join(".config/lume")).unwrap();+ std::fs::write(+ home.path().join(".config/lume/config.yaml"),+ format!("vmLocations:\n - name: x\n path: {}\n", other.display()),+ )+ .unwrap();+ let local = vm_dirs_for(CuaChannel::Local, home.path(), None);+ assert_eq!(local, [home.path().join(".lume-local")]);+ let stable = vm_dirs_for(CuaChannel::Stable, home.path(), None);+ assert_eq!(stable, [home.path().join(".lume"), other]);+ assert!(!local.contains(&home.path().join(".lume")));+ // LUME_HOME moves Local's default one, never Stable's.+ assert_eq!(+ vm_dirs_for(CuaChannel::Local, home.path(), Some("~/moved")),+ [home.path().join("moved")]+ );+ assert_eq!(+ vm_dirs_for(CuaChannel::Stable, home.path(), Some("~/moved")),+ stable+ );}#[test]diff --git a/libs/cua/crates/cua-vmm/src/lume/mod.rs b/libs/cua/crates/cua-vmm/src/lume/mod.rsindex ba951f5880..77ff0380d5 100644--- a/libs/cua/crates/cua-vmm/src/lume/mod.rs+++ b/libs/cua/crates/cua-vmm/src/lume/mod.rs@@ -26,6 +26,7 @@ use std::sync::Arc;use std::time::Duration;use async_trait::async_trait;+use cua_home::channel::CuaChannel;use crate::error::{Result, VmmError};use crate::exec::{GuestExec, PrefixExec};@@ -33,6 +34,7 @@ use crate::host;use crate::runtime::Runtime;use crate::types::*;+pub use builtin::LumeCmd;pub use client::{CreateVm, LumeClient, RunVm, SetVm, SharedDir, VmDetails};pub use owned::{OwnedKind, OwnedVm, OwnedVms};pub use ssh::LumeSshExec;@@ -93,7 +95,14 @@ pub const INSTALL_URL: &str =/// Configuration for [`LumeRuntime`].#[derive(Clone, Debug)]pub struct LumeConfig {- /// API base URL (default `$LUME_API` or `http://127.0.0.1:7777`).+ /// The Cua channel this Lume belongs to (default: this process's,+ /// [`CuaChannel::current`]). It decides the default URL and port, the+ /// VM directory, the binary name and the fallback ports: Stable's+ /// `lume` on `:7777` with VMs in `~/.lume`, Local's `lume-local` on+ /// `:7787` with VMs in `~/.lume-local`.+ pub channel: CuaChannel,+ /// API base URL (default `$LUME_API`, else the channel's:+ /// `http://127.0.0.1:7777` for Stable, `http://127.0.0.1:7787` for Local).pub url: String,/// Start `lume serve` when the API is unreachable.pub spawn_serve: bool,@@ -111,13 +120,16 @@ pub struct LumeConfig {impl Default for LumeConfig {fn default() -> Self {+ let channel = CuaChannel::current();Self {- url: serving_url(- &std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into()),- ),+ channel,+ url: serving_url(&crate::local_network::lume_base_with(+ channel,+ std::env::var("LUME_API").ok().as_deref(),+ )),spawn_serve: true,allow_install: false,- root: host::cua_home().join("vmm").join("lume"),+ root: default_root(),ip_timeout: Duration::from_secs(300),pull_timeout: Duration::from_secs(3600),leases_path: lease::LEASES_PATH.into(),@@ -163,7 +175,11 @@ fn remember_move(from: &str, to: &str) {/// The version of the `lume serve` at `client`: what it reports, else (on/// this Mac) its executable's `--version`.-async fn server_version(client: &LumeClient) -> Option<String> {+async fn server_version(+ channel: CuaChannel,+ config_root: &std::path::Path,+ client: &LumeClient,+) -> Option<String> {if let Some(v) = client.reported_version().await {return Some(v);}@@ -172,12 +188,17 @@ async fn server_version(client: &LumeClient) -> Option<String> {return None;}let port = url_port(&url)?;+ let config_root = config_root.to_path_buf();tokio::task::spawn_blocking(move || {- // Only a `lume` is asked for its version (never, say, a test's- // own fake server process).+ // Only a Lume (`lume`, or a channel's own such as `lume-local`) is+ // asked for its version, never, say, a test's own fake server+ // process.builtin::serving_binary(port)- .filter(|b| b.file_name().is_some_and(|n| n == "lume"))- .and_then(|b| builtin::binary_version(&b))+ .filter(|b| {+ b.file_name()+ .is_some_and(|n| CuaChannel::ALL.iter().any(|c| n == c.lume_bin_name()))+ })+ .and_then(|b| builtin::binary_version_in(channel, &config_root, &b))}).await.ok()@@ -234,13 +255,10 @@ pub fn warm_vm_names(base: &str) -> [String; 2] {/// (a warm state, a checkpoint) or a claimed pool member would otherwise/// keep the name it was saved with. Bounded retries while SSH comes up;/// failures are logged, never fatal.-fn set_macos_hostname_later(vm: &str, name: &str) {- let Some(bin) = lume_bin() else { return };+fn set_macos_hostname_later(lume: Option<LumeCmd>, vm: &str, name: &str) {+ let Some(lume) = lume else { return };let host = macos_hostname(name);- let exec = PrefixExec {- program: bin.display().to_string(),- prefix: vec!["ssh".into(), vm.to_string()],- };+ let exec = lume_ssh_prefix(&lume, vm);let vm = vm.to_string();crate::cleanup::spawn(async move {let script = format!(@@ -278,10 +296,69 @@ pub fn macos_hostname(name: &str) -> String {if h.is_empty() { "space".into() } else { h }}+/// A guest command prefix: `lume ssh <vm>`, run with `lume`'s environment.+fn lume_ssh_prefix(lume: &LumeCmd, vm: &str) -> PrefixExec {+ let (program, mut prefix) = lume.wrapped();+ prefix.extend(["ssh".to_string(), vm.to_string()]);+ PrefixExec { program, prefix }+}++/// `lume --version`'s output, run as `lume` runs (its channel's+/// environment), for a report; `None` when it fails or takes over 5 s.+pub async fn version_text(lume: &LumeCmd) -> Option<String> {+ let run = lume+ .tokio_command()+ .arg("--version")+ .stdin(std::process::Stdio::null())+ .kill_on_drop(true)+ .output();+ let out = tokio::time::timeout(Duration::from_secs(5), run)+ .await+ .ok()?+ .ok()?;+ out.status+ .success()+ .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())+}++/// [`lume_cmd_for`] this process's channel.+pub fn lume_cmd() -> Result<Option<LumeCmd>> {+ lume_cmd_for(CuaChannel::current())+}++/// The Lume for `channel` to run a process from, with the environment that+/// keeps it in the channel's VM directory ([`LumeCmd`]); `None` when there+/// is no Lume yet. For a caller that hands a command to another process+/// (`lume attach`: [`LumeCmd::argv`]).+pub fn lume_cmd_for(channel: CuaChannel) -> Result<Option<LumeCmd>> {+ match lume_bin_for(channel) {+ Some(bin) => Ok(Some(LumeCmd::new(channel, &default_root(), bin)?)),+ None => Ok(None),+ }+}++/// State for Linux disk conversions and seeds, and the private config and+/// temp directories of Local's Lume: `<cua home>/vmm/lume`.+pub(crate) fn default_root() -> PathBuf {+ root_in(&host::cua_home())+}++/// [`default_root`] under the cua home `home`.+pub(crate) fn root_in(home: &std::path::Path) -> PathBuf {+ home.join("vmm").join("lume")+}+/// Locate the `lume` binary for the `runtime.lume` setting: this Mac's-/// own, or the built-in one ([`builtin`]) when installed.+/// own, or the built-in one ([`builtin`]) when installed. For this+/// process's channel ([`lume_bin_for`]).pub fn lume_bin() -> Option<PathBuf> {- builtin::resolve(builtin::LumeSource::current())+ lume_bin_for(CuaChannel::current())+}++/// [`lume_bin`] for `channel`: Stable's own Lume is `lume`, Local's+/// `lume-local` (Local never uses Stable's).+pub fn lume_bin_for(channel: CuaChannel) -> Option<PathBuf> {+ builtin::resolve_for(channel, builtin::LumeSource::current())}/// Deletes a clone whose create was cut off (dropped) before its first@@ -370,7 +447,7 @@ impl LumeRuntime {/// GPU acceleration on this host ([`crate::gpu::lume_support`]).pub fn gpu_support(&self) -> crate::gpu::GpuSupport {- crate::gpu::lume_support(lume_bin().is_some())+ crate::gpu::lume_support(self.bin().is_some())}/// After `name` was deleted: GPU acceleration's host preference goes@@ -397,10 +474,46 @@ impl LumeRuntime {&self.client}+ /// The Lume this runtime runs: this Mac's own or the built-in one, for+ /// its channel ([`lume_bin_for`]).+ fn bin(&self) -> Option<PathBuf> {+ lume_bin_for(self.cfg.channel)+ }++ /// The Lume this runtime runs, with the environment its channel needs+ /// ([`LumeCmd`]). Every Lume process this runtime starts, `serve`+ /// included, is made from this, so a Local Lume never runs without its+ /// own VM directory.+ fn lume(&self) -> Result<Option<LumeCmd>> {+ match self.bin() {+ Some(bin) => Ok(Some(LumeCmd::new(self.cfg.channel, &self.cfg.root, bin)?)),+ None => Ok(None),+ }+ }++ /// [`LumeRuntime::lume`] for work that is best effort: a failure is+ /// logged and the work skipped.+ fn lume_or_log(&self) -> Option<LumeCmd> {+ self.lume().unwrap_or_else(|e| {+ tracing::warn!(error = %e, "could not prepare the Lume environment");+ None+ })+ }++ /// Where this runtime's Lume keeps VMs by default (`~/.lume`, or+ /// Local's `~/.lume-local` / `$LUME_HOME`).+ fn vm_dir(&self) -> PathBuf {+ crate::storage::default_lume_dir(+ self.cfg.channel,+ &host::home_dir(),+ crate::storage::lume_home_env().as_deref(),+ )+ }+/// The port of the `lume serve` in use (moved off the configured one/// when an old Lume holds it).fn port(&self) -> u16 {- url_port(&self.client.base()).unwrap_or(7777)+ url_port(&self.client.base()).unwrap_or_else(|| self.cfg.channel.lume_port())}/// Make sure a current `lume serve` answers, starting (and, if allowed,@@ -422,7 +535,8 @@ impl LumeRuntime {return Ok(());}let source = builtin::LumeSource::current();- match builtin::judge_server(source, server_version(&self.client).await.as_deref()) {+ let version = server_version(self.cfg.channel, &self.cfg.root, &self.client).await;+ match builtin::judge_server(source, version.as_deref()) {builtin::ServerVerdict::Use => {}builtin::ServerVerdict::UseOld(v) => {tracing::warn!(@@ -442,7 +556,7 @@ impl LumeRuntime {}/// The `lume serve` at `old_url` is Lume `old` (too old): use a current- /// one on the first of [`builtin::fallback_ports`] that has one or is+ /// one on the first of [`builtin::fallback_ports_for`] that has one or is/// free, starting it there. The old server keeps running untouched.async fn serve_elsewhere(&self, old_url: &str, old: &str) -> Result<()> {let too_old = format!(@@ -455,14 +569,15 @@ impl LumeRuntime {"update it (or stop it and let cua run its built-in Lume)",));}- let port = url_port(old_url).unwrap_or(7777);- for p in builtin::fallback_ports(port) {+ let port = url_port(old_url).unwrap_or_else(|| self.cfg.channel.lume_port());+ let ports: Vec<u16> = builtin::fallback_ports_for(self.cfg.channel, port).collect();+ for &p in &ports {let url = builtin::with_port(old_url, p);let candidate = LumeClient::new(url.clone());if candidate.reachable().await {// Only a Lume known to be current (cua's own from an earlier// run); anything else on the port is left alone.- if server_version(&candidate)+ if server_version(self.cfg.channel, &self.cfg.root, &candidate).await.is_some_and(|v| builtin::new_enough(&v)){@@ -491,8 +606,8 @@ impl LumeRuntime {too_old,format!("ports {}-{} are taken too; update or stop that Lume",- port.saturating_add(1),- port.saturating_add(9)+ ports.first().copied().unwrap_or(port),+ ports.last().copied().unwrap_or(port)),))}@@ -513,7 +628,7 @@ impl LumeRuntime {));}let source = builtin::LumeSource::current();- let bin = match lume_bin() {+ let bin = match self.bin() {Some(b) => b,// Nothing to ask: the pinned, signed Lume, into cua's own dir.None if source.allows_builtin() => builtin::ensure().await?,@@ -524,15 +639,32 @@ impl LumeRuntime {Choose Built-in for macOS VMs in Settings (or `cua config set runtime.lume builtin`)",));}- None if self.cfg.allow_install => {+ // The official installer is Stable's (`lume`, its LaunchAgent and+ // port): Local never runs it over a Stable install.+ None if self.cfg.allow_install && !self.cfg.channel.is_local() => {install_lume().await?;if self.client.reachable().await {return Ok(()); // installer's LaunchAgent started it}- lume_bin().ok_or_else(|| {- VmmError::missing("lume", "installer finished but `lume` is not on PATH")+ self.bin().ok_or_else(|| {+ VmmError::missing(+ self.cfg.channel.lume_bin_name(),+ format!(+ "installer finished but `{}` is not on PATH",+ self.cfg.channel.lume_bin_name()+ ),+ )})?}+ None if self.cfg.channel.is_local() => {+ return Err(VmmError::missing(+ self.cfg.channel.lume_bin_name(),+ format!(+ "install it with Lume's install-local.sh, or let cua use its built-in Lume (`cua config set runtime.lume builtin`); `{}` is not on PATH",+ self.cfg.channel.lume_bin_name()+ ),+ ));+ }None => {return Err(VmmError::missing("lume",@@ -542,8 +674,10 @@ impl LumeRuntime {));}};+ std::fs::create_dir_all(&self.cfg.root)?;+ let lume = LumeCmd::new(self.cfg.channel, &self.cfg.root, &bin)?;if source == builtin::LumeSource::System- && let Some(v) = builtin::binary_version(&bin).filter(|v| !builtin::new_enough(v))+ && let Some(v) = builtin::binary_version(&lume).filter(|v| !builtin::new_enough(v)){tracing::warn!(bin = %bin.display(),@@ -555,10 +689,9 @@ impl LumeRuntime {}// No `lume serve` answers, so none of its pulls runs: a pull a// killed serve left half-made in its temp dir is only taking space.- sweep_stale_pull_dirs(&lume_temp_dir(), STALE_PULL_DIR_IDLE);- std::fs::create_dir_all(&self.cfg.root)?;+ sweep_pull_dirs_for(&lume, &lume_temp_dir(), STALE_PULL_DIR_IDLE);let log = std::fs::File::create(self.cfg.root.join("serve.log"))?;- let mut cmd = std::process::Command::new(&bin);+ let mut cmd = lume.command();cmd.args(["serve", "--port", &self.port().to_string()]).stdin(std::process::Stdio::null()).stdout(log.try_clone()?)@@ -814,7 +947,8 @@ impl LumeRuntime {disk: &std::path::Path,seed: Option<&std::path::Path>,) -> Result<()> {- let bin = lume_bin()+ let lume = self+ .lume()?.ok_or_else(|| VmmError::missing("lume", "binary needed for Linux disk VMs"))?;let log = self.cfg.root.join(name).join("run.log");let mut args = vec![@@ -832,9 +966,7 @@ impl LumeRuntime {args.push("--mount".into());args.push(s.display().to_string());}- let argv: Vec<&str> = args.iter().map(String::as_str).collect();- host::run(bin, &argv).await?;- Ok(())+ cli_run(&lume, &args).await}/// The macOS setup share: a read-only host directory mounted in the guest@@ -926,7 +1058,7 @@ impl LumeRuntime {}}crate::disk::ensure_space(- &host::home_dir().join(".lume"),+ &self.vm_dir(),crate::disk::LUME_PULL_ESTIMATE,&format!("pull {reference}"),)?;@@ -945,8 +1077,8 @@ impl LumeRuntime {let pulled = match creds.filter(|c| c.applies_to(crate::registry_of(reference))) {// `lume serve`'s pull API takes no credentials: the `lume pull`// CLI reads them from its environment (never argv).- Some(c) => match lume_bin() {- Some(bin) => cli_pull(&bin, reference, base_name, c, self.cfg.pull_timeout).await,+ Some(c) => match self.lume()? {+ Some(lume) => cli_pull(&lume, reference, base_name, c, self.cfg.pull_timeout).await,None => Err(VmmError::missing("lume","binary needed to pull a private image",@@ -1085,14 +1217,14 @@ pub fn cli_pull_args(reference: &str, name: &str) -> Vec<String> {/// credentials from `GITHUB_USERNAME` / `GITHUB_TOKEN` in its environment./// The credentials never go on argv or into a log line or error.pub async fn cli_pull(- bin: &std::path::Path,+ lume: &LumeCmd,reference: &str,name: &str,creds: &RegistryCredentials,timeout: Duration,) -> Result<()> {let args = cli_pull_args(reference, name);- let mut cmd = tokio::process::Command::new(bin);+ let mut cmd = lume.tokio_command();cmd.args(&args).env("GITHUB_USERNAME", &creds.username).env("GITHUB_TOKEN", &creds.password)@@ -1128,6 +1260,19 @@ pub async fn cli_pull(})}+/// Runs the `lume` CLI to completion with `args` (the VM-directory+/// environment of its channel applies), for what has no `lume serve` call.+async fn cli_run(lume: &LumeCmd, args: &[String]) -> Result<()> {+ let (program, lead) = lume.wrapped();+ let argv: Vec<&str> = lead+ .iter()+ .map(String::as_str)+ .chain(args.iter().map(String::as_str))+ .collect();+ host::run(program, &argv).await?;+ Ok(())+}+/// Host-side marker: this VM got a workload environment from cua-vmm (so a/// later start without one clears it).const MACOS_ENV_MARKER: &str = "env-applied";@@ -1161,6 +1306,13 @@ fn lume_temp_dir() -> PathBuf {std::env::temp_dir()}+/// [`sweep_stale_pull_dirs`] in the temp directory `lume` pulls into: its+/// private one (Local's), else `shared`, the user's. Local never looks in+/// the shared one, where Stable's running Lume may be mid-pull.+fn sweep_pull_dirs_for(lume: &LumeCmd, shared: &std::path::Path, idle: Duration) -> usize {+ sweep_stale_pull_dirs(lume.temp_dir().unwrap_or(shared), idle)+}+/// Removes the `lume_vm_*` dirs in `temp` (a pull's half-made VM, left by a/// `lume serve` that was killed mid-pull: it cleans up only when it can)/// that nothing wrote for `idle`. Returns how many it removed.@@ -1294,8 +1446,8 @@ const CLI_STATUS_TIMEOUT: Duration = Duration::from_secs(15);/// A VM's status from `lume get <name> --format json`, for when `lume serve`/// is not running.-async fn cli_status(bin: &std::path::Path, name: &str) -> Result<Status> {- let mut cmd = tokio::process::Command::new(bin);+async fn cli_status(lume: &LumeCmd, name: &str) -> Result<Status> {+ let mut cmd = lume.tokio_command();cmd.args(["get", name, "--format", "json"]).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped())@@ -1493,7 +1645,7 @@ impl LumeRuntime {self.ensure_base_with(&spec.image, &base, spec.registry_auth.as_ref()).await?;crate::disk::ensure_space(- &host::home_dir().join(".lume"),+ &self.vm_dir(),crate::disk::VM_CREATE_ESTIMATE,&format!("create VM {}", spec.name),)?;@@ -1524,7 +1676,7 @@ impl LumeRuntime {self.wait_restored(&spec.name).await;tracing::info!(vm = %spec.name, warm = %warm, "resumed a new Space from the image's warm state");let inst = self.finish_start(spec, true).await?;- set_macos_hostname_later(&spec.name, &spec.name);+ set_macos_hostname_later(self.lume_or_log(), &spec.name, &spec.name);return Ok(inst);}// APFS clonefile: copy-on-write, so the clone costs only what@@ -1612,7 +1764,7 @@ impl LumeRuntime {}let inst = self.finish_start(spec, macos_booted).await?;if resumes_state && macos_booted {- set_macos_hostname_later(&spec.name, &spec.name);+ set_macos_hostname_later(self.lume_or_log(), &spec.name, &spec.name);}Ok(inst)}@@ -1625,11 +1777,7 @@ impl LumeRuntime {));let vm = self.wait_for_ip(&spec.name).await?;if macos_booted {- let bin = lume_bin();- let exec = bin.map(|b| PrefixExec {- program: b.display().to_string(),- prefix: vec!["ssh".into(), spec.name.clone()],- });+ let exec = self.lume()?.map(|l| lume_ssh_prefix(&l, &spec.name));self.sync_macos_env(&spec.name,&spec.env,@@ -2017,7 +2165,11 @@ impl Runtime for LumeRuntime {.await?.ok_or_else(|| VmmError::NotFound(new_name.into()))?;if vm.os.eq_ignore_ascii_case("macos") {- set_macos_hostname_later(new_name, identity.hostname.as_deref().unwrap_or(new_name));+ set_macos_hostname_later(+ self.lume_or_log(),+ new_name,+ identity.hostname.as_deref().unwrap_or(new_name),+ );}Ok(Self::instance(&vm, None, &self.load_ports(new_name)))}@@ -2142,8 +2294,8 @@ impl Runtime for LumeRuntime {// something starts it). The `lume` CLI reads the VM's state from// its directory without a server, so a status check does not have// to start one.- Err(VmmError::Missing { .. }) => match lume_bin() {- Some(bin) => cli_status(&bin, name).await,+ Err(VmmError::Missing { .. }) => match self.lume()? {+ Some(lume) => cli_status(&lume, name).await,// No Lume on this machine at all (the built-in one is set// up on first use): it runs no VM, so none has this name.None => Err(VmmError::NotFound(name.into())),@@ -2204,12 +2356,10 @@ impl Runtime for LumeRuntime {.await?.ok_or_else(|| VmmError::NotFound(name.into()))?;if vm.os.eq_ignore_ascii_case("macos") {- let bin =- lume_bin().ok_or_else(|| VmmError::missing("lume", "needed for `lume ssh`"))?;- return Ok(Some(Arc::new(LumeSshExec::new(- bin.display().to_string(),- name,- ))));+ let lume = self+ .lume()?+ .ok_or_else(|| VmmError::missing("lume", "needed for `lume ssh`"))?;+ return Ok(Some(Arc::new(LumeSshExec::from_lume(&lume, name))));}Ok(None)}@@ -2219,6 +2369,294 @@ impl Runtime for LumeRuntime {mod tests {use super::*;+ fn runtime_for(channel: CuaChannel, url: &str) -> LumeRuntime {+ LumeRuntime::new(LumeConfig {+ channel,+ url: url.into(),+ spawn_serve: false,+ ..LumeConfig::default()+ })+ }++ /// Stable is unchanged (`:7777`); Local serves on its own port, and a+ /// URL without one falls back to the channel's.+ #[test]+ fn each_channel_serves_on_its_own_port() {+ for (channel, port) in [(CuaChannel::Stable, 7777), (CuaChannel::Local, 7787)] {+ assert_eq!(channel.lume_port(), port);+ assert_eq!(runtime_for(channel, channel.lume_api()).port(), port);+ assert_eq!(runtime_for(channel, "http://localhost").port(), port);+ }+ // `LUME_API` (here, the configured URL) still decides when it has a port.+ assert_eq!(+ runtime_for(CuaChannel::Local, "http://127.0.0.1:7900").port(),+ 7900+ );+ assert_eq!(+ runtime_for(CuaChannel::Stable, "http://127.0.0.1:7900").port(),+ 7900+ );+ }++ /// A runtime keeps its VMs where its channel does.+ #[test]+ fn each_channel_keeps_its_vms_in_its_own_directory() {+ let home = host::home_dir();+ let stable = runtime_for(CuaChannel::Stable, "http://127.0.0.1:1").vm_dir();+ let local = runtime_for(CuaChannel::Local, "http://127.0.0.1:1").vm_dir();+ // Stable ignores LUME_HOME: the pinned Lume does too.+ assert_eq!(stable, home.join(".lume"));+ if crate::storage::lume_home_env().is_none() {+ assert_eq!(local, home.join(".lume-local"));+ assert_ne!(stable, local);+ }+ }++ fn pull_dir(parent: &std::path::Path, name: &str) {+ let d = parent.join(name);+ std::fs::create_dir_all(d.join("sub")).unwrap();+ std::fs::write(d.join("sub/disk.img"), b"x").unwrap();+ }++ /// Starting Local's Lume sweeps its own temp directory, never the+ /// shared one where Stable's running Lume may be mid-pull. Stable's+ /// sweep is as it was.+ #[test]+ fn local_s_start_up_sweep_leaves_stable_s_pull_dirs_alone() {+ let t = tempfile::tempdir().unwrap();+ let shared = t.path().join("shared-tmp");+ let root = t.path().join("cua-local/vmm/lume");+ let vms = t.path().join(".lume-local");+ std::fs::create_dir_all(&shared).unwrap();+ // Stable's Lume is pulling (quiet for longer than the sweep's idle+ // time, as a pull waiting on the network can be).+ pull_dir(&shared, "lume_vm_stable-pull");+ let local = LumeCmd::with_vm_dir(CuaChannel::Local, &root, "/opt/lume", &vms).unwrap();+ let stable = LumeCmd::with_vm_dir(CuaChannel::Stable, &root, "/opt/lume", &vms).unwrap();+ // Local's Lume pulls into a temp directory of its own, under its home.+ let private = local.temp_dir().expect("Local has its own temp dir");+ assert!(private.starts_with(&root) && private.is_dir());+ assert!(+ local+ .env()+ .iter()+ .any(|(k, v)| *k == "TMPDIR" && v == private.as_os_str())+ );+ assert_eq!(stable.temp_dir(), None);+ assert!(stable.env().iter().all(|(k, _)| *k != "TMPDIR"));+ pull_dir(private, "lume_vm_local-pull");++ // Local's sweep (everything counts as stale) removes its own only.+ assert_eq!(sweep_pull_dirs_for(&local, &shared, Duration::ZERO), 1);+ assert!(+ shared.join("lume_vm_stable-pull").exists(),+ "Stable's pull was swept"+ );+ assert!(!private.join("lume_vm_local-pull").exists());++ // Stable's sweep still covers the shared directory.+ assert_eq!(sweep_pull_dirs_for(&stable, &shared, Duration::ZERO), 1);+ assert!(!shared.join("lume_vm_stable-pull").exists());+ }++ /// A stand-in Lume that finds VMs the way Lume does: the default+ /// location in `$XDG_CONFIG_HOME/lume/config.yaml`, else `stable_dir`.+ /// Named `lume` (the bundled one, Stable's; 0.6.0 and newer), it ignores+ /// `LUME_HOME` for VMs; named `lume-local` it follows it (#5804).+ #[cfg(unix)]+ fn fake_lume_named(name: &str, dir: &std::path::Path, stable_dir: &std::path::Path) -> PathBuf {+ use std::os::unix::fs::PermissionsExt;+ let follows_lume_home = name == CuaChannel::Local.lume_bin_name();+ let bin = dir.join(name);+ std::fs::write(+ &bin,+ format!(+ "#!/bin/sh\n\+ vms='{stable}'\n\+ cfg=\"${{XDG_CONFIG_HOME:+$XDG_CONFIG_HOME/lume/config.yaml}}\"\n\+ if [ -n \"$cfg\" ] && [ -f \"$cfg\" ]; then\n\+ vms=$(sed -n 's/^ *path: *\"\\(.*\\)\"$/\\1/p' \"$cfg\" | head -n 1)\n\+ fi\n\+ {home_rule}\+ sub=\"$1\"; shift\n\+ case \"$sub\" in\n\+ get) [ -f \"$vms/$1/config.json\" ] || {{ echo \"Error: Virtual machine not found: $1\"; exit 1; }}\n\+ echo \"[{{\\\"name\\\":\\\"$1\\\",\\\"status\\\":\\\"stopped\\\"}}]\" ;;\n\+ pull) mkdir -p \"$vms/$2\" && echo '{{}}' > \"$vms/$2/config.json\" ;;\n\+ run) [ -f \"$vms/$1/config.json\" ] || {{ echo \"Error: Virtual machine not found: $1\" >&2; exit 1; }}\n\+ touch \"$vms/$1/ran\" ;;\n\+ ssh) if [ \"$1\" = --timeout ]; then shift 2; fi\n\+ [ -f \"$vms/$1/config.json\" ] || {{ echo \"Error: VM '$1' not found\"; exit 1; }}\n\+ /bin/sh -c \"$2\" 2>&1; rc=$?; echo; exit $rc ;;\n\+ *) exit 64 ;;\n\+ esac\n",+ stable = stable_dir.display(),+ home_rule = if follows_lume_home {+ "[ -n \"$LUME_HOME\" ] && vms=\"$LUME_HOME\"\n"+ } else {+ ""+ }+ ),+ )+ .unwrap();+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();+ bin+ }++ /// A Lume named `lume-local` (an installed one, which Local prefers)+ /// follows `LUME_HOME`; the same environment keeps it in Local's+ /// directory too (#5804).+ #[cfg(unix)]+ #[tokio::test]+ async fn a_lume_local_named_binary_stays_in_local_s_vm_directory() {+ let t = tempfile::tempdir().unwrap();+ let stable_dir = t.path().join(".lume");+ let local_dir = t.path().join(".lume-local");+ for (dir, vm) in [(&stable_dir, "stable-vm"), (&local_dir, "local-vm")] {+ std::fs::create_dir_all(dir.join(vm)).unwrap();+ std::fs::write(dir.join(vm).join("config.json"), "{}").unwrap();+ }+ let bin = fake_lume_named(CuaChannel::Local.lume_bin_name(), t.path(), &stable_dir);+ let local = LumeCmd::with_vm_dir(+ CuaChannel::Local,+ &t.path().join("cua-root"),+ &bin,+ &local_dir,+ )+ .unwrap();+ assert_eq!(+ cli_status(&local, "local-vm").await.unwrap(),+ Status::Stopped+ );+ assert!(matches!(+ cli_status(&local, "stable-vm").await,+ Err(VmmError::NotFound(_))+ ));+ // Without the environment it would use Stable's, as a `lume` does.+ let bare = LumeCmd::plain(&bin);+ assert_eq!(+ cli_status(&bare, "stable-vm").await.unwrap(),+ Status::Stopped+ );+ }++ /// Both channels' VM directories hold a VM. Every Lume CLI path (`get`,+ /// `pull`, `run`, `ssh` as a guest command prefix and as `LumeSshExec`,+ /// and the `serve` command) sees only its own channel's, even though+ /// the Lume ignores `LUME_HOME` for VMs.+ #[cfg(unix)]+ #[tokio::test]+ async fn every_lume_cli_path_stays_in_its_own_channel_s_vm_directory() {+ use crate::exec::ExecRequest;+ let t = tempfile::tempdir().unwrap();+ let stable_dir = t.path().join(".lume");+ let local_dir = t.path().join(".lume-local");+ for (dir, vm) in [(&stable_dir, "stable-vm"), (&local_dir, "local-vm")] {+ std::fs::create_dir_all(dir.join(vm)).unwrap();+ std::fs::write(dir.join(vm).join("config.json"), "{}").unwrap();+ }+ let bin = fake_lume_named("lume", t.path(), &stable_dir);+ let root = t.path().join("cua-root");+ let stable = LumeCmd::with_vm_dir(CuaChannel::Stable, &root, &bin, &stable_dir).unwrap();+ let local = LumeCmd::with_vm_dir(CuaChannel::Local, &root, &bin, &local_dir).unwrap();+ let timeout = Duration::from_secs(20);+ let own = [+ (&stable, "stable-vm", "local-vm"),+ (&local, "local-vm", "stable-vm"),+ ];++ // The stand-in does what Lume does without the environment: Local+ // would land in Stable's directory.+ let bare = LumeCmd::plain(&bin);+ assert_eq!(+ cli_status(&bare, "stable-vm").await.unwrap(),+ Status::Stopped+ );+ assert!(matches!(+ cli_status(&bare, "local-vm").await,+ Err(VmmError::NotFound(_))+ ));+ // The contract (#5804): a Lume named `lume` takes `LUME_HOME` for+ // its release-channel file only, so `LUME_HOME` alone does not move+ // its VMs. The config under `XDG_CONFIG_HOME` is what does.+ let only_home = std::process::Command::new(&bin)+ .args(["get", "local-vm", "--format", "json"])+ .env("LUME_HOME", &local_dir)+ .output()+ .unwrap();+ assert!(+ !only_home.status.success(),+ "LUME_HOME alone isolated a `lume`"+ );+ assert!(local.env().iter().any(|(k, _)| *k == "XDG_CONFIG_HOME"));++ for (lume, mine, other) in own {+ // `lume get`+ assert_eq!(cli_status(lume, mine).await.unwrap(), Status::Stopped);+ assert!(matches!(+ cli_status(lume, other).await,+ Err(VmmError::NotFound(_))+ ));+ // `lume run`+ cli_run(lume, &["run".into(), mine.into()]).await.unwrap();+ assert!(cli_run(lume, &["run".into(), other.into()]).await.is_err());+ // `lume ssh` as a guest command prefix (hostname, environment)+ let out = lume_ssh_prefix(lume, mine)+ .exec(ExecRequest::sh("echo hi").timeout(timeout))+ .await+ .unwrap();+ assert_eq!((out.exit_code, out.stdout_str().trim()), (0, "hi"));+ let out = lume_ssh_prefix(lume, other)+ .exec(ExecRequest::sh("echo hi").timeout(timeout))+ .await+ .unwrap();+ assert_eq!(out.exit_code, 1);+ assert!(out.stdout_str().contains("not found"));+ // `lume ssh` as `LumeSshExec` (guest exec)+ let ssh = LumeSshExec::from_lume(lume, mine);+ let out = ssh+ .exec(ExecRequest::sh("echo hi").timeout(timeout))+ .await+ .unwrap();+ assert_eq!((out.exit_code, out.stdout_str().trim()), (0, "hi"));+ let ssh = LumeSshExec::from_lume(lume, other);+ let out = ssh+ .exec(ExecRequest::sh("echo hi").timeout(timeout))+ .await+ .unwrap();+ assert_eq!(out.exit_code, 1);+ // the command `serve` is started from (and `lume attach` is+ // handed to another process as)+ let mut cmd = lume.tokio_command();+ let got = cmd.args(["get", other]).output().await.unwrap();+ assert!(!got.status.success());+ let argv = lume.argv(["get", mine]);+ let got = tokio::process::Command::new(&argv[0])+ .args(&argv[1..])+ .output()+ .await+ .unwrap();+ assert!(got.status.success(), "{argv:?}");+ }++ // `lume pull` makes a base in its own directory, and only there.+ let creds = RegistryCredentials::new("me", "s3cret");+ for (lume, dir, elsewhere, base) in [+ (&stable, &stable_dir, &local_dir, "stable-base"),+ (&local, &local_dir, &stable_dir, "local-base"),+ ] {+ cli_pull(lume, "ghcr.io/me/img:1", base, &creds, timeout)+ .await+ .unwrap();+ assert!(dir.join(base).join("config.json").is_file(), "{base}");+ assert!(!elsewhere.join(base).exists(), "{base} leaked");+ }+ // Each `run` only touched its own VM.+ assert!(stable_dir.join("stable-vm/ran").exists());+ assert!(local_dir.join("local-vm/ran").exists());+ assert!(!stable_dir.join("local-vm").exists() && !local_dir.join("stable-vm").exists());+ }+/// A killed serve's half-made pull is removed; a pull still being/// written, and anything not Lume's, stays.#[test]@@ -2279,7 +2717,10 @@ mod tests {).unwrap();std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();- assert_eq!(cli_status(&bin, "cua-box").await.unwrap(), Status::Stopped);+ assert_eq!(+ cli_status(&LumeCmd::plain(&bin), "cua-box").await.unwrap(),+ Status::Stopped+ );}#[test]@@ -2951,7 +3392,7 @@ mod tests {std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();let creds = RegistryCredentials::new("me", "s3cret");cli_pull(- &bin,+ &LumeCmd::plain(&bin),"ghcr.io/me/img:1","base",&creds,@@ -2970,7 +3411,7 @@ mod tests {]);let err = cli_pull(- &bin,+ &LumeCmd::plain(&bin),"ghcr.io/me/fail:1","base",&creds,diff --git a/libs/cua/crates/cua-vmm/src/lume/ssh.rs b/libs/cua/crates/cua-vmm/src/lume/ssh.rsindex 65923d62e4..34afc75c5b 100644--- a/libs/cua/crates/cua-vmm/src/lume/ssh.rs+++ b/libs/cua/crates/cua-vmm/src/lume/ssh.rs@@ -21,14 +21,28 @@ use crate::exec::{ExecChunk, ExecOutput, ExecRequest, GuestExec, shell_quote};pub struct LumeSshExec {/// The `lume` binary.pub program: String,+ /// Arguments before `lume`'s own: `lume`'s environment, when it needs+ /// one, through `env` ([`super::LumeCmd::wrapped`]).+ pub prefix: Vec<String>,/// VM name.pub vm: String,}impl LumeSshExec {+ /// `lume ssh` run as `lume` runs it: for the channel's own VM directory.+ pub fn from_lume(lume: &super::LumeCmd, vm: impl Into<String>) -> Self {+ let (program, prefix) = lume.wrapped();+ Self {+ program,+ prefix,+ vm: vm.into(),+ }+ }+pub fn new(program: impl Into<String>, vm: impl Into<String>) -> Self {Self {program: program.into(),+ prefix: Vec::new(),vm: vm.into(),}}@@ -170,7 +184,12 @@ impl GuestExec for LumeSshExec {});}let nonce = nonce();- let argv = self.argv(&req, &nonce);+ let argv: Vec<String> = self+ .prefix+ .iter()+ .cloned()+ .chain(self.argv(&req, &nonce))+ .collect();let (raw_tx, mut raw_rx) = mpsc::channel::<ExecChunk>(64);let program = self.program.clone();let timeout = req.timeout;diff --git a/libs/cua/crates/cua-vmm/src/storage.rs b/libs/cua/crates/cua-vmm/src/storage.rsindex c88be3a669..4a3c5b8534 100644--- a/libs/cua/crates/cua-vmm/src/storage.rs+++ b/libs/cua/crates/cua-vmm/src/storage.rs@@ -13,6 +13,8 @@ use std::time::Duration;use serde::{Deserialize, Serialize};+use cua_home::channel::CuaChannel;+use crate::container::engine::{self, EngineKind};use crate::host;@@ -38,15 +40,70 @@ pub fn host_volume(path: &Path) -> Option<Volume> {})}-/// Lume's default VM storage directory (`~/.config/lume/config.yaml`,-/// else `~/.lume`): where a macOS Space's clone is written.+/// The variable Lume reads its home and VM directory from. Spaces Local+/// follows it and sets it for the Lume it starts ([`crate::lume::LumeCmd`]).+/// Stable ignores it: the Lume it runs (the pinned 0.6.0, and any before+/// the one that honours it) keeps VMs where its `config.yaml` says, so+/// Spaces must look there too.+pub const LUME_HOME_VAR: &str = "LUME_HOME";++/// `$LUME_HOME`, when set and not blank.+pub fn lume_home_env() -> Option<String> {+ std::env::var(LUME_HOME_VAR)+ .ok()+ .filter(|v| !v.trim().is_empty())+}++/// Lume's default VM storage directory for this process's channel: where a+/// macOS Space's clone is written.+///+/// * Stable (unchanged): the default location in+/// `~/.config/lume/config.yaml`, else `~/.lume`;+/// * Local: `$LUME_HOME` when set, else `~/.lume-local`+/// ([`CuaChannel::lume_dir`]); never Stable's `~/.config/lume/config.yaml`.pub fn lume_dir() -> PathBuf {+ lume_dir_for(CuaChannel::current())+}++/// [`lume_dir`] for `channel`.+pub fn lume_dir_for(channel: CuaChannel) -> PathBuf {let home = host::home_dir();- std::fs::read_to_string(home.join(".config/lume/config.yaml"))- .ok()- .and_then(|y| lume_default_location(&y))- .map(|p| expand_home(&p, &home))- .unwrap_or_else(|| home.join(".lume"))+ let yaml = std::fs::read_to_string(home.join(".config/lume/config.yaml")).ok();+ lume_dir_with(channel, &home, lume_home_env().as_deref(), yaml.as_deref())+}++/// [`lume_dir`] for `channel`, with its inputs given (`$LUME_HOME`, and the+/// text of Lume's `config.yaml` when there is one).+pub fn lume_dir_with(+ channel: CuaChannel,+ home: &Path,+ lume_home: Option<&str>,+ config_yaml: Option<&str>,+) -> PathBuf {+ if channel.is_local() {+ return default_lume_dir(channel, home, lume_home);+ }+ config_yaml+ .and_then(lume_default_location)+ .map(|p| expand_home(&p, home))+ .unwrap_or_else(|| default_lume_dir(channel, home, None))+}++/// The VM directory `channel`'s Lume uses before its `config.yaml` is+/// consulted: for Local `lume_home` (a leading `~` is `home`), else+/// `~/.lume-local`; for Stable always `~/.lume`, whatever `lume_home` says+/// ([`LUME_HOME_VAR`]). The names come from [`CuaChannel::lume_dir`].+pub fn default_lume_dir(channel: CuaChannel, home: &Path, lume_home: Option<&str>) -> PathBuf {+ if channel.is_local()+ && let Some(h) = lume_home.map(str::trim).filter(|h| !h.is_empty())+ {+ return expand_home(h, home);+ }+ let dir = channel.lume_dir();+ match dir.file_name() {+ Some(name) => home.join(name),+ None => dir,+ }}/// The cua home: QEMU instances (`vmm/qemu`) and the containerDisk cache@@ -65,7 +122,23 @@ fn expand_home(p: &str, home: &Path) -> PathBuf {/// The path of Lume's `defaultLocationName` in its `config.yaml`.pub fn lume_default_location(yaml: &str) -> Option<String> {- let unquote = |v: &str| v.trim().trim_matches('"').trim_matches('\'').to_string();+ // A double-quoted scalar is read with its escapes (`\\`, `\"`: what+ // `builtin::config_yaml` writes, and what Lume's parser reads); a+ // single-quoted one with `''` for a quote; anything else as it is.+ let unquote = |v: &str| {+ let v = v.trim();+ if v.len() >= 2+ && v.starts_with('"')+ && v.ends_with('"')+ && let Ok(s) = serde_json::from_str::<String>(v)+ {+ return s;+ }+ if v.len() >= 2 && v.starts_with('\'') && v.ends_with('\'') {+ return v[1..v.len() - 1].replace("''", "'");+ }+ v.trim_matches('"').trim_matches('\'').to_string()+ };let default = yaml.lines().find_map(|l| l.trim().strip_prefix("defaultLocationName:"))@@ -267,6 +340,80 @@ mod platform {mod tests {use super::*;+ #[test]+ fn stable_keeps_lume_s_own_vm_directory_rules() {+ let home = Path::new("/Users/a");+ let ext = "defaultLocationName: \"ext\"\nvmLocations:\n - name: \"ext\"\n path: \"/Volumes/X/lume\"\n";+ assert_eq!(+ lume_dir_with(CuaChannel::Stable, home, None, None),+ PathBuf::from("/Users/a/.lume")+ );+ assert_eq!(+ lume_dir_with(CuaChannel::Stable, home, None, Some(ext)),+ PathBuf::from("/Volumes/X/lume")+ );+ // A blank LUME_HOME says nothing.+ assert_eq!(+ lume_dir_with(CuaChannel::Stable, home, Some(" "), Some(ext)),+ PathBuf::from("/Volumes/X/lume")+ );+ }++ #[test]+ fn local_keeps_its_vms_apart_from_stable_s() {+ let home = Path::new("/Users/a");+ // Stable's config.yaml is not Local's to read.+ let ext = "defaultLocationName: \"ext\"\nvmLocations:\n - name: \"ext\"\n path: \"/Volumes/X/lume\"\n";+ assert_eq!(+ lume_dir_with(CuaChannel::Local, home, None, Some(ext)),+ PathBuf::from("/Users/a/.lume-local")+ );+ assert_eq!(+ lume_dir_with(CuaChannel::Local, home, None, None),+ PathBuf::from("/Users/a/.lume-local")+ );+ // The names come from the channel.+ assert_eq!(+ CuaChannel::Local.lume_dir().file_name(),+ Some(std::ffi::OsStr::new(".lume-local"))+ );+ assert_ne!(+ lume_dir_with(CuaChannel::Local, home, None, None),+ lume_dir_with(CuaChannel::Stable, home, None, None)+ );+ }++ #[test]+ fn lume_home_moves_local_s_directory_and_never_stable_s() {+ let home = Path::new("/Users/a");+ let cfg = Some(+ "defaultLocationName: \"h\"\nvmLocations:\n - name: \"h\"\n path: \"/Volumes/X/lume\"\n",+ );+ // Local follows it.+ assert_eq!(+ lume_dir_with(CuaChannel::Local, home, Some("/Volumes/X/vms"), cfg),+ PathBuf::from("/Volumes/X/vms")+ );+ assert_eq!(+ lume_dir_with(CuaChannel::Local, home, Some("~/vms"), None),+ PathBuf::from("/Users/a/vms")+ );+ // Stable does not: the pinned Lume keeps VMs where its config says,+ // so that is where Spaces must look.+ assert_eq!(+ lume_dir_with(CuaChannel::Stable, home, Some("/Volumes/X/vms"), cfg),+ PathBuf::from("/Volumes/X/lume")+ );+ assert_eq!(+ lume_dir_with(CuaChannel::Stable, home, Some("/Volumes/X/vms"), None),+ PathBuf::from("/Users/a/.lume")+ );+ assert_eq!(+ default_lume_dir(CuaChannel::Stable, home, Some("/Volumes/X/vms")),+ PathBuf::from("/Users/a/.lume")+ );+ }+#[test]fn lume_default_location_follows_the_config() {let yaml = r#"diff --git a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rsindex d5604f47da..eb9d1a542d 100644--- a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs+++ b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs@@ -289,6 +289,7 @@ pub async fn serve(state: Arc<Mutex<FakeLume>>) -> String {pub fn runtime(url: String) -> LumeRuntime {let home = temp_home();LumeRuntime::new(LumeConfig {+ channel: cua_home::channel::CuaChannel::Stable,url,spawn_serve: false,allow_install: false,diff --git a/libs/cua/crates/cua-volume/src/service.rs b/libs/cua/crates/cua-volume/src/service.rsindex 3f56d9c1ff..5ddf987a47 100644--- a/libs/cua/crates/cua-volume/src/service.rs+++ b/libs/cua/crates/cua-volume/src/service.rs@@ -15,11 +15,18 @@//! | macOS | `nfs` | a localhost NFSv3 server, mounted with the system's `mount_nfs` (feature `nfs`) |//! | Linux | `fuse` | FUSE through `/dev/fuse` and `fusermount3` (feature `fuse`) |//! | other | none | reported as `unsupported` |+//!+//! The volume is mounted on `~/Cua Volume` (macOS) or `~/cua-volume`+//! (elsewhere), named "Cua Volume". A Cua Spaces Local build+//! ([`cua_home::channel::CuaChannel::Local`]) uses `~/Cua Volume Local` and+//! "Cua Volume Local" instead, so it never shares a folder with the Stable+//! app on the same Mac. `CUA_DRIVE_MOUNT_PATH` moves either.use std::path::{Path, PathBuf};use std::sync::Arc;use std::time::Duration;+use cua_home::channel::CuaChannel;use serde::{Deserialize, Serialize};use crate::backend::{Backend, Condition};@@ -29,8 +36,8 @@ use crate::feed::{DeviceId, Feed, SyncEvent, SyncStatus};use crate::vfs::Vfs;use crate::{Context, Drive, Error, Result, new_id};-/// The Finder volume's name.-pub const VOLUME_NAME: &str = "Cua Volume";+/// The environment variable that overrides where the volume mounts.+pub const MOUNT_PATH_VAR: &str = "CUA_DRIVE_MOUNT_PATH";/// Where S3 keys are kept (never in `config.json`).pub trait KeyStore: Send + Sync {@@ -207,6 +214,9 @@ pub struct DriveService {vfs: Arc<Vfs>,mount: tokio::sync::Mutex<MountState>,settings: std::sync::Mutex<MountSettings>,+ /// Which Cua Spaces build this is: it names the volume and where it+ /// mounts by default (Stable `~/Cua Volume`, Local `~/Cua Volume Local`).+ channel: CuaChannel,}impl std::fmt::Debug for DriveService {@@ -236,9 +246,52 @@ pub fn mount_method() -> &'static str {}}+/// Where the volume mounts: `env_path` (`CUA_DRIVE_MOUNT_PATH`) when set,+/// else the user's saved `saved` path, else the channel's default under+/// `user_home` (see [`default_mount_path`]).+fn resolve_mount_path(+ env_path: Option<&std::ffi::OsStr>,+ saved: Option<&Path>,+ channel: CuaChannel,+ user_home: &Path,+ macos: bool,+) -> PathBuf {+ if let Some(p) = env_path.filter(|p| !p.is_empty()) {+ return PathBuf::from(p);+ }+ if let Some(p) = saved {+ return p.to_path_buf();+ }+ default_mount_path(channel, user_home, macos)+}++/// The default mount folder under `user_home`: the channel's volume name on+/// macOS (`Cua Volume`, `Cua Volume Local`), that name in lower case with+/// dashes elsewhere (`cua-volume`, `cua-volume-local`).+fn default_mount_path(channel: CuaChannel, user_home: &Path, macos: bool) -> PathBuf {+ if macos {+ user_home.join(channel.volume_name())+ } else {+ user_home.join(channel.volume_name().to_lowercase().replace(' ', "-"))+ }+}+impl DriveService {- /// The service for `drive` (whose state lives in `<home>/volume`).+ /// The service for `drive` (whose state lives in `<home>/volume`), for+ /// the channel of this process ([`CuaChannel::current`]).pub fn new(drive: Drive, home: &Path, keys: Arc<dyn KeyStore>) -> Result<Arc<DriveService>> {+ Self::new_for_channel(drive, home, keys, CuaChannel::current())+ }++ /// [`DriveService::new`] for an explicit channel: Local names the volume+ /// "Cua Volume Local" and mounts it on `~/Cua Volume Local`, so it never+ /// touches the Stable volume's folder.+ pub fn new_for_channel(+ drive: Drive,+ home: &Path,+ keys: Arc<dyn KeyStore>,+ channel: CuaChannel,+ ) -> Result<Arc<DriveService>> {let state = state_dir(home);std::fs::create_dir_all(&state)?;let settings: MountSettings = std::fs::read(settings_path(home))@@ -269,6 +322,7 @@ impl DriveService {error: None,}),settings: std::sync::Mutex::new(settings),+ channel,}))}@@ -471,24 +525,22 @@ impl DriveService {// -- Mount ---------------------------------------------------------fn mount_path(&self) -> PathBuf {- if let Some(p) = std::env::var_os("CUA_DRIVE_MOUNT_PATH").filter(|p| !p.is_empty()) {- return PathBuf::from(p);- }- if let Some(p) = self.settings.lock().unwrap().path.clone() {- return p;- }let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));- if cfg!(target_os = "macos") {- home.join(VOLUME_NAME)- } else {- home.join("cua-volume")- }+ resolve_mount_path(+ std::env::var_os(MOUNT_PATH_VAR).as_deref(),+ self.settings.lock().unwrap().path.as_deref(),+ self.channel,+ &home,+ cfg!(target_os = "macos"),+ )}- /// Where the volume mounts (`None`: the default, `~/Cua Volume` on- /// macOS, `~/cua-volume` elsewhere). Takes effect on the next mount.+ /// Where the volume mounts (`None`: the channel's default, `~/Cua Volume`+ /// on macOS and `~/cua-volume` elsewhere for Stable; `~/Cua Volume Local`+ /// and `~/cua-volume-local` for Local). `CUA_DRIVE_MOUNT_PATH` still+ /// overrides both. Takes effect on the next mount.pub fn set_mount_path(&self, path: Option<PathBuf>) -> Result<()> {self.settings.lock().unwrap().path = path;self.save_settings()@@ -516,7 +568,7 @@ impl DriveService {state: state.into(),method: method.into(),path,- volume_name: VOLUME_NAME.into(),+ volume_name: self.channel.volume_name().into(),detail,settings_url: None,}@@ -874,6 +926,103 @@ mod tests {assert_eq!(m.volume_name, "Cua Volume");}+ #[test]+ fn the_default_mount_folder_follows_the_channel() {+ let home = Path::new("/Users/ada");+ // Stable is what it always was.+ assert_eq!(+ default_mount_path(CuaChannel::Stable, home, true),+ home.join("Cua Volume")+ );+ assert_eq!(+ default_mount_path(CuaChannel::Stable, home, false),+ home.join("cua-volume")+ );+ // Local has its own folder beside it, on every platform.+ assert_eq!(+ default_mount_path(CuaChannel::Local, home, true),+ home.join("Cua Volume Local")+ );+ assert_eq!(+ default_mount_path(CuaChannel::Local, home, false),+ home.join("cua-volume-local")+ );+ for macos in [true, false] {+ let stable = default_mount_path(CuaChannel::Stable, home, macos);+ let local = default_mount_path(CuaChannel::Local, home, macos);+ assert_ne!(stable, local);+ assert!(!local.starts_with(&stable) && !stable.starts_with(&local));+ }+ // On macOS the channel's own mount path is this default.+ if let Some(user_home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {+ for c in CuaChannel::ALL {+ assert_eq!(+ default_mount_path(c, Path::new(&user_home), true),+ c.volume_mount_path()+ );+ }+ }+ }++ #[test]+ fn the_mount_path_override_beats_a_saved_path_and_the_channel() {+ use std::ffi::OsStr;+ let home = Path::new("/Users/ada");+ let saved = Path::new("/Volumes/Big/Cua");+ for c in CuaChannel::ALL {+ // CUA_DRIVE_MOUNT_PATH wins over everything, for both channels.+ assert_eq!(+ resolve_mount_path(Some(OsStr::new("/mnt/x")), Some(saved), c, home, true),+ Path::new("/mnt/x")+ );+ // Then the path saved in the app's settings.+ assert_eq!(resolve_mount_path(None, Some(saved), c, home, true), saved);+ // An empty override is no override.+ assert_eq!(+ resolve_mount_path(Some(OsStr::new("")), None, c, home, true),+ default_mount_path(c, home, true)+ );+ assert_eq!(+ resolve_mount_path(None, None, c, home, true),+ default_mount_path(c, home, true)+ );+ }+ }++ #[tokio::test]+ async fn each_channel_names_and_mounts_its_own_volume() {+ // The default mount of this process, unless the environment moves it.+ let moved = std::env::var_os(MOUNT_PATH_VAR).is_some_and(|p| !p.is_empty());+ let user_home = std::env::var_os("HOME")+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from("."));+ for (channel, name) in [+ (CuaChannel::Stable, "Cua Volume"),+ (CuaChannel::Local, "Cua Volume Local"),+ ] {+ let home = tempfile::tempdir().unwrap();+ let drive = Drive::open_local(home.path());+ let svc = DriveService::new_for_channel(drive, home.path(), Arc::new(EnvKeys), channel)+ .unwrap();+ assert_eq!(svc.mount_status().await.volume_name, name);+ if !moved {+ assert_eq!(+ svc.mount_path(),+ default_mount_path(channel, &user_home, cfg!(target_os = "macos"))+ );+ // A path the user chose still wins.+ let chosen = home.path().join("elsewhere");+ svc.set_mount_path(Some(chosen.clone())).unwrap();+ assert_eq!(svc.mount_path(), chosen);+ svc.set_mount_path(None).unwrap();+ assert_eq!(+ svc.mount_path(),+ default_mount_path(channel, &user_home, cfg!(target_os = "macos"))+ );+ }+ }+ }+/// Opt-in (CUA_DRIVE_NFS_TEST=1, macOS): mounts through the service,/// uses the volume like any program, unmounts.#[cfg(all(feature = "nfs", target_os = "macos"))]@@ -885,7 +1034,7 @@ mod tests {}let base = PathBuf::from(std::env::var("CUA_DRIVE_TEST_DIR").expect("CUA_DRIVE_TEST_DIR"));let home = base.join(format!("svc-{}", new_id()));- let mnt = home.join("mnt").join(VOLUME_NAME);+ let mnt = home.join("mnt").join(CuaChannel::Stable.volume_name());let drive = Drive::open_local(&home);let svc = DriveService::new(drive.clone(), &home, Arc::new(EnvKeys)).unwrap();svc.set_mount_path(Some(mnt.clone())).unwrap();diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.ktindex d63332835a..7690021728 100644--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt@@ -3147,7 +3147,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_func_telemetry_use_app_notice() != 17365.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}- if (lib.uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 62628.toShort()) {+ if (lib.uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 53713.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cua_sdk_checksum_method_agentsetup_detect() != 59369.toShort()) {@@ -5542,7 +5542,8 @@ public interface AgentSetupInterface {/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/suspend fun `configureMcp`(`agents`: List<kotlin.String>, `server`: AgentMcpServer?): List<AgentSetupOutcome>@@ -5712,7 +5713,8 @@ open class AgentSetup: Disposable, AutoCloseable, AgentSetupInterface/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/@Throws(CuaException::class)@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.pyindex fc3dbdd230..81caa5ff94 100644--- a/libs/cua/python/src/cua/_native.py+++ b/libs/cua/python/src/cua/_native.py@@ -607,7 +607,7 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_agentrun_wait() != 14426:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")- if lib.uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 62628:+ if lib.uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 53713:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_agentsetup_detect() != 59369:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")@@ -28191,7 +28191,8 @@ class AgentSetupProtocol(typing.Protocol):async def configure_mcp(self, agents: typing.List[str],server: typing.Optional[AgentMcpServer]) -> typing.List[AgentSetupOutcome]:"""Configures the MCP server (default: `cua mcp`, `cua` resolved on- PATH) for `agents`.+ PATH; `cua-local mcp` named `cua-local` for the Local app) for+ `agents`. A server without a name gets the channel's."""raise NotImplementedErrordef detect(self, ) -> typing.List[AgentInfo]:@@ -28293,7 +28294,8 @@ class AgentSetup(AgentSetupProtocol):async def configure_mcp(self, agents: typing.List[str],server: typing.Optional[AgentMcpServer]) -> typing.List[AgentSetupOutcome]:"""Configures the MCP server (default: `cua mcp`, `cua` resolved on- PATH) for `agents`.+ PATH; `cua-local mcp` named `cua-local` for the Local app) for+ `agents`. A server without a name gets the channel's."""_UniffiFfiConverterSequenceString.check_lower(agents)diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swiftindex 0c3fdaeda8..588743adb7 100644--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift@@ -980,7 +980,8 @@ public protocol AgentSetupProtocol: AnyObject, Sendable {/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/func configureMcp(agents: [String], server: AgentMcpServer?) async throws -> [AgentSetupOutcome]@@ -1104,7 +1105,8 @@ open class AgentSetup: AgentSetupProtocol, @unchecked Sendable {/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/open func configureMcp(agents: [String], server: AgentMcpServer?)async throws -> [AgentSetupOutcome] {return@@ -48225,7 +48227,7 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_func_telemetry_use_app_notice() != 17365) {return InitializationResult.apiChecksumMismatch}- if (uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 62628) {+ if (uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 53713) {return InitializationResult.apiChecksumMismatch}if (uniffi_cua_sdk_checksum_method_agentsetup_detect() != 59369) {diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.tsindex e8a56ecfd7..bf83c42cb7 100644--- a/libs/cua/typescript/src/native/cua_sdk.ts+++ b/libs/cua/typescript/src/native/cua_sdk.ts@@ -24325,7 +24325,8 @@ export interface AgentSetupLike {/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/configureMcp(agents: Array<string>, server: AgentMcpServer | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<AgentSetupOutcome>>;/**@@ -24405,7 +24406,8 @@ private constructor(pointer: UniffiHandle) {/*** Configures the MCP server (default: `cua mcp`, `cua` resolved on- * PATH) for `agents`.+ * PATH; `cua-local mcp` named `cua-local` for the Local app) for+ * `agents`. A server without a name gets the channel's.*/async configureMcp(agents: Array<string>, server: AgentMcpServer | undefined, asyncOpts_?: { signal: AbortSignal }): Promise<Array<AgentSetupOutcome>> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;@@ -44125,7 +44127,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_agentrun_wait() !== 14426) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentrun_wait");}- if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() !== 62628) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() !== 53713) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp");}if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_detect() !== 59369) {diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swiftindex 00715bc88a..2a2c2dd6cc 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift@@ -7160,7 +7160,8 @@ public struct AppCliInstallPlan: Equatable, Hashable {*/public var bundledVersion: String?/**- * Another `cua` found earlier on PATH (it would shadow `target`).+ * Another CLI of the same name found earlier on PATH (it would shadow+ * `target`).*/public var shadowedBy: String?/**@@ -7176,9 +7177,10 @@ public struct AppCliInstallPlan: Equatable, Hashable {*/public var pathLine: String?/**- * A working `cua` CLI already on this machine: `target`, else the- * first in the usual install folders or on PATH (a Finder-launched+ * A working CLI of this channel already on this machine: `target`, else+ * the first in the usual install folders or on PATH (a Finder-launched* app's PATH lacks `~/.local/bin`, so the folders are searched too).+ * Local looks for `cua-local` only: a Stable `cua` is not its CLI.*/public var found: String?@@ -7210,7 +7212,8 @@ public struct AppCliInstallPlan: Equatable, Hashable {* `cua --version` of the bundled CLI.*/bundledVersion: String?,/**- * Another `cua` found earlier on PATH (it would shadow `target`).+ * Another CLI of the same name found earlier on PATH (it would shadow+ * `target`).*/shadowedBy: String?,/*** `bin_dir` is already on PATH.@@ -7222,9 +7225,10 @@ public struct AppCliInstallPlan: Equatable, Hashable {* The line that would be added to `path_profile`.*/pathLine: String?,/**- * A working `cua` CLI already on this machine: `target`, else the- * first in the usual install folders or on PATH (a Finder-launched+ * A working CLI of this channel already on this machine: `target`, else+ * the first in the usual install folders or on PATH (a Finder-launched* app's PATH lacks `~/.local/bin`, so the folders are searched too).+ * Local looks for `cua-local` only: a Stable `cua` is not its CLI.*/found: String?) {self.source = sourceself.target = targetdiff --git a/libs/spaces-app-swift/Sources/CuaSpacesTeleport/InstallCuaPrompt.swift b/libs/spaces-app-swift/Sources/CuaSpacesTeleport/InstallCuaPrompt.swiftindex a0747da1b1..52062c964b 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesTeleport/InstallCuaPrompt.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesTeleport/InstallCuaPrompt.swift@@ -14,8 +14,17 @@ import Foundationpublic struct InstallCuaPrompt: Equatable, Sendable {/// Where people install Cua (the CLI and the Cua app).public static let installURL = URL(string: "https://cua.ai/install")!- /// Opens the Keyvault page of an installed Cua app.- public static let openURL = URL(string: "cua://keyvault")!+ /// Opens the Keyvault page of an installed Cua app: `cua://keyvault`, or+ /// `cua-local://keyvault` from Cua Spaces Local, whose bundle stamps its+ /// scheme as `CuaUrlScheme` (the two apps answer to different schemes).+ public static var openURL: URL { openURL(info: Bundle.main.infoDictionary) }++ /// [`openURL`] for the Info.plist `info`: its `CuaUrlScheme`, else `cua`.+ public static func openURL(info: [String: Any]?) -> URL {+ let scheme = ((info?["CuaUrlScheme"] as? String) ?? "")+ .trimmingCharacters(in: .whitespaces).lowercased()+ return URL(string: "\(scheme.isEmpty ? "cua" : scheme)://keyvault") ?? URL(string: "cua://keyvault")!+ }/// Cua is installed but not running (open it instead of installing).public let installed: Booldiff --git a/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swift b/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swiftindex 507f101bbb..d2c5a4a942 100644--- a/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swift+++ b/libs/spaces-app-swift/Tests/CuaSpacesTeleportTests/TeleportPickerTests.swift@@ -118,6 +118,16 @@ let safari = fixtureEntry("com.apple.Safari", "Safari", .unsupported, moves: [],#expect(InstallCuaPrompt.detect(CuaSDK.CuaError.TeleportRefused(message: "denied")) == nil)}+ /// Cua Spaces Local stamps its scheme: "Open Cua" opens its own Keyvault+ /// page, never the released app's.+ @Test func openCuaFollowsTheBundlesScheme() {+ #expect(InstallCuaPrompt.openURL(info: nil) == URL(string: "cua://keyvault"))+ #expect(InstallCuaPrompt.openURL(info: ["CuaUrlScheme": ""]) == URL(string: "cua://keyvault"))+ #expect(InstallCuaPrompt.openURL(info: ["CuaUrlScheme": "cua-local"]) == URL(string: "cua-local://keyvault"))+ // The test bundle is no Local build.+ #expect(InstallCuaPrompt.openURL == URL(string: "cua://keyvault"))+ }+@Test func pickOptionsConsentRunDone() async throws {let host = FakeTeleportHost(entries: [firefox, vscode, safari])let m = TeleportPickerModel(host: host, spaceName: "Dev")diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lockindex 6058efe692..721f7176a5 100644--- a/tests/e2e/cua-sdk/rust/Cargo.lock+++ b/tests/e2e/cua-sdk/rust/Cargo.lock@@ -1305,6 +1305,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lockindex 59e67261e2..ca6e95d8f2 100644--- a/tests/e2e/local-runtimes/Cargo.lock+++ b/tests/e2e/local-runtimes/Cargo.lock@@ -1132,6 +1132,7 @@ name = "cua-agent-setup"version = "0.8.0"dependencies = ["chrono",+ "cua-home","hex","include_dir","jsonc-parser",