Open source CapCut alternative.
TypeScript
feat(app): spawn and supervise the Cut engine in the Donkey app
David Lee8ac9e91fd16
diff --git a/.github/workflows/nightly-donkey-build.yml b/.github/workflows/nightly-donkey-build.ymlindex aea42b16..4e53eb6a 100644--- a/.github/workflows/nightly-donkey-build.yml+++ b/.github/workflows/nightly-donkey-build.yml@@ -89,6 +89,15 @@ jobs:brew install imagemagickfi+ # The Donkey Cut engine — the local server behind cut.donkeyuse.com — ships inside the+ # app and is version-locked to it. Built from site/ with bun (a devDependency there).+ - name: Build Donkey Cut engine+ if: steps.changes.outputs.should_build == 'true'+ working-directory: site+ run: |+ npm ci+ npm run engine:build+# The bundled CLI tools (ffmpeg, lit, pdf-fill, …) are NOT baked into the app: it downloads# them on first run from the artifact published by the Publish Bundled Tools workflow, so the# nightly package builds without vendoring them here.@@ -97,6 +106,7 @@ jobs:env:DONKEY_APP_VERSION: ${{ steps.nightly.outputs.version }}DONKEY_APP_BUILD: ${{ steps.nightly.outputs.build }}+ DONKEY_CUT_ENGINE_BIN: ${{ github.workspace }}/site/dist/cut-engine/donkey-cut-engine-arm64run: ./scripts/package-donkey-app.sh- name: Generate checksumdiff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swiftindex 4c6ff705..df74bdcb 100644--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift@@ -30,6 +30,9 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {/// run only while signed in and are torn down on sign-out.private var sessionHeartbeatTimer: Timer?private var sessionHeartbeatActiveObserver: NSObjectProtocol?+ /// Runs the Donkey Cut engine (the local server behind cut.donkeyuse.com) for the app's+ /// lifetime. Cut is free and standalone, so this starts regardless of sign-in state.+ private var cutEngineSupervisor: DonkeyCutEngineSupervisor?func applicationDidFinishLaunching(_ notification: Notification) {if ManualCaptureDebugLaunchHandler.shouldHandle(arguments: CommandLine.arguments) {@@ -59,6 +62,10 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {registerAuthCallbackHandler()installMainMenu()+ let cutEngineSupervisor = DonkeyCutEngineSupervisor()+ self.cutEngineSupervisor = cutEngineSupervisor+ cutEngineSupervisor.start()+// First install (never signed in) opens the onboarding card on its sign-in landing. A returning// user whose session has expired skips it: the notch comes up in login mode (driven by the auth// phase observer) and carries them back through sign-in inline.@@ -110,6 +117,7 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {)overlayController?.stop()uiUnderstandingCoordinator?.stop()+ cutEngineSupervisor?.stop()}/// Where to open the onboarding card.diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCutEngineSupervisor.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCutEngineSupervisor.swiftnew file mode 100644index 00000000..67562e4b--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCutEngineSupervisor.swift@@ -0,0 +1,148 @@+import Foundation++/// Runs the Donkey Cut engine — the local server behind cut.donkeyuse.com — for the app's lifetime.+///+/// Cut's page is static html/js served from the hosted site; everything real (project files, ffmpeg,+/// on-device speech, the user's own claude/codex logins) happens in this engine on 127.0.0.1. The app+/// spawns it at launch, restarts it with backoff if it dies, and terminates it on quit. The engine is+/// version-locked to the app: updates ride app releases, and the stamped version feeds the site's+/// update nudge.+///+/// Cut is free and standalone, so the engine runs regardless of Donkey sign-in state.+public final class DonkeyCutEngineSupervisor: @unchecked Sendable {+ /// The port the Cut client probes (see the site's engine discovery).+ private static let port = 41417++ /// All mutable state is confined to this queue.+ private let queue = DispatchQueue(label: "donkey.cut-engine-supervisor")+ private var process: Process?+ private var stopped = false+ private var restartDelay: TimeInterval = 2+ private var spawnedAt: Date?++ public init() {}++ public func start() {+ queue.async { self.spawnIfNeeded() }+ }++ public func stop() {+ queue.sync {+ stopped = true+ process?.terminate()+ process = nil+ }+ }++ /// The engine binary: a dev/test override first, then the copy shipped in the app bundle.+ /// `nil` (e.g. a dev build made without the site checkout) just means Donkey runs without Cut.+ private static func engineBinary() -> URL? {+ let fileManager = FileManager.default+ if let raw = getenv("DONKEY_CUT_ENGINE_BIN") {+ let override = String(cString: raw)+ if !override.isEmpty {+ let url = URL(fileURLWithPath: (override as NSString).expandingTildeInPath)+ if fileManager.isExecutableFile(atPath: url.path) { return url }+ }+ }+ guard let baked = Bundle.main.resourceURL?+ .appendingPathComponent("cut-engine", isDirectory: true)+ .appendingPathComponent("donkey-cut-engine")+ else { return nil }+ return fileManager.isExecutableFile(atPath: baked.path) ? baked : nil+ }++ /// Thread-crossing result box for the synchronous health probe.+ private final class Flag: @unchecked Sendable {+ var value = false+ }++ /// True when something on the port already answers as a Cut engine — another app instance or a+ /// dev server. Don't fight it; check again later.+ private func portAlreadyServed() -> Bool {+ guard let url = URL(string: "http://127.0.0.1:\(Self.port)/api/cut/engine/health") else { return false }+ var request = URLRequest(url: url)+ request.timeoutInterval = 1.0+ let semaphore = DispatchSemaphore(value: 0)+ let healthy = Flag()+ URLSession.shared.dataTask(with: request) { data, _, _ in+ if let data, let body = String(data: data, encoding: .utf8), body.contains("donkey-cut") {+ healthy.value = true+ }+ semaphore.signal()+ }.resume()+ semaphore.wait()+ return healthy.value+ }++ private func spawnIfNeeded() {+ guard !stopped, process == nil else { return }+ guard let binary = Self.engineBinary() else { return }+ if portAlreadyServed() {+ scheduleRespawn(after: 60)+ return+ }++ var environment = DonkeyCommandBackends.shellEnvironment()+ environment["DONKEY_CUT_ENGINE"] = "1"+ environment["DONKEY_CUT_VERSION"] =+ Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev"+ if let tools = DonkeyCommandBackends.bundledToolsDirectory {+ environment["DONKEY_CUT_TOOLS_DIR"] = tools.path+ }++ let child = Process()+ child.executableURL = binary+ child.environment = environment+ child.currentDirectoryURL = FileManager.default.homeDirectoryForCurrentUser+ let log = Self.openLog()+ child.standardOutput = log ?? FileHandle.nullDevice+ child.standardError = log ?? FileHandle.nullDevice+ child.terminationHandler = { [weak self] _ in+ guard let self else { return }+ self.queue.async {+ self.process = nil+ guard !self.stopped else { return }+ // A crash after a healthy stretch restarts promptly; rapid crash loops back off.+ let uptime = self.spawnedAt.map { Date().timeIntervalSince($0) } ?? 0+ if uptime > 300 { self.restartDelay = 2 }+ let delay = self.restartDelay+ self.restartDelay = min(self.restartDelay * 2, 60)+ self.scheduleRespawn(after: delay)+ }+ }++ do {+ try child.run()+ process = child+ spawnedAt = Date()+ } catch {+ scheduleRespawn(after: 60)+ }+ }++ private func scheduleRespawn(after delay: TimeInterval) {+ queue.asyncAfter(deadline: .now() + delay) { [weak self] in+ self?.spawnIfNeeded()+ }+ }++ /// Engine stdout/stderr land in ~/Library/Logs/Donkey/cut-engine.log; truncated when it grows+ /// past a few MB so it never balloons.+ private static func openLog() -> FileHandle? {+ let fileManager = FileManager.default+ let dir = fileManager.urls(for: .libraryDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Logs", isDirectory: true)+ .appendingPathComponent("Donkey", isDirectory: true)+ let file = dir.appendingPathComponent("cut-engine.log")+ try? fileManager.createDirectory(at: dir, withIntermediateDirectories: true)+ let size = (try? fileManager.attributesOfItem(atPath: file.path))?[.size] as? Int ?? 0+ if size > 5_000_000 { try? fileManager.removeItem(at: file) }+ if !fileManager.fileExists(atPath: file.path) {+ fileManager.createFile(atPath: file.path, contents: nil)+ }+ guard let handle = try? FileHandle(forWritingTo: file) else { return nil }+ handle.seekToEndOfFile()+ return handle+ }+}diff --git a/scripts/package-donkey-app.sh b/scripts/package-donkey-app.shindex 8078df85..3482b3dd 100755--- a/scripts/package-donkey-app.sh+++ b/scripts/package-donkey-app.sh@@ -323,6 +323,43 @@ stage_bundled_tools() {echo "Baked bundled tools from $source_dir into $dest_dir (offline override)."}+# The Donkey Cut engine — the local server behind cut.donkeyuse.com — is built from site/ by+# `npm run engine:build` and version-locked to the app. Point DONKEY_CUT_ENGINE_BIN at the built+# binary to bundle it; unset ships the app without Cut support.+stage_cut_engine() {+ local source_bin="${DONKEY_CUT_ENGINE_BIN:-}"+ if [ -z "$source_bin" ]; then+ echo "Not bundling the Donkey Cut engine (DONKEY_CUT_ENGINE_BIN unset)."+ return 0+ fi+ if [ ! -f "$source_bin" ]; then+ echo "DONKEY_CUT_ENGINE_BIN=$source_bin does not exist." >&2+ exit 1+ fi+ local dest_dir="$RESOURCES_DIR/cut-engine"+ mkdir -p "$dest_dir"+ cp "$source_bin" "$dest_dir/donkey-cut-engine"+ chmod +x "$dest_dir/donkey-cut-engine"+ # Bun-compiled binaries JIT through JavaScriptCore; under the hardened runtime they need the+ # JIT entitlements or the engine crashes at launch on a notarized build.+ local ents+ ents="$(mktemp -t cut-engine-entitlements).plist"+ cat > "$ents" <<'PLIST'+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+ <key>com.apple.security.cs.allow-jit</key><true/>+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/>+</dict></plist>+PLIST+ local sopts=(--force --sign "$APP_SIGN_IDENTITY")+ [ "$APP_SIGN_IDENTITY" != "-" ] && sopts+=(--options runtime --timestamp --entitlements "$ents")+ [ -n "${DONKEY_SIGN_KEYCHAIN:-}" ] && sopts+=(--keychain "$DONKEY_SIGN_KEYCHAIN")+ codesign "${sopts[@]}" "$dest_dir/donkey-cut-engine" >/dev/null 2>&1 || true+ rm -f "$ents"+ echo "Bundled the Donkey Cut engine from $source_bin."+}+rm -rf "$APP_DIR"mkdir -p "$MACOS_DIR" "$RESOURCES_DIR" "$FRAMEWORKS_DIR"cp "$EXECUTABLE" "$MACOS_DIR/Donkey"@@ -370,6 +407,7 @@ if [ -n "$SPARKLE_FRAMEWORK" ]; thenfistage_bundled_tools+stage_cut_engineSPARKLE_PLIST_KEYS=""if [ -n "$SPARKLE_FEED_URL" ] && [ -n "$SPARKLE_PUBLIC_ED_KEY" ]; thendiff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex 9b9ce785..62be8cb1 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -483,6 +483,16 @@ create_debug_app_bundle() {ln -sfn "$ROOT_DIR/vendor/donkey-tools" "$RESOURCES_DIR/donkey-tools"fi+ # Stage the Donkey Cut engine (built by `npm run engine:build` in site/) so the app+ # supervises it in dev. Optional: a build without it simply runs Donkey without Cut.+ cut_engine_arch="$(uname -m)"+ [ "$cut_engine_arch" = "x86_64" ] && cut_engine_arch="x64"+ cut_engine="$ROOT_DIR/site/dist/cut-engine/donkey-cut-engine-$cut_engine_arch"+ if [ -f "$cut_engine" ]; then+ mkdir -p "$RESOURCES_DIR/cut-engine"+ ln -sf "$cut_engine" "$RESOURCES_DIR/cut-engine/donkey-cut-engine"+ fi+sparkle_framework="$(find "$APP_DIR/.build" -path "*/debug/Sparkle.framework" -type d | head -n 1 || true)"if [ -n "$sparkle_framework" ]; thencp -R "$sparkle_framework" "$FRAMEWORKS_DIR/"