Skip to content

Commit 1ace34f

Browse files
authored
feat(computer-use): find and update reminders through app commands (#10222)
* feat(computer-use): find and update reminders through app commands * fix(computer-use): refuse stale reminder updates and bound replies in UTF-16 units
1 parent 86db551 commit 1ace34f

6 files changed

Lines changed: 356 additions & 43 deletions

File tree

‎apps/desktop/native/computer-use/ComputerUse.swift‎

Lines changed: 131 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,26 @@ struct Parameters: Decodable {
4242
var clickCount: Int?
4343
var accessibilityAction: String?
4444
var command: AppCommand?
45+
var expected: ReminderExpectation?
46+
}
47+
/// The reminder as the user saw it when approving an update; the write is refused if a field it changes has moved since.
48+
struct ReminderExpectation: Decodable {
49+
var title: String
50+
var due: String?
51+
var priority: Int
52+
var completed: Bool
53+
var notes: String?
4554
}
4655
/// One allowlisted app command. Commands go through EventKit and Contacts, never Apple Events or
47-
/// scripts, so they cannot reach a shell; each is a typed create or a list read, with no update,
48-
/// delete or search.
56+
/// scripts, so they cannot reach a shell; each is a typed create, a bounded read, or a reminder
57+
/// update by id. Nothing is ever deleted.
4958
struct AppCommand: Decodable {
5059
var name: String
60+
var id: String?
61+
var titleContains: String?
62+
var includeCompleted: Bool?
63+
var completed: Bool?
64+
var clearDue: Bool?
5165
var title: String?
5266
var notes: String?
5367
var due: String?
@@ -67,6 +81,16 @@ struct AppCommand: Decodable {
6781
var phones: [String]?
6882
var groupId: String?
6983
}
84+
/// At most `max` UTF-16 units, the unit the reply's schema counts, cut on a character boundary:
85+
/// Swift's `prefix` counts characters, and one emoji can be several units.
86+
func bounded(_ text: String, _ max: Int) -> String {
87+
guard text.utf16.count > max else { return text }
88+
var units = 0
89+
return String(text.prefix { character in
90+
units += character.utf16.count
91+
return units <= max
92+
})
93+
}
7094
func invalidCommand(_ message: String) -> ComputerError { ComputerError("invalid_arguments", message, dispatchState: "not_started") }
7195
/// A required, trimmed text field of bounded length.
7296
func commandText(_ value: String?, _ field: String, max: Int = 1024) throws -> String {
@@ -171,12 +195,96 @@ func eventDate(_ text: String?, _ field: String, allDay: Bool) throws -> Date {
171195
guard let date = isoDateTime(text) else { throw invalidCommand("\(field) must be a real ISO 8601 date-time.") }
172196
return date
173197
}
174-
func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
198+
/// Reminders matching a predicate; EventKit only offers the asynchronous fetch.
199+
func fetchReminders(_ store: EKEventStore, _ predicate: NSPredicate) async -> [EKReminder] {
200+
await withCheckedContinuation { continuation in
201+
store.fetchReminders(matching: predicate) { continuation.resume(returning: $0 ?? []) }
202+
}
203+
}
204+
/// A reminder as reads and confirmations report it.
205+
func reminderItem(_ reminder: EKReminder) -> [String: Any] {
206+
var item: [String: Any] = [
207+
"id": reminder.calendarItemIdentifier, "title": bounded((reminder.title ?? ""), 1024),
208+
"list": bounded(reminder.calendar.title, 1024), "priority": reminder.priority, "completed": reminder.isCompleted,
209+
]
210+
if let notes = reminder.notes, !notes.isEmpty { item["notes"] = bounded(notes, 8000) }
211+
if let due = reminder.dueDateComponents { item["due"] = dueText(due) }
212+
return item
213+
}
214+
/// Due components written back the way commands take them: `YYYY-MM-DD`, or this Mac's local `YYYY-MM-DDTHH:MM:SS`.
215+
func dueText(_ due: DateComponents) -> String {
216+
let day = String(format: "%04d-%02d-%02d", due.year ?? 0, due.month ?? 0, due.day ?? 0)
217+
guard due.hour != nil else { return day }
218+
var source = Calendar(identifier: .gregorian); source.timeZone = due.timeZone ?? .current
219+
guard let date = source.date(from: due) else { return day }
220+
let local = localGregorian().dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
221+
return String(format: "%04d-%02d-%02dT%02d:%02d:%02d", local.year ?? 0, local.month ?? 0, local.day ?? 0, local.hour ?? 0, local.minute ?? 0, local.second ?? 0)
222+
}
223+
/// Up to 50 reminders, incomplete unless asked otherwise, optionally in one list and matching part of a
224+
/// title; or the one reminder with `id`, which an update reads to show its current values.
225+
func findReminders(_ command: AppCommand) async throws -> [String: Any] {
226+
let contains = try optionalText(command.titleContains, "titleContains", max: 256)
227+
let store = try remindersStore()
228+
if let id = command.id {
229+
let found = (store.calendarItem(withIdentifier: id) as? EKReminder).map { [reminderItem($0)] } ?? []
230+
return ["kind": "command", "command": command.name, "reminders": found, "truncated": false]
231+
}
232+
var lists: [EKCalendar]?
233+
if let listId = command.listId {
234+
guard let found = store.calendar(withIdentifier: listId), found.allowedEntityTypes.contains(.reminder) else {
235+
throw ComputerError("list_unavailable", "No reminder list has this id; call list_reminder_lists.", dispatchState: "not_started")
236+
}
237+
lists = [found]
238+
}
239+
let predicate = command.includeCompleted == true
240+
? store.predicateForReminders(in: lists)
241+
: store.predicateForIncompleteReminders(withDueDateStarting: nil, ending: nil, calendars: lists)
242+
var matches = await fetchReminders(store, predicate)
243+
if let contains { matches = matches.filter { ($0.title ?? "").localizedCaseInsensitiveContains(contains) } }
244+
return ["kind": "command", "command": command.name, "reminders": matches.prefix(50).map(reminderItem), "truncated": matches.count > 50]
245+
}
246+
func runAppCommand(_ command: AppCommand, expected: ReminderExpectation? = nil) throws -> [String: Any] {
175247
switch command.name {
248+
case "update_reminder":
249+
let id = try commandText(command.id, "id", max: 256)
250+
let title = try command.title.map { try commandText($0, "Title") }
251+
// Blank notes clear them, as deleting them in the app would; others are trimmed, as a create trims them.
252+
if let notes = command.notes, notes.count > 8000 { throw invalidCommand("Notes are limited to 8000 characters.") }
253+
if let priority = command.priority, ![0, 1, 5, 9].contains(priority) { throw invalidCommand("Priority must be 0 (none), 1 (high), 5 (medium) or 9 (low).") }
254+
if command.due != nil && command.clearDue == true { throw invalidCommand("Pass due or clearDue, not both.") }
255+
let due = try command.due.map { try dueComponents($0) }
256+
guard title != nil || command.notes != nil || command.priority != nil || due != nil || command.clearDue == true || command.completed != nil else {
257+
throw invalidCommand("An update needs at least one field to change.")
258+
}
259+
let store = try remindersStore()
260+
guard let reminder = store.calendarItem(withIdentifier: id) as? EKReminder else {
261+
throw ComputerError("not_found", "No reminder has this id; call find_reminders.", dispatchState: "not_started")
262+
}
263+
guard reminder.calendar.allowsContentModifications else { throw ComputerError("list_read_only", "This reminder list is read-only.", dispatchState: "not_started") }
264+
guard let expected else { throw invalidCommand("An update needs the values the user approved.") }
265+
let now = reminderItem(reminder)
266+
let moved = (title != nil && now["title"] as? String != expected.title)
267+
|| ((due != nil || command.clearDue == true) && now["due"] as? String != expected.due)
268+
|| (command.priority != nil && now["priority"] as? Int != expected.priority)
269+
|| (command.completed != nil && now["completed"] as? Bool != expected.completed)
270+
|| (command.notes != nil && now["notes"] as? String != expected.notes)
271+
guard !moved else {
272+
throw ComputerError("reminder_changed", "This reminder changed while the user was confirming; read it again with find_reminders before retrying.", dispatchState: "not_started")
273+
}
274+
if let title { reminder.title = title }
275+
if let notes = command.notes { reminder.notes = try optionalText(notes, "Notes", max: 8000) }
276+
if let priority = command.priority { reminder.priority = priority }
277+
if let due { reminder.dueDateComponents = due }
278+
if command.clearDue == true { reminder.dueDateComponents = nil }
279+
if let completed = command.completed { reminder.isCompleted = completed }
280+
try checkCancellation()
281+
inputDispatched = true
282+
try store.save(reminder, commit: true)
283+
return ["kind": "command", "command": command.name, "updated": ["id": reminder.calendarItemIdentifier, "title": bounded((reminder.title ?? ""), 1024), "list": bounded(reminder.calendar.title, 1024)]]
176284
case "list_reminder_lists":
177285
let allLists = try remindersStore().calendars(for: .reminder)
178286
let lists = allLists.prefix(200).map { list -> [String: Any] in
179-
["id": list.calendarIdentifier, "title": String(list.title.prefix(1024)), "allowsModifications": list.allowsContentModifications]
287+
["id": list.calendarIdentifier, "title": bounded(list.title, 1024), "allowsModifications": list.allowsContentModifications]
180288
}
181289
return ["kind": "command", "command": command.name, "items": lists, "truncated": allLists.count > 200]
182290
case "create_reminder":
@@ -206,7 +314,7 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
206314
case "list_calendars":
207315
let allCalendars = try calendarStore().calendars(for: .event)
208316
let calendars = allCalendars.prefix(200).map { calendar -> [String: Any] in
209-
["id": calendar.calendarIdentifier, "title": String(calendar.title.prefix(1024)), "allowsModifications": calendar.allowsContentModifications]
317+
["id": calendar.calendarIdentifier, "title": bounded(calendar.title, 1024), "allowsModifications": calendar.allowsContentModifications]
210318
}
211319
return ["kind": "command", "command": command.name, "items": calendars, "truncated": allCalendars.count > 200]
212320
case "create_event":
@@ -245,7 +353,7 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
245353
case "list_contact_groups":
246354
let allGroups = try contactStore().groups(matching: nil)
247355
let groups = allGroups.prefix(200).map { group -> [String: Any] in
248-
["id": group.identifier, "title": String(group.name.prefix(1024)), "allowsModifications": true]
356+
["id": group.identifier, "title": bounded(group.name, 1024), "allowsModifications": true]
249357
}
250358
return ["kind": "command", "command": command.name, "items": groups, "truncated": allGroups.count > 200]
251359
case "create_contact_group":
@@ -290,8 +398,8 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
290398
inputDispatched = true
291399
try store.execute(request)
292400
let display = [given, family].compactMap { $0 }.joined(separator: " ")
293-
let title = String((display.isEmpty ? organization ?? "" : display).prefix(1024))
294-
return ["kind": "command", "command": command.name, "created": ["id": contact.identifier, "title": title, "list": String((group?.name ?? "Contacts").prefix(1024))]]
401+
let title = bounded((display.isEmpty ? organization ?? "" : display), 1024)
402+
return ["kind": "command", "command": command.name, "created": ["id": contact.identifier, "title": title, "list": bounded((group?.name ?? "Contacts"), 1024)]]
295403
default:
296404
throw ComputerError("unknown_command", "Unknown app command.", dispatchState: "not_started")
297405
}
@@ -688,9 +796,9 @@ final class Snapshot {
688796
var labels = [kAXTitleAttribute, kAXDescriptionAttribute].compactMap { values[$0] as? String }.filter { !$0.isEmpty }
689797
if labels.isEmpty { labels = [kAXPlaceholderValueAttribute, kAXHelpAttribute].compactMap { values[$0] as? String }.filter { !$0.isEmpty } }
690798
if role == kAXMenuItemRole, let shortcut = menuShortcut(element) { labels.append(shortcut) }
691-
if !isSecure, !labels.isEmpty { node["label"] = String(labels.joined(separator: " ").prefix(1024)) }
799+
if !isSecure, !labels.isEmpty { node["label"] = bounded(labels.joined(separator: " "), 1024) }
692800
if !isSecure, let raw = values[kAXValueAttribute] {
693-
if let value = raw as? String { node["value"] = String(value.prefix(2048)) }
801+
if let value = raw as? String { node["value"] = bounded(value, 2048) }
694802
else if let value = raw as? NSNumber { node["value"] = value.stringValue }
695803
}
696804
if !isSecure {
@@ -699,12 +807,12 @@ final class Snapshot {
699807
let writableValue = [kAXTextAreaRole, kAXTextFieldRole].contains(role)
700808
&& AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &writable) == .success && writable.boolValue
701809
node["editable"] = writableValue
702-
if let placeholder = values[kAXPlaceholderValueAttribute] as? String { node["placeholder"] = String(placeholder.prefix(1024)) }
810+
if let placeholder = values[kAXPlaceholderValueAttribute] as? String { node["placeholder"] = bounded(placeholder, 1024) }
703811
}
704812
if let enabled = values[kAXEnabledAttribute] as? Bool { node["enabled"] = enabled }
705813
if let rect = axRect(position: values[kAXPositionAttribute], size: values[kAXSizeAttribute]) { node.merge(rectJSON(rect)) { _, new in new } }
706814
var actions: CFArray?
707-
if AXUIElementCopyActionNames(element, &actions) == .success { node["actions"] = Array((actions as? [String] ?? []).prefix(128)).map { String($0.prefix(128)) } }
815+
if AXUIElementCopyActionNames(element, &actions) == .success { node["actions"] = Array((actions as? [String] ?? []).prefix(128)).map { bounded($0, 128) } }
708816
nodes.append(node)
709817
if role == kAXWindowRole, let preferredWindow, !CFEqual(element, preferredWindow) { continue }
710818
if !isSecure, entry.depth < 64 {
@@ -997,13 +1105,13 @@ func discoverApps() throws -> [[String: Any]] {
9971105
enumerator.skipDescendants()
9981106
guard let bundle = Bundle(url: url), let id = bundle.bundleIdentifier, id.utf8.count <= 255 else { continue }
9991107
let name = bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String ?? url.deletingPathExtension().lastPathComponent
1000-
entries[id] = ["bundleId": id, "name": String(name.prefix(1024)), "isActive": false]
1108+
entries[id] = ["bundleId": id, "name": bounded(name, 1024), "isActive": false]
10011109
} else if enumerator.level >= 3 { enumerator.skipDescendants() }
10021110
}
10031111
}
10041112
for app in NSWorkspace.shared.runningApplications where app.activationPolicy == .regular {
10051113
guard let id = app.bundleIdentifier, id.utf8.count <= 255 else { continue }
1006-
entries[id] = ["bundleId": id, "name": String((app.localizedName ?? id).prefix(1024)), "pid": app.processIdentifier, "isActive": app.isActive]
1114+
entries[id] = ["bundleId": id, "name": bounded((app.localizedName ?? id), 1024), "pid": app.processIdentifier, "isActive": app.isActive]
10071115
}
10081116
return Array(entries.values.sorted { ($0["bundleId"] as? String ?? "") < ($1["bundleId"] as? String ?? "") }.prefix(1000))
10091117
}
@@ -1064,7 +1172,10 @@ final class Driver {
10641172
case "list_apps": return ["kind": "apps", "apps": try discoverApps()]
10651173
case "app_command":
10661174
inputDispatched = false
1067-
return try runAppCommand(required(p.command, "command"))
1175+
let command = try required(p.command, "command")
1176+
// EventKit only fetches reminders asynchronously.
1177+
if command.name == "find_reminders" { return try await findReminders(command) }
1178+
return try runAppCommand(command, expected: p.expected)
10681179
case "activate_app":
10691180
try requireAccessibility()
10701181
let app = try await appFor(p.bundleId, launch: true)
@@ -1095,7 +1206,7 @@ final class Driver {
10951206
let matches = axWindows.filter { elementRect($0) == rect }
10961207
if matches.count == 1, onScreen(entry) { snapshot.windowElements[id.stringValue] = matches[0] }
10971208
var result: [String: Any] = ["windowId": id.stringValue, "title": entry[kCGWindowName as String] as? String ?? ""]
1098-
if let title = result["title"] as? String { result["title"] = String(title.prefix(4096)) }
1209+
if let title = result["title"] as? String { result["title"] = bounded(title, 4096) }
10991210
result.merge(rectJSON(rect)) { _, new in new }; return result
11001211
}
11011212
if snapshots.count >= 16 { snapshots.removeAll() }
@@ -1117,8 +1228,8 @@ final class Driver {
11171228
do {
11181229
guard #available(macOS 14.0, *) else { throw ComputerError("unsupported_os", "Screenshots require macOS 14 or later.") }
11191230
result["screenshot"] = try await screenshot(pid: app.processIdentifier, windowID: selectedWindowId, observedFrame: try required(snapshot.windowFrames[selectedWindowId], "observed window frame"))
1120-
} catch let error as ComputerError { result["screenshotError"] = String((error.code + ": " + error.message).prefix(2000)) }
1121-
catch { result["screenshotError"] = String(("capture_failed: " + String(describing: error)).prefix(2000)) }
1231+
} catch let error as ComputerError { result["screenshotError"] = bounded((error.code + ": " + error.message), 2000) }
1232+
catch { result["screenshotError"] = bounded(("capture_failed: " + String(describing: error)), 2000) }
11221233
}
11231234
result["isActive"] = app.isActive
11241235
return result
@@ -1153,7 +1264,7 @@ final class Driver {
11531264
var completed = 0
11541265
func stopped(_ message: String) -> [String: Any] {
11551266
["kind": "action", "action": "batch", "bundleId": bundle, "dispatched": true, "verified": false,
1156-
"sequence": ["completedSteps": completed, "totalSteps": steps.count, "error": String((message + " The remaining steps were not run; observe the app before continuing, and do not retry the batch.").prefix(2000))]]
1267+
"sequence": ["completedSteps": completed, "totalSteps": steps.count, "error": bounded((message + " The remaining steps were not run; observe the app before continuing, and do not retry the batch."), 2000)]]
11571268
}
11581269
for (index, step) in steps.enumerated() {
11591270
// Stop can arrive during the previous step's render wait; no later step may start after it.
@@ -1481,7 +1592,7 @@ struct Main {
14811592
if let dispatchState = error.dispatchState { details["dispatchState"] = dispatchState }
14821593
response = ["id": id, "error": details]
14831594
}
1484-
catch { response = ["id": id, "error": ["code": "request_failed", "message": String(String(describing: error).prefix(2000))]] }
1595+
catch { response = ["id": id, "error": ["code": "request_failed", "message": bounded(String(describing: error), 2000)]] }
14851596
let data: Data?
14861597
do { data = try encodeReply(response) } catch let error as ComputerError {
14871598
data = try? encodeReply(["id": id, "error": ["code": error.code, "message": error.message]])

0 commit comments

Comments
 (0)