Skip to content

Commit 484f75f

Browse files
committed
fix(computer-use): claim app commands, confirm full values, and keep contacts in their group's account
1 parent 0781720 commit 484f75f

7 files changed

Lines changed: 86 additions & 32 deletions

File tree

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

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,11 @@ func contactStore() throws -> CNContactStore {
129129
}
130130
return CNContactStore()
131131
}
132+
/// The Gregorian calendar in this Mac's time zone, so `YYYY-MM-DD` means the same day whatever calendar the user prefers.
133+
func localGregorian() -> Calendar {
134+
var calendar = Calendar(identifier: .gregorian); calendar.timeZone = .current
135+
return calendar
136+
}
132137
/// An ISO 8601 date-time; without an offset it is this Mac's local time.
133138
func isoDateTime(_ text: String) -> Date? {
134139
let zoned = ISO8601DateFormatter(); zoned.formatOptions = [.withInternetDateTime]
@@ -144,7 +149,7 @@ func eventDate(_ text: String?, _ field: String, allDay: Bool) throws -> Date {
144149
let text = try commandText(text, field, max: 64)
145150
if allDay {
146151
let parts = try dueComponents(text)
147-
guard parts.hour == nil, let date = Calendar.current.date(from: parts) else { throw invalidCommand("All-day \(field) must be YYYY-MM-DD.") }
152+
guard parts.hour == nil, let date = localGregorian().date(from: parts) else { throw invalidCommand("All-day \(field) must be YYYY-MM-DD.") }
148153
return date
149154
}
150155
guard let date = isoDateTime(text) else { throw invalidCommand("\(field) must be an ISO 8601 date-time.") }
@@ -178,6 +183,7 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
178183
let reminder = EKReminder(eventStore: store)
179184
reminder.calendar = list; reminder.title = title; reminder.notes = command.notes
180185
reminder.priority = command.priority ?? 0; reminder.dueDateComponents = due
186+
try checkCancellation()
181187
inputDispatched = true
182188
try store.save(reminder, commit: true)
183189
return ["kind": "command", "command": command.name, "created": ["id": reminder.calendarItemIdentifier, "title": title, "list": list.title]]
@@ -192,7 +198,10 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
192198
let start = try eventDate(command.start, "Start", allDay: allDay)
193199
let end = try eventDate(command.end, "End", allDay: allDay)
194200
guard allDay ? end >= start : end > start else { throw invalidCommand("End must be after start.") }
195-
guard end.timeIntervalSince(start) <= 31 * 86_400 else { throw invalidCommand("An event can last at most 31 days.") }
201+
// Calendar days, so a daylight-saving change inside the event does not shorten the limit.
202+
guard let limit = localGregorian().date(byAdding: .day, value: 31, to: start), end <= limit else {
203+
throw invalidCommand("An event can last at most 31 days.")
204+
}
196205
let location = try optionalText(command.location, "Location")
197206
let notes = try optionalText(command.notes, "Notes", max: 8000)
198207
if let minutes = command.alertMinutesBefore, !(0...40_320).contains(minutes) { throw invalidCommand("alertMinutesBefore must be 0 to 40320.") }
@@ -212,6 +221,7 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
212221
event.calendar = calendar; event.title = title; event.isAllDay = allDay
213222
event.startDate = start; event.endDate = end; event.location = location; event.notes = notes
214223
if let minutes = command.alertMinutesBefore { event.addAlarm(EKAlarm(relativeOffset: TimeInterval(-minutes * 60))) }
224+
try checkCancellation()
215225
inputDispatched = true
216226
try store.save(event, span: .thisEvent, commit: true)
217227
return ["kind": "command", "command": command.name, "created": ["id": event.eventIdentifier ?? event.calendarItemIdentifier, "title": title, "list": calendar.title]]
@@ -229,6 +239,7 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
229239
}
230240
let group = CNMutableGroup(); group.name = name
231241
let request = CNSaveRequest(); request.add(group, toContainerWithIdentifier: nil)
242+
try checkCancellation()
232243
inputDispatched = true
233244
try store.execute(request)
234245
return ["kind": "command", "command": command.name, "created": ["id": group.identifier, "title": name, "list": "Contacts"]]
@@ -253,8 +264,11 @@ func runAppCommand(_ command: AppCommand) throws -> [String: Any] {
253264
contact.organizationName = organization ?? ""; contact.jobTitle = jobTitle ?? ""
254265
contact.emailAddresses = emails.map { CNLabeledValue(label: CNLabelWork, value: $0 as NSString) }
255266
contact.phoneNumbers = phones.map { CNLabeledValue(label: CNLabelPhoneNumberMain, value: CNPhoneNumber(stringValue: $0)) }
256-
let request = CNSaveRequest(); request.add(contact, toContainerWithIdentifier: nil)
267+
// A group's members must live in the group's own account, so the contact is saved there.
268+
let container = try group.flatMap { try store.containers(matching: CNContainer.predicateForContainerOfGroup(withIdentifier: $0.identifier)).first?.identifier }
269+
let request = CNSaveRequest(); request.add(contact, toContainerWithIdentifier: container)
257270
if let group { request.addMember(contact, to: group) }
271+
try checkCancellation()
258272
inputDispatched = true
259273
try store.execute(request)
260274
let display = [given, family].compactMap { $0 }.joined(separator: " ")

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,23 @@ describe('native computer use authority and lifecycle', () => {
575575
await expect(click('s1')).rejects.toThrow('stale')
576576
})
577577

578+
it('revoking an app stops its app command while the write waits for confirmation', async () => {
579+
const { service, native, confirmAppCommand } = setup()
580+
let confirm: (answer: boolean) => void = () => {}
581+
confirmAppCommand.mockImplementation(
582+
() => new Promise<boolean>((resolve) => (confirm = resolve))
583+
)
584+
const pending = service.execute('revoked', 'chat', {
585+
action: 'app_command',
586+
command: { name: 'create_reminder', title: 'Pay rent' },
587+
})
588+
await vi.waitFor(() => expect(confirmAppCommand).toHaveBeenCalledOnce())
589+
service.revokeApp('com.apple.reminders')
590+
confirm(true)
591+
await expect(pending).rejects.toThrow('stopped')
592+
expect(native.request.mock.calls.map(([method]) => method)).not.toContain('app_command')
593+
})
594+
578595
it('blocks self-automation before showing an approval', async () => {
579596
const { service, approveApp, native } = setup()
580597
await expect(

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,12 +62,18 @@ const APP_COMMAND_APPS: Record<AppCommand['name'], string> = {
6262

6363
const PRIORITY_NAMES: Record<number, string> = { 1: 'High', 5: 'Medium', 9: 'Low' }
6464

65+
/** The app a call operates; an app command operates the app its data belongs to. */
66+
function workBundleId(input: ComputerUseWithAppCommandsInput): string | undefined {
67+
if (input.action === 'app_command') return APP_COMMAND_APPS[input.command.name]
68+
return 'bundleId' in input ? input.bundleId : undefined
69+
}
70+
6571
/** The exact fields a write will save, for the user to confirm; null for a read, which needs none. */
6672
function writeSummary(command: AppCommand): string | null {
6773
const lines = (entries: Array<[string, string | number | undefined]>) =>
6874
entries
6975
.filter(([, value]) => value !== undefined && value !== '')
70-
.map(([label, value]) => `${label}: ${String(value).slice(0, 500)}`)
76+
.map(([label, value]) => `${label}: ${value}`)
7177
.join('\n')
7278
switch (command.name) {
7379
case 'create_reminder':
@@ -200,7 +206,7 @@ export class ComputerUseService {
200206
)
201207
const persisted = this.deps.config.flush()
202208
for (const work of this.queued.values()) {
203-
if ('bundleId' in work.input && work.input.bundleId === bundleId) this.cancel(work.toolCallId)
209+
if (workBundleId(work.input) === bundleId) this.cancel(work.toolCallId)
204210
}
205211
for (const apps of this.taskGrants.values()) apps.delete(bundleId)
206212
this.invalidateSnapshots()

‎apps/sim/components/computer-use/activity.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ const ACTION_LABELS: Record<string, string> = {
1818
set_value: 'Editing',
1919
perform_action: 'Interacting',
2020
batch: 'Running steps',
21-
app_command: 'Adding an item',
21+
app_command: 'Working with app data',
2222
}
2323

2424
/** Remains visible while a native action is active, even if the permission group or device access revokes it. */

‎apps/sim/lib/computer-use/repository.integration.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,12 @@ describe.skipIf(!connection)('computer use one-shot admission in PostgreSQL', ()
114114
await requireConnection()`UPDATE copilot_chats SET user_id = 'user-2'`
115115
expect(await claimComputerUseTool(input)).toBeNull()
116116
})
117+
it('admits a typed app command with its canonical arguments', async () => {
118+
await requireConnection()`UPDATE copilot_async_tool_calls SET args = '{"action":"app_command","command":{"name":"create_reminder","title":"Pay rent"},"activity":{"title":"Adding a reminder"}}'`
119+
expect(await claimComputerUseTool(input)).toEqual({
120+
args: { action: 'app_command', command: { name: 'create_reminder', title: 'Pay rent' } },
121+
})
122+
})
117123
it('rejects malformed canonical targets before consuming a claim', async () => {
118124
await requireConnection()`UPDATE copilot_async_tool_calls SET args = '{"action":"click","bundleId":"com.apple.Notes"}'`
119125
expect(await claimComputerUseTool(input)).toBeNull()

‎apps/sim/lib/computer-use/repository.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { db } from '@sim/db'
22
import { copilotAsyncToolCalls, copilotChats, copilotRuns } from '@sim/db/schema'
3-
import { ComputerUseSchema } from '@sim/desktop-bridge/computer-use'
3+
import { ComputerUseWithAppCommandsSchema } from '@sim/desktop-bridge/computer-use'
44
import { omit, toRecord } from '@sim/utils/object'
55
import { and, eq, isNull, notInArray, sql } from 'drizzle-orm'
66
import { executableToolPermission } from '@/lib/mothership/async-runs/executable-tool-permission'
@@ -41,7 +41,8 @@ export async function claimComputerUseTool(input: ComputerUseClaim) {
4141
.limit(1)
4242
if (
4343
!pending ||
44-
!ComputerUseSchema.safeParse(omit(toRecord(pending.args), ['activity'])).success
44+
!ComputerUseWithAppCommandsSchema.safeParse(omit(toRecord(pending.args), ['activity']))
45+
.success
4546
)
4647
return null
4748
const now = new Date()
@@ -62,7 +63,7 @@ export async function claimComputerUseTool(input: ComputerUseClaim) {
6263
)
6364
.returning({ args: copilotAsyncToolCalls.args })
6465
return claimed
65-
? { args: ComputerUseSchema.parse(omit(toRecord(claimed.args), ['activity'])) }
66+
? { args: ComputerUseWithAppCommandsSchema.parse(omit(toRecord(claimed.args), ['activity'])) }
6667
: null
6768
})
6869
}

‎packages/desktop-bridge/src/computer-use.generated.ts‎

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -390,31 +390,41 @@ export const ComputerUseSnapshotSchema = z.strictObject({
390390
});
391391
export type ComputerUseSnapshot = z.infer<typeof ComputerUseSnapshotSchema>;
392392

393-
export const ComputerUseCommandResultSchema = z.strictObject({
394-
kind: z.literal("command"),
395-
command: z.enum([
396-
"list_reminder_lists",
397-
"create_reminder",
398-
"list_calendars",
399-
"create_event",
400-
"list_contact_groups",
401-
"create_contact_group",
402-
"create_contact",
403-
]),
404-
created: z
405-
.strictObject({ id: z.string().min(1).max(256), title: z.string().max(1024), list: z.string().max(1024) })
406-
.optional(),
407-
items: z
408-
.array(
409-
z.strictObject({
393+
const CommandItem = z.strictObject({
394+
id: z.string().min(1).max(256),
395+
title: z.string().max(1024),
396+
allowsModifications: z.boolean(),
397+
});
398+
399+
/** A create must return the id it committed, so a lost reply is never retried as a second create. */
400+
export const ComputerUseCommandResultSchema = z
401+
.strictObject({
402+
kind: z.literal("command"),
403+
command: z.enum([
404+
"list_reminder_lists",
405+
"create_reminder",
406+
"list_calendars",
407+
"create_event",
408+
"list_contact_groups",
409+
"create_contact_group",
410+
"create_contact",
411+
]),
412+
created: z
413+
.strictObject({
410414
id: z.string().min(1).max(256),
411415
title: z.string().max(1024),
412-
allowsModifications: z.boolean(),
413-
}),
414-
)
415-
.max(200)
416-
.optional(),
417-
});
416+
list: z.string().max(1024),
417+
})
418+
.optional(),
419+
items: z.array(CommandItem).max(200).optional(),
420+
})
421+
.refine(
422+
(result) =>
423+
result.command.startsWith("create_") ? result.created !== undefined : result.items !== undefined,
424+
{
425+
message: "A create returns created; a list returns items",
426+
},
427+
);
418428

419429
export const ComputerUseResultSchema = z.discriminatedUnion("kind", [
420430
ComputerUseStatusSchema,

0 commit comments

Comments
 (0)