diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml
index 04885c7..1757cd7 100644
--- a/.github/workflows/dotnet-ci.yml
+++ b/.github/workflows/dotnet-ci.yml
@@ -47,6 +47,7 @@ jobs:
timeout-minutes: 20
env:
SIDEPULSE_NATIVE_VAULT_TESTS: '1'
+ SIDEPULSE_INSTALL_SYSTEM_TESTS: '1'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
@@ -111,18 +112,15 @@ jobs:
foreach ($architecture in @('x64', 'arm64')) {
$rid = "$prefix-$architecture"
$destination = "artifacts/$rid"
- dotnet publish src/SidePulse.Cli -c Release -r $rid --self-contained true -o $destination
+ dotnet publish src/SidePulse.Cli -c Release -r $rid --self-contained true -p:NuGetLockFilePath=obj/packages.publish.lock.json -o $destination
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- Copy-Item LICENSE,NOTICE.md $destination
- Copy-Item -Recurse third-party $destination
- New-Item -ItemType Directory -Force "$destination/third-party/dotnet" | Out-Null
- Copy-Item "$env:DOTNET_ROOT/LICENSE.txt","$env:DOTNET_ROOT/ThirdPartyNotices.txt" "$destination/third-party/dotnet"
- Copy-Item docs/wiki/Getting-Started.md $destination
$version = ([xml](Get-Content src/SidePulse.Cli/SidePulse.Cli.csproj -Raw)).Project.PropertyGroup.Version
python scripts/package_manifest.py $destination $rid $version
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ($rid -eq $native) {
$binary = if ($IsWindows) { 'spn.exe' } else { 'spn' }
+ python scripts/install_smoke.py "$destination/$binary"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
python scripts/cli_smoke.py "$destination/$binary"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
python scripts/animation_smoke.py "$destination/$binary"
diff --git a/Directory.Build.props b/Directory.Build.props
index ce1e686..e920b1d 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -5,6 +5,7 @@
enable
true
true
+ embedded
true
diff --git a/README.md b/README.md
index d8fbc6b..f328678 100644
--- a/README.md
+++ b/README.md
@@ -2,9 +2,10 @@
An unofficial .NET companion for SidePulse, with a Spectre.Console terminal interface.
-**Status: 0.1.0-beta.1 candidate. Feature parity and hardware validation are still in progress.**
+**Status: 0.1.0-beta.2 candidate. Feature parity and hardware validation are still in progress.**
-The command is **`spn`**. See [beta notes and alpha migration](docs/releases/0.1.0-beta.1.md).
+The command is **`spn`**. See [single-file beta notes](docs/releases/0.1.0-beta.2.md)
+and [per-user installation/PATH](docs/wiki/Installation.md).
Start with [Getting started](docs/wiki/Getting-Started.md) for build, USB, phone delivery and Copilot CLI instructions.
diff --git a/docs/releases/0.1.0-beta.2.md b/docs/releases/0.1.0-beta.2.md
new file mode 100644
index 0000000..914a0e9
--- /dev/null
+++ b/docs/releases/0.1.0-beta.2.md
@@ -0,0 +1,38 @@
+# SidePulse.NET 0.1.0-beta.2
+
+Single-file portable executables with per-user installation and optional user PATH setup.
+
+- Each runtime archive contains one self-contained executable plus its small
+ format-2 update manifest. Docs, dependency/runtime licenses and notices are embedded.
+ A copied executable works alone; native runtime libraries can use a per-user cache.
+- `spn install --dry-run`, `spn install`, `spn install --status` and the interactive
+ Settings → Installation screen provide a permanent per-user location without elevation.
+- `--add-to-path` changes only user PATH on Windows. Unix uses a managed user-bin
+ launcher and, when needed, one explicit backed-up Bash/Zsh/sh profile block.
+ Command-name conflicts are refused. Repeated installation is idempotent.
+- New hook and detached-host setup use the stable installed executable. Existing
+ hook files still require explicit uninstall/reinstall; manual edits are preserved.
+- Verified upgrade, startup probe and rollback support the bundle layout.
+ Uninstall removes owned binaries/PATH entries while keeping credentials, settings,
+ user-added files and profile backups. Installed-process removal uses a waiting helper.
+
+## Install or upgrade
+
+Download the matching Windows/Linux/macOS x64 or ARM64 archive and verify
+`SHA256SUMS`. Extract and run `.\spn.exe install --dry-run` (PowerShell) or
+`./spn install --dry-run` (Unix). Apply with `install`, optionally adding
+`--add-to-path`; Unix supports `--shell bash`, `zsh` or `sh`.
+The absolute installed executable works immediately; reopen terminals after PATH setup.
+
+Beta 1's updater does not understand format 2. For that one transition, stop the
+host, download the new executable, and use its installer or a separate permanent
+directory. Existing owned/verified installations can be upgraded with backups;
+unowned destinations and edited files are refused. Alpha's command rename still
+requires the manual integration transition recorded in beta 1's notes.
+
+Use `spn docs --offline` for full installation, PATH ownership and recovery details.
+Hardware/firmware and installed-provider acceptance remain separate from native
+CI. Other architectures are cross-built, and packages remain unsigned. Full saved
+UI preferences and automatic migration of edited integrations remain open.
+
+This candidate remains an unpublished draft until acceptance is reviewed.
diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md
index 1559df5..696c54e 100644
--- a/docs/wiki/Getting-Started.md
+++ b/docs/wiki/Getting-Started.md
@@ -4,15 +4,15 @@
# Getting started with the beta candidate
-The executable is `spn` (`spn.exe` on Windows). Extract the complete platform
-archive into a permanent user-owned directory. Run `.\spn.exe` in PowerShell or
-`./spn` on Unix unless that directory is on PATH. The beta release notes include
-the manual alpha migration; no old-name alias is distributed.
+The executable is `spn` (`spn.exe` on Windows). Run `.\spn.exe` in PowerShell or
+`./spn` on Unix, then optionally `install --dry-run` and `install --add-to-path`.
+Single-file builds contain the runtime, docs and licenses; keep the small manifest
+for portable self-updates, or let install create it. See [[Installation]].
USB/SD writes, iPhone pairing/protected links, shared agent host, animation studio,
managed integrations and a persistent interactive session are implemented.
-Automatic per-user installation/PATH setup, saved UI preferences, remaining
-upstream integrations and physical firmware acceptance remain open.
+Per-user installation and optional PATH setup are available. Saved UI preferences,
+remaining upstream integrations and physical firmware acceptance remain open.
## Build and run
diff --git a/docs/wiki/Installation.md b/docs/wiki/Installation.md
new file mode 100644
index 0000000..87945f6
--- /dev/null
+++ b/docs/wiki/Installation.md
@@ -0,0 +1,100 @@
+# Installation and portable use
+
+`spn` is a self-contained single executable (`spn.exe` on Windows). Copying that
+executable alone is enough for portable use, offline documentation and licenses.
+The release archive also contains `sidepulse-install.json`, a small updater
+manifest. Native .NET libraries can be extracted into the runtime's per-user
+bundle cache; single-file does not mean zero files are ever written.
+
+## Install for this user
+
+```sh
+./spn install --dry-run
+./spn install
+./spn install --status --json
+```
+
+Use `.\spn.exe` in PowerShell. Installation is also available from **Settings →
+Installation** in the interactive session, with a preview and explicit Install action.
+Portable use remains available without running install or changing PATH.
+
+Default binary directories:
+
+| Platform | Location |
+|---|---|
+| Windows | `%LOCALAPPDATA%\Programs\SidePulse.NET\app` |
+| Linux | `~/.local/share/SidePulse.NET/app` |
+| macOS | the current user's local application-data directory, under `SidePulse.NET/app` |
+
+`--directory ` selects another dedicated directory. The default
+requires no administrator privileges. Existing unowned directories, modified
+application files and downgrades are refused. Repeat installation is idempotent.
+An upgrade of a verified owned directory uses a backup, startup probe and rollback.
+Source-directory files outside the package manifest are never copied.
+
+## Optional user PATH
+
+```powershell
+.\spn.exe install --add-to-path --dry-run
+.\spn.exe install --add-to-path
+```
+
+Windows changes **only the user PATH**, preserving existing entries and registry
+value type. It does not copy machine PATH into user PATH. Existing command-name
+conflicts are reported before installation. Restart terminals to pick up the
+changed environment; the installed absolute path works immediately.
+
+On Unix, a managed `~/.local/bin/spn` symlink points at the permanent executable.
+If that directory is already on PATH, no shell profile changes are needed.
+Otherwise choose the shell explicitly or let `SHELL` identify it:
+
+```sh
+./spn install --add-to-path --shell bash --dry-run
+./spn install --add-to-path --shell bash
+```
+
+Supported profiles are `.bashrc` for Bash, `.zshrc` for Zsh, and `.profile` for sh/dash.
+The preview shows the exact file and export block. An original profile gets a
+byte-exact private backup before one marked block is appended. Profile permissions,
+unrelated entries and subsequent edits outside that block are retained. Unknown
+shells require an explicit choice; no profile is guessed or edited silently.
+Open a fresh interactive shell afterward. Login-shell configurations that do not
+source these profiles can use the absolute executable or their own PATH setup.
+
+## Agents, host and existing settings
+
+Stop the shared host before installing/upgrading. Configurations, phone links,
+protected credentials, profiles and IPC identities keep their existing locations.
+After installation, new agent integration and detached-host setup use the stable
+installed absolute executable path, even when invoked from a portable copy.
+
+Existing managed hooks are not overwritten automatically. Preview their removal
+with the old executable, uninstall them using any original `--config` overrides,
+then reinstall using the installed `spn`. Preserve modified files for manual review.
+Restart agents and review their normal trust prompts. Deleting the original
+download directory does not affect newly registered installed hooks.
+
+## Uninstall and recovery
+
+```sh
+spn uninstall --dry-run
+spn uninstall
+```
+
+Remove managed agent integrations first and stop the host. Uninstall checks
+ownership/hashes, removes owned application and PATH/launcher entries, and preserves
+settings, credentials, user-added files and profile backups. A modified launcher
+or PATH block is refused rather than overwritten. No user data deletion option is
+implied by uninstalling the executable.
+
+When invoked from the installed application, a copied helper waits for the
+calling process to exit. Confirmed self-removal closes the interactive session.
+The command reports `scheduled`, not completed; the reported helper workspace
+contains `result.json` after completion and remains available for recovery.
+Removing from another portable copy completes directly. Locked executables or
+permission errors require closing the relevant process/reviewing the reported
+state; no process is forcibly killed. Settings remain available for reinstall.
+
+Installation registration and PATH ownership are stored in `installation.json`
+beside application settings, separate from protected phone credentials. `install
+--status` and `doctor` show installation context without exposing credentials.
diff --git a/docs/wiki/Updating.md b/docs/wiki/Updating.md
index 1e8627d..8a38026 100644
--- a/docs/wiki/Updating.md
+++ b/docs/wiki/Updating.md
@@ -32,9 +32,11 @@ signatures or protection against a compromised publisher account.
Self-update requires a self-contained distribution containing `sidepulse-install.json`.
Source builds, framework-dependent binaries, older previews without that manifest,
modified application files and symlinked installations require manual installation.
-The beta uses `spn` package/executable names. Upgrade from alpha manually using
-the release migration instructions; the old updater is not compatible with this
-rename. Subsequent beta updates retain the verified directory-package format.
+Beta 2 adds single-file manifest format 2, with exactly one owned executable.
+It also reads legacy format-1 directory packages. Beta 1's updater cannot read the
+new format: download the new executable and use `spn install` to adopt/upgrade the
+owned installation, or install into a separate directory. Stop the host first.
+Alpha still requires the manual rename transition described in beta 1's notes.
The install directory and its parent must be writable; the updater
never elevates privileges. Package-manager installations should use that manager.
diff --git a/scripts/install_smoke.py b/scripts/install_smoke.py
new file mode 100644
index 0000000..8c9facb
--- /dev/null
+++ b/scripts/install_smoke.py
@@ -0,0 +1,131 @@
+"""Native single-file installation, PATH ownership and detached uninstall acceptance."""
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+
+def main(executable):
+ source = Path(executable).resolve()
+ if os.name == 'nt' and os.environ.get('SIDEPULSE_INSTALL_SYSTEM_TESTS') != '1':
+ raise RuntimeError('Windows user-PATH smoke requires an isolated CI user and SIDEPULSE_INSTALL_SYSTEM_TESTS=1')
+ with tempfile.TemporaryDirectory(prefix='SidePulse install ü ') as directory:
+ root = Path(directory).resolve()
+ download = root / 'Downloads'
+ download.mkdir()
+ portable = download / source.name
+ shutil.copy2(source, portable) # Deliberately no loose runtime, docs or manifest.
+ target = root / 'Programs' / 'SidePulse ü' / 'app'
+ config = root / 'configuration'
+ env = dict(os.environ, SIDEPULSE_NET_HOME=str(config), DOTNET_BUNDLE_EXTRACT_BASE_DIR=str(root / 'runtime-cache'))
+ original_profile = b'# User settings \xc3\xbc\nexport KEEP=value\n'
+ if os.name != 'nt':
+ env.update(HOME=str(root), SHELL='/bin/bash')
+ profile = root / '.bashrc'
+ profile.write_bytes(original_profile)
+ else:
+ import winreg
+
+ def user_path():
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment') as key:
+ try:
+ return winreg.QueryValueEx(key, 'Path')
+ except FileNotFoundError:
+ return None
+
+ original_path = user_path()
+
+ def run(exe, *args, success=True, extra_env=None):
+ result = subprocess.run([str(exe), *args], text=True, capture_output=True, env=extra_env or env, timeout=45, cwd=root)
+ assert (result.returncode == 0) == success, (args, result.returncode, result.stdout, result.stderr)
+ return result
+
+ expected_version = run(portable, '--version').stdout.strip()
+ docs = json.loads(run(portable, 'docs', '--offline', '--json').stdout)
+ assert any('Beta.md' in name for name in docs)
+ licenses = run(portable, 'about', 'licenses', '--full', '--json').stdout
+ assert '.dotnet.LICENSE.txt' in licenses and '.dotnet.ThirdPartyNotices.txt' in licenses
+ arguments = ['install', '--directory', str(target), '--add-to-path', '--shell', 'bash', '--json']
+ preview = json.loads(run(portable, *arguments, '--dry-run').stdout)
+ assert preview['plan']['Executable'] == str(target / source.name)
+ assert not target.exists() and not config.exists()
+ if os.name != 'nt':
+ assert preview['path']['Profile'] == str(root / '.bashrc')
+ assert profile.read_bytes() == original_profile
+ collision = root / 'conflicting command'
+ collision.mkdir()
+ (collision / source.name).write_text('unrelated application')
+ conflicting_env = dict(env, PATH=str(collision) + os.pathsep + env['PATH'])
+ assert 'Another spn' in run(portable, *arguments, '--dry-run', success=False, extra_env=conflicting_env).stderr
+ assert not target.exists() and not config.exists()
+ run(portable, *arguments)
+ run(portable, *arguments) # Idempotent binary/PATH/profile installation.
+ installed = target / source.name
+ record = json.loads((config / 'installation.json').read_text())
+ assert record['Directory'] == str(target)
+ assert set(path.name for path in target.iterdir()) == {source.name, 'sidepulse-install.json'}
+ manifest = json.loads((target / 'sidepulse-install.json').read_text())
+ assert manifest['Format'] == 2 and len(manifest['Files']) == 1
+ if os.name != 'nt':
+ registration = next(item for item in record['PathEntries'] if item['Kind'] == 'profile')
+ assert Path(registration['Backup']).read_bytes() == original_profile
+ assert profile.read_text().count('# >>> SidePulse.NET PATH >>>') == 1
+ profile.write_bytes(profile.read_bytes() + b'# Added after installation\n')
+ shutil.rmtree(download)
+ unrelated = root / 'unrelated working directory'
+ unrelated.mkdir()
+ fresh_env = dict(env)
+ if os.name == 'nt':
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment') as key:
+ machine_path = winreg.QueryValueEx(key, 'Path')[0]
+ fresh_env['PATH'] = os.path.expandvars(machine_path + ';' + user_path()[0])
+ invocation = [os.environ.get('COMSPEC', r'C:\Windows\System32\cmd.exe'), '/d', '/c', 'spn', '--version']
+ else:
+ invocation = ['/bin/bash', '--noprofile', '--rcfile', str(profile), '-i', '-c', 'spn --version']
+ fresh = subprocess.run(invocation, stdin=subprocess.DEVNULL, capture_output=True, text=True, env=fresh_env, cwd=unrelated, timeout=45)
+ assert fresh.returncode == 0 and fresh.stdout.strip() == expected_version, (fresh.returncode, fresh.stdout, fresh.stderr)
+ run(installed, '--version')
+ assert json.loads(run(installed, 'install', '--status', '--json').stdout)['mode'] == 'installed'
+ run(installed, 'state', 'working', '--dry-run', '--json')
+ plugin = root / 'opencode.js'
+ run(installed, 'agents', 'install', 'opencode', '--config', str(plugin))
+ match = re.search(r'const executable =\s*(".*?");', plugin.read_text())
+ assert json.loads(match.group(1)) == str(installed)
+ run(installed, 'uninstall', success=False) # Hook paths must be removed explicitly.
+ run(installed, 'agents', 'uninstall', 'opencode', '--config', str(plugin))
+ # Unowned files, settings and profiles must survive application removal.
+ (target / 'personal.txt').write_text('keep')
+ (config / 'personal-settings.json').write_text('{"keep":true}')
+ run(installed, 'uninstall', '--dry-run', '--json')
+ scheduled = json.loads(run(installed, 'uninstall', '--json').stdout)
+ job = Path(scheduled['workspace'])
+ deadline = time.monotonic() + 20
+ while time.monotonic() < deadline and not (job / 'result.json').exists():
+ time.sleep(0.1)
+ assert (job / 'result.json').exists(), 'Detached uninstall did not complete'
+ assert not installed.exists() and not (config / 'installation.json').exists()
+ assert (target / 'personal.txt').read_text() == 'keep'
+ assert (config / 'personal-settings.json').exists()
+ if os.name != 'nt':
+ assert profile.read_bytes() == original_profile + b'# Added after installation\n'
+ assert not (root / '.local/bin/spn').exists()
+ assert Path(registration['Backup']).exists()
+ else:
+ assert user_path() == original_path, 'User PATH or its registry type was not restored exactly'
+ # Give the detached Windows helper time to close its executable before cleanup.
+ for attempt in range(100):
+ try:
+ shutil.rmtree(job)
+ break
+ except PermissionError:
+ time.sleep(0.1)
+ print('Single-file offline resources, install/PATH preview, conflicts, idempotence, stable hooks and owned uninstall passed.')
+
+
+if __name__ == '__main__':
+ main(sys.argv[1])
diff --git a/scripts/package_manifest.py b/scripts/package_manifest.py
index fbac505..c1d83f1 100644
--- a/scripts/package_manifest.py
+++ b/scripts/package_manifest.py
@@ -20,7 +20,7 @@ def write(directory, runtime, version):
files.append({'Path': path.relative_to(root).as_posix(),
'Sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
'Mode': path.stat().st_mode & 0o777})
- manifest.write_text(json.dumps({'Format': 1, 'Version': version, 'Runtime': runtime, 'Files': files}, indent=2) + '\n', encoding='utf-8')
+ manifest.write_text(json.dumps({'Format': 2 if len(files) == 1 and files[0]['Path'] == ('spn.exe' if runtime.startswith('win-') else 'spn') else 1, 'Version': version, 'Runtime': runtime, 'Files': files}, indent=2) + '\n', encoding='utf-8')
if __name__ == '__main__':
diff --git a/scripts/tests/test_release.py b/scripts/tests/test_release.py
index 43dbf20..f912f41 100644
--- a/scripts/tests/test_release.py
+++ b/scripts/tests/test_release.py
@@ -13,14 +13,16 @@
class ReleaseTests(unittest.TestCase):
- def packages(self, root, corrupt=False, wrong_version=False):
+ def packages(self, root, corrupt=False, wrong_version=False, single_file=False, hybrid=False):
for platform in ('win', 'linux', 'osx'):
for arch in ('x64', 'arm64'):
runtime = f'{platform}-{arch}'
names = ['spn.exe' if platform == 'win' else 'spn', 'spn.dll',
'hostfxr.dll' if platform == 'win' else 'libhostfxr.dylib' if platform == 'osx' else 'libhostfxr.so']
+ if single_file and not hybrid:
+ names = names[:1]
files = {name: name.encode() for name in names}
- manifest = {'Format': 1, 'Version': '0.1.0-beta.2' if wrong_version else '0.1.0-beta.1',
+ manifest = {'Format': 2 if single_file else 1, 'Version': '0.1.0-beta.2' if wrong_version else '0.1.0-beta.1',
'Runtime': runtime, 'Files': [{'Path': name, 'Sha256': hashlib.sha256(data).hexdigest(), 'Mode': 493} for name, data in files.items()]}
files['sidepulse-install.json'] = json.dumps(manifest).encode()
if corrupt:
@@ -53,6 +55,15 @@ def test_corrupt_package_cannot_become_a_release(self):
with self.assertRaisesRegex(ValueError, 'hash mismatch'):
verify(root, '0.1.0-beta.1')
+ def test_single_file_runtime_set_and_hybrid_rejection(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ self.packages(root, single_file=True)
+ verify(root, '0.1.0-beta.1')
+ self.packages(root, single_file=True, hybrid=True)
+ with self.assertRaisesRegex(ValueError, 'Single-file release contains unexpected'):
+ verify(root, '0.1.0-beta.1')
+
def test_project_and_package_version_must_agree(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
diff --git a/scripts/verify_release.py b/scripts/verify_release.py
index bea7ef6..2f67e03 100644
--- a/scripts/verify_release.py
+++ b/scripts/verify_release.py
@@ -35,7 +35,7 @@ def verify(directory, version):
raise ValueError('Release contains a link or special file')
add(files, item.name.removeprefix('./'), package.extractfile(item).read())
manifest = json.loads(files.pop('sidepulse-install.json'))
- if manifest['Format'] != 1 or manifest['Version'] != version or manifest['Runtime'] != runtime:
+ if manifest['Format'] not in (1, 2) or manifest['Version'] != version or manifest['Runtime'] != runtime:
raise ValueError('Release manifest version, runtime or format mismatch')
entries = manifest['Files']
if len({entry['Path'] for entry in entries}) != len(entries):
@@ -44,6 +44,10 @@ def verify(directory, version):
raise ValueError('Release manifest does not describe the complete archive')
required = {'spn.exe' if platform == 'win' else 'spn', 'spn.dll',
'hostfxr.dll' if platform == 'win' else 'libhostfxr.dylib' if platform == 'osx' else 'libhostfxr.so'}
+ if manifest['Format'] == 2:
+ required = {'spn.exe' if platform == 'win' else 'spn'}
+ if set(files) != required:
+ raise ValueError('Single-file release contains unexpected loose files')
if not required.issubset(files) or any(name in files for name in ('sidepulse-net', 'sidepulse-net.exe', 'sidepulse-net.dll')):
raise ValueError('Release executable/runtime layout is incomplete or contains the removed command')
for entry in entries:
diff --git a/src/SidePulse.Cli/About.cs b/src/SidePulse.Cli/About.cs
index ecb8af6..6f61e31 100644
--- a/src/SidePulse.Cli/About.cs
+++ b/src/SidePulse.Cli/About.cs
@@ -16,6 +16,8 @@ public class AboutSettings : CommandSettings
}
public static class ProjectInfo
{
+ [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("SingleFile", "IL3000", Justification = "An empty location intentionally detects a real published bundle, not a build apphost.")]
+ public static bool IsBundled() => string.IsNullOrEmpty(typeof(ProjectInfo).Assembly.Location);
public const string Website = "https://sidepulse.io/";
public const string Github = "https://github.com/Anheledir/SidePulse.NET";
public const string Upstream = "https://github.com/inteliwear/sidepulse";
@@ -31,6 +33,7 @@ public static IReadOnlyList Dependencies
}
}
public static IReadOnlyList LicenseResources => Assembly.GetManifestResourceNames().Where(n => n.Contains(".Licenses.", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToArray();
+ public static IReadOnlyList DocumentationResources => Assembly.GetManifestResourceNames().Where(n => n.Contains(".Docs.", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToArray();
public static string LicenseText(string name)
{
using var reader = new StreamReader(Assembly.GetManifestResourceStream(name)!); return reader.ReadToEnd();
@@ -73,10 +76,8 @@ public sealed class DocsCommand : Command
public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken)
{
if (!settings.Offline) return ProjectInfo.Link(ProjectInfo.Wiki, settings);
- var directory = Path.Combine(AppContext.BaseDirectory, "docs");
- var files = Directory.Exists(directory) ? Directory.GetFiles(directory, "*.md").Order(StringComparer.Ordinal).ToArray() : [];
- if (files.Length == 0) throw new IOException("Offline documentation is missing from this installation.");
- if (settings.Json) Output.Print(files); else foreach (var file in files) { Console.WriteLine(Path.GetFileName(file)); Console.WriteLine(File.ReadAllText(file)); }
+ var files = ProjectInfo.DocumentationResources;
+ if (settings.Json) Output.Print(files); else foreach (var file in files) { Console.WriteLine(file); Console.WriteLine(ProjectInfo.LicenseText(file)); }
return 0;
}
}
diff --git a/src/SidePulse.Cli/Agents.cs b/src/SidePulse.Cli/Agents.cs
index 9af2e13..83ec447 100644
--- a/src/SidePulse.Cli/Agents.cs
+++ b/src/SidePulse.Cli/Agents.cs
@@ -24,7 +24,7 @@ public sealed class AgentSettings : CommandSettings
[CommandArgument(0, "")]
public AgentProvider Agent { get; init; }
[CommandOption("--exe ")]
- public string Executable { get; init; } = Environment.ProcessPath ?? ApplicationIdentity.Command;
+ public string Executable { get; init; } = SidePulse.Cli.Installation.PreferredExecutable;
[CommandOption("--config ")]
[Description("Explicit provider configuration file; useful for project-scoped or isolated setup.")]
public string? Config { get; init; }
diff --git a/src/SidePulse.Cli/Doctor.cs b/src/SidePulse.Cli/Doctor.cs
index 924888e..3836863 100644
--- a/src/SidePulse.Cli/Doctor.cs
+++ b/src/SidePulse.Cli/Doctor.cs
@@ -23,6 +23,8 @@ public override int Execute(CommandContext context, DoctorSettings settings, Can
new("Platform", "ok", RuntimeInformation.OSDescription)
};
var devices = DeviceTransport.Discover();
+ var installation = UserInstallation.ReadRecord();
+ checks.Add(new("Installation", "info", installation is null ? "Portable. Use install --dry-run to preview per-user installation." : "Managed directory: " + installation.Directory));
checks.Add(new("USB discovery", devices.Count == 0 ? "info" : "ok", $"{devices.Count} mounted device(s). No write was attempted."));
try
{
diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs
index af36916..6fe7927 100644
--- a/src/SidePulse.Cli/Hooks.cs
+++ b/src/SidePulse.Cli/Hooks.cs
@@ -229,7 +229,7 @@ public sealed class HookConfigSettings : CommandSettings
{
[CommandOption("--exe ")]
[Description("Absolute path to a published spn executable.")]
- public string Executable { get; init; } = Environment.ProcessPath ?? ApplicationIdentity.Command;
+ public string Executable { get; init; } = Installation.PreferredExecutable;
[CommandOption("--output ")]
[Description("Create a NEW hook file. Existing files are never overwritten. Otherwise prints JSON.")]
public string? OutputPath { get; init; }
diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs
index ab4325c..03f649a 100644
--- a/src/SidePulse.Cli/HostManagement.cs
+++ b/src/SidePulse.Cli/HostManagement.cs
@@ -69,7 +69,7 @@ public sealed class HostStartSettings : TargetSettings
[CommandOption("--profile ")] public string? Profile { get; init; }
[CommandOption("--model ")] public DeviceModel? Model { get; init; }
[CommandOption("--exe ")]
- public string Executable { get; init; } = Environment.ProcessPath ?? ApplicationIdentity.Command;
+ public string Executable { get; init; } = Installation.PreferredExecutable;
public override ValidationResult Validate()
{
var result = base.Validate();
diff --git a/src/SidePulse.Cli/Installation.cs b/src/SidePulse.Cli/Installation.cs
new file mode 100644
index 0000000..9c7ec94
--- /dev/null
+++ b/src/SidePulse.Cli/Installation.cs
@@ -0,0 +1,202 @@
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Text.Json;
+using SidePulse.Core;
+using Spectre.Console.Cli;
+
+namespace SidePulse.Cli;
+
+public sealed class InstallSettings : CommandSettings
+{
+ [CommandOption("--directory ")] public string? Directory { get; init; }
+ [CommandOption("--add-to-path")]
+ [Description("Register spn in user PATH; on Unix create a user launcher and, when needed, a backed-up shell-profile block.")]
+ public bool AddToPath { get; init; }
+ [CommandOption("--shell ")] public string? Shell { get; init; }
+ [CommandOption("--status")] public bool Status { get; init; }
+ [CommandOption("--dry-run")] public bool DryRun { get; init; }
+ [CommandOption("--json")] public bool Json { get; init; }
+}
+
+public static class Installation
+{
+ public static string PreferredExecutable
+ {
+ get
+ {
+ var record = UserInstallation.ReadRecord();
+ if (record is null) return Environment.ProcessPath ?? ApplicationIdentity.Command;
+ var path = Path.Combine(record.Directory, ApplicationIdentity.CurrentExecutable);
+ if (!File.Exists(path)) throw new IOException("The managed executable is missing. Run install to repair it before registering integrations.");
+ return path;
+ }
+ }
+ public static object Status()
+ {
+ var record = UserInstallation.ReadRecord();
+ var current = Environment.ProcessPath ?? "";
+ var resolved = UserPath.ResolveCommand(Environment.GetEnvironmentVariable("PATH") ?? "");
+ var installed = record is null ? null : Path.Combine(record.Directory, ApplicationIdentity.CurrentExecutable);
+ return new { mode = record is null ? "portable" : "installed", executable = current,
+ directory = record?.Directory, installedExecutable = installed, installedExecutableExists = installed is not null && File.Exists(installed),
+ bundled = ProjectInfo.IsBundled(), pathRegistered = record?.PathEntries.Count > 0,
+ resolvedCommand = resolved, pathEffective = installed is not null && resolved is not null && (resolved.Equals(installed, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) || UserPath.IsOurLink(resolved, installed)),
+ record = UserInstallation.RecordPath, profileBackups = record?.PathEntries.Where(entry => entry.Kind == "profile" && entry.Backup is not null).Select(entry => entry.Backup).ToArray() ?? [] };
+ }
+ public static InstallationManifest SourceManifest()
+ {
+ var exe = HookConfiguration.Executable(Environment.ProcessPath ?? throw new IOException("Executable path is unavailable."));
+ var directory = Path.GetDirectoryName(exe)!;
+ var path = Path.Combine(directory, InstallationManifest.Filename);
+ if (File.Exists(path))
+ {
+ var manifest = InstallationManifest.Read(directory);
+ if (manifest.Version != ProjectInfo.Version || manifest.Runtime != GitHubReleases.RuntimeIdentifier) throw new IOException("Source package version or architecture does not match this executable.");
+ return manifest;
+ }
+ if (!ProjectInfo.IsBundled()) throw new IOException("Install from a published single-file executable or a complete self-contained package with its manifest.");
+ var mode = OperatingSystem.IsWindows() ? 0 : (int)File.GetUnixFileMode(exe);
+ return new(2, ProjectInfo.Version, GitHubReleases.RuntimeIdentifier, [new(ApplicationIdentity.CurrentExecutable, InstallationManifest.Hash(exe), mode)]);
+ }
+ public static async Task RequireStoppedHost(CancellationToken token)
+ {
+ if ((await HostControl.Request("status", token)).Running) throw new IOException("Stop the shared host with spn host stop before installing or uninstalling. Existing integrations keep their paths until explicitly repaired.");
+ }
+ public static void RequireNoManagedHooks()
+ {
+ var directory = Path.Combine(Path.GetDirectoryName(UserInstallation.RecordPath)!, "integrations");
+ if (Directory.Exists(directory) && Directory.EnumerateFiles(directory, "*.json").Any())
+ throw new IOException("Remove managed agent integrations with agents uninstall (including any --config overrides) before uninstalling the application. Provider settings and unrelated hooks are not removed automatically.");
+ }
+ public static void Print(bool json, object value, string text) { if (json) Output.Print(value); else Console.WriteLine(text); }
+}
+
+public sealed class InstallCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, InstallSettings settings, CancellationToken token)
+ {
+ if (settings.Status) { var status = Installation.Status(); Installation.Print(settings.Json, status, JsonSerializer.Serialize(status, Output.Json)); return 0; }
+ var manifest = Installation.SourceManifest();
+ var directory = Path.GetFullPath(settings.Directory ?? UserInstallation.DefaultDirectory);
+ var plan = UserInstallation.Plan(Path.GetDirectoryName(Environment.ProcessPath!)!, directory, manifest);
+ directory = plan.Destination;
+ var record = UserInstallation.ReadRecord();
+ if (record is not null && !Path.GetFullPath(record.Directory).Equals(directory, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
+ throw new IOException("A different managed installation is registered. Uninstall it before changing the installation directory.");
+ UserPathPlan? pathPlan = null;
+ var entries = record?.PathEntries ?? [];
+ if (settings.AddToPath)
+ {
+ if (entries.Count > 0) { UserPath.ValidateRemoval(entries); UserPath.CheckConflict(directory); }
+ else pathPlan = UserPath.Plan(directory, settings.Shell);
+ }
+ var preview = new { state = settings.DryRun ? "planned" : "installed", plan, path = pathPlan, existingPathEntries = entries,
+ restartTerminal = settings.AddToPath, preservesUserSettings = true };
+ if (settings.DryRun)
+ {
+ Installation.Print(settings.Json, preview, $"Install {plan.Version} into {directory}\nExecutable: {plan.Executable}\n" + (pathPlan?.Profile is { } profile ? $"PATH profile: {profile}\n{pathPlan.Block}" : settings.AddToPath ? "Register user PATH/launcher. Reopen terminals afterward." : "No PATH or shell-profile changes."));
+ return 0;
+ }
+ if (!plan.AlreadyInstalled) await Installation.RequireStoppedHost(token);
+ await UserInstallation.Install(plan, manifest, (path, cancellation) => Updater.Probe(path, manifest.Version, cancellation), token);
+ // Record the usable binary before optional PATH changes. A PATH failure is
+ // recoverable by rerunning install --add-to-path; credentials are separate.
+ UserInstallation.SaveRecord(new(1, directory, entries));
+ if (pathPlan is not null)
+ {
+ entries = UserPath.Apply(pathPlan);
+ try { UserInstallation.SaveRecord(new(1, directory, entries)); }
+ catch { UserPath.Remove(entries); throw; }
+ }
+ else if (settings.AddToPath && entries.Count > 0) UserPath.Repair(entries);
+ Installation.Print(settings.Json, new { state = plan.AlreadyInstalled ? "already-installed" : "installed", executable = plan.Executable, directory, pathRegistered = entries.Count > 0, restartTerminal = settings.AddToPath },
+ $"Installed: {plan.Executable}\n" + (settings.AddToPath ? "User PATH/launcher configured. Reopen terminals; use the absolute executable immediately." : "PATH was not changed.") + "\nPhone links and settings are preserved. Install integrations from this permanent executable path.");
+ return 0;
+ }
+}
+
+public sealed class UninstallSettings : CommandSettings
+{
+ [CommandOption("--dry-run")] public bool DryRun { get; init; }
+ [CommandOption("--json")] public bool Json { get; init; }
+}
+public sealed record UninstallPlan(string RecordPath, string RecordHash, UserInstallRecord Record, int ParentId, long ParentStartTicks);
+public sealed class UninstallCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, UninstallSettings settings, CancellationToken token)
+ {
+ var record = UserInstallation.ReadRecord();
+ if (record is null) { Installation.Print(settings.Json, new { state = "not-installed" }, "No managed installation is registered."); return 0; }
+ UserInstallation.ValidateRemoval(record);
+ Installation.RequireNoManagedHooks();
+ if (settings.DryRun)
+ {
+ Installation.Print(settings.Json, new { state = "planned", directory = record.Directory, removePathEntries = record.PathEntries, preservesUserSettings = true },
+ $"Remove owned application files from {record.Directory} and its managed PATH/launcher entries. Settings, phone links, user-added files and profile backups remain.");
+ return 0;
+ }
+ await Installation.RequireStoppedHost(token);
+ var currentDirectory = Path.GetDirectoryName(Environment.ProcessPath!);
+ if (!string.Equals(currentDirectory, record.Directory, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
+ {
+ UserInstallation.Remove(record);
+ Installation.Print(settings.Json, new { state = "removed" }, "Application and owned PATH entries removed. Settings and phone links retained."); return 0;
+ }
+ var job = Path.Combine(Path.GetDirectoryName(UserInstallation.RecordPath)!, "uninstall-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(job);
+ var manifest = InstallationManifest.Read(record.Directory);
+ foreach (var file in manifest.Files)
+ {
+ var path = InstallationManifest.Resolve(job, file.Path);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ File.Copy(InstallationManifest.Resolve(record.Directory, file.Path), path);
+ if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, (UnixFileMode)file.Mode);
+ }
+ File.Copy(Path.Combine(record.Directory, InstallationManifest.Filename), Path.Combine(job, InstallationManifest.Filename));
+ using var parent = Process.GetCurrentProcess();
+ var plan = new UninstallPlan(UserInstallation.RecordPath, InstallationManifest.Hash(UserInstallation.RecordPath), record, parent.Id, parent.StartTime.ToUniversalTime().Ticks);
+ var planPath = Path.Combine(job, "uninstall.json");
+ UserInstallation.AtomicWrite(planPath, JsonSerializer.SerializeToUtf8Bytes(plan, InstallationManifest.Json));
+ var start = new ProcessStartInfo(Path.Combine(job, ApplicationIdentity.CurrentExecutable)) { UseShellExecute = OperatingSystem.IsWindows(), CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden,
+ RedirectStandardInput = !OperatingSystem.IsWindows(), RedirectStandardOutput = !OperatingSystem.IsWindows(), RedirectStandardError = !OperatingSystem.IsWindows(), WorkingDirectory = job };
+ foreach (var argument in new[] { "internal-uninstall", "--plan", planPath }) start.ArgumentList.Add(argument);
+ using var helper = Process.Start(start) ?? throw new IOException("Could not start uninstall helper. The installation was preserved.");
+ if (!OperatingSystem.IsWindows()) helper.StandardInput.Close();
+ Installation.Print(settings.Json, new { state = "scheduled", workspace = job }, "Uninstall scheduled after this process exits. Settings and phone links are retained; the helper workspace remains for recovery.");
+ return 0;
+ }
+}
+public sealed class InternalUninstallSettings : CommandSettings
+{
+ [CommandOption("--plan ")] public string Plan { get; init; } = "";
+}
+public sealed class InternalUninstallCommand : AsyncCommand
+{
+ public override async Task ExecuteAsync(CommandContext context, InternalUninstallSettings settings, CancellationToken token)
+ {
+ if (!OperatingSystem.IsWindows()) HostLogs.Detach();
+ var plan = JsonSerializer.Deserialize(await File.ReadAllTextAsync(settings.Plan, token), InstallationManifest.Json) ?? throw new IOException("Invalid uninstall plan.");
+ var job = Path.GetDirectoryName(Environment.ProcessPath!)!;
+ if (Path.GetFullPath(settings.Plan) != Path.Combine(job, "uninstall.json") || Path.GetDirectoryName(job) != Path.GetDirectoryName(UserInstallation.RecordPath) || !Path.GetFileName(job).StartsWith("uninstall-", StringComparison.Ordinal)
+ || plan.RecordPath != UserInstallation.RecordPath || job == plan.Record.Directory) throw new IOException("Uninstall helpers must run from their private prepared workspace.");
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); deadline.CancelAfter(TimeSpan.FromSeconds(60));
+ try
+ {
+ using var parent = Process.GetProcessById(plan.ParentId);
+ if (parent.StartTime.ToUniversalTime().Ticks == plan.ParentStartTicks) await parent.WaitForExitAsync(deadline.Token);
+ }
+ catch (ArgumentException) { }
+ if (InstallationManifest.Hash(plan.RecordPath) != plan.RecordHash) throw new IOException("Installation registration changed. Uninstall refused.");
+ try
+ {
+ UserInstallation.Remove(UserInstallation.ReadRecord() ?? throw new IOException("Installation record is missing."));
+ UserInstallation.AtomicWrite(Path.Combine(job, "result.json"), JsonSerializer.SerializeToUtf8Bytes(new { state = "removed" }));
+ return 0;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ UserInstallation.AtomicWrite(Path.Combine(job, "result.json"), JsonSerializer.SerializeToUtf8Bytes(new { state = "failed", error = ex.Message, recoveryPackage = job }));
+ return 1;
+ }
+ }
+}
diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs
index ddfe613..8532afc 100644
--- a/src/SidePulse.Cli/Program.cs
+++ b/src/SidePulse.Cli/Program.cs
@@ -26,6 +26,9 @@ static string[] Normalize(string[] command)
config.ConfigureConsole(AnsiConsole.Console);
config.SetApplicationName(ApplicationIdentity.Command);
config.SetApplicationVersion(ProjectInfo.Version);
+ config.AddCommand("install").WithDescription("Install for this user; optionally configure user PATH.");
+ config.AddCommand("uninstall").WithDescription("Remove the managed installation while retaining settings and phone links.");
+ config.AddCommand("internal-uninstall").IsHidden();
config.AddBranch("animations", animations =>
{
animations.SetDescription("Create, validate, preview and send Dot / Pro LED patterns.");
diff --git a/src/SidePulse.Cli/ShellSession.cs b/src/SidePulse.Cli/ShellSession.cs
index 88a4be9..c923e01 100644
--- a/src/SidePulse.Cli/ShellSession.cs
+++ b/src/SidePulse.Cli/ShellSession.cs
@@ -52,11 +52,29 @@ public int Run(string[] args)
}
if (section == "Settings")
{
- var action = Interactive.Choose(section, [new("Diagnostics", ["doctor"]), new("Updates"), new("Profiles"), new("Back")]);
+ var action = Interactive.Choose(section, [new("Diagnostics", ["doctor"]), new("Installation"), new("Updates"), new("Profiles"), new("Back")]);
if (action is null || action.Label == "Back") { section = Back(); continue; }
if (action.Arguments is { } command) RunCommand(command); else { parents.Push(section); section = action.Label.ToLowerInvariant(); }
continue;
}
+ if (section == "installation")
+ {
+ var action = Interactive.Choose("Installation", [new("Status", ["install", "--status"]), new("Install for this user"), new("Uninstall"), new("Back")]);
+ if (action is null || action.Label == "Back") { section = Back(); continue; }
+ if (action.Arguments is { } direct) { RunCommand(direct); continue; }
+ var command = new List { action.Label == "Uninstall" ? "uninstall" : "install" };
+ if (command[0] == "install" && AnsiConsole.Confirm("Add spn to your user PATH? The preview shows any shell-profile changes.", false)) command.Add("--add-to-path");
+ if (RunCommand([.. command, "--dry-run"]) != 0) continue;
+ var apply = Interactive.Choose("Review installation changes", [new(command[0] == "install" ? "Install" : "Remove"), new("Back")]);
+ if (apply is not null && apply.Label != "Back")
+ {
+ var installedDirectory = UserInstallation.ReadRecord()?.Directory;
+ var removingThisSession = command[0] == "uninstall" && installedDirectory is not null
+ && installedDirectory.Equals(Path.GetDirectoryName(Environment.ProcessPath), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
+ if (RunCommand(command.ToArray()) == 0 && removingThisSession) return 0;
+ }
+ continue;
+ }
var group = section switch { "Animations" => "animations", "Help & about" => "about", _ => section };
var next = Interactive.Build(group);
if (next is null) section = Back(); else RunCommand(next);
@@ -113,7 +131,7 @@ private void SendState()
}
}
- private void RunCommand(string[] args)
+ private int RunCommand(string[] args)
{
using var cancellation = new CancellationTokenSource();
ConsoleCancelEventHandler cancel = (_, input) => { input.Cancel = true; cancellation.Cancel(); };
@@ -123,8 +141,9 @@ private void RunCommand(string[] args)
var result = execute(args, cancellation.Token);
recent = result == 0 ? "Completed: " + string.Join(' ', args.Take(2)) : "Action failed. Correct the input or output and retry.";
Console.WriteLine(recent);
+ return result;
}
- catch (OperationCanceledException) { recent = "Cancelled."; Console.WriteLine(recent); }
+ catch (OperationCanceledException) { recent = "Cancelled."; Console.WriteLine(recent); return 1; }
finally { Console.CancelKeyPress -= cancel; }
}
}
diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj
index abb0111..b1b6bcf 100644
--- a/src/SidePulse.Cli/SidePulse.Cli.csproj
+++ b/src/SidePulse.Cli/SidePulse.Cli.csproj
@@ -2,7 +2,10 @@
Exe
spn
- 0.1.0-beta.1
+ 0.1.0-beta.2
+ true
+ true
+ embedded
Unofficial SidePulse companion
MIT
@@ -17,9 +20,9 @@
-
-
-
-
+
+
+
+
diff --git a/src/SidePulse.Core/UpdatePackage.cs b/src/SidePulse.Core/UpdatePackage.cs
index f46aaad..50966f4 100644
--- a/src/SidePulse.Core/UpdatePackage.cs
+++ b/src/SidePulse.Core/UpdatePackage.cs
@@ -24,7 +24,7 @@ public static InstallationManifest Read(string directory)
if (!File.Exists(path) || new FileInfo(path).Length > 4 * 1024 * 1024) throw new IOException("This installation has no supported update manifest. Install a current self-contained preview/release manually first.");
var manifest = JsonSerializer.Deserialize(File.ReadAllText(path), Json) ?? throw new IOException("Invalid installation manifest.");
_ = new ReleaseVersion(manifest.Version);
- if (manifest.Format != 1 || manifest.Runtime is not ("win-x64" or "win-arm64" or "osx-x64" or "osx-arm64" or "linux-x64" or "linux-arm64") || manifest.Files is null || manifest.Files.Count is < 1 or > 10000) throw new IOException("Invalid installation manifest.");
+ if (manifest.Format is not (1 or 2) || manifest.Runtime is not ("win-x64" or "win-arm64" or "osx-x64" or "osx-arm64" or "linux-x64" or "linux-arm64") || manifest.Files is null || manifest.Files.Count is < 1 or > 10000) throw new IOException("Invalid installation manifest.");
var names = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var file in manifest.Files)
{
@@ -32,7 +32,11 @@ public static InstallationManifest Read(string directory)
if (file.Path.Equals(Filename, StringComparison.OrdinalIgnoreCase) || !names.Add(file.Path) || !Regex.IsMatch(file.Sha256, "^[0-9a-fA-F]{64}$", RegexOptions.CultureInvariant) || file.Mode is < 0 or > 511) throw new IOException("Invalid installation file entry.");
}
var exe = ApplicationIdentity.Executable(manifest.Runtime.StartsWith("win-", StringComparison.Ordinal));
- if (!names.Contains(exe) || !names.Contains(ApplicationIdentity.Assembly) || !names.Contains(manifest.Runtime.StartsWith("win-", StringComparison.Ordinal) ? "hostfxr.dll" : manifest.Runtime.StartsWith("osx-", StringComparison.Ordinal) ? "libhostfxr.dylib" : "libhostfxr.so")) throw new IOException("Self-update requires a complete self-contained application package.");
+ if (manifest.Format == 2)
+ {
+ if (names.Count != 1 || !names.Contains(exe)) throw new IOException("A single-file package must contain exactly its executable.");
+ }
+ else if (!names.Contains(exe) || !names.Contains(ApplicationIdentity.Assembly) || !names.Contains(manifest.Runtime.StartsWith("win-", StringComparison.Ordinal) ? "hostfxr.dll" : manifest.Runtime.StartsWith("osx-", StringComparison.Ordinal) ? "libhostfxr.dylib" : "libhostfxr.so")) throw new IOException("Self-update requires a complete self-contained application package.");
return manifest;
}
public void Verify(string directory, bool rejectExtras)
diff --git a/src/SidePulse.Core/UserInstallation.cs b/src/SidePulse.Core/UserInstallation.cs
new file mode 100644
index 0000000..76d7245
--- /dev/null
+++ b/src/SidePulse.Core/UserInstallation.cs
@@ -0,0 +1,143 @@
+using System.Text.Json;
+
+namespace SidePulse.Core;
+
+public sealed record PathRegistration(string Kind, string Location, string Value, string? Backup = null);
+public sealed record UserInstallRecord(int Format, string Directory, IReadOnlyList PathEntries);
+public sealed record InstallPlan(string Source, string Destination, string Executable, string Version, string Runtime, bool AlreadyInstalled);
+
+public static class UserInstallation
+{
+ public static string RecordPath => Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "installation.json");
+ public static string DefaultDirectory => OperatingSystem.IsWindows()
+ ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "SidePulse.NET", "app")
+ : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SidePulse.NET", "app");
+ public static string UserBin => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "bin");
+ public static UserInstallRecord? ReadRecord(string? path = null)
+ {
+ path ??= RecordPath;
+ if (!File.Exists(path)) return null;
+ if (new FileInfo(path).Length > 65536) throw new IOException("Installation record is too large. Existing files were preserved.");
+ var record = JsonSerializer.Deserialize(File.ReadAllText(path), InstallationManifest.Json);
+ if (record is null || record.Format != 1 || !Path.IsPathFullyQualified(record.Directory) || record.PathEntries is null || record.PathEntries.Count > 3)
+ throw new IOException("Installation record is invalid. Existing files were preserved.");
+ _ = Target(record.Directory);
+ UserPath.ValidateRecord(record);
+ return record;
+ }
+ public static void SaveRecord(UserInstallRecord record, string? path = null)
+ {
+ path ??= RecordPath;
+ if (OperatingSystem.IsWindows()) Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ else Directory.CreateDirectory(Path.GetDirectoryName(path)!, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ AtomicWrite(path, System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(record, InstallationManifest.Json));
+ }
+ public static void AtomicWrite(string path, byte[] bytes)
+ {
+ var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
+ try
+ {
+ var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None };
+ if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
+ using (var stream = new FileStream(temporary, options)) { stream.Write(bytes); stream.Flush(true); }
+ File.Move(temporary, path, true);
+ }
+ finally { if (File.Exists(temporary)) File.Delete(temporary); }
+ }
+ private static string Target(string directory)
+ {
+ var full = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar);
+ if (string.IsNullOrEmpty(full) || full == Path.GetPathRoot(full) || full == Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
+ throw new IOException("Choose a dedicated application directory, not a filesystem root or home directory.");
+ if (Directory.Exists(full) && (File.GetAttributes(full) & FileAttributes.ReparsePoint) != 0) throw new IOException("Installation directory cannot be a symbolic link.");
+ return full;
+ }
+ public static InstallPlan Plan(string source, string destination, InstallationManifest manifest)
+ {
+ source = Path.GetFullPath(source); destination = Target(destination);
+ var executable = ApplicationIdentity.Executable(manifest.Runtime.StartsWith("win-", StringComparison.Ordinal));
+ foreach (var file in manifest.Files)
+ {
+ var path = InstallationManifest.Resolve(source, file.Path);
+ if (!File.Exists(path) || (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0 || InstallationManifest.Hash(path) != file.Sha256.ToUpperInvariant())
+ throw new IOException("Source package verification failed: " + file.Path);
+ }
+ var same = false;
+ if (Directory.Exists(destination))
+ {
+ var installed = InstallationManifest.Read(destination);
+ installed.Verify(destination, false);
+ if (installed.Runtime != manifest.Runtime) throw new IOException("The installed architecture differs. Choose a different directory.");
+ if (new ReleaseVersion(installed.Version).CompareTo(new(manifest.Version)) > 0) throw new IOException("Installation would downgrade an existing version.");
+ same = installed.Version == manifest.Version && installed.Format == manifest.Format && installed.Files.Count == manifest.Files.Count
+ && installed.Files.Zip(manifest.Files).All(pair => pair.First.Path == pair.Second.Path && pair.First.Sha256.Equals(pair.Second.Sha256, StringComparison.OrdinalIgnoreCase)
+ && (manifest.Runtime.StartsWith("win-", StringComparison.Ordinal) || pair.First.Mode == pair.Second.Mode));
+ if (installed.Version == manifest.Version && !same) throw new IOException("An existing installation has different contents at the same version. It was preserved.");
+ }
+ else if (File.Exists(destination)) throw new IOException("Installation destination is an existing file.");
+ return new(source, destination, Path.Combine(destination, executable), manifest.Version, manifest.Runtime, same);
+ }
+ public static async Task Install(InstallPlan plan, InstallationManifest manifest, Func probe, CancellationToken token = default)
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(plan.Destination)!);
+ using var gate = UpdateTransaction.Lock(plan.Destination);
+ // Recheck under the shared installation/update lock before writing anything.
+ if (Plan(plan.Source, plan.Destination, manifest).AlreadyInstalled) return;
+ var job = Path.Combine(Path.GetDirectoryName(plan.Destination)!, ".sidepulse-update-install-" + Guid.NewGuid().ToString("N"));
+ var stage = Path.Combine(job, "stage");
+ if (OperatingSystem.IsWindows()) Directory.CreateDirectory(stage);
+ else Directory.CreateDirectory(stage, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ UpdatePlan? update = null;
+ try
+ {
+ foreach (var file in manifest.Files)
+ {
+ token.ThrowIfCancellationRequested();
+ var target = InstallationManifest.Resolve(stage, file.Path);
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ File.Copy(InstallationManifest.Resolve(plan.Source, file.Path), target);
+ if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(target, (UnixFileMode)file.Mode);
+ }
+ AtomicWrite(Path.Combine(stage, InstallationManifest.Filename), JsonSerializer.SerializeToUtf8Bytes(manifest, InstallationManifest.Json));
+ _ = InstallationManifest.Read(stage);
+ manifest.Verify(stage, true);
+ if (Directory.Exists(plan.Destination))
+ {
+ update = UpdateTransaction.Prepare(plan.Destination, stage, job, manifest.Version, manifest.Runtime, 0, 0);
+ // Apply takes the same cross-process lock. Release ours immediately before it.
+ gate.Dispose();
+ await UpdateTransaction.Apply(update, probe, token);
+ }
+ else
+ {
+ await probe(stage, token);
+ Directory.Move(stage, plan.Destination);
+ }
+ }
+ finally { if (update is null && Directory.Exists(job)) Directory.Delete(job, true); }
+ }
+ public static void ValidateRemoval(UserInstallRecord record)
+ {
+ _ = Target(record.Directory);
+ var manifest = InstallationManifest.Read(record.Directory);
+ manifest.Verify(record.Directory, false);
+ UserPath.ValidateRemoval(record.PathEntries);
+ }
+ public static void Remove(UserInstallRecord record, string? recordPath = null)
+ {
+ ValidateRemoval(record);
+ using var gate = UpdateTransaction.Lock(record.Directory);
+ ValidateRemoval(record);
+ UserPath.Remove(record.PathEntries);
+ var manifest = InstallationManifest.Read(record.Directory);
+ foreach (var file in manifest.Files) File.Delete(InstallationManifest.Resolve(record.Directory, file.Path));
+ File.Delete(Path.Combine(record.Directory, InstallationManifest.Filename));
+ var ownedDirectories = new HashSet();
+ foreach (var file in manifest.Files)
+ for (var parent = Path.GetDirectoryName(InstallationManifest.Resolve(record.Directory, file.Path)); parent is not null && parent != record.Directory; parent = Path.GetDirectoryName(parent)) ownedDirectories.Add(parent);
+ foreach (var directory in ownedDirectories.OrderByDescending(value => value.Length))
+ if (!Directory.EnumerateFileSystemEntries(directory).Any()) Directory.Delete(directory);
+ if (!Directory.EnumerateFileSystemEntries(record.Directory).Any()) Directory.Delete(record.Directory);
+ File.Delete(recordPath ?? RecordPath);
+ }
+}
diff --git a/src/SidePulse.Core/UserPath.cs b/src/SidePulse.Core/UserPath.cs
new file mode 100644
index 0000000..791c9c3
--- /dev/null
+++ b/src/SidePulse.Core/UserPath.cs
@@ -0,0 +1,203 @@
+using System.Runtime.Versioning;
+using System.Text;
+using Microsoft.Win32;
+using System.Runtime.InteropServices;
+
+namespace SidePulse.Core;
+
+public sealed record UserPathPlan(string Directory, string Executable, string? Launcher, string? Profile, string? Block, bool AlreadyOnPath);
+
+public static class UserPath
+{
+ private static string Block(string bin) => "\n# >>> SidePulse.NET PATH >>>\nexport PATH='" + bin.Replace("'", "'\"'\"'") + "':\"$PATH\"\n# <<< SidePulse.NET PATH <<<\n";
+ public static void ValidateRecord(UserInstallRecord record)
+ {
+ var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
+ var executable = Path.Combine(record.Directory, ApplicationIdentity.CurrentExecutable);
+ foreach (var entry in record.PathEntries)
+ {
+ var valid = entry.Kind switch
+ {
+ "windows-path" => OperatingSystem.IsWindows() && entry.Location == "HKCU/Environment/Path" && entry.Value == record.Directory && entry.Backup is null or "absent",
+ "launcher" => !OperatingSystem.IsWindows() && entry.Location == Path.Combine(UserInstallation.UserBin, "spn") && entry.Value == executable && entry.Backup is null,
+ "profile" => !OperatingSystem.IsWindows() && new[] { ".bashrc", ".zshrc", ".profile" }.Any(name => entry.Location == Path.Combine(home, name))
+ && entry.Value == Block(UserInstallation.UserBin) && (entry.Backup is null || entry.Backup.StartsWith(entry.Location + ".sidepulse-path-", StringComparison.Ordinal) && entry.Backup.EndsWith(".bak", StringComparison.Ordinal)),
+ _ => false
+ };
+ if (!valid) throw new IOException("Installation PATH ownership record is invalid. Existing files were preserved.");
+ }
+ }
+ public static bool Contains(string path, string directory) => path.Split(Path.PathSeparator).Any(entry => SamePath(entry.Trim().Trim('"'), directory));
+ private static bool SamePath(string first, string second)
+ {
+ if (string.IsNullOrWhiteSpace(first)) return false;
+ try { return Path.GetFullPath(Environment.ExpandEnvironmentVariables(first)).TrimEnd(Path.DirectorySeparatorChar).Equals(Path.GetFullPath(second).TrimEnd(Path.DirectorySeparatorChar), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException) { return false; }
+ }
+ public static string? ResolveCommand(string searchPath)
+ {
+ var names = OperatingSystem.IsWindows()
+ ? (Environment.GetEnvironmentVariable("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").Split(';').Where(extension => extension.StartsWith('.') && extension.IndexOfAny(['/', '\\', ':', '\r', '\n']) < 0)
+ .Concat([".exe", ".ps1"]).Distinct(StringComparer.OrdinalIgnoreCase).Select(extension => "spn" + extension).ToArray()
+ : new[] { ApplicationIdentity.CurrentExecutable };
+ foreach (var entry in searchPath.Split(Path.PathSeparator))
+ {
+ if (string.IsNullOrWhiteSpace(entry)) continue;
+ foreach (var name in names)
+ {
+ var candidate = Path.Combine(entry.Trim('"'), name);
+ if (File.Exists(candidate)) return Path.GetFullPath(candidate);
+ }
+ }
+ return null;
+ }
+ public static void CheckConflict(string directory, string? searchPath = null)
+ {
+ var executable = Path.Combine(directory, ApplicationIdentity.CurrentExecutable);
+ var current = ResolveCommand(searchPath ?? Environment.GetEnvironmentVariable("PATH") ?? "");
+ if (current is not null && !SamePath(current, executable) && !IsOurLink(current, executable))
+ throw new IOException("Another spn resolves first on PATH: " + current + ". Resolve that conflict before registering this installation.");
+ }
+ public static UserPathPlan Plan(string directory, string? shell, string? userBin = null, string? home = null, string? searchPath = null)
+ {
+ home ??= Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
+ searchPath ??= Environment.GetEnvironmentVariable("PATH") ?? "";
+ var executable = Path.Combine(directory, ApplicationIdentity.CurrentExecutable);
+ var bin = OperatingSystem.IsWindows() ? directory : userBin ?? UserInstallation.UserBin;
+ if (bin.IndexOfAny(['\r', '\n', '\0', Path.PathSeparator]) >= 0) throw new IOException("The installation/PATH directory cannot contain a newline or PATH separator.");
+ var launcher = OperatingSystem.IsWindows() ? null : Path.Combine(bin, ApplicationIdentity.Command);
+ var current = ResolveCommand(searchPath);
+ if (current is not null && !SamePath(current, executable) && (launcher is null || !SamePath(current, launcher) || !IsOurLink(launcher, executable)))
+ throw new IOException("Another spn resolves first on PATH: " + current + ". Resolve that conflict before adding this installation to PATH.");
+ if (launcher is not null && (File.Exists(launcher) || new FileInfo(launcher).LinkTarget is not null) && !IsOurLink(launcher, executable))
+ throw new IOException("The user launcher already exists and is not owned by this installation: " + launcher);
+ var onPath = Contains(searchPath, bin);
+ if (OperatingSystem.IsWindows() || onPath) return new(directory, executable, launcher, null, null, onPath);
+ shell ??= Path.GetFileName(Environment.GetEnvironmentVariable("SHELL"));
+ var profile = shell switch { "bash" => ".bashrc", "zsh" => ".zshrc", "sh" or "dash" => ".profile", _ => throw new IOException("Choose --shell bash, zsh or sh to add PATH to its profile; no profile was guessed.") };
+ var block = Block(bin);
+ var path = Path.Combine(home, profile);
+ if (File.Exists(path) && File.ReadAllText(path).Contains("# >>> SidePulse.NET PATH >>>", StringComparison.Ordinal))
+ throw new IOException("The shell profile already has a SidePulse.NET PATH block. Use the recorded installation or review it manually.");
+ return new(directory, executable, launcher, path, block, false);
+ }
+ public static bool IsOurLink(string path, string target)
+ {
+ var link = new FileInfo(path);
+ return link.LinkTarget is { } value && SamePath(Path.IsPathFullyQualified(value) ? value : Path.Combine(Path.GetDirectoryName(path)!, value), target);
+ }
+ public static IReadOnlyList Apply(UserPathPlan plan)
+ {
+ var result = new List();
+ try
+ {
+ if (OperatingSystem.IsWindows())
+ {
+ if (WindowsAdd(plan.Directory) is { } entry) result.Add(entry);
+ }
+ else
+ {
+ if (plan.Launcher is { } launcher && !IsOurLink(launcher, plan.Executable))
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(launcher)!);
+ File.CreateSymbolicLink(launcher, plan.Executable);
+ result.Add(new("launcher", launcher, plan.Executable));
+ }
+ if (plan.Profile is { } profile && plan.Block is { } block)
+ {
+ if (File.Exists(profile) && (File.GetAttributes(profile) & FileAttributes.ReparsePoint) != 0) throw new IOException("Shell profile is a symbolic link. Configure PATH manually instead.");
+ var before = File.Exists(profile) ? File.ReadAllBytes(profile) : [];
+ var mode = File.Exists(profile) ? File.GetUnixFileMode(profile) : UnixFileMode.UserRead | UnixFileMode.UserWrite;
+ var original = new UTF8Encoding(false, true).GetString(before);
+ if (original.Contains("# >>> SidePulse.NET PATH >>>", StringComparison.Ordinal)) throw new IOException("The PATH profile changed during installation. Review it before retrying.");
+ var backup = File.Exists(profile) ? profile + ".sidepulse-path-" + Guid.NewGuid().ToString("N") + ".bak" : null;
+ if (backup is not null) UserInstallation.AtomicWrite(backup, before);
+ UserInstallation.AtomicWrite(profile, before.Concat(Encoding.UTF8.GetBytes(block)).ToArray());
+ File.SetUnixFileMode(profile, mode);
+ result.Add(new("profile", profile, block, backup));
+ }
+ }
+ return result;
+ }
+ catch { Remove(result); throw; }
+ }
+ public static void ValidateRemoval(IReadOnlyList registrations)
+ {
+ foreach (var entry in registrations)
+ {
+ if (entry.Kind == "launcher" && (File.Exists(entry.Location) || new FileInfo(entry.Location).LinkTarget is not null) && !IsOurLink(entry.Location, entry.Value))
+ throw new IOException("The managed launcher was changed. Review it before uninstalling.");
+ if (entry.Kind == "profile" && File.Exists(entry.Location))
+ {
+ if ((File.GetAttributes(entry.Location) & FileAttributes.ReparsePoint) != 0) throw new IOException("The managed profile was replaced by a symbolic link. Review it before uninstalling.");
+ var content = File.ReadAllText(entry.Location);
+ if (!content.Contains(entry.Value, StringComparison.Ordinal) || content.IndexOf(entry.Value, StringComparison.Ordinal) != content.LastIndexOf(entry.Value, StringComparison.Ordinal))
+ throw new IOException("The managed PATH block was modified. Review the profile and its backup before uninstalling.");
+ }
+ if (entry.Kind is not ("launcher" or "profile" or "windows-path")) throw new IOException("Unknown managed PATH entry.");
+ }
+ }
+ public static void Repair(IReadOnlyList registrations)
+ {
+ ValidateRemoval(registrations);
+ if (registrations.Any(entry => entry.Kind == "profile" && !File.Exists(entry.Location)))
+ throw new IOException("The managed shell profile is missing. Restore its retained backup or configure PATH manually; the profile was not replaced.");
+ foreach (var entry in registrations)
+ {
+ if (entry.Kind == "windows-path" && OperatingSystem.IsWindows()) _ = WindowsAdd(entry.Value);
+ if (entry.Kind == "launcher" && new FileInfo(entry.Location).LinkTarget is null && !File.Exists(entry.Location))
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(entry.Location)!);
+ File.CreateSymbolicLink(entry.Location, entry.Value);
+ }
+ }
+ }
+ public static void Remove(IReadOnlyList registrations)
+ {
+ ValidateRemoval(registrations);
+ foreach (var entry in registrations.Reverse())
+ {
+ if (entry.Kind == "windows-path" && OperatingSystem.IsWindows()) WindowsRemove(entry);
+ else if (entry.Kind == "launcher" && new FileInfo(entry.Location).LinkTarget is not null) File.Delete(entry.Location);
+ else if (entry.Kind == "profile" && File.Exists(entry.Location))
+ {
+ if (OperatingSystem.IsWindows()) throw new IOException("Unix profile registration is not valid on Windows.");
+ var mode = File.GetUnixFileMode(entry.Location);
+ var content = new UTF8Encoding(false, true).GetString(File.ReadAllBytes(entry.Location));
+ UserInstallation.AtomicWrite(entry.Location, Encoding.UTF8.GetBytes(content.Replace(entry.Value, "", StringComparison.Ordinal)));
+ File.SetUnixFileMode(entry.Location, mode);
+ }
+ }
+ }
+ [SupportedOSPlatform("windows")]
+ private static PathRegistration? WindowsAdd(string directory)
+ {
+ using var environment = Registry.CurrentUser.CreateSubKey("Environment", true);
+ var absent = environment.GetValue("Path", null, RegistryValueOptions.DoNotExpandEnvironmentNames) is null;
+ var original = environment.GetValue("Path", "", RegistryValueOptions.DoNotExpandEnvironmentNames) as string ?? throw new IOException("User PATH is not a string.");
+ if (Contains(original, directory)) return null;
+ var kind = environment.GetValueNames().Any(name => name.Equals("Path", StringComparison.OrdinalIgnoreCase)) ? environment.GetValueKind("Path") : RegistryValueKind.ExpandString;
+ if (kind is not (RegistryValueKind.String or RegistryValueKind.ExpandString)) throw new IOException("User PATH has an unsupported registry type.");
+ environment.SetValue("Path", original + (original.Length == 0 ? "" : ";") + directory, kind);
+ NotifyWindowsEnvironment();
+ return new("windows-path", "HKCU/Environment/Path", directory, absent ? "absent" : null);
+ }
+ [SupportedOSPlatform("windows")]
+ private static void WindowsRemove(PathRegistration registration)
+ {
+ using var environment = Registry.CurrentUser.OpenSubKey("Environment", true);
+ if (environment?.GetValue("Path", null, RegistryValueOptions.DoNotExpandEnvironmentNames) is not string original) return;
+ var parts = original.Split(';').ToList();
+ var index = parts.FindLastIndex(part => part.Equals(registration.Value, StringComparison.OrdinalIgnoreCase));
+ if (index < 0) return;
+ parts.RemoveAt(index);
+ var remaining = string.Join(';', parts);
+ if (remaining.Length == 0 && registration.Backup == "absent") environment.DeleteValue("Path", false);
+ else environment.SetValue("Path", remaining, environment.GetValueKind("Path"));
+ NotifyWindowsEnvironment();
+ }
+ [SupportedOSPlatform("windows")]
+ private static void NotifyWindowsEnvironment() => SendMessageTimeout(new IntPtr(0xffff), 0x1a, IntPtr.Zero, "Environment", 2, 1000, out _);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
+ private static extern IntPtr SendMessageTimeout(IntPtr window, uint message, IntPtr parameter, string value, uint flags, uint timeout, out UIntPtr result);
+}
diff --git a/tests/SidePulse.Tests/InstallationTests.cs b/tests/SidePulse.Tests/InstallationTests.cs
new file mode 100644
index 0000000..9b8423d
--- /dev/null
+++ b/tests/SidePulse.Tests/InstallationTests.cs
@@ -0,0 +1,153 @@
+using System.Text;
+using System.Text.Json;
+using SidePulse.Core;
+using Xunit;
+
+namespace SidePulse.Tests;
+
+public sealed class InstallationTests
+{
+ private sealed class Fixture : IDisposable
+ {
+ public string Root { get; } = Path.Combine(Path.GetTempPath(), "SidePulse install ü " + Guid.NewGuid());
+ public string Source => Path.Combine(Root, "download");
+ public string Target => Path.Combine(Root, "managed", "app");
+ public InstallationManifest Manifest { get; }
+ public Fixture()
+ {
+ Directory.CreateDirectory(Source);
+ var exe = Path.Combine(Source, ApplicationIdentity.CurrentExecutable);
+ File.WriteAllText(exe, "bundle fixture");
+ File.WriteAllText(Path.Combine(Source, "unrelated-download.txt"), "do not install this");
+ Manifest = new(2, "1.0.0", GitHubReleases.RuntimeIdentifier, [new(ApplicationIdentity.CurrentExecutable, InstallationManifest.Hash(exe), 493)]);
+ }
+ public void Dispose()
+ {
+ var receipt = UpdateTransaction.ReceiptPath(Target);
+ if (File.Exists(receipt)) File.Delete(receipt);
+ Directory.Delete(Root, true);
+ }
+ }
+ [Fact]
+ public async Task PreviewCreatesNothingAndInstallIsOwnedAndIdempotent()
+ {
+ using var fixture = new Fixture();
+ var plan = UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest);
+ Assert.False(Directory.Exists(Path.GetDirectoryName(fixture.Target)));
+ await UserInstallation.Install(plan, fixture.Manifest, (directory, _) =>
+ {
+ Assert.True(File.Exists(Path.Combine(directory, ApplicationIdentity.CurrentExecutable)));
+ return Task.CompletedTask;
+ });
+ Assert.Equal(2, InstallationManifest.Read(fixture.Target).Format);
+ Assert.False(File.Exists(Path.Combine(fixture.Target, "unrelated-download.txt")));
+ Assert.True(UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest).AlreadyInstalled);
+ File.WriteAllText(Path.Combine(fixture.Target, "personal.txt"), "keep");
+ Directory.CreateDirectory(Path.Combine(fixture.Target, "empty-user-directory"));
+ var recordPath = Path.Combine(fixture.Root, "registration.json");
+ var record = new UserInstallRecord(1, fixture.Target, []);
+ UserInstallation.SaveRecord(record, recordPath);
+ UserInstallation.Remove(record, recordPath);
+ Assert.Equal("keep", File.ReadAllText(Path.Combine(fixture.Target, "personal.txt")));
+ Assert.True(Directory.Exists(Path.Combine(fixture.Target, "empty-user-directory")));
+ Assert.False(File.Exists(recordPath));
+ }
+ [Fact]
+ public async Task FailedProbeAndUnownedDestinationLeaveExistingFilesIntact()
+ {
+ using var fixture = new Fixture();
+ var plan = UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest);
+ await Assert.ThrowsAsync(() => UserInstallation.Install(plan, fixture.Manifest, (_, _) => throw new IOException("probe failed")));
+ Assert.False(Directory.Exists(fixture.Target));
+ Directory.CreateDirectory(fixture.Target);
+ File.WriteAllText(Path.Combine(fixture.Target, "unrelated"), "keep");
+ Assert.Throws(() => UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest));
+ Assert.Equal("keep", File.ReadAllText(Path.Combine(fixture.Target, "unrelated")));
+ }
+ [Fact]
+ public async Task EditedExecutableCannotBeReplacedOrUninstalled()
+ {
+ using var fixture = new Fixture();
+ await UserInstallation.Install(UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest), fixture.Manifest, (_, _) => Task.CompletedTask);
+ File.WriteAllText(Path.Combine(fixture.Target, ApplicationIdentity.CurrentExecutable), "user edit");
+ Assert.Throws(() => UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest));
+ Assert.Throws(() => UserInstallation.Remove(new(1, fixture.Target, []), Path.Combine(fixture.Root, "record.json")));
+ Assert.Equal("user edit", File.ReadAllText(Path.Combine(fixture.Target, ApplicationIdentity.CurrentExecutable)));
+ }
+ [Fact]
+ public async Task DirectoryPackageUpgradeRollsBackOnProbeFailureAndPreservesUserFiles()
+ {
+ using var fixture = new Fixture();
+ Directory.CreateDirectory(fixture.Target);
+ var native = OperatingSystem.IsWindows() ? "hostfxr.dll" : OperatingSystem.IsMacOS() ? "libhostfxr.dylib" : "libhostfxr.so";
+ foreach (var name in new[] { ApplicationIdentity.CurrentExecutable, ApplicationIdentity.Assembly, native }) File.WriteAllText(Path.Combine(fixture.Target, name), "old package");
+ var files = Directory.GetFiles(fixture.Target).Select(path => new InstalledFile(Path.GetFileName(path), InstallationManifest.Hash(path), 493)).ToArray();
+ var legacy = new InstallationManifest(1, "0.9.0", fixture.Manifest.Runtime, files);
+ File.WriteAllText(Path.Combine(fixture.Target, InstallationManifest.Filename), JsonSerializer.Serialize(legacy));
+ File.WriteAllText(Path.Combine(fixture.Target, "personal"), "preserve");
+ await Assert.ThrowsAsync(() => UserInstallation.Install(UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest), fixture.Manifest,
+ (_, _) => throw new IOException("probe failure")));
+ Assert.Equal(1, InstallationManifest.Read(fixture.Target).Format);
+ Assert.Equal("old package", File.ReadAllText(Path.Combine(fixture.Target, ApplicationIdentity.CurrentExecutable)));
+ await UserInstallation.Install(UserInstallation.Plan(fixture.Source, fixture.Target, fixture.Manifest), fixture.Manifest, (_, _) => Task.CompletedTask);
+ Assert.Equal(2, InstallationManifest.Read(fixture.Target).Format);
+ Assert.False(File.Exists(Path.Combine(fixture.Target, ApplicationIdentity.Assembly)));
+ Assert.Equal("preserve", File.ReadAllText(Path.Combine(fixture.Target, "personal")));
+ }
+ [Fact]
+ public void BundleManifestRequiresExactlyTheExecutableAndKeepsLegacyDirectorySupport()
+ {
+ using var fixture = new Fixture();
+ var manifestPath = Path.Combine(fixture.Source, InstallationManifest.Filename);
+ File.WriteAllText(manifestPath, JsonSerializer.Serialize(fixture.Manifest));
+ Assert.Equal(2, InstallationManifest.Read(fixture.Source).Format);
+ var invalid = fixture.Manifest with { Files = fixture.Manifest.Files.Append(new("spn.dll", new string('A', 64), 493)).ToArray() };
+ File.WriteAllText(manifestPath, JsonSerializer.Serialize(invalid));
+ Assert.Throws(() => InstallationManifest.Read(fixture.Source));
+ File.WriteAllText(manifestPath, JsonSerializer.Serialize(fixture.Manifest with { Format = 1 }));
+ Assert.Throws(() => InstallationManifest.Read(fixture.Source));
+ }
+ [Fact]
+ public void UnixPathHasExactBackupPreservesOutsideEditsAndRefusesChangedManagedContent()
+ {
+ if (OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ var profile = Path.Combine(fixture.Root, ".bashrc");
+ byte[] original = [0xef, 0xbb, 0xbf, .. Encoding.UTF8.GetBytes("# custom\nexport KEEP=value\n")];
+ File.WriteAllBytes(profile, original);
+ File.SetUnixFileMode(profile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead);
+ var mode = File.GetUnixFileMode(profile);
+ var bin = Path.Combine(fixture.Root, "bin");
+ var plan = UserPath.Plan(fixture.Target, "bash", bin, fixture.Root, "/usr/bin:/bin");
+ Assert.False(Directory.Exists(bin));
+ var registrations = UserPath.Apply(plan);
+ Assert.True(UserPath.IsOurLink(Path.Combine(bin, "spn"), Path.Combine(fixture.Target, "spn")));
+ Assert.Equal(original, File.ReadAllBytes(registrations.Single(item => item.Kind == "profile").Backup!));
+ Assert.Equal(mode, File.GetUnixFileMode(profile));
+ File.AppendAllText(profile, "# added after install\n");
+ UserPath.Remove(registrations);
+ Assert.Equal(original.Concat(Encoding.UTF8.GetBytes("# added after install\n")).ToArray(), File.ReadAllBytes(profile));
+ Assert.False(File.Exists(Path.Combine(bin, "spn")));
+ var second = UserPath.Apply(UserPath.Plan(fixture.Target, "bash", bin, fixture.Root, "/usr/bin:/bin"));
+ File.WriteAllText(profile, File.ReadAllText(profile).Replace("export PATH", "# changed PATH", StringComparison.Ordinal));
+ Assert.Throws(() => UserPath.Remove(second));
+ Assert.NotNull(new FileInfo(Path.Combine(bin, "spn")).LinkTarget);
+ }
+ [Fact]
+ public void ExistingCommandAndUnownedLauncherAreNeverOverwritten()
+ {
+ using var fixture = new Fixture();
+ var bin = Path.Combine(fixture.Root, "bin");
+ Directory.CreateDirectory(bin);
+ var competing = Path.Combine(bin, ApplicationIdentity.CurrentExecutable);
+ File.WriteAllText(competing, "other application");
+ Assert.Throws(() => UserPath.Plan(fixture.Target, "bash", bin, fixture.Root, bin));
+ Assert.Equal("other application", File.ReadAllText(competing));
+ if (OperatingSystem.IsWindows())
+ {
+ File.Delete(competing);
+ File.WriteAllText(Path.Combine(bin, "spn.cmd"), "other wrapper");
+ Assert.Throws(() => UserPath.Plan(fixture.Target, "bash", bin, fixture.Root, bin));
+ }
+ }
+}