From b1fa700979de6cc9e414fc86141cf98ff4e30ae1 Mon Sep 17 00:00:00 2001 From: David Tai <8346495+davidtai@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:17:28 -0600 Subject: [PATCH 1/5] Sandbox setup: put the VM images and jobs on external drives (--disk) `darkbloom sandbox setup --disk ` (repeatable) passes each drive, as an absolute path, to the add-on installer's plan and install. Before anything is downloaded, setup checks each drive with statfs: mounted at its /Volumes/, APFS, ownership on. With ownership off it prints the exact `sudo diskutil enableOwnership ` line and stops; it never runs sudo or formats a drive. --disk goes only to an installer that names it; otherwise setup says work disks need add-on 1.2.0 or later and changes nothing. A set-up Mac offers --disk only when its add-on's status reports disks. The plan's `disks` render as one Work disk line each, and a plan that refuses a disk stops setup with the installer's fix and exit status. Co-Authored-By: Claude Opus 5.5 --- changelog.d/sandbox-setup-work-disks.md | 6 + docs/provider/cli-reference.md | 34 ++- docs/provider/sandboxes.md | 42 +++ .../darkbloom/Sandbox/SandboxAddon.swift | 6 +- .../Sandbox/SandboxEligibility.swift | 16 +- .../darkbloom/Sandbox/SandboxInstaller.swift | 22 +- .../Sandbox/SandboxSetupCommand.swift | 90 +++++- .../Sandbox/SandboxSetupProgress.swift | 23 +- .../darkbloom/Sandbox/SandboxWorkDisk.swift | 84 ++++++ .../SandboxTestSupport.swift | 9 +- .../SandboxWorkDiskTests.swift | 272 ++++++++++++++++++ 11 files changed, 575 insertions(+), 29 deletions(-) create mode 100644 changelog.d/sandbox-setup-work-disks.md create mode 100644 provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift diff --git a/changelog.d/sandbox-setup-work-disks.md b/changelog.d/sandbox-setup-work-disks.md new file mode 100644 index 0000000000..abe84a5054 --- /dev/null +++ b/changelog.d/sandbox-setup-work-disks.md @@ -0,0 +1,6 @@ +### Sandbox setup can put the VM images and jobs on an external drive + +- `darkbloom sandbox setup --disk ` (repeatable) passes each drive to the add-on's installer, for its plan and its install. The VM images and the jobs go on those drives; the add-on, its settings and logs stay in `~/DarkbloomSandbox`. Add `--disk ~` to keep using the internal disk too. +- Before it downloads anything, setup checks each drive: mounted, APFS, ownership on. With ownership off it prints the exact command, such as `sudo diskutil enableOwnership /Volumes/FastSSD`, and stops. The command needs an administrator, so setup never runs it, and it never formats a drive. +- The plan shows each drive, its free space and the jobs it gets. When the installer refuses a drive, setup shows the installer's fix and stops. +- `--disk` needs an add-on release with work disks (1.2.0 or later). With an earlier release, setup says so and changes nothing. On a Mac that is set up, setup suggests `--disk` only when the installed add-on supports it. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 9d91261278..4090b9d6c1 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1061,7 +1061,7 @@ service, to download the add-on's installer. Code: ```bash darkbloom sandbox [status [--json]] -darkbloom sandbox setup [--yes] [--no-browser] [--linux-slots ] [--macos-slots ] [--wait-ready] [--server ] +darkbloom sandbox setup [--yes] [--no-browser] [--linux-slots ] [--macos-slots ] [--disk ]... [--wait-ready] [--server ] darkbloom sandbox pause | resume darkbloom sandbox logs [-f] [-n ] darkbloom sandbox uninstall [--yes] @@ -1075,6 +1075,7 @@ darkbloom sandbox uninstall [--yes] | `setup --yes`, `-y` | `false` | Skip the confirmation | | `setup --no-browser` | `false` | The installer does not open the approval page; open the printed link | | `setup --linux-slots `, `--macos-slots ` | what fits the Mac | Jobs at a time: Linux `0`–`16`, macOS `0`–`2`; both `0` is refused. The plan and the install take a chosen count as it is; setup shows it as `(your choice)` | +| `setup --disk ` | none: the internal disk | Repeatable. A work disk for the VM images and jobs, such as `/Volumes/FastSSD`; `~` keeps the internal disk as well. Setup makes each path absolute, checks it (see [Setup](#setup)) and passes it on in order. Needs an add-on release with work disks (1.2.0 or later). The add-on, its settings and logs stay in `~/DarkbloomSandbox` | | `setup --wait-ready` | `false` | The installer waits until the images are downloaded and the Mac takes jobs | | `setup --server ` | `https://api-sandbox.darkbloom.dev` | Where `install.sh` comes from: an `https` URL without credentials, query or fragment | | `pause` | — | `darkbloom-sandbox pause`: running jobs finish, no new jobs; then prints how many still run | @@ -1090,6 +1091,17 @@ darkbloom sandbox uninstall [--yes] stops before anything is downloaded (`provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift`, `SandboxEligibility`; measurements in `SandboxHostProbe`). + With `--disk`, one `Work disk` line follows per disk, from `statfs` on the + path (or its nearest existing parent). A path under `/Volumes/` must be + on the volume mounted there, and the volume must be APFS with ownership on. + A disk that fails stops setup before anything is downloaded, with the fix: + for ownership off, the exact command, such as + `sudo diskutil enableOwnership /Volumes/FastSSD`. The command needs an + administrator, so setup prints it and never runs it; setup never formats a + drive either. The installer checks each disk again by the add-on's own rules + (local, writable, not a disk image) + (`provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift`, + `SandboxWorkDisk`). 2. **Download.** Downloads `/install.sh` over HTTPS: a redirect is followed only to another `https` URL, and the response must be HTTP 200 over `https`, at most 1 MiB, with a `#!` first line naming a shell. The script is @@ -1097,7 +1109,9 @@ darkbloom sandbox uninstall [--yes] the plan and the install, and removed afterwards. The installer verifies the add-on release before it installs it; the CLI does not verify the script beyond TLS (`provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift`, - `SandboxInstaller`). + `SandboxInstaller`). With `--disk`, a script that does not name `--disk` + comes from a release without work disks: setup says that work disks need + add-on 1.2.0 or later and stops, changing nothing. 3. **Plan.** A script that names `--plan` (add-on 1.1.1 and later) runs with `--plan --json-progress` and the owner's slot options, without `--yes` and with stdin closed. It verifies the release, runs the add-on's own checks and @@ -1152,7 +1166,7 @@ darkbloom sandbox uninstall [--yes] terminal and without `--yes`, setup stops before installing. 5. **Install.** A script that names `--json-progress` runs with `--json-progress --yes` and the owner's `--no-browser`, `--wait-ready` and - slot options, with stdin closed, and its stages render as + slot options and each `--disk `, with stdin closed, and its stages render as [progress events](#installer-progress-events). Any other script is an older installer: it runs with the terminal and only the slot options, and the CLI says so. @@ -1178,7 +1192,7 @@ Rerunning `setup` decides from the add-on's answer | No add-on, or `not_installed` | A first setup: check, plan, explain, confirm, install | | `waiting_for_approval`, `waitlisted`, `enrolling` | Runs the installer again to continue, without the check or the question | | `stopped`, `error`, no answer within 10 s, a failed status, an add-on older than `status --json` | Runs the installer again to repair or update the add-on | -| `ready`, `running`, `paused`, `downloading_images`, `updating`, an unknown state | Reports the state, then checks the plan again (below); with `--linux-slots` or `--macos-slots` it runs the installer to apply them, without the plan | +| `ready`, `running`, `paused`, `downloading_images`, `updating`, an unknown state | Reports the state, then checks the plan again (below); with `--linux-slots`, `--macos-slots` or `--disk` it runs the installer to apply them, without the plan, after the `Work disk` lines. The report offers `--disk` only when the add-on's `status --json` has a `disks` member | On a Mac that is set up, after the report, setup downloads the installer and runs its plan as for a first setup, which changes nothing, and compares the @@ -1214,8 +1228,16 @@ With `--plan --json-progress` (add-on 1.1.1) the installer exits 0 after one `macos_limit`, `free_bytes`, `floor_bytes`, `linux_images_bytes`, `macos_images_bytes`, `linux_slot_bytes`, `macos_slot_bytes`, `cores`, `cores_kept`, `memory_bytes`, `memory_kept_bytes` and `provider_memory_bytes` -(`SandboxSizingPlan`). It ignores `root`, `volume_bytes` and unknown members. A -line with another schema or without one of the numbers is not a plan. +(`SandboxSizingPlan`), and from `disks` (releases with work disks) each +entry's `path`, `root_volume`, `free_bytes`, `floor_bytes`, `linux_slots` and +`macos_slots`. When the plan uses an external disk or more than one disk, an +`[INFO] Work disk` line per disk follows the `Disk` line, such as +`/Volumes/FastSSD: 900 GiB free; 93 GiB stays free; 2 Linux jobs, 1 macOS job`. +It ignores `root`, `volume_bytes` and unknown members. A line with another +schema or without one of the numbers is not a plan. With `--disk`, a failed plan +(exit `2` when the installer refuses a disk) stops setup with the installer's +last stderr lines and its exit status, since the CLI's estimate knows no work +disks; without `--disk`, setup falls back to the estimate as before. | `status` | Meaning | The CLI | |---|---|---| diff --git a/docs/provider/sandboxes.md b/docs/provider/sandboxes.md index 58d031c578..ea8d2cc2f2 100644 --- a/docs/provider/sandboxes.md +++ b/docs/provider/sandboxes.md @@ -44,6 +44,8 @@ into your Darkbloom balance. rules. To choose the number of jobs, add `--linux-slots ` and `--macos-slots `; `--macos-slots 1` keeps one of macOS's two macOS VMs for your own use. + To put the VM images and jobs on an external drive, add `--disk `; + see [Use an external drive](#use-an-external-drive). 2. Approve this Mac in your browser. The installer opens the approval page with the code filled in, and setup prints the link and code as well. Sign in with @@ -56,6 +58,38 @@ into your Darkbloom balance. takes jobs once an image is installed. To keep setup open until then, add `--wait-ready` to step 1. +## Use an external drive + +If the internal disk is what limits this Mac, or to spare it the wear, give the +jobs another drive. The VM images and the jobs then use that drive. The add-on, +its settings and its logs stay in `~/DarkbloomSandbox`. This needs add-on 1.2.0 +or later; with an earlier release setup says so and changes nothing. + +1. Use a Thunderbolt or USB4 NVMe SSD that stays connected and powered. A job + on a drive that goes away is stopped and is not paid. +2. Format it as APFS in Disk Utility. Erasing deletes everything on the drive. + Setup never formats a drive. +3. Turn on ownership, which macOS leaves off for external drives. This needs an + administrator, so run it yourself: + + ```bash + sudo diskutil enableOwnership /Volumes/FastSSD + ``` + +4. Run setup with the drive. Repeat `--disk` for more drives, and add + `--disk ~` to keep using the internal disk too: + + ```bash + darkbloom sandbox setup --disk /Volumes/FastSSD + ``` + +Setup checks each drive before it downloads anything. When a drive is not APFS, +or has ownership off, setup stops and prints the fix, for example the exact +`diskutil enableOwnership` command. The plan then shows each drive, its free +space and the jobs it gets. Each drive keeps its own free space: a tenth of the +drive, 50 to 100 GiB. Running setup again keeps the drives you chose; give +`--disk` again to change them. + ## Verify ```bash @@ -76,6 +110,7 @@ Settled jobs are in the console under **Billing → Earnings**. | Take jobs again | `darkbloom sandbox resume` | | Follow the add-on's log | `darkbloom sandbox logs -f` | | Change the jobs at a time | `darkbloom sandbox setup --linux-slots --macos-slots ` | +| Put the images and jobs on an external drive | `darkbloom sandbox setup --disk /Volumes/` | | Remove the add-on and its files | `darkbloom sandbox uninstall` | Uninstalling ends running jobs, which are not paid: pause first and uninstall @@ -112,6 +147,13 @@ While jobs run, setup skips the check. The Ctrl-C if you like: the Mac enrolls once it is approved, and `setup` follows the waiting enrollment when you run it again. A restart ends that wait; run setup again after one. +- **`[FAIL] Work disk: … ignores file ownership`.** Ownership is off on the + drive. Run the `↳ fix:` command (`sudo diskutil enableOwnership …`), then run + setup again. +- **`[FAIL] Work disk: … is not APFS`** or **`is not a mounted drive`.** Format + the drive as APFS in Disk Utility, or connect it, then run setup again. +- **`work disks need add-on 1.2.0 or later`.** The add-on release on offer + cannot use other drives yet. Run setup without `--disk`. - **`[WARN] Network`, `Power` or `Sleep`.** These do not block setup, but a sleeping, unplugged or dropped Mac loses its running jobs, and lost jobs are not paid. Follow the `↳ fix:` line. diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift index 89f9d42544..a1a05ed492 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift @@ -151,6 +151,9 @@ struct SandboxAddonStatus: Equatable, Sendable { var accepting: Bool? var lastUpdateCheck: Date? var consoleURL: String? + /// The add-on reports its work disks (`disks`), so it takes + /// `install --disk`. + var supportsWorkDisks = false } extension SandboxAddonStatus { @@ -188,7 +191,8 @@ extension SandboxAddonStatus { }, accepting: object["accepting"] as? Bool, lastUpdateCheck: Self.timestamp(object["last_update_check"]), - consoleURL: text("console_url")) + consoleURL: text("console_url"), + supportsWorkDisks: object["disks"] is [Any]) } /// Unix seconds (or milliseconds) or an ISO 8601 string. diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift index 05d76d019a..47cd16ffc0 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift @@ -244,7 +244,21 @@ extension SandboxSizingPlan { .init(level: level("disk"), name: "Disk", detail: "\(gibDown(freeBytes)) GiB free; \(gibDown(floorBytes)) GiB stays free for you; " + disk("Linux", linux) + "; " + disk("macOS", macOS)), - ] + ] + diskChecks + } + + /// One line per disk when the plan uses a work disk (an external drive, + /// or more than one disk): its room and the jobs placed on it. + private var diskChecks: [SandboxEligibility.Check] { + guard disks.count > 1 || disks.contains(where: { !$0.rootVolume }) else { return [] } + return disks.map { disk in + let jobs = [("Linux", disk.linuxSlots), ("macOS", disk.macOSSlots)].filter { $0.1 > 0 } + .map { name, count in "\(count) \(name) job" + (count == 1 ? "" : "s") } + return .init(level: .info, name: "Work disk", + detail: "\(disk.path)\(disk.rootVolume ? " (internal)" : ""): " + + "\(gibDown(disk.freeBytes)) GiB free; \(gibDown(disk.floorBytes)) GiB stays free; " + + (jobs.isEmpty ? "no jobs" : jobs.joined(separator: ", "))) + } } /// The verdict, then what this Mac can run at a time or what it lacks. diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift index 68d4b71e4a..937472a0c0 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift @@ -8,6 +8,8 @@ struct SandboxSetupOptions: Equatable, Sendable { var waitReady = false var linuxSlots: Int? var macOSSlots: Int? + /// `--disk`: absolute paths, in the owner's order. + var disks: [String] = [] } /// Downloads the add-on's installer (`install.sh`) from the Darkbloom @@ -24,6 +26,9 @@ enum SandboxInstaller { /// text: they check this Mac and print the add-on's slot plan, installing /// nothing. An installer is run with it only when its text names it. static let planOption = "--plan" + /// Installers whose release supports work disks (external drives) accept + /// this option, repeated, and name it in their text. + static let diskOption = "--disk" enum Failure: Error, Equatable, CustomStringConvertible { case download(URL, String) @@ -103,8 +108,13 @@ enum SandboxInstaller { String(decoding: script, as: UTF8.self).contains(planOption) } + static func supportsDisks(_ script: Data) -> Bool { + String(decoding: script, as: UTF8.self).contains(diskOption) + } + /// The installer's arguments. An installer without `--json-progress` - /// knows only the slot options, so the others are left out for it. + /// knows only the slot options, so the others are left out for it; setup + /// gives `--disk` only to an installer that names it. static func arguments(_ options: SandboxSetupOptions, jsonProgress: Bool) -> [String] { var arguments: [String] = [] if jsonProgress { @@ -113,20 +123,20 @@ enum SandboxInstaller { if options.noBrowser { arguments.append("--no-browser") } if options.waitReady { arguments.append("--wait-ready") } } - return arguments + slotArguments(options) + return arguments + sizingArguments(options) } /// The arguments that ask for the add-on's plan for the owner's slot - /// counts. No `--yes`: the plan installs nothing. + /// counts and disks. No `--yes`: the plan installs nothing. static func planArguments(_ options: SandboxSetupOptions) -> [String] { - [planOption, jsonProgressOption] + slotArguments(options) + [planOption, jsonProgressOption] + sizingArguments(options) } - private static func slotArguments(_ options: SandboxSetupOptions) -> [String] { + private static func sizingArguments(_ options: SandboxSetupOptions) -> [String] { var arguments: [String] = [] if let linux = options.linuxSlots { arguments += ["--linux-slots", String(linux)] } if let macOS = options.macOSSlots { arguments += ["--macos-slots", String(macOS)] } - return arguments + return arguments + options.disks.flatMap { [diskOption, $0] } } /// Writes the script into a new owner-only directory and returns its path; diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift index 135a89ce32..5c86b658d9 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift @@ -15,9 +15,14 @@ extension Sandbox { it in your browser. Running it again reports the current state, continues an unfinished setup, repairs or updates \ - the add-on, or applies new slot counts. On a Mac that is set up, it asks the installer's plan \ - again and offers the add-on's slot counts when they differ from the installed ones; with --yes \ - or without a terminal it applies them only when they add slots and remove none. + the add-on, or applies new slot counts or work disks. On a Mac that is set up, it asks the \ + installer's plan again and offers the add-on's slot counts when they differ from the installed \ + ones; with --yes or without a terminal it applies them only when they add slots and remove none. + + With --disk, the VM images and jobs go on that drive instead of the internal disk; the add-on, \ + its settings and logs stay in ~/DarkbloomSandbox. The drive must be APFS with ownership on: setup \ + checks both first and prints the command to run when ownership is off. Setup never formats a \ + drive or runs sudo. Work disks need add-on \(SandboxWorkDisk.minimumAddonVersion) or later. """) @Flag(name: .shortAndLong, help: "Don't ask for confirmation.") @@ -32,6 +37,12 @@ extension Sandbox { @Option(name: .customLong("macos-slots"), help: "macOS jobs to run at a time (0-2). Default: what fits this Mac.") var macOSSlots: Int? + @Option(name: .customLong("disk"), help: ArgumentHelp( + "A drive for the VM images and jobs, such as /Volumes/FastSSD (APFS, ownership on). Repeat for " + + "more drives; add ~ to keep using the internal disk too.", + valueName: "volume")) + var disks: [String] = [] + @Flag(help: "Wait until the VM images are downloaded and this Mac is ready for jobs.") var waitReady = false @@ -51,11 +62,15 @@ extension Sandbox { if linuxSlots == 0, macOSSlots == 0 { throw ValidationError("--linux-slots 0 with --macos-slots 0 leaves nothing to run") } + if disks.contains(where: \.isEmpty) { + throw ValidationError("--disk needs a drive, such as /Volumes/FastSSD") + } } var options: SandboxSetupOptions { SandboxSetupOptions(server: server, noBrowser: noBrowser, waitReady: waitReady, - linuxSlots: linuxSlots, macOSSlots: macOSSlots) + linuxSlots: linuxSlots, macOSSlots: macOSSlots, + disks: disks.map { SandboxWorkDisk.absolutePath($0) }) } mutating func run() async throws { @@ -87,7 +102,9 @@ enum SandboxSetupPlan: Equatable, Sendable { /// A first setup: check eligibility and ask first. case fresh - static func decide(_ query: SandboxAddonQuery, changingSlots: Bool) -> SandboxSetupPlan { + static func decide(_ query: SandboxAddonQuery, changingSlots: Bool, changingDisks: Bool = false) + -> SandboxSetupPlan + { let repair = "running the installer again to repair it" let capitalizedRepair = "Running the installer again to repair it" switch query { @@ -107,7 +124,9 @@ enum SandboxSetupPlan: Equatable, Sendable { guard let detail = status.detail else { return .rerun("The add-on reports an error; \(repair).") } return .rerun("The add-on reports an error: \(detail). \(capitalizedRepair).") case .ready, .running, .paused, .downloadingImages, .updating, .unknown: - return changingSlots ? .rerun("Applying the new slot counts.") : .alreadySetUp(status) + let changes = [changingSlots ? "slot counts" : nil, changingDisks ? "work disks" : nil].compactMap { $0 } + return changes.isEmpty ? .alreadySetUp(status) + : .rerun("Applying the new \(changes.joined(separator: " and ")).") } case .outdated: return .rerun("Updating the add-on: this version is older than the CLI expects.") @@ -132,17 +151,24 @@ struct SandboxSetupFlow { var probe: @Sendable (SandboxAddon) async -> SandboxHostFacts = { await SandboxHostProbe.live(addon: $0, imagesInstalled: false) } + /// The volume of each `--disk`. + var workDiskVolume: @Sendable (String) -> SandboxWorkDisk.Volume? = SandboxWorkDisk.volume(at:) private var cli: String { Sandbox.cli } func run() async throws { let existing = addon.queryStatus(timeout: Sandbox.statusTimeout) let changingSlots = options.linuxSlots != nil || options.macOSSlots != nil - switch SandboxSetupPlan.decide(existing, changingSlots: changingSlots) { + switch SandboxSetupPlan.decide(existing, changingSlots: changingSlots, changingDisks: !options.disks.isEmpty) { case .alreadySetUp(let status): try await reportAndRecheckSizing(status) case .rerun(let reason): print(reason) + if !options.disks.isEmpty { + print("") + print(DoctorTerminalStyle.heading("Checking the work disks", color: color)) + try checkWorkDisks() + } try await withInstaller { try await install($0, script: $1, options: options) } case .fresh: let eligibility = try await checkMac() @@ -158,6 +184,14 @@ struct SandboxSetupFlow { private static let changeCountsHint = "To change how many jobs run at a time: \(Sandbox.cli) sandbox setup " + "--linux-slots --macos-slots " + /// The ways to change the install: the slot counts, and work disks + /// only when the installed add-on takes them. + private func printChangeHints(_ status: SandboxAddonStatus) { + print(Self.changeCountsHint) + guard status.supportsWorkDisks else { return } + print("To put the VM images and jobs on an external drive: \(cli) sandbox setup --disk /Volumes/") + } + /// Reports the install, then asks the installer's `--plan` how many jobs /// this Mac fits now and offers what differs. Changes nothing unless the /// owner agrees, or, without a prompt, the plan only adds slots. Skipped @@ -169,13 +203,13 @@ struct SandboxSetupFlow { SandboxStatusView.lines(status, color: color).forEach { print($0) } print("") guard status.jobsRunning == 0 else { - print(Self.changeCountsHint) + printChangeHints(status) print("Jobs are running, so setup did not check whether this Mac now fits other slot counts. Run " + "`\(cli) sandbox setup` again once they finish; `\(cli) sandbox pause` keeps new ones from starting.") return } try await withInstaller(ifUnavailable: { failure in - print(Self.changeCountsHint) + printChangeHints(status) print("Could not check whether this Mac now fits other slot counts: \(failure)") }) { installer, script in let plan = try await withTransientNote("Checking how many jobs this Mac fits now…") { @@ -183,7 +217,7 @@ struct SandboxSetupFlow { } // The same counts (or no plan to compare) keep today's report exactly. guard let plan, let change = SandboxSlotChange(installed: status, plan: plan) else { - print(Self.changeCountsHint) + printChangeHints(status) return } guard offer(change, plan: plan) else { return } @@ -243,9 +277,23 @@ struct SandboxSetupFlow { print(DoctorTerminalStyle.verdict("Not eligible: \(refusal)", level: .fail, color: color)) throw ExitCode.failure } + try checkWorkDisks() return eligibility } + /// Prints a `Work disk` line per `--disk`; throws, before anything is + /// downloaded, when one is not ready. The fixes are the owner's to run: + /// setup never formats a drive or runs `sudo`. + private func checkWorkDisks() throws { + let checks = options.disks.map { SandboxWorkDisk.check(path: $0, volume: workDiskVolume($0)) } + printChecks(checks) + guard checks.contains(where: { $0.level == .fail }) else { return } + print("") + print(DoctorTerminalStyle.verdict("A work disk is not ready: run the fix above, then run setup again. " + + "Nothing changed.", level: .fail, color: color)) + throw ExitCode.failure + } + /// Prints the add-on's plan (else the fallback estimate) and the /// trade-off, then asks. False when the owner declines; throws when no job /// fits. @@ -297,17 +345,29 @@ struct SandboxSetupFlow { private func requestAddonPlan(_ installer: URL, script: Data) async throws -> SandboxSizingPlan? { guard SandboxInstaller.supportsPlan(script) else { return nil } let output = SandboxOutputTail() + let errors = SandboxOutputTail() let exit = try await SandboxChildProcess.run( Self.shell, [installer.path] + SandboxInstaller.planArguments(options), currentDirectory: installer.deletingLastPathComponent(), closeStandardInput: true, - standardOutput: .tail(output), standardError: .tail(SandboxOutputTail())) + standardOutput: .tail(output), standardError: .tail(errors)) // Ctrl-C or a signal stops setup; it never goes on to install. if exit.interrupted || exit.signal != nil { print("") print("Setup stopped. Nothing changed.") throw ExitCode(exit.interrupted ? 130 : 1) } - guard exit.succeeded else { return nil } + guard exit.succeeded else { + // The CLI's estimate knows no work disks, and the installer + // refuses a disk it cannot use (exit 2) with the fix on stderr. + guard options.disks.isEmpty else { + print("") + errors.lastLines(5).forEach { print(" \($0)") } + print(DoctorTerminalStyle.verdict("The installer could not plan for these work disks; fix what it " + + "says above, then run setup again. Nothing changed.", level: .fail, color: color)) + throw ExitCode(exit.status > 0 ? exit.status : 1) + } + return nil + } return output.lastLines(.max).compactMap(SandboxSizingPlan.init(line:)).last } @@ -343,6 +403,12 @@ struct SandboxSetupFlow { printError("\(failure) Check this Mac's connection, then run `\(cli) sandbox setup` again.") throw ExitCode.failure } + guard options.disks.isEmpty || SandboxInstaller.supportsDisks(script) else { + printError("The add-on release that \(options.server) offers does not support --disk: work disks need " + + "add-on \(SandboxWorkDisk.minimumAddonVersion) or later. Nothing changed. Run " + + "`\(cli) sandbox setup` without --disk, or with it once that release is available.") + throw ExitCode.failure + } let installer = try SandboxInstaller.stage(script) defer { try? FileManager.default.removeItem(at: installer.deletingLastPathComponent()) } try await body(installer, script) diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift index 03468a4f2c..11bc6459bb 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift @@ -159,6 +159,20 @@ struct SandboxSizingPlan: Equatable, Sendable { var memoryKeptBytes: Int64 /// Memory kept for a running inference provider. var providerMemoryBytes: Int64 + /// Each disk and the slots placed on it (`disks`, add-on releases with + /// work disks); empty from earlier ones. + var disks: [Disk] = [] + + struct Disk: Equatable, Sendable { + /// Its mount point. + var path: String + /// The install root's own volume, the internal disk. + var rootVolume: Bool + var freeBytes: Int64 + var floorBytes: Int64 + var linuxSlots: Int + var macOSSlots: Int + } } extension SandboxSizingPlan { @@ -178,9 +192,16 @@ extension SandboxSizingPlan { let cores = object["cores"] as? Int, let coresKept = object["cores_kept"] as? Int, let memory = object["memory_bytes"] as? Int64, let memoryKept = object["memory_kept_bytes"] as? Int64, let providerMemory = object["provider_memory_bytes"] as? Int64 else { return nil } + let disks = (object["disks"] as? [[String: Any]] ?? []).compactMap { disk -> Disk? in + guard let path = disk["path"] as? String, let free = disk["free_bytes"] as? Int64, + let floor = disk["floor_bytes"] as? Int64 else { return nil } + return Disk(path: path, rootVolume: disk["root_volume"] as? Bool ?? false, freeBytes: free, + floorBytes: floor, linuxSlots: disk["linux_slots"] as? Int ?? 0, + macOSSlots: disk["macos_slots"] as? Int ?? 0) + } self.init(message: object["message"] as? String, linux: linux, macOS: macOS, freeBytes: free, floorBytes: floor, cores: cores, coresKept: coresKept, memoryBytes: memory, - memoryKeptBytes: memoryKept, providerMemoryBytes: providerMemory) + memoryKeptBytes: memoryKept, providerMemoryBytes: providerMemory, disks: disks) } } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift new file mode 100644 index 0000000000..fe22d1e7a6 --- /dev/null +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift @@ -0,0 +1,84 @@ +import Darwin +import Foundation + +/// A drive the owner gives with `setup --disk`, for the add-on's VM images and +/// jobs. Setup checks the two things an owner must set up by hand, APFS and +/// ownership, before it downloads anything; the installer checks each disk +/// again by the add-on's full rules before it writes anything. +enum SandboxWorkDisk { + /// The first add-on release whose installer takes `--disk`. + static let minimumAddonVersion = "1.2.0" + + /// The volume that holds a path, as `statfs` reports it. + struct Volume: Equatable, Sendable { + var mountPoint: String + var fileSystem: String + var ignoresOwnership: Bool + } + + /// `argument` as an absolute path: `~` expanded, a relative path taken + /// from `directory`. The installer runs in its own directory, so it must + /// never get a relative path. + static func absolutePath(_ argument: String, + directory: String = FileManager.default.currentDirectoryPath) -> String { + let expanded = (argument as NSString).expandingTildeInPath + let absolute = expanded.hasPrefix("/") ? expanded : (directory as NSString).appendingPathComponent(expanded) + return (absolute as NSString).standardizingPath + } + + /// The volume of `path`, or of its nearest existing parent. Nil only when + /// `statfs` fails. + static func volume(at path: String) -> Volume? { + var probe = path + while probe != "/", access(probe, F_OK) != 0 { probe = (probe as NSString).deletingLastPathComponent } + var info = statfs() + guard statfs(probe, &info) == 0 else { return nil } + func text(_ field: inout T) -> String { + withUnsafePointer(to: &field) { + $0.withMemoryRebound(to: CChar.self, capacity: MemoryLayout.size) { String(cString: $0) } + } + } + return Volume(mountPoint: text(&info.f_mntonname), fileSystem: text(&info.f_fstypename), + ignoresOwnership: info.f_flags & UInt32(MNT_IGNORE_OWNERSHIP) != 0) + } + + /// One `Work disk` line: a pass, or a failure with the exact fix. Setup + /// never formats a drive or runs `sudo`: the owner runs the fix. + static func check(path: String, volume: Volume?) -> SandboxEligibility.Check { + func refuse(_ detail: String, fix: String) -> SandboxEligibility.Check { + SandboxEligibility.Check(level: .fail, name: "Work disk", detail: detail, fix: fix) + } + guard let volume else { + return refuse("\(path) cannot be read", fix: "check the path, then run setup again") + } + let components = path.split(separator: "/") + if components.count >= 2, components[0] == "Volumes" { + let mount = "/Volumes/\(components[1])" + guard volume.mountPoint == mount || volume.mountPoint.hasPrefix(mount + "/") else { + return refuse("\(mount) is not a mounted drive", + fix: "connect the drive and check that it shows in Finder, then run setup again") + } + } + guard volume.fileSystem == "apfs" else { + return refuse("\(volume.mountPoint) is \(volume.fileSystem), not APFS", + fix: "copy off what you keep, erase the drive as APFS in Disk Utility (this deletes " + + "everything on it), then run setup again") + } + guard !volume.ignoresOwnership else { + return refuse("\(volume.mountPoint) ignores file ownership; turning it on needs an administrator, " + + "so run this yourself, then run setup again", + fix: "sudo diskutil enableOwnership \(shellWord(volume.mountPoint))") + } + let location = volume.mountPoint == path ? path : "\(path) (on \(volume.mountPoint))" + return SandboxEligibility.Check(level: .pass, name: "Work disk", detail: "\(location): APFS, ownership on") + } + + /// `text` as one shell word, quoted only when it needs it. + static func shellWord(_ text: String) -> String { + let plain = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/._-+:@%") + guard !text.isEmpty, text.unicodeScalars.allSatisfy(plain.contains) else { + return "'" + text.replacingOccurrences(of: "'", with: #"'\''"#) + "'" + } + return text + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift index 450b53eb52..f8490a3731 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift @@ -184,16 +184,21 @@ enum FakeSandboxInstaller { /// `plan` lines make it an installer with plan mode (add-on 1.1.1): with /// `--plan` it records its arguments, prints them, installs nothing and /// exits with `planExitStatus`. Without, the script never names `--plan`. + /// `planStandardError` goes to stderr in plan mode. `workDisks` makes it + /// name `--disk`, as a release with work disks does. static func script(events: [String] = events, plan: [String]? = nil, planExitStatus: Int32 = 0, + planStandardError: String? = nil, addonStatus: String = SandboxFixtures.downloading, standardError: String? = nil, - exitStatus: Int32 = 0, jsonProgress: Bool = true) -> String { - let header = jsonProgress ? "# Understands --json-progress." : "# An installer from before progress events." + exitStatus: Int32 = 0, jsonProgress: Bool = true, workDisks: Bool = false) -> String { + let header = (jsonProgress ? "# Understands --json-progress." : "# An installer from before progress events.") + + (workDisks ? " Takes \(SandboxInstaller.diskOption) (work disks)." : "") let plain = jsonProgress ? "" : "echo '==> Darkbloom Sandbox 1.0.0 downloaded and checked'" let planMode = plan.map { lines in """ if [ "${1:-}" = \(SandboxInstaller.planOption) ]; then printf '%s\\n' "$@" > "$root/plan-arguments" \(lines.map { "printf '%s\\n' \(quoted($0))" }.joined(separator: "\n")) + \(planStandardError.map { "echo \(quoted($0)) >&2" } ?? "") exit \(planExitStatus) fi """ diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift new file mode 100644 index 0000000000..c1c0946c59 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift @@ -0,0 +1,272 @@ +import ArgumentParser +import Foundation +import Testing + +@testable import darkbloom + +@Suite("darkbloom sandbox setup --disk") +struct SandboxWorkDiskTests { + static let ready = SandboxWorkDisk.Volume(mountPoint: "/Volumes/FastSSD", fileSystem: "apfs", + ignoresOwnership: false) + static let ownershipOff = SandboxWorkDisk.Volume(mountPoint: "/Volumes/FastSSD", fileSystem: "apfs", + ignoresOwnership: true) + static let enableOwnership = "sudo diskutil enableOwnership /Volumes/FastSSD" + + /// A plan for `/Volumes/FastSSD` alone: 2 Linux and 1 macOS slots on it. + static let externalPlan = FakeSandboxInstaller.plan( + message: "2 Linux slots and 1 macOS slot", linux: 2, macOS: 1, + extra: #","disks":[{"path":"/Volumes/FastSSD","directory":"/Volumes/FastSSD/DarkbloomSandbox","# + + #""root_volume":false,"volume_bytes":\#(Int64(1_000) << 30),"free_bytes":\#(Int64(900) << 30),"# + + #""floor_bytes":\#(Int64(93) << 30),"linux_slots":2,"macos_slots":1,"linux_images_bytes":0,"# + + #""macos_images_bytes":0,"cache":true}]"#) + + // MARK: - Options and arguments + + @Test("--disk repeats, becomes an absolute path, and an empty one is refused") + func parsing() throws { + let setup = try Sandbox.Setup.parse(["--disk", "/Volumes/FastSSD/", "--disk", "~"]) + #expect(setup.options.disks == ["/Volumes/FastSSD", NSHomeDirectory()]) + #expect(try Sandbox.Setup.parse([]).options.disks.isEmpty) + #expect(throws: (any Error).self) { try Sandbox.Setup.parse(["--disk", ""]) } + #expect(SandboxWorkDisk.absolutePath("FastSSD", directory: "/Volumes") == "/Volumes/FastSSD") + #expect(SandboxWorkDisk.absolutePath("../Volumes/FastSSD", directory: "/Users") == "/Volumes/FastSSD") + let help = Sandbox.Setup.helpMessage(columns: 1_000) + #expect(help.contains("--disk ")) + #expect(help.contains("Work disks need add-on \(SandboxWorkDisk.minimumAddonVersion) or later.")) + } + + @Test("the plan and the install get each --disk in order; only an installer that names --disk takes them") + func installerArguments() { + let options = SandboxSetupOptions(linuxSlots: 1, disks: ["/Volumes/FastSSD", "/Users/ada"]) + let disks = ["--disk", "/Volumes/FastSSD", "--disk", "/Users/ada"] + #expect(SandboxInstaller.planArguments(options) == ["--plan", "--json-progress", "--linux-slots", "1"] + disks) + #expect(SandboxInstaller.arguments(options, jsonProgress: true) + == ["--json-progress", "--yes", "--linux-slots", "1"] + disks) + #expect(SandboxInstaller.supportsDisks(Data(FakeSandboxInstaller.script(workDisks: true).utf8))) + #expect(!SandboxInstaller.supportsDisks(Data(FakeSandboxInstaller.script(plan: []).utf8))) + } + + @Test("an installed add-on that reports its disks takes --disk; one without the member does not") + func addonSupport() { + #expect(SandboxFixtures.status(Self.statusWithDisks).supportsWorkDisks) + #expect(!SandboxFixtures.status(SandboxFixtures.ready).supportsWorkDisks) + #expect(!SandboxFixtures.status(SandboxFixtures.minimal).supportsWorkDisks) + } + + @Test("a set-up Mac given --disk runs the installer again to apply the disks") + func rerunPlan() { + let json = SandboxFixtures.ready + let query = SandboxAddonQuery.status(SandboxFixtures.status(json), json: json) + #expect(SandboxSetupPlan.decide(query, changingSlots: false, changingDisks: true) + == .rerun("Applying the new work disks.")) + #expect(SandboxSetupPlan.decide(query, changingSlots: true, changingDisks: true) + == .rerun("Applying the new slot counts and work disks.")) + #expect(SandboxSetupPlan.decide(query, changingSlots: false, changingDisks: false) + == .alreadySetUp(SandboxFixtures.status(json))) + } + + // MARK: - The drive check + + @Test("an APFS drive with ownership on passes; each other drive fails with its exact fix") + func check() { + #expect(SandboxWorkDisk.check(path: "/Volumes/FastSSD", volume: Self.ready) == .init( + level: .pass, name: "Work disk", detail: "/Volumes/FastSSD: APFS, ownership on")) + let home = SandboxWorkDisk.Volume(mountPoint: "/System/Volumes/Data", fileSystem: "apfs", ignoresOwnership: false) + #expect(SandboxWorkDisk.check(path: "/Users/ada", volume: home).detail + == "/Users/ada (on /System/Volumes/Data): APFS, ownership on") + let ownership = SandboxWorkDisk.check(path: "/Volumes/FastSSD", volume: Self.ownershipOff) + #expect(ownership.level == .fail) + #expect(ownership.fix == Self.enableOwnership) + let spaced = SandboxWorkDisk.Volume(mountPoint: "/Volumes/Fast SSD's", fileSystem: "apfs", ignoresOwnership: true) + #expect(SandboxWorkDisk.check(path: "/Volumes/Fast SSD's", volume: spaced).fix + == #"sudo diskutil enableOwnership '/Volumes/Fast SSD'\''s'"#) + let exFAT = SandboxWorkDisk.Volume(mountPoint: "/Volumes/FastSSD", fileSystem: "exfat", ignoresOwnership: true) + let format = SandboxWorkDisk.check(path: "/Volumes/FastSSD", volume: exFAT) + #expect(format.level == .fail && format.detail == "/Volumes/FastSSD is exfat, not APFS") + #expect(format.fix?.contains("erase the drive as APFS in Disk Utility") == true) + // Unplugged: /Volumes/FastSSD resolves to the internal disk. + let unplugged = SandboxWorkDisk.check(path: "/Volumes/FastSSD/sandbox", volume: home) + #expect(unplugged.level == .fail && unplugged.detail == "/Volumes/FastSSD is not a mounted drive") + #expect(SandboxWorkDisk.check(path: "/Volumes/FastSSD", volume: nil).level == .fail) + } + + @Test("statfs: the temporary directory's volume, and a drive that is not there") + func liveVolume() throws { + let temporary = SandboxWorkDisk.absolutePath(NSTemporaryDirectory()) + let volume = try #require(SandboxWorkDisk.volume(at: temporary)) + #expect(!volume.mountPoint.isEmpty && !volume.fileSystem.isEmpty) + let missing = "/Volumes/no-such-drive-\(UUID().uuidString)" + #expect(SandboxWorkDisk.check(path: missing, volume: SandboxWorkDisk.volume(at: missing)).detail + == "\(missing) is not a mounted drive") + } + + @Test("the plan shows each work disk and the jobs placed on it; the internal disk alone shows none") + func planDisks() throws { + let plan = try #require(SandboxSizingPlan(line: Self.externalPlan)) + #expect(plan.disks == [.init(path: "/Volumes/FastSSD", rootVolume: false, freeBytes: 900 << 30, + floorBytes: 93 << 30, linuxSlots: 2, macOSSlots: 1)]) + #expect(plan.checks.map(\.name) == ["CPU", "Memory", "Disk", "Work disk"]) + #expect(plan.checks.last == .init(level: .info, name: "Work disk", detail: + "/Volumes/FastSSD: 900 GiB free; 93 GiB stays free; 2 Linux jobs, 1 macOS job")) + let internalOnly = try #require(SandboxSizingPlan(line: FakeSandboxInstaller.plan( + extra: #","disks":[{"path":"/System/Volumes/Data","root_volume":true,"free_bytes":1,"floor_bytes":1}]"#))) + #expect(internalOnly.checks.count == 3) + } + + // MARK: - Setup + + static let statusWithDisks = SandboxFixtures.ready.replacingOccurrences( + of: #"{"accepting""#, with: #"{"disks":[{"path":"/System/Volumes/Data","state":"online"}],"accepting""#) + + @Test("ownership off: setup prints the one-line diskutil command and stops before downloading anything") + func ownershipOff() async throws { + let result = try await #require(processExitsWith: .failure, observing: [\.standardOutputContent]) { + _ = try CLICommandSandbox.enter(autoRestart: false) + await exitWithCommandStatus { + defer { print("requests \(CoordinatorStub.requests.count)") } + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid", disks: ["/Volumes/FastSSD"]), + confirmed: true, addon: .live(), interactiveInput: false, terminal: false, color: false, + probe: { _ in .mac(cores: 16, memoryGiB: 128) }, + workDiskVolume: { _ in Self.ownershipOff }).run() + } + } + #expect(decodedText(result.standardOutputContent).hasSuffix(""" + [PASS] Sleep: off on the power adapter + [FAIL] Work disk: /Volumes/FastSSD ignores file ownership; turning it on needs an administrator, so \ + run this yourself, then run setup again + ↳ fix: \(Self.enableOwnership) + + A work disk is not ready: run the fix above, then run setup again. Nothing changed. + requests 0 + + """)) + } + + @Test("an installer whose release has no work disks: setup names the add-on version and installs nothing") + func releaseWithoutDisks() async throws { + let result = try await #require(processExitsWith: .failure, + observing: [\.standardOutputContent, \.standardErrorContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + plan: [FakeSandboxInstaller.plan()]).utf8))]) + await exitWithCommandStatus { + defer { + let root = sandbox.sandboxAddonRoot + print("planned \(FileManager.default.fileExists(atPath: root.appendingPathComponent("plan-arguments").path))") + } + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid", disks: ["/Volumes/FastSSD"]), + confirmed: true, addon: .live(), interactiveInput: false, terminal: false, color: false, + probe: { _ in .mac(cores: 16, memoryGiB: 128) }, workDiskVolume: { _ in Self.ready }).run() + } + } + #expect(decodedText(result.standardOutputContent).hasSuffix( + " [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on\nplanned false\n")) + #expect(decodedText(result.standardErrorContent).contains( + "The add-on release that https://sandbox.invalid offers does not support --disk: work disks need add-on " + + "\(SandboxWorkDisk.minimumAddonVersion) or later. Nothing changed.")) + } + + @Test("--disk reaches the plan and the install, and the plan shows the jobs on each disk") + func firstSetupWithDisk() async throws { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + plan: [Self.externalPlan], workDisks: true).utf8))]) + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid", disks: ["/Volumes/FastSSD"]), + confirmed: true, addon: .live(), interactiveInput: false, terminal: false, color: false, + probe: { _ in .mac(cores: 16, memoryGiB: 128) }, workDiskVolume: { _ in Self.ready }).run() + for (marker, file) in [("== PLAN", "plan-arguments"), ("== INSTALL", "installer-arguments")] { + print(marker) + print(try String(contentsOf: sandbox.sandboxAddonRoot.appendingPathComponent(file), encoding: .utf8), + terminator: "") + } + } + let output = decodedText(result.standardOutputContent) + #expect(output.contains(" [PASS] Sleep: off on the power adapter\n" + + " [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on\n")) + #expect(output.contains("macOS images 46 GiB + 40 GiB per macOS job\n" + + " [INFO] Work disk: /Volumes/FastSSD: 900 GiB free; 93 GiB stays free; 2 Linux jobs, 1 macOS job\n")) + #expect(output.hasSuffix("== PLAN\n--plan\n--json-progress\n--disk\n/Volumes/FastSSD\n" + + "== INSTALL\n--json-progress\n--yes\n--disk\n/Volumes/FastSSD\n")) + } + + @Test("a work disk the installer refuses in its plan: setup shows the installer's fix and keeps its exit status") + func planRefusesDisk() async throws { + let refusal = "error: /Volumes/FastSSD is a disk image; use a drive" + let result = try await #require(processExitsWith: .exitCode(2), observing: [\.standardOutputContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + plan: [], planExitStatus: 2, planStandardError: refusal, workDisks: true).utf8))]) + await exitWithCommandStatus { + defer { + let installed = sandbox.sandboxAddonRoot.appendingPathComponent("installer-arguments") + print("installed \(FileManager.default.fileExists(atPath: installed.path))") + } + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid", disks: ["/Volumes/FastSSD"]), + confirmed: true, addon: .live(), interactiveInput: false, terminal: false, color: false, + probe: { _ in .mac(cores: 16, memoryGiB: 128) }, workDiskVolume: { _ in Self.ready }).run() + } + } + #expect(decodedText(result.standardOutputContent).hasSuffix(""" + [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on + + \(refusal) + The installer could not plan for these work disks; fix what it says above, then run setup again. \ + Nothing changed. + installed false + + """)) + } + + @Test("a set-up Mac given --disk checks the drive, then runs the installer with it") + func rerunWithDisk() async throws { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + try FakeSandboxAddon.install(.current(status: Self.statusWithDisks), at: sandbox.sandboxAddonRoot) + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + plan: [Self.externalPlan], addonStatus: Self.statusWithDisks, workDisks: true).utf8))]) + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid", disks: ["/Volumes/FastSSD"]), + confirmed: false, addon: .live(), interactiveInput: false, terminal: false, color: false, + workDiskVolume: { _ in Self.ready }).run() + print("== INSTALL") + print(try String(contentsOf: sandbox.sandboxAddonRoot.appendingPathComponent("installer-arguments"), + encoding: .utf8), terminator: "") + } + let output = decodedText(result.standardOutputContent) + #expect(output.hasPrefix(""" + Applying the new work disks. + + Checking the work disks + [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on + + """)) + #expect(output.hasSuffix("== INSTALL\n--json-progress\n--yes\n--disk\n/Volumes/FastSSD\n")) + } + + @Test("a set-up Mac offers --disk only when its add-on takes it") + func hint() async throws { + let diskHint = "To put the VM images and jobs on an external drive: darkbloom sandbox setup --disk /Volumes/" + for (status, offered) in [(Self.statusWithDisks, true), (SandboxFixtures.ready, false)] { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + [status = status as String] in + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + try FakeSandboxAddon.install(.current(status: status), at: sandbox.sandboxAddonRoot) + // No installer to download: the report and its hints only. + try await SandboxSetupFlow(options: SandboxSetupOptions(server: "https://sandbox.invalid"), + confirmed: false, addon: .live(), interactiveInput: false, + terminal: false, color: false).run() + } + let output = decodedText(result.standardOutputContent) + #expect(output.contains("--linux-slots --macos-slots \n" + + (offered ? diskHint + "\n" : "") + "Could not check"), "\(offered)") + } + } +} From 76d432f351cc206b1fce54ccc15e764371962015 Mon Sep 17 00:00:00 2001 From: David Tai <8346495+davidtai@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:17:28 -0600 Subject: [PATCH 2/5] Sandbox setup --disk: refactor pass (shared option and job-count helpers, relative-path guard, clearer stop lines) Co-Authored-By: Claude Opus 5.5 --- .../darkbloom/Sandbox/SandboxEligibility.swift | 13 +++++++++---- .../darkbloom/Sandbox/SandboxInstaller.swift | 14 ++++++-------- .../darkbloom/Sandbox/SandboxSetupCommand.swift | 4 ++-- .../darkbloom/Sandbox/SandboxWorkDisk.swift | 4 +++- .../DarkbloomCLITests/SandboxWorkDiskTests.swift | 8 ++++---- 5 files changed, 24 insertions(+), 19 deletions(-) diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift index 47cd16ffc0..9b0d1f9959 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift @@ -252,8 +252,9 @@ extension SandboxSizingPlan { private var diskChecks: [SandboxEligibility.Check] { guard disks.count > 1 || disks.contains(where: { !$0.rootVolume }) else { return [] } return disks.map { disk in - let jobs = [("Linux", disk.linuxSlots), ("macOS", disk.macOSSlots)].filter { $0.1 > 0 } - .map { name, count in "\(count) \(name) job" + (count == 1 ? "" : "s") } + let jobs = [("Linux", disk.linuxSlots), ("macOS", disk.macOSSlots)].compactMap { name, count -> String? in + count > 0 ? Self.jobCount(count, name) : nil + } return .init(level: .info, name: "Work disk", detail: "\(disk.path)\(disk.rootVolume ? " (internal)" : ""): " + "\(gibDown(disk.freeBytes)) GiB free; \(gibDown(disk.floorBytes)) GiB stays free; " @@ -308,11 +309,15 @@ extension SandboxSizingPlan { } private static func slotLine(_ name: String, _ platform: Platform) -> String { - let jobs = platform.slots == 0 ? "no \(name) jobs" - : "\(platform.slots) \(name) job" + (platform.slots == 1 ? "" : "s") + let jobs = platform.slots == 0 ? "no \(name) jobs" : jobCount(platform.slots, name) guard platform.automatic else { return "\(jobs) (your choice)" } return platform.limit.map { "\(jobs) (limited by \($0))" } ?? jobs } + + /// `1 Linux job`, `2 macOS jobs`. + private static func jobCount(_ count: Int, _ name: String) -> String { + "\(count) \(name) job" + (count == 1 ? "" : "s") + } } extension SandboxSizingPlan.Platform { diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift index 937472a0c0..ff2cc61d65 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxInstaller.swift @@ -100,16 +100,14 @@ enum SandboxInstaller { return data } - static func supportsJSONProgress(_ script: Data) -> Bool { - String(decoding: script, as: UTF8.self).contains(jsonProgressOption) - } + static func supportsJSONProgress(_ script: Data) -> Bool { names(script, jsonProgressOption) } - static func supportsPlan(_ script: Data) -> Bool { - String(decoding: script, as: UTF8.self).contains(planOption) - } + static func supportsPlan(_ script: Data) -> Bool { names(script, planOption) } + + static func supportsDisks(_ script: Data) -> Bool { names(script, diskOption) } - static func supportsDisks(_ script: Data) -> Bool { - String(decoding: script, as: UTF8.self).contains(diskOption) + private static func names(_ script: Data, _ option: String) -> Bool { + String(decoding: script, as: UTF8.self).contains(option) } /// The installer's arguments. An installer without `--json-progress` diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift index 5c86b658d9..1fd9ec3d1d 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift @@ -289,7 +289,7 @@ struct SandboxSetupFlow { printChecks(checks) guard checks.contains(where: { $0.level == .fail }) else { return } print("") - print(DoctorTerminalStyle.verdict("A work disk is not ready: run the fix above, then run setup again. " + print(DoctorTerminalStyle.verdict("A work disk is not ready: follow the fix above, then run setup again. " + "Nothing changed.", level: .fail, color: color)) throw ExitCode.failure } @@ -362,7 +362,7 @@ struct SandboxSetupFlow { guard options.disks.isEmpty else { print("") errors.lastLines(5).forEach { print(" \($0)") } - print(DoctorTerminalStyle.verdict("The installer could not plan for these work disks; fix what it " + print(DoctorTerminalStyle.verdict("The installer's plan failed with these work disks; fix what it " + "says above, then run setup again. Nothing changed.", level: .fail, color: color)) throw ExitCode(exit.status > 0 ? exit.status : 1) } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift index fe22d1e7a6..08b12f7576 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift @@ -30,7 +30,9 @@ enum SandboxWorkDisk { /// `statfs` fails. static func volume(at path: String) -> Volume? { var probe = path - while probe != "/", access(probe, F_OK) != 0 { probe = (probe as NSString).deletingLastPathComponent } + while probe != "/", !probe.isEmpty, access(probe, F_OK) != 0 { + probe = (probe as NSString).deletingLastPathComponent + } var info = statfs() guard statfs(probe, &info) == 0 else { return nil } func text(_ field: inout T) -> String { diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift index c1c0946c59..17ff8fe400 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift @@ -7,9 +7,9 @@ import Testing @Suite("darkbloom sandbox setup --disk") struct SandboxWorkDiskTests { static let ready = SandboxWorkDisk.Volume(mountPoint: "/Volumes/FastSSD", fileSystem: "apfs", - ignoresOwnership: false) + ignoresOwnership: false) static let ownershipOff = SandboxWorkDisk.Volume(mountPoint: "/Volumes/FastSSD", fileSystem: "apfs", - ignoresOwnership: true) + ignoresOwnership: true) static let enableOwnership = "sudo diskutil enableOwnership /Volumes/FastSSD" /// A plan for `/Volumes/FastSSD` alone: 2 Linux and 1 macOS slots on it. @@ -137,7 +137,7 @@ struct SandboxWorkDiskTests { run this yourself, then run setup again ↳ fix: \(Self.enableOwnership) - A work disk is not ready: run the fix above, then run setup again. Nothing changed. + A work disk is not ready: follow the fix above, then run setup again. Nothing changed. requests 0 """)) @@ -216,7 +216,7 @@ struct SandboxWorkDiskTests { [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on \(refusal) - The installer could not plan for these work disks; fix what it says above, then run setup again. \ + The installer's plan failed with these work disks; fix what it says above, then run setup again. \ Nothing changed. installed false From 04bde04f949ae089ac5708d82c3a8fef00b3351a Mon Sep 17 00:00:00 2001 From: David Tai <8346495+davidtai@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:17:28 -0600 Subject: [PATCH 3/5] Sandbox --disk tests: keep the exit test's refusal text static (exit tests capture no locals) Co-Authored-By: Claude Opus 5.5 --- .../Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift index 17ff8fe400..b60e9e7201 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift @@ -194,13 +194,15 @@ struct SandboxWorkDiskTests { + "== INSTALL\n--json-progress\n--yes\n--disk\n/Volumes/FastSSD\n")) } + /// The installer's refusal of a disk in its plan, on stderr. + static let planRefusal = "error: /Volumes/FastSSD is a disk image; use a drive" + @Test("a work disk the installer refuses in its plan: setup shows the installer's fix and keeps its exit status") func planRefusesDisk() async throws { - let refusal = "error: /Volumes/FastSSD is a disk image; use a drive" let result = try await #require(processExitsWith: .exitCode(2), observing: [\.standardOutputContent]) { let sandbox = try CLICommandSandbox.enter(autoRestart: false) CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( - plan: [], planExitStatus: 2, planStandardError: refusal, workDisks: true).utf8))]) + plan: [], planExitStatus: 2, planStandardError: Self.planRefusal, workDisks: true).utf8))]) await exitWithCommandStatus { defer { let installed = sandbox.sandboxAddonRoot.appendingPathComponent("installer-arguments") @@ -215,7 +217,7 @@ struct SandboxWorkDiskTests { #expect(decodedText(result.standardOutputContent).hasSuffix(""" [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on - \(refusal) + \(Self.planRefusal) The installer's plan failed with these work disks; fix what it says above, then run setup again. \ Nothing changed. installed false From 4010d449b01abf41b2fa838dd83a75d5fb5ec669 Mon Sep 17 00:00:00 2001 From: David Tai <8346495+davidtai@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:09:09 -0600 Subject: [PATCH 4/5] Sandbox setup: offer the external drives, turn ownership on when the owner agrees, show work disks in status - A first setup without --disk, at a prompt and from a release with work disks, lists the drives mounted at their own /Volumes/ that show in Finder and are local, writable and APFS, with room for the floor and a Linux job. Enter keeps the internal disk; a chosen drive gets the work disk check and goes to the plan and the install as one --disk. - With ownership off, at a prompt and without --yes, setup offers to run sudo diskutil enableOwnership in the terminal's foreground process group (sudo asks for the password), then checks the drive again. Otherwise it prints the command and stops, as before. Setup never formats a drive. - darkbloom sandbox status reads the add-on's disks and shows one Work disk line per disk (state, free space, slots, and the add-on's detail when a disk is not online) when an external drive or more than one disk is in use. Refs Layr-Labs/darkbloom-sandbox#193 Co-Authored-By: Claude Opus 5.5 --- changelog.d/sandbox-setup-work-disks.md | 4 +- docs/provider/cli-reference.md | 27 ++- docs/provider/sandboxes.md | 39 +++-- .../darkbloom/Sandbox/SandboxAddon.swift | 32 +++- .../Sandbox/SandboxSetupCommand.swift | 111 ++++++++++-- .../Sandbox/SandboxSetupProgress.swift | 13 ++ .../darkbloom/Sandbox/SandboxStatusView.swift | 17 ++ .../darkbloom/Sandbox/SandboxWorkDisk.swift | 151 +++++++++++++--- .../SandboxStatusTests.swift | 24 +++ .../SandboxWorkDiskTests.swift | 165 +++++++++++++++++- 10 files changed, 521 insertions(+), 62 deletions(-) diff --git a/changelog.d/sandbox-setup-work-disks.md b/changelog.d/sandbox-setup-work-disks.md index abe84a5054..3521cdd6c3 100644 --- a/changelog.d/sandbox-setup-work-disks.md +++ b/changelog.d/sandbox-setup-work-disks.md @@ -1,6 +1,8 @@ ### Sandbox setup can put the VM images and jobs on an external drive - `darkbloom sandbox setup --disk ` (repeatable) passes each drive to the add-on's installer, for its plan and its install. The VM images and the jobs go on those drives; the add-on, its settings and logs stay in `~/DarkbloomSandbox`. Add `--disk ~` to keep using the internal disk too. -- Before it downloads anything, setup checks each drive: mounted, APFS, ownership on. With ownership off it prints the exact command, such as `sudo diskutil enableOwnership /Volumes/FastSSD`, and stops. The command needs an administrator, so setup never runs it, and it never formats a drive. +- Without `--disk`, a first setup at a prompt lists the external APFS drives with room for jobs and asks where the VM images and jobs go. Enter keeps the internal disk. +- Setup checks each drive before it installs anything: mounted, APFS, ownership on. With ownership off it prints the exact command, such as `sudo diskutil enableOwnership /Volumes/FastSSD`, and offers to run it; sudo asks for your password. With `--yes` or without a terminal it prints the command and stops. Setup never formats a drive. - The plan shows each drive, its free space and the jobs it gets. When the installer refuses a drive, setup shows the installer's fix and stops. +- `darkbloom sandbox status` shows each work disk, its free space and slots, and what to do when one is not connected. - `--disk` needs an add-on release with work disks (1.2.0 or later). With an earlier release, setup says so and changes nothing. On a Mac that is set up, setup suggests `--disk` only when the installed add-on supports it. diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 4090b9d6c1..eb2272a5fe 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1096,10 +1096,15 @@ darkbloom sandbox uninstall [--yes] on the volume mounted there, and the volume must be APFS with ownership on. A disk that fails stops setup before anything is downloaded, with the fix: for ownership off, the exact command, such as - `sudo diskutil enableOwnership /Volumes/FastSSD`. The command needs an - administrator, so setup prints it and never runs it; setup never formats a - drive either. The installer checks each disk again by the add-on's own rules - (local, writable, not a disk image) + `sudo diskutil enableOwnership /Volumes/FastSSD`. At a prompt and without + `--yes`, setup then asks `Turn ownership on for /Volumes/FastSSD now?` + (default no). On yes it runs that command in the terminal's foreground + process group, so sudo asks for the password itself; the CLI never reads it. + Then setup checks the disk again. If the command fails, setup prints + `Ownership is still off on …` and stops. With `--yes` or without a terminal, + setup prints the command and stops. Setup never formats a drive. The + installer checks each disk again by the add-on's own rules (local, writable, + not a disk image) (`provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift`, `SandboxWorkDisk`). 2. **Download.** Downloads `/install.sh` over HTTPS: a redirect is @@ -1112,6 +1117,19 @@ darkbloom sandbox uninstall [--yes] `SandboxInstaller`). With `--disk`, a script that does not name `--disk` comes from a release without work disks: setup says that work disks need add-on 1.2.0 or later and stops, changing nothing. + **Drive choice.** On a first setup without `--disk`, at a prompt and + without `--yes`, a script that names `--disk` makes setup list the drives + that can take the VM images and jobs, under `Where the VM images and jobs + go`: `1) This Mac's internal disk`, then one line per drive with its free + space, and a note when its ownership is off. A drive is listed when it is + mounted at its own `/Volumes/`, shows in Finder, is local, writable + and APFS, and has room for its floor (a tenth of the drive, 50 to 100 GiB) + plus a Linux job and its images (34 GiB). Setup asks `Choose 1-N [1]:`; + Enter or the end of input keeps the internal disk, and any other answer + that is not a listed number asks again. A chosen drive gets the `Work disk` + check above (with the ownership offer) and goes to the plan and the install + as one `--disk`. The plan's lines then follow under `The add-on's plan for + this Mac`. 3. **Plan.** A script that names `--plan` (add-on 1.1.1 and later) runs with `--plan --json-progress` and the owner's slot options, without `--yes` and with stdin closed. It verifies the release, runs the add-on's own checks and @@ -1314,6 +1332,7 @@ add-ons still render (`provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swi | `accepting` | bool | A ready Mac with `false` shows the add-on's `detail` | | `last_update_check` | Unix seconds or null (milliseconds and ISO 8601 are read too) | `Updates` line | | `console_url` | string | `Console` line and the setup summary | +| `disks` | `[{"path", "root_volume", "state", "detail", "free_bytes", "slots": {"linux": {"total"}, "macos": {"total"}}, …}]` (add-on releases with work disks) | The member's presence means the add-on takes `--disk`. When it lists an external drive or more than one disk, one `Work disk` line per disk follows `Images`, such as `/Volumes/FastSSD: online, 812 GiB free; slots: Linux 2, macOS 1`. A disk that is not `online` adds its `detail` in parentheses. An entry without `path` or `state` is skipped | An add-on that answers with exit status `64` or its usage on stderr predates the option or action: `status` then shows the add-on's own `status` output, diff --git a/docs/provider/sandboxes.md b/docs/provider/sandboxes.md index ea8d2cc2f2..f2d94d61e2 100644 --- a/docs/provider/sandboxes.md +++ b/docs/provider/sandboxes.md @@ -44,8 +44,9 @@ into your Darkbloom balance. rules. To choose the number of jobs, add `--linux-slots ` and `--macos-slots `; `--macos-slots 1` keeps one of macOS's two macOS VMs for your own use. - To put the VM images and jobs on an external drive, add `--disk `; - see [Use an external drive](#use-an-external-drive). + To put the VM images and jobs on an external drive, add `--disk `, + or pick the drive when setup asks; see + [Use an external drive](#use-an-external-drive). 2. Approve this Mac in your browser. The installer opens the approval page with the code filled in, and setup prints the link and code as well. Sign in with @@ -69,26 +70,33 @@ or later; with an earlier release setup says so and changes nothing. on a drive that goes away is stopped and is not paid. 2. Format it as APFS in Disk Utility. Erasing deletes everything on the drive. Setup never formats a drive. -3. Turn on ownership, which macOS leaves off for external drives. This needs an - administrator, so run it yourself: +3. Turn on ownership, which macOS leaves off for external drives. Setup offers + to do this for you (step 4). To do it yourself: ```bash sudo diskutil enableOwnership /Volumes/FastSSD ``` -4. Run setup with the drive. Repeat `--disk` for more drives, and add - `--disk ~` to keep using the internal disk too: +4. Run `darkbloom sandbox setup`. On a first setup it lists the drives with + room for jobs and asks where the VM images and jobs go. Press Enter to keep + the internal disk, or type the drive's number. You can also name the drive. + Repeat `--disk` for more drives, and add `--disk ~` to keep using the + internal disk too: ```bash darkbloom sandbox setup --disk /Volumes/FastSSD ``` -Setup checks each drive before it downloads anything. When a drive is not APFS, -or has ownership off, setup stops and prints the fix, for example the exact -`diskutil enableOwnership` command. The plan then shows each drive, its free -space and the jobs it gets. Each drive keeps its own free space: a tenth of the -drive, 50 to 100 GiB. Running setup again keeps the drives you chose; give -`--disk` again to change them. +Setup checks each drive before it installs anything. When ownership is off, +setup prints the command and asks whether to run it. If you agree, sudo asks +for your password, and setup checks the drive again. With `--yes`, or without +a terminal, setup prints the command and stops. When a drive is not APFS, setup +stops and tells you to erase it as APFS in Disk Utility; setup never formats a +drive. The plan then shows each drive, its free space and the jobs it gets. +Each drive keeps its own free space: a tenth of the drive, 50 to 100 GiB. +Running setup again keeps the drives you chose; give `--disk` again to change +them. `darkbloom sandbox status` shows each drive, its free space and slots, +and what to do when one is not connected. ## Verify @@ -148,8 +156,11 @@ While jobs run, setup skips the check. The the waiting enrollment when you run it again. A restart ends that wait; run setup again after one. - **`[FAIL] Work disk: … ignores file ownership`.** Ownership is off on the - drive. Run the `↳ fix:` command (`sudo diskutil enableOwnership …`), then run - setup again. + drive. Answer yes when setup offers to turn it on, or run the `↳ fix:` + command (`sudo diskutil enableOwnership …`) yourself, then run setup again. +- **`Work disk: … offline` in `darkbloom sandbox status`.** The drive is not + connected, so its slots take no jobs. Connect it again; its slots take jobs + once its images are checked. - **`[FAIL] Work disk: … is not APFS`** or **`is not a mounted drive`.** Format the drive as APFS in Disk Utility, or connect it, then run setup again. - **`work disks need add-on 1.2.0 or later`.** The add-on release on offer diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift index a1a05ed492..dea3b334cb 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxAddon.swift @@ -154,6 +154,23 @@ struct SandboxAddonStatus: Equatable, Sendable { /// The add-on reports its work disks (`disks`), so it takes /// `install --disk`. var supportsWorkDisks = false + /// Its work disks, in order: the internal disk alone without `--disk`. + var disks: [Disk] = [] + + /// One work disk, as `status --json` reports it. + struct Disk: Equatable, Sendable { + /// Its mount point. + var path: String + /// The install root's own volume, the internal disk. + var rootVolume: Bool + /// `online`, `verifying` or `offline`. + var state: String + /// What to do about it, when it is not online. + var detail: String? + var freeBytes: Int64? + var linuxSlots: Int + var macOSSlots: Int + } } extension SandboxAddonStatus { @@ -192,7 +209,20 @@ extension SandboxAddonStatus { accepting: object["accepting"] as? Bool, lastUpdateCheck: Self.timestamp(object["last_update_check"]), consoleURL: text("console_url"), - supportsWorkDisks: object["disks"] is [Any]) + supportsWorkDisks: object["disks"] is [Any], + disks: (object["disks"] as? [[String: Any]] ?? []).compactMap(Self.disk)) + } + + /// One entry of `disks`; nil without a path and a state. + private static func disk(_ entry: [String: Any]) -> Disk? { + guard let path = entry["path"] as? String, let state = entry["state"] as? String else { return nil } + func total(_ platform: String) -> Int { + let slots = (entry["slots"] as? [String: Any])?[platform] as? [String: Any] + return max(0, slots?["total"] as? Int ?? 0) + } + return Disk(path: path, rootVolume: entry["root_volume"] as? Bool ?? false, state: state, + detail: (entry["detail"] as? String).flatMap { $0.isEmpty ? nil : $0 }, + freeBytes: entry["free_bytes"] as? Int64, linuxSlots: total("linux"), macOSSlots: total("macos")) } /// Unix seconds (or milliseconds) or an ISO 8601 string. diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift index 1fd9ec3d1d..e22496b781 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift @@ -20,9 +20,11 @@ extension Sandbox { ones; with --yes or without a terminal it applies them only when they add slots and remove none. With --disk, the VM images and jobs go on that drive instead of the internal disk; the add-on, \ - its settings and logs stay in ~/DarkbloomSandbox. The drive must be APFS with ownership on: setup \ - checks both first and prints the command to run when ownership is off. Setup never formats a \ - drive or runs sudo. Work disks need add-on \(SandboxWorkDisk.minimumAddonVersion) or later. + its settings and logs stay in ~/DarkbloomSandbox. Without --disk, at a prompt, setup lists the \ + external APFS drives with room for jobs and asks which one to use (Enter keeps the internal \ + disk). The drive must be APFS with ownership on: setup checks both first. When ownership is off \ + it prints the command and, at a prompt, offers to run it (sudo asks for your password). Setup \ + never formats a drive. Work disks need add-on \(SandboxWorkDisk.minimumAddonVersion) or later. """) @Flag(name: .shortAndLong, help: "Don't ask for confirmation.") @@ -153,6 +155,11 @@ struct SandboxSetupFlow { } /// The volume of each `--disk`. var workDiskVolume: @Sendable (String) -> SandboxWorkDisk.Volume? = SandboxWorkDisk.volume(at:) + /// The drives to offer when the owner gives no `--disk`. + var workDiskCandidates: @Sendable () -> [SandboxWorkDisk.Volume] = { SandboxWorkDisk.candidates() } + /// Turns ownership on for the drive mounted there (`sudo diskutil + /// enableOwnership`) on this terminal; true when it did. + var enableOwnership: @Sendable (String) -> Bool = { SandboxWorkDisk.enableOwnership(mountPoint: $0) } private var cli: String { Sandbox.cli } @@ -167,14 +174,16 @@ struct SandboxSetupFlow { if !options.disks.isEmpty { print("") print(DoctorTerminalStyle.heading("Checking the work disks", color: color)) - try checkWorkDisks() + try checkWorkDisks(options.disks) } try await withInstaller { try await install($0, script: $1, options: options) } case .fresh: let eligibility = try await checkMac() try await withInstaller { installer, script in - guard try await sizeAndConfirm(eligibility, installer: installer, script: script) else { return } - try await install(installer, script: script, options: options) + let chosen = try chooseWorkDisk(script: script) + guard try await sizeAndConfirm(eligibility, installer: installer, script: script, options: chosen) + else { return } + try await install(installer, script: script, options: chosen) } } } @@ -213,7 +222,7 @@ struct SandboxSetupFlow { print("Could not check whether this Mac now fits other slot counts: \(failure)") }) { installer, script in let plan = try await withTransientNote("Checking how many jobs this Mac fits now…") { - try await requestAddonPlan(installer, script: script) + try await requestAddonPlan(installer, script: script, options: options) } // The same counts (or no plan to compare) keep today's report exactly. guard let plan, let change = SandboxSlotChange(installed: status, plan: plan) else { @@ -277,28 +286,92 @@ struct SandboxSetupFlow { print(DoctorTerminalStyle.verdict("Not eligible: \(refusal)", level: .fail, color: color)) throw ExitCode.failure } - try checkWorkDisks() + try checkWorkDisks(options.disks) return eligibility } - /// Prints a `Work disk` line per `--disk`; throws, before anything is - /// downloaded, when one is not ready. The fixes are the owner's to run: - /// setup never formats a drive or runs `sudo`. - private func checkWorkDisks() throws { - let checks = options.disks.map { SandboxWorkDisk.check(path: $0, volume: workDiskVolume($0)) } - printChecks(checks) - guard checks.contains(where: { $0.level == .fail }) else { return } + /// Prints a `Work disk` line per disk; throws, before anything is + /// installed, when one is not ready. At a prompt it offers to turn + /// ownership on (sudo asks for the password), then checks that disk + /// again; the other fixes are the owner's. Setup never formats a drive. + private func checkWorkDisks(_ disks: [String]) throws { + var ready = true + for path in disks { + let check = SandboxWorkDisk.check(path: path, volume: workDiskVolume(path)) + printChecks([check]) + guard check.level == .fail else { continue } + if let mount = ownershipToTurnOn(path), turnOnOwnership(mount) { + let again = SandboxWorkDisk.check(path: path, volume: workDiskVolume(path)) + printChecks([again]) + if again.level != .fail { continue } + } + ready = false + } + guard !ready else { return } print("") print(DoctorTerminalStyle.verdict("A work disk is not ready: follow the fix above, then run setup again. " + "Nothing changed.", level: .fail, color: color)) throw ExitCode.failure } + /// The mount point of the drive at `path` when its one problem is + /// ownership off and there is a prompt to offer the fix at. + private func ownershipToTurnOn(_ path: String) -> String? { + guard !confirmed, interactiveInput, let volume = workDiskVolume(path), + SandboxWorkDisk.problem(path: path, volume: volume) == .ownershipOff else { return nil } + return volume.mountPoint + } + + /// Asks, then runs the fix for ownership off; true when it ran and exited 0. + private func turnOnOwnership(_ mount: String) -> Bool { + guard SandboxTerminal.confirm("Turn ownership on for \(mount) now? Setup runs the command above; sudo asks " + + "for your password.") else { return false } + guard enableOwnership(mount) else { + print("Ownership is still off on \(mount).") + return false + } + return true + } + + /// Without `--disk`, at a prompt, and from a release with work disks: + /// lists the external drives that could take the VM images and jobs and + /// asks which one to use. Enter (or no drive to offer) keeps the internal + /// disk. Returns the options with the chosen drive, checked. + private func chooseWorkDisk(script: Data) throws -> SandboxSetupOptions { + guard options.disks.isEmpty, !confirmed, interactiveInput, SandboxInstaller.supportsDisks(script) else { + return options + } + let drives = workDiskCandidates() + guard !drives.isEmpty else { return options } + print("") + print(DoctorTerminalStyle.heading("Where the VM images and jobs go", color: color)) + print(" 1) This Mac's internal disk") + for (index, drive) in drives.enumerated() { + let note = drive.ignoresOwnership ? "; ownership is off, setup can turn it on" : "" + print(" \(index + 2)) \(drive.mountPoint): \(drive.freeBytes / SandboxEligibility.gib) GiB free\(note)") + } + print(" Use an external drive only if it is a Thunderbolt or USB4 NVMe SSD that stays connected: a job on " + + "a drive that goes away is stopped and not paid.") + let choice = SandboxTerminal.choose(count: drives.count + 1) + var chosen = options + if choice > 1 { + chosen.disks = [drives[choice - 2].mountPoint] + print("") + print(DoctorTerminalStyle.heading("Checking the work disks", color: color)) + try checkWorkDisks(chosen.disks) + } + // The plan's lines follow; they no longer sit under "Checking this Mac". + print("") + print(DoctorTerminalStyle.heading("The add-on's plan for this Mac", color: color)) + return chosen + } + /// Prints the add-on's plan (else the fallback estimate) and the /// trade-off, then asks. False when the owner declines; throws when no job /// fits. - private func sizeAndConfirm(_ eligibility: SandboxEligibility, installer: URL, script: Data) async throws -> Bool { - let reportedPlan = try await requestAddonPlan(installer, script: script) + private func sizeAndConfirm(_ eligibility: SandboxEligibility, installer: URL, script: Data, + options: SandboxSetupOptions) async throws -> Bool { + let reportedPlan = try await requestAddonPlan(installer, script: script, options: options) let plan: SandboxSizingPlan if let reportedPlan { plan = reportedPlan @@ -342,7 +415,9 @@ struct SandboxSetupFlow { /// release and sizes this Mac without installing anything. Nil, for the /// fallback, from an installer without plan mode (it names no `--plan`), /// a failed run or one without a `plan` event. - private func requestAddonPlan(_ installer: URL, script: Data) async throws -> SandboxSizingPlan? { + private func requestAddonPlan(_ installer: URL, script: Data, options: SandboxSetupOptions) async throws + -> SandboxSizingPlan? + { guard SandboxInstaller.supportsPlan(script) else { return nil } let output = SandboxOutputTail() let errors = SandboxOutputTail() diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift index 11bc6459bb..44b9f21edd 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift @@ -483,4 +483,17 @@ enum SandboxTerminal { let answer = readInput()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" return ["y", "yes"].contains(answer) || (defaultYes && answer.isEmpty) } + + /// Asks for a number from 1 to `count` until it gets one; an empty answer + /// or the end of input is 1. + static func choose(count: Int, readInput: () -> String? = { readLine() }, + emit: (String) -> Void = { write($0) }) -> Int { + while true { + emit("Choose 1-\(count) [1]: ") + guard let answer = readInput()?.trimmingCharacters(in: .whitespacesAndNewlines), !answer.isEmpty else { + return 1 + } + if let number = Int(answer), (1...count).contains(number) { return number } + } + } } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxStatusView.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxStatusView.swift index 24189682a9..4c5edbf74c 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxStatusView.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxStatusView.swift @@ -92,6 +92,7 @@ enum SandboxStatusView { lines.append(" Free slots: \(slots)") } if !status.images.isEmpty { lines.append(" Images: \(imagesText(status.images))") } + lines += diskLines(status.disks) if let host = status.hostID { lines.append(" Host: \(host)") } let checked = status.lastUpdateCheck.map { "last checked \(darkbloom.Status.compactDuration(max(0, now.timeIntervalSince($0)))) ago" @@ -185,6 +186,22 @@ enum SandboxStatusView { return platform } + /// One `Work disk` line per disk when the add-on uses an external drive + /// or more than one disk: its state, free space and slots, and what to do + /// when it is not online. None for the internal disk alone. + static func diskLines(_ disks: [SandboxAddonStatus.Disk]) -> [String] { + guard disks.count > 1 || disks.contains(where: { !$0.rootVolume }) else { return [] } + return disks.map { disk in + var text = disk.path + (disk.rootVolume ? " (internal)" : "") + ": " + disk.state + if let free = disk.freeBytes { text += ", \(max(0, free) / SandboxEligibility.gib) GiB free" } + let slots = [("Linux", disk.linuxSlots), ("macOS", disk.macOSSlots)].filter { $0.1 > 0 } + .map { "\($0.0) \($0.1)" } + if !slots.isEmpty { text += "; slots: " + slots.joined(separator: ", ") } + if disk.state != "online", let detail = disk.detail { text += " (\(detail))" } + return " Work disk: " + text + } + } + static func jobs(_ count: Int) -> String { count == 1 ? "1 job" : "\(count) jobs" } static func percent(_ fraction: Double) -> String { "\(Int((fraction * 100).rounded(.down)))%" } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift index 08b12f7576..aae5db04fe 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift @@ -1,10 +1,10 @@ import Darwin import Foundation -/// A drive the owner gives with `setup --disk`, for the add-on's VM images and -/// jobs. Setup checks the two things an owner must set up by hand, APFS and -/// ownership, before it downloads anything; the installer checks each disk -/// again by the add-on's full rules before it writes anything. +/// A drive for the add-on's VM images and jobs (`setup --disk`, or the drive +/// the owner picks in setup). Setup checks the two things an owner must set up +/// by hand, APFS and ownership, before it downloads anything; the installer +/// checks each disk again by the add-on's full rules before it writes anything. enum SandboxWorkDisk { /// The first add-on release whose installer takes `--disk`. static let minimumAddonVersion = "1.2.0" @@ -14,6 +14,25 @@ enum SandboxWorkDisk { var mountPoint: String var fileSystem: String var ignoresOwnership: Bool + /// Space free for this user (`df`'s Avail) and the volume's size. + var freeBytes: Int64 = 0 + var volumeBytes: Int64 = 0 + /// A local disk (`MNT_LOCAL`), not a network share. + var local = true + var readOnly = false + /// Hidden from Finder (`MNT_DONTBROWSE`), as Time Machine and system volumes are. + var hidden = false + } + + /// Why a drive cannot take the add-on's work yet, in the order setup checks. + enum Problem: Equatable, Sendable { + /// `statfs` failed on the path and every parent. + case unreadable + /// The path names `/Volumes/`, and no drive is mounted there. + case notMounted(String) + case notAPFS + /// macOS ignores file ownership on the volume; an administrator can turn it on. + case ownershipOff } /// `argument` as an absolute path: `~` expanded, a relative path taken @@ -40,12 +59,31 @@ enum SandboxWorkDisk { $0.withMemoryRebound(to: CChar.self, capacity: MemoryLayout.size) { String(cString: $0) } } } + func flag(_ mask: Int32) -> Bool { info.f_flags & UInt32(mask) != 0 } + let blockSize = Int64(info.f_bsize) return Volume(mountPoint: text(&info.f_mntonname), fileSystem: text(&info.f_fstypename), - ignoresOwnership: info.f_flags & UInt32(MNT_IGNORE_OWNERSHIP) != 0) + ignoresOwnership: flag(MNT_IGNORE_OWNERSHIP), + freeBytes: Int64(clamping: info.f_bavail) * blockSize, + volumeBytes: Int64(clamping: info.f_blocks) * blockSize, + local: flag(MNT_LOCAL), readOnly: flag(MNT_RDONLY), hidden: flag(MNT_DONTBROWSE)) + } + + /// What keeps `path` (on `volume`) from taking the add-on's work, if anything. + static func problem(path: String, volume: Volume?) -> Problem? { + guard let volume else { return .unreadable } + let components = path.split(separator: "/") + if components.count >= 2, components[0] == "Volumes" { + let mount = "/Volumes/\(components[1])" + guard volume.mountPoint == mount || volume.mountPoint.hasPrefix(mount + "/") else { + return .notMounted(mount) + } + } + guard volume.fileSystem == "apfs" else { return .notAPFS } + return volume.ignoresOwnership ? .ownershipOff : nil } /// One `Work disk` line: a pass, or a failure with the exact fix. Setup - /// never formats a drive or runs `sudo`: the owner runs the fix. + /// never formats a drive. static func check(path: String, volume: Volume?) -> SandboxEligibility.Check { func refuse(_ detail: String, fix: String) -> SandboxEligibility.Check { SandboxEligibility.Check(level: .fail, name: "Work disk", detail: detail, fix: fix) @@ -53,26 +91,97 @@ enum SandboxWorkDisk { guard let volume else { return refuse("\(path) cannot be read", fix: "check the path, then run setup again") } - let components = path.split(separator: "/") - if components.count >= 2, components[0] == "Volumes" { - let mount = "/Volumes/\(components[1])" - guard volume.mountPoint == mount || volume.mountPoint.hasPrefix(mount + "/") else { - return refuse("\(mount) is not a mounted drive", - fix: "connect the drive and check that it shows in Finder, then run setup again") - } - } - guard volume.fileSystem == "apfs" else { + switch problem(path: path, volume: volume) { + case .unreadable: + return refuse("\(path) cannot be read", fix: "check the path, then run setup again") + case .notMounted(let mount): + return refuse("\(mount) is not a mounted drive", + fix: "connect the drive and check that it shows in Finder, then run setup again") + case .notAPFS: return refuse("\(volume.mountPoint) is \(volume.fileSystem), not APFS", fix: "copy off what you keep, erase the drive as APFS in Disk Utility (this deletes " + "everything on it), then run setup again") + case .ownershipOff: + return refuse("\(volume.mountPoint) ignores file ownership; turning it on needs an administrator", + fix: enableOwnershipCommand(volume.mountPoint)) + case nil: + let location = volume.mountPoint == path ? path : "\(path) (on \(volume.mountPoint))" + return SandboxEligibility.Check(level: .pass, name: "Work disk", detail: "\(location): APFS, ownership on") } - guard !volume.ignoresOwnership else { - return refuse("\(volume.mountPoint) ignores file ownership; turning it on needs an administrator, " - + "so run this yourself, then run setup again", - fix: "sudo diskutil enableOwnership \(shellWord(volume.mountPoint))") + } + + /// `sudo diskutil enableOwnership `, the mount point as one shell word. + static func enableOwnershipCommand(_ mountPoint: String) -> String { + "sudo diskutil enableOwnership \(shellWord(mountPoint))" + } + + /// Runs `sudo diskutil enableOwnership ` on this terminal, so sudo + /// asks for the password itself; the CLI never reads it. False when it + /// did not exit 0, or when there is no terminal to ask on. + static func enableOwnership(mountPoint: String) -> Bool { + runInForeground("/usr/bin/sudo", ["--", "/usr/sbin/diskutil", "enableOwnership", mountPoint]) == 0 + } + + /// Runs `executable` in this process's group, attached to the terminal, + /// and returns its exit status. Foundation's `Process` would start it in a + /// group of its own, outside the terminal's foreground job, where sudo's + /// password prompt stops on SIGTTIN. Nil without a terminal in the + /// foreground, when it cannot start, or when a signal ends it. + static func runInForeground(_ executable: String, _ arguments: [String]) -> Int32? { + guard isatty(STDIN_FILENO) != 0, tcgetpgrp(STDIN_FILENO) == getpgrp() else { return nil } + var actions: posix_spawn_file_actions_t? + guard posix_spawn_file_actions_init(&actions) == 0 else { return nil } + defer { posix_spawn_file_actions_destroy(&actions) } + var attributes: posix_spawnattr_t? + guard posix_spawnattr_init(&attributes) == 0 else { return nil } + defer { posix_spawnattr_destroy(&attributes) } + // Only the terminal is inherited, not the CLI's other files or sockets. + guard posix_spawn_file_actions_addinherit_np(&actions, STDIN_FILENO) == 0, + posix_spawn_file_actions_addinherit_np(&actions, STDOUT_FILENO) == 0, + posix_spawn_file_actions_addinherit_np(&actions, STDERR_FILENO) == 0, + posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_CLOEXEC_DEFAULT)) == 0 else { return nil } + let strings = ([executable] + arguments).map { strdup($0) } + defer { strings.forEach { free($0) } } + guard strings.allSatisfy({ $0 != nil }) else { return nil } + var argv = strings + [nil] + var pid: pid_t = 0 + let spawned = argv.withUnsafeMutableBufferPointer { buffer in + posix_spawn(&pid, executable, &actions, &attributes, buffer.baseAddress!, environ) + } + guard spawned == 0 else { return nil } + var status: Int32 = 0 + while waitpid(pid, &status, 0) < 0 { + guard errno == EINTR else { return nil } + } + guard status & 0x7f == 0 else { return nil } + return (status >> 8) & 0xff + } + + // MARK: - Drives to offer + + /// The free space a drive needs to be offered: its floor (a tenth of the + /// drive, 50 to 100 GiB) plus the first Linux job and its images, the + /// least the add-on places on a disk. + static func minimumFreeBytes(volumeBytes: Int64) -> Int64 { + SandboxEligibility.freeSpaceFloor(volumeBytes: volumeBytes) + SandboxEligibility.linuxImagesBytes + + SandboxEligibility.linuxSlotBytes + } + + /// The drives setup offers when the owner gives no `--disk`: each volume + /// mounted at its own `/Volumes/` that shows in Finder, local, + /// writable and APFS, with room for a job. A drive with ownership off is + /// offered too: setup can turn it on. Sorted by name. + static func candidates(volumesDirectory: String = "/Volumes", + inspect: (String) -> Volume? = SandboxWorkDisk.volume(at:)) -> [Volume] { + let names = (try? FileManager.default.contentsOfDirectory(atPath: volumesDirectory)) ?? [] + return names.sorted().compactMap { name -> Volume? in + let mount = volumesDirectory + "/" + name + // The startup disk's link (`Macintosh HD` → `/`) has another mount point. + guard !name.hasPrefix("."), let found = inspect(mount), found.mountPoint == mount, found.local, + !found.readOnly, !found.hidden, found.fileSystem == "apfs", + found.freeBytes >= minimumFreeBytes(volumeBytes: found.volumeBytes) else { return nil } + return found } - let location = volume.mountPoint == path ? path : "\(path) (on \(volume.mountPoint))" - return SandboxEligibility.Check(level: .pass, name: "Work disk", detail: "\(location): APFS, ownership on") } /// `text` as one shell word, quoted only when it needs it. diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxStatusTests.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxStatusTests.swift index 22afbc9825..007b018a87 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxStatusTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxStatusTests.swift @@ -75,6 +75,30 @@ struct SandboxStatusTests { ]) } + @Test("status shows each work disk when the add-on uses an external drive, and what to do when one is offline") + func workDisks() throws { + let gib: Int64 = 1 << 30 + let disks = #""" + "disks":[{"cache":true,"detail":null,"floor_bytes":1,"free_bytes":\#(812 * gib),"images":[],"path":"/Volumes/FastSSD","reason":null,"root_volume":false,"slots":{"linux":{"free":2,"total":2},"macos":{"free":1,"total":1}},"state":"online","volume_bytes":1},{"cache":false,"detail":"plug the disk in; its slots take jobs again once it is back","floor_bytes":null,"free_bytes":null,"images":[],"path":"/Volumes/Other","reason":"missing","root_volume":false,"slots":{"linux":{"free":0,"total":1},"macos":{"free":0,"total":0}},"state":"offline","volume_bytes":null},{"path":"/System/Volumes/Data","root_volume":true,"state":"online","detail":"ignored while online"},{"state":"online"}], + """# + let status = SandboxFixtures.status(SandboxFixtures.ready.replacingOccurrences(of: #"{"accepting""#, + with: "{" + disks + #""accepting""#)) + #expect(status.supportsWorkDisks) + #expect(status.disks.count == 3) + #expect(status.disks.first == .init(path: "/Volumes/FastSSD", rootVolume: false, state: "online", detail: nil, + freeBytes: 812 * gib, linuxSlots: 2, macOSSlots: 1)) + let lines = SandboxStatusView.lines(status) + let images = try #require(lines.firstIndex(of: " Images: Linux installed, macOS installed")) + #expect(Array(lines[(images + 1)...(images + 3)]) == [ + " Work disk: /Volumes/FastSSD: online, 812 GiB free; slots: Linux 2, macOS 1", + " Work disk: /Volumes/Other: offline; slots: Linux 1 (plug the disk in; its slots take jobs again once it is back)", + " Work disk: /System/Volumes/Data (internal): online", + ]) + let internalOnly = #"{"disks":[{"path":"/System/Volumes/Data","root_volume":true,"state":"online"}],"accepting""# + #expect(SandboxStatusView.lines(SandboxFixtures.status(SandboxFixtures.ready.replacingOccurrences( + of: #"{"accepting""#, with: internalOnly))).allSatisfy { !$0.contains("Work disk") }) + } + @Test("each state says what it means for inference, or the add-on's own detail, and what to run next") func states() { func screen(_ json: String) -> [String] { SandboxStatusView.lines(SandboxFixtures.status(json)) } diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift index b60e9e7201..4ab68110e0 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxWorkDiskTests.swift @@ -88,6 +88,72 @@ struct SandboxWorkDiskTests { let unplugged = SandboxWorkDisk.check(path: "/Volumes/FastSSD/sandbox", volume: home) #expect(unplugged.level == .fail && unplugged.detail == "/Volumes/FastSSD is not a mounted drive") #expect(SandboxWorkDisk.check(path: "/Volumes/FastSSD", volume: nil).level == .fail) + #expect(SandboxWorkDisk.problem(path: "/Volumes/FastSSD", volume: Self.ready) == nil) + #expect(SandboxWorkDisk.problem(path: "/Volumes/FastSSD", volume: Self.ownershipOff) == .ownershipOff) + #expect(SandboxWorkDisk.problem(path: "/Volumes/FastSSD", volume: exFAT) == .notAPFS) + #expect(SandboxWorkDisk.problem(path: "/Volumes/FastSSD", volume: nil) == .unreadable) + // Another drive that ignores ownership, under the path of one that is unplugged: not mounted comes first. + let other = SandboxWorkDisk.Volume(mountPoint: "/Volumes/Other", fileSystem: "apfs", ignoresOwnership: true) + #expect(SandboxWorkDisk.problem(path: "/Volumes/FastSSD", volume: other) == .notMounted("/Volumes/FastSSD")) + } + + @Test("setup offers only drives mounted at their own /Volumes/, shown in Finder, local, writable, APFS and with room") + func candidates() throws { + let volumes = FileManager.default.temporaryDirectory.appendingPathComponent("volumes-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: volumes) } + let names = ["Zed", "Fast", "Startup", "Share", "Locked", "Backup", "Stick", "Small", ".hidden", "Owners"] + for name in names { + try FileManager.default.createDirectory(at: volumes.appendingPathComponent(name), + withIntermediateDirectories: true) + } + let root = volumes.path + let roomy = SandboxWorkDisk.Volume(mountPoint: "", fileSystem: "apfs", ignoresOwnership: false, + freeBytes: 900 << 30, volumeBytes: 2_000 << 30) + func at(_ name: String, _ change: (inout SandboxWorkDisk.Volume) -> Void = { _ in }) -> SandboxWorkDisk.Volume { + var volume = roomy + volume.mountPoint = root + "/" + name + change(&volume) + return volume + } + let byName: [String: SandboxWorkDisk.Volume] = [ + "Zed": at("Zed"), "Fast": at("Fast"), + // The startup disk's link: another mount point. + "Startup": at("Startup") { $0.mountPoint = "/" }, + "Share": at("Share") { $0.local = false }, + "Locked": at("Locked") { $0.readOnly = true }, + "Backup": at("Backup") { $0.hidden = true }, + "Stick": at("Stick") { $0.fileSystem = "exfat" }, + // A 2 TB drive keeps 100 GiB free and needs 34 GiB for a Linux job and its images. + "Small": at("Small") { $0.freeBytes = 133 << 30 }, + ".hidden": at(".hidden"), + "Owners": at("Owners") { $0.ignoresOwnership = true; $0.freeBytes = 134 << 30 }, + ] + let offered = SandboxWorkDisk.candidates(volumesDirectory: root) { path in + byName[(path as NSString).lastPathComponent] + } + #expect(offered.map(\.mountPoint) == ["Fast", "Owners", "Zed"].map { root + "/" + $0 }) + #expect(SandboxWorkDisk.minimumFreeBytes(volumeBytes: 2_000 << 30) == 134 << 30) + #expect(SandboxWorkDisk.candidates(volumesDirectory: root + "/missing") { _ in roomy }.isEmpty) + } + + @Test("the drive choice: Enter or the end of input is 1, and setup asks again until it gets a number in range") + func choose() { + var answers: [String?] = ["4", "two", "0", " 3 "] + var prompts: [String] = [] + #expect(SandboxTerminal.choose(count: 3, readInput: { answers.removeFirst() }, emit: { prompts.append($0) }) == 3) + #expect(prompts == Array(repeating: "Choose 1-3 [1]: ", count: 4)) + #expect(SandboxTerminal.choose(count: 3, readInput: { "" }, emit: { _ in }) == 1) + #expect(SandboxTerminal.choose(count: 3, readInput: { nil }, emit: { _ in }) == 1) + } + + @Test("without a terminal in the foreground, setup runs no command for the owner") + func foregroundNeedsTerminal() async throws { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + try replaceStandardInput(with: "") + print("status \(SandboxWorkDisk.runInForeground("/usr/bin/true", []).map { "\($0)" } ?? "none")") + print("enabled \(SandboxWorkDisk.enableOwnership(mountPoint: "/Volumes/FastSSD"))") + } + #expect(decodedText(result.standardOutputContent) == "status none\nenabled false\n") } @Test("statfs: the temporary directory's volume, and a drive that is not there") @@ -116,7 +182,7 @@ struct SandboxWorkDiskTests { // MARK: - Setup static let statusWithDisks = SandboxFixtures.ready.replacingOccurrences( - of: #"{"accepting""#, with: #"{"disks":[{"path":"/System/Volumes/Data","state":"online"}],"accepting""#) + of: #"{"accepting""#, with: #"{"disks":[{"path":"/System/Volumes/Data","root_volume":true,"state":"online"}],"accepting""#) @Test("ownership off: setup prints the one-line diskutil command and stops before downloading anything") func ownershipOff() async throws { @@ -133,8 +199,7 @@ struct SandboxWorkDiskTests { } #expect(decodedText(result.standardOutputContent).hasSuffix(""" [PASS] Sleep: off on the power adapter - [FAIL] Work disk: /Volumes/FastSSD ignores file ownership; turning it on needs an administrator, so \ - run this yourself, then run setup again + [FAIL] Work disk: /Volumes/FastSSD ignores file ownership; turning it on needs an administrator ↳ fix: \(Self.enableOwnership) A work disk is not ready: follow the fix above, then run setup again. Nothing changed. @@ -252,6 +317,100 @@ struct SandboxWorkDiskTests { #expect(output.hasSuffix("== INSTALL\n--json-progress\n--yes\n--disk\n/Volumes/FastSSD\n")) } + @Test("at a prompt without --disk, setup lists the drives, and the one chosen goes to the plan") + func chooseDrive() async throws { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + plan: [Self.externalPlan], workDisks: true).utf8))]) + try replaceStandardInput(with: "2\nn\n") + var offered = Self.ownershipOff + offered.freeBytes = 900 << 30 + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid"), + confirmed: false, addon: .live(), interactiveInput: true, terminal: false, color: false, + probe: { _ in .mac(cores: 16, memoryGiB: 128) }, workDiskVolume: { _ in Self.ready }, + workDiskCandidates: { [offered] in [offered] }).run() + print("== PLAN") + print(try String(contentsOf: sandbox.sandboxAddonRoot.appendingPathComponent("plan-arguments"), + encoding: .utf8), terminator: "") + let installed = sandbox.sandboxAddonRoot.appendingPathComponent("installer-arguments") + print("installed \(FileManager.default.fileExists(atPath: installed.path))") + } + let output = decodedText(result.standardOutputContent) + #expect(output.contains(""" + Where the VM images and jobs go + 1) This Mac's internal disk + 2) /Volumes/FastSSD: 900 GiB free; ownership is off, setup can turn it on + Use an external drive only if it is a Thunderbolt or USB4 NVMe SSD that stays connected: a job on a \ + drive that goes away is stopped and not paid. + Choose 1-2 [1]:\u{20} + Checking the work disks + [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on + + The add-on's plan for this Mac + [PASS] CPU: 16 cores; you keep 4 + + """)) + #expect(output.hasSuffix("Set up Darkbloom Sandbox on this Mac? [y/N]: Nothing changed.\n== PLAN\n" + + "--plan\n--json-progress\n--disk\n/Volumes/FastSSD\ninstalled false\n")) + } + + @Test("ownership off at a prompt: setup offers the command, runs it when the owner agrees, and checks again") + func turnOwnershipOn() async throws { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + plan: [Self.externalPlan], workDisks: true).utf8))]) + try replaceStandardInput(with: "y\nn\n") + let marker = sandbox.sandboxAddonRoot.deletingLastPathComponent().appendingPathComponent("ownership").path + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid", disks: ["/Volumes/FastSSD"]), + confirmed: false, addon: .live(), interactiveInput: true, terminal: false, color: false, + probe: { _ in .mac(cores: 16, memoryGiB: 128) }, + workDiskVolume: { _ in FileManager.default.fileExists(atPath: marker) ? Self.ready : Self.ownershipOff }, + workDiskCandidates: { [] }, + enableOwnership: { FileManager.default.createFile(atPath: marker, contents: Data($0.utf8)) }).run() + let enabled = try String(contentsOfFile: marker, encoding: .utf8) + print("enabled on \(enabled)") + } + let output = decodedText(result.standardOutputContent) + #expect(output.contains(""" + [FAIL] Work disk: /Volumes/FastSSD ignores file ownership; turning it on needs an administrator + ↳ fix: \(Self.enableOwnership) + Turn ownership on for /Volumes/FastSSD now? Setup runs the command above; sudo asks for your password. \ + [y/N]: [PASS] Work disk: /Volumes/FastSSD: APFS, ownership on + [PASS] CPU: 16 cores; you keep 4 + + """)) + #expect(output.hasSuffix("Nothing changed.\nenabled on /Volumes/FastSSD\n")) + } + + @Test("ownership still off after the command: setup stops before downloading anything") + func ownershipStillOff() async throws { + let result = try await #require(processExitsWith: .failure, observing: [\.standardOutputContent]) { + _ = try CLICommandSandbox.enter(autoRestart: false) + try replaceStandardInput(with: "y\n") + await exitWithCommandStatus { + defer { print("requests \(CoordinatorStub.requests.count)") } + try await SandboxSetupFlow( + options: SandboxSetupOptions(server: "https://sandbox.invalid", disks: ["/Volumes/FastSSD"]), + confirmed: false, addon: .live(), interactiveInput: true, terminal: false, color: false, + probe: { _ in .mac(cores: 16, memoryGiB: 128) }, workDiskVolume: { _ in Self.ownershipOff }, + enableOwnership: { _ in false }).run() + } + } + #expect(decodedText(result.standardOutputContent).hasSuffix(""" + [y/N]: Ownership is still off on /Volumes/FastSSD. + + A work disk is not ready: follow the fix above, then run setup again. Nothing changed. + requests 0 + + """)) + } + @Test("a set-up Mac offers --disk only when its add-on takes it") func hint() async throws { let diskHint = "To put the VM images and jobs on an external drive: darkbloom sandbox setup --disk /Volumes/" From 98ed5674728bebb48d3084e4aab7f3a2e00c9742 Mon Sep 17 00:00:00 2001 From: David Tai <8346495+davidtai@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:23:37 -0600 Subject: [PATCH 5/5] Sandbox setup work disks: refactor pass (one statfs per drive check, one unreadable line) - checkWorkDisks reads each drive's volume once and gives it to both the Work disk check and the ownership offer; it read the volume twice before the offer. - SandboxWorkDisk.check builds the "cannot be read" refusal once for the nil volume and the unreadable problem, so the two cannot drift. - The type's comment says the drive check runs before setup installs anything: a drive picked from the list is checked after install.sh is downloaded. No change to output, flags or the add-on contract. Co-Authored-By: Claude Opus 5.5 --- .../darkbloom/Sandbox/SandboxSetupCommand.swift | 13 +++++++------ .../Sources/darkbloom/Sandbox/SandboxWorkDisk.swift | 9 ++++----- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift index e22496b781..6c3332801b 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift @@ -297,10 +297,11 @@ struct SandboxSetupFlow { private func checkWorkDisks(_ disks: [String]) throws { var ready = true for path in disks { - let check = SandboxWorkDisk.check(path: path, volume: workDiskVolume(path)) + let volume = workDiskVolume(path) + let check = SandboxWorkDisk.check(path: path, volume: volume) printChecks([check]) guard check.level == .fail else { continue } - if let mount = ownershipToTurnOn(path), turnOnOwnership(mount) { + if let mount = ownershipToTurnOn(path, on: volume), turnOnOwnership(mount) { let again = SandboxWorkDisk.check(path: path, volume: workDiskVolume(path)) printChecks([again]) if again.level != .fail { continue } @@ -314,10 +315,10 @@ struct SandboxSetupFlow { throw ExitCode.failure } - /// The mount point of the drive at `path` when its one problem is - /// ownership off and there is a prompt to offer the fix at. - private func ownershipToTurnOn(_ path: String) -> String? { - guard !confirmed, interactiveInput, let volume = workDiskVolume(path), + /// The mount point of the drive at `path` (on `volume`) when its one + /// problem is ownership off and there is a prompt to offer the fix at. + private func ownershipToTurnOn(_ path: String, on volume: SandboxWorkDisk.Volume?) -> String? { + guard !confirmed, interactiveInput, let volume, SandboxWorkDisk.problem(path: path, volume: volume) == .ownershipOff else { return nil } return volume.mountPoint } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift index aae5db04fe..aac16f5905 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxWorkDisk.swift @@ -3,7 +3,7 @@ import Foundation /// A drive for the add-on's VM images and jobs (`setup --disk`, or the drive /// the owner picks in setup). Setup checks the two things an owner must set up -/// by hand, APFS and ownership, before it downloads anything; the installer +/// by hand, APFS and ownership, before it installs anything; the installer /// checks each disk again by the add-on's full rules before it writes anything. enum SandboxWorkDisk { /// The first add-on release whose installer takes `--disk`. @@ -88,12 +88,11 @@ enum SandboxWorkDisk { func refuse(_ detail: String, fix: String) -> SandboxEligibility.Check { SandboxEligibility.Check(level: .fail, name: "Work disk", detail: detail, fix: fix) } - guard let volume else { - return refuse("\(path) cannot be read", fix: "check the path, then run setup again") - } + let unreadable = refuse("\(path) cannot be read", fix: "check the path, then run setup again") + guard let volume else { return unreadable } switch problem(path: path, volume: volume) { case .unreadable: - return refuse("\(path) cannot be read", fix: "check the path, then run setup again") + return unreadable case .notMounted(let mount): return refuse("\(mount) is not a mounted drive", fix: "connect the drive and check that it shows in Finder, then run setup again")