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
bin/ci: run on Windows (Git for Windows' bash, never WSL's) (#6719)
ddupont3d05b19523fb
diff --git a/apps/cua-spaces-desktop/.gitignore b/apps/cua-spaces-desktop/.gitignoreindex 57aee96bb1..773eec9e45 100644--- a/apps/cua-spaces-desktop/.gitignore+++ b/apps/cua-spaces-desktop/.gitignore@@ -6,3 +6,6 @@ release//native/# Synthetic H.264 streams (scripts/video/encode.sh)./scripts/video/.cache/+# Cua Spaces Local (scripts/install-local.ps1): the build output and the pinned pnpm it fetches.+/dist-local/+/.local-tools/diff --git a/apps/cua-spaces-desktop/README.md b/apps/cua-spaces-desktop/README.mdindex cb416ed15a..3d291820aa 100644--- a/apps/cua-spaces-desktop/README.md+++ b/apps/cua-spaces-desktop/README.md@@ -767,3 +767,57 @@ Swift app's files stay as they are.| `CUA_SPACES_TEST_STREAM_URL` | Answer every `spaces.openStream` with this URL (`{id}`, `{tier}` filled in), for the WebCodecs harness || `CUA_SPACES_TEST_PRESENCE=1` | Answer every `presence.join` with two synthetic participants circling the picture (screenshots, the WebCodecs harness) || `CUA_BIN`, `CUA_HOME` | Where to find `cua` and `~/.cua`. A `CUA_BIN` that doesn't exist means no cua (demo data) |++## Run a Local build next to the released app (Windows)++`scripts/install-local.ps1` builds this checkout and installs it as **Cua Spaces+Local**, beside a released Cua Spaces, so you can try a branch (a new UI, the+`windows:*` images) without touching the app you use. It is the Windows+counterpart of `apps/cua-spaces-macos/scripts/install-local.sh`, and unsigned.++```powershell+powershell -NoProfile -ExecutionPolicy Bypass -File scripts\install-local.ps1+powershell -File scripts\install-local.ps1 -NoLaunch # install without starting it+powershell -File scripts\install-local.ps1 -Release # build with the release Electron fuses+powershell -File scripts\install-local.ps1 -Prefix D:\apps # app in D:\apps\Programs\Cua Spaces Local+powershell -File scripts\install-local.ps1 -SkipRustBuild # use native\win32-<arch> as it is+powershell -File scripts\install-local.ps1 -SkipWebBuild # use apps\cua-spaces-web\dist as it is+powershell -File scripts\install-local.ps1 -NoIntegration # files only: no Start Menu, PATH or scheme+powershell -File scripts\uninstall-local.ps1 [-Purge] # remove it (-Purge also its state)+```++It first lists, in one message, everything the build needs that is missing:+Rust (rustup, MSVC) with the Visual Studio C++ Build Tools, CMake, Node 22 or+later, pnpm, and for the web UI the `wasm32` Rust target and `wasm-bindgen-cli`+(the versions the release build pins). Nothing is built before they are all+there. Builds run at BelowNormal priority (`-NormalPriority` opts out). On a+cold machine the Rust build takes a while.++| | Cua Spaces | Cua Spaces Local |+|---|---|---|+| App | `%LOCALAPPDATA%\Programs\cua-spaces` | `%LOCALAPPDATA%\Programs\Cua Spaces Local` (`Cua Spaces Local.exe`) |+| App id, AppUserModelID | `ai.cua.spaces.desktop` | `ai.cua.spaces.desktop.local` (own taskbar group and Run entry) |+| CLI | `cua` | `cua-local` (`...\Cua Spaces Local\bin`, added to the user PATH) |+| Cua home | `%USERPROFILE%\.cua` | `%USERPROFILE%\.cua-local` (the app sets `CUA_HOME`) |+| Channel, ports, sign-in | `CUA_CHANNEL=stable` | `CUA_CHANNEL=local`, set by the app (`CuaChannel::Local`) |+| Backend | production | staging (`CUA_ENV=prod` opts in) |+| User data | `%APPDATA%\Cua Spaces` | `%APPDATA%\Cua Spaces Local` |+| URL scheme | `cua://` | `cua-local://` |+| Updates | electron-updater feed | none (no `app-update.yml`) |++The shell knows it is Local from its executable name or `CUA_CHANNEL=local`+(`src/channel.ts`); the packaging is `packaging/electron-builder.local.cjs`+(`electron-builder --win dir`, no installer). The build is staged next to the+install and verified (`cua-local --version`, the native layer, the web UI, no+update feed) before the live copy is swapped, and the old copy is put back if the+swap fails. The script refuses a `-Prefix` that would put the app on, inside or+above anything the released Cua Spaces owns, and a folder at the Local path that+the installer did not make (it keeps a `.cua-spaces-local.json` marker there).+It stops only processes running from the Local folder.++`scripts/tests/install-local.tests.ps1` tests the path, refusal and PATH checks+and that the names match `src/channel.ts`, the builder config and+`CuaChannel::Local`; it builds nothing and touches no registry or PATH.++Not covered: the unattended-access host service (`cua host setup`) still+downloads the pinned `cua-spacesd`, which does not know the Local ports.diff --git a/apps/cua-spaces-desktop/packaging/electron-builder.local.cjs b/apps/cua-spaces-desktop/packaging/electron-builder.local.cjsnew file mode 100644index 0000000000..cc9caac06a--- /dev/null+++ b/apps/cua-spaces-desktop/packaging/electron-builder.local.cjs@@ -0,0 +1,39 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// electron-builder config for "Cua Spaces Local" (Windows): the release config+// with the Local names, no installer and no update feed. scripts/install-local.ps1+// builds with it (`electron-builder --win dir --config packaging/electron-builder.local.cjs`)+// and installs the unpacked app beside a released Cua Spaces: another app id+// (so another AppUserModelID, taskbar group and Run entry), another+// executable (`Cua Spaces Local.exe`, which is how src/channel.ts knows it is+// Local), another URL scheme (`cua-local://`), another output folder, and no+// `app-update.yml`, so electron-updater has nothing to check.+//+// The runtime half (CUA_CHANNEL=local, CUA_HOME=~/.cua-local, user data+// folder) is src/channel.ts's. Always unsigned.++const base = require("../electron-builder.config.cjs");++/** @type {import("electron-builder").Configuration} */+module.exports = {+ ...base,+ appId: "ai.cua.spaces.desktop.local",+ productName: "Cua Spaces Local",+ directories: { ...base.directories, output: "dist-local" },+ protocols: [{ name: "Cua Local", schemes: ["cua-local"] }],+ // Never a feed: a Local build is not updated from the release channel.+ publish: null,+ win: {+ ...base.win,+ // Unsigned, whatever the environment has.+ azureSignOptions: undefined,+ target: [{ target: "dir", arch: [process.env.CUA_SPACES_LOCAL_ARCH || "x64"] }],+ },+ // The installer's is the released app's; there is no installer here.+ nsis: undefined,+ // Release-only checks and signing hooks stay; the executable name follows productName.+ extraMetadata: { ...base.extraMetadata, name: "cua-spaces-local" },+ afterSign: undefined,+};+diff --git a/apps/cua-spaces-desktop/scripts/_local-common.ps1 b/apps/cua-spaces-desktop/scripts/_local-common.ps1new file mode 100644index 0000000000..2bf116e20e--- /dev/null+++ b/apps/cua-spaces-desktop/scripts/_local-common.ps1@@ -0,0 +1,303 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Names and checks shared by install-local.ps1 and uninstall-local.ps1 (Cua+# Spaces Local on Windows; the counterpart of apps/cua-spaces-macos/scripts/+# _local-common.sh). Dot-sourced; no side effects besides the definitions.+# Works in Windows PowerShell 5.1 and PowerShell 7.+#+# THE NAMES BELOW MIRROR src/channel.ts (the app's own) and+# packaging/electron-builder.local.cjs, and `CuaChannel::Local` in+# libs/cua/crates/cua-home/src/channel.rs for the CLI and home names;+# scripts/tests/install-local.tests.ps1 fails when one stops matching.++$script:Local = @{+ AppDirName = 'Cua Spaces Local'+ ExeName = 'Cua Spaces Local.exe'+ CliName = 'cua-local'+ CliExeName = 'cua-local.exe'+ AppId = 'ai.cua.spaces.desktop.local'+ UrlScheme = 'cua-local'+ HomeDirName = '.cua-local'+ UserDataDirName = 'Cua Spaces Local'+ ShortcutName = 'Cua Spaces Local.lnk'+ MarkerName = '.cua-spaces-local.json'+}++# What the released Cua Spaces owns. Never created, replaced or removed here.+$script:Released = @{+ AppId = 'ai.cua.spaces.desktop'+ UrlScheme = 'cua'+ HomeDirName = '.cua'+ CliExeName = 'cua.exe'+}++function Write-Step([string]$Message) { Write-Host "==> $Message" -ForegroundColor Cyan }+function Write-Ok([string]$Message) { Write-Host $Message -ForegroundColor Green }+function Write-Warn([string]$Message) { Write-Host "warning: $Message" -ForegroundColor Yellow }+function Write-Err([string]$Message) { [Console]::Error.WriteLine("error: $Message") }++# --- Paths ---------------------------------------------------------------------++# The full path with `.`, `..` and the trailing separator resolved, and a link+# (symlink or junction) anywhere along the existing part replaced by its target,+# so nothing in a path can hide where it lands.+function Resolve-RealPath([string]$Path) {+ $full = [System.IO.Path]::GetFullPath($Path)+ $root = [System.IO.Path]::GetPathRoot($full)+ $rest = $full.Substring($root.Length).Split([char[]]@('\', '/'), [System.StringSplitOptions]::RemoveEmptyEntries)+ $current = $root+ foreach ($segment in $rest) {+ $next = Join-Path $current $segment+ if (Test-Path -LiteralPath $next) {+ $item = Get-Item -LiteralPath $next -Force+ if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {+ $target = @($item.Target)[0]+ if ($target) {+ if (-not [System.IO.Path]::IsPathRooted($target)) { $target = Join-Path $current $target }+ $next = Resolve-RealPath $target+ }+ }+ }+ $current = $next+ }+ if ($current.Length -le 3) { return $current }+ return $current.TrimEnd('\', '/')+}++function Test-PathInside([string]$Child, [string]$Parent) {+ $c = $Child.TrimEnd('\', '/').ToLowerInvariant()+ $p = $Parent.TrimEnd('\', '/').ToLowerInvariant()+ return ($c -eq $p) -or $c.StartsWith($p + '\')+}++# The roots the released Cua Spaces owns, for this user and machine. The+# released installer's folder is Programs\cua-spaces (the package name) or, in+# older builds, Programs\Cua Spaces; the CLI it puts on PATH is Programs\cua\bin.+function Get-ReleasedRoots([string]$LocalAppData, [string]$UserProfile, [string]$ProgramFiles) {+ $roots = @(+ (Join-Path $LocalAppData 'Programs\cua-spaces'),+ (Join-Path $LocalAppData 'Programs\Cua Spaces'),+ (Join-Path $LocalAppData 'Programs\Cua'),+ (Join-Path $UserProfile $script:Released.HomeDirName)+ )+ if ($ProgramFiles) {+ $roots += (Join-Path $ProgramFiles 'Cua Spaces')+ $roots += (Join-Path $ProgramFiles 'cua-spaces')+ }+ return $roots+}++# The released root `Path` is, is inside, or contains; $null when none. A path+# that holds a released root would delete it on replace, so both directions+# count. (Windows paths compare case-insensitively.)+function Find-ReleasedOverlap([string]$Path, [string[]]$Roots) {+ foreach ($r in $Roots) {+ if ((Test-PathInside $Path $r) -or (Test-PathInside $r $Path)) { return $r }+ }+ return $null+}++# --- What is at the install path ------------------------------------------------++# 'absent', 'empty', 'local' (our marker, with the Local app id) or 'foreign'+# (anything else: a released app, someone's files). Only absent, empty and local+# may be written; foreign is refused, so the script never replaces what it did+# not install.+function Get-InstallState([string]$Dir) {+ if (-not (Test-Path -LiteralPath $Dir)) { return 'absent' }+ $item = Get-Item -LiteralPath $Dir -Force+ if (-not $item.PSIsContainer) { return 'foreign' }+ if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { return 'foreign' }+ $entries = @(Get-ChildItem -LiteralPath $Dir -Force)+ if ($entries.Count -eq 0) { return 'empty' }+ $marker = Join-Path $Dir $script:Local.MarkerName+ if (-not (Test-Path -LiteralPath $marker -PathType Leaf)) { return 'foreign' }+ try { $info = Get-Content -LiteralPath $marker -Raw | ConvertFrom-Json } catch { return 'foreign' }+ if ($info.appId -ne $script:Local.AppId) { return 'foreign' }+ return 'local'+}++# --- PATH (user scope) ----------------------------------------------------------++function Test-PathListHas([string]$List, [string]$Entry) {+ $e = $Entry.TrimEnd('\').ToLowerInvariant()+ foreach ($part in ($List -split ';')) {+ if ($part -and $part.TrimEnd('\').ToLowerInvariant() -eq $e) { return $true }+ }+ return $false+}++function Add-PathListEntry([string]$List, [string]$Entry) {+ if (Test-PathListHas $List $Entry) { return $List }+ if ([string]::IsNullOrEmpty($List)) { return $Entry }+ return $List.TrimEnd(';') + ';' + $Entry+}++function Remove-PathListEntry([string]$List, [string]$Entry) {+ $e = $Entry.TrimEnd('\').ToLowerInvariant()+ $kept = @(($List -split ';') | Where-Object { $_ -and $_.TrimEnd('\').ToLowerInvariant() -ne $e })+ return ($kept -join ';')+}++# --- Versions -------------------------------------------------------------------++# Node 22 or later.+function Test-NodeVersionOk([string]$Version) {+ if ($Version -notmatch '^v?(\d+)\.') { return $false }+ return [int]$Matches[1] -ge 22+}++# The pinned wasm-bindgen version out of apps/cua-spaces-web/scripts/build-core-wasm.mjs,+# and the toolchain channel out of a rust-toolchain.toml; $null when not there.+function Get-WasmBindgenPin([string]$ScriptPath) {+ if (-not (Test-Path -LiteralPath $ScriptPath)) { return $null }+ $m = Select-String -LiteralPath $ScriptPath -Pattern '^const WASM_BINDGEN = "(.+)"' | Select-Object -First 1+ if ($m) { return $m.Matches[0].Groups[1].Value }+ return $null+}++function Get-ToolchainChannel([string]$TomlPath) {+ if (-not (Test-Path -LiteralPath $TomlPath)) { return $null }+ $m = Select-String -LiteralPath $TomlPath -Pattern '^channel\s*=\s*"(.+)"' | Select-Object -First 1+ if ($m) { return $m.Matches[0].Groups[1].Value }+ return $null+}++# --- Processes ------------------------------------------------------------------++# Processes running a program from inside `Dir` (the Local app, its daemon):+# nothing outside the folder is ever named.+function Get-ProcessesUnder([string]$Dir) {+ $found = @()+ foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {+ $path = $null+ try { $path = $p.Path } catch { }+ if ($path -and (Test-PathInside $path $Dir)) { $found += $p }+ }+ return $found+}++function Stop-ProcessesUnder([string]$Dir) {+ $procs = @(Get-ProcessesUnder $Dir)+ foreach ($p in $procs) { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue }+ if ($procs.Count -gt 0) { Start-Sleep -Milliseconds 800 }+ return $procs.Count+}++# --- Windows integration ---------------------------------------------------------++$script:ShortcutSource = @'+using System;+using System.Runtime.InteropServices;+public static class CuaLocalShortcut {+ [ComImport, Guid("00021401-0000-0000-C000-000000000046")] class CShellLink { }+ [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]+ interface IShellLinkW {+ void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder f, int c, IntPtr d, int fl);+ void GetIDList(out IntPtr p); void SetIDList(IntPtr p);+ void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder f, int c);+ void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string d);+ void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder f, int c);+ void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string d);+ void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder f, int c);+ void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string a);+ void GetHotkey(out short h); void SetHotkey(short h);+ void GetShowCmd(out int s); void SetShowCmd(int s);+ void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder f, int c, out int i);+ void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string f, int i);+ void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string p, int r);+ void Resolve(IntPtr h, int f);+ void SetPath([MarshalAs(UnmanagedType.LPWStr)] string p);+ }+ [StructLayout(LayoutKind.Sequential, Pack = 4)] struct PROPERTYKEY { public Guid fmtid; public uint pid; }+ [StructLayout(LayoutKind.Explicit)] struct PROPVARIANT {+ [FieldOffset(0)] public ushort vt; [FieldOffset(8)] public IntPtr p;+ }+ [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")]+ interface IPropertyStore {+ void GetCount(out uint c); void GetAt(uint i, out PROPERTYKEY k);+ void GetValue(ref PROPERTYKEY k, out PROPVARIANT v);+ void SetValue(ref PROPERTYKEY k, ref PROPVARIANT v); void Commit();+ }+ [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("0000010b-0000-0000-C000-000000000046")]+ interface IPersistFile {+ void GetClassID(out Guid g); [PreserveSig] int IsDirty();+ void Load([MarshalAs(UnmanagedType.LPWStr)] string f, int m);+ void Save([MarshalAs(UnmanagedType.LPWStr)] string f, [MarshalAs(UnmanagedType.Bool)] bool r);+ void SaveCompleted([MarshalAs(UnmanagedType.LPWStr)] string f);+ void GetCurFile([MarshalAs(UnmanagedType.LPWStr)] out string f);+ }+ [DllImport("ole32.dll")] static extern int PropVariantClear(ref PROPVARIANT v);+ public static void Create(string link, string target, string dir, string aumid, string desc) {+ IShellLinkW sl = (IShellLinkW)new CShellLink();+ sl.SetPath(target); sl.SetWorkingDirectory(dir); sl.SetDescription(desc);+ sl.SetIconLocation(target, 0);+ IPropertyStore ps = (IPropertyStore)sl;+ PROPERTYKEY key = new PROPERTYKEY { fmtid = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), pid = 5 };+ PROPVARIANT v = new PROPVARIANT { vt = 31, p = Marshal.StringToCoTaskMemUni(aumid) };+ try { ps.SetValue(ref key, ref v); ps.Commit(); } finally { PropVariantClear(ref v); }+ ((IPersistFile)sl).Save(link, true);+ }+}+'@++# A Start Menu shortcut that carries the app's AppUserModelID (the one+# src/channel.ts gives the app), so the taskbar groups the window under it and+# toasts name it; IShellLink and IPropertyStore, which PowerShell has no cmdlet for.+function New-AppShortcut([string]$LinkPath, [string]$Target, [string]$WorkingDir, [string]$AppUserModelId, [string]$Description) {+ if (-not ('CuaLocalShortcut' -as [type])) { Add-Type -TypeDefinition $script:ShortcutSource }+ $dir = Split-Path -Parent $LinkPath+ if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }+ [CuaLocalShortcut]::Create($LinkPath, $Target, $WorkingDir, $AppUserModelId, $Description)+}++# Tells running programs (Explorer, new terminals) that the environment changed.+function Send-EnvironmentChange {+ if (-not ('CuaLocalNative.Win' -as [type])) {+ Add-Type -Namespace CuaLocalNative -Name Win -MemberDefinition @'+[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]+public static extern System.IntPtr SendMessageTimeout(System.IntPtr h, uint m, System.UIntPtr w, string l, uint f, uint t, out System.UIntPtr r);+'@+ }+ $r = [UIntPtr]::Zero+ [void][CuaLocalNative.Win]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 2000, [ref]$r)+}++# The user PATH as stored: [Environment]::GetEnvironmentVariable expands %VARS% and writing it back would+# store every entry expanded (and change the value's type), so the registry value is read and written as it is.+function Get-UserPath {+ $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)+ try {+ $value = $key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)+ return [string]$value+ } finally { $key.Close() }+}+function Set-UserPath([string]$Value) {+ $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)+ try { $key.SetValue('Path', $Value, [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Close() }+ Send-EnvironmentChange+}++# Whether `Text` contains `Part`, as plain text (a path can hold wildcard characters), any case.+function Test-ContainsText([string]$Text, [string]$Part) {+ return ($Text.IndexOf($Part, [System.StringComparison]::OrdinalIgnoreCase) -ge 0)+}++# The protocol key for cua-local:// (what Electron's setAsDefaultProtocolClient+# writes as well), so links work before the first launch. Removed again only+# when its command still points into the Local app.+function Register-LocalProtocol([string]$Exe) {+ $key = "HKCU:\Software\Classes\$($script:Local.UrlScheme)"+ New-Item -Path $key -Force | Out-Null+ Set-ItemProperty -Path $key -Name '(default)' -Value "URL:$($script:Local.AppDirName)"+ Set-ItemProperty -Path $key -Name 'URL Protocol' -Value ''+ New-Item -Path "$key\shell\open\command" -Force | Out-Null+ Set-ItemProperty -Path "$key\shell\open\command" -Name '(default)' -Value ('"{0}" "%1"' -f $Exe)+}++function Get-LocalProtocolCommand {+ $key = "HKCU:\Software\Classes\$($script:Local.UrlScheme)\shell\open\command"+ if (-not (Test-Path $key)) { return $null }+ return (Get-ItemProperty -Path $key).'(default)'+}diff --git a/apps/cua-spaces-desktop/scripts/install-local.ps1 b/apps/cua-spaces-desktop/scripts/install-local.ps1new file mode 100644index 0000000000..8925cb6804--- /dev/null+++ b/apps/cua-spaces-desktop/scripts/install-local.ps1@@ -0,0 +1,392 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++<#+.SYNOPSIS+Builds Cua Spaces from this checkout and installs it as "Cua Spaces Local",+next to a released Cua Spaces: another app id and AppUserModelID, app folder,+executable, CLI (`cua-local`), cua home (`%USERPROFILE%\.cua-local`), channel+(ports, names, sign-in), URL scheme (`cua-local://`), user data folder and no+update feed. The Windows counterpart of+apps/cua-spaces-macos/scripts/install-local.sh.++.DESCRIPTION+ scripts\install-local.ps1 [-Release] [-NoLaunch] [-Prefix DIR]+ [-SkipRustBuild] [-SkipWebBuild]+ [-NoIntegration] [-NormalPriority]++ -Release build with the Electron fuses the release build flips+ (default: fuses off, so the app can be debugged with+ --inspect, as CUA_SPACES_NO_FUSES=1 does)+ -NoLaunch do not start the app when it is installed+ -Prefix DIR install under DIR\Programs instead of %LOCALAPPDATA%\Programs.+ DIR is resolved (`..`, links) and refused when the app+ would be, hold, or be inside anything the released Cua+ Spaces owns (Programs\cua-spaces, Programs\Cua Spaces,+ Programs\Cua, %USERPROFILE%\.cua, Program Files\Cua Spaces)+ -SkipRustBuild do not run cargo: use native\win32-<arch> as it is+ -SkipWebBuild do not build the web UI (apps\cua-spaces-web): use the+ build already in its dist\, or the one $env:CUA_WEBUI_DIST+ names. Stops when there is none.+ -NoIntegration do not touch the Start Menu, the user PATH or the+ cua-local:// registration (the files only)+ -NormalPriority builds run at BelowNormal priority by default, so a PC in+ use stays usable; this keeps the normal one++Needs (checked first; one message says what to install): Rust (rustup) with the+MSVC toolchain and the Visual Studio C++ Build Tools, CMake (the audio codec+build), Node 22 or later, pnpm, the wasm32 Rust target and wasm-bindgen-cli+(the versions the release build pins).++What it installs, and nothing else (default paths):+ %LOCALAPPDATA%\Programs\Cua Spaces Local\ the app+ %LOCALAPPDATA%\Programs\Cua Spaces Local\bin\cua-local.exe the CLI (a copy of the app's cua.exe)+ the user PATH entry for that bin folder+ %APPDATA%\Microsoft\Windows\Start Menu\Programs\Cua Spaces Local.lnk+ HKCU\Software\Classes\cua-local the cua-local:// scheme++What it never touches: the released Cua Spaces and its `cua`, %USERPROFILE%\.cua,+their Run entry, scheme and PATH entry, and any folder at the Local path that is+not the Local one (it refuses). The build is staged and verified first; the live+copy is swapped only then, and put back if the swap fails.++The app sets CUA_CHANNEL=local and CUA_HOME=%USERPROFILE%\.cua-local at start+(src\channel.ts), so the daemon and every child inherit them; a variable that is+already set wins. Local talks to staging (CUA_ENV=prod opts in).++Uninstall: scripts\uninstall-local.ps1.+#>+[CmdletBinding()]+param(+ [switch]$Release,+ [switch]$NoLaunch,+ [string]$Prefix = '',+ [switch]$SkipRustBuild,+ [switch]$SkipWebBuild,+ [switch]$NoIntegration,+ [switch]$NormalPriority+)++$ErrorActionPreference = 'Stop'+Set-StrictMode -Version 2++$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path+. (Join-Path $ScriptDir '_local-common.ps1')++$AppDir = (Resolve-Path (Join-Path $ScriptDir '..')).Path+$RepoRoot = (Resolve-Path (Join-Path $AppDir '..\..')).Path+$WebApp = Join-Path $RepoRoot 'apps\cua-spaces-web'+$WasmScript = Join-Path $WebApp 'scripts\build-core-wasm.mjs'+$WasmToolchainFile = Join-Path $RepoRoot 'apps\cua-spaces\rust-toolchain.toml'+$Arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { 'arm64' } else { 'x64' }+$NativeDir = Join-Path $AppDir "native\win32-$Arch"+$BuilderConfig = 'packaging/electron-builder.local.cjs'+$BuildOut = Join-Path $AppDir 'dist-local'++function Stop-Install([string]$Message) { Write-Err $Message; exit 1 }++# Runs a native program; a non-zero exit stops the script. (Windows PowerShell+# 5.1 turns a program's stderr into errors under 'Stop', so it is relaxed here.)+function Invoke-Native([string]$What, [string]$File, [string[]]$Arguments, [string]$WorkDir) {+ $previous = $ErrorActionPreference+ $ErrorActionPreference = 'Continue'+ Push-Location $WorkDir+ try { & $File @Arguments | Out-Host; $code = $LASTEXITCODE } finally { Pop-Location; $ErrorActionPreference = $previous }+ if ($code -ne 0) { Stop-Install "$What failed (exit $code). Nothing was installed." }+}++# The pnpm this checkout pins (package.json "packageManager"). pnpm 10 cannot read pnpm 11's+# lockfile and its self-switch can leave a broken copy, so a pnpm of another major than the pin+# is not used: the pinned one is installed into+# .local-tools (npm, a folder of this checkout; nothing global changes).+function Resolve-Pnpm {+ $pin = (Get-Content (Join-Path $AppDir 'package.json') -Raw | ConvertFrom-Json).packageManager+ if ($pin -notmatch '^pnpm@(\d+)\.[\d.]+') { return 'pnpm' }+ $version = ($pin -replace '^pnpm@', '')+ $major = $Matches[1]+ $have = ''+ if (Test-Tool 'pnpm') { $have = ((& pnpm --version 2>$null) | Out-String).Trim() }+ if ($have -like "$major.*") { return 'pnpm' }+ $private = Join-Path $AppDir ".local-tools\pnpm-$version"+ $exe = Join-Path $private 'node_modules\.bin\pnpm.cmd'+ if (-not (Test-Path $exe)) {+ Write-Step "installing pnpm $version (this checkout pins it; this PC has pnpm $have) into $private"+ New-Item -ItemType Directory -Path $private -Force | Out-Null+ Invoke-Native 'npm install pnpm' 'npm' @('install', '--prefix', $private, "pnpm@$version", '--no-audit', '--no-fund', '--loglevel=error') $AppDir+ }+ return $exe+}++if ($env:OS -ne 'Windows_NT') { Stop-Install 'Cua Spaces Local (this script) is for Windows.' }+if (-not $NormalPriority) {+ # Children inherit it: cargo, node and the compilers stay out of the way.+ try { (Get-Process -Id $PID).PriorityClass = 'BelowNormal' } catch { Write-Warn "could not lower the priority: $($_.Exception.Message)" }+}++# --- Where it goes -------------------------------------------------------------++if (-not $Prefix) { $Prefix = $env:LOCALAPPDATA }+if (-not [System.IO.Path]::IsPathRooted($Prefix)) { Stop-Install "-Prefix must be an absolute path (got: $Prefix)" }+$ProgramsDir = Resolve-RealPath (Join-Path $Prefix 'Programs')+$InstallDir = Join-Path $ProgramsDir $Local.AppDirName+$StageDir = Join-Path $ProgramsDir ($Local.AppDirName + '.new')+$OldDir = Join-Path $ProgramsDir ($Local.AppDirName + '.old')+$BinDir = Join-Path $InstallDir 'bin'+$CliPath = Join-Path $BinDir $Local.CliExeName+$ExePath = Join-Path $InstallDir $Local.ExeName+$ShortcutPath = Join-Path $env:APPDATA ('Microsoft\Windows\Start Menu\Programs\' + $Local.ShortcutName)++# None of what this script writes is, holds, or is inside anything the+# released Cua Spaces owns.+$roots = Get-ReleasedRoots $env:LOCALAPPDATA $env:USERPROFILE $env:ProgramFiles+foreach ($p in @($InstallDir, $StageDir, $OldDir)) {+ $hit = Find-ReleasedOverlap $p $roots+ if ($hit) { Stop-Install "refusing to use ${p}: it is, holds or is inside $hit, which the released Cua Spaces owns." }+}+if ((Split-Path -Leaf $InstallDir) -ne $Local.AppDirName) { Stop-Install "internal error: app path $InstallDir" }++# --- Preflight: nothing is built or changed when the Local path holds something else ---++foreach ($p in @($InstallDir, $StageDir, $OldDir)) {+ $state = Get-InstallState $p+ if ($state -eq 'foreign') {+ # Our own leftovers (a failed earlier run) are removed; anything else is refused.+ $isLeftover = ($p -ne $InstallDir) -and (Test-Path -LiteralPath (Join-Path $p $Local.ExeName))+ if (-not $isLeftover) {+ Stop-Install "refusing to touch ${p}: it is not a Cua Spaces Local install (no $($Local.MarkerName) with the Local app id). Move it away or pass another -Prefix."+ }+ }+}++# --- Preflight: the tools the build needs --------------------------------------++$Missing = New-Object System.Collections.Generic.List[string]+function Add-Missing([string]$Text) { $Missing.Add($Text) }+function Test-Tool([string]$Name) { return [bool](Get-Command $Name -ErrorAction SilentlyContinue) }++$BuildWeb = (-not $SkipWebBuild) -and (-not $env:CUA_WEBUI_DIST)+$WebDist = if ($env:CUA_WEBUI_DIST) { $env:CUA_WEBUI_DIST } else { Join-Path $WebApp 'dist' }++function Test-Prerequisites {+ # A shell that did not get rustup's PATH entry still has cargo here.+ $cargoBin = Join-Path $env:USERPROFILE '.cargo\bin'+ if ((Test-Path $cargoBin) -and ($env:PATH -notlike "*$cargoBin*")) { $env:PATH = "$cargoBin;$env:PATH" }++ if (-not $SkipRustBuild) {+ if (-not (Test-Tool 'cmake')) { Add-Missing 'CMake (the audio codec build needs it): winget install Kitware.CMake' }+ $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'+ $hasMsvc = $false+ if (Test-Path $vswhere) {+ $found = & $vswhere -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2>$null+ $hasMsvc = [bool]$found+ }+ if (-not $hasMsvc -and -not (Test-Tool 'cl')) {+ Add-Missing 'the Visual Studio C++ Build Tools (the "Desktop development with C++" workload, MSVC and a Windows SDK): winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"'+ }+ }+ if ((-not $SkipRustBuild) -or $BuildWeb) {+ if (-not (Test-Tool 'cargo') -or -not (Test-Tool 'rustup')) {+ Add-Missing 'Rust (cargo and rustup), MSVC host: winget install Rustlang.Rustup (then open a new terminal)'+ }+ }+ # The shell itself (electron-builder, tsdown) always needs Node and pnpm.+ if (-not (Test-Tool 'node')) {+ Add-Missing 'Node 22 or later: winget install OpenJS.NodeJS'+ } elseif (-not (Test-NodeVersionOk (& node --version))) {+ Add-Missing "Node 22 or later, this PC has $(& node --version): winget install OpenJS.NodeJS"+ }+ if (-not (Test-Tool 'pnpm')) { Add-Missing 'pnpm: corepack enable (or: winget install pnpm.pnpm)' }+ if ($BuildWeb) {+ # 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 = Get-ToolchainChannel $WasmToolchainFile+ if ($toolchain -and (Test-Tool 'rustup')) {+ $targets = & rustup target list --installed --toolchain $toolchain 2>$null+ if (-not ($targets -contains 'wasm32-unknown-unknown')) {+ Add-Missing "the wasm32 Rust target for Rust $toolchain (the web UI): rustup toolchain install $toolchain --profile minimal --target wasm32-unknown-unknown"+ }+ }+ $pin = Get-WasmBindgenPin $WasmScript+ if ($pin) {+ $have = if (Test-Tool 'wasm-bindgen') { (& wasm-bindgen --version) } else { '' }+ if ("$have" -notlike "*$pin*") { Add-Missing "wasm-bindgen-cli $pin (the web UI): cargo install wasm-bindgen-cli --version $pin --locked" }+ }+ }+}++Test-Prerequisites+if ($Missing.Count -gt 0) {+ Write-Err "Cua Spaces Local cannot be built yet: $($Missing.Count) thing(s) to install first. Nothing was built or changed."+ foreach ($m in $Missing) { [Console]::Error.WriteLine(" - $m") }+ [Console]::Error.WriteLine('Install them, then run this script again.')+ exit 1+}++if ($SkipRustBuild) {+ foreach ($f in @('cua_spaces_ffi.dll', 'cua_node_runtime.node', 'cua.exe')) {+ if (-not (Test-Path (Join-Path $NativeDir $f))) {+ Stop-Install "-SkipRustBuild: there is no $f in $NativeDir. Build it (node scripts\build-native.mjs) or leave out -SkipRustBuild."+ }+ }+}+if (-not $BuildWeb -and -not (Test-Path (Join-Path $WebDist 'index.html'))) {+ Stop-Install "there is no web UI build at ${WebDist}\index.html, and without it Cua Spaces Local shows ""The new UI is not in this build"". Build it ((cd apps\cua-spaces-web; pnpm install --ignore-workspace --frozen-lockfile; pnpm build)) or leave out -SkipWebBuild."+}++Write-Host 'Cua Spaces Local installer' -ForegroundColor Cyan+Write-Host " source: $RepoRoot"+Write-Host " config: $(if ($Release) { 'release (Electron fuses on)' } else { 'debug (Electron fuses off)' })"+Write-Host " app: $InstallDir"+Write-Host " cli: $CliPath"+Write-Host ''++# --- Build ---------------------------------------------------------------------++$env:CI = 'true'+# The pinned pnpm goes first on PATH, so the `pnpm` inside package scripts is it too.+$env:npm_config_manage_package_manager_versions = 'false'+$pnpmPath = Resolve-Pnpm+if ($pnpmPath -ne 'pnpm') { $env:PATH = (Split-Path -Parent $pnpmPath) + ';' + $env:PATH }+$webProc = $null+$webLog = Join-Path ([System.IO.Path]::GetTempPath()) "cua-local-webui-$PID.log"+if ($BuildWeb) {+ Write-Step 'building the web UI (apps\cua-spaces-web: pnpm install, pnpm build) in the background'+ $cmd = "pnpm install --ignore-workspace --frozen-lockfile > ""$webLog"" 2>&1 && pnpm build >> ""$webLog"" 2>&1"+ $webProc = Start-Process -FilePath "$env:ComSpec" -ArgumentList '/d', '/c', $cmd -WorkingDirectory $WebApp -PassThru -WindowStyle Hidden+ $null = $webProc.Handle+}+function Wait-WebBuild {+ if (-not $webProc) { return }+ $webProc.WaitForExit()+ if ($webProc.ExitCode -ne 0) {+ Get-Content $webLog -Tail 60 | ForEach-Object { [Console]::Error.WriteLine($_) }+ Stop-Install "the web UI build failed (log: $webLog). Nothing was installed."+ }+ Remove-Item $webLog -Force -ErrorAction SilentlyContinue+ Write-Ok 'the web UI is built'+}++Write-Step 'installing the desktop shell dependencies (pnpm install --frozen-lockfile)'+Invoke-Native 'pnpm install' 'pnpm' @('install', '--frozen-lockfile') $AppDir++if (-not $SkipRustBuild) {+ Write-Step 'building the native layer: the Cua Spaces library, the Node runtime and cua.exe (cargo, release)'+ Invoke-Native 'the native build' 'node' @('scripts/build-native.mjs') $AppDir+}+Wait-WebBuild+if ($BuildWeb -or $SkipWebBuild) {+ if (-not (Test-Path (Join-Path $WebDist 'index.html'))) { Stop-Install "the web UI build left no ${WebDist}\index.html" }+}+if ($env:CUA_WEBUI_DIST -and ((Resolve-RealPath $env:CUA_WEBUI_DIST) -ne (Resolve-RealPath (Join-Path $WebApp 'dist')))) {+ Write-Warn 'CUA_WEBUI_DIST is set, but the shell packs apps\cua-spaces-web\dist: copy the build there to use it.'+}++Write-Step 'packaging the app (electron-builder --win dir, Local config)'+Remove-Item -LiteralPath $BuildOut -Recurse -Force -ErrorAction SilentlyContinue+$env:CUA_SPACES_ARCHS = $Arch+$env:CUA_SPACES_LOCAL_ARCH = $Arch+if ($Release) { Remove-Item Env:\CUA_SPACES_NO_FUSES -ErrorAction SilentlyContinue } else { $env:CUA_SPACES_NO_FUSES = '1' }+Invoke-Native 'pnpm build' 'pnpm' @('build') $AppDir+Invoke-Native 'electron-builder' 'pnpm' @('exec', 'electron-builder', '--win', 'dir', "--$Arch", '--config', $BuilderConfig, '--publish', 'never') $AppDir+$Built = Join-Path $BuildOut $(if ($Arch -eq 'arm64') { 'win-arm64-unpacked' } else { 'win-unpacked' })+if (-not (Test-Path (Join-Path $Built $Local.ExeName))) {+ Stop-Install "electron-builder did not produce $($Local.ExeName) in ${Built}: it did not build the Local config, so nothing was installed."+}++# --- Stage and verify -------------------------------------------------------------++Write-Step "staging in $StageDir"+$rollback = $null+try {+ Remove-Item -LiteralPath $StageDir -Recurse -Force -ErrorAction SilentlyContinue+ New-Item -ItemType Directory -Path $ProgramsDir -Force | Out-Null+ Copy-Item -LiteralPath $Built -Destination $StageDir -Recurse+ $stageBin = Join-Path $StageDir 'bin'+ New-Item -ItemType Directory -Path $stageBin -Force | Out-Null+ # The CLI is a copy named cua-local.exe: the CLI knows it is the Local channel by that name+ # (CuaChannel::path_is_local). A copy, not a link: no privilege, and PATH never names cua.exe.+ $nativeCli = Join-Path $StageDir 'resources\native\cua.exe'+ Copy-Item -LiteralPath $nativeCli -Destination (Join-Path $stageBin $Local.CliExeName)++ $problems = @()+ foreach ($f in @($Local.ExeName, 'resources\app.asar', 'resources\native\cua_spaces_ffi.dll', 'resources\native\cua_node_runtime.node', 'resources\web\index.html', "bin\$($Local.CliExeName)")) {+ if (-not (Test-Path (Join-Path $StageDir $f))) { $problems += "missing $f" }+ }+ if (Test-Path (Join-Path $StageDir 'resources\app-update.yml')) { $problems += 'it has an update feed (resources\app-update.yml)' }+ $cliVersion = ''+ try { $cliVersion = (& (Join-Path $stageBin $Local.CliExeName) --version 2>&1 | Out-String).Trim() } catch { $problems += "cua-local --version failed: $($_.Exception.Message)" }+ if ($LASTEXITCODE -ne 0 -or -not $cliVersion) { $problems += "cua-local --version printed nothing useful (exit $LASTEXITCODE)" }+ if ($problems.Count -gt 0) {+ Stop-Install ("the staged build does not verify: " + ($problems -join '; ') + '. Nothing was installed.')+ }+ Write-Ok "verified: $cliVersion"++ $pkgVersion = (Get-Content (Join-Path $AppDir 'package.json') -Raw | ConvertFrom-Json).version+ $marker = [ordered]@{+ appId = $Local.AppId+ version = $pkgVersion+ source = $RepoRoot+ installedAt = (Get-Date).ToString('o')+ pathEntry = $null+ shortcut = $null+ protocol = $false+ }++ # --- Swap -------------------------------------------------------------------+ $liveState = Get-InstallState $InstallDir+ if ($liveState -eq 'local') {+ Write-Step 'stopping the running Cua Spaces Local (only processes from its folder)'+ $stopped = Stop-ProcessesUnder $InstallDir+ if ($stopped -gt 0) { Write-Host " stopped $stopped process(es)" }+ }+ Remove-Item -LiteralPath $OldDir -Recurse -Force -ErrorAction SilentlyContinue+ if (Test-Path -LiteralPath $InstallDir) {+ Move-Item -LiteralPath $InstallDir -Destination $OldDir+ $rollback = $OldDir+ }+ try {+ Move-Item -LiteralPath $StageDir -Destination $InstallDir+ } catch {+ if ($rollback) { Move-Item -LiteralPath $OldDir -Destination $InstallDir -ErrorAction SilentlyContinue }+ throw+ }++ # --- Windows integration -------------------------------------------------------+ if (-not $NoIntegration) {+ Write-Step 'Start Menu shortcut, user PATH, cua-local:// scheme'+ New-AppShortcut $ShortcutPath $ExePath $InstallDir $Local.AppId 'Cua Spaces Local'+ $marker.shortcut = $ShortcutPath+ $userPath = Get-UserPath+ if (-not (Test-PathListHas $userPath $BinDir)) {+ Set-UserPath (Add-PathListEntry $userPath $BinDir)+ $marker.pathEntry = $BinDir+ } else {+ $marker.pathEntry = $BinDir+ }+ Register-LocalProtocol $ExePath+ $marker.protocol = $true+ }+ ($marker | ConvertTo-Json) | Set-Content -LiteralPath (Join-Path $InstallDir $Local.MarkerName) -Encoding UTF8+ $rollback = $null+ Remove-Item -LiteralPath $OldDir -Recurse -Force -ErrorAction SilentlyContinue+} finally {+ Remove-Item -LiteralPath $StageDir -Recurse -Force -ErrorAction SilentlyContinue+ if ($rollback -and (Test-Path -LiteralPath $OldDir) -and -not (Test-Path -LiteralPath $InstallDir)) {+ Move-Item -LiteralPath $OldDir -Destination $InstallDir -ErrorAction SilentlyContinue+ Write-Warn 'the install failed; the previous Cua Spaces Local was put back.'+ }+}++Write-Host ''+Write-Ok 'Cua Spaces Local is installed.'+Write-Host " app: $ExePath"+Write-Host " cli: $CliPath (open a new terminal: cua-local --version)"+Write-Host " home: $(Join-Path $env:USERPROFILE $Local.HomeDirName) (the app sets CUA_HOME and CUA_CHANNEL=local)"+Write-Host ' scheme: cua-local:// updates: none'++if (-not $NoLaunch) {+ Write-Step 'starting Cua Spaces Local'+ # The app inherits this script's priority: it runs at the normal one.+ try { (Get-Process -Id $PID).PriorityClass = 'Normal' } catch { }+ Start-Process -FilePath $ExePath -WorkingDirectory $InstallDir+}diff --git a/apps/cua-spaces-desktop/scripts/tests/install-local.tests.ps1 b/apps/cua-spaces-desktop/scripts/tests/install-local.tests.ps1new file mode 100644index 0000000000..dac496a928--- /dev/null+++ b/apps/cua-spaces-desktop/scripts/tests/install-local.tests.ps1@@ -0,0 +1,131 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++# Tests the pure parts of scripts\install-local.ps1 and uninstall-local.ps1+# (the path, refusal, PATH-list and version checks in _local-common.ps1), and+# that the names in it are the ones the app (src\channel.ts), the builder config+# and CuaChannel::Local have. Builds nothing and touches no registry, PATH, Start+# Menu or real home: everything runs in a temporary folder. Plain PowerShell,+# works in Windows PowerShell 5.1 and PowerShell 7:+#+# powershell -NoProfile -File scripts\tests\install-local.tests.ps1+#+# Each check prints PASS or FAIL; the exit status is the number of FAILs.+$ErrorActionPreference = 'Stop'+$here = Split-Path -Parent $MyInvocation.MyCommand.Path+$scripts = Split-Path -Parent $here+$app = Split-Path -Parent $scripts+. (Join-Path $scripts '_local-common.ps1')++$script:fails = 0+function Check([string]$Name, [bool]$Condition) {+ if ($Condition) { Write-Host "PASS $Name" } else { Write-Host "FAIL $Name"; $script:fails++ }+}++$work = Join-Path ([System.IO.Path]::GetTempPath()) ("cua-install-local-test-" + [guid]::NewGuid().ToString('N'))+New-Item -ItemType Directory -Path $work | Out-Null+try {+ # --- Released roots and overlap -------------------------------------------------+ $lad = Join-Path $work 'AppData\Local'+ $prof = Join-Path $work 'profile'+ $pf = Join-Path $work 'Program Files'+ $roots = Get-ReleasedRoots $lad $prof $pf+ $localApp = Join-Path $lad 'Programs\Cua Spaces Local'+ Check 'the Local app folder overlaps no released root' ($null -eq (Find-ReleasedOverlap $localApp $roots))+ Check 'Programs\cua-spaces is the released app' ($null -ne (Find-ReleasedOverlap (Join-Path $lad 'Programs\cua-spaces') $roots))+ Check 'a folder inside the released app is refused' ($null -ne (Find-ReleasedOverlap (Join-Path $lad 'Programs\cua-spaces\resources') $roots))+ Check 'Programs\Cua Spaces (older release) is refused, in any case' ($null -ne (Find-ReleasedOverlap (Join-Path $lad 'programs\CUA SPACES') $roots))+ Check 'the released home ~\.cua is refused' ($null -ne (Find-ReleasedOverlap (Join-Path $prof '.cua') $roots))+ Check '~\.cua-local is not the released home (a prefix is not a path)' ($null -eq (Find-ReleasedOverlap (Join-Path $prof '.cua-local') $roots))+ Check 'a folder that holds a released root is refused' ($null -ne (Find-ReleasedOverlap (Join-Path $lad 'Programs') $roots))+ Check 'Program Files\Cua Spaces is refused' ($null -ne (Find-ReleasedOverlap (Join-Path $pf 'Cua Spaces\x') $roots))+ Check 'Test-PathInside compares whole segments' (-not (Test-PathInside 'C:\a\bc' 'C:\a\b'))+ Check 'Test-PathInside is case-insensitive' (Test-PathInside 'C:\A\B\c' 'c:\a\b')++ # --- Resolve-RealPath: .. and links ---------------------------------------------+ $real = Join-Path $work 'real'+ New-Item -ItemType Directory -Path $real | Out-Null+ Check 'Resolve-RealPath resolves ..' ((Resolve-RealPath (Join-Path $real '..\real\x')) -eq (Join-Path $real 'x'))+ $link = Join-Path $work 'link'+ $linked = $false+ try { New-Item -ItemType Junction -Path $link -Target $real | Out-Null; $linked = $true } catch { Write-Host 'SKIP junction (cannot create one here)' }+ if ($linked) {+ Check 'Resolve-RealPath follows a junction to its target' ((Resolve-RealPath (Join-Path $link 'x')) -eq (Join-Path $real 'x'))+ $hidden = Resolve-RealPath (Join-Path $link 'x')+ Check 'a junction to a released root cannot hide it' ($null -ne (Find-ReleasedOverlap (Resolve-RealPath (Join-Path $link 'y')) @($real)))+ }++ # --- Install state: only absent, empty and Local are writable -------------------+ $d = Join-Path $work 'state'+ Check 'an absent folder is absent' ((Get-InstallState $d) -eq 'absent')+ New-Item -ItemType Directory -Path $d | Out-Null+ Check 'an empty folder is empty' ((Get-InstallState $d) -eq 'empty')+ Set-Content -LiteralPath (Join-Path $d 'file.txt') 'x'+ Check 'a folder of someone else''s files is foreign' ((Get-InstallState $d) -eq 'foreign')+ Set-Content -LiteralPath (Join-Path $d $Local.MarkerName) '{"appId":"ai.cua.spaces.desktop"}'+ Check 'a marker with the released app id is foreign' ((Get-InstallState $d) -eq 'foreign')+ Set-Content -LiteralPath (Join-Path $d $Local.MarkerName) 'not json'+ Check 'a broken marker is foreign' ((Get-InstallState $d) -eq 'foreign')+ Set-Content -LiteralPath (Join-Path $d $Local.MarkerName) ('{"appId":"' + $Local.AppId + '"}')+ Check 'a marker with the Local app id is local' ((Get-InstallState $d) -eq 'local')+ $f = Join-Path $work 'afile'+ Set-Content -LiteralPath $f 'x'+ Check 'a file at the path is foreign' ((Get-InstallState $f) -eq 'foreign')++ # --- PATH list ---------------------------------------------------------------------+ $bin = 'C:\Users\me\AppData\Local\Programs\Cua Spaces Local\bin'+ $relBin = 'C:\Users\me\AppData\Local\Programs\cua\bin'+ $list = "C:\Windows;$relBin"+ $added = Add-PathListEntry $list $bin+ Check 'Add-PathListEntry appends' ($added -eq "$list;$bin")+ Check 'Add-PathListEntry is idempotent (any case, trailing slash)' ((Add-PathListEntry $added ($bin.ToUpper() + '\')) -eq $added)+ Check 'Add-PathListEntry on an empty PATH' ((Add-PathListEntry '' $bin) -eq $bin)+ Check 'Remove-PathListEntry removes only that entry' ((Remove-PathListEntry $added $bin) -eq $list)+ Check 'Remove-PathListEntry keeps the released cua folder' ((Remove-PathListEntry $added $bin) -like "*$relBin*")++ Check 'Test-ContainsText is plain text, any case (a path may hold [ or *)' ((Test-ContainsText 'x C:\A[1]\App.exe y' 'c:\a[1]\app.exe') -and -not (Test-ContainsText 'C:\a\b' 'C:\a*'))++ # --- Versions and pins -----------------------------------------------------------------+ Check 'Node 22 is enough' (Test-NodeVersionOk 'v22.0.0')+ Check 'Node 24 is enough' (Test-NodeVersionOk 'v24.13.0')+ Check 'Node 20 is not' (-not (Test-NodeVersionOk 'v20.11.1'))+ Check 'garbage is not a Node version' (-not (Test-NodeVersionOk 'node'))+ $pin = Get-WasmBindgenPin (Join-Path $app '..\cua-spaces-web\scripts\build-core-wasm.mjs')+ Check 'the wasm-bindgen pin is read from the web build script' ($pin -match '^\d+\.\d+\.\d+$')+ $chan = Get-ToolchainChannel (Join-Path $app '..\cua-spaces\rust-toolchain.toml')+ Check 'the Rust toolchain channel is read' ($chan -match '^\d+\.\d+\.\d+$')++ # --- The names are the app's, the builder's and CuaChannel::Local's -----------------+ $ts = Get-Content -LiteralPath (Join-Path $app 'src\channel.ts') -Raw+ Check 'src/channel.ts has the Local app id' ($ts.Contains('"' + $Local.AppId + '"'))+ Check 'src/channel.ts has the Local URL scheme' ($ts.Contains('"' + $Local.UrlScheme + '"'))+ Check 'src/channel.ts has the Local home folder' ($ts.Contains('"' + $Local.HomeDirName + '"'))+ Check 'src/channel.ts has the Local user data folder' ($ts.Contains('"' + $Local.UserDataDirName + '"'))+ Check 'src/channel.ts names the Local executable' ($ts.Contains($Local.ExeName.ToLowerInvariant()))+ Check 'the Local app id is the released one plus .local' ($Local.AppId -eq ($Released.AppId + '.local'))+ $cfg = Get-Content -LiteralPath (Join-Path $app 'packaging\electron-builder.local.cjs') -Raw+ Check 'the builder config has the Local app id' ($cfg.Contains('"' + $Local.AppId + '"'))+ Check 'the builder config has the Local product name (the executable)' ($cfg.Contains('productName: "' + $Local.AppDirName + '"'))+ Check 'the builder config has the Local scheme' ($cfg.Contains('"' + $Local.UrlScheme + '"'))+ Check 'the builder config has no update feed' ($cfg -match 'publish:\s*null')+ $rs = Get-Content -LiteralPath (Join-Path $app '..\..\libs\cua\crates\cua-home\src\channel.rs') -Raw+ Check 'CuaChannel::Local has the CLI name' ($rs.Contains('"' + $Local.CliName + '"'))+ Check 'CuaChannel::Local has the home folder' ($rs.Contains('"' + $Local.HomeDirName + '"'))+ Check 'CuaChannel::Local has the URL scheme' ($rs.Contains('"' + $Local.UrlScheme + '"'))+ Check 'the CLI is not named like the released cua.exe' ($Local.CliExeName -ne $Released.CliExeName)++ # --- The scripts parse (5.1 and 7) --------------------------------------------------------+ foreach ($s in @('install-local.ps1', 'uninstall-local.ps1', '_local-common.ps1')) {+ $errors = $null+ [void][System.Management.Automation.Language.Parser]::ParseFile((Join-Path $scripts $s), [ref]$null, [ref]$errors)+ Check "$s parses" ($errors.Count -eq 0)+ }+ Check 'the scripts hold no em dash (scripts/check-no-em-dash.sh)' (-not ((Get-ChildItem -LiteralPath $scripts -Filter '*.ps1' -Recurse | Select-String -Pattern ([string][char]0x2014)) | Select-Object -First 1))+} finally {+ Remove-Item -LiteralPath $link -Force -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue+}++if ($script:fails -gt 0) { Write-Host "$($script:fails) check(s) failed."; exit $script:fails }+Write-Host 'All checks passed.'+exit 0diff --git a/apps/cua-spaces-desktop/scripts/uninstall-local.ps1 b/apps/cua-spaces-desktop/scripts/uninstall-local.ps1new file mode 100644index 0000000000..62b463e149--- /dev/null+++ b/apps/cua-spaces-desktop/scripts/uninstall-local.ps1@@ -0,0 +1,103 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++<#+.SYNOPSIS+Removes Cua Spaces Local (scripts\install-local.ps1) and only that.++.DESCRIPTION+ scripts\uninstall-local.ps1 [-Prefix DIR] [-Purge]++Removes the Local app folder (with its bundled `cua-local`), the Start Menu+shortcut, the user PATH entry and the cua-local:// scheme the installer added+(each only when it still points into the Local app), after stopping the+processes running from the Local folder. The sign-in and state stay+(%USERPROFILE%\.cua-local, %APPDATA%\Cua Spaces Local) unless -Purge is given.++It never touches the released Cua Spaces, its `cua`, %USERPROFILE%\.cua, its Run+entry or scheme, and refuses a folder at the Local path that is not the Local+one.+#>+[CmdletBinding()]+param(+ [string]$Prefix = '',+ [switch]$Purge+)++$ErrorActionPreference = 'Stop'+Set-StrictMode -Version 2+$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path+. (Join-Path $ScriptDir '_local-common.ps1')++function Stop-Uninstall([string]$Message) { Write-Err $Message; exit 1 }++if (-not $Prefix) { $Prefix = $env:LOCALAPPDATA }+if (-not [System.IO.Path]::IsPathRooted($Prefix)) { Stop-Uninstall "-Prefix must be an absolute path (got: $Prefix)" }+$InstallDir = Join-Path (Resolve-RealPath (Join-Path $Prefix 'Programs')) $Local.AppDirName+$BinDir = Join-Path $InstallDir 'bin'+$ExePath = Join-Path $InstallDir $Local.ExeName+$ShortcutPath = Join-Path $env:APPDATA ('Microsoft\Windows\Start Menu\Programs\' + $Local.ShortcutName)++$roots = Get-ReleasedRoots $env:LOCALAPPDATA $env:USERPROFILE $env:ProgramFiles+$hit = Find-ReleasedOverlap $InstallDir $roots+if ($hit) { Stop-Uninstall "refusing to remove ${InstallDir}: it is, holds or is inside $hit, which the released Cua Spaces owns." }++$state = Get-InstallState $InstallDir+if ($state -eq 'foreign') {+ Stop-Uninstall "refusing to touch ${InstallDir}: it is not a Cua Spaces Local install (no $($Local.MarkerName) with the Local app id)."+}++# Stop what runs from the Local folder (the app, its daemon): nothing else.+if ($state -ne 'absent') {+ Write-Step 'stopping Cua Spaces Local'+ $n = Stop-ProcessesUnder $InstallDir+ if ($n -gt 0) { Write-Host " stopped $n process(es)" }+}++# The user PATH entry: only exactly this install's bin folder.+$userPath = Get-UserPath+if ($userPath -and (Test-PathListHas $userPath $BinDir)) {+ Set-UserPath (Remove-PathListEntry $userPath $BinDir)+ Write-Host " removed $BinDir from the user PATH"+}++# The scheme, when it is still the Local app's.+$command = Get-LocalProtocolCommand+if ($command -and (Test-ContainsText $command $ExePath)) {+ Remove-Item -Path "HKCU:\Software\Classes\$($Local.UrlScheme)" -Recurse -Force+ Write-Host " removed the $($Local.UrlScheme):// scheme"+} elseif ($command) {+ Write-Warn "left HKCU\Software\Classes\$($Local.UrlScheme): it does not point into $InstallDir"+}++# The Start Menu shortcut, when it points into the Local app.+if (Test-Path -LiteralPath $ShortcutPath) {+ $target = (New-Object -ComObject WScript.Shell).CreateShortcut($ShortcutPath).TargetPath+ if ($target -and (Test-PathInside $target $InstallDir)) {+ Remove-Item -LiteralPath $ShortcutPath -Force+ Write-Host ' removed the Start Menu shortcut'+ } else {+ Write-Warn "left ${ShortcutPath}: it does not point into $InstallDir"+ }+}++if ($state -ne 'absent') {+ Remove-Item -LiteralPath $InstallDir -Recurse -Force+ Write-Host " removed $InstallDir"+}++if ($Purge) {+ $state2 = @(+ (Join-Path $env:APPDATA $Local.UserDataDirName),+ (Join-Path $env:USERPROFILE $Local.HomeDirName)+ )+ foreach ($d in $state2) {+ # The names are Local's; the released app's folders are never in this list.+ if ((Find-ReleasedOverlap $d $roots) -or -not (Test-Path -LiteralPath $d)) { continue }+ Remove-Item -LiteralPath $d -Recurse -Force+ Write-Host " removed $d"+ }+} else {+ Write-Host " kept your state: $(Join-Path $env:USERPROFILE $Local.HomeDirName) and $(Join-Path $env:APPDATA $Local.UserDataDirName) (-Purge removes them)"+}+Write-Ok 'Cua Spaces Local is uninstalled.'diff --git a/apps/cua-spaces-desktop/src/channel.ts b/apps/cua-spaces-desktop/src/channel.tsnew file mode 100644index 0000000000..c9b726750e--- /dev/null+++ b/apps/cua-spaces-desktop/src/channel.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The build channel of this app: the released "Cua Spaces", or a locally built+// "Cua Spaces Local" that runs beside it and shares nothing with it (the+// Windows counterpart of the macOS app's CuaChannel::Local; the Rust names are+// libs/cua/crates/cua-home/src/channel.rs's, and test/channel.test.ts keeps+// the ones repeated here in step with it). scripts/install-local.ps1 installs+// the Local one.+//+// A process is Local when CUA_CHANNEL=local, or when its executable is+// `Cua Spaces Local.exe` (what the Local package is named). An unknown+// CUA_CHANNEL value is Stable's, as in Rust, but never silently: the Rust side+// refuses it and the app then fails to start rather than guess.+import * as path from "node:path";++export type ChannelName = "stable" | "local";++export interface Channel {+ name: ChannelName;+ isLocal: boolean;+ appName: string;+ /** The AppUserModelID (Windows groups taskbar buttons and toasts by it), and the Run entry's name. */+ appUserModelId: string;+ /** The URL scheme of the add-machine link: `cua://add/<code>` or `cua-local://add/<code>`. */+ deepLinkScheme: string;+ /** The registry key (HKCU) the app records what it put on PATH under. */+ registryKey: string;+ /** The user data folder's name under %APPDATA%. */+ userDataDirName: string;+ /** The cua home's name under the user's profile (`CUA_HOME` is pinned to it for Local). */+ homeDirName: string;+}++const STABLE: Channel = {+ name: "stable",+ isLocal: false,+ appName: "Cua Spaces",+ appUserModelId: "ai.cua.spaces.desktop",+ deepLinkScheme: "cua",+ registryKey: "Software\\ai.cua.spaces.desktop",+ userDataDirName: "Cua Spaces",+ homeDirName: ".cua",+};++const LOCAL: Channel = {+ name: "local",+ isLocal: true,+ appName: "Cua Spaces Local",+ appUserModelId: "ai.cua.spaces.desktop.local",+ deepLinkScheme: "cua-local",+ registryKey: "Software\\ai.cua.spaces.desktop.local",+ userDataDirName: "Cua Spaces Local",+ homeDirName: ".cua-local",+};++/** The Local package's executable (electron-builder names it after productName). */+export const LOCAL_EXECUTABLE = "cua spaces local.exe";++/** The channel for a `CUA_CHANNEL` value and an executable path (the environment decides first). */+export function resolveChannel(env: NodeJS.ProcessEnv = process.env, execPath: string = process.execPath): Channel {+ const set = env.CUA_CHANNEL?.trim().toLowerCase();+ if (set === "local") return LOCAL;+ if (set === "stable") return STABLE;+ if (set) throw new Error(`CUA_CHANNEL=${JSON.stringify(env.CUA_CHANNEL)} is not a Cua channel (stable or local)`);+ return path.win32.basename(execPath).toLowerCase() === LOCAL_EXECUTABLE ? LOCAL : STABLE;+}++/**+ * Local's cua home, as `CuaChannel::env_home_dir` has it: `~/.cua-local` on+ * staging (Local's default deployment), `~/.cua-local/envs/prod` on the+ * `CUA_ENV=prod` opt-in.+ */+export function localCuaHome(profile: string, env: NodeJS.ProcessEnv = process.env): string {+ const base = path.win32.join(profile, LOCAL.homeDirName);+ return (env.CUA_ENV ?? "").trim().toLowerCase() === "prod" ? path.win32.join(base, "envs", "prod") : base;+}++/** The channel of this process. */+export const channel: Channel = resolveChannel();diff --git a/apps/cua-spaces-desktop/src/deep-link.ts b/apps/cua-spaces-desktop/src/deep-link.tsindex 47a7c31b2f..2a95a045dd 100644--- a/apps/cua-spaces-desktop/src/deep-link.ts+++ b/apps/cua-spaces-desktop/src/deep-link.ts@@ -5,8 +5,10 @@// opened in this app. It brings the app forward on Machines with Join with a// code filled in. It never joins on its own: the page asks first.import { normalizeCode } from "./bridge/join-with-code";+import { channel } from "./channel";-export const DEEP_LINK_SCHEME = "cua";+/** `cua`, or `cua-local` for Cua Spaces Local, which never opens the released app. */+export const DEEP_LINK_SCHEME = channel.deepLinkScheme;/*** The app's route for a `cua://add/<code>[?relay=<url>]` link (alsodiff --git a/apps/cua-spaces-desktop/src/login-item.ts b/apps/cua-spaces-desktop/src/login-item.tsindex abfcfa4009..9e6f2fc4a1 100644--- a/apps/cua-spaces-desktop/src/login-item.ts+++ b/apps/cua-spaces-desktop/src/login-item.ts@@ -12,6 +12,7 @@import { app, shell } from "electron";import * as os from "node:os";import * as path from "node:path";+import { channel } from "./channel";import { LinuxAutostart, type LoginItemControlling, type LoginItemStatus } from "./model/login-item";/** The flag a login launch carries on Windows and Linux. */@@ -41,7 +42,7 @@ class MacLoginItem implements LoginItemControlling {}/** The Run entry's name: the AppUserModelID (main.ts), the name Electron reads `openAtLogin` under whatever `name` it is given. */-export const WINDOWS_RUN_NAME = "ai.cua.spaces.desktop";+export const WINDOWS_RUN_NAME = channel.appUserModelId;/*** What both `setLoginItemSettings` and `getLoginItemSettings` are given ondiff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.tsindex ed77d654b8..46ab382408 100644--- a/apps/cua-spaces-desktop/src/main.ts+++ b/apps/cua-spaces-desktop/src/main.ts@@ -10,6 +10,7 @@ import { initCrashReporting } from "./crash-reporting-main";import { createBridge } from "./bridge";import { hasBrowser } from "./browser";import { appBuild } from "./bundle-version";+import { channel, localCuaHome } from "./channel";import { ELECTRON_EVENT_CHANNEL } from "./channels";import { applyChromiumKeychainSwitches } from "./chromium-keychain";import { installGlobalShortcut, type GlobalShortcut } from "./global-shortcut";@@ -40,8 +41,9 @@ import { applyThemeToWindow, createMainWindow, handleOverlayDim, handleOverlaySuimport { WindowDropTargets, windowNumberOf, type DropWindow } from "./window-drop";// Must match `appId` (Windows; macOS has the Swift app's bundle id) and the-// Linux desktop entry in electron-builder.config.cjs.-const APP_USER_MODEL_ID = "ai.cua.spaces.desktop";+// Linux desktop entry in electron-builder.config.cjs. Cua Spaces Local has its+// own (src/channel.ts, packaging/electron-builder.local.cjs).+const APP_USER_MODEL_ID = channel.appUserModelId;const LINUX_ID = "cua-spaces";/**@@ -51,7 +53,15 @@ const LINUX_ID = "cua-spaces";*/const E2E_DEMO = process.env.CUA_SPACES_E2E_DEMO === "1";-app.setName("Cua Spaces");+if (channel.isLocal) {+ // Cua Spaces Local (a Windows build from scripts/install-local.ps1) shares nothing with the+ // released app: its own cua home, channel (ports, names, sign-in), user data and URL scheme.+ // Set before anything starts, so the native library and every child process inherit them; a+ // variable that is already set wins.+ process.env.CUA_CHANNEL = "local";+ process.env.CUA_HOME ||= localCuaHome(process.env.USERPROFILE || homedir(), process.env);+}+app.setName(channel.appName);// Windows groups taskbar buttons and toasts by this id; the NSIS shortcuts carry the same one.if (process.platform === "win32") app.setAppUserModelId(APP_USER_MODEL_ID);// Linux: WM_CLASS (X11) and the Wayland app id must match the desktop entry's@@ -61,6 +71,7 @@ if (process.platform === "linux") {app.setDesktopName(`${LINUX_ID}.desktop`);}if (process.env.CUA_SPACES_USER_DATA) app.setPath("userData", process.env.CUA_SPACES_USER_DATA);+else if (channel.isLocal) app.setPath("userData", path.join(app.getPath("appData"), channel.userDataDirName));// Crash reporting as early as the app's name and data folder are settled (Sentry keeps its queue// and the Crashpad reports there) and before the native library loads, which reads CUA_CRASH_*.initCrashReporting();diff --git a/apps/cua-spaces-desktop/src/menu.ts b/apps/cua-spaces-desktop/src/menu.tsindex 981d3cddab..1a96f49824 100644--- a/apps/cua-spaces-desktop/src/menu.ts+++ b/apps/cua-spaces-desktop/src/menu.ts@@ -14,6 +14,7 @@// Quit is this app's own item rather than the `quit` role, and the app// registers `ApplePersistenceIgnoreState` as the Swift app does, so macOS// adds no "Quit and Keep Windows" beside it (this app restores no windows).+import { channel } from "./channel";import { app, Menu, shell, systemPreferences, type MenuItemConstructorOptions } from "electron";/** The docs "Cua Spaces Help" opens. */@@ -80,5 +81,5 @@ export function menuTemplate(platform: NodeJS.Platform, actions: MenuActions, {export function installMenu(actions: MenuActions): void {// AppKit offers "Quit and Keep Windows" to apps that restore their windows; this one doesn't.if (process.platform === "darwin") systemPreferences.registerDefaults({ ApplePersistenceIgnoreState: true });- Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate(process.platform, actions, { dev: !app.isPackaged })));+ Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate(process.platform, actions, { dev: !app.isPackaged, appName: channel.appName })));}diff --git a/apps/cua-spaces-desktop/src/model/cli-record.ts b/apps/cua-spaces-desktop/src/model/cli-record.tsindex 4ce74a85f3..e8fbc79c95 100644--- a/apps/cua-spaces-desktop/src/model/cli-record.ts+++ b/apps/cua-spaces-desktop/src/model/cli-record.ts@@ -4,6 +4,8 @@import { execFile } from "node:child_process";import * as path from "node:path";+import { channel } from "../channel";+/*** Windows: the key the uninstaller reads (packaging/installer.nsh) to remove* the `cua` this app put on PATH with the app, and nothing it did not: the@@ -11,7 +13,7 @@ import * as path from "node:path";* Elsewhere the CLI stays, like the user's ~/.cua: the .deb's is a link into* the app that goes with it, as the SwiftUI app's into its bundle.*/-export const WINDOWS_APP_KEY = "HKCU\\Software\\ai.cua.spaces.desktop";+export const WINDOWS_APP_KEY = `HKCU\\${channel.registryKey}`;/** The `reg add` calls that record an installed CLI. */export function cliRecordArgs(target: string, addedToPath: boolean): string[][] {diff --git a/apps/cua-spaces-desktop/src/tray.ts b/apps/cua-spaces-desktop/src/tray.tsindex f5e4100e53..128ddf4389 100644--- a/apps/cua-spaces-desktop/src/tray.ts+++ b/apps/cua-spaces-desktop/src/tray.ts@@ -13,6 +13,7 @@import { app, Menu, nativeImage, nativeTheme, Tray, type MenuItemConstructorOptions } from "electron";import { existsSync } from "node:fs";import * as path from "node:path";+import { channel } from "./channel";let tray: Tray | null = null;let quitting = false;@@ -136,7 +137,7 @@ export function installTray(o: {if (!icon) return;tray = new Tray(trayImage(icon));- tray.setToolTip("Cua Spaces");+ tray.setToolTip(channel.appName);const fallback: TrayMenuItem[] = [{ id: "open", label: "Open Cua Spaces", enabled: true },diff --git a/apps/cua-spaces-desktop/src/window.ts b/apps/cua-spaces-desktop/src/window.tsindex cf4e6ef1b5..91e9d9fede 100644--- a/apps/cua-spaces-desktop/src/window.ts+++ b/apps/cua-spaces-desktop/src/window.ts@@ -5,6 +5,7 @@ import { app, BrowserWindow, ipcMain, screen, shell, type BrowserWindowConstructimport { existsSync, writeFileSync } from "node:fs";import * as path from "node:path";import { captureRoutes } from "./capture";+import { channel } from "./channel";import { opensOutside } from "./external-url";import { windowIconPath } from "./icon";import { APP_ORIGIN } from "./protocol";@@ -228,7 +229,9 @@ export function appWindow(options: BrowserWindowConstructorOptions): BrowserWind* itself): the saved bounds are neither used nor overwritten. */export function createMainWindow({ demo = false, remember = true }: { demo?: boolean; remember?: boolean } = {}): BrowserWindow {const bounds = hidden() ? { ...DEFAULT_SIZE, width: 1440, height: 900 } : remember ? restoredBounds() : { ...DEFAULT_SIZE };- const win = appWindow({ ...bounds, title: "Cua Spaces" });+ const win = appWindow({ ...bounds, title: channel.appName });+ // The page's own <title> is "Cua Spaces": Cua Spaces Local keeps its name, so the two apps differ in the taskbar and Alt+Tab.+ if (channel.isLocal) win.on("page-title-updated", (event) => event.preventDefault());// performance.now() counts from process start.win.once("ready-to-show", () => {diff --git a/apps/cua-spaces-desktop/test/channel.test.ts b/apps/cua-spaces-desktop/test/channel.test.tsnew file mode 100644index 0000000000..ee6d8350c0--- /dev/null+++ b/apps/cua-spaces-desktop/test/channel.test.ts@@ -0,0 +1,59 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The Stable and Local channels (src/channel.ts): which one a process is, and+// that Local shares no name with the released app.+import { readFileSync } from "node:fs";+import * as path from "node:path";+import { describe, expect, it } from "vitest";+import { LOCAL_EXECUTABLE, localCuaHome, resolveChannel } from "../src/channel";++const STABLE_EXE = "C:\\Users\\me\\AppData\\Local\\Programs\\cua-spaces\\Cua Spaces.exe";+const LOCAL_EXE = "C:\\Users\\me\\AppData\\Local\\Programs\\Cua Spaces Local\\Cua Spaces Local.exe";++describe("resolveChannel", () => {+ it("is Stable for the released executable and an empty environment", () => {+ expect(resolveChannel({}, STABLE_EXE).name).toBe("stable");+ });+ it("is Local for the Local executable, whatever the case", () => {+ expect(resolveChannel({}, LOCAL_EXE).isLocal).toBe(true);+ expect(resolveChannel({}, LOCAL_EXE.toUpperCase()).isLocal).toBe(true);+ });+ it("lets CUA_CHANNEL decide first", () => {+ expect(resolveChannel({ CUA_CHANNEL: "local" }, STABLE_EXE).isLocal).toBe(true);+ expect(resolveChannel({ CUA_CHANNEL: " Stable " }, LOCAL_EXE).isLocal).toBe(false);+ });+ it("does not guess at an unknown CUA_CHANNEL", () => {+ expect(() => resolveChannel({ CUA_CHANNEL: "loca1" }, LOCAL_EXE)).toThrow(/not a Cua channel/);+ });+ it("names the Local package's executable", () => {+ expect(LOCAL_EXECUTABLE).toBe("cua spaces local.exe");+ });+});++describe("Local shares nothing with Stable", () => {+ const stable = resolveChannel({}, STABLE_EXE);+ const local = resolveChannel({}, LOCAL_EXE);+ it("has its own names", () => {+ expect(local.appUserModelId).toBe(`${stable.appUserModelId}.local`);+ expect(local.deepLinkScheme).toBe("cua-local");+ for (const key of ["appName", "appUserModelId", "deepLinkScheme", "registryKey", "userDataDirName", "homeDirName"] as const) {+ expect(local[key]).not.toBe(stable[key]);+ }+ });+ it("keeps Stable's names as released", () => {+ expect(stable.registryKey).toBe("Software\\ai.cua.spaces.desktop");+ expect(local.registryKey).toBe("Software\\ai.cua.spaces.desktop.local");+ expect(stable).toMatchObject({ appName: "Cua Spaces", appUserModelId: "ai.cua.spaces.desktop", deepLinkScheme: "cua", homeDirName: ".cua" });+ });+ it("homes on staging in ~/.cua-local and on prod below it, as CuaChannel::Local does", () => {+ expect(localCuaHome("C:\\Users\\me", {})).toBe("C:\\Users\\me\\.cua-local");+ expect(localCuaHome("C:\\Users\\me", { CUA_ENV: "prod" })).toBe("C:\\Users\\me\\.cua-local\\envs\\prod");+ expect(localCuaHome("C:\\Users\\me", { CUA_ENV: "staging" })).toBe("C:\\Users\\me\\.cua-local");+ });+ it("matches the Rust names", () => {+ const rs = readFileSync(path.join(__dirname, "../../../libs/cua/crates/cua-home/src/channel.rs"), "utf8");+ expect(rs).toContain(`"${local.homeDirName}"`);+ expect(rs).toContain(`"${local.deepLinkScheme}"`);+ });+});diff --git a/bin/ci b/bin/ciindex e53a12b8bb..10a1edcca4 100755--- a/bin/ci+++ b/bin/ci@@ -55,6 +55,46 @@ ROOT = Path(os.environ.get("CUA_CI_ROOT") or Path(__file__).resolve().parent.parHOOK_MARKER = "# bin/ci pre-push hook"CHAINED_HOOK = "pre-push.pre-bin-ci"STATUS_CONTEXT = "local-ci"+IS_WINDOWS = os.name == "nt"+++def find_bash() -> str:+ """The bash that runs the checks' commands (they are bash). On Windows that is Git for+ Windows' bash (CUA_CI_BASH overrides it): a bare `bash` there is usually System32\\bash.exe,+ which is WSL and would run the checks inside a Linux distribution."""+ if not IS_WINDOWS:+ return "bash"+ given = os.environ.get("CUA_CI_BASH")+ if given:+ return given+ git = shutil.which("git")+ if git:+ # .../Git/cmd/git.exe, .../Git/bin/git.exe or .../Git/mingw64/bin/git.exe: the Git root is above it.+ for root in list(Path(git).resolve().parents)[:3]:+ for rel in (("bin", "bash.exe"), ("usr", "bin", "bash.exe")):+ candidate = root.joinpath(*rel)+ if candidate.exists():+ return str(candidate)+ sys.exit("bin/ci: needs Git for Windows' bash (install Git for Windows, or set CUA_CI_BASH to its bash.exe); it will not use `bash` from PATH, which may be WSL")+++BASH = find_bash()+_shim_dir: Optional[str] = None+++def python3_shim_dir() -> Optional[str]:+ """Windows: a directory with a `python3` for the checks (Python there is `python`, or the Store stub)."""+ global _shim_dir+ if not IS_WINDOWS:+ return None+ if _shim_dir is None:+ _shim_dir = tempfile.mkdtemp(prefix="bin-ci-shim-")+ exe = Path(sys.executable).as_posix()+ for name in ("python3", "python"):+ with open(os.path.join(_shim_dir, name), "w", newline="\n") as fh:+ fh.write(f'#!/bin/sh\nexec "{exe}" "$@"\n')+ atexit.register(shutil.rmtree, _shim_dir, True)+ return _shim_dir# ---------------------------------------------------------------- model@@ -142,10 +182,10 @@ def disk_free_gb(path: Path) -> float:def dir_size_gb(path: Path) -> float:if not Path(path).exists():return 0.0- out = subprocess.run(["du", "-sk", str(path)], capture_output=True, text=True)try:+ out = subprocess.run(["du", "-sk", str(path)], capture_output=True, text=True)return int(out.stdout.split()[0]) * 1024 / 1e9- except (IndexError, ValueError):+ except (IndexError, ValueError, OSError):total = 0for dp, _, files in os.walk(path):for f in files:@@ -208,6 +248,10 @@ class DiskGuard:def kill_all(self) -> None:with self.lock:procs = list(self.procs.values())+ if IS_WINDOWS:+ for p in procs:+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(p.pid)], capture_output=True)+ returnfor sig in (signal.SIGTERM, signal.SIGKILL):for p in procs:try:@@ -444,7 +488,7 @@ def package_of(path: str) -> Optional[Tuple[str, str]]:text = manifest.read_text(errors="replace")m = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', text, re.M | re.S)if m:- return str(d.relative_to(ROOT)), m.group(1)+ return d.relative_to(ROOT).as_posix(), m.group(1)d = d.parentreturn None@@ -887,7 +931,12 @@ class Context:self.guard: Optional[DiskGuard] = Nonedef env(self) -> Dict[str, str]:- return {**self.lean, **os.environ, **self.rust_env, "CARGO_TARGET_DIR": str(self.target), "CUA_TELEMETRY": "0", "DO_NOT_TRACK": "1"}+ env = {**self.lean, **os.environ, **self.rust_env, "CARGO_TARGET_DIR": str(self.target), "CUA_TELEMETRY": "0", "DO_NOT_TRACK": "1"}+ shim = python3_shim_dir()+ if shim:+ key = next((k for k in env if k.upper() == "PATH"), "PATH")+ env[key] = shim + os.pathsep + env.get(key, "")+ return envdef cleanup_target(self) -> None:if self.guard:@@ -914,8 +963,8 @@ class Context:with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as fh:fh.write("\n".join(changes.files) + "\n")try:- out = subprocess.run(f"{TSX} scripts/docs-generators/runner.ts --changed-files-file {shlex.quote(fh.name)}",- shell=True, cwd=str(ROOT), capture_output=True, text=True, env=self.env())+ out = subprocess.run([BASH, "-c", f"{TSX} scripts/docs-generators/runner.ts --changed-files-file {shlex.quote(Path(fh.name).as_posix())}"],+ cwd=str(ROOT), capture_output=True, text=True, env=self.env())finally:os.unlink(fh.name)if out.returncode != 0:@@ -998,7 +1047,7 @@ class Runner:return f"missing {path}: run {how}"log.write(f"$ {how}\n".encode())log.flush()- rc = subprocess.run(how, shell=True, cwd=str(ROOT), stdout=log, stderr=subprocess.STDOUT, env=self.ctx.env(), executable="/bin/bash").returncode+ rc = subprocess.run([BASH, "-c", how], cwd=str(ROOT), stdout=log, stderr=subprocess.STDOUT, env=self.ctx.env()).returncodeif rc != 0 or not (ROOT / path).exists():return f"could not install {path} ({how}); see the log"return None@@ -1033,8 +1082,8 @@ class Runner:env.setdefault("RUSTUP_HOME", str(real / ".rustup"))home = tempfile.mkdtemp(prefix="bin-ci-home-")env["HOME"] = home- proc = subprocess.Popen(["bash", "-o", "pipefail", "-c", c.cmd], cwd=str(ROOT / c.cwd), stdout=log, stderr=subprocess.STDOUT,- stdin=subprocess.DEVNULL, env=env, start_new_session=True)+ proc = subprocess.Popen([BASH, "-o", "pipefail", "-c", c.cmd], cwd=str(ROOT / c.cwd), stdout=log, stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL, env=env, start_new_session=not IS_WINDOWS)guard = self.ctx.guard if heavy else Noneif guard:guard.register(proc)@@ -1136,7 +1185,7 @@ def apply_fixes(results: List[Result], ctx: Context, logdir: Path) -> List[Resulout.append(r)continueprint(f" {color('fixing', '36')} {r.check.title}: {'; '.join(cmds)}", flush=True)- ok = all(subprocess.run(["bash", "-c", cmd], cwd=str(ROOT), env=ctx.env()).returncode == 0 for cmd in cmds)+ ok = all(subprocess.run([BASH, "-c", cmd], cwd=str(ROOT), env=ctx.env()).returncode == 0 for cmd in cmds)again = Runner(ctx, logdir, quiet=True).run(r.check) if ok else rif again.status == "pass":again.status, again.detail = "fixed", "fixed; review and commit the changes"@@ -1360,6 +1409,10 @@ def raise_open_file_limit(want: int = 65536) -> None:def main(argv: Sequence[str]) -> int:+ if IS_WINDOWS and not sys.flags.utf8_mode:+ # Windows reads files in the ANSI code page by default; the repo is UTF-8. Run again in UTF-8+ # mode (children inherit PYTHONUTF8).+ return subprocess.run([sys.executable, "-X", "utf8", str(Path(__file__).resolve()), *argv], env={**os.environ, "PYTHONUTF8": "1"}).returncodeargs = parse_args(argv)os.chdir(ROOT)raise_open_file_limit()@@ -1408,7 +1461,10 @@ def main(argv: Sequence[str]) -> int:logdir = state_dir() / "logs"for old in logdir.glob("*.log"):- old.unlink()+ try:+ old.unlink()+ except OSError: # Windows: a log another bin/ci run (a test of this one) still has open+ passsweep_stale_targets()atexit.register(ctx.cleanup_target)signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))diff --git a/docs/contributing/CI.md b/docs/contributing/CI.mdindex e58067c862..1a4be145a9 100644--- a/docs/contributing/CI.md+++ b/docs/contributing/CI.md@@ -36,6 +36,15 @@ bin/ci --list # show the plan and the exact commandsbin/ci --only rust-fmt,lockfiles```+### Windows++`bin/ci` runs on Windows from PowerShell, cmd or Git Bash: `python bin\ci --quick` (Python 3.10 or later;+`python3` is not needed). The checks are bash, so it runs them with **Git for Windows' bash**, found next+to `git` (set `CUA_CI_BASH` to another `bash.exe`). It never uses `bash` from `PATH`: there that is usually+`C:\Windows\System32\bash.exe`, which is WSL, and would run the checks inside a Linux distribution.+It runs in UTF-8 mode and gives the checks a `python3`. Cargo checks need the MSVC toolchain; on a shared PC+use `--quick`. The sign-off is the same (`python bin\ci --signoff`; its description ends with `(win32)`).+### Disk safetyHeavy checks (cargo test, clippy, build, cross-target) run one at a time, one crate per cargo call, withdiff --git a/scripts/ci/tests/test_bin_ci.py b/scripts/ci/tests/test_bin_ci.pyindex 3ba2d13ca0..668b537189 100644--- a/scripts/ci/tests/test_bin_ci.py+++ b/scripts/ci/tests/test_bin_ci.py@@ -26,6 +26,11 @@ def load():ci = load()+def sh_script(path):+ """Argv that runs a #!/bin/sh script: Windows cannot execute one, so Git for Windows' bash does."""+ return [ci.BASH, Path(path).as_posix()] if os.name == "nt" else [str(path)]++class FakeContext:"""Routes without cargo or the docs runner."""@@ -195,14 +200,14 @@ class Hook(unittest.TestCase):(self.hooks / "pre-push").write_text("#!/bin/sh\necho guard-ran; exit 3\n")(self.hooks / "pre-push").chmod(0o755)ci.install_hook(force=False)- out = subprocess.run([str(self.hooks / "pre-push"), "origin", "url"], input="refs/heads/x 1 refs/heads/x 0\n",+ out = subprocess.run(sh_script(self.hooks / "pre-push") + ["origin", "url"], input="refs/heads/x 1 refs/heads/x 0\n",capture_output=True, text=True, cwd=self.repo)self.assertEqual(out.returncode, 3)self.assertIn("guard-ran", out.stdout)def test_skip_variable(self):ci.install_hook(force=False)- out = subprocess.run([str(self.hooks / "pre-push"), "origin", "url"], input="", capture_output=True, text=True,+ out = subprocess.run(sh_script(self.hooks / "pre-push") + ["origin", "url"], input="", capture_output=True, text=True,cwd=self.repo, env={**os.environ, "CUA_SKIP_LOCAL_CI": "1"})self.assertEqual(out.returncode, 0)self.assertIn("skipped", out.stderr)diff --git a/scripts/ci/tests/test_bin_ci_disk_guard.py b/scripts/ci/tests/test_bin_ci_disk_guard.pyindex 7fc48b55b3..c891989201 100644--- a/scripts/ci/tests/test_bin_ci_disk_guard.py+++ b/scripts/ci/tests/test_bin_ci_disk_guard.py@@ -132,8 +132,8 @@ class PerCrate(unittest.TestCase):def test_many_run_one_at_a_time_and_fail_if_any_failed(self):cmd = ci.per_crate("cargo test {p}", ["a", "b"], " -- x")self.assertEqual(cmd, "rc=0; cargo test -p a -- x || rc=1; cargo test -p b -- x || rc=1; exit $rc")- self.assertEqual(subprocess.run(["bash", "-c", ci.per_crate("{p}", ["true", "false"]).replace("-p ", "")]).returncode, 1)- self.assertEqual(subprocess.run(["bash", "-c", ci.per_crate("{p}", ["true", "true"]).replace("-p ", "")]).returncode, 0)+ self.assertEqual(subprocess.run([ci.BASH, "-c", ci.per_crate("{p}", ["true", "false"]).replace("-p ", "")]).returncode, 1)+ self.assertEqual(subprocess.run([ci.BASH, "-c", ci.per_crate("{p}", ["true", "true"]).replace("-p ", "")]).returncode, 0)class Plan(unittest.TestCase):diff --git a/scripts/spdx-headers.py b/scripts/spdx-headers.pyindex 725a5c2e0b..e0633f2fd0 100755--- a/scripts/spdx-headers.py+++ b/scripts/spdx-headers.py@@ -190,7 +190,7 @@ def main() -> int:for root in fsl_roots()for path in iter_source_files(root, extensions)if nearest_license_is_fsl(path, cache)- and not str(path.relative_to(REPO)).startswith(HEADER_EXEMPT_DIRS)+ and not path.relative_to(REPO).as_posix().startswith(HEADER_EXEMPT_DIRS)]label = "FSL packages"else:@@ -220,7 +220,7 @@ def main() -> int:continueif (GENERATED_ELSEWHERE.search(path.name)- or str(rel).startswith(GENERATED_DIRS)+ or rel.as_posix().startswith(GENERATED_DIRS)or (args.fsl and foreign_notice(head))):foreign.append(rel)