Open source CapCut alternative.
TypeScript
feat(app): install bundled CLI tools on first run
David Le62c6e5c9d052
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swiftindex 1dba9332..dc013f44 100644--- a/apps/Donkey/Package.swift+++ b/apps/Donkey/Package.swift@@ -40,6 +40,7 @@ let package = Package(],resources: [.process("Resources/local-app-finder-profiles.json"),+ .process("Resources/bundled-tools.json"),.copy("Resources/BuiltInSkills")],swiftSettings: [diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex 2837bf9f..176f5ece 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -32,6 +32,13 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {return}+ // Kick off the first-run download of the bundled CLI tools (ffmpeg/yt-dlp/...) in the background,+ // so a later media task runs them by bare name instead of hunting for Homebrew. Non-blocking and a+ // no-op once the current version is installed or when nothing is published yet.+ Task.detached(priority: .utility) {+ await BundledToolsInstaller.shared.installIfNeeded()+ }+let authCoordinator = DonkeyAuthCoordinator()self.authCoordinator = authCoordinator// Seed the process-wide session gate before any surface is built, so the warm cache, Livediff --git a/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift b/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swiftnew file mode 100644index 00000000..13945c71--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift@@ -0,0 +1,59 @@+import Foundation++/// The prebuilt CLI tools (ffmpeg, ffprobe, yt-dlp, ...) that Donkey's capability skills run by bare+/// name. The shipped app stays small and downloads a self-contained arm64 bundle on first run into+/// Application Support; this type is the shared knowledge of *what* to fetch and *where* it lives.+///+/// `bundled-tools.json` (in the app's resource bundle) is the single source of truth for the version,+/// download URL, and checksum; scripts/publish-bundled-tools.sh builds the artifact and rewrites it.+public enum BundledTools {+ /// The manifest describing the published tools bundle. An empty `sha256` means nothing is published+ /// yet, so callers should treat the bundle as unavailable rather than downloading something unverified.+ public struct Manifest: Decodable, Sendable, Equatable {+ public let version: String+ public let arch: String+ public let url: String+ public let sha256: String++ public var isPublished: Bool {+ !sha256.isEmpty && URL(string: url) != nil+ }+ }++ /// Where first-run-downloaded tools are extracted. Writable, survives app updates, and is the first+ /// place `shellEnvironment()` looks for the tools on PATH.+ public static var installDirectory: URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("donkey-tools", isDirectory: true)+ }++ /// The version-marker file written after a successful install, so we re-download only when the+ /// manifest names a newer bundle.+ static var installedVersionMarker: URL {+ installDirectory.appendingPathComponent(".version", isDirectory: false)+ }++ /// The bundle is usable if a sentinel tool exists in the install directory. ffmpeg is mandatory in+ /// every bundle, so its presence is the cheapest "are the tools really here" check.+ public static func isInstalled(at directory: URL) -> Bool {+ FileManager.default.isExecutableFile(atPath: directory.appendingPathComponent("ffmpeg").path)+ }++ /// The version currently installed in Application Support, or nil if none/partial.+ public static var installedVersion: String? {+ guard isInstalled(at: installDirectory),+ let raw = try? String(contentsOf: installedVersionMarker, encoding: .utf8)+ else { return nil }+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.isEmpty ? nil : trimmed+ }++ /// Load the bundled manifest from the app's resources. Returns nil if it is missing or malformed.+ public static func loadManifest() -> Manifest? {+ guard let url = Bundle.module.url(forResource: "bundled-tools", withExtension: "json"),+ let data = try? Data(contentsOf: url)+ else { return nil }+ return try? JSONDecoder().decode(Manifest.self, from: data)+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/BundledToolsInstaller.swift b/apps/Donkey/Sources/DonkeyRuntime/BundledToolsInstaller.swiftnew file mode 100644index 00000000..6a60240c--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/BundledToolsInstaller.swift@@ -0,0 +1,123 @@+import CryptoKit+import Foundation+import os++/// Downloads the prebuilt CLI tools bundle (ffmpeg, yt-dlp, ...) into Application Support on first run, so+/// the shipped app stays small and the capability skills "just work" without the user installing anything.+///+/// Serialized via an actor: safe to call on every launch and concurrently — it no-ops when the manifest+/// version is already installed, when nothing is published yet, or when an install is already in flight.+/// Verifies the SHA-256 before trusting the bytes and swaps the new tools in atomically.+public actor BundledToolsInstaller {+ public static let shared = BundledToolsInstaller()++ private var installing = false+ private let log = Logger(subsystem: "com.donkey.app", category: "BundledTools")++ enum InstallError: Error {+ case badURL+ case checksumMismatch(expected: String, got: String)+ case extractFailed(status: Int32)+ case noToolsInArchive+ }++ public init() {}++ /// Ensure the published tools bundle is installed and current. Returns whether usable tools are present+ /// afterward. Cheap to call repeatedly; the heavy download runs only when the installed version differs+ /// from the manifest.+ @discardableResult+ public func installIfNeeded() async -> Bool {+ guard let manifest = BundledTools.loadManifest(), manifest.isPublished else {+ // Nothing published yet (empty sha256): rely on whatever is already on disk (e.g. a dev symlink+ // or an offline-baked bundle); never download something unverified.+ return BundledTools.isInstalled(at: BundledTools.installDirectory)+ }+ if BundledTools.installedVersion == manifest.version { return true }+ guard !installing else { return false }+ installing = true+ defer { installing = false }++ do {+ try await install(manifest)+ log.info("installed bundled tools \(manifest.version, privacy: .public)")+ return true+ } catch {+ log.error("bundled tools install failed: \(String(describing: error), privacy: .public)")+ return BundledTools.isInstalled(at: BundledTools.installDirectory)+ }+ }++ private func install(_ manifest: BundledTools.Manifest) async throws {+ guard let url = URL(string: manifest.url) else { throw InstallError.badURL }+ let fm = FileManager.default++ let (downloaded, _) = try await URLSession.shared.download(from: url)+ defer { try? fm.removeItem(at: downloaded) }++ let digest = try sha256Hex(of: downloaded)+ guard digest == manifest.sha256.lowercased() else {+ throw InstallError.checksumMismatch(expected: manifest.sha256.lowercased(), got: digest)+ }++ // Extract into a private staging dir, then swap into place so a crash mid-extract never leaves a+ // half-populated tools directory that `isInstalled` would treat as good.+ let staging = fm.temporaryDirectory.appendingPathComponent("donkey-tools-stage-\(UUID().uuidString)", isDirectory: true)+ try fm.createDirectory(at: staging, withIntermediateDirectories: true)+ defer { try? fm.removeItem(at: staging) }+ try extractTarGz(downloaded, into: staging)++ let root = try resolveToolsRoot(in: staging)+ let dest = BundledTools.installDirectory+ try fm.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)+ if fm.fileExists(atPath: dest.path) { try fm.removeItem(at: dest) }+ try fm.moveItem(at: root, to: dest)++ markExecutables(in: dest)+ try manifest.version.write(to: BundledTools.installedVersionMarker, atomically: true, encoding: .utf8)+ }++ /// Stream the file through SHA-256 so a ~250MB archive isn't all held in memory.+ private func sha256Hex(of file: URL) throws -> String {+ let handle = try FileHandle(forReadingFrom: file)+ defer { try? handle.close() }+ var hasher = SHA256()+ while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty {+ hasher.update(data: chunk)+ }+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()+ }++ private func extractTarGz(_ archive: URL, into directory: URL) throws {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/tar")+ process.arguments = ["-xzf", archive.path, "-C", directory.path]+ try process.run()+ process.waitUntilExit()+ guard process.terminationStatus == 0 else {+ throw InstallError.extractFailed(status: process.terminationStatus)+ }+ }++ /// The tarball may be flat (ffmpeg at the root) or wrapped in a top-level dir; return whichever level+ /// actually holds the tools.+ private func resolveToolsRoot(in staging: URL) throws -> URL {+ if BundledTools.isInstalled(at: staging) { return staging }+ let entries = (try? FileManager.default.contentsOfDirectory(at: staging, includingPropertiesForKeys: nil)) ?? []+ for entry in entries where BundledTools.isInstalled(at: entry) { return entry }+ throw InstallError.noToolsInArchive+ }++ /// tar preserves modes, but be defensive: mark every top-level regular file executable so a bare-name+ /// invocation works even if the archive lost its bits.+ private func markExecutables(in directory: URL) {+ let fm = FileManager.default+ let entries = (try? fm.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isRegularFileKey])) ?? []+ for entry in entries {+ let isRegular = (try? entry.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) ?? false+ if isRegular {+ try? fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: entry.path)+ }+ }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex 3a85fc3e..96a62dc1 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -674,20 +674,25 @@ public enum DonkeyCommandBackends {)}- /// The bundled command-line tools directory inside the packaged app- /// (`…/Contents/Resources/donkey-tools`). Skills invoke `ffmpeg`/`yt-dlp` and the- /// other bundled tools by bare name and rely on this being on the shell PATH.- /// `nil` in dev/test builds (SwiftPM) where no packaged tools directory exists,- /// so the environment is left to inherit unchanged there.- static let bundledToolsDirectory: URL? = {- guard let dir = Bundle.main.resourceURL?+ /// The directory holding the bundled command-line tools (`ffmpeg`/`yt-dlp`/...), which skills invoke+ /// by bare name and rely on being on the shell PATH. Resolved fresh each call (not cached) so tools+ /// that `BundledToolsInstaller` downloads after launch are picked up without a relaunch.+ ///+ /// Preference order: the first-run download in Application Support, then a copy baked into the app+ /// bundle (the offline override, or a dev symlink). `nil` when neither exists, so the child process+ /// inherits the environment unchanged and skills fall back to whatever the user has installed.+ static var bundledToolsDirectory: URL? {+ let installed = BundledTools.installDirectory+ if BundledTools.isInstalled(at: installed) {+ return installed+ }+ if let baked = Bundle.main.resourceURL?.appendingPathComponent("donkey-tools", isDirectory: true),- FileManager.default.fileExists(atPath: dir.path)- else {- return nil+ FileManager.default.fileExists(atPath: baked.path) {+ return baked}- return dir- }()+ return nil+ }/// The environment for a `shell_exec` child: the app's environment with the bundled/// tools directory appended to PATH. Appended, not prepended, so a tool the user hasdiff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.mdindex 633038ba..e49cc3d9 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md@@ -10,6 +10,12 @@ tools: shell_exec, llm.generatename. Downloading and writing files is reversible — propose the command and letthe consent gate handle approval; do not fall back to a browser.+Never probe for or install Homebrew (or any package manager), and never check+whether these tools exist first — just run them by bare name. The app installs+them itself on first launch; if one is briefly missing the command fails with+`command not found`, in which case say the media tools are still installing and+stop. Do not try to install anything.+## Download from a URL (yt-dlp)- Always single-quote the URL — `?` and `&` are shell metacharacters: `yt-dlp -P ~/Downloads 'URL'`.- Default the destination to `~/Downloads`; honor a different folder only if the user names one. yt-dlp already picks the best quality.diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/bundled-tools.json b/apps/Donkey/Sources/DonkeyRuntime/Resources/bundled-tools.jsonnew file mode 100644index 00000000..dfa1008a--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/bundled-tools.json@@ -0,0 +1,7 @@+{+ "_comment": "Single source of truth for the prebuilt CLI tools bundle (ffmpeg, yt-dlp, ...) the app downloads on first run. Produced and published by scripts/publish-bundled-tools.sh, which builds the tools, uploads the tarball as a GitHub release asset, and rewrites version+sha256 here. The app (BundledToolsInstaller) and the dev script (ensure-bundled-tools.sh) both read this. An empty sha256 means nothing is published yet: the installer no-ops and dev falls back to building from source.",+ "version": "2026.06.22",+ "arch": "arm64",+ "url": "https://github.com/DonkeyUseCorp/Donkey/releases/download/bundled-tools-2026.06.22/donkey-tools-2026.06.22-arm64.tar.gz",+ "sha256": ""+}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/BundledToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/BundledToolsTests.swiftnew file mode 100644index 00000000..76379808--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/BundledToolsTests.swift@@ -0,0 +1,43 @@+import DonkeyRuntime+import Foundation+import Testing++@Suite+struct BundledToolsTests {+ private func decode(_ json: String) -> BundledTools.Manifest? {+ try? JSONDecoder().decode(BundledTools.Manifest.self, from: Data(json.utf8))+ }++ @Test+ func emptyChecksumMeansNotPublished() {+ // An empty sha256 is the "nothing published yet" sentinel: callers must not download.+ let m = decode(#"{"version":"1","arch":"arm64","url":"https://x/y.tar.gz","sha256":""}"#)+ #expect(m?.isPublished == false)+ }++ @Test+ func realChecksumAndURLMeansPublished() {+ let m = decode(#"{"version":"1","arch":"arm64","url":"https://x/y.tar.gz","sha256":"abc123"}"#)+ #expect(m?.isPublished == true)+ }++ @Test+ func malformedURLIsNotPublished() {+ let m = decode(#"{"version":"1","arch":"arm64","url":"","sha256":"abc123"}"#)+ #expect(m?.isPublished == false)+ }++ @Test+ func shippedManifestLoadsAndNamesAnArm64Asset() {+ // The manifest bundled into the app must parse and point at a versioned arm64 tools asset.+ let m = BundledTools.loadManifest()+ #expect(m != nil)+ #expect(m?.arch == "arm64")+ #expect(m?.url.contains("donkey-tools") == true)+ }++ @Test+ func installDirectoryIsUnderApplicationSupport() {+ #expect(BundledTools.installDirectory.path.contains("Application Support/Donkey/donkey-tools"))+ }+}