From 276f6b28e4bfbf471140d404d5b5f14ddd8f7258 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:28:23 -0800 Subject: [PATCH 01/16] test(provider): darkbloom uninstall keeps or removes, inside Darkbloom's folders An end user on provider 0.10.7 ran `darkbloom stop --uninstall`, saw "Provider service uninstalled", and still had the cluster setup, the pairing and the settings; his agent then wiped things by hand to start over. These checks describe the command that replaces that: one `darkbloom uninstall` that either keeps models and settings or removes everything, and never deletes outside Darkbloom's folders. ProviderUninstallTests runs on a fake home in a temporary root: the real provider, watchdog and cluster service agent removals go through a fake launchctl (LaunchctlControl's task-local runner and home), and the drain, `cluster pair --forget` and `cluster link --remove` are recorded stand-ins. - (a) keep: every agent is booted out and its file removed; every other file is unchanged; nothing is unpaired. - (b) everything: settings, caches, Darkbloom's models, the cluster model store, the command link and ~/.darkbloom (last) are gone; forget and link remove run once each, forget first; another tool's model and a chosen model folder stay. - (c) dry run: lists every action and path with sizes; no file and no launchctl call changes. - (d) a model folder linked to another disk, settings linked elsewhere, a foreign command link and a link inside ~/.darkbloom: refused or not followed, and what they point to stays. A model cache that is a link, or shared with another install, is kept. - (e) without a terminal, no mode (or no --yes) refuses with one line. - (f) a paired leader and member end with the right line about the other Mac, in both modes. - (g) a failed step is reported and the safe steps after it still run; a service that did not stop keeps every file; a provider that did not drain keeps its agents. A second run fails nothing. UninstallCommandTests parses `uninstall` and its flags, refuses conflicting flags, and keeps `stop --uninstall` as it is. Red on origin/dev (0f99ddb180): ProviderUninstallTests does not compile ("cannot find type 'ProviderUninstall' in scope"); with it set aside, UninstallCommandTests fails 3 of 3 (unexpectedExtraValues "uninstall", "Unknown option '--keep-data'", stop's help names no uninstall). Co-Authored-By: Claude Opus 5.5 --- .../UninstallCommandTests.swift | 42 ++ .../Service/ProviderUninstallTests.swift | 454 ++++++++++++++++++ 2 files changed, 496 insertions(+) create mode 100644 provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift diff --git a/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift new file mode 100644 index 0000000000..764a15fb2c --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift @@ -0,0 +1,42 @@ +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 the mode flags, --yes, --dry-run, --json and stop's drain options") + func uninstallParses() throws { + for arguments in [["uninstall"], ["uninstall", "--keep-data", "--yes"], ["uninstall", "--everything", "-y"], + ["uninstall", "--everything", "--dry-run", "--json"], ["uninstall", "--dry-run"], + ["uninstall", "--keep-data", "--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 are refused before anything runs") + func conflictingFlagsAreRefused() { + for (arguments, message) in [(["uninstall", "--keep-data", "--everything"], "Choose one of --keep-data and --everything."), + (["uninstall", "--everything", "--json"], "--json goes with --dry-run.")] { + do { + _ = try Darkbloom.parseAsRoot(arguments) + Issue.record("\(arguments) parsed") + } catch { + #expect(Darkbloom.message(for: error).contains(message), "\(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..8ee6f5303b --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -0,0 +1,454 @@ +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]] = [] + var failBootout: Set = [] + + 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": + if failBootout.contains(label) { + return .init(status: 5, stdout: "", stderr: "Boot-out failed: 5: Input/output error\n") + } + 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 ?? "") } } } + 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 clusterLabel = ClusterServiceAgentPlan.labelPrefix + "0123456789ab" + + let root: URL + let home: URL + let outside: URL + let paths: ProviderUninstallPaths + let launchd: FakeLaunchd + let calls = 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", + ".cache/huggingface/hub/models--org--ours/snapshots/rev1/.darkbloom-manifest.json", + ".cache/huggingface/hub/models--org--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/snapshots/rev1/model.safetensors", + ".cache/huggingface/hub/.artifact-writer-locks/models--org--ours", + ".cache/huggingface/darkbloom-cluster-models/org--ours/model.safetensors", + "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)) + } + 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 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) } + + 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) -> 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") }, + 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() + }, + 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) +} + +@Suite("darkbloom uninstall") +struct ProviderUninstallTests { + @Test("(a) keep: every service is removed and every file stays") + func keepRemovesServicesAndKeepsData() async throws { + let fixture = try Fixture.make() + defer { fixture.remove() } + let before = fixture.tree(fixture.root, excluding: "home/Library/LaunchAgents") + let plan = fixture.plan(pairing: fixture.pairing) + let report = await fixture.run(.keepData, 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.tree(fixture.root, excluding: "home/Library/LaunchAgents") == before, "no file was deleted") + #expect(fixture.calls.all == ["drain", "cluster stop", "lease released"], "no unpairing and no cable change") + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("keep-summary-leader", summary, fixture) + #expect(summary.contains("To come back: install Darkbloom again, then run `darkbloom start` or `darkbloom cluster`.")) + #expect(summary.contains(ProviderUninstall.keychainLine)) + } + + @Test("(b) everything: data, models, the app and the command link go; 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"), 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/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("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 Darkbloom folder: the app, logs, pairing and cluster setup", + "the folder with the running app goes last") + let summary = ProviderUninstall.summary(report, plan: plan) + transcript("everything-summary-leader", summary, fixture) + #expect(summary.contains { $0.hasPrefix("Space freed: 250 MB (this disk had 1 GB free, now 1.25 GB") }) + #expect(summary.contains { $0.hasPrefix("Kept: Models in the folder you chose") && $0.contains(fixture.savedModels.path) }) + #expect(summary.contains(ProviderUninstall.keychainLine)) + } + + @Test("(c) dry run: lists every action and path with sizes, and changes nothing") + 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 lines = ProviderUninstall.dryRun(plan, mode: .everything) + let text = lines.joined(separator: "\n") + transcript("screen", ProviderUninstall.screen(plan), fixture) + transcript("dry-run-everything", lines, fixture) + transcript("dry-run-keep-data", ProviderUninstall.dryRun(plan, mode: .keepData), fixture) + + #expect(fixture.tree(fixture.root) == before) + #expect(fixture.launchd.callCount == 0, "nothing asked launchd") + #expect(fixture.calls.all.isEmpty) + for item in plan.items where item.verdict == .remove { + #expect(text.contains("Delete \(ProviderUninstall.row(item))")) + #expect(item.bytes > 0 || item.path == fixture.paths.commandLink.path, "\(item.label) is measured") + } + #expect(plan.items.first { $0.label == "Model org/ours" }.map { $0.bytes >= 16384 } == true, "sizes are measured") + 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)", + "Forget the pairing with M3 Ultra, 512 GB", "Undo the cable port setup"] { + #expect(text.contains(action), "\(action)") + } + #expect(text.contains("Keeps Models in the folder you chose")) + let keep = ProviderUninstall.dryRun(plan, mode: .keepData).joined(separator: "\n") + #expect(!keep.contains("Delete ") && !keep.contains("Forget") && keep.contains("Keeps every file")) + 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]])?.count == 2) + } + + @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("refused: ") == true }.count == 3) + #expect(status(report, "Delete Settings") == .skipped) + } + + @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(ProviderUninstall.invocation(keepData: false, everything: false, yes: false, dryRun: false, + interactive: false, cli: "darkbloom") == .refuse(usage)) + #expect(ProviderUninstall.invocation(keepData: false, everything: true, yes: false, dryRun: false, + interactive: false, cli: "darkbloom") == .refuse(usage), "no one to confirm") + #expect(!usage.contains("\n")) + #expect(ProviderUninstall.invocation(keepData: false, everything: false, yes: false, dryRun: false, interactive: true) == .ask) + #expect(ProviderUninstall.invocation(keepData: false, everything: true, yes: false, dryRun: false, interactive: true) + == .run(.everything, confirm: true)) + #expect(ProviderUninstall.invocation(keepData: true, everything: false, yes: true, dryRun: false, interactive: false) + == .run(.keepData, confirm: false)) + #expect(ProviderUninstall.invocation(keepData: false, everything: false, yes: false, dryRun: true, interactive: false) + == .dryRun([.keepData, .everything])) + } + + @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: [], items: [], 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("(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.installDirectory) && !fixture.exists(fixture.paths.configDirectory), + "deleting files does not need the cable") + 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(.everything, 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("everything-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(.keepData, 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) + } +} From f735f8f7f25413d2aed0c880c2770ae86a0e06e6 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:34:55 -0800 Subject: [PATCH 02/16] feat(provider): darkbloom uninstall, keeping models and settings or removing everything `darkbloom stop --uninstall` printed "Provider service uninstalled" and left the cluster service, the pairing, the cable port setup, the settings, the models and the app on the Mac. An end user (provider 0.10.7, four Macs in two pairs) could not start over without having his agent wipe files by hand. The team's call: "never coming back (remove config & weights); might be coming back (keep the config & weights)". `darkbloom uninstall` does that. In a terminal it shows what each choice removes, with sizes, and asks 1, 2 or 3: 1. Keep models and settings: the drain of `darkbloom stop`, then `darkbloom cluster stop` (with `--local-only` when the other Mac does not answer), then the provider, watchdog and desktop API agents as `stop --uninstall` removes them. Every file stays. The summary ends with how to come back: install again, then `darkbloom start` or `darkbloom cluster`. 2. Remove everything: also `cluster pair --forget` for each pairing (one call each, before the cable is touched, so a leader still tells its member), `cluster link --remove` (the same macOS prompt), and then Darkbloom's folders one step each: settings, encrypted caches, the models Darkbloom downloaded (a receipt or an unfinished download in the default cache), the cluster model store, the `/usr/local/bin` link the installer made, and ~/.darkbloom last, since the app this command runs from is in it. The summary says what was removed and the space freed on the home volume. 3. Cancel. For scripts and agents: `--keep-data` or `--everything` with `--yes`, `--dry-run` (with `--json`), and stop's `--timeout`/`--force`. Without a terminal, no mode (or no `--yes`) prints one usage line and exits 64. Safety. ProviderUninstall.inventory lists every target with its size and a verdict. A target is deleted only when its resolved path is one of Darkbloom's roots or inside one (ProviderUninstallPaths.roots); a link to elsewhere, or a folder with another disk mounted inside, is refused and reported. FileManager removes links inside a folder without following them. A model or cache folder the person chose, a default model cache that is a link, other tools' models, and models another install (~/.darkbloom-dev) shares are kept and listed. Keep mode never reaches a delete. Keychain items are never touched; the summary says so. Each step is idempotent and reported as done, skipped or failed with its reason; a failure stops only what depends on it (a provider that did not drain keeps its agents; a service that did not stop keeps every file). On a paired Mac both modes end with a line about the other Mac, by name and role: run `darkbloom uninstall` there too, or `darkbloom cluster` on it to pair it with another Mac. `stop --uninstall` is unchanged; its help now points to `uninstall`. WatchdogAgent.plistPath follows LaunchctlControl.homeDirectory(), as LaunchAgent and ClusterServiceAgent do, so tests can bind a fake home; production paths are the same. Docs: cli-reference (`darkbloom uninstall`), installation (Uninstall), two-mac-cluster (Uninstall), troubleshooting (Uninstall and start over), and changelog.d/provider-uninstall-keep-or-remove.md. Green: ProviderUninstallTests 9/9 and UninstallCommandTests 3/3; with DARKBLOOM_RELEASE_ENVIRONMENT=prod (as CI), the LaunchAgent removal and lifecycle, watchdog adapter and cluster service agent suites pass too (75 tests). Co-Authored-By: Claude Opus 5.5 --- .../provider-uninstall-keep-or-remove.md | 7 + docs/provider/cli-reference.md | 84 ++++- docs/provider/installation.md | 71 ++-- docs/provider/troubleshooting.md | 21 +- docs/provider/two-mac-cluster.md | 26 +- .../Service/Uninstall/ProviderUninstall.swift | 350 ++++++++++++++++++ .../Uninstall/ProviderUninstallPlan.swift | 251 +++++++++++++ .../ProviderCore/Service/WatchdogAgent.swift | 2 +- .../Sources/darkbloom/Darkbloom.swift | 1 + .../Sources/darkbloom/StopCommand.swift | 2 +- .../Sources/darkbloom/UninstallCommand.swift | 191 ++++++++++ 11 files changed, 969 insertions(+), 37 deletions(-) create mode 100644 changelog.d/provider-uninstall-keep-or-remove.md create mode 100644 provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift create mode 100644 provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift create mode 100644 provider-swift/Sources/darkbloom/UninstallCommand.swift 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..db2160e909 --- /dev/null +++ b/changelog.d/provider-uninstall-keep-or-remove.md @@ -0,0 +1,7 @@ +### Uninstall Darkbloom: keep your data, or remove everything + +- `darkbloom uninstall` takes Darkbloom off a Mac in one step. In a terminal it shows what each choice removes, with sizes, and asks: keep models and settings (you might come back), remove everything (not coming back), or cancel. +- Keeping models and settings stops serving the way `darkbloom stop` does, stops this Mac's part of a two-Mac pair and removes every Darkbloom background service, including the cluster service. Every file stays, with the pairing and the cable port setup; install again and run `darkbloom start` or `darkbloom cluster` to come back. +- Removing everything also forgets the pairing, undoes the cable port setup (macOS asks for your password) and deletes Darkbloom's settings, the models it downloaded, its caches, logs, the app and the `darkbloom` command link, then says what it removed and how much space it freed. +- It never deletes anything outside Darkbloom's folders: models in a folder you chose, and links that point elsewhere, are kept and listed. Keychain keys stay; a new install replaces them. On a paired Mac it ends with what to run on the other Mac. +- For scripts and agents: `--keep-data` or `--everything` 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..7ca7cab651 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: keep models and settings, or remove everything ([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,83 @@ 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 one of two ways. In a terminal with no flags it +shows what each way removes, with sizes, and asks: **1** keep models and +settings, **2** remove everything, **3** cancel. Removing everything also asks +for the word `yes`. + +```bash +darkbloom uninstall # the screen: 1, 2 or 3 +darkbloom uninstall --keep-data --yes # you might come back +darkbloom uninstall --everything --dry-run # every action and path, with sizes; changes nothing +darkbloom uninstall --everything --yes # not coming back +``` + +| Flag | Type | Default | Effect | +|---|---|---|---| +| `--keep-data` | flag | `false` | Stop serving and remove every background service; keep every file | +| `--everything` | flag | `false` | Also forget the pairing, undo the cable port setup and delete Darkbloom's folders | +| `--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 one usage line and exits 64. `--keep-data` and `--everything` together, +or `--json` without `--dry-run`, are refused before anything runs. + +**The steps, in order.** Each is idempotent; the summary lists each one as +`done`, `skipped` or `failed`, with the reason, and the command exits 1 when one +failed. A failed step does not stop the safe steps after it. + +| # | Step | Mode | Through | Skipped when | +|---|---|---|---|---| +| 1 | Stop serving on this Mac | both | the [stop](#darkbloom-stop) drain (`ServiceDrain`) | the provider service was not running | +| 2 | Stop this Mac's cluster part and remove its service | both | `darkbloom cluster stop`; when the other Mac does not answer, `cluster stop --local-only` | no cluster service on this Mac | +| 3–5 | Remove the provider, watchdog and desktop API launch agents | both | what `stop --uninstall` runs (`LaunchAgent.uninstall`, `WatchdogAgent.uninstall`, `DesktopService.uninstall`) | not installed, or serving did not stop in step 1 | +| 6 | Forget the pairing with the other Mac | everything | `darkbloom cluster pair --forget `, once per pairing | this Mac is not paired | +| 7 | Undo the cable port setup | everything | `darkbloom cluster link --remove` (macOS asks for an administrator's password) | nothing to undo | +| 8 | Delete Darkbloom's folders, one step each (table below) | everything | | already gone, refused, or a service did not stop in steps 1–5 | + +**What `--everything` deletes**, from `ProviderUninstallPaths` and +`ProviderUninstall.inventory` in +`provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift`: + +| Item | Path | +|---|---| +| Settings | `~/.config/darkbloom` (`provider.toml`, saved cluster setups) | +| Encrypted prompt caches | `~/Library/Caches/darkbloom` | +| 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` | +| Cluster model store | `~/.cache/huggingface/darkbloom-cluster-models` | +| The command link | `/usr/local/bin/darkbloom`, only while it links to `~/.darkbloom/bin/darkbloom` | +| Darkbloom folder | `~/.darkbloom`: the app, `bin/`, logs, pairing, cluster setup and service state. Last, since the command runs from the app in it | + +What it never deletes: + +- 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; +- models and caches in a folder you chose (`[backend] model_cache_directory`, + `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; +- 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`) and the shell `PATH` line the installer added. + +The summary reports the space freed as the change in the home volume's free +space. On a paired Mac it ends with one line about the other Mac, by name when +known: run `darkbloom uninstall` there too, or `darkbloom cluster` on it to pair +it with another Mac. After `--keep-data`, install again and run `darkbloom start` +or `darkbloom cluster` to come back. + +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..370e9eec08 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,52 @@ each Mac: `darkbloom cluster`; no SSH, no network settings typed). ## Uninstall +One command takes Darkbloom off this Mac. In a terminal, it shows what each +choice removes, with sizes, and asks: + +```bash +darkbloom uninstall +``` + +1. **Keep models and settings (you might come back).** Stops serving (the drain + of `darkbloom stop`), stops this Mac's part of a two-Mac pair and removes + every Darkbloom background service: the provider, its watchdog, the desktop + API and the cluster service. Every file stays, with the pairing and the cable + port setup. To come back, install again, then run `darkbloom start` or + `darkbloom cluster`. +2. **Remove everything (not coming back).** Also forgets this Mac's pairing, + undoes the cable port setup (macOS asks for an administrator's password) and + deletes `~/.darkbloom` (the app, logs, pairing and cluster setup), + `~/.config/darkbloom`, `~/Library/Caches/darkbloom`, the models Darkbloom + downloaded into `~/.cache/huggingface/hub`, the cluster model store and the + `/usr/local/bin/darkbloom` link. Removing everything asks for the word `yes`, + then lists each step as done, skipped or failed, and the space freed. +3. **Cancel.** + +For scripts and agents: + +```bash +darkbloom uninstall --everything --dry-run # every action and path, with sizes; changes nothing (--json too) +darkbloom uninstall --keep-data --yes +darkbloom uninstall --everything --yes +``` + +It never deletes models or caches in a folder you chose, anything that +resolves outside Darkbloom's folders, or Keychain keys (a new install replaces +them). Before removing everything, remove what it leaves, 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..ba07f4f8a2 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,21 @@ 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 **Keep models and settings** or **Remove everything** ([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 --everything`, then install again. Deleting `~/.darkbloom` by hand leaves the cluster service, the pairing on the other Mac and the cable port setup behind | +| `Usage: darkbloom uninstall --keep-data\|--everything [--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 `--keep-data` or `--everything` 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 --everything` again; every step is idempotent | +| `failed Undo the cable port setup: …` | The macOS prompt was declined, or could not show (no screen, over SSH) | Run `darkbloom uninstall --everything` again at the Mac's screen; without a screen, run the printed `sudo sh …` line as an administrator | +| `skipped Delete …: refused: …` | The path is a link, or resolves outside Darkbloom's folders | Nothing outside Darkbloom's folders is deleted; remove it yourself if you don't need it | +| 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..d33d11f22c 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,29 @@ 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 and asks how: + +- **Keep models and settings (you might come back).** 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. The pairing, the cable port setup + and the models stay: install again and run `darkbloom cluster`, and the pair + resumes. +- **Remove everything (not coming back).** It also forgets the pairing, as + `darkbloom cluster pair --forget` (a leader tells the other Mac first, over + the cable), undoes the cable port setup, as `darkbloom cluster link --remove` + (one approval), and deletes Darkbloom's folders, the cluster model store + included. + +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 +either way 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..632041cb48 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -0,0 +1,350 @@ +import Foundation + +/// `darkbloom uninstall`: takes Darkbloom off this Mac in the way the person chooses. Both ways stop serving and +/// remove every background service. `keepData` keeps every file, so installing again resumes; `everything` also +/// unpairs, undoes the cable port setup and deletes Darkbloom's folders (`ProviderUninstallPaths`). 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 keepData = "keep-data" + case everything + } + + /// How a step ended when it did not throw. + public enum Outcome: Equatable, Sendable { + case done(String? = nil) + case skipped(String) + } + + public struct Step: Codable, Sendable, Equatable { + public enum Status: String, Codable, 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 pairing or file changes (releases the drain's lease). + public var servicesHandled: () -> Void + /// `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 = {}, + 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.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 items: [ProviderUninstallItem] + public let availableBefore: Int64? + public let availableAfter: Int64? + public var failed: Bool { steps.contains { $0.status == .failed } } + } + + static let stopServingStep = "Stop serving on this Mac" + static let clusterStep = "Stop this Mac's cluster part and remove its service" + static let cableStep = "Undo the cable port setup" + static let servicesRunningReason = "a Darkbloom service may still be running (see the failed step above)" + + /// 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 + } + } + let serving = await step(stopServingStep, operations.stopServing) + var servicesStopped = await step(clusterStep, operations.stopClusterPart) && 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: "serving did not stop (see the failed step above)")) + continue + } + servicesStopped = await step(service.name, service.remove) && servicesStopped + } + operations.servicesHandled() + guard mode == .everything else { + return Report(mode: mode, steps: steps, items: items, availableBefore: nil, availableAfter: nil) + } + 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: "Forget this Mac's pairing", 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. + _ = await step(cableStep, operations.removeCableSetup) + let before = operations.availableBytes() + for item in items where item.verdict != .keep { + let name = "Delete \(item.label)" + guard item.verdict == .remove else { + steps.append(.init(name: name, status: .skipped, detail: "refused: \(item.reason ?? "outside Darkbloom's folders")")) + continue + } + guard servicesStopped else { + steps.append(.init(name: name, status: .skipped, detail: servicesRunningReason)) + 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") } + try operations.delete(URL(fileURLWithPath: item.path)) + return .done(item.bytes > 0 ? formatBytes(item.bytes) : nil) + } + } + return Report(mode: mode, steps: steps, items: items, availableBefore: before, availableAfter: operations.availableBytes()) + } + + 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 } + } +} + +// MARK: - What the person reads + +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 cluster service's launch agent files (`ClusterServiceAgent.installedLabels`); empty when it is not set up. + public let clusterService: [String] + 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, clusterService: [String] = [], services: [Service], + items: [ProviderUninstallItem], pairing: ProviderUninstallPairing?, elsewhere: [String] = []) { + self.cli = cli; self.clusterService = clusterService; self.services = services; self.items = items + self.pairing = pairing; self.elsewhere = elsewhere + } + + var removed: [ProviderUninstallItem] { items.filter { $0.verdict == .remove } } + var kept: [ProviderUninstallItem] { items.filter { $0.verdict == .keep } } + var refused: [ProviderUninstallItem] { items.filter { $0.verdict == .refused } } + var removedBytes: Int64 { removed.reduce(0) { $0 + $1.bytes } } + } + + public static let keychainLine = "Keychain keys (Secure Enclave and App Attest) stay; a new install replaces them." + + public static func usage(cli: String = BuildEnvironment.current.cliName) -> String { + "Usage: \(cli) uninstall --keep-data|--everything [--yes] [--dry-run [--json]] (no terminal to ask which)" + } + + /// The interactive screen: what each choice does, with sizes. + public static func screen(_ plan: Plan) -> [String] { + var lines = ["Uninstall Darkbloom from this Mac", "", + " 1) Keep models and settings (you might come back)", + " Stops serving and removes Darkbloom's background services.", + " Keeps \(formatBytes(plan.removedBytes + plan.kept.reduce(0) { $0 + $1.bytes })): " + + "models, settings, pairing, logs and the cable port setup.", + " 2) Remove everything (not coming back)", + " Also unpairs this Mac, undoes the cable port setup (macOS asks for your password)", + " and deletes \(formatBytes(plan.removedBytes)):"] + lines += plan.removed.map { " \(row($0))" } + lines += plan.kept.map { " Keeps \($0.label) (\(formatBytes($0.bytes)), \($0.path)): \($0.reason ?? "")" } + lines += plan.refused.map { " Not deleted: \($0.label) (\($0.path)): \($0.reason ?? "")" } + lines += plan.elsewhere.map { " \($0)" } + lines += [" 3) Cancel", ""] + 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`") + action("\(clusterStep), as `\(plan.cli) cluster stop`: " + + (plan.clusterService.isEmpty ? "no cluster service on this Mac" : plan.clusterService.joined(separator: ", "))) + for service in plan.services { + action("Remove the \(service.name): \(service.path ?? "not installed")") + } + if mode == .everything { + if let pairing = plan.pairing { + for peer in 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 { action("Delete \(row(item))") } + lines += plan.refused.map { " Not deleted: \($0.label) (\($0.path)): \($0.reason ?? "")" } + lines.append(" Frees up to \(formatBytes(plan.removedBytes)). \(keychainLine)") + } else { + lines.append(" Keeps every file: \(formatBytes(plan.items.reduce(0) { $0 + $1.bytes })) in \(plan.items.count) places.") + } + lines += plan.kept.map { " Keeps \($0.label) (\(formatBytes($0.bytes)), \($0.path)): \($0.reason ?? "")" } + lines += plan.elsewhere.map { " \($0)" } + return lines + } + + /// The summary after a run: each step with its status, then what stays and, on a paired Mac, the other Mac. + public static func summary(_ report: Report, plan: Plan) -> [String] { + let headline: String + switch (report.mode, report.failed) { + case (.keepData, false): headline = "Darkbloom is stopped on this Mac; nothing was deleted." + case (.keepData, true): headline = "Darkbloom is not fully stopped on this Mac (see the failed step); nothing was deleted." + case (.everything, false): headline = "Darkbloom is removed from this Mac." + case (.everything, true): headline = "Darkbloom is not fully removed from this Mac (see the failed step)." + } + 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 report.mode == .everything { + 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))).") + } + lines += plan.kept.map { "Kept: \($0.label) (\(formatBytes($0.bytes)), \($0.path)): \($0.reason ?? "")" } + } else { + lines.append("Kept every file: models, settings, pairing, logs and the cable port setup " + + "(\(formatBytes(plan.items.reduce(0) { $0 + $1.bytes }))).") + } + lines += plan.elsewhere + lines.append(keychainLine) + if report.mode == .keepData { + lines.append("To come back: install Darkbloom again, then run `\(plan.cli) start` or `\(plan.cli) cluster`.") + } + if let pairing = plan.pairing { lines.append(otherMacLine(pairing, cli: plan.cli)) } + return lines + } + + /// 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 { + item.bytes > 0 ? "\(item.label) \(formatBytes(item.bytes)) \(item.path)" : "\(item.label) \(item.path)" + } + + 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) + } + + public static func invocation(keepData: Bool, everything: Bool, yes: Bool, dryRun: Bool, interactive: Bool, + cli: String = BuildEnvironment.current.cliName) -> Invocation { + let mode: Mode? = keepData ? .keepData : everything ? .everything : 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] + let kept: [ProviderUninstallItem] + let refused: [ProviderUninstallItem] + } + public let schema = "darkbloom_uninstall_plan_v1" + public let modes: [ModePlan] + /// What this command never removes, each with how to remove it. + public let elsewhere: [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)] + 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) } + if mode == .everything { + 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.map { .init(action: "Delete \($0.label)", path: $0.path, bytes: $0.bytes) } + } + // `--keep-data` keeps every item, whatever `--everything` would do with it. + let keptByKeepData = plan.items.map { ProviderUninstallItem(label: $0.label, path: $0.path, bytes: $0.bytes, + verdict: .keep, reason: $0.reason) } + return .init(mode: mode, actions: actions, kept: mode == .everything ? plan.kept : keptByKeepData, + refused: mode == .everything ? plan.refused : []) + } + return .init(modes: modePlans, elsewhere: plan.elsewhere + [keychainLine], + otherMac: plan.pairing.map { otherMacLine($0, cli: plan.cli) }) + } +} 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..726cef37ff --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -0,0 +1,251 @@ +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? + + 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) + 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) + } + + 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 `--everything` deletes it. +public struct ProviderUninstallItem: Codable, Sendable, Equatable { + public enum Verdict: String, Codable, Sendable { + /// Darkbloom's, inside its folders: deleted 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 let label: String + public let path: String + public let bytes: Int64 + public let verdict: Verdict + public let reason: String? +} + +/// 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 } + var pairing = Self(peers: records.pairings.map { Peer(pin: $0.peerPin, name: $0.peerName) }, + otherMacName: latest?.peerName, role: nil) + guard let paths = try? ClusterUserPaths(homeDirectory: home), + let record = try? ClusterSetupStore(paths: .init(paths: paths)).readRecord(), + let leadership = record.leadership, leadership.peerPin == latest?.peerPin else { return pairing } + pairing.otherMacName = 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 = try? ClusterSetupLinkExchange.pairing(store: .default(home: home)), + let claim = record.control?.claim(localID: local.localMemberID, peerID: local.peerMemberID) { + pairing.role = claim.leaderID == local.localMemberID ? .leader : .member + } + return pairing + } +} + +extension ProviderUninstall { + /// 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) { + guard let item = item(label, url, paths: paths, keep: reason) else { return } + items.append(item) + } + // A chosen folder inside Darkbloom's own goes with it, so only one outside them is listed as kept. + func chosen(_ url: URL?) -> URL? { + guard let url else { return nil } + let resolved = ProviderUninstallPaths.canonical(url.path) + return paths.roots.contains { resolved == $0 || resolved.hasPrefix($0 + "/") } ? nil : url + } + add("Settings", paths.configDirectory) + add("Encrypted prompt caches", paths.cacheDirectory) + if let saved = chosen(paths.savedCacheDirectory) { + add("Encrypted prompt caches in the folder you chose", saved, keep: "outside Darkbloom's folders") + } + items += models(paths) + if let saved = chosen(paths.savedModelCache) { + add("Models in the folder you chose", saved, keep: "outside Darkbloom's folders") + } + add("Cluster model store", paths.clusterModelStore, keep: paths.otherInstall.map(sharedReason)) + add("The `\(paths.commandLink.lastPathComponent)` command link", paths.commandLink) + add("Darkbloom folder: the app, logs, pairing and cluster setup", paths.installDirectory) + return items + } + + 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 let item = item("Model \(id)", folder, paths: paths, keep: paths.otherInstall.map(sharedReason)) { items.append(item) } + } + let locks = cache.appendingPathComponent(".artifact-writer-locks", isDirectory: true) + if paths.otherInstall == nil, let item = item("Model download locks", locks, paths: paths) { 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: "it is not the link Darkbloom's installer made") + } + 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") + } + 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) + } + + /// 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, each hard-linked file once; and whether a folder + /// inside it is on another volume. + static func measure(_ url: URL) -> (bytes: Int64, otherVolume: Bool) { + 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 bytes: Int64 = 0, seen = Set<[UInt64]>(), otherVolume = false + while let relative = walker.nextObject() as? String { + var info = stat() + guard lstat(url.appendingPathComponent(relative).path, &info) == 0 else { continue } + if info.st_mode & S_IFMT == S_IFDIR { + 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 } + bytes += Int64(info.st_blocks) * 512 + } + return (bytes, otherVolume) + } +} 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..e9d159bfed --- /dev/null +++ b/provider-swift/Sources/darkbloom/UninstallCommand.swift @@ -0,0 +1,191 @@ +import ArgumentParser +import Darwin +import Foundation +import ProviderCore + +/// `darkbloom uninstall`: keep models and settings (you might come back), or remove everything (not coming back). +/// `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, `cluster pair --forget` and `cluster link --remove`. +struct Uninstall: AsyncParsableCommand { + static let configuration = CommandConfiguration( + abstract: "Take Darkbloom off this Mac: keep models and settings, or remove everything.", + discussion: """ + In a terminal without options, it shows what each choice removes, with sizes, and asks. \ + --keep-data stops serving and removes Darkbloom's background services (the provider, its watchdog, the \ + desktop API and this Mac's cluster service) and keeps every file: install again, then run \ + `\(BuildEnvironment.current.cliName) start` or `\(BuildEnvironment.current.cliName) cluster` to come back. \ + --everything also forgets this Mac's pairing, undoes the cable port setup (macOS asks for an \ + administrator's password) and deletes Darkbloom's folders: settings, the models it downloaded, caches, \ + logs and the app. Models in a folder you chose are kept, and Keychain keys are never deleted. + """) + + @Flag(name: .customLong("keep-data"), help: "Keep models and settings (you might come back).") + var keepData = false + @Flag(help: "Remove everything (not coming back): unpair, undo the cable port setup, delete Darkbloom's folders.") + var everything = 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 !(keepData && everything) else { throw ValidationError("Choose one of --keep-data and --everything.") } + 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(keepData: keepData, everything: everything, yes: yes, + dryRun: dryRun, interactive: interactive) + 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(), chosen == .keepData || Self.confirm(chosen) 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(mode) 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 { 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 }, + 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() }, + 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 } + } + + /// 1, 2 or 3 from the screen; nil to cancel. + static func choose(readInput: () -> String? = { readLine() }) -> ProviderUninstall.Mode? { + print("Choose 1-3: ", terminator: "") + fflush(stdout) + switch readInput()?.trimmingCharacters(in: .whitespacesAndNewlines) { + case "1": return .keepData + case "2": return .everything + default: return nil + } + } + + /// Removing everything takes the word yes; keeping data takes y or yes. + static func confirm(_ mode: ProviderUninstall.Mode, readInput: () -> String? = { readLine() }) -> Bool { + print(mode == .everything ? "Delete these files and unpair this Mac? Type yes to continue: " : "Continue? [y/N]: ", + terminator: "") + fflush(stdout) + let answer = readInput()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" + return mode == .everything ? answer == "yes" : ["y", "yes"].contains(answer) + } +} From da284c748adaa3810c4fdf5cffe811234f56baae Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:36:04 -0800 Subject: [PATCH 03/16] test(provider): the uninstall's line about the other Mac reads the saved setup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Check (f) composed the last line from a role and a name handed in. This one writes the leadership record `darkbloom cluster` keeps (ClusterSetupStore) in a private temporary home, as a leader and then as a member, and expects the role and the other Mac's name to come from it: "The other Mac (Apple M4 Max, 128 GB) followed this one" on the leader, "… led this pair" on the member. With no saved setup, or one saved for another pairing, the pairing's own name is used and no role is claimed. Red against the previous commit: "type 'ProviderUninstallPairing' has no member 'describing'". Co-Authored-By: Claude Opus 5.5 --- .../Service/ProviderUninstallTests.swift | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 8ee6f5303b..d1323b9786 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -396,6 +396,30 @@ struct ProviderUninstallTests { #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("(g) one failing step: the others run, and the summary says which failed and why") func failedStepIsReportedAndTheRestRun() async throws { let fixture = try Fixture.make() From c38652e773d2dc38ab6b7aa40613352abd0c109a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:37:27 -0800 Subject: [PATCH 04/16] refactor(provider): read the other Mac's name and role through one seam ProviderUninstallPairing.read now loads the pairings and hands the peers, the latest pairing and this Mac's link pairing to describing(peers: latest:home:local:), which reads the leadership record and the control claim as before. Behavior is unchanged; the previous commit's check now drives the reader with a leadership record saved as a leader and as a member. Green (DARKBLOOM_RELEASE_ENVIRONMENT=prod, as CI): ProviderUninstallTests 10/10, UninstallCommandTests 3/3, and the LaunchAgent removal and lifecycle, watchdog adapter and cluster service agent suites (76 tests). Co-Authored-By: Claude Opus 5.5 --- .../Uninstall/ProviderUninstallPlan.swift | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index 726cef37ff..be2b402487 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -108,16 +108,21 @@ public struct ProviderUninstallPairing: Sendable, Equatable { 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 } - var pairing = Self(peers: records.pairings.map { Peer(pin: $0.peerPin, name: $0.peerName) }, - otherMacName: latest?.peerName, role: nil) - guard let paths = try? ClusterUserPaths(homeDirectory: home), + 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?.peerPin else { return pairing } - pairing.otherMacName = leadership.peerName.isEmpty ? pairing.otherMacName : leadership.peerName + 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 = try? ClusterSetupLinkExchange.pairing(store: .default(home: home)), - let claim = record.control?.claim(localID: local.localMemberID, peerID: local.peerMemberID) { + if let local, let claim = record.control?.claim(localID: local.localMemberID, peerID: local.peerMemberID) { pairing.role = claim.leaderID == local.localMemberID ? .leader : .member } return pairing From 4448c11215224175864eab27adc97fa4b5d7a9ff Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:43:48 -0800 Subject: [PATCH 05/16] test(provider): a declined cable prompt keeps the app so the uninstall can run again `cluster link --remove` needs an administrator's approval. When it is declined, or cannot be shown (over SSH it prints `sudo sh ~/.darkbloom/cluster-device/link-remove.sh`), the cable port setup stays. Its record, that script and the app that can undo it are all in ~/.darkbloom. So --everything must keep ~/.darkbloom and the command link, saying why, and still delete the settings, caches and models. Check (g) now expects exactly that. Red against the previous commit (DARKBLOOM_RELEASE_ENVIRONMENT=prod): the folder holding the pairing and the command link are deleted, and no step says it was kept (3 issues in (g)). Co-Authored-By: Claude Opus 5.5 --- .../Service/ProviderUninstallTests.swift | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index d1323b9786..8eb112ba9f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -430,8 +430,16 @@ struct ProviderUninstallTests { #expect(report.failed) #expect(report.steps.filter { $0.status == .failed }.map(\.name) == ["Undo the cable port setup"]) - #expect(!fixture.exists(fixture.paths.installDirectory) && !fixture.exists(fixture.paths.configDirectory), - "deleting files does not need the cable") + #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 Darkbloom folder: the app, logs, pairing and cluster setup"]) 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")) From 120975d5cd21bcbbd2c9b7cf0bf174716fcdb970 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:45:34 -0800 Subject: [PATCH 06/16] fix(provider): keep ~/.darkbloom when the cable port setup could not be undone ProviderUninstall.inventory marks the two items whose deletion takes the `darkbloom` command away: the command link and ~/.darkbloom, which holds the app, the cable records `cluster link --remove` reads, and the administrator's link-remove.sh it writes when no prompt can be shown. ProviderUninstall.run skips both when the cable step failed. The reason reads: "kept, so the uninstall can run again and undo the cable port setup". Settings, caches, models and the cluster model store are still deleted. Running it again offers only what is left. The marker is not part of the JSON plan. The docs' step table, the installation section and the troubleshooting row say what happens. Green (DARKBLOOM_RELEASE_ENVIRONMENT=prod): ProviderUninstallTests 10/10, UninstallCommandTests 3/3, and the LaunchAgent removal and lifecycle, watchdog adapter and cluster service agent suites (76 tests). Co-Authored-By: Claude Opus 5.5 --- docs/provider/cli-reference.md | 2 +- docs/provider/installation.md | 4 +++- docs/provider/troubleshooting.md | 2 +- .../Service/Uninstall/ProviderUninstall.swift | 8 +++++++- .../Service/Uninstall/ProviderUninstallPlan.swift | 14 ++++++++++---- 5 files changed, 22 insertions(+), 8 deletions(-) diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 7ca7cab651..7da682e3c5 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1333,7 +1333,7 @@ failed. A failed step does not stop the safe steps after it. | 3–5 | Remove the provider, watchdog and desktop API launch agents | both | what `stop --uninstall` runs (`LaunchAgent.uninstall`, `WatchdogAgent.uninstall`, `DesktopService.uninstall`) | not installed, or serving did not stop in step 1 | | 6 | Forget the pairing with the other Mac | everything | `darkbloom cluster pair --forget `, once per pairing | this Mac is not paired | | 7 | Undo the cable port setup | everything | `darkbloom cluster link --remove` (macOS asks for an administrator's password) | nothing to undo | -| 8 | Delete Darkbloom's folders, one step each (table below) | everything | | already gone, refused, or a service did not stop in steps 1–5 | +| 8 | Delete Darkbloom's folders, one step each (table below) | everything | | already gone, refused, or a service did not stop in steps 1–5. When step 7 did not complete, `~/.darkbloom` and the command link stay, so the command can run again | **What `--everything` deletes**, from `ProviderUninstallPaths` and `ProviderUninstall.inventory` in diff --git a/docs/provider/installation.md b/docs/provider/installation.md index 370e9eec08..65659241e3 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -308,7 +308,9 @@ darkbloom uninstall `~/.config/darkbloom`, `~/Library/Caches/darkbloom`, the models Darkbloom downloaded into `~/.cache/huggingface/hub`, the cluster model store and the `/usr/local/bin/darkbloom` link. Removing everything asks for the word `yes`, - then lists each step as done, skipped or failed, and the space freed. + then lists each step as done, skipped or failed, and the space freed. If the + cable port setup could not be undone, `~/.darkbloom` stays so you can run it + again. 3. **Cancel.** For scripts and agents: diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index ba07f4f8a2..a4ef47c296 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -258,7 +258,7 @@ SSD caching remains enabled by default with no resident retention; use | `Usage: darkbloom uninstall --keep-data\|--everything [--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 `--keep-data` or `--everything` 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 --everything` again; every step is idempotent | -| `failed Undo the cable port setup: …` | The macOS prompt was declined, or could not show (no screen, over SSH) | Run `darkbloom uninstall --everything` again at the Mac's screen; without a screen, run the printed `sudo sh …` line as an administrator | +| `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 --everything` again at the Mac's screen; without a screen, run the printed `sudo sh …` line as an administrator, then run it again | | `skipped Delete …: refused: …` | The path is a link, or resolves outside Darkbloom's folders | Nothing outside Darkbloom's folders is deleted; remove it yourself if you don't need it | | 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 | diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift index 632041cb48..1175bb1feb 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -65,6 +65,8 @@ public enum ProviderUninstall { static let clusterStep = "Stop this Mac's cluster part and remove its service" static let cableStep = "Undo the cable port setup" 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?, @@ -105,7 +107,7 @@ public enum ProviderUninstall { steps.append(.init(name: "Forget this Mac's pairing", 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. - _ = await step(cableStep, operations.removeCableSetup) + let cableUndone = await step(cableStep, operations.removeCableSetup) let before = operations.availableBytes() for item in items where item.verdict != .keep { let name = "Delete \(item.label)" @@ -117,6 +119,10 @@ public enum ProviderUninstall { steps.append(.init(name: name, status: .skipped, detail: servicesRunningReason)) continue } + guard cableUndone || !item.removesTheCommand 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. diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index be2b402487..cf47c2b695 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -85,6 +85,11 @@ public struct ProviderUninstallItem: Codable, Sendable, Equatable { public let bytes: Int64 public let verdict: Verdict public let reason: String? + /// Deleting it takes away the `darkbloom` command: the install folder (the app, and the cable records + /// `cluster link --remove` reads) and the command link. + var removesTheCommand = false + + private enum CodingKeys: String, CodingKey { case label, path, bytes, verdict, reason } } /// The other Mac this one is paired with, from the saved records only (no cable, no key). @@ -134,8 +139,9 @@ extension ProviderUninstall { /// 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) { - guard let item = item(label, url, paths: paths, keep: reason) else { return } + func add(_ label: String, _ url: URL, keep reason: String? = nil, removesTheCommand: Bool = false) { + guard var item = item(label, url, paths: paths, keep: reason) else { return } + item.removesTheCommand = removesTheCommand items.append(item) } // A chosen folder inside Darkbloom's own goes with it, so only one outside them is listed as kept. @@ -154,8 +160,8 @@ extension ProviderUninstall { add("Models in the folder you chose", saved, keep: "outside Darkbloom's folders") } add("Cluster model store", paths.clusterModelStore, keep: paths.otherInstall.map(sharedReason)) - add("The `\(paths.commandLink.lastPathComponent)` command link", paths.commandLink) - add("Darkbloom folder: the app, logs, pairing and cluster setup", paths.installDirectory) + add("The `\(paths.commandLink.lastPathComponent)` command link", paths.commandLink, removesTheCommand: true) + add("Darkbloom folder: the app, logs, pairing and cluster setup", paths.installDirectory, removesTheCommand: true) return items } From 650576130578444cd6b9cdcfd3b2946c13333f28 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:55:29 -0800 Subject: [PATCH 07/16] test(provider): uninstall offers remove everything or keep models The owner's spec (2026-11-04): "darkbloom uninstall should have 2 options, 1 uninstall all items or uninstall but leave models". Both options now stop serving, remove every background service, revoke the account token (best effort), unpair, undo the cable port setup and delete settings, logs, caches, ~/.darkbloom (the app last) and the command link. The only difference: --keep-models keeps the model folders Darkbloom downloaded and the cluster model store, so a reinstall finds them. ProviderUninstallTests: - (a) keep models: everything but the models is removed, including the pairing (forget) and the cable setup (link remove). The model folders, locks and cluster store are unchanged, their receipts and refs are byte-identical, and a fresh `ModelScanner.scanAllModels` over the fake cache finds the model again. The summary says what was kept and where, and gives the install command, then `darkbloom start` or `darkbloom cluster`. - (b) everything: as before; revoke, forget and link remove once each. - (c) dry run for both choices, the approved screen's lines, and the JSON plan. - (e) sizes are clone-aware: a model cloned into the cluster store counts once, and not at all while a clone outside Darkbloom's folders holds the blocks. - (f) the token is revoked once, best effort: an unconfirmed revocation is reported as skipped and blocks nothing. A provider that did not stop keeps its token. - Every earlier safety check stays: outside targets, shared or linked caches, the terminal rule, the other Mac's line, failed steps and idempotency. UninstallCommandTests parses `--everything` and `--keep-models`, and refuses `--keep-data` with the usage. Red against 120975d5cd (DARKBLOOM_RELEASE_ENVIRONMENT=prod, tests sandboxed with no-darkbloom.sb): - ProviderUninstallTests does not compile: 43 errors, such as "type 'ProviderUninstall.Mode' has no member 'keepModels'", "extra argument 'revokeToken'" and "type 'ProviderUninstall' has no member 'uniqueBytes'". - With it set aside, UninstallCommandTests fails 2 of 3 (5 issues): "Unknown option '--keep-models'", `--keep-data --yes` parsed, and the usage does not name `[--everything] [--keep-models]`. Co-Authored-By: Claude Opus 5.5 --- .../UninstallCommandTests.swift | 18 +- .../Service/ProviderUninstallTests.swift | 214 +++++++++++++----- 2 files changed, 171 insertions(+), 61 deletions(-) diff --git a/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift index 764a15fb2c..59dd5fba18 100644 --- a/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/UninstallCommandTests.swift @@ -9,26 +9,30 @@ import Testing struct UninstallCommandTests { private let cli = BuildEnvironment.current.cliName - @Test("uninstall is a command, with the mode flags, --yes, --dry-run, --json and stop's drain options") + @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", "--keep-data", "--yes"], ["uninstall", "--everything", "-y"], - ["uninstall", "--everything", "--dry-run", "--json"], ["uninstall", "--dry-run"], - ["uninstall", "--keep-data", "--yes", "--force", "--timeout", "30"]] { + 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 are refused before anything runs") + @Test("conflicting flags, and the old --keep-data, are refused with the usage before anything runs") func conflictingFlagsAreRefused() { - for (arguments, message) in [(["uninstall", "--keep-data", "--everything"], "Choose one of --keep-data and --everything."), - (["uninstall", "--everything", "--json"], "--json goes with --dry-run.")] { + 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)") } } } diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 8eb112ba9f..4260aed12f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -50,6 +50,7 @@ private final class Calls: @unchecked Sendable { 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 @@ -78,16 +79,21 @@ private struct Fixture { "\(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", - ".cache/huggingface/hub/models--org--ours/snapshots/rev1/.darkbloom-manifest.json", - ".cache/huggingface/hub/models--org--ours/snapshots/rev1/model.safetensors", + "\(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/snapshots/rev1/model.safetensors", - ".cache/huggingface/hub/.artifact-writer-locks/models--org--ours", - ".cache/huggingface/darkbloom-cluster-models/org--ours/model.safetensors", + ".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) @@ -101,6 +107,11 @@ private struct Fixture { 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) @@ -133,7 +144,8 @@ private struct Fixture { items: ProviderUninstall.inventory(paths), pairing: pairing) } - func operations(drainFails: Bool = false, clusterFails: Bool = false, linkFails: Bool = false) -> ProviderUninstall.Operations { + 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( @@ -162,6 +174,11 @@ private struct Fixture { }), ], 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") @@ -200,26 +217,50 @@ private func transcript(_ name: String, _ lines: [String], _ fixture: Fixture) { @Suite("darkbloom uninstall") struct ProviderUninstallTests { - @Test("(a) keep: every service is removed and every file stays") - func keepRemovesServicesAndKeepsData() async throws { + @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 before = fixture.tree(fixture.root, excluding: "home/Library/LaunchAgents") + 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(.keepData, items: plan.items, 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.tree(fixture.root, excluding: "home/Library/LaunchAgents") == before, "no file was deleted") - #expect(fixture.calls.all == ["drain", "cluster stop", "lease released"], "no unpairing and no cable change") + #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-summary-leader", summary, fixture) - #expect(summary.contains("To come back: install Darkbloom again, then run `darkbloom start` or `darkbloom cluster`.")) + 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; forget and link remove run once each") + @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() } @@ -229,15 +270,16 @@ struct ProviderUninstallTests { #expect(!report.failed, "\(report.steps)") for gone in [fixture.paths.installDirectory, fixture.paths.configDirectory, fixture.paths.cacheDirectory, - hub.appendingPathComponent("models--org--ours"), hub.appendingPathComponent("models--org--partial"), + 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/snapshots/rev1/model.safetensors")), + #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")!, @@ -246,50 +288,86 @@ struct ProviderUninstallTests { "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("Kept: Models in the folder you chose") && $0.contains(fixture.savedModels.path) }) + #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: lists every action and path with sizes, and changes nothing") + @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 lines = ProviderUninstall.dryRun(plan, mode: .everything) - let text = lines.joined(separator: "\n") - transcript("screen", ProviderUninstall.screen(plan), fixture) - transcript("dry-run-everything", lines, fixture) - transcript("dry-run-keep-data", ProviderUninstall.dryRun(plan, mode: .keepData), fixture) + 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 item in plan.items where item.verdict == .remove { - #expect(text.contains("Delete \(ProviderUninstall.row(item))")) - #expect(item.bytes > 0 || item.path == fixture.paths.commandLink.path, "\(item.label) is measured") - } - #expect(plan.items.first { $0.label == "Model org/ours" }.map { $0.bytes >= 16384 } == true, "sizes are measured") - 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)", - "Forget the pairing with M3 Ultra, 512 GB", "Undo the cable port setup"] { - #expect(text.contains(action), "\(action)") + 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(text.contains("Keeps Models in the folder you chose")) - let keep = ProviderUninstall.dryRun(plan, mode: .keepData).joined(separator: "\n") - #expect(!keep.contains("Delete ") && !keep.contains("Forget") && keep.contains("Keeps every file")) + #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): ") 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]])?.count == 2) + #expect((document["modes"] as? [[String: Any]])?.map { $0["mode"] as? String } == ["everything", "keep-models"]) + } + + @Test("(e) 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") @@ -352,18 +430,23 @@ struct ProviderUninstallTests { @Test("(e) without a terminal and without a mode, it refuses with one usage line") func invocationNeedsAModeWithoutATerminal() { let usage = ProviderUninstall.usage(cli: "darkbloom") - #expect(ProviderUninstall.invocation(keepData: false, everything: false, yes: false, dryRun: false, + #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(keepData: false, everything: true, yes: false, dryRun: false, + #expect(ProviderUninstall.invocation(everything: true, keepModels: false, yes: false, dryRun: false, interactive: false, cli: "darkbloom") == .refuse(usage), "no one to confirm") - #expect(!usage.contains("\n")) - #expect(ProviderUninstall.invocation(keepData: false, everything: false, yes: false, dryRun: false, interactive: true) == .ask) - #expect(ProviderUninstall.invocation(keepData: false, everything: true, yes: false, dryRun: false, interactive: true) + #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(keepData: true, everything: false, yes: true, dryRun: false, interactive: false) - == .run(.keepData, confirm: false)) - #expect(ProviderUninstall.invocation(keepData: false, everything: false, yes: false, dryRun: true, interactive: false) - == .dryRun([.keepData, .everything])) + #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])) + // 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") @@ -386,7 +469,7 @@ struct ProviderUninstallTests { + "or `darkbloom cluster` on it to pair it with another Mac."), ] for mode in ProviderUninstall.Mode.allCases { - let report = ProviderUninstall.Report(mode: mode, steps: [], items: [], availableBefore: nil, availableAfter: nil) + 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)") } @@ -420,6 +503,29 @@ struct ProviderUninstallTests { "a setup saved for another pairing says nothing about this one") } + @Test("(f) 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() @@ -449,7 +555,7 @@ struct ProviderUninstallTests { let second = try Fixture.make() defer { second.remove() } let secondPlan = second.plan(pairing: second.pairing) - let stuck = await second.run(.everything, items: secondPlan.items, 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) @@ -458,14 +564,14 @@ struct ProviderUninstallTests { $0.status == .skipped && $0.detail == ProviderUninstall.servicesRunningReason }) #expect(second.exists(second.paths.installDirectory)) let stuckSummary = ProviderUninstall.summary(stuck, plan: secondPlan) - transcript("everything-summary-cluster-stuck", stuckSummary, second) + 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(.keepData, operations: third.operations(drainFails: true)) + 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"))) From 798585e97981ac7b994664fc58ee3070dc47c23a Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:01:12 -0800 Subject: [PATCH 08/16] feat(provider): uninstall's two choices, remove everything or keep models MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner's spec (2026-11-04): "darkbloom uninstall should have 2 options, 1 uninstall all items or uninstall but leave models". The approved screen: 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): Steps. Both choices run the same steps: - drain, then `cluster stop`, then remove the agents; - revoke the account token best effort, through `darkbloom logout`'s own `Logout.revokeSavedToken`, once the provider has stopped; it is reported as done or skipped and never fails the uninstall; - forget the pairing, then undo the cable port setup; - delete settings, caches, the command link and ~/.darkbloom, the app last. `--keep-models` keeps every item of kind `model`: the receipted or unfinished model folders in the default cache, their download locks and the cluster model store. Their `refs/` and receipts are untouched, so a reinstall's `ModelScanner` finds them again. Sizes. They are clone-aware. `measure` records each file's `ATTR_CMNEXT_PRIVATESIZE`, `_CLONEID` and `_CLONE_REFCNT`, and `uniqueBytes` counts a pure-clone family's shared blocks once, and only when every clone of them is being deleted. The cluster store's clones of the downloaded models are therefore counted once. The screen reads one key (Esc, q, Ctrl-C or Ctrl-D cancel). Its lines below the choices appear only when this Mac has folders no choice deletes, or parts with their own uninstall. Summary. It says what was removed, what was kept and where, and the space freed. After keep models it gives the way back: the install command, then `darkbloom start` or `darkbloom cluster`, with the models found automatically. A chosen model folder needs `darkbloom models location`. Chosen, external or shared model folders and Keychain keys are listed as never touched. On a paired Mac it ends with the line about the other Mac. Flags and cleanups: - `--everything` | `--keep-models`, with `--yes`, `--dry-run` and `--json`. `--keep-data` is gone, so the parser refuses it with the usage; nothing had shipped. Non-TTY without a mode still prints the one-line usage and exits 64. - `Report.items` is dropped. The `removesTheCommand` marker becomes `ProviderUninstallItem.kind` (`data`, `model`, `command`), which the JSON plan carries. - Docs: the CLI reference (the screen, the steps, a deletion table per choice, a note on prod and dev sharing cluster files), installation, two-mac-cluster and troubleshooting are updated, and the changelog fragment is rewritten for the two choices. Green (DARKBLOOM_RELEASE_ENVIRONMENT=prod, sandboxed with no-darkbloom.sb): ProviderUninstallTests 12/12, UninstallCommandTests 3/3, and the LaunchAgent removal and lifecycle, watchdog adapter and cluster service agent suites, 78 tests in all. No sandbox denial touched ~/.darkbloom. Co-Authored-By: Claude Opus 5.5 --- .../provider-uninstall-keep-or-remove.md | 12 +- docs/provider/cli-reference.md | 116 ++++++---- docs/provider/installation.md | 43 ++-- docs/provider/troubleshooting.md | 12 +- docs/provider/two-mac-cluster.md | 31 +-- .../Service/Uninstall/ProviderUninstall.swift | 212 +++++++++++------- .../Uninstall/ProviderUninstallPlan.swift | 118 ++++++++-- .../Sources/darkbloom/UninstallCommand.swift | 79 ++++--- 8 files changed, 385 insertions(+), 238 deletions(-) diff --git a/changelog.d/provider-uninstall-keep-or-remove.md b/changelog.d/provider-uninstall-keep-or-remove.md index db2160e909..8bd4172606 100644 --- a/changelog.d/provider-uninstall-keep-or-remove.md +++ b/changelog.d/provider-uninstall-keep-or-remove.md @@ -1,7 +1,7 @@ -### Uninstall Darkbloom: keep your data, or remove everything +### Uninstall Darkbloom: remove everything, or keep the models -- `darkbloom uninstall` takes Darkbloom off a Mac in one step. In a terminal it shows what each choice removes, with sizes, and asks: keep models and settings (you might come back), remove everything (not coming back), or cancel. -- Keeping models and settings stops serving the way `darkbloom stop` does, stops this Mac's part of a two-Mac pair and removes every Darkbloom background service, including the cluster service. Every file stays, with the pairing and the cable port setup; install again and run `darkbloom start` or `darkbloom cluster` to come back. -- Removing everything also forgets the pairing, undoes the cable port setup (macOS asks for your password) and deletes Darkbloom's settings, the models it downloaded, its caches, logs, the app and the `darkbloom` command link, then says what it removed and how much space it freed. -- It never deletes anything outside Darkbloom's folders: models in a folder you chose, and links that point elsewhere, are kept and listed. Keychain keys stay; a new install replaces them. On a paired Mac it ends with what to run on the other Mac. -- For scripts and agents: `--keep-data` or `--everything` with `--yes`, and `--dry-run` (with `--json`) to list every action and path without changing anything. `darkbloom stop --uninstall` works as before. +- `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. +- 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 anything outside Darkbloom's folders, such as models in a folder you chose or links that point elsewhere, and never touches Keychain keys; the summary lists what was kept and where. On a paired Mac it ends with what to run on the other Mac. +- 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 7da682e3c5..bbe5eb67d2 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -156,7 +156,7 @@ Subcommands declared by `Darkbloom.configuration.subcommands`: | `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 and keeps every file | | `StopCommand.swift` (`Stop`) | -| `uninstall` | Take Darkbloom off this Mac: keep models and settings, or remove everything ([below](#darkbloom-uninstall)) | | `UninstallCommand.swift` (`Uninstall`) | +| `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`) | @@ -1297,76 +1297,98 @@ handling and launchd's termination allowance. ## `darkbloom uninstall` -Take Darkbloom off this Mac, in one of two ways. In a terminal with no flags it -shows what each way removes, with sizes, and asks: **1** keep models and -settings, **2** remove everything, **3** cancel. Removing everything also asks -for the word `yes`. +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. ```bash -darkbloom uninstall # the screen: 1, 2 or 3 -darkbloom uninstall --keep-data --yes # you might come back -darkbloom uninstall --everything --dry-run # every action and path, with sizes; changes nothing -darkbloom uninstall --everything --yes # not coming back +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 | |---|---|---|---| -| `--keep-data` | flag | `false` | Stop serving and remove every background service; keep every file | -| `--everything` | flag | `false` | Also forget the pairing, undo the cable port setup and delete Darkbloom's folders | +| `--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 one usage line and exits 64. `--keep-data` and `--everything` together, -or `--json` without `--dry-run`, are refused before anything runs. +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.** Each is idempotent; the summary lists each one as -`done`, `skipped` or `failed`, with the reason, and the command exits 1 when one -failed. A failed step does not stop the safe steps after it. +**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. A failed step does not stop the safe steps +after it. -| # | Step | Mode | Through | Skipped when | -|---|---|---|---|---| -| 1 | Stop serving on this Mac | both | the [stop](#darkbloom-stop) drain (`ServiceDrain`) | the provider service was not running | -| 2 | Stop this Mac's cluster part and remove its service | both | `darkbloom cluster stop`; when the other Mac does not answer, `cluster stop --local-only` | no cluster service on this Mac | -| 3–5 | Remove the provider, watchdog and desktop API launch agents | both | what `stop --uninstall` runs (`LaunchAgent.uninstall`, `WatchdogAgent.uninstall`, `DesktopService.uninstall`) | not installed, or serving did not stop in step 1 | -| 6 | Forget the pairing with the other Mac | everything | `darkbloom cluster pair --forget `, once per pairing | this Mac is not paired | -| 7 | Undo the cable port setup | everything | `darkbloom cluster link --remove` (macOS asks for an administrator's password) | nothing to undo | -| 8 | Delete Darkbloom's folders, one step each (table below) | everything | | already gone, refused, or a service did not stop in steps 1–5. When step 7 did not complete, `~/.darkbloom` and the command link stay, so the command can run again | - -**What `--everything` deletes**, from `ProviderUninstallPaths` and -`ProviderUninstall.inventory` in -`provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift`: - -| Item | Path | -|---|---| -| Settings | `~/.config/darkbloom` (`provider.toml`, saved cluster setups) | -| Encrypted prompt caches | `~/Library/Caches/darkbloom` | -| 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` | -| Cluster model store | `~/.cache/huggingface/darkbloom-cluster-models` | -| The command link | `/usr/local/bin/darkbloom`, only while it links to `~/.darkbloom/bin/darkbloom` | -| Darkbloom folder | `~/.darkbloom`: the app, `bin/`, logs, pairing, cluster setup and service state. Last, since the command runs from the app in 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` | no cluster service on this Mac | +| 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 | +| 8 | Undo the cable port setup | `darkbloom cluster link --remove` (macOS asks for an administrator's password) | nothing to undo | +| 9 | Delete Darkbloom's folders, one step each (table below) | | already gone, refused, 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 | deleted | deleted | -What it never deletes: +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; - models and caches in a folder you chose (`[backend] model_cache_directory`, `darkbloom cache set --directory`), the default model cache when it is a link, - and other tools' models; + and other tools' models. After a reinstall, `darkbloom models location ` + uses a chosen model folder again; - the models and the cluster model store while another Darkbloom install - (`~/.darkbloom-dev`, `~/.darkbloom-staging`) shares them; + (`~/.darkbloom-dev`, `~/.darkbloom-staging`) shares them. Cluster pairing and + setup files under `~/.darkbloom` are shared by every install on the Mac, so + removing the production install removes them for a development install too; - 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`) and the shell `PATH` line the installer added. - -The summary reports the space freed as the change in the home volume's free -space. On a paired Mac it ends with one line about the other Mac, by name when -known: run `darkbloom uninstall` there too, or `darkbloom cluster` on it to pair -it with another Mac. After `--keep-data`, install again and run `darkbloom start` -or `darkbloom cluster` to come back. + (`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). 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` diff --git a/docs/provider/installation.md b/docs/provider/installation.md index 65659241e3..d9776a860a 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -289,41 +289,40 @@ each Mac: `darkbloom cluster`; no SSH, no network settings typed). ## Uninstall -One command takes Darkbloom off this Mac. In a terminal, it shows what each -choice removes, with sizes, and asks: +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. **Keep models and settings (you might come back).** Stops serving (the drain - of `darkbloom stop`), stops this Mac's part of a two-Mac pair and removes - every Darkbloom background service: the provider, its watchdog, the desktop - API and the cluster service. Every file stays, with the pairing and the cable - port setup. To come back, install again, then run `darkbloom start` or - `darkbloom cluster`. -2. **Remove everything (not coming back).** Also forgets this Mac's pairing, - undoes the cable port setup (macOS asks for an administrator's password) and - deletes `~/.darkbloom` (the app, logs, pairing and cluster setup), - `~/.config/darkbloom`, `~/Library/Caches/darkbloom`, the models Darkbloom - downloaded into `~/.cache/huggingface/hub`, the cluster model store and the - `/usr/local/bin/darkbloom` link. Removing everything asks for the word `yes`, - then lists each step as done, skipped or failed, and the space freed. If the - cable port setup could not be undone, `~/.darkbloom` stays so you can run it - again. -3. **Cancel.** +1. **Remove everything.** The app, settings, pairing, logs and all models. +2. **Keep models.** Removes everything else; a reinstall reuses the models. + +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 --everything --dry-run # every action and path, with sizes; changes nothing (--json too) -darkbloom uninstall --keep-data --yes +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 ``` -It never deletes models or caches in a folder you chose, anything that +No choice deletes models or caches in a folder you chose, anything that resolves outside Darkbloom's folders, or Keychain keys (a new install replaces -them). Before removing everything, remove what it leaves, if you use it: +them). Remove what it leaves first, if you use it: ```bash sudo darkbloom fan uninstall # fan control: restores macOS automatic control diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index a4ef47c296..ba4b3d7dbe 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -253,12 +253,14 @@ SSD caching remains enabled by default with no resident retention; use | 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 **Keep models and settings** or **Remove everything** ([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 --everything`, then install again. Deleting `~/.darkbloom` by hand leaves the cluster service, the pairing on the other Mac and the cable port setup behind | -| `Usage: darkbloom uninstall --keep-data\|--everything [--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 `--keep-data` or `--everything` with `--yes`; check first with `--dry-run` | +| 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 --everything` again; every step is idempotent | -| `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 --everything` again at the Mac's screen; without a screen, run the printed `sudo sh …` line as an administrator, then run it again | +| `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 | | `skipped Delete …: refused: …` | The path is a link, or resolves outside Darkbloom's folders | Nothing outside Darkbloom's folders is deleted; remove it yourself if you don't need it | | 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 | diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index d33d11f22c..c04835d32d 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -823,24 +823,25 @@ altogether, see [Uninstall](#uninstall). ## Uninstall -`darkbloom uninstall` takes Darkbloom off one Mac of the pair and asks how: - -- **Keep models and settings (you might come back).** 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. The pairing, the cable port setup - and the models stay: install again and run `darkbloom cluster`, and the pair - resumes. -- **Remove everything (not coming back).** It also forgets the pairing, as - `darkbloom cluster pair --forget` (a leader tells the other Mac first, over - the cable), undoes the cable port setup, as `darkbloom cluster link --remove` - (one approval), and deletes Darkbloom's folders, the cluster model store - included. +`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. 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 -either way 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). +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 index 1175bb1feb..3a3974ec03 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -1,13 +1,14 @@ import Foundation -/// `darkbloom uninstall`: takes Darkbloom off this Mac in the way the person chooses. Both ways stop serving and -/// remove every background service. `keepData` keeps every file, so installing again resumes; `everything` also -/// unpairs, undoes the cable port setup and deletes Darkbloom's folders (`ProviderUninstallPaths`). Nothing in the -/// Keychain is touched. Each step is idempotent; a failed one is reported and the safe ones after it still run. +/// `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 keepData = "keep-data" case everything + case keepModels = "keep-models" } /// How a step ended when it did not throw. @@ -31,8 +32,10 @@ public enum ProviderUninstall { 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 pairing or file changes (releases the drain's lease). + /// 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`. @@ -43,19 +46,19 @@ public enum ProviderUninstall { 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.forget = forget; self.removeCableSetup = removeCableSetup - self.delete = delete; self.availableBytes = availableBytes + 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 items: [ProviderUninstallItem] public let availableBefore: Int64? public let availableAfter: Int64? public var failed: Bool { steps.contains { $0.status == .failed } } @@ -63,7 +66,9 @@ public enum ProviderUninstall { 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 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)" @@ -90,14 +95,17 @@ public enum ProviderUninstall { 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: "serving did not stop (see the failed step above)")) + steps.append(.init(name: service.name, status: .skipped, detail: stillServingReason)) continue } servicesStopped = await step(service.name, service.remove) && servicesStopped } operations.servicesHandled() - guard mode == .everything else { - return Report(mode: mode, steps: steps, items: items, availableBefore: nil, availableAfter: nil) + // 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)) } if let pairing { for peer in pairing.peers { @@ -109,7 +117,7 @@ public enum ProviderUninstall { // After the pairing, which tells the other Mac over the cable; this takes the cable's address away. let cableUndone = await step(cableStep, operations.removeCableSetup) let before = operations.availableBytes() - for item in items where item.verdict != .keep { + for item in items where item.verdict != .keep && !(mode == .keepModels && item.kind == .model) { let name = "Delete \(item.label)" guard item.verdict == .remove else { steps.append(.init(name: name, status: .skipped, detail: "refused: \(item.reason ?? "outside Darkbloom's folders")")) @@ -119,7 +127,7 @@ public enum ProviderUninstall { steps.append(.init(name: name, status: .skipped, detail: servicesRunningReason)) continue } - guard cableUndone || !item.removesTheCommand else { + guard cableUndone || item.kind != .command else { steps.append(.init(name: name, status: .skipped, detail: cableRetryReason)) continue } @@ -131,7 +139,7 @@ public enum ProviderUninstall { return .done(item.bytes > 0 ? formatBytes(item.bytes) : nil) } } - return Report(mode: mode, steps: steps, items: items, availableBefore: before, availableAfter: operations.availableBytes()) + return Report(mode: mode, steps: steps, availableBefore: before, availableAfter: operations.availableBytes()) } static func isLink(_ path: String) -> Bool { @@ -164,6 +172,8 @@ extension ProviderUninstall { 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] public let services: [Service] @@ -172,39 +182,46 @@ extension ProviderUninstall { /// 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, clusterService: [String] = [], services: [Service], - items: [ProviderUninstallItem], pairing: ProviderUninstallPairing?, elsewhere: [String] = []) { - self.cli = cli; self.clusterService = clusterService; self.services = services; self.items = items - self.pairing = pairing; self.elsewhere = elsewhere + public init(cli: String = BuildEnvironment.current.cliName, + installCommand: String = "curl -fsSL \(BuildEnvironment.current.coordinatorHTTPURL)/install.sh | bash", + clusterService: [String] = [], services: [Service], items: [ProviderUninstallItem], + pairing: ProviderUninstallPairing?, elsewhere: [String] = []) { + self.cli = cli; self.installCommand = installCommand; self.clusterService = clusterService + self.services = services; self.items = items; self.pairing = pairing; self.elsewhere = elsewhere } - var removed: [ProviderUninstallItem] { items.filter { $0.verdict == .remove } } + /// What `mode` deletes, in order. + func removed(_ mode: Mode) -> [ProviderUninstallItem] { + items.filter { $0.verdict == .remove && !(mode == .keepModels && $0.kind == .model) } + } + 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 } } - var removedBytes: Int64 { removed.reduce(0) { $0 + $1.bytes } } + /// 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) } } - public static let keychainLine = "Keychain keys (Secure Enclave and App Attest) stay; a new install replaces them." + 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): " public static func usage(cli: String = BuildEnvironment.current.cliName) -> String { - "Usage: \(cli) uninstall --keep-data|--everything [--yes] [--dry-run [--json]] (no terminal to ask which)" + "Usage: \(cli) uninstall --everything|--keep-models [--yes] [--dry-run [--json]] (no terminal to ask which)" } - /// The interactive screen: what each choice does, with sizes. + /// 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) Keep models and settings (you might come back)", - " Stops serving and removes Darkbloom's background services.", - " Keeps \(formatBytes(plan.removedBytes + plan.kept.reduce(0) { $0 + $1.bytes })): " - + "models, settings, pairing, logs and the cable port setup.", - " 2) Remove everything (not coming back)", - " Also unpairs this Mac, undoes the cable port setup (macOS asks for your password)", - " and deletes \(formatBytes(plan.removedBytes)):"] - lines += plan.removed.map { " \(row($0))" } - lines += plan.kept.map { " Keeps \($0.label) (\(formatBytes($0.bytes)), \($0.path)): \($0.reason ?? "")" } - lines += plan.refused.map { " Not deleted: \($0.label) (\($0.path)): \($0.reason ?? "")" } - lines += plan.elsewhere.map { " \($0)" } - lines += [" 3) Cancel", ""] + " 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 } @@ -219,55 +236,65 @@ extension ProviderUninstall { for service in plan.services { action("Remove the \(service.name): \(service.path ?? "not installed")") } - if mode == .everything { - if let pairing = plan.pairing { - for peer in 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 { action("Delete \(row(item))") } - lines += plan.refused.map { " Not deleted: \($0.label) (\($0.path)): \($0.reason ?? "")" } - lines.append(" Frees up to \(formatBytes(plan.removedBytes)). \(keychainLine)") - } else { - lines.append(" Keeps every file: \(formatBytes(plan.items.reduce(0) { $0 + $1.bytes })) in \(plan.items.count) places.") - } - lines += plan.kept.map { " Keeps \($0.label) (\(formatBytes($0.bytes)), \($0.path)): \($0.reason ?? "")" } - lines += plan.elsewhere.map { " \($0)" } + action("\(tokenStep), as `\(plan.cli) logout` does (best effort)") + 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, then what stays and, on a paired Mac, the other Mac. + /// 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] { - let headline: String - switch (report.mode, report.failed) { - case (.keepData, false): headline = "Darkbloom is stopped on this Mac; nothing was deleted." - case (.keepData, true): headline = "Darkbloom is not fully stopped on this Mac (see the failed step); nothing was deleted." - case (.everything, false): headline = "Darkbloom is removed from this Mac." - case (.everything, true): headline = "Darkbloom is not fully removed from this Mac (see the failed step)." - } + let headline = report.failed ? "Darkbloom is not fully removed from this Mac (see the failed step)." + : report.mode == .keepModels ? "Darkbloom is removed from this Mac; its models are kept." + : "Darkbloom 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 report.mode == .everything { - 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))).") - } - lines += plan.kept.map { "Kept: \($0.label) (\(formatBytes($0.bytes)), \($0.path)): \($0.reason ?? "")" } - } else { - lines.append("Kept every file: models, settings, pairing, logs and the cable port setup " - + "(\(formatBytes(plan.items.reduce(0) { $0 + $1.bytes }))).") + 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))).") } - lines += plan.elsewhere - lines.append(keychainLine) - if report.mode == .keepData { - lines.append("To come back: install Darkbloom again, then run `\(plan.cli) start` or `\(plan.cli) cluster`.") + 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 { lines.append(otherMacLine(pairing, cli: plan.cli)) } return lines } + static let chosenModelsLabel = "Models in the folder you chose" + static let clusterStoreLabel = "Cluster model store" + + /// 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 outside Darkbloom's, Keychain keys, and what has its own uninstall. + static func neverTouched(_ plan: Plan) -> [String] { + plan.kept.map { "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" @@ -305,9 +332,26 @@ extension ProviderUninstall { case refuse(String) } - public static func invocation(keepData: Bool, everything: Bool, yes: Bool, dryRun: Bool, interactive: Bool, + /// 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, cli: String = BuildEnvironment.current.cliName) -> Invocation { - let mode: Mode? = keepData ? .keepData : everything ? .everything : nil + 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) } @@ -323,13 +367,15 @@ extension ProviderUninstall { 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 this command never removes, each with how to remove it. - public let elsewhere: [String] + /// What no option removes, each with how to remove it. + public let neverTouched: [String] public let otherMac: String? } @@ -339,18 +385,14 @@ extension ProviderUninstall { 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) } - if mode == .everything { - 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.map { .init(action: "Delete \($0.label)", path: $0.path, bytes: $0.bytes) } - } - // `--keep-data` keeps every item, whatever `--everything` would do with it. - let keptByKeepData = plan.items.map { ProviderUninstallItem(label: $0.label, path: $0.path, bytes: $0.bytes, - verdict: .keep, reason: $0.reason) } - return .init(mode: mode, actions: actions, kept: mode == .everything ? plan.kept : keptByKeepData, - refused: mode == .everything ? plan.refused : []) + actions.append(.init(action: tokenStep, path: nil, bytes: nil)) + 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 \($0.label)", 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, elsewhere: plan.elsewhere + [keychainLine], + return .init(modes: modePlans, neverTouched: [keychainLine] + plan.elsewhere, otherMac: plan.pairing.map { otherMacLine($0, cli: plan.cli) }) } } diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index cf47c2b695..3240b9e353 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -69,10 +69,10 @@ public struct ProviderUninstallPaths: Sendable, Equatable { } } -/// One thing `darkbloom uninstall` lists: what it is, its size and whether `--everything` deletes it. +/// 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 by `--everything`. + /// 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 @@ -80,16 +80,35 @@ public struct ProviderUninstallItem: Codable, Sendable, Equatable { 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? - /// Deleting it takes away the `darkbloom` command: the install folder (the app, and the cable records - /// `cluster link --remove` reads) and the command link. - var removesTheCommand = false + public var kind: Kind = .data + /// Its files' blocks, for counting APFS clones once (`ProviderUninstall.uniqueBytes`). + var files: [ProviderUninstallFile] = [] - private enum CodingKeys: String, CodingKey { case label, path, bytes, verdict, reason } + 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). @@ -139,9 +158,9 @@ extension ProviderUninstall { /// 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, removesTheCommand: Bool = false) { + 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.removesTheCommand = removesTheCommand + item.kind = kind items.append(item) } // A chosen folder inside Darkbloom's own goes with it, so only one outside them is listed as kept. @@ -157,11 +176,11 @@ extension ProviderUninstall { } items += models(paths) if let saved = chosen(paths.savedModelCache) { - add("Models in the folder you chose", saved, keep: "outside Darkbloom's folders") + add(chosenModelsLabel, saved, keep: "outside Darkbloom's folders") } - add("Cluster model store", paths.clusterModelStore, keep: paths.otherInstall.map(sharedReason)) - add("The `\(paths.commandLink.lastPathComponent)` command link", paths.commandLink, removesTheCommand: true) - add("Darkbloom folder: the app, logs, pairing and cluster setup", paths.installDirectory, removesTheCommand: true) + add(clusterStoreLabel, paths.clusterModelStore, keep: paths.otherInstall.map(sharedReason), kind: .model) + add("The `\(paths.commandLink.lastPathComponent)` command link", paths.commandLink, kind: .command) + add("Darkbloom folder: the app, logs, pairing and cluster setup", paths.installDirectory, kind: .command) return items } @@ -182,10 +201,16 @@ extension ProviderUninstall { let folder = cache.appendingPathComponent(name, isDirectory: true) guard isDarkbloomModel(folder) else { continue } let id = name.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/") - if let item = item("Model \(id)", folder, paths: paths, keep: paths.otherInstall.map(sharedReason)) { items.append(item) } + 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, let item = item("Model download locks", locks, paths: paths) { items.append(item) } + if paths.otherInstall == nil, var item = item("Model download locks", locks, paths: paths) { + item.kind = .model + items.append(item) + } return items } @@ -223,7 +248,7 @@ extension ProviderUninstall { 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) + 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. @@ -237,26 +262,71 @@ extension ProviderUninstall { return URL(fileURLWithPath: destination, relativeTo: link.deletingLastPathComponent()).standardizedFileURL.path } - /// Allocated bytes under `url`, never following a link, each hard-linked file once; and whether a folder - /// inside it is on another volume. - static func measure(_ url: URL) -> (bytes: Int64, otherVolume: Bool) { + /// 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) -> (bytes: Int64, otherVolume: Bool, files: [ProviderUninstallFile]) { var root = stat() - guard stat(url.path, &root) == 0 else { return (0, false) } + 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) + return (Int64(root.st_blocks) * 512, false, []) } - var bytes: Int64 = 0, seen = Set<[UInt64]>(), otherVolume = 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(url.appendingPathComponent(relative).path, &info) == 0 else { continue } + guard lstat(path, &info) == 0 else { continue } if info.st_mode & S_IFMT == S_IFDIR { 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 } - bytes += Int64(info.st_blocks) * 512 + 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) + } + + /// 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) } - return (bytes, otherVolume) } } diff --git a/provider-swift/Sources/darkbloom/UninstallCommand.swift b/provider-swift/Sources/darkbloom/UninstallCommand.swift index e9d159bfed..fa39b5f78f 100644 --- a/provider-swift/Sources/darkbloom/UninstallCommand.swift +++ b/provider-swift/Sources/darkbloom/UninstallCommand.swift @@ -3,26 +3,24 @@ import Darwin import Foundation import ProviderCore -/// `darkbloom uninstall`: keep models and settings (you might come back), or remove everything (not coming back). -/// `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, `cluster pair --forget` and `cluster link --remove`. +/// `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: keep models and settings, or remove everything.", + abstract: "Take Darkbloom off this Mac: remove everything, or keep the models.", discussion: """ - In a terminal without options, it shows what each choice removes, with sizes, and asks. \ - --keep-data stops serving and removes Darkbloom's background services (the provider, its watchdog, the \ - desktop API and this Mac's cluster service) and keeps every file: install again, then run \ - `\(BuildEnvironment.current.cliName) start` or `\(BuildEnvironment.current.cliName) cluster` to come back. \ - --everything also forgets this Mac's pairing, undoes the cable port setup (macOS asks for an \ - administrator's password) and deletes Darkbloom's folders: settings, the models it downloaded, caches, \ - logs and the app. Models in a folder you chose are kept, and Keychain keys are never deleted. + 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. Models in a folder you chose and Keychain keys are never deleted. """) - @Flag(name: .customLong("keep-data"), help: "Keep models and settings (you might come back).") - var keepData = false - @Flag(help: "Remove everything (not coming back): unpair, undo the cable port setup, delete Darkbloom's folders.") + @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.") @@ -32,14 +30,14 @@ struct Uninstall: AsyncParsableCommand { @OptionGroup var drain: DrainOptions func validate() throws { - guard !(keepData && everything) else { throw ValidationError("Choose one of --keep-data and --everything.") } + 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(keepData: keepData, everything: everything, yes: yes, + let invocation = ProviderUninstall.invocation(everything: everything, keepModels: keepModels, yes: yes, dryRun: dryRun, interactive: interactive) if case .refuse(let line) = invocation { printError(line) @@ -58,16 +56,13 @@ struct Uninstall: AsyncParsableCommand { return case .ask: ProviderUninstall.screen(plan).forEach { print($0) } - guard let chosen = Self.choose(), chosen == .keepData || Self.confirm(chosen) else { - print("Nothing changed.") - return - } + guard let chosen = Self.choose() 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(mode) else { print("Nothing changed."); return } + guard Self.confirm() else { print("Nothing changed."); return } } } let report = await ProviderUninstall.run(mode, items: plan.items, pairing: plan.pairing, @@ -94,7 +89,8 @@ struct Uninstall: AsyncParsableCommand { 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 }, + return .init(installCommand: "curl -fsSL \(BuildEnvironment.current.coordinatorHTTPURL)/install.sh | bash", + clusterService: ClusterServiceAgent.installedLabels().map { ClusterServiceAgent.plistPath(label: $0).path }, 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(), @@ -144,6 +140,12 @@ struct Uninstall: AsyncParsableCommand { }), ], 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) @@ -169,23 +171,32 @@ struct Uninstall: AsyncParsableCommand { func release() { session?.release(); session = nil } } - /// 1, 2 or 3 from the screen; nil to cancel. - static func choose(readInput: () -> String? = { readLine() }) -> ProviderUninstall.Mode? { - print("Choose 1-3: ", terminator: "") + /// Reads keys without Enter until one decides (`ProviderUninstall.key`); nil to cancel. + static func choose() -> ProviderUninstall.Mode? { + print(ProviderUninstall.choicePrompt, terminator: "") fflush(stdout) - switch readInput()?.trimmingCharacters(in: .whitespacesAndNewlines) { - case "1": return .keepData - case "2": return .everything - default: return nil + 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 + } } } - /// Removing everything takes the word yes; keeping data takes y or yes. - static func confirm(_ mode: ProviderUninstall.Mode, readInput: () -> String? = { readLine() }) -> Bool { - print(mode == .everything ? "Delete these files and unpair this Mac? Type yes to continue: " : "Continue? [y/N]: ", - terminator: "") + /// 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) let answer = readInput()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" - return mode == .everything ? answer == "yes" : ["y", "yes"].contains(answer) + return ["y", "yes"].contains(answer) } } From 4a1f605b2ae2edb2fb5f40d0e3be4d0011f25b05 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:14:54 -0800 Subject: [PATCH 09/16] refactor(provider): split the uninstall engine from what it prints ProviderUninstall.swift held the engine (the steps, their order and the rules that skip a step after a failure) and, below it, 240 lines of what the person reads: the screen, the dry run, the summary, choosing a mode and the dry-run JSON. The engine is the part a safety review reads; it now stands alone. - ProviderUninstall.swift keeps the engine: Mode, Outcome, Step, Operations, Report, the step names, run, removeAgent and StepFailure. - ProviderUninstallText.swift (new) holds the screen, the dry run, the summary, choosing a mode and the dry-run JSON. - ProviderUninstall.Plan, with the two item labels the inventory gives, moves to ProviderUninstallPlan.swift, beside the inventory that builds its items and the uniqueBytes that sizes them. Moves only: across the three files the non-blank lines are the same, apart from the new file's import. The docs' file citations (inventory in ProviderUninstallPlan.swift, run in ProviderUninstall.swift) still hold. The 78 sandboxed tests pass, and the screen, both dry runs, the JSON and the four summaries the tests write are byte-identical. Co-Authored-By: Claude Opus 5.5 --- .../Service/Uninstall/ProviderUninstall.swift | 237 ------------------ .../Uninstall/ProviderUninstallPlan.swift | 42 ++++ .../Uninstall/ProviderUninstallText.swift | 196 +++++++++++++++ 3 files changed, 238 insertions(+), 237 deletions(-) create mode 100644 provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift index 3a3974ec03..c59bef1820 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -159,240 +159,3 @@ public enum ProviderUninstall { public init(_ description: String) { self.description = description } } } - -// MARK: - What the person reads - -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] - 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] = [], services: [Service], items: [ProviderUninstallItem], - pairing: ProviderUninstallPairing?, elsewhere: [String] = []) { - self.cli = cli; self.installCommand = installCommand; self.clusterService = clusterService - 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 == .keepModels && $0.kind == .model) } - } - 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 } } - /// 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) } - } - - 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): " - - 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`") - action("\(clusterStep), as `\(plan.cli) cluster stop`: " - + (plan.clusterService.isEmpty ? "no cluster service on this Mac" : plan.clusterService.joined(separator: ", "))) - for service in plan.services { - action("Remove the \(service.name): \(service.path ?? "not installed")") - } - action("\(tokenStep), as `\(plan.cli) logout` does (best effort)") - 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] { - let headline = report.failed ? "Darkbloom is not fully removed from this Mac (see the failed step)." - : report.mode == .keepModels ? "Darkbloom is removed from this Mac; its models are kept." - : "Darkbloom 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 { lines.append(otherMacLine(pairing, cli: plan.cli)) } - return lines - } - - static let chosenModelsLabel = "Models in the folder you chose" - static let clusterStoreLabel = "Cluster model store" - - /// 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 outside Darkbloom's, Keychain keys, and what has its own uninstall. - static func neverTouched(_ plan: Plan) -> [String] { - plan.kept.map { "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 { - item.bytes > 0 ? "\(item.label) \(formatBytes(item.bytes)) \(item.path)" : "\(item.label) \(item.path)" - } - - 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, - cli: String = BuildEnvironment.current.cliName) -> Invocation { - 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)] - 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)) - 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 \($0.label)", 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.pairing.map { otherMacLine($0, cli: plan.cli) }) - } -} diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index 3240b9e353..48d691f327 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -154,6 +154,48 @@ public struct ProviderUninstallPairing: Sendable, Equatable { } 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] + 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] = [], services: [Service], items: [ProviderUninstallItem], + pairing: ProviderUninstallPairing?, elsewhere: [String] = []) { + self.cli = cli; self.installCommand = installCommand; self.clusterService = clusterService + 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 == .keepModels && $0.kind == .model) } + } + 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 } } + /// 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 clusterStoreLabel = "Cluster model store" + /// 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] { 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..10c5609df1 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift @@ -0,0 +1,196 @@ +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): " + + 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`") + action("\(clusterStep), as `\(plan.cli) cluster stop`: " + + (plan.clusterService.isEmpty ? "no cluster service on this Mac" : plan.clusterService.joined(separator: ", "))) + for service in plan.services { + action("Remove the \(service.name): \(service.path ?? "not installed")") + } + action("\(tokenStep), as `\(plan.cli) logout` does (best effort)") + 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] { + let headline = report.failed ? "Darkbloom is not fully removed from this Mac (see the failed step)." + : report.mode == .keepModels ? "Darkbloom is removed from this Mac; its models are kept." + : "Darkbloom 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 { lines.append(otherMacLine(pairing, cli: plan.cli)) } + return lines + } + + /// 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 outside Darkbloom's, Keychain keys, and what has its own uninstall. + static func neverTouched(_ plan: Plan) -> [String] { + plan.kept.map { "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 { + item.bytes > 0 ? "\(item.label) \(formatBytes(item.bytes)) \(item.path)" : "\(item.label) \(item.path)" + } + + 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, + cli: String = BuildEnvironment.current.cliName) -> Invocation { + 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)] + 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)) + 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 \($0.label)", 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.pairing.map { otherMacLine($0, cli: plan.cli) }) + } +} From 6a6a36cba7595cfb4e1cb408d747bc8d72486a32 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:16:39 -0800 Subject: [PATCH 10/16] refactor(provider): state keep-models' one difference once, drop unused pieces - ProviderUninstall.Mode.keeps(_:) is the only difference between the two choices: keep-models keeps every .model item. run's deletion loop and Plan.removed(_:) each wrote it out; changing one alone would have made the dry run list a deletion the run skips, or the reverse. - Step and Step.Status drop Codable. Nothing encodes a step or a report; only the dry run has JSON. - Uninstall.plan() no longer passes Plan an installCommand. It was a copy of the default that the tests check, so the CLI now prints the checked one. - ProviderUninstallTests: FakeLaunchd.failBootout, which no test ever set, is gone. The clone-size and token tests drop the (e) and (f) they borrowed from the checklist letters in 276f6b28e4, where (e) is the no-terminal rule and (f) the line about the other Mac. Every #expect and #require stays (112 before and after). No behavior or text change: the 78 sandboxed tests pass, and the screen, both dry runs, the JSON and the four summaries the tests write are byte-identical to 798585e979's. Co-Authored-By: Claude Opus 5.5 --- .../Service/Uninstall/ProviderUninstall.swift | 9 ++++++--- .../Service/Uninstall/ProviderUninstallPlan.swift | 2 +- provider-swift/Sources/darkbloom/UninstallCommand.swift | 3 +-- .../Service/ProviderUninstallTests.swift | 8 ++------ 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift index c59bef1820..f51f5e30fc 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -9,6 +9,9 @@ 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. @@ -17,8 +20,8 @@ public enum ProviderUninstall { case skipped(String) } - public struct Step: Codable, Sendable, Equatable { - public enum Status: String, Codable, Sendable { case done, skipped, failed } + 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? @@ -117,7 +120,7 @@ public enum ProviderUninstall { // After the pairing, which tells the other Mac over the cable; this takes the cable's address away. let cableUndone = await step(cableStep, operations.removeCableSetup) let before = operations.availableBytes() - for item in items where item.verdict != .keep && !(mode == .keepModels && item.kind == .model) { + 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: "refused: \(item.reason ?? "outside Darkbloom's folders")")) diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index 48d691f327..637f9112b8 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -183,7 +183,7 @@ extension ProviderUninstall { /// What `mode` deletes, in order. func removed(_ mode: Mode) -> [ProviderUninstallItem] { - items.filter { $0.verdict == .remove && !(mode == .keepModels && $0.kind == .model) } + 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 } } diff --git a/provider-swift/Sources/darkbloom/UninstallCommand.swift b/provider-swift/Sources/darkbloom/UninstallCommand.swift index fa39b5f78f..d41940226a 100644 --- a/provider-swift/Sources/darkbloom/UninstallCommand.swift +++ b/provider-swift/Sources/darkbloom/UninstallCommand.swift @@ -89,8 +89,7 @@ struct Uninstall: AsyncParsableCommand { elsewhere.append("Darkbloom Sandbox stays (\(sandbox.root.path)); to remove it, run `\(cli) sandbox uninstall` " + "before removing everything.") } - return .init(installCommand: "curl -fsSL \(BuildEnvironment.current.coordinatorHTTPURL)/install.sh | bash", - clusterService: ClusterServiceAgent.installedLabels().map { ClusterServiceAgent.plistPath(label: $0).path }, + return .init(clusterService: ClusterServiceAgent.installedLabels().map { ClusterServiceAgent.plistPath(label: $0).path }, 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(), diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 4260aed12f..2b81c35d5d 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -10,7 +10,6 @@ private final class FakeLaunchd: @unchecked Sendable { private let lock = NSLock() private var loaded: Set private var calls: [[String]] = [] - var failBootout: Set = [] init(loaded: Set) { self.loaded = loaded } @@ -23,9 +22,6 @@ private final class FakeLaunchd: @unchecked Sendable { 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": - if failBootout.contains(label) { - return .init(status: 5, stdout: "", stderr: "Boot-out failed: 5: Input/output error\n") - } loaded.remove(label) return .init(status: 0, stdout: "", stderr: "") case "disable", "enable": @@ -346,7 +342,7 @@ struct ProviderUninstallTests { #expect((document["modes"] as? [[String: Any]])?.map { $0["mode"] as? String } == ["everything", "keep-models"]) } - @Test("(e) sizes count an APFS clone once, and not at all while a clone outside stays") + @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() } @@ -503,7 +499,7 @@ struct ProviderUninstallTests { "a setup saved for another pairing says nothing about this one") } - @Test("(f) the account token is revoked once, best effort: an unconfirmed revocation is reported and blocks nothing") + @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() } From 007b20051c4ff26efeec4199fba1ce62540be066 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:31:45 -0800 Subject: [PATCH 11/16] test(provider): uninstall keeps a chosen models folder, refuses root, asks after 1 The validator's findings on #1772, as tests: - A models folder the person chose inside ~/.darkbloom (`models location ~/.darkbloom/models`) stays in both modes, with the cluster store beside it; the screen, both dry runs and the summary name them as kept, the rest of the folder goes and the app is deleted last. - Run as root (a user-id seam), every form of the command is refused, dry run included. - A folder it refused reads "not removed", the headline says Darkbloom is not fully removed, and the report is incomplete. - After 1 on the screen, one more question names the models' size; only y or yes goes on. - A disk mounted at a folder is told from one that is not. - The cluster store beside a chosen folder outside Darkbloom's is listed. Red at 6a6a36cba7: the suite does not compile (no `incomplete`, `rootRefusal`, `userID:`, `confirmed`, `everythingQuestion`, `isMountPoint`). The validator's cases run against the same sources (scratch, not committed): C and its Remove-everything variant delete the chosen model, the headline still says removed, the store beside a chosen folder is not listed, and a disk mounted at ~/Library/Caches/darkbloom is emptied before EBUSY. Co-Authored-By: Claude Opus 5.5 --- .../Service/ProviderUninstallTests.swift | 106 +++++++++++++++++- 1 file changed, 105 insertions(+), 1 deletion(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 2b81c35d5d..201b9a1a9a 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -55,6 +55,8 @@ private struct Fixture { 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") } @@ -126,6 +128,13 @@ private struct Fixture { 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) } @@ -181,6 +190,10 @@ private struct Fixture { 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 @@ -333,6 +346,11 @@ struct ProviderUninstallTests { " 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)) @@ -400,8 +418,80 @@ struct ProviderUninstallTests { "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("refused: ") == true }.count == 3) + #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")) + } + + @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 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("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") @@ -438,6 +528,20 @@ struct ProviderUninstallTests { == .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)) From 1821a01b696a5d97ff6630b41a84850b08d5e0d7 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:41:26 -0800 Subject: [PATCH 12/16] fix(provider): uninstall never deletes a chosen models folder, refuses root The validator's findings on #1772: - A models folder the person chose is never deleted, in either mode. With `models location ~/.darkbloom/models`, the folder and the cluster store beside it stay, with the folders that lead to them; the rest of ~/.darkbloom goes, the app last. The screen, the dry run and the summary list them as "Kept:" (outside Darkbloom's folders, "Never touched:"), and "frees" no longer counts them. - Run as root, every form of the command, dry run included, refuses with "Run `darkbloom uninstall` as yourself, not with sudo: ..." and exits 64. - A folder it refused reads "not removed: ", the first line says Darkbloom is not fully removed, and the command exits 1. A command link the installer did not make is not Darkbloom's, so it alone does not count. - After 1 on the screen it asks once: "Remove everything, including of models? This can't be undone. [y/N]". Keep models and `--everything --yes` ask nothing more. - A folder that is another disk's mount point is refused ("another disk is mounted here"), as one holding a mount already was. - The cluster model store beside a chosen models folder is listed. The CLI reference, the installation, two-Mac and troubleshooting uninstall sections and the changelog fragment say so. `Cluster.Stop.parse([])` is unchanged; #1774 follows up on it. Co-Authored-By: Claude Opus 5.5 --- .../provider-uninstall-keep-or-remove.md | 4 +- docs/provider/cli-reference.md | 47 +++++++++--- docs/provider/installation.md | 14 +++- docs/provider/troubleshooting.md | 4 +- docs/provider/two-mac-cluster.md | 4 +- .../Service/Uninstall/ProviderUninstall.swift | 32 +++++++- .../Uninstall/ProviderUninstallPlan.swift | 74 +++++++++++++++---- .../Uninstall/ProviderUninstallText.swift | 38 ++++++++-- .../Sources/darkbloom/UninstallCommand.swift | 16 ++-- .../Service/ProviderUninstallTests.swift | 9 +++ 10 files changed, 195 insertions(+), 47 deletions(-) diff --git a/changelog.d/provider-uninstall-keep-or-remove.md b/changelog.d/provider-uninstall-keep-or-remove.md index 8bd4172606..6241880f00 100644 --- a/changelog.d/provider-uninstall-keep-or-remove.md +++ b/changelog.d/provider-uninstall-keep-or-remove.md @@ -1,7 +1,7 @@ ### 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. +- `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 anything outside Darkbloom's folders, such as models in a folder you chose or links that point elsewhere, and never touches Keychain keys; the summary lists what was kept and where. On a paired Mac it ends with what to run on the other Mac. +- 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. - 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 bbe5eb67d2..3ff76a2d81 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1317,6 +1317,21 @@ 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 @@ -1340,8 +1355,8 @@ 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. A failed step does not stop the safe steps -after it. +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 | |---|---|---|---| @@ -1351,7 +1366,7 @@ after it. | 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 | | 8 | Undo the cable port setup | `darkbloom cluster link --remove` (macOS asks for an administrator's password) | nothing to undo | -| 9 | Delete Darkbloom's folders, one step each (table below) | | already gone, refused, 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 | +| 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`: @@ -1363,17 +1378,25 @@ in `provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan. | 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 | 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; -- models and caches in a folder you chose (`[backend] model_cache_directory`, - `darkbloom cache set --directory`), the default model cache when it is a link, - and other tools' models. After a reinstall, `darkbloom models location ` - uses a chosen model folder again; + 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; +- 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. Cluster pairing and setup files under `~/.darkbloom` are shared by every install on the Mac, so @@ -1384,7 +1407,11 @@ What no choice deletes (the summary lists them): 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). After **Keep models** it ends with +(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 diff --git a/docs/provider/installation.md b/docs/provider/installation.md index d9776a860a..1033deed20 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -296,9 +296,13 @@ with this Mac's sizes and reads one key (Esc cancels): darkbloom uninstall ``` -1. **Remove everything.** The app, settings, pairing, logs and all models. +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 @@ -320,9 +324,11 @@ darkbloom uninstall --keep-models --yes darkbloom uninstall --everything --yes ``` -No choice deletes models or caches in a folder you chose, anything that -resolves outside Darkbloom's folders, or Keychain keys (a new install replaces -them). Remove what it leaves first, if you use it: +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). Remove what it leaves first, if you +use it: ```bash sudo darkbloom fan uninstall # fan control: restores macOS automatic control diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index ba4b3d7dbe..464f00e8cb 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -261,7 +261,9 @@ SSD caching remains enabled by default with no resident retention; use | `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 | -| `skipped Delete …: refused: …` | The path is a link, or resolves outside Darkbloom's folders | Nothing outside Darkbloom's folders is deleted; remove it yourself if you don't need it | +| `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 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 | | 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). diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index c04835d32d..b0435406c9 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -835,7 +835,9 @@ altogether, see [Uninstall](#uninstall). **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. +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`. 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 diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift index f51f5e30fc..b12ac86e4c 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -65,6 +65,14 @@ public enum ProviderUninstall { 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" @@ -123,7 +131,7 @@ public enum ProviderUninstall { 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: "refused: \(item.reason ?? "outside Darkbloom's folders")")) + steps.append(.init(name: name, status: .skipped, detail: notRemoved(item.reason ?? "outside Darkbloom's folders"))) continue } guard servicesStopped else { @@ -138,13 +146,33 @@ public enum ProviderUninstall { // 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") } - try operations.delete(URL(fileURLWithPath: item.path)) + 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)" } + static func isLink(_ path: String) -> Bool { (try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil } diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index 637f9112b8..aaf467f7f1 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -97,6 +97,10 @@ public struct ProviderUninstallItem: Codable, Sendable, Equatable { 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] = [] + /// 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 } } @@ -194,7 +198,11 @@ extension ProviderUninstall { } static let chosenModelsLabel = "Models in the folder you chose" + 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 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. @@ -205,25 +213,48 @@ extension ProviderUninstall { item.kind = kind items.append(item) } - // A chosen folder inside Darkbloom's own goes with it, so only one outside them is listed as kept. - func chosen(_ url: URL?) -> URL? { - guard let url else { return nil } - let resolved = ProviderUninstallPaths.canonical(url.path) - return paths.roots.contains { resolved == $0 || resolved.hasPrefix($0 + "/") } ? nil : url + 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: [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) } add("Settings", paths.configDirectory) add("Encrypted prompt caches", paths.cacheDirectory) - if let saved = chosen(paths.savedCacheDirectory) { - add("Encrypted prompt caches in the folder you chose", saved, keep: "outside Darkbloom's folders") - } items += models(paths) - if let saved = chosen(paths.savedModelCache) { - add(chosenModelsLabel, saved, keep: "outside Darkbloom's folders") - } add(clusterStoreLabel, paths.clusterModelStore, keep: paths.otherInstall.map(sharedReason), kind: .model) add("The `\(paths.commandLink.lastPathComponent)` command link", paths.commandLink, kind: .command) add("Darkbloom folder: the app, logs, pairing and cluster setup", paths.installDirectory, kind: .command) - return items + return items.compactMap { around($0, protected) } + } + + /// `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: [String]) -> ProviderUninstallItem? { + guard item.verdict == .remove, !protected.isEmpty else { return item } + let resolved = ProviderUninstallPaths.canonical(item.path) + if protected.contains(where: { resolved == $0 || resolved.hasPrefix($0 + "/") }) { return nil } + let inside = protected.filter { $0.hasPrefix(resolved + "/") } + guard !inside.isEmpty else { return item } + let measured = measure(URL(fileURLWithPath: resolved), excluding: inside) + 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 + return kept } private static func sharedReason(_ other: URL) -> String { "\(other.lastPathComponent) on this Mac uses it too" } @@ -276,8 +307,7 @@ extension ProviderUninstall { 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: "it is not the link Darkbloom's installer made") + 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) } @@ -285,6 +315,10 @@ extension ProviderUninstall { 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, @@ -306,7 +340,7 @@ extension ProviderUninstall { /// 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) -> (bytes: Int64, otherVolume: Bool, files: [ProviderUninstallFile]) { + 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, @@ -319,7 +353,8 @@ extension ProviderUninstall { var info = stat() guard lstat(path, &info) == 0 else { continue } if info.st_mode & S_IFMT == S_IFDIR { - if info.st_dev != root.st_dev { otherVolume = true; walker.skipDescendants() } + 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 } @@ -330,6 +365,13 @@ extension ProviderUninstall { 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 { diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift index 10c5609df1..4dc287eabb 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift @@ -6,6 +6,23 @@ 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)" } @@ -51,6 +68,7 @@ extension ProviderUninstall { /// 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] { let headline = report.failed ? "Darkbloom is not fully removed from this Mac (see the failed step)." + : report.incomplete ? "Darkbloom is not fully removed from this Mac: some of its folders were not removed (see below)." : report.mode == .keepModels ? "Darkbloom is removed from this Mac; its models are kept." : "Darkbloom is removed from this Mac." var lines = [headline] @@ -87,10 +105,11 @@ extension ProviderUninstall { + "\(formatBytes(plan.modelBytes)), in \(folders.joined(separator: " and "))." } - /// What no option deletes: folders outside Darkbloom's, Keychain keys, and what has its own uninstall. + /// 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 { "Never touched: \($0.label) (\(formatBytes($0.bytes)), \($0.path)): \($0.reason ?? "")" } - + [keychainLine] + plan.elsewhere + 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. @@ -106,7 +125,13 @@ extension ProviderUninstall { } static func row(_ item: ProviderUninstallItem) -> String { - item.bytes > 0 ? "\(item.label) \(formatBytes(item.bytes)) \(item.path)" : "\(item.label) \(item.path)" + 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 the models you chose" } static func formatBytes(_ bytes: Int64) -> String { @@ -148,7 +173,8 @@ extension ProviderUninstall { } public static func invocation(everything: Bool, keepModels: Bool, yes: Bool, dryRun: Bool, interactive: Bool, - cli: String = BuildEnvironment.current.cliName) -> Invocation { + 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)) } @@ -186,7 +212,7 @@ extension ProviderUninstall { actions.append(.init(action: tokenStep, path: nil, bytes: nil)) 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 \($0.label)", path: $0.path, bytes: $0.bytes) } + 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) } diff --git a/provider-swift/Sources/darkbloom/UninstallCommand.swift b/provider-swift/Sources/darkbloom/UninstallCommand.swift index d41940226a..f949406f51 100644 --- a/provider-swift/Sources/darkbloom/UninstallCommand.swift +++ b/provider-swift/Sources/darkbloom/UninstallCommand.swift @@ -14,7 +14,9 @@ struct Uninstall: AsyncParsableCommand { 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. Models in a folder you chose and Keychain keys are never deleted. + 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. """) @Flag(help: "Remove everything: the app, settings, pairing, logs and all models.") @@ -38,7 +40,7 @@ struct Uninstall: AsyncParsableCommand { 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) + dryRun: dryRun, interactive: interactive, userID: geteuid()) if case .refuse(let line) = invocation { printError(line) throw ExitCode.validationFailure @@ -57,6 +59,11 @@ struct Uninstall: AsyncParsableCommand { 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 @@ -69,7 +76,7 @@ struct Uninstall: AsyncParsableCommand { operations: Self.operations(drain: drain)) { print("→ \($0)") } print("") ProviderUninstall.summary(report, plan: plan).forEach { print($0) } - if report.failed { throw ExitCode.failure } + if report.failed || report.incomplete { throw ExitCode.failure } } /// What this Mac has, read before anything changes. @@ -195,7 +202,6 @@ struct Uninstall: AsyncParsableCommand { static func confirm(readInput: () -> String? = { readLine() }) -> Bool { print("Continue? [y/N]: ", terminator: "") fflush(stdout) - let answer = readInput()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" - return ["y", "yes"].contains(answer) + return ProviderUninstall.confirmed(readInput()) } } diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 201b9a1a9a..9085063d5d 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -426,6 +426,10 @@ struct ProviderUninstallTests { 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") @@ -451,6 +455,11 @@ struct ProviderUninstallTests { #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") From 0b10d2b757028b6703cbb7acfdd65bb7d9b13d10 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:19:41 -0800 Subject: [PATCH 13/16] test(provider): uninstall beside the other install keeps the shared pair The 0.10.8 candidate's B12 and B11, as tests: - On a Mac with both the production and the DevNet app, each install's uninstall keeps what the other still uses: the pairing (no unpair call), the cable port setup (no cable call) and the cluster files every install shares (~/.darkbloom/cluster*, ~/.config/darkbloom/clusters). The screen, the dry run, --json and the summary name it, the summary's first line names the install it removed, and the run neither fails nor is incomplete. Its own app and command go; the other's stay. Both directions. - The install folder's row names the pairing and cluster setup only for ~/.darkbloom, where they are. - A cluster service running without its login agent is named in the dry run. Red at 1821a01b69: the B12 test runs and fails in both directions (the unpair and cable stand-ins are called, the production uninstall deletes the shared cluster files, nothing names them). With the B11 and label checks added, the suite does not compile (no `clusterServiceRunning:`, no `installFolderLabel`). Co-Authored-By: Claude Opus 5.5 --- .../Service/ProviderUninstallTests.swift | 74 ++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 9085063d5d..de7b5cbbea 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -293,7 +293,7 @@ struct ProviderUninstallTests { #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 Darkbloom folder: the app, logs, pairing and cluster setup", + #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) @@ -493,6 +493,76 @@ struct ProviderUninstallTests { #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() } + // 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. + for install in [this, other] { + 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) } + 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)") + 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("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 /. @@ -654,7 +724,7 @@ struct ProviderUninstallTests { 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 Darkbloom folder: the app, logs, pairing and cluster setup"]) + "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")) From 4b4d8cb9571d4636d8a8f275cd6e4f50e1d3bf55 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:24:29 -0800 Subject: [PATCH 14/16] fix(provider): uninstall keeps the pair the other install on this Mac uses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit B12, from the 0.10.8 candidate on the owner's kind of Mac: the DevNet app's uninstall forgot the pairing and undid the cable port setup that the production app on the same Mac uses (and the other way round, which also deleted the shared cluster files in ~/.darkbloom). - `ProviderUninstallPaths.otherEnvironment` tells the other install by its app or its `bin/` command in its own folder, not by the folder alone: ~/.darkbloom also holds the cluster files a DevNet-only Mac writes. - With another install present, the inventory lists "This Mac's pairing, cluster setup and cable port setup" as kept, naming the other install and its uninstall. The cluster files every install shares (~/.darkbloom/cluster*, ~/.config/darkbloom/clusters) stay while the rest of those folders goes. The run skips the unpair and cable steps ("kept: … on this Mac also uses it"), the dry run and --json leave them out, and the summary's first line names the install it removed. Without another install nothing changes. - The install folder's row names the pairing and cluster setup only for ~/.darkbloom, where they are. - B11: the dry run names a cluster service running without a login agent (`ClusterService.running`, the service's lock), which step 2 stops. The CLI reference, the installation, two-Mac and troubleshooting sections and the changelog fragment say so. `Cluster.Stop.parse([])` is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../provider-uninstall-keep-or-remove.md | 1 + docs/provider/cli-reference.md | 25 ++++-- docs/provider/installation.md | 5 +- docs/provider/troubleshooting.md | 1 + docs/provider/two-mac-cluster.md | 4 +- .../Service/Uninstall/ProviderUninstall.swift | 18 ++++- .../Uninstall/ProviderUninstallPlan.swift | 78 ++++++++++++++++--- .../Uninstall/ProviderUninstallText.swift | 35 ++++++--- .../Sources/darkbloom/UninstallCommand.swift | 5 +- .../Service/ProviderUninstallTests.swift | 2 + 10 files changed, 141 insertions(+), 33 deletions(-) diff --git a/changelog.d/provider-uninstall-keep-or-remove.md b/changelog.d/provider-uninstall-keep-or-remove.md index 6241880f00..68b52769b2 100644 --- a/changelog.d/provider-uninstall-keep-or-remove.md +++ b/changelog.d/provider-uninstall-keep-or-remove.md @@ -4,4 +4,5 @@ - 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, and says so; uninstall the other one too to remove them. 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 3ff76a2d81..49f644538c 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1361,11 +1361,11 @@ 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` | no cluster service on this Mac | +| 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` | no cluster service on this Mac. 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 | -| 8 | Undo the cable port setup | `darkbloom cluster link --remove` (macOS asks for an administrator's password) | nothing to undo | +| 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` @@ -1398,9 +1398,22 @@ What no choice deletes (the summary lists them): (`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. Cluster pairing and - setup files under `~/.darkbloom` are shared by every install on the Mac, so - removing the production install removes them for a development install too; + (`~/.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). 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 diff --git a/docs/provider/installation.md b/docs/provider/installation.md index 1033deed20..9306bceda8 100644 --- a/docs/provider/installation.md +++ b/docs/provider/installation.md @@ -327,7 +327,10 @@ 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). Remove what it leaves first, if you +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 diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 464f00e8cb..607ad67358 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -264,6 +264,7 @@ SSD caching remains enabled by default with no resident retention; use | `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 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). diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index b0435406c9..38229a1a03 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -837,7 +837,9 @@ altogether, see [Uninstall](#uninstall). 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`. +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 diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift index b12ac86e4c..c267f64af2 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -79,6 +79,7 @@ public enum ProviderUninstall { 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 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 = @@ -118,15 +119,26 @@ public enum ProviderUninstall { } else { steps.append(.init(name: tokenStep, status: .skipped, detail: stillServingReason)) } - if let pairing { + // Another install on this Mac uses the same pairing and cable port setup: both stay with it. + let sharedWith = items.lazy.compactMap(\.sharedWith).first + 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: "Forget this Mac's pairing", status: .skipped, detail: "this Mac is not paired")) + 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 = await step(cableStep, operations.removeCableSetup) + 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)" diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index aaf467f7f1..5569d9ae40 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -25,6 +25,10 @@ public struct ProviderUninstallPaths: Sendable, Equatable { 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) @@ -36,6 +40,13 @@ public struct ProviderUninstallPaths: Sendable, Equatable { 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) } @@ -62,6 +73,17 @@ public struct ProviderUninstallPaths: Sendable, Equatable { [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) } @@ -99,6 +121,10 @@ public struct ProviderUninstallItem: Codable, Sendable, Equatable { 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? /// Kept although it lies inside one of Darkbloom's folders, because the person chose it for models. var keptInDarkbloomFolder = false @@ -171,6 +197,9 @@ extension ProviderUninstall { 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? @@ -179,9 +208,11 @@ extension ProviderUninstall { public init(cli: String = BuildEnvironment.current.cliName, installCommand: String = "curl -fsSL \(BuildEnvironment.current.coordinatorHTTPURL)/install.sh | bash", - clusterService: [String] = [], services: [Service], items: [ProviderUninstallItem], + 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 } @@ -192,12 +223,15 @@ extension ProviderUninstall { 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" @@ -224,7 +258,7 @@ extension ProviderUninstall { 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: [String] = [] + var protected: [(path: String, what: String)] = [] for (label, folder, insideReason) in [(chosenModelsLabel, chosenModels, chosenInsideReason), (chosenStoreLabel, chosenStore, chosenStoreInsideReason)] { guard let folder else { continue } @@ -232,31 +266,57 @@ extension ProviderUninstall { 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) + protected.append((folder.path, "the models you chose")) } 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("Darkbloom folder: the app, logs, pairing and cluster setup", paths.installDirectory, 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. " + + "Run `\(other.cliName) uninstall` there to remove them") + shared.keptInDarkbloomFolder = true + shared.sharedWith = installName(other) + items.append(shared) + protected += files.map { (ProviderUninstallPaths.canonical($0.path), "the cluster files \(installName(other)) uses") } + } return items.compactMap { around($0, protected) } } /// `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: [String]) -> ProviderUninstallItem? { + private static func around(_ item: ProviderUninstallItem, _ protected: [(path: String, what: String)]) -> ProviderUninstallItem? { guard item.verdict == .remove, !protected.isEmpty else { return item } let resolved = ProviderUninstallPaths.canonical(item.path) - if protected.contains(where: { resolved == $0 || resolved.hasPrefix($0 + "/") }) { return nil } - let inside = protected.filter { $0.hasPrefix(resolved + "/") } + if protected.contains(where: { resolved == $0.path || resolved.hasPrefix($0.path + "/") }) { return nil } + let inside = protected.filter { $0.path.hasPrefix(resolved + "/") } guard !inside.isEmpty else { return item } - let measured = measure(URL(fileURLWithPath: resolved), excluding: inside) + 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 + 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 diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift index 4dc287eabb..17140ab460 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift @@ -50,13 +50,17 @@ extension ProviderUninstall { func action(_ text: String) { number += 1; lines.append(" \(number). \(text)") } action("\(stopServingStep): drain accepted requests, as `\(plan.cli) stop`") action("\(clusterStep), as `\(plan.cli) cluster stop`: " - + (plan.clusterService.isEmpty ? "no cluster service on this Mac" : plan.clusterService.joined(separator: ", "))) + + (!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)") - 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)") + 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)) } @@ -67,10 +71,15 @@ extension ProviderUninstall { /// 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] { - let headline = report.failed ? "Darkbloom is not fully removed from this Mac (see the failed step)." - : report.incomplete ? "Darkbloom is not fully removed from this Mac: some of its folders were not removed (see below)." - : report.mode == .keepModels ? "Darkbloom is removed from this Mac; its models are kept." - : "Darkbloom is removed from this Mac." + 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: some of its folders were not removed (see below)." + : 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) @@ -90,7 +99,7 @@ extension ProviderUninstall { + "`\(plan.cli) models location `.") } } - if let pairing = plan.pairing { lines.append(otherMacLine(pairing, cli: plan.cli)) } + if let pairing = plan.pairing, !plan.sharesCluster { lines.append(otherMacLine(pairing, cli: plan.cli)) } return lines } @@ -131,7 +140,7 @@ extension ProviderUninstall { /// 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 the models you chose" + item.keeping.isEmpty ? item.label : item.label + ", except " + item.keepingWhat } static func formatBytes(_ bytes: Int64) -> String { @@ -210,13 +219,15 @@ extension ProviderUninstall { 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)) - 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)) + 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.pairing.map { otherMacLine($0, cli: plan.cli) }) + otherMac: plan.sharesCluster ? nil : plan.pairing.map { otherMacLine($0, cli: plan.cli) }) } } diff --git a/provider-swift/Sources/darkbloom/UninstallCommand.swift b/provider-swift/Sources/darkbloom/UninstallCommand.swift index f949406f51..789d960726 100644 --- a/provider-swift/Sources/darkbloom/UninstallCommand.swift +++ b/provider-swift/Sources/darkbloom/UninstallCommand.swift @@ -16,7 +16,9 @@ struct Uninstall: AsyncParsableCommand { 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. + 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. """) @Flag(help: "Remove everything: the app, settings, pairing, logs and all models.") @@ -97,6 +99,7 @@ struct Uninstall: AsyncParsableCommand { + "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(), diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index de7b5cbbea..80addca8fb 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -544,6 +544,8 @@ struct ProviderUninstallTests { 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)") } From f910a85f073b4f04004eddb9235e30747e5682d4 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:33:52 -0800 Subject: [PATCH 15/16] test(provider): uninstall step 2 beside the other install, and F3 - Beside the other install (both directions, a fake home with both apps and stand-in launchd): step 2 never stops the pair (the cluster-stop stand-in is not called), removes only this install's own cluster service agent (`ClusterServiceAgentPlan.label` of its app), and leaves the other install's agent and any other agent loaded and installed. The dry run, --json and the summary say so. - F3: with `models location ~/.darkbloom`, the app folder stays with the chosen folder; the summary's first line says Darkbloom is not fully removed because its app folder is the models folder, the step says what to do, the dry run names it, and the run is incomplete (exit 1). Red at 4b4d8cb957: both tests compile and fail (step 2 runs the cluster stop, which removes every cluster agent; F3's headline says "Darkbloom is removed from this Mac."). Co-Authored-By: Claude Opus 5.5 --- .../Service/ProviderUninstallTests.swift | 106 +++++++++++++++--- 1 file changed, 92 insertions(+), 14 deletions(-) diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 80addca8fb..0303faefeb 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -33,6 +33,7 @@ private final class FakeLaunchd: @unchecked Sendable { } 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 } } } @@ -224,6 +225,30 @@ private func transcript(_ name: String, _ lines: [String], _ fixture: Fixture) { 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") @@ -498,20 +523,7 @@ struct ProviderUninstallTests { for (this, other) in [(BuildEnvironment.dev, BuildEnvironment.prod), (.prod, .dev)] { let fixture = try Fixture.make() defer { fixture.remove() } - // 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. - for install in [this, other] { - 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) } + 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), @@ -565,6 +577,72 @@ struct ProviderUninstallTests { "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(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 /. From 9246f9fd85d0a0921d4defde7de4b0864e7bd22f Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:36:03 -0800 Subject: [PATCH 16/16] fix(provider): uninstall step 2 removes only this install's cluster service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Finishes B12: with the cluster shared with the other install on this Mac, step 2 never stops the pair and never touches the other install's agent. It removes only this install's own cluster service agent, labelled by `ClusterServiceAgentPlan` for its app, through a small engine operation (`ProviderUninstall.removeOwnClusterAgent`), so #1774's `--service` follow-up only changes the unshared path. The dry run, --json and the summary say "Remove this install's cluster service: … the pair and the production Darkbloom's cluster service are left as they are"; the kept line says so too. Without another install, step 2 is unchanged (`Cluster.Stop.parse([])`). F3: when the models folder is ~/.darkbloom itself (or holds it), the app folder stays with it and is now refused rather than silently kept: the summary's first line says Darkbloom is not fully removed because its app folder is the models folder, the step says to move the models out and run ~/.darkbloom/bin/darkbloom uninstall again, and the command exits 1. Models inside a chosen folder still stay without counting, and a link is judged by where it is, not where it points, so the command link still goes. The CLI reference, troubleshooting and the changelog fragment say so. Co-Authored-By: Claude Opus 5.5 --- .../provider-uninstall-keep-or-remove.md | 2 +- docs/provider/cli-reference.md | 12 ++++-- docs/provider/troubleshooting.md | 1 + .../Service/Uninstall/ProviderUninstall.swift | 23 +++++++++-- .../Uninstall/ProviderUninstallPlan.swift | 38 +++++++++++++++---- .../Uninstall/ProviderUninstallText.swift | 32 ++++++++++++---- .../Sources/darkbloom/UninstallCommand.swift | 2 +- .../Service/ProviderUninstallTests.swift | 2 + 8 files changed, 90 insertions(+), 22 deletions(-) diff --git a/changelog.d/provider-uninstall-keep-or-remove.md b/changelog.d/provider-uninstall-keep-or-remove.md index 68b52769b2..1c58bfd098 100644 --- a/changelog.d/provider-uninstall-keep-or-remove.md +++ b/changelog.d/provider-uninstall-keep-or-remove.md @@ -4,5 +4,5 @@ - 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, and says so; uninstall the other one too to remove them. A dry run also names a cluster service running without a login agent. +- 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 49f644538c..8036bc196a 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1361,7 +1361,7 @@ 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` | no cluster service on this Mac. The dry run also names a cluster service running without a login agent (`ClusterService.running`), which this step stops | +| 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) | @@ -1393,7 +1393,12 @@ What no choice deletes (the summary lists them): `~/.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; + 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; @@ -1405,7 +1410,8 @@ What no choice deletes (the summary lists them): 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). The screen, + `~/.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.`): diff --git a/docs/provider/troubleshooting.md b/docs/provider/troubleshooting.md index 607ad67358..d8374ec468 100644 --- a/docs/provider/troubleshooting.md +++ b/docs/provider/troubleshooting.md @@ -263,6 +263,7 @@ SSD caching remains enabled by default with no resident retention; use | `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 | diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift index c267f64af2..858dba1058 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstall.swift @@ -80,6 +80,7 @@ public enum ProviderUninstall { 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 = @@ -102,8 +103,16 @@ public enum ProviderUninstall { 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) - var servicesStopped = await step(clusterStep, operations.stopClusterPart) && serving + 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 { @@ -119,8 +128,6 @@ public enum ProviderUninstall { } else { steps.append(.init(name: tokenStep, status: .skipped, detail: stillServingReason)) } - // Another install on this Mac uses the same pairing and cable port setup: both stay with it. - let sharedWith = items.lazy.compactMap(\.sharedWith).first 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)) @@ -185,6 +192,16 @@ public enum ProviderUninstall { 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 } diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift index 5569d9ae40..c2100c15bb 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallPlan.swift @@ -125,6 +125,10 @@ public struct ProviderUninstallItem: Codable, Sendable, Equatable { 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 @@ -236,6 +240,9 @@ extension ProviderUninstall { 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 @@ -266,7 +273,7 @@ extension ProviderUninstall { 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, "the models you chose")) + protected.append((folder.path, chosenWhat)) } add("Settings", paths.configDirectory) add("Encrypted prompt caches", paths.cacheDirectory) @@ -280,21 +287,38 @@ extension ProviderUninstall { 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. " - + "Run `\(other.cliName) uninstall` there to remove them") + 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") } } - return items.compactMap { around($0, protected) } + // 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)]) -> ProviderUninstallItem? { + private static func around(_ item: ProviderUninstallItem, _ protected: [(path: String, what: String)], + advice: String) -> ProviderUninstallItem? { guard item.verdict == .remove, !protected.isEmpty else { return item } - let resolved = ProviderUninstallPaths.canonical(item.path) - if protected.contains(where: { resolved == $0.path || resolved.hasPrefix($0.path + "/") }) { return nil } + // 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)) diff --git a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift index 17140ab460..3f40daa910 100644 --- a/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift +++ b/provider-swift/Sources/ProviderCore/Service/Uninstall/ProviderUninstallText.swift @@ -49,10 +49,15 @@ extension ProviderUninstall { var number = 0 func action(_ text: String) { number += 1; lines.append(" \(number). \(text)") } action("\(stopServingStep): drain accepted requests, as `\(plan.cli) stop`") - 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")) + 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")") } @@ -77,7 +82,7 @@ extension ProviderUninstall { 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: some of its folders were not removed (see below)." + : 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] @@ -103,6 +108,15 @@ extension ProviderUninstall { 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 @@ -215,8 +229,12 @@ extension ProviderUninstall { 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)] - let clusterAgents: [String?] = plan.clusterService.isEmpty ? [nil] : plan.clusterService - actions += clusterAgents.map { .init(action: clusterStep, path: $0, 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 { diff --git a/provider-swift/Sources/darkbloom/UninstallCommand.swift b/provider-swift/Sources/darkbloom/UninstallCommand.swift index 789d960726..2f7bcea26b 100644 --- a/provider-swift/Sources/darkbloom/UninstallCommand.swift +++ b/provider-swift/Sources/darkbloom/UninstallCommand.swift @@ -18,7 +18,7 @@ struct Uninstall: AsyncParsableCommand { 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. + other one, and only this install's own cluster service is removed. """) @Flag(help: "Remove everything: the app, settings, pairing, logs and all models.") diff --git a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift index 0303faefeb..79554cb241 100644 --- a/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Service/ProviderUninstallTests.swift @@ -635,6 +635,8 @@ struct ProviderUninstallTests { #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)