diff --git a/docs/CLI.md b/docs/CLI.md index 41417ab5f..4d4c298b2 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1388,9 +1388,11 @@ Entries are ordered by platform, then version, then variant. have not been deleted. Simlock does not track which variant a device uses, so two variants of one version show the same count. - `foreignDevices` counts the devices outside Simlock that use the - component: simulators in Xcode's default device set, or AVDs in your own - AVD home (`ANDROID_AVD_HOME`, or `~/.android/avd`). Simlock only reads - them. + component. On iOS that is the simulators in Xcode's default device set + that have been booted at least once; macOS creates a set of simulators for + every runtime it installs, and those do not count until someone uses one. + On Android it is every AVD in your own AVD home (`ANDROID_AVD_HOME`, or + `~/.android/avd`). Simlock only reads them. A platform whose tools cannot answer is left out, and the other platform is still listed. A gateway answers `UNSUPPORTED_IN_GATEWAY_MODE`; run the @@ -1434,26 +1436,33 @@ every one of them and removes nothing. way, is never removed, and there is no flag to force it. - **No device uses it.** None of Simlock's own devices of that platform and version, in any state, leased ones included, and none of yours: a - simulator in Xcode's default device set or an AVD in your own AVD home, - booted or not. Otherwise it fails with `COMPONENT_IN_USE` (exit 12), and - the error says how many of each use it. Delete those devices first. + simulator in Xcode's default device set that has been booted at least + once, running now or not, or any AVD in your own AVD home. Otherwise it + fails with `COMPONENT_IN_USE` (exit 12), and the error says how many of + each use it. Delete those devices first. Simulators in the default device + set that were never booted do not block a removal. - **Nothing else is installing or removing on that platform.** Otherwise it fails with `COMPONENT_BUSY` (exit 11). Run it again once that ends. A `component install` or lease download that arrives while a removal runs waits for it, and no new Simlock device is created on the component being removed: a lease request for it fails with `RUNTIME_MISSING`. -An iOS runtime is removed with `simctl runtime delete`. macOS can keep the -runtime's download in its own asset store afterwards. When it does, the -result carries `residue`, a sentence that says so and how to get the space -back: remove the platform in Xcode's Settings, under Platforms. Simlock never -deletes files there itself. An Android image is removed with -`sdkmanager --uninstall`. +An iOS runtime is removed with `simctl runtime delete`. Two things can stay +behind, and the result's `residue` names each one that did: + +- The never-booted simulators of that runtime in Xcode's default device set. + They become unavailable, and Simlock does not delete them. `residue` says + how many there are; `xcrun simctl delete unavailable` clears them. +- The runtime's download in macOS's own asset store. `residue` says so and + how to get the space back: remove the platform in Xcode's Settings, under + Platforms. Simlock never deletes files there itself. ```text -{"platform":"ios","version":"26.4","outcome":"removed","sizeBytes":9103456789,"residue":"The download of iOS 26.4 (23E244) ..."} +{"platform":"ios","version":"26.4","outcome":"removed","sizeBytes":9103456789,"residue":"11 never-used simulators in the default device set are now unavailable; ... The download of iOS 26.4 (23E244) ..."} ``` +An Android image is removed with `sdkmanager --uninstall`. + Every removal emits `component.removed`, naming the component and who asked; see [EVENTS.md](EVENTS.md#components). Nothing removes a component on its own: no cleanup rule, idle timer or low-disk reaction does. Stopping the diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 682d2f9e1..9e2cee40a 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -378,8 +378,10 @@ const { components } = await client.listComponents({ platform: "android" }); - `devices` counts Simlock's own devices of this platform and version that have not been deleted; two variants of one version show the same count. `foreignDevices` counts the devices outside Simlock that use the - component: simulators in Xcode's default device set, AVDs in the user's - own AVD home. + component: simulators in Xcode's default device set that have been booted + at least once, and every AVD in the user's own AVD home. The simulators + macOS creates by itself for each runtime it installs do not count until + someone boots one. - A gateway rejects it with `UNSUPPORTED_IN_GATEWAY_MODE`. ## Removing a runtime: `removeComponent` @@ -398,13 +400,17 @@ const result = await admin.removeComponent({ platform: "ios", version: "26.4" }) - `outcome` is `removed`, or `would-remove` for a dry run. `sizeBytes` is absent when it could not be read. The catalog stops listing the component at once. -- `residue`, when present, says what stayed on disk and how to reclaim it: - on iOS, macOS can keep the runtime's download in its asset store, which - Xcode's Settings, under Platforms, removes. +- `residue`, when present, says what stayed behind and how to reclaim it. + On iOS that can be the runtime's never-booted simulators in Xcode's + default device set, now unavailable, which `xcrun simctl delete + unavailable` clears, and the runtime's download in macOS's asset store, + which Xcode's Settings, under Platforms, removes. Simlock deletes + neither. - It rejects, removing nothing, with `COMPONENT_NOT_OWNED` when Simlock did not install the component or it changed on disk since, `COMPONENT_IN_USE` when a device uses it, Simlock's or not (`details` - carries `devices` and `foreignDevices`), and `COMPONENT_BUSY` while an + carries `devices` and `foreignDevices`; a never-booted simulator in the + default device set does not count), and `COMPONENT_BUSY` while an install or removal runs or waits on that platform. Other rejections: `FORBIDDEN` for an agent session, `NO_DRIVER`, and `UNSUPPORTED_IN_GATEWAY_MODE` from a gateway. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 07e4728c7..46f2c5bfe 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -829,7 +829,9 @@ still the same one on disk, and `installedAt` is when it did. `devices` counts Simlock's own devices of this platform and version that have not been deleted; two variants of one version show the same count. `foreignDevices` counts the devices outside Simlock that use the component: simulators in -Xcode's default device set, AVDs in the user's own AVD home. +Xcode's default device set that have been booted at least once, and every +AVD in the user's own AVD home. The simulators macOS creates by itself for +each runtime it installs do not count until someone boots one. A platform whose tools cannot answer is left out. `400 BAD_REQUEST` for a `platform` other than `ios` or `android`; `501 UNSUPPORTED_IN_GATEWAY_MODE` @@ -855,9 +857,12 @@ The answer is one JSON body, not a stream: `outcome` is `removed`, or `would-remove` for a dry run. `sizeBytes` is the disk the component took, left out when it could not be read. `residue` -appears when something stayed on disk after the removal: on iOS, macOS can -keep the runtime's download in its own asset store, and `residue` says so and -how to reclaim it (remove the platform in Xcode's Settings, under Platforms). +appears when something stayed behind after the removal, and names each +thing. On iOS that is the runtime's never-booted simulators in Xcode's +default device set, which become unavailable (`residue` says how many, and +that `xcrun simctl delete unavailable` clears them), and the runtime's +download when macOS keeps it in its own asset store (remove the platform in +Xcode's Settings, under Platforms). Simlock deletes neither. A removed component leaves `GET /v1/catalog` and `GET /v1/components` at once, and the removal is reported as a `component.removed` event naming who asked. @@ -869,7 +874,8 @@ platform. Each refusal removes nothing: disk since. There is no way to force it. - `409 COMPONENT_IN_USE` — a device uses it: one of Simlock's, in any state, leased ones included, or one outside Simlock (a simulator in Xcode's - default device set, an AVD in the user's own AVD home). The body carries + default device set that has been booted at least once, an AVD in the + user's own AVD home). Never-booted simulators do not block it. The body carries `devices` and `foreignDevices`, how many of each. - `409 COMPONENT_BUSY` — an install or removal runs or waits on that platform; try again once it ends. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 0da668d2a..1dfc5fa6d 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1504,6 +1504,10 @@ read-only, never downloads, and every process it starts is bounded, like `listCatalog`. iOS reads `simctl runtime list -j` (iOS images only) and counts devices per runtime in the default device set with an unscoped `simctl list -j devices`, the one unscoped call besides the pre-root path's. +One function, `devicesPerRuntime`, decides which of them count for the +listing and the removal alike: only a device whose entry carries +`lastUsedAt`, so the never-used simulators macOS creates for every installed +runtime do not block a removal (#241). Android reads the installed images, sizes each directory with `Filesystem.directorySize`, and counts AVDs in the user's own AVD home whose `config.ini` names the image's directory. On both platforms a foreign-device @@ -1573,8 +1577,11 @@ steps run through `runBoundedProcess` (`src/drivers/installer-process.ts`), which ends the process `SIGTERM` then `SIGKILL` and answers only once it has exited. iOS runs `simctl --set runtime delete ` without `--keep-asset` (the `--set` from `#scopedSimctlArgv`, like every scoped call), -then reads the asset store (#79) and reports `residue` when the build's -download is still there; `simlock simctl runtime delete` stays refused and +then reports `residue`: how many never-used default-set simulators of the +runtime, counted in the listing taken before the delete, are now unavailable +(Simlock deletes none of them; `xcrun simctl delete unavailable` does), and, +after reading the asset store (#79), that the build's download is still +there, each when it applies; `simlock simctl runtime delete` stays refused and points at `simlock component remove`. Android runs `sdkmanager --uninstall `. A second Simlock instance's devices and a foreign device created after the driver's diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 802a18610..314b2e27d 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -103,8 +103,9 @@ emits it after the driver's `removeComponent` returned and the component record from the registry (events rule 3); a dry run, a refusal (`COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `COMPONENT_BUSY`) and a driver failure emit nothing, and a failure keeps the record. `requesterId` is the admin session's principal, never a caller-supplied id (safety rule -6). `residue` is the driver's sentence, carried unread: on iOS it names the asset-store download -`simctl runtime delete` left behind (#79). +6). `residue` is the driver's text, carried unread: on iOS it names the never-used default-set +simulators the removal left unavailable and the asset-store download `simctl runtime delete` +left behind (#79), each when there is one. ## System diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index 33780ef5e..2c267c891 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -364,6 +364,12 @@ build, its version) is still there, the result and `component.removed` carry way to reclaim it. The removal itself succeeded either way, and Simlock still never deletes a file in the store (ADR 0010 §8). +**Measured:** on Xcode 26.4.1 (macOS 26.6.1), on 2026-10-02, `simctl runtime +delete` of the iOS 18.6 runtime, without `--keep-asset`, unregistered it — it +left `simctl runtime list` — and left its download in the store: the 8.9 GB +asset was still there two minutes after the delete. So `residue` is the +expected result of an iOS removal on that Xcode, not an edge case. + **The knob:** `downloads.policy` decides whether the host downloads runtimes at all; short of that, the reclaim is manual and periodic, driven by what `doctor` and `component remove` report. @@ -373,10 +379,18 @@ at all; short of that, the reclaim is manual and periodic, driven by what `simlock component remove` refuses while a device uses the component: every device in this instance's registry, in any state but `deleted` (and every device being provisioned that has no record yet), plus the devices the driver -counts outside Simlock — simulators in the machine's default device set, -AVDs in the user's own AVD home. +counts outside Simlock — simulators in the machine's default device set +that have been used at least once, AVDs in the user's own AVD home. + +**The pitfall:** three kinds of device are not counted. -**The pitfall:** two kinds of device are not counted. +- A **never-used simulator in the default device set** — one with no + `lastUsedAt` in `simctl list -j devices`. macOS creates about eleven of + them for every runtime it installs, so counting them would make every + runtime unremovable (#241). A simulator the user created by hand and has + not booted yet looks the same and is not counted either. The removal makes + it unavailable; Simlock does not delete it, and `residue` says how many + there are and that `xcrun simctl delete unavailable` clears them. - A **second Simlock instance** on the same machine keeps its devices in its own root, which this instance cannot see and must not read. Removing a @@ -386,13 +400,17 @@ AVDs in the user's own AVD home. once in the removal's checks and once more in the driver, just before the platform's own removal. A simulator or AVD the user creates between that count and the end of `simctl runtime delete` / `sdkmanager --uninstall` is - not seen. A new *Simlock* device cannot slip in the same way: the removal + not seen, and neither is a never-used simulator the user boots for the + first time in that window. A new *Simlock* device cannot slip in the same way: the removal marks the component inside the decision gate, and `DeviceProvisioner` refuses every device on a marked component until the removal settles. -**Why it is accepted:** both need knowledge Simlock does not have without -reaching outside what it owns. The ADR accepts them (Consequences, and §8's -"a foreign device created after the driver's last count is not seen"), and +**Why it is accepted:** the second and third need knowledge Simlock does not +have without reaching outside what it owns, and the first is the only rule +under which a runtime Simlock installed can be removed at all; a never-used +simulator holds no user data, and becoming unavailable loses nothing. The ADR +accepts them (Consequences, and §8's rule on unused simulators and "a +foreign device created after the driver's last count is not seen"), and removal is never automatic: an operator runs it, after reading `simlock component list`. diff --git a/docs/internal/adr/0010-components-have-one-owner-in-the-core.md b/docs/internal/adr/0010-components-have-one-owner-in-the-core.md index 441012bf0..cdf2f66f9 100644 --- a/docs/internal/adr/0010-components-have-one-owner-in-the-core.md +++ b/docs/internal/adr/0010-components-have-one-owner-in-the-core.md @@ -14,6 +14,11 @@ `--allow-download` does nothing through a gateway "until the downloads feature is specified" becomes permanent (§7). Changes safety rules 1 and 4; each changes in the task that makes its new text true (§4, §8). +- **Amended:** §8 by + [#241](https://github.com/callstackincubator/simlock/issues/241), before + it was implemented, on the maintainer's decision: a foreign device counts + as a user when the driver says it is one, and never-used iOS simulators do + not. - **Depends on:** ADR 0003 (the contract), ADR 0005 (the gateway), ADR 0008 (the catalog). @@ -212,12 +217,22 @@ Counting foreign devices is the only place a driver looks at devices that are not Simlock's: the platform's default device set on iOS, the user's own AVD home on Android. It reads them and never writes there. +A foreign device counts as a user when the driver says it is one. On Android +that is every AVD in the user's AVD home. On iOS it is a simulator in the +default set that has been used at least once: when a runtime install ends, +macOS creates a batch of unused simulators for it by itself, and counting +them would make every runtime Simlock installs unremovable ([#241](https://github.com/callstackincubator/simlock/issues/241)). +One driver function decides this for the listing and the removal alike. +The unused simulators are left in place: removing the runtime makes them +unavailable, and the result reports how many there are and how to clear +them. Simlock deletes none of them. + `component.remove` is an admin operation. It removes a component only when all of these hold: - it is Simlock's (§5); - no device Simlock can see uses it: none of its own in any state but - `deleted`, and no foreign one, booted or not; + `deleted`, and no foreign one the driver counts as a user, running or not; - no install is running or waiting on that platform. The check and the removal cannot be split by a new Simlock device. The installer @@ -228,8 +243,8 @@ device created after the driver's last count is not seen. The driver gains `removeComponent(receipt)`. It proves the receipt again, counts foreign devices again, removes, and verifies. When something stays on -disk it says so: an iOS runtime's download can outlive `simctl runtime -delete` (#79). Simlock asks `simctl` to delete the runtime and reports what +disk it says so: an iOS runtime's unused simulators, now unavailable, and its +download, which can outlive `simctl runtime delete` (#79). Simlock asks `simctl` to delete the runtime and reports what `simctl` left; it never deletes a file in the macOS asset store itself. A dry run does every check a removal does and removes nothing. The CLI confirms or requires diff --git a/docs/internal/agent-rules/safety.md b/docs/internal/agent-rules/safety.md index 7fcce79a2..7a3322823 100644 --- a/docs/internal/agent-rules/safety.md +++ b/docs/internal/agent-rules/safety.md @@ -14,12 +14,16 @@ never enforce them only inside an individual rule or driver. admin's explicit `component.remove`, and only when a component record's receipt equals the receipt of what is installed now ([ADR 0010](../adr/0010-components-have-one-owner-in-the-core.md) §5, §8). - It is never removed while any device uses it, Simlock's own in any state - but `deleted` or a foreign one, booted or not; and nothing removes one on - its own — no cleanup rule, idle tier or disk-pressure reaction. To count - foreign devices a driver may read the platform's default device locations - (the machine's default simulator set, the user's own AVD home), and never - writes there. Simlock never deletes a file in the macOS asset store: it + It is never removed while any device uses it: Simlock's own in any state + but `deleted`, or a foreign one the driver counts as a user, running or + not. On iOS a foreign user is a simulator that has been used at least + once, because macOS creates unused ones by itself for every installed + runtime; on Android every AVD in the user's AVD home is one. Unused + simulators are left in place, and the removal reports them. Nothing + removes a component on its own — no cleanup rule, idle tier or + disk-pressure reaction. To count foreign devices a driver may read the + platform's default device locations (the machine's default simulator set, + the user's own AVD home), and never writes there. Simlock never deletes a file in the macOS asset store: it asks `simctl` to delete the runtime and reports what `simctl` left. There is exactly one exception, and it is opt-in: `doctor --purge-orphans` diff --git a/src/core/driver.ts b/src/core/driver.ts index db5429a8e..6b5d44c83 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -524,7 +524,9 @@ export interface InstalledComponent { * `findComponent` and `installComponent` use, so a listed component and the record of its install * compare equal with `sameReceipt`. `variant` is the driver's own words for what tells two * components of one version apart, carried unread. `sizeBytes` is absent when the driver could - * not read it. `foreignDevices` counts the devices outside Simlock's root that use it. + * not read it. `foreignDevices` is the number of devices outside Simlock's root that count as + * users of it; the driver decides what counts as a user, and a removal is refused while it is + * above zero. */ export interface DriverComponent extends InstalledComponent { readonly variant?: string; @@ -543,8 +545,8 @@ export interface ComponentInstallResult extends InstalledComponent { /** * What one `removeComponent` freed and left. `sizeBytes` is the component's size as listed just - * before it was removed, absent when the driver could not read it. `residue` is a sentence for - * the operator when something stays on disk after the removal, and how to reclaim it. + * before it was removed, absent when the driver could not read it. `residue` is one sentence or + * more for the operator when something stays on disk after the removal, and how to reclaim it. */ export interface ComponentRemoval { readonly sizeBytes?: number; diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 1f34ecfd4..5b07af8ba 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -2875,6 +2875,22 @@ describe("AndroidDriver listComponents()", () => { ]); }); + it("counts every AVD in the user's AVD home that names the image, booted before or never (#241)", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + const sysdir = "system-images/android-35/google_apis/arm64-v8a/"; + // Never booted: only what avdmanager writes. + await userAvd(filesystem, "Fresh", sysdir); + // Booted: the emulator has written its disk image and hardware config beside config.ini. + await userAvd(filesystem, "Booted", sysdir); + await filesystem.writeFileAtomic(`${userAvdHome}/Booted.avd/userdata-qemu.img`, "data"); + await filesystem.writeFileAtomic(`${userAvdHome}/Booted.avd/hardware-qemu.ini`, "hw\n"); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + const listed = await driver.listComponents(); + + expect(listed.map(({ foreignDevices }) => foreignDevices)).toEqual([2]); + }); + it("finds an AVD beside a pointer file with an empty path, counts nothing for an AVD whose directory is gone, and still lists the image", async () => { const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); const sysdir = "system-images/android-35/google_apis/arm64-v8a/"; diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 5722a2679..3c67ad0cc 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -3199,17 +3199,41 @@ describe("IosSimctlDriver listComponents()", () => { return { match: runtimeListInvocation, result: { code: 0, stderr: "", stdout } }; } - function defaultSetListed(devices: Readonly>) { + /** + * The default set's devices per runtime: a number is that many used devices, or name both + * kinds. A used device carries `lastUsedAt`, as `simctl list -j devices` reports one that has + * been booted; an unused one -- like the batch CoreSimulator creates when a runtime install + * ends -- carries every other key a real entry has and no `lastUsedAt`. + */ + function defaultSetListed( + devices: Readonly< + Record + >, + ) { + const entry = (runtime: string, index: number, used: boolean) => ({ + dataPath: `/Users/me/Library/Developer/CoreSimulator/Devices/${runtime}-${String(index)}/data`, + dataPathSize: used ? 1_500_000_000 : 18_000_000, + deviceTypeIdentifier: "com.apple.CoreSimulator.SimDeviceType.iPhone-16", + isAvailable: true, + ...(used ? { lastUsedAt: "2026-10-01T12:00:00Z" } : {}), + logPath: `/Users/me/Library/Logs/CoreSimulator/${runtime}-${String(index)}`, + logPathSize: 4096, + name: `user-${String(index)}`, + state: "Shutdown", + udid: `USER-${runtime}-${String(index)}`, + }); const stdout = JSON.stringify({ devices: Object.fromEntries( - Object.entries(devices).map(([runtime, count]) => [ - runtime, - Array.from({ length: count }, (_, index) => ({ - name: `user-${String(index)}`, - state: "Shutdown", - udid: `USER-${runtime}-${String(index)}`, - })), - ]), + Object.entries(devices).map(([runtime, counts]) => { + const { unused = 0, used = 0 } = typeof counts === "number" ? { used: counts } : counts; + return [ + runtime, + [ + ...Array.from({ length: used }, (_, index) => entry(runtime, index, true)), + ...Array.from({ length: unused }, (_, index) => entry(runtime, used + index, false)), + ], + ]; + }), ), }); return { match: defaultSetInvocation, result: { code: 0, stderr: "", stdout } }; @@ -3247,7 +3271,7 @@ describe("IosSimctlDriver listComponents()", () => { ]); }); - it("counts a device in the default device set that uses an image's runtime as foreign, and reads no device in Simlock's own set for it", async () => { + it("counts a device in the default device set that has lastUsedAt and uses an image's runtime as foreign, and reads no device in Simlock's own set for it", async () => { const used = image("18.4", "22E238"); const unused = image("26.0", "23A343"); // The scripted runner refuses any call it was not given, so a `simctl --set list` @@ -3270,6 +3294,43 @@ describe("IosSimctlDriver listComponents()", () => { ]); }); + it("does not count a device in the default device set without lastUsedAt, such as the ones macOS creates when a runtime install ends (#241)", async () => { + const fresh = image("18.6", "22G86"); + const runner = new ScriptedProcessRunner([ + imagesListed([fresh]), + // What a runtime install leaves on Xcode 26.4.1: about eleven never-booted simulators of + // it. One more the user has booted is the only one that counts. + defaultSetListed({ [fresh.runtime]: { unused: 11, used: 1 } }), + ]); + const driver = await createDriver(runner); + + const listed = await driver.listComponents(); + + expect(listed.map(({ foreignDevices }) => foreignDevices)).toEqual([1]); + }); + + it("counts a default-set entry that is not a device object as a user, so an unreadable entry never unblocks a removal (#241)", async () => { + const fresh = image("18.6", "22G86"); + const runner = new ScriptedProcessRunner([ + imagesListed([fresh]), + { + match: defaultSetInvocation, + result: { + code: 0, + stderr: "", + stdout: JSON.stringify({ + devices: { [fresh.runtime]: ["garbled", null, { name: "fresh", udid: "U-1" }] }, + }), + }, + }, + ]); + const driver = await createDriver(runner); + + const listed = await driver.listComponents(); + + expect(listed.map(({ foreignDevices }) => foreignDevices)).toEqual([2]); + }); + it("lists a runtime with the receipt installComponent returned for it, and runs no installer to list", async () => { const before = [ { build: "22E238", id: "IMG-184", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-18-4" }, @@ -3430,13 +3491,14 @@ describe("IosSimctlDriver listComponents()", () => { return filesystem; } - it("deletes the image the receipt names with simctl runtime delete and no --keep-asset, and reports no residue when its download is gone", async () => { + it("deletes the image the receipt names with simctl runtime delete and no --keep-asset, and reports no residue when it had no unused default-set device and its download is gone", async () => { + // Another runtime's never-used devices are not this removal's to report. const runner = new ScriptedProcessRunner([ imagesListed([target, other]), - defaultSetListed({}), + defaultSetListed({ [other.runtime]: { unused: 4 } }), deleted, imagesListed([other]), - defaultSetListed({}), + defaultSetListed({ [other.runtime]: { unused: 4 } }), ]); // Other builds' downloads are in the store, one of them of the same version; this one's // is not. @@ -3474,6 +3536,140 @@ describe("IosSimctlDriver listComponents()", () => { ); }); + it("removes the runtime when its only default-set devices were never used (#241)", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({ [target.runtime]: { unused: 11 } }), + deleted, + imagesListed([]), + defaultSetListed({ [target.runtime]: { unused: 11 } }), + ]); + const driver = await createDriver(runner, new FakeClock(), await assetStore([])); + + await expect(driver.removeComponent(receipt, { signal: signal() })).resolves.toMatchObject({ + sizeBytes: 7_000_000_000, + }); + expect(runner.calls[2]?.args).toEqual(deleteInvocation.args); + }); + + it("reports three unused default-set devices as unavailable in residue, naming xcrun simctl delete unavailable (#241)", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({ [target.runtime]: { unused: 3 } }), + deleted, + imagesListed([]), + defaultSetListed({ [target.runtime]: { unused: 3 } }), + ]); + const driver = await createDriver(runner, new FakeClock(), await assetStore([])); + + const removal = await driver.removeComponent(receipt, { signal: signal() }); + + expect(removal.residue).toBe( + "3 never-used simulators in the default device set are now unavailable; Simlock does " + + "not delete simulators there -- `xcrun simctl delete unavailable` clears them", + ); + }); + + it("names a single unused default-set device in the singular in residue (#241)", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({ [target.runtime]: { unused: 1 } }), + deleted, + imagesListed([]), + defaultSetListed({ [target.runtime]: { unused: 1 } }), + ]); + const driver = await createDriver(runner, new FakeClock(), await assetStore([])); + + const removal = await driver.removeComponent(receipt, { signal: signal() }); + + expect(removal.residue).toMatch( + /^1 never-used simulator in the default device set is now unavailable;/, + ); + }); + + it("carries both the unavailable devices and the download left in the asset store in residue (#241)", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({ [target.runtime]: { unused: 2 } }), + deleted, + imagesListed([]), + defaultSetListed({ [target.runtime]: { unused: 2 } }), + ]); + const driver = await createDriver( + runner, + new FakeClock(), + await assetStore([["26.4", "23E244"]]), + ); + + const removal = await driver.removeComponent(receipt, { signal: signal() }); + + // Two sentences, the devices first, joined as prose. + expect(removal.residue).toMatch( + /^2 never-used simulators .*`xcrun simctl delete unavailable` clears them\. The download of iOS 26\.4 \(23E244\) .*Xcode's Settings -> Platforms to get the space back$/, + ); + }); + + it("reports no unavailable simulators when another installed build of the same runtime stays behind (#241)", async () => { + // Two builds of iOS 26.4 share one runtime identifier, so its simulators keep working + // on the build that stays. + const sibling = image("26.4", "23E200", { id: "IMG-26.4-23E200" }); + const runner = new ScriptedProcessRunner([ + imagesListed([target, sibling]), + defaultSetListed({ [target.runtime]: { unused: 3 } }), + deleted, + imagesListed([sibling]), + defaultSetListed({ [target.runtime]: { unused: 3 } }), + ]); + const driver = await createDriver(runner, new FakeClock(), await assetStore([])); + + const removal = await driver.removeComponent(receipt, { signal: signal() }); + + expect(removal).toEqual({ sizeBytes: 7_000_000_000 }); + }); + + it("runs no simctl command that writes to the default device set: its only unscoped call is the device list (#241)", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({ [target.runtime]: { unused: 11 } }), + deleted, + imagesListed([]), + defaultSetListed({ [target.runtime]: { unused: 11 } }), + ]); + const driver = await createDriver(runner, new FakeClock(), await assetStore([])); + + await driver.removeComponent(receipt, { signal: signal() }); + + // Every call that names no `--set` addresses the default set; each must be the read. + const unscoped = runner.calls.filter( + (call) => call.command === "xcrun" && !call.args.includes("--set"), + ); + expect(unscoped.map((call) => call.args)).toEqual([ + defaultSetInvocation.args, + defaultSetInvocation.args, + ]); + expect(runner.calls).toHaveLength(5); + }); + + it("reports the same foreign-device count in listComponents and in removeComponent's refusal for the same default set (#241)", async () => { + const set = defaultSetListed({ [target.runtime]: { unused: 9, used: 2 } }); + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + set, + imagesListed([target]), + set, + ]); + const driver = await createDriver(runner); + + const [listed] = await driver.listComponents(); + const error = await driver + .removeComponent(receipt, { signal: signal() }) + .catch((caught: unknown) => caught); + + expect(listed?.foreignDevices).toBe(2); + expect(error).toBeInstanceOf(ComponentInUseError); + expect(error).toMatchObject({ foreignDevices: listed?.foreignDevices }); + }); + it("fails with simctl's own error when runtime delete exits non-zero", async () => { // No listing after the failure: the scripted runner fails any call it was not given. const runner = new ScriptedProcessRunner([ @@ -3492,11 +3688,12 @@ describe("IosSimctlDriver listComponents()", () => { expect(runner.calls).toHaveLength(3); }); - it("refuses with ComponentInUseError when a device in the default device set uses the runtime, and deletes nothing", async () => { + it("refuses with ComponentInUseError when one default-set device of the runtime has lastUsedAt, and deletes nothing", async () => { // The scripted runner fails any call it was not given, so a delete would fail this test. + // Ten never-used devices beside the used one: only the used one counts. const runner = new ScriptedProcessRunner([ imagesListed([target]), - defaultSetListed({ [target.runtime]: 1 }), + defaultSetListed({ [target.runtime]: { unused: 10, used: 1 } }), ]); const driver = await createDriver(runner); diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index ed3445b13..0d5fd313b 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -538,19 +538,25 @@ export class IosSimctlDriver implements Driver { * One entry per iOS runtime image `simctl runtime list -j` reports: its version, its size, its * build as the variant, and the receipt `findComponent` and `installComponent` build for the * runtime it provides. `foreignDevices` counts the devices in the machine's default device set - * whose runtime is the image's; that read is an unscoped `simctl list`, which mutates nothing. + * whose runtime is the image's and that have been used at least once (`devicesPerRuntime`); + * that read is an unscoped `simctl list`, which mutates nothing. * An image that reports no version names no component and is left out. */ async listComponents(): Promise { - return (await this.#listedImages()).map(({ image: _image, ...component }) => component); + return (await this.#listedImages()).map( + ({ image: _image, unusedDevices: _unused, ...component }) => component, + ); } /** * Removes the runtime image whose receipt this is with `simctl runtime delete ` -- no * `--keep-asset`, so CoreSimulator is asked to let go of its download too -- through the steps - * every driver takes (`removeListedComponent`): refused when a device in the machine's default - * set uses it, verified gone afterwards. When the download is still in the macOS asset store - * afterwards (#79), `residue` says so and how to reclaim it; Simlock never deletes a file there. + * every driver takes (`removeListedComponent`): refused when a used device in the machine's + * default set has its runtime, verified gone afterwards. Never-used default-set devices of the + * runtime, counted in the listing taken before the delete, do not block it; they become + * unavailable and stay where they are, and `residue` says how many and how to clear them. When + * the download is still in the macOS asset store afterwards (#79), `residue` says that too. + * Nothing is written to the default set: Simlock never deletes a simulator or a file there. */ async removeComponent( receipt: ComponentReceipt, @@ -560,9 +566,13 @@ export class IosSimctlDriver implements Driver { list: () => this.#listedImages(), platform: this.platform, receipt, - remove: async ({ image, version }) => { + remove: async ({ image, unusedDevices, version }) => { await this.#deleteRuntimeImage(image.identifier, options.signal); - return this.#downloadResidue(image, version); + const sentences = [ + unavailableDevicesResidue(unusedDevices), + (await this.#downloadResidue(image, version)).residue, + ].filter((sentence) => sentence !== undefined); + return sentences.length === 0 ? {} : { residue: sentences.join(". ") }; }, }); } @@ -615,35 +625,46 @@ export class IosSimctlDriver implements Driver { }; } - /** `listComponents`' entries, each with the runtime image it describes. */ - async #listedImages(): Promise<(DriverComponent & { readonly image: RuntimeImage })[]> { + /** + * `listComponents`' entries, each with the runtime image it describes and the number of its + * default-set devices that were never used (`devicesPerRuntime`). + */ + async #listedImages(): Promise { const [images, defaultSet] = await Promise.all([ this.#loadRuntimeImages(), this.#legacySimctl(["list", "-j", "devices"], COMMAND_TIMEOUT_MS), ]); - let foreign: ReadonlyMap; + let foreign: ReadonlyMap; try { foreign = devicesPerRuntime(JSON.parse(defaultSet.stdout) as unknown); } catch (error: unknown) { if (error instanceof DriverCrashError) throw error; throw new DriverCrashError(`Could not parse simctl device list: ${errorMessage(error)}`); } - return images - .filter(isIosImage) - .flatMap((image): (DriverComponent & { readonly image: RuntimeImage })[] => - image.version === undefined - ? [] - : [ - { - foreignDevices: foreign.get(image.runtimeIdentifier) ?? 0, - image, - receipt: imageReceipt(image), - version: image.version, - ...(image.build === undefined ? {} : { variant: image.build }), - ...(image.sizeBytes === undefined ? {} : { sizeBytes: image.sizeBytes }), - }, - ], - ); + return images.filter(isIosImage).flatMap((image): ListedImage[] => + image.version === undefined + ? [] + : [ + { + foreignDevices: foreign.get(image.runtimeIdentifier)?.used ?? 0, + image, + // Another image of the same runtime keeps its simulators available after this + // one goes, so only the runtime's last image has unused devices to report. + unusedDevices: images.some( + (other) => + other !== image && + isIosImage(other) && + other.runtimeIdentifier === image.runtimeIdentifier, + ) + ? 0 + : (foreign.get(image.runtimeIdentifier)?.unused ?? 0), + receipt: imageReceipt(image), + version: image.version, + ...(image.build === undefined ? {} : { variant: image.build }), + ...(image.sizeBytes === undefined ? {} : { sizeBytes: image.sizeBytes }), + }, + ], + ); } /** The receipt of every runtime installed right now, before an installer run. */ @@ -2074,19 +2095,58 @@ function isIosImage(image: RuntimeImage): boolean { return image.platformIdentifier === IOS_SIMULATOR_PLATFORM; } +/** One `listComponents` entry with what `removeComponent` needs beyond it. */ +type ListedImage = DriverComponent & { + readonly image: RuntimeImage; + readonly unusedDevices: number; +}; + +/** + * The `residue` sentence for the never-used default-set simulators a runtime removal leaves + * behind, or nothing when there were none. Simlock does not delete them (safety rule 1). + */ +function unavailableDevicesResidue(unused: number): string | undefined { + if (unused === 0) return undefined; + const subject = + unused === 1 + ? "1 never-used simulator in the default device set is" + : `${String(unused)} never-used simulators in the default device set are`; + return ( + `${subject} now unavailable; Simlock does not delete simulators there -- ` + + "`xcrun simctl delete unavailable` clears them" + ); +} + +/** The default-set devices of one runtime, split by whether each has been used. */ +interface DefaultSetDevices { + /** Used at least once: these count as users of the runtime (`foreignDevices`). */ + readonly used: number; + /** Never used: macOS created them on its own, and they do not block a removal. */ + readonly unused: number; +} + /** - * How many devices a `simctl list -j devices` answer holds under each runtime: the answer is - * keyed by runtime identifier, with one array of devices under each. + * Counts the default set's devices per runtime identifier: a `simctl list -j devices` answer is + * keyed by runtime identifier, with one array of devices under each. This is the one place that decides + * which of them use a runtime, for listing and for removal alike: a device counts when its + * `simctl list -j devices` entry carries `lastUsedAt`, which only a device that has been booted + * has; an entry that is not an object counts as used, so an unreadable entry never unblocks a + * removal. When a runtime install ends, CoreSimulator creates a batch of simulators for it in the + * default set by itself; those carry no `lastUsedAt`, and counting them would make every runtime + * Simlock installs unremovable. */ -function devicesPerRuntime(value: unknown): ReadonlyMap { +function devicesPerRuntime(value: unknown): ReadonlyMap { if (!isRecord(value) || !isRecord(value.devices)) { throw new DriverCrashError("Invalid simctl device list JSON"); } return new Map( - Object.entries(value.devices).map(([runtime, devices]) => [ - runtime, - Array.isArray(devices) ? devices.length : 0, - ]), + Object.entries(value.devices).map(([runtime, devices]): [string, DefaultSetDevices] => { + const entries: readonly unknown[] = Array.isArray(devices) ? devices : []; + const used = entries.filter( + (device) => !isRecord(device) || device.lastUsedAt !== undefined, + ).length; + return [runtime, { unused: entries.length - used, used }]; + }), ); }