Skip to content

Commit c6822a5

Browse files
committed
feat(computer-use): add typed reminder app commands behind a desktop capability
1 parent 5858006 commit c6822a5

23 files changed

Lines changed: 407 additions & 50 deletions

File tree

‎apps/desktop/build/entitlements.mac.plist‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,9 @@
1414
Hardened Runtime denies the camera no matter what the user allowed. -->
1515
<key>com.apple.security.device.camera</key>
1616
<true/>
17+
<!-- Computer Use app commands add confirmed reminders through EventKit;
18+
the Hardened Runtime denies EventKit access without this key. -->
19+
<key>com.apple.security.personal-information.calendars</key>
20+
<true/>
1721
</dict>
1822
</plist>

‎apps/desktop/electron-builder.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ mac:
7070
# unless the bundle declares why it wants the device.
7171
extendInfo:
7272
NSScreenCaptureUsageDescription: Mothership captures approved app windows to understand and verify computer-use actions.
73+
NSRemindersFullAccessUsageDescription: Mothership adds reminders you confirm and lists your reminder lists so it can file them correctly.
7374
NSMicrophoneUsageDescription: Sim uses your microphone for voice input in Chat and for meetings you join in the built-in browser.
7475
NSCameraUsageDescription: Sim uses your camera for meetings you join in the built-in browser, such as Google Meet.
7576
# macOS 15 blocks connections to private addresses (self-hosted servers on a

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

Lines changed: 86 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import AppKit
22
import ApplicationServices
3+
import EventKit
34
import ScreenCaptureKit
45

56
nonisolated(unsafe) var cancellationRequested: sig_atomic_t = 0
@@ -39,6 +40,85 @@ struct Parameters: Decodable {
3940
var button: String?
4041
var clickCount: Int?
4142
var accessibilityAction: String?
43+
var command: AppCommand?
44+
}
45+
/// One allowlisted app command. Commands go through EventKit, never Apple Events or scripts, so they
46+
/// cannot reach a shell; each is a typed create or a list read, with no update, delete or search.
47+
struct AppCommand: Decodable {
48+
var name: String
49+
var title: String?
50+
var notes: String?
51+
var due: String?
52+
var listId: String?
53+
var priority: Int?
54+
}
55+
/// The event store for reminders, available only once the user has granted full Reminders access.
56+
/// Checking never prompts; the grant happens from settings, outside the tool call.
57+
func remindersStore() throws -> EKEventStore {
58+
guard EKEventStore.authorizationStatus(for: .reminder) == .fullAccess else {
59+
throw ComputerError("reminders_permission_required", "Allow Reminders access for Mothership in System Settings, then retry.", dispatchState: "not_started")
60+
}
61+
return EKEventStore()
62+
}
63+
/// A due date: `YYYY-MM-DD` is date-only; a date-time must be ISO 8601 with an explicit offset or `Z`,
64+
/// so the reminder never depends on the helper's time zone guess.
65+
func dueComponents(_ text: String) throws -> DateComponents {
66+
var calendar = Calendar(identifier: .gregorian)
67+
if text.range(of: #"^\d{4}-\d{2}-\d{2}$"#, options: .regularExpression) != nil {
68+
let parts = text.split(separator: "-").compactMap { Int($0) }
69+
let components = DateComponents(calendar: calendar, year: parts[0], month: parts[1], day: parts[2])
70+
guard components.isValidDate else { throw ComputerError("invalid_arguments", "Due date is not a real date.", dispatchState: "not_started") }
71+
return DateComponents(year: parts[0], month: parts[1], day: parts[2])
72+
}
73+
let formatter = ISO8601DateFormatter(); formatter.formatOptions = [.withInternetDateTime]
74+
guard let date = formatter.date(from: text) else {
75+
throw ComputerError("invalid_arguments", "Due must be YYYY-MM-DD or an ISO 8601 date-time with an offset.", dispatchState: "not_started")
76+
}
77+
calendar.timeZone = .current
78+
return calendar.dateComponents([.year, .month, .day, .hour, .minute, .timeZone], from: date)
79+
}
80+
/// Reminders access as the status reports it, read without prompting.
81+
func remindersAuthorization() -> String {
82+
switch EKEventStore.authorizationStatus(for: .reminder) {
83+
case .fullAccess: return "granted"
84+
case .notDetermined: return "not_determined"
85+
default: return "denied"
86+
}
87+
}
88+
func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
89+
switch command.name {
90+
case "list_reminder_lists":
91+
let lists = try remindersStore().calendars(for: .reminder).prefix(200).map { list -> [String: Any] in
92+
["id": list.calendarIdentifier, "title": String(list.title.prefix(1024)), "allowsModifications": list.allowsContentModifications]
93+
}
94+
return ["kind": "command", "command": command.name, "items": lists]
95+
case "create_reminder":
96+
let title = (command.title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
97+
guard !title.isEmpty, title.count <= 1024 else { throw ComputerError("invalid_arguments", "A reminder needs a title of at most 1024 characters.", dispatchState: "not_started") }
98+
guard (command.notes?.count ?? 0) <= 8000 else { throw ComputerError("invalid_arguments", "Notes are limited to 8000 characters.", dispatchState: "not_started") }
99+
guard [0, 1, 5, 9].contains(command.priority ?? 0) else { throw ComputerError("invalid_arguments", "Priority must be 0 (none), 1 (high), 5 (medium) or 9 (low).", dispatchState: "not_started") }
100+
let due = try command.due.map(dueComponents)
101+
let store = try remindersStore()
102+
let list: EKCalendar
103+
if let listId = command.listId {
104+
guard let found = store.calendar(withIdentifier: listId), found.allowedEntityTypes.contains(.reminder) else {
105+
throw ComputerError("list_unavailable", "No reminder list has this id; call list_reminder_lists.", dispatchState: "not_started")
106+
}
107+
list = found
108+
} else {
109+
guard let fallback = store.defaultCalendarForNewReminders() else { throw ComputerError("list_unavailable", "Reminders has no default list; pass listId.", dispatchState: "not_started") }
110+
list = fallback
111+
}
112+
guard list.allowsContentModifications else { throw ComputerError("list_read_only", "This reminder list is read-only.", dispatchState: "not_started") }
113+
let reminder = EKReminder(eventStore: store)
114+
reminder.calendar = list; reminder.title = title; reminder.notes = command.notes
115+
reminder.priority = command.priority ?? 0; reminder.dueDateComponents = due
116+
inputDispatched = true
117+
try store.save(reminder, commit: true)
118+
return ["kind": "command", "command": command.name, "created": ["id": reminder.calendarItemIdentifier, "title": title, "list": list.title]]
119+
default:
120+
throw ComputerError("unknown_command", "Unknown app command.", dispatchState: "not_started")
121+
}
42122
}
43123
struct Request: Decodable { let id: String; let method: String; let params: Parameters }
44124
func required<T>(_ value: T?, _ name: String) throws -> T {
@@ -798,11 +878,15 @@ final class Driver {
798878
let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
799879
_ = AXIsProcessTrustedWithOptions(options)
800880
case "screenCapture": _ = CGRequestScreenCaptureAccess()
881+
case "reminders": _ = try? await EKEventStore().requestFullAccessToReminders()
801882
default: throw ComputerError("invalid_arguments", "Unknown permission.")
802883
}
803-
return ["kind": "status", "platform": "darwin", "accessibility": AXIsProcessTrusted(), "screenRecording": CGPreflightScreenCaptureAccess()]
804-
case "status": return ["kind": "status", "platform": "darwin", "accessibility": AXIsProcessTrusted(), "screenRecording": CGPreflightScreenCaptureAccess()]
884+
return ["kind": "status", "platform": "darwin", "accessibility": AXIsProcessTrusted(), "screenRecording": CGPreflightScreenCaptureAccess(), "reminders": remindersAuthorization()]
885+
case "status": return ["kind": "status", "platform": "darwin", "accessibility": AXIsProcessTrusted(), "screenRecording": CGPreflightScreenCaptureAccess(), "reminders": remindersAuthorization()]
805886
case "list_apps": return ["kind": "apps", "apps": try discoverApps()]
887+
case "app_command":
888+
inputDispatched = false
889+
return try runAppCommand(required(p.command, "command"))
806890
case "activate_app":
807891
try requireAccessibility()
808892
let app = try await appFor(p.bundleId, launch: true)

‎apps/desktop/native/computer-use/Info.plist‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@
1111
<key>LSMinimumSystemVersion</key><string>14.0</string>
1212
<key>LSUIElement</key><true/>
1313
<key>NSHighResolutionCapable</key><true/>
14+
<key>NSRemindersFullAccessUsageDescription</key><string>Mothership adds reminders you confirm and lists your reminder lists so it can file them correctly.</string>
1415
<key>NSScreenCaptureUsageDescription</key><string>Mothership captures the app window you select to understand and verify computer-use actions.</string>
1516
</dict></plist>

‎apps/desktop/native/computer-use/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ Compile each architecture with `swiftc -parse-as-library -O -target arm64-apple-
66

77
## Protocol
88

9-
Persistent newline-delimited JSON over stdin/stdout: `{id,method,params}` returns `{id,result}` or `{id,error:{code,message,dispatchState?}}`. The producer contract is `worker/packages/contracts/src/computer-use.ts` in mothership, copied into the desktop bridge by contract sync. `request_permission` is a local onboarding method, never a model tool; params are `{permission:"accessibility"|"screenCapture"}`. Status/preflight never triggers prompts. Errors go through the protocol, and stdout contains no logs.
9+
Persistent newline-delimited JSON over stdin/stdout: `{id,method,params}` returns `{id,result}` or `{id,error:{code,message,dispatchState?}}`. The producer contract is `worker/packages/contracts/src/computer-use.ts` in mothership, copied into the desktop bridge by contract sync. `request_permission` is a local onboarding method, never a model tool; params are `{permission:"accessibility"|"screenCapture"|"reminders"}`. Status/preflight never triggers prompts; it reports `reminders` as `granted`, `denied` or `not_determined`.
10+
11+
`app_command` takes `{command:{name,...}}` and runs one allowlisted command through EventKit, never Apple Events or scripts: `list_reminder_lists` returns `{kind:"command",items:[{id,title,allowsModifications}]}`, and `create_reminder` (`title`, optional `notes`, `due` as `YYYY-MM-DD` or an ISO 8601 date-time with an offset, `listId`, `priority` 0/1/5/9) returns `{kind:"command",created:{id,title,list}}`. Without full Reminders access it fails with `reminders_permission_required` before touching anything. There is no update, delete or search. The desktop service confirms each create with the user before sending it. Errors go through the protocol, and stdout contains no logs.
1012

1113
The helper observes up to 2000 accessibility nodes (depth 64, queue 4000, traversal deadline 8 seconds, each AX call timeout 250ms). Selected-window and focused-element ancestry are prioritized. The menu bar and menus are read in place, so an open menu's items and their submenus come first; items of closed menus are read last, capped at 80 menu nodes. Electron accessibility is enabled using its documented `AXManualAccessibility` attribute. The helper observes 100 windows and 1000 apps. Requests are bounded to 128 KiB during ingestion. Text/value input is capped at 32000 UTF-16 units. State references are per-process, per-app, expire after 60 seconds, and are consumed by every action that reaches the app; a request that fails before sending anything reports `dispatchState: "not_started"` and keeps them valid. An Accessibility failure counts as sent unless Accessibility rejected the request before the app saw it (unsupported attribute or action, illegal argument). Restarts invalidate all references. Screen captures exclude window shadows, preserve the selected window’s coordinate geometry, and are capped to 1600 pixels on the longest side and 8 MiB encoded. Complete JSON replies are capped at 16 MiB: oversized observations omit screenshots first, then truncate accessibility nodes, while preserving action outcomes. Screenshots are optional and failure is reported in `screenshotError` without discarding accessibility state. macOS 26 uses the screenshot-specific capture API; the macOS 14/15 API path includes only the selected window in a display filter and crops its exact frame. That older path requires the window to fit within one display and reports `capture_geometry_unavailable` otherwise.
1214

‎apps/desktop/native/computer-use/tests/NativeTests.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,16 @@ import AppKit
3636
precondition(isProtectedApp(bundle), bundle)
3737
}
3838
for bundle in ["com.apple.TextEdit", "com.apple.finder", "com.apple.Safari"] { precondition(!isProtectedApp(bundle), bundle) }
39+
let dateOnly = try dueComponents("2027-05-04")
40+
precondition(dateOnly.year == 2027 && dateOnly.month == 5 && dateOnly.day == 4 && dateOnly.hour == nil)
41+
let timed = try dueComponents("2027-05-04T09:30:00Z")
42+
precondition(timed.hour != nil && timed.minute != nil)
43+
for due in ["2027-02-30", "2027-05-04T09:30:00", "May 4", "2027-5-4"] {
44+
expectError("invalid_arguments") { _ = try dueComponents(due) }
45+
}
46+
expectError("unknown_command") { _ = try runAppCommand(AppCommand(name: "run_script")) }
47+
expectError("invalid_arguments") { _ = try runAppCommand(AppCommand(name: "create_reminder", title: " ")) }
48+
expectError("invalid_arguments") { _ = try runAppCommand(AppCommand(name: "create_reminder", title: "Pay rent", priority: 3)) }
3949
var queue = AXTraversalQueue<String>(limit: 1000)
4050
queue.append(AXTraversalEntry(element: "menu", parent: nil, depth: 0, menu: true, priority: false))
4151
queue.append(AXTraversalEntry(element: "content", parent: nil, depth: 0, menu: false, priority: false))

‎apps/desktop/src/main/computer-use/service.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ function setup(enabled = true, askForApps = true) {
2828
kind: 'apps',
2929
apps: [{ bundleId: 'com.example.Fixture', name: 'Fixture', pid: 42, isActive: false }],
3030
}
31+
if (method === 'app_command')
32+
return {
33+
kind: 'command',
34+
command: 'create_reminder',
35+
created: { id: 'r1', title: 'Pay rent', list: 'Reminders' },
36+
}
3137
if (method === 'get_app_state')
3238
return {
3339
kind: 'state',
@@ -48,6 +54,7 @@ function setup(enabled = true, askForApps = true) {
4854
})
4955
const native = { request, stop: vi.fn() }
5056
const approveApp = vi.fn(async (): Promise<'always' | 'deny' | 'once'> => 'always')
57+
const confirmAppCommand = vi.fn(async (_request: { appName: string; summary: string }) => true)
5158
const onActivity = vi.fn()
5259
const openPermissionSettings = vi.fn(async () => {})
5360
const setStopShortcutActive = vi.fn((active: boolean) => active)
@@ -56,6 +63,7 @@ function setup(enabled = true, askForApps = true) {
5663
native,
5764
supported: true,
5865
approveApp,
66+
confirmAppCommand,
5967
onActivity,
6068
setStopShortcutActive,
6169
openPermissionSettings,
@@ -77,6 +85,7 @@ function setup(enabled = true, askForApps = true) {
7785
config,
7886
native,
7987
approveApp,
88+
confirmAppCommand,
8089
onActivity,
8190
setStopShortcutActive,
8291
openPermissionSettings,
@@ -116,6 +125,61 @@ describe('native computer use authority and lifecycle', () => {
116125
expect(native.request.mock.calls.map(([method]) => method)).toEqual(['list_apps'])
117126
})
118127

128+
it('confirms each app-command write before the helper runs it, and never observes after', async () => {
129+
const { service, native, confirmAppCommand } = setup()
130+
const create = {
131+
action: 'app_command',
132+
command: { name: 'create_reminder', title: 'Pay rent', due: '2027-05-04', priority: 1 },
133+
}
134+
confirmAppCommand.mockResolvedValueOnce(false)
135+
await expect(service.execute('declined', 'chat', create)).rejects.toMatchObject({
136+
details: { code: 'user_declined', dispatchState: 'not_started' },
137+
})
138+
expect(native.request.mock.calls.map(([method]) => method)).not.toContain('app_command')
139+
expect(confirmAppCommand.mock.calls[0]?.[0].summary).toContain('Priority: High')
140+
141+
await expect(service.execute('confirmed', 'chat', create)).resolves.toMatchObject({
142+
kind: 'command',
143+
created: { id: 'r1' },
144+
})
145+
const methods = native.request.mock.calls.map(([method]) => method)
146+
expect(methods.filter((method) => method === 'app_command')).toHaveLength(1)
147+
expect(methods).not.toContain('get_app_state')
148+
})
149+
150+
it('refuses an app command when the user denies the app, before asking to confirm', async () => {
151+
const { service, native, approveApp, confirmAppCommand } = setup()
152+
approveApp.mockResolvedValue('deny')
153+
await expect(
154+
service.execute('denied', 'chat', {
155+
action: 'app_command',
156+
command: { name: 'create_reminder', title: 'Pay rent' },
157+
})
158+
).rejects.toThrow('denied')
159+
expect(confirmAppCommand).not.toHaveBeenCalled()
160+
expect(native.request.mock.calls.map(([method]) => method)).not.toContain('app_command')
161+
})
162+
163+
it('lists reminder lists without a write confirmation', async () => {
164+
const { service, native, confirmAppCommand } = setup()
165+
native.request.mockImplementation(async (method: string) =>
166+
method === 'app_command'
167+
? {
168+
kind: 'command',
169+
command: 'list_reminder_lists',
170+
items: [{ id: 'l1', title: 'Sprint 14', allowsModifications: true }],
171+
}
172+
: { kind: 'apps', apps: [] }
173+
)
174+
await expect(
175+
service.execute('lists', 'chat', {
176+
action: 'app_command',
177+
command: { name: 'list_reminder_lists' },
178+
})
179+
).resolves.toMatchObject({ items: [{ title: 'Sprint 14' }] })
180+
expect(confirmAppCommand).not.toHaveBeenCalled()
181+
})
182+
119183
it('binds observed elements to their originating chat', async () => {
120184
const { state, click, native } = setup()
121185
await state('owner')

0 commit comments

Comments
 (0)