Open source CapCut alternative.
TypeScript
Update modal UI
David Le602029f2d700
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swiftindex ad030c4a..e158da85 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayController.swift@@ -8,25 +8,37 @@ final class PointerPromptOverlayController {private let model: PointerPromptOverlayModelprivate let fixedPlacement: PointerPromptPlacement = .bottomRight+ private let activationShortcut: PointerPromptActivationShortcutprivate var panel: NSPanel?private var timer: Timer?- private var globalCommandClickMonitor: Any?- private var localCommandClickMonitor: Any?-- init(model: PointerPromptOverlayModel) {+ private var globalActivationMonitor: Any?+ private var localActivationMonitor: Any?+ private var activationTapStartedAt: Date?+ private var activationTapIsClean = false+ private var completedActivationTapCount = 0+ private var lastActivationTapCompletedAt: Date?+ private var activationHoldStartedAt: Date?++ init(+ model: PointerPromptOverlayModel,+ activationShortcut: PointerPromptActivationShortcut = .doubleCommand+ ) {self.model = model+ self.activationShortcut = activationShortcut}func show() {let rootView = PointerPromptOverlayRootView(model: model)+ let initialContentSize = currentContentSizelet hostingView = NSHostingView(rootView: rootView)- hostingView.frame = CGRect(origin: .zero, size: Self.contentSize)+ hostingView.frame = CGRect(origin: .zero, size: initialContentSize)+ hostingView.autoresizingMask = [.width, .height]hostingView.wantsLayer = truehostingView.layer?.backgroundColor = NSColor.clear.cgColorlet panel = PointerPromptPanel(- contentRect: CGRect(origin: .zero, size: Self.contentSize),+ contentRect: CGRect(origin: .zero, size: initialContentSize),styleMask: [.borderless],backing: .buffered,defer: false@@ -38,6 +50,7 @@ final class PointerPromptOverlayController {panel.hasShadow = falsepanel.hidesOnDeactivate = falsepanel.isReleasedWhenClosed = false+ panel.becomesKeyOnlyIfNeeded = falsepanel.ignoresMouseEvents = truepanel.dragRegionProvider = { [weak self] inself?.composerDragRegions() ?? []@@ -51,7 +64,7 @@ final class PointerPromptOverlayController {]self.panel = panel- startCommandClickMonitoring()+ startActivationMonitoring()positionAtCurrentMouseLocation()panel.orderFrontRegardless()startTimer()@@ -60,49 +73,184 @@ final class PointerPromptOverlayController {func stop() {timer?.invalidate()timer = nil- stopCommandClickMonitoring()+ stopActivationMonitoring()panel?.close()panel = nil}- private func startCommandClickMonitoring() {- stopCommandClickMonitoring()+ private func startActivationMonitoring() {+ stopActivationMonitoring()- globalCommandClickMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown]) { [weak self] event in- guard event.modifierFlags.contains(.command) else { return }+ let activationEventMask: NSEvent.EventTypeMask = [+ .flagsChanged,+ .keyDown,+ .leftMouseDown,+ .rightMouseDown,+ .otherMouseDown+ ]+ globalActivationMonitor = NSEvent.addGlobalMonitorForEvents(matching: activationEventMask) { [weak self] event in+ let eventType = event.type+ let modifierFlags = event.modifierFlags+ Task { @MainActor in+ self?.handleActivationEvent(type: eventType, modifierFlags: modifierFlags)+ }+ }+ localActivationMonitor = NSEvent.addLocalMonitorForEvents(matching: activationEventMask) { [weak self] event in+ let eventType = event.type+ let modifierFlags = event.modifierFlagsTask { @MainActor in- self?.activateAtCurrentMouseLocation()+ self?.handleActivationEvent(type: eventType, modifierFlags: modifierFlags)}+ return event+ }+ }++ private func stopActivationMonitoring() {+ if let globalActivationMonitor {+ NSEvent.removeMonitor(globalActivationMonitor)+ self.globalActivationMonitor = nil}- localCommandClickMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) { [weak self] event in- if event.modifierFlags.contains(.command) {- Task { @MainActor in- self?.activateAtCurrentMouseLocation()+ if let localActivationMonitor {+ NSEvent.removeMonitor(localActivationMonitor)+ self.localActivationMonitor = nil+ }+ }++ private func handleActivationEvent(+ type: NSEvent.EventType,+ modifierFlags: NSEvent.ModifierFlags+ ) {+ switch type {+ case .flagsChanged:+ handleModifierFlagsChanged(modifierFlags)+ case .keyDown, .leftMouseDown, .rightMouseDown, .otherMouseDown:+ resetActivationTapSequence()+ default:+ break+ }+ }++ private func handleModifierFlagsChanged(_ modifierFlags: NSEvent.ModifierFlags) {+ let flags = modifierFlags+ .intersection(.deviceIndependentFlagsMask)+ .subtracting(.capsLock)+ let activationModifierFlag = activationShortcut.modifier.eventModifierFlag+ let isActivationModifierDown = flags.contains(activationModifierFlag)+ let isCleanActivationModifierOnly = flags == activationModifierFlag++ if isCleanActivationModifierOnly {+ if activationTapStartedAt == nil {+ let now = Date()+ activationTapStartedAt = now+ activationTapIsClean = true+ if shouldStartVoiceHoldCandidate(at: now) {+ activationHoldStartedAt = now}}+ return+ }- return event+ if isActivationModifierDown {+ if activationTapStartedAt == nil {+ activationTapStartedAt = Date()+ }+ activationTapIsClean = false+ completedActivationTapCount = 0+ lastActivationTapCompletedAt = nil+ activationHoldStartedAt = nil+ return}++ guard flags.isEmpty else {+ resetActivationTapSequence()+ return+ }++ guard let activationTapStartedAt else { return }++ let now = Date()+ let tapDuration = now.timeIntervalSince(activationTapStartedAt)+ let completedCleanTap = activationTapIsClean &&+ tapDuration <= activationShortcut.maximumTapDuration+ self.activationTapStartedAt = nil+ activationTapIsClean = false++ guard completedCleanTap else {+ resetActivationTapSequence()+ return+ }++ registerCompletedActivationTap(at: now)+ }++ private func registerCompletedActivationTap(at now: Date) {+ if let lastActivationTapCompletedAt,+ now.timeIntervalSince(lastActivationTapCompletedAt) <= activationShortcut.maximumTapInterval {+ completedActivationTapCount += 1+ } else {+ completedActivationTapCount = 1+ }++ lastActivationTapCompletedAt = now+ activationHoldStartedAt = nil++ guard completedActivationTapCount >= activationShortcut.tapCount else {+ return+ }++ resetActivationTapSequence()+ activateAtCurrentMouseLocation()+ }++ private func resetActivationTapSequence() {+ activationTapStartedAt = nil+ activationTapIsClean = false+ completedActivationTapCount = 0+ lastActivationTapCompletedAt = nil+ activationHoldStartedAt = nil}- private func stopCommandClickMonitoring() {- if let globalCommandClickMonitor {- NSEvent.removeMonitor(globalCommandClickMonitor)- self.globalCommandClickMonitor = nil+ private func shouldStartVoiceHoldCandidate(at now: Date) -> Bool {+ guard activationShortcut.holdToVoiceInputDuration != nil,+ completedActivationTapCount == activationShortcut.tapCount - 1,+ let lastActivationTapCompletedAt else {+ return false}- if let localCommandClickMonitor {- NSEvent.removeMonitor(localCommandClickMonitor)- self.localCommandClickMonitor = nil+ return now.timeIntervalSince(lastActivationTapCompletedAt) <=+ activationShortcut.maximumTapInterval+ }++ private func activateVoiceInputIfNeeded() {+ guard let holdToVoiceInputDuration = activationShortcut.holdToVoiceInputDuration,+ let activationHoldStartedAt,+ activationTapIsClean,+ Date().timeIntervalSince(activationHoldStartedAt) >= holdToVoiceInputDuration else {+ return}++ resetActivationTapSequence()+ activateVoiceInputAtCurrentMouseLocation()}private func activateAtCurrentMouseLocation() {+ guard !model.promptState.isActive else {+ NSApp.activate(ignoringOtherApps: true)+ panel?.makeKeyAndOrderFront(nil)+ focusComposerTextInput()+ return+ }+activate(at: NSEvent.mouseLocation)}+ private func activateVoiceInputAtCurrentMouseLocation() {+ activateAtCurrentMouseLocation()+ model.handle(.voiceInputRequested)+ }+private func positionAtCurrentMouseLocation() {tick(mouseLocation: NSEvent.mouseLocation)}@@ -115,6 +263,7 @@ final class PointerPromptOverlayController {NSApp.activate(ignoringOtherApps: true)panel.makeKeyAndOrderFront(nil)+ focusComposerTextInput()}private func startTimer() {@@ -131,8 +280,11 @@ final class PointerPromptOverlayController {private func tick(mouseLocation explicitMouseLocation: CGPoint? = nil) {guard let panel else { return }+ activateVoiceInputIfNeeded()updateMouseEventPassthrough(for: panel)if model.promptState.isActive, explicitMouseLocation == nil {+ resizeActivePanelIfNeeded(panel)+ updateMouseEventPassthrough(for: panel)return}@@ -150,7 +302,7 @@ final class PointerPromptOverlayController {for placement: PointerPromptPlacement,mouseLocation: CGPoint) -> CGRect {- let size = Self.contentSize+ let size = currentContentSizelet anchor = agentPointerTipAnchor(for: placement)let agentPointerTipLocation = agentPointerTipLocation(for: placement,@@ -183,7 +335,7 @@ final class PointerPromptOverlayController {if placement.placesContentOnLeft {pointerSlotX = stageHorizontalInset +PointerPromptLayout.stageHorizontalPadding +- PointerPromptLayout.composerSize.width ++ PointerPromptLayout.composerWidth +PointerPromptLayout.pointerComposerSpacing} else {pointerSlotX = stageHorizontalInset + PointerPromptLayout.stageHorizontalPadding@@ -195,7 +347,7 @@ final class PointerPromptOverlayController {return CGPoint(x: pointerTipX,- y: Self.contentSize.height - pointerTipYFromTop+ y: currentContentSize.height - pointerTipYFromTop)}@@ -205,23 +357,23 @@ final class PointerPromptOverlayController {}private var stageHorizontalInset: CGFloat {- (Self.contentSize.width - stageContentWidth) / 2+ (currentContentSize.width - stageContentWidth) / 2}private var stageVerticalInset: CGFloat {- (Self.contentSize.height - stageContentHeight) / 2+ (currentContentSize.height - stageContentHeight) / 2}private var stageContentWidth: CGFloat {PointerPromptLayout.stageHorizontalPadding * 2 +PointerPromptLayout.pointerSlotSize.width +PointerPromptLayout.pointerComposerSpacing +- PointerPromptLayout.composerSize.width+ PointerPromptLayout.composerWidth}private var stageContentHeight: CGFloat {PointerPromptLayout.stageVerticalPadding * 2 +- PointerPromptLayout.composerSize.height+ currentComposerHeight}private var pointerTipYFromTop: CGFloat {@@ -238,36 +390,51 @@ final class PointerPromptOverlayController {guard model.promptState.isActive else { return [] }let composerFrame = composerFrame(for: fixedPlacement)- let dragThickness = PointerPromptLayout.composerDragBorderThickness- let closeButtonClearance = PointerPromptLayout.closeButtonInset * 2 +- PointerPromptLayout.closeButtonSize-- return [+ let inputFrame = composerInputFrame(in: composerFrame)+ let closeControlFrame = CGRect(+ x: composerFrame.minX + PointerPromptLayout.closeButtonInset,+ y: composerFrame.maxY -+ PointerPromptLayout.closeButtonInset -+ PointerPromptLayout.closeButtonSize,+ width: PointerPromptLayout.closeControlWidth,+ height: PointerPromptLayout.closeButtonSize+ ).insetBy(dx: -6, dy: -6)++ var regions = [CGRect(- x: composerFrame.minX + closeButtonClearance,- y: composerFrame.maxY - dragThickness,- width: composerFrame.width - closeButtonClearance,- height: dragThickness+ x: closeControlFrame.maxX,+ y: inputFrame.maxY,+ width: composerFrame.maxX - closeControlFrame.maxX,+ height: composerFrame.maxY - inputFrame.maxY),CGRect(x: composerFrame.minX,- y: composerFrame.minY,- width: composerFrame.width,- height: dragThickness+ y: inputFrame.maxY,+ width: closeControlFrame.minX - composerFrame.minX,+ height: composerFrame.maxY - inputFrame.maxY),CGRect(x: composerFrame.minX,- y: composerFrame.minY + dragThickness,- width: dragThickness,- height: composerFrame.height - dragThickness - closeButtonClearance+ y: inputFrame.minY,+ width: inputFrame.minX - composerFrame.minX,+ height: inputFrame.height+ ),+ CGRect(+ x: inputFrame.maxX,+ y: inputFrame.minY,+ width: composerFrame.maxX - inputFrame.maxX,+ height: inputFrame.height),CGRect(- x: composerFrame.maxX - dragThickness,- y: composerFrame.minY + dragThickness,- width: dragThickness,- height: composerFrame.height - dragThickness * 2+ x: composerFrame.minX,+ y: composerFrame.minY,+ width: composerFrame.width,+ height: inputFrame.minY - composerFrame.minY)]++ regions.removeAll { $0.width <= 0 || $0.height <= 0 }+ return regions}private func composerFrame(for placement: PointerPromptPlacement) -> CGRect {@@ -283,9 +450,9 @@ final class PointerPromptOverlayController {return CGRect(x: x,- y: Self.contentSize.height - composerTopFromPanelTop - PointerPromptLayout.composerSize.height,- width: PointerPromptLayout.composerSize.width,- height: PointerPromptLayout.composerSize.height+ y: currentContentSize.height - composerTopFromPanelTop - currentComposerHeight,+ width: PointerPromptLayout.composerWidth,+ height: currentComposerHeight)}@@ -293,15 +460,104 @@ final class PointerPromptOverlayController {stageVerticalInset + PointerPromptLayout.stageVerticalPadding}+ private func composerInputFrame(in composerFrame: CGRect) -> CGRect {+ let inputHeight = PointerPromptLayout.composerInputHeight(+ inputTextHeight: model.inputTextHeight+ )++ return CGRect(+ x: composerFrame.minX + PointerPromptLayout.composerInputHorizontalPadding,+ y: composerFrame.minY + PointerPromptLayout.composerBottomPadding,+ width: composerFrame.width - PointerPromptLayout.composerInputHorizontalPadding * 2,+ height: inputHeight+ )+ }+private func updateMouseEventPassthrough(for panel: NSPanel) {guard model.promptState.isActive else {panel.ignoresMouseEvents = truereturn}+ if isComposerTextInputFocused(in: panel) {+ panel.ignoresMouseEvents = false+ return+ }+let mouseLocationInPanel = panel.convertPoint(fromScreen: NSEvent.mouseLocation)panel.ignoresMouseEvents = !composerFrame(for: fixedPlacement).contains(mouseLocationInPanel)}++ private var currentContentSize: CGSize {+ PointerPromptLayout.contentSize(inputTextHeight: model.inputTextHeight)+ }++ private var currentComposerHeight: CGFloat {+ PointerPromptLayout.composerHeight(inputTextHeight: model.inputTextHeight)+ }++ private func resizeActivePanelIfNeeded(_ panel: NSPanel) {+ let size = currentContentSize+ let frame = panel.frame+ guard abs(frame.width - size.width) > 0.5 ||+ abs(frame.height - size.height) > 0.5 else {+ return+ }++ panel.setFrame(+ CGRect(+ x: frame.minX,+ y: frame.maxY - size.height,+ width: size.width,+ height: size.height+ ),+ display: true+ )+ }++ private func focusComposerTextInput(attempt: Int = 0) {+ guard let panel else { return }++ panel.ignoresMouseEvents = false+ panel.makeKeyAndOrderFront(nil)++ guard let textView = firstComposerTextView(in: panel.contentView) else {+ guard attempt < 8 else { return }++ DispatchQueue.main.asyncAfter(deadline: .now() + 0.025) {+ self.focusComposerTextInput(attempt: attempt + 1)+ }+ return+ }++ panel.makeFirstResponder(textView)+ textView.window?.makeFirstResponder(textView)+ }++ private func firstComposerTextView(in view: NSView?) -> NSTextView? {+ guard let view else { return nil }++ if let textView = view as? NSTextView {+ return textView+ }++ for subview in view.subviews {+ if let textView = firstComposerTextView(in: subview) {+ return textView+ }+ }++ return nil+ }++ private func isComposerTextInputFocused(in panel: NSPanel) -> Bool {+ guard let textView = firstComposerTextView(in: panel.contentView) else {+ return false+ }++ return panel.firstResponder === textView ||+ textView.window?.firstResponder === textView+ }}private final class PointerPromptPanel: NSPanel {@@ -325,3 +581,12 @@ private final class PointerPromptPanel: NSPanel {super.sendEvent(event)}}++private extension PointerPromptActivationModifier {+ var eventModifierFlag: NSEvent.ModifierFlags {+ switch self {+ case .command:+ .command+ }+ }+}diff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swiftindex e55082d2..b19d7e25 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayModel.swift@@ -9,6 +9,7 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSink@Published private(set) var promptState: PointerPromptState@Published var messageText = ""@Published var placement: PointerPromptPlacement = .bottomRight+ @Published var inputTextHeight = PointerPromptLayout.composerInputTextMinimumHeightprivate let runtimeProvider: any RuntimeStatusProvidingprivate let aiProvider: any AIHarnessSnapshotProviding@@ -51,6 +52,10 @@ final class PointerPromptOverlayModel: ObservableObject, PointerPromptIntentSinkmessageText = ""promptState.leadingSignalLevel = .thinking+ case .inputTextHeightChanged(let height):+ let clampedHeight = max(PointerPromptLayout.composerInputTextMinimumHeight, height)+ guard abs(inputTextHeight - clampedHeight) > 0.5 else { return }+ inputTextHeight = clampedHeightcase .dismissed:promptState.isPrimaryActionEnabled = falsepromptState.isActive = falsediff --git a/apps/Donkey/Sources/Donkey/PointerPromptOverlayRootView.swift b/apps/Donkey/Sources/Donkey/PointerPromptOverlayRootView.swiftindex 097eded3..e7b747b0 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptOverlayRootView.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptOverlayRootView.swift@@ -1,3 +1,4 @@+import DonkeyContractsimport DonkeyUIimport SwiftUI@@ -8,12 +9,13 @@ struct PointerPromptOverlayRootView: View {PointerPromptStageView(state: model.promptState,messageText: $model.messageText,+ inputTextHeight: model.inputTextHeight,placement: model.placement,intentSink: model).frame(- width: PointerPromptOverlayController.contentSize.width,- height: PointerPromptOverlayController.contentSize.height+ width: PointerPromptLayout.contentSize(inputTextHeight: model.inputTextHeight).width,+ height: PointerPromptLayout.contentSize(inputTextHeight: model.inputTextHeight).height)}}diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptActivationShortcut.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptActivationShortcut.swiftnew file mode 100644index 00000000..79675fa3--- /dev/null+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptActivationShortcut.swift@@ -0,0 +1,35 @@+import Foundation++public enum PointerPromptActivationModifier: String, Equatable, Sendable {+ case command+}++public struct PointerPromptActivationShortcut: Equatable, Sendable {+ public var modifier: PointerPromptActivationModifier+ public var tapCount: Int+ public var maximumTapDuration: TimeInterval+ public var maximumTapInterval: TimeInterval+ public var holdToVoiceInputDuration: TimeInterval?++ public init(+ modifier: PointerPromptActivationModifier,+ tapCount: Int,+ maximumTapDuration: TimeInterval,+ maximumTapInterval: TimeInterval,+ holdToVoiceInputDuration: TimeInterval? = nil+ ) {+ self.modifier = modifier+ self.tapCount = max(1, tapCount)+ self.maximumTapDuration = max(0, maximumTapDuration)+ self.maximumTapInterval = max(0, maximumTapInterval)+ self.holdToVoiceInputDuration = holdToVoiceInputDuration.map { max(0, $0) }+ }++ public static let doubleCommand = PointerPromptActivationShortcut(+ modifier: .command,+ tapCount: 2,+ maximumTapDuration: 0.45,+ maximumTapInterval: 0.45,+ holdToVoiceInputDuration: 0.28+ )+}diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swiftindex 7e4ee534..7ed08a41 100644--- a/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptContracts.swift@@ -1,3 +1,4 @@+import CoreGraphicsimport Foundationpublic struct PointerPromptState: Equatable, Sendable {@@ -188,6 +189,7 @@ public enum PointerPromptIntent: Equatable, Sendable {case voiceInputRequestedcase primaryActionRequested(promptText: String)case messageSubmitted(text: String)+ case inputTextHeightChanged(CGFloat)case dismissed}diff --git a/apps/Donkey/Sources/DonkeyContracts/PointerPromptLayout.swift b/apps/Donkey/Sources/DonkeyContracts/PointerPromptLayout.swiftindex e0ecfa58..4856cb76 100644--- a/apps/Donkey/Sources/DonkeyContracts/PointerPromptLayout.swift+++ b/apps/Donkey/Sources/DonkeyContracts/PointerPromptLayout.swift@@ -1,7 +1,8 @@import CoreGraphicspublic enum PointerPromptLayout {- public static let contentSize = CGSize(width: 448, height: 166)+ public static let contentWidth: CGFloat = 448+ public static let contentExtraHeight: CGFloat = 4public static let stageHorizontalPadding: CGFloat = 8public static let stageVerticalPadding: CGFloat = 10public static let pointerSlotSize = CGSize(width: 58, height: 68)@@ -11,9 +12,47 @@ public enum PointerPromptLayout {public static let pointerDistanceFromCursor: CGFloat = 48public static let pointerDiagonalComponent = pointerDistanceFromCursor / CGFloat(2).squareRoot()public static let pointerComposerSpacing: CGFloat = 16- public static let composerSize = CGSize(width: 350, height: 142)+ public static let composerWidth: CGFloat = 350public static let composerCornerRadius: CGFloat = 12public static let composerDragBorderThickness: CGFloat = 14+ public static let composerTitlebarHeight: CGFloat = 48+ public static let composerBottomPadding: CGFloat = 16+ public static let composerInputHorizontalPadding: CGFloat = 16+ public static let composerInputLeadingContentPadding: CGFloat = 20+ public static let composerInputTrailingContentPadding: CGFloat = 8+ public static let composerInputMinimumHeight: CGFloat = 46.4+ public static let composerInputTextMinimumHeight: CGFloat = 19.2+ public static let composerInputTextVerticalPadding: CGFloat = 13.6+ public static let composerInputVoiceButtonSize: CGFloat = 33.6public static let closeButtonSize: CGFloat = 12- public static let closeButtonInset: CGFloat = 12+ public static let closeButtonInset: CGFloat = 16+ public static let closeControlWidth = closeButtonSize++ public static let contentSize = contentSize(inputTextHeight: composerInputTextMinimumHeight)+ public static let composerSize = CGSize(+ width: composerWidth,+ height: composerHeight(inputTextHeight: composerInputTextMinimumHeight)+ )++ public static func composerInputHeight(inputTextHeight: CGFloat) -> CGFloat {+ max(+ composerInputMinimumHeight,+ inputTextHeight + composerInputTextVerticalPadding * 2+ )+ }++ public static func composerHeight(inputTextHeight: CGFloat) -> CGFloat {+ composerTitlebarHeight ++ composerInputHeight(inputTextHeight: inputTextHeight) ++ composerBottomPadding+ }++ public static func contentSize(inputTextHeight: CGFloat) -> CGSize {+ CGSize(+ width: contentWidth,+ height: stageVerticalPadding * 2 ++ composerHeight(inputTextHeight: inputTextHeight) ++ contentExtraHeight+ )+ }}diff --git a/apps/Donkey/Sources/DonkeyUI/PointerPromptStageView.swift b/apps/Donkey/Sources/DonkeyUI/PointerPromptStageView.swiftindex 0cb124d4..8b47e2d9 100644--- a/apps/Donkey/Sources/DonkeyUI/PointerPromptStageView.swift+++ b/apps/Donkey/Sources/DonkeyUI/PointerPromptStageView.swift@@ -5,17 +5,20 @@ import SwiftUIpublic struct PointerPromptStageView: View {private let state: PointerPromptState@Binding private var messageText: String+ private let inputTextHeight: CGFloatprivate let placement: PointerPromptPlacementprivate weak var intentSink: (any PointerPromptIntentSink)?public init(state: PointerPromptState,messageText: Binding<String>,+ inputTextHeight: CGFloat = PointerPromptLayout.composerInputTextMinimumHeight,placement: PointerPromptPlacement = .bottomRight,intentSink: any PointerPromptIntentSink) {self.state = stateself._messageText = messageText+ self.inputTextHeight = inputTextHeightself.placement = placementself.intentSink = intentSink}@@ -59,9 +62,7 @@ public struct PointerPromptStageView: View {PointerPromptComposer(state: state,messageText: $messageText,- addContext: {- intentSink?.handle(.addContextRequested)- },+ inputTextHeight: inputTextHeight,voiceInput: {intentSink?.handle(.voiceInputRequested)},@@ -70,11 +71,14 @@ public struct PointerPromptStageView: View {},submit: {intentSink?.handle(.messageSubmitted(text: messageText))+ },+ inputTextHeightChanged: { height in+ intentSink?.handle(.inputTextHeightChanged(height))}).frame(- width: PointerPromptLayout.composerSize.width,- height: PointerPromptLayout.composerSize.height+ width: PointerPromptLayout.composerWidth,+ height: PointerPromptLayout.composerHeight(inputTextHeight: inputTextHeight))}@@ -89,65 +93,56 @@ public struct PointerPromptStageView: View {private struct PointerPromptComposer: View {let state: PointerPromptState@Binding var messageText: String- let addContext: @MainActor () -> Void+ let inputTextHeight: CGFloatlet voiceInput: @MainActor () -> Voidlet dismiss: @MainActor () -> Voidlet submit: @MainActor () -> Void- @FocusState private var isFocused: Bool+ let inputTextHeightChanged: @MainActor (CGFloat) -> Voidvar body: some View {ZStack(alignment: .topLeading) {- VStack(alignment: .leading, spacing: 12) {- TextField(state.promptText, text: $messageText)- .textFieldStyle(.roundedBorder)- .font(.system(size: 13))- .lineLimit(1)- .focused($isFocused)- .onSubmit(submit)- .accessibilityLabel("Message for Donkey")+ HStack(spacing: 12) {+ ComposerMultilineTextInput(+ text: $messageText,+ placeholder: state.promptText,+ isActive: state.isActive,+ textHeightChanged: inputTextHeightChanged,+ submit: submit+ ).frame(maxWidth: .infinity)- .padding(.leading, closeButtonContentClearance)-- Divider()-- HStack(spacing: 10) {- ComposerToolbarButton(- systemName: "plus",- title: "Add",- action: addContext- )-- ComposerToolbarButton(- systemName: "waveform",- title: "Voice",- action: voiceInput- )-- Spacer(minLength: 12)-- ComposerToolbarButton(- systemName: "arrow.up",- title: "Send",- isProminent: true,- isDisabled: isSubmitDisabled,- action: submit- )- }- }- .padding(16)+ .frame(height: inputTextHeight)- ComposerCloseButton(action: dismiss)- .padding(.leading, PointerPromptLayout.closeButtonInset)- .padding(.top, PointerPromptLayout.closeButtonInset)+ ComposerVoiceButton(action: voiceInput)+ }+ .frame(height: PointerPromptLayout.composerInputHeight(inputTextHeight: inputTextHeight))+ .padding(.leading, PointerPromptLayout.composerInputLeadingContentPadding)+ .padding(.trailing, PointerPromptLayout.composerInputTrailingContentPadding)+ .background {+ Capsule(style: .continuous)+ .fill(Color(red: 0.13, green: 0.13, blue: 0.13))+ .overlay {+ Capsule(style: .continuous)+ .stroke(Color.white.opacity(0.07), lineWidth: 1)+ }+ }+ .padding(.horizontal, PointerPromptLayout.composerInputHorizontalPadding)+ .padding(.top, PointerPromptLayout.composerTitlebarHeight)+ .padding(.bottom, PointerPromptLayout.composerBottomPadding)++ ComposerCloseControl(close: dismiss)+ .offset(+ x: PointerPromptLayout.closeButtonInset,+ y: PointerPromptLayout.closeButtonInset+ )}.frame(maxWidth: .infinity, maxHeight: .infinity).background {RoundedRectangle(cornerRadius: PointerPromptLayout.composerCornerRadius, style: .continuous)- .fill(Color(nsColor: .windowBackgroundColor))+ .fill(Color(red: 0.08, green: 0.085, blue: 0.085))}.overlay {RoundedRectangle(cornerRadius: PointerPromptLayout.composerCornerRadius, style: .continuous)- .stroke(Color(nsColor: .separatorColor), lineWidth: 1)+ .stroke(Color.white.opacity(0.09), lineWidth: 1)}.shadow(color: Color.black.opacity(state.isActive ? 0.16 : 0.08),@@ -156,75 +151,281 @@ private struct PointerPromptComposer: View {y: state.isActive ? 6 : 3).controlSize(.regular)- .onAppear(perform: syncFocusWithActiveState)- .onChange(of: state.isActive) { _, _ in- syncFocusWithActiveState()+ }+}++private struct ComposerMultilineTextInput: NSViewRepresentable {+ @Binding var text: String+ let placeholder: String+ let isActive: Bool+ let textHeightChanged: @MainActor (CGFloat) -> Void+ let submit: @MainActor () -> Void++ func makeNSView(context: Context) -> NSScrollView {+ let scrollView = NSScrollView()+ scrollView.drawsBackground = false+ scrollView.borderType = .noBorder+ scrollView.hasVerticalScroller = false+ scrollView.hasHorizontalScroller = false+ scrollView.autohidesScrollers = true++ let textView = ComposerTextView()+ textView.delegate = context.coordinator+ textView.shouldFocusWhenAttached = isActive+ textView.placeholder = placeholder+ textView.submit = {+ Task { @MainActor in+ submit()+ }}+ textView.string = text+ textView.font = .systemFont(ofSize: 16)+ textView.textColor = .white+ textView.insertionPointColor = .white+ textView.backgroundColor = .clear+ textView.drawsBackground = false+ textView.isRichText = false+ textView.importsGraphics = false+ textView.allowsUndo = true+ textView.isEditable = true+ textView.isSelectable = true+ textView.isHorizontallyResizable = false+ textView.isVerticallyResizable = true+ textView.minSize = CGSize(+ width: 0,+ height: PointerPromptLayout.composerInputTextMinimumHeight+ )+ textView.maxSize = CGSize(+ width: CGFloat.greatestFiniteMagnitude,+ height: CGFloat.greatestFiniteMagnitude+ )+ textView.autoresizingMask = [.width]+ textView.textContainerInset = .zero+ textView.textContainer?.lineFragmentPadding = 0+ textView.textContainer?.widthTracksTextView = true+ textView.textContainer?.heightTracksTextView = false+ textView.textContainer?.containerSize = CGSize(+ width: scrollView.contentSize.width,+ height: .greatestFiniteMagnitude+ )+ scrollView.documentView = textView++ return scrollView}- private var isSubmitDisabled: Bool {- !state.isPrimaryActionEnabled ||- messageText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ func updateNSView(_ scrollView: NSScrollView, context: Context) {+ context.coordinator.parent = self+ guard let textView = scrollView.documentView as? ComposerTextView else { return }++ textView.shouldFocusWhenAttached = isActive+ textView.placeholder = placeholder+ textView.submit = {+ Task { @MainActor in+ submit()+ }+ }++ if textView.string != text {+ textView.string = text+ textView.needsDisplay = true+ }++ DispatchQueue.main.async {+ context.coordinator.updateTextContainerWidth(for: textView, in: scrollView)+ context.coordinator.reportTextHeight(for: textView)++ if isActive, textView.window?.firstResponder !== textView {+ textView.focusIfNeeded()+ }+ }}- private var closeButtonContentClearance: CGFloat {- PointerPromptLayout.closeButtonInset +- PointerPromptLayout.closeButtonSize+ func makeCoordinator() -> Coordinator {+ Coordinator(parent: self)}- private func syncFocusWithActiveState() {- guard state.isActive else {- isFocused = false- return+ @MainActor+ final class Coordinator: NSObject, NSTextViewDelegate {+ var parent: ComposerMultilineTextInput++ init(parent: ComposerMultilineTextInput) {+ self.parent = parent}- DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {- isFocused = true+ func textDidChange(_ notification: Notification) {+ guard let textView = notification.object as? ComposerTextView else { return }++ parent.text = textView.string+ textView.needsDisplay = true+ reportTextHeight(for: textView)+ }++ func updateTextContainerWidth(+ for textView: NSTextView,+ in scrollView: NSScrollView+ ) {+ let width = max(1, scrollView.contentView.bounds.width)+ let height = max(+ PointerPromptLayout.composerInputTextMinimumHeight,+ scrollView.contentView.bounds.height+ )+ textView.textContainer?.containerSize = CGSize(+ width: width,+ height: .greatestFiniteMagnitude+ )+ textView.frame = CGRect(+ x: 0,+ y: 0,+ width: width,+ height: height+ )+ }++ func reportTextHeight(for textView: NSTextView) {+ guard let layoutManager = textView.layoutManager,+ let textContainer = textView.textContainer else {+ return+ }++ layoutManager.ensureLayout(for: textContainer)+ let usedRect = layoutManager.usedRect(for: textContainer)+ let measuredHeight = ceil(max(+ PointerPromptLayout.composerInputTextMinimumHeight,+ usedRect.height+ ))+ parent.textHeightChanged(measuredHeight)}}}-private struct ComposerCloseButton: View {- let action: @MainActor () -> Void+private final class ComposerTextView: NSTextView {+ var placeholder = ""+ var submit: (() -> Void)?+ var shouldFocusWhenAttached = false++ override var acceptsFirstResponder: Bool {+ true+ }++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ focusIfNeeded()+ }++ func focusIfNeeded() {+ guard shouldFocusWhenAttached else { return }++ window?.makeFirstResponder(self)+ }++ override func keyDown(with event: NSEvent) {+ let isReturn = event.keyCode == 36 || event.keyCode == 76+ let shouldInsertNewline = event.modifierFlags.contains(.shift)++ if isReturn, !shouldInsertNewline {+ submit?()+ return+ }++ super.keyDown(with: event)+ }++ override func draw(_ dirtyRect: NSRect) {+ super.draw(dirtyRect)++ guard string.isEmpty, !placeholder.isEmpty else { return }++ let attributes: [NSAttributedString.Key: Any] = [+ .foregroundColor: NSColor.white.withAlphaComponent(0.58),+ .font: font ?? NSFont.systemFont(ofSize: 16)+ ]+ (placeholder as NSString).draw(at: .zero, withAttributes: attributes)+ }+}++private struct ComposerCloseControl: View {+ let close: @MainActor () -> Voidvar body: some View {- Button(action: action) {- ZStack {- Circle()- .fill(Color(nsColor: .systemRed))- .overlay {- Circle()- .stroke(Color.black.opacity(0.18), lineWidth: 0.5)- }+ ComposerTrafficLight(+ color: Color.white.opacity(0.34),+ hoverColor: Color(nsColor: .systemRed),+ accessibilityLabel: "Close prompt",+ action: close+ )+ }+}- Image(systemName: "xmark")- .font(.system(size: 6, weight: .bold))- .foregroundStyle(Color.black.opacity(0.58))+private struct ComposerTrafficLight: View {+ let color: Color+ var hoverColor: Color?+ var accessibilityLabel: String?+ var action: (@MainActor () -> Void)?+ @State private var isHovered = false++ @ViewBuilder+ var body: some View {+ if let action {+ Button(action: action) {+ trafficLight}+ .buttonStyle(.plain).frame(width: PointerPromptLayout.closeButtonSize,height: PointerPromptLayout.closeButtonSize)+ .contentShape(Circle())+ .onHover { isHovered = $0 }+ .accessibilityLabel(accessibilityLabel ?? "Window control")+ } else {+ trafficLight+ .accessibilityHidden(true)}- .buttonStyle(.plain)- .contentShape(Circle())- .accessibilityLabel("Close prompt")+ }++ private var trafficLight: some View {+ ZStack {+ Circle()+ .fill(isHovered ? hoverColor ?? color : color)+ .overlay {+ Circle()+ .stroke(Color.black.opacity(0.18), lineWidth: 0.5)+ }++ if action != nil {+ Image(systemName: "xmark")+ .font(.system(size: 6, weight: .bold))+ .foregroundStyle(Color.black.opacity(0.58))+ .opacity(isHovered ? 1 : 0)+ }+ }+ .animation(.easeOut(duration: 0.12), value: isHovered)+ .frame(+ width: PointerPromptLayout.closeButtonSize,+ height: PointerPromptLayout.closeButtonSize+ )}}-private struct ComposerToolbarButton: View {- let systemName: String- let title: String- var isProminent = false- var isDisabled = false+private struct ComposerVoiceButton: View {let action: @MainActor () -> Voidvar body: some View {Button(action: action) {- Label(title, systemImage: systemName)+ Image(systemName: "waveform")+ .font(.system(size: 16, weight: .semibold))+ .foregroundStyle(Color.black)+ .frame(+ width: PointerPromptLayout.composerInputVoiceButtonSize,+ height: PointerPromptLayout.composerInputVoiceButtonSize+ )+ .background {+ Circle()+ .fill(Color.white)+ }}- .disabled(isDisabled)- .accessibilityLabel(title)+ .buttonStyle(.plain)+ .accessibilityLabel("Voice input")}}diff --git a/docs/README.md b/docs/README.mdindex 7e5b5751..b0159be1 100644--- a/docs/README.md+++ b/docs/README.md@@ -6,7 +6,7 @@ Plans describe what we might build. Guides describe what Donkey currently suppor## Product Guides-- [Pointer Prompt Overlay](guides/pointer-prompt-overlay.md): command-click agent pointer and standard macOS-style `Make this so` composer that follows the mouse at a fixed offset.+- [Pointer Prompt Overlay](guides/pointer-prompt-overlay.md): double-Command agent pointer and standard macOS-style `Make this so` composer that follows the mouse at a fixed offset.## Engineering Guidesdiff --git a/docs/guides/pointer-prompt-overlay.md b/docs/guides/pointer-prompt-overlay.mdindex c2addb2c..a29eb8e6 100644--- a/docs/guides/pointer-prompt-overlay.md+++ b/docs/guides/pointer-prompt-overlay.md@@ -5,12 +5,13 @@Donkey supports a floating macOS pointer prompt overlay:- shows a small inactive agent pointer that follows the user pointer immediately when Donkey starts-- command-click anywhere to activate and focus the prompt composer at the current pointer location+- double-tap Command and release to activate and focus the prompt composer at the current pointer location without clicking into the target app+- double-tap Command and hold the second Command press to activate voice input- shows a native-cursor-sized agent arrowhead and standard macOS-style `Make this so` composer-- shows the text input, add context, voice, send controls, and active pointer shadow only while active+- shows a dynamic multiline text input, white voice button, and active pointer shadow only while active- keeps the pointer and composer pinned where activation happened until the user closes or drags the composer-- closes the active composer with a traffic-light-style top-left close button and returns to the inactive following pointer-- supports dragging the active composer by its border areas+- closes the active composer with a single gray traffic-light-style top-left close button that turns into a close affordance on hover+- supports dragging the active composer from any area outside the input surface- lets normal clicks pass through the inactive pointer-only overlay and transparent active overlay space- follows the user mouse at a fixed 45-degree bottom-right diagonal- keeps that fixed offset at screen edges instead of flipping or clamping to the visible screen bounds@@ -25,15 +26,20 @@ This is a visual UI capability. It does not capture the screen, send input, call- The overlay window is an `NSPanel` owned by `PointerPromptOverlayController`.- SwiftUI rendering stays in `DonkeyUI`; it receives `PointerPromptState` and `PointerPromptPlacement` from `DonkeyContracts`.- Product state stays in `PointerPromptOverlayModel`.-- Treat the composer like a standard macOS input panel: one surface can contain typed text, submission, and adjacent controls.+- Treat the composer like a compact macOS window containing a single rounded input surface. The input has a fixed width, wraps text into additional lines, and grows the overlay height as text expands.+- Return submits typed text. Shift-Return inserts a deliberate newline.+- The only visible input-adjacent control for now is the white voice button.- Composer controls should emit typed `PointerPromptIntent` values instead of reaching into runtime, AI, or controller code.- Pointer colors load from JSON into `PointerPromptTheme`; views must not hard-code product colors.-- The active composer should use a normal system-window corner radius, expose a traffic-light-style top-left close control, and keep controls/content areas interactive while only border regions drag the window. Transparent active overlay space must pass clicks through to windows underneath.+- The active composer should use a normal system-window corner radius, reserve a small titlebar band with a single gray traffic-light-style top-left close control that shows its close affordance on hover, and keep the input surface and close control interactive while non-input composer surfaces drag the window. Transparent active overlay space must pass clicks through to windows underneath.- The active composer top edge should align with the highest visible point of the agent pointer.- The agent pointer should remain close to native cursor size, use the mirrored SVG cursor silhouette from the Noun Project pointer asset, point in the same up-left direction as the native macOS cursor, and keep its tip 48px from the real pointer on an equal x/y diagonal.- Runtime placement is fixed to `bottomRight`; alternate `PointerPromptPlacement` values are only rendering variants.- The controller must not clamp visible pointer/composer bounds to `NSScreen.visibleFrame`; cursor positioning is a direct fixed-offset calculation.-- Launch positioning and command-click focus handling belong in `PointerPromptOverlayController`, not the SwiftUI view.+- Launch positioning and double-Command focus handling belong in `PointerPromptOverlayController`, not the SwiftUI view.+- Double-Command is the only active shortcut today. Its default lives in `PointerPromptActivationShortcut.doubleCommand` so a future settings layer can supply a different shortcut without rewriting controller event handling.+- Double-Command prompt activation should require two clean Command down/up taps within 450ms. Any intervening key press, mouse press, extra modifier, or overlong Command hold should reset the sequence so normal shortcuts do not summon the composer.+- Holding the second clean Command press for the shortcut's configured hold duration should activate the composer and send the voice input intent instead of waiting for the second release.- Keep the overlay non-invasive: no capture loop, input execution, Accessibility prompt, or LLM call in this feature.## Verification@@ -45,7 +51,7 @@ swift buildswift run Donkey```-Launch Donkey and confirm only the small agent pointer appears and follows the main pointer at a fixed bottom-right diagonal offset. Command-click anywhere to show the composer with keyboard focus, then move the mouse and confirm the active pointer and composer stay pinned. Click through transparent overlay space into another desktop window, drag the composer from border areas, close it with the top-left close button, and confirm the inactive pointer resumes following the main pointer. Type a message, confirm the send control enables, and activate near the bottom-right screen edge to confirm the prompt keeps the same fixed offset instead of flipping or clamping.+Launch Donkey and confirm only the small agent pointer appears and follows the main pointer at a fixed bottom-right diagonal offset. Double-tap Command and release to show the composer with keyboard focus, then move the mouse and confirm the active pointer and composer stay pinned. Double-tap Command again but hold the second Command press, and confirm voice input is requested. Type enough text to wrap and confirm the window grows downward while its top edge stays fixed. Press Shift-Return and confirm it inserts a newline; press Return and confirm it submits. Click through transparent overlay space into another desktop window, drag the composer from non-input areas, close it with the top-left close button, and confirm the inactive pointer resumes following the main pointer. Activate near the bottom-right screen edge to confirm the prompt keeps the same fixed offset instead of flipping or clamping. Confirm Command plus another key, Command-click, and a single Command tap do not activate the composer.To verify color customization, edit `apps/Donkey/Sources/Donkey/Resources/theme.json`, rebuild, and run Donkey.diff --git a/docs/guides/swift-mvc.md b/docs/guides/swift-mvc.mdindex 613500ae..9260ea16 100644--- a/docs/guides/swift-mvc.md+++ b/docs/guides/swift-mvc.md@@ -15,7 +15,7 @@ Donkey Swift code should keep product state, UI rendering, and AppKit orchestrat- Keep SwiftUI views value-like: pass state in, pass typed intent sinks out, and avoid timers, global mouse reads, model providers, or window management inside views.- Keep models on `@MainActor` when they publish UI state. Models may depend on narrow provider protocols, but not on AppKit windows or timers.-- Keep controllers on `@MainActor` when they touch AppKit. Controllers may read `NSEvent.mouseLocation`, monitor command-click activation, own `NSPanel`, and translate geometry into model state.+- Keep controllers on `@MainActor` when they touch AppKit. Controllers may read `NSEvent.mouseLocation`, monitor double-Command activation, own `NSPanel`, and translate geometry into model state.- Keep app entry files small. They should define `@main`, delegate adaptation, and little else.- Prefer target-level separation for reusable contracts and UI: `DonkeyContracts`, `DonkeyUI`, `DonkeyRuntime`, and `DonkeyAI`.- Keep shared UI state types in `DonkeyContracts`, not in `DonkeyUI`, when models and views both need them.@@ -28,7 +28,7 @@ The pointer overlay follows this split:- model state covers prompt text, typed input, placement, theme, and typed intents- views render the composer and pointer from model state-- the controller owns AppKit-only work such as the floating panel, command-click activation, screen bounds, and movement timing+- the controller owns AppKit-only work such as the floating panel, double-Command activation, fixed-offset positioning, and movement timing- app entry bootstraps the feature and avoids owning product behavior## Review Checklist