Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2024-05-28 - Main Thread Blocking in async @MainActor methods
**Learning:** In Swift Concurrency, `async` methods on a `@MainActor` class execute on the main thread. If they perform synchronous blocking operations (like `DiskInfo.current()` which involves `URLResourceValues` I/O, or `Foundation.Process.waitUntilExit()`), they will block the UI and prevent other main actor tasks from running, even though they are inside an `async` function.
**Action:** Always offload synchronous blocking operations from the main thread using `await Task.detached { ... }.value` when executing within a `@MainActor` context.
23 changes: 13 additions & 10 deletions Sources/Cacheout/ViewModels/CacheoutViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ class CacheoutViewModel: ObservableObject {
func scan() async {
isScanning = true
isNodeModulesScanning = true
diskInfo = DiskInfo.current()
diskInfo = await Task.detached { DiskInfo.current() }.value

// Scan caches and node_modules in parallel
async let cacheResults = scanner.scanAll(CacheCategory.allCategories)
Expand Down Expand Up @@ -241,21 +241,24 @@ class CacheoutViewModel: ObservableObject {
]

do {
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8) ?? ""

if process.terminationStatus == 0 {
let result = try await Task.detached { () -> (Int32, String) in
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8) ?? ""
return (process.terminationStatus, output)
}.value

if result.0 == 0 {
// Extract "Total reclaimed space:" line
if let line = output.components(separatedBy: "\n")
if let line = result.1.components(separatedBy: "\n")
.first(where: { $0.contains("reclaimed") }) {
lastDockerPruneResult = line.trimmingCharacters(in: .whitespaces)
} else {
lastDockerPruneResult = "Docker pruned successfully"
}
} else {
let lowerOutput = output.lowercased()
let lowerOutput = result.1.lowercased()
if lowerOutput.contains("cannot connect") ||
lowerOutput.contains("is the docker daemon running") ||
lowerOutput.contains("connection refused") ||
Expand All @@ -270,7 +273,7 @@ class CacheoutViewModel: ObservableObject {
}

// Refresh disk info after prune
diskInfo = DiskInfo.current()
diskInfo = await Task.detached { DiskInfo.current() }.value
}

func clean() async {
Expand Down