Open source CapCut alternative.
TypeScript
fix(app): pin bundled tools to each app version
David Leec6cc42361a2
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex 9c611a2c..c49c21eb 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -226,7 +226,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {conversation.status != .failed else {return}- if BundledTools.installedVersion != nil {+ if BundledTools.isCurrentVersionReady {updateConversation(id: id, detail: "Tools ready", status: .completed)} else {notchConversations.removeAll { $0.id == id }@@ -433,8 +433,8 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {updateChecker.checkForUpdatesInBackground()}- func showUpdateUI() {- updateChecker.showUpdateUI()+ func installAvailableUpdate() {+ updateChecker.installAvailableUpdate()}/// Push the logged-out state into the notch. The app delegate drives this from the authdiff --git a/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift b/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swiftindex 2073cc53..65c15a3e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift@@ -38,33 +38,75 @@ public enum BundledTools {}}- /// 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 {+ /// Parent of the per-version tool installs. Writable, survives app updates, and is where+ /// `shellEnvironment()` looks for the tools on PATH. Each published bundle lives in its own+ /// `<baseDirectory>/<version>` subdirectory (see `installDirectory(forVersion:)`), so an app build+ /// reads and writes only the version its manifest pins — a different build (e.g. a dev copy) installing+ /// another version into a sibling directory cannot disturb it. The overlay symlink dir is a sibling of+ /// this one.+ public static var baseDirectory: 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)+ /// Where a specific bundle version is installed. The version string IS the directory name, so the+ /// directory itself records which bundle is present — there is no separate marker file to drift out of+ /// sync with the bytes on disk.+ public static func installDirectory(forVersion version: String) -> URL {+ baseDirectory.appendingPathComponent(version, isDirectory: true)}- /// 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.+ /// The bundle is usable if a sentinel tool exists in the 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+ /// A pre-namespacing install: ffmpeg sits directly under `baseDirectory` instead of in a `<version>`+ /// subdirectory. The installer clears such a layout once before installing the versioned set, so an+ /// app updated from an older build reclaims the loose copy rather than leaving it as orphaned cruft.+ public static var hasLegacyFlatInstall: Bool { isInstalled(at: baseDirectory) }++ /// Installed bundle versions present on disk — each a `<baseDirectory>/<version>` directory holding a+ /// usable ffmpeg — ordered most-recently-used first (the installer refreshes a version's mtime on every+ /// launch that uses it). Empty when nothing is installed. The legacy flat layout is not a version+ /// directory, so it never appears here.+ public static func installedVersions() -> [URL] {+ let fileManager = FileManager.default+ let entries = (try? fileManager.contentsOfDirectory(+ at: baseDirectory,+ includingPropertiesForKeys: [.contentModificationDateKey]+ )) ?? []+ func modified(_ url: URL) -> Date {+ (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast+ }+ return entries.filter { isInstalled(at: $0) }.sorted { modified($0) > modified($1) }+ }++ /// The install directory the running app should use right now: the version its manifest pins when that+ /// version is installed, otherwise the most-recently-used installed version (so usable tools still+ /// resolve while the pinned version is still downloading, or when the manifest can't be read). `nil`+ /// only when no tools are installed at all.+ public static func resolvedInstallDirectory() -> URL? {+ if let version = loadManifest()?.version {+ let pinned = installDirectory(forVersion: version)+ if isInstalled(at: pinned) { return pinned }+ }+ if let newest = installedVersions().first { return newest }+ // A pre-namespacing flat install still has usable tools until the versioned install replaces them,+ // so a build updated from an older copy keeps its capabilities through the one-time migration.+ return hasLegacyFlatInstall ? baseDirectory : nil+ }++ /// Whether the tools this app build pins are ready, i.e. setup has nothing left to do: the manifest's+ /// version is installed, or — when nothing is published — any usable tools exist (a dev symlink or+ /// offline-baked copy). Drives the "setup already done" decisions.+ public static var isCurrentVersionReady: Bool {+ if let manifest = loadManifest(), manifest.isPublished {+ return isInstalled(at: installDirectory(forVersion: manifest.version))+ }+ return resolvedInstallDirectory() != nil}/// Load the bundled manifest from the app's resources. Returns nil if it is missing or malformed.diff --git a/apps/Donkey/Sources/DonkeyRuntime/BundledToolsInstaller.swift b/apps/Donkey/Sources/DonkeyRuntime/BundledToolsInstaller.swiftindex 0b8c8e09..6c43a063 100644--- a/apps/Donkey/Sources/DonkeyRuntime/BundledToolsInstaller.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/BundledToolsInstaller.swift@@ -34,6 +34,11 @@ public actor BundledToolsInstaller {/// first run shouldn't strand the tools; the app retries here and again on the next launch.private static let maxAttempts = 3+ /// How many recently-used bundle versions to keep alongside the current one. A dev build and a prod+ /// build pin different versions, so more than one survives; the cap stops the per-version store from+ /// growing without bound as versions roll (each extracted bundle is ~180MB on disk).+ private static let versionsToKeep = 3+enum InstallError: Error {case badURLcase checksumMismatch(expected: String, got: String)@@ -56,15 +61,21 @@ public actor BundledToolsInstaller {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.- let present = BundledTools.isInstalled(at: BundledTools.installDirectory)- if present { repairSelfExtractingTools(in: BundledTools.installDirectory) }- return present+ if let present = BundledTools.resolvedInstallDirectory() {+ repairSelfExtractingTools(in: present)+ return true+ }+ return false}- if BundledTools.installedVersion == manifest.version {- // Already current — but still make sure the self-extracting tools actually launch. A copy that- // shipped signed with the hardened runtime but no library-validation exception can't start at- // all, and the version match alone would hide that until a skill tried to run the tool.- repairSelfExtractingTools(in: BundledTools.installDirectory)+ // This build pins exactly one bundle version; it only ever reads and writes that version's own+ // directory, so a different build's version sitting in a sibling directory is irrelevant here.+ let dest = BundledTools.installDirectory(forVersion: manifest.version)+ if BundledTools.isInstalled(at: dest) {+ // Already installed — but still make sure the self-extracting tools actually launch (a hardened+ // copy without the library-validation exception can't start, which the presence check alone+ // would hide), and refresh the mtime so version GC treats this version as in-use.+ touch(dest)+ repairSelfExtractingTools(in: dest)return true}guard !installing else { return false }@@ -76,7 +87,7 @@ public actor BundledToolsInstaller {onEvent?(.started)for attempt in 1...Self.maxAttempts {do {- try await install(manifest, onEvent: onEvent)+ try await install(manifest, into: dest, onEvent: onEvent)log.info("installed bundled tools \(manifest.version, privacy: .public)")onEvent?(.completed)return true@@ -91,11 +102,14 @@ public actor BundledToolsInstaller {}}onEvent?(.failed)- return BundledTools.isInstalled(at: BundledTools.installDirectory)+ // Even when this build's pinned version failed to install, the app still has usable tools whenever+ // any version is present (the agent keeps working), so report that rather than a hard "no tools".+ return BundledTools.resolvedInstallDirectory() != nil}private func install(_ manifest: BundledTools.Manifest,+ into dest: URL,onEvent: (@Sendable (BundledToolsSetupEvent) -> Void)?) async throws {guard let url = URL(string: manifest.url) else { throw InstallError.badURL }@@ -119,14 +133,54 @@ public actor BundledToolsInstaller {try extractTarGz(downloaded, into: staging)let root = try resolveToolsRoot(in: staging)- let dest = BundledTools.installDirectory+ clearLegacyFlatInstall()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)repairSelfExtractingTools(in: dest)- try manifest.version.write(to: BundledTools.installedVersionMarker, atomically: true, encoding: .utf8)+ touch(dest)+ pruneOldVersions(keeping: manifest.version)+ }++ /// Stamp the version directory's mtime as "just used" so version GC keeps the bundles an app build+ /// actually launches. Called on both the already-installed and the freshly-installed paths.+ private func touch(_ directory: URL) {+ try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: directory.path)+ }++ /// Remove a pre-namespacing flat install (loose ffmpeg + dylibs + the old `.version` marker directly+ /// under `baseDirectory`) the one time it is found, so an app updated from an older build reclaims that+ /// copy instead of leaving ~180MB of orphaned files. A version install is a subdirectory that itself+ /// holds ffmpeg; those are never touched, so this can't delete a sibling build's pinned tools.+ private func clearLegacyFlatInstall() {+ guard BundledTools.hasLegacyFlatInstall else { return }+ let fm = FileManager.default+ let entries = (try? fm.contentsOfDirectory(+ at: BundledTools.baseDirectory,+ includingPropertiesForKeys: [.isDirectoryKey]+ )) ?? []+ for entry in entries {+ let isDirectory = (try? entry.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false+ if isDirectory && BundledTools.isInstalled(at: entry) { continue }+ try? fm.removeItem(at: entry)+ }+ }++ /// Keep the current version plus the few most-recently-used others, reclaiming truly stale installs so+ /// the tools store can't grow without bound as versions roll. mtime is refreshed on each launch that+ /// uses a version, so a dev build and a prod build that are both in active use both survive; only a+ /// version nothing has launched in a while ages out (and re-downloads on demand, which the now-immutable+ /// published assets make reliable).+ private func pruneOldVersions(keeping current: String) {+ let fm = FileManager.default+ let versions = BundledTools.installedVersions() // most-recently-used first+ var keep = Set(versions.prefix(Self.versionsToKeep).map { $0.lastPathComponent })+ keep.insert(current)+ for directory in versions where !keep.contains(directory.lastPathComponent) {+ try? fm.removeItem(at: directory)+ }}/// Download the archive to a temp file, reporting fractional progress as the bytes arrive. Adiff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex 6beb5c38..7e56a7a3 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -1163,8 +1163,7 @@ public enum DonkeyCommandBackends {return baked}}- let installed = BundledTools.installDirectory- if BundledTools.isInstalled(at: installed) {+ if let installed = BundledTools.resolvedInstallDirectory() {return installed}if let baked = Bundle.main.resourceURL?@@ -1232,7 +1231,7 @@ public enum DonkeyCommandBackends {private static func preferredBundledToolsOverlay() -> URL? {guard let toolsDirectory = bundledToolsDirectory else { return nil }let fileManager = FileManager.default- let overlay = BundledTools.installDirectory+ let overlay = BundledTools.baseDirectory.deletingLastPathComponent().appendingPathComponent("donkey-tools-preferred", isDirectory: true)do {@@ -1245,9 +1244,9 @@ public enum DonkeyCommandBackends {let target = toolsDirectory.appendingPathComponent(name)guard fileManager.isExecutableFile(atPath: target.path) else { continue }let link = overlay.appendingPathComponent(name)- // Recreate only when missing or pointing at a stale target — the bundled dir can move from the- // baked app copy to the downloaded install dir between launches, but an in-place version bump- // keeps the same path so the symlink stays valid and this is a no-op.+ // Recreate only when missing or pointing at a stale target — the bundled dir can move between+ // launches (the baked app copy, or a per-version download dir whose path changes when the+ // pinned version changes), so relink whenever the target no longer matches and otherwise no-op.if (try? fileManager.destinationOfSymbolicLink(atPath: link.path)) != target.path {try? fileManager.removeItem(at: link)try? fileManager.createSymbolicLink(at: link, withDestinationURL: target)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/BundledToolsTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/BundledToolsTests.swiftindex 76379808..2b56fb30 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/BundledToolsTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/BundledToolsTests.swift@@ -37,7 +37,16 @@ struct BundledToolsTests {}@Test- func installDirectoryIsUnderApplicationSupport() {- #expect(BundledTools.installDirectory.path.contains("Application Support/Donkey/donkey-tools"))+ func baseDirectoryIsUnderApplicationSupport() {+ #expect(BundledTools.baseDirectory.path.contains("Application Support/Donkey/donkey-tools"))+ }++ @Test+ func installDirectoryNestsTheVersionUnderBase() {+ // Each published version installs into its own `<base>/<version>` directory, so one app build's+ // pinned tools can never overwrite another's. The version IS the directory name.+ let dir = BundledTools.installDirectory(forVersion: "2026.06.25")+ #expect(dir.deletingLastPathComponent().path == BundledTools.baseDirectory.path)+ #expect(dir.lastPathComponent == "2026.06.25")}}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swiftindex 51afc36d..69517144 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/FunctionalEval/FunctionalEvalFixture.swift@@ -151,7 +151,8 @@ enum ShellHelper {// vendor dir, set by the eval toolchain) wins over the Application Support install — and point// pdfium at that dir so `lit` can parse PDFs, matching production.let toolsPath = environment["DONKEY_TOOLS_DIR"].flatMap { $0.isEmpty ? nil : $0 }- ?? BundledTools.installDirectory.path+ ?? BundledTools.resolvedInstallDirectory()?.path+ ?? BundledTools.baseDirectory.pathenvironment["PATH"] = (environment["PATH"] ?? "/usr/bin:/bin:/opt/homebrew/bin") + ":" + toolsPathenvironment["PDFIUM_LIB_PATH"] = toolsPathprocess.environment = environmentdiff --git a/docs/guides/releasing-donkey.md b/docs/guides/releasing-donkey.mdindex 70dddf3b..aa922d75 100644--- a/docs/guides/releasing-donkey.md+++ b/docs/guides/releasing-donkey.md@@ -55,12 +55,22 @@ The capability skills (media, pdf) run CLI tools — `ffmpeg`, `yt-dlp`, and a fothers — that the app downloads once the user signs in (so the bundle stays outof the app download, and isn't fetched for someone who never gets past sign-in).The download surfaces in the notch as a progress conversation the user can watch-but not stop or dismiss; it retries on its own and no-ops once the published-version is already installed. The `Publish Bundled Tools` workflow builds them from source on an+but not stop or dismiss; it retries on its own and no-ops once the version this+build pins is already installed. The `Publish Bundled Tools` workflow builds them from source on anarm64 runner, signs and notarizes them, uploads the bundle as a GitHub releaseasset, and commits the refreshed `bundled-tools.json` (the manifest the app readsto know what to fetch). It runs on demand and whenever the tools recipe changes.+Each manifest pins one bundle version by sha256, and that pairing is permanent.+Every published version installs into its own `donkey-tools/<version>/` directory,+so an app build reads and writes only the version it pins — a dev build and a+released build keep separate copies and never disturb each other. Published assets+are immutable to match: re-publishing a version that already has an asset+auto-bumps to `<version>.1` instead of overwriting it, so the bytes a shipped app+pinned always stay fetchable and pass verification. (The bug this prevents: a+date-named version was once re-uploaded with different bytes, and every app that+had pinned the original sha could no longer finish tool setup.)+Every tool is re-signed during the build: relocating their bundled librariesinvalidates the original signature, and macOS will not run an unsigned binary onApple Silicon. Without the secrets below the tools are only ad-hoc signed — finediff --git a/scripts/publish-bundled-tools.sh b/scripts/publish-bundled-tools.shindex e619f233..7c628023 100755--- a/scripts/publish-bundled-tools.sh+++ b/scripts/publish-bundled-tools.sh@@ -8,7 +8,11 @@# Run on an arm64 macOS build machine with Homebrew + Xcode and an authenticated `gh`. Usage:# scripts/publish-bundled-tools.sh [version] # version defaults to today's date (YYYY.MM.DD)#-# After it finishes, commit the updated bundled-tools.json so the app ships pointing at the new asset.+# Published assets are IMMUTABLE: once a version's tarball exists on its release, that version is frozen,+# because a shipped app pins it by sha256 and could never re-verify different bytes. If the chosen version+# already has a published asset, this auto-bumps to <version>.1, .2, … rather than clobbering it — so a+# same-day re-publish becomes a new version. After it finishes, commit the updated bundled-tools.json so+# the app ships pointing at the new asset.set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -18,7 +22,24 @@ MANIFEST="$ROOT_DIR/apps/Donkey/Sources/DonkeyRuntime/Resources/bundled-tools.jsREPO="${DONKEY_TOOLS_REPO:-DonkeyUseCorp/Donkey}"ARCH="arm64"-VERSION="${1:-$(date +%Y.%m.%d)}"++# True when that release already carries that asset — i.e. the version is already published and frozen.+asset_published() { # tag asset-name+ gh release view "$1" --repo "$REPO" --json assets --jq '.assets[].name' 2>/dev/null | grep -qx "$2"+}++# Pick the first version at or after the requested one whose asset is not already published, so we never+# overwrite frozen bytes. Bumps <base> -> <base>.1 -> <base>.2 … (matching the existing .N convention).+choose_immutable_version() {+ local base="$1" v="$1" n=1+ while asset_published "bundled-tools-$v" "donkey-tools-$v-$ARCH.tar.gz"; do+ v="$base.$n"; n=$((n + 1))+ done+ [ "$v" = "$base" ] || echo "Version $base already published; using $v to keep bundles immutable." >&2+ printf '%s' "$v"+}++VERSION="$(choose_immutable_version "${1:-$(date +%Y.%m.%d)}")"TAG="bundled-tools-$VERSION"ASSET="donkey-tools-$VERSION-$ARCH.tar.gz"URL="https://github.com/$REPO/releases/download/$TAG/$ASSET"@@ -92,7 +113,9 @@ if ! gh release view "$TAG" --repo "$REPO" >/dev/null 2>&1; thengh release create "$TAG" --repo "$REPO" --title "$TAG" \--notes "Prebuilt Donkey CLI tools ($ARCH) — $VERSION."fi-gh release upload "$TAG" "$OUT" --repo "$REPO" --clobber+# No --clobber: choose_immutable_version guaranteed this asset isn't published yet, so this only ever+# uploads fresh bytes and never overwrites a version a shipped app already pinned.+gh release upload "$TAG" "$OUT" --repo "$REPO"echoecho "Published $ASSET → $URL"