Open source CapCut alternative.
TypeScript
feat(app): generative choice-form UI
David Le2c55badc1388
diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swiftindex d20c30bd..04fd46ac 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayController.swift@@ -732,6 +732,9 @@ final class UserQueryOverlayController {},reloadCreditsRequested: { [weak self] conversationID inself?.model.reloadCredits(id: conversationID)+ },+ submitChoiceForm: { [weak self] conversationID, selection in+ self?.model.submitChoiceForm(conversationID: conversationID, selection: selection)})}diff --git a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swiftindex ac28d249..f0d352e8 100644--- a/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryOverlayModel.swift@@ -929,6 +929,28 @@ final class UserQueryOverlayModel: ObservableObject, UserQueryIntentSink {selectedConversationID = nil}+ /// Submit a generative options form (user.choose) for a conversation waiting on the user. The picks are+ /// encoded into the one response line the planner reads back ("Selected options: id=value, …") and+ /// routed as that conversation's reply — the exact path a typed clarification answer takes — so the+ /// harness resumes the task with the choices. No-op if the conversation isn't actually awaiting a form.+ func submitChoiceForm(conversationID: String, selection: [String: String]) {+ guard let conversation = conversation(withID: conversationID),+ conversation.status == .waitingForClarification else {+ return+ }+ let response: String+ if let json = conversation.metadata["genericHarness.choiceForm"],+ let form = HarnessChoiceForm.decode(fromJSON: json) {+ response = form.encodeSelectionResponse(selection)+ } else {+ response = "Selected options: "+ + selection.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: ", ")+ }+ // Pin the answer to the waiting conversation so it resumes that thread rather than starting a new one.+ replyTargetConversationID = conversationID+ runLocalCommand(response)+ }+/// Take the pinned Reply target, if any, for the submission about to run. Cleared on read so it only/// applies to the one answer (which also un-dims the rows), and dropped if the conversation is no longer/// around (fall back to normal routing).diff --git a/apps/Donkey/Sources/DonkeyContracts/HarnessChoiceForm.swift b/apps/Donkey/Sources/DonkeyContracts/HarnessChoiceForm.swiftnew file mode 100644index 00000000..d3563bc5--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/HarnessChoiceForm.swift@@ -0,0 +1,142 @@+import Foundation++/// A generative UI form the agent surfaces to the user mid-turn: a titled set of fields, each a typed+/// control (a segmented button group, a dropdown, or a toggle), every one carrying a default the planner+/// guesses from the request. It is app-agnostic — video generation is the first caller (speed/quality,+/// audio), but any tool can request one to let the user pick before the agent commits.+///+/// The shape is deliberately FLAT so a model can emit it as plain JSON and so the renderer can switch on+/// one string. Extend the vocabulary by adding a `ControlKind` case plus its renderer (notch panel) and+/// its value reading here — the rest of the pipeline (request → wait → render → submit → resume) is+/// untouched. Nothing in the harness core branches on a specific field id, so the same primitive serves+/// any future use case.+public struct HarnessChoiceForm: Codable, Equatable, Sendable {+ /// The kinds of control a field can render. Add a case to grow the vocabulary (e.g. `slider`,+ /// `text`); the decoder, the notch renderer, and `defaultValue(for:)` are the only switches to update.+ public enum ControlKind: String, Codable, Equatable, Sendable {+ case segmented // a single-select row of buttons — best for 2–4 mutually exclusive choices+ case dropdown // a single-select menu — best for many choices or to save space+ case toggle // an on/off switch+ }++ public struct Option: Codable, Equatable, Sendable, Identifiable {+ /// The value returned in the selection when this option is chosen.+ public var id: String+ public var label: String+ /// Optional one-line elaboration shown under the label (e.g. "Quicker, lower cost").+ public var detail: String?++ public init(id: String, label: String, detail: String? = nil) {+ self.id = id+ self.label = label+ self.detail = detail+ }+ }++ public struct Field: Codable, Equatable, Sendable, Identifiable {+ /// Stable key this field's chosen value is returned under in the selection.+ public var id: String+ public var label: String+ /// Optional secondary line under the label.+ public var help: String?+ public var control: ControlKind+ /// Options for `segmented`/`dropdown`; ignored for `toggle`.+ public var options: [Option]+ /// Default selected option id for `segmented`/`dropdown`. Falls back to the first option.+ public var selected: String?+ /// Default state for `toggle`.+ public var on: Bool?++ public init(+ id: String,+ label: String,+ help: String? = nil,+ control: ControlKind,+ options: [Option] = [],+ selected: String? = nil,+ on: Bool? = nil+ ) {+ self.id = id+ self.label = label+ self.help = help+ self.control = control+ self.options = options+ self.selected = selected+ self.on = on+ }++ /// The value this field starts on — the planner's guessed default. Segmented/dropdown resolve to+ /// the declared `selected` if it names a real option, else the first option's id; a toggle to+ /// "true"/"false". Returns nil only for an option-less select (a malformed field).+ public var defaultValue: String? {+ switch control {+ case .segmented, .dropdown:+ if let selected, options.contains(where: { $0.id == selected }) {+ return selected+ }+ return options.first?.id+ case .toggle:+ return (on ?? false) ? "true" : "false"+ }+ }+ }++ public var title: String+ public var subtitle: String?+ public var submitLabel: String+ public var fields: [Field]++ public init(+ title: String,+ subtitle: String? = nil,+ submitLabel: String = "Continue",+ fields: [Field]+ ) {+ self.title = title+ self.subtitle = subtitle+ self.submitLabel = submitLabel+ self.fields = fields+ }+}++public extension HarnessChoiceForm {+ /// Decodes a form from the JSON a tool (or the planner) produced. Returns nil for malformed JSON or a+ /// form with no fields — the caller then falls back to plain conversation rather than an empty panel.+ static func decode(fromJSON json: String) -> HarnessChoiceForm? {+ guard let data = json.data(using: .utf8),+ let form = try? JSONDecoder().decode(HarnessChoiceForm.self, from: data),+ !form.fields.isEmpty+ else {+ return nil+ }+ return form+ }++ func encodedJSON() -> String? {+ guard let data = try? JSONEncoder().encode(self) else { return nil }+ return String(data: data, encoding: .utf8)+ }++ /// The selection the form starts on — every field at its guessed default. The user submits this as-is+ /// (one tap) or after adjusting controls.+ var defaultSelection: [String: String] {+ var selection: [String: String] = [:]+ for field in fields {+ if let value = field.defaultValue {+ selection[field.id] = value+ }+ }+ return selection+ }++ /// Encodes the user's choices into the single response line the waiting planner reads back (as the+ /// user's clarification answer). Stable `id=value` pairs, ordered by the form's fields, so the planner+ /// maps them onto its next tool call deterministically — never by parsing free text.+ func encodeSelectionResponse(_ selection: [String: String]) -> String {+ let pairs = fields.compactMap { field -> String? in+ guard let value = selection[field.id] ?? field.defaultValue else { return nil }+ return "\(field.id)=\(value)"+ }+ return "Selected options: " + pairs.joined(separator: ", ")+ }+}diff --git a/apps/Donkey/Sources/DonkeyUI/ChoiceFormPanel.swift b/apps/Donkey/Sources/DonkeyUI/ChoiceFormPanel.swiftnew file mode 100644index 00000000..a7f1dbc3--- /dev/null+++ b/apps/Donkey/Sources/DonkeyUI/ChoiceFormPanel.swift@@ -0,0 +1,173 @@+import DonkeyContracts+import SwiftUI++/// The inline options form (the agent's generative UI) rendered ON a waiting conversation row — a small+/// stack of fields (segmented choices, dropdowns, toggles) the user adjusts and submits. It owns the+/// in-progress selection (seeded from the form's guessed defaults, so one tap submits) and hands the+/// final choices back through `onSubmit`.+///+/// It styles FLAT — underlined text choices, plain menus, a bare switch — deliberately no boxed "cards",+/// to sit cleanly within the conversation row rather than stacking a panel inside a panel. It is+/// form-agnostic: it switches only on `field.control`, never a field id, so the same view serves video+/// options today and any future caller. Add a control kind by adding a branch in `controlView`.+struct ChoiceFormPanel: View {+ let form: HarnessChoiceForm+ let accent: Color+ let onSubmit: @MainActor ([String: String]) -> Void++ @State private var selection: [String: String]++ init(form: HarnessChoiceForm, accent: Color, onSubmit: @escaping @MainActor ([String: String]) -> Void) {+ self.form = form+ self.accent = accent+ self.onSubmit = onSubmit+ _selection = State(initialValue: form.defaultSelection)+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 11) {+ if let subtitle = form.subtitle, !subtitle.isEmpty {+ Text(subtitle)+ .font(.system(size: 11, weight: .regular))+ .foregroundStyle(Color.white.opacity(0.5))+ }++ ForEach(form.fields) { field in+ fieldView(field)+ }++ submitButton+ .padding(.top, 1)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }++ @ViewBuilder+ private func fieldView(_ field: HarnessChoiceForm.Field) -> some View {+ // A toggle reads best with its label on the same line; selects get a label above the choices.+ if field.control == .toggle {+ HStack(spacing: 8) {+ fieldLabel(field)+ Spacer(minLength: 8)+ toggleControl(field)+ }+ } else {+ VStack(alignment: .leading, spacing: 5) {+ fieldLabel(field)+ controlView(field)+ }+ }+ }++ private func fieldLabel(_ field: HarnessChoiceForm.Field) -> some View {+ HStack(alignment: .firstTextBaseline, spacing: 6) {+ Text(field.label)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(Color.white.opacity(0.82))+ if let help = field.help, !help.isEmpty {+ Text(help)+ .font(.system(size: 11, weight: .regular))+ .foregroundStyle(Color.white.opacity(0.4))+ }+ }+ }++ @ViewBuilder+ private func controlView(_ field: HarnessChoiceForm.Field) -> some View {+ switch field.control {+ case .segmented:+ segmentedControl(field)+ case .dropdown:+ dropdownControl(field)+ case .toggle:+ toggleControl(field)+ }+ }++ // MARK: - Segmented (flat, underlined text choices — no cards)++ private func segmentedControl(_ field: HarnessChoiceForm.Field) -> some View {+ let current = selection[field.id] ?? field.defaultValue+ return VStack(alignment: .leading, spacing: 3) {+ HStack(spacing: 16) {+ ForEach(field.options) { option in+ let isOn = current == option.id+ Button {+ selection[field.id] = option.id+ } label: {+ Text(option.label)+ .font(.system(size: 12, weight: isOn ? .semibold : .regular))+ .foregroundStyle(isOn ? accent : Color.white.opacity(0.5))+ .padding(.bottom, 3)+ .overlay(alignment: .bottom) {+ Rectangle()+ .fill(isOn ? accent : Color.clear)+ .frame(height: 1.5)+ }+ }+ .buttonStyle(.plain)+ }+ }+ // The chosen option's elaboration, shown once below the row rather than crowding each choice.+ if let detail = field.options.first(where: { $0.id == current })?.detail, !detail.isEmpty {+ Text(detail)+ .font(.system(size: 10, weight: .regular))+ .foregroundStyle(Color.white.opacity(0.4))+ }+ }+ }++ // MARK: - Dropdown (plain menu — no box)++ private func dropdownControl(_ field: HarnessChoiceForm.Field) -> some View {+ let currentID = selection[field.id] ?? field.defaultValue+ let currentLabel = field.options.first { $0.id == currentID }?.label ?? "Choose"+ return Menu {+ ForEach(field.options) { option in+ Button(option.label) { selection[field.id] = option.id }+ }+ } label: {+ HStack(spacing: 5) {+ Text(currentLabel)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(accent)+ Image(systemName: "chevron.down")+ .font(.system(size: 9, weight: .semibold))+ .foregroundStyle(accent.opacity(0.8))+ }+ }+ .menuStyle(.borderlessButton)+ .menuIndicator(.hidden)+ .fixedSize()+ }++ // MARK: - Toggle (bare switch)++ private func toggleControl(_ field: HarnessChoiceForm.Field) -> some View {+ let isOn = Binding<Bool>(+ get: { (selection[field.id] ?? field.defaultValue) == "true" },+ set: { selection[field.id] = $0 ? "true" : "false" }+ )+ return Toggle(isOn: isOn) { EmptyView() }+ .labelsHidden()+ .toggleStyle(.switch)+ .tint(accent)+ .scaleEffect(0.85, anchor: .trailing)+ }++ // MARK: - Submit++ private var submitButton: some View {+ Button {+ onSubmit(selection)+ } label: {+ Text(form.submitLabel.isEmpty ? "Continue" : form.submitLabel)+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(Color.black.opacity(0.85))+ .padding(.horizontal, 16)+ .padding(.vertical, 6)+ .background(Capsule(style: .continuous).fill(accent))+ }+ .buttonStyle(.plain)+ }+}diff --git a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swiftindex 1716ce83..8f9cbc52 100644--- a/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift+++ b/apps/Donkey/Sources/DonkeyUI/UserQueryNotchStatusView.swift@@ -61,6 +61,9 @@ public struct UserQueryNotchStatusView: View {/// A conversation that failed for lack of credits shows a "Reload credits" CTA in its banner; tapping it/// fires this so the app can open the billing page (reuses the permission-banner button styling).private let reloadCreditsRequested: @MainActor (String) -> Void+ /// A conversation waiting on a generative options form (user.choose) submits the user's picks through+ /// this — (conversationID, selection of fieldID→value). The harness resumes the task with the choices.+ private let submitChoiceForm: @MainActor (String, [String: String]) -> Voidpublic init(state: UserQueryState,@@ -95,7 +98,8 @@ public struct UserQueryNotchStatusView: View {updateRequested: @escaping @MainActor () -> Void,needsLogin: Bool = false,loginRequested: @escaping @MainActor () -> Void = {},- reloadCreditsRequested: @escaping @MainActor (String) -> Void = { _ in }+ reloadCreditsRequested: @escaping @MainActor (String) -> Void = { _ in },+ submitChoiceForm: @escaping @MainActor (String, [String: String]) -> Void = { _, _ in }) {self.state = stateself.updateState = updateState@@ -130,6 +134,7 @@ public struct UserQueryNotchStatusView: View {self.needsLogin = needsLoginself.loginRequested = loginRequestedself.reloadCreditsRequested = reloadCreditsRequested+ self.submitChoiceForm = submitChoiceForm}public var body: some View {@@ -541,6 +546,18 @@ public struct UserQueryNotchStatusView: View {return running[index]}+ /// The generative options form (user.choose) a conversation is awaiting, decoded from its gate+ /// metadata, or nil. Rendered INLINE on the conversation row (like the permission banner), not as a+ /// separate panel — only while the conversation is actually waiting on the user for it.+ private func choiceForm(for conversation: UserQueryConversation) -> HarnessChoiceForm? {+ guard conversation.status == .waitingForClarification,+ let json = conversation.metadata["genericHarness.choiceForm"],+ !json.isEmpty else {+ return nil+ }+ return HarnessChoiceForm.decode(fromJSON: json)+ }+private var expandedContent: some View {Group {if needsLogin {@@ -636,8 +653,13 @@ public struct UserQueryNotchStatusView: View {.padding(.bottom, Self.contentInset)}+ /// The leading arrow over the expanded composer-only surface. It renders only while the notch holds no+ /// conversation (`!hasConversationDisplayText`, line 195), so by construction there is nothing for it to+ /// narrate — it is always the idle silhouette, never tinted by an accent. Drawing it filled let a+ /// just-deleted conversation's accent linger (via the `accentColor` fallback to the stale `accentIndex`)+ /// as a stray colored arrow floating over the empty composer.private var expandedNotchArrow: some View {- DonkeyCursorMark(color: accentColor)+ DonkeyCursorMark(color: accentColor, silhouette: true).frame(width: 15, height: 15).position(x: expandedNotchArrowX, y: expandedNotchArrowY)}@@ -898,6 +920,7 @@ public struct UserQueryNotchStatusView: View {private func conversationRow(_ conversation: UserQueryConversation) -> some View {let isPermission = conversation.status == .waitingForPermission+ let inlineForm = choiceForm(for: conversation)// The reply dim is applied per-element rather than to the whole row so the pointer of a conversation that// itself needs the user can stay lit while everything else recedes.let contentDim = rowReplyDimOpacity(for: conversation)@@ -929,7 +952,8 @@ public struct UserQueryNotchStatusView: View {// First line runs all the way to just left of the pinned top-right controls..padding(.trailing, controlsReserve(for: conversation))- if !isPermission {+ // The form carries its own title, so the row's status subtext is suppressed for it too.+ if !isPermission && inlineForm == nil {Text(conversationStatusDescription(conversation)).font(.system(size: 12, weight: .regular)).foregroundStyle(Color.white.opacity(0.42))@@ -948,6 +972,14 @@ public struct UserQueryNotchStatusView: View {if isPermission {permissionBanner(for: conversation).opacity(contentDim)+ } else if let inlineForm {+ ChoiceFormPanel(+ form: inlineForm,+ accent: accentColor(for: conversation.accentIndex)+ ) { selection in+ submitChoiceForm(conversation.id, selection)+ }+ .opacity(contentDim)} else if showsReloadCreditsBanner(conversation) {reloadCreditsBanner(for: conversation).opacity(contentDim)