Skip to content

Commit 2c64716

Browse files
committed
fix(computer-use): reject impossible app-command dates and name the destination in confirmations
- The helper's zoned date-time parser rolled Feb 30, Feb 29 in a common year and hour 24 into other days and accepted offsets like +25:00; zoned values are now checked part by part, while local times keep the strict formatter - Reminders trim their title and notes with the same helpers events use, so the confirmation shows exactly what is saved - The confirmation names the chosen list, calendar or group, read from the helper when it is shown; an id missing from a complete list is refused before the user is asked - Synced the computer-use contract, which now refuses impossible dates at tool validation
1 parent 57fa18e commit 2c64716

5 files changed

Lines changed: 183 additions & 71 deletions

File tree

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

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -88,17 +88,15 @@ func remindersStore() throws -> EKEventStore {
8888
}
8989
/// A due date: `YYYY-MM-DD` is date-only; a date-time is ISO 8601, and one without an offset is this
9090
/// Mac's local time, as typing it into the app would be.
91-
func dueComponents(_ text: String) throws -> DateComponents {
91+
func dueComponents(_ text: String, _ field: String = "Due") throws -> DateComponents {
9292
var calendar = Calendar(identifier: .gregorian)
9393
if text.range(of: #"^\d{4}-\d{2}-\d{2}$"#, options: .regularExpression) != nil {
9494
let parts = text.split(separator: "-").compactMap { Int($0) }
9595
let components = DateComponents(calendar: calendar, year: parts[0], month: parts[1], day: parts[2])
96-
guard components.isValidDate else { throw ComputerError("invalid_arguments", "Due date is not a real date.", dispatchState: "not_started") }
96+
guard components.isValidDate else { throw invalidCommand("\(field) is not a real date.") }
9797
return DateComponents(year: parts[0], month: parts[1], day: parts[2])
9898
}
99-
guard let date = isoDateTime(text) else {
100-
throw ComputerError("invalid_arguments", "Due must be YYYY-MM-DD or an ISO 8601 date-time.", dispatchState: "not_started")
101-
}
99+
guard let date = isoDateTime(text) else { throw invalidCommand("\(field) must be YYYY-MM-DD or a real ISO 8601 date-time.") }
102100
calendar.timeZone = .current
103101
return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .timeZone], from: date)
104102
}
@@ -134,29 +132,42 @@ func localGregorian() -> Calendar {
134132
var calendar = Calendar(identifier: .gregorian); calendar.timeZone = .current
135133
return calendar
136134
}
137-
/// An ISO 8601 date-time; without an offset it is this Mac's local time.
135+
let isoDateTimePattern = try! NSRegularExpression(pattern: #"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(?:(Z)|([+-])(\d{2}):(\d{2}))?$"#)
136+
/// An ISO 8601 date-time; without an offset it is this Mac's local time. Fractions of a second do not
137+
/// matter to a calendar item, so they are dropped. Every field must be in range: `ISO8601DateFormatter`
138+
/// rolls Feb 30 into March and accepts any offset, so a zoned time is checked part by part.
138139
func isoDateTime(_ text: String) -> Date? {
139-
for options: ISO8601DateFormatter.Options in [[.withInternetDateTime], [.withInternetDateTime, .withFractionalSeconds]] {
140-
let zoned = ISO8601DateFormatter(); zoned.formatOptions = options
141-
if let date = zoned.date(from: text) { return date }
140+
guard let match = isoDateTimePattern.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return nil }
141+
func part(_ index: Int) -> String? { Range(match.range(at: index), in: text).map { String(text[$0]) } }
142+
func number(_ index: Int) -> Int? { part(index).flatMap { Int($0) } }
143+
var zone: TimeZone?
144+
if part(7) != nil { zone = TimeZone(secondsFromGMT: 0) }
145+
if let sign = part(8), let hours = number(9), let minutes = number(10) {
146+
guard hours <= 14, minutes < 60 else { return nil }
147+
zone = TimeZone(secondsFromGMT: (sign == "-" ? -1 : 1) * (hours * 3600 + minutes * 60))
148+
}
149+
guard let zone else {
150+
// A local time keeps the formatter, which resolves a repeated hour at a daylight-saving change.
151+
let whole = String(text.prefix(19))
152+
let local = DateFormatter(); local.locale = Locale(identifier: "en_US_POSIX"); local.timeZone = .current
153+
local.dateFormat = whole.count == 16 ? "yyyy-MM-dd'T'HH:mm" : "yyyy-MM-dd'T'HH:mm:ss"
154+
local.isLenient = false
155+
return local.date(from: whole)
142156
}
143-
// Fractions of a second do not matter to a calendar item, so a local time drops them.
144-
guard text.range(of: #"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?$"#, options: .regularExpression) != nil else { return nil }
145-
let whole = String(text.prefix(19))
146-
let local = DateFormatter(); local.locale = Locale(identifier: "en_US_POSIX"); local.timeZone = .current
147-
local.dateFormat = whole.count == 16 ? "yyyy-MM-dd'T'HH:mm" : "yyyy-MM-dd'T'HH:mm:ss"
148-
local.isLenient = false
149-
return local.date(from: whole)
157+
var calendar = Calendar(identifier: .gregorian); calendar.timeZone = zone
158+
let components = DateComponents(year: number(1), month: number(2), day: number(3), hour: number(4), minute: number(5), second: number(6) ?? 0)
159+
guard components.isValidDate(in: calendar) else { return nil }
160+
return calendar.date(from: components)
150161
}
151162
/// An event boundary: an ISO 8601 date-time (local without an offset), or `YYYY-MM-DD` for all-day events.
152163
func eventDate(_ text: String?, _ field: String, allDay: Bool) throws -> Date {
153164
let text = try commandText(text, field, max: 64)
154165
if allDay {
155-
let parts = try dueComponents(text)
166+
let parts = try dueComponents(text, field)
156167
guard parts.hour == nil, let date = localGregorian().date(from: parts) else { throw invalidCommand("All-day \(field) must be YYYY-MM-DD.") }
157168
return date
158169
}
159-
guard let date = isoDateTime(text) else { throw invalidCommand("\(field) must be an ISO 8601 date-time.") }
170+
guard let date = isoDateTime(text) else { throw invalidCommand("\(field) must be a real ISO 8601 date-time.") }
160171
return date
161172
}
162173
func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
@@ -168,11 +179,10 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
168179
}
169180
return ["kind": "command", "command": command.name, "items": lists, "truncated": allLists.count > 200]
170181
case "create_reminder":
171-
let title = (command.title ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
172-
guard !title.isEmpty, title.count <= 1024 else { throw ComputerError("invalid_arguments", "A reminder needs a title of at most 1024 characters.", dispatchState: "not_started") }
173-
guard (command.notes?.count ?? 0) <= 8000 else { throw ComputerError("invalid_arguments", "Notes are limited to 8000 characters.", dispatchState: "not_started") }
174-
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") }
175-
let due = try command.due.map(dueComponents)
182+
let title = try commandText(command.title, "Title")
183+
let notes = try optionalText(command.notes, "Notes", max: 8000)
184+
guard [0, 1, 5, 9].contains(command.priority ?? 0) else { throw invalidCommand("Priority must be 0 (none), 1 (high), 5 (medium) or 9 (low).") }
185+
let due = try command.due.map { try dueComponents($0) }
176186
let store = try remindersStore()
177187
let list: EKCalendar
178188
if let listId = command.listId {
@@ -186,7 +196,7 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
186196
}
187197
guard list.allowsContentModifications else { throw ComputerError("list_read_only", "This reminder list is read-only.", dispatchState: "not_started") }
188198
let reminder = EKReminder(eventStore: store)
189-
reminder.calendar = list; reminder.title = title; reminder.notes = command.notes
199+
reminder.calendar = list; reminder.title = title; reminder.notes = notes
190200
reminder.priority = command.priority ?? 0; reminder.dueDateComponents = due
191201
try checkCancellation()
192202
inputDispatched = true

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,11 @@ import AppKit
4242
precondition(timed.hour != nil && timed.minute != nil && timed.second == 45)
4343
let localDue = try dueComponents("2027-05-04T09:30")
4444
precondition(localDue.hour == 9 && localDue.minute == 30)
45-
for due in ["2027-02-30", "2027-05-04T25:30:00", "May 4", "2027-5-4"] {
45+
for due in ["2027-02-30", "2027-05-04T25:30:00", "May 4", "2027-5-4", "2027-02-30T09:00:00Z", "2027-02-29T09:00:00.5+01:00", "2027-05-04T24:00:00Z", "2027-05-04T09:00:00+25:00", "2027-05-04T09:00:00+05:99"] {
4646
expectError("invalid_arguments") { _ = try dueComponents(due) }
4747
}
48+
precondition(isoDateTime("2028-02-29T09:00Z") == Date(timeIntervalSince1970: 1_835_427_600))
49+
precondition(isoDateTime("2027-05-04T09:00:00+05:30") == Date(timeIntervalSince1970: 1_809_401_400))
4850
expectError("unknown_command") { _ = try runAppCommand(AppCommand(name: "run_script")) }
4951
expectError("invalid_arguments") { _ = try runAppCommand(AppCommand(name: "create_reminder", title: " ")) }
5052
expectError("invalid_arguments") { _ = try runAppCommand(AppCommand(name: "create_reminder", title: "Pay rent", priority: 3)) }

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

Lines changed: 82 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -20,38 +20,40 @@ function setup(enabled = true, askForApps = true) {
2020
config.set('computerUseEnabled', enabled)
2121
config.set('computerUseAskForApps', askForApps)
2222
let sequence = 0
23-
const request = vi.fn(async (method: string): Promise<ComputerUseResult> => {
24-
if (method === 'status' || method === 'request_permission')
25-
return { kind: 'status', platform: 'darwin', accessibility: true, screenRecording: false }
26-
if (method === 'list_apps')
23+
const request = vi.fn(
24+
async (method: string, _params?: Record<string, unknown>): Promise<ComputerUseResult> => {
25+
if (method === 'status' || method === 'request_permission')
26+
return { kind: 'status', platform: 'darwin', accessibility: true, screenRecording: false }
27+
if (method === 'list_apps')
28+
return {
29+
kind: 'apps',
30+
apps: [{ bundleId: 'com.example.Fixture', name: 'Fixture', pid: 42, isActive: false }],
31+
}
32+
if (method === 'app_command')
33+
return {
34+
kind: 'command',
35+
command: 'create_reminder',
36+
created: { id: 'r1', title: 'Pay rent', list: 'Reminders' },
37+
}
38+
if (method === 'get_app_state')
39+
return {
40+
kind: 'state',
41+
bundleId: 'com.example.Fixture',
42+
snapshotId: `s${++sequence}`,
43+
windowId: '1',
44+
windows: [],
45+
nodes: [{ elementId: 'e1', role: 'AXTextArea', actions: [], windowId: '1' }],
46+
truncated: false,
47+
}
2748
return {
28-
kind: 'apps',
29-
apps: [{ bundleId: 'com.example.Fixture', name: 'Fixture', pid: 42, isActive: false }],
30-
}
31-
if (method === 'app_command')
32-
return {
33-
kind: 'command',
34-
command: 'create_reminder',
35-
created: { id: 'r1', title: 'Pay rent', list: 'Reminders' },
36-
}
37-
if (method === 'get_app_state')
38-
return {
39-
kind: 'state',
49+
kind: 'action',
50+
action: 'click',
4051
bundleId: 'com.example.Fixture',
41-
snapshotId: `s${++sequence}`,
42-
windowId: '1',
43-
windows: [],
44-
nodes: [{ elementId: 'e1', role: 'AXTextArea', actions: [], windowId: '1' }],
45-
truncated: false,
52+
dispatched: true,
53+
verified: false,
4654
}
47-
return {
48-
kind: 'action',
49-
action: 'click',
50-
bundleId: 'com.example.Fixture',
51-
dispatched: true,
52-
verified: false,
5355
}
54-
})
56+
)
5557
const native = { request, stop: vi.fn() }
5658
const approveApp = vi.fn(async (): Promise<'always' | 'deny' | 'once'> => 'always')
5759
const confirmAppCommand = vi.fn(async (_request: { appName: string; summary: string }) => true)
@@ -177,6 +179,58 @@ describe('native computer use authority and lifecycle', () => {
177179
)
178180
})
179181

182+
it('names the chosen list, calendar or group in the confirmation, not its id', async () => {
183+
const { service, native, confirmAppCommand } = setup()
184+
const lists = {
185+
list_reminder_lists: 'Sprint 14',
186+
list_calendars: 'Travel',
187+
list_contact_groups: 'Hires Q1 2027',
188+
}
189+
let truncated = false
190+
native.request.mockImplementation(async (method, params): Promise<ComputerUseResult> => {
191+
if (method !== 'app_command') return { kind: 'apps', apps: [] }
192+
const { name } = params?.command as { name: keyof typeof lists }
193+
return {
194+
kind: 'command',
195+
command: name,
196+
items: [{ id: 'id-1', title: lists[name], allowsModifications: true }],
197+
truncated,
198+
}
199+
})
200+
confirmAppCommand.mockResolvedValue(false)
201+
for (const command of [
202+
{ name: 'create_reminder', title: 'Pay rent', listId: 'id-1' },
203+
{
204+
name: 'create_event',
205+
title: 'Flight',
206+
start: '2027-06-09T07:15',
207+
end: '2027-06-09T08:10',
208+
calendarId: 'id-1',
209+
},
210+
{ name: 'create_contact', givenName: 'Ana', groupId: 'id-1' },
211+
])
212+
await expect(
213+
service.execute(`named-${command.name}`, 'chat', { action: 'app_command', command })
214+
).rejects.toMatchObject({ details: { code: 'user_declined' } })
215+
expect(
216+
confirmAppCommand.mock.calls.map(([request]) => request.summary.split('\n').at(-1))
217+
).toEqual(['List: Sprint 14', 'Calendar: Travel', 'Group: Hires Q1 2027'])
218+
219+
const deleted = {
220+
action: 'app_command',
221+
command: { name: 'create_reminder', title: 'Pay rent', listId: 'deleted-list' },
222+
}
223+
await expect(service.execute('deleted', 'chat', deleted)).rejects.toMatchObject({
224+
details: { code: 'list_unavailable', dispatchState: 'not_started' },
225+
})
226+
expect(confirmAppCommand).toHaveBeenCalledTimes(3)
227+
truncated = true
228+
await expect(service.execute('past-limit', 'chat', deleted)).rejects.toMatchObject({
229+
details: { code: 'user_declined' },
230+
})
231+
expect(confirmAppCommand.mock.lastCall?.[0].summary).toContain('List: deleted-list')
232+
})
233+
180234
it('refuses an app command when the user denies the app, before asking to confirm', async () => {
181235
const { service, native, approveApp, confirmAppCommand } = setup()
182236
approveApp.mockResolvedValue('deny')

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

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,24 @@ function workBundleId(input: ComputerUseWithAppCommandsInput): string | undefine
6868
return 'bundleId' in input ? input.bundleId : undefined
6969
}
7070

71-
/** The exact fields a write will save, for the user to confirm; null for a read, which needs none. */
72-
function writeSummary(command: AppCommand): string | null {
71+
/** The list, calendar or group a write names by id, and the read that lists its kind. */
72+
function chosenDestination(
73+
command: AppCommand
74+
): { id: string; list: 'list_reminder_lists' | 'list_calendars' | 'list_contact_groups' } | null {
75+
if (command.name === 'create_reminder' && command.listId)
76+
return { id: command.listId, list: 'list_reminder_lists' }
77+
if (command.name === 'create_event' && command.calendarId)
78+
return { id: command.calendarId, list: 'list_calendars' }
79+
if (command.name === 'create_contact' && command.groupId)
80+
return { id: command.groupId, list: 'list_contact_groups' }
81+
return null
82+
}
83+
84+
/**
85+
* The exact fields a write will save, for the user to confirm; null for a read, which needs none.
86+
* `destination` is the chosen list, calendar or group by name, so the user can tell where it goes.
87+
*/
88+
function writeSummary(command: AppCommand, destination: string | undefined): string | null {
7389
// Trimmed exactly as the helper trims before saving, so the user confirms the saved values.
7490
const lines = (entries: Array<[string, string | number | undefined]>) =>
7591
entries
@@ -83,7 +99,7 @@ function writeSummary(command: AppCommand): string | null {
8399
['Reminder', command.title],
84100
['Due', command.due],
85101
['Priority', command.priority ? PRIORITY_NAMES[command.priority] : undefined],
86-
['List', command.listId ?? 'default'],
102+
['List', destination ?? 'default'],
87103
['Notes', command.notes],
88104
])
89105
case 'create_event':
@@ -99,7 +115,7 @@ function writeSummary(command: AppCommand): string | null {
99115
? `${command.alertMinutesBefore} minutes before`
100116
: undefined,
101117
],
102-
['Calendar', command.calendarId ?? 'default'],
118+
['Calendar', destination ?? 'default'],
103119
['Notes', command.notes],
104120
])
105121
case 'create_contact_group':
@@ -111,7 +127,7 @@ function writeSummary(command: AppCommand): string | null {
111127
['Job title', command.jobTitle],
112128
['Emails', command.emails?.map((email) => email.trim()).join(', ')],
113129
['Phones', command.phones?.map((phone) => phone.trim()).join(', ')],
114-
['Group', command.groupId],
130+
['Group', destination],
115131
])
116132
default:
117133
return null
@@ -437,7 +453,7 @@ export class ComputerUseService {
437453
this.activity = { ...this.activity, appName }
438454
this.deps.onActivity(this.activity)
439455
}
440-
const summary = writeSummary(command)
456+
const summary = writeSummary(command, await this.destinationName(command, work))
441457
if (summary !== null) {
442458
const confirmed = await this.deps.confirmAppCommand(
443459
{ appName, summary },
@@ -452,12 +468,39 @@ export class ComputerUseService {
452468
})
453469
}
454470
this.check(work)
471+
return await this.appCommand(command)
472+
}
473+
474+
/** Runs one app command in the helper and checks the reply is for that command. */
475+
private async appCommand(
476+
command: AppCommand
477+
): Promise<Extract<ComputerUseResult, { kind: 'command' }>> {
455478
const result = await this.deps.native.request('app_command', { command })
456479
if (result.kind !== 'command' || result.command !== command.name)
457480
throw new Error('Computer Use returned a result for a different command.')
458481
return result
459482
}
460483

484+
/**
485+
* The name of the list, calendar or group a write chose by id, read when it is confirmed so the
486+
* name is current. An id missing from a complete read is refused before the user is asked; past
487+
* the read's limit the id itself is shown, and the helper checks it before saving.
488+
*/
489+
private async destinationName(command: AppCommand, work: ToolWork): Promise<string | undefined> {
490+
const destination = chosenDestination(command)
491+
if (!destination) return undefined
492+
const lists = await this.appCommand({ name: destination.list })
493+
this.check(work)
494+
const chosen = lists.items?.find((item) => item.id === destination.id)
495+
if (chosen) return chosen.title
496+
if (lists.truncated) return destination.id
497+
throw new ComputerUseError({
498+
code: 'list_unavailable',
499+
message: `No list, calendar or group has this id; call ${destination.list}.`,
500+
dispatchState: 'not_started',
501+
})
502+
}
503+
461504
private rememberSnapshot(work: ToolWork, snapshot: ComputerUseSnapshot, windowId?: string): void {
462505
if (!('bundleId' in work.input) || snapshot.bundleId !== work.input.bundleId)
463506
throw new Error('Computer Use returned state for a different app.')

0 commit comments

Comments
 (0)