Skip to content

Add Clean Up… to a new Tools menu - #292

Open
tongliuTL wants to merge 19 commits into
Homebrew:mainfrom
tongliuTL:cleanup-tab
Open

tongliuTL wants to merge 19 commits into
Homebrew:mainfrom
tongliuTL:cleanup-tab

Conversation

@tongliuTL

@tongliuTL tongliuTL commented Oct 23, 2026 •

Copy link
Copy Markdown

Review: move to a Tools menu

What and why

Why the change

BrewUI has no way to run brew cleanup, so Cakebrew users switching over must open Terminal to see what is stale and reclaim the space, and this adds Tools › Clean Up…, which previews exactly what will be removed and then runs it.

Special things to note

  • Following review, this replaces the earlier Cleanup tab: the sidebar and ⌘1–⌘6 are back to what main has. The new Tools menu is named so other occasional commands can join it later.
  • Following review, the preview (brew cleanup --dry-run) is read-only, so it runs directly through the command runner like brew config rather than through the command centre: it stays out of the console and never queues behind a running install or upgrade. Lines the parser does not read are shown verbatim in the sheet under a warning that the list may be incomplete.
  • A Remove all cached downloads toggle adds --prune=all to both the preview and the run.
  • What runs is what was reviewed: Clean Up runs brew cleanup with the same flags as a mutating maintenance operation in the console, then closes the sheet. It stays disabled until a current, non-empty preview for those flags has loaded. brew cleanup already autoremoves unneeded dependencies, so there is no separate brew autoremove action. Unreferenced cached downloads are the one thing a run removes that the preview cannot list, because Homebrew's dry run skips them, so the command summary mentions them.
  • Out of scope: brew bundle cleanup. It uninstalls everything a chosen Brewfile does not list, so it needs a file picker and its own review.

Change outline

The menu command opens a sheet on the focused main window:

 BrewApp
   .commands
+    ToolsCommands                      # Tools › Clean Up…, disabled with no main window
 MainWindowView
+  .focusedSceneValue(\.showCleanup)
+  .sheet(isPresented: $showsCleanup)
+    CleanupSheetRoot                   # BrewFeatureCleanup
+      CleanupSheet(viewModel: CleanupViewModel)
+        "Remove all cached downloads" toggle   # adds --prune=all
+        unneeded formulae + paths to remove, Homebrew's own sizes and total
+        footer: copyable command, Cancel, destructive Clean Up (never default)

Each time the sheet opens it previews, then the button runs the real command:

sheet appears / prune toggle changes
  BrewCleanupRepository.load(pruneAll:)
    commandRunner.run(brew cleanup --dry-run [--prune=all])       # read-only, not in the console
    CleanupOutputParser.parse(stdout) -> CleanupReport            # unknown lines kept as unreadLines

Clean Up pressed (canCleanUp: loaded, not empty, no failure, same pruneAll)
  commandCenter.perform(brew cleanup [--prune=all])               # mutating maintenance op
    console streams output, installed inventory reconciles
  sheet closes

The parsed preview is a small new model:

struct CleanupReport {
    var pruneAll: Bool                 // which preview this is
    var unneededFormulae: [String]     // "Would autoremove N unneeded formulae"
    var removals: [CleanupRemoval]     // path, kind (file, broken link, empty folder), size
    var reclaimableSpace: String?      // "would free approximately X"
    var unreadLines: [String]          // anything else, shown under a warning
}

Where it lives:

 Homebrew/Features/Tools/ToolsCommands.swift           # new menu
 Sources/
   BrewCore/                                           # CleanupReport, BrewCommands, operation kinds
+    .cleanup (mutating)
   BrewRepositories/                                   # BrewCleanupRepository, CleanupOutputParser
   BrewRepositoryInterfaces/                           # CleanupRepository protocol, stub, preview data
+  BrewFeatureCleanup/                                 # new package: view model, sheet, copy
   BrewUIComponents/Theme/BrewSpacing.swift            # listSheetWidth/Height
 BrewUITests/                                          # CleanupScreen, CleanupUITests, fixtures

Validation

macOS 27.0.1, Apple M5 Pro, Xcode 27.1, Swift 6.4. upstream/main is merged in.

  • scripts/test on the latest upstream/main merge: 1,245 package tests pass, including the parser, repository, view model, command and AXID tests.
  • mint run swiftformat --lint ., mint run swiftlint lint --strict, BrewUILint over the production tree and scripts/localize verify: all pass.
  • scripts/localize sync stops on Xcode 27.1, which names package build folders <Target>-t.build while the script looks for <Target>.build. I ran xcstringstool sync with that path widened, kept its package-catalog output and added the two new app-catalog keys (Tools, Clean Up…) by hand, because its app-catalog pass also reorders existing translations.
  • scripts/test-ui -only-testing:BrewUITests/CleanupUITests -only-testing:BrewUITests/NavigationUITests: 5 of 5 pass. The Cleanup tests open Tools › Clean Up… and check the fixture rows before pressing Cancel, and check the empty state before pressing Done.
  • CI on 2c026c8: 11 checks pass (including build and unit tests, UI tests, live end-to-end canaries, SwiftFormat/SwiftLint/BrewUILint and workflow syntax) and 3 deploy jobs are skipped.
  • Manual: ran the app against real Homebrew 7.0.12 and opened Tools › Clean Up…. The sheet listed the 9 paths and the 124.9MB total from brew cleanup --dry-run, then Cancel closed it without running anything. Not repeated since the preview moved out of the console.
  • Not run: Clean Up for real against this machine's Homebrew.
  • I followed the conventions and workflow, checked for duplicate PRs and kept this change focused.
  • I added regression coverage for bug fixes or explained why automated coverage is impractical, and reported the relevant validation above.

Screenshots

Before After
No Tools menu; brew cleanup needs Terminal. Tools › Clean Up…
Tools menu with Clean Up…

The Clean Up sheet with a real dry run:

Clean Up Homebrew sheet listing what brew cleanup would remove

Screenshots were taken from a debug build (hence the Debug menu) against real Homebrew, in light appearance. They predate the preview moving out of the console; the sheet looks the same unless Homebrew prints a line the parser does not read.

AI assistance

  • AI was used to generate or assist with generating this PR.

Claude Code wrote the implementation, tests and this description, and ran the checks listed above.

🤖 Generated with Claude Code

tongliuTL and others added 2 commits October 23, 2026 11:05
Preview `brew cleanup --dry-run` through the command centre so the
Cleanup tab lists unneeded dependencies, old versions, stale downloads
and logs with Homebrew's own sizes and total. Clean Up runs
`brew cleanup` with the same flags after a confirmation, and an option
adds `--prune=all` to both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Drop the unused raw output from CleanupReport, share the card chrome
and error text within the view, derive the row id from its path and
give the cleanup fixture its own scenario arm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • New Features
    • Added Tools › Clean Up…, with a preview of removable formulae and files and Homebrew’s estimated reclaimable space.
    • Choose whether to include additional pruning, retry a failed preview, or run cleanup. Unrecognised preview output is flagged so the list may be incomplete.
    • Cancel closes the sheet without running cleanup; an empty installation shows a clean state. Running cleanup closes the sheet, with the result shown in the console. Homebrew may also remove unneeded dependencies unless automatic removal is disabled in Homebrew settings.
  • Documentation
    • Documented that previews run outside the command centre and console, without waiting behind other operations, and that cleanup results appear in the console.

The change adds a Cleanup sheet that previews brew cleanup --dry-run, displays eligible formulae and removals, and can run brew cleanup. It adds command and repository support, connects the sheet to the Tools menu, and adds unit and UI test coverage. It also changes how workflow checks pass values to grep.

Changes: Cleanup feature

Layer / File(s) Summary
Cleanup contracts and commands
Sources/BrewCore/Models/*, Sources/BrewCore/Operations/*, Sources/BrewRepositoryInterfaces/*, Sources/BrewAppEnvironment/*, Sources/BrewCLI/*, Tests/BrewCoreTests/*
Adds cleanup report and operation types, command builders, repository interfaces, and supporting fakes and preview data. Tests cover cleanup command arguments and operation kind.
Cleanup preview pipeline
Sources/BrewRepositories/*, Tests/BrewRepositoriesTests/*, ARCHITECTURE.md
Parses recognised Homebrew dry-run output and loads previews through the cleanup repository. The repository tracks refresh state and handles command failures. Tests cover parsing, option selection, and refresh behaviour.
Cleanup interface and actions
Sources/BrewFeatureCleanup/*, Sources/BrewUIComponents/Theme/BrewSpacing.swift, Sources/BrewAccessibilityID/AXID.swift, Tests/BrewFeatureCleanupTests/*, Tests/BrewAccessibilityIDTests/*
Adds the cleanup view model and sheet. The interface presents report items, clean and failed states, prune-all controls, confirmation text, and cleanup actions.
App integration and UI validation
Package.swift, Homebrew.xcodeproj/project.pbxproj, Homebrew/BrewApp.swift, Homebrew/Features/MainWindow/Views/MainWindowView.swift, Homebrew/Features/Tools/ToolsCommands.swift, Homebrew/Localizable.xcstrings, BrewUITests/*
Adds the feature package to the app, provides its repository through the environment, connects the Tools menu action to sheet presentation, and adds populated and empty cleanup UI scenarios.

Workflow grep input handling

Layer / File(s) Summary
Build and release checks
.github/workflows/build.yml, .github/workflows/release.yml
Changes the identity and version checks to pass values to grep through Bash here-strings. The patterns and failure handling remain unchanged.
Merge Risk: Low · up to 617df

The Clean Up preview may not list every item a real run removes, such as unreferenced cached downloads or downloads cached after the preview. This is a bounded copy and documentation accuracy concern. It is mergeable with owner awareness.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Add Clean Up… to a new Tools menu" matches the main change. The PR adds a Tools menu with a Clean Up… command that previews and runs brew cleanup, as shown in the changed files ToolsCommand…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description explains the change: a new Tools › Clean Up… sheet that previews brew cleanup --dry-run and then runs brew cleanup, plus a Remove all cached downloads toggle (--prune=all), valid…
Full details: Title check

Explanation

The title "Add Clean Up… to a new Tools menu" matches the main change. The PR adds a Tools menu with a Clean Up… command that previews and runs brew cleanup, as shown in the changed files ToolsCommands.swift, MainWindowView.swift, and the new BrewFeatureCleanup package. The title is concise and specific, and it does not describe anything absent from the changeset.

Full details: Description check

Explanation

The description explains the change: a new Tools › Clean Up… sheet that previews brew cleanup --dry-run and then runs brew cleanup, plus a Remove all cached downloads toggle (--prune=all), validation steps and screenshots. It matches the changeset, including the new CleanupSheet, BrewCleanupRepository, CleanupOutputParser, ToolsCommands and the Package.swift BrewFeatureCleanup target, so it is not off-topic.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: f6d4081
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7e865722-6d40-499a-8ec8-900f182afa39
Commits

Reviewing files that changed from the base of the PR and between f6a168f and 617df07.

Files selected for processing: 2

  • .github/workflows/build.yml
  • .github/workflows/release.yml

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments: 3
Sources/BrewFeatureCleanup/Views/CleanupView.swift: 2

94-94: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Expose one ViewModel property for the disabled state of the controls.

Both the "Check Again" button and the prune-all toggle compose viewModel.isRefreshing || viewModel.isCleaningUp in the view. The two sites must stay in step. The repository guideline requires one ViewModel property for each UI decision.

Add a derived property to CleanupViewModel and bind to it.

Proposed fix
 // CleanupViewModel.swift
+    /// Header controls wait while a preview or a cleanup run is in progress.
+    var areHeaderControlsDisabled: Bool {
+        isRefreshing || isCleaningUp
+    }
 // CleanupView.swift, headerControls
-            .disabled(viewModel.isRefreshing || viewModel.isCleaningUp)
+            .disabled(viewModel.areHeaderControlsDisabled)
 // CleanupView.swift, pruneAllToggle
-            .disabled(viewModel.isRefreshing || viewModel.isCleaningUp)
+            .disabled(viewModel.areHeaderControlsDisabled)

As per coding guidelines: "Expose one ViewModel property for each UI decision instead of composing multiple raw flags in a view."

Also applies to: 110-110

Source: Coding guidelines


140-140: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace the fixed font size with a theme token.

.font(.system(size: 44)) uses a fixed size. It does not scale with Dynamic Type. It is also a magic number in a view. The design system requires relative SwiftUI font styles. The coding conventions require the theme for typography.

Use a semantic font token from BrewUIComponents, or add one for large empty-state icons.

As per coding guidelines: "Support Dynamic Type – Yes – use relative SwiftUI font styles, not fixed sizes" and "Extend semantic tokens … instead of introducing raw colours or magic numbers in views."

Source: Coding guidelines

Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift: 1

153-164: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Wait for cleanup completion, not scheduler yields.

The tests wait for !viewModel.isCleaningUp, but waitUntil only performs 500 Task.yield() calls. The cleanup task can still be awaiting the command centre or the repository reload when those iterations finish. Use a target-shared readiness helper or an explicit test completion signal. Do not rely on the phase stream alone because the view model reloads before it clears isCleaningUp.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: e3510ee
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1d009767-a908-49a6-a1e7-11c08b0a7557
📥 Commits

Reviewing files that changed from the base of the PR and between e3510ee and 13f5df2.

📒 Files selected for processing: 41
  • ARCHITECTURE.md
  • BrewUITests/Fixtures/ScenarioFixtures.swift
  • BrewUITests/Harness/BrewUITestScenario.swift
  • BrewUITests/Screens/CleanupScreen.swift
  • BrewUITests/Screens/Sidebar.swift
  • BrewUITests/Tests/CleanupUITests.swift
  • BrewUITests/Tests/NavigationUITests.swift
  • Homebrew.xcodeproj/project.pbxproj
  • Homebrew/BrewApp.swift
  • Homebrew/Features/MainWindow/Views/MainWindowView.swift
  • Homebrew/Localizable.xcstrings
  • Homebrew/Views/MainSidebarView.swift
  • Homebrew/Views/SidebarItem.swift
  • Package.swift
  • README.md
  • Sources/BrewAccessibilityID/AXID.swift
  • Sources/BrewAppEnvironment/RepositoryEnvironment.swift
  • Sources/BrewAppEnvironment/UnimplementedRepositories.swift
  • Sources/BrewCLI/LiveBrewMutatingCommandFactory.swift
  • Sources/BrewCore/Models/CleanupReport+Placeholdable.swift
  • Sources/BrewCore/Models/CleanupReport.swift
  • Sources/BrewCore/Operations/BrewCommands.swift
  • Sources/BrewCore/Operations/BrewMutatingCommandFactory.swift
  • Sources/BrewCore/Operations/BrewOperationModels.swift
  • Sources/BrewFeatureCleanup/Resources/Localizable.xcstrings
  • Sources/BrewFeatureCleanup/ViewModels/CleanupRemovalItem.swift
  • Sources/BrewFeatureCleanup/ViewModels/CleanupViewModel.swift
  • Sources/BrewFeatureCleanup/Views/CleanupRoot.swift
  • Sources/BrewFeatureCleanup/Views/CleanupView.swift
  • Sources/BrewRepositories/BrewCleanupRepository.swift
  • Sources/BrewRepositories/CleanupOutputParser.swift
  • Sources/BrewRepositoryInterfaces/CommandJob.swift
  • Sources/BrewRepositoryInterfaces/Fakes/Stubs.swift
  • Sources/BrewRepositoryInterfaces/PreviewSupport/PreviewSupport+Cleanup.swift
  • Sources/BrewRepositoryInterfaces/Protocols/CleanupRepository.swift
  • Tests/BrewAccessibilityIDTests/AXIDTests.swift
  • Tests/BrewCoreTests/BrewCommandsTests.swift
  • Tests/BrewCoreTests/BrewOperationIDTests.swift
  • Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift
  • Tests/BrewRepositoriesTests/BrewCleanupRepositoryTests.swift
  • Tests/BrewRepositoriesTests/CleanupOutputParserTests.swift

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@MikeMcQuaid MikeMcQuaid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

brew cleanup is run automatically. Why does it need dedicated UI?

- Clear a stale refresh failure when the preview switches option.
- Expose one view model property for disabling the header controls.
- Wait on a deadline in the view model tests rather than a yield count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tongliuTL

Copy link
Copy Markdown
Author

@coderabbitai Nitpicks, addressed in 2f2b5a7:

  • Header controls: added CleanupViewModel.areHeaderControlsDisabled; both controls bind to it.
  • Test waits: waitUntil now polls against a 5s deadline instead of 500 yields.
  • Fixed 44pt icon: kept on purpose. It matches the Doctor empty state (DoctorView.swift:97), and BrewFonts has no icon-sized token. Happy to change both in a separate PR if maintainers want one.

@tongliuTL

tongliuTL commented Oct 23, 2026 •

Copy link
Copy Markdown
Author

@MikeMcQuaid Fair point — automatic cleanup covers most of it. What it doesn't give a GUI user:

  • Visibility: what would be removed and how much space it frees. The automatic run is silent and only happens as part of brew install/upgrade/reinstall (a full sweep at most every 30 days).
  • --prune=all: clearing the whole download cache on demand. Automatic cleanup only removes downloads older than 120 days.
  • Parity for Cakebrew users: this is the one tool I missed after switching. Cleaning up on demand meant opening Terminal.

If you'd rather not have a dedicated tab, I'm happy to shrink it to a "Clean Up" action inside Doctor or wherever you see best fit.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments: 1
Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift: 1

158-158: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Replace the wall-clock deadline with a readiness signal.

If command-centre execution or the subsequent reload takes more than five seconds on a busy test worker, waitUntil records a failure even when both complete correctly. Wait for an explicit completion signal from the test double. Use an injected clock if the test must check timeout behaviour. As per coding guidelines, “Drive timeout tests from explicit readiness signals and injected clocks rather than short wall-clock deadlines.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: e3510ee
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b768f31c-a0a1-4acf-8780-ccf503559130
📥 Commits

Reviewing files that changed from the base of the PR and between 13f5df2 and 2f2b5a7.

📒 Files selected for processing: 5
  • Sources/BrewFeatureCleanup/ViewModels/CleanupViewModel.swift
  • Sources/BrewFeatureCleanup/Views/CleanupView.swift
  • Sources/BrewRepositories/BrewCleanupRepository.swift
  • Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift
  • Tests/BrewRepositoriesTests/BrewCleanupRepositoryTests.swift
🚧 Files skipped from review as they are similar to previous changes: 1
  • Tests/BrewRepositoriesTests/BrewCleanupRepositoryTests.swift

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@coderabbitai

coderabbitai Bot commented Oct 23, 2026

Copy link
Copy Markdown

CodeRabbit chat interactions are restricted to organization members for this repository. Ask an organization member to interact with CodeRabbit, or set chat.allow_non_org_members: true in your configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tongliuTL
tongliuTL requested a review from MikeMcQuaid October 24, 2026 00:57

@MikeMcQuaid MikeMcQuaid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't request my rereview. Want @graeme's thoughts before we go further here.

The view model tests now await the stub repository's reload signal,
which every cleanup run ends with, rather than polling against a
wall-clock deadline that a busy worker could miss.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
@graeme

graeme commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

Agree with @MikeMcQuaid. This is really not a fundamental enough feature to have its own tab I think adding it to Doctor in a way that doesn't look weird would need a bit of thought.

Alternatively a simpler option would just be to create a "Tools" menu in the menu bar. I'd imagine that will become the home for a few other similar commands.

Stick this in there as "Clean up..." and have that launch a confirmation dialog which says what would be removed.

tongliuTL and others added 2 commits November 3, 2026 10:36
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
Review asked for a menu command rather than a sidebar tab. Tools > Clean
Up… opens a sheet that previews brew cleanup with a dry run, lists what
it would remove and runs it only from the sheet's Clean Up button. The
Cleanup tab, its sidebar entry and its shortcut are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
@tongliuTL tongliuTL changed the title Add a Cleanup tab for brew cleanup Add Clean Up… to a new Tools menu Nov 3, 2026

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up Comments

Nitpick Cover the prune-all cleanup submission.

101-109: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the prune-all cleanup submission.

The prune-all test keeps the pruneAll: false report and never runs cleanUp(). A change that drops --prune=all from the submitted cleanup would pass the suite. Add a test that supplies a pruneAll: true report, runs cleanup after enabling prune-all, and checks the submitted operation. The helper must also map the prune-all argument list so the run succeeds.

Suggested test and helper change
-    private static func recordingCenter(exitCode: Int32, stderr: String = "") -> RecordingSerialBrewCommandCenter {
+    private static func recordingCenter(
+        exitCode: Int32,
+        stderr: String = "",
+        arguments: [String] = ["cleanup"],
+    ) -> RecordingSerialBrewCommandCenter {
         let context = BrewCommandExecutionContext(
             commandRunner: MockBrewCommandRunner(responses: [
-                ["cleanup"]: CommandOutput(standardOutput: "", standardError: stderr, terminationStatus: exitCode),
+                arguments: CommandOutput(standardOutput: "", standardError: stderr, terminationStatus: exitCode),
             ]),
         #expect(viewModel.cleanupDisplayCommand == "brew cleanup --prune=all")
         #expect(repository.loadedOptions == [true])
     }
+
+    @Test func `prune all runs brew cleanup with --prune=all when the preview matches`() async throws {
+        let report = CleanupReport(
+            pruneAll: true,
+            unneededFormulae: Self.report.unneededFormulae,
+            removals: Self.report.removals,
+            reclaimableSpace: Self.report.reclaimableSpace,
+        )
+        let center = Self.recordingCenter(exitCode: 0, arguments: ["cleanup", "--prune=all"])
+        let viewModel = Self.viewModel(repository: StubCleanupRepository(report: report), commandCenter: center)
+
+        await viewModel.setPruneAll(true)
+        #expect(viewModel.canCleanUp)
+
+        try await #require(viewModel.cleanUp()).value
+
+        let entries = await center.recordedSubmitEntries
+        #expect(entries.map(\.kind) == [.cleanup])
+        #expect(entries.first?.id == .maintenance(token: "cleanup", displayCommand: "brew cleanup --prune=all"))
+    }

Open the source location

Nitpick Record brew invocations and check that Cancel starts no cleanup.

16-19: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy lift

Record brew invocations and check that Cancel starts no cleanup.

The test checks only that the sheet closes after Cancel. A regression that starts brew cleanup before the sheet is dismissed would still pass. FakeBrew does not record invocations, so the test cannot observe a submitted command.

Record each invocation in a form the UI test can read. Match whole argument lines. The sheet runs cleanup --dry-run when it opens, so a prefix match would also match that preview.

After Cancel, the test must wait for any pending asynchronous work before it checks for a cleanup line. The synchronisation point must complete whether or not a command was submitted. The current UI provides no completion state for a cleanup submission, so this point must be added. A fixed delay cannot prove absence, and an immediate check can pass before a submitted command starts.

Open the source location

SwiftUI does not pass an accessibility identifier from a Commands button
to its menu item, so the Clean Up UI tests could not find it. Look the
item up by its English title and pin the stubbed launch to English, as
the live suite already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
@tongliuTL

Copy link
Copy Markdown
Author

Thanks @graeme, that makes sense. I've moved it to a new Tools menu as "Clean Up…", which opens a sheet showing what brew cleanup would remove (with the --prune=all option) before anything runs. The tab is gone.

Disable Clean Up after a failed refresh and when the loaded preview was
made without the prune option the run would use. Move the confirmation
message into the scrolling list so a long formula list cannot push the
footer out of the sheet. Cover the prune-all run with a test.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
@tongliuTL

Copy link
Copy Markdown
Author

Review-body nitpicks from the latest CodeRabbit review:

  • Prune-all submission test: added in 1c9faa1 (prune all runs brew cleanup with --prune=all when the preview matches); the recording helper now takes the argument list.
  • Recording brew invocations in CleanupUITests: not changing here. Fake brew's fixtures live in the app's own temporary directory and proving an absence needs a new completion signal in the UI, which is a harness change of its own. cleanUp() is the only submit path and only the Clean Up button calls it; unit tests cover that it never submits without a removable, current preview.

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up Comments

Nitpick Add a repository test for recovery after a failed refresh.

122-126: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a repository test for recovery after a failed refresh.

BrewCleanupRepository clears refreshFailure when a same-option load succeeds. No test covers a same-option failure followed by a successful load, so a regression that keeps the failure set would not fail any current test. The existing tests cover a failure that stays set and an option switch that clears the failure.

Add a test to BrewCleanupRepositoryTests that uses SequencedRunner to succeed, fail, then succeed on the same option:

🧪 Suggested test
+    @Test func `a successful refresh after a failed one clears the failure`() async {
+        let success = MockBrewCommandRunnerBehavior.output(CommandOutput(
+            standardOutput: "Would remove: /cache/a.tar.gz (1MB)\n",
+            standardError: "",
+            terminationStatus: 0,
+        ))
+        let runner = SequencedRunner([
+            success,
+            .throw(BrewCommandError.launchFailed(underlying: "spawn failed")),
+            success,
+        ])
+        let context = BrewCommandExecutionContext(commandRunner: runner, locator: BrewExecutableLocator(overrideURL: Self.brewURL))
+        let repository = BrewCleanupRepository(
+            commandCenter: SerialBrewCommandCenter(executionContext: context, reconciler: NoopBrewOperationReconciler()),
+        )
+
+        await repository.load(pruneAll: false)
+        await repository.load(pruneAll: false)
+        await repository.load(pruneAll: false)
+
+        #expect(repository.refreshFailure == nil && repository.state.value?.removals.count == 1)
+    }

Place the test after a failed refresh keeps the prior report and records the failure. The test drives the production load(pruneAll:) path, so it does not reset any state by hand.

The view-model stub cannot clear refreshFailure on load. A view-model assertion would need a manual reset, so this test covers recovery at the repository boundary.

Open the source location

The irreversibility statement sat at the end of the scroll region, so a
long report pushed it out of view while Clean Up stayed enabled. It now
sits above the list as a fixed short line; the variable list of formulae
autoremove uninstalls stays inside the scroll region.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up Comments

Nitpick Add a test for the nil uninstall message.

102-102: Trivial · Functional Correctness · Quick win

Add a test for the nil uninstall message.

The only uninstallMessage test uses a report with formulae. Nothing asserts the nil case. A change that returns text for a removal-only report would still pass, and CleanupSheet would show a false uninstall statement. The suggested test covers this case.

Suggested test
     @Test func `the confirmation names the formulae it will uninstall`() {
         let viewModel = Self.viewModel(repository: StubCleanupRepository(report: Self.report))
         #expect(viewModel.uninstallMessage == "This also uninstalls libyaml, m4.")
     }
+
+    @Test func `the confirmation is absent when no formulae are uninstalled`() {
+        let report = CleanupReport(
+            pruneAll: false,
+            unneededFormulae: [],
+            removals: [CleanupRemoval(path: "/cache/a.tar.gz", kind: .file, size: "12.7MB")],
+            reclaimableSpace: "12.7MB",
+        )
+        let viewModel = Self.viewModel(repository: StubCleanupRepository(report: report))
+        #expect(viewModel.uninstallMessage == nil)
+    }

Open the source location

Review info
Run configuration
  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: 3632253
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d8f3b3bc-4a48-48e8-9649-2f12877bb93b
Commits

Reviewing files that changed from the base of the PR and between 1c9faa1 and a397a75.

Files selected for processing: 4
  • Sources/BrewFeatureCleanup/Resources/Localizable.xcstrings
  • Sources/BrewFeatureCleanup/ViewModels/CleanupViewModel.swift
  • Sources/BrewFeatureCleanup/Views/CleanupSheet.swift
  • Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift
Files skipped from review as they are similar to previous changes: 1
  • Sources/BrewFeatureCleanup/Resources/Localizable.xcstrings

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

@tongliuTL

Copy link
Copy Markdown
Author

Review-body nitpicks from the latest CodeRabbit reviews, both added in a5aae54:

  • Repository recovery after a failed refresh: a successful refresh after a failed one clears the failure.
  • Nil uninstall message: the confirmation is absent when no formulae are uninstalled.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up Comments

Nitpick Add a test that Clean Up stays enabled for a cache-only preview.

112-113: Trivial · Functional Correctness · Quick win

Add a test that Clean Up stays enabled for a cache-only preview.

The cache-only test checks only the confirmation. A change that disables Clean Up when unneededFormulae is empty would still pass the suite. Add a separate test that asserts canCleanUp for a report with removals and no formulae.

Suggested test
+    @Test func `clean up is enabled for a cache-only preview`() {
+        let report = CleanupReport(
+            pruneAll: false,
+            unneededFormulae: [],
+            removals: [CleanupRemoval(path: "/cache/a.tar.gz", kind: .file, size: "12.7MB")],
+            reclaimableSpace: "12.7MB",
+        )
+        let viewModel = Self.viewModel(repository: StubCleanupRepository(report: report))
+        #expect(viewModel.canCleanUp)
+    }
+

Open the source location

Nitpick Make the recovery test detect a stale report after a successful refresh.

103-113: Trivial · Maintainability & Code Quality · Quick win

Make the recovery test detect a stale report after a successful refresh.

The recovery test loads the same output before and after the failure. A regression that keeps the previous report after a successful refresh that follows a failure would still pass. Return different output on the third load and assert its path.

🧪 Suggested test change
+        let recovered = MockBrewCommandRunnerBehavior.output(CommandOutput(
+            standardOutput: "Would remove: /cache/b.tar.gz (2MB)\n",
+            standardError: "",
+            terminationStatus: 0,
+        ))
-        let runner = SequencedRunner([success, .throw(BrewCommandError.launchFailed(underlying: "spawn failed")), success])
+        let runner = SequencedRunner([success, .throw(BrewCommandError.launchFailed(underlying: "spawn failed")), recovered])
-        #expect(repository.state.value?.removals.count == 1 && repository.refreshFailure == nil)
+        #expect(repository.state.value?.removals.map(\.path) == ["/cache/b.tar.gz"] && repository.refreshFailure == nil)

Open the source location

Review info
Run configuration
  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: 3632253
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2d511d2a-451d-47a1-85a6-c1d6cd74c14c
Commits

Reviewing files that changed from the base of the PR and between a397a75 and a5aae54.

Files selected for processing: 2
  • Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift
  • Tests/BrewRepositoriesTests/BrewCleanupRepositoryTests.swift

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Assert that Clean Up stays enabled for a cache-only preview, and make the
refresh recovery test return a different report after the failure so a
stale report would be caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
@tongliuTL

Copy link
Copy Markdown
Author

@coderabbitai Both follow-up nitpicks fixed in 806a3d7: added a test that Clean Up stays enabled for a cache-only preview, and the recovery test now returns a different report after the failure and asserts its path.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick comments: 1
Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift: 1

117-120: Trivial · Maintainability & Code Quality · Quick win

Add a cache-only submission test for cleanUp().

The cache-only test checks only canCleanUp. No test submits cleanup for a cache-only preview, so an added formulae requirement in cleanUp() would pass the suite. Add a test that builds the view model from cacheOnlyReport, calls cleanUp(), and asserts that the recording command center receives a .cleanup entry. This follows the pattern of the existing submission tests.

Review info
Run configuration
  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: 3632253
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f90adde5-9032-4513-91fa-754a2d6b2f5a
Commits

Reviewing files that changed from the base of the PR and between a5aae54 and 806a3d7.

Files selected for processing: 2
  • Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift
  • Tests/BrewRepositoriesTests/BrewCleanupRepositoryTests.swift

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@coderabbitai

coderabbitai Bot commented Nov 4, 2026

Copy link
Copy Markdown

CodeRabbit chat interactions are restricted to organization members for this repository. Ask an organization member to interact with CodeRabbit, or set chat.allow_non_org_members: true in your configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tongliuTL added a commit to tongliuTL/BrewUI that referenced this pull request Nov 4, 2026
@tongliuTL

Copy link
Copy Markdown
Author

@graeme, could you take a look when you have a moment?

@graeme graeme left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still think this could be simpler.

Please do not show the cleanup preview run in the console. I know there's an exception to the "only mutating commands in the console" rule with the Doctor, but I'd still rather we didn't add more unless adding value. To achieve this, you have to queue it behind mutating commands which isn't necessary; you could have it run in parallel with them creating a more responsive experience.

If you want to handle lines the parser doesn't read, better to add that as a partial error message in the clean-up sheet.

General advice for opening PRs here: if you keep the feature as simple as possible to achieve the goal, it'll get reviewed quicker. That's a good practice in general.

It's almost there. I think once you address this item, it'll be good to go.

tongliuTL and others added 2 commits November 12, 2026 14:47
The dry run changes nothing, so it now runs directly through the
command runner, like `brew config`, instead of the command centre. It
stays out of the console and no longer queues behind mutating commands.

Lines the parser does not read are kept on the report and shown in the
sheet as a partial error, so the list is never silently incomplete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
@tongliuTL

Copy link
Copy Markdown
Author

@graeme Thanks, done in 2e3f27b: the dry run now runs directly through the command runner (like brew config) instead of the command centre, so it no longer appears in the console or queues behind mutating commands, and the .cleanupPreview operation kind is gone. Lines the parser doesn't read are now shown verbatim in the sheet as a partial error. I also merged main in (a9da668).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Review info

Run configuration

  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: 772676d
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ae115944-b547-4847-be4a-746b5a4463be
Commits

Reviewing files that changed from the base of the PR and between 98439ff and a9da668.

Files selected for processing: 18

  • ARCHITECTURE.md
  • Homebrew.xcodeproj/project.pbxproj
  • Homebrew/BrewApp.swift
  • Homebrew/Localizable.xcstrings
  • Sources/BrewCore/Models/CleanupReport.swift
  • Sources/BrewCore/Operations/BrewCommands.swift
  • Sources/BrewCore/Operations/BrewOperationModels.swift
  • Sources/BrewFeatureCleanup/Resources/Localizable.xcstrings
  • Sources/BrewFeatureCleanup/Views/CleanupSheet.swift
  • Sources/BrewRepositories/BrewCleanupRepository.swift
  • Sources/BrewRepositories/CleanupOutputParser.swift
  • Sources/BrewRepositoryInterfaces/CommandJob.swift
  • Sources/BrewRepositoryInterfaces/Protocols/CleanupRepository.swift
  • Tests/BrewCoreTests/BrewCommandsTests.swift
  • Tests/BrewCoreTests/BrewOperationIDTests.swift
  • Tests/BrewFeatureCleanupTests/CleanupViewModelTests.swift
  • Tests/BrewRepositoriesTests/BrewCleanupRepositoryTests.swift
  • Tests/BrewRepositoriesTests/CleanupOutputParserTests.swift
Files skipped from review as they are similar to previous changes: 1

  • Homebrew/Localizable.xcstrings

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Waiting load calls recheck the in-flight preview after each wait and only
the finished task clears the handle, so two callers waiting for the other
option share one dry run. A retained report now shows the re-check spinner
and a failure with Retry in both the empty and the non-empty state, and the
command summary says a run also removes unreferenced cached downloads,
which the dry run does not list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
@tongliuTL
tongliuTL requested a review from graeme November 12, 2026 21:10
@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

@github-actions github-actions Bot added the Stale label Dec 4, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments

Minor 1
  1. Clarify the preview's limits.
Review info

Run configuration

  • Source mode: Auto
  • Repository: Homebrew/BrewUI
  • Branch: main
  • File: .coderabbit.config.ts
  • Commit: f6d4081
  • Layers: Repository TS config (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 47e77da9-cbad-4c2a-acac-440918040387
Commits

Reviewing files that changed from the base of the PR and between b78bbfa and f6a168f.

Files selected for processing: 5

  • ARCHITECTURE.md
  • Homebrew.xcodeproj/project.pbxproj
  • Homebrew/BrewApp.swift
  • Homebrew/Localizable.xcstrings
  • Package.swift
Files skipped from review as they are similar to previous changes: 1

  • Homebrew/Localizable.xcstrings

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Comment thread ARCHITECTURE.md Resolved
@tongliuTL

tongliuTL commented Dec 4, 2026 •

Copy link
Copy Markdown
Author

Hi @graeme, thanks again for the steer on keeping this simple. Your points from 12 November are addressed: the preview no longer goes through the console or queues behind other commands, and lines the parser doesn't read now show as a partial warning in the sheet. I've also brought the branch up to date with main. I'm happy to make further changes whenever you have time for another look.

@github-actions github-actions Bot removed the Stale label Dec 4, 2026
tongliuTL and others added 2 commits December 3, 2026 22:02
Newer shellcheck flags piping into grep -q under pipefail (SC2337).
Feed grep from a here-string instead; behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
Upstream fixed the same shellcheck SC2337 warnings in Homebrew#341, so take
main's versions of build.yml and release.yml. This PR no longer
touches the workflows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MPohgvgVhj9yTCLQRiEYE7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants