Open source CapCut alternative.
TypeScript
fix(app): make the system-tool capability probe non-blocking and bounded
David Lecfbfb46f6ff8
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift b/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swiftindex 475dc207..4ea7a114 100644--- a/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift@@ -20,6 +20,7 @@ public actor SystemToolCapabilityProbe {private let ttl: TimeIntervalprivate let toolNames: [String]private var cached: (expires: Date, summary: String)?+ private var probeTask: Task<Void, Never>?public init(cacheURL: URL? = nil,@@ -41,25 +42,39 @@ public actor SystemToolCapabilityProbe {/// A one-line summary of installed vs missing tools, e.g./// `Installed: git 2.43, jq 1.7, python3 3.12.2. Not installed: node, ffmpeg.`/// Cached in memory and on disk; recomputed only after the TTL lapses.+ ///+ /// Never blocks on subprocesses: with no fresh cache it kicks the probe off+ /// in the background and returns an empty summary, so a user turn never+ /// waits on `which`/`--version` children. The next turn gets the cached line.public func summary(now: Date = Date()) async -> String {if let cached, cached.expires > now { return cached.summary }if let disk = loadFromDisk(), disk.expires > now {cached = diskreturn disk.summary}- let summary = probe()- let entry = (expires: now.addingTimeInterval(ttl), summary: summary)+ if probeTask == nil {+ let tools = toolNames+ probeTask = Task.detached(priority: .utility) { [weak self] in+ let summary = Self.probe(tools: tools)+ await self?.store(summary: summary)+ }+ }+ return ""+ }++ private func store(summary: String) {+ let entry = (expires: Date().addingTimeInterval(ttl), summary: summary)cached = entrysaveToDisk(entry)- return summary+ probeTask = nil}// MARK: - Probing- private func probe() -> String {+ private static func probe(tools: [String]) -> String {var installed: [String] = []var missing: [String] = []- for tool in toolNames {+ for tool in tools {guard let path = run("/usr/bin/which", [tool]), !path.isEmpty else {missing.append(tool)continue@@ -77,7 +92,7 @@ public actor SystemToolCapabilityProbe {}/// Best-effort version string from the tool's own version flag.- private func version(of tool: String) -> String? {+ private static func version(of tool: String) -> String? {guard let raw = run("/usr/bin/env", [tool, "--version"]) ?? run("/usr/bin/env", [tool, "version"]) else {return nil}@@ -92,21 +107,43 @@ public actor SystemToolCapabilityProbe {return nil}- /// Run a short, bounded subprocess and return trimmed stdout (nil on failure).- private func run(_ launchPath: String, _ arguments: [String]) -> String? {+ /// Run a short subprocess and return trimmed stdout (nil on failure). The+ /// bound is real: a wedged child is killed at the deadline, and stderr is+ /// drained concurrently so a chatty tool can't fill the pipe and deadlock.+ private static func run(+ _ launchPath: String,+ _ arguments: [String],+ timeout: TimeInterval = 3+ ) -> String? {let process = Process()process.executableURL = URL(fileURLWithPath: launchPath)process.arguments = argumentslet outPipe = Pipe()+ let errPipe = Pipe()process.standardOutput = outPipe- process.standardError = Pipe()+ process.standardError = errPipe++ let finished = DispatchSemaphore(value: 0)+ process.terminationHandler = { _ in finished.signal() }do {try process.run()} catch {return nil}++ DispatchQueue.global(qos: .utility).async {+ _ = errPipe.fileHandleForReading.readDataToEndOfFile()+ }+ if finished.wait(timeout: .now() + timeout) == .timedOut {+ process.terminate()+ if finished.wait(timeout: .now() + 1.0) == .timedOut {+ kill(process.processIdentifier, SIGKILL)+ finished.wait()+ }+ return nil+ }+let data = outPipe.fileHandleForReading.readDataToEndOfFile()- process.waitUntilExit()guard process.terminationStatus == 0 else { return nil }let text = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""return text.isEmpty ? nil : textdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolCapabilityProbeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolCapabilityProbeTests.swiftnew file mode 100644index 00000000..a949cb05--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolCapabilityProbeTests.swift@@ -0,0 +1,33 @@+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct SystemToolCapabilityProbeTests {+ @Test+ func summaryNeverBlocksOnFirstUseAndServesTheBackgroundResultAfter() async throws {+ let cacheURL = FileManager.default.temporaryDirectory+ .appendingPathComponent("probe-tests-\(UUID().uuidString)", isDirectory: true)+ .appendingPathComponent("tool-capabilities.json")+ defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }++ // zsh ships with macOS, so the probe has one deterministic hit.+ let probe = SystemToolCapabilityProbe(cacheURL: cacheURL, toolNames: ["zsh"])++ // First call must not wait on subprocesses — it kicks the probe off and+ // returns an empty environment line.+ #expect(await probe.summary() == "")++ // The background probe lands shortly and subsequent calls serve it.+ var summary = ""+ for _ in 0..<100 where summary.isEmpty {+ try await Task.sleep(nanoseconds: 100_000_000)+ summary = await probe.summary()+ }+ #expect(summary.contains("zsh"))++ // The result is persisted: a fresh instance reads it without re-probing.+ let second = SystemToolCapabilityProbe(cacheURL: cacheURL, toolNames: ["zsh"])+ #expect(await second.summary() == summary)+ }+}