Open source CapCut alternative.
TypeScript
feat(app): centralize agent status in a typed activity model
David Le11de79df729a
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex 6fbc4f50..20874700 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -554,8 +554,7 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {activeTaskIDs.insert(taskID)lastActiveTaskID = taskID- updateTask(id: taskID, detail: "Paused", status: .paused)- appendTaskEvent(taskID: taskID, role: .system, text: "Paused")+ announceLifecycle(taskID: taskID, UserQueryActivity(kind: .paused), status: .paused)syncPrimaryTaskPausedFlag()Task { [commandHandler] in_ = await commandHandler.pauseCommand(taskID: taskID)@@ -570,9 +569,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {activeTaskIDs.insert(taskID)lastActiveTaskID = taskID- updateTask(id: taskID, detail: "Running", status: .running)+ // The live line falls back to the running activity ("Working"); the record logs "Resuming".+ announceLifecycle(taskID: taskID, UserQueryActivity(kind: .resumed), status: .running, liveDetail: "")updateSpawn(id: spawnStates.first { $0.taskID == taskID }?.id, resumesWork: true)- appendTaskEvent(taskID: taskID, role: .system, text: "Resumed")promptState.leadingSignalLevel = .thinkingpromptState.promptText = task.titlesyncPrimaryTaskPausedFlag()@@ -613,9 +612,15 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {// A Live-path shell consent resolves through the Live controller, which// re-executes the held command and reports back via onActed/onResponse.if task.metadata["live.shellConsent"] == "true" {- updateTask(id: taskID, detail: "Approved — running", status: .running, metadata: [:])+ announceLifecycle(+ taskID: taskID,+ UserQueryActivity(kind: .resumed),+ status: .running,+ liveDetail: "",+ metadata: [:]+ )if let turn = liveTurn, turn.taskID == taskID {- updateSpawn(id: turn.spawnID, label: "Approved — running", resumesWork: true)+ updateSpawn(id: turn.spawnID, label: UserQueryActivity.Kind.resumed.label, resumesWork: true)restartLiveTurnWatchdog()}syncPrimaryTaskPausedFlag()@@ -627,9 +632,9 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {activeTaskIDs.insert(taskID)lastActiveTaskID = taskID- let detail = Self.permissionApprovalDetail(for: task)- updateTask(id: taskID, detail: detail, status: .running)- appendTaskEvent(taskID: taskID, role: .system, text: detail)+ // After approval the task simply resumes; the live line falls back to the running activity+ // ("Working") rather than narrating an internal "approving permission" step.+ announceLifecycle(taskID: taskID, UserQueryActivity(kind: .resumed), status: .running, liveDetail: "")promptState.leadingSignalLevel = .thinkingpromptState.promptText = task.titlesyncPrimaryTaskPausedFlag()@@ -687,8 +692,11 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {}}- updateTask(id: taskID, detail: "Permission denied", status: .paused)- appendTaskEvent(taskID: taskID, role: .system, text: "Permission denied")+ announceLifecycle(+ taskID: taskID,+ UserQueryActivity(kind: .paused, summary: "Permission denied"),+ status: .paused+ )activeTaskIDs.remove(taskID)syncPrimaryTaskPausedFlag()}@@ -1089,6 +1097,33 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {return eventID}+ /// The single place a lifecycle transition announces itself. It sets the task's live status line+ /// from the typed activity, records the event in the in-app conversation store, and appends the+ /// same line to `thread.md` — so the conversation record stays the complete history we can render+ /// back to the user. New transitions pass a different `UserQueryActivity` kind; nothing else moves.+ private func announceLifecycle(+ taskID: String,+ _ activity: UserQueryActivity,+ status: UserQueryTaskStatus,+ liveDetail: String? = nil,+ metadata: [String: String]? = nil+ ) {+ updateTask(id: taskID, detail: liveDetail ?? activity.displayText, status: status, metadata: metadata)+ // In-app event store keeps plain text (structured data for the conversation view); thread.md+ // gets the icon-prefixed markdown line.+ _ = appendTaskEvent(taskID: taskID, role: .system, text: activity.displayText)+ recordThreadActivity(taskID: taskID, activity)+ }++ /// Appends a typed activity line to the task's `thread.md` conversation record. The thread file+ /// already exists from the run, so this only ever appends (off the main thread — small file IO).+ private func recordThreadActivity(taskID: String, _ activity: UserQueryActivity) {+ let line = activity.transcriptLine+ Task.detached {+ ThreadTranscript(id: taskID).systemEvent(line)+ }+ }+private func updateTask(id: String,title: String? = nil,@@ -1235,18 +1270,6 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {return "Uploaded assets: \(displayNames)"}- private static func permissionApprovalDetail(for task: UserQueryNotchTask) -> String {- let permissions = task.metadata["genericHarness.missingPermissions"]?- .split(separator: ",")- .map(String.init)- .filter { !$0.isEmpty } ?? []- guard !permissions.isEmpty else {- return "Approving permission"- }-- return "Approving \(permissions.joined(separator: ", "))"- }-private static func shouldShowChangedCourseState(for task: UserQueryNotchTask) -> Bool {switch task.status {case .running, .interrupted:diff --git a/apps/Donkey/Sources/DonkeyContracts/UserQueryActivity.swift b/apps/Donkey/Sources/DonkeyContracts/UserQueryActivity.swiftnew file mode 100644index 00000000..c0e8ec3d--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/UserQueryActivity.swift@@ -0,0 +1,192 @@+import Foundation++/// A typed, presentable unit of "what the agent is doing" inside a task.+///+/// This is the single, centralized vocabulary the UI speaks instead of scattering ad-hoc status+/// strings ("Approved — continuing", "Running", …) across the model and the views. It drives the+/// notch status line today and is built to back the full conversation/transcript view next: each+/// rendered line is one `UserQueryActivity`, so adding a row type later means adding a `Kind` case+/// and its presentation here — nothing else changes.+///+/// Classification only ever matches typed fields (task status, registry tool names), never raw user+/// text, per the harness rules.+public struct UserQueryActivity: Equatable, Sendable {+ /// The kinds of activity a task surfaces. Extend by adding a case plus its entry in `label`,+ /// `systemImage`, and `transcriptIcon` — those switches are exhaustive so the compiler flags any+ /// case left unpresented.+ public enum Kind: String, Codable, Equatable, Sendable, CaseIterable {+ case working // generic in-progress / thinking+ case observing // reading the screen (accessibility / vision)+ case reading // reading a file or document+ case editing // changing UI state (click, type, drag)+ case searching // looking something up+ case running // running a shell command / skill+ case browsing // navigating the web or an app+ case verifying // checking the result holds+ case message // a conversational reply+ case waitingForInput // needs the user to answer+ case waitingForPermission+ case waitingForReview+ case paused+ case resumed+ case completed+ case failed+ case interrupted+ case needsAttention+ }++ public var kind: Kind+ /// Free-text specifics (the model's narration, the consent reason, an error). Empty falls back to+ /// the kind's label.+ public var summary: String++ public init(kind: Kind, summary: String = "") {+ self.kind = kind+ self.summary = summary.trimmingCharacters(in: .whitespacesAndNewlines)+ }++ /// The user-facing one-liner: the activity's own text when it has any, else the kind's label.+ public var displayText: String {+ summary.isEmpty ? kind.label : summary+ }++ /// SF Symbol for in-app surfaces (the notch and the future conversation view).+ public var systemImage: String { kind.systemImage }++ /// The line written into the conversation record (`thread.md`), prefixed with the kind's icon so+ /// it reads on its own when the thread is rendered back to the user.+ public var transcriptLine: String {+ "\(kind.transcriptIcon) \(displayText)"+ }+}++public extension UserQueryActivity.Kind {+ /// The concise label shown when an activity has no specifics of its own.+ var label: String {+ switch self {+ case .working: return "Working"+ case .observing: return "Looking at the screen"+ case .reading: return "Reading"+ case .editing: return "Making changes"+ case .searching: return "Searching"+ case .running: return "Running a command"+ case .browsing: return "Browsing"+ case .verifying: return "Verifying"+ case .message: return "Conversation"+ case .waitingForInput: return "Waiting for your reply"+ case .waitingForPermission: return "Waiting for approval"+ case .waitingForReview: return "Waiting for your review"+ case .paused: return "Paused"+ case .resumed: return "Resuming"+ case .completed: return "Done"+ case .failed: return "Stopped"+ case .interrupted: return "Changed course"+ case .needsAttention: return "Needs attention"+ }+ }++ /// SF Symbol used by in-app surfaces.+ var systemImage: String {+ switch self {+ case .working: return "ellipsis"+ case .observing: return "eye"+ case .reading: return "doc.text"+ case .editing: return "pencil"+ case .searching: return "magnifyingglass"+ case .running: return "terminal"+ case .browsing: return "safari"+ case .verifying: return "checkmark.seal"+ case .message: return "text.bubble"+ case .waitingForInput: return "questionmark.circle"+ case .waitingForPermission: return "lock.shield"+ case .waitingForReview: return "doc.text.magnifyingglass"+ case .paused: return "pause.circle"+ case .resumed: return "play.circle"+ case .completed: return "checkmark.circle"+ case .failed: return "xmark.circle"+ case .interrupted: return "arrow.triangle.branch"+ case .needsAttention: return "exclamationmark.circle"+ }+ }++ /// Emoji used in the markdown conversation record (`thread.md`).+ var transcriptIcon: String {+ switch self {+ case .working: return "⚙️"+ case .observing: return "👀"+ case .reading: return "📄"+ case .editing: return "✏️"+ case .searching: return "🔍"+ case .running: return "⌨️"+ case .browsing: return "🧭"+ case .verifying: return "✅"+ case .message: return "💬"+ case .waitingForInput: return "❓"+ case .waitingForPermission: return "🔒"+ case .waitingForReview: return "📝"+ case .paused: return "⏸️"+ case .resumed: return "▶️"+ case .completed: return "🎉"+ case .failed: return "⚠️"+ case .interrupted: return "🔀"+ case .needsAttention: return "❗️"+ }+ }+}++public extension UserQueryActivity {+ /// Maps a task's lifecycle status to an activity kind.+ static func kind(forStatus status: UserQueryTaskStatus) -> Kind {+ switch status {+ case .chatting: return .message+ case .running: return .working+ case .paused: return .paused+ case .completed: return .completed+ case .waitingForClarification: return .waitingForInput+ case .waitingForPermission: return .waitingForPermission+ case .waitingForReview: return .waitingForReview+ case .interrupted: return .interrupted+ case .needsAttention: return .needsAttention+ case .failed: return .failed+ }+ }++ /// Classifies a running step by its registry tool name (a typed field, never user text). Unknown+ /// tools fall back to `.working`; add a case as new tool families surface in the conversation view.+ static func kind(forToolNamed name: String) -> Kind {+ let tool = name.lowercased()+ switch tool {+ case "shell_exec", "skill_run": return .running+ case "ax.observe", "vision.capture": return .observing+ case "conversation.respond": return .message+ case "user.clarify": return .waitingForInput+ case "permission.request": return .waitingForPermission+ case "run.complete": return .completed+ default: break+ }++ // Family heuristics on the typed tool name for tools not called out above.+ if tool.hasSuffix(".search") { return .searching }+ if tool.hasSuffix(".read") || tool.hasPrefix("file") { return .reading }+ if tool.hasSuffix(".verify") { return .verifying }+ if tool.contains(".click") || tool.contains(".type") || tool.contains(".press")+ || tool.contains(".drag") || tool.contains(".scroll") {+ return .editing+ }+ return .working+ }++ /// The activity a task is currently surfacing. While running it prefers the live tool hint+ /// (`activity.tool` metadata) so the line reads like the agent's current step; otherwise the+ /// status drives the kind. The task's `detail` carries any specifics.+ static func current(for task: UserQueryNotchTask) -> UserQueryActivity {+ let summary = task.detail.trimmingCharacters(in: .whitespacesAndNewlines)+ let kind: Kind+ if task.status == .running, let tool = task.metadata["activity.tool"], !tool.isEmpty {+ kind = self.kind(forToolNamed: tool)+ } else {+ kind = self.kind(forStatus: task.status)+ }+ return UserQueryActivity(kind: kind, summary: summary)+ }+}diff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swiftindex bd595a05..7d8341f9 100644--- a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift@@ -951,29 +951,10 @@ public struct UserQueryNotchStatusView: View {task.id == primaryTask?.id}+ /// The task's status line, resolved through the centralized activity vocabulary so the notch and+ /// the future conversation view speak the same language.private func taskStatusDescription(_ task: UserQueryNotchTask) -> String {- switch task.status {- case .chatting:- return task.detail.isEmpty ? "Conversation" : task.detail- case .running:- return task.detail.isEmpty ? "Running" : task.detail- case .paused:- return "Paused"- case .completed:- return task.detail.isEmpty ? "Done" : task.detail- case .waitingForClarification:- return task.detail.isEmpty ? "Waiting for detail" : task.detail- case .waitingForPermission:- return task.detail.isEmpty ? "Waiting for approval" : task.detail- case .waitingForReview:- return task.detail.isEmpty ? "Waiting for review" : task.detail- case .interrupted:- return task.detail.isEmpty ? "Changed course" : task.detail- case .needsAttention:- return task.detail.isEmpty ? "Needs attention" : task.detail- case .failed:- return task.detail.isEmpty ? "Stopped" : task.detail- }+ UserQueryActivity.current(for: task).displayText}private func accentColor(for index: Int) -> Color {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryActivityTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryActivityTests.swiftnew file mode 100644index 00000000..242e82b6--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/UserQueryActivityTests.swift@@ -0,0 +1,74 @@+import DonkeyContracts+import Foundation+import Testing++@Suite+struct UserQueryActivityTests {+ private func task(+ status: UserQueryTaskStatus,+ detail: String = "",+ metadata: [String: String] = [:]+ ) -> UserQueryNotchTask {+ UserQueryNotchTask(+ id: "t",+ title: "Title",+ detail: detail,+ status: status,+ accentIndex: 0,+ metadata: metadata+ )+ }++ @Test+ func displayTextPrefersSummaryThenFallsBackToKindLabel() {+ #expect(UserQueryActivity(kind: .paused).displayText == "Paused")+ #expect(UserQueryActivity(kind: .paused, summary: "Permission denied").displayText == "Permission denied")+ }++ @Test+ func everyKindHasNonEmptyPresentation() {+ for kind in UserQueryActivity.Kind.allCases {+ #expect(!kind.label.isEmpty)+ #expect(!kind.systemImage.isEmpty)+ #expect(!kind.transcriptIcon.isEmpty)+ }+ }++ @Test+ func runningStatusWithNoNarrationReadsAsWorkingNotAnInternalString() {+ // The post-approval / post-resume state: status running, no detail. The line must derive a+ // clean activity label, never a hardcoded "Approved — continuing".+ let activity = UserQueryActivity.current(for: task(status: .running))+ #expect(activity.kind == .working)+ #expect(activity.displayText == "Working")+ }++ @Test+ func runningStatusUsesToolHintWhenPresent() {+ let activity = UserQueryActivity.current(for: task(status: .running, metadata: ["activity.tool": "shell_exec"]))+ #expect(activity.kind == .running)+ }++ @Test+ func toolNamesMapToKindsByTypedFieldNotUserText() {+ #expect(UserQueryActivity.kind(forToolNamed: "ax.observe") == .observing)+ #expect(UserQueryActivity.kind(forToolNamed: "shell_exec") == .running)+ #expect(UserQueryActivity.kind(forToolNamed: "user.clarify") == .waitingForInput)+ #expect(UserQueryActivity.kind(forToolNamed: "music.search") == .searching)+ #expect(UserQueryActivity.kind(forToolNamed: "totally.unknown.tool") == .working)+ }++ @Test+ func statusMapsToKind() {+ #expect(UserQueryActivity.kind(forStatus: .waitingForPermission) == .waitingForPermission)+ #expect(UserQueryActivity.kind(forStatus: .completed) == .completed)+ #expect(UserQueryActivity.kind(forStatus: .chatting) == .message)+ }++ @Test+ func transcriptLineCarriesIconForTheRecord() {+ let line = UserQueryActivity(kind: .paused).transcriptLine+ #expect(line.contains("Paused"))+ #expect(line.first.map { !$0.isLetter } == true) // leads with the kind's icon, not the label+ }+}