Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions apps/desktop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,12 @@ Mothership's `computer` tool is available on macOS 14+ once the user opts in und
group with the **Computer Use** restriction. Older desktop builds omit this optional bridge and
continue to work.

The user grants Accessibility and Screen Recording through macOS, then approves each app for the
current task or persistently. Persistent app approvals are listed in Settings and can be revoked.
Sign-out and deployment changes clear computer-use approval and opt-in. The conversation shows the
The user grants Accessibility and Screen Recording through macOS; every app is then available except
Sim, System Settings, password managers and terminals (shell access has its own Terminal control),
which the helper refuses. With **Ask before using a new
app** on, each app's first use is approved for the task or persistently, and persistent approvals are
listed in Settings and can be revoked. Sign-out and deployment changes clear opt-in, the ask choice
and approvals. The conversation shows the
active app/action and a Stop button; **⌘⇧Esc** also stops active work when the shortcut is available.
Stop cancels queued actions, in-flight authorization, approval prompts and the native helper.
Already completed input cannot be undone.
Expand Down
20 changes: 18 additions & 2 deletions apps/desktop/native/computer-use/ComputerUse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,26 @@ func elementRect(_ element: AXUIElement) -> CGRect? {
AXValueGetValue(unsafeBitCast(rawSize, to: AXValue.self), .cgSize, &size) else { return nil }
return CGRect(origin: position, size: size)
}
/// Apps computer use never operates, lowercased: macOS security settings, password managers, and
/// terminals, whose shell access has its own Terminal control.
let PROTECTED_APPS: Set<String> = [
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
"com.apple.systempreferences", "com.apple.keychainaccess", "com.apple.passwords",
"com.1password.1password", "com.agilebits.onepassword7", "com.agilebits.onepassword-osx", "com.bitwarden.desktop",
"org.keepassxc.keepassxc", "com.lastpass.lastpass", "in.sinew.enpass-desktop", "me.proton.pass.electron",
"com.markmcguill.strongbox", "com.markmcguill.strongbox.mac",
"com.apple.terminal", "com.googlecode.iterm2", "dev.warp.warp-stable", "com.mitchellh.ghostty",
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
"net.kovidgoyal.kitty", "org.alacritty", "com.github.wez.wezterm", "co.zeit.hyper", "org.tabby",
]
/// Whether computer use refuses an app: Sim's own apps and `PROTECTED_APPS`. Bundle identifiers match
/// case-insensitively in Launch Services.
func isProtectedApp(_ bundle: String) -> Bool {
let key = bundle.lowercased()
return key == Bundle.main.bundleIdentifier?.lowercased() || key.hasPrefix("com.simstudio.") || key.hasPrefix("ai.sim.desktop") || PROTECTED_APPS.contains(key)
}
func appFor(_ bundleId: String?, launch: Bool = false) async throws -> NSRunningApplication {
let bundle = try required(bundleId, "bundleId")
guard bundle != Bundle.main.bundleIdentifier, !bundle.hasPrefix("com.simstudio."), !bundle.hasPrefix("ai.sim.desktop"), bundle != "com.apple.systempreferences" else {
throw ComputerError("protected_app", "Computer use cannot control its own app or macOS security settings.")
guard !isProtectedApp(bundle) else {
throw ComputerError("protected_app", "Computer use does not operate Sim, System Settings, password managers, or terminals; use the terminal tool for shell work.")
}
var apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundle).filter { !$0.isTerminated }
if apps.isEmpty && launch {
Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/native/computer-use/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Persistent newline-delimited JSON over stdin/stdout: `{id,method,params}` return

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.

Coordinates in action inputs are window-local points; node frames are global screen points. Coordinate input without a `windowId` targets the window the snapshot selected, and an element target uses its own window; `press_key` with an `elementId` focuses that element first. Window bounds must still match the observed snapshot. App PID and launch time must match. Secure fields and descendants are unavailable as action targets; secure values and labels are suppressed. Sim's own apps and System Settings are protected targets. `get_app_state` can open an installed bundle ID without activating it. `list_apps` discovers installed apps under `/Applications`, `/System/Applications`, and `~/Applications` (bounded to 5000 filesystem entries and depth 3), merging running regular apps; installed apps omit `pid`.
Coordinates in action inputs are window-local points; node frames are global screen points. Coordinate input without a `windowId` targets the window the snapshot selected, and an element target uses its own window; `press_key` with an `elementId` focuses that element first. Window bounds must still match the observed snapshot. App PID and launch time must match. Secure fields and descendants are unavailable as action targets; secure values and labels are suppressed. Sim's own apps, System Settings, password managers and terminals are protected targets (`PROTECTED_APPS`, matched case-insensitively); shell work belongs to the separate Terminal control. `get_app_state` can open an installed bundle ID without activating it. `list_apps` discovers installed apps under `/Applications`, `/System/Applications`, and `~/Applications` (bounded to 5000 filesystem entries and depth 3), merging running regular apps; installed apps omit `pid`.

AXPress and AXSetValue are direct semantic operations. Keyboard events target the app PID. Cmd+A uses the focused editor's writable accessibility selection range where supported. Coordinate mouse input requires the target app in front; `activate_app` makes that focus change explicit and confirms it. Click/drag/scroll validate the foreground process, unchanged window geometry and the app that receives the point; the topmost window-list entry is not the click target because Notification Center and the Dock keep full-screen click-through windows. A hit on a window's own background counts as that window. Background tabs and minimized windows share bounds with the window in front, so they take no coordinate input. An action that opens UI (AXPress, AXPick, AXShowMenu) and times out while the app shows a sheet, modal or menu (`cannotComplete`) counts as dispatched; any other action that times out fails as uncertain. A menu-item press that leaves the item's own menu open with the app highlighting that item (Calendar on macOS 26) is completed with Return. Sheets, including Go to Folder and out-of-process open and save panels whose contents report no window, count as the window they are attached to. Menu item labels carry their shortcuts (for example ⇧⌘N). Some apps ignore background keyboard events. `dispatched:true,verified:false` means only dispatch succeeded; the agent must observe again to establish the outcome. No foreground activation fallback is hidden inside the helper. Native key codes currently assume the US layout for shortcuts; literal text uses Unicode events. Unsupported shortcuts fail explicitly.

Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/native/computer-use/tests/NativeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ import AppKit
expectError("unsupported_key") { _ = try parseKey("F99") }
expectError("invalid_arguments") { _ = try parseKey("Hyper+A") }
expectError("invalid_arguments") { _ = try required(Optional<String>.none, "example") }
for bundle in ["com.apple.systempreferences", "com.apple.Terminal", "COM.GOOGLECODE.ITERM2", "net.kovidgoyal.kitty", "com.1password.1password", "com.apple.Passwords", "com.bitwarden.desktop", "ai.sim.desktop", "com.simstudio.computer-use"] {
precondition(isProtectedApp(bundle), bundle)
}
for bundle in ["com.apple.TextEdit", "com.apple.finder", "com.apple.Safari"] { precondition(!isProtectedApp(bundle), bundle) }
var queue = AXTraversalQueue<String>(limit: 1000)
queue.append(AXTraversalEntry(element: "menu", parent: nil, depth: 0, menu: true, priority: false))
queue.append(AXTraversalEntry(element: "content", parent: nil, depth: 0, menu: false, priority: false))
Expand Down
23 changes: 22 additions & 1 deletion apps/desktop/src/main/computer-use/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})

function setup(enabled = true) {
/** `askForApps` defaults on so the approval tests exercise the prompt; the default device mode asks for nothing. */
function setup(enabled = true, askForApps = true) {
const root = mkdtempSync(join(tmpdir(), 'sim-computer-use-test-'))
roots.push(root)
const config = createConfigStore(join(root, 'settings.json'))
config.set('computerUseEnabled', enabled)
config.set('computerUseAskForApps', askForApps)
let sequence = 0
const request = vi.fn(async (method: string): Promise<ComputerUseResult> => {
if (method === 'status' || method === 'request_permission')
Expand Down Expand Up @@ -412,6 +414,25 @@ describe('native computer use authority and lifecycle', () => {
await expect(click('s1')).rejects.toThrow('stale')
})

it('operates any unprotected app without asking or saving an approval by default', async () => {
const { state, click, service, native, approveApp, onActivity } = setup(true, false)
await state()
await click('s1')
expect(approveApp).not.toHaveBeenCalled()
expect(service.listAppPermissions()).toEqual([])
expect(onActivity).toHaveBeenCalledWith(expect.objectContaining({ appName: 'Fixture' }))
expect(native.request.mock.calls.filter(([method]) => method === 'list_apps')).toHaveLength(1)
})

it('asks for new apps only once the user turns asking on, and clears that choice on reset', async () => {
const { state, service, approveApp } = setup(true, false)
await expect(service.setAskForApps(true)).resolves.toMatchObject({ askForApps: true })
approveApp.mockResolvedValueOnce('deny')
await expect(state()).rejects.toThrow('denied')
service.reset()
expect((await service.getStatus()).askForApps).toBe(false)
})

it('clears grants and opt-in on account reset', async () => {
const { state, service, native } = setup()
await state()
Expand Down
41 changes: 36 additions & 5 deletions apps/desktop/src/main/computer-use/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,19 @@ export class ComputerUseService {
private snapshots = new Map<string, SnapshotOwnership>()
private activity: ComputerUseActivity | null = null
private taskGrants = new Map<string, Map<string, string>>()
/** App names from the helper's app list, so an unprompted action can name its app without listing apps again. */
private appNames = new Map<string, string>()

constructor(private readonly deps: ComputerUseServiceDeps) {}

isEnabled(): boolean {
return this.deps.supported && this.deps.config.get('computerUseEnabled') === true
}

private asksForApps(): boolean {
return this.deps.config.get('computerUseAskForApps') === true
}

getActivity(): ComputerUseActivity | null {
return this.activity
}
Expand All @@ -68,6 +74,7 @@ export class ComputerUseService {
enabled: this.isEnabled(),
permissions: { accessibility: false, screenCapture: false },
activeAction: this.activity,
askForApps: this.asksForApps(),
}
if (!status.enabled) return status
const native = await this.deps.native.request('status', {})
Expand All @@ -94,6 +101,16 @@ export class ComputerUseService {
return this.getStatus()
}

async setAskForApps(ask: boolean): Promise<ComputerUseStatus> {
const previous = this.asksForApps()
this.deps.config.set('computerUseAskForApps', ask)
if (!this.deps.config.flush()) {
this.deps.config.set('computerUseAskForApps', previous)
throw new Error('Could not save Computer Use settings.')
}
return this.getStatus()
}

async requestPermission(
permission: 'accessibility' | 'screenCapture'
): Promise<ComputerUseStatus> {
Expand Down Expand Up @@ -127,7 +144,9 @@ export class ComputerUseService {

reset(): void {
this.cancel()
this.appNames.clear()
this.deps.config.set('computerUseEnabled', false)
this.deps.config.set('computerUseAskForApps', false)
this.deps.config.set('computerUseAllowedApps', [])
if (!this.deps.config.flush())
throw new Error('Could not clear saved Computer Use permissions.')
Expand Down Expand Up @@ -338,16 +357,14 @@ export class ComputerUseService {
})
}

/** Every unprotected app is allowed unless the user chose to approve each app's first use. */
private async authorizeApp(bundleId: string, work: ToolWork): Promise<string> {
const approved = this.listAppPermissions().find((app) => app.bundleId === bundleId)
if (approved) return approved.displayName
const taskName = this.taskGrants.get(work.scopeId)?.get(bundleId)
if (taskName) return taskName
const apps = await this.deps.native.request('list_apps', {})
this.check(work)
const app =
apps.kind === 'apps' ? apps.apps.find((app) => app.bundleId === bundleId) : undefined
const target = { bundleId, displayName: app?.name ?? bundleId }
const target = { bundleId, displayName: await this.appName(bundleId, work) }
if (!this.asksForApps()) return target.displayName
const answer = await this.deps.approveApp(target, work.controller.signal)
this.check(work)
if (answer === 'deny')
Expand All @@ -371,4 +388,18 @@ export class ComputerUseService {
}
return target.displayName
}

private async appName(bundleId: string, work: ToolWork): Promise<string> {
const known = this.appNames.get(bundleId)
if (known) return known
const apps = await this.deps.native.request('list_apps', {})
this.check(work)
if (apps.kind === 'apps') {
this.appNames.clear()
for (const app of apps.apps) this.appNames.set(app.bundleId, app.name)
}
/** An app outside the scanned folders keeps its bundle ID, so it is not rescanned on every action. */
if (!this.appNames.has(bundleId)) this.appNames.set(bundleId, bundleId)
return this.appNames.get(bundleId) ?? bundleId
}
}
2 changes: 2 additions & 0 deletions apps/desktop/src/main/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ export interface DesktopSettings {
preventSleepWhileRunning?: boolean
/** Native app access is opt-in and cleared when the signed-in account changes. */
computerUseEnabled?: boolean
/** Ask before operating an app for the first time; by default every unprotected app is allowed. */
computerUseAskForApps?: boolean
computerUseAllowedApps?: Array<{ bundleId: string; displayName: string }>
/** Device-wide browser page appearance; `app` follows Sim. */
browserTheme?: 'app' | 'light' | 'dark'
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/main/ipc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@ describe('registerIpcHandlers', () => {
computerRoots.push(root)
const config = createConfigStore(join(root, 'settings.json'))
config.set('computerUseEnabled', true)
config.set('computerUseAskForApps', true)
const status: ComputerUseResult = {
kind: 'status',
platform: 'darwin',
Expand Down
12 changes: 12 additions & 0 deletions apps/desktop/src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,18 @@ export function registerIpcHandlers(deps: IpcDeps): void {
return deps.computerUse?.requestPermission(permission)
},
},
'computer-use:set-ask-for-apps': {
kind: 'invoke',
gate: 'app-origin',
requiresAccountData: true,
needsUserActivation: true,
denied: null,
handler: (ask) => {
if (typeof ask !== 'boolean')
throw new Error('A boolean Computer Use preference is required.')
return deps.computerUse?.setAskForApps(ask)
},
},
'computer-use:list-permissions': {
kind: 'invoke',
gate: 'app-origin',
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ const api: SimDesktopApi = {
setEnabled: (enabled: boolean) => ipcRenderer.invoke('computer-use:set-enabled', enabled),
requestPermission: (permission: 'accessibility' | 'screenCapture') =>
ipcRenderer.invoke('computer-use:request-permission', permission),
setAskForApps: (ask: boolean) => ipcRenderer.invoke('computer-use:set-ask-for-apps', ask),
listAppPermissions: () => ipcRenderer.invoke('computer-use:list-permissions'),
revokeApp: (bundleId: string) => ipcRenderer.invoke('computer-use:revoke-app', bundleId),
executeTool: (toolCallId: string, params: ComputerUseInput) =>
Expand Down
Loading
Loading