diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 3e6e6e6..04885c7 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -92,7 +92,7 @@ jobs: - name: Exercise CLI and local host with simulated hardware shell: pwsh run: | - $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } + $binary = if ($IsWindows) { 'spn.exe' } else { 'spn' } python scripts/cli_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } python scripts/terminal_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" @@ -122,7 +122,7 @@ jobs: python scripts/package_manifest.py $destination $rid $version if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($rid -eq $native) { - $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } + $binary = if ($IsWindows) { 'spn.exe' } else { 'spn' } python scripts/cli_smoke.py "$destination/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } python scripts/animation_smoke.py "$destination/$binary" @@ -133,16 +133,16 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } if ($IsWindows) { - Compress-Archive -Path "$destination/*" -DestinationPath "artifacts/sidepulse-net-$rid.zip" + Compress-Archive -Path "$destination/*" -DestinationPath "artifacts/spn-$rid.zip" } else { - tar -czf "artifacts/sidepulse-net-$rid.tar.gz" -C $destination . + tar -czf "artifacts/spn-$rid.tar.gz" -C $destination . if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } } - name: Upload platform previews uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: sidepulse-net-${{ runner.os }}-preview + name: spn-${{ runner.os }}-preview path: | artifacts/*.zip artifacts/*.tar.gz diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index df77ac0..025b9c7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,4 @@ -name: Release +name: Prepare release on: push: tags: ['v*'] @@ -11,25 +11,36 @@ concurrency: jobs: validate: runs-on: ubuntu-latest + outputs: + version: ${{ steps.version.outputs.version }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - - name: Require a version tag matching the application + - name: Validate release version and notes + id: version env: RELEASE_REF: ${{ github.ref }} + RELEASE_EVENT: ${{ github.event_name }} run: | python3 - <<'PY' - import os, re, xml.etree.ElementTree as ET + import os, re, pathlib, xml.etree.ElementTree as ET version = ET.parse('src/SidePulse.Cli/SidePulse.Cli.csproj').findtext('./PropertyGroup/Version') - if os.environ['RELEASE_REF'] != 'refs/tags/v' + version or not re.fullmatch(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?', version): - raise SystemExit('Select/push a vVERSION tag matching the project version; build metadata is not used for release tags.') + if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?', version): + raise SystemExit('Invalid project release version.') + expected = 'refs/heads/main' if os.environ['RELEASE_EVENT'] == 'workflow_dispatch' else 'refs/tags/v' + version + if os.environ['RELEASE_REF'] != expected: + raise SystemExit('Dispatch on main, or push a matching vVERSION tag.') + if not pathlib.Path('docs/releases/' + version + '.md').is_file(): + raise SystemExit('Versioned release notes are required.') + with open(os.environ['GITHUB_OUTPUT'], 'a') as output: + output.write('version=' + version + '\n') PY build: needs: validate uses: ./.github/workflows/dotnet-ci.yml - publish: - needs: build + draft: + needs: [validate, build] runs-on: ubuntu-latest permissions: contents: write @@ -44,17 +55,20 @@ jobs: GH_REPO: ${{ github.repository }} RELEASE_RUN: ${{ github.run_id }} run: | - gh run download "$RELEASE_RUN" --pattern 'sidepulse-net-*-preview' --dir release-input + gh run download "$RELEASE_RUN" --pattern 'spn-*-preview' --dir release-input mkdir release-files find release-input -type f \( -name '*.zip' -o -name '*.tar.gz' \) -exec cp -n {} release-files/ \; python3 scripts/release_checksums.py release-files - - name: Upload all assets before making the release visible + python3 scripts/verify_release.py release-files '${{ needs.validate.outputs.version }}' + - name: Create an unpublished release draft env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} - RELEASE_TAG: ${{ github.ref_name }} + RELEASE_VERSION: ${{ needs.validate.outputs.version }} + RELEASE_COMMIT: ${{ github.sha }} run: | flags=() + RELEASE_TAG="v$RELEASE_VERSION" if [[ "$RELEASE_TAG" == *-* ]]; then flags+=(--prerelease); fi - gh release create "$RELEASE_TAG" --verify-tag --draft --title "SidePulse.NET ${RELEASE_TAG#v}" --generate-notes "${flags[@]}" release-files/* - gh release edit "$RELEASE_TAG" --draft=false "${flags[@]}" + gh release create "$RELEASE_TAG" --target "$RELEASE_COMMIT" --draft --title "SidePulse.NET $RELEASE_VERSION" --notes-file "docs/releases/$RELEASE_VERSION.md" "${flags[@]}" release-files/* + echo "Release draft prepared. Review downloads, notes and acceptance before publishing." >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index f485ead..d8fbc6b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ An unofficial .NET companion for SidePulse, with a Spectre.Console terminal interface. -**Status: first C# implementation preview. Feature parity and hardware validation are still in progress.** +**Status: 0.1.0-beta.1 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). Start with [Getting started](docs/wiki/Getting-Started.md) for build, USB, phone delivery and Copilot CLI instructions. @@ -12,7 +14,7 @@ an agent is working, waiting for input or finished. ## Preview functionality -- Cursor menus, script-command review/copy/export, plain/quiet/JSON output. +- Persistent interactive session, repeatable Send state, action palette, script-command copy/export and plain/quiet/JSON output. - Copilot CLI, Codex, Claude Code, Kiro CLI V3 hooks and an OpenCode plugin with shared status aggregation. - Writable USB/SD LED output, iPhone linking and native protected credentials. - Dot/Pro animation simulation, custom editor, upstream patterns and state profiles. @@ -69,7 +71,7 @@ The solution contains a portable core, a Spectre.Console CLI and behavioral test Command groups include `devices`, `state`, `write`, `dashboard`, `host`, `agents`, `link`, `animations`, `profiles`, `about`, `docs` and `update`. Use `--help` for subcommands and `--dry-run` where supported before changing files or sending a program. -The command name `sidepulse-net` coexists with the existing Python port. +The command name `spn` coexists with the existing Python port. QR pairing and protected token storage use DPAPI on Windows, Keychain on macOS and Secret Service on Linux. Login-startup registration, firmware-verified simulator parity, @@ -94,15 +96,15 @@ Contributions: [CONTRIBUTING.md](CONTRIBUTING.md). License: [MIT](LICENSE). ## Agent setup and background use ```shell -sidepulse-net agents install codex --dry-run -sidepulse-net agents install codex -sidepulse-net agents install claude -sidepulse-net agents install kiro -sidepulse-net agents install copilot -sidepulse-net agents install opencode -sidepulse-net host start --phone default -sidepulse-net host status -sidepulse-net host stop +spn agents install codex --dry-run +spn agents install codex +spn agents install claude +spn agents install kiro +spn agents install copilot +spn agents install opencode +spn host start --phone default +spn host status +spn host stop ``` See [agent integrations](docs/wiki/Agent-Integrations.md) for provider capabilities, @@ -112,15 +114,15 @@ for logs and foreground use. Additional providers remain planned. ## Animation studio and scripting ```shell -sidepulse-net animations preview cyan-roll --both -sidepulse-net animations edit --file custom.LED --model dot -sidepulse-net animations validate custom.LED --quiet -sidepulse-net animations import personal --file custom.LED --model dot -sidepulse-net animations apply personal --model dot --phone default --brightness 40 -sidepulse-net profiles set personal --state Working --pattern cyan-roll --brightness 40 -sidepulse-net host start --phone default --profile personal --model dot -sidepulse-net about credits -sidepulse-net about licenses --full +spn animations preview cyan-roll --both +spn animations edit --file custom.LED --model dot +spn animations validate custom.LED --quiet +spn animations import personal --file custom.LED --model dot +spn animations apply personal --model dot --phone default --brightness 40 +spn profiles set personal --state Working --pattern cyan-roll --brightness 40 +spn host start --phone default --profile personal --model dot +spn about credits +spn about licenses --full ``` Run with no arguments in a terminal for arrow-key menus and guided setup. Review @@ -137,11 +139,11 @@ licensed dependency credits. Browser opening requires `--open`. ## Verified updates ```shell -sidepulse-net update check -sidepulse-net update install --prerelease --dry-run -sidepulse-net host stop -sidepulse-net update install --prerelease -sidepulse-net update status +spn update check +spn update install --prerelease --dry-run +spn host stop +spn update install --prerelease +spn update status ``` The updater selects a published GitHub release for the current OS/architecture, @@ -150,4 +152,6 @@ exits. A backup and startup probe support rollback. Use self-contained packages with an installation manifest; older previews need one manual upgrade. Stop the host first and confirm `installed` before restarting it. See [updating and recovery](docs/wiki/Updating.md). Adding the release workflow does not -publish a release; a matching version tag explicitly triggers publishing. +publish a release. A matching version tag or manual Prepare release run on `main` +builds and verifies six archives, then creates an unpublished release draft. +Publishing the reviewed draft is a separate explicit release action. diff --git a/docs/releases/0.1.0-beta.1.md b/docs/releases/0.1.0-beta.1.md new file mode 100644 index 0000000..e130641 --- /dev/null +++ b/docs/releases/0.1.0-beta.1.md @@ -0,0 +1,72 @@ +# SidePulse.NET 0.1.0-beta.1 + +First beta candidate. The command is now **`spn`** (`spn.exe` on Windows). +The product and repository remain SidePulse.NET. No old-name alias is included. + +## Changes + +- Interactive launches stay open after commands. Home, section navigation and a + searchable `/` action palette support repeated work; Esc at Home stays in the app. +- Send state keeps its output and Preview mode during the session. Choose a state + and press Enter to send again. Output selection lists connected devices and saved phones. +- Script commands leave simple arguments unquoted and escape shell-sensitive values. + Portable executable paths use an absolute invocation when `spn` is not on PATH. +- State, write, animation and host delivery select one mounted USB device, otherwise + the saved default or sole phone. Explicit targets never fall back on failure. +- Native OpenCode event plugin joins Copilot, Codex, Claude Code and Kiro integrations. + +## Downloads and installation + +Choose exactly one archive for your OS and architecture: + +| OS | x64 | ARM64 | +|---|---|---| +| Windows | `spn-win-x64.zip` | `spn-win-arm64.zip` | +| macOS | `spn-osx-x64.tar.gz` | `spn-osx-arm64.tar.gz` | +| Linux | `spn-linux-x64.tar.gz` | `spn-linux-arm64.tar.gz` | + +Verify the archive against `SHA256SUMS`, then extract the **complete archive** into +its own permanent directory. Windows suggestion: `%LOCALAPPDATA%\Programs\SidePulse.NET`; +macOS/Linux: a user-owned directory under `~/.local/share/SidePulse.NET`. +Run `.\spn.exe` in PowerShell or `./spn` on Unix. An optional manual user PATH entry +lets other terminals use `spn`; reopen terminals after changing PATH. + +This beta uses self-contained directory packages, not single-file executables. +Do not copy the apphost alone: runtime files and `sidepulse-install.json` are required. +There is no automatic installer, PATH/profile modification or signing in this beta. +`spn docs --offline` and `spn about licenses --full` work without a network connection. + +## Upgrade from the alpha preview + +1. With the **old executable**, stop the host and uninstall each managed integration + using its existing `--config` override where applicable. Existing ownership checks + refuse modified files; preserve those files and merge them manually. +2. Extract the new complete package into its permanent directory. Keep the old copy + until the new setup is verified. Do not use the alpha updater to cross this rename. +3. Run `spn link list` and confirm saved phone aliases are present. Storage paths, + native credential identity, profiles and IPC identity are unchanged. +4. Reinstall integrations with `spn agents install ` from the permanent + executable. Restart the agents and review their normal trust prompts. +5. Start the host, send one test state and verify the actual device display. + Remove obsolete downloaded files manually after verification. + +Existing provider filenames such as `sidepulse-net.json` and `sidepulse-net.js` +remain ownership identifiers. They are not compatibility executables. + +## Validation and remaining limits + +Native CI builds/tests on Windows x64, Linux x64 and macOS ARM64, exercises generated +hooks/plugins, and tests update replacement and rollback with simulated hardware. +Other architecture packages are cross-built; they still need native acceptance. + +Real device/firmware parity and each installed agent version need separate recorded +acceptance. Bridge HTTP success does not acknowledge the physical LED display. +Linux saved links require Secret Service; macOS uses Keychain; Windows uses DPAPI. + +The persistent UI is an initial delivery slice: comprehensive saved settings, +first-run installation, automatic managed-hook repair and the full responsive frame +remain open in issues #17/#18. Existing advanced setup forms are still guided menus. +Updates require stopping the host and running outside the installation directory; +retain backups until `spn update status` confirms success. + +This release remains a **draft** until its packages and acceptance have been reviewed. diff --git a/docs/wiki/Agent-Integrations.md b/docs/wiki/Agent-Integrations.md index 091a237..30317aa 100644 --- a/docs/wiki/Agent-Integrations.md +++ b/docs/wiki/Agent-Integrations.md @@ -9,17 +9,17 @@ and limitations. Unknown providers/events are not guessed from terminal text. ## Setup, inspection and removal ```shell -sidepulse-net agents list -sidepulse-net agents install copilot --dry-run -sidepulse-net agents install copilot -sidepulse-net agents install codex -sidepulse-net agents install claude -sidepulse-net agents install kiro -sidepulse-net agents install opencode --dry-run -sidepulse-net agents install opencode -sidepulse-net agents status claude --json -sidepulse-net agents uninstall claude --dry-run -sidepulse-net agents uninstall claude +spn agents list +spn agents install copilot --dry-run +spn agents install copilot +spn agents install codex +spn agents install claude +spn agents install kiro +spn agents install opencode --dry-run +spn agents install opencode +spn agents status claude --json +spn agents uninstall claude --dry-run +spn agents uninstall claude ``` Run the published executable, or supply its absolute path with `--exe`. @@ -88,10 +88,10 @@ These are passive status hooks: their output never contains policy decisions. ## OpenCode ```shell -sidepulse-net agents install opencode -sidepulse-net host start --phone default -sidepulse-net agents status opencode --json -sidepulse-net agents uninstall opencode --dry-run +spn agents install opencode +spn host start --phone default +spn agents status opencode --json +spn agents uninstall opencode --dry-run ``` Restart OpenCode after installation. The plugin subscribes to native events: diff --git a/docs/wiki/Animations.md b/docs/wiki/Animations.md index b60a2f0..8fc551e 100644 --- a/docs/wiki/Animations.md +++ b/docs/wiki/Animations.md @@ -7,15 +7,15 @@ output requires an explicit model. File transport still requires writable storag this feature does not add direct USB or SD read transports. ```sh -sidepulse-net animations list -sidepulse-net animations preview cyan-roll --model dot -sidepulse-net animations preview --file custom.LED --model pro -sidepulse-net animations preview --file custom.LED --both -sidepulse-net animations validate custom.LED --quiet -sidepulse-net animations edit --file custom.LED --model dot -sidepulse-net animations import personal --file custom.LED --model dot -sidepulse-net animations export personal --model dot --output exported.LED -sidepulse-net animations apply personal --model dot --phone default --brightness 40 +spn animations list +spn animations preview cyan-roll --model dot +spn animations preview --file custom.LED --model pro +spn animations preview --file custom.LED --both +spn animations validate custom.LED --quiet +spn animations edit --file custom.LED --model dot +spn animations import personal --file custom.LED --model dot +spn animations export personal --model dot --output exported.LED +spn animations apply personal --model dot --phone default --brightness 40 ``` The editor supports guided color, per-LED color/hold, off, roll, brightness, @@ -48,10 +48,10 @@ preview runs for 10 seconds by default; `--seconds` permits up to 600 seconds. ## Agent state profiles ```sh -sidepulse-net profiles set personal --state Working --pattern cyan-roll --brightness 40 -sidepulse-net profiles set personal --state Waiting --pattern amber-pulse -sidepulse-net profiles show personal --json -sidepulse-net host start --phone default --profile personal --model dot +spn profiles set personal --state Working --pattern cyan-roll --brightness 40 +spn profiles set personal --state Waiting --pattern amber-pulse +spn profiles show personal --json +spn host start --phone default --profile personal --model dot ``` Unassigned states retain the original status patterns. Profile brightness applies diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index 9d80c42..a08b02e 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -26,8 +26,8 @@ Provide a migration report and a way to undo new configuration. ## Commands and conflicts -Initially expose `sidepulse-net`. An optional `sidepulse` alias is a deliberate -choice because the user already has a working Python command by that name. +The executable is `spn` (`spn.exe` on Windows). No compatibility command or alias +is distributed. The Python `sidepulse` installation remains independent. Detect competing hooks and writers in diagnostics, and offer targeted repair rather than automatically deleting another application's configuration. diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index a30e0c5..1559df5 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -2,13 +2,17 @@ > and Copilot are now implemented. See [[Host-Management]] and [[Agent-Integrations]]. > The manual Copilot hook generation below remains available for existing users. -# Getting started with the implementation preview +# Getting started with the beta candidate -The first implementation is an alpha preview. USB discovery/writes, status profiles, -raw programs, silent iPhone bridge delivery with an existing APNS token, session -aggregation, QR pairing, native protected phone links, diagnostics and a foreground -Copilot CLI host are implemented. Background-service installation, full LED grammar validation, -animation rendering, migration and remaining agent integrations remain planned. +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. + +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. ## Build and run @@ -27,8 +31,8 @@ Publish a Windows application without a Python or .NET runtime requirement: dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64 ``` -Run `artifacts/win-x64/sidepulse-net.exe`. For macOS or Linux, replace `win-x64` -with the desired runtime identifier and run `./sidepulse-net`. CI publishes +Run `artifacts/win-x64/spn.exe`. For macOS or Linux, replace `win-x64` +with the desired runtime identifier and run `./spn`. CI publishes archives for `win-x64`, `win-arm64`, `osx-x64`, `osx-arm64`, `linux-x64` and `linux-arm64`. Windows archives use ZIP; Unix archives use tar.gz to retain executable permissions. Extract the inner archive after downloading the Actions @@ -38,9 +42,9 @@ These are unsigned preview builds, not installers or stable releases. ## USB device ```powershell -sidepulse-net devices --json -sidepulse-net state working --device E:\ -sidepulse-net write 'off\n#ff9900 1.6s pulse\nrepeat' --escapes --device E:\ +spn devices --json +spn state working --device E:\ +spn write 'off\n#ff9900 1.6s pulse\nrepeat' --escapes --device E:\ ``` An explicit directory must contain `LEDS.LED`; the tool will not create device files @@ -52,10 +56,10 @@ the firmware remains responsible for LED syntax validation. ## Pair an iPhone ```powershell -sidepulse-net link pair iphone -sidepulse-net link list -sidepulse-net state done --phone iphone -sidepulse-net host --phone default +spn link pair iphone +spn link list +spn state done --phone iphone +spn host --phone default ``` Scan the terminal QR using the SidePulse app's pairing flow. The pairing URI is @@ -88,18 +92,18 @@ can use environment-token delivery without saved links. See [[Platforms]]. The first linked phone becomes the default. Without target options, state, write, animation apply and host delivery use exactly one mounted USB device; if none is found, they use the saved default phone (or the only saved phone). For example, -`sidepulse-net state working` works with a paired default phone and no USB device. +`spn state working` works with a paired default phone and no USB device. Multiple mounted devices require an explicit target. Multiple phones without a default require `--phone` or `link default `. Explicit `--device`, `--phone` and `--token-env` always take precedence. A failed selection, credential read or delivery never retries on a different output. ```powershell -sidepulse-net link rename iphone personal -sidepulse-net link default personal -sidepulse-net link list --json -sidepulse-net link remove personal -sidepulse-net doctor --json +spn link rename iphone personal +spn link default personal +spn link list --json +spn link remove personal +spn doctor --json ``` Aliases are case-insensitive and use 1–40 letters, digits, underscores or hyphens. @@ -118,9 +122,9 @@ environment. Keep the value out of command history, source control and screensho Save it securely using the native credential vault, or use it directly without persistence: ```powershell -sidepulse-net link import iphone --token-env SIDEPULSE_TOKEN -sidepulse-net state working --token-env SIDEPULSE_TOKEN -sidepulse-net host --token-env SIDEPULSE_TOKEN +spn link import iphone --token-env SIDEPULSE_TOKEN +spn state working --token-env SIDEPULSE_TOKEN +spn host --token-env SIDEPULSE_TOKEN ``` Saved links and pairing are available on Windows, macOS and Linux when the native @@ -139,22 +143,22 @@ upstream protocol at the revision in `upstream.json`. Start the host in a terminal, choosing either USB or the phone environment token: ```powershell -sidepulse-net host --device E:\ +spn host --device E:\ ``` Create the hook directory if needed, then generate a new, separate hook file: ```powershell New-Item -ItemType Directory -Force "$env:USERPROFILE\.copilot\hooks" | Out-Null -sidepulse-net hook-config --exe C:\Tools\SidePulse.NET\sidepulse-net.exe --output "$env:USERPROFILE\.copilot\hooks\sidepulse-net.json" +spn hook-config --exe C:\Tools\SidePulse.NET\spn.exe --output "$env:USERPROFILE\.copilot\hooks\sidepulse-net.json" ``` On macOS/Linux, use: ```bash mkdir -p ~/.copilot/hooks -sidepulse-net hook-config --exe /absolute/path/to/sidepulse-net --output ~/.copilot/hooks/sidepulse-net.json -sidepulse-net host --phone default +spn hook-config --exe /absolute/path/to/spn --output ~/.copilot/hooks/sidepulse-net.json +spn host --phone default ``` Generated files include both Bash and PowerShell wrappers. Bash inherits JSON diff --git a/docs/wiki/Host-Management.md b/docs/wiki/Host-Management.md index 241775b..2f250a3 100644 --- a/docs/wiki/Host-Management.md +++ b/docs/wiki/Host-Management.md @@ -6,11 +6,11 @@ listener. The phone token remains in the native credential store or process environment; it is never added to command arguments or logs. ```shell -sidepulse-net host start --phone default -sidepulse-net host status -sidepulse-net host status --json -sidepulse-net host logs --tail 30 -sidepulse-net host stop +spn host start --phone default +spn host status +spn host status --json +spn host logs --tail 30 +spn host stop ``` Choose a target with `--phone`, `--device` or `--token-env`. `--dry-run` runs the @@ -29,10 +29,10 @@ in memory only and begin unknown after restart. For a foreground session: ```shell -sidepulse-net host run --phone default +spn host run --phone default ``` -The earlier `sidepulse-net host --phone default` shorthand remains supported. +The earlier `spn host --phone default` shorthand remains supported. Ctrl+C stops the foreground host. Upgrade by stopping the old host before replacing binaries; older preview hosts do not implement the control protocol. A process started from a terminal is detached on Unix. Windows launches it without @@ -53,7 +53,7 @@ not evidence of actual LED or phone receipt. ## Clearing abandoned sessions -`sidepulse-net host reset` clears all tracked sessions and queues the Unknown +`spn host reset` clears all tracked sessions and queues the Unknown pattern. Use `--json` for a machine-readable snapshot. This explicitly discards history; it does not mark tasks successful or stop agent processes. The next agent event establishes fresh state. A stopped host returns exit code 1. diff --git a/docs/wiki/Product-Concept.md b/docs/wiki/Product-Concept.md index d71b7fc..b9d9db2 100644 --- a/docs/wiki/Product-Concept.md +++ b/docs/wiki/Product-Concept.md @@ -37,4 +37,4 @@ Firmware and raw USB parity require a dedicated compatibility investigation. Confirm dashboard interaction details, packaging/name availability, service lifetime and startup behavior, aggregation policy and how long completion stays -visible. .NET 10 LTS and separate `sidepulse-net` command are the proposed defaults. +visible. .NET 10 LTS and separate `spn` command are the proposed defaults. diff --git a/docs/wiki/Scripting-and-Menus.md b/docs/wiki/Scripting-and-Menus.md index 05c647a..6a5b855 100644 --- a/docs/wiki/Scripting-and-Menus.md +++ b/docs/wiki/Scripting-and-Menus.md @@ -1,12 +1,24 @@ # Scripting and interactive menus -In a terminal, `sidepulse-net` opens an arrow-key menu. Bare groups `animations`, +In a terminal, `spn` opens a persistent session. Bare groups `animations`, `profiles`, `agents`, `host`, `link`, and `about` open their respective menus. -Up/Down select, Enter continues, Escape goes back. Fully specified commands always +Up/Down select, Enter continues, Escape goes back one section. Escape at Home +stays in the session; choose Quit to leave. `/` opens a searchable action palette. +Commands and recoverable failures return to their section. Ctrl+C cancels a +running command; when idle it exits. The detached host keeps running. +Fully specified commands always execute directly. The legacy `host --phone default` shorthand remains supported. -Guided actions display a single-line script command before running. Review offers -Run, Copy command, Choose shell and Back. PowerShell and Bash quoting preserve +Send state retains its output choice and Preview mode until the session ends. +Choose a state and press Enter to send; there is no repeated target or Run/Copy +dialog. Change output lists mounted devices and saved phones; Auto selects one +USB device, otherwise the default/sole saved phone. Preview never sends. +Saved application-wide UI preferences and first-run installation are still planned. + +Advanced guided actions display a single-line script command before running. Review offers +Run, Copy command, Choose shell and Back. Simple arguments remain unquoted. +Portable commands use the executable's absolute path when it is not on PATH; +quoted PowerShell executable paths include the invocation operator. PowerShell and Bash quoting preserve literal values; CMD export rejects values it cannot safely represent. Clipboard support uses the OS clipboard or installed `wl-copy` / `xclip`; otherwise copy the printed line. Secrets are represented by phone aliases or environment variable @@ -35,15 +47,15 @@ Raw `write` retains envelope-only validation for forward compatibility; use `--`; literal values containing a flag should be passed after `--` where supported. ```sh -sidepulse-net animations validate --file build.LED --quiet -sidepulse-net animations preview --file build.LED --model dot --at 500 --json -sidepulse-net state Working --phone default --quiet -sidepulse-net devices --json -sidepulse-net about credits --json -sidepulse-net about licenses --full -sidepulse-net about github -sidepulse-net about github --open -sidepulse-net docs --offline +spn animations validate --file build.LED --quiet +spn animations preview --file build.LED --model dot --at 500 --json +spn state Working --phone default --quiet +spn devices --json +spn about credits --json +spn about licenses --full +spn about github +spn about github --open +spn docs --offline ``` `about` includes manufacturer, project and upstream links, credits, dependency diff --git a/docs/wiki/Terminal-Experience.md b/docs/wiki/Terminal-Experience.md index 519d160..cb1f365 100644 --- a/docs/wiki/Terminal-Experience.md +++ b/docs/wiki/Terminal-Experience.md @@ -31,12 +31,12 @@ complete desktop-style terminal UI framework. ## Proposed commands ```powershell -sidepulse-net -sidepulse-net link -sidepulse-net state working -sidepulse-net devices list --json -sidepulse-net integrations install copilot -sidepulse-net doctor +spn +spn link +spn state working +spn devices list --json +spn integrations install copilot +spn doctor ``` These commands are proposals, not installation instructions. Reserve `--quiet`, diff --git a/docs/wiki/Updating.md b/docs/wiki/Updating.md index 8857c8f..1e8627d 100644 --- a/docs/wiki/Updating.md +++ b/docs/wiki/Updating.md @@ -1,14 +1,14 @@ # Checking and installing updates ```sh -sidepulse-net update -sidepulse-net update check --json -sidepulse-net update check --prerelease -sidepulse-net update install --prerelease --dry-run -sidepulse-net host stop -sidepulse-net update install --prerelease -sidepulse-net update status --json -sidepulse-net host start --phone default +spn update +spn update check --json +spn update check --prerelease +spn update install --prerelease --dry-run +spn host stop +spn update install --prerelease +spn update status --json +spn host start --phone default ``` A bare `update` checks only in scripts; in a terminal it offers a cursor menu. @@ -32,8 +32,10 @@ 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 first updater-capable preview is 0.1.0-alpha.6. Older versions must be upgraded -manually once. The install directory and its parent must be writable; the updater +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. +The install directory and its parent must be writable; the updater never elevates privileges. Package-manager installations should use that manager. Run the command from outside the installation directory. Stop the agent host and diff --git a/scripts/release_checksums.py b/scripts/release_checksums.py index b5dd053..c022394 100644 --- a/scripts/release_checksums.py +++ b/scripts/release_checksums.py @@ -6,7 +6,7 @@ def write(directory): root = Path(directory) - expected = {f'sidepulse-net-{platform}-{arch}' + ('.zip' if platform == 'win' else '.tar.gz') + expected = {f'spn-{platform}-{arch}' + ('.zip' if platform == 'win' else '.tar.gz') for platform in ('win', 'linux', 'osx') for arch in ('x64', 'arm64')} archives = {p.name: p for p in root.iterdir() if p.is_file() and (p.name.endswith('.zip') or p.name.endswith('.tar.gz'))} if set(archives) != expected: diff --git a/scripts/terminal_smoke.py b/scripts/terminal_smoke.py index 316d825..3074122 100644 --- a/scripts/terminal_smoke.py +++ b/scripts/terminal_smoke.py @@ -25,7 +25,7 @@ def main(executable): class Terminal: def __init__(self, args): self.master, slave = pty.openpty() - fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 40, 120, 0, 0)) + fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 30, 100, 0, 0)) self.process = subprocess.Popen([executable, *args], stdin=slave, stdout=slave, stderr=slave, env=env) os.close(slave) self.output = b'' @@ -41,7 +41,7 @@ def until(self, text): break self.output += data if needle in self.output: - self.output = b'' + self.output = self.output[self.output.index(needle) + len(needle):] return if self.process.poll() is not None: break @@ -69,11 +69,45 @@ def finish(self): menu = Terminal([]) try: - menu.until('About') - menu.send(b'\x1b[A\r') # wrap from Animations to About + menu.until('Quit') + menu.send(b'\x1b') # Esc at Home never exits. + menu.until('Quit') + menu.send(b'/') + menu.until('Actions') + menu.send(b'Help\r') # searchable action palette + for _ in range(4): + menu.until('Manufacturer website') + if _ == 0: + menu.send(b'\x1b[B' * 4) + menu.send(b'\r') + menu.until('Peter Kuhar') menu.until('Manufacturer website') - menu.send(b'\x1b[B' * 4 + b'\r') - menu.until('Peter Kuhar') + menu.send(b'\x1b') + menu.until('Quit') + menu.send(b'/') + menu.until('Actions') + menu.send(b'Send\r') + menu.until('Preview mode: off') + menu.send(b'\r') # Live send fails; remain in the same workspace. + menu.until('No output found') + menu.until('Preview mode: off') + fcntl.ioctl(menu.master, termios.TIOCSWINSZ, struct.pack('HHHH', 20, 60, 0, 0)) + menu.send(b'\x1b[B' * 6 + b'\r') # Enable Preview once. + for _ in range(5): + menu.until('Preview mode: on') + menu.send(b'\r') + menu.until('LED preview') + menu.until('Preview mode: on') + menu.send(b'\x1b') + menu.until('Quit') + menu.send(b'\x1b[B' * 2 + b'\r') # Devices & phones + menu.until('Mounted devices') + menu.send(b'\r') + menu.until('Completed: devices') + menu.until('Mounted devices') + menu.send(b'\x1b') + menu.until('Quit') + menu.send(b'\x1b[A' * 3 + b'\r') # explicit Quit menu.finish() finally: if menu.process.poll() is None: @@ -101,7 +135,7 @@ def finish(self): finally: if editor.process.poll() is None: editor.process.kill() - print('Cursor menus, Spectre preview controls and editor save passed.') + print('Persistent navigation, ten actions across three sections, failed-send recovery, narrow preview and editor save passed.') if __name__ == '__main__': diff --git a/scripts/tests/test_release.py b/scripts/tests/test_release.py new file mode 100644 index 0000000..43dbf20 --- /dev/null +++ b/scripts/tests/test_release.py @@ -0,0 +1,65 @@ +import hashlib +import io +import json +from pathlib import Path +import sys +import tarfile +import tempfile +import unittest +import zipfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from verify_release import verify + + +class ReleaseTests(unittest.TestCase): + def packages(self, root, corrupt=False, wrong_version=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'] + 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', + '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: + files[names[0]] = b'changed after manifest generation' + if platform == 'win': + with zipfile.ZipFile(root / f'spn-{runtime}.zip', 'w') as package: + for name, data in files.items(): + package.writestr(name, data) + else: + with tarfile.open(root / f'spn-{runtime}.tar.gz', 'w:gz') as package: + for name, data in files.items(): + info = tarfile.TarInfo('./' + name) + info.size = len(data) + package.addfile(info, io.BytesIO(data)) + + def test_complete_six_runtime_set_is_verified(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root) + verify(root, '0.1.0-beta.1') + self.assertEqual(6, len((root / 'SHA256SUMS').read_text().splitlines())) + (root / 'spn-win-arm64.zip').unlink() + with self.assertRaises(ValueError): + verify(root, '0.1.0-beta.1') + + def test_corrupt_package_cannot_become_a_release(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root, corrupt=True) + with self.assertRaisesRegex(ValueError, 'hash mismatch'): + verify(root, '0.1.0-beta.1') + + def test_project_and_package_version_must_agree(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root, wrong_version=True) + with self.assertRaisesRegex(ValueError, 'version, runtime or format mismatch'): + verify(root, '0.1.0-beta.1') + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/verify_release.py b/scripts/verify_release.py new file mode 100644 index 0000000..bea7ef6 --- /dev/null +++ b/scripts/verify_release.py @@ -0,0 +1,63 @@ +"""Verify the six release archives against their embedded installation manifests.""" +import hashlib +import json +from pathlib import Path, PurePosixPath +import sys +import tarfile +import zipfile + +from release_checksums import write + + +def verify(directory, version): + root = Path(directory) + # Enforce the exact runtime set before checking any contents. + write(root) + for platform in ('win', 'linux', 'osx'): + for architecture in ('x64', 'arm64'): + runtime = f'{platform}-{architecture}' + archive = root / (f'spn-{runtime}' + ('.zip' if platform == 'win' else '.tar.gz')) + files = {} + if platform == 'win': + with zipfile.ZipFile(archive) as package: + for item in package.infolist(): + if item.is_dir(): + continue + if (item.external_attr >> 16) & 0o170000 not in (0, 0o100000): + raise ValueError('Release contains a link or special file') + add(files, item.filename, package.read(item)) + else: + with tarfile.open(archive, 'r:gz') as package: + for item in package: + if item.isdir(): + continue + if not item.isfile(): + 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: + raise ValueError('Release manifest version, runtime or format mismatch') + entries = manifest['Files'] + if len({entry['Path'] for entry in entries}) != len(entries): + raise ValueError('Duplicate manifest file') + if set(files) != {entry['Path'] for entry in entries}: + 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 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: + if hashlib.sha256(files[entry['Path']]).hexdigest().lower() != entry['Sha256'].lower(): + raise ValueError('Release file hash mismatch: ' + entry['Path']) + print(f'Verified {archive.name}: {len(files)} files, version {version}') + + +def add(files, name, data): + path = PurePosixPath(name) + if path.is_absolute() or any(part in ('', '.', '..') for part in name.split('/')) or '\\' in name or ':' in name or name in files: + raise ValueError('Unsafe or duplicate archive path') + files[name] = data + + +if __name__ == '__main__': + verify(*sys.argv[1:]) diff --git a/src/SidePulse.Cli/Agents.cs b/src/SidePulse.Cli/Agents.cs index b0c9c39..9af2e13 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 ?? "sidepulse-net"; + public string Executable { get; init; } = Environment.ProcessPath ?? ApplicationIdentity.Command; [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/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index 14fc6d8..af36916 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -228,8 +228,8 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting public sealed class HookConfigSettings : CommandSettings { [CommandOption("--exe ")] - [Description("Absolute path to a published sidepulse-net executable.")] - public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net"; + [Description("Absolute path to a published spn executable.")] + public string Executable { get; init; } = Environment.ProcessPath ?? ApplicationIdentity.Command; [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 b22a4f2..ab4325c 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 ?? "sidepulse-net"; + public string Executable { get; init; } = Environment.ProcessPath ?? ApplicationIdentity.Command; public override ValidationResult Validate() { var result = base.Validate(); diff --git a/src/SidePulse.Cli/Interactive.cs b/src/SidePulse.Cli/Interactive.cs index ea6e74d..9e053fe 100644 --- a/src/SidePulse.Cli/Interactive.cs +++ b/src/SidePulse.Cli/Interactive.cs @@ -7,6 +7,8 @@ namespace SidePulse.Cli; public sealed record MenuItem(string Label, string[]? Arguments = null); public static class Interactive { + private static readonly Dictionary Selections = new(); + public static bool InSession { get; set; } public static string[]? Resolve(string[] args) { if (!TerminalMode.Interactive) @@ -34,12 +36,12 @@ public static class Interactive public static MenuItem? Choose(string title, IReadOnlyList items) { if (!TerminalMode.Interactive) throw new ArgumentException("This action requires an interactive terminal."); - var selected = 0; + var selected = InSession ? Math.Clamp(Selections.GetValueOrDefault(title), 0, items.Count - 1) : 0; MenuItem? result = null; IRenderable Draw() { var rows = items.Select((item, i) => (IRenderable)new Text((i == selected ? "> " : " ") + item.Label, i == selected ? new Style(Color.Cyan1, decoration: Decoration.Bold) : Style.Plain)).ToList(); - rows.Add(new Text("\n↑/↓ select · Enter continue · Esc back", new Style(Color.Grey))); + rows.Add(new Text(InSession ? "\n↑/↓ select · Enter continue · Esc back · / actions" : "\n↑/↓ select · Enter continue · Esc back", new Style(Color.Grey))); if (items[selected].Arguments is { } arguments) rows.Add(new Panel(new Text(TerminalMode.Command(arguments))).Header("Script command").Border(BoxBorder.Rounded)); return new Panel(new Rows(rows)).Header(Markup.Escape(title)).Border(BoxBorder.Rounded); } @@ -48,11 +50,14 @@ IRenderable Draw() live.Refresh(); while (true) { - var key = Console.ReadKey(true).Key; + var input = Console.ReadKey(true); + var key = input.Key; + if (InSession && input.KeyChar == '/') throw new ActionPaletteRequested(); if (key == ConsoleKey.Escape) break; if (key == ConsoleKey.Enter) { result = items[selected]; break; } if (key == ConsoleKey.UpArrow) selected = (selected + items.Count - 1) % items.Count; if (key == ConsoleKey.DownArrow) selected = (selected + 1) % items.Count; + if (InSession) Selections[title] = selected; live.UpdateTarget(Draw()); live.Refresh(); } }); @@ -74,7 +79,7 @@ IRenderable Draw() catch (ArgumentException ex) { Console.Error.WriteLine(ex.Message); shell = TerminalMode.Shell; } } } - private static List Target() + internal static List Target() { var kind = Pick("Output target", new[] { "USB / SD", "Saved phone", "Token environment variable" }); return kind switch @@ -84,7 +89,7 @@ private static List Target() _ => ["--device", Path.GetFullPath(Ask("Mount directory or LEDS.LED path"))] }; } - private static string[]? Build(string group) + internal static string[]? Build(string group) { if (group == "update") { diff --git a/src/SidePulse.Cli/Links.cs b/src/SidePulse.Cli/Links.cs index 5d2184f..1b91ce1 100644 --- a/src/SidePulse.Cli/Links.cs +++ b/src/SidePulse.Cli/Links.cs @@ -155,7 +155,7 @@ public override async Task ExecuteAsync(CommandContext context, PairPhoneSe var phone = await pairing; store.Add(phone); AnsiConsole.MarkupLine("[green]Linked and saved securely:[/] " + Markup.Escape(phone.Name)); - AnsiConsole.WriteLine($"Try: sidepulse-net state done --phone {phone.Alias}"); + AnsiConsole.WriteLine($"Try: spn state done --phone {phone.Alias}"); return 0; } finally diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index 30571c6..ddfe613 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -1,23 +1,30 @@ using Spectre.Console; using Spectre.Console.Cli; using SidePulse.Cli; +using SidePulse.Core; args = TerminalMode.Configure(args); -try { args = Interactive.Resolve(args) ?? []; } -catch (Exception ex) { return TerminalMode.Error(ex); } -if (args.Length == 0) return 0; - -if (args.Length == 1 && args[0] == "update") args = ["update", "check"]; - -// Preserve the original foreground shorthand while adding lifecycle subcommands. -if (args.Length >= 1 && args[0] == "host" && (args.Length == 1 || args[1].StartsWith('-') && args[1] is not "--help" and not "-h")) - args = new[] { "host", "run" }.Concat(args.Skip(1)).ToArray(); +var session = ShellSession.ShouldStart(args); +if (!session) +{ + try { args = Interactive.Resolve(args) ?? []; } + catch (Exception ex) { return TerminalMode.Error(ex); } + if (args.Length == 0) return 0; +} +static string[] Normalize(string[] command) +{ + if (command.Length == 1 && command[0] == "update") return ["update", "check"]; + if (command.Length >= 1 && command[0] == "host" && (command.Length == 1 || command[1].StartsWith('-') && command[1] is not "--help" and not "-h")) + return new[] { "host", "run" }.Concat(command.Skip(1)).ToArray(); + return command; +} +args = Normalize(args); using var logOutput = HostLogs.Redirect(args); var app = new CommandApp(); app.Configure(config => { config.ConfigureConsole(AnsiConsole.Console); - config.SetApplicationName("sidepulse-net"); + config.SetApplicationName(ApplicationIdentity.Command); config.SetApplicationVersion(ProjectInfo.Version); config.AddBranch("animations", animations => { @@ -94,5 +101,5 @@ return TerminalMode.Error(exception); }); }); -try { return app.Run(args); } +try { return session ? new ShellSession((command, token) => app.Run(Normalize(command), token)).Run(args) : app.Run(args); } catch (Exception ex) { return TerminalMode.Error(ex); } diff --git a/src/SidePulse.Cli/ShellSession.cs b/src/SidePulse.Cli/ShellSession.cs new file mode 100644 index 0000000..88a4be9 --- /dev/null +++ b/src/SidePulse.Cli/ShellSession.cs @@ -0,0 +1,130 @@ +using SidePulse.Core; +using Spectre.Console; + +namespace SidePulse.Cli; + +public sealed class ActionPaletteRequested : Exception; + +/// Owns navigation; command execution happens only after menu rendering ends. +public sealed class ShellSession(Func execute) +{ + private static readonly MenuItem[] Home = [new("Send state"), new("Animations"), new("Devices & phones"), + new("Agents & host"), new("Settings"), new("Help & about"), new("Quit")]; + private static readonly string[] Groups = ["about", "animations", "agents", "link", "host", "profiles", "update"]; + private readonly List target = []; + private readonly Stack parents = new(); + private bool preview; + private string? recent; + public static bool ShouldStart(string[] args) => TerminalMode.Interactive && (args.Length == 0 || args.Length == 1 && Groups.Contains(args[0])); + + public int Run(string[] args) + { + string? section = args.FirstOrDefault(); + Interactive.InSession = true; + try + { + while (true) + { + try + { + if (section is null) + { + if (recent is not null) Console.WriteLine(recent); + var action = Interactive.Choose("SidePulse.NET · Home", Home); + if (action is null) continue; // Home Esc is navigation, never Quit. + if (action.Label == "Quit") return 0; + section = action.Label; + } + if (section == "Send state") { SendState(); section = null; continue; } + if (section == "Devices & phones") + { + var action = Interactive.Choose(section, [new("Mounted devices", ["devices"]), new("Saved phones"), new("Back")]); + if (action is null || action.Label == "Back") { section = Back(); continue; } + if (action.Arguments is { } command) RunCommand(command); else { parents.Push(section); section = "link"; } + continue; + } + if (section == "Agents & host") + { + var action = Interactive.Choose(section, [new("Agent integrations"), new("Background host"), new("Back")]); + if (action is not null && action.Label != "Back") parents.Push(section); + section = action?.Label switch { "Agent integrations" => "agents", "Background host" => "host", _ => Back() }; + continue; + } + if (section == "Settings") + { + var action = Interactive.Choose(section, [new("Diagnostics", ["doctor"]), 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; + } + var group = section switch { "Animations" => "animations", "Help & about" => "about", _ => section }; + var next = Interactive.Build(group); + if (next is null) section = Back(); else RunCommand(next); + } + catch (ActionPaletteRequested) + { + // Spectre's prompt owns the terminal only after the previous Live is disposed. + var previous = section; + section = AnsiConsole.Prompt(new SelectionPrompt().Title("Actions").EnableSearch() + .AddChoices(Home.Select(item => item.Label).Prepend("Back"))); + if (section == "Quit") return 0; + if (section == "Back") section = previous; + else parents.Clear(); + } + catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException) + { + recent = "Action failed: " + ex.Message; + Console.Error.WriteLine(recent); + } + } + } + finally { Interactive.InSession = false; } + } + + private string? Back() => parents.TryPop(out var parent) ? parent : null; + + private void SendState() + { + while (true) + { + var items = new[] { AgentState.Working, AgentState.Waiting, AgentState.Done, AgentState.Error, AgentState.Idle, AgentState.Unknown }.Select(state => new MenuItem(state.ToString(), ["state", state.ToString(), .. target, .. (preview ? new[] { "--dry-run" } : Array.Empty())])).ToList(); + items.AddRange([new(preview ? "Preview mode: on" : "Preview mode: off"), new("Change output"), new("Back")]); + var selected = Interactive.Choose("Send state · " + (preview ? "Preview" : "Live") + " · " + (target.Count == 0 ? "Auto: USB, then default phone" : string.Join(' ', target)), items); + if (selected is null || selected.Label == "Back") return; + if (selected.Arguments is { } command) { RunCommand(command); continue; } + if (selected.Label.StartsWith("Preview mode:", StringComparison.Ordinal)) { preview = !preview; continue; } + var output = Interactive.Choose("Output", [new("Auto: USB, then default phone"), new("USB / SD"), new("Saved phone"), new("Back")]); + if (output is null || output.Label == "Back") continue; + if (output.Label.StartsWith("Auto:", StringComparison.Ordinal)) { target.Clear(); continue; } + if (output.Label == "Saved phone") + { + var phones = File.Exists(LinkStore.DefaultPath) ? PhoneStores.Open().List() : []; + if (phones.Count == 0) { Console.WriteLine("No saved phones. Pair one under Devices & phones."); continue; } + var phone = Interactive.Choose("Saved phones", phones.Select(item => new MenuItem(item.Name + " (" + item.Alias + ")", ["--phone", item.Alias])).ToArray()); + if (phone?.Arguments is { } choice) { target.Clear(); target.AddRange(choice); } + } + else + { + var devices = DeviceTransport.Discover(); + if (devices.Count == 0) { Console.WriteLine("No mounted devices. Connect SidePulse or select a phone."); continue; } + var device = Interactive.Choose("Mounted devices", devices.Select(item => new MenuItem(item.Label, ["--device", item.Path])).ToArray()); + if (device?.Arguments is { } choice) { target.Clear(); target.AddRange(choice); } + } + } + } + + private void RunCommand(string[] args) + { + using var cancellation = new CancellationTokenSource(); + ConsoleCancelEventHandler cancel = (_, input) => { input.Cancel = true; cancellation.Cancel(); }; + Console.CancelKeyPress += cancel; + try + { + 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); + } + catch (OperationCanceledException) { recent = "Cancelled."; Console.WriteLine(recent); } + finally { Console.CancelKeyPress -= cancel; } + } +} diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index 252636b..abb0111 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -1,8 +1,8 @@ Exe - sidepulse-net - 0.1.0-alpha.6 + spn + 0.1.0-beta.1 Unofficial SidePulse companion MIT @@ -20,5 +20,6 @@ + diff --git a/src/SidePulse.Cli/TerminalMode.cs b/src/SidePulse.Cli/TerminalMode.cs index 3aeed8a..3c86b6e 100644 --- a/src/SidePulse.Cli/TerminalMode.cs +++ b/src/SidePulse.Cli/TerminalMode.cs @@ -1,5 +1,7 @@ using System.Diagnostics; using System.Text; +using System.Text.RegularExpressions; +using SidePulse.Core; using Spectre.Console; namespace SidePulse.Cli; @@ -21,6 +23,9 @@ public static string[] Configure(string[] args) ColorEnabled = !noColor; if (Quiet && !Json) Console.SetOut(TextWriter.Null); if (noColor || Quiet) AnsiConsole.Console = AnsiConsole.Create(new AnsiConsoleSettings { Out = new AnsiConsoleOutput(Console.Out), Ansi = Console.IsOutputRedirected || Quiet ? AnsiSupport.No : AnsiSupport.Detect, ColorSystem = ColorSystemSupport.NoColors, Enrichment = new ProfileEnrichment { UseDefaultEnrichers = false } }); + // Use the same actual TTY/flag decision for Spectre prompts and our key loop. + // CI markers alone do not make a genuine attached PTY non-interactive. + AnsiConsole.Profile.Capabilities.Interactive = Interactive; var literal = false; var result = args.Where(a => { if (a == "--") literal = true; return literal || a is not "--quiet" and not "--no-interactive" and not "--no-color"; }).ToList(); // Spectre binds JSON to individual commands; normalize a leading global spelling. @@ -38,7 +43,12 @@ public static int Error(Exception exception) else Console.Error.WriteLine("Error: " + exception.Message); return 1; } - public static string Quote(string value, string shell) => value.IndexOfAny(['\r', '\n']) >= 0 ? throw new ArgumentException("Multiline values cannot be exported as a single-line command. Use a file instead.") : shell switch + public static string Quote(string value, string shell) + { + if (value.IndexOfAny(['\r', '\n', '\0']) >= 0) throw new ArgumentException("Multiline or NUL values cannot be exported as a single-line command. Use a file instead."); + if (shell is not ("powershell" or "bash" or "cmd")) throw new ArgumentException("Choose powershell, bash or cmd."); + if (Regex.IsMatch(value, @"\A[A-Za-z0-9_./:-]+\z", RegexOptions.CultureInvariant)) return value; + return shell switch { "powershell" => "'" + value.Replace("'", "''") + "'", "bash" => "'" + value.Replace("'", "'\"'\"'") + "'", @@ -46,12 +56,33 @@ public static int Error(Exception exception) "cmd" when value.IndexOfAny(['%', '!', '"', '\r', '\n']) >= 0 => throw new ArgumentException("This value cannot safely be exported for CMD. Choose PowerShell instead."), "cmd" => "\"" + value.TrimEnd('\\') + new string('\\', 2 * (value.Length - value.TrimEnd('\\').Length)) + "\"", _ => throw new ArgumentException("Choose powershell, bash or cmd.") - }; - public static string Command(IEnumerable args, string? shell = null) + }; + } + public static string Command(IEnumerable args, string? shell = null, string? executable = null) { shell ??= Shell; + executable ??= Invocation(); + var invocation = Quote(executable, shell); + if (shell == "powershell" && invocation.StartsWith('\'')) invocation = "& " + invocation; var values = args.Select(a => Quote(a, shell)); - return "sidepulse-net " + string.Join(' ', values); + return invocation + " " + string.Join(' ', values); + } + private static string Invocation() + { + var process = Environment.ProcessPath; + if (process is null || !Path.GetFileName(process).Equals(ApplicationIdentity.CurrentExecutable, StringComparison.OrdinalIgnoreCase)) return ApplicationIdentity.Command; + foreach (var entry in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)) + { + if (string.IsNullOrWhiteSpace(entry)) continue; + try + { + var candidate = Path.GetFullPath(Path.Combine(entry, ApplicationIdentity.CurrentExecutable)); + if (!File.Exists(candidate)) continue; + return candidate.Equals(process, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ? ApplicationIdentity.Command : process; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException) { } + } + return process; } public static void Footer(IEnumerable args, string? shell = null) => AnsiConsole.Write(new Panel(new Text(Command(args, shell))).Header("Script command").Border(BoxBorder.Rounded)); public static bool Copy(string text) diff --git a/src/SidePulse.Cli/Updates.cs b/src/SidePulse.Cli/Updates.cs index 6d3f25e..cc4b7e1 100644 --- a/src/SidePulse.Cli/Updates.cs +++ b/src/SidePulse.Cli/Updates.cs @@ -31,7 +31,7 @@ public static string Target } public static async Task Probe(string target, string version, CancellationToken cancellationToken) { - var executable = Path.Combine(target, OperatingSystem.IsWindows() ? "sidepulse-net.exe" : "sidepulse-net"); + var executable = Path.Combine(target, ApplicationIdentity.CurrentExecutable); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TimeSpan.FromSeconds(15)); var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true, WorkingDirectory = target }; start.ArgumentList.Add("--version"); @@ -69,10 +69,10 @@ public override async Task ExecuteAsync(CommandContext context, UpdateSetti if (!check.Available) throw new IOException("The release is missing a package or SHA256SUMS; update refused."); if (settings.DryRun) { Updater.Print(settings, new { state = "planned", check }, $"Would download, verify and install {check.Asset} ({check.Latest}) into {Updater.Target}."); return 0; } var installed = InstallationManifest.Read(Updater.Target); - if (installed.Version != ProjectInfo.Version || installed.Runtime != check.Runtime || Path.GetFileName(Environment.ProcessPath) != (OperatingSystem.IsWindows() ? "sidepulse-net.exe" : "sidepulse-net")) throw new IOException("Self-update requires an unmodified self-contained release installation."); + if (installed.Version != ProjectInfo.Version || installed.Runtime != check.Runtime || Path.GetFileName(Environment.ProcessPath) != (ApplicationIdentity.CurrentExecutable)) throw new IOException("Self-update requires an unmodified self-contained release installation."); using var gate = UpdateTransaction.Lock(Updater.Target); if (UpdateTransaction.Status(Updater.Target)?.State is "prepared" or "scheduled" or "applying" or "recovery-required") throw new IOException("An update is pending or needs recovery. Run update status first."); - if ((await HostControl.Request("status", deadline.Token)).Running) throw new IOException("Stop the agent host with 'sidepulse-net host stop' before updating, then restart it after update status reports installed."); + if ((await HostControl.Request("status", deadline.Token)).Running) throw new IOException("Stop the agent host with 'spn host stop' before updating, then restart it after update status reports installed."); var working = Path.GetFullPath(Environment.CurrentDirectory).TrimEnd(Path.DirectorySeparatorChar); if (working.Equals(Updater.Target, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) || working.StartsWith(Updater.Target + Path.DirectorySeparatorChar, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) throw new IOException("Run the update from outside the installation directory so its folder can be replaced."); installed.Verify(Updater.Target, false); @@ -89,14 +89,14 @@ public override async Task ExecuteAsync(CommandContext context, UpdateSetti await UpdatePackage.Extract(archive, stage, release.Version, check.Runtime, deadline.Token); using var current = Process.GetCurrentProcess(); plan = UpdateTransaction.Prepare(Updater.Target, stage, job, release.Version, check.Runtime, current.Id, current.StartTime.ToUniversalTime().Ticks); - var helper = Path.Combine(job, "helper", OperatingSystem.IsWindows() ? "sidepulse-net.exe" : "sidepulse-net"); + var helper = Path.Combine(job, "helper", ApplicationIdentity.CurrentExecutable); var start = new ProcessStartInfo(helper) { UseShellExecute = OperatingSystem.IsWindows(), WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, RedirectStandardInput = !OperatingSystem.IsWindows(), RedirectStandardOutput = !OperatingSystem.IsWindows(), RedirectStandardError = !OperatingSystem.IsWindows(), WorkingDirectory = job }; foreach (var argument in new[] { "internal-update", "--plan", Path.Combine(job, "plan.json") }) start.ArgumentList.Add(argument); UpdateTransaction.Receipt(plan, "scheduled"); using var process = Process.Start(start) ?? throw new IOException("Could not launch the update helper."); if (!OperatingSystem.IsWindows()) process.StandardInput.Close(); - Updater.Print(settings, new { state = "scheduled", version = plan.Version, receipt = plan.Receipt, backup = plan.Backup }, "Verified update scheduled. It will apply after this command exits. Run 'sidepulse-net update status' to confirm before restarting the host."); + Updater.Print(settings, new { state = "scheduled", version = plan.Version, receipt = plan.Receipt, backup = plan.Backup }, "Verified update scheduled. It will apply after this command exits. Run 'spn update status' to confirm before restarting the host."); return 0; } catch diff --git a/src/SidePulse.Core/ApplicationIdentity.cs b/src/SidePulse.Core/ApplicationIdentity.cs new file mode 100644 index 0000000..e747f2c --- /dev/null +++ b/src/SidePulse.Core/ApplicationIdentity.cs @@ -0,0 +1,9 @@ +namespace SidePulse.Core; + +public static class ApplicationIdentity +{ + public const string Command = "spn"; + public const string Assembly = Command + ".dll"; + public static string Executable(bool windows) => windows ? Command + ".exe" : Command; + public static string CurrentExecutable => Executable(OperatingSystem.IsWindows()); +} diff --git a/src/SidePulse.Core/HookConfiguration.cs b/src/SidePulse.Core/HookConfiguration.cs index 2670689..9b9c76a 100644 --- a/src/SidePulse.Core/HookConfiguration.cs +++ b/src/SidePulse.Core/HookConfiguration.cs @@ -9,8 +9,8 @@ public static class HookConfiguration public static string Executable(string path) { path = Path.GetFullPath(path); - if (!File.Exists(path) || !Path.GetFileNameWithoutExtension(path).Equals("sidepulse-net", StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException("Use --exe with a published sidepulse-net executable."); + if (!File.Exists(path) || !Path.GetFileNameWithoutExtension(path).Equals(ApplicationIdentity.Command, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Use --exe with a published spn executable."); return path; } public static (string Bash, string PowerShell) Commands(string exe, AgentProvider provider, string name) diff --git a/src/SidePulse.Core/Releases.cs b/src/SidePulse.Core/Releases.cs index 02dfccc..a1b6e0f 100644 --- a/src/SidePulse.Core/Releases.cs +++ b/src/SidePulse.Core/Releases.cs @@ -49,7 +49,7 @@ public sealed class GitHubReleases(HttpClient client) public const string ChecksumsName = "SHA256SUMS"; public const long MaximumArchiveBytes = 512L * 1024 * 1024; public static string RuntimeIdentifier => (OperatingSystem.IsWindows() ? "win" : OperatingSystem.IsMacOS() ? "osx" : OperatingSystem.IsLinux() ? "linux" : throw new PlatformNotSupportedException("Self-update supports Windows, macOS and Linux.")) + "-" + (RuntimeInformation.ProcessArchitecture switch { Architecture.X64 => "x64", Architecture.Arm64 => "arm64", _ => throw new PlatformNotSupportedException("Self-update supports x64 and ARM64.") }); - public static string AssetName(string runtime) => "sidepulse-net-" + runtime + (runtime.StartsWith("win-", StringComparison.Ordinal) ? ".zip" : ".tar.gz"); + public static string AssetName(string runtime) => ApplicationIdentity.Command + "-" + runtime + (runtime.StartsWith("win-", StringComparison.Ordinal) ? ".zip" : ".tar.gz"); private async Task Get(Uri uri, CancellationToken cancellationToken) { using var request = new HttpRequestMessage(HttpMethod.Get, uri); diff --git a/src/SidePulse.Core/UpdatePackage.cs b/src/SidePulse.Core/UpdatePackage.cs index da5249a..f46aaad 100644 --- a/src/SidePulse.Core/UpdatePackage.cs +++ b/src/SidePulse.Core/UpdatePackage.cs @@ -31,8 +31,8 @@ public static InstallationManifest Read(string directory) Relative(file.Path); 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 = manifest.Runtime.StartsWith("win-", StringComparison.Ordinal) ? "sidepulse-net.exe" : "sidepulse-net"; - if (!names.Contains(exe) || !names.Contains("sidepulse-net.dll") || !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."); + 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."); return manifest; } public void Verify(string directory, bool rejectExtras) diff --git a/tests/SidePulse.Tests/AgentTests.cs b/tests/SidePulse.Tests/AgentTests.cs index d6956d2..a096139 100644 --- a/tests/SidePulse.Tests/AgentTests.cs +++ b/tests/SidePulse.Tests/AgentTests.cs @@ -51,7 +51,7 @@ public void GeneratedSchemasContainSilentWrappersAndNoPolicyDecisions() { foreach (var provider in Enum.GetValues()) { - var generated = HookConfiguration.Generate(provider, "/tmp/O'Brien test/sidepulse-net", false); + var generated = HookConfiguration.Generate(provider, "/tmp/O'Brien test/spn", false); var json = generated.ToJsonString(); Assert.DoesNotContain("permissionDecision", json); Assert.DoesNotContain("dangerously", json); @@ -66,7 +66,7 @@ public void GeneratedSchemasContainSilentWrappersAndNoPolicyDecisions() Assert.NotEmpty(generated["hooks"]!.AsArray()); } else Assert.NotEmpty(generated["hooks"]!.AsObject()); - var windows = HookConfiguration.Generate(provider, @"C:\Tools\test\sidepulse-net.exe", true).ToJsonString(); + var windows = HookConfiguration.Generate(provider, @"C:\Tools\test\spn.exe", true).ToJsonString(); if (provider != AgentProvider.Copilot) Assert.Contains("EncodedCommand", windows); } } @@ -79,7 +79,7 @@ public void InstallationPreviewMergeAndUninstallPreserveUnrelatedSettingsExactly var original = "{\n \"permissions\": {\"allow\": [\"Read\"]},\n \"hooks\": {\"Stop\": [{\"hooks\": [{\"type\":\"command\",\"command\":\"my-script\"}]}]}\n}\n"; File.WriteAllText(target, original); var installer = new HookInstallation(Path.Combine(directory, "manifests")); - var fragment = HookConfiguration.Generate(AgentProvider.Claude, "/tmp/sidepulse-net", false); + var fragment = HookConfiguration.Generate(AgentProvider.Claude, "/tmp/spn", false); Assert.Equal("preview", installer.Install(target, AgentProvider.Claude, fragment, true).State); Assert.Equal(original, File.ReadAllText(target)); Assert.False(Directory.Exists(Path.Combine(directory, "manifests"))); @@ -103,9 +103,9 @@ public void ReinstallWithADifferentExecutableFailsWithoutChangingFiles(AgentProv { var target = Path.Combine(directory, "hooks.json"); var installer = new HookInstallation(Path.Combine(directory, "manifests")); - installer.Install(target, provider, HookConfiguration.Generate(provider, "/old/sidepulse-net", false), false); + installer.Install(target, provider, HookConfiguration.Generate(provider, "/old/spn", false), false); var before = File.ReadAllBytes(target); - var error = Assert.Throws(() => installer.Install(target, provider, HookConfiguration.Generate(provider, "/new/sidepulse-net", false), false)); + var error = Assert.Throws(() => installer.Install(target, provider, HookConfiguration.Generate(provider, "/new/spn", false), false)); Assert.Contains("Uninstall", error.Message); Assert.Equal(before, File.ReadAllBytes(target)); }); @@ -117,11 +117,11 @@ public void UninstallPreviewDoesNotCreateALockFile() { var target = Path.Combine(directory, "hooks.json"); var installer = new HookInstallation(Path.Combine(directory, "manifests")); - installer.Install(target, AgentProvider.Codex, HookConfiguration.Generate(AgentProvider.Codex, "/tmp/sidepulse-net", false), false); + installer.Install(target, AgentProvider.Codex, HookConfiguration.Generate(AgentProvider.Codex, "/tmp/spn", false), false); var before = File.ReadAllBytes(target); - File.Delete(target + ".sidepulse-net.lock"); + File.Delete(target + ".spn.lock"); Assert.Equal("preview-remove", installer.Uninstall(target, true).State); - Assert.False(File.Exists(target + ".sidepulse-net.lock")); + Assert.False(File.Exists(target + ".spn.lock")); Assert.Equal(before, File.ReadAllBytes(target)); Assert.Equal("installed", installer.Status(target).State); }); @@ -133,7 +133,7 @@ public void UninstallRefusesChangedSettingsAndInvalidInputIsNotOverwritten() { var target = Path.Combine(directory, "hooks.json"); var installer = new HookInstallation(Path.Combine(directory, "manifests")); - installer.Install(target, AgentProvider.Codex, HookConfiguration.Generate(AgentProvider.Codex, "/tmp/sidepulse-net", false), false); + installer.Install(target, AgentProvider.Codex, HookConfiguration.Generate(AgentProvider.Codex, "/tmp/spn", false), false); File.AppendAllText(target, " "); Assert.Equal("modified", installer.Status(target).State); Assert.Throws(() => installer.Uninstall(target, false)); @@ -150,7 +150,7 @@ public void DedicatedFilesAreRemovedButUnownedFilesAreNeverReplaced() { var target = Path.Combine(directory, "sidepulse-net.json"); var installer = new HookInstallation(Path.Combine(directory, "manifests")); - var fragment = HookConfiguration.Generate(AgentProvider.Kiro, "/tmp/sidepulse-net", false); + var fragment = HookConfiguration.Generate(AgentProvider.Kiro, "/tmp/spn", false); installer.Install(target, AgentProvider.Kiro, fragment, false); installer.Uninstall(target, false); Assert.False(File.Exists(target)); @@ -183,13 +183,13 @@ public void OpenCodeOwnsOnlyItsPluginAndRefusesModifiedOrUnownedFiles() { var target = Path.Combine(directory, "sidepulse-net.js"); var installer = new HookInstallation(Path.Combine(directory, "manifests")); - var generated = HookConfiguration.Generate(AgentProvider.OpenCode, "C:\\O'Brien ü\\sidepulse-net.exe", true); + var generated = HookConfiguration.Generate(AgentProvider.OpenCode, "C:\\O'Brien ü\\spn.exe", true); Assert.Equal("preview", installer.Install(target, AgentProvider.OpenCode, generated, true).State); Assert.False(File.Exists(target)); installer.Install(target, AgentProvider.OpenCode, generated, false); Assert.Equal(generated["plugin"]!.GetValue(), File.ReadAllText(target)); Assert.Equal("installed", installer.Install(target, AgentProvider.OpenCode, generated, false).State); - Assert.Throws(() => installer.Install(target, AgentProvider.OpenCode, HookConfiguration.Generate(AgentProvider.OpenCode, "/new/sidepulse-net", false), false)); + Assert.Throws(() => installer.Install(target, AgentProvider.OpenCode, HookConfiguration.Generate(AgentProvider.OpenCode, "/new/spn", false), false)); File.AppendAllText(target, "// manual edit"); Assert.Throws(() => installer.Uninstall(target, false)); File.WriteAllText(target, generated["plugin"]!.GetValue()); diff --git a/tests/SidePulse.Tests/TerminalTests.cs b/tests/SidePulse.Tests/TerminalTests.cs index 8c1f77b..fc60145 100644 --- a/tests/SidePulse.Tests/TerminalTests.cs +++ b/tests/SidePulse.Tests/TerminalTests.cs @@ -5,6 +5,43 @@ namespace SidePulse.Tests; public sealed class TerminalTests { + [Fact] + public void ExportedArgumentsRoundTripThroughTheNativeShell() + { + var directory = Path.Combine(Path.GetTempPath(), "SidePulse quoting ü " + Guid.NewGuid()); + Directory.CreateDirectory(directory); + var script = Path.Combine(directory, "read arguments.py"); + try + { + File.WriteAllText(script, "import json,sys\nprint(json.dumps(sys.argv[1:]))\n"); + string[] values = ["", "simple", "Ned's ü", "C:\\folder with spaces\\", "a&b|c<>d()", "$HOME`literal"]; + foreach (var shell in OperatingSystem.IsWindows() ? new[] { "powershell", "cmd" } : new[] { "bash" }) + { + var start = new System.Diagnostics.ProcessStartInfo(shell == "powershell" ? "pwsh" : shell) + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, + StandardOutputEncoding = System.Text.Encoding.UTF8 + }; + var command = TerminalMode.Command(new[] { script }.Concat(values), shell, OperatingSystem.IsWindows() ? "python" : "python3"); + // cmd consumes one raw command string; CRT argument-list escaping + // would add backslashes before its shell quotes and change the command. + if (shell == "cmd") start.Arguments = "/d /s /c \"" + command + "\""; + else + { + foreach (var argument in shell == "powershell" ? new[] { "-NoLogo", "-NoProfile", "-NonInteractive", "-Command" } : new[] { "-c" }) start.ArgumentList.Add(argument); + start.ArgumentList.Add(command); + } + using var process = System.Diagnostics.Process.Start(start)!; + var output = process.StandardOutput.ReadToEnd(); + var errors = process.StandardError.ReadToEnd(); + Assert.True(process.WaitForExit(10000), "Shell argument round trip timed out."); + Assert.True(process.ExitCode == 0, errors); + Assert.Equal(values, System.Text.Json.JsonSerializer.Deserialize(output)); + } + } + finally { Directory.Delete(directory, true); } + } + [Fact] public void CommandExportsQuoteLiteralMetacharactersAndRejectMultilineValues() { @@ -15,8 +52,24 @@ public void CommandExportsQuoteLiteralMetacharactersAndRejectMultilineValues() Assert.Throws(() => TerminalMode.Quote("%PATH%", "cmd")); Assert.Throws(() => TerminalMode.Quote("!PATH!", "cmd")); Assert.Throws(() => TerminalMode.Quote("first\nsecond", "bash")); - Assert.StartsWith("sidepulse-net ", TerminalMode.Command(["animations", "preview", value], "bash")); + Assert.StartsWith("spn ", TerminalMode.Command(["animations", "preview", value], "bash")); } + [Fact] + public void SimpleCommandsAreReadableAndPortablePowerShellPathsRemainExecutable() + { + Assert.Equal("spn state working --phone default", TerminalMode.Command(["state", "working", "--phone", "default"], "powershell", "spn")); + Assert.Equal("& 'C:\\Ned''s ü\\spn.exe' state working", TerminalMode.Command(["state", "working"], "powershell", "C:\\Ned's ü\\spn.exe")); + foreach (var shell in new[] { "powershell", "bash", "cmd" }) + { + Assert.Equal("--dry-run", TerminalMode.Quote("--dry-run", shell)); + Assert.NotEqual("", TerminalMode.Quote("", shell)); + Assert.Throws(() => TerminalMode.Quote("nul\0value", shell)); + } + Assert.Equal("spn", SidePulse.Core.ApplicationIdentity.Command); + Assert.Equal("spn.exe", SidePulse.Core.ApplicationIdentity.Executable(true)); + Assert.Equal("spn", SidePulse.Core.ApplicationIdentity.Executable(false)); + } + [Fact] public void CreditsAndOfflineLicensesAreEmbeddedForEveryRuntimePackage() { diff --git a/tests/SidePulse.Tests/UpdateTests.cs b/tests/SidePulse.Tests/UpdateTests.cs index 8d23b91..0e714db 100644 --- a/tests/SidePulse.Tests/UpdateTests.cs +++ b/tests/SidePulse.Tests/UpdateTests.cs @@ -63,7 +63,7 @@ public async Task HashVerificationPrecedesExtractionAndRejectsCorruption() { using var temp = new Temp(); var bytes = Encoding.UTF8.GetBytes("not really a zip; hash verification is independent"); - var asset = "sidepulse-net-win-x64.zip"; + var asset = "spn-win-x64.zip"; var digest = Convert.ToHexString(SHA256.HashData(bytes)); var checksum = Encoding.UTF8.GetBytes(digest + " " + asset + "\n"); var corrupt = false; @@ -183,7 +183,7 @@ public async Task ValidArchivesExtractAndVerifyTheirManifest(bool tarFormat) var manifest = await UpdatePackage.Extract(archive, destination, "2.0.0", "linux-x64"); manifest.Verify(destination, true); Assert.Equal("2.0.0", manifest.Version); - Assert.True(File.Exists(System.IO.Path.Combine(destination, "sidepulse-net"))); + Assert.True(File.Exists(System.IO.Path.Combine(destination, "spn"))); } [Fact] public async Task TarLinksAreRejected() @@ -231,7 +231,7 @@ public async Task ChangedCurrentFilesRefuseSwapAndConcurrentLocksFail() { using var fixture = new Installation(); var plan = fixture.Prepare(); using (var gate = UpdateTransaction.Lock(fixture.Target)) await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => Task.CompletedTask)); - File.WriteAllText(System.IO.Path.Combine(fixture.Target, "sidepulse-net.dll"), "local change"); + File.WriteAllText(System.IO.Path.Combine(fixture.Target, "spn.dll"), "local change"); await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => Task.CompletedTask)); Assert.Equal("1.0.0", InstallationManifest.Read(fixture.Target).Version); } @@ -245,7 +245,7 @@ public void NewOwnedFilesCannotOverwriteUserAddedFiles() Assert.Throws(() => fixture.Prepare()); Assert.Equal("personal", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "custom.txt"))); } - private static object Release(string tag, bool draft = false, bool prerelease = true) => new { tag_name = tag, draft, prerelease, assets = new[] { new { name = "sidepulse-net-linux-x64.tar.gz", size = 10 }, new { name = "SHA256SUMS", size = 100 } } }; + private static object Release(string tag, bool draft = false, bool prerelease = true) => new { tag_name = tag, draft, prerelease, assets = new[] { new { name = "spn-linux-x64.tar.gz", size = 10 }, new { name = "SHA256SUMS", size = 100 } } }; private static HttpResponseMessage Json(string text) => new(HttpStatusCode.OK) { Content = new StringContent(text) }; private sealed class Handler(Func handler) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(handler(request)); } @@ -272,7 +272,7 @@ public Installation() foreach (var (directory, version) in new[] { (Target, "1.0.0"), (Stage, "2.0.0") }) { Directory.CreateDirectory(directory); - foreach (var name in new[] { "sidepulse-net", "sidepulse-net.dll", "libhostfxr.so" }) File.WriteAllText(System.IO.Path.Combine(directory, name), name + version); + foreach (var name in new[] { "spn", "spn.dll", "libhostfxr.so" }) File.WriteAllText(System.IO.Path.Combine(directory, name), name + version); WriteManifest(directory, version); } } diff --git a/tests/SidePulse.Tests/packages.lock.json b/tests/SidePulse.Tests/packages.lock.json index 54e14f2..ab46a49 100644 --- a/tests/SidePulse.Tests/packages.lock.json +++ b/tests/SidePulse.Tests/packages.lock.json @@ -105,19 +105,19 @@ "xunit.extensibility.core": "[2.9.3]" } }, - "sidepulse-net": { + "sidepulse.core": { "type": "Project", "dependencies": { - "QRCoder": "[1.8.1, )", - "SidePulse.Core": "[1.0.0, )", - "Spectre.Console": "[0.57.2, )", - "Spectre.Console.Cli": "[0.57.2, )" + "System.Security.Cryptography.ProtectedData": "[10.0.13, )" } }, - "sidepulse.core": { + "spn": { "type": "Project", "dependencies": { - "System.Security.Cryptography.ProtectedData": "[10.0.13, )" + "QRCoder": "[1.8.1, )", + "SidePulse.Core": "[1.0.0, )", + "Spectre.Console": "[0.57.2, )", + "Spectre.Console.Cli": "[0.57.2, )" } }, "QRCoder": {