diff --git a/changelog.d/provider-uninstall-keep-or-remove.md b/changelog.d/provider-uninstall-keep-or-remove.md new file mode 100644 index 0000000000..1c58bfd098 --- /dev/null +++ b/changelog.d/provider-uninstall-keep-or-remove.md @@ -0,0 +1,8 @@ +### Uninstall Darkbloom: remove everything, or keep the models + +- `darkbloom uninstall` takes Darkbloom off a Mac in one step. In a terminal it shows two choices with this Mac's sizes: **Remove everything** (the app, settings, pairing, logs and all models) or **Keep models** (everything else goes; a reinstall reuses the models). Esc cancels, and **Remove everything** asks once more, with the size of the models it deletes. Run it as yourself: with `sudo` it refuses and says so. +- Both choices stop serving the way `darkbloom stop` does, stop this Mac's part of a two-Mac pair, remove every Darkbloom background service, revoke this Mac's account token where the coordinator can confirm it, unpair, undo the cable port setup (macOS asks for your password) and delete Darkbloom's settings, logs, caches, the app and the `darkbloom` command link. +- **Keep models** leaves the models Darkbloom downloaded and the cluster model store in place: after installing again, `darkbloom start` or `darkbloom cluster` finds them without downloading. The sizes count APFS clones once. +- It never deletes a models folder you chose or the cluster model store beside it, even inside `~/.darkbloom`, nor anything outside Darkbloom's folders (links that point elsewhere, another disk mounted in them), and never touches Keychain keys; the summary lists what was kept and where. When a folder of Darkbloom's could not be removed, the summary says Darkbloom is not fully removed, says why, and the command exits 1. On a paired Mac it ends with what to run on the other Mac. +- On a Mac with both the production and the DevNet app, uninstalling one keeps this Mac's pairing, cluster setup and cable port setup, which the other still uses, removes only its own cluster service, and says so; uninstall the other one too to remove them. When your models folder is `~/.darkbloom` itself, the summary says Darkbloom is not fully removed and what to do. A dry run also names a cluster service running without a login agent. +- For scripts and agents: `--everything` or `--keep-models` with `--yes`, and `--dry-run` (with `--json`) to list every action and path without changing anything. `darkbloom stop --uninstall` works as before. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 5ecb5a7811..8036bc196a 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-11-03 +> Last updated: 2026-11-04 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -155,7 +155,8 @@ Subcommands declared by `Darkbloom.configuration.subcommands`: | `switch` | Gracefully replace hosted models in the running coordinator-connected provider, without restart or reconnect | | `SwitchCommand.swift` (`Switch`) | | `addon` | Debug add-on holds on the running provider: `status` (default), `hold`, `release` | | `AddonCommand.swift` (`Addon`) | | `sandbox` | Set up and manage [Darkbloom Sandbox](./sandboxes.md) CI jobs through its add-on: status (bare), `setup`, `pause`, `resume`, `logs`, `uninstall` | | `Sandbox/SandboxCommand.swift` (`Sandbox`) | -| `stop` | Drain accepted requests, then stop the LaunchAgent; `--uninstall` removes the provider, watchdog and desktop API agents | | `StopCommand.swift` (`Stop`) | +| `stop` | Drain accepted requests, then stop the LaunchAgent; `--uninstall` removes the provider, watchdog and desktop API agents and keeps every file | | `StopCommand.swift` (`Stop`) | +| `uninstall` | Take Darkbloom off this Mac: remove everything, or everything but the models ([below](#darkbloom-uninstall)) | | `UninstallCommand.swift` (`Uninstall`) | | `restart` | Drain, restart with recorded configuration, and confirm fresh authorization | ✓ | `RestartCommand.swift` (`Restart`) | | `status` | Config, hardware, schedule, live daemon state (including the coordinator's last `Trust: / ` message), per-slot KV/MTP posture | ✓ | `StatusCommand.swift` (`Status`) | | `doctor` | Diagnostics (see [troubleshooting](./troubleshooting.md#doctor-checks)) | ✓ | `DoctorCommand.swift` (`Doctor`) | @@ -1279,7 +1280,7 @@ darkbloom stop [--timeout ] [--force] [--uninstall] |---|---|---|---| | `--timeout ` | integer, 0–3600 | `600` | Wait for accepted coordinator requests, local response writes and the coordinator acknowledgement | | `--force` | flag | `false` | Explicitly permit bounded cancellation and termination of unfinished work | -| `--uninstall` | flag | `false` | After draining or explicit force, remove the provider and watchdog plists and boot out and remove the desktop API agent (`io.darkbloom.desktop-api`, best effort) | +| `--uninstall` | flag | `false` | After draining or explicit force, remove the provider and watchdog plists and boot out and remove the desktop API agent (`io.darkbloom.desktop-api`, best effort). Every file, the cluster service and the pairing stay; [`darkbloom uninstall`](#darkbloom-uninstall) takes Darkbloom off the Mac | The command disarms the watchdog and disables login/reboot startup before requesting the drain. If setup fails before the mailbox request is published, @@ -1294,6 +1295,151 @@ Code: `provider-swift/Sources/darkbloom/ServiceDrain.swift` (`DrainOptions`, (`Stop`). See [graceful lifecycle behavior](#graceful-stop-and-restart) for signal handling and launchd's termination allowance. +## `darkbloom uninstall` + +Take Darkbloom off this Mac. In a terminal with no flags it shows two choices +with this Mac's sizes and reads one key: + +```text +Uninstall Darkbloom from this Mac + + 1) Remove everything + The app, settings, pairing, logs and all models · frees 412 GB + 2) Keep models + Removes everything else; a reinstall reuses the 410 GB of models + + Choose 1 or 2 (Esc cancels): +``` + +The sizes are measured on this Mac. APFS clones (the cluster model store clones +the downloaded models) count once, and blocks a clone outside Darkbloom's +folders still uses are not counted. Lines under the choices appear only when +this Mac has folders no choice deletes, or Darkbloom parts with their own +uninstall. + +**1** asks once more, and only `y` or `yes` goes on; anything else changes +nothing (`ProviderUninstall.everythingQuestion`). **2** asks nothing more. + +```text + Remove everything, including 410 GB of models? This can't be undone. [y/N]: +``` + +Run as root (`sudo`), every form of the command, `--dry-run` included, prints +this and exits 64 before it lists or changes anything +(`ProviderUninstall.rootRefusal`): + +```text +Run `darkbloom uninstall` as yourself, not with sudo: it removes your own Darkbloom, and asks for your password when a step needs it. +``` + +```bash +darkbloom uninstall # the screen: 1, 2 or Esc +darkbloom uninstall --keep-models --dry-run # every action and path, with sizes; changes nothing +darkbloom uninstall --keep-models --yes # a reinstall reuses the models +darkbloom uninstall --everything --yes # nothing left behind +``` + +| Flag | Type | Default | Effect | +|---|---|---|---| +| `--everything` | flag | `false` | Remove everything: the app, settings, pairing, logs and all models | +| `--keep-models` | flag | `false` | Remove everything but the models, so a reinstall reuses them | +| `--yes`, `-y` | flag | `false` | Don't ask for confirmation | +| `--dry-run` | flag | `false` | List every action and path with sizes, and change nothing. Without a mode it lists both | +| `--json` | flag | `false` | With `--dry-run`: the plan as JSON (`darkbloom_uninstall_plan_v1`) | +| `--timeout`, `--force` | | | The [stop](#darkbloom-stop) drain options | + +Without a terminal, a mode and `--yes` are required; otherwise the command +prints `Usage: darkbloom uninstall --everything|--keep-models [--yes] [--dry-run [--json]] (no terminal to ask which)` +and exits 64. Both modes together, `--json` without `--dry-run`, or an unknown +flag are refused with the usage before anything runs. + +**The steps, in order, the same for both choices.** Each is idempotent; the +summary lists each one as `done`, `skipped` or `failed`, with the reason, and the +command exits 1 when one failed or when a folder of Darkbloom's was not removed. +A failed step does not stop the safe steps after it. + +| # | Step | Through | Skipped when | +|---|---|---|---| +| 1 | Stop serving on this Mac | the [stop](#darkbloom-stop) drain (`ServiceDrain`) | the provider service was not running | +| 2 | Stop this Mac's cluster part and remove its service | `darkbloom cluster stop`; when the other Mac does not answer, `cluster stop --local-only`. Beside another install that shares the pair (below), it is `Remove this install's cluster service` instead: only this install's own agent (`ClusterServiceAgentPlan.label` of its app) goes, through `ProviderUninstall.removeOwnClusterAgent`; the pair is not stopped and the other install's agent is not touched | no cluster service on this Mac (beside another install: this install has none). The dry run also names a cluster service running without a login agent (`ClusterService.running`), which this step stops | +| 3–5 | Remove the provider, watchdog and desktop API launch agents | what `stop --uninstall` runs (`LaunchAgent.uninstall`, `WatchdogAgent.uninstall`, `DesktopService.uninstall`) | not installed, or serving did not stop in step 1 | +| 6 | Revoke this Mac's account token, best effort | what `darkbloom logout` does (`Logout.revokeSavedToken`) | no saved token, the coordinator did not confirm it, or serving did not stop. It never fails the uninstall; the token file goes with `~/.darkbloom` | +| 7 | Forget the pairing with the other Mac | `darkbloom cluster pair --forget `, once per pairing | this Mac is not paired, or another install on this Mac uses the pairing (below) | +| 8 | Undo the cable port setup | `darkbloom cluster link --remove` (macOS asks for an administrator's password) | nothing to undo, or another install on this Mac uses it (below) | +| 9 | Delete Darkbloom's folders, one step each (table below) | | already gone, refused (`not removed: `), or a service did not stop in steps 1–5. When step 8 did not complete, `~/.darkbloom` and the command link stay, so the command can run again | + +**What is deleted**, from `ProviderUninstallPaths` and `ProviderUninstall.inventory` +in `provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift`: + +| Item | Path | 1) Remove everything | 2) Keep models | +|---|---|---|---| +| Settings | `~/.config/darkbloom` (`provider.toml`, saved cluster setups) | deleted | deleted | +| Encrypted prompt caches | `~/Library/Caches/darkbloom` | deleted | deleted | +| Each model Darkbloom downloaded | `~/.cache/huggingface/hub/models----`, only folders holding Darkbloom's receipt (`.darkbloom-manifest.json`) or its unfinished download (`.local-staging-*`), and `.artifact-writer-locks` | deleted | kept, with their `refs/` and receipts, so a reinstall's scan finds them | +| Cluster model store | `~/.cache/huggingface/darkbloom-cluster-models` | deleted | kept | +| The command link | `/usr/local/bin/darkbloom`, only while it links to `~/.darkbloom/bin/darkbloom` | deleted | deleted | +| Darkbloom folder | `~/.darkbloom`: the app, `bin/`, logs, pairing, account token, cluster setup and service state. Last, since the command runs from the app in it. When a models folder you chose is inside it, everything else in it is deleted, the app last | deleted | deleted | + +What no choice deletes (the summary lists them): + +- anything that resolves outside those folders. A target that is a link, or + whose resolved path is elsewhere, is refused and reported, and a link inside a + deleted folder is removed without following it. A folder that is another + disk's mount point, or holds one, is refused too; +- a models folder you chose (`[backend] model_cache_directory`, set by + `darkbloom models location`) and the cluster model store beside it + (`darkbloom-cluster-models` in the same parent folder), in both choices and + wherever they are. Inside Darkbloom's folders (for example + `~/.darkbloom/models`) they stay with the folders that lead to them, and the + screen, the dry run and the summary list them as `Kept:`; elsewhere, as + `Never touched:`. After a reinstall, `darkbloom models location ` uses + the chosen folder again. When the chosen folder is `~/.darkbloom` itself (or + holds it), the app folder stays with it: the summary's first line says + Darkbloom is not fully removed because its app folder is your models folder, + the step says to move the models out and run `~/.darkbloom/bin/darkbloom + uninstall` again (the settings naming the folder are gone by then, so that run + deletes the rest), and the command exits 1; +- caches in a folder you chose outside Darkbloom's folders + (`darkbloom cache set --directory`), the default model cache when it is a + link, and other tools' models; +- the models and the cluster model store while another Darkbloom install + (`~/.darkbloom-dev`, `~/.darkbloom-staging`) shares them; +- this Mac's pairing, cluster setup and cable port setup while another install + is on this Mac: the production app and the DevNet app (`darkbloom-dev`) use + the same ones. The other install counts when its app or `bin/` command is in + its folder (`ProviderUninstallPaths.otherEnvironment`). Steps 7 and 8 are + skipped (`kept: on this Mac also uses it`), the files + every install shares stay (`~/.darkbloom/cluster*` and + `~/.config/darkbloom/clusters`; the rest of those folders goes), and step 2 + removes only this install's own cluster service. The screen, + the dry run, `--json` and the summary list it, here for `darkbloom-dev + uninstall`, and the summary's first line names the install it removed + (`Darkbloom Dev is removed from this Mac.`): + + ```text + Kept: This Mac's pairing, cluster setup and cable port setup (40 KB, ~/.darkbloom/cluster*): the production Darkbloom on this Mac also uses them. Run `darkbloom uninstall` there to remove them + ``` + +- Keychain items (Secure Enclave and App Attest keys); a new install replaces them; +- the fan helper (`sudo darkbloom fan uninstall`), Darkbloom Sandbox + (`darkbloom sandbox uninstall`), a legacy MDM profile (`darkbloom unenroll`) and + the shell `PATH` line the installer added. + +The summary says what was removed, what was kept and where, and the space freed +(the change in the home volume's free space). When a folder of Darkbloom's was +refused, its step reads `not removed: `, the first line is `Darkbloom is not +fully removed from this Mac: some of its folders were not removed (see below).` +and the command exits 1. A command link the installer did not make is reported +the same way but is not Darkbloom's, so it alone does not count. After **Keep models** it ends with +the way back: the install command, then `darkbloom start` or `darkbloom cluster`; +the models are found automatically. On a paired Mac its last line names the other +Mac: run `darkbloom uninstall` there too, or `darkbloom cluster` on it to pair it +with another Mac. + +Code: `provider-swift/Sources/darkbloom/UninstallCommand.swift` (`Uninstall`) and +`provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift` +(`ProviderUninstall.run`). + ## `darkbloom restart` Drain accepted work, reload the recorded launchd configuration, and confirm a diff --git a/docs/provider/installation.md b/docs/provider/installation.md index c357d0d2b8..9306bceda8 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -1,6 +1,6 @@ # Install, update, and uninstall the provider -> Last updated: 2026-11-02 +> Last updated: 2026-11-04 How to put the `darkbloom` CLI on an Apple Silicon Mac with `scripts/install.sh`, what the script verifies before it touches an existing install, how the binary @@ -289,35 +289,62 @@ each Mac: `darkbloom cluster`; no SSH, no network settings typed). ## Uninstall +One command takes Darkbloom off this Mac. In a terminal it shows two choices +with this Mac's sizes and reads one key (Esc cancels): + +```bash +darkbloom uninstall +``` + +1. **Remove everything.** The app, settings, pairing, logs and all models. It + asks once more, with the size of the models it deletes; only `y` goes on. +2. **Keep models.** Removes everything else; a reinstall reuses the models. + +Run it as yourself, not with `sudo`: it refuses to run as root, and macOS asks +for the password when a step needs it. + +Both choices stop serving (the drain of `darkbloom stop`), stop this Mac's +part of a two-Mac pair, remove every Darkbloom background service, revoke this +Mac's account token, forget the pairing, undo the cable port setup (macOS asks +for an administrator's password) and delete `~/.config/darkbloom`, +`~/Library/Caches/darkbloom`, the `/usr/local/bin/darkbloom` link and +`~/.darkbloom`, which holds the app, logs and pairing. **Remove everything** also +deletes the models Darkbloom downloaded into `~/.cache/huggingface/hub` and the +cluster model store. **Keep models** leaves them where they are: after +reinstalling, `darkbloom start` or `darkbloom cluster` finds them without +downloading. The summary lists each step as done, skipped or failed, what was +kept and where, and the space freed. If the cable port setup could not be +undone, `~/.darkbloom` stays so you can run it again. + +For scripts and agents: + +```bash +darkbloom uninstall --keep-models --dry-run # every action and path, with sizes; changes nothing (--json too) +darkbloom uninstall --keep-models --yes +darkbloom uninstall --everything --yes +``` + +No choice deletes a models folder you chose or the cluster model store beside +it, even inside `~/.darkbloom` (the rest of that folder goes), caches in a +folder you chose, anything that resolves outside Darkbloom's folders, or +Keychain keys (a new install replaces them). With both the production and the +DevNet app on this Mac, uninstalling one keeps this Mac's pairing, cluster setup +and cable port setup, which the other uses; uninstall that one too to remove +them. Remove what it leaves first, if you +use it: + ```bash -sudo darkbloom fan uninstall # only if fan control was enabled -darkbloom cluster link --remove # only if `darkbloom cluster` set up a two-Mac link; asks for approval -darkbloom stop --uninstall # stops the daemon, removes both LaunchAgent plists -darkbloom unenroll # opens System Settings to remove the MDM profile; offers to delete config + tokens -rm -rf ~/.darkbloom ~/.config/darkbloom -sudo rm -f /usr/local/bin/darkbloom +sudo darkbloom fan uninstall # fan control: restores macOS automatic control +darkbloom sandbox uninstall # Darkbloom Sandbox +darkbloom unenroll # a legacy MDM profile ``` -`darkbloom cluster link --remove` (`provider-swift/Sources/darkbloom/ClusterLinkCommand.swift`) -restores what `darkbloom cluster` changed for a two-Mac link: it removes the -network service `Darkbloom Cluster Link ()`, switches the services it -turned off on that port on again and puts the port back into its bridge, or, -for a link set up by an earlier version, removes the root launchd job -`io.darkbloom.cluster-link.` and the address it kept. Run it before -deleting `~/.darkbloom`, which holds the record of what was changed; without -the record it still removes Darkbloom's own service or job. It changes nothing -on a Mac that never ran `darkbloom cluster`. - -`darkbloom stop --uninstall` (`provider-swift/Sources/darkbloom/StopCommand.swift`) -disarms the watchdog first, deletes `~/Library/LaunchAgents/io.darkbloom.watchdog.plist` -and `io.darkbloom.provider.plist`, and disables both labels in launchd. -`darkbloom unenroll` (`provider-swift/Sources/darkbloom/UnenrollCommand.swift`) -opens System Settings → Device Management (macOS does not let a binary remove a -profile) and, after confirmation or with `--force`, deletes -`~/.config/darkbloom/`, `~/.darkbloom/auth_token` and the legacy key files. -Remove the `# Darkbloom` `PATH` line from your rc file by hand. Model weights -live in `~/.cache/huggingface/hub`; delete them with `darkbloom models remove ` -before removing the CLI. +Then remove the `# Darkbloom` `PATH` line from your rc file by hand. On a +paired Mac, run `darkbloom uninstall` on the other Mac too, or `darkbloom +cluster` on it to pair it with another Mac. `darkbloom stop --uninstall` still +removes only the provider, watchdog and desktop API agents and keeps every file. +Every flag, step and path rule is in the +[CLI reference](./cli-reference.md#darkbloom-uninstall). ## Related diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 8f1ffde203..d8374ec468 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -1,10 +1,10 @@ # Provider troubleshooting -> Last updated: 2026-11-02 +> Last updated: 2026-11-04 Symptom → check → fix for the `darkbloom` provider: installer exits, `doctor` -check names, service lifecycle, coordinator connection, updates, models and the -KV-backend guard. For operators; every fix is a command you run on the Mac. +check names, service lifecycle, coordinator connection, updates, models, the +KV-backend guard and uninstalling. For operators; every fix is a command you run on the Mac. ## Prerequisites @@ -249,6 +249,27 @@ SSD caching remains enabled by default with no resident retention; use (or amounts that match a smaller RAM class) while `doctor` is green, follow [Check a missing base reward](base-rewards.md). +## Uninstall and start over + +| Symptom | Cause | Fix | +|---|---|---| +| After `darkbloom stop --uninstall`, the cluster setup, pairing and settings are still there | `stop --uninstall` removes only the provider, watchdog and desktop API agents and keeps every file | `darkbloom uninstall`: choose **Remove everything**, or **Keep models** to reuse the models after a reinstall ([installation](./installation.md#uninstall)) | +| You want to start from scratch | Saved settings, the pairing and the cluster setup bring the old setup back | `darkbloom uninstall --keep-models` (or `--everything`), then install again: settings, pairing and cable setup start fresh and the kept models are found. Deleting `~/.darkbloom` by hand leaves the cluster service, the pairing on the other Mac and the cable port setup behind | +| `Usage: darkbloom uninstall --everything\|--keep-models [--yes] [--dry-run [--json]] (no terminal to ask which)` | No terminal to ask in (an agent or a script), and no mode with `--yes` | Pass `--everything` or `--keep-models` with `--yes`; check first with `--dry-run` | +| `failed Stop serving on this Mac: …` | The provider did not finish its accepted requests in time, or cannot drain | Run it again with a longer `--timeout`, or `--force` to interrupt them. Its services are kept until it stops | +| `skipped Delete …: a Darkbloom service may still be running` | A step that stops a service failed (it is listed above) | Fix that step, then run `darkbloom uninstall` again with the same choice; every step is idempotent | +| `skipped Revoke this Mac's account token: …` | No saved token, the coordinator was not reached, or it could not confirm the token | Nothing to do: the token file is deleted with `~/.darkbloom` | +| After **Keep models** and a reinstall, models in a folder you chose are not listed | That location was saved in the deleted `provider.toml` | `darkbloom models location ` | +| `failed Undo the cable port setup: …` | The macOS prompt was declined, or could not show (no screen, over SSH) | `~/.darkbloom` and the `darkbloom` command stay for this. Run `darkbloom uninstall` again at the Mac's screen with the same choice; without a screen, run the printed `sudo sh …` line as an administrator, then run it again | +| `Run \`darkbloom uninstall\` as yourself, not with sudo: …` (exit 64) | It was run with `sudo`. As root it would read root's home folder, not yours | Run `darkbloom uninstall` without `sudo`; macOS asks for the password when the cable port step needs it | +| `skipped Delete …: not removed: …`, and the first line says Darkbloom is not fully removed (exit 1) | The path is a link, resolves outside Darkbloom's folders, or another disk is mounted at it or inside it | Nothing outside Darkbloom's folders is deleted. Remove it yourself if you don't need it, or eject the disk and run `darkbloom uninstall` again | +| `Darkbloom is not fully removed from this Mac: its app folder is your models folder, so it was kept (see below).` (exit 1) | `darkbloom models location ~/.darkbloom` made the app folder your models folder, and a folder you chose is never deleted | Move the models you want to keep out of `~/.darkbloom`, then run `~/.darkbloom/bin/darkbloom uninstall` again: the settings naming that folder are gone, so it deletes the rest | +| `~/.darkbloom` is still there after the uninstall, holding your models | You chose a models folder inside it (`darkbloom models location ~/.darkbloom/models`); a folder you chose is never deleted, and the summary lists it as `Kept:` | Move the folder, or delete it yourself if you don't need the models | +| After uninstalling the DevNet app (or the production one), the pairing and cable port setup are still there | The other install on this Mac uses them, so the summary lists them as `Kept:` | Run the other install's uninstall too (`darkbloom uninstall` or `darkbloom-dev uninstall`) to remove them | +| The other Mac still shows the pair | Each Mac keeps its own pairing | Run `darkbloom uninstall` on it too, or `darkbloom cluster` on it to pair it with another Mac | + +Steps, paths and safety rules: [`darkbloom uninstall`](./cli-reference.md#darkbloom-uninstall). + ## Collect a report ```bash diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index b890bccc16..38229a1a03 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -1,6 +1,6 @@ # Two Macs as one provider (guided setup) -> Last updated: 2026-11-03 +> Last updated: 2026-11-04 Two Apple Silicon Macs joined by one Thunderbolt 5 cable serve a model together: each Mac holds part of its layers, and the pair serves as one provider. Setting @@ -818,7 +818,34 @@ removes the pair's prompt-cache records (its own single-Mac cache stays) and stops its part; each Mac also removes its own pair records when it unpairs. `darkbloom cluster stop` stops a Mac's cluster service and keeps it from starting at login. On the leader it stops the pair first. When the other Mac is gone for -good, `darkbloom cluster stop --local-only` stops only this one. +good, `darkbloom cluster stop --local-only` stops only this one. To take Darkbloom off a Mac +altogether, see [Uninstall](#uninstall). + +## Uninstall + +`darkbloom uninstall` takes Darkbloom off one Mac of the pair. It offers +**Remove everything** or **Keep models**, and both do the same for the pair: + +- this Mac stops its part, as `darkbloom cluster stop` does (the leader stops + the pair first), and no Darkbloom service starts at login any more; +- it forgets the pairing, as `darkbloom cluster pair --forget` (a leader tells + the other Mac first, over the cable); +- it undoes the cable port setup, as `darkbloom cluster link --remove` (one + approval). + +**Keep models** keeps the models and the cluster model store, so after a +reinstall `darkbloom cluster` pairs again and uses them without copying or +downloading. **Remove everything** deletes them too, after asking once more. A +models folder you chose, and the cluster model store beside it, stay with either +choice. Run it as yourself, not with `sudo`. On a Mac with both the production +and the DevNet app, uninstalling one keeps the pairing, cluster setup and cable +port setup the other uses. + +When the other Mac does not answer, this Mac stops only its own part, as +`darkbloom cluster stop --local-only`. The other Mac keeps its own pairing, so +the command ends with one line about it, by name: run `darkbloom uninstall` +there too, or `darkbloom cluster` on it to pair it with another Mac. Every step +and path: [CLI reference](./cli-reference.md#darkbloom-uninstall). ## Cache settings diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift new file mode 100644 index 0000000000..858dba1058 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -0,0 +1,221 @@ +import Foundation + +/// `darkbloom uninstall`: takes Darkbloom off this Mac. Both ways stop serving, remove every background service, +/// revoke the account token (best effort), unpair, undo the cable port setup and delete Darkbloom's folders +/// (`ProviderUninstallPaths`), the app last. `keepModels` keeps the model folders Darkbloom downloaded and the +/// cluster model store, so a reinstall finds them. Nothing in the Keychain is touched. Each step is idempotent; a +/// failed one is reported and the safe ones after it still run. +public enum ProviderUninstall { + public enum Mode: String, Codable, Sendable, CaseIterable { + case everything + case keepModels = "keep-models" + + /// The one difference between the two: `keepModels` keeps every `.model` item in place. + func keeps(_ item: ProviderUninstallItem) -> Bool { self == .keepModels && item.kind == .model } + } + + /// How a step ended when it did not throw. + public enum Outcome: Equatable, Sendable { + case done(String? = nil) + case skipped(String) + } + + public struct Step: Sendable, Equatable { + public enum Status: String, Sendable { case done, skipped, failed } + public let name: String + public let status: Status + public let detail: String? + } + + /// Everything a run touches outside this file, so that checks can run it on a fake home with no launchd. + public struct Operations { + /// Drains and stops the provider, as `darkbloom stop` does. + public var stopServing: () async throws -> Outcome + /// Stops this Mac's part of a pair and removes the cluster service, as `darkbloom cluster stop` does. + public var stopClusterPart: () async throws -> Outcome + /// The provider, watchdog and desktop API launch agents, by name, as `darkbloom stop --uninstall` removes them. + public var removeServices: [(name: String, remove: () throws -> Outcome)] + /// Called once the services are handled, before any account, pairing or file changes (releases the drain's lease). + public var servicesHandled: () -> Void + /// Revokes the saved account token as `darkbloom logout` does. Best effort: it reports, it never fails. + public var revokeToken: () async -> Outcome + /// `darkbloom cluster pair --forget `. + public var forget: (_ peerPin: String) throws -> Void + /// `darkbloom cluster link --remove`. + public var removeCableSetup: () throws -> Outcome + public var delete: (URL) throws -> Void + /// Free bytes on the home volume, to report the space freed. + public var availableBytes: () -> Int64? + + public init(stopServing: @escaping () async throws -> Outcome, stopClusterPart: @escaping () async throws -> Outcome, + removeServices: [(name: String, remove: () throws -> Outcome)], servicesHandled: @escaping () -> Void = {}, + revokeToken: @escaping () async -> Outcome, + forget: @escaping (String) throws -> Void, removeCableSetup: @escaping () throws -> Outcome, + delete: @escaping (URL) throws -> Void = { try FileManager.default.removeItem(at: $0) }, + availableBytes: @escaping () -> Int64? = { nil }) { + self.stopServing = stopServing; self.stopClusterPart = stopClusterPart; self.removeServices = removeServices + self.servicesHandled = servicesHandled; self.revokeToken = revokeToken; self.forget = forget + self.removeCableSetup = removeCableSetup; self.delete = delete; self.availableBytes = availableBytes + } + } + + public struct Report: Sendable, Equatable { + public let mode: Mode + public let steps: [Step] + public let availableBefore: Int64? + public let availableAfter: Int64? + public var failed: Bool { steps.contains { $0.status == .failed } } + /// Something of Darkbloom's that was to go is still here: refused, or kept because an earlier step failed. + /// A command link the installer did not make is not Darkbloom's, so leaving it leaves nothing of Darkbloom's. + public var incomplete: Bool { + steps.contains { + $0.status == .skipped && $0.name.hasPrefix("Delete ") && $0.detail != "already gone" + && $0.detail != notRemoved(foreignLinkReason) + } + } + } + + static let stopServingStep = "Stop serving on this Mac" + static let clusterStep = "Stop this Mac's cluster part and remove its service" + static let tokenStep = "Revoke this Mac's account token" + static let cableStep = "Undo the cable port setup" + static let forgetStep = "Forget this Mac's pairing" + static let ownClusterStep = "Remove this install's cluster service" + static let stillServingReason = "serving did not stop (see the failed step above)" + static let servicesRunningReason = "a Darkbloom service may still be running (see the failed step above)" + static let cableRetryReason = + "kept, so the uninstall can run again and undo the cable port setup (it holds the app and the cable records)" + + /// Runs `mode`. `items` is `inventory(_:)`, read before anything changed; `announce` prints each step as it starts. + public static func run(_ mode: Mode, items: [ProviderUninstallItem], pairing: ProviderUninstallPairing?, + operations: Operations, announce: (String) -> Void = { _ in }) async -> Report { + var steps: [Step] = [] + func step(_ name: String, _ body: () async throws -> Outcome) async -> Bool { + announce(name) + do { + switch try await body() { + case .done(let detail): steps.append(.init(name: name, status: .done, detail: detail)) + case .skipped(let reason): steps.append(.init(name: name, status: .skipped, detail: reason)) + } + return true + } catch { + steps.append(.init(name: name, status: .failed, detail: "\(error)")) + return false + } + } + // Another install on this Mac uses the same pair, pairing and cable port setup: they all stay with it. + let sharedWith = items.lazy.compactMap(\.sharedWith).first + let serving = await step(stopServingStep, operations.stopServing) + let clusterHandled: Bool + if let other = sharedWith, let own = items.lazy.compactMap(\.ownClusterAgent).first { + clusterHandled = await step(ownClusterStep) { try removeOwnClusterAgent(own, keptFor: other) } + } else { + clusterHandled = await step(clusterStep, operations.stopClusterPart) + } + var servicesStopped = clusterHandled && serving + for service in operations.removeServices { + // As `stop --uninstall`: a provider that did not drain keeps its agents, so nothing interrupts it. + guard serving else { + steps.append(.init(name: service.name, status: .skipped, detail: stillServingReason)) + continue + } + servicesStopped = await step(service.name, service.remove) && servicesStopped + } + operations.servicesHandled() + // As `darkbloom logout`: only once the provider holding the token has stopped. + if serving { + _ = await step(tokenStep) { await operations.revokeToken() } + } else { + steps.append(.init(name: tokenStep, status: .skipped, detail: stillServingReason)) + } + let keptForOther = sharedWith.map { "kept: \($0) on this Mac also uses it" } + if pairing != nil, let keptForOther { + steps.append(.init(name: forgetStep, status: .skipped, detail: keptForOther)) + } else if let pairing { + for peer in pairing.peers { + _ = await step("Forget the pairing with \(peer.name)") { try operations.forget(peer.pin); return .done() } + } + } else { + steps.append(.init(name: forgetStep, status: .skipped, detail: "this Mac is not paired")) + } + // After the pairing, which tells the other Mac over the cable; this takes the cable's address away. + let cableUndone: Bool + if let keptForOther { + steps.append(.init(name: cableStep, status: .skipped, detail: keptForOther)) + cableUndone = true + } else { + cableUndone = await step(cableStep, operations.removeCableSetup) + } + let before = operations.availableBytes() + for item in items where item.verdict != .keep && !mode.keeps(item) { + let name = "Delete \(item.label)" + guard item.verdict == .remove else { + steps.append(.init(name: name, status: .skipped, detail: notRemoved(item.reason ?? "outside Darkbloom's folders"))) + continue + } + guard servicesStopped else { + steps.append(.init(name: name, status: .skipped, detail: servicesRunningReason)) + continue + } + guard cableUndone || item.kind != .command else { + steps.append(.init(name: name, status: .skipped, detail: cableRetryReason)) + continue + } + _ = await step(name) { + // The install folder holds the app this command runs from; it is deleted last. macOS keeps a + // running executable's image after its file is unlinked, and nothing after this loads from it. + guard FileManager.default.fileExists(atPath: item.path) || isLink(item.path) else { return .skipped("already gone") } + if item.keeping.isEmpty { + try operations.delete(URL(fileURLWithPath: item.path)) + } else { + try deleteAround(URL(fileURLWithPath: ProviderUninstallPaths.canonical(item.path)), keeping: item.keeping, + operations.delete) + } + return .done(item.bytes > 0 ? formatBytes(item.bytes) : nil) + } + } + return Report(mode: mode, steps: steps, availableBefore: before, availableAfter: operations.availableBytes()) + } + + /// Deletes everything in `folder` except `keeping` (resolved paths inside it) and the folders that lead to them. + /// An app bundle goes last, as the install folder's app does when the folder goes whole. + static func deleteAround(_ folder: URL, keeping: [String], _ delete: (URL) throws -> Void) throws { + let names = try FileManager.default.contentsOfDirectory(atPath: folder.path) + .sorted { ($0.hasSuffix(".app") ? 1 : 0, $0) < ($1.hasSuffix(".app") ? 1 : 0, $1) } + for name in names { + let child = folder.appendingPathComponent(name) + guard !keeping.contains(child.path) else { continue } + let inside = keeping.filter { $0.hasPrefix(child.path + "/") } + if inside.isEmpty { try delete(child) } else { try deleteAround(child, keeping: inside, delete) } + } + } + + static func notRemoved(_ reason: String) -> String { "not removed: \(reason)" } + + /// Step 2 beside another install that shares the pair: boots out and deletes only this install's own agent. The + /// pair is not stopped and the other install's agent is not touched. + static func removeOwnClusterAgent(_ label: String, keptFor other: String) throws -> Outcome { + let leftAlone = "the pair and \(other)'s cluster service are left as they are" + guard FileManager.default.fileExists(atPath: ClusterServiceAgent.plistPath(label: label).path) + || ClusterServiceAgent.isLoaded(label: label) else { return .skipped("this install has none; \(leftAlone)") } + try ClusterServiceAgent.remove(label: label) + return .done("removed \(label); \(leftAlone)") + } + + static func isLink(_ path: String) -> Bool { + (try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil + } + + /// One launch agent: skipped when neither its file nor a loaded job exists, else removed by its own `uninstall`. + public static func removeAgent(plist: URL, loaded: @autoclosure () -> Bool, uninstall: () throws -> Void) throws -> Outcome { + guard FileManager.default.fileExists(atPath: plist.path) || loaded() else { return .skipped("not installed") } + try uninstall() + return .done() + } + + /// A step that ended without the wanted result, in a sentence. + public struct StepFailure: Error, CustomStringConvertible { + public let description: String + public init(_ description: String) { self.description = description } + } +} diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift new file mode 100644 index 0000000000..c2100c15bb --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -0,0 +1,500 @@ +import DarkbloomClusterSecurity +import Darwin +import Foundation + +/// Where this build of Darkbloom keeps things on this Mac, as `darkbloom uninstall` sees them. The roots are fixed +/// names under the home directory; a saved model or cache location the person chose is never one of them. +public struct ProviderUninstallPaths: Sendable, Equatable { + /// The home directory with its own links resolved (`/var` → `/private/var`), so every root is canonical. + public let home: URL + /// `~/.darkbloom`: the app, the `bin/` links, logs, pairing, cluster setup and service state. + public let installDirectory: URL + public let appBundleName: String + /// `~/.config/darkbloom`: `provider.toml` and saved cluster setups. + public let configDirectory: URL + /// `~/Library/Caches/darkbloom`: the encrypted prompt caches. + public let cacheDirectory: URL + /// `~/.cache/huggingface/hub`, where Darkbloom downloads models unless another location is saved. + public let modelCache: URL + /// `~/.cache/huggingface/darkbloom-cluster-models`, the cluster's model store beside it. + public let clusterModelStore: URL + /// The link the installer adds when it can (`/usr/local/bin/darkbloom` → `~/.darkbloom/bin/darkbloom`). + public let commandLink: URL + /// A model or cache location saved in `provider.toml`, which is kept. + public var savedModelCache: URL? + public var savedCacheDirectory: URL? + /// Another Darkbloom install on this Mac (`~/.darkbloom-dev`, …) reads the same model cache, so its models stay. + public var otherInstall: URL? + /// Another Darkbloom install on this Mac, told by its app or its command in its own folder. Not by the folder + /// alone: `~/.darkbloom` also holds the cluster files every install writes. It shares this Mac's pairing, cluster + /// setup and cable port setup (`sharedClusterFiles`), so those stay. + public var otherEnvironment: BuildEnvironment? + + public init(home: URL, environment: BuildEnvironment = .current, commandLinkDirectory: URL = URL(fileURLWithPath: "/usr/local/bin")) { + let home = URL(fileURLWithPath: Self.canonical(home.path), isDirectory: true) + self.home = home + installDirectory = environment.installDirectory(home: home) + appBundleName = environment.appBundleName + configDirectory = environment.configDirectory(home: home) + cacheDirectory = home.appendingPathComponent("Library/Caches/\(environment.encryptedCacheNamespace)", isDirectory: true) + modelCache = home.appendingPathComponent(".cache/huggingface/hub", isDirectory: true) + clusterModelStore = home.appendingPathComponent(".cache/huggingface/darkbloom-cluster-models", isDirectory: true) + commandLink = commandLinkDirectory.appendingPathComponent(environment.cliName) + otherEnvironment = BuildEnvironment.allCases.filter { $0 != environment }.first { other in + let folder = other.installDirectory(home: home) + return [other.appBundleName, "bin/\(other.cliName)"].contains { + var info = stat() + return lstat(folder.appendingPathComponent($0).path, &info) == 0 + } + } + otherInstall = BuildEnvironment.allCases.filter { $0 != environment } + .map { $0.installDirectory(home: home) } + .first { FileManager.default.fileExists(atPath: $0.path) } + } + + /// The live paths, with the locations saved in the `provider.toml` at `configPath`, resolved as the provider + /// resolves them (`ConfigManager.modelCacheDirectory`, `CacheStorage.root`). + public static func live(config: ProviderConfig?, configPath: URL, + home: URL = FileManager.default.homeDirectoryForCurrentUser) -> Self { + var paths = Self(home: home) + if let config { + paths.savedModelCache = (try? ConfigManager.modelCacheDirectory(in: config, relativeTo: configPath)) + .flatMap { $0 }.map { URL(fileURLWithPath: $0, isDirectory: true) } + paths.savedCacheDirectory = config.cache.directory.map { + URL(fileURLWithPath: $0, isDirectory: true).appendingPathComponent(BuildEnvironment.current.encryptedCacheNamespace) + } + } + return paths + } + + /// The folders a deletion may resolve into. A target counts only when its resolved path is one of these or + /// inside one, so a link to anywhere else, or one of these that is itself a link, is refused. + var roots: [String] { + [installDirectory, configDirectory, cacheDirectory, modelCache, clusterModelStore].map(\.path) + } + + /// The cluster files every install on this Mac reads and writes, whichever install it is: `~/.darkbloom/cluster*` + /// (pairing, setup, device and link records: `ClusterUserPaths`, `ClusterSetupWizardStore`, `ClusterMemberHealth`) + /// and the saved cluster setups in `~/.config/darkbloom/clusters`. + var sharedClusterFiles: [URL] { + let darkbloom = BuildEnvironment.prod.installDirectory(home: home) + let names = ((try? FileManager.default.contentsOfDirectory(atPath: darkbloom.path)) ?? []).filter { $0.hasPrefix("cluster") } + return names.sorted().map { darkbloom.appendingPathComponent($0) } + + [BuildEnvironment.prod.configDirectory(home: home).appendingPathComponent("clusters", isDirectory: true)] + .filter { FileManager.default.fileExists(atPath: $0.path) } + } + + static func canonical(_ path: String) -> String { + guard let resolved = realpath(path, nil) else { return URL(fileURLWithPath: path).standardizedFileURL.path } + defer { free(resolved) } + return String(cString: resolved) + } +} + +/// One thing `darkbloom uninstall` lists: what it is, its size and whether it is deleted. +public struct ProviderUninstallItem: Codable, Sendable, Equatable { + public enum Verdict: String, Codable, Sendable { + /// Darkbloom's, inside its folders: deleted (a model only by `--everything`). + case remove + /// Outside Darkbloom's folders (a location the person chose, another install's): never deleted. + case keep + /// It looks like Darkbloom's but resolves outside its folders: never deleted, and said why. + case refused + } + + public enum Kind: String, Codable, Sendable { + case data + /// A model folder Darkbloom downloaded, its download locks or the cluster model store: `--keep-models` keeps it. + case model + /// Deleting it takes away the `darkbloom` command: the install folder (the app, and the cable records + /// `cluster link --remove` reads) and the command link. + case command + } + + public let label: String + public let path: String + public let bytes: Int64 + public let verdict: Verdict + public let reason: String? + public var kind: Kind = .data + /// Its files' blocks, for counting APFS clones once (`ProviderUninstall.uniqueBytes`). + var files: [ProviderUninstallFile] = [] + /// Folders inside it that stay (resolved paths): the models folder the person chose, and the store beside it. + var keeping: [String] = [] + /// What `keeping` is, as the deleted folder's row names it ("the models you chose"). + var keepingWhat = "" + /// The other install whose cluster state this item keeps: the pairing and the cable port setup stay with it. + var sharedWith: String? + /// This install's own cluster service agent (`ClusterServiceAgentPlan.label` of its app), and its file when + /// installed. Beside another install, step 2 removes only this one. + var ownClusterAgent: String? + var ownClusterAgentPlist: String? + /// Kept although it lies inside one of Darkbloom's folders, because the person chose it for models. + var keptInDarkbloomFolder = false + + private enum CodingKeys: String, CodingKey { case label, path, bytes, verdict, reason, kind } +} + +/// One regular file's allocated bytes and, on APFS, its clone facts (`getattrlist`'s `ATTR_CMNEXT_*`). +struct ProviderUninstallFile: Sendable, Equatable { + let allocated: Int64 + /// Bytes no other file shares. + var privateBytes: Int64? + /// Pure clones (`clonefile`, `cp -c`) share one id while neither changes; `references` is how many files hold it. + var cloneID: UInt64? + var references: UInt32? +} + +/// The other Mac this one is paired with, from the saved records only (no cable, no key). +public struct ProviderUninstallPairing: Sendable, Equatable { + public struct Peer: Sendable, Equatable { + public let pin: String + public let name: String + public init(pin: String, name: String) { self.pin = pin; self.name = name } + } + public var peers: [Peer] + /// The other Mac of the current pair, as `darkbloom cluster` names it. + public var otherMacName: String? + /// This Mac's role in that pair. + public var role: ClusterOnboardingRole? + + public init(peers: [Peer], otherMacName: String?, role: ClusterOnboardingRole?) { + self.peers = peers; self.otherMacName = otherMacName; self.role = role + } + + /// Nil when this Mac holds no pairing. + public static func read(home: URL = FileManager.default.homeDirectoryForCurrentUser) -> Self? { + guard let records = try? ClusterPairingStore.default(home: home).load(), !records.pairings.isEmpty else { return nil } + let latest = records.pairings.max { $0.pairedAt < $1.pairedAt } + return describing(peers: records.pairings.map { Peer(pin: $0.peerPin, name: $0.peerName) }, + latest: latest.map { Peer(pin: $0.peerPin, name: $0.peerName) }, home: home, + local: try? ClusterSetupLinkExchange.pairing(store: .default(home: home))) + } + + /// The other Mac's name and this Mac's role in the latest pairing, from the setup `darkbloom cluster` saved for it. + static func describing(peers: [Peer], latest: Peer?, home: URL, local: ClusterSetupLinkExchange.Pairing?) -> Self { + var pairing = Self(peers: peers, otherMacName: latest?.name, role: nil) + guard let latest, let paths = try? ClusterUserPaths(homeDirectory: home), + let record = try? ClusterSetupStore(paths: .init(paths: paths)).readRecord(), + let leadership = record.leadership, leadership.peerPin == latest.pin else { return pairing } + if !leadership.peerName.isEmpty { pairing.otherMacName = leadership.peerName } + pairing.role = ClusterOnboardingRole(rawValue: leadership.role) + // After onboarding the derived control leadership decides who leads, as `darkbloom cluster` shows it. + if let local, let claim = record.control?.claim(localID: local.localMemberID, peerID: local.peerMemberID) { + pairing.role = claim.leaderID == local.localMemberID ? .leader : .member + } + return pairing + } +} + +extension ProviderUninstall { + /// What `darkbloom uninstall` (or `--dry-run`) runs on this Mac, in order. + public struct Plan: Sendable, Equatable { + public struct Service: Sendable, Equatable { + public let name: String + /// The launch agent file, or nil when it is not installed. + public let path: String? + public init(name: String, path: String?) { self.name = name; self.path = path } + } + public let cli: String + /// The command that installs Darkbloom again, for the way back after `--keep-models`. + public let installCommand: String + /// The cluster service's launch agent files (`ClusterServiceAgent.installedLabels`); empty when it is not set up. + public let clusterService: [String] + /// A cluster service holds this Mac's service lock without a login agent (`ClusterService.running`), as one + /// `darkbloom cluster` started in a session does. + public let clusterServiceRunning: Bool + public let services: [Service] + public let items: [ProviderUninstallItem] + public let pairing: ProviderUninstallPairing? + /// Darkbloom things this command never removes, each with how to remove it (the fan helper, …). + public let elsewhere: [String] + + public init(cli: String = BuildEnvironment.current.cliName, + installCommand: String = "curl -fsSL \(BuildEnvironment.current.coordinatorHTTPURL)/install.sh | bash", + clusterService: [String] = [], clusterServiceRunning: Bool = false, services: [Service], + items: [ProviderUninstallItem], + pairing: ProviderUninstallPairing?, elsewhere: [String] = []) { + self.cli = cli; self.installCommand = installCommand; self.clusterService = clusterService + self.clusterServiceRunning = clusterServiceRunning + self.services = services; self.items = items; self.pairing = pairing; self.elsewhere = elsewhere + } + + /// What `mode` deletes, in order. + func removed(_ mode: Mode) -> [ProviderUninstallItem] { + items.filter { $0.verdict == .remove && !mode.keeps($0) } + } + var models: [ProviderUninstallItem] { items.filter { $0.verdict == .remove && $0.kind == .model } } + var kept: [ProviderUninstallItem] { items.filter { $0.verdict == .keep } } + var refused: [ProviderUninstallItem] { items.filter { $0.verdict == .refused } } + /// Another install on this Mac uses the same pairing and cable port setup, so they stay (`inventory`). + var sharesCluster: Bool { items.contains { $0.sharedWith != nil } } + /// Disk space deleting `mode`'s items frees, with APFS clones counted once. + func frees(_ mode: Mode) -> Int64 { uniqueBytes(removed(mode)) } + var modelBytes: Int64 { uniqueBytes(models) } + } + + static let chosenModelsLabel = "Models in the folder you chose" + static let sharedClusterLabel = "This Mac's pairing, cluster setup and cable port setup" + static let foreignLinkReason = "it is not the link Darkbloom's installer made" + static let chosenStoreLabel = "Cluster model store beside the folder you chose" + static let clusterStoreLabel = "Cluster model store" + static let chosenInsideReason = "you chose this folder for models, so it stays, with the folders that lead to it" + static let chosenWhat = "the models you chose" + static let chosenFolderIsItReason = "it is the models folder you chose, which is never deleted" + static let chosenFolderHoldsItReason = "it is inside the models folder you chose, which is never deleted" + static let chosenStoreInsideReason = "it holds the cluster's copies of the models you chose, so it stays too" + + /// Everything `--everything` would delete or keep, in deletion order: the install folder (with the app this + /// command runs from) comes last. + public static func inventory(_ paths: ProviderUninstallPaths) -> [ProviderUninstallItem] { + var items: [ProviderUninstallItem] = [] + func add(_ label: String, _ url: URL, keep reason: String? = nil, kind: ProviderUninstallItem.Kind = .data) { + guard var item = item(label, url, paths: paths, keep: reason) else { return } + item.kind = kind + items.append(item) + } + func inRoots(_ resolved: String) -> Bool { paths.roots.contains { resolved == $0 || resolved.hasPrefix($0 + "/") } } + // A chosen cache folder inside Darkbloom's own goes with it, so only one outside them is listed as kept. + if let saved = paths.savedCacheDirectory, !inRoots(ProviderUninstallPaths.canonical(saved.path)) { + add("Encrypted prompt caches in the folder you chose", saved, keep: "outside Darkbloom's folders") + } + // A models folder the person chose is never deleted, in either mode and wherever it is; nor is the cluster + // store the provider keeps beside it (`ClusterModelStoreLocation`). Inside one of Darkbloom's folders, that + // folder is deleted around them. + let chosenModels = paths.savedModelCache.map { URL(fileURLWithPath: ProviderUninstallPaths.canonical($0.path)) } + .flatMap { $0.path == ProviderUninstallPaths.canonical(paths.modelCache.path) ? nil : $0 } + let chosenStore = chosenModels.map { $0.deletingLastPathComponent().appendingPathComponent("darkbloom-cluster-models") } + var protected: [(path: String, what: String)] = [] + for (label, folder, insideReason) in [(chosenModelsLabel, chosenModels, chosenInsideReason), + (chosenStoreLabel, chosenStore, chosenStoreInsideReason)] { + guard let folder else { continue } + let inside = inRoots(folder.path) + guard var kept = item(label, folder, paths: paths, keep: inside ? insideReason : "outside Darkbloom's folders") else { continue } + kept.keptInDarkbloomFolder = inside + items.append(kept) + protected.append((folder.path, chosenWhat)) + } + add("Settings", paths.configDirectory) + add("Encrypted prompt caches", paths.cacheDirectory) + items += models(paths) + add(clusterStoreLabel, paths.clusterModelStore, keep: paths.otherInstall.map(sharedReason), kind: .model) + add("The `\(paths.commandLink.lastPathComponent)` command link", paths.commandLink, kind: .command) + add(installFolderLabel(paths), paths.installDirectory, kind: .command) + // Another install on this Mac reads the same pairing, cluster setup and cable port setup: they stay with it. + if let other = paths.otherEnvironment { + let files = paths.sharedClusterFiles + var shared = ProviderUninstallItem(label: sharedClusterLabel, + path: paths.home.appendingPathComponent(".darkbloom/cluster*").path, + bytes: files.reduce(0) { $0 + measure($1).bytes }, verdict: .keep, + reason: "\(installName(other)) on this Mac also uses them; the pair and its " + + "cluster service are left as they are. Run `\(other.cliName) uninstall` there to remove them") + shared.keptInDarkbloomFolder = true + shared.sharedWith = installName(other) + let ownAgent = ClusterServiceAgentPlan.label(executablePath: paths.installDirectory + .appendingPathComponent("\(paths.appBundleName)/Contents/MacOS/\(paths.commandLink.lastPathComponent)").path) + let ownPlist = paths.home.appendingPathComponent("Library/LaunchAgents/\(ownAgent).plist") + shared.ownClusterAgent = ownAgent + shared.ownClusterAgentPlist = FileManager.default.fileExists(atPath: ownPlist.path) ? ownPlist.path : nil + items.append(shared) + protected += files.map { (ProviderUninstallPaths.canonical($0.path), "the cluster files \(installName(other)) uses") } + } + // What finishes the uninstall once the models are out: the settings that named the folder are gone by then. + let again = "\(paths.installDirectory.path)/bin/\(paths.commandLink.lastPathComponent) uninstall" + let advice = ". To finish, move the models you want to keep out of it, then run `\(again)` again, which deletes the rest of it" + return items.compactMap { around($0, protected, advice: advice) } + } + + /// `item` with the protected folders inside it left out (and measured without them); nil when it lies inside one. + private static func around(_ item: ProviderUninstallItem, _ protected: [(path: String, what: String)], + advice: String) -> ProviderUninstallItem? { + guard item.verdict == .remove, !protected.isEmpty else { return item } + // A link is deleted itself, never what it points to, so where the link is decides (the command link). + let resolved = isLink(item.path) ? item.path : ProviderUninstallPaths.canonical(item.path) + if let holder = protected.first(where: { resolved == $0.path || resolved.hasPrefix($0.path + "/") }) { + // It stays with the folder the person chose for models. Models there are theirs; anything else of + // Darkbloom's staying, the app folder above all, means Darkbloom is not fully removed: refused, and named. + guard holder.what == chosenWhat, item.kind != .model else { return nil } + return ProviderUninstallItem(label: item.label, path: item.path, bytes: item.bytes, verdict: .refused, + reason: (resolved == holder.path ? chosenFolderIsItReason : chosenFolderHoldsItReason) + advice, + kind: item.kind) + } + let inside = protected.filter { $0.path.hasPrefix(resolved + "/") } + guard !inside.isEmpty else { return item } + let measured = measure(URL(fileURLWithPath: resolved), excluding: inside.map(\.path)) + var kept = ProviderUninstallItem(label: item.label, path: item.path, bytes: measured.bytes, verdict: item.verdict, + reason: item.reason, kind: item.kind, files: measured.files) + kept.keeping = inside.map(\.path) + kept.keepingWhat = inside.map(\.what).reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } } + .joined(separator: " and ") + return kept + } + + /// The install folder's row. The pairing and cluster setup are in `~/.darkbloom` whichever install made them. + static func installFolderLabel(_ paths: ProviderUninstallPaths) -> String { + paths.installDirectory.lastPathComponent == BuildEnvironment.prod.installDirectoryName + ? "Darkbloom folder: the app, logs, pairing and cluster setup" : "Darkbloom folder: the app and logs" + } + + /// How the summary and the kept lines name an install: the production one, or by its app's name. + static func installName(_ environment: BuildEnvironment) -> String { + environment == .prod ? "the production Darkbloom" : environment.appDisplayName + } + + private static func sharedReason(_ other: URL) -> String { "\(other.lastPathComponent) on this Mac uses it too" } + + /// The model folders Darkbloom downloaded into the default model cache: those holding its verified receipt or + /// its unfinished download. Anything else there belongs to another tool and is not listed. + static func models(_ paths: ProviderUninstallPaths) -> [ProviderUninstallItem] { + let cache = paths.modelCache + guard FileManager.default.fileExists(atPath: cache.path) else { return [] } + guard ProviderUninstallPaths.canonical(cache.path) == cache.path else { + return [placed("Models", cache, verdict: .keep, + reason: "it links to \(ProviderUninstallPaths.canonical(cache.path)), outside Darkbloom's folders")] + } + var items: [ProviderUninstallItem] = [] + let names = ((try? FileManager.default.contentsOfDirectory(atPath: cache.path)) ?? []).sorted() + for name in names where name.hasPrefix("models--") { + let folder = cache.appendingPathComponent(name, isDirectory: true) + guard isDarkbloomModel(folder) else { continue } + let id = name.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/") + if var item = item("Model \(id)", folder, paths: paths, keep: paths.otherInstall.map(sharedReason)) { + item.kind = .model + items.append(item) + } + } + let locks = cache.appendingPathComponent(".artifact-writer-locks", isDirectory: true) + if paths.otherInstall == nil, var item = item("Model download locks", locks, paths: paths) { + item.kind = .model + items.append(item) + } + return items + } + + static func isDarkbloomModel(_ folder: URL) -> Bool { + let snapshots = folder.appendingPathComponent("snapshots", isDirectory: true) + let entries = (try? FileManager.default.contentsOfDirectory(atPath: snapshots.path)) ?? [] + return entries.contains { entry in + entry.hasPrefix(".local-staging-") || FileManager.default.fileExists( + atPath: snapshots.appendingPathComponent(entry).appendingPathComponent(".darkbloom-manifest.json").path) + } + } + + /// Nil when nothing is there. The command link is Darkbloom's only while it points at this install's `bin/`. + static func item(_ label: String, _ url: URL, paths: ProviderUninstallPaths, keep reason: String? = nil) -> ProviderUninstallItem? { + var info = stat() + guard lstat(url.path, &info) == 0 else { return nil } + if let reason { return placed(label, url, verdict: .keep, reason: reason) } + if url == paths.commandLink { + // Only the link itself is removed, never what it points to. + let destination = linkDestination(url).map(URL.init(fileURLWithPath:)) + guard info.st_mode & S_IFMT == S_IFLNK, let destination, destination.lastPathComponent == url.lastPathComponent, + ProviderUninstallPaths.canonical(destination.deletingLastPathComponent().path) + == paths.installDirectory.appendingPathComponent("bin").path else { + return .init(label: label, path: url.path, bytes: 0, verdict: .refused, reason: foreignLinkReason) + } + return .init(label: label, path: url.path, bytes: 0, verdict: .remove, reason: nil) + } + let resolved = ProviderUninstallPaths.canonical(url.path) + guard paths.roots.contains(where: { resolved == $0 || resolved.hasPrefix($0 + "/") }) else { + return placed(label, url, verdict: .refused, reason: "it resolves to \(resolved), outside Darkbloom's folders") + } + if isMountPoint(url) { + return .init(label: label, path: url.path, bytes: measure(url).bytes, verdict: .refused, + reason: "another disk is mounted here") + } + let measured = measure(url) + if measured.otherVolume { + return .init(label: label, path: url.path, bytes: measured.bytes, verdict: .refused, + reason: "another disk is mounted inside it") + } + return .init(label: label, path: url.path, bytes: measured.bytes, verdict: .remove, reason: nil, files: measured.files) + } + + /// Sized where it resolves, so a kept or refused link shows what it holds. + private static func placed(_ label: String, _ url: URL, verdict: ProviderUninstallItem.Verdict, reason: String) -> ProviderUninstallItem { + let bytes = measure(URL(fileURLWithPath: ProviderUninstallPaths.canonical(url.path))).bytes + return .init(label: label, path: url.path, bytes: bytes, verdict: verdict, reason: reason) + } + + static func linkDestination(_ link: URL) -> String? { + guard let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: link.path) else { return nil } + return URL(fileURLWithPath: destination, relativeTo: link.deletingLastPathComponent()).standardizedFileURL.path + } + + /// Allocated bytes under `url`, never following a link and each hard-linked file once; whether a folder inside + /// it is on another volume; and each file's blocks, which `uniqueBytes` counts with APFS clones once. + static func measure(_ url: URL, excluding: [String] = []) -> (bytes: Int64, otherVolume: Bool, files: [ProviderUninstallFile]) { + var root = stat() + guard stat(url.path, &root) == 0 else { return (0, false, []) } + guard root.st_mode & S_IFMT == S_IFDIR, lstat(url.path, &root) == 0, root.st_mode & S_IFMT == S_IFDIR, + let walker = FileManager.default.enumerator(atPath: url.path) else { + return (Int64(root.st_blocks) * 512, false, []) + } + var files: [ProviderUninstallFile] = [], seen = Set<[UInt64]>(), otherVolume = false + while let relative = walker.nextObject() as? String { + let path = url.appendingPathComponent(relative).path + var info = stat() + guard lstat(path, &info) == 0 else { continue } + if info.st_mode & S_IFMT == S_IFDIR { + if excluding.contains(path) { walker.skipDescendants() } + else if info.st_dev != root.st_dev { otherVolume = true; walker.skipDescendants() } + continue + } + if info.st_nlink > 1, !seen.insert([UInt64(UInt32(bitPattern: info.st_dev)), info.st_ino]).inserted { continue } + var file = ProviderUninstallFile(allocated: Int64(info.st_blocks) * 512) + if info.st_mode & S_IFMT == S_IFREG { cloneFacts(path, into: &file) } + files.append(file) + } + return (files.reduce(0) { $0 + $1.allocated }, otherVolume, files) + } + + /// Whether another volume is mounted at `url`: its device differs from its parent folder's. + public static func isMountPoint(_ url: URL) -> Bool { + var own = stat(), parent = stat() + guard lstat(url.path, &own) == 0, stat(url.deletingLastPathComponent().path, &parent) == 0 else { return false } + return own.st_dev != parent.st_dev + } + + /// Bytes deleting all of `files` frees: a pure-clone family's shared blocks count once, and only when every + /// file holding them is among `files`. Clones that have since diverged are each counted in full. + static func uniqueBytes(_ files: [ProviderUninstallFile]) -> Int64 { + var total: Int64 = 0 + var families: [UInt64: (members: Int, references: UInt32, shared: Int64)] = [:] + for file in files { + guard let id = file.cloneID, let references = file.references, references > 1, let own = file.privateBytes else { + total += file.allocated + continue + } + total += own + var family = families[id] ?? (0, references, 0) + family.members += 1 + family.shared = max(family.shared, file.allocated - own) + families[id] = family + } + return families.values.reduce(total) { $0 + ($1.members >= Int($1.references) ? $1.shared : 0) } + } + + /// The deduplicated size of `items` together. + public static func uniqueBytes(_ items: [ProviderUninstallItem]) -> Int64 { + uniqueBytes(items.flatMap { $0.files.isEmpty ? [ProviderUninstallFile(allocated: $0.bytes)] : $0.files }) + } + + /// `ATTR_CMNEXT_PRIVATESIZE`, `_CLONEID` and `_CLONE_REFCNT`, when the volume returns all three (APFS). + private static func cloneFacts(_ path: String, into file: inout ProviderUninstallFile) { + var request = attrlist() + request.bitmapcount = u_short(ATTR_BIT_MAP_COUNT) + request.commonattr = attrgroup_t(ATTR_CMN_RETURNED_ATTRS) + let wanted = attrgroup_t(ATTR_CMNEXT_PRIVATESIZE | ATTR_CMNEXT_CLONEID | ATTR_CMNEXT_CLONE_REFCNT) + request.forkattr = wanted + var buffer = [UInt8](repeating: 0, count: 64) + guard getattrlist(path, &request, &buffer, buffer.count, UInt32(FSOPT_ATTR_CMN_EXTENDED | FSOPT_NOFOLLOW)) == 0 else { return } + buffer.withUnsafeBytes { raw in + // u_int32_t length, attribute_set_t (five groups; forkattr last), then the values in bit order. + guard raw.loadUnaligned(fromByteOffset: 20, as: attrgroup_t.self) & wanted == wanted else { return } + file.privateBytes = raw.loadUnaligned(fromByteOffset: 24, as: Int64.self) + file.cloneID = raw.loadUnaligned(fromByteOffset: 32, as: UInt64.self) + file.references = raw.loadUnaligned(fromByteOffset: 40, as: UInt32.self) + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift new file mode 100644 index 0000000000..3f40daa910 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift @@ -0,0 +1,251 @@ +import Foundation + +// MARK: - What the person reads + +extension ProviderUninstall { + public static let keychainLine = "Never touched: Keychain keys (Secure Enclave and App Attest); a new install replaces them." + public static let choicePrompt = " Choose 1 or 2 (Esc cancels): " + + /// Asked once after 1 on the screen, which deletes the models too. + public static func everythingQuestion(_ plan: Plan) -> String { + plan.models.isEmpty ? " Remove everything? This can't be undone. [y/N]: " + : " Remove everything, including \(formatBytes(plan.modelBytes)) of models? This can't be undone. [y/N]: " + } + + /// y or yes; anything else, nothing included, is no. + public static func confirmed(_ answer: String?) -> Bool { + ["y", "yes"].contains(answer?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "") + } + + /// Run as root, it would read root's home, find nothing of the person's Darkbloom and still undo the Mac's cable setup. + public static func rootRefusal(cli: String = BuildEnvironment.current.cliName) -> String { + "Run `\(cli) uninstall` as yourself, not with sudo: it removes your own Darkbloom, and asks for your password when a " + + "step needs it." + } + + public static func usage(cli: String = BuildEnvironment.current.cliName) -> String { + "Usage: \(cli) uninstall --everything|--keep-models [--yes] [--dry-run [--json]] (no terminal to ask which)" + } + + /// The interactive screen above `choicePrompt`. Lines below the two choices appear only when this Mac has + /// folders no option deletes, or Darkbloom parts with their own uninstall. + public static func screen(_ plan: Plan) -> [String] { + var lines = ["Uninstall Darkbloom from this Mac", "", + " 1) Remove everything", + " The app, settings, pairing, logs and all models · frees \(formatBytes(plan.frees(.everything)))", + " 2) Keep models", + plan.models.isEmpty ? " Removes everything else (no models are downloaded)" + : " Removes everything else; a reinstall reuses the \(formatBytes(plan.modelBytes)) of models"] + let notes = neverTouched(plan).filter { $0 != keychainLine } + + plan.refused.map { "Not deleted: \($0.label) (\($0.path)): \($0.reason ?? "")" } + if !notes.isEmpty { lines += [""] + notes.map { " \($0)" } } + lines.append("") + return lines + } + + /// `--dry-run`: every action and path, with sizes, for `mode`. + public static func dryRun(_ plan: Plan, mode: Mode) -> [String] { + var lines = ["\(plan.cli) uninstall --\(mode.rawValue) would, changing nothing now:"] + var number = 0 + func action(_ text: String) { number += 1; lines.append(" \(number). \(text)") } + action("\(stopServingStep): drain accepted requests, as `\(plan.cli) stop`") + if let shared = plan.items.first(where: { $0.sharedWith != nil }), let other = shared.sharedWith { + action("\(ownClusterStep): \(shared.ownClusterAgentPlist ?? "this install has none"); the pair and \(other)'s " + + "cluster service are left as they are") + } else { + action("\(clusterStep), as `\(plan.cli) cluster stop`: " + + (!plan.clusterService.isEmpty ? plan.clusterService.joined(separator: ", ") + : plan.clusterServiceRunning ? "no login agent, but a cluster service is running on this Mac; this stops it" + : "no cluster service on this Mac")) + } + for service in plan.services { + action("Remove the \(service.name): \(service.path ?? "not installed")") + } + action("\(tokenStep), as `\(plan.cli) logout` does (best effort)") + if !plan.sharesCluster { + for peer in plan.pairing?.peers ?? [] { action("Forget the pairing with \(peer.name), as `\(plan.cli) cluster pair --forget`") } + action("\(cableStep), as `\(plan.cli) cluster link --remove` (macOS asks for an administrator's password)") + } + for item in plan.removed(mode) { action("Delete \(row(item))") } + lines.append(" Frees \(formatBytes(plan.frees(mode))) (APFS clones counted once).") + if mode == .keepModels, !plan.models.isEmpty { lines.append(" " + keptModelsLine(plan)) } + lines += plan.refused.map { " Not deleted: \($0.label) (\($0.path)): \($0.reason ?? "")" } + lines += neverTouched(plan).map { " \($0)" } + return lines + } + + /// The summary after a run: each step with its status, what was kept and where, then the way back and the other Mac. + public static func summary(_ report: Report, plan: Plan) -> [String] { + var name = "Darkbloom" + if plan.sharesCluster, let this = BuildEnvironment.allCases.first(where: { $0.cliName == plan.cli }) { + // Beside another install, "Darkbloom" alone would also mean the one that stays. + name = installName(this).prefix(1).uppercased() + installName(this).dropFirst() + } + let headline = report.failed ? "\(name) is not fully removed from this Mac (see the failed step)." + : report.incomplete ? "\(name) is not fully removed from this Mac: " + incompleteReason(plan) + : report.mode == .keepModels ? "\(name) is removed from this Mac; its models are kept." + : "\(name) is removed from this Mac." + var lines = [headline] + lines += report.steps.map { step in + let status = step.status.rawValue.padding(toLength: 8, withPad: " ", startingAt: 0) + return " \(status) \(step.name)" + (step.detail.map { ": \($0)" } ?? "") + } + if let before = report.availableBefore, let after = report.availableAfter, + report.steps.contains(where: { $0.name.hasPrefix("Delete ") && $0.status == .done }) { + lines.append("Space freed: \(formatBytes(max(0, after - before))) (this disk had \(formatBytes(before)) free, now \(formatBytes(after))).") + } + if report.mode == .keepModels, !plan.models.isEmpty { lines.append(keptModelsLine(plan)) } + lines += neverTouched(plan) + if report.mode == .keepModels { + lines.append("To come back: run `\(plan.installCommand)`, then `\(plan.cli) start` or `\(plan.cli) cluster`; " + + "the models are found automatically.") + if plan.kept.contains(where: { $0.label == chosenModelsLabel }) { + lines.append("Models in the folder you chose are not found automatically: after installing, run " + + "`\(plan.cli) models location `.") + } + } + if let pairing = plan.pairing, !plan.sharesCluster { lines.append(otherMacLine(pairing, cli: plan.cli)) } + return lines + } + + /// Why the run left something of Darkbloom's: its app folder is (in) the models folder the person chose, or a folder + /// was refused. + static func incompleteReason(_ plan: Plan) -> String { + let reasons = plan.refused.filter { $0.kind == .command }.compactMap(\.reason) + return reasons.contains { $0.hasPrefix(chosenFolderIsItReason) } ? "its app folder is your models folder, so it was kept (see below)." + : reasons.contains { $0.hasPrefix(chosenFolderHoldsItReason) } ? "its app folder is inside your models folder, so it was kept (see below)." + : "some of its folders were not removed (see below)." + } + + /// The models `--keep-models` keeps, with their size and folders. + static func keptModelsLine(_ plan: Plan) -> String { + let count = plan.models.filter { URL(fileURLWithPath: $0.path).lastPathComponent.hasPrefix("models--") }.count + let store = plan.models.contains { $0.label == clusterStoreLabel } + let folders = Set(plan.models.map { + $0.label == clusterStoreLabel ? $0.path : URL(fileURLWithPath: $0.path).deletingLastPathComponent().path + }).sorted() + return "Kept: \(count) model\(count == 1 ? "" : "s")\(store ? " and the cluster model store" : ""), " + + "\(formatBytes(plan.modelBytes)), in \(folders.joined(separator: " and "))." + } + + /// What no option deletes: folders the person chose or outside Darkbloom's, Keychain keys, and what has its own + /// uninstall. A chosen models folder inside Darkbloom's own is named as kept. + static func neverTouched(_ plan: Plan) -> [String] { + plan.kept.map { "\($0.keptInDarkbloomFolder ? "Kept" : "Never touched"): \($0.label) (\(formatBytes($0.bytes)), \($0.path)): " + + ($0.reason ?? "") } + [keychainLine] + plan.elsewhere + } + + /// The last line on a paired Mac, about the other one. + static func otherMacLine(_ pairing: ProviderUninstallPairing, cli: String) -> String { + let name = pairing.otherMacName.map { "The other Mac (\($0))" } ?? "The other Mac" + let relation: String + switch pairing.role { + case .leader: relation = "followed this one" + case .member: relation = "led this pair" + case nil: relation = "is paired with this one" + } + return "\(name) \(relation): run `\(cli) uninstall` there too, or `\(cli) cluster` on it to pair it with another Mac." + } + + static func row(_ item: ProviderUninstallItem) -> String { + let label = deletedLabel(item) + return item.bytes > 0 ? "\(label) \(formatBytes(item.bytes)) \(item.path)" : "\(label) \(item.path)" + } + + /// What deleting `item` takes: all of it, or all but the models folder the person chose inside it. + static func deletedLabel(_ item: ProviderUninstallItem) -> String { + item.keeping.isEmpty ? item.label : item.label + ", except " + item.keepingWhat + } + + static func formatBytes(_ bytes: Int64) -> String { + let formatter = ByteCountFormatter() + formatter.countStyle = .file + formatter.allowsNonnumericFormatting = false + return formatter.string(fromByteCount: bytes) + } +} + +// MARK: - Choosing a mode + +extension ProviderUninstall { + public enum Invocation: Equatable, Sendable { + /// Ask on the screen (a terminal, no mode given). + case ask + /// Run `mode`; `confirm` asks once in the terminal first. + case run(Mode, confirm: Bool) + case dryRun([Mode]) + /// Refused before anything runs, with the line to print. + case refuse(String) + } + + /// What one read of keys on the screen means: a choice, cancel, or nothing (keep waiting). + public enum Key: Equatable, Sendable { + case choose(Mode) + case cancel + } + + /// `1` or `2` choose; Esc alone, `q`, Ctrl-C, Ctrl-D or the end of input cancel; anything else (an arrow key's + /// escape sequence too) is ignored. + public static func key(_ bytes: [UInt8]) -> Key? { + switch bytes { + case [UInt8(ascii: "1")]: return .choose(.everything) + case [UInt8(ascii: "2")]: return .choose(.keepModels) + case [], [0x1B], [UInt8(ascii: "q")], [0x03], [0x04]: return .cancel + default: return nil + } + } + + public static func invocation(everything: Bool, keepModels: Bool, yes: Bool, dryRun: Bool, interactive: Bool, + userID: uid_t = geteuid(), cli: String = BuildEnvironment.current.cliName) -> Invocation { + guard userID != 0 else { return .refuse(rootRefusal(cli: cli)) } + let mode: Mode? = everything ? .everything : keepModels ? .keepModels : nil + if dryRun { return .dryRun(mode.map { [$0] } ?? Mode.allCases) } + guard let mode else { return interactive ? .ask : .refuse(usage(cli: cli)) } + if yes { return .run(mode, confirm: false) } + return interactive ? .run(mode, confirm: true) : .refuse(usage(cli: cli)) + } +} + +// MARK: - Dry run as JSON + +extension ProviderUninstall { + public struct DryRunDocument: Encodable { + public struct Action: Encodable { let action: String; let path: String?; let bytes: Int64? } + public struct ModePlan: Encodable { + let mode: Mode + let actions: [Action] + /// Bytes the deletions free, APFS clones counted once. + let frees: Int64 + let kept: [ProviderUninstallItem] + let refused: [ProviderUninstallItem] + } + public let schema = "darkbloom_uninstall_plan_v1" + public let modes: [ModePlan] + /// What no option removes, each with how to remove it. + public let neverTouched: [String] + public let otherMac: String? + } + + public static func dryRunDocument(_ plan: Plan, modes: [Mode]) -> DryRunDocument { + let modePlans = modes.map { mode -> DryRunDocument.ModePlan in + var actions = [DryRunDocument.Action(action: stopServingStep, path: nil, bytes: nil)] + if let shared = plan.items.first(where: { $0.sharedWith != nil }) { + actions.append(.init(action: ownClusterStep, path: shared.ownClusterAgentPlist, bytes: nil)) + } else { + let clusterAgents: [String?] = plan.clusterService.isEmpty ? [nil] : plan.clusterService + actions += clusterAgents.map { .init(action: clusterStep, path: $0, bytes: nil) } + } + actions += plan.services.map { .init(action: "Remove the \($0.name)", path: $0.path, bytes: nil) } + actions.append(.init(action: tokenStep, path: nil, bytes: nil)) + if !plan.sharesCluster { + actions += (plan.pairing?.peers ?? []).map { .init(action: "Forget the pairing with \($0.name)", path: nil, bytes: nil) } + actions.append(.init(action: cableStep, path: nil, bytes: nil)) + } + actions += plan.removed(mode).map { .init(action: "Delete \(deletedLabel($0))", path: $0.path, bytes: $0.bytes) } + let keptModels = mode == .keepModels ? plan.models : [] + return .init(mode: mode, actions: actions, frees: plan.frees(mode), kept: keptModels + plan.kept, refused: plan.refused) + } + return .init(modes: modePlans, neverTouched: [keychainLine] + plan.elsewhere, + otherMac: plan.sharesCluster ? nil : plan.pairing.map { otherMacLine($0, cli: plan.cli) }) + } +} diff --git a/provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift b/provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift index 68233d055e..3617a04e61 100644 --- a/provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift @@ -23,7 +23,7 @@ public enum WatchdogAgent: Sendable { public static let checkIntervalSeconds = 60 public static func plistPath() -> URL { - FileManager.default.homeDirectoryForCurrentUser + LaunchctlControl.homeDirectory() .appendingPathComponent("Library/LaunchAgents") .appendingPathComponent("\(label).plist") } diff --git a/provider-swift/Sources/darkbloom/Darkbloom.swift b/provider-swift/Sources/darkbloom/Darkbloom.swift index 2c6098ab57..4fa2c6405b 100644 --- a/provider-swift/Sources/darkbloom/Darkbloom.swift +++ b/provider-swift/Sources/darkbloom/Darkbloom.swift @@ -32,6 +32,7 @@ struct Darkbloom: AsyncParsableCommand { Addon.self, Sandbox.self, Stop.self, + Uninstall.self, Restart.self, Status.self, Doctor.self, diff --git a/provider-swift/Sources/darkbloom/StopCommand.swift b/provider-swift/Sources/darkbloom/StopCommand.swift index c1d11eb3cc..e04d008c15 100644 --- a/provider-swift/Sources/darkbloom/StopCommand.swift +++ b/provider-swift/Sources/darkbloom/StopCommand.swift @@ -9,7 +9,7 @@ struct Stop: AsyncParsableCommand { @OptionGroup var drain: DrainOptions - @Flag(help: "Also remove the provider, watchdog and desktop API launchd agents (full uninstall).") + @Flag(help: "Also remove the provider, watchdog and desktop API launchd agents; files stay. To take Darkbloom off this Mac, run `\(BuildEnvironment.current.cliName) uninstall`.") var uninstall = false mutating func run() async throws { diff --git a/provider-swift/Sources/darkbloom/UninstallCommand.swift b/provider-swift/Sources/darkbloom/UninstallCommand.swift new file mode 100644 index 0000000000..2f7bcea26b --- /dev/null +++ b/provider-swift/Sources/darkbloom/UninstallCommand.swift @@ -0,0 +1,210 @@ +import ArgumentParser +import Darwin +import Foundation +import ProviderCore + +/// `darkbloom uninstall`: remove everything, or everything but the models. `ProviderUninstall` owns the steps, their +/// order and every path rule; this command asks, and wires the commands it reuses: `stop`'s drain, `cluster stop`, +/// `stop --uninstall`'s agents, `logout`'s token revocation, `cluster pair --forget` and `cluster link --remove`. +struct Uninstall: AsyncParsableCommand { + static let configuration = CommandConfiguration( + abstract: "Take Darkbloom off this Mac: remove everything, or keep the models.", + discussion: """ + In a terminal without options, it shows both choices with this Mac's sizes and asks. Both stop serving, \ + remove every Darkbloom background service, revoke this Mac's account token, unpair, undo the cable port \ + setup (macOS asks for an administrator's password) and delete Darkbloom's settings, logs, caches, the \ + app and the command link. --everything also deletes the models Darkbloom downloaded; --keep-models keeps \ + them, so a reinstall finds them. Choosing 1 on the screen asks once more before deleting the models. A \ + models folder you chose, and the cluster model store beside it, are never deleted, even inside \ + Darkbloom's own folder; nor are Keychain keys. Run it as yourself, not with sudo. With both the \ + production and the DevNet app on this Mac, the pairing, cluster setup and cable port setup stay for the \ + other one, and only this install's own cluster service is removed. + """) + + @Flag(help: "Remove everything: the app, settings, pairing, logs and all models.") + var everything = false + @Flag(name: .customLong("keep-models"), help: "Remove everything but the models, so a reinstall reuses them.") + var keepModels = false + @Flag(name: .shortAndLong, help: "Don't ask for confirmation.") + var yes = false + @Flag(name: .customLong("dry-run"), help: "List every action and path with sizes, and change nothing.") + var dryRun = false + @Flag(help: "With --dry-run: print the plan as JSON.") + var json = false + @OptionGroup var drain: DrainOptions + + func validate() throws { + guard !(keepModels && everything) else { throw ValidationError("Choose one of --everything and --keep-models.") } + guard !json || dryRun else { throw ValidationError("--json goes with --dry-run.") } + } + + mutating func run() async throws { + Darkbloom.ensureLogging() + let interactive = isatty(STDIN_FILENO) != 0 && isatty(STDOUT_FILENO) != 0 + let invocation = ProviderUninstall.invocation(everything: everything, keepModels: keepModels, yes: yes, + dryRun: dryRun, interactive: interactive, userID: geteuid()) + if case .refuse(let line) = invocation { + printError(line) + throw ExitCode.validationFailure + } + let plan = Self.plan() + let mode: ProviderUninstall.Mode + switch invocation { + case .refuse: return + case .dryRun(let modes): + if json { try printJSON(ProviderUninstall.dryRunDocument(plan, modes: modes)); return } + for (index, mode) in modes.enumerated() { + if index > 0 { print("") } + ProviderUninstall.dryRun(plan, mode: mode).forEach { print($0) } + } + return + case .ask: + ProviderUninstall.screen(plan).forEach { print($0) } + guard let chosen = Self.choose() else { print("Nothing changed."); return } + if chosen == .everything { + print(ProviderUninstall.everythingQuestion(plan), terminator: "") + fflush(stdout) + guard ProviderUninstall.confirmed(readLine()) else { print("Nothing changed."); return } + } + mode = chosen + case .run(let given, let confirm): + mode = given + if confirm { + ProviderUninstall.dryRun(plan, mode: mode).forEach { print($0) } + guard Self.confirm() else { print("Nothing changed."); return } + } + } + let report = await ProviderUninstall.run(mode, items: plan.items, pairing: plan.pairing, + operations: Self.operations(drain: drain)) { print("→ \($0)") } + print("") + ProviderUninstall.summary(report, plan: plan).forEach { print($0) } + if report.failed || report.incomplete { throw ExitCode.failure } + } + + /// What this Mac has, read before anything changes. + static func plan() -> ProviderUninstall.Plan { + let configPath = ConfigManager.defaultConfigPath(home: FileManager.default.homeDirectoryForCurrentUser) + let config = FileManager.default.fileExists(atPath: configPath.path) ? try? ConfigManager.load(from: configPath) : nil + let agents: [(String, URL)] = [("provider service", LaunchAgent.plistPath()), ("watchdog service", WatchdogAgent.plistPath()), + ("desktop API service", DesktopService.plistPath())] + var elsewhere: [String] = [] + let cli = BuildEnvironment.current.cliName + if FanServiceManager().isInstalled() { + elsewhere.append("The fan helper stays (a system service every Darkbloom install shares); " + + "to remove it, run `sudo \(cli) fan uninstall` before removing everything.") + } + let sandbox = SandboxAddon.live() + if sandbox.isInstalled { + elsewhere.append("Darkbloom Sandbox stays (\(sandbox.root.path)); to remove it, run `\(cli) sandbox uninstall` " + + "before removing everything.") + } + return .init(clusterService: ClusterServiceAgent.installedLabels().map { ClusterServiceAgent.plistPath(label: $0).path }, + clusterServiceRunning: ClusterService.running(), + services: agents.map { .init(name: $0.0, path: FileManager.default.fileExists(atPath: $0.1.path) ? $0.1.path : nil) }, + items: ProviderUninstall.inventory(.live(config: config, configPath: configPath)), + pairing: ProviderUninstallPairing.read(), + elsewhere: elsewhere) + } + + /// The live steps, each through the command or function that does it today. + static func operations(drain: DrainOptions) -> ProviderUninstall.Operations { + let lifecycle = LifecycleHold() + let executable = URL(fileURLWithPath: Start.currentExecutablePath()) + return .init( + stopServing: { + let wasLoaded = LaunchAgent.isLoaded() + lifecycle.session = try await ServiceDrain.prepare(options: drain) + try await ServiceDrain.stopDrainedProvider() + return wasLoaded ? .done() : .skipped("the provider service was not running") + }, + stopClusterPart: { + let current = ClusterServiceAgentPlan.label(executablePath: ClusterService.resolvedExecutable(executable)) + guard !ClusterServiceAgent.installedLabels().isEmpty || ClusterServiceAgent.isLoaded(label: current) + || ClusterService.running() else { return .skipped("no cluster service on this Mac") } + do { + var stop = try Cluster.Stop.parse([]) + try await stop.run() + return .done() + } catch { + // The pair could not stop together (the other Mac did not answer): this Mac is leaving, so stop + // only its own part, as `cluster stop --local-only` does when the other Mac is gone. + var stop = try Cluster.Stop.parse(["--local-only"]) + try await stop.run() + return .done("the other Mac was not asked to stop (\(error))") + } + }, + removeServices: [ + ("Remove the provider service", { + try ProviderUninstall.removeAgent(plist: LaunchAgent.plistPath(), loaded: LaunchAgent.isLoaded(), + uninstall: LaunchAgent.uninstall) + }), + ("Remove the watchdog service", { + try ProviderUninstall.removeAgent(plist: WatchdogAgent.plistPath(), loaded: WatchdogAgent.isLoaded(), + uninstall: WatchdogAgent.uninstall) + }), + ("Remove the desktop API service", { + try ProviderUninstall.removeAgent(plist: DesktopService.plistPath(), + loaded: LaunchAgent.isLoaded(agentLabel: DesktopService.label), + uninstall: { try DesktopService.uninstall() }) + }), + ], + servicesHandled: { lifecycle.release() }, + revokeToken: { + // `darkbloom logout`'s revocation. The token file goes with ~/.darkbloom. + guard let token = AuthTokenStore.load() else { return .skipped("no saved account token") } + return await Logout.revokeSavedToken(token) ? .done() + : .skipped("the coordinator did not confirm it (offline, or the token's issuer is unknown)") + }, + forget: { pin in try Cluster.Pair.parse(["--forget", pin]).run() }, + removeCableSetup: { + let result = ClusterLinkRepair.remove(device: nil) + result.summaryLines.forEach { print($0) } + // As `cluster link --remove` prints them: where no prompt could be, the commands go to standard error. + if let script = result.manualScript { + fflush(stdout); printError("sudo sh \(script)") + } else if !result.manualCommands.isEmpty { + fflush(stdout); result.manualCommands.forEach { printError($0) } + } + guard result.outcome.exitCode == 0 else { throw ProviderUninstall.StepFailure(result.message) } + return result.outcome == .removed ? .done() : .skipped("nothing to undo") + }, + availableBytes: { + let values = try? FileManager.default.homeDirectoryForCurrentUser.resourceValues(forKeys: [.volumeAvailableCapacityKey]) + return values?.volumeAvailableCapacity.map(Int64.init) + }) + } + + /// The drain's lease, held until the services are removed, so an update cannot start the provider in between. + private final class LifecycleHold: @unchecked Sendable { + var session: SelfUpdater.UpdateSession? + func release() { session?.release(); session = nil } + } + + /// Reads keys without Enter until one decides (`ProviderUninstall.key`); nil to cancel. + static func choose() -> ProviderUninstall.Mode? { + print(ProviderUninstall.choicePrompt, terminator: "") + fflush(stdout) + var saved = termios() + tcgetattr(STDIN_FILENO, &saved) + var raw = saved + raw.c_lflag &= ~UInt(ECHO | ICANON | ISIG) + tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) + defer { tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved) } + while true { + var buffer = [UInt8](repeating: 0, count: 8) + let count = read(STDIN_FILENO, &buffer, buffer.count) + switch ProviderUninstall.key(Array(buffer.prefix(max(0, count)))) { + case .choose(let mode)?: print(mode == .everything ? "1" : "2"); return mode + case .cancel?: print("Esc"); return nil + case nil: continue + } + } + } + + /// A mode given as a flag, in a terminal without --yes: y or yes goes on. + static func confirm(readInput: () -> String? = { readLine() }) -> Bool { + print("Continue? [y/N]: ", terminator: "") + fflush(stdout) + return ProviderUninstall.confirmed(readInput()) + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift new file mode 100644 index 0000000000..59dd5fba18 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift @@ -0,0 +1,46 @@ +import ArgumentParser +import ProviderCore +import Testing + +@testable import darkbloom + +// Parsing only: nothing here runs a command, launchd or a prompt. +@Suite("Uninstall command") +struct UninstallCommandTests { + private let cli = BuildEnvironment.current.cliName + + @Test("uninstall is a command, with --everything or --keep-models, --yes, --dry-run, --json and stop's drain options") + func uninstallParses() throws { + for arguments in [["uninstall"], ["uninstall", "--everything", "--yes"], ["uninstall", "--keep-models", "-y"], + ["uninstall", "--keep-models", "--dry-run", "--json"], ["uninstall", "--dry-run"], + ["uninstall", "--everything", "--yes", "--force", "--timeout", "30"]] { + let command = try Darkbloom.parseAsRoot(arguments) + #expect(String(describing: type(of: command)) == "Uninstall", "\(arguments)") + } + #expect(Darkbloom.helpMessage().contains("uninstall")) + } + + @Test("conflicting flags, and the old --keep-data, are refused with the usage before anything runs") + func conflictingFlagsAreRefused() { + for (arguments, message) in [(["uninstall", "--everything", "--keep-models"], "Choose one of --everything and --keep-models."), + (["uninstall", "--everything", "--json"], "--json goes with --dry-run."), + (["uninstall", "--keep-data", "--yes"], "Unknown option '--keep-data'")] { + do { + _ = try Darkbloom.parseAsRoot(arguments) + Issue.record("\(arguments) parsed") + } catch { + #expect(Darkbloom.message(for: error).contains(message), "\(arguments)") + #expect(Darkbloom.fullMessage(for: error).contains("Usage: \(cli) uninstall [--everything] [--keep-models]"), + "\(arguments)") + #expect(Darkbloom.exitCode(for: error) == .validationFailure, "\(arguments)") + } + } + } + + @Test("stop --uninstall still parses as before, and its help points to uninstall") + func stopUninstallIsUnchanged() throws { + let stop = try #require(try Darkbloom.parseAsRoot(["stop", "--uninstall"]) as? Stop) + #expect(stop.uninstall) + #expect(Stop.helpMessage().contains("`\(cli) uninstall`")) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift new file mode 100644 index 0000000000..79554cb241 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -0,0 +1,853 @@ +import Foundation +import Testing +@testable import ProviderCore + +// `darkbloom uninstall` on a fake home: real files in a temporary root, the real provider, watchdog and cluster +// service agent removals through a fake launchctl, and recorded stand-ins for the drain, the pairing and the cable. +// Nothing here runs launchctl, a provider or a prompt, or reads the real home or Keychain. + +private final class FakeLaunchd: @unchecked Sendable { + private let lock = NSLock() + private var loaded: Set + private var calls: [[String]] = [] + + init(loaded: Set) { self.loaded = loaded } + + func run(_ arguments: [String]) throws -> LaunchctlControl.Output { + lock.withLock { + calls.append(arguments) + let label = arguments.count > 1 ? String(arguments[1].split(separator: "/").last ?? "") : "" + switch arguments.first { + case "print": + return loaded.contains(label) ? .init(status: 0, stdout: "", stderr: "") + : .init(status: 113, stdout: "", stderr: "Could not find service \"\(label)\" in domain for user gui: 501\n") + case "bootout": + loaded.remove(label) + return .init(status: 0, stdout: "", stderr: "") + case "disable", "enable": + return .init(status: 0, stdout: "", stderr: "") + default: + return .init(status: 64, stdout: "", stderr: "unexpected launchctl \(arguments)\n") + } + } + } + + var bootedOut: [String] { lock.withLock { calls.filter { $0.first == "bootout" }.map { String($0[1].split(separator: "/").last ?? "") } } } + func load(_ label: String) { lock.withLock { _ = loaded.insert(label) } } + var callCount: Int { lock.withLock { calls.count } } +} + +private final class Calls: @unchecked Sendable { + private let lock = NSLock() + private var entries: [String] = [] + func add(_ entry: String) { lock.withLock { entries.append(entry) } } + var all: [String] { lock.withLock { entries } } + func count(_ prefix: String) -> Int { all.filter { $0.hasPrefix(prefix) }.count } +} + +private struct Fixture { + static let pin = String(repeating: "ab", count: 32) + static let ours = ".cache/huggingface/hub/models--org--ours-mlx" + static let clusterLabel = ClusterServiceAgentPlan.labelPrefix + "0123456789ab" + + let root: URL + let home: URL + let outside: URL + let paths: ProviderUninstallPaths + let launchd: FakeLaunchd + let calls = Calls() + /// Every path the run asked to delete, in order. + let deletes = Calls() + + var agents: URL { home.appendingPathComponent("Library/LaunchAgents") } + var desktopPlist: URL { agents.appendingPathComponent("io.darkbloom.desktop-api.plist") } + var savedModels: URL { outside.appendingPathComponent("external-hub") } + + /// A provider Mac with every Darkbloom place filled, a saved model folder on "another volume" and another tool's model. + static func make() throws -> Fixture { + let base = FileManager.default.temporaryDirectory.appendingPathComponent("uninstall-" + UUID().uuidString) + try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true) + let root = URL(fileURLWithPath: ProviderUninstallPaths.canonical(base.path), isDirectory: true) + let home = root.appendingPathComponent("home", isDirectory: true) + var paths = ProviderUninstallPaths(home: home, commandLinkDirectory: root.appendingPathComponent("usr/local/bin")) + let fixture = Fixture(root: root, home: home, outside: root.appendingPathComponent("outside"), paths: paths, + launchd: FakeLaunchd(loaded: [LaunchAgent.label, WatchdogAgent.label, clusterLabel])) + let install = paths.installDirectory.lastPathComponent + let app = "\(install)/\(paths.appBundleName)/Contents/MacOS/\(paths.commandLink.lastPathComponent)" + for file in [app, "\(install)/provider.log", "\(install)/cluster-setup/wizard.json", + "\(install)/cluster-pairing/pairings.json", "\(install)/auth_token", + "\(paths.configDirectory.path.dropFirst(home.path.count + 1))/provider.toml", + "\(paths.cacheDirectory.path.dropFirst(home.path.count + 1))/kv3/segment", + "\(Self.ours)/snapshots/rev1/.darkbloom-manifest.json", "\(Self.ours)/snapshots/rev1/model.safetensors", + ".cache/huggingface/hub/models--org--partial/snapshots/.local-staging-v2__org__partial/a.part", + ".cache/huggingface/hub/models--org--other-mlx/snapshots/rev1/model.safetensors", + ".cache/huggingface/hub/.artifact-writer-locks/models--org--ours-mlx", + ".cache/huggingface/darkbloom-cluster-models/org--ours/.darkbloom-manifest.json", + "Library/LaunchAgents/\(LaunchAgent.label).plist", "Library/LaunchAgents/\(WatchdogAgent.label).plist", + "Library/LaunchAgents/io.darkbloom.desktop-api.plist", "Library/LaunchAgents/\(clusterLabel).plist"] { + try fixture.write(home.appendingPathComponent(file)) + } + // The scanner's selected revision, and the cluster store's copy as `darkbloom cluster` makes it: an APFS clone. + let ref = home.appendingPathComponent("\(Self.ours)/refs/main") + try FileManager.default.createDirectory(at: ref.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("rev1".utf8).write(to: ref) + try fixture.clone(home.appendingPathComponent("\(Self.ours)/snapshots/rev1/model.safetensors"), + to: home.appendingPathComponent(".cache/huggingface/darkbloom-cluster-models/org--ours/model.safetensors")) + try fixture.link(home.appendingPathComponent("\(install)/bin/\(paths.commandLink.lastPathComponent)"), + to: "../\(paths.appBundleName)/Contents/MacOS/\(paths.commandLink.lastPathComponent)") + try fixture.link(paths.commandLink, to: paths.installDirectory.appendingPathComponent("bin/\(paths.commandLink.lastPathComponent)").path) + try fixture.write(fixture.savedModels.appendingPathComponent("models--org--big/snapshots/rev1/.darkbloom-manifest.json")) + paths.savedModelCache = fixture.savedModels + return Fixture(root: root, home: home, outside: fixture.outside, paths: paths, launchd: fixture.launchd) + } + + func write(_ url: URL, bytes: Int = 8192) throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(repeating: 7, count: bytes).write(to: url) + } + + func clone(_ source: URL, to destination: URL) throws { + try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) + guard clonefile(source.path, destination.path, 0) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + } + + func link(_ url: URL, to destination: String) throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(atPath: url.path, withDestinationPath: destination) + } + + func exists(_ url: URL) -> Bool { + var info = stat() + return lstat(url.path, &info) == 0 + } + + /// Every path under `url` (links not followed), to compare before and after. + func tree(_ url: URL, excluding excluded: String? = nil) -> [String] { + let all = (FileManager.default.enumerator(atPath: url.path)?.allObjects as? [String]) ?? [] + return all.filter { excluded == nil || !$0.hasPrefix(excluded!) }.sorted() + } + + func remove() { try? FileManager.default.removeItem(at: root) } + + /// The same Mac with `models location` set to `folder`. + func choosingModels(_ folder: URL) -> Fixture { + var paths = paths + paths.savedModelCache = folder + return Fixture(root: root, home: home, outside: outside, paths: paths, launchd: launchd) + } + + var pairing: ProviderUninstallPairing { + .init(peers: [.init(pin: Self.pin, name: "M3 Ultra, 512 GB")], otherMacName: "M3 Ultra, 512 GB", role: .leader) + } + + func plan(pairing: ProviderUninstallPairing?) -> ProviderUninstall.Plan { + let installed = { (name: String) in FileManager.default.fileExists(atPath: agents.appendingPathComponent(name).path) } + let services = [("provider service", "\(LaunchAgent.label).plist"), ("watchdog service", "\(WatchdogAgent.label).plist"), + ("desktop API service", desktopPlist.lastPathComponent)] + return .init(cli: "darkbloom", + clusterService: installed("\(Fixture.clusterLabel).plist") ? [agents.appendingPathComponent("\(Fixture.clusterLabel).plist").path] : [], + services: services.map { .init(name: $0.0, path: installed($0.1) ? agents.appendingPathComponent($0.1).path : nil) }, + items: ProviderUninstall.inventory(paths), pairing: pairing) + } + + func operations(drainFails: Bool = false, clusterFails: Bool = false, linkFails: Bool = false, + tokenUnconfirmed: Bool = false) -> ProviderUninstall.Operations { + let calls = calls, desktop = desktopPlist + let free = Calls() + return .init( + stopServing: { + calls.add("drain") + if drainFails { throw ProviderUninstall.StepFailure("1 accepted request still running after 600 s") } + return .done() + }, + stopClusterPart: { + calls.add("cluster stop") + if clusterFails { throw ProviderUninstall.StepFailure("the other Mac did not acknowledge the stop") } + return try ClusterServiceAgent.uninstall().isEmpty ? .skipped("no cluster service on this Mac") : .done() + }, + removeServices: [ + ("Remove the provider service", { + try ProviderUninstall.removeAgent(plist: LaunchAgent.plistPath(), loaded: LaunchAgent.isLoaded(), + uninstall: LaunchAgent.uninstall) + }), + ("Remove the watchdog service", { + try ProviderUninstall.removeAgent(plist: WatchdogAgent.plistPath(), loaded: WatchdogAgent.isLoaded(), + uninstall: WatchdogAgent.uninstall) + }), + ("Remove the desktop API service", { + try ProviderUninstall.removeAgent(plist: desktop, loaded: false, + uninstall: { try FileManager.default.removeItem(at: desktop) }) + }), + ], + servicesHandled: { calls.add("lease released") }, + revokeToken: { + calls.add("revoke token") + return tokenUnconfirmed ? .skipped("the coordinator did not confirm it (offline, or the token's issuer is unknown)") + : .done() + }, + forget: { calls.add("forget \($0)") }, + removeCableSetup: { + calls.add("link remove") + if linkFails { throw ProviderUninstall.StepFailure("the macOS prompt was declined; nothing was changed") } + return .done() + }, + delete: { [deletes] in + deletes.add($0.path) + try FileManager.default.removeItem(at: $0) + }, + availableBytes: { + free.add("measured") + return free.count("measured") == 1 ? 1_000_000_000 : 1_250_000_000 + }) + } + + /// Runs with the fake home and the fake launchctl. + func run(_ mode: ProviderUninstall.Mode, items: [ProviderUninstallItem]? = nil, pairing: ProviderUninstallPairing? = nil, + operations: ProviderUninstall.Operations? = nil) async -> ProviderUninstall.Report { + await LaunchctlControl.$homeDirectoryForTesting.withValue(home) { + await LaunchctlControl.$runnerForTesting.withValue({ try launchd.run($0) }) { + await ProviderUninstall.run(mode, items: items ?? ProviderUninstall.inventory(paths), pairing: pairing, + operations: operations ?? self.operations()) + } + } + } +} + +private func status(_ report: ProviderUninstall.Report, _ name: String) -> ProviderUninstall.Step.Status? { + report.steps.first { $0.name == name }?.status +} + +/// With `UNINSTALL_TRANSCRIPT_DIR` set, keeps what a person would read, with the fake root shown as `~`'s parent. +private func transcript(_ name: String, _ lines: [String], _ fixture: Fixture) { + guard let directory = ProcessInfo.processInfo.environment["UNINSTALL_TRANSCRIPT_DIR"] else { return } + let text = lines.joined(separator: "\n").replacingOccurrences(of: fixture.home.path, with: "~") + .replacingOccurrences(of: fixture.root.path, with: "") + "\n" + try? text.write(toFile: directory + "/" + name + ".txt", atomically: true, encoding: .utf8) +} + +/// The owner's Mac: the production and the DevNet app, each with its command, and the cluster files every install reads +/// (`ClusterUserPaths`, the pairing store, the setup wizard) in ~/.darkbloom and ~/.config/darkbloom. Returns those files. +private func installBoth(_ fixture: Fixture) throws -> [URL] { + for install in [BuildEnvironment.prod, .dev] { + let folder = install.installDirectory(home: fixture.home) + let binary = folder.appendingPathComponent("\(install.appBundleName)/Contents/MacOS/\(install.cliName)") + if !fixture.exists(binary) { try fixture.write(binary) } + let bin = folder.appendingPathComponent("bin/\(install.cliName)") + if !fixture.exists(bin) { try fixture.link(bin, to: "../\(install.appBundleName)/Contents/MacOS/\(install.cliName)") } + try fixture.write(folder.appendingPathComponent("provider.log")) + } + let shared = [".darkbloom/cluster-pairing/pairings.json", ".darkbloom/cluster-setup/wizard.json", + ".darkbloom/cluster-device/link-alias.json", ".darkbloom/cluster/device-index.json", + ".config/darkbloom/clusters/0123.cluster.json"].map { fixture.home.appendingPathComponent($0) } + for file in shared { try fixture.write(file) } + return shared +} + +/// The cluster service agent `install`'s app installs (`ClusterServiceAgentPlan.label` of its app). +private func clusterAgent(_ install: BuildEnvironment, _ fixture: Fixture) -> String { + ClusterServiceAgentPlan.label(executablePath: install.installDirectory(home: fixture.home) + .appendingPathComponent("\(install.appBundleName)/Contents/MacOS/\(install.cliName)").path) +} + +@Suite("darkbloom uninstall") +struct ProviderUninstallTests { + @Test("(a) keep models: everything else goes, unpaired and cable undone; the models stay and are found again") + func keepModelsRemovesEverythingElse() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let hub = fixture.home.appendingPathComponent(".cache/huggingface/hub") + let models = [hub.appendingPathComponent("models--org--ours-mlx"), hub.appendingPathComponent("models--org--partial"), + hub.appendingPathComponent(".artifact-writer-locks"), fixture.paths.clusterModelStore] + let before = models.map { fixture.tree($0) } + let receipts = [Fixture.ours + "/refs/main", Fixture.ours + "/snapshots/rev1/.darkbloom-manifest.json", + ".cache/huggingface/darkbloom-cluster-models/org--ours/.darkbloom-manifest.json"] + .map { try? Data(contentsOf: fixture.home.appendingPathComponent($0)) } + let plan = fixture.plan(pairing: fixture.pairing) + let report = await fixture.run(.keepModels, items: plan.items, pairing: fixture.pairing) + + #expect(!report.failed, "\(report.steps)") + #expect(fixture.tree(fixture.agents).isEmpty, "provider, watchdog, desktop API and cluster agents are gone") + #expect(Set(fixture.launchd.bootedOut) == [LaunchAgent.label, WatchdogAgent.label, Fixture.clusterLabel]) + #expect(fixture.calls.all == ["drain", "cluster stop", "lease released", "revoke token", "forget \(Fixture.pin)", + "link remove"], "unpaired and the cable undone, as for everything") + for gone in [fixture.paths.installDirectory, fixture.paths.configDirectory, fixture.paths.cacheDirectory, + fixture.paths.commandLink] { + #expect(!fixture.exists(gone), "\(gone.path) is deleted") + } + #expect(models.map { fixture.tree($0) } == before, "every model folder, lock and the cluster store stay as they were") + #expect(receipts.allSatisfy { $0 != nil }) + #expect([Fixture.ours + "/refs/main", Fixture.ours + "/snapshots/rev1/.darkbloom-manifest.json", + ".cache/huggingface/darkbloom-cluster-models/org--ours/.darkbloom-manifest.json"] + .map { try? Data(contentsOf: fixture.home.appendingPathComponent($0)) } == receipts, "receipts and refs are untouched") + // A reinstall's discovery: the scanner over the same cache finds the model again. + #expect(ModelScanner.scanAllModels(in: hub, environment: [:]).map(\.id).contains("org/ours-mlx")) + #expect(fixture.exists(fixture.savedModels.appendingPathComponent("models--org--big/snapshots/rev1/.darkbloom-manifest.json"))) + #expect(!report.steps.contains { $0.name.hasPrefix("Delete Model") || $0.name == "Delete Cluster model store" }) + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("keep-models-summary-leader", summary, fixture) + #expect(summary.first == "Darkbloom is removed from this Mac; its models are kept.") + #expect(summary.contains { $0.hasPrefix("Kept: 2 models and the cluster model store, ") && $0.contains(hub.path) }) + #expect(summary.contains("To come back: run `curl -fsSL \(BuildEnvironment.current.coordinatorHTTPURL)/install.sh | bash`, " + + "then `darkbloom start` or `darkbloom cluster`; the models are found automatically.")) + #expect(summary.contains { $0.hasPrefix("Models in the folder you chose are not found automatically") }) + #expect(summary.contains(ProviderUninstall.keychainLine)) + #expect(summary.contains { $0.hasPrefix("Never touched: Models in the folder you chose") && $0.contains(fixture.savedModels.path) }) + } + + @Test("(b) everything: data, models, the app and the command link go; revoke, forget and link remove run once each") + func everythingRemovesDarkbloomData() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let hub = fixture.home.appendingPathComponent(".cache/huggingface/hub") + let plan = fixture.plan(pairing: fixture.pairing) + let report = await fixture.run(.everything, items: plan.items, pairing: fixture.pairing) + + #expect(!report.failed, "\(report.steps)") + for gone in [fixture.paths.installDirectory, fixture.paths.configDirectory, fixture.paths.cacheDirectory, + hub.appendingPathComponent("models--org--ours-mlx"), hub.appendingPathComponent("models--org--partial"), + hub.appendingPathComponent(".artifact-writer-locks"), fixture.paths.clusterModelStore, + fixture.paths.commandLink] { + #expect(!fixture.exists(gone), "\(gone.path) is deleted") + } + #expect(fixture.exists(hub.appendingPathComponent("models--org--other-mlx/snapshots/rev1/model.safetensors")), + "another tool's model in the shared cache stays") + #expect(fixture.exists(fixture.savedModels.appendingPathComponent("models--org--big/snapshots/rev1/.darkbloom-manifest.json")), + "models in the folder the person chose stay") + #expect(fixture.calls.count("revoke token") == 1) + #expect(fixture.calls.count("forget \(Fixture.pin)") == 1) + #expect(fixture.calls.count("link remove") == 1) + #expect(fixture.calls.all.firstIndex(of: "forget \(Fixture.pin)")! < fixture.calls.all.firstIndex(of: "link remove")!, + "the other Mac is told over the cable before the cable's setup is undone") + #expect(report.steps.last?.name == "Delete " + ProviderUninstall.installFolderLabel(fixture.paths), + "the folder with the running app goes last") + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("everything-summary-leader", summary, fixture) + #expect(summary.first == "Darkbloom is removed from this Mac.") + #expect(summary.contains { $0.hasPrefix("Space freed: 250 MB (this disk had 1 GB free, now 1.25 GB") }) + #expect(summary.contains { $0.hasPrefix("Never touched: Models in the folder you chose") && $0.contains(fixture.savedModels.path) }) + #expect(summary.contains(ProviderUninstall.keychainLine)) + #expect(!summary.contains { $0.hasPrefix("To come back") }) + } + + @Test("(c) dry run, both choices: every action and path with sizes, and nothing changes") + func dryRunChangesNothing() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let before = fixture.tree(fixture.root) + let plan = fixture.plan(pairing: fixture.pairing) + let everything = ProviderUninstall.dryRun(plan, mode: .everything) + let keepModels = ProviderUninstall.dryRun(plan, mode: .keepModels) + transcript("screen", ProviderUninstall.screen(plan) + [ProviderUninstall.choicePrompt], fixture) + transcript("dry-run-everything", everything, fixture) + transcript("dry-run-keep-models", keepModels, fixture) + + #expect(fixture.tree(fixture.root) == before) + #expect(fixture.launchd.callCount == 0, "nothing asked launchd") + #expect(fixture.calls.all.isEmpty) + for (lines, mode) in [(everything, ProviderUninstall.Mode.everything), (keepModels, .keepModels)] { + let text = lines.joined(separator: "\n") + for action in ["Stop serving on this Mac", + "Stop this Mac's cluster part and remove its service, as `darkbloom cluster stop`: " + + "\(fixture.agents.path)/\(Fixture.clusterLabel).plist", + "Remove the provider service: \(fixture.agents.path)/\(LaunchAgent.label).plist", + "Remove the watchdog service: \(fixture.agents.path)/\(WatchdogAgent.label).plist", + "Remove the desktop API service: \(fixture.desktopPlist.path)", + "Revoke this Mac's account token, as `darkbloom logout` does (best effort)", + "Forget the pairing with M3 Ultra, 512 GB", "Undo the cable port setup", + "Delete Settings", "Delete Darkbloom folder"] { + #expect(text.contains(action), "\(mode): \(action)") + } + for item in plan.items where item.verdict == .remove { + #expect(text.contains("Delete \(ProviderUninstall.row(item))") == (mode == .everything || item.kind != .model), + "\(mode): \(item.label)") + } + #expect(text.contains("Never touched: Models in the folder you chose")) + } + #expect(keepModels.contains { $0.hasPrefix(" Kept: 2 models and the cluster model store") }) + let screen = ProviderUninstall.screen(plan) + #expect(Array(screen.prefix(6)) == ["Uninstall Darkbloom from this Mac", "", + " 1) Remove everything", + " The app, settings, pairing, logs and all models · frees \(ProviderUninstall.formatBytes(plan.frees(.everything)))", + " 2) Keep models", + " Removes everything else; a reinstall reuses the \(ProviderUninstall.formatBytes(plan.modelBytes)) of models"]) + #expect(ProviderUninstall.choicePrompt == " Choose 1 or 2 (Esc cancels): ") + // Pressing 1 asks once more, naming what can't come back. + let question = ProviderUninstall.everythingQuestion(plan) + transcript("everything-question", [question], fixture) + #expect(question == " Remove everything, including \(ProviderUninstall.formatBytes(plan.modelBytes)) of models? " + + "This can't be undone. [y/N]: ") + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + let json = try encoder.encode(ProviderUninstall.dryRunDocument(plan, modes: ProviderUninstall.Mode.allCases)) + transcript("dry-run-json", [String(decoding: json, as: UTF8.self)], fixture) + let document = try #require(try JSONSerialization.jsonObject(with: json) as? [String: Any]) + #expect(document["schema"] as? String == "darkbloom_uninstall_plan_v1") + #expect((document["modes"] as? [[String: Any]])?.map { $0["mode"] as? String } == ["everything", "keep-models"]) + } + + @Test("sizes count an APFS clone once, and not at all while a clone outside stays") + func clonedModelIsCountedOnce() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let weights = fixture.home.appendingPathComponent("\(Fixture.ours)/snapshots/rev1/model.safetensors") + let storeCopy = fixture.paths.clusterModelStore.appendingPathComponent("org--ours/model.safetensors") + for url in [storeCopy, weights] { try FileManager.default.removeItem(at: url) } + try Data((0..<(4 << 20)).map { UInt8(truncatingIfNeeded: $0 &* 2_654_435_761 >> 13) }).write(to: weights) + try fixture.clone(weights, to: storeCopy) + let items = ProviderUninstall.inventory(fixture.paths) + let model = try #require(items.first { $0.label == "Model org/ours-mlx" }) + let store = try #require(items.first { $0.label == "Cluster model store" }) + #expect(model.bytes >= 4 << 20 && store.bytes >= 4 << 20, "each item shows its own size") + let both = ProviderUninstall.uniqueBytes([model, store]) + #expect(both == model.bytes + store.bytes - (4 << 20), "the clone's 4 MiB are counted once") + let plan = fixture.plan(pairing: nil) + #expect(plan.modelBytes == ProviderUninstall.uniqueBytes(plan.models)) + #expect(plan.frees(.everything) == plan.items.filter { $0.verdict == .remove }.reduce(0) { $0 + $1.bytes } - (4 << 20)) + // A third clone outside Darkbloom's folders keeps those blocks in use: deleting both frees none of them. + try fixture.clone(weights, to: fixture.outside.appendingPathComponent("my-copy.safetensors")) + let again = ProviderUninstall.inventory(fixture.paths).filter { [model.label, store.label].contains($0.label) } + #expect(ProviderUninstall.uniqueBytes(again) == model.bytes + store.bytes - 2 * (4 << 20)) + } + + @Test("(d) a link or a path outside Darkbloom's folders is refused and left as it is") + func outsideTargetsAreRefused() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let elsewhere = fixture.outside.appendingPathComponent("elsewhere/keep.txt") + try fixture.write(elsewhere) + // A link inside Darkbloom's folder: removing the folder removes the link, never what it points to. + try fixture.link(fixture.paths.installDirectory.appendingPathComponent("models"), to: elsewhere.deletingLastPathComponent().path) + // A model folder that is a link to another disk, with Darkbloom's receipt there. + let linkedModel = fixture.outside.appendingPathComponent("linked-model") + try fixture.write(linkedModel.appendingPathComponent("snapshots/rev1/.darkbloom-manifest.json")) + let hubLink = fixture.home.appendingPathComponent(".cache/huggingface/hub/models--org--linked") + try fixture.link(hubLink, to: linkedModel.path) + // Settings moved to another folder and linked back. + let movedSettings = fixture.outside.appendingPathComponent("dotfiles-darkbloom") + try FileManager.default.moveItem(at: fixture.paths.configDirectory, to: movedSettings) + try fixture.link(fixture.paths.configDirectory, to: movedSettings.path) + // A command link that is not the installer's. + try FileManager.default.removeItem(at: fixture.paths.commandLink) + try fixture.link(fixture.paths.commandLink, to: fixture.outside.appendingPathComponent("other-tool").path) + + let items = ProviderUninstall.inventory(fixture.paths) + let refused = Dictionary(uniqueKeysWithValues: items.filter { $0.verdict == .refused }.map { ($0.path, $0.reason ?? "") }) + #expect(refused[hubLink.path]?.contains("outside Darkbloom's folders") == true) + #expect(refused[fixture.paths.configDirectory.path]?.contains("resolves to \(movedSettings.path)") == true) + #expect(refused[fixture.paths.commandLink.path] == "it is not the link Darkbloom's installer made") + + let report = await fixture.run(.everything, items: items) + #expect(fixture.exists(elsewhere), "the file behind the link inside ~/.darkbloom stays") + #expect(fixture.exists(linkedModel.appendingPathComponent("snapshots/rev1/.darkbloom-manifest.json"))) + #expect(fixture.exists(hubLink) && fixture.exists(fixture.paths.configDirectory) && fixture.exists(fixture.paths.commandLink), + "refused links are not removed either") + #expect(fixture.exists(movedSettings.appendingPathComponent("provider.toml"))) + #expect(!fixture.exists(fixture.paths.installDirectory)) + #expect(report.steps.filter { $0.detail?.hasPrefix("not removed: ") == true }.count == 3) + #expect(status(report, "Delete Settings") == .skipped) + // What it refused is still Darkbloom's: the summary does not call it removed, and the command exits 1. + #expect(report.incomplete && !report.failed) + let summary = ProviderUninstall.summary(report, plan: fixture.plan(pairing: nil)) + transcript("everything-summary-settings-link", summary, fixture) + #expect(summary.first == "Darkbloom is not fully removed from this Mac: some of its folders were not removed (see below).") + #expect(summary.contains(" skipped Delete Settings: not removed: it resolves to \(movedSettings.path), outside Darkbloom's folders")) + // A command link the installer did not make is not Darkbloom's: leaving only that leaves nothing of Darkbloom's. + let linkOnly = ProviderUninstall.Report(mode: .everything, steps: report.steps.filter { $0.name.hasPrefix("Delete The ") }, + availableBefore: nil, availableAfter: nil) + #expect(linkOnly.steps.count == 1 && !linkOnly.incomplete) + } + + @Test("blocker: a model folder the person chose inside ~/.darkbloom is kept in both modes, named, and the rest goes") + func chosenModelsInsideDarkbloomFolderAreKept() async throws { + for mode in ProviderUninstall.Mode.allCases { + let base = try Fixture.make() + defer { base.remove() } + // The validator's case: `darkbloom models location ~/.darkbloom/models`, and the store the provider puts beside it. + let chosen = base.paths.installDirectory.appendingPathComponent("models", isDirectory: true) + let model = chosen.appendingPathComponent("models--org--chosen/snapshots/rev1/model.safetensors") + try base.write(model) + try base.write(chosen.appendingPathComponent("models--org--chosen/snapshots/rev1/.darkbloom-manifest.json")) + let store = base.paths.installDirectory.appendingPathComponent("darkbloom-cluster-models/org--chosen/model.safetensors") + try base.clone(model, to: store) + let fixture = base.choosingModels(chosen) + let plan = fixture.plan(pairing: nil) + let screen = ProviderUninstall.screen(plan) + let dryRun = ProviderUninstall.dryRun(plan, mode: mode) + transcript("screen-chosen-inside", screen + [ProviderUninstall.choicePrompt], fixture) + transcript("dry-run-\(mode.rawValue)-chosen-inside", dryRun, fixture) + for lines in [screen, dryRun] { + #expect(lines.contains { $0.contains("Kept: Models in the folder you chose") && $0.contains(chosen.path) }, "\(mode)") + #expect(lines.contains { $0.contains("Kept: Cluster model store beside the folder you chose") }, "\(mode)") + } + #expect(dryRun.contains { $0.contains("Delete Darkbloom folder") && $0.contains("except the models you chose") }, "\(mode)") + let document = ProviderUninstall.dryRunDocument(plan, modes: [mode]).modes[0] + #expect(document.actions.contains { + $0.action.hasSuffix(", except the models you chose") && $0.path == fixture.paths.installDirectory.path + }, "\(mode): the JSON names the exception too") + #expect(document.kept.contains { $0.path == chosen.path }, "\(mode)") + + let report = await fixture.run(mode, items: plan.items, pairing: nil) + #expect(fixture.exists(model) && fixture.exists(store), "\(mode): the chosen folder and the store beside it stay") + for gone in [fixture.paths.appBundleName, "provider.log", "auth_token", "cluster-pairing", "bin"] { + #expect(!fixture.exists(fixture.paths.installDirectory.appendingPathComponent(gone)), "\(mode): \(gone) is deleted") + } + #expect(!fixture.exists(fixture.paths.configDirectory), "\(mode): settings are deleted") + #expect(fixture.deletes.all.last == fixture.paths.installDirectory.appendingPathComponent(fixture.paths.appBundleName).path, + "\(mode): the app is deleted last") + #expect(!report.failed && !report.incomplete, "\(mode): \(report.steps)") + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("\(mode.rawValue)-summary-chosen-inside", summary, fixture) + #expect(summary.contains { $0.hasPrefix("Kept: Models in the folder you chose") && $0.contains(chosen.path) }) + #expect(summary.contains { $0.hasPrefix("Kept: Cluster model store beside the folder you chose") }) + } + } + + @Test("the cluster model store beside a chosen model folder outside Darkbloom's folders is listed and never touched") + func storeBesideAChosenFolderIsListed() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let store = fixture.savedModels.deletingLastPathComponent().appendingPathComponent("darkbloom-cluster-models/org--big/model.safetensors") + try fixture.write(store) + let plan = fixture.plan(pairing: nil) + for mode in ProviderUninstall.Mode.allCases { + #expect(ProviderUninstall.dryRun(plan, mode: mode).contains { + $0.hasPrefix(" Never touched: Cluster model store beside the folder you chose") && $0.contains(store.deletingLastPathComponent().deletingLastPathComponent().path) + }, "\(mode)") + } + _ = await fixture.run(.everything, items: plan.items, pairing: nil) + #expect(fixture.exists(store)) + } + + @Test("B12: beside the other install, the pairing, cable port setup and shared cluster files stay, both ways") + func sharedClusterStateStaysWithTheOtherInstall() async throws { + for (this, other) in [(BuildEnvironment.dev, BuildEnvironment.prod), (.prod, .dev)] { + let fixture = try Fixture.make() + defer { fixture.remove() } + let shared = try installBoth(fixture) + let paths = ProviderUninstallPaths(home: fixture.home, environment: this, + commandLinkDirectory: fixture.paths.commandLink.deletingLastPathComponent()) + let plan = ProviderUninstall.Plan(cli: this.cliName, services: [], items: ProviderUninstall.inventory(paths), + pairing: fixture.pairing) + let otherName = other == .prod ? "the production Darkbloom" : other.appDisplayName + let kept = "Kept: This Mac's pairing, cluster setup and cable port setup" + let screen = ProviderUninstall.screen(plan), dryRun = ProviderUninstall.dryRun(plan, mode: .everything) + transcript("screen-\(this.rawValue)-beside-\(other.rawValue)", screen + [ProviderUninstall.choicePrompt], fixture) + transcript("dry-run-\(this.rawValue)-beside-\(other.rawValue)", dryRun, fixture) + for lines in [screen, dryRun] { + #expect(lines.contains { $0.contains(kept) && $0.contains("\(otherName) on this Mac also uses them") + && $0.contains("Run `\(other.cliName) uninstall` there to remove them") }, "\(this)") + } + #expect(!dryRun.contains { $0.contains("Forget the pairing") || $0.contains(ProviderUninstall.cableStep) }, "\(this)") + let document = ProviderUninstall.dryRunDocument(plan, modes: [.everything]).modes[0] + #expect(document.kept.contains { $0.label.hasPrefix("This Mac's pairing") }, "\(this): the JSON keeps it too") + #expect(!document.actions.contains { $0.action.hasPrefix("Forget the pairing") || $0.action == ProviderUninstall.cableStep }, + "\(this)") + + let report = await fixture.run(.everything, items: plan.items, pairing: fixture.pairing) + #expect(!fixture.calls.all.contains { $0.hasPrefix("forget") || $0 == "link remove" }, "\(this): the shared steps never run") + for file in shared { #expect(fixture.exists(file), "\(this): \(file.path) stays") } + let own = this.installDirectory(home: fixture.home) + #expect(!fixture.exists(own.appendingPathComponent(this.appBundleName)) && !fixture.exists(own.appendingPathComponent("bin")), + "\(this): its own app and command go") + #expect(fixture.exists(other.installDirectory(home: fixture.home).appendingPathComponent(other.appBundleName)), "\(this)") + #expect(!report.failed && !report.incomplete, "\(this): \(report.steps)") + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("\(this.rawValue)-summary-beside-\(other.rawValue)", summary, fixture) + let thisName = this == .prod ? "The production Darkbloom" : this.appDisplayName + #expect(summary.first == "\(thisName) is removed from this Mac.", "\(this)") + #expect(summary.contains { $0.hasPrefix(kept) }, "\(this)") + #expect(!summary.contains { $0.hasPrefix("The other Mac") }, "\(this): the pair still works, through the other install") + #expect(document.kept.count > 0 && ProviderUninstall.dryRunDocument(plan, modes: [.everything]).otherMac == nil, "\(this)") + for step in ["Forget this Mac's pairing", ProviderUninstall.cableStep] { + #expect(summary.contains(" skipped \(step): kept: \(otherName) on this Mac also uses it"), "\(this): \(step)") + } + } + } + + @Test("B11: a cluster service running without its login agent is named in the dry run") + func runningClusterServiceWithoutAgentIsNamed() { + for running in [false, true] { + let plan = ProviderUninstall.Plan(cli: "darkbloom", clusterServiceRunning: running, services: [], items: [], pairing: nil) + #expect(ProviderUninstall.dryRun(plan, mode: .everything)[2] == " 2. Stop this Mac's cluster part and remove its service, " + + "as `darkbloom cluster stop`: " + + (running ? "no login agent, but a cluster service is running on this Mac; this stops it" : "no cluster service on this Mac")) + } + let dev = ProviderUninstallPaths(home: FileManager.default.temporaryDirectory.appendingPathComponent("no-such-home"), environment: .dev) + #expect(ProviderUninstall.installFolderLabel(dev) == "Darkbloom folder: the app and logs", + "the pairing and cluster setup are in ~/.darkbloom, not in ~/.darkbloom-dev") + } + + @Test("B12 step 2: beside the other install, only this install's cluster agent goes; the pair and the other's agent stay") + func stepTwoRemovesOnlyThisInstallsClusterAgent() async throws { + for (this, other) in [(BuildEnvironment.dev, BuildEnvironment.prod), (.prod, .dev)] { + let fixture = try Fixture.make() + defer { fixture.remove() } + _ = try installBoth(fixture) + let own = clusterAgent(this, fixture), theirs = clusterAgent(other, fixture) + for label in [own, theirs] { + try fixture.write(fixture.agents.appendingPathComponent("\(label).plist")) + fixture.launchd.load(label) + } + let paths = ProviderUninstallPaths(home: fixture.home, environment: this, + commandLinkDirectory: fixture.paths.commandLink.deletingLastPathComponent()) + let plan = ProviderUninstall.Plan(cli: this.cliName, services: [], items: ProviderUninstall.inventory(paths), + pairing: fixture.pairing) + let otherName = other == .prod ? "the production Darkbloom" : other.appDisplayName + let ownPlist = fixture.agents.appendingPathComponent("\(own).plist") + let dryRun = ProviderUninstall.dryRun(plan, mode: .everything) + transcript("dry-run-\(this.rawValue)-beside-\(other.rawValue)-step2", dryRun, fixture) + #expect(dryRun.contains(" 2. Remove this install's cluster service: \(ownPlist.path); the pair and \(otherName)'s " + + "cluster service are left as they are"), "\(this)") + #expect(!dryRun.contains { $0.contains(ProviderUninstall.clusterStep) }, "\(this): the pair is not stopped") + let actions = ProviderUninstall.dryRunDocument(plan, modes: [.everything]).modes[0].actions + #expect(actions.contains { $0.action == "Remove this install's cluster service" && $0.path == ownPlist.path }, "\(this)") + #expect(!actions.contains { $0.action == ProviderUninstall.clusterStep }, "\(this)") + + let report = await fixture.run(.everything, items: plan.items, pairing: fixture.pairing) + #expect(!fixture.calls.all.contains("cluster stop"), "\(this): the pair is never stopped") + #expect(fixture.launchd.bootedOut.contains(own) && !fixture.exists(ownPlist), "\(this): its own agent goes") + for kept in [theirs, Fixture.clusterLabel] { + #expect(!fixture.launchd.bootedOut.contains(kept), "\(this): \(kept) is not booted out") + #expect(fixture.exists(fixture.agents.appendingPathComponent("\(kept).plist")), "\(this): \(kept) stays installed") + } + #expect(!report.failed && !report.incomplete, "\(this): \(report.steps)") + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("\(this.rawValue)-summary-beside-\(other.rawValue)-step2", summary, fixture) + #expect(summary.contains(" done Remove this install's cluster service: removed \(own); the pair and \(otherName)'s " + + "cluster service are left as they are"), "\(this)") + #expect(summary.contains { $0.hasPrefix("Kept: This Mac's pairing") && $0.contains("the pair and its cluster service are left as they are") }, + "\(this)") + } + } + + @Test("F3: a models folder that is ~/.darkbloom itself keeps the app, and the summary says Darkbloom is not fully removed") + func modelsFolderThatIsTheAppFolderIsNotCalledRemoved() async throws { + let base = try Fixture.make() + defer { base.remove() } + let install = base.paths.installDirectory + try base.write(install.appendingPathComponent("models--org--chosen/snapshots/rev1/.darkbloom-manifest.json")) + let fixture = base.choosingModels(install) + let plan = fixture.plan(pairing: nil) + let cli = fixture.paths.commandLink.lastPathComponent + let advice = "run `\(install.path)/bin/\(cli) uninstall` again" + let dryRun = ProviderUninstall.dryRun(plan, mode: .everything) + transcript("dry-run-everything-models-in-app-folder", dryRun, fixture) + #expect(dryRun.contains { $0.hasPrefix(" Not deleted: Darkbloom folder") && $0.contains("it is the models folder you chose") }) + let report = await fixture.run(.everything, items: plan.items, pairing: nil) + #expect(fixture.exists(install.appendingPathComponent(fixture.paths.appBundleName)), "the folder you chose stays, app included") + #expect(!dryRun.contains { $0.contains("Not deleted: The `\(cli)` command link") }, "the link is not in the folder") + #expect(!fixture.exists(fixture.paths.commandLink), "the command link, outside the folder, goes") + #expect(report.incomplete && !report.failed, "\(report.steps)") + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("everything-summary-models-in-app-folder", summary, fixture) + #expect(summary.first == "Darkbloom is not fully removed from this Mac: its app folder is your models folder, so it was kept (see below).") + #expect(summary.contains { $0.contains("skipped Delete Darkbloom folder") && $0.contains("not removed: it is the models folder you chose") + && $0.contains(advice) }, "the summary says what to do") + } + + @Test("a disk mounted at a folder is told from one that is not") + func mountPointsAreDetected() throws { + // devfs is mounted at /dev; /usr is on the same volume as /. + #expect(ProviderUninstall.isMountPoint(URL(fileURLWithPath: "/dev"))) + #expect(!ProviderUninstall.isMountPoint(URL(fileURLWithPath: "/usr"))) + let fixture = try Fixture.make() + defer { fixture.remove() } + #expect(!ProviderUninstall.isMountPoint(fixture.paths.cacheDirectory)) + } + + @Test("(d) a model cache that is itself a link, or shared with another install, is kept") + func sharedOrLinkedModelsAreKept() throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + try FileManager.default.createDirectory(at: fixture.home.appendingPathComponent(".darkbloom-staging"), withIntermediateDirectories: true) + let shared = ProviderUninstallPaths(home: fixture.home, environment: .dev, commandLinkDirectory: fixture.paths.commandLink.deletingLastPathComponent()) + let items = ProviderUninstall.inventory(shared) + #expect(items.filter { $0.label.hasPrefix("Model ") || $0.label == "Cluster model store" }.allSatisfy { $0.verdict == .keep }) + #expect(!items.contains { $0.label == "Model download locks" }) + + let hub = fixture.home.appendingPathComponent(".cache/huggingface/hub") + let moved = fixture.outside.appendingPathComponent("volume-hub") + try FileManager.default.moveItem(at: hub, to: moved) + try fixture.link(hub, to: moved.path) + let linked = ProviderUninstall.inventory(fixture.paths) + #expect(linked.first { $0.label == "Models" }?.verdict == .keep) + #expect(!linked.contains { $0.label.hasPrefix("Model ") && $0.verdict == .remove }) + } + + @Test("(e) without a terminal and without a mode, it refuses with one usage line") + func invocationNeedsAModeWithoutATerminal() { + let usage = ProviderUninstall.usage(cli: "darkbloom") + #expect(usage == "Usage: darkbloom uninstall --everything|--keep-models [--yes] [--dry-run [--json]] (no terminal to ask which)") + #expect(ProviderUninstall.invocation(everything: false, keepModels: false, yes: false, dryRun: false, + interactive: false, cli: "darkbloom") == .refuse(usage)) + #expect(ProviderUninstall.invocation(everything: true, keepModels: false, yes: false, dryRun: false, + interactive: false, cli: "darkbloom") == .refuse(usage), "no one to confirm") + #expect(ProviderUninstall.invocation(everything: false, keepModels: false, yes: false, dryRun: false, interactive: true) == .ask) + #expect(ProviderUninstall.invocation(everything: true, keepModels: false, yes: false, dryRun: false, interactive: true) + == .run(.everything, confirm: true)) + #expect(ProviderUninstall.invocation(everything: false, keepModels: true, yes: true, dryRun: false, interactive: false) + == .run(.keepModels, confirm: false)) + #expect(ProviderUninstall.invocation(everything: false, keepModels: false, yes: false, dryRun: true, interactive: false) + == .dryRun([.everything, .keepModels])) + // Run as root (`sudo`), it would read root's home and miss this person's Darkbloom: refused, dry run too. + let root = ProviderUninstall.rootRefusal(cli: "darkbloom") + #expect(root == "Run `darkbloom uninstall` as yourself, not with sudo: it removes your own Darkbloom, " + + "and asks for your password when a step needs it.") + for (everything, keepModels, yes, dryRun) in [(false, false, false, false), (true, false, true, false), + (false, true, true, false), (false, false, false, true)] { + #expect(ProviderUninstall.invocation(everything: everything, keepModels: keepModels, yes: yes, dryRun: dryRun, + interactive: true, userID: 0, cli: "darkbloom") == .refuse(root)) + } + #expect(ProviderUninstall.invocation(everything: true, keepModels: false, yes: true, dryRun: false, interactive: false, + userID: 501) == .run(.everything, confirm: false)) + // After 1 on the screen, one more question; anything but y or yes keeps everything. + for answer in ["y", "yes", " Y "] { #expect(ProviderUninstall.confirmed(answer)) } + for answer in [nil, "", "n", "no", "1"] as [String?] { #expect(!ProviderUninstall.confirmed(answer)) } + // The screen's keys: 1 or 2 choose, Esc cancels, an arrow key's sequence or another key waits. + #expect(ProviderUninstall.key(Array("1".utf8)) == .choose(.everything)) + #expect(ProviderUninstall.key(Array("2".utf8)) == .choose(.keepModels)) + for cancel in [[0x1B], [], Array("q".utf8), [0x03], [0x04]] as [[UInt8]] { #expect(ProviderUninstall.key(cancel) == .cancel) } + for ignored in [[0x1B, 0x5B, 0x41], Array("3".utf8), Array("\n".utf8)] as [[UInt8]] { #expect(ProviderUninstall.key(ignored) == nil) } + } + + @Test("(f) on a paired leader and member, the last line names the other Mac and what to run there") + func pairedMacsEndWithTheOtherMac() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let leader = fixture.pairing + var member = leader + member.role = .member + member.otherMacName = "M4 Max, 128 GB" + var unnamed = leader + unnamed.otherMacName = nil + unnamed.role = nil + let cases: [(ProviderUninstallPairing, String)] = [ + (leader, "The other Mac (M3 Ultra, 512 GB) followed this one: run `darkbloom uninstall` there too, " + + "or `darkbloom cluster` on it to pair it with another Mac."), + (member, "The other Mac (M4 Max, 128 GB) led this pair: run `darkbloom uninstall` there too, " + + "or `darkbloom cluster` on it to pair it with another Mac."), + (unnamed, "The other Mac is paired with this one: run `darkbloom uninstall` there too, " + + "or `darkbloom cluster` on it to pair it with another Mac."), + ] + for mode in ProviderUninstall.Mode.allCases { + let report = ProviderUninstall.Report(mode: mode, steps: [], availableBefore: nil, availableAfter: nil) + for (pairing, line) in cases { + #expect(ProviderUninstall.summary(report, plan: fixture.plan(pairing: pairing)).last == line, "\(mode)") + } + let alone = ProviderUninstall.summary(report, plan: fixture.plan(pairing: nil)) + #expect(!alone.contains { $0.hasPrefix("The other Mac") }) + } + #expect(ProviderUninstallPairing.read(home: fixture.home) == nil, "an unreadable or absent pairing is not a pair") + } + + @Test("(f) the other Mac's name and this Mac's role come from the saved setup, as `darkbloom cluster` shows them") + func pairedRoleComesFromTheSavedSetup() throws { + let home = try NativePairMemberFixture.privateRoot() + defer { try? FileManager.default.removeItem(at: home) } + let store = ClusterSetupStore(paths: .init(paths: try ClusterUserPaths(homeDirectory: home))) + let pin = Fixture.pin + let peers = [ProviderUninstallPairing.Peer(pin: pin, name: "Apple M3 Ultra, 512 GB")] + #expect(ProviderUninstallPairing.describing(peers: peers, latest: peers[0], home: home, local: nil) + == .init(peers: peers, otherMacName: "Apple M3 Ultra, 512 GB", role: nil), "no saved setup: the pairing's name") + for (role, relation) in [("leader", "followed this one"), ("member", "led this pair")] { + _ = try store.updateRecord { + $0.leadership = ClusterOnboardingLeadership(role: role, leaderPin: String(repeating: "a", count: 64), peerPin: pin, + peerName: "Apple M4 Max, 128 GB", since: "2026-11-03T00:00:00Z") + } + let pairing = ProviderUninstallPairing.describing(peers: peers, latest: peers[0], home: home, local: nil) + #expect(pairing.role == ClusterOnboardingRole(rawValue: role)) + #expect(ProviderUninstall.otherMacLine(pairing, cli: "darkbloom") == "The other Mac (Apple M4 Max, 128 GB) \(relation): " + + "run `darkbloom uninstall` there too, or `darkbloom cluster` on it to pair it with another Mac.") + } + _ = try store.updateRecord { $0.leadership?.peerPin = String(repeating: "c", count: 64) } + #expect(ProviderUninstallPairing.describing(peers: peers, latest: peers[0], home: home, local: nil).role == nil, + "a setup saved for another pairing says nothing about this one") + } + + @Test("the account token is revoked once, best effort: an unconfirmed revocation is reported and blocks nothing") + func tokenRevocationIsBestEffort() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let plan = fixture.plan(pairing: fixture.pairing) + let report = await fixture.run(.keepModels, items: plan.items, pairing: fixture.pairing, + operations: fixture.operations(tokenUnconfirmed: true)) + #expect(fixture.calls.count("revoke token") == 1) + #expect(report.steps.first { $0.name == "Revoke this Mac's account token" } + == .init(name: "Revoke this Mac's account token", status: .skipped, + detail: "the coordinator did not confirm it (offline, or the token's issuer is unknown)")) + #expect(!report.failed) + #expect(!fixture.exists(fixture.paths.installDirectory), "the token goes with ~/.darkbloom all the same") + #expect(fixture.calls.count("forget") == 1 && fixture.calls.count("link remove") == 1) + + // A provider that did not stop still holds the token: it is not revoked under it. + let second = try Fixture.make() + defer { second.remove() } + let draining = await second.run(.everything, operations: second.operations(drainFails: true)) + #expect(second.calls.count("revoke token") == 0) + #expect(status(draining, "Revoke this Mac's account token") == .skipped) + } + + @Test("(g) one failing step: the others run, and the summary says which failed and why") + func failedStepIsReportedAndTheRestRun() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let plan = fixture.plan(pairing: fixture.pairing) + let report = await fixture.run(.everything, items: plan.items, pairing: fixture.pairing, + operations: fixture.operations(linkFails: true)) + + #expect(report.failed) + #expect(report.steps.filter { $0.status == .failed }.map(\.name) == ["Undo the cable port setup"]) + #expect(!fixture.exists(fixture.paths.configDirectory) && !fixture.exists(fixture.paths.clusterModelStore), + "deleting settings and models does not need the cable") + // The app, the cable records and an administrator's script are in ~/.darkbloom: it stays, with the command + // link, so `darkbloom uninstall --everything` can run again and undo the cable port setup. + #expect(fixture.exists(fixture.paths.installDirectory.appendingPathComponent("cluster-pairing/pairings.json"))) + #expect(fixture.exists(fixture.paths.commandLink)) + let retry = "kept, so the uninstall can run again and undo the cable port setup (it holds the app and the cable records)" + let kept = report.steps.filter { $0.status == .skipped && $0.detail == retry }.map(\.name) + #expect(kept == ["Delete The `\(fixture.paths.commandLink.lastPathComponent)` command link", + "Delete " + ProviderUninstall.installFolderLabel(fixture.paths)]) + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("everything-summary-link-declined", summary, fixture) + #expect(summary.contains(" failed Undo the cable port setup: the macOS prompt was declined; nothing was changed")) + #expect(summary.contains { $0.hasPrefix(" done Delete Settings: ") }) + + // A cluster service that did not stop: every other service is still removed, and no file is deleted under it. + let second = try Fixture.make() + defer { second.remove() } + let secondPlan = second.plan(pairing: second.pairing) + let stuck = await second.run(.keepModels, items: secondPlan.items, pairing: second.pairing, + operations: second.operations(clusterFails: true)) + #expect(stuck.steps.filter { $0.status == .failed }.map(\.name) == ["Stop this Mac's cluster part and remove its service"]) + #expect(status(stuck, "Remove the provider service") == .done && status(stuck, "Remove the watchdog service") == .done) + #expect(second.calls.count("forget") == 1 && second.calls.count("link remove") == 1) + #expect(stuck.steps.filter { $0.name.hasPrefix("Delete ") }.allSatisfy { + $0.status == .skipped && $0.detail == ProviderUninstall.servicesRunningReason }) + #expect(second.exists(second.paths.installDirectory)) + let stuckSummary = ProviderUninstall.summary(stuck, plan: secondPlan) + transcript("keep-models-summary-cluster-stuck", stuckSummary, second) + #expect(stuckSummary.first == "Darkbloom is not fully removed from this Mac (see the failed step).") + #expect(!stuckSummary.contains { $0.hasPrefix("Space freed") }, "nothing was deleted, so no space is claimed") + + // A provider that did not drain keeps its agents, as `stop --uninstall` leaves them. + let third = try Fixture.make() + defer { third.remove() } + let draining = await third.run(.keepModels, operations: third.operations(drainFails: true)) + #expect(status(draining, "Stop serving on this Mac") == .failed) + #expect(status(draining, "Remove the provider service") == .skipped) + #expect(third.exists(third.agents.appendingPathComponent("\(LaunchAgent.label).plist"))) + #expect(!third.launchd.bootedOut.contains(LaunchAgent.label)) + } + + @Test("every step is idempotent: a second run finds nothing left and fails nothing") + func secondRunFindsNothing() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + _ = await fixture.run(.everything, pairing: fixture.pairing) + let again = await fixture.run(.everything) + #expect(!again.failed, "\(again.steps)") + #expect(again.steps.filter { $0.name.hasPrefix("Remove the ") }.allSatisfy { $0.status == .skipped && $0.detail == "not installed" }) + #expect(!again.steps.contains { $0.name.hasPrefix("Delete ") && $0.status != .skipped }) + #expect(status(again, "Forget this Mac's pairing") == .skipped) + } +}