From 0a63df9c50f099976c9fb317eccb4d98514b24cd Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:02:42 +0900 Subject: [PATCH 1/3] feat(desktop): drive macOS apps via Codex Computer Use inside code mode Adds a guest namespace desktop.* (list_apps, get_app_state, click, set_value, type_text, press_key, scroll, drag, select_text, perform_secondary_action, run, status) backed by the signed codex-computer-use-mcp broker. - One broker session per server process so element indexes survive across execute_code calls; the CLI closes it on exit. - Screenshots are metadata unless requested; desktop.run batches steps and stops at the first failure or missing expect text. - Off by default (config.desktop.enabled). Optional disclaimLauncher works around macOS making the host app the responsible process. - Contract doc structure/desktop-surface.md, catalog and coverage rows, tests. --- README.ko.md | 4 +- README.md | 4 +- src/cli.js | 3 +- src/config.js | 9 ++ src/execution-worker.js | 2 +- src/guest-guidance.js | 1 + src/host/actions.js | 2 + src/host/desktop/desktop-actions.js | 20 ++++ src/host/desktop/desktop.js | 139 ++++++++++++++++++++++++++++ src/host/globals.js | 26 ++++++ src/sandbox.js | 4 +- src/tools.js | 2 +- structure/INDEX.md | 2 + structure/desktop-surface.md | 56 +++++++++++ structure/manifest.json | 9 ++ test/completeness-invariant.test.js | 12 +++ test/desktop.test.js | 105 +++++++++++++++++++++ 17 files changed, 391 insertions(+), 9 deletions(-) create mode 100644 src/host/desktop/desktop-actions.js create mode 100644 src/host/desktop/desktop.js create mode 100644 structure/desktop-surface.md create mode 100644 test/desktop.test.js diff --git a/README.ko.md b/README.ko.md index a48e31b..cc547ed 100644 --- a/README.ko.md +++ b/README.ko.md @@ -188,7 +188,7 @@ Aside는 2.0초에 그 서버를 껐고 복원은 3.6초에 다시 켰습니다. CLI는 Aside의 도구 목록 캐시를 손으로 쓰지 않습니다. 그렇게 만든 캐시는 도구 정의가 바뀌는 순간 조용히 낡습니다. -이제 에이전트는 `mcp__aside-codemode__execute_code`를 바로 호출합니다. **2,034바이트**짜리 도구 +이제 에이전트는 `mcp__aside-codemode__execute_code`를 바로 호출합니다. **2,043바이트**짜리 도구 설명은 모든 MCP 세션의 문맥에 항상 들어갑니다. CLI의 3,808바이트짜리 계정 블록보다 상주 문맥이 작다는 점도 MCP를 주 경로로 삼은 이유입니다. @@ -411,7 +411,7 @@ TODO, all, every, each, across, repository, project라는 말은 검색 결과 `search.content`, `search.files`, `search.count` 가운데 하나를 한 번 부르고, 같은 코드 본문에서 결과를 거른 뒤 적중한 파일만 읽습니다. -**상주 문맥 비용, 실측값.** MCP 경로는 **2,034바이트**짜리 도구 설명을 모든 MCP 세션에 계속 둡니다. +**상주 문맥 비용, 실측값.** MCP 경로는 **2,043바이트**짜리 도구 설명을 모든 MCP 세션에 계속 둡니다. CLI 경로는 **3,808바이트**짜리 계정 `AGENTS.md` 블록을 계속 두고, **8,973바이트**짜리 사용자 스킬은 필요할 때만 읽습니다. 상주 문맥이 더 작은 MCP가 주 경로에 유리합니다. MCP를 붙이지 못하거나 bash 카드를 선호할 때는 지원되는 CLI 경로를 씁니다. 이 비용은 작업을 묶어 줄인 왕복 횟수와 별개입니다. diff --git a/README.md b/README.md index 3da618e..adf82c5 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ entry still points at an older installation. Anything but `activated` comes with step. The CLI never writes Aside's inventory cache by hand; doing so would go stale when the tool definition changes. -The agent then calls `mcp__aside-codemode__execute_code` directly. Its **2,034-byte** tool +The agent then calls `mcp__aside-codemode__execute_code` directly. Its **2,043-byte** tool description is always resident in every MCP session. That is less resident context than the CLI route's 3,808-byte account block, one reason MCP is the first-class route. @@ -437,7 +437,7 @@ Do not replace code mode with a native `read_file` loop, a bash `find`/`grep` pi repeated grep calls. Make one `search.content`, `search.files` or `search.count` call, filter the result, and read only the hits in the same body. -**Resident context cost, measured.** The MCP route keeps its **2,034-byte** tool description +**Resident context cost, measured.** The MCP route keeps its **2,043-byte** tool description resident in every MCP session. The CLI route keeps the **3,808-byte** account `AGENTS.md` block resident and loads the **8,973-byte** user skill only on demand. The smaller always-resident footprint favours MCP as the first-class route. The CLI route remains supported where MCP does diff --git a/src/cli.js b/src/cli.js index 1ba2a8e..f1f4292 100644 --- a/src/cli.js +++ b/src/cli.js @@ -19,7 +19,7 @@ import { loadConfig } from './config.js'; import { makeRootGuard } from './paths.js'; import { resolveCwd } from './host/cwd.js'; import { createDetailedRgResolver, getAsideBundledRgPath } from './rg.js'; -import { createHostGlobals } from './host/globals.js'; +import { createHostGlobals, closeSharedDesktop } from './host/globals.js'; import { runCode } from './sandbox.js'; import { requireInteger, fitEnvelope } from './execution-output.js'; import { resolveBrowserContext, parseCliArgv, parseExecutionArgv, validateAccount, validateHost, routingReport } from './browser-context.js'; @@ -471,6 +471,7 @@ try { timeoutMs = Math.min(requested, config.maxTimeoutMs); } catch (e) { fail(e.message); } const out = await runCode(code, { timeoutMs, globals, maxResultBytes: config.maxResultBytes }); +await closeSharedDesktop().catch(() => {}); if (browserContext) { out.browserContext = routingReport(browserContext); } diff --git a/src/config.js b/src/config.js index 63c7125..1030782 100644 --- a/src/config.js +++ b/src/config.js @@ -37,6 +37,8 @@ const DEFAULTS = { // ~30s internal screenshot timeout; the host deadline is derived as inner + slack. browseCaps: { enabled: true, timeoutMs: 25000, maxTabs: 8, concurrency: 4 }, browseContext: null, + // Off by default: driving native macOS apps is a bigger blast radius than reading files. + desktop: { enabled: false, packageDir: null, disclaimLauncher: null, idleMs: 120000 }, excludeGlobs: DEFAULT_EXCLUDES, }; @@ -131,6 +133,13 @@ export function loadConfig(argv = process.argv.slice(2), env = process.env) { if ('maxTabs' in obj.browseCaps) cfg.browseCaps.maxTabs = requireInteger('browseCaps.maxTabs', obj.browseCaps.maxTabs); if ('concurrency' in obj.browseCaps) cfg.browseCaps.concurrency = requireInteger('browseCaps.concurrency', obj.browseCaps.concurrency); } + if (obj.desktop && typeof obj.desktop === 'object') { + cfg.desktop = { ...(cfg.desktop || {}) }; + if ('enabled' in obj.desktop) cfg.desktop.enabled = obj.desktop.enabled === true; + if ('packageDir' in obj.desktop) cfg.desktop.packageDir = obj.desktop.packageDir === null ? null : String(obj.desktop.packageDir); + if ('disclaimLauncher' in obj.desktop) cfg.desktop.disclaimLauncher = obj.desktop.disclaimLauncher === null ? null : String(obj.desktop.disclaimLauncher); + if ('idleMs' in obj.desktop) cfg.desktop.idleMs = requireInteger('desktop.idleMs', obj.desktop.idleMs); + } if (obj.browseContext && typeof obj.browseContext === 'object') { if (!cfg.browseContext) cfg.browseContext = {}; if ('account' in obj.browseContext) { diff --git a/src/execution-worker.js b/src/execution-worker.js index 0158a47..bff5e82 100644 --- a/src/execution-worker.js +++ b/src/execution-worker.js @@ -50,7 +50,7 @@ function syncRpc(name, args) { if (message.error) throw Object.assign(new Error(message.error.error), message.error); return message.value; } -const injected = { search: {}, fs: {}, actions: {}, browse: {}, report: {}, api: {}, recipes: {} }; +const injected = { search: {}, fs: {}, actions: {}, browse: {}, report: {}, api: {}, desktop: {}, recipes: {} }; for (const name of manifest) { const [root, method] = name.split('.'); if (method) injected[root][method] = (...args) => root === 'actions' ? syncRpc(name, args) : rpc(name, args); diff --git a/src/guest-guidance.js b/src/guest-guidance.js index 04e103f..7899333 100644 --- a/src/guest-guidance.js +++ b/src/guest-guidance.js @@ -16,6 +16,7 @@ const NAMESPACE_CALLS = { search: ['search.content({ path, query })', 'search.content'], browse: ['browse.exec({ urls })', 'browse.exec'], api: ['api.batch(requests)', 'api.batch'], + desktop: ['desktop.get_app_state({ app })', 'desktop.get_app_state'], report: ['report.build(options)', 'report.build'], recipes: ['recipes.run(name, input)', 'recipes.run'], read_file: ['read_file({ path })', 'read_file'], diff --git a/src/host/actions.js b/src/host/actions.js index e466a30..d2c8dbc 100644 --- a/src/host/actions.js +++ b/src/host/actions.js @@ -17,6 +17,7 @@ import { checkBrowseArgs, } from './browse/actions-schema.js'; import { validateRecipeRun } from './browse/watch.js'; +import { DESKTOP_ACTIONS } from './desktop/desktop-actions.js'; import { parseApplyPatch } from './patch.js'; // The guest manifest exposes these same functions twice: once as globals and once through @@ -54,6 +55,7 @@ const REGISTRY = [ ...REPORT_ACTIONS, ...API_ACTIONS, ...RECIPE_ACTIONS, + ...DESKTOP_ACTIONS, { path: 'read_file', description: 'Read a file using the Aside read_file shape. offset/limit are 1-indexed lines.', diff --git a/src/host/desktop/desktop-actions.js b/src/host/desktop/desktop-actions.js new file mode 100644 index 0000000..153f562 --- /dev/null +++ b/src/host/desktop/desktop-actions.js @@ -0,0 +1,20 @@ +// Catalog rows for the guest `desktop` namespace (macOS Codex Computer Use). +export const ENABLE_DESKTOP_HINT = 'Turn it on in codemode.config.json: "desktop": { "enabled": true, "packageDir": "<…/node_modules/codex-computer-use-mcp>", "disclaimLauncher": "" }.'; + +const APP = { type: 'string', required: true, description: 'App name, full app path, or bundle id (e.g. "KakaoTalk")' }; +const OPTS = 'Second argument { image?: true } returns the screenshot as base64; default is metadata only, so trees can be filtered in-guest without flooding the context.'; + +export const DESKTOP_ACTIONS = [ + { path: 'desktop.list_apps', description: 'Running and recently used macOS apps.', signature: 'desktop.list_apps({}) => Promise<{ok,text}>', inputs: {} }, + { path: 'desktop.get_app_state', description: 'Accessibility tree (+ optional screenshot) of an app key window. Call once per execution before acting on that app.', signature: 'desktop.get_app_state({ app }, opts?) => Promise<{ok,text,image?}>', inputs: { app: APP, opts: { type: 'object', required: false, description: '{ image: true } returns the screenshot as base64' } }, notes: OPTS }, + { path: 'desktop.click', description: 'Click an element index or screenshot pixel.', signature: 'desktop.click({ app, element_index?, x?, y?, click_count?, mouse_button? }) => Promise<{ok,text}>', inputs: { app: APP, element_index: { type: 'string', required: false, description: 'Index from get_app_state' }, x: { type: 'number', required: false, description: 'Screenshot x' }, y: { type: 'number', required: false, description: 'Screenshot y' }, click_count: { type: 'number', required: false, description: 'Default 1' }, mouse_button: { type: 'string', required: false, description: 'left | right | middle' } } }, + { path: 'desktop.perform_secondary_action', description: 'Invoke a secondary AX action on an element.', signature: 'desktop.perform_secondary_action({ app, element_index, action }) => Promise<{ok,text}>', inputs: { app: APP, element_index: { type: 'string', required: true, description: 'Element index' }, action: { type: 'string', required: true, description: 'AX action name' } } }, + { path: 'desktop.set_value', description: 'Set a settable AX element value (text fields).', signature: 'desktop.set_value({ app, element_index, value }) => Promise<{ok,text}>', inputs: { app: APP, element_index: { type: 'string', required: true, description: 'Element index' }, value: { type: 'string', required: true, description: 'New value' } } }, + { path: 'desktop.select_text', description: 'Select text or place the cursor in a text element.', signature: 'desktop.select_text({ app, element_index, text, prefix?, suffix?, selection? }) => Promise<{ok,text}>', inputs: { app: APP, element_index: { type: 'string', required: true, description: 'Element index' }, text: { type: 'string', required: true, description: 'Target text' }, prefix: { type: 'string', required: false, description: 'Disambiguating prefix' }, suffix: { type: 'string', required: false, description: 'Disambiguating suffix' }, selection: { type: 'string', required: false, description: 'text | cursor_before | cursor_after' } } }, + { path: 'desktop.scroll', description: 'Scroll an element by pages.', signature: 'desktop.scroll({ app, element_index, direction, pages? }) => Promise<{ok,text}>', inputs: { app: APP, element_index: { type: 'string', required: true, description: 'Element index' }, direction: { type: 'string', required: true, description: 'up | down | left | right' }, pages: { type: 'number', required: false, description: 'Default 1' } } }, + { path: 'desktop.drag', description: 'Drag between screenshot pixels.', signature: 'desktop.drag({ app, from_x, from_y, to_x, to_y }) => Promise<{ok,text}>', inputs: { app: APP, from_x: { type: 'number', required: true, description: 'Start x' }, from_y: { type: 'number', required: true, description: 'Start y' }, to_x: { type: 'number', required: true, description: 'End x' }, to_y: { type: 'number', required: true, description: 'End y' } } }, + { path: 'desktop.press_key', description: 'Press a key or chord (xdotool syntax: Return, super+c).', signature: 'desktop.press_key({ app, key }) => Promise<{ok,text}>', inputs: { app: APP, key: { type: 'string', required: true, description: 'Key or chord' } } }, + { path: 'desktop.type_text', description: 'Type literal text into the focused element.', signature: 'desktop.type_text({ app, text }) => Promise<{ok,text}>', inputs: { app: APP, text: { type: 'string', required: true, description: 'Literal text' } } }, + { path: 'desktop.run', description: 'Run many desktop steps in one host round-trip; stops at the first failure or missing expect text.', signature: 'desktop.run(steps, opts?) => Promise<{ok,complete,failedAt?,results}>', inputs: { steps: { type: 'array', required: true, description: 'Array of { method, args, expect } (expect is an optional substring check)' }, opts: { type: 'object', required: false, description: 'keepText returns full text per step; textChars caps it (default 300)' } } }, + { path: 'desktop.status', description: 'Whether desktop control is on, broker verification, and the TCC launcher.', signature: 'desktop.status() => Promise', inputs: {} }, +]; diff --git a/src/host/desktop/desktop.js b/src/host/desktop/desktop.js new file mode 100644 index 0000000..c68c462 --- /dev/null +++ b/src/host/desktop/desktop.js @@ -0,0 +1,139 @@ +// Guest namespace `desktop`: Codex Computer Use (macOS native apps) inside code mode. +// +// Why here and not as a separate MCP: the agent's cost is turns and context, not the tool +// call. A plain MCP spends one model round-trip per click and pours every accessibility tree +// and screenshot into the context. Here the guest batches get_app_state -> filter -> click -> +// verify inside one execute_code and returns only what it chose to return. +// +// Transport: the host does NOT talk to SkyComputerUseClient directly. That client only answers +// a parent it trusts ("Sender process is not authenticated"), so the host borrows the +// signed-broker session from the `codex-computer-use-mcp` package, which runs the OpenAI-signed +// `codex app-server` with the client attached. Elements stay addressable across calls because +// that broker session lives as long as this namespace (idle-closed after config.desktop.idleMs). +// +// TCC: when Aside spawns the chain, macOS makes Aside the responsible process, and Aside lacks +// com.apple.security.automation.apple-events, so every call dies with bootstrapTimedOut. Set +// desktop.disclaimLauncher (or env CU_DISCLAIM_LAUNCHER) to a launcher that execs its argv with +// responsibility_spawnattrs_setdisclaim(1); the broker package must honour that env var. +import { pathToFileURL } from 'node:url'; +import path from 'node:path'; +import { existsSync } from 'node:fs'; +import { ENABLE_DESKTOP_HINT } from './desktop-actions.js'; + +export const DESKTOP_METHODS = Object.freeze([ + 'list_apps', 'get_app_state', 'click', 'perform_secondary_action', 'set_value', + 'select_text', 'scroll', 'drag', 'press_key', 'type_text', +]); + +// get_app_state returns { content: [ {type:'text', text}, {type:'image', data, mimeType} ] }. +// The guest gets text in full and images as metadata only unless it asks; an image is the +// single biggest thing that can flood the context, so it must be opted into per call. +function shapeResult(method, raw, { withImage }) { + const content = Array.isArray(raw?.content) ? raw.content : []; + const text = content.filter((c) => c && c.type === 'text').map((c) => c.text).join('\n'); + const images = content.filter((c) => c && c.type === 'image'); + const out = { method, ok: raw?.isError !== true, text }; + if (images.length) { + out.image = withImage + ? { mimeType: images[0].mimeType, data: images[0].data } + : { mimeType: images[0].mimeType, bytes: Math.round(String(images[0].data || '').length * 0.75), omitted: true }; + } + if (!out.ok) out.error = text || 'official computer use error'; + return out; +} + +async function loadBroker(packageDir) { + const sessionUrl = pathToFileURL(path.join(packageDir, 'dist', 'session-executor.js')).href; + const statusUrl = pathToFileURL(path.join(packageDir, 'dist', 'direct-service.js')).href; + const [{ DirectSessionExecutor }, { getDirectStatus }] = await Promise.all([import(sessionUrl), import(statusUrl)]); + return { DirectSessionExecutor, getDirectStatus }; +} + +export function createDesktop({ config = {}, signal, env = process.env, loader = loadBroker } = {}) { + const caps = config.desktop || {}; + let executor = null; + let broker = null; + + function requireEnabled(name) { + if (caps.enabled !== true) { + const e = new Error(`desktop.${name} needs desktop control, which is off. ${ENABLE_DESKTOP_HINT}`); + e.code = 'EDISABLED'; + throw e; + } + if (process.platform !== 'darwin') { + const e = new Error('desktop.* drives macOS apps through Codex Computer Use and is macOS-only.'); + e.code = 'ENOTSUP'; + throw e; + } + if (!caps.packageDir || !existsSync(path.join(caps.packageDir, 'dist', 'session-executor.js'))) { + const e = new Error('desktop.packageDir must point at an installed codex-computer-use-mcp package (…/node_modules/codex-computer-use-mcp).'); + e.code = 'ENOTFOUND'; + throw e; + } + } + + async function getExecutor() { + if (executor) return executor; + const launcher = caps.disclaimLauncher || env.CU_DISCLAIM_LAUNCHER; + if (launcher) process.env.CU_DISCLAIM_LAUNCHER = launcher; + broker = await loader(caps.packageDir); + executor = new broker.DirectSessionExecutor({ idleTimeoutMs: caps.idleMs ?? 120000 }); + signal?.addEventListener?.('abort', () => { void executor?.close().catch(() => {}); executor = null; }, { once: true }); + return executor; + } + + function method(name) { + return async (args = {}, opts = {}) => { + requireEnabled(name); + if (args === null || typeof args !== 'object' || Array.isArray(args)) { + const e = new Error(`desktop.${name}(args) takes one object, e.g. desktop.${name}({ app: "KakaoTalk" }).`); + e.code = 'EBADVAL'; + throw e; + } + const ex = await getExecutor(); + const raw = await ex.execute(name, args, { signal }); + return shapeResult(name, raw, { withImage: opts && opts.image === true }); + }; + } + + const api = {}; + for (const m of DESKTOP_METHODS) api[m] = method(m); + + // Many steps, one host round-trip, stop at the first failure. Each step is + // { method, args, expect? } where expect is a substring the step's text must contain. + api.run = async (steps = [], opts = {}) => { + requireEnabled('run'); + if (!Array.isArray(steps) || !steps.length) { + const e = new Error('desktop.run(steps) takes a non-empty array of { method, args, expect? }.'); + e.code = 'EBADVAL'; + throw e; + } + const results = []; + for (const [i, step] of steps.entries()) { + if (!step || !DESKTOP_METHODS.includes(step.method)) { + results.push({ step: i, ok: false, error: `unknown method ${step && step.method}` }); + return { ok: false, complete: false, failedAt: i, results }; + } + let r; + try { r = await api[step.method](step.args || {}, { image: false }); } + catch (e) { r = { method: step.method, ok: false, error: e.message }; } + if (r.ok && step.expect && !String(r.text).includes(step.expect)) { + r = { ...r, ok: false, error: `expected text not found: ${step.expect}` }; + } + results.push({ step: i, method: r.method, ok: r.ok, ...(r.error ? { error: r.error } : {}), + text: opts.keepText ? r.text : String(r.text || '').slice(0, opts.textChars ?? 300) }); + if (!r.ok) return { ok: false, complete: false, failedAt: i, results }; + } + return { ok: true, complete: true, results }; + }; + + api.status = async () => { + if (caps.enabled !== true) return { enabled: false, hint: ENABLE_DESKTOP_HINT }; + requireEnabled('status'); + const b = broker || await loader(caps.packageDir); + return { enabled: true, launcher: Boolean(caps.disclaimLauncher || env.CU_DISCLAIM_LAUNCHER), ...b.getDirectStatus() }; + }; + + api._close = async () => { await executor?.close().catch(() => {}); executor = null; }; + return Object.freeze(api); +} diff --git a/src/host/globals.js b/src/host/globals.js index 8c30194..f29d933 100644 --- a/src/host/globals.js +++ b/src/host/globals.js @@ -7,6 +7,31 @@ import { createActions } from './actions.js'; import { createBrowse } from './browse/browse.js'; import { createReport, createApiNamespace } from './namespaces.js'; import { resolveBrowserContext } from '../browser-context.js'; +import { createDesktop } from './desktop/desktop.js'; + +// One broker session per server process, not per execution: get_app_state element indexes +// are only valid inside the signed session that produced them, and a guest that reads the tree +// in one execute_code and clicks in the next must hit the same session. The broker idle-closes +// it after desktop.idleMs. +let desktopSingleton = null; +let desktopKey = null; +function sharedDesktop(config) { + const key = JSON.stringify(config.desktop || {}); + if (!desktopSingleton || desktopKey !== key) { + if (desktopSingleton) void desktopSingleton._close(); + desktopSingleton = createDesktop({ config }); + desktopKey = key; + } + return desktopSingleton; +} + +// The CLI is one-shot: close the broker so the process exits now, not after idleMs. +export async function closeSharedDesktop() { + const d = desktopSingleton; + desktopSingleton = null; + desktopKey = null; + if (d) await d._close(); +} export function createHostGlobals(config, assertInside, signal, { browserContext } = {}) { const rgRunner = createRgRunner(createRgResolver(config, process.env, { signal }), { excludeGlobs: config.excludeGlobs, signal }); @@ -26,6 +51,7 @@ export function createHostGlobals(config, assertInside, signal, { browserContext browse, report: createReport({ config, signal, assertInside, browserContext: resolvedContext }), api: createApiNamespace(), + desktop: sharedDesktop(config), recipes: browse._recipes, }; } diff --git a/src/sandbox.js b/src/sandbox.js index 773b72a..fa6b9df 100644 --- a/src/sandbox.js +++ b/src/sandbox.js @@ -8,7 +8,7 @@ import { import { isDecoratedResult } from './result-envelope.js'; const HOST_DRAIN_MS = 1000; -const ROOTS = ['search', 'fs', 'actions', 'browse', 'report', 'api', 'recipes', 'read_file', 'write_file', 'edit_file', 'apply_patch']; +const ROOTS = ['search', 'fs', 'actions', 'browse', 'report', 'api', 'desktop', 'recipes', 'read_file', 'write_file', 'edit_file', 'apply_patch']; function hostMethods(globals) { const methods = new Map(); @@ -17,7 +17,7 @@ function hostMethods(globals) { if (typeof value === 'function') methods.set(root, value.bind(globals)); else if (value && typeof value === 'object') { for (const [name, fn] of Object.entries(value)) { - if (typeof fn === 'function') methods.set(`${root}.${name}`, fn.bind(value)); + if (typeof fn === 'function' && !name.startsWith('_')) methods.set(`${root}.${name}`, fn.bind(value)); } } } diff --git a/src/tools.js b/src/tools.js index 4bc2cb8..29dc150 100644 --- a/src/tools.js +++ b/src/tools.js @@ -13,7 +13,7 @@ const GUEST_API_DOC = [ 'For "this page" or an already-open tab, use browse.attach; it reads the existing tab without opening or closing one.', 'Code is an async function body; await freely and return the answer. Only return and console output enter context, capped at 64 KiB on the RETURN path: a big page reads whole, so fs.write it and fs.grepFile it, then return a small answer.', 'Discover calls with actions.find(query) -> actions.describe(path) -> actions.check(path,args). The catalog includes browse.readText, browse.attach and treeNodes.', - 'Globals: search, fs, actions, browse, report, api, recipes, read_file, write_file, edit_file, apply_patch, console.', + 'Globals: search, fs, actions, browse, report, api, desktop, recipes, read_file, write_file, edit_file, apply_patch, console.', 'There is no module loader: import(), require, process and fetch do not exist; string-built code and dynamic import are refused. Use the injected APIs.', 'Searches prune by .gitignore, dotfiles, excludeGlobs and binary content by default; rg skips binary SILENTLY. scope.coverage marks each off/on/unknown: absence needs complete:true and every entry off.', 'Search arrays stay iterable; serialization is {rows,complete,truncated,partial,scope}, and counts add the same to matches/files. Preserve the envelope when projecting. complete:false, truncated:true or partial mean rows are missing.', diff --git a/structure/INDEX.md b/structure/INDEX.md index 8350d5c..ce35b0e 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -35,6 +35,7 @@ The batch surface that drives Aside, and how it refuses work that cannot succeed | --- | --- | | [`browse-surface.md`](browse-surface.md) | The job schema, block detection and the breaker, capture verification, and ref-addressed actions. | | [`local-surface.md`](local-surface.md) | The guest file tools, ripgrep-backed search, scope reporting, and write coordination. | +| [`desktop-surface.md`](desktop-surface.md) | The macOS Computer Use namespace: why it lives in code mode, its signed-broker transport, the responsibility disclaim, and its result shape. | ### Tier 4 — Delivery @@ -59,6 +60,7 @@ What an install writes into an account, and the budget it spends there. | `src/host/browse/policy.js` | [`session-contract.md`](session-contract.md) | | `src/host/browse/result-contract.js` | [`batch-contract.md`](batch-contract.md) | | `src/host/browse/session.js` | [`batch-contract.md`](batch-contract.md) | +| `src/host/desktop/` | [`desktop-surface.md`](desktop-surface.md) | | `src/host/file-lock.js` | [`local-surface.md`](local-surface.md) | | `src/host/fs.js` | [`local-surface.md`](local-surface.md) | | `src/host/globals.js` | [`overview.md`](overview.md) | diff --git a/structure/desktop-surface.md b/structure/desktop-surface.md new file mode 100644 index 0000000..4d6e9f9 --- /dev/null +++ b/structure/desktop-surface.md @@ -0,0 +1,56 @@ +# Desktop surface + +`desktop.*` lets guest code drive native macOS apps through the official Codex Computer Use +engine. It exists for the same reason the rest of code mode does: one model turn should be +able to read an app, pick what matters, act, and check the result, and only the answer should +come back. + +## Why a namespace, not another MCP server + +A Computer Use MCP server costs one model round-trip per click, and every accessibility tree +and screenshot it returns lands in the context. A chat app's tree is thousands of characters; +its screenshot is over a hundred kilobytes. Inside code mode the guest reads the tree, filters +it with ordinary JavaScript, acts, and verifies, and returns a few lines. + +## Transport + +The code lives in `src/host/desktop/`: `desktop.js` is the namespace and `desktop-actions.js` +is its catalog. + +The host does not speak to `SkyComputerUseClient` directly. That client answers only a parent +it trusts and replies "Sender process is not authenticated" to anything else. The host loads +the `DirectSessionExecutor` from an installed `codex-computer-use-mcp` package, which runs the +OpenAI-signed `codex app-server` with the client attached and verifies both signatures. + +One executor lives per server process, not per execution. Element indexes returned by +`get_app_state` are only valid inside the session that produced them, so a guest that reads in +one `execute_code` and clicks in the next must reach the same session. The broker closes it +after `desktop.idleMs` of inactivity. The CLI closes it when its single execution ends. + +## macOS responsibility + +When Aside launches the chain, macOS treats Aside as the responsible process for every child. +Aside's signature does not carry `com.apple.security.automation.apple-events`, so every call +fails with `bootstrapTimedOut`, and toggling privacy settings cannot fix it. The fix is to +launch the signed `codex` binary with `responsibility_spawnattrs_setdisclaim(1)`, so that binary +answers for itself. `desktop.disclaimLauncher` (or `CU_DISCLAIM_LAUNCHER`) names a launcher that +does this; the broker package must honour that variable at the point where it spawns `codex`. + +## Configuration and defaults + +Off by default. Driving native apps has a larger blast radius than reading files. + + "desktop": { "enabled": true, "packageDir": "…/node_modules/codex-computer-use-mcp", + "disclaimLauncher": "…/disclaim.py", "idleMs": 120000 } + +`desktop.status()` reports whether it is on, whether the broker verified, and whether a +launcher is set. It never throws for the disabled case. + +## Result shape + +Each method returns `{ method, ok, text, image?, error? }`. `text` is the official text content. +A screenshot is returned as `{ mimeType, bytes, omitted: true }` unless the call passes +`{ image: true }` as its second argument. `desktop.run(steps)` executes `{ method, args, +expect? }` steps in order, stops at the first failure or missing `expect` substring, and trims +each step's text to `textChars` (default 300) unless `keepText` is set. A stopped run reports +`complete: false` and `failedAt`. diff --git a/structure/manifest.json b/structure/manifest.json index c673c97..72afd43 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -112,6 +112,15 @@ "src/register.js", "src/paths.js" ] + }, + { + "path": "desktop-surface.md", + "tier": 3, + "title": "Desktop surface", + "scope": "The macOS Computer Use namespace: why it lives in code mode, its signed-broker transport, the responsibility disclaim, and its result shape.", + "documents": [ + "src/host/desktop/" + ] } ] } diff --git a/test/completeness-invariant.test.js b/test/completeness-invariant.test.js index e43a31a..7d27ced 100644 --- a/test/completeness-invariant.test.js +++ b/test/completeness-invariant.test.js @@ -62,6 +62,18 @@ const COVERAGE = { 'report.build': { items: 'selector', outFile: 'neutral', title: 'neutral', paper: 'neutral', timeoutMs: 'may-omit' }, 'api.batch': { requests: 'selector' }, 'api.adapters': {}, + 'desktop.list_apps': {}, + 'desktop.get_app_state': { app: 'selector', opts: 'neutral' }, + 'desktop.click': { app: 'selector', element_index: 'selector', x: 'selector', y: 'selector', click_count: 'neutral', mouse_button: 'neutral' }, + 'desktop.perform_secondary_action': { app: 'selector', element_index: 'selector', action: 'neutral' }, + 'desktop.set_value': { app: 'selector', element_index: 'selector', value: 'neutral' }, + 'desktop.select_text': { app: 'selector', element_index: 'selector', text: 'selector', prefix: 'selector', suffix: 'selector', selection: 'neutral' }, + 'desktop.scroll': { app: 'selector', element_index: 'selector', direction: 'neutral', pages: 'neutral' }, + 'desktop.drag': { app: 'selector', from_x: 'selector', from_y: 'selector', to_x: 'selector', to_y: 'selector' }, + 'desktop.press_key': { app: 'selector', key: 'neutral' }, + 'desktop.type_text': { app: 'selector', text: 'neutral' }, + 'desktop.run': { steps: 'selector', opts: 'neutral' }, + 'desktop.status': {}, 'recipes.list': {}, 'recipes.describe': { name: 'selector' }, 'recipes.run': { name: 'selector', args: 'selector' }, diff --git a/test/desktop.test.js b/test/desktop.test.js new file mode 100644 index 0000000..0cd5196 --- /dev/null +++ b/test/desktop.test.js @@ -0,0 +1,105 @@ +// desktop.* (macOS Codex Computer Use) — contract tests with a fake broker. No real app is driven. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createDesktop, DESKTOP_METHODS } from '../src/host/desktop/desktop.js'; +import { createActions } from '../src/host/actions.js'; +import { loadConfig } from '../src/config.js'; + +function fakePackageDir() { + const dir = mkdtempSync(path.join(tmpdir(), 'cu-pkg-')); + mkdirSync(path.join(dir, 'dist')); + writeFileSync(path.join(dir, 'dist', 'session-executor.js'), ''); + return dir; +} + +function fakeLoader(log) { + return async () => ({ + DirectSessionExecutor: class { + constructor(opts) { log.push(['ctor', opts.idleTimeoutMs]); } + async execute(method, args) { + log.push([method, args]); + if (args.fail) return { isError: true, content: [{ type: 'text', text: 'boom' }] }; + return { content: [{ type: 'text', text: `tree for ${args.app || 'all'}\nline 2` }, { type: 'image', mimeType: 'image/jpeg', data: 'QUJDRA==' }] }; + } + async close() { log.push(['close']); } + }, + getDirectStatus: () => ({ brokerVerified: true }), + }); +} + +const on = (extra = {}) => ({ desktop: { enabled: true, packageDir: fakePackageDir(), idleMs: 5, ...extra } }); +const darwin = process.platform === 'darwin'; + +test('desktop is off by default and says how to turn it on', async () => { + const d = createDesktop({ config: {}, loader: fakeLoader([]) }); + await assert.rejects(() => d.list_apps({}), (e) => e.code === 'EDISABLED' && /desktop/.test(e.message)); + assert.deepEqual((await d.status()).enabled, false); +}); + +test('config default keeps desktop disabled', () => { + assert.equal(loadConfig([], { CODEMODE_IGNORE_REPO_CONFIG: '1', XDG_CONFIG_HOME: mkdtempSync(path.join(tmpdir(), 'xdg-')) }).desktop.enabled, false); +}); + +test('exposes the ten official methods plus run and status', () => { + const d = createDesktop({ config: on(), loader: fakeLoader([]) }); + for (const m of DESKTOP_METHODS) assert.equal(typeof d[m], 'function', m); + assert.equal(typeof d.run, 'function'); + assert.equal(typeof d.status, 'function'); + assert.equal(DESKTOP_METHODS.length, 10); +}); + +test('images are metadata unless the caller opts in', { skip: !darwin }, async () => { + const d = createDesktop({ config: on(), loader: fakeLoader([]) }); + const a = await d.get_app_state({ app: 'X' }); + assert.equal(a.ok, true); + assert.equal(a.image.omitted, true); + assert.equal('data' in a.image, false); + const b = await d.get_app_state({ app: 'X' }, { image: true }); + assert.equal(b.image.data, 'QUJDRA=='); +}); + +test('one broker executor is reused across calls (element indexes stay valid)', { skip: !darwin }, async () => { + const log = []; + const d = createDesktop({ config: on(), loader: fakeLoader(log) }); + await d.get_app_state({ app: 'X' }); + await d.click({ app: 'X', element_index: '3' }); + assert.equal(log.filter((r) => r[0] === 'ctor').length, 1); +}); + +test('run batches steps, trims text, and stops at the first failure or missing expect', { skip: !darwin }, async () => { + const d = createDesktop({ config: on(), loader: fakeLoader([]) }); + const good = await d.run([{ method: 'list_apps', args: {} }, { method: 'get_app_state', args: { app: 'X' }, expect: 'tree for X' }], { textChars: 4 }); + assert.equal(good.ok, true); + assert.equal(good.results[1].text, 'tree'); + const miss = await d.run([{ method: 'get_app_state', args: { app: 'X' }, expect: 'nope' }, { method: 'click', args: { app: 'X' } }]); + assert.equal(miss.ok, false); + assert.equal(miss.failedAt, 0); + assert.equal(miss.results.length, 1); + const err = await d.run([{ method: 'click', args: { app: 'X', fail: true } }]); + assert.equal(err.ok, false); + const bad = await d.run([{ method: 'rm_rf', args: {} }]); + assert.equal(bad.failedAt, 0); +}); + +test('non-object args are refused before reaching the broker', { skip: !darwin }, async () => { + const log = []; + const d = createDesktop({ config: on(), loader: fakeLoader(log) }); + await assert.rejects(() => d.click('X'), (e) => e.code === 'EBADVAL'); + assert.equal(log.length, 0); +}); + +test('a wrong packageDir is a named error, not a crash', { skip: !darwin }, async () => { + const d = createDesktop({ config: { desktop: { enabled: true, packageDir: '/nonexistent' } }, loader: fakeLoader([]) }); + await assert.rejects(() => d.list_apps({}), (e) => e.code === 'ENOTFOUND'); +}); + +test('the catalog lists every desktop entry and check() validates required inputs', () => { + const actions = createActions(); + const paths = actions.list().map((r) => r.path).filter((p) => p.startsWith('desktop.')); + for (const m of [...DESKTOP_METHODS, 'run', 'status']) assert.ok(paths.includes('desktop.' + m), m); + assert.equal(actions.check('desktop.click', { app: 'X', element_index: '1' }).ok, true); + assert.equal(actions.check('desktop.type_text', { app: 'X' }).ok, false); +}); From 61d97418bb56b2c479752da173b67aa4dec3c4a2 Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:48:10 +0900 Subject: [PATCH 2/3] fix(desktop): one broker start, per-execution cancellation, null run opts Concurrent first calls each opened a broker session and leaked all but one. The shared namespace never saw the execution abort signal, so a timed-out desktop.run kept clicking through its remaining steps. Each execution now gets a view bound to its own signal; the session stays shared. Tests inject the platform so they run on every CI OS. --- src/host/desktop/desktop.js | 103 +++++++++++++++++++++++------------ src/host/globals.js | 2 +- structure/desktop-surface.md | 5 ++ test/desktop.test.js | 58 ++++++++++++++++---- 4 files changed, 121 insertions(+), 47 deletions(-) diff --git a/src/host/desktop/desktop.js b/src/host/desktop/desktop.js index c68c462..99e911d 100644 --- a/src/host/desktop/desktop.js +++ b/src/host/desktop/desktop.js @@ -49,9 +49,19 @@ async function loadBroker(packageDir) { return { DirectSessionExecutor, getDirectStatus }; } -export function createDesktop({ config = {}, signal, env = process.env, loader = loadBroker } = {}) { +function abortError(name) { + const e = new Error(`desktop.${name} was not sent: the execution was cancelled or timed out.`); + e.code = 'EABORTED'; + return e; +} + +// The executor (and with it the broker session) is shared by every execution that uses this +// namespace, so element indexes survive from one execute_code to the next. The abort signal is +// not shared: each execution gets a view bound to its own signal through _view(signal), so a +// timed-out execution stops issuing clicks without tearing down the session other executions use. +export function createDesktop({ config = {}, signal, env = process.env, loader = loadBroker, platform = process.platform } = {}) { const caps = config.desktop || {}; - let executor = null; + let executorPromise = null; let broker = null; function requireEnabled(name) { @@ -60,7 +70,7 @@ export function createDesktop({ config = {}, signal, env = process.env, loader = e.code = 'EDISABLED'; throw e; } - if (process.platform !== 'darwin') { + if (platform !== 'darwin') { const e = new Error('desktop.* drives macOS apps through Codex Computer Use and is macOS-only.'); e.code = 'ENOTSUP'; throw e; @@ -72,68 +82,93 @@ export function createDesktop({ config = {}, signal, env = process.env, loader = } } - async function getExecutor() { - if (executor) return executor; - const launcher = caps.disclaimLauncher || env.CU_DISCLAIM_LAUNCHER; - if (launcher) process.env.CU_DISCLAIM_LAUNCHER = launcher; - broker = await loader(caps.packageDir); - executor = new broker.DirectSessionExecutor({ idleTimeoutMs: caps.idleMs ?? 120000 }); - signal?.addEventListener?.('abort', () => { void executor?.close().catch(() => {}); executor = null; }, { once: true }); - return executor; + // Concurrent first calls (Promise.all in the guest) share one in-flight start, so only one + // broker session is ever opened. A failed start is forgotten so the next call can retry. + function getExecutor() { + if (!executorPromise) { + executorPromise = (async () => { + const launcher = caps.disclaimLauncher || env.CU_DISCLAIM_LAUNCHER; + if (launcher) process.env.CU_DISCLAIM_LAUNCHER = launcher; + broker = await loader(caps.packageDir); + return new broker.DirectSessionExecutor({ idleTimeoutMs: caps.idleMs ?? 120000 }); + })(); + executorPromise.catch(() => { executorPromise = null; }); + } + return executorPromise; } - function method(name) { - return async (args = {}, opts = {}) => { - requireEnabled(name); - if (args === null || typeof args !== 'object' || Array.isArray(args)) { - const e = new Error(`desktop.${name}(args) takes one object, e.g. desktop.${name}({ app: "KakaoTalk" }).`); - e.code = 'EBADVAL'; - throw e; - } - const ex = await getExecutor(); - const raw = await ex.execute(name, args, { signal }); - return shapeResult(name, raw, { withImage: opts && opts.image === true }); - }; + async function invoke(name, args, opts, sig) { + requireEnabled(name); + if (args === null || typeof args !== 'object' || Array.isArray(args)) { + const e = new Error(`desktop.${name}(args) takes one object, e.g. desktop.${name}({ app: "KakaoTalk" }).`); + e.code = 'EBADVAL'; + throw e; + } + if (sig?.aborted) throw abortError(name); + const ex = await getExecutor(); + if (sig?.aborted) throw abortError(name); + const raw = await ex.execute(name, args, { signal: sig }); + return shapeResult(name, raw, { withImage: Boolean(opts && opts.image === true) }); } - const api = {}; - for (const m of DESKTOP_METHODS) api[m] = method(m); - // Many steps, one host round-trip, stop at the first failure. Each step is // { method, args, expect? } where expect is a substring the step's text must contain. - api.run = async (steps = [], opts = {}) => { + // The guest cannot interrupt a host-side loop, so cancellation is checked before every step. + async function runSteps(steps, opts, sig) { requireEnabled('run'); if (!Array.isArray(steps) || !steps.length) { const e = new Error('desktop.run(steps) takes a non-empty array of { method, args, expect? }.'); e.code = 'EBADVAL'; throw e; } + const o = opts && typeof opts === 'object' ? opts : {}; const results = []; for (const [i, step] of steps.entries()) { + if (sig?.aborted) { + results.push({ step: i, ok: false, error: abortError('run').message }); + return { ok: false, complete: false, failedAt: i, results }; + } if (!step || !DESKTOP_METHODS.includes(step.method)) { results.push({ step: i, ok: false, error: `unknown method ${step && step.method}` }); return { ok: false, complete: false, failedAt: i, results }; } let r; - try { r = await api[step.method](step.args || {}, { image: false }); } + try { r = await invoke(step.method, step.args || {}, { image: false }, sig); } catch (e) { r = { method: step.method, ok: false, error: e.message }; } if (r.ok && step.expect && !String(r.text).includes(step.expect)) { r = { ...r, ok: false, error: `expected text not found: ${step.expect}` }; } results.push({ step: i, method: r.method, ok: r.ok, ...(r.error ? { error: r.error } : {}), - text: opts.keepText ? r.text : String(r.text || '').slice(0, opts.textChars ?? 300) }); + text: o.keepText ? r.text : String(r.text || '').slice(0, o.textChars ?? 300) }); if (!r.ok) return { ok: false, complete: false, failedAt: i, results }; } return { ok: true, complete: true, results }; - }; + } - api.status = async () => { + async function status() { if (caps.enabled !== true) return { enabled: false, hint: ENABLE_DESKTOP_HINT }; requireEnabled('status'); const b = broker || await loader(caps.packageDir); return { enabled: true, launcher: Boolean(caps.disclaimLauncher || env.CU_DISCLAIM_LAUNCHER), ...b.getDirectStatus() }; - }; + } + + async function close() { + const p = executorPromise; + executorPromise = null; + if (!p) return; + const ex = await p.catch(() => null); + await ex?.close().catch(() => {}); + } + + function view(sig) { + const api = {}; + for (const m of DESKTOP_METHODS) api[m] = (args = {}, opts = {}) => invoke(m, args, opts, sig); + api.run = (steps = [], opts = {}) => runSteps(steps, opts, sig); + api.status = status; + api._close = close; + api._view = view; + return Object.freeze(api); + } - api._close = async () => { await executor?.close().catch(() => {}); executor = null; }; - return Object.freeze(api); + return view(signal); } diff --git a/src/host/globals.js b/src/host/globals.js index f29d933..99c8886 100644 --- a/src/host/globals.js +++ b/src/host/globals.js @@ -51,7 +51,7 @@ export function createHostGlobals(config, assertInside, signal, { browserContext browse, report: createReport({ config, signal, assertInside, browserContext: resolvedContext }), api: createApiNamespace(), - desktop: sharedDesktop(config), + desktop: sharedDesktop(config)._view(signal), recipes: browse._recipes, }; } diff --git a/structure/desktop-surface.md b/structure/desktop-surface.md index 4d6e9f9..f6436e0 100644 --- a/structure/desktop-surface.md +++ b/structure/desktop-surface.md @@ -27,6 +27,11 @@ One executor lives per server process, not per execution. Element indexes return one `execute_code` and clicks in the next must reach the same session. The broker closes it after `desktop.idleMs` of inactivity. The CLI closes it when its single execution ends. +The abort signal is per execution even though the session is shared: each execution gets a +view of the namespace bound to its own signal. When an execution times out or is cancelled, its +calls stop being sent and `desktop.run` stops before its next step, while the session stays open +for other executions. Concurrent first calls share one start, so only one session is opened. + ## macOS responsibility When Aside launches the chain, macOS treats Aside as the responsible process for every child. diff --git a/test/desktop.test.js b/test/desktop.test.js index 0cd5196..baa5b9e 100644 --- a/test/desktop.test.js +++ b/test/desktop.test.js @@ -31,7 +31,6 @@ function fakeLoader(log) { } const on = (extra = {}) => ({ desktop: { enabled: true, packageDir: fakePackageDir(), idleMs: 5, ...extra } }); -const darwin = process.platform === 'darwin'; test('desktop is off by default and says how to turn it on', async () => { const d = createDesktop({ config: {}, loader: fakeLoader([]) }); @@ -44,15 +43,15 @@ test('config default keeps desktop disabled', () => { }); test('exposes the ten official methods plus run and status', () => { - const d = createDesktop({ config: on(), loader: fakeLoader([]) }); + const d = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader([]) }); for (const m of DESKTOP_METHODS) assert.equal(typeof d[m], 'function', m); assert.equal(typeof d.run, 'function'); assert.equal(typeof d.status, 'function'); assert.equal(DESKTOP_METHODS.length, 10); }); -test('images are metadata unless the caller opts in', { skip: !darwin }, async () => { - const d = createDesktop({ config: on(), loader: fakeLoader([]) }); +test('images are metadata unless the caller opts in', async () => { + const d = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader([]) }); const a = await d.get_app_state({ app: 'X' }); assert.equal(a.ok, true); assert.equal(a.image.omitted, true); @@ -61,16 +60,16 @@ test('images are metadata unless the caller opts in', { skip: !darwin }, async ( assert.equal(b.image.data, 'QUJDRA=='); }); -test('one broker executor is reused across calls (element indexes stay valid)', { skip: !darwin }, async () => { +test('one broker executor is reused across calls (element indexes stay valid)', async () => { const log = []; - const d = createDesktop({ config: on(), loader: fakeLoader(log) }); + const d = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader(log) }); await d.get_app_state({ app: 'X' }); await d.click({ app: 'X', element_index: '3' }); assert.equal(log.filter((r) => r[0] === 'ctor').length, 1); }); -test('run batches steps, trims text, and stops at the first failure or missing expect', { skip: !darwin }, async () => { - const d = createDesktop({ config: on(), loader: fakeLoader([]) }); +test('run batches steps, trims text, and stops at the first failure or missing expect', async () => { + const d = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader([]) }); const good = await d.run([{ method: 'list_apps', args: {} }, { method: 'get_app_state', args: { app: 'X' }, expect: 'tree for X' }], { textChars: 4 }); assert.equal(good.ok, true); assert.equal(good.results[1].text, 'tree'); @@ -84,15 +83,15 @@ test('run batches steps, trims text, and stops at the first failure or missing e assert.equal(bad.failedAt, 0); }); -test('non-object args are refused before reaching the broker', { skip: !darwin }, async () => { +test('non-object args are refused before reaching the broker', async () => { const log = []; - const d = createDesktop({ config: on(), loader: fakeLoader(log) }); + const d = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader(log) }); await assert.rejects(() => d.click('X'), (e) => e.code === 'EBADVAL'); assert.equal(log.length, 0); }); -test('a wrong packageDir is a named error, not a crash', { skip: !darwin }, async () => { - const d = createDesktop({ config: { desktop: { enabled: true, packageDir: '/nonexistent' } }, loader: fakeLoader([]) }); +test('a wrong packageDir is a named error, not a crash', async () => { + const d = createDesktop({ platform: 'darwin', config: { desktop: { enabled: true, packageDir: '/nonexistent' } }, loader: fakeLoader([]) }); await assert.rejects(() => d.list_apps({}), (e) => e.code === 'ENOTFOUND'); }); @@ -103,3 +102,38 @@ test('the catalog lists every desktop entry and check() validates required input assert.equal(actions.check('desktop.click', { app: 'X', element_index: '1' }).ok, true); assert.equal(actions.check('desktop.type_text', { app: 'X' }).ok, false); }); + +test('concurrent first calls open one broker session', async () => { + const log = []; + const d = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader(log) }); + await Promise.all([d.list_apps({}), d.get_app_state({ app: 'X' }), d.click({ app: 'X', element_index: '1' })]); + assert.equal(log.filter((r) => r[0] === 'ctor').length, 1); +}); + +test('a cancelled execution stops a run before the next step and leaves the shared session open', async () => { + const log = []; + const shared = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader(log) }); + const ctl = new AbortController(); + const d = shared._view(ctl.signal); + const first = { method: 'get_app_state', args: { app: 'X' } }; + const orig = first.args; + first.args = new Proxy(orig, { get(t, k) { if (k === 'app') ctl.abort(); return t[k]; } }); + const out = await d.run([first, { method: 'click', args: { app: 'X', element_index: '1' } }]); + assert.equal(out.ok, false); + assert.equal(out.failedAt, 1); + assert.equal(log.some((r) => r[0] === 'click'), false); + await assert.rejects(() => d.click({ app: 'X' }), (e) => e.code === 'EABORTED'); + assert.equal((await shared.click({ app: 'X', element_index: '1' })).ok, true); + assert.equal(log.some((r) => r[0] === 'close'), false); +}); + +test('run treats null options as defaults', async () => { + const d = createDesktop({ platform: 'darwin', config: on(), loader: fakeLoader([]) }); + const out = await d.run([{ method: 'list_apps', args: {} }], null); + assert.equal(out.ok, true); +}); + +test('desktop refuses non-macOS hosts with a named error', async () => { + const d = createDesktop({ platform: 'linux', config: on(), loader: fakeLoader([]) }); + await assert.rejects(() => d.list_apps({}), (e) => e.code === 'ENOTSUP'); +}); From 8284944a2888d893d9e660df1f7b425b28b767ee Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:48:10 +0900 Subject: [PATCH 3/3] docs: count desktop actions; mark 0.9.0 schema figures as predating them --- BENCHMARKS.md | 4 ++++ README.ko.md | 2 +- README.md | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 3c4df9c..65b317d 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -101,6 +101,10 @@ Re-measured at 0.9.0, after the completeness work widened eleven signatures and description named the 64 KiB return-path cap. The four numbers moved together and the note records the run: [aside-mcp-attach-260918.md](evidence/aside-mcp-attach-260918.md). +These are 0.9.0 figures and have not been re-measured since. The `desktop` namespace later added +twelve catalog rows (46 in all) and named itself in the resident description, which the suite +checks against the README; the definition total, schema and description sum above predate it. + ## Where codemode loses - **Single small grep.** Roughly a tie on time and **larger** on bytes: 43,948 against diff --git a/README.ko.md b/README.ko.md index cc547ed..75c88a3 100644 --- a/README.ko.md +++ b/README.ko.md @@ -87,7 +87,7 @@ PCRE2를 포함한 15.2.0으로 확인됐습니다. 바이너리는 `runtime/nat 그래서 에이전트의 실제 선택지는 bash로 부르는 POSIX `grep`과 `find`였고, 위 수치를 ripgrep이 아니라 그쪽에 대고 재는 이유도 그것입니다. ripgrep은 베이스라인이 아니라 천장입니다. 이 패키지는 -그 엔진을 도구 하나 뒤의 게스트 액션 34개로 표면에 올립니다. +그 엔진을 도구 하나 뒤의 게스트 액션 46개로 표면에 올립니다. ripgrep을 직접 부를 때와는 비슷합니다. `search.*`가 바로 그 바이너리를 부르니까요. 더 빠른 검색 엔진이 아니라, Aside가 이미 담아둔 엔진을 닿게 만들고 결과를 모델 앞에서 거르는 겁니다. diff --git a/README.md b/README.md index adf82c5..41b90c6 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ in bash is using an undocumented implementation detail, not a provided tool. So an agent's real options were POSIX `grep` and `find` through bash, which is why the numbers above are measured against those and not against ripgrep. Ripgrep is the ceiling, not the -baseline. This package puts that engine on the surface as 34 guest actions behind one tool. +baseline. This package puts that engine on the surface as 46 guest actions behind one tool. Against ripgrep called directly the two are level, because `search.*` shells out to that same binary. This is not a faster search engine. It is the engine Aside already shipped, reachable,