Open source CapCut alternative.
TypeScript
feat(app): surface web.automate and media-call failures distinctly
David Le3d53db313ca4
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swiftindex 9184c19c..3ad2927d 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift@@ -82,9 +82,16 @@ public struct HostedTextGenerator: Sendable {return .unsupportedType(resolvedMIME)}// Reject an oversized file up front (with a chunk-it signal) rather than reading the whole- // thing just to overrun the request-body limit at the network.- if let size = Self.fileByteSize(attachmentPath), size > Self.maxInlineMediaBytes {- return .tooLarge(bytes: size, limit: Self.maxInlineMediaBytes)+ // thing just to overrun the request-body limit at the network. The body base64-encodes the+ // bytes (~+33%), so compare the PROJECTED base64 size — `size * 4 / 3`, rounded up — against+ // the wire limit, not the raw byte count. Report the raw size and the raw-equivalent limit+ // (the largest raw file that fits under the base64 cap) so the numbers stay sensible.+ if let size = Self.fileByteSize(attachmentPath) {+ let base64Size = (size + 2) / 3 * 4+ if base64Size > Self.maxInlineMediaBytes {+ let rawEquivalentLimit = Self.maxInlineMediaBytes / 4 * 3+ return .tooLarge(bytes: size, limit: rawEquivalentLimit)+ }}// Read + base64-encode off the cooperative executor (the media arm is wired onto the always-on// Live session path), and memory-map so the raw bytes aren't held resident alongside the@@ -126,10 +133,15 @@ public struct HostedTextGenerator: Sendable {])let backend = self.backend- guard let response = try? await AIDeadline.enforce(seconds: mediaTimeoutSeconds, {- try await backend.createResponse(request)- }) else {- return .empty+ let response: RemoteInferenceJSONValue+ do {+ // A timeout or a thrown error is a retryable failure, NOT an empty model output. Catch it+ // so the caller can re-chunk / retry rather than treat it as "model returned no text".+ response = try await AIDeadline.enforce(seconds: mediaTimeoutSeconds, {+ try await backend.createResponse(request)+ })+ } catch {+ return .timedOut(reason: String(describing: error))}// A transcript cut off at the token ceiling comes back non-empty but incomplete; surface it as// truncated so the caller re-chunks instead of writing a silently-partial subtitle file.@@ -143,6 +155,8 @@ public struct HostedTextGenerator: Sendable {return .text(text)}+ /// The wire/body limit: the maximum size of the base64-encoded inline media in the request body.+ /// A raw file passes only when its base64 projection (`bytes * 4 / 3`) stays under this.private static let maxInlineMediaBytes = 14 * 1024 * 1024private static func inferredMIMEType(for url: URL) -> String? {diff --git a/apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swift b/apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swiftindex bca8f224..0a3bb8e7 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedWebAutomate.swift@@ -10,7 +10,6 @@ public struct RemoteBrowserRunStatus: Codable, Sendable {public var text: String?public var structured: String?public var recordingUrl: String?- public var liveUrl: String?public var stepCount: Intpublic var lastStepSummary: String?}@@ -25,22 +24,31 @@ public struct HostedWebAutomate: Sendable {self.backend = backend}- public func run(_ request: HarnessWebAutomateRequest) async -> String? {+ /// Runs a browser task and returns the formatted text plus whether the run actually succeeded, so+ /// the executor reports `.failed` (keeping the text as the failure message) on anything but a+ /// genuine success. `succeeded == false` covers a nil result (the backend errored/timed out) as+ /// well as a run the backend reports did not complete the task.+ public func run(_ request: HarnessWebAutomateRequest) async -> HarnessWebAutomateOutcome {guard let result = try? await backend.runBrowserTask(task: request.task,startURL: request.startURL,structuredOutputSchemaJSON: request.structuredOutputSchemaJSON) else {- return nil+ return HarnessWebAutomateOutcome(+ text: "The browser task did not complete (the run could not be reached).",+ succeeded: false+ )}- return format(result)+ return HarnessWebAutomateOutcome(text: format(result), succeeded: result.isTaskSuccessful == true)}private func format(_ status: RemoteBrowserRunStatus) -> String {var lines: [String] = []- let state = status.isTaskSuccessful == false- ? "did not fully succeed (\(status.status))"- : "completed (\(status.status))"+ // The run is only a success when the backend explicitly reports `isTaskSuccessful == true`; a+ // nil (backend sent null on error/timeout/stop) or false is surfaced as "did not fully succeed".+ let state = status.isTaskSuccessful == true+ ? "completed (\(status.status))"+ : "did not fully succeed (\(status.status))"lines.append("Browser task \(state) after \(status.stepCount) steps.")if let structured = status.structured {lines.append("")diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftindex b336aa5d..14110ee9 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -270,6 +270,20 @@ public struct HarnessWebAutomateRequest: Sendable {}}+/// The result of a `web.automate` run: the formatted text block for the agent to read plus whether+/// the run actually succeeded. The executor reports `.failed` (keeping `text` as the failure message)+/// whenever `succeeded` is false, so an errored, timed-out, or unsuccessful run is never reported as+/// a success.+public struct HarnessWebAutomateOutcome: Sendable {+ public var text: String+ public var succeeded: Bool++ public init(text: String, succeeded: Bool) {+ self.text = text+ self.succeeded = succeeded+ }+}+/// Outcome of the multimodal arm of `llm.generate` — a model call over a local audio/video file./// Distinguishes the cases a caller can act on (re-chunk a truncated transcript, fix an unreadable,/// oversized, or non-media file) instead of collapsing every failure to a bare nil.@@ -284,7 +298,10 @@ public enum HarnessMediaGenerationOutcome: Sendable {case tooLarge(bytes: Int, limit: Int)/// The file's resolved type is not audio or video.case unsupportedType(String)- /// The model returned no usable text (empty reply, timeout, or a content block).+ /// The media model call timed out or threw before producing output — retryable (re-chunk / retry),+ /// distinct from `.empty`. Carries a short reason for the trace.+ case timedOut(reason: String)+ /// The model genuinely returned an empty/whitespace string (not a timeout or thrown error).case empty}@@ -330,7 +347,7 @@ public struct HarnessBuiltInToolServices: Sendable {/// Agentic web automation: a task (navigate/click/fill/extract) in, the run's result as a text/// block out (final output, status, any recording link), or nil on failure. Backs the/// `web.automate` tool, which runs through the hosted Browser Use Cloud backend and bills credits.- public var webAutomator: (@Sendable (HarnessWebAutomateRequest) async -> String?)?+ public var webAutomator: (@Sendable (HarnessWebAutomateRequest) async -> HarnessWebAutomateOutcome)?/// The file-understanding layer behind `files.describe`: a file URL in, a structured/// `FileUnderstanding` out (OCR for images, text for PDFs, dimensions/metadata), or nil to fall/// back to the built-in Foundation understanding. The runtime supplies this; without it the tool@@ -358,7 +375,7 @@ public struct HarnessBuiltInToolServices: Sendable {mediaGenerator: (@Sendable (_ prompt: String, _ file: URL, _ mimeType: String?) async -> HarnessMediaGenerationOutcome)? = nil,webSearcher: (@Sendable (String) async -> String?)? = nil,webFetcher: (@Sendable (String) async -> String?)? = nil,- webAutomator: (@Sendable (HarnessWebAutomateRequest) async -> String?)? = nil,+ webAutomator: (@Sendable (HarnessWebAutomateRequest) async -> HarnessWebAutomateOutcome)? = nil,fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)? = nil,imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)? = nil) {@@ -1712,6 +1729,10 @@ public enum BuiltInHarnessToolExecutors {return failed(context, "The media file is \(bytes / 1_000_000)MB, over the \(limit / 1_000_000)MB inline limit — extract compact audio or split it into chunks.", reason: "mediaFileTooLarge")case .unsupportedType(let mime):return failed(context, "llm.generate `filePath` must be audio or video; got \(mime). Pass an explicit `mimeType` if the extension is unusual.", reason: "mediaUnsupportedType")+ case .timedOut(let reason):+ // A timeout or thrown error is retryable — surface it as such rather than as "no text"+ // so the planner re-chunks or retries instead of giving up.+ return failed(context, "The media model call did not finish (\(reason)) — split the media into shorter chunks and retry.", reason: "mediaTimedOut")case .empty:generated = nil}@@ -1874,8 +1895,18 @@ public enum BuiltInHarnessToolExecutors {startURL: trimmed(context.call.input["startUrl"]),structuredOutputSchemaJSON: trimmed(context.call.input["schema"]))- guard let result = await automator(request), !result.isEmpty else {- return failed(context, "The browser task did not complete.", reason: "webAutomateFailed")+ let outcome = await automator(request)+ let result = outcome.text+ // Report failure (keeping the diagnostic text) whenever the run did not genuinely succeed —+ // an errored, timed-out, or unsuccessful run must never be surfaced to the agent as a success.+ guard outcome.succeeded, !result.isEmpty else {+ let message = result.isEmpty ? "The browser task did not complete." : result+ return failed(+ context,+ message.count > 600 ? String(message.prefix(600)) + "…" : message,+ reason: "webAutomateFailed",+ metadata: ["text": message]+ )}return success(context,@@ -1990,17 +2021,18 @@ public enum BuiltInHarnessToolExecutors {private static func failed(_ context: HarnessToolExecutionContext,_ summary: String,- reason: String+ reason: String,+ metadata: [String: String] = [:]) -> HarnessToolResult {HarnessToolResult(callID: context.call.id,toolName: context.call.name,status: .failed,summary: summary,- metadata: [+ metadata: metadata.merging(["executor": "builtInGeneric","reason": reason- ]+ ]) { _, reserved in reserved })}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 496b0b89..c0c9741a 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -310,6 +310,9 @@ struct GenericHarnessTests {(.unreadableFile, "mediaFileUnreadable"),(.tooLarge(bytes: 20_000_000, limit: 14_000_000), "mediaFileTooLarge"),(.unsupportedType("image/png"), "mediaUnsupportedType"),+ // A timeout / thrown error is retryable and must reach the planner as its own reason, not+ // as "no text".+ (.timedOut(reason: "deadline"), "mediaTimedOut"),(.empty, "emptyGeneration")]for (outcome, expectedReason) in cases {