From 1e7187113c0f07359f9c04bc923ebb24cb377d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 20:28:12 +0100 Subject: [PATCH 01/15] refactor(plugins): key a platform claim by an optional appleOs leaf A platform claim key gains an optional leaf part, so a managed package can hold `{ kind: 'platform', family: 'apple', appleOs: 'macos' }` while the bundled Apple owner keeps the `apple` family claim for iOS and tvOS. Only `apple` narrows, and only to macOS. The registry keeps a leaf setup apart from the family setups, and the platform composition answers for the leaf through its own selection: an absent package raises `plugin-not-installed` with the `@agent-device/macos` install command. Part of #4675 --- packages/contracts/package.json | 4 + packages/contracts/src/macos-platform-leaf.ts | 272 ++++++++++++++++++ packages/contracts/src/platform-plugin.ts | 3 + packages/contracts/src/plugin-installation.ts | 30 ++ packages/contracts/src/plugin-inventory.ts | 6 + packages/plugins/src/platform.test.ts | 107 ++++++- packages/plugins/src/platform.ts | 31 +- packages/plugins/src/registry.ts | 36 ++- packages/plugins/src/validate.ts | 140 +++++++-- src/core/platform-plugin-absence.ts | 10 +- src/daemon-composition.ts | 1 + src/platform-runtime/installed-platforms.ts | 5 +- src/platform-runtime/platform-plugins.ts | 59 +++- src/provider-device-runtimes.ts | 2 + 14 files changed, 660 insertions(+), 46 deletions(-) create mode 100644 packages/contracts/src/macos-platform-leaf.ts diff --git a/packages/contracts/package.json b/packages/contracts/package.json index bf99a33d61..36efd27e7e 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -312,6 +312,10 @@ "types": "./src/logs-runtime-plan.ts", "default": "./src/logs-runtime-plan.ts" }, + "./macos-platform-leaf": { + "types": "./src/macos-platform-leaf.ts", + "default": "./src/macos-platform-leaf.ts" + }, "./linux-tool-provider": { "types": "./src/linux-tool-provider.ts", "default": "./src/linux-tool-provider.ts" diff --git a/packages/contracts/src/macos-platform-leaf.ts b/packages/contracts/src/macos-platform-leaf.ts new file mode 100644 index 0000000000..369a4a4b47 --- /dev/null +++ b/packages/contracts/src/macos-platform-leaf.ts @@ -0,0 +1,272 @@ +/** + * The macOS leaf of the Apple family (ADR 0034, issue #4675). + * + * macOS desktop automation is not a platform family: a Mac is an `apple` device whose `appleOs` is + * `macos`. The bundled Apple owner keeps the family claim and every iOS and tvOS route. At each of + * its macOS branches it calls the operations below, which the managed `@agent-device/macos` package + * supplies through a leaf claim `{ kind: 'platform', family: 'apple', appleOs: 'macos' }`. + * + * The leaf owns both macOS app backends, the desktop surfaces, and the Swift helper. The Apple owner + * keeps the one XCTest runner, so the leaf reaches it through {@link MacOsRunner}, a capability the + * owner binds to one device and hands in per call. + */ + +import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { EnvMap } from '@agent-device/kernel/source-value'; +import type { AppsFilter } from './app-inventory.ts'; +import type { + Interactor, + RunnerCallOptions, + RunnerContext, + SnapshotResult, +} from './interactor-types.ts'; +import type { RuntimeOperationUnavailability } from './platform-runtime.ts'; +import type { ScrollExecutionOptions } from './scroll-command.ts'; +import type { ScrollDirection } from './scroll-gesture.ts'; +import type { MacOsHelperSurface, SessionSurface } from './session-surface.ts'; +import type { CaptureSnapshotInput } from './snapshot-runtime.ts'; + +/** The TCC services the macOS helper grants and resets. */ +export type MacOsPermissionTarget = 'accessibility' | 'screen-recording' | 'input-monitoring'; + +/** How an app-surface action reached the app, as the helper reports it. */ +export type MacOsDeliveryMechanism = + | 'ax-press' + | 'ax-focus' + | 'ax-value' + | 'ax-selected-text' + | 'ax-confirm' + | 'ax-scroll-bar' + | 'ax-show-menu' + | 'key-events'; + +/** What the host answered one macOS tool: its streams and its exit code. */ +export type MacOsCommandResult = Readonly<{ + stdout: string; + stderr: string; + exitCode: number; +}>; + +/** How one macOS tool call runs. `kill` names a first signal for a child that must undo something. */ +export type MacOsCommandOptions = Readonly<{ + cwd?: string; + allowFailure?: boolean; + timeoutMs?: number; + signal?: AbortSignal; + stdin?: string; + kill?: Readonly<{ signal: 'SIGTERM'; graceMs: number }>; +}>; + +/** A process the host started and left running; the caller owns its stop. */ +export type MacOsBackgroundProcess = Readonly<{ + pid?: number; + wait: Promise>; + terminate(): Promise; +}>; + +export type MacOsInstalledApp = { bundleId: string; name: string; url?: string }; + +export type MacOsOpenOptions = { background?: boolean }; + +/** The host routes a request may substitute: LaunchServices, the pasteboard, and appearance. */ +export type MacOsHostProvider = { + /** `background` launches or reopens without bringing the app to the front. */ + openBundle(bundleId: string, url?: string, options?: MacOsOpenOptions): Promise; + openTarget(target: string, options?: MacOsOpenOptions): Promise; + readClipboard(): Promise; + writeClipboard(text: string): Promise; + readDarkMode(): Promise; + setDarkMode(enabled: boolean): Promise; + listApps(filter: AppsFilter): Promise; +}; + +/** + * The Apple tool routes of one request, as the Apple owner resolved them. The leaf runs every + * command through `runCommand`, so a request that scopes its own Apple tools reaches the leaf too + * and no command starts from the plugin's bundled copy of the host kit. + */ +export type MacOsLeafTools = Readonly<{ + runCommand( + cmd: string, + args: string[], + options?: MacOsCommandOptions, + ): Promise; + /** Starts a command the caller stops itself, with its output captured. */ + startBackground(cmd: string, args: string[]): MacOsBackgroundProcess; + /** The helper transport a scoped request supplies in place of the leaf's own binary. */ + helper?: Readonly<{ + run(args: string[], options?: MacOsCommandOptions): Promise; + }>; + /** The host routes a scoped request supplies in place of the leaf's local ones. */ + host?: MacOsHostProvider; + readPlistJson(path: string, signal?: AbortSignal): Promise | null>; + /** True when a request scoped the Apple tools: the helper binary is then that scope's to name. */ + scoped: boolean; +}>; + +/** The macOS wire cases of the Apple XCTest runner that the leaf maps commands to. */ +export type MacOsRunnerCommand = + | Readonly<{ + command: 'desktopScroll'; + direction: ScrollDirection; + amount?: number; + pixels?: number; + durationMs?: number; + appBundleId?: string; + }> + | Readonly<{ + command: 'mouseClick'; + x: number; + y: number; + button: 'secondary' | 'middle'; + appBundleId?: string; + }>; + +/** + * The Apple XCTest runner, bound by the Apple owner to one macOS device. It is the only way the + * leaf reaches the runner: the owner keeps the runner's build, session, and transport. + */ +export type MacOsRunner = Readonly<{ + run(command: MacOsRunnerCommand, options?: RunnerCallOptions): Promise>; +}>; + +export type MacOsSurfaceSnapshotOptions = Omit< + NonNullable, + 'surface' +> & { surface: MacOsHelperSurface }; + +type HelperContext = { bundleId?: string; signal?: AbortSignal; env: Readonly }; + +export type MacOsPressResult = { + x: number; + y: number; + holdMs?: number; + clicks?: number; + doubleClick?: boolean; + bundleId?: string; + surface?: SessionSurface; + mechanism?: MacOsDeliveryMechanism; + /** The window the helper acted in, for an app-surface press. */ + windowTitle?: string; +}; + +/** Every macOS operation the Apple owner delegates, bound to one request's tools. */ +export type MacOsLeafOperations = Readonly<{ + resolveApp(app: string): Promise; + /** The open target of an app device (ADR 0035): its own app, which a link alone also opens. */ + resolveAppDeviceOpenTarget( + device: DeviceInfo, + target: string | undefined, + ): Promise<{ appBundleId: string; appName?: string }>; + openApp( + device: DeviceInfo, + app: string, + options?: { appBundleId?: string; url?: string }, + ): Promise; + closeApp(device: DeviceInfo, app: string, env: Readonly): Promise; + listApps(filter: AppsFilter): Promise; + readClipboardText(): Promise; + writeClipboardText(text: string): Promise; + setAppearance(state: string): Promise; + frontmostApp( + env: Readonly, + ): Promise<{ bundleId?: string; appName?: string; pid?: number }>; + runPermissionAction( + action: 'grant' | 'reset', + target: MacOsPermissionTarget, + env: Readonly, + ): Promise<{ + target: MacOsPermissionTarget; + granted: boolean; + requested: boolean; + openedSettings: boolean; + action: 'grant' | 'reset'; + message?: string; + }>; + runAlertAction( + action: 'get' | 'accept' | 'dismiss', + options: { bundleId?: string; surface?: SessionSurface; env: Readonly }, + ): Promise<{ + title?: string; + role?: string; + buttons?: string[]; + action?: string; + bundleId?: string; + }>; + readTextAtPoint( + x: number, + y: number, + options: HelperContext & { surface: MacOsHelperSurface }, + ): Promise<{ text: string }>; + press( + x: number, + y: number, + options: HelperContext & { + surface: MacOsHelperSurface; + holdMs?: number; + /** Independent presses, each a single click; `--count` on every platform. */ + clicks?: number; + /** Post each press as a double-click pair; `--double-tap`. */ + doubleClick?: boolean; + intervalMs?: number; + }, + ): Promise; + screenshot( + outPath: string, + options: HelperContext & { surface: MacOsHelperSurface }, + ): Promise<{ path: string; surface?: SessionSurface }>; + captureSurfaceSnapshot( + options: MacOsSurfaceSnapshotOptions, + signal: AbortSignal | undefined, + env: Readonly, + ): Promise; + /** Samples host system audio through the helper's ScreenCaptureKit probe. */ + startAudioProbe(options: { + durationMs: number; + bucketMs: number; + statusPath: string; + env: Readonly; + }): Promise; + /** The interactor of the `native` app backend: helper actions, with no runner request. */ + nativeAppInteractor( + base: Interactor, + context: RunnerContext, + env: Readonly, + ): Promise; + /** The operations the `native` app backend refuses at admission. */ + nativeBackendFacts(): Promise>>; + /** The XCTest backend's desktop scroll, mapped to the runner's `desktopScroll` wire case. */ + desktopScroll( + runner: MacOsRunner, + context: RunnerContext, + runnerOptions: RunnerCallOptions, + direction: ScrollDirection, + options?: ScrollExecutionOptions, + ): Promise>; + /** The XCTest backend's secondary and middle click, mapped to the `mouseClick` wire case. */ + alternateClick( + runner: MacOsRunner, + context: RunnerContext, + runnerOptions: RunnerCallOptions, + point: { x: number; y: number }, + button: 'secondary' | 'middle', + ): Promise>; +}>; + +/** What the macOS leaf's `setup(host)` registers. */ +export type MacOsPlatformLeafRegistration = Readonly<{ + family: 'apple'; + appleOs: 'macos'; + /** Binds the leaf's operations to the tools the Apple owner resolved for one request. */ + bind(tools: MacOsLeafTools): MacOsLeafOperations; +}>; + +/** + * How the running process answers for the macOS leaf, installed or not. `get()` raises the typed + * `plugin-not-installed` outcome with the install command when the package is absent, and the + * package's own error when it failed to load. + */ +export type MacOsPlatformLeafSelection = Readonly<{ + active?: MacOsPlatformLeafRegistration; + get(): MacOsPlatformLeafRegistration; +}>; diff --git a/packages/contracts/src/platform-plugin.ts b/packages/contracts/src/platform-plugin.ts index 1383c55043..6be7bb9c55 100644 --- a/packages/contracts/src/platform-plugin.ts +++ b/packages/contracts/src/platform-plugin.ts @@ -3,6 +3,7 @@ import type { DoctorCheck } from './doctor.ts'; import type { HostDiagnosticsContext } from './host-diagnostics.ts'; import type { InventoryPlatformModule, PlatformModuleRegistry } from './platform-module.ts'; import type { LinuxToolProvider } from './linux-tool-provider.ts'; +import type { MacOsPlatformLeafSelection } from './macos-platform-leaf.ts'; import type { PlatformRuntimeModule } from './platform-runtime-operations.ts'; import type { WebProvider } from './web-provider.ts'; import type { VegaToolProvider } from './vega-tool-provider.ts'; @@ -181,6 +182,8 @@ export type PlatformModuleSelection = Readonly<{ vega: VegaPlatformSelection; harmony: HarmonyPlatformSelection; linux: LinuxPlatformSelection; + /** The macOS leaf of the bundled Apple family, which a managed package supplies. */ + macos: MacOsPlatformLeafSelection; inventoryModules: readonly InventoryPlatformModule[]; runtimeModules: readonly PlatformRuntimeModule[]; reportAbsent(family: Platform): AppError; diff --git a/packages/contracts/src/plugin-installation.ts b/packages/contracts/src/plugin-installation.ts index b220a614f7..1705409d26 100644 --- a/packages/contracts/src/plugin-installation.ts +++ b/packages/contracts/src/plugin-installation.ts @@ -124,6 +124,16 @@ export function getOptionalPlatformPluginDeclaration( : undefined; } +/** + * The vetted declaration for the macOS leaf of the Apple family. macOS is not a family, so it has no + * row in the family catalog: the bundled Apple owner delegates its macOS branches to this package. + */ +export const MACOS_PLATFORM_PLUGIN_DECLARATION = Object.freeze({ + package: '@agent-device/macos', + label: 'macOS desktop', + nightlyTag: 'nightly-0.22', +} as const satisfies PluginReleaseDeclaration & Readonly<{ label: string }>); + /** The `error.details.reason` a caller reads when a capability needs a plugin that is not installed. */ export const PLUGIN_INSTALLATION_REASONS = { notInstalled: 'plugin-not-installed', @@ -152,3 +162,23 @@ export function missingOptionalPlatformError(family: Platform, coreVersion: stri }, ); } + +/** + * The typed outcome for a macOS request the composition has no leaf for: `plugin-not-installed` with + * the package that provides macOS desktop automation and its installation command. iOS and tvOS + * requests never reach it, because the bundled Apple owner serves them. + */ +export function missingMacOsPlatformError(coreVersion: string): AppError { + const declaration = MACOS_PLATFORM_PLUGIN_DECLARATION; + return new AppError( + 'UNSUPPORTED_PLATFORM', + `${declaration.label} automation requires the ${declaration.package} plugin.`, + { + reason: PLUGIN_INSTALLATION_REASONS.notInstalled, + family: 'apple', + appleOs: 'macos', + package: declaration.package, + ...pluginInstallationHint(declaration, coreVersion), + }, + ); +} diff --git a/packages/contracts/src/plugin-inventory.ts b/packages/contracts/src/plugin-inventory.ts index a340df132e..56a6c9e7b6 100644 --- a/packages/contracts/src/plugin-inventory.ts +++ b/packages/contracts/src/plugin-inventory.ts @@ -18,6 +18,8 @@ type PluginInventoryIdentity = Readonly<{ provider?: string; backend?: string; platform?: string; + /** The leaf an `apple` platform claim narrows to: the macOS desktop mechanics. */ + appleOs?: 'macos'; source: PluginSource; package?: string; version?: string; @@ -88,6 +90,10 @@ function readEntry(value: unknown): PluginInventoryEntry | undefined { ...(typeof value.provider === 'string' ? { provider: value.provider } : {}), ...(typeof value.backend === 'string' ? { backend: value.backend } : {}), ...(typeof value.platform === 'string' ? { platform: value.platform } : {}), + // A leaf is read only beside the family it narrows: macOS under `apple`. + ...(value.platform === 'apple' && value.appleOs === 'macos' + ? { appleOs: 'macos' as const } + : {}), source: value.source, ...(typeof value.package === 'string' ? { package: value.package } : {}), ...(typeof value.version === 'string' ? { version: value.version } : {}), diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts index 8482b59661..a6aa279d54 100644 --- a/packages/plugins/src/platform.test.ts +++ b/packages/plugins/src/platform.test.ts @@ -2,7 +2,11 @@ import { expect, test } from 'vitest'; import { pluginHome, selectPlugin } from '@agent-device/test-kit'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { storePluginCandidates } from './store.ts'; -import { resolveProviderPlugins, startProviderRegistry } from './registry.ts'; +import { + resolveProviderPlugins, + startProviderRegistry, + type PluginCandidate, +} from './registry.ts'; const WEB_PACKAGE = '@agent-device/web'; const stateDir = '/fixture-state'; @@ -37,10 +41,18 @@ function selectWeb(home: string, opts: Parameters[3] = {}) ); } -async function startStore(env: HostEnvironment['env']) { +/** The bundled Apple owner's reserved family claim, as the composition root declares it. */ +const builtinApple = { + source: 'builtin', + dormant: true, + declaredClaims: [{ kind: 'platform', id: 'apple' }], + load: () => undefined, +} as const; + +async function startStore(env: HostEnvironment['env'], builtins: readonly PluginCandidate[] = []) { const candidates = await storePluginCandidates(env); const host = { env, cwd: '/' }; - const resolved = await resolveProviderPlugins(candidates); + const resolved = await resolveProviderPlugins([...builtins, ...candidates]); return await startProviderRegistry(resolved, host, { platformHost: { ...host, @@ -182,3 +194,92 @@ test('platform and replay claims in one package activate independently', async ( expect(registry.platforms.map(({ family }) => family)).toEqual(['web']); await registry.close(); }); + +const MACOS_PACKAGE = '@agent-device/macos'; +const macOsLeafClaim = `{ + kind: 'platform', + family: 'apple', + appleOs: 'macos', + setup: host => ({ family: 'apple', appleOs: 'macos', bind: () => ({ stateDir: host.stateDir }) }), +}`; + +function selectMacOsLeaf(home: string, name = MACOS_PACKAGE) { + selectPlugin( + home, + name, + `export default () => ({ apiVersion: 3, contributes: [${macOsLeafClaim}] });`, + { claims: { apiVersion: 3, platform: 'apple', appleOs: 'macos' } }, + ); +} + +test('a macOS leaf claim coexists with the bundled apple family claim and registers no family', async () => { + const { home, env } = pluginHome(); + selectMacOsLeaf(home); + const registry = await startStore(env, [builtinApple]); + expect(registry.inventory).toMatchObject([ + { source: 'store', package: MACOS_PACKAGE, platform: 'apple', appleOs: 'macos', state: 'active' }, + ]); + expect(registry.platforms).toEqual([]); + expect(registry.platformLeaves.map(({ family, appleOs }) => `${family}:${appleOs}`)).toEqual([ + 'apple:macos', + ]); + await expect(registry.close()).resolves.toMatchObject([ + { platform: 'apple', appleOs: 'macos', source: 'store' }, + ]); +}); + +test('a second package loses the macOS leaf, and a package cannot take the apple family', async () => { + const { home, env } = pluginHome(); + selectMacOsLeaf(home); + selectMacOsLeaf(home, 'later-macos'); + selectPlugin(home, 'whole-apple', "throw new Error('must never import');", { + claims: { apiVersion: 3, platform: 'apple' }, + }); + const registry = await startStore(env, [builtinApple]); + expect( + registry.inventory.map((entry) => [ + entry.package, + entry.appleOs, + entry.state === 'failed' ? entry.error.reason : entry.state, + ]), + ).toEqual([ + [MACOS_PACKAGE, 'macos', 'active'], + ['later-macos', 'macos', 'duplicate_platform'], + ['whole-apple', undefined, 'duplicate_platform'], + ]); + expect(registry.platformLeaves).toHaveLength(1); + await registry.close(); +}); + +test.each([ + ['another family', { apiVersion: 3, platform: 'web', appleOs: 'macos' }], + ['an Apple OS the owner keeps', { apiVersion: 3, platform: 'apple', appleOs: 'ios' }], +])('a leaf declared for %s is refused before its entry is imported', async (_name, claims) => { + const { home, env } = pluginHome(); + selectPlugin(home, 'bad-leaf', "throw new Error('must never import');", { claims }); + const registry = await startStore(env, [builtinApple]); + expect(registry.inventory).toMatchObject([ + { package: 'bad-leaf', state: 'failed', error: { reason: 'invalid_plugin' } }, + ]); + expect(registry.platformLeaves).toEqual([]); + await registry.close(); +}); + +test('a leaf setup that binds nothing is recorded as failed', async () => { + const { home, env } = pluginHome(); + selectPlugin( + home, + MACOS_PACKAGE, + `export default () => ({ apiVersion: 3, contributes: [{ + kind: 'platform', family: 'apple', appleOs: 'macos', + setup: () => ({ family: 'apple', appleOs: 'macos' }), + }] });`, + { claims: { apiVersion: 3, platform: 'apple', appleOs: 'macos' } }, + ); + const registry = await startStore(env, [builtinApple]); + expect(registry.inventory).toMatchObject([ + { appleOs: 'macos', state: 'failed', error: { reason: 'invalid_plugin' } }, + ]); + expect(registry.platformLeaves).toEqual([]); + await registry.close(); +}); diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index 3090e501ae..ca47e095c5 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -13,6 +13,7 @@ import type { } from '@agent-device/contracts/platform-plugin'; import type { PlatformRuntimeModule } from '@agent-device/contracts/platform-runtime-operations'; import type { LinuxToolProvider } from '@agent-device/contracts/linux-tool-provider'; +import type { MacOsPlatformLeafRegistration } from '@agent-device/contracts/macos-platform-leaf'; import type { HostOperatingSystem, OwnedProcessRecord, @@ -304,11 +305,25 @@ export type RegisteredPlatformSetup = Family }> : never; -export type PlatformContribution = { - [Family in Platform]: Readonly<{ - kind: 'platform'; - family: Family; - /** Registers modules and operations. Setup itself does not start or install the backend. */ - setup(host: PlatformHost): PlatformSetup | Promise>; - }>; -}[Platform]; +export type PlatformContribution = + | { + [Family in Platform]: Readonly<{ + kind: 'platform'; + family: Family; + appleOs?: never; + /** Registers modules and operations. Setup itself does not start or install the backend. */ + setup(host: PlatformHost): PlatformSetup | Promise>; + }>; + }[Platform] + | MacOsPlatformLeafContribution; + +/** + * The one leaf contribution: macOS desktop automation under the bundled `apple` family. The Apple + * owner keeps the family claim and calls what this setup registers at its macOS branches. + */ +export type MacOsPlatformLeafContribution = Readonly<{ + kind: 'platform'; + family: 'apple'; + appleOs: 'macos'; + setup(host: PlatformHost): MacOsPlatformLeafRegistration | Promise; +}>; diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index c541e99a1d..43d90dda4a 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -1,4 +1,5 @@ import type { PlatformHost, RegisteredPlatformSetup } from './platform.ts'; +import type { MacOsPlatformLeafRegistration } from '@agent-device/contracts/macos-platform-leaf'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { NATIVE_REPLAY_BACKEND, @@ -105,15 +106,25 @@ export type ProviderRegistration = Readonly<{ dispose?: () => Promise | void; }>; -/** Every id held in one claim space. */ +/** Every claim held in one claim space, keyed so a leaf claim is a different holding than its id. */ type ClaimedClaims = Map>; +/** + * What one claim occupies in its space: the id, with the leaf appended when the claim narrows. The + * spaces compare this rather than the bare id, so the `apple` family claim and a package's macOS leaf + * holding coexist and two packages cannot both hold the same leaf. + */ +function claimHolding(claim: PluggedClaim): string { + return claim.appleOs === undefined ? claim.id : `${claim.id}:${claim.appleOs}`; +} + type Claim = PluggedClaim & { slot: Slot; contribution: Contribution; failure?: AppError; registration?: ProviderRegistration; platformSetup?: RegisteredPlatformSetup; + platformLeaf?: MacOsPlatformLeafRegistration; replaySetup?: ReplayBackendSetup | ReplayExecutionSetup; replayLoading?: Promise; executionLoading?: Promise; @@ -144,6 +155,8 @@ export type ResolvedProviderPlugins = Readonly<{ export type ProviderRegistry = Readonly<{ registrations: readonly ProviderRegistration[]; platforms: readonly RegisteredPlatformSetup[]; + /** The leaf setups: operations a bundled family's owner delegates to an installed package. */ + platformLeaves: readonly MacOsPlatformLeafRegistration[]; resolveReplayBackend: ReplayBackendResolver; resolveReplayExecution: ReplayExecutionResolver; claimedProviders: readonly string[]; @@ -224,8 +237,9 @@ function claimObstacle(claimed: ClaimedClaims, claim: PluggedClaim): AppError | function reserveClaim(claimed: ClaimedClaims, claim: PluggedClaim): boolean { let ids = claimed.get(claim.kind); if (ids === undefined) claimed.set(claim.kind, (ids = new Set())); - if (ids.has(claim.id)) return false; - ids.add(claim.id); + const holding = claimHolding(claim); + if (ids.has(holding)) return false; + ids.add(holding); return true; } @@ -328,6 +342,9 @@ export async function startProviderRegistry( platforms: Object.freeze( claims.flatMap(({ platformSetup }) => (platformSetup ? [platformSetup] : [])), ), + platformLeaves: Object.freeze( + claims.flatMap(({ platformLeaf }) => (platformLeaf ? [platformLeaf] : [])), + ), claimedProviders: resolved.claimedProviders, inventory, resolveReplayBackend: async (id, host, packageName) => { @@ -362,7 +379,8 @@ export async function startProviderRegistry( close: once(async () => { closed = true; const activated = claims.filter( - (claim) => claim.registration || claim.replaySetup || claim.platformSetup, + (claim) => + claim.registration || claim.replaySetup || claim.platformSetup || claim.platformLeaf, ); return await Promise.all([...activated].reverse().map((claim) => cleanUpClaim(claim))); }), @@ -383,6 +401,7 @@ async function setUpClaims( claim.registration = undefined; claim.replaySetup = undefined; claim.platformSetup = undefined; + claim.platformLeaf = undefined; } } } @@ -405,9 +424,14 @@ async function setUpClaim( reason: PLUGIN_REASONS.platformHostMissing, }); const result = await contribution.setup(policy.platformHost); - claim.platformSetup = Object.freeze( - validateClaimSetup({ kind: contribution.kind, id: contribution.family }, result), + const setup = Object.freeze( + validateClaimSetup( + { kind: contribution.kind, id: contribution.family, appleOs: claim.appleOs }, + result, + ), ); + if ('bind' in setup) claim.platformLeaf = setup; + else claim.platformSetup = setup; return; } if (scope === 'platforms') return; diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index d4afbc55b3..5574eb0bac 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -1,4 +1,5 @@ import type { RegisteredPlatformSetup } from './platform.ts'; +import type { MacOsPlatformLeafRegistration } from '@agent-device/contracts/macos-platform-leaf'; import { isPlatform, type Platform } from '@agent-device/kernel/device-identity'; import { NATIVE_REPLAY_BACKEND } from '@agent-device/contracts/replay-execution'; import type { @@ -38,14 +39,54 @@ const CLAIM_ID = /^[a-z][a-z0-9-]*$/; /** The claim space one contribution kind owns. */ export type ClaimKind = 'provider' | 'platform' | 'replay-backend' | 'replay-execution'; -/** One claim: its kind's space and the id this plugin holds in it. */ -export type PluggedClaim = Readonly<{ kind: ClaimKind; id: string }>; +/** + * One claim: its kind's space, the id this plugin holds in it, and the leaf part where the space has + * one. The `platform` space narrows an Apple family claim to one Apple OS, so a managed package can + * own macOS desktop mechanics while the bundled Apple owner keeps the family claim. No other space + * narrows, and an id without a leaf claims the whole id. + */ +export type PluggedClaim = Readonly<{ kind: ClaimKind; id: string; appleOs?: PlatformClaimLeaf }>; /** How a claim's space names it in the inventory and in a cleanup outcome. */ export type ClaimIdentity = Readonly< - { provider: string } | { backend: string } | { platform: string } + | { provider: string; appleOs?: never } + | { backend: string; appleOs?: never } + | { platform: string; appleOs?: PlatformClaimLeaf } >; +/** + * The leaf part a `platform` claim key may carry: the one Apple OS the bundled Apple owner + * delegates to an installed package. iOS and tvOS stay with the owner, so they are not leaves. + */ +export type PlatformClaimLeaf = 'macos'; +type ClaimLeaf = PlatformClaimLeaf; + +/** + * The leaf a platform claim narrows to. Only `apple` narrows, and only to macOS, so this answers no + * leaf for another family or for any other value. + */ +function readClaimLeaf(value: unknown, family: string): ClaimLeaf | undefined { + return family === 'apple' && value === 'macos' ? value : undefined; +} + +/** + * The leaf one claim declares under `field`, refusing a declaration the id cannot narrow instead of + * silently widening it to the whole family. + */ +function requireClaimLeaf( + field: string | undefined, + source: Record, + id: string, +): ClaimLeaf | undefined { + const declared = field === undefined ? undefined : source[field]; + if (declared === undefined) return undefined; + const leaf = readClaimLeaf(declared, id); + if (leaf === undefined) { + throw invalidPlugin(`A platform claim narrows only apple to macos with ${field}: ${id}`); + } + return leaf; +} + /** Deterministic order for reading a package's static claims and for claim spaces. */ const CLAIM_KINDS: { readonly [Kind in ClaimKind]: ClaimKindSpec } = { provider: { @@ -64,19 +105,25 @@ const CLAIM_KINDS: { readonly [Kind in ClaimKind]: ClaimKindSpec } = { platform: { metadataField: 'platform', contributionIdField: 'family', + leafField: 'appleOs', rejectId: (id) => isPlatform(id) ? undefined : { reason: PLUGIN_REASONS.invalidPlugin, message: `Unknown platform family: ${id}` }, duplicateReason: 'duplicate_platform', - identityFor: (id) => ({ platform: id }), + identityFor: (id, appleOs) => ({ + platform: id, + ...(appleOs === undefined ? {} : { appleOs }), + }), readMetadata: (value) => readableClaimId(value, 'platform'), + readLeaf: (value, family) => readClaimLeaf(value, family), readContribution: (value) => { const id = readableClaimId(value.family, 'family'); if (typeof value.setup !== 'function') { throw invalidPlugin('A platform contribution must provide setup(host)'); } - return { kind: 'platform', id }; + const appleOs = requireClaimLeaf(CLAIM_KINDS.platform.leafField, value, id); + return { kind: 'platform', id, ...(appleOs === undefined ? {} : { appleOs }) }; }, validateSetup: validatePlatformSetup, }, @@ -147,7 +194,7 @@ const CLAIM_KINDS: { readonly [Kind in ClaimKind]: ClaimKindSpec } = { */ type ClaimSetup = { provider: undefined; - platform: RegisteredPlatformSetup; + platform: RegisteredPlatformSetup | MacOsPlatformLeafRegistration; 'replay-backend': ReplayBackendSetup; 'replay-execution': ReplayExecutionSetup; }; @@ -157,22 +204,29 @@ type ClaimKindSpec = Readonly<{ metadataField: string; /** The contribution field that spells this kind's id. */ contributionIdField: string; + /** + * The one field this space's claim reads for its leaf part, in the package manifest and in the + * contribution. Only the `platform` space declares it, and only an `apple` id has a leaf to name. + */ + leafField?: string; /** Ids no plugin may claim in this space. */ rejectId?(id: string): { reason: string; message: string } | undefined; /** What a claim that loses this space's duplicate race reports. */ duplicateReason: string; /** How this space names the claim in the inventory and in cleanup outcomes. */ - identityFor(id: string): ClaimIdentity; + identityFor(id: string, leaf?: ClaimLeaf): ClaimIdentity; /** Reads the id out of the `agent-device` field. */ readMetadata(value: unknown): string; + /** Reads the leaf part of this space's claim, answering none for an id that cannot narrow. */ + readLeaf?(value: unknown, id: string): ClaimLeaf | undefined; /** Validates one contribution of this kind and answers its claim. */ readContribution(value: Record): PluggedClaim; /** Reads the name of a malformed contribution for failure reporting. */ readNamedId?(value: unknown): string | undefined; /** Reads the identity of a refused legacy contribution. */ readLegacyClaim?(value: Record): string | undefined; - /** Checks what setup returned before the registry keeps the claim. */ - validateSetup(value: unknown, id: string): ClaimSetup[Kind]; + /** Checks what setup returned before the registry keeps the claim, for a leaf or a whole id. */ + validateSetup(value: unknown, id: string, leaf?: ClaimLeaf): ClaimSetup[Kind]; }>; /** The claim spaces, in the order a package's static claims are read and compared. */ @@ -213,9 +267,9 @@ function claimOfContribution(value: unknown): PluggedClaim { return spec.readContribution(value); } -/** One claim as the store's declared claims and the registry compare them: `kind:id`. */ +/** One claim as the store's declared claims and the registry compare them: `kind:id`, leaf last. */ export function claimKeyOf(claim: PluggedClaim): string { - return `${claim.kind}:${claim.id}`; + return `${claim.kind}:${claim.id}${claim.appleOs === undefined ? '' : `:${claim.appleOs}`}`; } /** Why a claim cannot be held at all: a reserved id belongs to the host, not to a package. */ @@ -225,7 +279,7 @@ export function reservedClaimError(claim: PluggedClaim): AppError | undefined { if (rejection) { return new AppError('INVALID_ARGS', rejection.message, { reason: rejection.reason, - ...spec.identityFor(claim.id), + ...spec.identityFor(claim.id, claim.appleOs), }); } return undefined; @@ -249,18 +303,29 @@ export function readableClaimsOfValue(value: unknown): readonly PluggedClaim[] { const readNamedId = spec.readNamedId ?? namedId; const declared = readNamedId(value[spec.metadataField]); const legacy = spec.readLegacyClaim?.(value); - const ids = declared === undefined ? namedContributionIds(value.contributes, kind) : [declared]; - return (legacy === undefined ? ids : [legacy, ...ids]).map((id) => ({ kind, id })); + const named = (id: string): PluggedClaim => { + const appleOs = spec.readLeaf?.(value[spec.leafField ?? ''], id); + return appleOs === undefined ? { kind, id } : { kind, id, appleOs }; + }; + if (declared !== undefined) return [named(declared)]; + const fromContributions = namedContributionClaims(value.contributes, kind); + return legacy === undefined ? fromContributions : [{ kind, id: legacy }, ...fromContributions]; }); } -function namedContributionIds(contributions: unknown, kind: ClaimKind): readonly string[] { +function namedContributionClaims( + contributions: unknown, + kind: ClaimKind, +): readonly PluggedClaim[] { if (!Array.isArray(contributions)) return []; - const { contributionIdField, readNamedId = namedId } = CLAIM_KINDS[kind]; + const { contributionIdField, leafField, readNamedId = namedId, readLeaf } = CLAIM_KINDS[kind]; return contributions.flatMap((contribution) => { if (!isRecord(contribution) || contribution.kind !== kind) return []; const id = readNamedId(contribution[contributionIdField]); - return id === undefined ? [] : [id]; + if (id === undefined) return []; + const leaf = leafField === undefined ? undefined : readNamedId(contribution[leafField]); + const appleOs = leaf === undefined ? undefined : readLeaf?.(leaf, id); + return [appleOs === undefined ? { kind, id } : { kind, id, appleOs }]; }); } @@ -273,13 +338,14 @@ export function duplicateClaimError(claim: PluggedClaim): AppError { const spec = CLAIM_KINDS[claim.kind]; return new AppError('INVALID_ARGS', `Duplicate ${claim.kind} claim: ${claim.id}`, { reason: spec.duplicateReason, - ...spec.identityFor(claim.id), + ...spec.identityFor(claim.id, claim.appleOs), }); } -/** How a claim's space names it: `provider` or `backend`. */ +/** How a claim's space names it: `provider`, `backend`, or `platform` with its leaf. */ export function identityOfClaim(claim: PluggedClaim): ClaimIdentity { - return CLAIM_KINDS[claim.kind].identityFor(claim.id); + const spec = CLAIM_KINDS[claim.kind]; + return spec.identityFor(claim.id, claim.appleOs); } /** Checks a setup result against the kind that asked for it. */ @@ -287,7 +353,7 @@ export function validateClaimSetup( claim: PluggedClaim & { kind: Kind }, value: unknown, ): ClaimSetup[Kind] { - return CLAIM_KINDS[claim.kind].validateSetup(value, claim.id); + return CLAIM_KINDS[claim.kind].validateSetup(value, claim.id, claim.appleOs); } /** @@ -305,17 +371,43 @@ export function readPluginPackageClaims(field: unknown): readonly PluggedClaim[] const declared = field[spec.metadataField]; if (declared === undefined) continue; const id = spec.readMetadata(declared); - assertClaimAvailable({ kind, id }); - claims.push({ kind, id }); + const appleOs = requireClaimLeaf(spec.leafField, field, id); + const claim: PluggedClaim = appleOs === undefined ? { kind, id } : { kind, id, appleOs }; + assertClaimAvailable(claim); + claims.push(claim); } return claims; } -function validatePlatformSetup(value: unknown, family: string): RegisteredPlatformSetup { +function validatePlatformSetup( + value: unknown, + family: string, + leaf?: ClaimLeaf, +): RegisteredPlatformSetup | MacOsPlatformLeafRegistration { + if (leaf !== undefined) { + assertPlatformLeafSetup(value, family, leaf); + return value; + } assertPlatformSetup(value, family); return value; } +/** A leaf registers no family modules: the family's owner calls the operations it binds. */ +function assertPlatformLeafSetup( + value: unknown, + family: string, + leaf: ClaimLeaf, +): asserts value is MacOsPlatformLeafRegistration { + if ( + !isRecord(value) || + value.family !== family || + value.appleOs !== leaf || + typeof value.bind !== 'function' + ) { + throw invalidPlugin(`Platform leaf setup must supply bind(tools): ${family}:${leaf}`); + } +} + function assertPlatformSetup( value: unknown, family: string, diff --git a/src/core/platform-plugin-absence.ts b/src/core/platform-plugin-absence.ts index 2268c853bc..26813849e3 100644 --- a/src/core/platform-plugin-absence.ts +++ b/src/core/platform-plugin-absence.ts @@ -1,6 +1,9 @@ import type { Platform } from '@agent-device/kernel/device'; import type { AppError } from '@agent-device/kernel/errors'; -import { missingOptionalPlatformError } from '@agent-device/contracts/plugin-installation'; +import { + missingMacOsPlatformError, + missingOptionalPlatformError, +} from '@agent-device/contracts/plugin-installation'; import { readVersion } from '@agent-device/host-kit/version'; /** @@ -16,3 +19,8 @@ import { readVersion } from '@agent-device/host-kit/version'; export function missingPlatformPlugin(family: Platform): AppError { return missingOptionalPlatformError(family, readVersion()); } + +/** How this runtime reports a macOS request when no package holds the macOS leaf (#4675). */ +export function missingMacOsPlatformPlugin(): AppError { + return missingMacOsPlatformError(readVersion()); +} diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index 6e001b253b..a34aa5e8b6 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -136,6 +136,7 @@ export async function composeDaemonRuntimeDeps( providerComposition.platforms, providerComposition.inventory, providerComposition.assertSelectionCurrent, + providerComposition.platformLeaves, ); const { web, vega, harmony, linux } = platforms; const hostDiagnostics = createHostDiagnostics(host, web, vega, harmony, linux); diff --git a/src/platform-runtime/installed-platforms.ts b/src/platform-runtime/installed-platforms.ts index f95a8573d2..abc03e2a0d 100644 --- a/src/platform-runtime/installed-platforms.ts +++ b/src/platform-runtime/installed-platforms.ts @@ -42,7 +42,9 @@ export async function startInstalledPlatforms( (candidate) => packages.has(candidate.package) || candidate.declaredClaims?.some( - ({ kind, id }) => kind === 'platform' && (family === undefined || id === family), + ({ kind, id, appleOs }) => + kind === 'platform' && + (family === undefined || (id === family && appleOs === undefined)), ), ); const resolved = await resolveProviderPlugins([...builtinPlatformCandidates(), ...candidates]); @@ -66,6 +68,7 @@ export async function startInstalledPlatforms( registry.platforms, registry.inventory, assertSelectionCurrent, + registry.platformLeaves, ), close: async () => { await registry.close(); diff --git a/src/platform-runtime/platform-plugins.ts b/src/platform-runtime/platform-plugins.ts index bbc90c57de..0c895e9381 100644 --- a/src/platform-runtime/platform-plugins.ts +++ b/src/platform-runtime/platform-plugins.ts @@ -10,14 +10,21 @@ import type { WebPlatformSelection, WebPlatformRegistration, } from '@agent-device/contracts/platform-plugin'; +import type { + MacOsPlatformLeafRegistration, + MacOsPlatformLeafSelection, +} from '@agent-device/contracts/macos-platform-leaf'; import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import type { Platform } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import type { PluginCandidate, ProviderRegistry } from '@agent-device/plugins/registry'; -import { getOptionalPlatformPluginDeclaration } from '@agent-device/contracts/plugin-installation'; +import { + getOptionalPlatformPluginDeclaration, + MACOS_PLATFORM_PLUGIN_DECLARATION, +} from '@agent-device/contracts/plugin-installation'; import { BUILTIN_PLATFORM_PLUGINS } from '../core/interactors/register-builtins.ts'; import { registerPlatformPluginSet } from '../core/platform-plugin-registry.ts'; -import { missingPlatformPlugin } from '../core/platform-plugin-absence.ts'; +import { missingMacOsPlatformPlugin, missingPlatformPlugin } from '../core/platform-plugin-absence.ts'; type RuntimePlatformPlugin = PlatformPlugin & { web?: WebPlatformRegistration; @@ -43,11 +50,13 @@ export function composePlatformPlugins( platforms: ProviderRegistry['platforms'], inventory: readonly PluginInventoryEntry[], assertPluginSelectionCurrent?: (packageName: string) => void, + platformLeaves: ProviderRegistry['platformLeaves'] = [], ): PlatformModuleSelection { function selectedClaim(family: Platform) { const expected = getOptionalPlatformPluginDeclaration(family)?.package; return ( - inventory.find((entry) => entry.platform === family) ?? + // A leaf entry names its family too, but it holds the leaf, not the family. + inventory.find((entry) => entry.platform === family && entry.appleOs === undefined) ?? inventory.find( (entry) => expected !== undefined && @@ -147,9 +156,53 @@ export function composePlatformPlugins( vega, harmony, linux, + macos: composeMacOsLeaf(platformLeaves, inventory, assertPluginSelectionCurrent), inventoryModules: platforms.map((platform) => platform.inventoryModule), runtimeModules: platforms.map((platform) => platform.runtimeModule), reportAbsent, assertSelectionCurrent, }; } + +/** + * The macOS leaf selection. macOS is a leaf of the bundled Apple family, so no family registry + * answers for it: `get()` is the one authority on its absence, as the optional families' selections + * are on theirs. An uninstalled package raises `plugin-not-installed` with its install command, and + * one that failed to load raises its own error. + */ +function composeMacOsLeaf( + platformLeaves: readonly MacOsPlatformLeafRegistration[], + inventory: readonly PluginInventoryEntry[], + assertPluginSelectionCurrent?: (packageName: string) => void, +): MacOsPlatformLeafSelection { + const packageName = MACOS_PLATFORM_PLUGIN_DECLARATION.package; + const active = platformLeaves.find((leaf) => leaf.appleOs === 'macos'); + const claim = + inventory.find((entry) => entry.platform === 'apple' && entry.appleOs === 'macos') ?? + inventory.find( + (entry) => + entry.package === packageName && + entry.state === 'failed' && + entry.platform === undefined && + entry.provider === undefined && + entry.backend === undefined, + ); + return { + active, + get() { + // A store selection that changed under the running process is refused before it is used. + if (assertPluginSelectionCurrent && (claim === undefined || claim.source === 'store')) { + assertPluginSelectionCurrent(claim?.package ?? packageName); + } + if (active) return active; + if (claim?.state !== 'failed') throw missingMacOsPlatformPlugin(); + const { code, message, ...details } = claim.error; + throw new AppError(code, message, { + ...details, + family: 'apple', + appleOs: 'macos', + package: claim.package, + }); + }, + }; +} diff --git a/src/provider-device-runtimes.ts b/src/provider-device-runtimes.ts index d42bd9eedd..1d5b7d10a5 100644 --- a/src/provider-device-runtimes.ts +++ b/src/provider-device-runtimes.ts @@ -16,6 +16,7 @@ import { PROVIDER_PLUGIN_POLICY } from './provider-plugin-policy.ts'; export type ProviderRuntimeComposition = Readonly<{ platforms: ProviderRegistry['platforms']; + platformLeaves: ProviderRegistry['platformLeaves']; assertSelectionCurrent?: PluginRegistryPolicy['assertSelectionCurrent']; resolveReplayBackend: import('@agent-device/plugins/replay-backend').ReplayBackendResolver; resolveReplayExecution: import('@agent-device/contracts/replay-execution').ReplayExecutionResolver; @@ -73,6 +74,7 @@ async function composeProviderRuntime( const registry = await startProviderRegistry(resolved, host, policy); return Object.freeze({ platforms: registry.platforms, + platformLeaves: registry.platformLeaves, assertSelectionCurrent: policy.assertSelectionCurrent, runtimes: Object.freeze(registry.registrations.map(({ runtime }) => runtime)), platformModules: Object.freeze( From e459d1ec94580832543709563bfbe8132c392540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 20:54:57 +0100 Subject: [PATCH 02/15] refactor(macos): scaffold the macOS platform plugin and its leaf interface `@agent-device/macos` is a managed platform plugin that contributes the leaf `{ kind: 'platform', family: 'apple', appleOs: 'macos' }`. Its `setup(host)` registers `bind(tools)`, which returns every macOS operation the bundled Apple owner delegates. The Apple owner keeps the `apple` claim and gains a leaf port. The composition binds the process's leaf selection to it, and the owner asks the port at its macOS branches. An absent package answers typed `plugin-not-installed` with the `@agent-device/macos` install command. The owner hands the leaf two capabilities per call: the Apple tool routes of the calling request, so a scoped request reaches the leaf and no command starts from the plugin's bundled host kit, and the XCTest runner bound to one macOS device for the runner's macOS wire cases. Part of #4675 --- examples/sdk/tsconfig.json | 1 + packages/build-config/src/index.ts | 7 +- packages/contracts/src/macos-platform-leaf.ts | 43 +++++- packages/contracts/src/scroll-gesture.ts | 122 +++++++++++++++ packages/platform-apple/package.json | 10 +- .../src/__tests__/macos-leaf.fixtures.ts | 53 +++++++ .../platform-apple/src/core/macos-desktop.ts | 51 +++++++ .../platform-apple/src/core/macos-runner.ts | 14 ++ .../src/macos-desktop-facade.ts | 10 ++ packages/platform-apple/src/macos-leaf.ts | 36 +++++ packages/platform-macos/build.mjs | 14 ++ packages/platform-macos/package.json | 61 ++++++++ packages/platform-macos/src/index.ts | 94 ++++++++++++ .../platform-macos/src/toolbox.fixtures.ts | 144 ++++++++++++++++++ packages/platform-macos/src/toolbox.ts | 12 ++ packages/platform-macos/tsconfig.json | 23 +++ packages/plugins/src/contract.ts | 1 + packages/plugins/src/platform.ts | 2 + pnpm-lock.yaml | 27 ++++ ...daemon-composition-platform-plugin.test.ts | 137 +++++++++++++++++ src/platform-runtime-macos-leaf.fixtures.ts | 47 ++++++ src/platform-runtime/installed-platforms.ts | 3 +- src/platform-runtime/platform-plugins.ts | 13 +- src/platform-runtime/plugin-host.ts | 1 + src/sdk/plugins.ts | 1 + tsconfig.typecheck.json | 1 + 26 files changed, 912 insertions(+), 16 deletions(-) create mode 100644 packages/platform-apple/src/__tests__/macos-leaf.fixtures.ts create mode 100644 packages/platform-apple/src/core/macos-desktop.ts create mode 100644 packages/platform-apple/src/core/macos-runner.ts create mode 100644 packages/platform-apple/src/macos-desktop-facade.ts create mode 100644 packages/platform-apple/src/macos-leaf.ts create mode 100644 packages/platform-macos/build.mjs create mode 100644 packages/platform-macos/package.json create mode 100644 packages/platform-macos/src/index.ts create mode 100644 packages/platform-macos/src/toolbox.fixtures.ts create mode 100644 packages/platform-macos/src/toolbox.ts create mode 100644 packages/platform-macos/tsconfig.json create mode 100644 src/platform-runtime-macos-leaf.fixtures.ts diff --git a/examples/sdk/tsconfig.json b/examples/sdk/tsconfig.json index d49258e64c..0752b6f6b1 100644 --- a/examples/sdk/tsconfig.json +++ b/examples/sdk/tsconfig.json @@ -60,6 +60,7 @@ { "path": "../../packages/platform-apple" }, { "path": "../../packages/platform-harmonyos" }, { "path": "../../packages/platform-linux" }, + { "path": "../../packages/platform-macos" }, { "path": "../../packages/platform-vega" }, { "path": "../../packages/platform-web" }, { "path": "../../packages/plugins" }, diff --git a/packages/build-config/src/index.ts b/packages/build-config/src/index.ts index e9ba70e3fa..63f0775b31 100644 --- a/packages/build-config/src/index.ts +++ b/packages/build-config/src/index.ts @@ -47,13 +47,14 @@ export function assertManagedPlatformPluginFactory( packageJsonUrl: URL, factory: () => { apiVersion: unknown; - contributes: readonly { kind: unknown; family: unknown }[]; + contributes: readonly { kind: unknown; family: unknown; appleOs?: unknown }[]; }, label: string, ): void { const manifest = JSON.parse(readFileSync(packageJsonUrl, 'utf8'))['agent-device'] as { apiVersion: unknown; platform: unknown; + appleOs?: unknown; }; const { apiVersion, contributes } = factory(); const [platform] = contributes; @@ -61,7 +62,9 @@ export function assertManagedPlatformPluginFactory( apiVersion !== manifest.apiVersion || contributes.length !== 1 || platform?.kind !== 'platform' || - platform.family !== manifest.platform + platform.family !== manifest.platform || + // A leaf claim is part of the pair: a package that narrows must contribute the same leaf. + platform.appleOs !== manifest.appleOs ) { throw new Error(`The managed ${label} factory must match its package claim`); } diff --git a/packages/contracts/src/macos-platform-leaf.ts b/packages/contracts/src/macos-platform-leaf.ts index 369a4a4b47..706f9ebecb 100644 --- a/packages/contracts/src/macos-platform-leaf.ts +++ b/packages/contracts/src/macos-platform-leaf.ts @@ -20,7 +20,7 @@ import type { RunnerContext, SnapshotResult, } from './interactor-types.ts'; -import type { RuntimeOperationUnavailability } from './platform-runtime.ts'; +import type { RuntimeOperationFact } from './platform-runtime.ts'; import type { ScrollExecutionOptions } from './scroll-command.ts'; import type { ScrollDirection } from './scroll-gesture.ts'; import type { MacOsHelperSurface, SessionSurface } from './session-surface.ts'; @@ -91,8 +91,15 @@ export type MacOsLeafTools = Readonly<{ args: string[], options?: MacOsCommandOptions, ): Promise; + /** + * The process table of the host these tools run on. A scoped request answers it with its own + * executor, so a probe never pairs pids from one host with tools on another. + */ + listProcesses(options: { + timeoutMs: number; + }): Promise[]>; /** Starts a command the caller stops itself, with its output captured. */ - startBackground(cmd: string, args: string[]): MacOsBackgroundProcess; + startBackground(cmd: string, args: string[]): Promise; /** The helper transport a scoped request supplies in place of the leaf's own binary. */ helper?: Readonly<{ run(args: string[], options?: MacOsCommandOptions): Promise; @@ -150,6 +157,25 @@ export type MacOsPressResult = { windowTitle?: string; }; +/** + * The interactor members the `native` app backend serves itself. The Apple owner assembles the + * session's interactor from these and from its own members that never reach the runner. + */ +export type MacOsNativeAppActions = Required< + Pick< + Interactor, + | 'tap' + | 'pressPoint' + | 'longPress' + | 'focus' + | 'type' + | 'fill' + | 'scroll' + | 'back' + | 'setOrientation' + > +>; + /** Every macOS operation the Apple owner delegates, bound to one request's tools. */ export type MacOsLeafOperations = Readonly<{ resolveApp(app: string): Promise; @@ -227,14 +253,17 @@ export type MacOsLeafOperations = Readonly<{ statusPath: string; env: Readonly; }): Promise; - /** The interactor of the `native` app backend: helper actions, with no runner request. */ - nativeAppInteractor( - base: Interactor, + /** + * The actions of the `native` app backend: helper actions, with no runner request. `base` is the + * Apple owner's interactor, which the press of another surface goes back to. + */ + nativeAppActions( + base: Pick, context: RunnerContext, env: Readonly, - ): Promise; + ): Promise; /** The operations the `native` app backend refuses at admission. */ - nativeBackendFacts(): Promise>>; + nativeBackendFacts(): Promise>>; /** The XCTest backend's desktop scroll, mapped to the runner's `desktopScroll` wire case. */ desktopScroll( runner: MacOsRunner, diff --git a/packages/contracts/src/scroll-gesture.ts b/packages/contracts/src/scroll-gesture.ts index 155f25da4e..c54cb77628 100644 --- a/packages/contracts/src/scroll-gesture.ts +++ b/packages/contracts/src/scroll-gesture.ts @@ -3,6 +3,7 @@ import { SCROLL_REASONS } from './scroll-reasons.ts'; import { defineStringEnum } from './string-enum.ts'; import { isViewportRootNode } from './snapshot-visibility.ts'; import type { Rect, SnapshotNode } from '@agent-device/kernel/snapshot'; +import type { ScrollExecutionOptions, ScrollReleaseBehavior } from './scroll-command.ts'; // What a caller may ASK for, as opposed to `ScrollDirection` (what the gesture resolves to): // `top`/`bottom` are scroll-to-extreme requests with no direction of their own, and `refresh` is one @@ -564,3 +565,124 @@ function isMeasurableRect(rect: Rect): boolean { rect.height > 0 ); } + +// How an Apple XCTest runner scroll reply becomes the scroll result every caller publishes. The +// bundled Apple owner and the macOS leaf both send scroll commands to the one runner, so the wire +// fields and the reply normalization live beside the scroll plan they are checked against. + +type NormalizedScrollOptions = { + amount?: number; + pixels?: number; + durationMs?: number; + preferProvidedPixels?: boolean; +}; + +export function normalizeAppleScrollResultWithResolvedFrame( + runnerResult: Record, + direction: ScrollDirection, + options?: ScrollExecutionOptions, + config: { includeDuration?: boolean } = { includeDuration: true }, +): Record { + const referenceWidth = readFiniteNumber(runnerResult.referenceWidth); + const referenceHeight = readFiniteNumber(runnerResult.referenceHeight); + if (referenceWidth === undefined || referenceHeight === undefined) { + return normalizeAppleScrollResult(runnerResult, { amount: options?.amount }); + } + + // Recompute the plan from the runner's resolved frame so reported pixels match the planned + // travel (TS keeps buildScrollGesturePlan for Android and recording anyway). + const plan = buildScrollGesturePlan({ + direction, + amount: options?.amount, + pixels: options?.pixels, + referenceWidth, + referenceHeight, + }); + return normalizeAppleScrollResult(runnerResult, { + amount: options?.amount, + pixels: plan.pixels, + durationMs: config?.includeDuration ? options?.durationMs : undefined, + preferProvidedPixels: true, + }); +} + +export function scrollRunnerFields( + options: ScrollExecutionOptions | undefined, + config: { includeDuration?: boolean; includeReleaseBehavior?: boolean } = {}, +): Record { + return { + ...(options?.amount !== undefined ? { amount: options.amount } : {}), + ...(options?.pixels !== undefined ? { pixels: options.pixels } : {}), + ...(config.includeDuration !== false && options?.durationMs !== undefined + ? { durationMs: options.durationMs } + : {}), + ...(config.includeReleaseBehavior !== false && options?.releaseBehavior !== undefined + ? { scrollReleaseBehavior: options.releaseBehavior } + : {}), + }; +} + +function readFiniteNumber(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) ? value : undefined; +} + +export function normalizeAppleScrollResult( + runnerResult: Record, + options?: NormalizedScrollOptions, +): Record { + const { x1, y1, x2, y2 } = remapRunnerCoordinates(runnerResult); + const referenceWidth = readFiniteNumber(runnerResult.referenceWidth); + const referenceHeight = readFiniteNumber(runnerResult.referenceHeight); + const horizontalTravel = + x1 !== undefined && x2 !== undefined ? Math.round(Math.abs(x2 - x1)) : undefined; + const verticalTravel = + y1 !== undefined && y2 !== undefined ? Math.round(Math.abs(y2 - y1)) : undefined; + const travelPixels = selectScrollTravelPixels(options, horizontalTravel, verticalTravel); + const keyboardMinY = readFiniteNumber(runnerResult.keyboardMinY); + + return { + ...(x1 !== undefined ? { x1 } : {}), + ...(y1 !== undefined ? { y1 } : {}), + ...(x2 !== undefined ? { x2 } : {}), + ...(y2 !== undefined ? { y2 } : {}), + ...(referenceWidth !== undefined ? { referenceWidth } : {}), + ...(referenceHeight !== undefined ? { referenceHeight } : {}), + // Avoidance evidence (#2500) is reported only when it happened: `referenceHeight` above already + // names the clipped axis, and a plain `false` here could not tell "no keyboard" apart from a + // platform that never runs the clip. + ...(runnerResult.keyboardAvoided === true ? { keyboardAvoided: true } : {}), + ...(keyboardMinY !== undefined ? { keyboardMinY } : {}), + ...(options?.amount !== undefined ? { amount: options.amount } : {}), + ...(travelPixels !== undefined ? { pixels: travelPixels } : {}), + ...(options?.durationMs !== undefined ? { durationMs: options.durationMs } : {}), + }; +} + +function selectScrollTravelPixels( + options: NormalizedScrollOptions | undefined, + horizontalTravel: number | undefined, + verticalTravel: number | undefined, +): number | undefined { + if (options?.preferProvidedPixels && options.pixels !== undefined) return options.pixels; + if (horizontalTravel !== undefined && horizontalTravel > 0) return horizontalTravel; + if (verticalTravel !== undefined && verticalTravel > 0) return verticalTravel; + return undefined; +} + +function remapRunnerCoordinates(runnerResult: Record): { + x1?: number; + y1?: number; + x2?: number; + y2?: number; +} { + const x = readFiniteNumber(runnerResult.x); + const y = readFiniteNumber(runnerResult.y); + const x2 = readFiniteNumber(runnerResult.x2); + const y2 = readFiniteNumber(runnerResult.y2); + return { + ...(x !== undefined ? { x1: x } : {}), + ...(y !== undefined ? { y1: y } : {}), + ...(x2 !== undefined ? { x2 } : {}), + ...(y2 !== undefined ? { y2 } : {}), + }; +} diff --git a/packages/platform-apple/package.json b/packages/platform-apple/package.json index 22d8a60e25..e0d4df834e 100644 --- a/packages/platform-apple/package.json +++ b/packages/platform-apple/package.json @@ -43,9 +43,13 @@ "types": "./src/install-artifact-facade.ts", "default": "./src/install-artifact-facade.ts" }, - "./macos": { - "types": "./src/macos-facade.ts", - "default": "./src/macos-facade.ts" + "./macos-desktop": { + "types": "./src/macos-desktop-facade.ts", + "default": "./src/macos-desktop-facade.ts" + }, + "./macos-leaf": { + "types": "./src/macos-leaf.ts", + "default": "./src/macos-leaf.ts" }, "./perf": { "types": "./src/perf-facade.ts", diff --git a/packages/platform-apple/src/__tests__/macos-leaf.fixtures.ts b/packages/platform-apple/src/__tests__/macos-leaf.fixtures.ts new file mode 100644 index 0000000000..d1bce894f7 --- /dev/null +++ b/packages/platform-apple/src/__tests__/macos-leaf.fixtures.ts @@ -0,0 +1,53 @@ +import type { + MacOsLeafOperations, + MacOsLeafTools, + MacOsPlatformLeafRegistration, +} from '@agent-device/contracts/macos-platform-leaf'; +import { missingMacOsPlatformError } from '@agent-device/contracts/plugin-installation'; +import { bindMacOsLeaf } from '../macos-leaf.ts'; + +/** One operation the Apple owner delegated to the leaf, with the arguments it passed. */ +export type MacOsLeafCall = { operation: keyof MacOsLeafOperations; args: unknown[] }; + +/** + * Binds a recording macOS leaf to the Apple owner, the way a composition with the installed + * `@agent-device/macos` package does. Each operation a test names answers the owner; any other + * operation fails the test. The package's own tests pin what the operations do. + */ +export function bindMacOsLeafFixture(answers: Partial = {}): { + calls: MacOsLeafCall[]; + /** The Apple tools the owner resolved for each delegated call, in order. */ + tools: MacOsLeafTools[]; +} { + const calls: MacOsLeafCall[] = []; + const tools: MacOsLeafTools[] = []; + const registration: MacOsPlatformLeafRegistration = { + family: 'apple', + appleOs: 'macos', + bind(requestTools) { + tools.push(requestTools); + return new Proxy({} as MacOsLeafOperations, { + get: (_target, name) => { + const operation = name as keyof MacOsLeafOperations; + return async (...args: unknown[]) => { + calls.push({ operation, args }); + const answer = answers[operation] as ((...input: unknown[]) => unknown) | undefined; + if (!answer) throw new Error(`macOS leaf fixture: no answer for ${operation}`); + return await answer(...args); + }; + }, + }); + }, + }; + bindMacOsLeaf({ active: registration, get: () => registration }); + return { calls, tools }; +} + +/** Binds the selection of a composition that has no macOS package installed. */ +export function bindAbsentMacOsLeafFixture(): void { + bindMacOsLeaf({ + get: () => { + throw missingMacOsPlatformError('0.22.0-dev'); + }, + }); +} diff --git a/packages/platform-apple/src/core/macos-desktop.ts b/packages/platform-apple/src/core/macos-desktop.ts new file mode 100644 index 0000000000..9bf187f401 --- /dev/null +++ b/packages/platform-apple/src/core/macos-desktop.ts @@ -0,0 +1,51 @@ +import type { + MacOsLeafOperations, + MacOsLeafTools, +} from '@agent-device/contracts/macos-platform-leaf'; +import { requireMacOsLeaf } from '../macos-leaf.ts'; +import { + hasScopedAppleToolProvider, + readApplePlistJson, + resolveAppleToolProvider, +} from './tool-provider.ts'; + +/** + * The macOS operations of the installed leaf, bound to the Apple tools of the calling request. + * The leaf runs every command through these tools, so a request that scopes its own Apple tools + * reaches the leaf, and no command starts from the plugin's bundled copy of the host kit. + */ +export function macOsDesktop(): MacOsLeafOperations { + return requireMacOsLeaf().bind(currentMacOsLeafTools()); +} + +function currentMacOsLeafTools(): MacOsLeafTools { + const provider = resolveAppleToolProvider(); + return { + runCommand: provider.runCommand, + // The host-kit process and exec modules load with the first call that needs them, so this + // binding stays off the eager closure of the façades that reach it (ADR 0019). + listProcesses: async ({ timeoutMs }) => { + const { listHostProcesses } = await import('@agent-device/host-kit/process'); + return await listHostProcesses({ runCommand: provider.runCommand, timeoutMs }); + }, + startBackground: async (cmd, args) => { + const { runCmdBackground } = await import('@agent-device/host-kit/command'); + const { child, wait } = runCmdBackground(cmd, args, { + allowFailure: true, + captureOutput: true, + }); + return { + ...(child.pid === undefined ? {} : { pid: child.pid }), + wait, + terminate: async () => { + child.kill('SIGTERM'); + await wait.catch(() => {}); + }, + }; + }, + ...(provider.macosHelper ? { helper: provider.macosHelper } : {}), + ...(provider.macosHost ? { host: provider.macosHost } : {}), + readPlistJson: readApplePlistJson, + scoped: hasScopedAppleToolProvider(), + }; +} diff --git a/packages/platform-apple/src/core/macos-runner.ts b/packages/platform-apple/src/core/macos-runner.ts new file mode 100644 index 0000000000..95145e2839 --- /dev/null +++ b/packages/platform-apple/src/core/macos-runner.ts @@ -0,0 +1,14 @@ +import type { MacOsRunner } from '@agent-device/contracts/macos-platform-leaf'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { runAppleRunnerCommand } from './runner-client.ts'; + +/** + * The Apple XCTest runner bound to one macOS device. The owner keeps the runner's build, session, + * and transport; the leaf sends only the runner's macOS wire cases through this capability. + */ +export function macOsRunner( + device: DeviceInfo, + run: typeof runAppleRunnerCommand = runAppleRunnerCommand, +): MacOsRunner { + return { run: async (command, options) => await run(device, command, options) }; +} diff --git a/packages/platform-apple/src/macos-desktop-facade.ts b/packages/platform-apple/src/macos-desktop-facade.ts new file mode 100644 index 0000000000..a92a2117f2 --- /dev/null +++ b/packages/platform-apple/src/macos-desktop-facade.ts @@ -0,0 +1,10 @@ +import type { MacOsLeafOperations } from '@agent-device/contracts/macos-platform-leaf'; + +/** + * The macOS operations of the installed leaf, bound to the Apple tools of the calling request. The + * binding loads with the first macOS call, so importing this façade evaluates no Apple mechanics. + */ +export async function macOsDesktop(): Promise { + const { macOsDesktop: bind } = await import('./core/macos-desktop.ts'); + return bind(); +} diff --git a/packages/platform-apple/src/macos-leaf.ts b/packages/platform-apple/src/macos-leaf.ts new file mode 100644 index 0000000000..916de189ad --- /dev/null +++ b/packages/platform-apple/src/macos-leaf.ts @@ -0,0 +1,36 @@ +import type { + MacOsPlatformLeafRegistration, + MacOsPlatformLeafSelection, +} from '@agent-device/contracts/macos-platform-leaf'; +import { missingMacOsPlatformError } from '@agent-device/contracts/plugin-installation'; +import { readVersion } from '@agent-device/host-kit/version'; + +/** + * The macOS leaf port of the bundled Apple owner (ADR 0034, issue #4675). + * + * The owner keeps the `apple` family claim and every iOS and tvOS route. macOS desktop automation + * belongs to the managed `@agent-device/macos` package, which holds the leaf claim. The composition + * root binds the process's leaf selection here once, and every macOS branch of the owner asks this + * port for the leaf. The port is process-wide because the owner's entry points take a device, not + * a composition. + */ +let boundSelection: MacOsPlatformLeafSelection | undefined; + +/** Binds the composition's macOS leaf selection. The last composition of a process wins. */ +export function bindMacOsLeaf(selection: MacOsPlatformLeafSelection): void { + boundSelection = selection; +} + +/** Whether a package holds the macOS leaf, which decides if this host lists its Mac as a device. */ +export function isMacOsLeafInstalled(): boolean { + return boundSelection?.active !== undefined; +} + +/** + * The installed macOS leaf. An absent package raises the typed `plugin-not-installed` outcome with + * the install command; a package that failed to load raises its own error. + */ +export function requireMacOsLeaf(): MacOsPlatformLeafRegistration { + if (!boundSelection) throw missingMacOsPlatformError(readVersion()); + return boundSelection.get(); +} diff --git a/packages/platform-macos/build.mjs b/packages/platform-macos/build.mjs new file mode 100644 index 0000000000..e22f0da9d9 --- /dev/null +++ b/packages/platform-macos/build.mjs @@ -0,0 +1,14 @@ +import { build } from 'tsdown'; +import { + assertManagedPlatformPluginFactory, + managedPlatformPluginBuildConfig, +} from '@agent-device/build-config'; +import macOsPlatformPlugin from './src/index.ts'; + +assertManagedPlatformPluginFactory( + new URL('./package.json', import.meta.url), + macOsPlatformPlugin, + 'macOS', +); + +await build(managedPlatformPluginBuildConfig); diff --git a/packages/platform-macos/package.json b/packages/platform-macos/package.json new file mode 100644 index 0000000000..48a415b2b2 --- /dev/null +++ b/packages/platform-macos/package.json @@ -0,0 +1,61 @@ +{ + "name": "@agent-device/macos", + "version": "0.22.0-dev", + "private": true, + "type": "module", + "description": "Managed macOS desktop platform plugin for agent-device.", + "exports": { + "./agent-device": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "devDependencies": { + "@agent-device/build-config": "workspace:*", + "@agent-device/capture-kit": "workspace:*", + "@agent-device/contracts": "workspace:*", + "@agent-device/host-kit": "workspace:*", + "@agent-device/kernel": "workspace:*", + "@agent-device/provision-kit": "workspace:*", + "@agent-device/test-kit": "workspace:*", + "agent-device": "workspace:*" + }, + "engines": { + "node": ">=22.12" + }, + "files": [ + "dist", + "macos-helper", + "!macos-helper/**/.build", + "!macos-helper/Tests/**", + "macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift", + "macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift" + ], + "license": "MIT", + "agent-device": { + "apiVersion": 3, + "platform": "apple", + "appleOs": "macos" + }, + "scripts": { + "build": "node --experimental-strip-types build.mjs", + "build:helper": "node --experimental-strip-types ../../scripts/swift-toolchain-tmpdir.ts swift build -c release --package-path macos-helper", + "test:helper": "node --experimental-strip-types ../../scripts/swift-toolchain-tmpdir.ts swift test --package-path macos-helper", + "prepack": "pnpm build" + }, + "publishConfig": { + "exports": { + "./agent-device": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + } + }, + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/callstack/agent-device.git", + "directory": "packages/platform-macos" + }, + "homepage": "https://agent-device.dev/docs/commands#macos-desktop-targets" +} diff --git a/packages/platform-macos/src/index.ts b/packages/platform-macos/src/index.ts new file mode 100644 index 0000000000..f362e97653 --- /dev/null +++ b/packages/platform-macos/src/index.ts @@ -0,0 +1,94 @@ +import type { MacOsPlatformLeafContribution, PlatformHost } from 'agent-device/plugins'; +import type { + MacOsLeafOperations, + MacOsLeafTools, + MacOsPlatformLeafRegistration, +} from '@agent-device/contracts/macos-platform-leaf'; +import type { MacOsToolbox } from './toolbox.ts'; + +/** + * The implementation modules, each resolved exactly once per process. The façade must stay + * metadata-eager (ADR 0019), so a module enters with the first operation that needs it. Only the + * modules are memoized: each `bind` carries its own host and tools. + */ +let appsModule: Promise | undefined; +const loadApps = () => (appsModule ??= import('./apps.ts')); + +let helperModule: Promise | undefined; +const loadHelper = () => (helperModule ??= import('./helper.ts')); + +let runnerCommandsModule: Promise | undefined; +const loadRunnerCommands = () => (runnerCommandsModule ??= import('./runner-commands.ts')); + +/** Every macOS operation the Apple owner delegates, bound to one request's tools. */ +function bindMacOsOperations(box: MacOsToolbox): MacOsLeafOperations { + return Object.freeze({ + resolveApp: async (app) => await (await loadApps()).resolveMacOsApp(box, app), + resolveAppDeviceOpenTarget: async (device, target) => + await (await loadApps()).resolveMacOsAppDeviceOpenTarget(box, device, target), + openApp: async (device, app, options) => + await (await loadApps()).openMacOsApp(box, device, app, options), + closeApp: async (device, app, env) => + await (await loadApps()).closeMacOsApp(box, device, app, env), + listApps: async (filter) => await (await loadApps()).listMacApps(box, filter), + readClipboardText: async () => await (await loadApps()).readMacOsClipboardText(box), + writeClipboardText: async (text) => await (await loadApps()).writeMacOsClipboardText(box, text), + setAppearance: async (state) => await (await loadApps()).setMacOsAppearance(box, state), + frontmostApp: async (env) => await (await loadHelper()).resolveFrontmostMacOsApp(box, env), + runPermissionAction: async (action, target, env) => + await (await loadHelper()).runMacOsPermissionAction(box, action, target, env), + runAlertAction: async (action, options) => + await (await loadHelper()).runMacOsAlertAction(box, action, options), + readTextAtPoint: async (x, y, options) => + await (await loadHelper()).runMacOsReadTextAction(box, x, y, options), + press: async (x, y, options) => + await (await loadHelper()).runMacOsPressAction(box, x, y, options), + screenshot: async (outPath, options) => + await (await loadHelper()).runMacOsScreenshotAction(box, outPath, options), + captureSurfaceSnapshot: async (options, signal, env) => { + const { captureMacOsSurfaceSnapshot } = await import('./surface-snapshot.ts'); + return await captureMacOsSurfaceSnapshot(box, options, signal, env); + }, + startAudioProbe: async (options) => + await (await loadHelper()).startMacOsAudioProbeProcess(box, options), + nativeAppActions: async (base, context, env) => { + const { macOsNativeAppActions } = await import('./native-app-actions.ts'); + return macOsNativeAppActions(box, base, context, env); + }, + nativeBackendFacts: async () => + (await import('./native-backend-facts.ts')).MACOS_NATIVE_BACKEND_FACTS, + desktopScroll: async (runner, context, runnerOptions, direction, options) => + await ( + await loadRunnerCommands() + ).runMacOsDesktopScroll(runner, context, runnerOptions, direction, options), + alternateClick: async (runner, context, runnerOptions, point, button) => + await ( + await loadRunnerCommands() + ).runMacOsAlternateClick(runner, context, runnerOptions, point, button), + } satisfies MacOsLeafOperations); +} + +function macOsPlatformPlugin() { + return { + apiVersion: 3, + contributes: [ + { + kind: 'platform', + family: 'apple', + appleOs: 'macos', + // The leaf registers no family module: the bundled Apple owner keeps the `apple` claim and + // calls what `bind` returns at its macOS branches. Importing this package evaluates nothing + // but itself, and `setup` starts no process and builds no helper. + setup(host: PlatformHost): MacOsPlatformLeafRegistration { + return { + family: 'apple', + appleOs: 'macos', + bind: (tools: MacOsLeafTools) => bindMacOsOperations({ host, tools }), + }; + }, + }, + ], + } satisfies { apiVersion: 3; contributes: [MacOsPlatformLeafContribution] }; +} + +export { macOsPlatformPlugin as default }; diff --git a/packages/platform-macos/src/toolbox.fixtures.ts b/packages/platform-macos/src/toolbox.fixtures.ts new file mode 100644 index 0000000000..166b3402c3 --- /dev/null +++ b/packages/platform-macos/src/toolbox.fixtures.ts @@ -0,0 +1,144 @@ +import { accessSync, constants } from 'node:fs'; +import type { PlatformHost } from 'agent-device/plugins'; +import type { + MacOsBackgroundProcess, + MacOsCommandOptions, + MacOsCommandResult, + MacOsHostProvider, + MacOsLeafTools, +} from '@agent-device/contracts/macos-platform-leaf'; +import { acquireProcessLock, withProcessLock } from '@agent-device/host-kit/file'; +import { listHostProcesses, readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import type { MacOsToolbox } from './toolbox.ts'; + +type RunCommand = ( + cmd: string, + args: string[], + options?: MacOsCommandOptions, +) => Promise; + +/** One diagnostic the plugin recorded through the host. */ +export type MacOsHostDiagnostic = Readonly<{ + level?: string; + phase: string; + data?: Record; +}>; + +export type MacOsToolboxFixture = MacOsToolbox & + Readonly<{ + /** Every diagnostic the plugin recorded through the host, in order. */ + diagnostics: MacOsHostDiagnostic[]; + /** Every lock the plugin asked the host to hold, in order. */ + locks: { lockDirPath: string; timeoutMs: number; signal?: AbortSignal }[]; + /** Every background command the plugin started, in order. */ + background: { cmd: string; args: string[] }[]; + }>; + +const unexpectedCommand: RunCommand = async (cmd, args) => { + throw new Error(`macos-toolbox-fixture: unexpected command ${[cmd, ...args].join(' ')}`); +}; + +/** + * Binds the plugin's operations to an in-memory host and to the Apple tools a test names, the way + * the Apple owner hands them in for one request. Nothing spawns unless the test's own `runCommand` + * does. Naming any tool marks the toolbox as scoped, exactly as a request that scopes its Apple + * tools is. + */ +export function macOsToolboxFixture( + input: Readonly<{ + runCommand?: RunCommand; + macosHelper?: { + run(args: string[], options?: MacOsCommandOptions): Promise; + }; + macosHost?: MacOsHostProvider; + plist?: { readJson(path: string): Promise | null> }; + scoped?: boolean; + hostOs?: PlatformHost['hostOs']; + /** Receives every diagnostic as well, for a test that asserts on a spy. */ + emitDiagnostic?: (event: MacOsHostDiagnostic) => void; + }> = {}, +): MacOsToolboxFixture { + const runCommand = input.runCommand ?? unexpectedCommand; + const diagnostics: MacOsHostDiagnostic[] = []; + const locks: MacOsToolboxFixture['locks'] = []; + const background: MacOsToolboxFixture['background'] = []; + const tools: MacOsLeafTools = { + runCommand, + listProcesses: async ({ timeoutMs }) => + await listHostProcesses({ + runCommand: async (cmd, args, options) => + await runCommand(cmd, args, { + timeoutMs: options.timeoutMs, + allowFailure: options.allowFailure, + }), + timeoutMs, + }), + startBackground: async (cmd, args): Promise => { + background.push({ cmd, args }); + return { + pid: 4242, + wait: Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }), + terminate: async () => {}, + }; + }, + ...(input.macosHelper ? { helper: input.macosHelper } : {}), + ...(input.macosHost ? { host: input.macosHost } : {}), + readPlistJson: async (plistPath) => { + if (input.plist) return await input.plist.readJson(plistPath); + const result = await runCommand('plutil', ['-convert', 'json', '-o', '-', plistPath], { + allowFailure: true, + }); + if (result.exitCode !== 0 || !result.stdout.trim()) return null; + return JSON.parse(result.stdout) as Record; + }, + scoped: + input.scoped ?? + (input.runCommand !== undefined || + input.macosHelper !== undefined || + input.macosHost !== undefined), + }; + const host = { + env: {}, + cwd: '/', + stateDir: '/fixture-state', + hostOs: input.hostOs ?? 'darwin', + emitDiagnostic: (event: MacOsHostDiagnostic) => { + diagnostics.push(event); + input.emitDiagnostic?.(event); + }, + isFileExecutable: async (candidate: string) => { + try { + accessSync(candidate, constants.X_OK); + return true; + } catch { + return false; + } + }, + processes: { + withLock: async (params: { + lockDirPath: string; + timeoutMs: number; + signal?: AbortSignal; + task: () => Promise; + }) => { + locks.push({ + lockDirPath: params.lockDirPath, + timeoutMs: params.timeoutMs, + ...(params.signal ? { signal: params.signal } : {}), + }); + // The real host lock, taken the way the core's plugin host takes it. + return await withProcessLock({ + acquire: async () => + await acquireProcessLock({ + lockDirPath: params.lockDirPath, + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + timeoutMs: params.timeoutMs, + ...(params.signal ? { signal: params.signal } : {}), + }), + task: params.task, + }); + }, + }, + } as unknown as PlatformHost; + return { host, tools, diagnostics, locks, background }; +} diff --git a/packages/platform-macos/src/toolbox.ts b/packages/platform-macos/src/toolbox.ts new file mode 100644 index 0000000000..2a4353de6b --- /dev/null +++ b/packages/platform-macos/src/toolbox.ts @@ -0,0 +1,12 @@ +import type { PlatformHost } from 'agent-device/plugins'; +import type { MacOsLeafTools } from '@agent-device/contracts/macos-platform-leaf'; + +/** + * What every macOS operation runs with: the host the plugin was set up with, and the Apple tool + * routes the Apple owner resolved for the request that called it. Commands go through `tools`, so a + * request that scopes its own Apple tools reaches them. Locks, diagnostics, and machine facts go + * through `host`. Nothing here starts a process from the plugin's own copy of the host kit. + */ +export type MacOsToolbox = Readonly<{ host: PlatformHost; tools: MacOsLeafTools }>; + +export type MacOsRunCommand = MacOsLeafTools['runCommand']; diff --git a/packages/platform-macos/tsconfig.json b/packages/platform-macos/tsconfig.json new file mode 100644 index 0000000000..5acae24d04 --- /dev/null +++ b/packages/platform-macos/tsconfig.json @@ -0,0 +1,23 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": true, + "noEmit": false, + "emitDeclarationOnly": true, + "declaration": true, + "declarationDir": "./dist-types", + "rootDir": ".", + "paths": { "agent-device/plugins": ["./node_modules/agent-device/src/sdk/plugins.ts"] }, + "tsBuildInfoFile": "./dist-types/index.tsbuildinfo" + }, + "include": ["src"], + "references": [ + { "path": "../build-config" }, + { "path": "../capture-kit" }, + { "path": "../contracts" }, + { "path": "../host-kit" }, + { "path": "../kernel" }, + { "path": "../provision-kit" }, + { "path": "../test-kit" } + ] +} diff --git a/packages/plugins/src/contract.ts b/packages/plugins/src/contract.ts index 5562e66538..3d70c91d55 100644 --- a/packages/plugins/src/contract.ts +++ b/packages/plugins/src/contract.ts @@ -106,6 +106,7 @@ export type ProviderContribution; export type { + MacOsPlatformLeafContribution, PlatformBackgroundCommand, PlatformBackgroundProcess, PlatformContribution, diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index ca47e095c5..f34a3c14a4 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -245,6 +245,8 @@ export type PlatformHostProcesses = Readonly<{ timeoutMs: number; /** Names this lock in a timeout or an unverified release, in the request's log. */ description?: string; + /** Ends the wait for a claim the plugin cannot take when the request is cancelled. */ + signal?: AbortSignal; task: () => Promise; }): Promise; }>; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0622a1efc3..ea43727f42 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -859,6 +859,33 @@ importers: specifier: workspace:* version: link:../.. + packages/platform-macos: + devDependencies: + '@agent-device/build-config': + specifier: workspace:* + version: link:../build-config + '@agent-device/capture-kit': + specifier: workspace:* + version: link:../capture-kit + '@agent-device/contracts': + specifier: workspace:* + version: link:../contracts + '@agent-device/host-kit': + specifier: workspace:* + version: link:../host-kit + '@agent-device/kernel': + specifier: workspace:* + version: link:../kernel + '@agent-device/provision-kit': + specifier: workspace:* + version: link:../provision-kit + '@agent-device/test-kit': + specifier: workspace:* + version: link:../test-kit + agent-device: + specifier: workspace:* + version: link:../.. + packages/platform-vega: devDependencies: '@agent-device/build-config': diff --git a/src/daemon-composition-platform-plugin.test.ts b/src/daemon-composition-platform-plugin.test.ts index 7e381c4b3f..a0ab44b576 100644 --- a/src/daemon-composition-platform-plugin.test.ts +++ b/src/daemon-composition-platform-plugin.test.ts @@ -267,3 +267,140 @@ test('absent web reports the same install hint for daemon inventory, interactors }); }); }); + +const macOsPackage = '@agent-device/macos'; +const macOsDevice = { + platform: 'apple', + appleOs: 'macos', + id: 'host-macos-local', + name: 'Host Mac', + kind: 'device', + target: 'desktop', + booted: true, +} as const; +const iosSimulator = { + platform: 'apple', + appleOs: 'ios', + id: 'sim-1', + name: 'iPhone', + kind: 'simulator', + target: 'mobile', + booted: true, +} as const; + +// A macOS leaf that answers one operation from what the Apple owner hands it: the state directory +// of the host it was set up with, and the shape of the request's tools. +const macOsLeafPlugin = ` + export default () => ({ + apiVersion: 3, + contributes: [{ + kind: 'platform', + family: 'apple', + appleOs: 'macos', + setup(host) { + return { + family: 'apple', + appleOs: 'macos', + bind: (tools) => ({ + readClipboardText: async () => + [host.stateDir, typeof tools.runCommand, String(tools.scoped)].join('|'), + }), + }; + }, + }], + }); +`; + +function selectMacOsLeaf(home: string) { + selectPlugin(home, macOsPackage, macOsLeafPlugin, { + claims: { apiVersion: 3, platform: 'apple', appleOs: 'macos' }, + }); +} + +test('absent macOS reports its install hint for a macOS request and leaves iOS and tvOS to the bundled owner', async () => { + const { home, env } = pluginHome(); + const stateDir = path.join(home, 'state'); + await withDaemonComposition(env, stateDir, async (deps) => { + const gateway = deps.requestRouter.deviceInventoryGateways.localOnly; + const absent = { + code: 'UNSUPPORTED_PLATFORM', + details: expect.objectContaining({ + reason: 'plugin-not-installed', + family: 'apple', + appleOs: 'macos', + package: macOsPackage, + installCommand: expect.stringContaining('agent-device plugins add @agent-device/macos'), + hint: expect.stringContaining('agent-device plugins add @agent-device/macos'), + }), + }; + // `--platform macos` and its `apple` desktop spelling both name the leaf. + await expect(gateway.discover({ platform: 'macos' }, inventoryScope())).rejects.toMatchObject( + absent, + ); + await expect( + gateway.discover({ platform: 'apple', target: 'desktop' }, inventoryScope()), + ).rejects.toMatchObject(absent); + // A macOS command on a device named some other way meets the same outcome at its first leaf call. + const mac = await deps.interactorResolution.resolve(macOsDevice, {}); + await expect(mac.readClipboard!()).rejects.toMatchObject(absent); + // The Apple family is bundled: an iOS and a tvOS device resolve with no package installed. + for (const device of [ + iosSimulator, + { ...iosSimulator, appleOs: 'tvos', target: 'tv' }, + ] as const) { + await expect(deps.interactorResolution.resolve(device, {})).resolves.toHaveProperty('tap'); + } + expect(deps.pluginInventory.some((entry) => entry.appleOs === 'macos')).toBe(false); + }); +}); + +test('an installed macOS plugin serves the leaf the bundled apple owner delegates to', async () => { + const { home, env } = pluginHome(); + const stateDir = path.join(home, 'state'); + selectMacOsLeaf(home); + await withDaemonComposition(env, stateDir, async (deps) => { + expect(deps.pluginInventory).toContainEqual( + expect.objectContaining({ + package: macOsPackage, + platform: 'apple', + appleOs: 'macos', + source: 'store', + state: 'active', + }), + ); + // The leaf holds no family: the bundled owner still discovers, and now lists this Mac. + const devices = await deps.requestRouter.deviceInventoryGateways.localOnly.discover( + { platform: 'macos' }, + inventoryScope(), + ); + expect(devices).toEqual([ + expect.objectContaining({ platform: 'apple', appleOs: 'macos', id: 'host-macos-local' }), + ]); + // The owner's macOS branch reaches the installed leaf, with the host the leaf was set up with + // and the Apple tools of the calling request. + const mac = await deps.interactorResolution.resolve(devices[0]!, {}); + await expect(mac.readClipboard!()).resolves.toBe(`${stateDir}|function|false`); + }); +}); + +test('a macOS plugin that fails to load reports its own error instead of an install hint', async () => { + const { home, env } = pluginHome(); + const stateDir = path.join(home, 'state'); + selectPlugin(home, macOsPackage, "throw new Error('broken macOS build');", { + claims: { apiVersion: 3, platform: 'apple', appleOs: 'macos' }, + }); + await withDaemonComposition(env, stateDir, async (deps) => { + await expect( + deps.requestRouter.deviceInventoryGateways.localOnly.discover( + { platform: 'macos' }, + inventoryScope(), + ), + ).rejects.toMatchObject({ + details: expect.objectContaining({ + reason: 'plugin_load_failed', + package: macOsPackage, + appleOs: 'macos', + }), + }); + }); +}); diff --git a/src/platform-runtime-macos-leaf.fixtures.ts b/src/platform-runtime-macos-leaf.fixtures.ts new file mode 100644 index 0000000000..ad78fbd84a --- /dev/null +++ b/src/platform-runtime-macos-leaf.fixtures.ts @@ -0,0 +1,47 @@ +import { createRequire } from 'node:module'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { createLiveTestHostEnvironment } from '@agent-device/test-kit'; +import type { + MacOsPlatformLeafRegistration, + MacOsPlatformLeafSelection, +} from '@agent-device/contracts/macos-platform-leaf'; +import type { PlatformModuleSelection } from '@agent-device/contracts/platform-plugin'; +import type { PlatformHost } from '@agent-device/plugins/contract'; +import type { PluginCandidate } from '@agent-device/plugins/registry'; +import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; +import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; + +const pluginRequire = createRequire( + new URL('../packages/platform-macos/package.json', import.meta.url), +); +const { default: macOsPlatformPlugin } = (await import( + pluginRequire.resolve('@agent-device/macos/agent-device') +)) as { + default(): { contributes: [{ setup(host: PlatformHost): MacOsPlatformLeafRegistration }] }; +}; + +/** The macOS package as a host that embeds the runtime hands it to the daemon composition. */ +export function macOsPluginCandidateFixture(): PluginCandidate { + return { source: 'embedder', package: '@agent-device/macos', load: () => macOsPlatformPlugin() }; +} + +/** The macOS leaf as the managed `@agent-device/macos` package registers it. */ +export function macOsLeafSelectionFixture( + host: HostEnvironment = createLiveTestHostEnvironment(), + stateDir = '/test-macos-state', +): MacOsPlatformLeafSelection { + const active = macOsPlatformPlugin().contributes[0].setup( + createPlatformPluginHost(host, stateDir), + ); + return { active, get: () => active }; +} + +/** + * The platform selection of a process with the macOS package installed and no other platform + * plugin. Composing it binds the leaf to the bundled Apple owner, as the daemon's composition does. + */ +export function macOsPlatformCompositionFixture( + ...args: Parameters +): PlatformModuleSelection { + return composePlatformPlugins([], [], undefined, [macOsLeafSelectionFixture(...args).get()]); +} diff --git a/src/platform-runtime/installed-platforms.ts b/src/platform-runtime/installed-platforms.ts index abc03e2a0d..51ac0c5259 100644 --- a/src/platform-runtime/installed-platforms.ts +++ b/src/platform-runtime/installed-platforms.ts @@ -43,8 +43,7 @@ export async function startInstalledPlatforms( packages.has(candidate.package) || candidate.declaredClaims?.some( ({ kind, id, appleOs }) => - kind === 'platform' && - (family === undefined || (id === family && appleOs === undefined)), + kind === 'platform' && (family === undefined || (id === family && appleOs === undefined)), ), ); const resolved = await resolveProviderPlugins([...builtinPlatformCandidates(), ...candidates]); diff --git a/src/platform-runtime/platform-plugins.ts b/src/platform-runtime/platform-plugins.ts index 0c895e9381..404b3eb007 100644 --- a/src/platform-runtime/platform-plugins.ts +++ b/src/platform-runtime/platform-plugins.ts @@ -17,6 +17,7 @@ import type { import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import type { Platform } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; +import { bindMacOsLeaf } from '@agent-device/platform-apple/macos-leaf'; import type { PluginCandidate, ProviderRegistry } from '@agent-device/plugins/registry'; import { getOptionalPlatformPluginDeclaration, @@ -24,7 +25,10 @@ import { } from '@agent-device/contracts/plugin-installation'; import { BUILTIN_PLATFORM_PLUGINS } from '../core/interactors/register-builtins.ts'; import { registerPlatformPluginSet } from '../core/platform-plugin-registry.ts'; -import { missingMacOsPlatformPlugin, missingPlatformPlugin } from '../core/platform-plugin-absence.ts'; +import { + missingMacOsPlatformPlugin, + missingPlatformPlugin, +} from '../core/platform-plugin-absence.ts'; type RuntimePlatformPlugin = PlatformPlugin & { web?: WebPlatformRegistration; @@ -150,13 +154,18 @@ export function composePlatformPlugins( }, }; + // The bundled Apple owner reaches the leaf through its own port, because its entry points take a + // device rather than a composition. Binding here keeps every composition and its owner in step. + const macos = composeMacOsLeaf(platformLeaves, inventory, assertPluginSelectionCurrent); + bindMacOsLeaf(macos); + return { interactors, web, vega, harmony, linux, - macos: composeMacOsLeaf(platformLeaves, inventory, assertPluginSelectionCurrent), + macos, inventoryModules: platforms.map((platform) => platform.inventoryModule), runtimeModules: platforms.map((platform) => platform.runtimeModule), reportAbsent, diff --git a/src/platform-runtime/plugin-host.ts b/src/platform-runtime/plugin-host.ts index bdc46ba814..355cc501ce 100644 --- a/src/platform-runtime/plugin-host.ts +++ b/src/platform-runtime/plugin-host.ts @@ -180,6 +180,7 @@ function createPlatformPluginProcessPort(host: HostEnvironment): PlatformHost['p owner: { ...(await readCurrentOwnerIdentityAsync()), acquiredAtMs: Date.now() }, timeoutMs: params.timeoutMs, ...(params.description === undefined ? {} : { description: params.description }), + ...(params.signal === undefined ? {} : { signal: params.signal }), }), task: params.task, }); diff --git a/src/sdk/plugins.ts b/src/sdk/plugins.ts index 3493c0078b..a084808cf6 100644 --- a/src/sdk/plugins.ts +++ b/src/sdk/plugins.ts @@ -15,6 +15,7 @@ export type { } from '@agent-device/plugins/host'; export type { Contribution, + MacOsPlatformLeafContribution, PlatformBackgroundCommand, PlatformBackgroundProcess, PlatformContribution, diff --git a/tsconfig.typecheck.json b/tsconfig.typecheck.json index c2731d90d3..0a0b6ffca0 100644 --- a/tsconfig.typecheck.json +++ b/tsconfig.typecheck.json @@ -29,6 +29,7 @@ { "path": "packages/platform-apple" }, { "path": "packages/platform-harmonyos" }, { "path": "packages/platform-linux" }, + { "path": "packages/platform-macos" }, { "path": "packages/platform-vega" }, { "path": "packages/platform-web" }, { "path": "packages/plugins" }, From 3891979ce14e5be67fab6ddbf5daa395899dcfe4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 20:55:05 +0100 Subject: [PATCH 03/15] refactor(macos): move macOS desktop automation and its Swift helper into the plugin The published core no longer contains the macOS desktop implementation. The `os/macos` sources (both app backends' macOS code, the desktop surfaces, the LaunchServices probe, the host routes and the helper client) and the `apple/macos-helper` Swift package move to `packages/platform-macos`, and the `@agent-device/platform-apple/macos` facade is removed. Every macOS branch of the bundled Apple owner now calls the installed leaf. The owner still assembles the native backend's interactor and still owns the one XCTest runner; the leaf maps a desktop scroll and an alternate click onto the runner's `desktopScroll` and `mouseClick` wire cases through the device-bound capability the owner hands it. The runner scroll normalization both share moves beside the scroll plan in contracts. The plugin runs each command through the Apple tools the owner resolved for the request, and takes the screen-capture lock, machine facts and diagnostics from the host its setup received. `PlatformHost.processes.withLock` gains a `signal` so a cancelled request stops waiting for a held lock, as it did in core. Unfiltered discovery lists this Mac only when the package is installed, and a macOS request without it answers `plugin-not-installed`. Host system audio sampling is the helper's, so the audio probe needs the package for every family. Part of #4675 --- contracts/fixtures/runner-requests.json | 8 +- .../snapshot-visibility-viewport-root.test.ts | 4 +- .../support/handlers/session-test-harness.ts | 13 +- .../__tests__/session-device-claims.test.ts | 31 +-- .../session-close-shutdown.fixtures.ts | 9 +- .../src/__tests__/alert.test.ts | 9 +- .../__tests__/index-runner-requests.test.ts | 10 - .../interactor-macos-native-backend.test.ts | 31 +++ .../interactor-macos-surface.test.ts | 32 +-- .../interactor-screenshot-backend.test.ts | 12 +- packages/platform-apple/src/alert.ts | 4 +- .../src/app-resolution-facade.ts | 2 +- .../app-launch-accessibility.test.ts | 3 + .../__tests__/app-launch-close-quit.test.ts | 37 +-- .../src/core/__tests__/app-settings.test.ts | 101 +++----- .../core/__tests__/macos-helper-test-utils.ts | 24 -- .../src/core/__tests__/scroll.test.ts | 6 +- .../src/core/__tests__/tool-provider.test.ts | 55 ----- .../platform-apple/src/core/app-device-io.ts | 6 +- .../platform-apple/src/core/app-launch.ts | 6 +- .../platform-apple/src/core/app-resolution.ts | 17 +- .../platform-apple/src/core/app-settings.ts | 8 +- packages/platform-apple/src/core/scroll.ts | 124 +--------- .../src/core/tool-provider-types.ts | 20 +- .../platform-apple/src/core/tool-provider.ts | 7 - packages/platform-apple/src/index.test.ts | 4 +- .../platform-apple/src/interactions.test.ts | 81 +++---- packages/platform-apple/src/interactions.ts | 27 ++- packages/platform-apple/src/interactor.ts | 58 ++++- packages/platform-apple/src/inventory.test.ts | 95 +++++--- packages/platform-apple/src/inventory.ts | 13 +- packages/platform-apple/src/macos-facade.ts | 6 - .../src/os/macos/app-backend.test.ts | 16 -- .../src/os/macos/app-backend.ts | 7 - .../src/os/macos/desktop-scroll.ts | 38 --- .../src/os/macos/native-backend-facts.test.ts | 41 ---- .../src/os/macos/native-backend-facts.ts | 28 --- packages/platform-apple/src/runtime.test.ts | 12 +- packages/platform-apple/src/runtime.ts | 16 +- .../src/screenshot-support.test.ts | 3 + .../macos-helper/Package.swift | 0 .../AppWindowScreenshot.swift | 0 .../AgentDeviceMacOSHelper/AudioProbe.swift | 0 .../BackgroundInteraction.swift | 0 .../AgentDeviceMacOSHelper/GhostCursor.swift | 0 .../SnapshotTraversal.swift | 0 .../Sources/AgentDeviceMacOSHelper/main.swift | 0 .../MouseClickDelivery.swift | 0 .../MouseClickSchedule.swift | 0 .../AppWindowScreenshotTests.swift | 0 .../AudioProbeTests.swift | 0 .../BackgroundInteractionTests.swift | 5 +- .../PackStub.swift | 0 .../RectResponseTests.swift | 0 .../ScreenshotResponseTests.swift | 0 .../MouseClickScheduleTests.swift | 0 .../AgentDeviceMacOSInputTests/PackStub.swift | 0 .../macos => platform-macos/src}/apps.test.ts | 118 ++++++---- .../os/macos => platform-macos/src}/apps.ts | 69 +++--- .../src}/helper-build.test.ts | 96 ++++---- .../src}/helper-resolution.test.ts | 19 +- .../src}/helper.test.ts | 122 ++++++---- .../os/macos => platform-macos/src}/helper.ts | 222 ++++++++++-------- .../src}/host-provider.test.ts | 80 ++++++- .../src}/host-provider.ts | 55 +++-- .../src}/launch-services-registration.test.ts | 50 ++-- .../src}/launch-services-registration.ts | 63 +++-- .../src/native-app-actions.test.ts} | 47 ++-- .../src/native-app-actions.ts} | 46 ++-- .../src/native-backend-facts.test.ts | 23 ++ .../src/native-backend-facts.ts | 24 ++ .../runner-commands-runner-requests.test.ts | 41 ++++ .../platform-macos/src/runner-commands.ts | 47 ++++ .../src}/surface-snapshot.test.ts | 13 +- .../src}/surface-snapshot.ts | 13 +- src/core/__tests__/interactors.test.ts | 5 + src/core/interactors-app-events.test.ts | 5 + src/daemon-composition.test.ts | 37 +-- ...ple-application-tools-close-alerts.test.ts | 5 +- ...rm-runtime-apple-application-tools.test.ts | 12 +- ...latform-runtime-apple-application-tools.ts | 15 +- ...rm-runtime-apple-close-composition.test.ts | 13 +- src/platform-runtime-audio-probe-host.ts | 12 +- src/platform-runtime-device-inventory.test.ts | 6 + src/platform-runtime-host.test.ts | 19 +- src/platform-runtime-operation-host.test.ts | 14 +- src/platform-runtime-operation-host.ts | 4 +- 87 files changed, 1175 insertions(+), 1149 deletions(-) create mode 100644 packages/platform-apple/src/__tests__/interactor-macos-native-backend.test.ts delete mode 100644 packages/platform-apple/src/core/__tests__/macos-helper-test-utils.ts delete mode 100644 packages/platform-apple/src/macos-facade.ts delete mode 100644 packages/platform-apple/src/os/macos/app-backend.test.ts delete mode 100644 packages/platform-apple/src/os/macos/app-backend.ts delete mode 100644 packages/platform-apple/src/os/macos/desktop-scroll.ts delete mode 100644 packages/platform-apple/src/os/macos/native-backend-facts.test.ts delete mode 100644 packages/platform-apple/src/os/macos/native-backend-facts.ts rename {apple => packages/platform-macos}/macos-helper/Package.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickDelivery.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickSchedule.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSHelperTests/AppWindowScreenshotTests.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSHelperTests/AudioProbeTests.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift (97%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSHelperTests/RectResponseTests.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSHelperTests/ScreenshotResponseTests.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSInputTests/MouseClickScheduleTests.swift (100%) rename {apple => packages/platform-macos}/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift (100%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/apps.test.ts (60%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/apps.ts (75%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/helper-build.test.ts (73%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/helper-resolution.test.ts (71%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/helper.test.ts (78%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/helper.ts (79%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/host-provider.test.ts (80%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/host-provider.ts (78%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/launch-services-registration.test.ts (96%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/launch-services-registration.ts (87%) rename packages/{platform-apple/src/os/macos/native-app-interactor.test.ts => platform-macos/src/native-app-actions.test.ts} (81%) rename packages/{platform-apple/src/os/macos/native-app-interactor.ts => platform-macos/src/native-app-actions.ts} (76%) create mode 100644 packages/platform-macos/src/native-backend-facts.test.ts create mode 100644 packages/platform-macos/src/native-backend-facts.ts create mode 100644 packages/platform-macos/src/runner-commands-runner-requests.test.ts create mode 100644 packages/platform-macos/src/runner-commands.ts rename packages/{platform-apple/src/os/macos => platform-macos/src}/surface-snapshot.test.ts (78%) rename packages/{platform-apple/src/os/macos => platform-macos/src}/surface-snapshot.ts (66%) diff --git a/contracts/fixtures/runner-requests.json b/contracts/fixtures/runner-requests.json index c94294fb32..accbc1ab0e 100644 --- a/contracts/fixtures/runner-requests.json +++ b/contracts/fixtures/runner-requests.json @@ -74,12 +74,12 @@ {"name": "ios-simulator.runner-snapshot-bridge.describe", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "snapshotBridge", "appBundleId": "com.example.app", "snapshotBridge": {"verb": "describe", "requestId": "", "generation": "41:1700000000.000001", "expectedPid": 41, "expectedProcessStartTime": "1700000000.000001", "maxDepth": 128, "maxNodes": 5000, "maxDurationMs": 4000, "maxResponseBytes": 4194304}, "commandId": ""}}, {"name": "ios-simulator.runner-snapshot-bridge.describe-surface-hosts", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "snapshotBridge", "appBundleId": "com.example.app", "snapshotBridge": {"verb": "describe", "requestId": "", "generation": "41:1700000000.000001", "expectedPid": 41, "expectedProcessStartTime": "1700000000.000001", "maxDepth": 128, "maxNodes": 5000, "maxDurationMs": 4000, "maxResponseBytes": 4194304, "surfaceHostExecutables": ["SafariViewService.app/SafariViewService", "PassbookUIService.app/PassbookUIService"]}, "commandId": ""}}, {"name": "ios-simulator.runner-snapshot-bridge.target", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "snapshotBridge", "appBundleId": "com.example.app", "snapshotBridge": {"verb": "target", "requestId": "", "maxDurationMs": 4000}, "commandId": ""}}, - {"name": "macos.desktop-scroll.amount", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "desktopScroll", "direction": "down", "amount": 0.5, "durationMs": 300, "appBundleId": "com.example.app", "commandId": ""}}, - {"name": "macos.desktop-scroll.pixels", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "desktopScroll", "direction": "up", "pixels": 200, "durationMs": 300, "appBundleId": "com.example.app", "commandId": ""}}, + {"name": "macos.desktop-scroll.amount", "producer": "packages/platform-macos/src/runner-commands-runner-requests.test.ts", "request": {"command": "desktopScroll", "direction": "down", "amount": 0.5, "durationMs": 300, "appBundleId": "com.example.app"}}, + {"name": "macos.desktop-scroll.pixels", "producer": "packages/platform-macos/src/runner-commands-runner-requests.test.ts", "request": {"command": "desktopScroll", "direction": "up", "pixels": 200, "durationMs": 300, "appBundleId": "com.example.app"}}, {"name": "macos.interactions-drag.single", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "drag", "x": 100, "y": 400, "x2": 100, "y2": 200, "durationMs": 120, "appBundleId": "com.example.app", "commandId": ""}}, {"name": "macos.interactions-focus.coordinate", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "tap", "x": 10, "y": 20, "appBundleId": "com.example.app", "commandId": ""}}, - {"name": "macos.interactions-mouse-click.middle", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "mouseClick", "x": 10, "y": 20, "button": "middle", "appBundleId": "com.example.app", "commandId": ""}}, - {"name": "macos.interactions-mouse-click.secondary", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "mouseClick", "x": 10, "y": 20, "button": "secondary", "appBundleId": "com.example.app", "commandId": ""}}, + {"name": "macos.interactions-mouse-click.middle", "producer": "packages/platform-macos/src/runner-commands-runner-requests.test.ts", "request": {"command": "mouseClick", "x": 10, "y": 20, "button": "middle", "appBundleId": "com.example.app"}}, + {"name": "macos.interactions-mouse-click.secondary", "producer": "packages/platform-macos/src/runner-commands-runner-requests.test.ts", "request": {"command": "mouseClick", "x": 10, "y": 20, "button": "secondary", "appBundleId": "com.example.app"}}, {"name": "macos.interactions-single-press-tap.coordinate", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "tap", "x": 10, "y": 20, "appBundleId": "com.example.app", "commandId": ""}}, {"name": "macos.interactions-tap.coordinate", "producer": "packages/platform-apple/src/__tests__/index-runner-requests.test.ts", "request": {"command": "tap", "x": 10, "y": 20, "appBundleId": "com.example.app", "commandId": ""}}, {"name": "macos.recording-start.output-path", "producer": "src/__tests__/screen-recording-runner-requests.test.ts", "request": {"command": "recordStart", "outPath": "/tmp/capture.mp4", "appBundleId": "com.example.app"}}, diff --git a/packages/contracts/src/snapshot-visibility-viewport-root.test.ts b/packages/contracts/src/snapshot-visibility-viewport-root.test.ts index 5e0bd362aa..5eb817f76b 100644 --- a/packages/contracts/src/snapshot-visibility-viewport-root.test.ts +++ b/packages/contracts/src/snapshot-visibility-viewport-root.test.ts @@ -96,7 +96,7 @@ const ANDROID_EMITTED_TYPES = [ 'androidx.core.widget.NestedScrollView', ] as const; -// apple/macos-helper/.../SnapshotTraversal.swift `normalizedSnapshotType`. Three +// packages/platform-macos/macos-helper/.../SnapshotTraversal.swift `normalizedSnapshotType`. Three // output classes, all represented below: // 1. every one of the 13 roles the switch maps to a fixed short name; // 2. `AXWindow`, whose output is the SUBROLE unless that subrole is @@ -150,7 +150,7 @@ function macosFixedOutputsFromEmitter(): string[] { const swift = fs.readFileSync( path.join( REPO_ROOT, - 'apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift', + 'packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift', ), 'utf8', ); diff --git a/packages/daemon/src/__tests__/support/handlers/session-test-harness.ts b/packages/daemon/src/__tests__/support/handlers/session-test-harness.ts index a564848752..b1ededd0c9 100644 --- a/packages/daemon/src/__tests__/support/handlers/session-test-harness.ts +++ b/packages/daemon/src/__tests__/support/handlers/session-test-harness.ts @@ -48,12 +48,9 @@ vi.mock('@agent-device/platform-apple/runner/operations', async (importOriginal) releaseIosRunnerOnClose: vi.fn(async () => {}), }; }); -vi.mock('@agent-device/platform-apple/macos', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - runMacOsAlertAction: vi.fn(async () => {}), - }; +vi.mock('@agent-device/platform-apple/macos-desktop', () => { + const runAlertAction = vi.fn(async () => ({})); + return { macOsDesktop: async () => ({ runAlertAction }) }; }); vi.mock('@agent-device/platform-apple/app-resolution', async (importOriginal) => { const actual = @@ -103,7 +100,7 @@ import { stopIosRunnerSession, releaseIosRunnerOnClose, } from '@agent-device/platform-apple/runner/operations'; -import { runMacOsAlertAction } from '@agent-device/platform-apple/macos'; +import { macOsDesktop } from '@agent-device/platform-apple/macos-desktop'; import { resolveIosApp, resolveIosSimulatorDeepLinkBundleId, @@ -122,7 +119,7 @@ export const mockPrewarmAppleRunnerCache = vi.mocked(prewarmAppleRunnerCache); const mockPrepareIosRunner = vi.mocked(prepareIosRunner); const mockStopIosRunner = vi.mocked(stopIosRunnerSession); const mockReleaseRunnerOnClose = vi.mocked(releaseIosRunnerOnClose); -const mockDismissMacOsAlert = vi.mocked(runMacOsAlertAction); +const mockDismissMacOsAlert = vi.mocked((await macOsDesktop()).runAlertAction); export const mockResolveAndroidPackage = vi.mocked(resolveAndroidPackageForOpen); const mockCleanupRetainedMaterializedPaths = vi.mocked(cleanupRetainedMaterializedPathsForSession); export const mockRunCmd = vi.mocked(runCmd); diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-device-claims.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-device-claims.test.ts index f8ce88c60a..dfff31c449 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-device-claims.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-device-claims.test.ts @@ -64,11 +64,6 @@ import { handleSessionOpenCommands as handleProductionOpenCommand } from '../../ import { hostAppDevice, type DeviceInfo } from '@agent-device/kernel/device'; import { makeAuthoringSession } from '../../../__tests__/support/session-factories.ts'; import { AppError } from '@agent-device/kernel/errors'; -import { resolveMacOsAppDeviceOpenTarget } from '@agent-device/platform-apple/app-resolution'; -import { - createLocalAppleToolProvider, - withAppleToolProvider, -} from '@agent-device/platform-apple/tool-provider'; import { bindProviderLifecycleRuntime, bindLifecycleRuntime, @@ -799,25 +794,15 @@ test('closing another app from an app device session is refused before teardown, actions: [], }); mockDispatch.mockResolvedValue(undefined); - // The platform resolves the target as open does and refuses another app of the Mac. - // The production platform refusal, over a stubbed list of installed apps. - const provider = createLocalAppleToolProvider({ - runCommand: async () => ({ exitCode: 0, stdout: '', stderr: '' }), + // The platform resolves the target as open does and refuses another app of the Mac. The macOS + // package owns that refusal and its own tests pin it; here it arrives as its typed outcome. + resolveOpenTargetFixture.mockImplementationOnce(async () => { + throw new AppError( + 'INVALID_ARGS', + 'This session drives com.apple.TextEdit as its own device, so it cannot open or close com.apple.calculator.', + { reason: 'app-device-scope', bundleId: 'com.apple.TextEdit' }, + ); }); - const macosHost = { - ...provider.macosHost!, - listApps: async () => [ - { bundleId: 'com.apple.TextEdit', name: 'TextEdit' }, - { bundleId: 'com.apple.calculator', name: 'Calculator' }, - ], - }; - resolveOpenTargetFixture.mockImplementationOnce( - async (device, _directResolve, input) => - await withAppleToolProvider( - { ...provider, macosHost }, - async () => await resolveMacOsAppDeviceOpenTarget(device, input.target), - ), - ); const outcome = await handleCloseCommand({ host: createTestHostEnvironment(), diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-shutdown.fixtures.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-shutdown.fixtures.ts index 79dce1d00d..25d14d216e 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-shutdown.fixtures.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-shutdown.fixtures.ts @@ -23,12 +23,9 @@ vi.mock('@agent-device/platform-apple/perf', async (importOriginal) => { cleanupAppleXctracePerfCapture: vi.fn(async () => ({})), }; }); -vi.mock('@agent-device/platform-apple/macos', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - runMacOsAlertAction: vi.fn(async () => {}), - }; +vi.mock('@agent-device/platform-apple/macos-desktop', () => { + const runAlertAction = vi.fn(async () => ({})); + return { macOsDesktop: async () => ({ runAlertAction }) }; }); vi.mock('@agent-device/host-kit/command', async (importOriginal) => { const actual = await importOriginal(); diff --git a/packages/platform-apple/src/__tests__/alert.test.ts b/packages/platform-apple/src/__tests__/alert.test.ts index 4432b1a1d9..c3d2ab60b7 100644 --- a/packages/platform-apple/src/__tests__/alert.test.ts +++ b/packages/platform-apple/src/__tests__/alert.test.ts @@ -2,7 +2,10 @@ import assert from 'node:assert/strict'; import { afterEach, test, vi } from 'vitest'; vi.mock('../core/runner-client.ts', () => ({ runAppleRunnerCommand: vi.fn() })); -vi.mock('../os/macos/helper.ts', () => ({ runMacOsAlertAction: vi.fn() })); +vi.mock('../core/macos-desktop.ts', () => { + const operations = { runAlertAction: vi.fn() }; + return { macOsDesktop: () => operations }; +}); import { ALERT_MIN_READ_BUDGET_MS, @@ -17,11 +20,11 @@ import { import { AppError } from '@agent-device/kernel/errors'; import { IOS_SIMULATOR, MACOS_DEVICE } from './device-fixtures.ts'; import { runAppleRunnerCommand } from '../core/runner-client.ts'; -import { runMacOsAlertAction } from '../os/macos/helper.ts'; +import { macOsDesktop } from '../core/macos-desktop.ts'; import { actOnAppleAlert, alertIfPresent, awaitAppleAlert, readAppleAlert } from '../alert.ts'; const mockRunner = vi.mocked(runAppleRunnerCommand); -const mockHelper = vi.mocked(runMacOsAlertAction); +const mockHelper = vi.mocked(macOsDesktop().runAlertAction); const runnerOptions = {}; /** diff --git a/packages/platform-apple/src/__tests__/index-runner-requests.test.ts b/packages/platform-apple/src/__tests__/index-runner-requests.test.ts index e5dc2d336b..9941788bad 100644 --- a/packages/platform-apple/src/__tests__/index-runner-requests.test.ts +++ b/packages/platform-apple/src/__tests__/index-runner-requests.test.ts @@ -115,8 +115,6 @@ const INTERACTOR_SITES: Record = { IOS_SIMULATOR, press({ count: 2, intervalMs: 50, holdMs: 600 }), ], - 'macos.interactions-mouse-click.secondary': [MACOS_DEVICE, press({ button: 'secondary' })], - 'macos.interactions-mouse-click.middle': [MACOS_DEVICE, press({ button: 'middle' })], 'ios-simulator.interactions-single-press-double-tap.single': [ IOS_SIMULATOR, press({ doubleTap: true }), @@ -165,14 +163,6 @@ const INTERACTOR_SITES: Record = { IOS_SIMULATOR, (i) => i.scroll('left', { amount: 0.5, releaseBehavior: 'inertial' }), ], - 'macos.desktop-scroll.amount': [ - MACOS_DEVICE, - (i) => i.scroll('down', { amount: 0.5, durationMs: 300 }), - ], - 'macos.desktop-scroll.pixels': [ - MACOS_DEVICE, - (i) => i.scroll('up', { pixels: 200, durationMs: 300 }), - ], 'ios-simulator.interactor-find-text.text': [ IOS_SIMULATOR, (i) => i.findText!('Ready', { appBundleId: APP }), diff --git a/packages/platform-apple/src/__tests__/interactor-macos-native-backend.test.ts b/packages/platform-apple/src/__tests__/interactor-macos-native-backend.test.ts new file mode 100644 index 0000000000..331cd06608 --- /dev/null +++ b/packages/platform-apple/src/__tests__/interactor-macos-native-backend.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from 'vitest'; +import { createAppleInteractor } from '../interactor.ts'; +import { MACOS_DEVICE } from './device-fixtures.ts'; +import { bindMacOsLeafFixture } from './macos-leaf.fixtures.ts'; + +const nativeHost = { env: { AGENT_DEVICE_MACOS_APP_BACKEND: 'native' }, cwd: process.cwd() }; + +test('the native backend interactor takes its actions from the installed leaf and offers no runner-only member', async () => { + const leaf = bindMacOsLeafFixture({ + nativeAppActions: async () => ({ tap: async () => ({ mechanism: 'ax-press' }) }) as never, + }); + const context = { appBundleId: 'com.apple.TextEdit' }; + const interactor = createAppleInteractor(MACOS_DEVICE, context, nativeHost); + + // Assembled member by member: what only the XCTest runner serves is absent, not refused late. + expect(interactor.gestureViewport).toBeUndefined(); + expect(interactor.doubleTap).toBeUndefined(); + expect(interactor.findText).toBeUndefined(); + // Building the interactor asks the leaf nothing; the action does. + expect(leaf.calls).toEqual([]); + + await expect(interactor.tap(10, 20)).resolves.toEqual({ mechanism: 'ax-press' }); + expect(leaf.calls).toHaveLength(1); + expect(leaf.calls[0]).toMatchObject({ operation: 'nativeAppActions' }); + expect(leaf.calls[0]?.args.slice(1)).toEqual([context, nativeHost.env]); +}); + +test('the XCTest backend interactor keeps its runner members', () => { + const interactor = createAppleInteractor(MACOS_DEVICE, {}, { env: {}, cwd: process.cwd() }); + expect(interactor.findText).toBeTypeOf('function'); +}); diff --git a/packages/platform-apple/src/__tests__/interactor-macos-surface.test.ts b/packages/platform-apple/src/__tests__/interactor-macos-surface.test.ts index 35d2194e1a..85256f7e28 100644 --- a/packages/platform-apple/src/__tests__/interactor-macos-surface.test.ts +++ b/packages/platform-apple/src/__tests__/interactor-macos-surface.test.ts @@ -9,20 +9,20 @@ import { type SessionSurface, } from '@agent-device/contracts/session'; -vi.mock('../os/macos/helper.ts', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - runMacOsScreenshotAction: vi.fn(async (outPath: string) => ({ path: outPath })), - runMacOsSnapshotAction: vi.fn(async (surface: SessionSurface) => ({ - surface, +// The installed macOS leaf, as the Apple owner reaches it: one recorded entry point per helper +// operation the owner delegates. +vi.mock('../core/macos-desktop.ts', () => { + const operations = { + screenshot: vi.fn(async (outPath: string) => ({ path: outPath })), + captureSurfaceSnapshot: vi.fn(async () => ({ nodes: [], truncated: false, backend: 'macos-helper' as const, })), - runMacOsReadTextAction: vi.fn(async () => ({ text: 'helper' })), - runMacOsPressAction: vi.fn(async (x: number, y: number) => ({ x, y })), + readTextAtPoint: vi.fn(async () => ({ text: 'helper' })), + press: vi.fn(async (x: number, y: number) => ({ x, y })), }; + return { macOsDesktop: () => operations }; }); vi.mock('../core/screenshot.ts', async (importOriginal) => { @@ -43,17 +43,19 @@ vi.mock('../core/runner-client.ts', async (importOriginal) => { }); import { createAppleInteractor } from '../interactor.ts'; -import { - runMacOsPressAction, - runMacOsReadTextAction, - runMacOsScreenshotAction, - runMacOsSnapshotAction, -} from '../os/macos/helper.ts'; +import { macOsDesktop } from '../core/macos-desktop.ts'; import { captureScreenshotViaRunner, screenshotIos } from '../core/screenshot.ts'; import { runAppleRunnerCommand } from '../core/runner-client.ts'; bindTestCommandHost(); +const { + screenshot: runMacOsScreenshotAction, + captureSurfaceSnapshot: runMacOsSnapshotAction, + readTextAtPoint: runMacOsReadTextAction, + press: runMacOsPressAction, +} = macOsDesktop(); + const macOsDevice: DeviceInfo = { platform: 'apple', appleOs: 'macos', diff --git a/packages/platform-apple/src/__tests__/interactor-screenshot-backend.test.ts b/packages/platform-apple/src/__tests__/interactor-screenshot-backend.test.ts index a18f45e750..0ff6858756 100644 --- a/packages/platform-apple/src/__tests__/interactor-screenshot-backend.test.ts +++ b/packages/platform-apple/src/__tests__/interactor-screenshot-backend.test.ts @@ -10,15 +10,17 @@ vi.mock('../core/screenshot.ts', async (importOriginal) => { }; }); -vi.mock('../os/macos/helper.ts', async (importOriginal) => ({ - ...(await importOriginal()), - runMacOsScreenshotAction: vi.fn(), -})); +vi.mock('../core/macos-desktop.ts', () => { + const operations = { screenshot: vi.fn() }; + return { macOsDesktop: () => operations }; +}); import { createAppleInteractor } from '../interactor.ts'; -import { runMacOsScreenshotAction } from '../os/macos/helper.ts'; +import { macOsDesktop } from '../core/macos-desktop.ts'; import { captureScreenshotViaRunner, screenshotIos } from '../core/screenshot.ts'; +const runMacOsScreenshotAction = macOsDesktop().screenshot; + const device: DeviceInfo = { platform: 'apple', appleOs: 'ios', diff --git a/packages/platform-apple/src/alert.ts b/packages/platform-apple/src/alert.ts index 6bf69b3c8c..cdc2ee0fb2 100644 --- a/packages/platform-apple/src/alert.ts +++ b/packages/platform-apple/src/alert.ts @@ -18,7 +18,7 @@ import type { EnvMap } from '@agent-device/kernel/source-value'; import { AppError } from '@agent-device/kernel/errors'; import { sleep } from '@agent-device/host-kit/retry'; import { runAppleRunnerCommand } from './core/runner-client.ts'; -import { runMacOsAlertAction } from './os/macos/helper.ts'; +import { macOsDesktop } from './core/macos-desktop.ts'; /** * Apple's four alert legs. R59 moved them here from the daemon: how long to look for a transient @@ -56,7 +56,7 @@ function runAppleAlert( ? { surface: options.surface } : { bundleId: options?.appBundleId, surface: options?.surface }; return async (action) => - (await runMacOsAlertAction(action, { ...target, env })) as Record; + (await macOsDesktop().runAlertAction(action, { ...target, env })) as Record; } return async (action, timeoutMs) => (await runAppleRunnerCommand( diff --git a/packages/platform-apple/src/app-resolution-facade.ts b/packages/platform-apple/src/app-resolution-facade.ts index bd566a016f..e4e9f8ac7c 100644 --- a/packages/platform-apple/src/app-resolution-facade.ts +++ b/packages/platform-apple/src/app-resolution-facade.ts @@ -5,5 +5,5 @@ export { invalidateIosAppResolutionCache, resolveIosApp, resolveIosSimulatorDeepLinkBundleId, + resolveMacOsAppDeviceOpenTarget, } from './core/app-resolution.ts'; -export { resolveMacOsAppDeviceOpenTarget } from './os/macos/apps.ts'; diff --git a/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts b/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts index f6bee85501..7a00f223da 100644 --- a/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { beforeEach, test, vi } from 'vitest'; import { openIosApp } from '../app-launch.ts'; import { withFakeAppleTool } from '../../__tests__/fake-apple-tool.ts'; +import { bindMacOsLeafFixture } from '../../__tests__/macos-leaf.fixtures.ts'; import { IOS_TEST_DEVICE, IOS_TEST_SIMULATOR, @@ -97,6 +98,8 @@ for (const device of [ { ...IOS_TEST_SIMULATOR, appleOs: 'visionos' }, ] as DeviceInfo[]) { test(`does not write accessibility for ${device.kind}/${device.appleOs}`, async () => { + // A macOS open goes to the installed leaf, which starts no Apple tool of this owner. + bindMacOsLeafFixture({ openApp: async () => {} }); await withFakeAppleTool( () => '', async ({ calls }) => { diff --git a/packages/platform-apple/src/core/__tests__/app-launch-close-quit.test.ts b/packages/platform-apple/src/core/__tests__/app-launch-close-quit.test.ts index 92a0d330e4..91f01ddb5d 100644 --- a/packages/platform-apple/src/core/__tests__/app-launch-close-quit.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-launch-close-quit.test.ts @@ -1,8 +1,6 @@ import { bindTestCommandHost } from '@agent-device/test-kit'; import { beforeEach, test, vi } from 'vitest'; import assert from 'node:assert/strict'; -import { promises as fs } from 'node:fs'; -import path from 'node:path'; vi.mock('@agent-device/host-kit/command', async (importOriginal) => { const actual = await importOriginal(); @@ -22,7 +20,7 @@ import { closeIosApp } from '../app-launch.ts'; import { ensureBootedSimulator } from '../simulator.ts'; import { IOS_SIMULATOR_TERMINATE_TIMEOUT_MS } from '../config.ts'; import { runCmd } from '@agent-device/host-kit/command'; -import { withMockedMacOsHelper } from './macos-helper-test-utils.ts'; +import { bindMacOsLeafFixture } from '../../__tests__/macos-leaf.fixtures.ts'; import { IOS_TEST_SIMULATOR, MACOS_TEST_DEVICE } from './apple-core-stub-helpers.ts'; bindTestCommandHost(); @@ -36,32 +34,15 @@ beforeEach(() => { mockEnsureBootedSimulator.mockImplementation(simulatorActual.ensureBootedSimulator); }); -test('closeIosApp on macOS uses helper quit for bundle identifiers', async () => { - await withMockedMacOsHelper( - [ - '#!/bin/sh', - String.raw`printf "%s\n" "$@" > "$AGENT_DEVICE_TEST_ARGS_FILE"`, - "cat <<'JSON'", - '{"ok":true,"data":{"bundleId":"com.example.foobar","running":false,"terminated":false,"forceTerminated":false}}', - 'JSON', - '', - ].join('\n'), - async ({ tmpDir }) => { - const argsLogPath = path.join(tmpDir, 'args.log'); - const previousArgsFile = process.env.AGENT_DEVICE_TEST_ARGS_FILE; - process.env.AGENT_DEVICE_TEST_ARGS_FILE = argsLogPath; +test('closeIosApp on macOS delegates the close to the installed leaf', async () => { + const leaf = bindMacOsLeafFixture({ closeApp: async () => {} }); - try { - await closeIosApp(MACOS_TEST_DEVICE, 'com.example.foobar', undefined, process.env); - const logged = await fs.readFile(argsLogPath, 'utf8'); - assert.equal(logged, 'app\nquit\n--bundle-id\ncom.example.foobar\n'); - } finally { - if (previousArgsFile === undefined) delete process.env.AGENT_DEVICE_TEST_ARGS_FILE; - else process.env.AGENT_DEVICE_TEST_ARGS_FILE = previousArgsFile; - } - }, - { tempPrefix: 'agent-device-macos-close-helper-test-' }, - ); + await closeIosApp(MACOS_TEST_DEVICE, 'com.example.foobar', undefined, process.env); + + assert.deepEqual(leaf.calls, [ + { operation: 'closeApp', args: [MACOS_TEST_DEVICE, 'com.example.foobar', process.env] }, + ]); + assert.equal(mockRunCmd.mock.calls.length, 0); }); test('closeIosApp on iOS simulator bounds simctl terminate', async () => { diff --git a/packages/platform-apple/src/core/__tests__/app-settings.test.ts b/packages/platform-apple/src/core/__tests__/app-settings.test.ts index 8b3da532f0..35f543b95d 100644 --- a/packages/platform-apple/src/core/__tests__/app-settings.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-settings.test.ts @@ -27,7 +27,7 @@ const retryActual = await vi.importActual('../simulator.ts'); import { APP_SETTINGS_REASONS, setIosSetting } from '../app-settings.ts'; -import { withMockedMacOsHelper } from './macos-helper-test-utils.ts'; +import { bindMacOsLeafFixture } from '../../__tests__/macos-leaf.fixtures.ts'; import { ensureBootedSimulator } from '../simulator.ts'; import { AppError, @@ -209,81 +209,34 @@ test('setIosSetting touchid reports COMMAND_FAILED with the notifyutil attempt w ); }); -test('setIosSetting appearance toggle queries current osascript appearance on macOS', async () => { - await withFakeAppleTool( - (args) => { - if (args[0] !== 'osascript' || args[1] !== '-e') return unexpectedArgs(args); - const script = args[2] ?? ''; - if (script.includes('get dark mode')) return 'true'; - if (script.includes('set dark mode to false')) return ''; - return unexpectedArgs(args); - }, - async ({ calls }) => { - await setIosSetting( - MACOS_TEST_DEVICE, - 'appearance', - 'toggle', - undefined, - undefined, - process.env, - ); - const flat = calls.map((args) => args.join(' ')); - assert.equal( - flat.some((line) => line.includes('get dark mode')), - true, - flat.join('; '), - ); - assert.equal( - flat.some((line) => line.includes('set dark mode to false')), - true, - flat.join('; '), - ); - }, - ); -}); +test('setIosSetting on macOS delegates appearance and permission to the installed leaf', async () => { + const granted = { + action: 'grant' as const, + granted: true, + openedSettings: false, + requested: true, + target: 'accessibility' as const, + }; + const leaf = bindMacOsLeafFixture({ + setAppearance: async () => {}, + runPermissionAction: async () => granted, + }); -test('setIosSetting permission grant accessibility uses macOS helper', async () => { - await withMockedMacOsHelper( - [ - '#!/bin/sh', - String.raw`printf "%s\n" "$@" > "$AGENT_DEVICE_TEST_ARGS_FILE"`, - "cat <<'JSON'", - '{"ok":true,"data":{"target":"accessibility","action":"grant","granted":true,"requested":true,"openedSettings":false}}', - 'JSON', - '', - ].join('\n'), - async ({ tmpDir }) => { - const argsLogPath = path.join(tmpDir, 'args.log'); - const previousArgsFile = process.env.AGENT_DEVICE_TEST_ARGS_FILE; - process.env.AGENT_DEVICE_TEST_ARGS_FILE = argsLogPath; - - try { - const result = await setIosSetting( - MACOS_TEST_DEVICE, - 'permission', - 'grant', - undefined, - { - permissionTarget: 'accessibility', - }, - process.env, - ); - const logged = await fs.readFile(argsLogPath, 'utf8'); - assert.equal(logged, 'permission\ngrant\naccessibility\n'); - assert.deepEqual(result, { - action: 'grant', - granted: true, - openedSettings: false, - requested: true, - target: 'accessibility', - }); - } finally { - if (previousArgsFile === undefined) delete process.env.AGENT_DEVICE_TEST_ARGS_FILE; - else process.env.AGENT_DEVICE_TEST_ARGS_FILE = previousArgsFile; - } - }, - { tempPrefix: 'agent-device-macos-permission-grant-test-' }, + await setIosSetting(MACOS_TEST_DEVICE, 'appearance', 'toggle', undefined, undefined, process.env); + const result = await setIosSetting( + MACOS_TEST_DEVICE, + 'permission', + 'grant', + undefined, + { permissionTarget: 'accessibility' }, + process.env, ); + + assert.deepEqual(result, granted); + assert.deepEqual(leaf.calls, [ + { operation: 'setAppearance', args: ['toggle'] }, + { operation: 'runPermissionAction', args: ['grant', 'accessibility', process.env] }, + ]); }); test('setIosSetting rejects unsupported macOS permission deny action', async () => { diff --git a/packages/platform-apple/src/core/__tests__/macos-helper-test-utils.ts b/packages/platform-apple/src/core/__tests__/macos-helper-test-utils.ts deleted file mode 100644 index 768166e08c..0000000000 --- a/packages/platform-apple/src/core/__tests__/macos-helper-test-utils.ts +++ /dev/null @@ -1,24 +0,0 @@ -import fs from 'node:fs/promises'; -import path from 'node:path'; -import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; - -export async function withMockedMacOsHelper( - script: string, - run: (ctx: { tmpDir: string; helperPath: string }) => Promise, - options?: { tempPrefix?: string }, -): Promise { - const tmpDir = await mkdtempForTest(options?.tempPrefix ?? 'agent-device-macos-helper-test-'); - const helperPath = path.join(tmpDir, 'agent-device-macos-helper'); - await fs.writeFile(helperPath, script, 'utf8'); - await fs.chmod(helperPath, 0o755); - const previousHelperPath = process.env.AGENT_DEVICE_MACOS_HELPER_BIN; - process.env.AGENT_DEVICE_MACOS_HELPER_BIN = helperPath; - - try { - return await run({ tmpDir, helperPath }); - } finally { - if (previousHelperPath === undefined) delete process.env.AGENT_DEVICE_MACOS_HELPER_BIN; - else process.env.AGENT_DEVICE_MACOS_HELPER_BIN = previousHelperPath; - await fs.rm(tmpDir, { recursive: true, force: true }); - } -} diff --git a/packages/platform-apple/src/core/__tests__/scroll.test.ts b/packages/platform-apple/src/core/__tests__/scroll.test.ts index 53a06b73f0..71f0683ca9 100644 --- a/packages/platform-apple/src/core/__tests__/scroll.test.ts +++ b/packages/platform-apple/src/core/__tests__/scroll.test.ts @@ -1,10 +1,8 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import { AppError } from '@agent-device/kernel/errors'; -import { - normalizeAppleScrollResultWithResolvedFrame, - withAppleScrollKeyboardOcclusion, -} from '../scroll.ts'; +import { normalizeAppleScrollResultWithResolvedFrame } from '@agent-device/contracts/scroll-gesture'; +import { withAppleScrollKeyboardOcclusion } from '../scroll.ts'; test('a clipped runner frame yields travel and evidence for the band actually swiped', () => { // The runner clips the interaction frame above the keyboard and reports the clipped axis, so the diff --git a/packages/platform-apple/src/core/__tests__/tool-provider.test.ts b/packages/platform-apple/src/core/__tests__/tool-provider.test.ts index f05e26849d..b27ec9d22a 100644 --- a/packages/platform-apple/src/core/__tests__/tool-provider.test.ts +++ b/packages/platform-apple/src/core/__tests__/tool-provider.test.ts @@ -172,58 +172,3 @@ test('scoped Apple tool provider handles non-xcrun tool execution', async () => assert.equal(result.stdout, 'focused'); assert.deepEqual(calls, [['open', ['-a', 'Simulator']]]); }); - -test('local Apple tool provider exposes macOS host operations as semantic methods', async () => { - const calls: Array<[string, string[], string | undefined]> = []; - const provider = createLocalAppleToolProvider({ - runCommand: async (cmd, args, options) => { - // The bundle open's LaunchServices registration probe is the seam's own read, asserted in - // launch-services-registration.test.ts; this routing test only reports it as listing the bundle. - if (cmd === '/usr/bin/lsappinfo') { - return { exitCode: 0, stdout: 'ASN:0x0-0x1234-"Demo":\n', stderr: '' }; - } - if (cmd === 'ps') { - return { exitCode: 0, stdout: ' 1 0 /sbin/launchd\n', stderr: '' }; - } - calls.push([cmd, args, typeof options?.stdin === 'string' ? options.stdin : undefined]); - if (cmd === 'pbpaste') { - return { exitCode: 0, stdout: 'copied\r\n', stderr: '' }; - } - if (cmd === 'osascript' && args.join(' ').includes('get dark mode')) { - return { exitCode: 0, stdout: 'false\n', stderr: '' }; - } - return { exitCode: 0, stdout: '', stderr: '' }; - }, - }); - const host = provider.macosHost; - assert.ok(host); - - await host.openBundle('com.example.demo', 'demo://open'); - await host.openTarget('https://example.test'); - await host.writeClipboard('secret'); - const clipboard = await host.readClipboard(); - const darkMode = await host.readDarkMode(); - await host.setDarkMode(true); - - assert.equal(clipboard, 'copied'); - assert.equal(darkMode, false); - assert.deepEqual(calls, [ - ['open', ['-b', 'com.example.demo', 'demo://open'], undefined], - ['open', ['https://example.test'], undefined], - ['pbcopy', [], 'secret'], - ['pbpaste', [], undefined], - [ - 'osascript', - ['-e', 'tell application "System Events" to tell appearance preferences to get dark mode'], - undefined, - ], - [ - 'osascript', - [ - '-e', - 'tell application "System Events" to tell appearance preferences to set dark mode to true', - ], - undefined, - ], - ]); -}); diff --git a/packages/platform-apple/src/core/app-device-io.ts b/packages/platform-apple/src/core/app-device-io.ts index 6f4e6535a7..19d53cbcf2 100644 --- a/packages/platform-apple/src/core/app-device-io.ts +++ b/packages/platform-apple/src/core/app-device-io.ts @@ -1,14 +1,14 @@ import { isMacOs, isTvOsDevice, type DeviceInfo } from '@agent-device/kernel/device'; import { requireExecSuccess } from '@agent-device/host-kit/command'; import { ensureBootedSimulator, requireSimulatorDevice } from './simulator.ts'; -import { readMacOsClipboardText, writeMacOsClipboardText } from '../os/macos/apps.ts'; +import { macOsDesktop } from './macos-desktop.ts'; import { runSimctlForDevice } from './simctl-execution.ts'; import { runAppleRunnerCommand } from './runner-client.ts'; import type { AppleRunnerCommandOptions } from '@agent-device/apple-runner'; export async function readIosClipboardText(device: DeviceInfo): Promise { if (isMacOs(device)) { - return await readMacOsClipboardText(); + return await macOsDesktop().readClipboardText(); } requireSimulatorDevice(device, 'clipboard'); await ensureBootedSimulator(device); @@ -31,7 +31,7 @@ export async function writeIosClipboardText( runnerOptions?: AppleRunnerCommandOptions, ): Promise { if (isMacOs(device)) { - await writeMacOsClipboardText(text); + await macOsDesktop().writeClipboardText(text); return; } requireSimulatorDevice(device, 'clipboard'); diff --git a/packages/platform-apple/src/core/app-launch.ts b/packages/platform-apple/src/core/app-launch.ts index 9f296b6e3a..25bda9d271 100644 --- a/packages/platform-apple/src/core/app-launch.ts +++ b/packages/platform-apple/src/core/app-launch.ts @@ -33,7 +33,7 @@ import { import { ensureBootedSimulator } from './simulator.ts'; import { runXcrun, type ScopedSimctlCommand } from './tool-provider.ts'; import type { EnvMap } from '@agent-device/kernel/source-value'; -import { closeMacOsApp, openMacOsApp } from '../os/macos/apps.ts'; +import { macOsDesktop } from './macos-desktop.ts'; import { resolveIosApp } from './app-resolution.ts'; import { buildSimctlArgsForDevice } from './simctl.ts'; @@ -80,7 +80,7 @@ export async function openIosApp( '--launch-args is not supported on macOS; launch arguments are currently iOS-only.', ); } - await openMacOsApp(device, app, options); + await macOsDesktop().openApp(device, app, options); return; } const explicitUrl = options?.url?.trim(); @@ -213,7 +213,7 @@ export async function closeIosApp( env: Readonly, ): Promise { if (isMacOs(device)) { - await closeMacOsApp(device, app, env); + await macOsDesktop().closeApp(device, app, env); return; } const bundleId = await resolveIosApp(device, app); diff --git a/packages/platform-apple/src/core/app-resolution.ts b/packages/platform-apple/src/core/app-resolution.ts index 533760e5f5..86db7ebf55 100644 --- a/packages/platform-apple/src/core/app-resolution.ts +++ b/packages/platform-apple/src/core/app-resolution.ts @@ -9,7 +9,7 @@ import { import type { IosAppInfo } from './app-info.ts'; import { filterAppleAppsByBundlePrefix } from './app-filter.ts'; import { buildAppNotInstalledError } from './app-resolution-error.ts'; -import { listMacApps, resolveMacOsApp } from '../os/macos/apps.ts'; +import { macOsDesktop } from './macos-desktop.ts'; import { resolveAppleToolProvider } from './tool-provider.ts'; import { resolveIosPhysicalDeviceControl } from './physical-device-control.ts'; @@ -48,7 +48,7 @@ export async function resolveIosApp( options: IosAppResolutionOptions = {}, ): Promise { if (isMacOs(device)) { - return await resolveMacOsApp(app); + return await macOsDesktop().resolveApp(app); } const trimmed = app.trim(); const alias = resolveIosAppAlias(trimmed); @@ -283,7 +283,7 @@ function parseUrlScheme(url: string): string | undefined { export async function listIosApps(device: DeviceInfo, filter: AppsFilter): Promise { if (isMacOs(device)) { - return await listMacApps(filter); + return await macOsDesktop().listApps(filter); } if (device.kind === 'simulator') { const apps = await listSimulatorApps(device); @@ -333,3 +333,14 @@ async function listSimulatorAppMetadata( const read = await resolveAppleToolProvider().simulatorApps.list(device, options); return read.type === 'listed' ? read.apps : []; } + +/** + * The open target of a macOS app device (ADR 0035): its own app, which a link alone also opens. + * The installed macOS leaf resolves it; naming another app is refused before anything launches. + */ +export async function resolveMacOsAppDeviceOpenTarget( + device: DeviceInfo, + target: string | undefined, +): Promise<{ appBundleId: string; appName?: string }> { + return await macOsDesktop().resolveAppDeviceOpenTarget(device, target); +} diff --git a/packages/platform-apple/src/core/app-settings.ts b/packages/platform-apple/src/core/app-settings.ts index 7c2dc3913a..a2d61740cf 100644 --- a/packages/platform-apple/src/core/app-settings.ts +++ b/packages/platform-apple/src/core/app-settings.ts @@ -19,8 +19,8 @@ import { type CommandAttemptFailure, type ReasonTable, } from '@agent-device/kernel/errors'; -import { setMacOsAppearance } from '../os/macos/apps.ts'; -import { runMacOsPermissionAction, type MacOsPermissionTarget } from '../os/macos/helper.ts'; +import type { MacOsPermissionTarget } from '@agent-device/contracts/macos-platform-leaf'; +import { macOsDesktop } from './macos-desktop.ts'; import { closeIosApp } from './app-launch.ts'; import { applySimctlSetting } from './simctl-settings.ts'; import { readIosTextSize, setIosTextSize } from './settings-text-size.ts'; @@ -204,7 +204,7 @@ async function setMacOsHostSetting( const normalized = MACOS_HOST_SETTINGS.find((name) => name === setting.toLowerCase()); switch (normalized) { case 'appearance': - await setMacOsAppearance(state); + await macOsDesktop().setAppearance(state); return; case 'permission': { const action = parsePermissionAction(state); @@ -215,7 +215,7 @@ async function setMacOsHostSetting( ); } const permissionTarget = parseMacOsPermissionTarget(options?.permissionTarget); - return await runMacOsPermissionAction(action, permissionTarget, env); + return await macOsDesktop().runPermissionAction(action, permissionTarget, env); } case undefined: throw new AppError('UNSUPPORTED_OPERATION', `Unsupported macOS setting: ${setting}`); diff --git a/packages/platform-apple/src/core/scroll.ts b/packages/platform-apple/src/core/scroll.ts index b33e8fb85b..ba6db59a09 100644 --- a/packages/platform-apple/src/core/scroll.ts +++ b/packages/platform-apple/src/core/scroll.ts @@ -2,23 +2,11 @@ import { DEFAULT_IOS_SCROLL_AMOUNT, DEFAULT_IOS_SCROLL_DURATION_MS, type ScrollExecutionOptions, - type ScrollReleaseBehavior, } from '@agent-device/contracts/scroll-command'; -import { - type ScrollDirection, - SCROLL_KEYBOARD_OCCLUDES_SURFACE_DETAILS, - buildScrollGesturePlan, -} from '@agent-device/contracts/scroll-gesture'; +import { SCROLL_KEYBOARD_OCCLUDES_SURFACE_DETAILS } from '@agent-device/contracts/scroll-gesture'; import { AppError } from '@agent-device/kernel/errors'; import { SCROLL_KEYBOARD_OCCLUDES_SURFACE_RUNNER_CODE } from '@agent-device/apple-runner'; -export type NormalizedScrollOptions = { - amount?: number; - pixels?: number; - durationMs?: number; - preferProvidedPixels?: boolean; -}; - export type AppleScrollOptions = ScrollExecutionOptions; /** @@ -49,113 +37,3 @@ export function materializeIosScrollOptions( releaseBehavior: options?.releaseBehavior ?? 'controlled', }; } - -export function normalizeAppleScrollResultWithResolvedFrame( - runnerResult: Record, - direction: ScrollDirection, - options?: AppleScrollOptions, - config: { includeDuration?: boolean } = { includeDuration: true }, -): Record { - const referenceWidth = readFiniteNumber(runnerResult.referenceWidth); - const referenceHeight = readFiniteNumber(runnerResult.referenceHeight); - if (referenceWidth === undefined || referenceHeight === undefined) { - return normalizeAppleScrollResult(runnerResult, { amount: options?.amount }); - } - - // Recompute the plan from the runner's resolved frame so reported pixels match the planned - // travel (TS keeps buildScrollGesturePlan for Android and recording anyway). - const plan = buildScrollGesturePlan({ - direction, - amount: options?.amount, - pixels: options?.pixels, - referenceWidth, - referenceHeight, - }); - return normalizeAppleScrollResult(runnerResult, { - amount: options?.amount, - pixels: plan.pixels, - durationMs: config?.includeDuration ? options?.durationMs : undefined, - preferProvidedPixels: true, - }); -} - -export function scrollRunnerFields( - options: AppleScrollOptions | undefined, - config: { includeDuration?: boolean; includeReleaseBehavior?: boolean } = {}, -): Record { - return { - ...(options?.amount !== undefined ? { amount: options.amount } : {}), - ...(options?.pixels !== undefined ? { pixels: options.pixels } : {}), - ...(config.includeDuration !== false && options?.durationMs !== undefined - ? { durationMs: options.durationMs } - : {}), - ...(config.includeReleaseBehavior !== false && options?.releaseBehavior !== undefined - ? { scrollReleaseBehavior: options.releaseBehavior } - : {}), - }; -} - -function readFiniteNumber(value: unknown): number | undefined { - return typeof value === 'number' && Number.isFinite(value) ? value : undefined; -} - -export function normalizeAppleScrollResult( - runnerResult: Record, - options?: NormalizedScrollOptions, -): Record { - const { x1, y1, x2, y2 } = remapRunnerCoordinates(runnerResult); - const referenceWidth = readFiniteNumber(runnerResult.referenceWidth); - const referenceHeight = readFiniteNumber(runnerResult.referenceHeight); - const horizontalTravel = - x1 !== undefined && x2 !== undefined ? Math.round(Math.abs(x2 - x1)) : undefined; - const verticalTravel = - y1 !== undefined && y2 !== undefined ? Math.round(Math.abs(y2 - y1)) : undefined; - const travelPixels = selectScrollTravelPixels(options, horizontalTravel, verticalTravel); - const keyboardMinY = readFiniteNumber(runnerResult.keyboardMinY); - - return { - ...(x1 !== undefined ? { x1 } : {}), - ...(y1 !== undefined ? { y1 } : {}), - ...(x2 !== undefined ? { x2 } : {}), - ...(y2 !== undefined ? { y2 } : {}), - ...(referenceWidth !== undefined ? { referenceWidth } : {}), - ...(referenceHeight !== undefined ? { referenceHeight } : {}), - // Avoidance evidence (#2500) is reported only when it happened: `referenceHeight` above already - // names the clipped axis, and a plain `false` here could not tell "no keyboard" apart from a - // platform that never runs the clip. - ...(runnerResult.keyboardAvoided === true ? { keyboardAvoided: true } : {}), - ...(keyboardMinY !== undefined ? { keyboardMinY } : {}), - ...(options?.amount !== undefined ? { amount: options.amount } : {}), - ...(travelPixels !== undefined ? { pixels: travelPixels } : {}), - ...(options?.durationMs !== undefined ? { durationMs: options.durationMs } : {}), - }; -} - -function selectScrollTravelPixels( - options: NormalizedScrollOptions | undefined, - horizontalTravel: number | undefined, - verticalTravel: number | undefined, -): number | undefined { - if (options?.preferProvidedPixels && options.pixels !== undefined) return options.pixels; - if (horizontalTravel !== undefined && horizontalTravel > 0) return horizontalTravel; - if (verticalTravel !== undefined && verticalTravel > 0) return verticalTravel; - return undefined; -} - -function remapRunnerCoordinates(runnerResult: Record): { - x1?: number; - y1?: number; - x2?: number; - y2?: number; -} { - const x = readFiniteNumber(runnerResult.x); - const y = readFiniteNumber(runnerResult.y); - const x2 = readFiniteNumber(runnerResult.x2); - const y2 = readFiniteNumber(runnerResult.y2); - return { - ...(x !== undefined ? { x1: x } : {}), - ...(y !== undefined ? { y1: y } : {}), - ...(x2 !== undefined ? { x2 } : {}), - ...(y2 !== undefined ? { y2 } : {}), - }; -} diff --git a/packages/platform-apple/src/core/tool-provider-types.ts b/packages/platform-apple/src/core/tool-provider-types.ts index 11acfd7da5..efb422a413 100644 --- a/packages/platform-apple/src/core/tool-provider-types.ts +++ b/packages/platform-apple/src/core/tool-provider-types.ts @@ -1,8 +1,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { AppsFilter } from '@agent-device/contracts/device'; import type { ScopedSimctlArgs } from '@agent-device/contracts/platform-runtime-host'; import { type ExecOptions, type ExecResult } from '@agent-device/host-kit/command'; -import type { IosAppInfo } from './app-info.ts'; +import type { MacOsHostProvider } from '@agent-device/contracts/macos-platform-leaf'; /** Cleanup ignores scoped request cancellation but keeps explicit signals and its own deadline. */ export type AppleToolExecOptions = ExecOptions & @@ -37,18 +36,11 @@ export type ApplePlistProvider = { readJson(path: string, signal?: AbortSignal): Promise | null>; }; -export type MacOsOpenOptions = { background?: boolean }; - -export type AppleMacOsHostProvider = { - /** `background` launches or reopens without bringing the app to the front. */ - openBundle(bundleId: string, url?: string, options?: MacOsOpenOptions): Promise; - openTarget(target: string, options?: MacOsOpenOptions): Promise; - readClipboard(): Promise; - writeClipboard(text: string): Promise; - readDarkMode(): Promise; - setDarkMode(enabled: boolean): Promise; - listApps(filter: AppsFilter): Promise; -}; +/** + * The macOS host routes a request may substitute. A provider that names none leaves them to the + * installed macOS leaf, which answers them with the local tools of this host. + */ +export type AppleMacOsHostProvider = MacOsHostProvider; export type AppleSimulatorFileCopy = { device: DeviceInfo; diff --git a/packages/platform-apple/src/core/tool-provider.ts b/packages/platform-apple/src/core/tool-provider.ts index ea5fec81af..00faa6440c 100644 --- a/packages/platform-apple/src/core/tool-provider.ts +++ b/packages/platform-apple/src/core/tool-provider.ts @@ -13,7 +13,6 @@ import type { ScopedSimctlCommand, } from '@agent-device/contracts/platform-runtime-host'; import { createScopedProvider } from '@agent-device/kernel/scoped-provider'; -import { createLocalAppleMacOsHostProvider } from '../os/macos/host-provider.ts'; import type { AppleMacOsHelperProvider, AppleMacOsHostProvider, @@ -177,12 +176,6 @@ export function createLocalAppleToolProvider( : async (args, options) => await runCommand('xcrun', ['devicectl', ...args], options), }, plist, - macosHost: - provider.macosHost ?? - createLocalAppleMacOsHostProvider( - runCommand, - async (plistPath) => await plist.readJson(plistPath), - ), whichCommand: provider.whichCommand ?? (async (cmd) => await whichCmd(cmd, commandHostEnvironment().env)), }; diff --git a/packages/platform-apple/src/index.test.ts b/packages/platform-apple/src/index.test.ts index d4315d38af..d46c54ce42 100644 --- a/packages/platform-apple/src/index.test.ts +++ b/packages/platform-apple/src/index.test.ts @@ -21,8 +21,8 @@ test('lazy Apple tool provider preserves the local semantic operation shape', () assert.equal(typeof provider.simctl.run, 'function'); assert.equal(typeof provider.devicectl.run, 'function'); assert.equal(typeof provider.plist?.readJson, 'function'); - assert.equal(typeof provider.macosHost?.openBundle, 'function'); - assert.equal(typeof provider.macosHost?.listApps, 'function'); + // The local macOS host routes belong to the installed macOS leaf, not to this provider. + assert.equal(provider.macosHost, undefined); }); test('Apple app resolution facade preserves its synchronous helper contract', () => { diff --git a/packages/platform-apple/src/interactions.test.ts b/packages/platform-apple/src/interactions.test.ts index 9940d24670..a2a635a13e 100644 --- a/packages/platform-apple/src/interactions.test.ts +++ b/packages/platform-apple/src/interactions.test.ts @@ -4,6 +4,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { iosRunnerOverrides, performGestureApple } from './interactions.ts'; import { runAppleRunnerCommand } from './core/runner-client.ts'; +import { bindMacOsLeafFixture } from './__tests__/macos-leaf.fixtures.ts'; import { AppError } from '@agent-device/kernel/errors'; import { gestureRefusalMessage } from '@agent-device/contracts/gesture-admission'; import { APPLE_MULTI_TOUCH_UNSUPPORTED_HINTS } from './multitouch-support.ts'; @@ -255,17 +256,17 @@ test('iosRunnerOverrides owns fused repeated presses with deterministic jitter', ]); }); -test('iosRunnerOverrides owns alternate-button presses', async () => { +test('a macOS alternate-button press goes to the installed leaf with the device-bound runner', async () => { mockRunAppleRunnerCommand.mockResolvedValue({ clicked: true }); - const { overrides } = iosRunnerOverrides( - MACOS_TEST_DEVICE, - { - appBundleId: 'com.example.App', - }, - process.env, - ); + const sent = { command: 'mouseClick', x: 1, y: 2, button: 'secondary' } as const; + const leaf = bindMacOsLeafFixture({ + alternateClick: async (runner, _context, runnerOptions) => + await runner.run(sent, runnerOptions), + }); + const context = { appBundleId: 'com.example.App' }; + const { overrides, runnerOpts } = iosRunnerOverrides(MACOS_TEST_DEVICE, context, process.env); - await overrides.pressPoint!( + const result = await overrides.pressPoint!( { x: 100, y: 200 }, { button: 'secondary', @@ -277,13 +278,16 @@ test('iosRunnerOverrides owns alternate-button presses', async () => { }, ); - assert.deepEqual(mockRunAppleRunnerCommand.mock.calls[0]?.[1], { - command: 'mouseClick', - x: 100, - y: 200, - button: 'secondary', - appBundleId: 'com.example.App', - }); + // The owner hands the leaf the point and the button; the leaf maps them to the wire command. + assert.deepEqual(leaf.calls[0]?.args.slice(1), [ + context, + runnerOpts, + { x: 100, y: 200 }, + 'secondary', + ]); + // The capability is bound to this device and reaches the one Apple runner. + assert.deepEqual(mockRunAppleRunnerCommand.mock.calls[0], [MACOS_TEST_DEVICE, sent, runnerOpts]); + assert.deepEqual(result, { clicked: true }); }); test('iosRunnerOverrides remaps a later chunk failure to global press indices', async () => { @@ -615,40 +619,25 @@ test('iosRunnerOverrides maps tvOS scroll duration to remote press hold duration assert.deepEqual(result, { durationMs: 50 }); }); -test('iosRunnerOverrides maps macOS desktop scroll to a desktop wheel command', async () => { - mockRunAppleRunnerCommand.mockResolvedValueOnce({ - x: 737.5, - y: 476.5, - referenceWidth: 400, - referenceHeight: 800, +test('a macOS scroll goes to the installed leaf with the device-bound runner', async () => { + mockRunAppleRunnerCommand.mockResolvedValueOnce({ x: 737.5, y: 476.5 }); + const sent = { command: 'desktopScroll', direction: 'down', pixels: 200 } as const; + const leaf = bindMacOsLeafFixture({ + desktopScroll: async (runner, _context, runnerOptions) => await runner.run(sent, runnerOptions), }); - - const { overrides } = iosRunnerOverrides( - MACOS_TEST_DEVICE, - { - appBundleId: 'com.example.App', - }, - process.env, - ); + const context = { appBundleId: 'com.example.App' }; + const { overrides, runnerOpts } = iosRunnerOverrides(MACOS_TEST_DEVICE, context, process.env); const result = await overrides.scroll('down', { pixels: 200, durationMs: 50 }); - assert.equal(mockRunAppleRunnerCommand.mock.calls.length, 1); - assert.deepEqual(mockRunAppleRunnerCommand.mock.calls[0]?.[1], { - command: 'desktopScroll', - direction: 'down', - pixels: 200, - durationMs: 50, - appBundleId: 'com.example.App', - }); - assert.deepEqual(result, { - x1: 737.5, - y1: 476.5, - referenceWidth: 400, - referenceHeight: 800, - pixels: 200, - durationMs: 50, - }); + assert.deepEqual(leaf.calls[0]?.args.slice(1), [ + context, + runnerOpts, + 'down', + { pixels: 200, durationMs: 50 }, + ]); + assert.deepEqual(mockRunAppleRunnerCommand.mock.calls, [[MACOS_TEST_DEVICE, sent, runnerOpts]]); + assert.deepEqual(result, { x: 737.5, y: 476.5 }); }); test('iosRunnerOverrides rejects macOS desktop scroll duration above the shared cap', async () => { diff --git a/packages/platform-apple/src/interactions.ts b/packages/platform-apple/src/interactions.ts index 9e8810d71b..78499433d5 100644 --- a/packages/platform-apple/src/interactions.ts +++ b/packages/platform-apple/src/interactions.ts @@ -20,6 +20,9 @@ import { import { type ScrollDirection, assertScrollGestureInput, + normalizeAppleScrollResult, + normalizeAppleScrollResultWithResolvedFrame, + scrollRunnerFields, } from '@agent-device/contracts/scroll-gesture'; import { assertAppleMultiTouchSupported } from './multitouch-support.ts'; import { @@ -38,13 +41,11 @@ import { } from '@agent-device/apple-runner'; import { materializeIosScrollOptions, - normalizeAppleScrollResult, - normalizeAppleScrollResultWithResolvedFrame, - scrollRunnerFields, withAppleScrollKeyboardOcclusion, type AppleScrollOptions, } from './core/scroll.ts'; -import { runMacosDesktopScroll } from './os/macos/desktop-scroll.ts'; +import { macOsDesktop } from './core/macos-desktop.ts'; +import { macOsRunner } from './core/macos-runner.ts'; import { appleRemotePressCommand } from './os/tvos/remote.ts'; type RunAppleRunnerCommand = typeof runAppleRunnerCommand; @@ -240,10 +241,9 @@ async function runMacOsSurfacePress( `${options.button} click is not supported on macOS ${surface} sessions.`, ); } - const { runMacOsPressAction } = await import('./os/macos/helper.ts'); // `count` is independent presses and `doubleTap` raises the click state inside each one, // the same reading every other platform gives the two flags. - const posted = await runMacOsPressAction(point.x, point.y, { + const posted = await macOsDesktop().press(point.x, point.y, { bundleId: context.appBundleId, surface, holdMs: options.holdMs, @@ -265,6 +265,16 @@ async function runAppleAlternateClick( point: { x: number; y: number }, button: 'secondary' | 'middle', ) { + if (isMacOs(device)) { + // The installed macOS leaf maps the click to the runner's `mouseClick` wire case. + return await macOsDesktop().alternateClick( + macOsRunner(device), + context, + runnerOpts, + point, + button, + ); + } return await runAppleRunnerCommand( device, { @@ -454,9 +464,8 @@ async function runAppleScroll( assertScrollGestureInput(options ?? {}); if (isMacOs(device)) { - return await runMacosDesktopScroll( - runRunnerCommand, - device, + return await macOsDesktop().desktopScroll( + macOsRunner(device, runRunnerCommand), ctx, runnerOpts, direction, diff --git a/packages/platform-apple/src/interactor.ts b/packages/platform-apple/src/interactor.ts index 310e45a2b9..aee0a16b2e 100644 --- a/packages/platform-apple/src/interactor.ts +++ b/packages/platform-apple/src/interactor.ts @@ -7,7 +7,7 @@ import { readIosSetting, setIosSetting } from './core/app-settings.ts'; import { captureScreenshotViaRunner, screenshotIos } from './core/screenshot.ts'; import { iosRunnerOverrides } from './interactions.ts'; import { appleRemotePressCommand } from './os/tvos/remote.ts'; -import { runMacOsScreenshotAction } from './os/macos/helper.ts'; +import { macOsDesktop } from './core/macos-desktop.ts'; import { actOnAppleAlert, awaitAppleAlert, readAppleAlert } from './alert.ts'; import { runAppleRunnerCommand } from './core/runner-client.ts'; import { isAppleFoldableSimulator, setAppleFoldableOrientation } from './foldable/orientation.ts'; @@ -23,6 +23,7 @@ import { KEYBOARD_RETURN_KEYS, type KeyboardReturnKey } from '@agent-device/cont import { SCREENSHOT_FULLSCREEN_REASONS } from '@agent-device/contracts/capture'; import { macOsHelperSurface, + readMacOsAppBackend, type MacOsHelperSurface, type SessionSurface, } from '@agent-device/contracts/session'; @@ -42,10 +43,7 @@ import type { ScreenshotOptions, SnapshotOptions, } from '@agent-device/contracts/interactor-types'; -import { captureMacOsSurfaceSnapshot } from './os/macos/surface-snapshot.ts'; -import { hostMacOsAppBackend } from './os/macos/app-backend.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; -import { macOsNativeAppInteractor } from './os/macos/native-app-interactor.ts'; import { presentAppleRunnerSnapshot, type AppleRunnerSnapshotPresentation, @@ -70,7 +68,8 @@ export function createAppleInteractor( ): Interactor { const env = host.env; const { overrides, runnerOpts } = iosRunnerOverrides(device, runnerContext, env); - const appBackend = isMacOs(device) ? hostMacOsAppBackend(env) : 'xctest'; + // The app-session backend the host selected through `AGENT_DEVICE_MACOS_APP_BACKEND`. + const appBackend = isMacOs(device) ? readMacOsAppBackend((name) => env[name]) : 'xctest'; const helperSurface = (surface: SessionSurface | undefined) => isMacOs(device) ? macOsHelperSurface(surface, appBackend) : undefined; const interactor: Interactor = { @@ -317,7 +316,11 @@ async function captureAppleSnapshot( env: Readonly, ) { if (helper) { - return await captureMacOsSurfaceSnapshot({ ...options, surface: helper }, options?.signal, env); + return await macOsDesktop().captureSurfaceSnapshot( + { ...options, surface: helper }, + options?.signal, + env, + ); } return await captureAppleRunnerSnapshot(device, options, runnerOpts); } @@ -625,7 +628,7 @@ async function runAppleScreenshot( }, ); } - await runMacOsScreenshotAction(outPath, { + await macOsDesktop().screenshot(outPath, { surface: helper, ...(helper === 'app' ? { bundleId: options.appBundleId } : {}), signal: runnerOpts.signal, @@ -666,8 +669,7 @@ async function readMacOsSurfaceTextAtPoint( signal: AbortSignal | undefined, env: Readonly, ): Promise { - const { runMacOsReadTextAction } = await import('./os/macos/helper.ts'); - const result = await runMacOsReadTextAction(point.x, point.y, { + const result = await macOsDesktop().readTextAtPoint(point.x, point.y, { bundleId: appBundleId, surface, signal, @@ -691,3 +693,41 @@ async function readRunnerTextAtPoint( // The runner answers `message` when it reached the element but rendered no readable text. return typeof result.message === 'string' ? result.message : undefined; } + +/** + * The macOS interactor of the native backend. It is assembled member by member so that nothing + * reaches the XCTest runner: the installed macOS leaf serves the actions on the session app through + * its helper, and only members whose macOS implementation uses local tooling or the helper are taken + * from `base`. Each action asks the leaf when it runs, so it uses the tools of the request it runs in. + */ +function macOsNativeAppInteractor( + base: Interactor, + context: RunnerContext, + env: Readonly, +): Interactor { + const native = async () => await macOsDesktop().nativeAppActions(base, context, env); + return { + open: base.open, + openDevice: base.openDevice, + close: base.close, + screenshot: base.screenshot, + snapshot: base.snapshot, + readTextAtPoint: base.readTextAtPoint, + readClipboard: base.readClipboard, + writeClipboard: base.writeClipboard, + setSetting: base.setSetting, + readAlert: base.readAlert, + awaitAlert: base.awaitAlert, + acceptAlert: base.acceptAlert, + dismissAlert: base.dismissAlert, + tap: async (...args) => await (await native()).tap(...args), + pressPoint: async (...args) => await (await native()).pressPoint(...args), + longPress: async (...args) => await (await native()).longPress(...args), + focus: async (...args) => await (await native()).focus(...args), + type: async (...args) => await (await native()).type(...args), + fill: async (...args) => await (await native()).fill(...args), + scroll: async (...args) => await (await native()).scroll(...args), + back: async (...args) => await (await native()).back(...args), + setOrientation: async (...args) => await (await native()).setOrientation(...args), + }; +} diff --git a/packages/platform-apple/src/inventory.test.ts b/packages/platform-apple/src/inventory.test.ts index 4c6401eb90..468697094d 100644 --- a/packages/platform-apple/src/inventory.test.ts +++ b/packages/platform-apple/src/inventory.test.ts @@ -4,8 +4,13 @@ import { AppError } from '@agent-device/kernel/errors'; import { createAppleInventorySource } from './inventory.ts'; import { commandResult, createInventoryHost, inventoryScope } from './inventory.fixtures.ts'; import { inventoryModule } from './index.ts'; +import { + bindAbsentMacOsLeafFixture, + bindMacOsLeafFixture, +} from './__tests__/macos-leaf.fixtures.ts'; test('Apple inventory projects the host Mac without loading native tools', async () => { + bindMacOsLeafFixture(); let commands = 0; const host = createInventoryHost({ which: async () => { @@ -117,39 +122,47 @@ test('simulator-only inventory avoids physical discovery and observes fresh boot assert.deepEqual(calls, [['simctl', 'list', '-j']]); }); -test('simulator-set inventory remains scoped while retaining the host Mac', async () => { - const calls: string[][] = []; - const host = createInventoryHost({ - run: async (request) => { - calls.push([request.tool, ...request.args]); - return commandResult( - JSON.stringify({ - devices: { - 'com.apple.CoreSimulator.SimRuntime.tvOS-18-0': [ - { - name: 'Apple TV 4K', - udid: 'tv-1', - state: 'Shutdown', - isAvailable: true, - }, - ], - }, - }), - ); - }, - }); +test.each([ + ['retaining the host Mac the installed macOS package serves', true, ['tv-1', 'host-macos-local']], + ['omitting the host Mac without the macOS package', false, ['tv-1']], +] as const)( + 'simulator-set inventory remains scoped while %s', + async (_name, installed, expected) => { + if (installed) bindMacOsLeafFixture(); + else bindAbsentMacOsLeafFixture(); + const calls: string[][] = []; + const host = createInventoryHost({ + run: async (request) => { + calls.push([request.tool, ...request.args]); + return commandResult( + JSON.stringify({ + devices: { + 'com.apple.CoreSimulator.SimRuntime.tvOS-18-0': [ + { + name: 'Apple TV 4K', + udid: 'tv-1', + state: 'Shutdown', + isAvailable: true, + }, + ], + }, + }), + ); + }, + }); - const devices = await createAppleInventorySource(host).discover( - { iosSimulatorSetPath: '/tmp/custom-set' }, - inventoryScope, - ); + const devices = await createAppleInventorySource(host).discover( + { iosSimulatorSetPath: '/tmp/custom-set' }, + inventoryScope, + ); - assert.deepEqual( - devices.map((device) => device.id), - ['tv-1', 'host-macos-local'], - ); - assert.deepEqual(calls, [['simctl', '--set', '/tmp/custom-set', 'list', '-j']]); -}); + assert.deepEqual( + devices.map((device) => device.id), + [...expected], + ); + assert.deepEqual(calls, [['simctl', '--set', '/tmp/custom-set', 'list', '-j']]); + }, +); test('unscoped Apple inventory starts simulator and physical discovery concurrently', async () => { const calls: string[] = []; @@ -176,3 +189,23 @@ test('unscoped Apple inventory starts simulator and physical discovery concurren releaseSimulators(); await discovery; }); + +test('a macOS request without the macOS package answers plugin-not-installed with its install command', async () => { + bindAbsentMacOsLeafFixture(); + const host = createInventoryHost({ which: async () => undefined }); + + for (const request of [ + { platform: 'macos' }, + { platform: 'apple', target: 'desktop' }, + ] as const) { + await assert.rejects( + async () => await createAppleInventorySource(host).discover(request, inventoryScope), + (error: unknown) => + error instanceof AppError && + error.code === 'UNSUPPORTED_PLATFORM' && + error.details?.reason === 'plugin-not-installed' && + error.details.package === '@agent-device/macos' && + String(error.details.hint).includes('agent-device plugins add @agent-device/macos'), + ); + } +}); diff --git a/packages/platform-apple/src/inventory.ts b/packages/platform-apple/src/inventory.ts index 9290db7526..69a08a0792 100644 --- a/packages/platform-apple/src/inventory.ts +++ b/packages/platform-apple/src/inventory.ts @@ -7,6 +7,7 @@ import type { import type { DeviceInventorySource } from '@agent-device/contracts/platform-module'; import { sortAppleDevicesForSelection, type DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; +import { isMacOsLeafInstalled, requireMacOsLeaf } from './macos-leaf.ts'; import { listPhysicalAppleDevices } from './physical-inventory.ts'; import { listAppleSimulators } from './simulator-inventory.ts'; @@ -24,6 +25,9 @@ async function discoverAppleDevices( scope: PlatformRequestScope, ): Promise { if (isMacOnlyRequest(request)) { + // A request that names macOS needs the leaf: an absent package answers `plugin-not-installed` + // with its install command, before any device is listed. + requireMacOsLeaf(); return [hostMacDevice(host)]; } if (host.hostOs !== 'darwin') { @@ -38,7 +42,7 @@ async function discoverAppleDevices( if (request.iosSimulatorSetPath || request.udid) { const simulators = await simulatorDiscovery; - const withHost = [...simulators, hostMacDevice(host)]; + const withHost = [...simulators, ...installedHostMacDevice(host)]; if (request.iosSimulatorSetPath || simulators.some((device) => device.id === request.udid)) { return sortAppleDevicesForSelection(withHost); } @@ -50,7 +54,7 @@ async function discoverAppleDevices( simulatorDiscovery, listPhysicalAppleDevices(host, scope), ]); - const withHost = [...simulators, hostMacDevice(host)]; + const withHost = [...simulators, ...installedHostMacDevice(host)]; return sortAppleDevicesForSelection(mergeAppleDevices(withHost, physical)); } @@ -87,6 +91,11 @@ function appleHostUnsupportedError(hostOs: HostOperatingSystem): AppError { }); } +/** Unfiltered discovery lists this Mac only when a package serves macOS desktop automation. */ +function installedHostMacDevice(host: DeviceInventoryHostFor<'apple'>): DeviceInfo[] { + return isMacOsLeafInstalled() ? [hostMacDevice(host)] : []; +} + function hostMacDevice(host: DeviceInventoryHostFor<'apple'>): DeviceInfo { return { platform: 'apple', diff --git a/packages/platform-apple/src/macos-facade.ts b/packages/platform-apple/src/macos-facade.ts deleted file mode 100644 index d33d7dff3b..0000000000 --- a/packages/platform-apple/src/macos-facade.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { - resolveFrontmostMacOsApp, - runMacOsAlertAction, - startMacOsAudioProbeProcess, -} from './os/macos/helper.ts'; -export { captureMacOsSurfaceSnapshot } from './os/macos/surface-snapshot.ts'; diff --git a/packages/platform-apple/src/os/macos/app-backend.test.ts b/packages/platform-apple/src/os/macos/app-backend.test.ts deleted file mode 100644 index 9e3b1c6b7f..0000000000 --- a/packages/platform-apple/src/os/macos/app-backend.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { bindTestCommandHost } from '@agent-device/test-kit'; -import { afterEach, expect, test, vi } from 'vitest'; -import { hostMacOsAppBackend } from './app-backend.ts'; - -bindTestCommandHost(); - -afterEach(() => { - vi.unstubAllEnvs(); -}); - -test('the host keeps XCTest for app sessions unless it opts into the native backend', () => { - vi.stubEnv('AGENT_DEVICE_MACOS_APP_BACKEND', ''); - expect(hostMacOsAppBackend(process.env)).toBe('xctest'); - vi.stubEnv('AGENT_DEVICE_MACOS_APP_BACKEND', 'native'); - expect(hostMacOsAppBackend(process.env)).toBe('native'); -}); diff --git a/packages/platform-apple/src/os/macos/app-backend.ts b/packages/platform-apple/src/os/macos/app-backend.ts deleted file mode 100644 index 1419794368..0000000000 --- a/packages/platform-apple/src/os/macos/app-backend.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { EnvMap } from '@agent-device/kernel/source-value'; -import { readMacOsAppBackend, type MacOsAppBackend } from '@agent-device/contracts/session'; - -/** The app-session backend the host selected through `AGENT_DEVICE_MACOS_APP_BACKEND`. */ -export function hostMacOsAppBackend(env: Readonly): MacOsAppBackend { - return readMacOsAppBackend((name) => env[name]); -} diff --git a/packages/platform-apple/src/os/macos/desktop-scroll.ts b/packages/platform-apple/src/os/macos/desktop-scroll.ts deleted file mode 100644 index 62d207e8d3..0000000000 --- a/packages/platform-apple/src/os/macos/desktop-scroll.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { RunnerCallOptions, RunnerContext } from '@agent-device/contracts/interactor-types'; -import type { ScrollDirection } from '@agent-device/contracts/scroll-gesture'; -import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { RunnerCommand } from '@agent-device/apple-runner'; -import { - normalizeAppleScrollResultWithResolvedFrame, - scrollRunnerFields, - type AppleScrollOptions, -} from '../../core/scroll.ts'; - -type RunRunnerCommand = ( - device: DeviceInfo, - command: RunnerCommand, - options?: RunnerCallOptions, -) => Promise>; - -export async function runMacosDesktopScroll( - runRunnerCommand: RunRunnerCommand, - device: DeviceInfo, - ctx: RunnerContext, - runnerOpts: RunnerCallOptions, - direction: ScrollDirection, - options?: AppleScrollOptions, -): Promise> { - const runnerResult = await runRunnerCommand( - device, - { - command: 'desktopScroll', - direction, - ...scrollRunnerFields(options, { includeDuration: true, includeReleaseBehavior: false }), - appBundleId: ctx.appBundleId, - }, - runnerOpts, - ); - return normalizeAppleScrollResultWithResolvedFrame(runnerResult, direction, options, { - includeDuration: true, - }); -} diff --git a/packages/platform-apple/src/os/macos/native-backend-facts.test.ts b/packages/platform-apple/src/os/macos/native-backend-facts.test.ts deleted file mode 100644 index a6a5422ee1..0000000000 --- a/packages/platform-apple/src/os/macos/native-backend-facts.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { expect, test } from 'vitest'; -import type { DeviceInfo } from '@agent-device/kernel/device'; -import { macOsNativeBackendFacts } from './native-backend-facts.ts'; - -const mac = { - platform: 'apple', - appleOs: 'macos', - id: 'host', - name: 'Mac', - kind: 'device', - target: 'desktop', -} as const satisfies DeviceInfo; - -test('the native backend refuses every runner-only macOS operation at admission', () => { - const facts = macOsNativeBackendFacts(mac, 'native'); - for (const operation of [ - 'screenRecordingStart', - 'screenRecordingReattach', - 'prepareAppleRunner', - 'longPressPoint', - 'back', - 'performGesturePlan', - 'performDirectionalFlingPlan', - 'performMultiTouchGesturePlan', - 'performTargetAuthoredDrag', - 'gestureViewport', - ]) { - expect(facts).toHaveProperty(operation, { - available: false, - reason: 'unsupported-device-backend', - hint: expect.stringContaining('AGENT_DEVICE_MACOS_APP_BACKEND'), - }); - } -}); - -test('the XCTest backend and other Apple devices keep their own facts', () => { - expect(macOsNativeBackendFacts(mac, 'xctest')).toEqual({}); - expect(macOsNativeBackendFacts({ ...mac, appleOs: 'ios', kind: 'simulator' }, 'native')).toEqual( - {}, - ); -}); diff --git a/packages/platform-apple/src/os/macos/native-backend-facts.ts b/packages/platform-apple/src/os/macos/native-backend-facts.ts deleted file mode 100644 index 2a4544b505..0000000000 --- a/packages/platform-apple/src/os/macos/native-backend-facts.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { backRuntimeOperationFacts } from '@agent-device/contracts/back-runtime'; -import { gestureRuntimeOperationFacts } from '@agent-device/contracts/gesture-runtime'; -import type { RuntimeOperationUnavailability } from '@agent-device/contracts/platform-runtime'; -import type { MacOsAppBackend } from '@agent-device/contracts/session'; -import { isMacOs, type DeviceInfo } from '@agent-device/kernel/device'; - -const nativeBackendUnavailable: RuntimeOperationUnavailability = Object.freeze({ - available: false, - reason: 'unsupported-device-backend', - hint: 'The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.', -}); - -/** - * The macOS operations only the XCTest runner can serve. Under the native backend they are - * refused at admission, before dispatch, for every macOS session of the daemon: the backend is a - * daemon setting, so no session on it may start the runner. Spread last over the leaf's facts. - */ -export function macOsNativeBackendFacts(device: DeviceInfo, appBackend: MacOsAppBackend) { - if (!isMacOs(device) || appBackend !== 'native') return {}; - return Object.freeze({ - screenRecordingStart: nativeBackendUnavailable, - screenRecordingReattach: nativeBackendUnavailable, - prepareAppleRunner: nativeBackendUnavailable, - longPressPoint: nativeBackendUnavailable, - ...backRuntimeOperationFacts({ back: nativeBackendUnavailable }), - ...gestureRuntimeOperationFacts({ unsupported: nativeBackendUnavailable }), - }); -} diff --git a/packages/platform-apple/src/runtime.test.ts b/packages/platform-apple/src/runtime.test.ts index 24909ce1e7..2777bbe965 100644 --- a/packages/platform-apple/src/runtime.test.ts +++ b/packages/platform-apple/src/runtime.test.ts @@ -19,6 +19,7 @@ import { HOVER_UNAVAILABLE_HINT } from '@agent-device/contracts/touch-runtime'; import type { AppleOS, DeviceInfo } from '@agent-device/kernel/device'; import { createApplePlatformRuntime } from './runtime.ts'; import { platformRuntimeHostFixture } from './runtime.fixtures.ts'; +import { bindMacOsLeafFixture } from './__tests__/macos-leaf.fixtures.ts'; bindTestCommandHost(); @@ -269,8 +270,16 @@ test('a misspelled macOS app backend fails macOS bindings only', async () => { } }); -test('the native macOS app backend refuses recording and the runner before dispatch', async () => { +test('the native macOS app backend refuses what the installed leaf names before dispatch', async () => { vi.stubEnv('AGENT_DEVICE_MACOS_APP_BACKEND', 'native'); + const refused = { available: false, reason: 'unsupported-device-backend' } as const; + const leaf = bindMacOsLeafFixture({ + nativeBackendFacts: async () => ({ + screenRecordingStart: refused, + prepareAppleRunner: refused, + back: refused, + }), + }); try { const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ device: leaves.macos, @@ -289,6 +298,7 @@ test('the native macOS app backend refuses recording and the runner before dispa expect(binding.operations[operation]).toBeTypeOf('undefined'); } expect(binding.facts.operations.tapPoint).toEqual({ available: true }); + expect(leaf.calls.map(({ operation }) => operation)).toContain('nativeBackendFacts'); } finally { vi.unstubAllEnvs(); } diff --git a/packages/platform-apple/src/runtime.ts b/packages/platform-apple/src/runtime.ts index bcb09b30ad..36459b63b6 100644 --- a/packages/platform-apple/src/runtime.ts +++ b/packages/platform-apple/src/runtime.ts @@ -63,9 +63,12 @@ import { createAppleSystemOperations } from './system/runtime.ts'; import { appleFoldableFacts, createAppleFoldableOperations } from './foldable/runtime.ts'; import { bindAppleFindTextRuntime, bindAppleSnapshotRuntime } from './runtime-snapshot.ts'; import { bindAppleQuerySelectorRuntime } from './runtime-selector-query.ts'; -import { macOsHelperSurface, type MacOsAppBackend } from '@agent-device/contracts/session'; -import { hostMacOsAppBackend } from './os/macos/app-backend.ts'; -import { macOsNativeBackendFacts } from './os/macos/native-backend-facts.ts'; +import { + macOsHelperSurface, + readMacOsAppBackend, + type MacOsAppBackend, +} from '@agent-device/contracts/session'; +import { macOsDesktop } from './core/macos-desktop.ts'; import { applyWatchOsOperationFacts, bindWatchOsOperations } from './os/watchos/facts.ts'; import { createAppleSnapshotRoute } from './snapshot-route.ts'; @@ -182,7 +185,7 @@ export function createApplePlatformRuntime(host: PlatformRuntimeHost): PlatformR let resolvedMacOsAppBackend: MacOsAppBackend | undefined; const macOsAppBackend = (device: DeviceInfo): MacOsAppBackend => isMacOs(device) - ? (resolvedMacOsAppBackend ??= hostMacOsAppBackend(host.hostEnvironment.env)) + ? (resolvedMacOsAppBackend ??= readMacOsAppBackend((name) => host.hostEnvironment.env[name])) : 'xctest'; const inspectFacts = async (device: DeviceInfo) => { const logs = await appLogs.inspectFacts(device); @@ -228,7 +231,10 @@ export function createApplePlatformRuntime(host: PlatformRuntimeHost): PlatformR listApps: apps, ...appleApplicationLifecycleFacts(device), shutdownTarget: shutdownFact(device), - ...macOsNativeBackendFacts(device, macOsAppBackend(device)), + // Under the native backend the installed macOS leaf names what only the runner serves. + ...(isMacOs(device) && macOsAppBackend(device) === 'native' + ? await macOsDesktop().nativeBackendFacts() + : {}), }), }); }; diff --git a/packages/platform-apple/src/screenshot-support.test.ts b/packages/platform-apple/src/screenshot-support.test.ts index 9ccd0cab1d..974ec4d4af 100644 --- a/packages/platform-apple/src/screenshot-support.test.ts +++ b/packages/platform-apple/src/screenshot-support.test.ts @@ -4,6 +4,7 @@ import type { Interactor, ScreenshotOptions } from '@agent-device/contracts/inte import type { MacOsAppBackend, SessionSurface } from '@agent-device/contracts/session'; import { createApplePlatformRuntime } from './runtime.ts'; import { platformRuntimeHostFixture } from './runtime.fixtures.ts'; +import { bindMacOsLeafFixture } from './__tests__/macos-leaf.fixtures.ts'; const simulator: DeviceInfo = { platform: 'apple', @@ -83,6 +84,8 @@ test.each([ ] satisfies [DeviceInfo, SessionSurface | undefined, MacOsAppBackend | undefined, boolean][])( 'the bound Apple capture declares runner support for %j on surface %s with app backend %s: %s', async (device, surface, appBackend, supported) => { + // The native rows read the leaf's admission facts; this test is about the capture route. + bindMacOsLeafFixture({ nativeBackendFacts: async () => ({}) }); const screenshot = vi.fn(async () => ({})); const resolve = vi.fn(async () => ({ screenshot }) as unknown as Interactor); const host = { diff --git a/apple/macos-helper/Package.swift b/packages/platform-macos/macos-helper/Package.swift similarity index 100% rename from apple/macos-helper/Package.swift rename to packages/platform-macos/macos-helper/Package.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickDelivery.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickDelivery.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickDelivery.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickDelivery.swift diff --git a/apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickSchedule.swift b/packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickSchedule.swift similarity index 100% rename from apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickSchedule.swift rename to packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickSchedule.swift diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/AppWindowScreenshotTests.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/AppWindowScreenshotTests.swift similarity index 100% rename from apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/AppWindowScreenshotTests.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/AppWindowScreenshotTests.swift diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/AudioProbeTests.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/AudioProbeTests.swift similarity index 100% rename from apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/AudioProbeTests.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/AudioProbeTests.swift diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift similarity index 97% rename from apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift index a14b3fbece..ae4ca6bf78 100644 --- a/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift +++ b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift @@ -29,10 +29,11 @@ private struct HelperOutcomesFixture: Decodable { let deliveryMechanisms: [String] } -/// `#filePath` is `/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/`. +/// `#filePath` is +/// `/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/`. private let repoRoot = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() - .deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() final class BackgroundInteractionTests: XCTestCase { /// The host keys refusals and mechanisms on these strings; the table is their one declaration. diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift similarity index 100% rename from apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/RectResponseTests.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/RectResponseTests.swift similarity index 100% rename from apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/RectResponseTests.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/RectResponseTests.swift diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/ScreenshotResponseTests.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/ScreenshotResponseTests.swift similarity index 100% rename from apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/ScreenshotResponseTests.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSHelperTests/ScreenshotResponseTests.swift diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSInputTests/MouseClickScheduleTests.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSInputTests/MouseClickScheduleTests.swift similarity index 100% rename from apple/macos-helper/Tests/AgentDeviceMacOSInputTests/MouseClickScheduleTests.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSInputTests/MouseClickScheduleTests.swift diff --git a/apple/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift b/packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift similarity index 100% rename from apple/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift rename to packages/platform-macos/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift diff --git a/packages/platform-apple/src/os/macos/apps.test.ts b/packages/platform-macos/src/apps.test.ts similarity index 60% rename from packages/platform-apple/src/os/macos/apps.test.ts rename to packages/platform-macos/src/apps.test.ts index b77a642154..2f8063e123 100644 --- a/packages/platform-apple/src/os/macos/apps.test.ts +++ b/packages/platform-macos/src/apps.test.ts @@ -10,9 +10,15 @@ import { openMacOsApp, resolveMacOsApp, resolveMacOsAppDeviceOpenTarget, + setMacOsAppearance, } from './apps.ts'; -import { createLocalAppleToolProvider, withAppleToolProvider } from '../../core/tool-provider.ts'; -import type { AppleMacOsHostProvider } from '../../core/tool-provider-types.ts'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; +import type { MacOsToolbox } from './toolbox.ts'; + +const withToolbox = async (box: MacOsToolbox, run: (box: MacOsToolbox) => Promise) => + await run(box); +import type { MacOsHostProvider } from '@agent-device/contracts/macos-platform-leaf'; +import { createLocalMacOsHostProvider } from './host-provider.ts'; const MACOS_DEVICE: DeviceInfo = { platform: 'apple', @@ -25,6 +31,7 @@ const MACOS_DEVICE: DeviceInfo = { }; const mockQuitMacOsApp = vi.mocked(quitMacOsApp); +const box = macOsToolboxFixture(); afterEach(() => { mockQuitMacOsApp.mockReset(); @@ -51,7 +58,7 @@ test('closeMacOsApp waits until an accepted termination has actually completed', forceTerminated: false, }); - await closeMacOsApp(MACOS_DEVICE, 'com.apple.systempreferences', process.env); + await closeMacOsApp(box, MACOS_DEVICE, 'com.apple.systempreferences', process.env); expect(mockQuitMacOsApp).toHaveBeenCalledTimes(3); }); @@ -65,7 +72,7 @@ test('closeMacOsApp fails immediately when neither termination request is accept }); await expect( - closeMacOsApp(MACOS_DEVICE, 'com.apple.systempreferences', process.env), + closeMacOsApp(box, MACOS_DEVICE, 'com.apple.systempreferences', process.env), ).rejects.toThrow('Failed to close macOS app com.apple.systempreferences'); expect(mockQuitMacOsApp).toHaveBeenCalledTimes(1); }); @@ -79,7 +86,7 @@ test('closeMacOsApp bounds termination confirmation', async () => { }); await expect( - closeMacOsApp(MACOS_DEVICE, 'com.apple.systempreferences', process.env), + closeMacOsApp(box, MACOS_DEVICE, 'com.apple.systempreferences', process.env), ).rejects.toMatchObject({ details: { reason: 'MACOS_APP_TERMINATION_TIMEOUT', attempts: 20 }, }); @@ -89,16 +96,16 @@ test('closeMacOsApp bounds termination confirmation', async () => { test('an app device opens its own app in the background and the whole Mac opens in front', async () => { const opened = async (device: DeviceInfo) => { const calls: string[][] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ runCommand: async (cmd, args) => { if (cmd === 'open') calls.push(args); return { exitCode: 0, stdout: '', stderr: '' }; }, }); - await withAppleToolProvider(provider, async () => { - await openMacOsApp(device, 'com.example.demo'); - await openMacOsApp(device, 'com.example.demo', { url: 'demo://open' }); - await openMacOsApp(device, 'demo://open'); + await withToolbox(provider, async (box) => { + await openMacOsApp(box, device, 'com.example.demo'); + await openMacOsApp(box, device, 'com.example.demo', { url: 'demo://open' }); + await openMacOsApp(box, device, 'demo://open'); }); return calls; }; @@ -118,10 +125,10 @@ test('an app device opens its own app in the background and the whole Mac opens test('an app device refuses to open or close another app before anything runs', async () => { const runCommand = vi.fn(async () => ({ exitCode: 0, stdout: '', stderr: '' })); const device = hostAppDevice(MACOS_DEVICE, 'com.example.demo'); - await withAppleToolProvider(createLocalAppleToolProvider({ runCommand }), async () => { + await withToolbox(macOsToolboxFixture({ runCommand }), async (box) => { for (const attempt of [ - openMacOsApp(device, 'com.example.other'), - closeMacOsApp(device, 'com.example.other', {}), + openMacOsApp(box, device, 'com.example.other'), + closeMacOsApp(box, device, 'com.example.other', {}), ]) { await expect(attempt).rejects.toMatchObject({ code: 'INVALID_ARGS', @@ -138,18 +145,12 @@ test('a bundle id in another case resolves to the installed app; a dotted name s { bundleId: 'com.apple.TextEdit', name: 'TextEdit' }, { bundleId: 'com.example.foo', name: 'Foo.Bar' }, ]); - const provider = createLocalAppleToolProvider({ - runCommand: async () => ({ exitCode: 0, stdout: '', stderr: '' }), + await withToolbox(localHostWith({ listApps }), async (box) => { + expect(await resolveMacOsApp(box, 'com.apple.TextEdit')).toBe('com.apple.TextEdit'); + expect(await resolveMacOsApp(box, 'COM.APPLE.TEXTEDIT')).toBe('com.apple.TextEdit'); + expect(await resolveMacOsApp(box, 'Foo.Bar')).toBe('com.example.foo'); + expect(await resolveMacOsApp(box, 'com.example.lowercase')).toBe('com.example.lowercase'); }); - await withAppleToolProvider( - { ...provider, macosHost: { ...provider.macosHost!, listApps } }, - async () => { - expect(await resolveMacOsApp('com.apple.TextEdit')).toBe('com.apple.TextEdit'); - expect(await resolveMacOsApp('COM.APPLE.TEXTEDIT')).toBe('com.apple.TextEdit'); - expect(await resolveMacOsApp('Foo.Bar')).toBe('com.example.foo'); - expect(await resolveMacOsApp('com.example.lowercase')).toBe('com.example.lowercase'); - }, - ); }); test('an app device resolves any name of its own app and refuses another app', async () => { @@ -157,40 +158,41 @@ test('an app device resolves any name of its own app and refuses another app', a { bundleId: 'com.apple.TextEdit', name: 'TextEdit' }, { bundleId: 'com.apple.calculator', name: 'Calculator' }, ]); - const provider = createLocalAppleToolProvider({ - runCommand: async () => ({ exitCode: 0, stdout: '', stderr: '' }), - }); const device = hostAppDevice(MACOS_DEVICE, 'com.apple.TextEdit'); - await withAppleToolProvider( - { ...provider, macosHost: { ...provider.macosHost!, listApps } }, - async () => { - // Opened by bundle id, closed by name: one app. - await expect(resolveMacOsAppDeviceOpenTarget(device, 'TextEdit')).resolves.toMatchObject({ - appBundleId: 'com.apple.TextEdit', - }); - await expect(resolveMacOsAppDeviceOpenTarget(device, 'Calculator')).rejects.toMatchObject({ - details: { reason: 'app-device-scope' }, - }); - }, - ); + await withToolbox(localHostWith({ listApps }), async (box) => { + // Opened by bundle id, closed by name: one app. + await expect(resolveMacOsAppDeviceOpenTarget(box, device, 'TextEdit')).resolves.toMatchObject({ + appBundleId: 'com.apple.TextEdit', + }); + await expect(resolveMacOsAppDeviceOpenTarget(box, device, 'Calculator')).rejects.toMatchObject({ + details: { reason: 'app-device-scope' }, + }); + }); }); +/** The local host routes with some of them replaced, as a scoped request supplies them. */ +function localHostWith(routes: Partial) { + const runCommand = async () => ({ exitCode: 0, stdout: '', stderr: '' }); + const local = createLocalMacOsHostProvider(macOsToolboxFixture({ runCommand })); + return macOsToolboxFixture({ runCommand, macosHost: { ...local, ...routes } }); +} + function macOsHost(apps: Array<{ name: string; bundleId: string }>) { - const openBundle = vi.fn(async () => undefined); + const openBundle = vi.fn(async () => undefined); const listApps = vi.fn(async () => apps); - const macosHost = { openBundle, listApps } as unknown as AppleMacOsHostProvider; + const macosHost = { openBundle, listApps } as unknown as MacOsHostProvider; return { openBundle, listApps, - run: (fn: () => Promise) => - withAppleToolProvider(createLocalAppleToolProvider({ macosHost }), fn), + run: (fn: (box: MacOsToolbox) => Promise) => + withToolbox(macOsToolboxFixture({ macosHost }), fn), }; } test('openMacOsApp opens a mixed-case bundle id without display-name resolution', async () => { const host = macOsHost([{ name: 'TextEdit', bundleId: 'com.apple.TextEdit' }]); - await host.run(() => openMacOsApp(MACOS_DEVICE, 'com.apple.TextEdit')); + await host.run((box) => openMacOsApp(box, MACOS_DEVICE, 'com.apple.TextEdit')); expect(host.openBundle).toHaveBeenCalledWith('com.apple.TextEdit', undefined, { background: false, @@ -201,7 +203,7 @@ test('openMacOsApp opens a mixed-case bundle id without display-name resolution' test('openMacOsApp resolves a display name to its canonical mixed-case bundle id', async () => { const host = macOsHost([{ name: 'TextEdit', bundleId: 'com.apple.TextEdit' }]); - await host.run(() => openMacOsApp(MACOS_DEVICE, 'TextEdit')); + await host.run((box) => openMacOsApp(box, MACOS_DEVICE, 'TextEdit')); expect(host.openBundle).toHaveBeenCalledWith('com.apple.TextEdit', undefined, { background: false, @@ -211,7 +213,9 @@ test('openMacOsApp resolves a display name to its canonical mixed-case bundle id test('openMacOsApp keeps the typed error for an app that is not installed', async () => { const host = macOsHost([]); - await expect(host.run(() => openMacOsApp(MACOS_DEVICE, 'No Such App'))).rejects.toMatchObject({ + await expect( + host.run((box) => openMacOsApp(box, MACOS_DEVICE, 'No Such App')), + ).rejects.toMatchObject({ code: 'APP_NOT_INSTALLED', }); expect(host.openBundle).not.toHaveBeenCalled(); @@ -221,10 +225,28 @@ test.each([ ['com.apple.TextEdit', 'com.apple.TextEdit'], ['com.x.My_App', 'com.x.My_App'], ['Booking.com', 'com.booking.BookingApp'], -])('resolveMacOsApp(%j) is %j', async (typed, expected) => { +])('resolveMacOsApp(box, %j) is %j', async (typed, expected) => { const host = macOsHost([{ name: 'Booking.com', bundleId: 'com.booking.BookingApp' }]); - expect(await host.run(() => resolveMacOsApp(typed))).toBe(expected); + expect(await host.run((box) => resolveMacOsApp(box, typed))).toBe(expected); // Only a lowercase-first dotted id is taken as a bundle id as typed; Booking.com is a name. expect(host.listApps).toHaveBeenCalledTimes(typed === 'Booking.com' ? 1 : 0); }); + +test('an appearance toggle reads the current osascript appearance and sets the other one', async () => { + const scripts: string[] = []; + const box = macOsToolboxFixture({ + runCommand: async (cmd, args) => { + if (cmd !== 'osascript' || args[0] !== '-e') throw new Error(`unexpected ${cmd}`); + scripts.push(args[1] ?? ''); + return { exitCode: 0, stdout: scripts.length === 1 ? 'true\n' : '', stderr: '' }; + }, + }); + + await setMacOsAppearance(box, 'toggle'); + + expect(scripts.map((script) => script.split('preferences to ')[1])).toEqual([ + 'get dark mode', + 'set dark mode to false', + ]); +}); diff --git a/packages/platform-apple/src/os/macos/apps.ts b/packages/platform-macos/src/apps.ts similarity index 75% rename from packages/platform-apple/src/os/macos/apps.ts rename to packages/platform-macos/src/apps.ts index 6a6c796ea6..d32e4039a5 100644 --- a/packages/platform-apple/src/os/macos/apps.ts +++ b/packages/platform-macos/src/apps.ts @@ -9,9 +9,13 @@ import { createAppResolutionCache, type AppResolutionCacheScope, } from '@agent-device/provision-kit/app-resolution-cache'; +import type { + MacOsHostProvider, + MacOsInstalledApp, +} from '@agent-device/contracts/macos-platform-leaf'; import { quitMacOsApp } from './helper.ts'; -import { resolveAppleToolProvider, type AppleMacOsHostProvider } from '../../core/tool-provider.ts'; -import type { IosAppInfo } from '../../core/app-info.ts'; +import { createLocalMacOsHostProvider } from './host-provider.ts'; +import type { MacOsToolbox } from './toolbox.ts'; const MACOS_APP_REASONS = { // The macOS app was still running after every termination attempt. @@ -36,7 +40,7 @@ const MACOS_APP_RESOLUTION_CACHE_SCOPE = { } satisfies AppResolutionCacheScope; const macOsAppResolutionCache = createAppResolutionCache(); -export async function resolveMacOsApp(app: string): Promise { +export async function resolveMacOsApp(box: MacOsToolbox, app: string): Promise { const trimmed = app.trim(); const alias = MACOS_ALIASES[trimmed.toLowerCase()]; @@ -51,7 +55,7 @@ export async function resolveMacOsApp(app: string): Promise { // An installed app matches by name, or by a bundle id spelled in another case: LaunchServices // matches bundle ids without regard to case. const wanted = trimmed.toLowerCase(); - const apps = await listMacApps('all'); + const apps = await listMacApps(box, 'all'); const matches = apps.filter( (entry) => entry.name.toLowerCase() === wanted || entry.bundleId.toLowerCase() === wanted, ); @@ -71,12 +75,13 @@ export async function resolveMacOsApp(app: string): Promise { * another app is refused before anything launches. */ export async function resolveMacOsAppDeviceOpenTarget( + box: MacOsToolbox, device: DeviceInfo, target: string | undefined, ): Promise<{ appBundleId: string; appName?: string }> { const app = requireHostApp(device); if (target && !isDeepLinkTarget(target)) { - assertAppDeviceBundle(device, await resolveMacOsApp(target)); + assertAppDeviceBundle(device, await resolveMacOsApp(box, target)); } return target ? { appBundleId: app.bundleId, appName: target } : { appBundleId: app.bundleId }; } @@ -86,6 +91,7 @@ export async function resolveMacOsAppDeviceOpenTarget( * where they are, and a link alone goes to the device's own app, not the default handler. */ export async function openMacOsApp( + box: MacOsToolbox, device: DeviceInfo, app: string, options?: { appBundleId?: string; url?: string }, @@ -93,7 +99,7 @@ export async function openMacOsApp( const openOptions = { background: device.hostApp !== undefined }; const target = app.trim(); if (device.hostApp && isDeepLinkTarget(target)) { - await resolveMacOsHostProvider().openBundle(device.hostApp.bundleId, target, openOptions); + await hostProvider(box).openBundle(device.hostApp.bundleId, target, openOptions); return; } const explicitUrl = options?.url?.trim(); @@ -101,30 +107,31 @@ export async function openMacOsApp( if (!isDeepLinkTarget(explicitUrl)) { throw new AppError('INVALID_ARGS', 'open requires a valid URL target'); } - const appId = options?.appBundleId ?? (await resolveMacOsApp(app)); + const appId = options?.appBundleId ?? (await resolveMacOsApp(box, app)); assertAppDeviceBundle(device, appId); - await resolveMacOsHostProvider().openBundle(appId, explicitUrl, openOptions); + await hostProvider(box).openBundle(appId, explicitUrl, openOptions); return; } if (isDeepLinkTarget(target)) { - await resolveMacOsHostProvider().openTarget(target, openOptions); + await hostProvider(box).openTarget(target, openOptions); return; } - const bundleId = options?.appBundleId ?? (await resolveMacOsApp(target)); + const bundleId = options?.appBundleId ?? (await resolveMacOsApp(box, target)); assertAppDeviceBundle(device, bundleId); - await resolveMacOsHostProvider().openBundle(bundleId, undefined, openOptions); + await hostProvider(box).openBundle(bundleId, undefined, openOptions); } export async function closeMacOsApp( + box: MacOsToolbox, device: DeviceInfo, app: string, env: Readonly, ): Promise { - const bundleId = await resolveMacOsApp(app); + const bundleId = await resolveMacOsApp(box, app); assertAppDeviceBundle(device, bundleId); - const request = await quitMacOsApp(bundleId, env); + const request = await quitMacOsApp(box, bundleId, env); if (!request.running) return; if (!request.terminated && !request.forceTerminated) { throw new AppError('COMMAND_FAILED', `Failed to close macOS app ${app}`, { @@ -136,7 +143,7 @@ export async function closeMacOsApp( } for (let attempt = 1; attempt < MACOS_APP_TERMINATION_MAX_ATTEMPTS; attempt += 1) { await sleep(MACOS_APP_TERMINATION_POLL_MS); - if (!(await quitMacOsApp(bundleId, env)).running) return; + if (!(await quitMacOsApp(box, bundleId, env)).running) return; } throw new AppError('COMMAND_FAILED', `Timed out waiting for macOS app ${app} to close`, { reason: MACOS_APP_REASONS.terminationTimeout.reason, @@ -165,32 +172,32 @@ function assertAppDeviceBundle(device: DeviceInfo, bundleId: string): void { ); } -export async function readMacOsClipboardText(): Promise { - return await resolveMacOsHostProvider().readClipboard(); +export async function readMacOsClipboardText(box: MacOsToolbox): Promise { + return await hostProvider(box).readClipboard(); } -export async function writeMacOsClipboardText(text: string): Promise { - await resolveMacOsHostProvider().writeClipboard(text); +export async function writeMacOsClipboardText(box: MacOsToolbox, text: string): Promise { + await hostProvider(box).writeClipboard(text); } -async function getMacOsDarkModeEnabled(): Promise { - return await resolveMacOsHostProvider().readDarkMode(); +async function getMacOsDarkModeEnabled(box: MacOsToolbox): Promise { + return await hostProvider(box).readDarkMode(); } -export async function setMacOsAppearance(state: string): Promise { +export async function setMacOsAppearance(box: MacOsToolbox, state: string): Promise { const action = parseAppearanceAction(state); - const darkMode = action === 'toggle' ? !(await getMacOsDarkModeEnabled()) : action === 'dark'; - await resolveMacOsHostProvider().setDarkMode(darkMode); + const darkMode = action === 'toggle' ? !(await getMacOsDarkModeEnabled(box)) : action === 'dark'; + await hostProvider(box).setDarkMode(darkMode); } -export async function listMacApps(filter: AppsFilter): Promise { - return await resolveMacOsHostProvider().listApps(filter); +export async function listMacApps( + box: MacOsToolbox, + filter: AppsFilter, +): Promise { + return await hostProvider(box).listApps(filter); } -function resolveMacOsHostProvider(): AppleMacOsHostProvider { - const host = resolveAppleToolProvider().macosHost; - if (!host) { - throw new AppError('UNSUPPORTED_OPERATION', 'macOS host provider is not available'); - } - return host; +/** The host routes a scoped request supplied, or the local ones this host answers itself. */ +function hostProvider(box: MacOsToolbox): MacOsHostProvider { + return box.tools.host ?? createLocalMacOsHostProvider(box); } diff --git a/packages/platform-apple/src/os/macos/helper-build.test.ts b/packages/platform-macos/src/helper-build.test.ts similarity index 73% rename from packages/platform-apple/src/os/macos/helper-build.test.ts rename to packages/platform-macos/src/helper-build.test.ts index 1309af9bb1..be88199711 100644 --- a/packages/platform-apple/src/os/macos/helper-build.test.ts +++ b/packages/platform-macos/src/helper-build.test.ts @@ -1,9 +1,9 @@ -import { bindTestCommandHost } from '@agent-device/test-kit'; +import { bindTestCommandHost, mkdtempForTest } from '@agent-device/test-kit'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import path from 'node:path'; import { afterEach, beforeEach, test, vi } from 'vitest'; -import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; bindTestCommandHost(); @@ -28,10 +28,10 @@ vi.mock('node:url', async (importOriginal) => { ...actual, fileURLToPath: (url: Parameters[0]) => { const href = (typeof url === 'string' ? url : url.href).replace(/\?.*$/, ''); - if (/\/os\/macos\/helper\.(?:ts|js)$/.test(href)) { - // A packaged copy of the module below the repo root, which is how the published layout - // sits relative to `apple/macos-helper`. - return `${layout.repoRoot}/dist/packages/platform-apple/src/os/macos/helper.js`; + if (/\/platform-macos\/src\/helper\.(?:ts|js)$/.test(href)) { + // The bundled module below the package root, which is how the published layout sits + // relative to `macos-helper`. + return `${layout.repoRoot}/dist/agent-device.mjs`; } return actual.fileURLToPath(url); }, @@ -43,59 +43,47 @@ vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => { return { ...actual, hostHomeDirectory: () => layout.home }; }); -vi.mock('@agent-device/host-kit/process', async (importOriginal) => { - const actual = await importOriginal(); - // The helper is a macOS-only build and the lane that scores this file runs on Linux. - return { ...actual, hostPlatform: () => 'darwin' }; -}); - -vi.mock('../../core/tool-provider.ts', async (importOriginal) => { - const { default: fsPromises } = await import('node:fs/promises'); - const { default: pathLib } = await import('node:path'); - const actual = await importOriginal(); +/** The Swift toolchain and the installed helper, doubled at the one seam `helper.ts` runs them through. */ +const runCommand = async (cmd: string, args: string[]) => { + if (cmd === 'swift' && args[0] === '--version') { + return { + exitCode: 0, + stdout: 'Swift version 6.2 (swiftlang-6.2.0.192.12), target: arm64-apple-darwin\n', + stderr: '', + }; + } + if (cmd === 'swift' && args[0] === 'build') { + layout.swiftBuildCalls.push([cmd, ...args].join(' ')); + // A release build leaves its product exactly where the install step expects to find it. + const binaryPath = path.join( + layout.packageRoot, + '.build', + 'release', + 'agent-device-macos-helper', + ); + await fs.mkdir(path.dirname(binaryPath), { recursive: true }); + await fs.writeFile(binaryPath, `// helper build ${layout.swiftBuildCalls.length}\n`); + return { exitCode: 0, stdout: 'Build complete!', stderr: '' }; + } + layout.helperCommands.push([cmd, ...args].join(' ')); return { - ...actual, - runAppleToolCommand: async (cmd: string, args: string[]) => { - if (cmd === 'swift' && args[0] === '--version') { - return { - exitCode: 0, - stdout: 'Swift version 6.2 (swiftlang-6.2.0.192.12), target: arm64-apple-darwin\n', - stderr: '', - }; - } - if (cmd === 'swift' && args[0] === 'build') { - layout.swiftBuildCalls.push([cmd, ...args].join(' ')); - // A release build leaves its product exactly where the install step expects to find it. - const binaryPath = pathLib.join( - layout.packageRoot, - '.build', - 'release', - 'agent-device-macos-helper', - ); - await fsPromises.mkdir(pathLib.dirname(binaryPath), { recursive: true }); - await fsPromises.writeFile( - binaryPath, - `// helper build ${layout.swiftBuildCalls.length}\n`, - ); - return { exitCode: 0, stdout: 'Build complete!', stderr: '' }; - } - layout.helperCommands.push([cmd, ...args].join(' ')); - return { - exitCode: 0, - stdout: JSON.stringify({ - ok: true, - data: { bundleId: 'com.example.Finder', appName: 'Finder', pid: 4242 }, - }), - stderr: '', - }; - }, + exitCode: 0, + stdout: JSON.stringify({ + ok: true, + data: { bundleId: 'com.example.Finder', appName: 'Finder', pid: 4242 }, + }), + stderr: '', }; -}); +}; + +// The helper is a macOS-only build and the lane that scores this file runs on Linux, so the host +// reports macOS. The toolbox is unscoped: a scoped request names its own helper binary instead. +const box = macOsToolboxFixture({ runCommand, scoped: false, hostOs: 'darwin' }); const scratchRoot = await mkdtempForTest('agent-device-macos-helper-build-'); layout.home = path.join(scratchRoot, 'home'); layout.repoRoot = path.join(scratchRoot, 'repo'); -layout.packageRoot = path.join(layout.repoRoot, 'apple', 'macos-helper'); +layout.packageRoot = path.join(layout.repoRoot, 'macos-helper'); // Imported after the mocks above and once the scratch home is known, because the install root is a // module-level constant resolved against the home directory. @@ -122,7 +110,7 @@ function sourcePath(...segments: string[]): string { /** A helper command is the freshness entry point: it cannot answer without fingerprinting the tree. */ async function askTheHelperForTheFrontmostApp(): Promise { - const frontmost = await resolveFrontmostMacOsApp(process.env); + const frontmost = await resolveFrontmostMacOsApp(box, process.env); assert.equal(frontmost.bundleId, 'com.example.Finder'); // The command runs the binary the freshness check just settled on, not a rebuild. assert.equal(layout.helperCommands.at(-1), `${installedHelperPath} app frontmost`); diff --git a/packages/platform-apple/src/os/macos/helper-resolution.test.ts b/packages/platform-macos/src/helper-resolution.test.ts similarity index 71% rename from packages/platform-apple/src/os/macos/helper-resolution.test.ts rename to packages/platform-macos/src/helper-resolution.test.ts index 6b06fc77eb..605aef4a75 100644 --- a/packages/platform-apple/src/os/macos/helper-resolution.test.ts +++ b/packages/platform-macos/src/helper-resolution.test.ts @@ -1,22 +1,24 @@ -import { bindTestCommandHost } from '@agent-device/test-kit'; +import { bindTestCommandHost, mkdtempForTest } from '@agent-device/test-kit'; import { test } from 'vitest'; import assert from 'node:assert/strict'; import { promises as fs } from 'node:fs'; import path from 'node:path'; -import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; import { quitMacOsApp, resolveMacOsHelperPackageRootFrom } from './helper.ts'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; + +const box = macOsToolboxFixture(); bindTestCommandHost(); test('resolveMacOsHelperPackageRootFrom finds helper package from source and dist-like paths', async () => { const repoRoot = await mkdtempForTest('agent-device-helper-root-'); - const helperRoot = path.join(repoRoot, 'apple', 'macos-helper'); + const helperRoot = path.join(repoRoot, 'macos-helper'); await fs.mkdir(helperRoot, { recursive: true }); await fs.writeFile(path.join(helperRoot, 'Package.swift'), '// test\n', 'utf8'); try { - const sourceLike = path.join(repoRoot, 'src', 'platforms', 'ios', 'macos-helper.ts'); - const distLike = path.join(repoRoot, 'dist', 'src', 'platforms', 'ios', 'macos-helper.js'); + const sourceLike = path.join(repoRoot, 'src', 'helper.ts'); + const distLike = path.join(repoRoot, 'dist', 'agent-device.mjs'); assert.equal(resolveMacOsHelperPackageRootFrom(sourceLike), helperRoot); assert.equal(resolveMacOsHelperPackageRootFrom(distLike), helperRoot); @@ -30,7 +32,7 @@ test('AGENT_DEVICE_MACOS_HELPER_BIN rejects relative override paths', async () = process.env.AGENT_DEVICE_MACOS_HELPER_BIN = './agent-device-macos-helper'; try { - await assert.rejects(() => quitMacOsApp('com.example.App', process.env), { + await assert.rejects(() => quitMacOsApp(box, 'com.example.App', process.env), { code: 'INVALID_ARGS', }); } finally { @@ -43,5 +45,8 @@ test('AGENT_DEVICE_MACOS_HELPER_BIN rejects relative override paths', async () = }); test('quitMacOsApp rejects invalid bundle identifiers before invoking helper', async () => { - await assert.rejects(() => quitMacOsApp('not a bundle id', process.env), /reverse-DNS form/i); + await assert.rejects( + () => quitMacOsApp(box, 'not a bundle id', process.env), + /reverse-DNS form/i, + ); }); diff --git a/packages/platform-apple/src/os/macos/helper.test.ts b/packages/platform-macos/src/helper.test.ts similarity index 78% rename from packages/platform-apple/src/os/macos/helper.test.ts rename to packages/platform-macos/src/helper.test.ts index 651aefc5ed..cf16b4d321 100644 --- a/packages/platform-apple/src/os/macos/helper.test.ts +++ b/packages/platform-macos/src/helper.test.ts @@ -3,7 +3,11 @@ import { test, beforeEach } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { macOsHelperSurface } from '@agent-device/contracts/session'; import { AppError } from '@agent-device/kernel/errors'; -import { createLocalAppleToolProvider, withAppleToolProvider } from '../../core/tool-provider.ts'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; +import type { MacOsToolbox } from './toolbox.ts'; + +const withToolbox = async (box: MacOsToolbox, run: (box: MacOsToolbox) => Promise) => + await run(box); import { readFileSync } from 'node:fs'; import { MACOS_DELIVERY_MECHANISMS, @@ -14,6 +18,7 @@ import { runMacOsReadTextAction, runMacOsScreenshotAction, quitMacOsApp, + runMacOsPermissionAction, runMacOsSnapshotAction, } from './helper.ts'; @@ -33,7 +38,7 @@ const nativeApp = macOsHelperSurface('app', 'native')!; test('macOS helper snapshot passes cancellation to the helper process', async () => { const controller = new AbortController(); let receivedSignal: AbortSignal | undefined; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (_args, options) => { receivedSignal = options?.signal; @@ -54,10 +59,10 @@ test('macOS helper snapshot passes cancellation to the helper process', async () }, }); - await withAppleToolProvider( + await withToolbox( provider, - async () => - await runMacOsSnapshotAction(desktop, { env: captureEnv, signal: controller.signal }), + async (box) => + await runMacOsSnapshotAction(box, desktop, { env: captureEnv, signal: controller.signal }), ); assert.equal(receivedSignal, controller.signal); @@ -73,7 +78,7 @@ function helperReturn(data: Record) { test('macOS helper press carries the hold, repeat count, and interval to the click schedule', async () => { let receivedArgs: string[] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { receivedArgs = args; @@ -82,10 +87,10 @@ test('macOS helper press carries the hold, repeat count, and interval to the cli }, }); - const result = await withAppleToolProvider( + const result = await withToolbox( provider, - async () => - await runMacOsPressAction(12, 34, { + async (box) => + await runMacOsPressAction(box, 12, 34, { env: captureEnv, surface: menubar, bundleId: 'com.example.Menu', @@ -117,7 +122,7 @@ test('macOS helper press carries the hold, repeat count, and interval to the cli test('macOS helper press carries an explicit zero interval instead of dropping it', async () => { let receivedArgs: string[] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { receivedArgs = args; @@ -126,10 +131,10 @@ test('macOS helper press carries an explicit zero interval instead of dropping i }, }); - await withAppleToolProvider( + await withToolbox( provider, - async () => - await runMacOsPressAction(7, 8, { + async (box) => + await runMacOsPressAction(box, 7, 8, { env: captureEnv, surface: desktop, clicks: 2, @@ -149,7 +154,7 @@ test('macOS helper press carries an explicit zero interval instead of dropping i test('macOS helper press keeps repeats independent and names a double-click explicitly', async () => { let receivedArgs: string[] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { receivedArgs = args; @@ -158,10 +163,10 @@ test('macOS helper press keeps repeats independent and names a double-click expl }, }); - await withAppleToolProvider( + await withToolbox( provider, - async () => - await runMacOsPressAction(7, 8, { + async (box) => + await runMacOsPressAction(box, 7, 8, { env: captureEnv, surface: frontmostApp, clicks: 3, @@ -183,7 +188,7 @@ test('macOS helper press outlives its own click schedule and forwards cancellati let receivedSignal: AbortSignal | undefined; let receivedKill: { signal: string; graceMs: number } | undefined; const controller = new AbortController(); - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (_args, options) => { receivedTimeoutMs = options?.timeoutMs; @@ -194,10 +199,10 @@ test('macOS helper press outlives its own click schedule and forwards cancellati }, }); - await withAppleToolProvider( + await withToolbox( provider, - async () => - await runMacOsPressAction(1, 2, { + async (box) => + await runMacOsPressAction(box, 1, 2, { env: captureEnv, surface: desktop, holdMs: 10_000, @@ -230,7 +235,7 @@ test('macOS click schedule mirrors the helper floors for the timeout it derives' test('macOS helper press stays a single held click when nothing is repeated', async () => { let receivedArgs: string[] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { receivedArgs = args; @@ -239,9 +244,9 @@ test('macOS helper press stays a single held click when nothing is repeated', as }, }); - await withAppleToolProvider( + await withToolbox( provider, - async () => await runMacOsPressAction(5, 6, { env: captureEnv, surface: frontmostApp }), + async (box) => await runMacOsPressAction(box, 5, 6, { env: captureEnv, surface: frontmostApp }), ); assert.equal(receivedArgs.includes('--clicks'), false); @@ -251,7 +256,7 @@ test('macOS helper press stays a single held click when nothing is repeated', as test('macOS helper screenshot argv carries only --out and --surface', async () => { let receivedArgs: string[] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { receivedArgs = args; @@ -260,10 +265,10 @@ test('macOS helper screenshot argv carries only --out and --surface', async () = }, }); - await withAppleToolProvider( + await withToolbox( provider, - async () => - await runMacOsScreenshotAction('/tmp/out.png', { env: captureEnv, surface: desktop }), + async (box) => + await runMacOsScreenshotAction(box, '/tmp/out.png', { env: captureEnv, surface: desktop }), ); assert.deepEqual(receivedArgs, ['screenshot', '--out', '/tmp/out.png', '--surface', 'desktop']); @@ -274,7 +279,7 @@ for (const hint of [ undefined, ]) { test(`a helper refusal carries its details and hint through untouched (${hint === undefined ? 'no hint' : 'with hint'})`, async () => { - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async () => ({ exitCode: 1, @@ -296,8 +301,8 @@ for (const hint of [ }, }); - const error = await withAppleToolProvider(provider, async () => - runMacOsScreenshotAction('/tmp/out.png', { + const error = await withToolbox(provider, async (box) => + runMacOsScreenshotAction(box, '/tmp/out.png', { surface: nativeApp, bundleId: 'com.apple.TextEdit', env: captureEnv, @@ -318,7 +323,7 @@ for (const hint of [ test('macOS helper screenshots never run two captures at once', async () => { let active = 0; let maxActive = 0; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async () => { active += 1; @@ -331,14 +336,14 @@ test('macOS helper screenshots never run two captures at once', async () => { }); const app = macOsHelperSurface('app', 'native')!; - await withAppleToolProvider(provider, async () => { + await withToolbox(provider, async (box) => { await Promise.all([ - runMacOsScreenshotAction('/tmp/one.png', { + runMacOsScreenshotAction(box, '/tmp/one.png', { env: captureEnv, surface: app, bundleId: 'com.example.one', }), - runMacOsScreenshotAction('/tmp/two.png', { + runMacOsScreenshotAction(box, '/tmp/two.png', { env: captureEnv, surface: app, bundleId: 'com.example.two', @@ -354,15 +359,15 @@ test('helper entry points accept only an owner-routed surface', () => { // unbranded or optional surface. const widenedCalls = async (out: string) => { // @ts-expect-error a bare literal skips the routing owner - await runMacOsSnapshotAction('desktop'); + await runMacOsSnapshotAction(box, 'desktop'); // @ts-expect-error a bare literal skips the routing owner - await runMacOsScreenshotAction(out, { env: captureEnv, surface: 'menubar' }); + await runMacOsScreenshotAction(box, out, { env: captureEnv, surface: 'menubar' }); // @ts-expect-error the surface is required - await runMacOsReadTextAction(1, 2, { bundleId: 'com.example' }); + await runMacOsReadTextAction(box, 1, 2, { bundleId: 'com.example' }); // @ts-expect-error the surface is required - await runMacOsPressAction(1, 2, {}); + await runMacOsPressAction(box, 1, 2, {}); // @ts-expect-error the surface is required - await runMacOsScreenshotAction(out); + await runMacOsScreenshotAction(box, out); }; assert.equal(typeof widenedCalls, 'function'); }); @@ -370,10 +375,7 @@ test('helper entry points accept only an owner-routed surface', () => { test('the helper vocabulary matches the table the Swift helper is held to', () => { const fixture = JSON.parse( readFileSync( - new URL( - '../../../../../contracts/fixtures/macos-native-helper-outcomes.json', - import.meta.url, - ), + new URL('../../../contracts/fixtures/macos-native-helper-outcomes.json', import.meta.url), 'utf8', ), ) as { @@ -391,7 +393,7 @@ test('the helper vocabulary matches the table the Swift helper is held to', () = test('the helper accepts a bundle id with an uppercase first segment and refuses a bare name', async () => { const receivedArgs: string[][] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { receivedArgs.push(args); @@ -405,10 +407,34 @@ test('the helper accepts a bundle id with an uppercase first segment and refuses }, }); - await withAppleToolProvider(provider, async () => { - await quitMacOsApp('Foo.Bar', captureEnv); - await assert.rejects(quitMacOsApp('TextEdit', captureEnv), { code: 'INVALID_ARGS' }); + await withToolbox(provider, async (box) => { + await quitMacOsApp(box, 'Foo.Bar', captureEnv); + await assert.rejects(quitMacOsApp(box, 'TextEdit', captureEnv), { code: 'INVALID_ARGS' }); }); assert.deepEqual(receivedArgs, [['app', 'quit', '--bundle-id', 'Foo.Bar']]); }); + +test('a permission grant names its action and target to the helper and returns its answer', async () => { + const granted = { + target: 'accessibility', + action: 'grant', + granted: true, + requested: true, + openedSettings: false, + }; + let receivedArgs: string[] = []; + const box = macOsToolboxFixture({ + macosHelper: { + run: async (args) => { + receivedArgs = args; + return helperReturn(granted); + }, + }, + }); + + const result = await runMacOsPermissionAction(box, 'grant', 'accessibility', captureEnv); + + assert.deepEqual(receivedArgs, ['permission', 'grant', 'accessibility']); + assert.deepEqual(result, granted); +}); diff --git a/packages/platform-apple/src/os/macos/helper.ts b/packages/platform-macos/src/helper.ts similarity index 79% rename from packages/platform-apple/src/os/macos/helper.ts rename to packages/platform-macos/src/helper.ts index 7efa2dd47f..5bffb3afc1 100644 --- a/packages/platform-apple/src/os/macos/helper.ts +++ b/packages/platform-macos/src/helper.ts @@ -15,28 +15,18 @@ import { renameHostPath, writeHostTextFile, } from '@agent-device/host-kit/host-file'; -import { - hostPlatform, - readCurrentOwnerIdentity, - writeHostStderr, -} from '@agent-device/host-kit/process'; -import { - resolveExecutableOverridePath, - runCmdBackground, - type ExecBackgroundResult, -} from '@agent-device/host-kit/command'; import type { EnvMap } from '@agent-device/kernel/source-value'; import type { MacOsHelperSurface, SessionSurface } from '@agent-device/contracts/session'; -import { - hasScopedAppleToolProvider, - resolveAppleToolProvider, - runAppleToolCommand, -} from '../../core/tool-provider.ts'; - -export type MacOsPermissionTarget = 'accessibility' | 'screen-recording' | 'input-monitoring'; +import type { + MacOsBackgroundProcess, + MacOsDeliveryMechanism, + MacOsPermissionTarget, +} from '@agent-device/contracts/macos-platform-leaf'; +import { resolveDeviceClaimRoot } from '@agent-device/host-kit/file'; +import type { MacOsToolbox } from './toolbox.ts'; // Keep this shape aligned with macOS helper SnapshotNodeResponse in -// apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift. +// macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift. export type MacOsSnapshotNode = { index: number; type?: string; @@ -186,13 +176,20 @@ export const MACOS_DELIVERY_MECHANISMS = [ 'ax-show-menu', 'key-events', ] as const; -/** How an app-surface action reached the app, as the helper reports it. */ -export type MacOsDeliveryMechanism = (typeof MACOS_DELIVERY_MECHANISMS)[number]; +type AssertTrue = T; +/** Compile-time pin: this table and the leaf contract name the same mechanisms. */ +export type MacOsDeliveryMechanismsMatchContract = AssertTrue< + [MacOsDeliveryMechanism] extends [(typeof MACOS_DELIVERY_MECHANISMS)[number]] + ? [(typeof MACOS_DELIVERY_MECHANISMS)[number]] extends [MacOsDeliveryMechanism] + ? true + : false + : false +>; export function resolveMacOsHelperPackageRootFrom(modulePath: string): string { let currentDir = path.dirname(modulePath); while (true) { - const candidate = path.join(currentDir, 'apple', 'macos-helper'); + const candidate = path.join(currentDir, 'macos-helper'); if (hostFileExistsSync(path.join(candidate, 'Package.swift'))) { return candidate; } @@ -236,7 +233,10 @@ async function listMacOsHelperSourceFiles(root: string): Promise { return files.flat().sort(); } -async function computeMacOsHelperFingerprint(packageRoot: string): Promise { +async function computeMacOsHelperFingerprint( + box: MacOsToolbox, + packageRoot: string, +): Promise { const files = await listMacOsHelperSourceFiles(packageRoot); const hash = createHash('sha256'); for (const filePath of files) { @@ -245,7 +245,7 @@ async function computeMacOsHelperFingerprint(packageRoot: string): Promise { } } -async function ensureMacOsHelperBinary(env: Readonly): Promise { - const configuredPath = await resolveExecutableOverridePath( - env[MACOS_HELPER_ENV_PATH], - MACOS_HELPER_ENV_PATH, - ); - if (configuredPath) { - return configuredPath; +/** + * The executable an override variable names. It must be an absolute path the host can execute: + * the host answers the probe, so it reads the same machine the spawn it authorizes runs on. + */ +async function resolveHelperOverridePath( + box: MacOsToolbox, + rawPath: string | undefined, +): Promise { + const candidate = rawPath?.trim(); + if (!candidate) return undefined; + if (!path.isAbsolute(candidate) || candidate.includes('\0')) { + throw new AppError( + 'INVALID_ARGS', + `${MACOS_HELPER_ENV_PATH} must be an absolute executable path, not ${JSON.stringify(rawPath)}`, + { envName: MACOS_HELPER_ENV_PATH, path: rawPath }, + ); } + if (!(await box.host.isFileExecutable(candidate))) { + throw new AppError( + 'TOOL_MISSING', + `${MACOS_HELPER_ENV_PATH} points to a missing or non-executable file: ${candidate}`, + { envName: MACOS_HELPER_ENV_PATH, path: candidate }, + ); + } + return candidate; +} +async function ensureMacOsHelperBinary(box: MacOsToolbox): Promise { const packageRoot = resolveMacOsHelperPackageRoot(); - const sourceFingerprint = await computeMacOsHelperFingerprint(packageRoot); + const sourceFingerprint = await computeMacOsHelperFingerprint(box, packageRoot); const installedPath = resolveInstalledMacOsHelperPath(); try { const installedFingerprint = await readInstalledMacOsHelperFingerprint(); @@ -291,8 +310,12 @@ async function ensureMacOsHelperBinary(env: Readonly): Promise { } const sourceBinary = resolveMacOsHelperSourceBinaryPath(); - writeHostStderr('agent-device: building macOS helper (first run or helper update)\n'); - await runAppleToolCommand('swift', ['build', '-c', 'release', '--package-path', packageRoot], { + box.host.emitDiagnostic({ + level: 'info', + phase: 'macos_helper_build', + data: { packageRoot, reason: 'first run or helper update' }, + }); + await box.tools.runCommand('swift', ['build', '-c', 'release', '--package-path', packageRoot], { cwd: packageRoot, timeoutMs: 120_000, }); @@ -308,41 +331,40 @@ async function ensureMacOsHelperBinary(env: Readonly): Promise { return installedPath; } -async function resolveMacOsHelperCommandPath(env: Readonly): Promise { - const configuredPath = env[MACOS_HELPER_ENV_PATH]?.trim(); - if (configuredPath) { - const resolvedPath = await resolveExecutableOverridePath(configuredPath, MACOS_HELPER_ENV_PATH); - if (resolvedPath) return resolvedPath; - } - if (hasScopedAppleToolProvider()) { +async function resolveMacOsHelperCommandPath( + box: MacOsToolbox, + env: Readonly, +): Promise { + const configuredPath = await resolveHelperOverridePath(box, env[MACOS_HELPER_ENV_PATH]); + if (configuredPath) return configuredPath; + if (box.tools.scoped) { return MACOS_HELPER_PRODUCT_NAME; } - if (hostPlatform() !== 'darwin') { + if (box.host.hostOs !== 'darwin') { throw new AppError('UNSUPPORTED_PLATFORM', 'macOS helper is only available on macOS'); } - return await ensureMacOsHelperBinary(env); + return await ensureMacOsHelperBinary(box); } -export async function startMacOsAudioProbeProcess(options: { - durationMs: number; - bucketMs: number; - statusPath: string; - env: Readonly; -}): Promise { - const helperPath = await resolveMacOsHelperCommandPath(options.env); - return runCmdBackground( - helperPath, - [ - 'audio-probe', - '--duration-ms', - String(options.durationMs), - '--bucket-ms', - String(options.bucketMs), - '--out', - options.statusPath, - ], - { allowFailure: true, captureOutput: true }, - ); +export async function startMacOsAudioProbeProcess( + box: MacOsToolbox, + options: { + durationMs: number; + bucketMs: number; + statusPath: string; + env: Readonly; + }, +): Promise { + const helperPath = await resolveMacOsHelperCommandPath(box, options.env); + return await box.tools.startBackground(helperPath, [ + 'audio-probe', + '--duration-ms', + String(options.durationMs), + '--bucket-ms', + String(options.bucketMs), + '--out', + options.statusPath, + ]); } const MACOS_HELPER_TIMEOUT_MS = 30_000; @@ -356,6 +378,7 @@ const MACOS_HELPER_TIMEOUT_MS = 30_000; const MACOS_HELPER_KILL_GRACE_MS = 1_000; async function runMacOsHelper>( + box: MacOsToolbox, args: string[], options: { signal?: AbortSignal; timeoutMs?: number; env: Readonly }, ): Promise { @@ -365,13 +388,13 @@ async function runMacOsHelper>( signal: options.signal, kill: { signal: 'SIGTERM' as const, graceMs: MACOS_HELPER_KILL_GRACE_MS }, }; - const helperProvider = resolveAppleToolProvider().macosHelper; + const helperProvider = box.tools.helper; const helperPath = helperProvider ? MACOS_HELPER_PRODUCT_NAME - : await resolveMacOsHelperCommandPath(options.env); + : await resolveMacOsHelperCommandPath(box, options.env); const result = helperProvider ? await helperProvider.run(args, helperOptions) - : await runAppleToolCommand(helperPath, args, helperOptions); + : await box.tools.runCommand(helperPath, args, helperOptions); const stdout = result.stdout.trim(); let parsed: HelperResult | null = null; if (stdout) { @@ -405,15 +428,19 @@ async function runMacOsHelper>( }); } -export async function resolveFrontmostMacOsApp(env: Readonly): Promise<{ +export async function resolveFrontmostMacOsApp( + box: MacOsToolbox, + env: Readonly, +): Promise<{ bundleId?: string; appName?: string; pid?: number; }> { - return await runMacOsHelper(['app', 'frontmost'], { env }); + return await runMacOsHelper(box, ['app', 'frontmost'], { env }); } export async function quitMacOsApp( + box: MacOsToolbox, bundleId: string, env: Readonly, ): Promise<{ @@ -422,12 +449,13 @@ export async function quitMacOsApp( terminated: boolean; forceTerminated: boolean; }> { - return await runMacOsHelper(['app', 'quit', '--bundle-id', assertMacOsBundleId(bundleId)], { + return await runMacOsHelper(box, ['app', 'quit', '--bundle-id', assertMacOsBundleId(bundleId)], { env, }); } export async function runMacOsPermissionAction( + box: MacOsToolbox, action: 'grant' | 'reset', target: MacOsPermissionTarget, env: Readonly, @@ -439,10 +467,11 @@ export async function runMacOsPermissionAction( action: 'grant' | 'reset'; message?: string; }> { - return await runMacOsHelper(['permission', action, target], { env }); + return await runMacOsHelper(box, ['permission', action, target], { env }); } export async function runMacOsAlertAction( + box: MacOsToolbox, action: 'get' | 'accept' | 'dismiss', options: { bundleId?: string; surface?: SessionSurface; env: Readonly }, ): Promise<{ @@ -454,10 +483,11 @@ export async function runMacOsAlertAction( }> { const args = ['alert', action]; appendMacOsHelperContextArgs(args, options); - return await runMacOsHelper(args, { env: options.env }); + return await runMacOsHelper(box, args, { env: options.env }); } export async function runMacOsSnapshotAction( + box: MacOsToolbox, surface: MacOsHelperSurface, options: { bundleId?: string; signal?: AbortSignal; env: Readonly }, ): Promise<{ @@ -470,10 +500,11 @@ export async function runMacOsSnapshotAction( }> { const args = ['snapshot', '--surface', surface]; appendMacOsHelperContextArgs(args, options); - return await runMacOsHelper(args, { signal: options.signal, env: options.env }); + return await runMacOsHelper(box, args, { signal: options.signal, env: options.env }); } export async function runMacOsReadTextAction( + box: MacOsToolbox, x: number, y: number, options: { @@ -487,7 +518,7 @@ export async function runMacOsReadTextAction( }> { const args = ['read', '--x', String(x), '--y', String(y)]; appendMacOsHelperContextArgs(args, options); - return await runMacOsHelper(args, { signal: options.signal, env: options.env }); + return await runMacOsHelper(box, args, { signal: options.signal, env: options.env }); } // Mirrors the helper's own floors (`MouseClickSchedule.swift`): the schedule the helper runs @@ -520,6 +551,7 @@ export function macOsClickScheduleMs(options: { } export async function runMacOsPressAction( + box: MacOsToolbox, x: number, y: number, options: { @@ -563,7 +595,7 @@ export async function runMacOsPressAction( } appendMacOsHelperContextArgs(args, options); appendGhostCursorArg(args, options.surface, options.env); - return await runMacOsHelper(args, { + return await runMacOsHelper(box, args, { signal: options.signal, env: options.env, timeoutMs: macOsClickScheduleMs(options) + MACOS_HELPER_TIMEOUT_MS + ghostCursorBudgetMs(args), @@ -572,6 +604,7 @@ export async function runMacOsPressAction( /** Inserts text at the app session's focused element without activating the app. */ export async function runMacOsTypeAction( + box: MacOsToolbox, text: string, options: { bundleId: string; @@ -584,7 +617,7 @@ export async function runMacOsTypeAction( if (options.delayMs && options.delayMs > 0) args.push('--delay-ms', String(options.delayMs)); appendMacOsHelperContextArgs(args, { bundleId: options.bundleId }); appendGhostCursorArg(args, 'app', options.env); - return await runMacOsHelper(args, { + return await runMacOsHelper(box, args, { signal: options.signal, env: options.env, timeoutMs: @@ -594,12 +627,13 @@ export async function runMacOsTypeAction( /** Dispatches one prepared app-surface action with the ghost-cursor settle budget added. */ function runMacOsAppSurfaceAction>( + box: MacOsToolbox, args: string[], options: { bundleId: string; signal?: AbortSignal; env: Readonly }, ): Promise { appendMacOsHelperContextArgs(args, { bundleId: options.bundleId }); appendGhostCursorArg(args, 'app', options.env); - return runMacOsHelper(args, { + return runMacOsHelper(box, args, { signal: options.signal, env: options.env, timeoutMs: MACOS_HELPER_TIMEOUT_MS + ghostCursorBudgetMs(args), @@ -608,12 +642,14 @@ function runMacOsAppSurfaceAction>( /** Replaces the value of the app session's text input at a point. */ export async function runMacOsFillAction( + box: MacOsToolbox, x: number, y: number, text: string, options: { bundleId: string; signal?: AbortSignal; env: Readonly }, ): Promise<{ mechanism?: MacOsDeliveryMechanism; role?: string; windowTitle?: string }> { return await runMacOsAppSurfaceAction( + box, ['fill', '--x', String(x), '--y', String(y), '--text', text], options, ); @@ -621,15 +657,21 @@ export async function runMacOsFillAction( /** Opens the context menu of the app session's element at a point, as a secondary click does. */ export async function runMacOsShowMenuAction( + box: MacOsToolbox, x: number, y: number, options: { bundleId: string; signal?: AbortSignal; env: Readonly }, ): Promise<{ mechanism?: MacOsDeliveryMechanism; role?: string; windowTitle?: string }> { - return await runMacOsAppSurfaceAction(['show-menu', '--x', String(x), '--y', String(y)], options); + return await runMacOsAppSurfaceAction( + box, + ['show-menu', '--x', String(x), '--y', String(y)], + options, + ); } /** Scrolls the scroll area at the center of the app session's front window. */ export async function runMacOsScrollAction( + box: MacOsToolbox, direction: 'up' | 'down' | 'left' | 'right', options: { bundleId: string; @@ -642,10 +684,11 @@ export async function runMacOsScrollAction( const args = ['scroll', '--direction', direction]; if (options.amount !== undefined) args.push('--amount', String(options.amount)); if (options.pixels !== undefined) args.push('--pixels', String(options.pixels)); - return await runMacOsAppSurfaceAction(args, options); + return await runMacOsAppSurfaceAction(box, args, options); } export async function runMacOsScreenshotAction( + box: MacOsToolbox, outPath: string, options: { surface: MacOsHelperSurface; @@ -660,8 +703,9 @@ export async function runMacOsScreenshotAction( const args = ['screenshot', '--out', outPath]; appendMacOsHelperContextArgs(args, options); return await withMacOsScreenCaptureLock( + box, options, - async () => await runMacOsHelper(args, { signal: options.signal, env: options.env }), + async () => await runMacOsHelper(box, args, { signal: options.signal, env: options.env }), ); } @@ -669,27 +713,21 @@ export async function runMacOsScreenshotAction( * ScreenCaptureKit fails or hangs window captures that two processes start at the same time * (measured on macOS 27 with two helpers capturing two apps), so every helper capture on this Mac * runs alone, whichever daemon asks. The lock sits in the host-global device claims directory, - * the store every daemon on the host already coordinates through. + * the store every daemon on the host already coordinates through. The host takes the claim, so + * the owner it records is the process that runs the capture. */ async function withMacOsScreenCaptureLock( + box: MacOsToolbox, options: { env: Readonly; signal?: AbortSignal }, task: () => Promise, ): Promise { - const { acquireProcessLock, withProcessLock, resolveDeviceClaimRoot } = - await import('@agent-device/host-kit/file'); const lockRoot = resolveDeviceClaimRoot(options.env); await ensureHostDirectory(lockRoot); - return await withProcessLock({ - acquire: async () => { - const owner = readCurrentOwnerIdentity(); - return await acquireProcessLock({ - lockDirPath: path.join(path.resolve(lockRoot), 'macos-screen-capture.lock'), - owner: { pid: owner.pid, startTime: owner.startTime, acquiredAtMs: Date.now() }, - timeoutMs: MACOS_HELPER_TIMEOUT_MS + 5_000, - description: 'the macOS screen capture lock', - signal: options.signal, - }); - }, + return await box.host.processes.withLock({ + lockDirPath: path.join(path.resolve(lockRoot), 'macos-screen-capture.lock'), + timeoutMs: MACOS_HELPER_TIMEOUT_MS + 5_000, + description: 'the macOS screen capture lock', + ...(options.signal === undefined ? {} : { signal: options.signal }), task, }); } diff --git a/packages/platform-apple/src/os/macos/host-provider.test.ts b/packages/platform-macos/src/host-provider.test.ts similarity index 80% rename from packages/platform-apple/src/os/macos/host-provider.test.ts rename to packages/platform-macos/src/host-provider.test.ts index 23a4eca08b..1f2886bc49 100644 --- a/packages/platform-apple/src/os/macos/host-provider.test.ts +++ b/packages/platform-macos/src/host-provider.test.ts @@ -2,9 +2,10 @@ import assert from 'node:assert/strict'; import { promises as fs } from 'node:fs'; import path from 'node:path'; import { afterEach, test, vi } from 'vitest'; -import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; -import type { AppleToolCommandExecutor } from '../../core/tool-provider-types.ts'; -import type { ExecResult } from '@agent-device/host-kit/command'; +import { mkdtempForTest } from '@agent-device/test-kit'; +import type { MacOsCommandResult } from '@agent-device/contracts/macos-platform-leaf'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; +import type { MacOsRunCommand } from './toolbox.ts'; // App discovery stats each candidate root through the host-file seam and asks that seam for the // home directory whose `Applications` folder is the third root. Only the two system roots are @@ -30,7 +31,7 @@ vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => { }; }); -import { createLocalAppleMacOsHostProvider } from './host-provider.ts'; +import { createLocalMacOsHostProvider } from './host-provider.ts'; type PlistReader = (plistPath: string) => Promise | null>; @@ -85,8 +86,8 @@ async function declareSystemRoot( function recordingRunCommand(params: { findLinesByRoot?: Record; failingRoots?: readonly string[]; -}): AppleToolCommandExecutor { - return async (cmd, args): Promise => { +}): MacOsRunCommand { + return async (cmd, args): Promise => { if (cmd === 'find' && args[1] === '-maxdepth') { const root = args[0]!; findCalls.push(root); @@ -109,12 +110,14 @@ async function listApps(params: { failingRoots?: readonly string[]; readPlistJson: PlistReader; }): Promise<{ bundleId: string; name: string }[]> { - const provider = createLocalAppleMacOsHostProvider( - recordingRunCommand({ - findLinesByRoot: params.findLinesByRoot, - failingRoots: params.failingRoots, + const provider = createLocalMacOsHostProvider( + macOsToolboxFixture({ + runCommand: recordingRunCommand({ + findLinesByRoot: params.findLinesByRoot, + failingRoots: params.failingRoots, + }), + plist: { readJson: params.readPlistJson }, }), - params.readPlistJson, ); return await provider.listApps(params.filter); } @@ -293,3 +296,58 @@ test('listApps hides Apple bundles for the user-installed filter and shows them { bundleId: 'com.apple.systempreferences', name: 'System Settings' }, ]); }); + +test('the local macOS host routes run their tools as semantic methods', async () => { + const calls: Array<[string, string[], string | undefined]> = []; + const host = createLocalMacOsHostProvider( + macOsToolboxFixture({ + runCommand: async (cmd, args, options) => { + // The bundle open's LaunchServices registration probe is the seam's own read, asserted in + // launch-services-registration.test.ts; this routing test only reports it as listing the bundle. + if (cmd === '/usr/bin/lsappinfo') { + return { exitCode: 0, stdout: 'ASN:0x0-0x1234-"Demo":\n', stderr: '' }; + } + if (cmd === 'ps') { + return { exitCode: 0, stdout: ' 1 0 /sbin/launchd\n', stderr: '' }; + } + calls.push([cmd, args, typeof options?.stdin === 'string' ? options.stdin : undefined]); + if (cmd === 'pbpaste') { + return { exitCode: 0, stdout: 'copied\r\n', stderr: '' }; + } + if (cmd === 'osascript' && args.join(' ').includes('get dark mode')) { + return { exitCode: 0, stdout: 'false\n', stderr: '' }; + } + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }), + ); + + await host.openBundle('com.example.demo', 'demo://open'); + await host.openTarget('https://example.test'); + await host.writeClipboard('secret'); + const clipboard = await host.readClipboard(); + const darkMode = await host.readDarkMode(); + await host.setDarkMode(true); + + assert.equal(clipboard, 'copied'); + assert.equal(darkMode, false); + assert.deepEqual(calls, [ + ['open', ['-b', 'com.example.demo', 'demo://open'], undefined], + ['open', ['https://example.test'], undefined], + ['pbcopy', [], 'secret'], + ['pbpaste', [], undefined], + [ + 'osascript', + ['-e', 'tell application "System Events" to tell appearance preferences to get dark mode'], + undefined, + ], + [ + 'osascript', + [ + '-e', + 'tell application "System Events" to tell appearance preferences to set dark mode to true', + ], + undefined, + ], + ]); +}); diff --git a/packages/platform-apple/src/os/macos/host-provider.ts b/packages/platform-macos/src/host-provider.ts similarity index 78% rename from packages/platform-apple/src/os/macos/host-provider.ts rename to packages/platform-macos/src/host-provider.ts index 6aa6a001df..ede9d00245 100644 --- a/packages/platform-apple/src/os/macos/host-provider.ts +++ b/packages/platform-macos/src/host-provider.ts @@ -1,28 +1,27 @@ import { hostFileStat, hostHomeDirectory } from '@agent-device/host-kit/host-file'; import path from 'node:path'; import type { AppsFilter } from '@agent-device/contracts/device'; -import { AppError } from '@agent-device/kernel/errors'; -import { requireExecSuccess } from '@agent-device/host-kit/command'; -import { filterAppleAppsByBundlePrefix } from '../../core/app-filter.ts'; -import type { IosAppInfo } from '../../core/app-info.ts'; import type { - AppleMacOsHostProvider, - AppleToolCommandExecutor, + MacOsHostProvider, + MacOsInstalledApp, MacOsOpenOptions, -} from '../../core/tool-provider-types.ts'; +} from '@agent-device/contracts/macos-platform-leaf'; +import { AppError, requireCommandSuccess } from '@agent-device/kernel/errors'; +import type { MacOsRunCommand, MacOsToolbox } from './toolbox.ts'; -type ApplePlistJsonReader = (plistPath: string) => Promise | null>; +type PlistJsonReader = (plistPath: string) => Promise | null>; -export function createLocalAppleMacOsHostProvider( - runCommand: AppleToolCommandExecutor, - readPlistJson: ApplePlistJsonReader, -): AppleMacOsHostProvider { +/** The local host routes: `open`, the pasteboard tools, `osascript`, and the app directories. */ +export function createLocalMacOsHostProvider(box: MacOsToolbox): MacOsHostProvider { + const runCommand = box.tools.runCommand; + const readPlistJson: PlistJsonReader = async (plistPath) => + await box.tools.readPlistJson(plistPath); return { openBundle: async (bundleId, url, options) => { // Loaded on the first bundle open, not when this provider is constructed: the probe's host-kit // reads stay off the Apple façades' eager closure (ADR 0019). const { resolveListedRunningBundle } = await import('./launch-services-registration.ts'); - const runningBundle = await resolveListedRunningBundle(runCommand, bundleId); + const runningBundle = await resolveListedRunningBundle(box, bundleId); await runCommand('open', [ ...openActivationArgs(options), ...(runningBundle @@ -34,14 +33,14 @@ export function createLocalAppleMacOsHostProvider( await runCommand('open', [...openActivationArgs(options), target]); }, readClipboard: async () => { - const result = requireExecSuccess( + const result = requireCommandSuccess( await runCommand('pbpaste', [], { allowFailure: true }), 'Failed to read macOS clipboard', ); return result.stdout.replaceAll('\r\n', '\n').replace(/\n$/, ''); }, writeClipboard: async (text) => { - requireExecSuccess( + requireCommandSuccess( await runCommand('pbcopy', [], { allowFailure: true, stdin: text, @@ -52,7 +51,7 @@ export function createLocalAppleMacOsHostProvider( readDarkMode: async () => { const script = 'tell application "System Events" to tell appearance preferences to get dark mode'; - const result = requireExecSuccess( + const result = requireCommandSuccess( await runCommand('osascript', ['-e', script], { allowFailure: true }), 'Failed to read macOS appearance', ); @@ -66,7 +65,7 @@ export function createLocalAppleMacOsHostProvider( }, setDarkMode: async (enabled) => { const script = `tell application "System Events" to tell appearance preferences to set dark mode to ${enabled ? 'true' : 'false'}`; - requireExecSuccess( + requireCommandSuccess( await runCommand('osascript', ['-e', script], { allowFailure: true }), 'Failed to set macOS appearance', ); @@ -92,10 +91,10 @@ function buildMacOpenPathArgs(bundlePath: string, url?: string): string[] { } async function listLocalMacApps( - runCommand: AppleToolCommandExecutor, - readPlistJson: ApplePlistJsonReader, + runCommand: MacOsRunCommand, + readPlistJson: PlistJsonReader, filter: AppsFilter, -): Promise { +): Promise { const appRoots = [ '/Applications', '/System/Applications', @@ -134,21 +133,21 @@ async function listLocalMacApps( return { bundleId, name: bundleInfo.appName ?? path.basename(appPath, '.app'), - } satisfies IosAppInfo; + } satisfies MacOsInstalledApp; }), ); - return filterAppleAppsByBundlePrefix( - apps - .filter((app): app is IosAppInfo => app !== null) - .sort((a, b) => a.name.localeCompare(b.name)), - filter, - ); + const listed = apps + .filter((app): app is MacOsInstalledApp => app !== null) + .sort((a, b) => a.name.localeCompare(b.name)); + return filter === 'user-installed' + ? listed.filter((app) => !app.bundleId.startsWith('com.apple.')) + : listed; } async function readMacOsBundleInfo( appBundlePath: string, - readPlistJson: ApplePlistJsonReader, + readPlistJson: PlistJsonReader, ): Promise<{ bundleId?: string; appName?: string }> { for (const infoPlistPath of [ path.join(appBundlePath, 'Contents', 'Info.plist'), diff --git a/packages/platform-apple/src/os/macos/launch-services-registration.test.ts b/packages/platform-macos/src/launch-services-registration.test.ts similarity index 96% rename from packages/platform-apple/src/os/macos/launch-services-registration.test.ts rename to packages/platform-macos/src/launch-services-registration.test.ts index 51c2510447..a1563d01ce 100644 --- a/packages/platform-apple/src/os/macos/launch-services-registration.test.ts +++ b/packages/platform-macos/src/launch-services-registration.test.ts @@ -2,16 +2,33 @@ import { mkdir, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { AppError } from '@agent-device/kernel/errors'; -import { runCmd, type ExecResult } from '@agent-device/host-kit/command'; -import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; +import { runCmd } from '@agent-device/host-kit/command'; +import { mkdtempForTest } from '@agent-device/test-kit'; +import type { MacOsCommandResult } from '@agent-device/contracts/macos-platform-leaf'; vi.mock('node:timers/promises', () => ({ setTimeout: vi.fn(async () => undefined) })); -vi.mock('@agent-device/host-kit/diagnostics', () => ({ emitDiagnostic: vi.fn() })); import { setTimeout as sleep } from 'node:timers/promises'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { createLocalAppleMacOsHostProvider } from './host-provider.ts'; -import type { AppleToolCommandExecutor } from '../../core/tool-provider-types.ts'; +import { createLocalMacOsHostProvider } from './host-provider.ts'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; +import type { MacOsRunCommand } from './toolbox.ts'; + +/** Every diagnostic the probe records through the host it was bound to. */ +const mockEmitDiagnostic = vi.fn(); + +/** The local host routes over one executor, bound the way the plugin binds them. */ +function localHostProvider( + runCommand: MacOsRunCommand, + readPlistJson: (plistPath: string) => Promise | null>, +) { + return createLocalMacOsHostProvider( + macOsToolboxFixture({ + runCommand, + plist: { readJson: readPlistJson }, + emitDiagnostic: mockEmitDiagnostic, + }), + ); +} const BUNDLE_ID = 'com.example.demo'; const DEMO_BUNDLE = '/Users/dev/DerivedData/Demo.app'; @@ -41,7 +58,7 @@ function psRows(rows: ReadonlyArray): s type RecordedCall = Readonly<{ cmd: string; args: string[]; timeoutMs: number | undefined }>; -type Stub = Partial | Error; +type Stub = Partial | Error; /** * The host tools one bundle open reads — `lsappinfo`, `ps`, `plutil`, and `open` itself — answered @@ -51,12 +68,12 @@ type Stub = Partial | Error; * test can make the scan throw, fail, or time out like any other read. */ function fakeMacHost(respond: (call: RecordedCall, index: number) => Stub = () => ({})): { - runCommand: AppleToolCommandExecutor; + runCommand: MacOsRunCommand; calls: RecordedCall[]; transcript(): Array<{ cmd: string; args: string[] }>; } { const calls: RecordedCall[] = []; - const runCommand: AppleToolCommandExecutor = async (cmd, args, options) => { + const runCommand: MacOsRunCommand = async (cmd, args, options) => { const call = { cmd, args, timeoutMs: options?.timeoutMs }; const index = calls.push(call) - 1; const answer = respond(call, index); @@ -103,8 +120,8 @@ function noRunningApps(): void { processTable.stdout = psRows([[1, '/sbin/launchd']]); } -function openBundle(runCommand: AppleToolCommandExecutor): Promise { - return createLocalAppleMacOsHostProvider(runCommand, async () => null).openBundle(BUNDLE_ID); +function openBundle(runCommand: MacOsRunCommand): Promise { + return localHostProvider(runCommand, async () => null).openBundle(BUNDLE_ID); } function registrationReads(calls: readonly RecordedCall[]): RecordedCall[] { @@ -112,7 +129,6 @@ function registrationReads(calls: readonly RecordedCall[]): RecordedCall[] { } const mockSleep = vi.mocked(sleep); -const mockEmitDiagnostic = vi.mocked(emitDiagnostic); beforeEach(() => { // The table resets with every test so a later test's `not.toHaveBeenCalled`-style expectation on @@ -153,11 +169,9 @@ test('openBundle sends a link to the listed running copy by its own path', async return {}; }); - await createLocalAppleMacOsHostProvider(runCommand, async () => null).openBundle( - BUNDLE_ID, - 'demo://item/1', - { background: true }, - ); + await localHostProvider(runCommand, async () => null).openBundle(BUNDLE_ID, 'demo://item/1', { + background: true, + }); expect(calls.at(-1)).toEqual({ cmd: 'open', args: ['-g', '-a', DEMO_BUNDLE, 'demo://item/1'] }); }); @@ -776,7 +790,7 @@ describe.skipIf(process.platform !== 'darwin')( // real bundle that is not actually running, and a real `open` would launch a real copy. Only // the target's own pid ever reports an ASN, so the wait ends only if pairing handed the probe // that pid. - const runCommand: AppleToolCommandExecutor = async (cmd, args, options) => { + const runCommand: MacOsRunCommand = async (cmd, args, options) => { if (cmd === 'open') return { exitCode: 0, stdout: '', stderr: '' }; if (cmd === PROCESS_TABLE_TOOL) { return { exitCode: 0, stdout: processTable.stdout, stderr: '' }; diff --git a/packages/platform-apple/src/os/macos/launch-services-registration.ts b/packages/platform-macos/src/launch-services-registration.ts similarity index 87% rename from packages/platform-apple/src/os/macos/launch-services-registration.ts rename to packages/platform-macos/src/launch-services-registration.ts index e0845ed14f..3425626e37 100644 --- a/packages/platform-apple/src/os/macos/launch-services-registration.ts +++ b/packages/platform-macos/src/launch-services-registration.ts @@ -1,11 +1,25 @@ import path from 'node:path'; import { setTimeout as sleep } from 'node:timers/promises'; import { AppError } from '@agent-device/kernel/errors'; -import { isCommandTimeoutError, type ExecResult } from '@agent-device/host-kit/command'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { listHostProcesses } from '@agent-device/host-kit/process'; -import { Deadline } from '@agent-device/host-kit/retry'; -import type { AppleToolCommandExecutor } from '../../core/tool-provider-types.ts'; +import type { MacOsCommandResult } from '@agent-device/contracts/macos-platform-leaf'; +import type { MacOsToolbox } from './toolbox.ts'; + +/** The one budget every read of a probe shares. */ +type Deadline = Readonly<{ remainingMs(): number }>; + +function deadlineAfter(timeoutMs: number): Deadline { + const expiresAtMs = Date.now() + timeoutMs; + return { remainingMs: () => Math.max(0, expiresAtMs - Date.now()) }; +} + +/** A read the host killed at its own `timeoutMs`, classified by its typed details. */ +function isCommandTimeout(error: unknown): boolean { + return ( + error instanceof AppError && + error.code === 'COMMAND_FAILED' && + typeof error.details?.timeoutMs === 'number' + ); +} const LAUNCH_SERVICES_POLL_MS = 200; const LAUNCH_SERVICES_MAX_POLLS = 10; @@ -56,20 +70,17 @@ const LSAPPINFO_ASN = /ASN:/; * delay a duplicate, never cause one, and never withhold the open. */ export async function resolveListedRunningBundle( - runCommand: AppleToolCommandExecutor, + box: MacOsToolbox, bundleId: string, ): Promise { - const deadline = Deadline.fromTimeoutMs(LAUNCH_SERVICES_PROBE_BUDGET_MS); + const deadline = deadlineAfter(LAUNCH_SERVICES_PROBE_BUDGET_MS); try { - const listed = await readsLaunchServicesInstance(runCommand, bundleId, deadline); + const listed = await readsLaunchServicesInstance(box, bundleId, deadline); // A read that cannot answer leaves this open the way it was before the check existed. if (listed === undefined) return undefined; - const running = await findRunningInstances(runCommand, bundleId, deadline); + const running = await findRunningInstances(box, bundleId, deadline); if (running.size === 0) return undefined; - if ( - !listed && - !(await waitForListing(runCommand, bundleId, [...running.values()].flat(), deadline)) - ) { + if (!listed && !(await waitForListing(box, bundleId, [...running.values()].flat(), deadline))) { return undefined; } return running.size === 1 ? [...running.keys()][0] : undefined; @@ -77,7 +88,7 @@ export async function resolveListedRunningBundle( // The probe is an extra read on someone else's app launch, so a host that cannot answer it at // all gets the open it would have had without the probe. The diagnostic is the only trace of // why a duplicate still happened. - emitDiagnostic({ + box.host.emitDiagnostic({ level: 'warn', phase: 'macos_launch_services_registration_probe_failed', data: { @@ -90,7 +101,7 @@ export async function resolveListedRunningBundle( } async function waitForListing( - runCommand: AppleToolCommandExecutor, + box: MacOsToolbox, bundleId: string, pids: readonly number[], deadline: Deadline, @@ -104,7 +115,7 @@ async function waitForListing( // rather than being read as a registration, which is what would hand the duplicate back. A // read that cannot run at all ends the probe, which opens the bundle the way an unreadable // host always did. - if ((await readsLaunchServicesInstance(runCommand, bundleId, deadline, pid)) === true) { + if ((await readsLaunchServicesInstance(box, bundleId, deadline, pid)) === true) { return true; } } @@ -121,16 +132,16 @@ async function waitForListing( * the caller holds refuses to read it as one, because that wait ends on its own bound. */ async function readsLaunchServicesInstance( - runCommand: AppleToolCommandExecutor, + box: MacOsToolbox, bundleId: string, deadline: Deadline, pid?: number, ): Promise { const timeoutMs = probeBudgetMs(deadline, LAUNCH_SERVICES_READ_TIMEOUT_MS); if (timeoutMs === undefined) return undefined; - let result: ExecResult; + let result: MacOsCommandResult; try { - result = await runCommand( + result = await box.tools.runCommand( LAUNCH_SERVICES_TOOL, ['find', `bundleid=${bundleId}`, ...(pid === undefined ? [] : [`pid=${pid}`])], { allowFailure: true, timeoutMs }, @@ -138,7 +149,7 @@ async function readsLaunchServicesInstance( } catch (error) { // A read killed at its own budget answers nothing, the way a non-zero exit does. Only a tool that // cannot run at all is worth ending the whole probe for. - if (isCommandTimeoutError(error)) return undefined; + if (isCommandTimeout(error)) return undefined; throw error; } if (result.exitCode !== 0) return undefined; @@ -147,7 +158,7 @@ async function readsLaunchServicesInstance( } async function findRunningInstances( - runCommand: AppleToolCommandExecutor, + box: MacOsToolbox, bundleId: string, deadline: Deadline, ): Promise> { @@ -156,12 +167,12 @@ async function findRunningInstances( // The provider's own executor, so every read of this probe answers about the same host its // `lsappinfo`, `plutil` and `open` run on: a scoped Apple provider must never pair pids from one // host with tools on another. - const processes = await listHostProcesses({ runCommand, timeoutMs }); + const processes = await box.tools.listProcesses({ timeoutMs }); if (processes.length === 0) { // A macOS host always has a process table, so no rows at all is the read failing rather than a // host running nothing. The open proceeds without this probe knowing anything, so the reason is // worth leaving behind. - emitDiagnostic({ + box.host.emitDiagnostic({ level: 'warn', phase: 'macos_launch_services_process_table_unreadable', data: { bundleId }, @@ -179,7 +190,7 @@ async function findRunningInstances( if (pidsByBundle.size === 0) return pidsByBundle; const bundlePaths = Array.from(pidsByBundle.keys()); const bundleIds = await readAppBundleIds( - runCommand, + box, bundlePaths.map((bundlePath) => path.join(bundlePath, APP_BUNDLE_INFO_PLIST)), deadline, ); @@ -219,13 +230,13 @@ function macAppBundlePath(command: string): string | undefined { * to. */ async function readAppBundleIds( - runCommand: AppleToolCommandExecutor, + box: MacOsToolbox, plistPaths: readonly string[], deadline: Deadline, ): Promise> { const timeoutMs = probeBudgetMs(deadline, BUNDLE_ID_READ_TIMEOUT_MS); if (timeoutMs === undefined) return new Map(); - const result = await runCommand( + const result = await box.tools.runCommand( BUNDLE_ID_TOOL, ['-extract', BUNDLE_ID_KEY, 'raw', ...plistPaths], { allowFailure: true, timeoutMs }, diff --git a/packages/platform-apple/src/os/macos/native-app-interactor.test.ts b/packages/platform-macos/src/native-app-actions.test.ts similarity index 81% rename from packages/platform-apple/src/os/macos/native-app-interactor.test.ts rename to packages/platform-macos/src/native-app-actions.test.ts index 1f2fe051d0..0bf00736f0 100644 --- a/packages/platform-apple/src/os/macos/native-app-interactor.test.ts +++ b/packages/platform-macos/src/native-app-actions.test.ts @@ -3,8 +3,10 @@ import assert from 'node:assert/strict'; import { afterEach, beforeEach, test, vi } from 'vitest'; import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types'; import { AppError } from '@agent-device/kernel/errors'; -import { createLocalAppleToolProvider, withAppleToolProvider } from '../../core/tool-provider.ts'; -import { macOsNativeAppInteractor } from './native-app-interactor.ts'; +import type { MacOsNativeAppActions } from '@agent-device/contracts/macos-platform-leaf'; +import { macOsNativeAppActions } from './native-app-actions.ts'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; +import type { MacOsToolbox } from './toolbox.ts'; bindTestCommandHost(); @@ -18,7 +20,7 @@ afterEach(() => { vi.unstubAllEnvs(); }); -/** The XCTest-backed interactor the native one draws from; any member it calls is recorded. */ +/** The Apple owner's interactor the native actions go back to; any member they call is recorded. */ function runnerInteractor(reached: string[] = []): Interactor { return new Proxy({} as Interactor, { get: (_target, member) => async () => { @@ -28,17 +30,21 @@ function runnerInteractor(reached: string[] = []): Interactor { }); } -function nativeInteractor(ctx: RunnerContext = context, reached: string[] = []): Interactor { - return macOsNativeAppInteractor(runnerInteractor(reached), ctx, process.env); +function nativeInteractor( + ctx: RunnerContext = context, + reached: string[] = [], + box: MacOsToolbox = macOsToolboxFixture(), +): MacOsNativeAppActions { + return macOsNativeAppActions(box, runnerInteractor(reached), ctx, process.env); } async function recordHelperCalls( data: Record, - run: (interactor: Interactor) => Promise, + run: (interactor: MacOsNativeAppActions) => Promise, ): Promise<{ calls: string[][]; result: unknown }> { const calls: string[][] = []; const reachedRunner: string[] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { calls.push([...args]); @@ -46,10 +52,7 @@ async function recordHelperCalls( }, }, }); - const result = await withAppleToolProvider( - provider, - async () => await run(nativeInteractor(context, reachedRunner)), - ); + const result = await run(nativeInteractor(context, reachedRunner, provider)); // Served through the helper alone: the XCTest-backed interactor never ran. assert.deepEqual(reachedRunner, []); return { calls, result }; @@ -80,7 +83,7 @@ test('a native tap presses the app surface under the ghost cursor and reports th test('a native secondary click opens the context menu at the point through the helper', async () => { const { calls, result } = await recordHelperCalls( { x: 10, y: 20, mechanism: 'ax-show-menu', windowTitle: 'Untitled' }, - async (interactor) => await interactor.pressPoint!({ x: 10, y: 20 }, secondaryClick), + async (interactor) => await interactor.pressPoint({ x: 10, y: 20 }, secondaryClick), ); assert.deepEqual(calls, [ ['show-menu', '--x', '10', '--y', '20', '--bundle-id', 'com.apple.TextEdit', '--ghost-cursor'], @@ -159,7 +162,7 @@ test('AGENT_DEVICE_MACOS_GHOST_CURSOR=0 sends the action without a drawn cursor' test('only a drawn cursor extends the helper deadline', async () => { const deadlines: Array = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (_args, options) => { deadlines.push(options?.timeoutMs); @@ -167,9 +170,9 @@ test('only a drawn cursor extends the helper deadline', async () => { }, }, }); - await withAppleToolProvider(provider, async () => await nativeInteractor().fill(1, 2, 'x')); + await nativeInteractor(context, [], provider).fill(1, 2, 'x'); vi.stubEnv('AGENT_DEVICE_MACOS_GHOST_CURSOR', '0'); - await withAppleToolProvider(provider, async () => await nativeInteractor().fill(1, 2, 'x')); + await nativeInteractor(context, [], provider).fill(1, 2, 'x'); assert.equal(deadlines[0]! - deadlines[1]!, 1_000); }); @@ -179,15 +182,12 @@ test('runner-only members refuse with the backend reason instead of starting XCT for (const refused of [ () => interactor.back(), () => interactor.setOrientation('portrait'), - () => interactor.pressPoint!({ x: 1, y: 2 }, { ...primaryClick, doubleTap: true }), - () => interactor.pressPoint!({ x: 1, y: 2 }, { ...primaryClick, holdMs: 500 }), + () => interactor.pressPoint({ x: 1, y: 2 }, { ...primaryClick, doubleTap: true }), + () => interactor.pressPoint({ x: 1, y: 2 }, { ...primaryClick, holdMs: 500 }), () => interactor.longPress(1, 2, 500), ]) { await assert.rejects(refused, isNativeBackendRefusal); } - assert.equal(interactor.gestureViewport, undefined); - assert.equal(interactor.doubleTap, undefined); - assert.equal(interactor.findText, undefined); assert.deepEqual(reached, []); }); @@ -201,7 +201,7 @@ test('an action without an app session refuses rather than falling back to the r test('a press on another surface stays with the helper press of that surface', async () => { const reached: string[] = []; - await nativeInteractor(context, reached).pressPoint!( + await nativeInteractor(context, reached).pressPoint( { x: 1, y: 2 }, { ...primaryClick, surface: 'menubar' }, ); @@ -209,7 +209,7 @@ test('a press on another surface stays with the helper press of that surface', a }); test('a helper refusal surfaces as an unsupported operation that keeps the helper reason', async () => { - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async () => ({ exitCode: 1, @@ -225,8 +225,7 @@ test('a helper refusal surfaces as an unsupported operation that keeps the helpe }, }); await assert.rejects( - async () => - await withAppleToolProvider(provider, async () => await nativeInteractor().tap(1, 2)), + async () => await nativeInteractor(context, [], provider).tap(1, 2), (error: unknown) => isNativeBackendRefusal(error) && (error as AppError).details?.helperReason === 'no-accessible-target', diff --git a/packages/platform-apple/src/os/macos/native-app-interactor.ts b/packages/platform-macos/src/native-app-actions.ts similarity index 76% rename from packages/platform-apple/src/os/macos/native-app-interactor.ts rename to packages/platform-macos/src/native-app-actions.ts index 557a472e43..622272262a 100644 --- a/packages/platform-apple/src/os/macos/native-app-interactor.ts +++ b/packages/platform-macos/src/native-app-actions.ts @@ -3,11 +3,15 @@ import type { PressPointOptions, RunnerContext, } from '@agent-device/contracts/interactor-types'; +import type { MacOsNativeAppActions } from '@agent-device/contracts/macos-platform-leaf'; import { macOsHelperSurface } from '@agent-device/contracts/session'; -import { assertScrollGestureInput } from '@agent-device/contracts/scroll-gesture'; import { AppError } from '@agent-device/kernel/errors'; import type { EnvMap } from '@agent-device/kernel/source-value'; -import { normalizeAppleScrollResultWithResolvedFrame } from '../../core/scroll.ts'; +import { + assertScrollGestureInput, + normalizeAppleScrollResultWithResolvedFrame, +} from '@agent-device/contracts/scroll-gesture'; +import type { MacOsToolbox } from './toolbox.ts'; import { MACOS_HELPER_REFUSAL_REASONS, runMacOsFillAction, @@ -23,17 +27,18 @@ const NATIVE_BACKEND_HINT = 'The native macOS app backend acts through accessibility actions only. Unset AGENT_DEVICE_MACOS_APP_BACKEND to drive this app with XCTest.'; /** - * The macOS interactor of the native backend. It is assembled member by member so that nothing - * reaches the XCTest runner: actions on the session app go through the macOS helper, and only - * members whose macOS implementation uses local tooling or the helper are taken from `base`. - * Runner-only commands are refused at admission by `macOsNativeBackendFacts`; the members the + * The actions of the native backend on the session app. Each goes through the macOS helper, so + * nothing here reaches the XCTest runner. The Apple owner assembles the session interactor from + * these and from its own members whose macOS implementation uses local tooling or the helper. + * Runner-only commands are refused at admission by `MACOS_NATIVE_BACKEND_FACTS`; the members the * interface requires for them refuse the same way. */ -export function macOsNativeAppInteractor( - base: Interactor, +export function macOsNativeAppActions( + box: MacOsToolbox, + base: Pick, ctx: RunnerContext, env: Readonly, -): Interactor { +): MacOsNativeAppActions { const bundleId = (): string => { if (ctx.appBundleId) return ctx.appBundleId; throw nativeBackendRefusal('an action on a session that names no app'); @@ -43,7 +48,7 @@ export function macOsNativeAppInteractor( options: Partial> = {}, ) => { const result = await withHelperRefusals( - runMacOsPressAction(point.x, point.y, { + runMacOsPressAction(box, point.x, point.y, { surface: NATIVE_APP_SURFACE, bundleId: bundleId(), clicks: options.count, @@ -55,19 +60,6 @@ export function macOsNativeAppInteractor( return actedOn(result); }; return { - open: base.open, - openDevice: base.openDevice, - close: base.close, - screenshot: base.screenshot, - snapshot: base.snapshot, - readTextAtPoint: base.readTextAtPoint, - readClipboard: base.readClipboard, - writeClipboard: base.writeClipboard, - setSetting: base.setSetting, - readAlert: base.readAlert, - awaitAlert: base.awaitAlert, - acceptAlert: base.acceptAlert, - dismissAlert: base.dismissAlert, tap: async (x, y) => await press({ x, y }), pressPoint: async (point, options) => { // Another surface's press is the helper's own surface press, never the runner's. @@ -76,7 +68,7 @@ export function macOsNativeAppInteractor( } if (options.button === 'secondary') { const result = await withHelperRefusals( - runMacOsShowMenuAction(point.x, point.y, { + runMacOsShowMenuAction(box, point.x, point.y, { bundleId: bundleId(), signal: ctx.signal, env, @@ -95,19 +87,19 @@ export function macOsNativeAppInteractor( focus: async (x, y) => await press({ x, y }), type: async (text, delayMs) => { await withHelperRefusals( - runMacOsTypeAction(text, { bundleId: bundleId(), delayMs, signal: ctx.signal, env }), + runMacOsTypeAction(box, text, { bundleId: bundleId(), delayMs, signal: ctx.signal, env }), ); }, fill: async (x, y, text) => { const result = await withHelperRefusals( - runMacOsFillAction(x, y, text, { bundleId: bundleId(), signal: ctx.signal, env }), + runMacOsFillAction(box, x, y, text, { bundleId: bundleId(), signal: ctx.signal, env }), ); return actedOn(result); }, scroll: async (direction, options) => { assertScrollGestureInput(options ?? {}); const result = await withHelperRefusals( - runMacOsScrollAction(direction, { + runMacOsScrollAction(box, direction, { bundleId: bundleId(), amount: options?.amount, pixels: options?.pixels, diff --git a/packages/platform-macos/src/native-backend-facts.test.ts b/packages/platform-macos/src/native-backend-facts.test.ts new file mode 100644 index 0000000000..e7fde33cd5 --- /dev/null +++ b/packages/platform-macos/src/native-backend-facts.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from 'vitest'; +import { MACOS_NATIVE_BACKEND_FACTS } from './native-backend-facts.ts'; + +test('the native backend refuses every runner-only macOS operation at admission', () => { + for (const operation of [ + 'screenRecordingStart', + 'screenRecordingReattach', + 'prepareAppleRunner', + 'longPressPoint', + 'back', + 'performGesturePlan', + 'performDirectionalFlingPlan', + 'performMultiTouchGesturePlan', + 'performTargetAuthoredDrag', + 'gestureViewport', + ]) { + expect(MACOS_NATIVE_BACKEND_FACTS).toHaveProperty(operation, { + available: false, + reason: 'unsupported-device-backend', + hint: expect.stringContaining('AGENT_DEVICE_MACOS_APP_BACKEND'), + }); + } +}); diff --git a/packages/platform-macos/src/native-backend-facts.ts b/packages/platform-macos/src/native-backend-facts.ts new file mode 100644 index 0000000000..033911c659 --- /dev/null +++ b/packages/platform-macos/src/native-backend-facts.ts @@ -0,0 +1,24 @@ +import { backRuntimeOperationFacts } from '@agent-device/contracts/back-runtime'; +import { gestureRuntimeOperationFacts } from '@agent-device/contracts/gesture-runtime'; +import type { RuntimeOperationUnavailability } from '@agent-device/contracts/platform-runtime'; + +const nativeBackendUnavailable: RuntimeOperationUnavailability = Object.freeze({ + available: false, + reason: 'unsupported-device-backend', + hint: 'The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.', +}); + +/** + * The macOS operations only the XCTest runner can serve. Under the native backend they are + * refused at admission, before dispatch, for every macOS session of the daemon: the backend is a + * daemon setting, so no session on it may start the runner. The Apple owner spreads them last over + * the leaf's facts. + */ +export const MACOS_NATIVE_BACKEND_FACTS = Object.freeze({ + screenRecordingStart: nativeBackendUnavailable, + screenRecordingReattach: nativeBackendUnavailable, + prepareAppleRunner: nativeBackendUnavailable, + longPressPoint: nativeBackendUnavailable, + ...backRuntimeOperationFacts({ back: nativeBackendUnavailable }), + ...gestureRuntimeOperationFacts({ unsupported: nativeBackendUnavailable }), +}); diff --git a/packages/platform-macos/src/runner-commands-runner-requests.test.ts b/packages/platform-macos/src/runner-commands-runner-requests.test.ts new file mode 100644 index 0000000000..274036cba7 --- /dev/null +++ b/packages/platform-macos/src/runner-commands-runner-requests.test.ts @@ -0,0 +1,41 @@ +import { test } from 'vitest'; +import { assertProducedRunnerRequests } from '@agent-device/test-kit'; +import type { MacOsRunner, MacOsRunnerCommand } from '@agent-device/contracts/macos-platform-leaf'; +import { runMacOsAlternateClick, runMacOsDesktopScroll } from './runner-commands.ts'; + +// The macOS wire cases of the Apple XCTest runner that this package maps commands to, driven through +// the leaf's own entry points and pinned to contracts/fixtures/runner-requests.json. The Apple owner +// binds the runner to a device and adds the transport's command id; the request here is what the +// leaf hands that capability. + +const APP = 'com.example.app'; +const context = { appBundleId: APP }; + +type Drive = (runner: MacOsRunner) => Promise; + +const SITES: Record = { + 'macos.desktop-scroll.amount': (runner) => + runMacOsDesktopScroll(runner, context, {}, 'down', { amount: 0.5, durationMs: 300 }), + 'macos.desktop-scroll.pixels': (runner) => + runMacOsDesktopScroll(runner, context, {}, 'up', { pixels: 200, durationMs: 300 }), + 'macos.interactions-mouse-click.secondary': (runner) => + runMacOsAlternateClick(runner, context, {}, { x: 10, y: 20 }, 'secondary'), + 'macos.interactions-mouse-click.middle': (runner) => + runMacOsAlternateClick(runner, context, {}, { x: 10, y: 20 }, 'middle'), +}; + +test('every macOS leaf request site builds exactly its golden runner request', async () => { + const captured: Array = []; + for (const [name, drive] of Object.entries(SITES)) { + const sent: MacOsRunnerCommand[] = []; + await drive({ + run: async (command) => { + sent.push(command); + return {}; + }, + }); + if (sent.length !== 1) throw new Error(`${name} must send exactly one runner request`); + captured.push([name, sent[0]!]); + } + assertProducedRunnerRequests(import.meta.filename, captured); +}); diff --git a/packages/platform-macos/src/runner-commands.ts b/packages/platform-macos/src/runner-commands.ts new file mode 100644 index 0000000000..3c2d7c144c --- /dev/null +++ b/packages/platform-macos/src/runner-commands.ts @@ -0,0 +1,47 @@ +import { + normalizeAppleScrollResultWithResolvedFrame, + scrollRunnerFields, + type ScrollDirection, +} from '@agent-device/contracts/scroll-gesture'; +import type { RunnerCallOptions, RunnerContext } from '@agent-device/contracts/interactor-types'; +import type { MacOsRunner } from '@agent-device/contracts/macos-platform-leaf'; +import type { ScrollExecutionOptions } from '@agent-device/contracts/scroll-command'; + +/** + * The XCTest app backend's macOS-only commands. The Apple owner keeps the runner and its two macOS + * wire cases; this module maps a desktop scroll and an alternate click onto them through the + * device-bound runner the owner hands in. + */ +export async function runMacOsDesktopScroll( + runner: MacOsRunner, + context: RunnerContext, + runnerOptions: RunnerCallOptions, + direction: ScrollDirection, + options?: ScrollExecutionOptions, +): Promise> { + const runnerResult = await runner.run( + { + command: 'desktopScroll', + direction, + ...scrollRunnerFields(options, { includeDuration: true, includeReleaseBehavior: false }), + appBundleId: context.appBundleId, + }, + runnerOptions, + ); + return normalizeAppleScrollResultWithResolvedFrame(runnerResult, direction, options, { + includeDuration: true, + }); +} + +export async function runMacOsAlternateClick( + runner: MacOsRunner, + context: RunnerContext, + runnerOptions: RunnerCallOptions, + point: { x: number; y: number }, + button: 'secondary' | 'middle', +): Promise> { + return await runner.run( + { command: 'mouseClick', x: point.x, y: point.y, button, appBundleId: context.appBundleId }, + runnerOptions, + ); +} diff --git a/packages/platform-apple/src/os/macos/surface-snapshot.test.ts b/packages/platform-macos/src/surface-snapshot.test.ts similarity index 78% rename from packages/platform-apple/src/os/macos/surface-snapshot.test.ts rename to packages/platform-macos/src/surface-snapshot.test.ts index 830f8741d2..b2e9e3da7c 100644 --- a/packages/platform-apple/src/os/macos/surface-snapshot.test.ts +++ b/packages/platform-macos/src/surface-snapshot.test.ts @@ -1,12 +1,16 @@ import { expect, test } from 'vitest'; import { macOsHelperSurface } from '@agent-device/contracts/session'; -import { createLocalAppleToolProvider, withAppleToolProvider } from '../../core/tool-provider.ts'; +import { macOsToolboxFixture } from './toolbox.fixtures.ts'; +import type { MacOsToolbox } from './toolbox.ts'; + +const withToolbox = async (box: MacOsToolbox, run: (box: MacOsToolbox) => Promise) => + await run(box); import { captureMacOsSurfaceSnapshot } from './surface-snapshot.ts'; test('an app snapshot carries the helper warning that web content may be missing', async () => { const warning = "The app's Chromium accessibility tree did not populate."; const calls: string[][] = []; - const provider = createLocalAppleToolProvider({ + const provider = macOsToolboxFixture({ macosHelper: { run: async (args) => { calls.push([...args]); @@ -27,10 +31,11 @@ test('an app snapshot carries the helper warning that web content may be missing }, }, }); - const result = await withAppleToolProvider( + const result = await withToolbox( provider, - async () => + async (box) => await captureMacOsSurfaceSnapshot( + box, { surface: macOsHelperSurface('app', 'native')!, appBundleId: 'com.openai.codex', diff --git a/packages/platform-apple/src/os/macos/surface-snapshot.ts b/packages/platform-macos/src/surface-snapshot.ts similarity index 66% rename from packages/platform-apple/src/os/macos/surface-snapshot.ts rename to packages/platform-macos/src/surface-snapshot.ts index 791b423096..76a7c04be9 100644 --- a/packages/platform-apple/src/os/macos/surface-snapshot.ts +++ b/packages/platform-macos/src/surface-snapshot.ts @@ -1,14 +1,11 @@ -import type { CaptureSnapshotInput } from '@agent-device/contracts/snapshot-runtime'; -import type { MacOsHelperSurface } from '@agent-device/contracts/session'; +import type { MacOsSurfaceSnapshotOptions } from '@agent-device/contracts/macos-platform-leaf'; +import type { MacOsToolbox } from './toolbox.ts'; import type { EnvMap } from '@agent-device/kernel/source-value'; import { shapeDesktopSurfaceSnapshot } from '@agent-device/capture-kit/snapshot-desktop-projection'; -type SnapshotSurfaceOptions = Omit, 'surface'> & { - surface: MacOsHelperSurface; -}; - export async function captureMacOsSurfaceSnapshot( - options: SnapshotSurfaceOptions, + box: MacOsToolbox, + options: MacOsSurfaceSnapshotOptions, signal: AbortSignal | undefined, env: Readonly, ) { @@ -17,7 +14,7 @@ export async function captureMacOsSurfaceSnapshot( import('./helper.ts'), import('@agent-device/contracts/snapshot-producers'), ]); - const result = await runMacOsSnapshotAction(surface, { + const result = await runMacOsSnapshotAction(box, surface, { bundleId: surface === 'menubar' || surface === 'app' ? options.appBundleId : undefined, signal, env, diff --git a/src/core/__tests__/interactors.test.ts b/src/core/__tests__/interactors.test.ts index 7d2a0ba47a..b5163e68c4 100644 --- a/src/core/__tests__/interactors.test.ts +++ b/src/core/__tests__/interactors.test.ts @@ -9,6 +9,11 @@ import type { ProviderDeviceRuntime } from '@agent-device/contracts/device'; import { getInteractor, getLocalInteractor } from '../interactors.ts'; import { createLiveTestHostEnvironment } from '@agent-device/test-kit'; +import { macOsPlatformCompositionFixture } from '../../platform-runtime-macos-leaf.fixtures.ts'; + +// macOS desktop automation is the managed macOS package's: composing it binds the leaf to the +// bundled Apple owner, as the daemon's composition does. +macOsPlatformCompositionFixture(); const iosSimulator: DeviceInfo = { platform: 'apple', diff --git a/src/core/interactors-app-events.test.ts b/src/core/interactors-app-events.test.ts index 7db8b4e9d9..a5bc122193 100644 --- a/src/core/interactors-app-events.test.ts +++ b/src/core/interactors-app-events.test.ts @@ -14,9 +14,14 @@ import { mkdtempForTest, } from '@agent-device/test-kit'; import { getInteractor } from './interactors.ts'; +import { macOsPlatformCompositionFixture } from '../platform-runtime-macos-leaf.fixtures.ts'; bindTestCommandHost(); +// macOS desktop automation is the managed macOS package's: composing it binds the leaf to the +// bundled Apple owner, as the daemon's composition does. +macOsPlatformCompositionFixture(); + async function triggerEvent(device: DeviceInfo, eventUrl: string, appBundleId?: string) { const operations = bindAdmittedLocalInteractorOperations({ operations: INTERACTOR_OPERATIONS, diff --git a/src/daemon-composition.test.ts b/src/daemon-composition.test.ts index dab016d995..c30a7488a6 100644 --- a/src/daemon-composition.test.ts +++ b/src/daemon-composition.test.ts @@ -9,7 +9,8 @@ import { mkdtempForTestSync, createTestHostEnvironment, } from '@agent-device/test-kit'; -import { createDaemonRuntimeDeps } from './daemon-composition.ts'; +import { composeDaemonRuntimeDeps, createDaemonRuntimeDeps } from './daemon-composition.ts'; +import { macOsPluginCandidateFixture } from './platform-runtime-macos-leaf.fixtures.ts'; import { createRuntimeStateHandle, runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import { resolveRunnerAppBundleId } from '@agent-device/platform-apple/runner/operations'; import { setActiveProviderDeviceRuntimes } from './provider-device-runtime.ts'; @@ -193,23 +194,27 @@ test('the composed daemon route configures interactors from its host, not from t const baseDir = mkdtempForTestSync(`agent-device-daemon-composition-host-config-${name}-`); // The snapshot disagrees with the process on purpose: it is written before the stub below // lands in some orders and after in others, so pin the host value explicitly after the spread. - return await createDaemonRuntimeDeps({ - host: createTestHostEnvironment({ - env: { - ...process.env, - AGENT_DEVICE_STATE_DIR: baseDir, - AGENT_DEVICE_MACOS_APP_BACKEND: backend, + // macOS desktop automation is the managed macOS package's, so the composition receives it. + return await composeDaemonRuntimeDeps( + { + host: createTestHostEnvironment({ + env: { + ...process.env, + AGENT_DEVICE_STATE_DIR: baseDir, + AGENT_DEVICE_MACOS_APP_BACKEND: backend, + }, + }), + baseDir, + sessionsDir: `${baseDir}/sessions`, + assertShutdownAllowed: undefined, + resolveSessionDir: (sessionId) => `${baseDir}/sessions/${sessionId}`, + resolveSessionArtifacts: () => { + throw new Error('unused'); }, - }), - baseDir, - sessionsDir: `${baseDir}/sessions`, - assertShutdownAllowed: undefined, - resolveSessionDir: (sessionId) => `${baseDir}/sessions/${sessionId}`, - resolveSessionArtifacts: () => { - throw new Error('unused'); + openWebSessionNames: () => [], }, - openWebSessionNames: () => [], - }); + [macOsPluginCandidateFixture()], + ); }; // The process claims the native backend for everyone. The runtime host says otherwise; only an diff --git a/src/platform-runtime-apple-application-tools-close-alerts.test.ts b/src/platform-runtime-apple-application-tools-close-alerts.test.ts index 7142a8ddd1..ed35e2184a 100644 --- a/src/platform-runtime-apple-application-tools-close-alerts.test.ts +++ b/src/platform-runtime-apple-application-tools-close-alerts.test.ts @@ -5,9 +5,8 @@ import { createAppleApplicationTools } from './platform-runtime-apple-applicatio const runMacOsAlertAction = vi.hoisted(() => vi.fn()); -vi.mock('@agent-device/platform-apple/macos', async (importOriginal) => ({ - ...(await importOriginal()), - runMacOsAlertAction, +vi.mock('@agent-device/platform-apple/macos-desktop', () => ({ + macOsDesktop: async () => ({ runAlertAction: runMacOsAlertAction }), })); const MACOS_DEVICE: DeviceInfo = { diff --git a/src/platform-runtime-apple-application-tools.test.ts b/src/platform-runtime-apple-application-tools.test.ts index 414732110c..179bded387 100644 --- a/src/platform-runtime-apple-application-tools.test.ts +++ b/src/platform-runtime-apple-application-tools.test.ts @@ -1,16 +1,16 @@ import { expect, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { resolveFrontmostMacOsApp } from '@agent-device/platform-apple/macos'; +import { macOsDesktop } from '@agent-device/platform-apple/macos-desktop'; import { prepareIosRunner, prewarmIosRunnerSession, } from '@agent-device/platform-apple/runner/operations'; import { createAppleApplicationTools } from './platform-runtime-apple-application-tools.ts'; -vi.mock('@agent-device/platform-apple/macos', () => ({ - resolveFrontmostMacOsApp: vi.fn(), - runMacOsAlertAction: vi.fn(), -})); +vi.mock('@agent-device/platform-apple/macos-desktop', () => { + const operations = { frontmostApp: vi.fn(), runAlertAction: vi.fn() }; + return { macOsDesktop: async () => operations }; +}); vi.mock('@agent-device/platform-apple/runner/operations', () => ({ prepareIosRunner: vi.fn(async () => ({ runner: { currentUptimeMs: 42 }, @@ -20,7 +20,7 @@ vi.mock('@agent-device/platform-apple/runner/operations', () => ({ prewarmIosRunnerSession: vi.fn(async () => {}), })); -const mockResolveFrontmostMacOsApp = vi.mocked(resolveFrontmostMacOsApp); +const mockResolveFrontmostMacOsApp = vi.mocked((await macOsDesktop()).frontmostApp); const mockPrepareIosRunner = vi.mocked(prepareIosRunner); const mockPrewarmIosRunnerSession = vi.mocked(prewarmIosRunnerSession); diff --git a/src/platform-runtime-apple-application-tools.ts b/src/platform-runtime-apple-application-tools.ts index af895d1a22..959d23d74b 100644 --- a/src/platform-runtime-apple-application-tools.ts +++ b/src/platform-runtime-apple-application-tools.ts @@ -41,8 +41,11 @@ let appResolutionModule: const loadAppResolution = () => (appResolutionModule ??= import('@agent-device/platform-apple/app-resolution')); -let macOsModule: Promise | undefined; -const loadMacOs = () => (macOsModule ??= import('@agent-device/platform-apple/macos')); +let macOsDesktopModule: + | Promise + | undefined; +const loadMacOsDesktop = () => + (macOsDesktopModule ??= import('@agent-device/platform-apple/macos-desktop')); let retryModule: Promise | undefined; const loadRetry = () => (retryModule ??= import('@agent-device/host-kit/retry')); @@ -172,8 +175,8 @@ async function resolveMacOsSurface( if (!isMacOs(device) || surface === 'app' || surface === 'desktop' || surface === 'menubar') { return {}; } - const { resolveFrontmostMacOsApp } = await loadMacOs(); - const frontmost = await resolveFrontmostMacOsApp(env); + const { macOsDesktop } = await loadMacOsDesktop(); + const frontmost = await (await macOsDesktop()).frontmostApp(env); return { appBundleId: frontmost.bundleId, appName: frontmost.appName }; } @@ -197,12 +200,12 @@ async function dismissMacOsCloseAlerts( env: Readonly, ): Promise { if (!isMacOs(device)) return; - const { runMacOsAlertAction } = await loadMacOs(); + const { macOsDesktop } = await loadMacOsDesktop(); const dismissOptions = input.surface === 'frontmost-app' ? { surface: 'frontmost-app' as const } : input.appBundleId ? { bundleId: input.appBundleId } : {}; - await runMacOsAlertAction('dismiss', { ...dismissOptions, env }); + await (await macOsDesktop()).runAlertAction('dismiss', { ...dismissOptions, env }); } diff --git a/src/platform-runtime-apple-close-composition.test.ts b/src/platform-runtime-apple-close-composition.test.ts index 88f1942b93..55e5eebbf0 100644 --- a/src/platform-runtime-apple-close-composition.test.ts +++ b/src/platform-runtime-apple-close-composition.test.ts @@ -22,12 +22,13 @@ vi.mock('@agent-device/platform-apple/runner/operations', async (importOriginal) }, }; }); -vi.mock('@agent-device/platform-apple/macos', async (importOriginal) => ({ - ...(await importOriginal()), - runMacOsAlertAction: async () => { - events.push('alerts'); - return {}; - }, +vi.mock('@agent-device/platform-apple/macos-desktop', () => ({ + macOsDesktop: async () => ({ + runAlertAction: async () => { + events.push('alerts'); + return {}; + }, + }), })); bindTestCommandHost(); diff --git a/src/platform-runtime-audio-probe-host.ts b/src/platform-runtime-audio-probe-host.ts index 0b53e69ba3..5d44b7b08b 100644 --- a/src/platform-runtime-audio-probe-host.ts +++ b/src/platform-runtime-audio-probe-host.ts @@ -46,16 +46,14 @@ export function createAudioProbeRuntimeHost(options: { bucketMs: number; statusPath: string; }): Promise => { - const { startMacOsAudioProbeProcess } = await import('@agent-device/platform-apple/macos'); - const probe = await startMacOsAudioProbeProcess({ ...input, env: host.env }); - const marker = await resolveManagedProcessIdentity(probe.child.pid ?? undefined); + // The sampler is the macOS helper's, so the installed macOS leaf starts it for every family. + const { macOsDesktop } = await import('@agent-device/platform-apple/macos-desktop'); + const probe = await (await macOsDesktop()).startAudioProbe({ ...input, env: host.env }); + const marker = await resolveManagedProcessIdentity(probe.pid); return Object.freeze({ ...(marker === undefined ? {} : { marker }), wait: probe.wait, - terminate: async () => { - probe.child.kill('SIGTERM'); - await probe.wait.catch(() => {}); - }, + terminate: probe.terminate, }); }, inspectProcess: async (marker: ManagedProcessIdentity) => inspectManagedProcess(marker), diff --git a/src/platform-runtime-device-inventory.test.ts b/src/platform-runtime-device-inventory.test.ts index 238c08d2af..663d8998bd 100644 --- a/src/platform-runtime-device-inventory.test.ts +++ b/src/platform-runtime-device-inventory.test.ts @@ -15,8 +15,14 @@ import { describe, expect, test, vi } from 'vitest'; import { attachAppleSelectionProbes } from './platform-runtime-device-inventory.ts'; // A core version no release channel pins, so an absent family's install hint names the bare package. +import { macOsPlatformCompositionFixture } from './platform-runtime-macos-leaf.fixtures.ts'; + const CORE_VERSION = '0.0.0-test'; +// macOS desktop automation is the managed macOS package's: composing it binds the leaf to the +// bundled Apple owner, as the daemon's composition does. +macOsPlatformCompositionFixture(); + const simctl = vi.hoisted(() => ({ listapps: [] as Array<{ deviceId: string; apps: Record }>, calls: [] as string[], diff --git a/src/platform-runtime-host.test.ts b/src/platform-runtime-host.test.ts index d698a9367b..37ff3c7acb 100644 --- a/src/platform-runtime-host.test.ts +++ b/src/platform-runtime-host.test.ts @@ -4,10 +4,9 @@ import path from 'node:path'; import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; import { createPlatformDeviceInventoryGateways } from './platform-runtime.ts'; -import { - vegaPlatformCompositionFixture, - vegaSelectionFixture, -} from './platform-runtime-vega-provider.fixtures.ts'; +import { vegaSelectionFixture } from './platform-runtime-vega-provider.fixtures.ts'; +import { macOsLeafSelectionFixture } from './platform-runtime-macos-leaf.fixtures.ts'; +import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; const toolchains = vi.hoisted(() => ({ appleEvaluations: 0, @@ -126,9 +125,15 @@ test('a host env with no home still inventories every family through the gateway cwd: process.cwd(), }, undefined, - // Vega is a platform plugin, so the scenario supplies it: the assertion covers what its - // inventory answers when the host env names no home, not the builtin family set. - vegaPlatformCompositionFixture({ env: {}, cwd: process.cwd() }), + // Vega is a platform plugin and macOS a leaf of the Apple family, so the scenario supplies + // both: the assertions cover what their inventories answer when the host env names no home, + // not the builtin family set. + composePlatformPlugins( + [vegaSelectionFixture({ env: {}, cwd: process.cwd() }).get()], + [], + undefined, + [macOsLeafSelectionFixture({ env: {}, cwd: process.cwd() }).get()], + ), ); const scope: PlatformRequestScope = Object.freeze({ signal: new AbortController().signal, diff --git a/src/platform-runtime-operation-host.test.ts b/src/platform-runtime-operation-host.test.ts index f27774b187..2edefec0ba 100644 --- a/src/platform-runtime-operation-host.test.ts +++ b/src/platform-runtime-operation-host.test.ts @@ -19,17 +19,19 @@ vi.mock('./platform-runtime-apple-tool-host.ts', () => ({ vi.mock('./platform-runtime-toolchain-host.ts', () => ({ createHostToolchainPreparer: () => capabilities.toolchains, })); -vi.mock('@agent-device/platform-apple/macos', async (importOriginal) => ({ - ...(await importOriginal()), - captureMacOsSurfaceSnapshot: vi.fn(async () => ({ +vi.mock('@agent-device/platform-apple/macos-desktop', () => { + const captureSurfaceSnapshot = vi.fn(async () => ({ backend: 'macos-helper' as const, producer: 'macos-helper' as const, nodes: [], truncated: false, - })), -})); + })); + return { macOsDesktop: async () => ({ captureSurfaceSnapshot }) }; +}); + +import { macOsDesktop } from '@agent-device/platform-apple/macos-desktop'; -import { captureMacOsSurfaceSnapshot } from '@agent-device/platform-apple/macos'; +const captureMacOsSurfaceSnapshot = (await macOsDesktop()).captureSurfaceSnapshot; import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; import { createPlatformRuntimeHost, diff --git a/src/platform-runtime-operation-host.ts b/src/platform-runtime-operation-host.ts index c8bfc87762..9e8559adfb 100644 --- a/src/platform-runtime-operation-host.ts +++ b/src/platform-runtime-operation-host.ts @@ -50,8 +50,8 @@ export async function loadMacOsSurfaceSnapshot( if (!surface) { throw new TypeError('Apple surface capture requires a helper-routed macOS surface'); } - const { captureMacOsSurfaceSnapshot } = await import('@agent-device/platform-apple/macos'); - return await captureMacOsSurfaceSnapshot({ ...options, surface }, signal, env); + const { macOsDesktop } = await import('@agent-device/platform-apple/macos-desktop'); + return await (await macOsDesktop()).captureSurfaceSnapshot({ ...options, surface }, signal, env); } export function createPlatformRuntimeHost(options: { From a96d86a15b264e9324eb21c5abf9ff166d4fe384 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 20:55:05 +0100 Subject: [PATCH 04/15] test(plugins): tidy the leaf claim tests after formatting --- packages/plugins/src/platform.test.ts | 14 ++++++++------ packages/plugins/src/validate.ts | 5 +---- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts index a6aa279d54..70dbe82b1c 100644 --- a/packages/plugins/src/platform.test.ts +++ b/packages/plugins/src/platform.test.ts @@ -2,11 +2,7 @@ import { expect, test } from 'vitest'; import { pluginHome, selectPlugin } from '@agent-device/test-kit'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { storePluginCandidates } from './store.ts'; -import { - resolveProviderPlugins, - startProviderRegistry, - type PluginCandidate, -} from './registry.ts'; +import { resolveProviderPlugins, startProviderRegistry, type PluginCandidate } from './registry.ts'; const WEB_PACKAGE = '@agent-device/web'; const stateDir = '/fixture-state'; @@ -217,7 +213,13 @@ test('a macOS leaf claim coexists with the bundled apple family claim and regist selectMacOsLeaf(home); const registry = await startStore(env, [builtinApple]); expect(registry.inventory).toMatchObject([ - { source: 'store', package: MACOS_PACKAGE, platform: 'apple', appleOs: 'macos', state: 'active' }, + { + source: 'store', + package: MACOS_PACKAGE, + platform: 'apple', + appleOs: 'macos', + state: 'active', + }, ]); expect(registry.platforms).toEqual([]); expect(registry.platformLeaves.map(({ family, appleOs }) => `${family}:${appleOs}`)).toEqual([ diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index 5574eb0bac..d42eb1196f 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -313,10 +313,7 @@ export function readableClaimsOfValue(value: unknown): readonly PluggedClaim[] { }); } -function namedContributionClaims( - contributions: unknown, - kind: ClaimKind, -): readonly PluggedClaim[] { +function namedContributionClaims(contributions: unknown, kind: ClaimKind): readonly PluggedClaim[] { if (!Array.isArray(contributions)) return []; const { contributionIdField, leafField, readNamedId = namedId, readLeaf } = CLAIM_KINDS[kind]; return contributions.flatMap((contribution) => { From 4cdd7211533a22831480705e333dd5d132a43d63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 21:02:45 +0100 Subject: [PATCH 05/15] chore(gates): move the macOS guards and package checks with the plugin The layering policy learns a managed leaf package: `packages/platform-macos` holds `{ platform: 'apple', appleOs: 'macos' }` and obeys every rule a managed family package obeys. The packed-core check refuses any macOS desktop path or helper marker, and `check:package` gains the macOS package smoke. The helper pack rules leave the core size report for a plugin-owned check, so the core guard now refuses a helper path outright and exempts no test path. Lane ownership, the native-dupes scan root, the eager-closure facade list and the Fallow facade entry follow the files. The macOS smoke lane installs the packed plugin before the replay gate, and the provider scenarios compose it. Part of #4675 --- .fallowrc.json | 5 - .github/actions/smoke-macos/action.yml | 24 ++ .jscpd-native.json | 8 +- package.json | 15 +- packages/platform-macos/package.json | 2 - .../platform-macos/test/package-smoke.mjs | 235 ++++++++++++++++++ packages/plugins/src/store.ts | 1 + scripts/__tests__/eager-closure-budgets.ts | 1 - .../fixtures/size-report-npm-pack.json | 16 -- scripts/__tests__/shipped-test-code.test.ts | 10 +- scripts/__tests__/size-report-package.test.ts | 101 +------- scripts/check-affected/device-lanes.test.ts | 13 +- scripts/check-affected/device-lanes.ts | 2 + scripts/check-affected/model.ts | 2 +- scripts/check-package.ts | 13 + scripts/layering/architecture-ownership.ts | 1 + .../layering/contracts-exports.snapshot.json | 1 + scripts/layering/model.ts | 2 + scripts/layering/package-boundaries.test.ts | 3 +- .../platform-package-leaf-policy.test.ts | 47 ++++ .../platform-package-policy.fixtures.ts | 25 +- .../layering/platform-package-policy.test.ts | 4 +- scripts/layering/platform-package-policy.ts | 58 ++++- .../layering/platform-package-repository.ts | 2 +- .../layering/process-globals-policy.test.ts | 2 +- scripts/lib/macos-helper-pack.d.mts | 13 + scripts/lib/macos-helper-pack.mjs | 79 ++++++ scripts/lib/shipped-test-code.ts | 13 +- scripts/size-report-package.d.mts | 3 - scripts/size-report-package.mjs | 81 +----- .../integration/provider-scenarios/harness.ts | 5 + .../macos-helper-package-contents.test.ts | 103 ++++++-- test/repo-guards/npm-package-scripts.test.ts | 3 +- 33 files changed, 635 insertions(+), 258 deletions(-) create mode 100644 packages/platform-macos/test/package-smoke.mjs create mode 100644 scripts/layering/platform-package-leaf-policy.test.ts create mode 100644 scripts/lib/macos-helper-pack.d.mts create mode 100644 scripts/lib/macos-helper-pack.mjs diff --git a/.fallowrc.json b/.fallowrc.json index 94413e7ce8..979cc3a6d7 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -253,11 +253,6 @@ "file": "packages/daemon/src/execution/interaction/index.ts", "exports": ["refMutationAdmissionResponse", "handleFindCommands", "handleInteractionCommands"] }, - { - // The macOS façade members are read off the memoized loadMacOs() loader in src/platform-runtime-apple-application-tools.ts. Fallow cannot connect that dynamic member read to the re-exports. - "file": "packages/platform-apple/src/macos-facade.ts", - "exports": ["resolveFrontmostMacOsApp", "runMacOsAlertAction"] - }, { // answerSimulatorLaunchConfirmation is called from packages/platform-apple/src/lifecycle.ts through the lazy loadLaunchConfirmation() import; Fallow cannot connect the dynamic member read. "file": "packages/platform-apple/src/launch-confirmation.ts", diff --git a/.github/actions/smoke-macos/action.yml b/.github/actions/smoke-macos/action.yml index 145fe3c21f..215db3fa45 100644 --- a/.github/actions/smoke-macos/action.yml +++ b/.github/actions/smoke-macos/action.yml @@ -72,6 +72,30 @@ runs: uses: ./.github/actions/run-gate with: gate: macos-helper + # macOS desktop automation is a managed plugin, so the replay lane serves it from the plugin + # store built here. The plugin is installed once and then answers the visible reply below and + # the macOS gate, which is the evidence that a user's `plugins add` install drives this Mac. The + # store is the one the gate action stages the replay pair into: that step merges its selections + # into the same config, so the daemon the gate starts carries all three packages. + - name: Install the macOS platform plugin + shell: bash + run: | + set -euo pipefail + # The steps below drive the packed entry point, which refuses to run without the build it + # ships beside it, and `plugins add` is a CLI command. + pnpm build + pnpm --filter @agent-device/macos pack --out "$RUNNER_TEMP/macos-plugin.tgz" + mkdir -p "$RUNNER_TEMP/agent-device-replay-plugins" + export AGENT_DEVICE_HOME="$RUNNER_TEMP/agent-device-replay-plugins" + echo "AGENT_DEVICE_HOME=$AGENT_DEVICE_HOME" >> "$GITHUB_ENV" + node bin/agent-device.mjs plugins add "$RUNNER_TEMP/macos-plugin.tgz" --json + node bin/agent-device.mjs plugins list --json + # The store is read when a daemon starts, so the first macOS command below must not reach a + # daemon that was already running without this entry. + pnpm clean:daemon + printf '\n$ agent-device devices --platform macos\n' + node bin/agent-device.mjs devices --platform macos --json + pnpm clean:daemon - name: Run macOS integration test uses: ./.github/actions/run-gate with: diff --git a/.jscpd-native.json b/.jscpd-native.json index 57d7a7d4cc..e033f7a52f 100644 --- a/.jscpd-native.json +++ b/.jscpd-native.json @@ -1,5 +1,11 @@ { - "path": ["apple", "android", "packages/platform-linux/linux", "packages/host-swift/swift"], + "path": [ + "apple", + "android", + "packages/platform-linux/linux", + "packages/platform-macos/macos-helper", + "packages/host-swift/swift" + ], "format": ["swift", "objectivec", "kotlin", "java", "python"], "formatsExts": { "objectivec": ["m", "h"] }, "mode": "weak", diff --git a/package.json b/package.json index 27466621ef..efedadf00c 100644 --- a/package.json +++ b/package.json @@ -115,12 +115,12 @@ "build:android-ime-helper": "AGENT_DEVICE_ANDROID_HELPER=ime sh ./scripts/build-android-helper.sh $(node -p \"require('./package.json').version\") .tmp/android-ime-helper", "package:android-ime-helper": "AGENT_DEVICE_ANDROID_HELPER=ime sh ./scripts/package-android-helper.sh $(node -p \"require('./package.json').version\") .tmp/android-ime-helper", "package:android-ime-helper:npm": "rm -rf android/ime-helper/dist && AGENT_DEVICE_ANDROID_HELPER=ime sh ./scripts/package-android-helper.sh $(node -p \"require('./package.json').version\") android/ime-helper/dist", - "build:macos-helper": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift build -c release --package-path apple/macos-helper", - "build:macos-helper:clean": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift package --package-path apple/macos-helper clean && pnpm build:macos-helper", - "test:macos-helper": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift test --package-path apple/macos-helper", + "build:macos-helper": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift build -c release --package-path packages/platform-macos/macos-helper", + "build:macos-helper:clean": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift package --package-path packages/platform-macos/macos-helper clean && pnpm build:macos-helper", + "test:macos-helper": "node --experimental-strip-types scripts/swift-toolchain-tmpdir.ts swift test --package-path packages/platform-macos/macos-helper", "check:macos-helper": "pnpm build:macos-helper && pnpm test:macos-helper", "prepare:publish-assets": "node scripts/prepare-publish-assets.mjs", - "build:package": "pnpm build && pnpm package:xcuitest && pnpm build:macos-helper:clean && pnpm prepare:publish-assets", + "build:package": "pnpm build && pnpm package:xcuitest && pnpm prepare:publish-assets", "package:npm": "pnpm build:package && pnpm check:package", "release:prepare": "rm -rf .tmp/release && pnpm check:mcp-metadata && pnpm build:package && pnpm check:package -- --pack-destination .tmp/release && node scripts/release-workspace.mjs pack", "ad": "node bin/agent-device.mjs", @@ -166,7 +166,7 @@ "depgraph:test": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/depgraph/model.test.ts scripts/depgraph/entries.test.ts scripts/depgraph/import-graph.test.ts scripts/depgraph/affected.test.ts scripts/depgraph/structure-summary.test.ts tools/depgraph-view/*.test.mjs", "check:production-exports": "fallow dead-code --config fallow-production-exports.json --production --unused-exports --fail-on-issues", "check:bundle-owner-files": "node --experimental-strip-types scripts/check-bundle-owner-files.ts", - "check:package": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs packages/platform-web/test/package-smoke.mjs packages/platform-vega/test/package-smoke.mjs packages/platform-harmonyos/test/package-smoke.mjs packages/platform-linux/test/package-smoke.mjs && node --experimental-strip-types scripts/check-package.ts", + "check:package": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs packages/platform-web/test/package-smoke.mjs packages/platform-vega/test/package-smoke.mjs packages/platform-harmonyos/test/package-smoke.mjs packages/platform-linux/test/package-smoke.mjs packages/platform-macos/test/package-smoke.mjs && node --experimental-strip-types scripts/check-package.ts", "check:provider-plugin": "node scripts/check-provider-plugin.mjs", "check:command-docs": "vitest run --project unit-core test/repo-guards/command-doc-coverage.test.ts test/repo-guards/command-doc-generated-blocks.test.ts test/repo-guards/reason-tables.test.ts", "generate:command-docs": "node --experimental-strip-types scripts/command-docs/generate.ts --write", @@ -237,11 +237,6 @@ "files": [ "bin", "dist", - "apple/macos-helper", - "!apple/macos-helper/**/.build", - "!apple/macos-helper/Tests/**", - "apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift", - "apple/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift", "apple/snapshot-bridge", "apple/fold-helper", "android/snapshot-helper/dist", diff --git a/packages/platform-macos/package.json b/packages/platform-macos/package.json index 48a415b2b2..89165ec816 100644 --- a/packages/platform-macos/package.json +++ b/packages/platform-macos/package.json @@ -39,8 +39,6 @@ }, "scripts": { "build": "node --experimental-strip-types build.mjs", - "build:helper": "node --experimental-strip-types ../../scripts/swift-toolchain-tmpdir.ts swift build -c release --package-path macos-helper", - "test:helper": "node --experimental-strip-types ../../scripts/swift-toolchain-tmpdir.ts swift test --package-path macos-helper", "prepack": "pnpm build" }, "publishConfig": { diff --git a/packages/platform-macos/test/package-smoke.mjs b/packages/platform-macos/test/package-smoke.mjs new file mode 100644 index 0000000000..87b8fe98f3 --- /dev/null +++ b/packages/platform-macos/test/package-smoke.mjs @@ -0,0 +1,235 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { macosHelperPackFailures } from '../../../scripts/lib/macos-helper-pack.mjs'; + +const repo = path.resolve(import.meta.dirname, '../../..'); + +/** + * A stand-in for the Swift helper the plugin builds on a user's Mac. It answers each helper command + * with one canned reply in the helper's own JSON envelope and appends its argv to a log, so the test + * can prove which helper commands the installed plugin sent. Building the real helper needs a Swift + * toolchain and several minutes; the override variable the plugin reads is the supported way to name + * another binary. + */ +function helperStubSource(logFile) { + const tree = { + surface: 'desktop', + nodes: [ + { + index: 0, + type: 'Window', + label: 'Stub Window', + rect: { x: 0, y: 0, width: 400, height: 300 }, + enabled: true, + hittable: true, + depth: 0, + }, + { + index: 1, + type: 'Button', + label: 'OK', + rect: { x: 40, y: 80, width: 60, height: 30 }, + enabled: true, + hittable: true, + depth: 1, + parentIndex: 0, + }, + ], + truncated: false, + backend: 'macos-helper', + }; + return [ + '#!/usr/bin/env node', + "const fs = require('node:fs');", + 'const args = process.argv.slice(2);', + `fs.appendFileSync(${JSON.stringify(logFile)}, args.join(' ') + '\\n');`, + String.raw`const reply = (data) => process.stdout.write(JSON.stringify({ ok: true, data }) + "\n");`, + 'const value = (flag) => args[args.indexOf(flag) + 1];', + `if (args[0] === 'snapshot') reply(${JSON.stringify(tree)});`, + "else if (args[0] === 'screenshot') {", + " fs.writeFileSync(value('--out'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));", + " reply({ path: value('--out'), surface: 'desktop' });", + '} else reply({});', + ].join('\n'); +} + +test('packed core serves macOS desktop automation only after the managed platform is installed', () => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-macos-pack-')); + const strippedHost = (source) => + Object.fromEntries( + Object.entries(source).filter(([name]) => !name.startsWith('AGENT_DEVICE_')), + ); + const env = { + ...strippedHost(process.env), + AGENT_DEVICE_HOME: path.join(scratch, 'home'), + AGENT_DEVICE_STATE_DIR: path.join(scratch, 'state'), + AGENT_DEVICE_CLAIMS_DIR: path.join(scratch, 'claims'), + AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', + }; + const exec = (command, args, cwd = scratch) => + execFileSync(command, args, { cwd, env, encoding: 'utf8', timeout: 180_000 }); + const cliText = (...args) => + exec(process.execPath, ['node_modules/agent-device/bin/agent-device.mjs', ...args], scratch); + const runCliWith = (environment, expectedExit, ...args) => { + const invoke = () => + execFileSync( + process.execPath, + ['node_modules/agent-device/bin/agent-device.mjs', ...args, '--json'], + { + cwd: scratch, + env: environment, + encoding: 'utf8', + timeout: 180_000, + maxBuffer: 32 * 1024 * 1024, + }, + ); + try { + const reply = JSON.parse(invoke()); + assert.equal(expectedExit, 0); + return reply; + } catch (error) { + if (expectedExit !== 0 && error.status === expectedExit) return JSON.parse(error.stdout); + throw error; + } + }; + const runCli = (expectedExit, ...args) => runCliWith(env, expectedExit, ...args); + try { + // The packed core carries no macOS desktop implementation and no Swift helper. The shared + // XCTest runner's macOS parts stay in the core by decision (#4675). + const [packed] = JSON.parse( + exec('npm', ['pack', '--ignore-scripts', '--json', '--pack-destination', scratch], repo), + ); + const corePaths = packed.files.map(({ path: file }) => file); + assert.deepEqual( + corePaths.filter((file) => /(?:^|\/)(?:platform-macos|macos-helper)(?:\/|$)/.test(file)), + [], + ); + exec( + 'pnpm', + ['pack', '--out', path.join(scratch, 'macos.tgz')], + path.join(repo, 'packages/platform-macos'), + ); + // The Swift helper ships with the plugin as buildable source and is resolved relative to it. A + // tarball without its manifest, its sources or a test target's pack stub installs and then fails + // on the first macOS command, so it is checked where it is packed. + const packedPlugin = exec('tar', ['tzf', path.join(scratch, 'macos.tgz')]) + .split('\n') + .filter(Boolean) + .map((file) => file.replace(/^package\//, '')); + assert.ok(packedPlugin.includes('dist/agent-device.mjs'), packedPlugin.join('\n')); + assert.deepEqual( + macosHelperPackFailures( + packedPlugin, + fs.readFileSync( + path.join(repo, 'packages/platform-macos/macos-helper/Package.swift'), + 'utf8', + ), + ), + [], + ); + fs.writeFileSync(path.join(scratch, 'package.json'), '{"private":true}'); + exec('npm', [ + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + path.join(scratch, packed.filename), + ]); + // The installed core carries the leaf's absence, not its implementation. + const installedCore = path.join(scratch, 'node_modules/agent-device'); + assert.equal(fs.existsSync(path.join(installedCore, 'apple/macos-helper')), false); + + // Without the plugin: a request that names macOS answers the typed outcome with the install + // command, an unfiltered request skips this Mac silently, and help still renders. + const { error } = runCli(1, 'devices', '--platform', 'macos'); + assert.equal(error.details.reason, 'plugin-not-installed'); + assert.equal(error.details.package, '@agent-device/macos'); + assert.match(error.hint, /agent-device plugins add @agent-device\/macos/); + + const open = runCli(1, 'open', 'TextEdit', '--platform', 'macos'); + assert.equal(open.error.details.reason, 'plugin-not-installed'); + + assert.match(cliText('help', 'devices'), /devices/); + runCli(0, 'daemon', 'stop'); + + runCli(0, 'plugins', 'add', './macos.tgz'); + // A daemon started before the store changed cannot see the new entry. + runCli(0, 'daemon', 'stop'); + + // The bundled Apple owner still discovers; with the leaf installed it lists this host's Mac. + const found = runCli(0, 'devices', '--platform', 'macos'); + assert.equal(found.data.devices.length, 1, JSON.stringify(found.data)); + assert.equal(found.data.devices[0].platform, 'macos'); + assert.equal(found.data.devices[0].id, 'host-macos-local'); + assert.equal(found.data.devices[0].target, 'desktop'); + const plugins = runCli(0, 'daemon', 'status').data.plugins; + assert.ok( + plugins.some( + (plugin) => + plugin.platform === 'apple' && plugin.appleOs === 'macos' && plugin.state === 'active', + ), + JSON.stringify(plugins), + ); + runCli(0, 'daemon', 'stop'); + + // A macOS session is this Mac's own desktop, so everything below needs a macOS host. The + // installed plugin then drives a whole desktop interaction through its helper. The native app + // backend keeps the run off the XCTest runner, which this check does not build. + if (process.platform !== 'darwin') return; + + const helperCalls = path.join(scratch, 'helper-calls.log'); + const helperStub = path.join(scratch, 'agent-device-macos-helper'); + fs.writeFileSync(helperStub, helperStubSource(helperCalls), 'utf8'); + fs.chmodSync(helperStub, 0o755); + const desktopEnv = { + ...env, + AGENT_DEVICE_MACOS_HELPER_BIN: helperStub, + AGENT_DEVICE_MACOS_APP_BACKEND: 'native', + }; + const desktop = ['--platform', 'macos', '--session', 'macos-pack']; + + runCliWith(desktopEnv, 0, 'open', '--surface', 'desktop', ...desktop); + const captured = runCliWith(desktopEnv, 0, 'snapshot', ...desktop); + assert.deepEqual( + captured.data.nodes.map((node) => node.label), + ['Stub Window', 'OK'], + JSON.stringify(captured.data.nodes), + ); + const shot = path.join(scratch, 'screen.png'); + const shotResult = runCliWith(desktopEnv, 0, 'screenshot', shot, ...desktop); + assert.equal(shotResult.data.path, shot); + assert.deepEqual([...fs.readFileSync(shot).subarray(0, 4)], [0x89, 0x50, 0x4e, 0x47]); + // A desktop session inspects; acting on it is refused by policy before any helper call. + const refused = runCliWith(desktopEnv, 1, 'press', '42', '84', ...desktop); + assert.equal(refused.error.code, 'UNSUPPORTED_OPERATION'); + runCliWith(desktopEnv, 0, 'close', ...desktop); + + // The helper commands the plugin sent, in order, among whatever else the session asked it. + const calls = fs.readFileSync(helperCalls, 'utf8').split('\n').filter(Boolean); + const expected = ['snapshot --surface desktop', `screenshot --out ${shot} --surface desktop`]; + let cursor = 0; + for (const call of calls) { + if (call === expected[cursor]) cursor += 1; + } + assert.equal( + cursor, + expected.length, + `the helper did not receive the desktop route. Expected in order: ${JSON.stringify( + expected, + null, + 2, + )} Got: ${JSON.stringify(calls, null, 2)}`, + ); + } finally { + try { + if (fs.existsSync(path.join(scratch, 'node_modules/agent-device'))) + runCli(0, 'daemon', 'stop'); + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } + } +}); diff --git a/packages/plugins/src/store.ts b/packages/plugins/src/store.ts index bd29274e24..50a9aef74d 100644 --- a/packages/plugins/src/store.ts +++ b/packages/plugins/src/store.ts @@ -296,6 +296,7 @@ export async function listPlugins(env: NodeJS.ProcessEnv, builtinProviders: read ...(entry.provider !== undefined ? { provider: entry.provider } : {}), ...(entry.backend !== undefined ? { backend: entry.backend } : {}), ...(entry.platform !== undefined ? { platform: entry.platform } : {}), + ...(entry.appleOs !== undefined ? { appleOs: entry.appleOs } : {}), compatible: entry.state === 'active', ...(entry.error ? { error: entry.error } : {}), })); diff --git a/scripts/__tests__/eager-closure-budgets.ts b/scripts/__tests__/eager-closure-budgets.ts index 899147cb73..b8e9f0341a 100644 --- a/scripts/__tests__/eager-closure-budgets.ts +++ b/scripts/__tests__/eager-closure-budgets.ts @@ -206,7 +206,6 @@ const APPLE_DOMAIN_MECHANICS_ENTRY_FILES: ReadonlySet = new Set([ 'packages/platform-apple/src/debug-symbols-facade.ts', 'packages/platform-apple/src/doctor-facade.ts', 'packages/platform-apple/src/install-artifact-facade.ts', - 'packages/platform-apple/src/macos-facade.ts', 'packages/platform-apple/src/perf-facade.ts', 'packages/platform-apple/src/physical-device-facade.ts', 'packages/platform-apple/src/runner-operations-facade.ts', diff --git a/scripts/__tests__/fixtures/size-report-npm-pack.json b/scripts/__tests__/fixtures/size-report-npm-pack.json index 223482dab8..40abce7786 100644 --- a/scripts/__tests__/fixtures/size-report-npm-pack.json +++ b/scripts/__tests__/fixtures/size-report-npm-pack.json @@ -61,14 +61,6 @@ "path": "apple/snapshot-bridge/ForegroundApplicationGeometry.h", "size": 0 }, - { - "path": "apple/macos-helper/Package.swift", - "size": 1057 - }, - { - "path": "apple/macos-helper/Sources/main.swift", - "size": 211 - }, { "path": "android/snapshot-helper/dist/helper.apk", "size": 307 @@ -92,14 +84,6 @@ { "path": "vendor/unknown.bin", "size": 78 - }, - { - "path": "apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift", - "size": 426 - }, - { - "path": "apple/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift", - "size": 426 } ], "entryCount": 21, diff --git a/scripts/__tests__/shipped-test-code.test.ts b/scripts/__tests__/shipped-test-code.test.ts index a32bbfeaef..715db31253 100644 --- a/scripts/__tests__/shipped-test-code.test.ts +++ b/scripts/__tests__/shipped-test-code.test.ts @@ -9,7 +9,6 @@ import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; import { testOnlyContentFailures, testOnlyPathFailures } from '../lib/shipped-test-code.ts'; -import { DOCUMENTED_PACK_STUBS } from '../size-report-package.mjs'; const repoRoot = path.resolve(import.meta.dirname, '../..'); @@ -19,7 +18,7 @@ const RUNNER_HOST_APP = test('testOnlyPathFailures rejects each test-only directory the packager must not copy', () => { const failures = testOnlyPathFailures([ 'dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertTests.swift', - 'apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/HelperTests.swift', + 'macos-helper/Tests/AgentDeviceMacOSHelperTests/HelperTests.swift', 'dist/src/__tests__/daemon.test.js', 'dist/fixtures/sample.json', 'dist/mocks/device-factory.js', @@ -40,11 +39,10 @@ test('testOnlyPathFailures rejects test-only file names in any shipped language' assert.equal(failures.length, 4); }); -test('testOnlyPathFailures exempts only the two documented PackStubs under Tests/', () => { - assert.deepEqual(testOnlyPathFailures([...DOCUMENTED_PACK_STUBS]), []); +test('testOnlyPathFailures exempts no path under a Tests/ directory', () => { + // The macOS helper's pack stubs ship in the @agent-device/macos plugin, so the core has none. assert.equal( - testOnlyPathFailures(['apple/macos-helper/Tests/AgentDeviceMacOSInputTests/ExtraTests.swift']) - .length, + testOnlyPathFailures(['macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift']).length, 1, ); }); diff --git a/scripts/__tests__/size-report-package.test.ts b/scripts/__tests__/size-report-package.test.ts index 96b49bc6c1..be624936b2 100644 --- a/scripts/__tests__/size-report-package.test.ts +++ b/scripts/__tests__/size-report-package.test.ts @@ -19,26 +19,11 @@ const fixturePack: { files: NpmPackEntry[] } = JSON.parse( const execFileAsync = promisify(execFile); -// The fixture pack ships the macOS helper (manifest, sources, and per-target PackStub.swift), -// so every assertion here names the manifest source the guard would read from the packed tree; -// without it the guard falls back to this checkout's manifest via repoRoot. -const helperManifestSource = [ - '.target(', - ' name: "AgentDeviceMacOSInput",', - '.executableTarget(', - ' name: "AgentDeviceMacOSHelper",', - '.testTarget(', - ' name: "AgentDeviceMacOSHelperTests",', - '.testTarget(', - ' name: "AgentDeviceMacOSInputTests",', -].join('\n'); - test('publish package requires bundled dependency license notices', () => { assert.throws( () => assertPublishPackageContents( fixturePack.files.filter((entry) => entry.path !== 'dist/src/THIRD_PARTY_NOTICES.txt'), - { macosHelperManifestSource: helperManifestSource }, ), /THIRD_PARTY_NOTICES\.txt/, ); @@ -48,7 +33,6 @@ test('publish package requires bundled dependency license notices', () => { fixturePack.files.map((entry) => entry.path === 'dist/src/THIRD_PARTY_NOTICES.txt' ? { ...entry, size: 0 } : entry, ), - { macosHelperManifestSource: helperManifestSource }, ), /non-empty.*THIRD_PARTY_NOTICES\.txt/, ); @@ -483,7 +467,6 @@ test('publish package gate rejects placeholder notices from the tree it packed', () => assertPublishPackageContents(fixturePack.files, { noticesRoot: root, - macosHelperManifestSource: helperManifestSource, }), /no bundled dependency notices/, ); @@ -491,22 +474,16 @@ test('publish package gate rejects placeholder notices from the tree it packed', assert.doesNotThrow(() => assertPublishPackageContents(fixturePack.files, { noticesRoot: root, - macosHelperManifestSource: helperManifestSource, }), ); }); test('publish package requires both Android helpers and excludes benchmark scripts', () => { - assert.doesNotThrow(() => - assertPublishPackageContents(fixturePack.files, { - macosHelperManifestSource: helperManifestSource, - }), - ); + assert.doesNotThrow(() => assertPublishPackageContents(fixturePack.files, {})); assert.throws( () => assertPublishPackageContents( fixturePack.files.filter((entry) => !entry.path.startsWith('android/ime-helper/')), - { macosHelperManifestSource: helperManifestSource }, ), /android\/ime-helper/, ); @@ -523,79 +500,25 @@ test('publish package requires both Android helpers and excludes benchmark scrip assert.doesNotThrow(() => assertPublishPackageContents( fixturePack.files.filter((entry) => !entry.path.startsWith('apple/snapshot-bridge/')), - { macosHelperManifestSource: helperManifestSource }, ), ); assert.throws( () => - assertPublishPackageContents( - [...fixturePack.files, { path: 'scripts/ios-snapshot-benchmark/run.ts', size: 1 }], - { macosHelperManifestSource: helperManifestSource }, - ), + assertPublishPackageContents([ + ...fixturePack.files, + { path: 'scripts/ios-snapshot-benchmark/run.ts', size: 1 }, + ]), /benchmark or build scripts/, ); - // Each declared test target needs its PackStub.swift or the install-time `swift build` of the - // packed tree dies; a missing one must name the missing path. - assert.throws( - () => - assertPublishPackageContents( - fixturePack.files.filter( - (entry) => - entry.path !== 'apple/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift', - ), - { macosHelperManifestSource: helperManifestSource }, - ), - /pack stubs: apple\/macos-helper\/Tests\/AgentDeviceMacOSInputTests\/PackStub\.swift/, - ); + // The macOS helper ships in the @agent-device/macos plugin; a helper path in the core pack names + // the package that owns it. assert.throws( () => - assertPublishPackageContents( - [ - ...fixturePack.files, - { - path: 'apple/macos-helper/Tests/AgentDeviceMacOSInputTests/ScheduleTests.swift', - size: 1, - }, - ], - { macosHelperManifestSource: helperManifestSource }, - ), - /macOS helper test sources/, - ); - // A stub path under Tests/ that the declared list does not name is a test source, not an - // exemption: the old suffix rule let any PackStub.swift through. - assert.throws( - () => - assertPublishPackageContents( - [ - ...fixturePack.files, - { - path: 'apple/macos-helper/Tests/AgentDeviceSneakyTests/PackStub.swift', - size: 1, - }, - ], - { macosHelperManifestSource: helperManifestSource }, - ), - /macOS helper test sources: apple\/macos-helper\/Tests\/AgentDeviceSneakyTests\/PackStub\.swift/, - ); - // The other direction: a declared stub whose target left the manifest is a dead stub riding in - // the pack on a stale package.json entry, exempt from the path guard, and must be named. - assert.throws( - () => - assertPublishPackageContents(fixturePack.files, { - // The manifest now declares only the Input test target; the pack still ships both stubs. - macosHelperManifestSource: ['.testTarget(', ' name: "AgentDeviceMacOSInputTests",'].join( - '\n', - ), - }), - /no test target declares: apple\/macos-helper\/Tests\/AgentDeviceMacOSHelperTests\/PackStub\.swift/, - ); - // Sources without the manifest are not a buildable Swift package; the pack must say so. - assert.throws( - () => - assertPublishPackageContents( - fixturePack.files.filter((entry) => entry.path !== 'apple/macos-helper/Package.swift'), - ), - /sources without its Package\.swift/, + assertPublishPackageContents([ + ...fixturePack.files, + { path: 'apple/macos-helper/Package.swift', size: 1 }, + ]), + /includes the macOS helper, which @agent-device\/macos ships: apple\/macos-helper\/Package\.swift/, ); }); diff --git a/scripts/check-affected/device-lanes.test.ts b/scripts/check-affected/device-lanes.test.ts index 33975a3c0c..a53359320e 100644 --- a/scripts/check-affected/device-lanes.test.ts +++ b/scripts/check-affected/device-lanes.test.ts @@ -25,7 +25,7 @@ test('a TypeScript-only Apple change selects the iOS and macOS lanes without a S for (const file of [ 'packages/platform-apple/src/core/app-resolution.ts', 'packages/platform-apple/src/runtime.ts', - 'packages/platform-apple/src/os/macos/desktop-scroll.ts', + 'packages/platform-apple/src/os/tvos/remote.ts', ]) { assert.deepEqual(lanes(file), ['replay-ios', 'replay-ios-device', 'replay-macos'], file); assert.ok( @@ -38,6 +38,16 @@ test('a TypeScript-only Apple change selects the iOS and macOS lanes without a S assert.deepEqual(lanes('test/integration/replays/macos/01-desktop.ad'), ['replay-macos']); }); +test('the macOS plugin owns only the macOS lanes, and its Swift helper adds the helper build', () => { + // macOS desktop automation is the managed macOS package's, so a change there carries no iOS lane. + assert.deepEqual(lanes('packages/platform-macos/src/helper.ts'), ['replay-macos']); + const helperLanes = lanes( + 'packages/platform-macos/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift', + ); + assert.ok(helperLanes.includes('macos-helper') && helperLanes.includes('replay-macos')); + assert.equal(helperLanes.includes('replay-ios'), false); +}); + test('a Swift runner change selects every platform build and every Apple lane', () => { assert.deepEqual(lanes('apple/runner/AgentDeviceRunner/Sources/Foo.swift'), [ 'swift-runner-ios', @@ -165,6 +175,7 @@ test('unit tests under src/ and packages/*/src own no lane', () => { test('a mixed tree is shared, and two Apple leaves are still Apple', () => { assert.equal(deviceLaneLeaf('packages/platform-apple/src/os/macos/x.ts'), 'apple'); + assert.equal(deviceLaneLeaf('packages/platform-macos/src/x.ts'), 'macos'); assert.equal(deviceLaneLeaf('test/integration/android-emulator-e2e/ios/x.ts'), 'shared'); assert.deepEqual(deviceLanesFor('packages/platform-apple/src/os/macos/x.ts').lanes, [ 'replay-ios', diff --git a/scripts/check-affected/device-lanes.ts b/scripts/check-affected/device-lanes.ts index f562175cdc..09413a2dcf 100644 --- a/scripts/check-affected/device-lanes.ts +++ b/scripts/check-affected/device-lanes.ts @@ -140,6 +140,8 @@ const RUNTIME_SURFACE: ReadonlyArray<{ root: string; owns: (file: string) => boo { root: 'android/', owns: () => true }, // The Linux plugin's AT-SPI helper: a runtime asset the Linux lanes execute through the plugin. { root: 'packages/platform-linux/linux/', owns: () => true }, + // The macOS plugin's Swift helper: source the plugin builds on the host the macOS lane drives. + { root: 'packages/platform-macos/macos-helper/', owns: () => true }, // macOS host Swift helpers that recording post-processing compiles on the daemon host. { root: 'packages/host-swift/swift/', owns: () => true }, // TS/Swift golden tables (own:golden-table in model.ts): the parity XCTest runs on the lane. diff --git a/scripts/check-affected/model.ts b/scripts/check-affected/model.ts index 182212a403..a231ebe54e 100644 --- a/scripts/check-affected/model.ts +++ b/scripts/check-affected/model.ts @@ -570,7 +570,7 @@ const BUILD_OWNERSHIP: ReadonlyArray<{ check: 'macos-helper', rule: 'own:macos-helper', detail: 'macOS helper is a separate Swift package build', - owns: (file) => file.startsWith('apple/macos-helper/'), + owns: (file) => file.startsWith('packages/platform-macos/macos-helper/'), }, { check: 'mcp-metadata', diff --git a/scripts/check-package.ts b/scripts/check-package.ts index e6d331d6fb..6146e9ca76 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -76,6 +76,19 @@ const EXCLUDED_IMPLEMENTATIONS = [ 'is required for input synthesis on Wayland', ], }, + { + // macOS is a leaf of the bundled Apple family, so the Apple owner stays. What must not ship is + // the desktop implementation and its Swift helper. The shared XCTest runner's macOS wire cases + // and Swift branches stay in the core by decision (#4675), so no marker names them. + owner: 'macos platform', + paths: [/(?:^|\/)platform-macos\//, /(?:^|\/)macos-helper(?:\/|$)/], + markers: [ + 'agent-device-macos-helper', + 'AGENT_DEVICE_MACOS_HELPER_BIN', + 'macos_launch_services_registration_probe_failed', + 'The native macOS app backend acts through accessibility actions only', + ], + }, ] as const; const repoRoot = path.resolve(import.meta.dirname, '..'); diff --git a/scripts/layering/architecture-ownership.ts b/scripts/layering/architecture-ownership.ts index 01523b0fdd..72523641f2 100644 --- a/scripts/layering/architecture-ownership.ts +++ b/scripts/layering/architecture-ownership.ts @@ -305,6 +305,7 @@ export const ARCHITECTURE_OWNERSHIP = { 'packages/platform-apple/', 'packages/platform-harmonyos/', 'packages/platform-linux/', + 'packages/platform-macos/', 'packages/platform-vega/', 'packages/platform-web/', 'packages/provider-aws-device-farm/', diff --git a/scripts/layering/contracts-exports.snapshot.json b/scripts/layering/contracts-exports.snapshot.json index 9b60b37cb8..db8536d2b9 100644 --- a/scripts/layering/contracts-exports.snapshot.json +++ b/scripts/layering/contracts-exports.snapshot.json @@ -74,6 +74,7 @@ "@agent-device/contracts/linux-tool-provider", "@agent-device/contracts/local-interactor-operation-set", "@agent-device/contracts/logs-runtime-plan", + "@agent-device/contracts/macos-platform-leaf", "@agent-device/contracts/managed-web-backend", "@agent-device/contracts/navigation", "@agent-device/contracts/network-runtime", diff --git a/scripts/layering/model.ts b/scripts/layering/model.ts index 16ad65329e..c7da387d29 100644 --- a/scripts/layering/model.ts +++ b/scripts/layering/model.ts @@ -130,6 +130,8 @@ export const UNRANKED_ZONES: ReadonlySet = new Set([ // The Apple-family runner engine: composed by platform-apple, below it in the package graph. 'apple-runner', ...PLATFORMS.map((family) => `platform-${family}`), + // The managed macOS leaf of the Apple family: a platform package that holds no family. + 'platform-macos', 'provider-webdriver', 'provider-aws-device-farm', 'provider-browserstack', diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index 2dadce4def..380aba66ac 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -643,7 +643,8 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/platform-apple/debug-symbols', '@agent-device/platform-apple/doctor', '@agent-device/platform-apple/install-artifact', - '@agent-device/platform-apple/macos', + '@agent-device/platform-apple/macos-desktop', + '@agent-device/platform-apple/macos-leaf', '@agent-device/platform-apple/perf', '@agent-device/platform-apple/physical-device', '@agent-device/platform-apple/runner-owner', diff --git a/scripts/layering/platform-package-leaf-policy.test.ts b/scripts/layering/platform-package-leaf-policy.test.ts new file mode 100644 index 0000000000..c9635092b0 --- /dev/null +++ b/scripts/layering/platform-package-leaf-policy.test.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { checkPlatformPackagePolicy } from './platform-package-policy.ts'; +import { declarations, policyOptions, validSources } from './platform-package-policy.fixtures.ts'; + +// The managed macOS leaf package (#4675): it holds a leaf of the bundled `apple` family, so R13 +// polices its declaration and its imports apart from the family packages. + +function messages( + sources: ReadonlyMap, + packages = declarations(), +): readonly string[] { + return checkPlatformPackagePolicy(sources, packages, policyOptions()).map( + ({ message }) => message, + ); +} + +test('the managed macOS leaf package is required and must declare the leaf it holds', () => { + const withoutLeaf = declarations().filter(({ family }) => family !== 'macos'); + assert.match( + messages(validSources(), withoutLeaf).join('\n'), + /missing managed platform leaf package packages\/platform-macos/, + ); + + // A leaf package that claims the whole family is not the leaf it is declared to be. + const familyClaim = declarations().map((declaration) => + declaration.family === 'macos' + ? { ...declaration, managedClaim: { platform: 'apple', apiVersion: 3 } } + : declaration, + ); + assert.match( + messages(validSources(), familyClaim).join('\n'), + /Managed platform must declare its family leaf and export only @agent-device\/macos\/agent-device/, + ); +}); + +test('the macOS leaf package may not import the Apple owner it serves', () => { + // The owner injects its runner and its tools; the leaf never reaches the owner's package. + const file = 'packages/platform-macos/src/runner-commands.ts'; + const found = messages( + new Map([ + ...validSources(), + [file, "import { runAppleRunnerCommand } from '@agent-device/platform-apple';"], + ]), + ).join('\n'); + assert.match(found, /platform-macos may not import sibling '@agent-device\/platform-apple'/); +}); diff --git a/scripts/layering/platform-package-policy.fixtures.ts b/scripts/layering/platform-package-policy.fixtures.ts index 006c391cee..1d076e4a07 100644 --- a/scripts/layering/platform-package-policy.fixtures.ts +++ b/scripts/layering/platform-package-policy.fixtures.ts @@ -32,7 +32,27 @@ function managedPackageName(family: string): string { return `@agent-device/${family}`; } -export function declarations(): PlatformPackageDeclaration[] { +/** The managed macOS leaf package: it holds a leaf of the bundled `apple` family, not a family. */ +export function macOsLeafDeclaration(): PlatformPackageDeclaration { + return { + dir: 'packages/platform-macos', + family: 'macos', + name: '@agent-device/macos', + managedClaim: { platform: 'apple', appleOs: 'macos', apiVersion: 3 }, + publishedSubpaths: ['./agent-device'], + private: true, + exportedSubpaths: ['@agent-device/macos/agent-device'], + }; +} + +/** Every platform package declaration, or only the family packages for a test that edits them by index. */ +export function declarations(scope: 'all' | 'families' = 'all'): PlatformPackageDeclaration[] { + return scope === 'families' + ? familyDeclarations() + : [...familyDeclarations(), macOsLeafDeclaration()]; +} + +function familyDeclarations(): PlatformPackageDeclaration[] { return CANONICAL_PLATFORM_FAMILIES.map((family) => ({ dir: `packages/platform-${family}`, family, @@ -53,7 +73,8 @@ export function declarations(): PlatformPackageDeclaration[] { '@agent-device/platform-apple/debug-symbols', '@agent-device/platform-apple/doctor', '@agent-device/platform-apple/install-artifact', - '@agent-device/platform-apple/macos', + '@agent-device/platform-apple/macos-desktop', + '@agent-device/platform-apple/macos-leaf', '@agent-device/platform-apple/perf', '@agent-device/platform-apple/physical-device', '@agent-device/platform-apple/runner/operations', diff --git a/scripts/layering/platform-package-policy.test.ts b/scripts/layering/platform-package-policy.test.ts index 03c64c4c12..2acf8289f4 100644 --- a/scripts/layering/platform-package-policy.test.ts +++ b/scripts/layering/platform-package-policy.test.ts @@ -65,7 +65,7 @@ test('untracked production TypeScript makes committed-state evidence fail closed }); test('family packages are exact, private, and expose only their root facade', () => { - const packages = declarations(); + const packages = declarations('families'); packages[0] = { ...packages[0]!, private: false }; packages[1] = { ...packages[1]!, name: '@agent-device/not-android' }; packages[2] = { ...packages[2]!, managedClaim: { platform: 'linux', apiVersion: 3 } }; @@ -830,7 +830,7 @@ test('managed platform code enters core only through the registry', () => { // diagnostic store never enter it: a runtime import of either runs outside the request the plugin was // asked to serve. The plugin binds to the host its `setup` receives instead. No managed package // carries an entry: every one of them is on the host. -for (const family of ['web', 'vega', 'harmonyos'] as const) { +for (const family of ['web', 'vega', 'harmonyos', 'macos'] as const) { test(`a managed platform package may not reach the host-kit command or diagnostics scope (${family})`, () => { const file = `packages/platform-${family}/src/new-surface.ts`; for (const specifier of [ diff --git a/scripts/layering/platform-package-policy.ts b/scripts/layering/platform-package-policy.ts index ed69a9e9b6..dd190870ab 100644 --- a/scripts/layering/platform-package-policy.ts +++ b/scripts/layering/platform-package-policy.ts @@ -47,7 +47,7 @@ export type PlatformPackageDeclaration = { family: string; name: string; private: boolean; - managedClaim?: { platform?: unknown; apiVersion?: unknown }; + managedClaim?: { platform?: unknown; apiVersion?: unknown; appleOs?: unknown }; publishedSubpaths?: readonly string[]; exportedSubpaths: readonly string[]; }; @@ -104,7 +104,8 @@ const MECHANICS_FACET_SUBPATHS: Readonly>> = { linux: '@agent-device/linux', }; +/** + * The managed packages that hold a leaf of a bundled family instead of a family (#4675). macOS + * desktop automation is the one leaf: the bundled Apple owner keeps the `apple` claim, and this + * package holds `{ platform: 'apple', appleOs: 'macos' }`. A leaf package is keyed by its + * `packages/platform-` directory and obeys every rule a managed family package obeys: one + * `./agent-device` entry, no sibling platform import, no host-kit export that reaches the exec or + * diagnostics roots, and a metadata-eager façade. + */ +export const MANAGED_PLATFORM_LEAVES: Readonly< + Record> +> = { + macos: { name: '@agent-device/macos', family: 'apple', appleOs: 'macos' }, +}; + +/** The managed package a `packages/platform-` directory holds, family or leaf. */ +function managedPackageName(owner: string): string | undefined { + return MANAGED_PLATFORMS[owner as PlatformFamily] ?? MANAGED_PLATFORM_LEAVES[owner]?.name; +} + +const MANAGED_PACKAGE_NAMES: readonly string[] = [ + ...Object.values(MANAGED_PLATFORMS), + ...Object.values(MANAGED_PLATFORM_LEAVES).map((leaf) => leaf.name), +]; + /** * The host-kit surfaces a managed platform package may not reach at runtime. Which exported names of a * subpath are dangerous is not listed here: it is derived from the host-kit module graph by @@ -301,11 +326,14 @@ function isTestKitTestImport(file: string, specifier: string): boolean { function managedPlatformDeclarationFailures( declaration: PlatformPackageDeclaration, expectedName: string, + // What the package's claim must name: its own family, or the family and leaf it narrows. + claim: Readonly<{ platform: string; appleOs?: string }> = { platform: declaration.family }, ): LayeringViolation[] { const file = `${declaration.dir}/package.json`; if ( declaration.name !== expectedName || - declaration.managedClaim?.platform !== declaration.family || + declaration.managedClaim?.platform !== claim.platform || + declaration.managedClaim?.appleOs !== claim.appleOs || declaration.managedClaim?.apiVersion !== 3 || declaration.exportedSubpaths.length !== 1 || declaration.exportedSubpaths[0] !== `${expectedName}/agent-device` || @@ -316,7 +344,7 @@ function managedPlatformDeclarationFailures( violation( file, 1, - `Managed platform must declare its family and export only ${expectedName}/agent-device`, + `Managed platform must declare its ${claim.appleOs === undefined ? 'family' : 'family leaf'} and export only ${expectedName}/agent-device`, ), ]; } @@ -377,9 +405,23 @@ function checkDeclarations(packages: readonly PlatformPackageDeclaration[]): Lay ); } } + for (const [leaf, { name, family, appleOs }] of Object.entries(MANAGED_PLATFORM_LEAVES)) { + const expectedDir = `packages/platform-${leaf}`; + const declaration = packages.find((pkg) => pkg.dir === expectedDir); + if (!declaration) { + violations.push( + violation(expectedDir, 1, `missing managed platform leaf package ${expectedDir}`), + ); + continue; + } + violations.push( + ...managedPlatformDeclarationFailures(declaration, name, { platform: family, appleOs }), + ); + } for (const declaration of packages) { if (!declaration.dir.startsWith('packages/platform-')) continue; const family = declaration.dir.slice('packages/platform-'.length); + if (Object.hasOwn(MANAGED_PLATFORM_LEAVES, family)) continue; if (!(CANONICAL_PLATFORM_FAMILIES as readonly string[]).includes(family)) { violations.push( violation(declaration.dir, 1, `${declaration.dir} is not a canonical platform family`), @@ -425,7 +467,7 @@ function checkSource( violations.push(...appleRunnerPackageSiteViolations(file, site)); } violations.push(...appleRunnerEntryImporterViolations(file, site)); - const managedImport = Object.values(MANAGED_PLATFORMS).some( + const managedImport = MANAGED_PACKAGE_NAMES.some( (name) => site.spec === name || site.spec.startsWith(name + '/'), ); if (managedImport && isProductionSourceFile(file)) { @@ -479,7 +521,7 @@ function checkSource( ); } if (!ownerFamily) continue; - const managedName = MANAGED_PLATFORMS[ownerFamily as PlatformFamily]; + const managedName = managedPackageName(ownerFamily); if (managedName && isProductionSourceFile(file)) { violations.push(...managedHostKitScopeViolations(file, site, managedName, hostKitReach)); } @@ -514,9 +556,7 @@ function checkSource( ); } const importsPluginTypes = - MANAGED_PLATFORMS[ownerFamily as PlatformFamily] && - site.typeOnly && - site.spec === 'agent-device/plugins'; + managedPackageName(ownerFamily) && site.typeOnly && site.spec === 'agent-device/plugins'; if ( resolvesOutsidePackage(file, site.spec, ownerFamily) || (/^agent-device(?:\/|$)/.test(site.spec) && !importsPluginTypes) diff --git a/scripts/layering/platform-package-repository.ts b/scripts/layering/platform-package-repository.ts index 52a8ad54b1..c0923dee02 100644 --- a/scripts/layering/platform-package-repository.ts +++ b/scripts/layering/platform-package-repository.ts @@ -35,7 +35,7 @@ export function readTrackedPlatformPackageDeclarations( private?: boolean; exports?: Record; publishConfig?: { exports?: Record }; - 'agent-device'?: { platform?: unknown; apiVersion?: unknown }; + 'agent-device'?: { platform?: unknown; apiVersion?: unknown; appleOs?: unknown }; }; const family = path.posix.basename(dir).slice('platform-'.length); return { diff --git a/scripts/layering/process-globals-policy.test.ts b/scripts/layering/process-globals-policy.test.ts index 6e72fc7a4d..6c8c2d779b 100644 --- a/scripts/layering/process-globals-policy.test.ts +++ b/scripts/layering/process-globals-policy.test.ts @@ -159,7 +159,7 @@ test('non-configuration process members and unrelated property names remain perm [], ); for (const file of [ - 'packages/platform-apple/src/os/macos/helper.ts', + 'packages/platform-macos/src/helper.ts', 'packages/apple-runner/src/runner-process-launch.ts', ]) { assert.equal(check('captureHostEnvironment(process);', file).length, 1, file); diff --git a/scripts/lib/macos-helper-pack.d.mts b/scripts/lib/macos-helper-pack.d.mts new file mode 100644 index 0000000000..defa0a3899 --- /dev/null +++ b/scripts/lib/macos-helper-pack.d.mts @@ -0,0 +1,13 @@ +// Type surface for the plain-Node helper pack rules: the package smoke imports the module with bare +// `node`, so it is not in the typechecked program. Keep this file in step with the exports there. +/** Where the helper sits in the packed `@agent-device/macos` tree. */ +export const MACOS_HELPER_PACK_ROOT: 'macos-helper'; + +/** The test targets the helper manifest declares. */ +export function readMacosHelperTestTargets(manifestSource: string): string[]; + +/** The helper's pack stubs: the only paths under its `Tests/` directory the package may carry. */ +export const DOCUMENTED_PACK_STUBS: readonly string[]; + +/** Every way the packed helper tree is not the buildable package it must be, one line each. */ +export function macosHelperPackFailures(paths: readonly string[], manifestSource: string): string[]; diff --git a/scripts/lib/macos-helper-pack.mjs b/scripts/lib/macos-helper-pack.mjs new file mode 100644 index 0000000000..d58b65fcc5 --- /dev/null +++ b/scripts/lib/macos-helper-pack.mjs @@ -0,0 +1,79 @@ +/** + * What the `@agent-device/macos` package must pack for its Swift helper, in one owner. + * + * The package ships `macos-helper` as buildable source and builds it on the user's machine. Its + * manifest declares the test targets, and SwiftPM refuses to load a package whose declared test + * target has no sources. So `files` ships exactly one `PackStub.swift` per target and excludes + * every other test source. Nothing else verifies the packed tree compiles before a user's first + * macOS command, so these rules read the pack's own file list. + */ + +/** Where the helper sits in the packed `@agent-device/macos` tree. */ +export const MACOS_HELPER_PACK_ROOT = 'macos-helper'; + +/** The test targets the helper manifest declares: the one reading of which test targets exist. */ +export function readMacosHelperTestTargets(manifestSource) { + return [...manifestSource.matchAll(/\.testTarget\(\s*name:\s*"([^"]+)"/g)].map( + (match) => match[1], + ); +} + +/** + * The helper's pack stubs: the only paths under its `Tests/` directory the package may carry. A new + * target's stub must be declared here, in the failing direction. + */ +export const DOCUMENTED_PACK_STUBS = Object.freeze([ + `${MACOS_HELPER_PACK_ROOT}/Tests/AgentDeviceMacOSHelperTests/PackStub.swift`, + `${MACOS_HELPER_PACK_ROOT}/Tests/AgentDeviceMacOSInputTests/PackStub.swift`, +]); + +/** Every way the packed helper tree is not the buildable package it must be, one line each. */ +export function macosHelperPackFailures(paths, manifestSource) { + const failures = []; + const testsRoot = `${MACOS_HELPER_PACK_ROOT}/Tests`; + const manifestPath = `${MACOS_HELPER_PACK_ROOT}/Package.swift`; + const documentedStubPaths = new Set(DOCUMENTED_PACK_STUBS); + const shippedSwiftTests = paths.filter( + (entryPath) => + (entryPath === testsRoot || entryPath.startsWith(`${testsRoot}/`)) && + !documentedStubPaths.has(entryPath), + ); + if (shippedSwiftTests.length > 0) { + failures.push(`npm pack includes macOS helper test sources: ${shippedSwiftTests.join(', ')}`); + } + const buildOutput = paths.filter((entryPath) => entryPath.includes('/.build/')); + if (buildOutput.length > 0) { + failures.push(`npm pack includes macOS helper build output: ${buildOutput.join(', ')}`); + } + // Sources without the manifest are not a buildable Swift package, and a package with no helper + // at all cannot serve a macOS command. + if (!paths.includes(manifestPath)) { + failures.push('npm pack ships no macOS helper Package.swift'); + return failures; + } + if (!paths.some((entryPath) => entryPath.startsWith(`${MACOS_HELPER_PACK_ROOT}/Sources/`))) { + failures.push('npm pack ships the macOS helper manifest without its sources'); + } + const expectedStubs = new Set( + readMacosHelperTestTargets(manifestSource).map( + (target) => `${testsRoot}/${target}/PackStub.swift`, + ), + ); + const missingStubs = [...expectedStubs].filter((stubPath) => !paths.includes(stubPath)); + if (missingStubs.length > 0) { + failures.push( + `npm pack is missing macOS helper test-target pack stubs: ${missingStubs.join(', ')}`, + ); + } + // The other direction: a declared stub whose target left the manifest stays exempt from the path + // rule above, so it is compared against the manifest set here. + const staleStubs = [...documentedStubPaths].filter( + (stubPath) => paths.includes(stubPath) && !expectedStubs.has(stubPath), + ); + if (staleStubs.length > 0) { + failures.push( + `npm pack ships documented pack stubs no test target declares: ${staleStubs.join(', ')}`, + ); + } + return failures; +} diff --git a/scripts/lib/shipped-test-code.ts b/scripts/lib/shipped-test-code.ts index 58c2392d59..b935d17349 100644 --- a/scripts/lib/shipped-test-code.ts +++ b/scripts/lib/shipped-test-code.ts @@ -13,7 +13,6 @@ */ import { UNIT_TEST_CONDITION } from '../package-apple-runner-source.mjs'; -import { DOCUMENTED_PACK_STUBS } from '../size-report-package.mjs'; /** Test-only directory names. Any packed path carrying one of these segments is test code. */ const TEST_ONLY_DIRECTORY_NAMES = new Set(['UnitTests', 'Tests', '__tests__', 'fixtures', 'mocks']); @@ -25,10 +24,6 @@ const TEST_ONLY_DIRECTORY_NAMES = new Set(['UnitTests', 'Tests', '__tests__', 'f const TEST_ONLY_FILE_PATTERN = /(^|[._])(test|spec)\.[^/]+$/; const TEST_ONLY_FILE_SUFFIX = 'ForTesting'; -// The allowed pack stubs live in scripts/size-report-package.mjs, the publish check that already -// requires one per test target; both decisions cannot drift. -const documentedPackStubPaths = new Set(DOCUMENTED_PACK_STUBS); - /** Packaged-source locations scanned for test code that survived stripping, by path segments. */ const RUNNER_SOURCE_ROOT = ['dist', 'apple', 'runner']; const RUNNER_HOST_APP_TARGET = [ @@ -66,16 +61,10 @@ function isTestOnlyFileName(fileName: string): boolean { return TEST_ONLY_FILE_PATTERN.test(fileName) || fileName.includes(TEST_ONLY_FILE_SUFFIX); } -/** - * Every packed path that names test code, as `path: reason` lines. The documented PackStubs are - * the single exemption; they are listed rather than patterned so a new stub has to be declared. - */ +/** Every packed path that names test code, as `path: reason` lines. Nothing is exempt. */ export function testOnlyPathFailures(packedPaths: Iterable): string[] { const failures: string[] = []; for (const packedPath of packedPaths) { - if (documentedPackStubPaths.has(packedPath)) { - continue; - } const directory = hasTestOnlyDirectory(packedPath); if (directory !== undefined) { failures.push(`${packedPath}: test-only directory "${directory}/" ships in the package.`); diff --git a/scripts/size-report-package.d.mts b/scripts/size-report-package.d.mts index 2056499a20..9b50cdc744 100644 --- a/scripts/size-report-package.d.mts +++ b/scripts/size-report-package.d.mts @@ -1,8 +1,6 @@ // Type surface for the plain-Node size-report module (it must stay runnable by bare `node`, so // it is not in the typechecked program). TypeScript resolves this file when a checked module // imports `./size-report-package.mjs`; keep it in step with the exports there. -export const DOCUMENTED_PACK_STUBS: readonly string[]; -export function readMacosHelperTestTargets(manifestSource: string): string[]; export type NpmPackEntry = Readonly<{ path: string; size: number }>; export function assertBundledLicenseNotices( entries: readonly NpmPackEntry[], @@ -14,7 +12,6 @@ export function assertPublishPackageContents( noticesRoot?: string; repoRoot?: string; requireSnapshotBridge?: boolean; - macosHelperManifestSource?: string; }>, ): void; diff --git a/scripts/size-report-package.mjs b/scripts/size-report-package.mjs index f873a1c557..f8a6a11d3a 100644 --- a/scripts/size-report-package.mjs +++ b/scripts/size-report-package.mjs @@ -23,29 +23,6 @@ export function assertSnapshotBridgeAssets(presentPaths, context) { } } -/** - * The test targets the macOS helper manifest declares — the one reading of "which test targets - * exist". SwiftPM refuses to load a package whose declared test target has no sources, so each - * name here must appear in the pack as `apple/macos-helper/Tests//PackStub.swift`. - */ -export function readMacosHelperTestTargets(manifestSource) { - return [...manifestSource.matchAll(/\.testTarget\(\s*name:\s*"([^"]+)"/g)].map( - (match) => match[1], - ); -} - -/** - * The macOS helper's pack stubs: the only paths under a `Tests/` directory the package may carry. - * SwiftPM refuses to resolve a declared test target without sources, so `files` ships exactly one - * stub per target; a new target's stub must be declared here, in the failing direction. One owner - * for both decisions this list governs: the publish check in this file, and the package-wide - * no-test-code path guard, which imports it (scripts/lib/shipped-test-code.ts). - */ -export const DOCUMENTED_PACK_STUBS = Object.freeze([ - 'apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/PackStub.swift', - 'apple/macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift', -]); - export function collectNpmPack(root) { const cachePath = path.join(root, '.tmp', 'npm-cache'); fs.mkdirSync(cachePath, { recursive: true }); @@ -176,59 +153,13 @@ export function assertPublishPackageContents(entries, options = {}) { if (forbiddenPaths.length > 0) { throw new Error(`npm pack includes benchmark or build scripts: ${forbiddenPaths.join(', ')}`); } - // The macOS helper ships as buildable source. Its manifest declares the test targets, so the - // packed tree must hold at least one source per target or the install-time `swift build` dies; - // `files` ships exactly the stubs DOCUMENTED_PACK_STUBS declares and excludes every other test - // source. Anything else under Tests/ in the pack means the exclusion list leaked real tests. - const documentedStubPaths = new Set(DOCUMENTED_PACK_STUBS); - const shippedSwiftTests = paths.filter( - (entryPath) => - (entryPath === 'apple/macos-helper/Tests' || - entryPath.startsWith('apple/macos-helper/Tests/')) && - !documentedStubPaths.has(entryPath), - ); - if (shippedSwiftTests.length > 0) { - throw new Error(`npm pack includes macOS helper test sources: ${shippedSwiftTests.join(', ')}`); - } - // Helper sources without the manifest are not a buildable Swift package, so a dropped - // `files` entry that ships Sources but not Package.swift must fail here, not on the user's - // machine. With the manifest present, read the target list from it — the pack and the - // manifest can then never drift onto different target sets. - if (paths.some((entryPath) => entryPath.startsWith('apple/macos-helper/Sources/'))) { - if (!paths.includes('apple/macos-helper/Package.swift')) { - throw new Error('npm pack ships macOS helper sources without its Package.swift'); - } - } - if (paths.includes('apple/macos-helper/Package.swift')) { - const manifestSource = - options.macosHelperManifestSource ?? - fs.readFileSync( - path.join(options.repoRoot ?? process.cwd(), 'apple/macos-helper/Package.swift'), - 'utf8', - ); - const expectedStubs = new Set( - readMacosHelperTestTargets(manifestSource).map( - (target) => `apple/macos-helper/Tests/${target}/PackStub.swift`, - ), - ); - const missingStubs = [...expectedStubs].filter((stubPath) => !paths.includes(stubPath)); - if (missingStubs.length > 0) { - throw new Error( - `npm pack is missing macOS helper test-target pack stubs: ${missingStubs.join(', ')}`, - ); - } - // The other direction: a declared stub whose target left the manifest stays exempt from the - // path guard above, so compare against the manifest set here. A target removed or renamed - // without retiring its package.json `files` entry and its DOCUMENTED_PACK_STUBS declaration - // would otherwise ship a dead stub forever. - const staleStubs = [...documentedStubPaths].filter( - (stubPath) => paths.includes(stubPath) && !expectedStubs.has(stubPath), + // macOS desktop automation and its Swift helper ship in the `@agent-device/macos` plugin. A + // helper path here means a `files` entry put the plugin's source back into the core. + const helperPaths = paths.filter((entryPath) => /(?:^|\/)macos-helper(?:\/|$)/.test(entryPath)); + if (helperPaths.length > 0) { + throw new Error( + `npm pack includes the macOS helper, which @agent-device/macos ships: ${helperPaths.join(', ')}`, ); - if (staleStubs.length > 0) { - throw new Error( - `npm pack ships documented pack stubs no test target declares: ${staleStubs.join(', ')}`, - ); - } } } diff --git a/test/integration/provider-scenarios/harness.ts b/test/integration/provider-scenarios/harness.ts index ca920cf76f..8123795420 100644 --- a/test/integration/provider-scenarios/harness.ts +++ b/test/integration/provider-scenarios/harness.ts @@ -1,6 +1,7 @@ import { webSelectionFixture } from '../../../src/platform-runtime-web-provider.fixtures.ts'; import { vegaSelectionFixture } from '../../../src/platform-runtime-vega-provider.fixtures.ts'; import { linuxSelectionFixture } from '../../../src/platform-runtime-linux-provider.fixtures.ts'; +import { macOsLeafSelectionFixture } from '../../../src/platform-runtime-macos-leaf.fixtures.ts'; import { composePlatformPlugins } from '../../../src/platform-runtime/platform-plugins.ts'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; @@ -191,6 +192,10 @@ export async function createProviderScenarioHarness( ...(linuxSelection ? [linuxSelection.get()] : []), ], [], + undefined, + // macOS desktop automation is the managed macOS package's. Composing its leaf binds it to + // the bundled Apple owner, so a macOS scenario runs the plugin's own implementation. + [macOsLeafSelectionFixture(input.host, input.baseDir).get()], ); const { web, vega, linux } = platforms; const defaultDeviceRuntimeGateway = createPlatformRuntimeGateway({ diff --git a/test/repo-guards/macos-helper-package-contents.test.ts b/test/repo-guards/macos-helper-package-contents.test.ts index ea585c336d..12007479d5 100644 --- a/test/repo-guards/macos-helper-package-contents.test.ts +++ b/test/repo-guards/macos-helper-package-contents.test.ts @@ -4,19 +4,25 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { runCmdSync } from '@agent-device/host-kit/command'; import { test } from 'vitest'; -import { readMacosHelperTestTargets } from '../../scripts/size-report-package.mjs'; +import { + DOCUMENTED_PACK_STUBS, + MACOS_HELPER_PACK_ROOT, + macosHelperPackFailures, + readMacosHelperTestTargets, +} from '../../scripts/lib/macos-helper-pack.mjs'; -// The npm package ships `apple/macos-helper` and builds it on the user's machine. Its manifest -// declares the test targets, and `files` ships only each target's PackStub.swift: SwiftPM refuses -// any load of a package whose declared test target has no sources, so the stubs are what keep the -// install-time `swift build` of the packed tree alive while the real tests stay out of the +// The `@agent-device/macos` package ships `macos-helper` and builds it on the user's machine. Its +// manifest declares the test targets, and `files` ships only each target's PackStub.swift: SwiftPM +// refuses any load of a package whose declared test target has no sources, so the stubs are what +// keep the install-time `swift build` of the packed tree alive while the real tests stay out of the // tarball. That forces the whole package — sources, tests, and manifest — into one directory, // which keeps every tool that copies the tree (Stryker's sandbox, coverage gates, Windows // checkouts) away from directory symlinks. Nothing else verifies the packed tree compiles — its // first consumer is a user's machine — so these guards hold the layout against the real pack list, // not the `files` text. const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); -const helperRoot = path.join(repoRoot, 'apple/macos-helper'); +const packageRoot = path.join(repoRoot, 'packages/platform-macos'); +const helperRoot = path.join(packageRoot, MACOS_HELPER_PACK_ROOT); const shippedManifestPath = path.join(helperRoot, 'Package.swift'); function shippedManifest(): string { @@ -29,11 +35,11 @@ function declaredTargetNames(manifest: string, kind: 'target' | 'executableTarge ].flatMap((match) => (match[1] === undefined ? [] : [match[1]])); } -function packedPaths(): string[] { +function packedPaths(root: string): string[] { // runCmdSync resolves `npm` through the PATH extensions a Windows checkout needs; a bare // execFileSync('npm', ...) there dies on ENOENT for npm.cmd. const result = runCmdSync('npm', ['pack', '--dry-run', '--json', '--ignore-scripts'], { - cwd: repoRoot, + cwd: root, maxBuffer: 64 * 1024 * 1024, }); const parsed = JSON.parse(result.stdout); @@ -62,15 +68,76 @@ test('every declared test target holds at least one real test in the checkout', } }); -test('the pack ships one PackStub.swift per declared test target and no other test source', () => { - const paths = packedPaths(); - const testTargetPaths = paths.filter((entryPath) => - entryPath.startsWith('apple/macos-helper/Tests/'), +test('the macOS plugin pack is a buildable helper package with one PackStub.swift per test target', () => { + const paths = packedPaths(packageRoot); + // Behavior, not config text: whatever `files` says, the tarball itself must carry the manifest, + // the sources and exactly the stubs — a missing stub breaks the install-time `swift build`, an + // extra test source ships dead tests. + assert.deepEqual(macosHelperPackFailures(paths, shippedManifest()), []); + assert.deepEqual( + paths.filter((entryPath) => entryPath.startsWith(`${MACOS_HELPER_PACK_ROOT}/Tests/`)).sort(), + [...DOCUMENTED_PACK_STUBS].sort(), + ); +}); + +test('the core pack carries no macOS helper', () => { + assert.deepEqual( + packedPaths(repoRoot).filter((entryPath) => /(?:^|\/)macos-helper(?:\/|$)/.test(entryPath)), + [], + ); +}); + +// The failure direction: the pack check can only ever watch a healthy package pass, so each rule is +// exercised here against a fixture path list. +const manifestSource = [ + '.testTarget(', + ' name: "AgentDeviceMacOSHelperTests",', + '.testTarget(', + ' name: "AgentDeviceMacOSInputTests",', +].join('\n'); +const healthyPack = [ + 'package.json', + 'dist/agent-device.mjs', + 'macos-helper/Package.swift', + 'macos-helper/Sources/AgentDeviceMacOSHelper/main.swift', + ...DOCUMENTED_PACK_STUBS, +]; + +test('the helper pack rules name each way a packed helper tree cannot build', () => { + assert.deepEqual(macosHelperPackFailures(healthyPack, manifestSource), []); + const without = (dropped: string) => healthyPack.filter((entryPath) => entryPath !== dropped); + const failuresOf = (paths: string[], manifest = manifestSource) => + macosHelperPackFailures(paths, manifest).join('\n'); + + // Each declared test target needs its PackStub.swift or the install-time `swift build` dies. + assert.match( + failuresOf(without('macos-helper/Tests/AgentDeviceMacOSInputTests/PackStub.swift')), + /pack stubs: macos-helper\/Tests\/AgentDeviceMacOSInputTests\/PackStub\.swift/, + ); + assert.match( + failuresOf([ + ...healthyPack, + 'macos-helper/Tests/AgentDeviceMacOSInputTests/ScheduleTests.swift', + ]), + /macOS helper test sources/, + ); + // A stub path the declared list does not name is a test source, not an exemption. + assert.match( + failuresOf([...healthyPack, 'macos-helper/Tests/AgentDeviceSneakyTests/PackStub.swift']), + /test sources: macos-helper\/Tests\/AgentDeviceSneakyTests\/PackStub\.swift/, + ); + // A declared stub whose target left the manifest is a dead stub riding in the pack. + assert.match( + failuresOf(healthyPack, ['.testTarget(', ' name: "AgentDeviceMacOSInputTests",'].join('\n')), + /no test target declares: macos-helper\/Tests\/AgentDeviceMacOSHelperTests\/PackStub\.swift/, + ); + assert.match(failuresOf(without('macos-helper/Package.swift')), /no macOS helper Package\.swift/); + assert.match( + failuresOf(without('macos-helper/Sources/AgentDeviceMacOSHelper/main.swift')), + /manifest without its sources/, + ); + assert.match( + failuresOf([...healthyPack, 'macos-helper/.build/release/agent-device-macos-helper']), + /build output/, ); - // Behavior, not config text: whatever `files` says, the tarball itself must carry exactly the - // stubs — a missing one breaks the install-time `swift build`, an extra one ships dead tests. - const expected = readMacosHelperTestTargets(shippedManifest()) - .map((target) => `apple/macos-helper/Tests/${target}/PackStub.swift`) - .sort(); - assert.deepEqual([...testTargetPaths].sort(), expected); }); diff --git a/test/repo-guards/npm-package-scripts.test.ts b/test/repo-guards/npm-package-scripts.test.ts index 0176c4c39f..eda09afd4f 100644 --- a/test/repo-guards/npm-package-scripts.test.ts +++ b/test/repo-guards/npm-package-scripts.test.ts @@ -52,7 +52,6 @@ test('the npm package build covers every package-owned output before verificatio assert.deepEqual(script('build:package').split(' && '), [ 'pnpm build', 'pnpm package:xcuitest', - 'pnpm build:macos-helper:clean', 'pnpm prepare:publish-assets', ]); assert.equal(script('prepare:publish-assets'), 'node scripts/prepare-publish-assets.mjs'); @@ -99,7 +98,7 @@ test('publishing cannot skip the package gate', () => { // The minimum-Node job runs the script directly — the repo's pinned pnpm needs a newer Node than // the floor that job covers — so it must still name the same entry point the script does. assert.deepEqual(script('check:package').split(' && '), [ - 'node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs packages/platform-web/test/package-smoke.mjs packages/platform-vega/test/package-smoke.mjs packages/platform-harmonyos/test/package-smoke.mjs packages/platform-linux/test/package-smoke.mjs', + 'node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs packages/maestro/test/package-smoke.mjs packages/replay/test/package-smoke.mjs packages/platform-web/test/package-smoke.mjs packages/platform-vega/test/package-smoke.mjs packages/platform-harmonyos/test/package-smoke.mjs packages/platform-linux/test/package-smoke.mjs packages/platform-macos/test/package-smoke.mjs', 'node --experimental-strip-types scripts/check-package.ts', ]); assert.match(packagedCliWorkflow, /with: \{ gate: package \}/); From 749e3e1ef38b6a993d460e98980ec142e143eb89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 21:12:22 +0100 Subject: [PATCH 06/15] refactor(macos): pin the helper's delivery mechanisms to the leaf contract with a total table --- CONTRIBUTING.md | 4 ++- docs/adr/0034-provider-plugin-registry.md | 11 +++++++- docs/agents/device-verification.md | 2 ++ packages/platform-macos/package.json | 2 +- packages/platform-macos/src/helper.ts | 34 ++++++++++------------- src/commands/schema/cli-help.ts | 5 ++++ website/docs/docs/commands.md | 1 + website/docs/docs/installation.md | 14 ++++++++-- 8 files changed, 49 insertions(+), 24 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 392e879ee8..ccbdb6aa4d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,7 +61,9 @@ project's `.tmp/`. The scripts refuse other override paths. They clean build out directory for every platform and keep other entries. Without an override, they clean the default directory under `~/.agent-device/apple-runner/derived`. -Android and macOS helper builds remain separate because they require their native toolchains: +Android and macOS helper builds remain separate because they require their native toolchains. +The macOS helper is part of the `@agent-device/macos` plugin and lives in +`packages/platform-macos/macos-helper`: ```bash pnpm build:android diff --git a/docs/adr/0034-provider-plugin-registry.md b/docs/adr/0034-provider-plugin-registry.md index c88a50f6dd..69a447f6c1 100644 --- a/docs/adr/0034-provider-plugin-registry.md +++ b/docs/adr/0034-provider-plugin-registry.md @@ -118,7 +118,16 @@ Required families retain completeness checks. Optional families may be absent. The current composition is in `src/platform-runtime.ts` and the family contract is in `packages/contracts/src/platform-module.ts`. macOS desktop remains a leaf under the single `apple` identity. -How the desktop runtime plugs into that identity is decided in [#4675](https://github.com/callstack/agent-device/issues/4675). +The managed `@agent-device/macos` package holds that leaf with the claim `{ kind: 'platform', family: 'apple', appleOs: 'macos' }` ([#4675](https://github.com/callstack/agent-device/issues/4675)). +A `platform` claim key has an optional `appleOs` part for this claim, and no other family uses it. +The bundled Apple owner keeps the `apple` claim for iOS and tvOS. +At each macOS branch, the owner calls the operations the installed leaf binds. +The leaf owns the two macOS app backends, the desktop surfaces, and the Swift helper. +The owner keeps the one Apple XCTest runner with its macOS wire cases, and gives the leaf a runner capability that is bound to one device. +The owner also gives the leaf the Apple tool routes of the calling request, so the leaf starts no command of its own. +When the package is absent, a macOS request returns `plugin-not-installed` with the install command, and discovery that names no platform omits the Mac. +A leaf of its own family was rejected because device identity would move out of the kernel and split the runner. +A plugin-owned runner was rejected because it needs a second Swift dispatch, build, and signing pipeline. ADR 0019 defines the platform runtime boundary. Version 2 plugins receive a typed incompatibility outcome without a compatibility shim. diff --git a/docs/agents/device-verification.md b/docs/agents/device-verification.md index dc35e807d7..ac87cbe6ac 100644 --- a/docs/agents/device-verification.md +++ b/docs/agents/device-verification.md @@ -59,6 +59,8 @@ The first run needs XCUITest automation permission. When you change Apple targets, synchronize the kernel model, runtime-fact admission, dispatch, discovery, and xctestrun preparation. Simulator-set scoping must not hide the host macOS target. +macOS desktop automation is the managed `@agent-device/macos` plugin. +Before you run a macOS device check, install the packed plugin with `agent-device plugins add` into an isolated `AGENT_DEVICE_HOME`. HarmonyOS has no provisioned CI device or HDC. Mocked tests do not replace local hardware evidence. Before you run a live smoke harness, read its entry file under `test/integration/` for environment requirements. diff --git a/packages/platform-macos/package.json b/packages/platform-macos/package.json index 89165ec816..c0d0e42ee3 100644 --- a/packages/platform-macos/package.json +++ b/packages/platform-macos/package.json @@ -55,5 +55,5 @@ "url": "git+https://github.com/callstack/agent-device.git", "directory": "packages/platform-macos" }, - "homepage": "https://agent-device.dev/docs/commands#macos-desktop-targets" + "homepage": "https://agent-device.dev/docs/commands#desktop-targets" } diff --git a/packages/platform-macos/src/helper.ts b/packages/platform-macos/src/helper.ts index 5bffb3afc1..1c5260a676 100644 --- a/packages/platform-macos/src/helper.ts +++ b/packages/platform-macos/src/helper.ts @@ -166,25 +166,21 @@ export const MACOS_HELPER_REFUSAL_REASONS: ReadonlySet = new Set([ MACOS_HELPER_REASONS.noScrollBar.reason, MACOS_HELPER_REASONS.noContextMenu.reason, ]); -export const MACOS_DELIVERY_MECHANISMS = [ - 'ax-press', - 'ax-focus', - 'ax-value', - 'ax-selected-text', - 'ax-confirm', - 'ax-scroll-bar', - 'ax-show-menu', - 'key-events', -] as const; -type AssertTrue = T; -/** Compile-time pin: this table and the leaf contract name the same mechanisms. */ -export type MacOsDeliveryMechanismsMatchContract = AssertTrue< - [MacOsDeliveryMechanism] extends [(typeof MACOS_DELIVERY_MECHANISMS)[number]] - ? [(typeof MACOS_DELIVERY_MECHANISMS)[number]] extends [MacOsDeliveryMechanism] - ? true - : false - : false ->; +// Total over the contract's mechanism type: a mechanism the leaf contract names and this table +// omits, or the reverse, fails the build. +const DELIVERY_MECHANISMS: Record = { + 'ax-press': true, + 'ax-focus': true, + 'ax-value': true, + 'ax-selected-text': true, + 'ax-confirm': true, + 'ax-scroll-bar': true, + 'ax-show-menu': true, + 'key-events': true, +}; +export const MACOS_DELIVERY_MECHANISMS: readonly MacOsDeliveryMechanism[] = Object.keys( + DELIVERY_MECHANISMS, +) as MacOsDeliveryMechanism[]; export function resolveMacOsHelperPackageRootFrom(modulePath: string): string { let currentDir = path.dirname(modulePath); diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index aa4cb2531e..15ea86c848 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -648,6 +648,11 @@ Rules: Use macOS only when the task targets desktop apps, desktop surfaces, or menu bar extras. +Dependency: + macOS desktop automation comes from the @agent-device/macos plugin. Before first use: + agent-device plugins add @agent-device/macos + Without it, a command that names --platform macos fails with details.reason plugin-not-installed and the install command. + Open and inspect: agent-device open TextEdit --platform macos agent-device snapshot -i --platform macos diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 181d75696c..b58e8bc12a 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -788,6 +788,7 @@ agent-device open --platform macos --surface desktop agent-device snapshot -i --platform apple --target desktop ``` +- macOS desktop automation runs through the optional `@agent-device/macos` plugin (`agent-device plugins add @agent-device/macos`; see [Installation](/docs/installation#macos-desktop-notes)). Without the plugin, a command such as `devices` or `open` that names `--platform macos` answers `UNSUPPORTED_PLATFORM` with `error.details.reason: plugin-not-installed`, the package name, and the install command. A `devices` call that names no platform leaves the Mac out. iOS and tvOS targets do not need the plugin. - `--platform macos`, or `--platform apple --target desktop`, selects the host Mac as a `desktop` target. - agent-device automates Electron and other Chromium-based macOS apps through the macOS accessibility tree. On the native backend, `snapshot` turns the app's Chromium accessibility tree on before reading it; once on, the tree stays on for the app's lifetime, so other surfaces see it too. See the Chromium note under the native backend below. - Use an `app` session for normal app control: `open`, `snapshot`, `click`, `fill`, `press`, `scroll`, `back`, `screenshot`, `record`. In app sessions, `screenshot` captures the app window, not the whole desktop. diff --git a/website/docs/docs/installation.md b/website/docs/docs/installation.md index 7ce1e009af..b41cc55e8d 100644 --- a/website/docs/docs/installation.md +++ b/website/docs/docs/installation.md @@ -20,7 +20,7 @@ Install `agent-device` on the machine where your coding agent runs terminal comm - HarmonyOS Command Line Tools for HarmonyOS (`hdc` available through `HDC_SDK_PATH`, `DEVECO_SDK_HOME`, or `HARMONYOS_COMMAND_LINE_TOOLS`), plus the HarmonyOS platform plugin (see [HarmonyOS prerequisites](#harmonyos-prerequisites)) - Amazon Vega Developer Tools and an SDK-matched Vega Virtual Device for Vega OS TV - Linux desktop tools (`xdotool` or `ydotool`, a clipboard tool, a screenshot tool, and `python3` with `python3-gi`) plus the Linux platform plugin for Linux desktop targets (see [Linux prerequisites](#linux-prerequisites)) -- Swift 5.9 or newer (Xcode command-line tools) for macOS desktop targets. `agent-device` builds its local macOS helper on first use +- Swift 5.9 or newer (Xcode command-line tools) plus the macOS platform plugin for macOS desktop targets (see [macOS desktop notes](#macos-desktop-notes)). The plugin builds its local macOS helper on first use ## Global install @@ -126,8 +126,18 @@ agent-device devices --platform linux ## macOS desktop notes +Install the macOS platform plugin before you use a macOS desktop target: + +```bash +agent-device plugins add @agent-device/macos +agent-device devices --platform macos +``` + +- The plugin holds macOS desktop automation and its Swift helper. iOS and tvOS targets do not need it. +- Without the plugin, a command such as `devices` or `open` that names `--platform macos` fails with `details.reason: "plugin-not-installed"` and the install command. Commands that name no platform leave the Mac out. +- `audio probe` samples host system audio through the helper, so it needs the plugin for iOS simulator and Android emulator sessions too. - macOS desktop automation uses a local `agent-device-macos-helper` for permission checks (`settings permission ...`), alert handling, and the `frontmost-app`, `desktop`, and `menubar` snapshot surfaces. -- `agent-device` builds the helper on first use and after updates, and caches it under `~/.agent-device/macos-helper/current/`. +- The plugin builds the helper on first use and after updates, and caches it under `~/.agent-device/macos-helper/current/`. - To use your own helper build, set `AGENT_DEVICE_MACOS_HELPER_BIN` to its absolute executable path. ## iOS physical device prerequisites From 4dc93c9ff81e8a4fa4366c19a25c522c9e7d3234 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 21:12:22 +0100 Subject: [PATCH 07/15] docs(macos): name the macOS plugin where macOS desktop automation is described The `help macos` topic, the website command and installation pages, CONTRIBUTING and the device verification guide state that macOS desktop automation is the `@agent-device/macos` plugin and how a request without it answers. ADR 0034 records the leaf claim, the owner delegation and the two rejected alternatives. Part of #4675 --- src/commands/schema/cli-help.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 15ea86c848..23377660f5 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -646,12 +646,7 @@ Rules: summary: 'macOS desktop, frontmost-app, and menu bar surfaces', body: `agent-device help macos -Use macOS only when the task targets desktop apps, desktop surfaces, or menu bar extras. - -Dependency: - macOS desktop automation comes from the @agent-device/macos plugin. Before first use: - agent-device plugins add @agent-device/macos - Without it, a command that names --platform macos fails with details.reason plugin-not-installed and the install command. +Use macOS only when the task targets desktop apps, desktop surfaces, or menu bar extras. It needs the macOS plugin; install it once with: agent-device plugins add @agent-device/macos Open and inspect: agent-device open TextEdit --platform macos From b46a7186f99d77ead9a6cabea406712d69b5ea45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 21:21:45 +0100 Subject: [PATCH 08/15] feat(plugins): name a platform leaf in the plugin listing, and record the extraction measurements `plugins list` prints `(apple macos)` for a package that holds the macOS leaf, so the listing does not read as a claim on the whole Apple family. The evidence note records the packed-core size against the 0.22 base and the live check. Part of #4675 --- ...s-platform-plugin-extraction-2026-11-21.md | 49 +++++++++++++++++++ .../platform-macos/test/package-smoke.mjs | 2 + src/cli/commands/plugins.ts | 9 +++- 3 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 docs/evidence/macos-platform-plugin-extraction-2026-11-21.md diff --git a/docs/evidence/macos-platform-plugin-extraction-2026-11-21.md b/docs/evidence/macos-platform-plugin-extraction-2026-11-21.md new file mode 100644 index 0000000000..1d60b30545 --- /dev/null +++ b/docs/evidence/macos-platform-plugin-extraction-2026-11-21.md @@ -0,0 +1,49 @@ +# macOS platform plugin extraction — measurements (2026-11-21) + +Issue #4675 moves macOS desktop automation and the `macos-helper` Swift package out of the published +core into the managed platform plugin `@agent-device/macos`. This note records the measurements for +that change. The decision is in ADR 0034. + +## Packed core size + +Both trees were built from a clean worktree with `pnpm install --frozen-lockfile && pnpm build`, then +packed with `npm pack --ignore-scripts --json`. Neither build ran `pnpm build:package`, so neither +pack holds the packaged runner source or the Android helper artifacts. The comparison is valid for +the difference, not for the published total. + +| Tree | Commit | Packed | Unpacked | Files | +| --- | --- | --- | --- | --- | +| `0.22` base | `80c44fe45e` | 1 638 382 B | 5 275 885 B | 645 | +| This change | `4dc93c9ff8` | 1 616 982 B | 5 188 827 B | 629 | +| Difference | | −21 400 B | −87 058 B | −16 | + +The base pack holds 11 `apple/macos-helper` files (116 181 B). The changed pack holds none. +The `@agent-device/macos` tarball is 70 157 B packed, 26 files, about 308 KB unpacked. + +The core keeps the shared Apple XCTest runner with its macOS wire cases and Swift desktop branches, +by the decision in #4675. That is why the JavaScript in `dist/src` changes by only −14 620 B: the +Apple owner still holds the runner routes, and the leaf port replaces the moved modules. + +## Live check on a Mac + +Host: macOS on Apple silicon, Xcode 27.1. The packed core was installed into an empty directory under +the repository `.tmp/`, with `AGENT_DEVICE_HOME` and `AGENT_DEVICE_STATE_DIR` inside it. + +| Step | Result | +| --- | --- | +| `devices --platform macos`, no plugin | `UNSUPPORTED_PLATFORM`, `plugin-not-installed`, install hint | +| `plugins add ./macos.tgz` | installed, listed as `(apple)` | +| `devices --platform macos` | the host Mac, `target=desktop` | +| `open TextEdit --platform macos` | opened | +| `snapshot -i`, default XCTest backend | blocked: see below | +| `open`, `snapshot -i`, `screenshot`, `press @e33`, `close`, native backend | all succeeded | + +The default XCTest backend did not start on this host. `prepare ios-runner --platform macos` answered +`COMMAND_FAILED: Runner did not accept connection (xcodebuild exited early)`, and the runner log +holds `Failed to initialize for UI testing: ... "Timed out while enabling automation mode."`. The +host has not authorized XCUITest Automation Mode. The runner is the shared core runner and this +change does not alter it. The permission was not granted and the check did not work around it. + +With `AGENT_DEVICE_MACOS_APP_BACKEND=native`, the plugin built its helper from the packed +`macos-helper` source and served the whole flow: a 45-node interactive snapshot of TextEdit, a +1172x976 window screenshot, and a press on a snapshot ref. The daemon was stopped afterwards. diff --git a/packages/platform-macos/test/package-smoke.mjs b/packages/platform-macos/test/package-smoke.mjs index 87b8fe98f3..2b1a105c82 100644 --- a/packages/platform-macos/test/package-smoke.mjs +++ b/packages/platform-macos/test/package-smoke.mjs @@ -157,6 +157,8 @@ test('packed core serves macOS desktop automation only after the managed platfor runCli(0, 'daemon', 'stop'); runCli(0, 'plugins', 'add', './macos.tgz'); + // The listing names the leaf the package holds, not the whole Apple family. + assert.match(cliText('plugins', 'list'), /@agent-device\/macos@\S+ \(apple macos\)/); // A daemon started before the store changed cannot see the new entry. runCli(0, 'daemon', 'stop'); diff --git a/src/cli/commands/plugins.ts b/src/cli/commands/plugins.ts index 6244967b1e..70168531f8 100644 --- a/src/cli/commands/plugins.ts +++ b/src/cli/commands/plugins.ts @@ -50,7 +50,7 @@ export const pluginsCommand: ClientCommandHandler = async ({ host, positionals, ] : plugins.map((plugin) => plugin.compatible - ? `${plugin.name}@${plugin.version} (${plugin.provider ?? plugin.platform ?? plugin.backend})` + ? `${plugin.name}@${plugin.version} (${plugin.provider ?? pluginPlatformLabel(plugin) ?? plugin.backend})` : plugin.name === undefined ? `Plugin config unavailable: ${plugin.error?.message}` : `${plugin.name}: unavailable; run plugins update ${plugin.name} or plugins remove ${plugin.name}`, @@ -72,3 +72,10 @@ export const pluginsCommand: ClientCommandHandler = async ({ host, positionals, ); return true; }; + +/** A platform claim as the listing names it: the family, with the leaf it narrows to when it has one. */ +function pluginPlatformLabel(plugin: { platform?: string; appleOs?: string }): string | undefined { + return plugin.platform === undefined || plugin.appleOs === undefined + ? plugin.platform + : `${plugin.platform} ${plugin.appleOs}`; +} From 411548d26fbbd85802dcbdb4a747015bc4e60fa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 21:21:55 +0100 Subject: [PATCH 09/15] docs(evidence): state the plugin install result without the listing label --- docs/evidence/macos-platform-plugin-extraction-2026-11-21.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/evidence/macos-platform-plugin-extraction-2026-11-21.md b/docs/evidence/macos-platform-plugin-extraction-2026-11-21.md index 1d60b30545..e0555101b4 100644 --- a/docs/evidence/macos-platform-plugin-extraction-2026-11-21.md +++ b/docs/evidence/macos-platform-plugin-extraction-2026-11-21.md @@ -32,7 +32,7 @@ the repository `.tmp/`, with `AGENT_DEVICE_HOME` and `AGENT_DEVICE_STATE_DIR` in | Step | Result | | --- | --- | | `devices --platform macos`, no plugin | `UNSUPPORTED_PLATFORM`, `plugin-not-installed`, install hint | -| `plugins add ./macos.tgz` | installed, listed as `(apple)` | +| `plugins add ./macos.tgz` | installed and listed | | `devices --platform macos` | the host Mac, `target=desktop` | | `open TextEdit --platform macos` | opened | | `snapshot -i`, default XCTest backend | blocked: see below | From 68d339fd2d031fcc8cb310d295dc285f22937a2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 21:32:05 +0100 Subject: [PATCH 10/15] fix(macos): bind the leaf port only from a process's whole platform selection Every platform composition bound the Apple owner's macOS leaf port, including the selection narrowed to the web family. That selection names no leaf, so it unbound an installed macOS leaf in the same process. The daemon composition and an unnarrowed installed-platform selection now bind explicitly, and composing a selection has no side effect on the owner. Part of #4675 --- packages/platform-apple/src/macos-leaf.ts | 5 ++++- ...daemon-composition-platform-plugin.test.ts | 8 ++++++- src/daemon-composition.ts | 4 +++- src/platform-runtime-host.test.ts | 16 ++++++++------ src/platform-runtime-macos-leaf.fixtures.ts | 10 ++++++--- src/platform-runtime/installed-platforms.ts | 22 +++++++++++++------ src/platform-runtime/platform-plugins.ts | 13 ++++++++--- .../integration/provider-scenarios/harness.ts | 10 ++++++--- 8 files changed, 62 insertions(+), 26 deletions(-) diff --git a/packages/platform-apple/src/macos-leaf.ts b/packages/platform-apple/src/macos-leaf.ts index 916de189ad..9e697beae0 100644 --- a/packages/platform-apple/src/macos-leaf.ts +++ b/packages/platform-apple/src/macos-leaf.ts @@ -16,7 +16,10 @@ import { readVersion } from '@agent-device/host-kit/version'; */ let boundSelection: MacOsPlatformLeafSelection | undefined; -/** Binds the composition's macOS leaf selection. The last composition of a process wins. */ +/** + * Binds the macOS leaf selection of the process. The composition root calls this for the selection + * that is the process's whole platform selection, never for one narrowed to a single family. + */ export function bindMacOsLeaf(selection: MacOsPlatformLeafSelection): void { boundSelection = selection; } diff --git a/src/daemon-composition-platform-plugin.test.ts b/src/daemon-composition-platform-plugin.test.ts index a0ab44b576..1778f428a9 100644 --- a/src/daemon-composition-platform-plugin.test.ts +++ b/src/daemon-composition-platform-plugin.test.ts @@ -358,7 +358,7 @@ test('an installed macOS plugin serves the leaf the bundled apple owner delegate const { home, env } = pluginHome(); const stateDir = path.join(home, 'state'); selectMacOsLeaf(home); - await withDaemonComposition(env, stateDir, async (deps) => { + await withDaemonComposition(env, stateDir, async (deps, host) => { expect(deps.pluginInventory).toContainEqual( expect.objectContaining({ package: macOsPackage, @@ -380,6 +380,12 @@ test('an installed macOS plugin serves the leaf the bundled apple owner delegate // and the Apple tools of the calling request. const mac = await deps.interactorResolution.resolve(devices[0]!, {}); await expect(mac.readClipboard!()).resolves.toBe(`${stateDir}|function|false`); + // A selection narrowed to one family names no leaf, so it must not unbind this one: the web + // backend composes only the web family, and the owner still reaches the macOS leaf afterwards. + await expect(createManagedWebBackend(host).doctor({ stateDir })).rejects.toMatchObject({ + details: expect.objectContaining({ reason: 'plugin-not-installed', family: 'web' }), + }); + await expect(mac.readClipboard!()).resolves.toBe(`${stateDir}|function|false`); }); }); diff --git a/src/daemon-composition.ts b/src/daemon-composition.ts index a34aa5e8b6..01786196ea 100644 --- a/src/daemon-composition.ts +++ b/src/daemon-composition.ts @@ -23,7 +23,7 @@ import { } from './provider-device-runtimes.ts'; import { readDaemonProviderCredentials } from './provider-credential-fingerprint.ts'; import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; -import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; +import { bindPlatformLeaves, composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; import type { WebPlatformSelection } from '@agent-device/contracts/platform-plugin'; import { getInteractor } from './core/interactors.ts'; import { @@ -138,6 +138,8 @@ export async function composeDaemonRuntimeDeps( providerComposition.assertSelectionCurrent, providerComposition.platformLeaves, ); + // This selection is the daemon's one platform selection, so its leaves are the owners' leaves. + bindPlatformLeaves(platforms); const { web, vega, harmony, linux } = platforms; const hostDiagnostics = createHostDiagnostics(host, web, vega, harmony, linux); const deviceRuntimeGateway = createPlatformRuntimeGateway({ diff --git a/src/platform-runtime-host.test.ts b/src/platform-runtime-host.test.ts index 37ff3c7acb..c068f361eb 100644 --- a/src/platform-runtime-host.test.ts +++ b/src/platform-runtime-host.test.ts @@ -6,7 +6,7 @@ import type { PlatformRequestScope } from '@agent-device/contracts/platform-runt import { createPlatformDeviceInventoryGateways } from './platform-runtime.ts'; import { vegaSelectionFixture } from './platform-runtime-vega-provider.fixtures.ts'; import { macOsLeafSelectionFixture } from './platform-runtime-macos-leaf.fixtures.ts'; -import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; +import { bindPlatformLeaves, composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; const toolchains = vi.hoisted(() => ({ appleEvaluations: 0, @@ -119,6 +119,13 @@ test('a host env with no home still inventories every family through the gateway // the gateways load the one host for all of them. Reverting the refusal makes both assertions // below red: the Apple host-Mac route fails with COMMAND_FAILED, and Vega fails with // COMMAND_FAILED instead of the honest TOOL_MISSING its PATH-only answer yields. + const platforms = composePlatformPlugins( + [vegaSelectionFixture({ env: {}, cwd: process.cwd() }).get()], + [], + undefined, + [macOsLeafSelectionFixture({ env: {}, cwd: process.cwd() }).get()], + ); + bindPlatformLeaves(platforms); const gateways = await createPlatformDeviceInventoryGateways( { env: {}, @@ -128,12 +135,7 @@ test('a host env with no home still inventories every family through the gateway // Vega is a platform plugin and macOS a leaf of the Apple family, so the scenario supplies // both: the assertions cover what their inventories answer when the host env names no home, // not the builtin family set. - composePlatformPlugins( - [vegaSelectionFixture({ env: {}, cwd: process.cwd() }).get()], - [], - undefined, - [macOsLeafSelectionFixture({ env: {}, cwd: process.cwd() }).get()], - ), + platforms, ); const scope: PlatformRequestScope = Object.freeze({ signal: new AbortController().signal, diff --git a/src/platform-runtime-macos-leaf.fixtures.ts b/src/platform-runtime-macos-leaf.fixtures.ts index ad78fbd84a..cdac1005c1 100644 --- a/src/platform-runtime-macos-leaf.fixtures.ts +++ b/src/platform-runtime-macos-leaf.fixtures.ts @@ -8,7 +8,7 @@ import type { import type { PlatformModuleSelection } from '@agent-device/contracts/platform-plugin'; import type { PlatformHost } from '@agent-device/plugins/contract'; import type { PluginCandidate } from '@agent-device/plugins/registry'; -import { composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; +import { bindPlatformLeaves, composePlatformPlugins } from './platform-runtime/platform-plugins.ts'; import { createPlatformPluginHost } from './platform-runtime/plugin-host.ts'; const pluginRequire = createRequire( @@ -38,10 +38,14 @@ export function macOsLeafSelectionFixture( /** * The platform selection of a process with the macOS package installed and no other platform - * plugin. Composing it binds the leaf to the bundled Apple owner, as the daemon's composition does. + * plugin. It binds the leaf to the bundled Apple owner, as the daemon's composition does. */ export function macOsPlatformCompositionFixture( ...args: Parameters ): PlatformModuleSelection { - return composePlatformPlugins([], [], undefined, [macOsLeafSelectionFixture(...args).get()]); + const platforms = composePlatformPlugins([], [], undefined, [ + macOsLeafSelectionFixture(...args).get(), + ]); + bindPlatformLeaves(platforms); + return platforms; } diff --git a/src/platform-runtime/installed-platforms.ts b/src/platform-runtime/installed-platforms.ts index 51ac0c5259..d8e2257a06 100644 --- a/src/platform-runtime/installed-platforms.ts +++ b/src/platform-runtime/installed-platforms.ts @@ -5,7 +5,11 @@ import { getOptionalPlatformPluginDeclaration } from '@agent-device/contracts/pl import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { PROVIDER_PLUGIN_POLICY } from '../provider-plugin-policy.ts'; -import { builtinPlatformCandidates, composePlatformPlugins } from './platform-plugins.ts'; +import { + bindPlatformLeaves, + builtinPlatformCandidates, + composePlatformPlugins, +} from './platform-plugins.ts'; import { createPlatformPluginHost } from './plugin-host.ts'; export type InstalledPlatforms = Readonly<{ @@ -62,13 +66,17 @@ export async function startInstalledPlatforms( 'platforms', ); try { + const platforms = composePlatformPlugins( + registry.platforms, + registry.inventory, + assertSelectionCurrent, + registry.platformLeaves, + ); + // Without `family` this is the whole selection of a process that runs outside the daemon, so + // its leaves are the owners' leaves. A selection narrowed to one family names no leaf. + if (family === undefined) bindPlatformLeaves(platforms); return Object.freeze({ - platforms: composePlatformPlugins( - registry.platforms, - registry.inventory, - assertSelectionCurrent, - registry.platformLeaves, - ), + platforms, close: async () => { await registry.close(); }, diff --git a/src/platform-runtime/platform-plugins.ts b/src/platform-runtime/platform-plugins.ts index 404b3eb007..0ade70dcce 100644 --- a/src/platform-runtime/platform-plugins.ts +++ b/src/platform-runtime/platform-plugins.ts @@ -154,10 +154,7 @@ export function composePlatformPlugins( }, }; - // The bundled Apple owner reaches the leaf through its own port, because its entry points take a - // device rather than a composition. Binding here keeps every composition and its owner in step. const macos = composeMacOsLeaf(platformLeaves, inventory, assertPluginSelectionCurrent); - bindMacOsLeaf(macos); return { interactors, @@ -173,6 +170,16 @@ export function composePlatformPlugins( }; } +/** + * Binds a process's platform selection to the bundled owners that delegate to a leaf. The Apple + * owner reaches the macOS leaf through its own port, because its entry points take a device rather + * than a composition. Only the composition that is the process's whole selection calls this: a + * composition narrowed to one family names no leaf, and must not unbind the one a process has. + */ +export function bindPlatformLeaves(platforms: PlatformModuleSelection): void { + bindMacOsLeaf(platforms.macos); +} + /** * The macOS leaf selection. macOS is a leaf of the bundled Apple family, so no family registry * answers for it: `get()` is the one authority on its absence, as the optional families' selections diff --git a/test/integration/provider-scenarios/harness.ts b/test/integration/provider-scenarios/harness.ts index 8123795420..ad60eec513 100644 --- a/test/integration/provider-scenarios/harness.ts +++ b/test/integration/provider-scenarios/harness.ts @@ -2,7 +2,10 @@ import { webSelectionFixture } from '../../../src/platform-runtime-web-provider. import { vegaSelectionFixture } from '../../../src/platform-runtime-vega-provider.fixtures.ts'; import { linuxSelectionFixture } from '../../../src/platform-runtime-linux-provider.fixtures.ts'; import { macOsLeafSelectionFixture } from '../../../src/platform-runtime-macos-leaf.fixtures.ts'; -import { composePlatformPlugins } from '../../../src/platform-runtime/platform-plugins.ts'; +import { + bindPlatformLeaves, + composePlatformPlugins, +} from '../../../src/platform-runtime/platform-plugins.ts'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import assert from 'node:assert/strict'; @@ -193,10 +196,11 @@ export async function createProviderScenarioHarness( ], [], undefined, - // macOS desktop automation is the managed macOS package's. Composing its leaf binds it to - // the bundled Apple owner, so a macOS scenario runs the plugin's own implementation. + // macOS desktop automation is the managed macOS package's, so a macOS scenario runs the + // plugin's own implementation. [macOsLeafSelectionFixture(input.host, input.baseDir).get()], ); + bindPlatformLeaves(platforms); const { web, vega, linux } = platforms; const defaultDeviceRuntimeGateway = createPlatformRuntimeGateway({ platforms, From da8234cc2332ba5a089ef6e72c94bf188512905e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 22:51:47 +0100 Subject: [PATCH 11/15] fix(apple): answer macOS facts without the installed leaf Under AGENT_DEVICE_MACOS_APP_BACKEND=native the admission-facts spread asked the macOS leaf for its native refusals, so a capability read raised plugin-not-installed for a Mac the process cannot drive. The backend is a daemon setting and listing facts is not a macOS call: ask the leaf only when it is installed, and keep the typed install outcome with the commands that need it. --- packages/platform-apple/src/runtime.test.ts | 26 ++++++++++++++++++++- packages/platform-apple/src/runtime.ts | 7 ++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/packages/platform-apple/src/runtime.test.ts b/packages/platform-apple/src/runtime.test.ts index 2777bbe965..9949572df6 100644 --- a/packages/platform-apple/src/runtime.test.ts +++ b/packages/platform-apple/src/runtime.test.ts @@ -19,7 +19,10 @@ import { HOVER_UNAVAILABLE_HINT } from '@agent-device/contracts/touch-runtime'; import type { AppleOS, DeviceInfo } from '@agent-device/kernel/device'; import { createApplePlatformRuntime } from './runtime.ts'; import { platformRuntimeHostFixture } from './runtime.fixtures.ts'; -import { bindMacOsLeafFixture } from './__tests__/macos-leaf.fixtures.ts'; +import { + bindAbsentMacOsLeafFixture, + bindMacOsLeafFixture, +} from './__tests__/macos-leaf.fixtures.ts'; bindTestCommandHost(); @@ -304,6 +307,27 @@ test('the native macOS app backend refuses what the installed leaf names before } }); +test('the native macOS app backend answers facts without the installed leaf', async () => { + vi.stubEnv('AGENT_DEVICE_MACOS_APP_BACKEND', 'native'); + bindAbsentMacOsLeafFixture(); + try { + // The backend is a daemon setting, so the lookup must answer its table for a Mac it cannot + // drive rather than raise the leaf's install outcome: listing facts is not a macOS call. + const facts = await createApplePlatformRuntime(platformRuntimeHostFixture()).inspectFacts( + leaves.macos, + ); + expect(facts.operations.screenRecordingStart).toEqual({ available: true }); + expect(facts.operations.back).toEqual({ available: true }); + expect(facts.operations.audioProbeStart).toEqual( + process.platform === 'darwin' + ? { available: true } + : expect.objectContaining({ available: false }), + ); + } finally { + vi.unstubAllEnvs(); + } +}); + test('hover has no Apple interactor route on macOS, iOS, or tvOS; the touch family reports its typed denial', async () => { for (const device of [leaves.macos, leaves.ios, leaves.tvos]) { const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({ diff --git a/packages/platform-apple/src/runtime.ts b/packages/platform-apple/src/runtime.ts index 36459b63b6..194572f57f 100644 --- a/packages/platform-apple/src/runtime.ts +++ b/packages/platform-apple/src/runtime.ts @@ -69,6 +69,7 @@ import { type MacOsAppBackend, } from '@agent-device/contracts/session'; import { macOsDesktop } from './core/macos-desktop.ts'; +import { isMacOsLeafInstalled } from './macos-leaf.ts'; import { applyWatchOsOperationFacts, bindWatchOsOperations } from './os/watchos/facts.ts'; import { createAppleSnapshotRoute } from './snapshot-route.ts'; @@ -231,8 +232,10 @@ export function createApplePlatformRuntime(host: PlatformRuntimeHost): PlatformR listApps: apps, ...appleApplicationLifecycleFacts(device), shutdownTarget: shutdownFact(device), - // Under the native backend the installed macOS leaf names what only the runner serves. - ...(isMacOs(device) && macOsAppBackend(device) === 'native' + // Under the native backend the installed macOS leaf names what only the runner serves. With + // no package installed there is nothing to ask: the facts answer no native refusal, and the + // typed `plugin-not-installed` outcome stays with the commands that need the leaf. + ...(isMacOs(device) && macOsAppBackend(device) === 'native' && isMacOsLeafInstalled() ? await macOsDesktop().nativeBackendFacts() : {}), }), From 4e5a9f6f51b37c792c180de1eac52f7a729ce914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 22:51:50 +0100 Subject: [PATCH 12/15] fix(plugins): refuse a platform leaf its family cannot narrow The two readers that describe a slot whose load failed read the declared `appleOs` with the leaf-tolerant reader, so `{ kind: 'platform', family: 'apple', appleOs: 'ios' }` came back as the whole `apple` claim. The registry reserved that widened claim, and the next package that really holds the family lost it as a duplicate. Both readers now refuse an un-narrowable leaf through the one helper the validating path uses, and a refused slot records the refusal instead of a claim. --- packages/plugins/src/platform.test.ts | 38 +++++++++++++ packages/plugins/src/registry.ts | 11 +++- packages/plugins/src/validate.test.ts | 79 +++++++++++++++++++++++++++ packages/plugins/src/validate.ts | 32 ++++++++--- 4 files changed, 150 insertions(+), 10 deletions(-) create mode 100644 packages/plugins/src/validate.test.ts diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts index 70dbe82b1c..9473c7f671 100644 --- a/packages/plugins/src/platform.test.ts +++ b/packages/plugins/src/platform.test.ts @@ -267,6 +267,44 @@ test.each([ await registry.close(); }); +test('a bad leaf in a returned plugin neither widens to the apple family nor denies it to the next package', async () => { + // A candidate with no package metadata claims what its factory returns. Before its claims are + // readable, the registry reads them off the returned value, and that read must refuse a leaf the + // family cannot narrow: reading it as the whole `apple` claim would deny that claim to the next + // package, which is the one that really holds it. + const badLeaf = { + source: 'embedder', + package: 'bad-leaf', + load: () => ({ + apiVersion: 3, + contributes: [{ kind: 'platform', family: 'apple', appleOs: 'ios', setup: () => undefined }], + }), + } as const; + const wholeApple = { + source: 'embedder', + package: 'whole-apple', + declaredClaims: [{ kind: 'platform', id: 'apple' }], + load: () => { + throw new Error('must never import'); + }, + } as const; + + const resolved = await resolveProviderPlugins([badLeaf, wholeApple]); + expect( + resolved + .inventory() + .map((entry) => [ + entry.package, + entry.platform, + entry.appleOs, + entry.state === 'failed' ? entry.error.reason : entry.state, + ]), + ).toEqual([ + ['bad-leaf', undefined, undefined, 'invalid_plugin'], + ['whole-apple', 'apple', undefined, 'plugin_load_failed'], + ]); +}); + test('a leaf setup that binds nothing is recorded as failed', async () => { const { home, env } = pluginHome(); selectPlugin( diff --git a/packages/plugins/src/registry.ts b/packages/plugins/src/registry.ts index 43d90dda4a..9ec2927180 100644 --- a/packages/plugins/src/registry.ts +++ b/packages/plugins/src/registry.ts @@ -287,7 +287,16 @@ function failedLoadClaims( failure: reservationFailure ?? failure, })); } - return readableClaimsOfValue(raw).map((claim) => { + let readable: readonly PluggedClaim[]; + try { + readable = readableClaimsOfValue(raw); + } catch { + // The declaration names a leaf its id cannot narrow, so it owns no claim: recording it against + // the widened id would deny that id to a package that really holds it. The slot reports the + // refusal the load raised. + return []; + } + return readable.map((claim) => { reserveClaim(claimed, claim); return { ...claim, slot, failure }; }); diff --git a/packages/plugins/src/validate.test.ts b/packages/plugins/src/validate.test.ts new file mode 100644 index 0000000000..41a042eba2 --- /dev/null +++ b/packages/plugins/src/validate.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; +import { claimKeyOf, readableClaimsOfValue } from './validate.ts'; + +// The readable claims of a value that failed before its claims were validated. The registry +// reserves these, so a leaf the id cannot narrow must refuse the read rather than widen the claim. + +const leafContribution = { + kind: 'platform', + family: 'apple', + appleOs: 'macos', + setup: () => undefined, +}; + +function appError(run: () => unknown): AppError { + try { + run(); + } catch (error) { + if (error instanceof AppError) return error; + throw error; + } + throw new Error('expected the readable claim read to refuse'); +} + +describe('readableClaimsOfValue reads one platform leaf spelling', () => { + test.each([ + ['the manifest spelling', { apiVersion: 3, platform: 'apple', appleOs: 'macos' }], + [ + 'the contribution spelling', + { + apiVersion: 3, + contributes: [leafContribution], + }, + ], + ] as const)('%s', (_name, value) => { + expect(readableClaimsOfValue(value).map(claimKeyOf)).toEqual(['platform:apple:macos']); + }); + + test.each([ + ['the manifest spelling', { apiVersion: 3, platform: 'apple', appleOs: 'ios' }], + ['a malformed leaf', { apiVersion: 3, platform: 'apple', appleOs: 'MacOS' }], + ['a leaf on another family', { apiVersion: 3, platform: 'web', appleOs: 'macos' }], + [ + 'the contribution spelling', + { + apiVersion: 3, + contributes: [{ ...leafContribution, appleOs: 'ios' }], + }, + ], + [ + 'a malformed contribution leaf', + { + apiVersion: 3, + contributes: [{ ...leafContribution, appleOs: true }], + }, + ], + [ + 'a leaf on another family in a contribution', + { + apiVersion: 3, + contributes: [{ ...leafContribution, family: 'web', appleOs: 'macos' }], + }, + ], + ] as const)('refers to %s as invalid_plugin rather than widening it', (_name, value) => { + const error = appError(() => readableClaimsOfValue(value)); + expect(error.code).toBe('INVALID_ARGS'); + expect(error.details?.reason).toBe('invalid_plugin'); + }); + + test('reads a whole-family platform claim and a provider claim unchanged', () => { + expect( + readableClaimsOfValue({ + apiVersion: 3, + platform: 'apple', + contributes: [{ kind: 'provider', provider: 'example' }], + }).map(claimKeyOf), + ).toEqual(['provider:example', 'platform:apple']); + }); +}); diff --git a/packages/plugins/src/validate.ts b/packages/plugins/src/validate.ts index d42eb1196f..eeb5debd4e 100644 --- a/packages/plugins/src/validate.ts +++ b/packages/plugins/src/validate.ts @@ -78,7 +78,15 @@ function requireClaimLeaf( source: Record, id: string, ): ClaimLeaf | undefined { - const declared = field === undefined ? undefined : source[field]; + return field === undefined ? undefined : requireDeclaredLeaf(source[field], field, id); +} + +/** + * The leaf one declared value names, refusing it the same way whichever reader reached it: a leaf + * that is present but cannot narrow its id would widen the claim to the whole id, which is a + * declaration no claim space admits. + */ +function requireDeclaredLeaf(declared: unknown, field: string, id: string): ClaimLeaf | undefined { if (declared === undefined) return undefined; const leaf = readClaimLeaf(declared, id); if (leaf === undefined) { @@ -116,7 +124,7 @@ const CLAIM_KINDS: { readonly [Kind in ClaimKind]: ClaimKindSpec } = { ...(appleOs === undefined ? {} : { appleOs }), }), readMetadata: (value) => readableClaimId(value, 'platform'), - readLeaf: (value, family) => readClaimLeaf(value, family), + readLeaf: (declaredLeaf, id) => requireDeclaredLeaf(declaredLeaf, 'appleOs', id), readContribution: (value) => { const id = readableClaimId(value.family, 'family'); if (typeof value.setup !== 'function') { @@ -217,8 +225,12 @@ type ClaimKindSpec = Readonly<{ identityFor(id: string, leaf?: ClaimLeaf): ClaimIdentity; /** Reads the id out of the `agent-device` field. */ readMetadata(value: unknown): string; - /** Reads the leaf part of this space's claim, answering none for an id that cannot narrow. */ - readLeaf?(value: unknown, id: string): ClaimLeaf | undefined; + /** + * Reads the leaf part this space's claim declares, refusing a declared leaf the id cannot narrow: + * answering no leaf would silently widen the claim to the whole id. Only the `platform` space + * declares a leaf, and only an `apple` id has one to name. + */ + readLeaf?(declaredLeaf: unknown, id: string): ClaimLeaf | undefined; /** Validates one contribution of this kind and answers its claim. */ readContribution(value: Record): PluggedClaim; /** Reads the name of a malformed contribution for failure reporting. */ @@ -292,9 +304,11 @@ function assertClaimAvailable(claim: PluggedClaim): void { } /** - * The claims a returned value already names, read through the same table without validating it. Only - * a slot that failed before its claims were readable uses this, so the inventory and the plugin that - * selected it can still say what it was meant to provide. + * The claims a returned value already names, read through the same table without validating the rest + * of it. Only a slot that failed before its claims were readable uses this, so the inventory and the + * plugin that selected it can still say what it was meant to provide. A leaf an id cannot narrow is + * refused here exactly as the validating readers refuse it: answering no leaf would widen the claim to + * the whole id, and a widened claim would deny that id to a package that really holds it. */ export function readableClaimsOfValue(value: unknown): readonly PluggedClaim[] { if (!isRecord(value)) return []; @@ -320,8 +334,8 @@ function namedContributionClaims(contributions: unknown, kind: ClaimKind): reado if (!isRecord(contribution) || contribution.kind !== kind) return []; const id = readNamedId(contribution[contributionIdField]); if (id === undefined) return []; - const leaf = leafField === undefined ? undefined : readNamedId(contribution[leafField]); - const appleOs = leaf === undefined ? undefined : readLeaf?.(leaf, id); + const declaredLeaf = leafField === undefined ? undefined : contribution[leafField]; + const appleOs = readLeaf?.(declaredLeaf, id); return [appleOs === undefined ? { kind, id } : { kind, id, appleOs }]; }); } From 7616bfd9082b0516085519e12f7899607e0d0f48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 22:52:25 +0100 Subject: [PATCH 13/15] docs(audio): state that host audio sampling needs the macOS plugin The ScreenCaptureKit sampler moved with the Swift helper, so a macOS session, iOS simulator, or Android emulator probe answers plugin-not-installed with no package installed. Say so in the audio help topic, the audio-probe and client API docs, and the capabilities generator, and pin the typed outcome with a host test. --- scripts/capability-matrix/annotations.ts | 2 +- scripts/capability-matrix/generate.ts | 2 +- .../schema/cli-help-workflows.test.ts | 4 ++++ src/commands/schema/cli-help-workflows.ts | 2 +- src/platform-runtime-audio-probe-host.test.ts | 22 +++++++++++++++++++ src/platform-runtime-macos-leaf.fixtures.ts | 9 ++++++++ website/docs/docs/capabilities.md | 4 ++-- website/docs/docs/client-api.md | 2 +- website/docs/docs/debugging-profiling.md | 2 +- 9 files changed, 42 insertions(+), 7 deletions(-) diff --git a/scripts/capability-matrix/annotations.ts b/scripts/capability-matrix/annotations.ts index 554899a3b7..46441a85ee 100644 --- a/scripts/capability-matrix/annotations.ts +++ b/scripts/capability-matrix/annotations.ts @@ -365,7 +365,7 @@ export const MATRIX_SECTIONS: readonly MatrixSection[] = [ commands: ['audio'], link: docs('debugging-profiling', 'audio-probes'), advertises: ['audioProbeStart', 'audioProbeReattach', 'audioProbeCleanup'], - note: 'A simulator, emulator, or macOS desktop session samples host system audio, which works on a macOS agent host and needs Screen Recording permission there.', + note: 'A simulator, emulator, or macOS desktop session samples host system audio, which works on a macOS agent host and needs Screen Recording permission there. The sampler is the `@agent-device/macos` plugin, so every one of those sessions needs the plugin installed.', cells: { 'web-browser': { text: 'Page media probe only; host capture unsupported', diff --git a/scripts/capability-matrix/generate.ts b/scripts/capability-matrix/generate.ts index e82c20a1aa..95fa5aa4fc 100644 --- a/scripts/capability-matrix/generate.ts +++ b/scripts/capability-matrix/generate.ts @@ -270,7 +270,7 @@ export function renderPage(data: MatrixData): string { '', 'Physical iOS devices discovered only through `xctrace` use the XCTest backend rather than CoreDevice: they support open/close, interactions, snapshots, and screenshots, while app inventory, installation, logs, performance sampling, recording, deep links, and launch arguments need CoreDevice.', '', - 'One capability depends on the agent machine rather than the target: system audio sampling works only when the daemon runs on macOS, which is what this page assumes.', + 'One capability depends on the agent machine rather than the target: system audio sampling works only when the daemon runs on macOS, which is what this page assumes, and it needs the `@agent-device/macos` plugin on that host — the sampler lives there — for a macOS, iOS simulator, or Android emulator session.', '', 'Check the device in front of you rather than trusting a table:', '', diff --git a/src/commands/schema/cli-help-workflows.test.ts b/src/commands/schema/cli-help-workflows.test.ts index 5359daa141..4ff294a20d 100644 --- a/src/commands/schema/cli-help-workflows.test.ts +++ b/src/commands/schema/cli-help-workflows.test.ts @@ -37,6 +37,10 @@ test('usageForCommand resolves debugging help topic', async () => { assert.match(help, /agent-device audio probe start 10 1000 --platform android/); assert.match(help, /compact rmsDbfs and peakDbfs arrays/); assert.match(help, /requires Screen Recording permission/); + assert.match( + help, + /The sampler is the macOS plugin's, so every one of those sessions needs it installed/, + ); assert.match(help, /Physical iOS and Android devices are not supported/); assert.match(help, /Memory artifact \(android-hprof\): \/tmp\/app\.hprof \(42MB\)/); assert.match(help, /Prefer perf memory sample over raw dumpsys\/leaks output/); diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index 7b8675d894..113d2c5276 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -107,7 +107,7 @@ Audio: agent-device audio probe start 10 1000 --platform android audio probe start uses duration seconds first, then bucket milliseconds. Results are compact rmsDbfs and peakDbfs arrays so agents can correlate audible moments with screenshots, actions, network entries, or frame samples. On web, audio probe samples HTML media elements and URL-backed media may be routed through the probe AudioContext while observed. - On macOS hosts, audio probe samples host system audio through ScreenCaptureKit for macOS sessions, iOS simulators, and Android emulators. It requires Screen Recording permission and is system-audio evidence, not app-instrumented audio. Physical iOS and Android devices are not supported. + On macOS hosts, audio probe samples host system audio through ScreenCaptureKit for macOS sessions, iOS simulators, and Android emulators. The sampler is the macOS plugin's, so every one of those sessions needs it installed: agent-device plugins add @agent-device/macos. It requires Screen Recording permission and is system-audio evidence, not app-instrumented audio. Physical iOS and Android devices are not supported. Crash symbolication: Crash routing: diff --git a/src/platform-runtime-audio-probe-host.test.ts b/src/platform-runtime-audio-probe-host.test.ts index c1a23c2d5c..7da547fe51 100644 --- a/src/platform-runtime-audio-probe-host.test.ts +++ b/src/platform-runtime-audio-probe-host.test.ts @@ -3,6 +3,7 @@ import { createTestHostEnvironment } from '@agent-device/test-kit'; import { emptyAudioProbeResult } from '@agent-device/contracts/audio-probe-result'; import type { AudioProbeQueryInput } from '@agent-device/contracts/audio-probe-runtime'; import { createAudioProbeRuntimeHost } from './platform-runtime-audio-probe-host.ts'; +import { bindAbsentMacOsLeafCompositionFixture } from './platform-runtime-macos-leaf.fixtures.ts'; import { makeWebProvider, webSelectionFixture } from './platform-runtime-web-provider.fixtures.ts'; const web = { @@ -16,6 +17,27 @@ const web = { const webPlugin = webSelectionFixture(); +test('an iOS or Android session without the macOS package answers plugin-not-installed when it samples host audio', async () => { + // The host sampler is the macOS helper's, so the leaf starts it for every darwin-hosted family + // (#4675). A composition that has no macOS package reports its install hint rather than a bare + // failure: the caller can fix this one by installing a plugin. + bindAbsentMacOsLeafCompositionFixture(); + const { hostCapture } = createAudioProbeRuntimeHost({ host: createTestHostEnvironment() }); + await expect( + hostCapture.start({ durationMs: 1_000, bucketMs: 100, statusPath: '/tmp/audio-status.json' }), + ).rejects.toMatchObject({ + code: 'UNSUPPORTED_PLATFORM', + details: expect.objectContaining({ + reason: 'plugin-not-installed', + family: 'apple', + appleOs: 'macos', + package: '@agent-device/macos', + installCommand: expect.stringContaining('agent-device plugins add @agent-device/macos'), + hint: expect.stringContaining('agent-device plugins add @agent-device/macos'), + }), + }); +}); + test('never falls back to the default browser session for a web audio probe', async () => { const { web: webAudio } = createAudioProbeRuntimeHost({ host: createTestHostEnvironment(), diff --git a/src/platform-runtime-macos-leaf.fixtures.ts b/src/platform-runtime-macos-leaf.fixtures.ts index cdac1005c1..8070791263 100644 --- a/src/platform-runtime-macos-leaf.fixtures.ts +++ b/src/platform-runtime-macos-leaf.fixtures.ts @@ -49,3 +49,12 @@ export function macOsPlatformCompositionFixture( bindPlatformLeaves(platforms); return platforms; } + +/** + * Binds the platform selection of a process with no macOS package installed, as the daemon's + * composition does. Every macOS branch of the bundled Apple owner then answers the typed + * `plugin-not-installed` outcome with the package's install command. + */ +export function bindAbsentMacOsLeafCompositionFixture(): void { + bindPlatformLeaves(composePlatformPlugins([], [], undefined, [])); +} diff --git a/website/docs/docs/capabilities.md b/website/docs/docs/capabilities.md index 6b36bce7c7..44f1d3b563 100644 --- a/website/docs/docs/capabilities.md +++ b/website/docs/docs/capabilities.md @@ -9,7 +9,7 @@ The target tables below are generated from the runtime command-admission facts t Physical iOS devices discovered only through `xctrace` use the XCTest backend rather than CoreDevice: they support open/close, interactions, snapshots, and screenshots, while app inventory, installation, logs, performance sampling, recording, deep links, and launch arguments need CoreDevice. -One capability depends on the agent machine rather than the target: system audio sampling works only when the daemon runs on macOS, which is what this page assumes. +One capability depends on the agent machine rather than the target: system audio sampling works only when the daemon runs on macOS, which is what this page assumes, and it needs the `@agent-device/macos` plugin on that host — the sampler lives there — for a macOS, iOS simulator, or Android emulator session. Check the device in front of you rather than trusting a table: @@ -241,7 +241,7 @@ What a **Yes** does not claim: - **Screen recording**: An iOS physical device records runner screenshots, not a native video stream: no audio, and dropped frames are expected. An Android clip covers 180 seconds, and a longer recording arrives as chunks. - **HTTP(S) request inspection**: Local native app sessions inspect the HTTP(S) entries present in the session app log; traffic absent from those logs is not captured. The three WebDriver provider clouds refuse a live dump: their traffic is on the provider side, and TestMu AI can return provider network-log artifacts after the session ends. Managed web sessions inspect the browser request history. -- **Audio probe**: A simulator, emulator, or macOS desktop session samples host system audio, which works on a macOS agent host and needs Screen Recording permission there. +- **Audio probe**: A simulator, emulator, or macOS desktop session samples host system audio, which works on a macOS agent host and needs Screen Recording permission there. The sampler is the `@agent-device/macos` plugin, so every one of those sessions needs the plugin installed. ## System and hardware diff --git a/website/docs/docs/client-api.md b/website/docs/docs/client-api.md index 6f2fd5e410..bd7458fce1 100644 --- a/website/docs/docs/client-api.md +++ b/website/docs/docs/client-api.md @@ -397,7 +397,7 @@ const audio = await client.observability.audio({ await client.observability.audio({ platform: 'web', action: 'probe', probeAction: 'stop' }); ``` -Pass `platform: 'web'`, `'macos'`, `'ios'` (simulators), or `'android'` (emulators on macOS hosts). See [Audio probes](/docs/debugging-profiling#audio-probes) for what each platform samples, permissions, and unsupported targets. +Pass `platform: 'web'`, `'macos'`, `'ios'` (simulators), or `'android'` (emulators on macOS hosts). Every host-capture platform needs the `@agent-device/macos` plugin on the daemon's host, because the sampler lives there. See [Audio probes](/docs/debugging-profiling#audio-probes) for what each platform samples, permissions, and unsupported targets. `client.observability.perf()` requires an options object with an explicit `area`; a call without one fails with an error that names the replacement. The option shapes mirror the `perf` CLI forms: diff --git a/website/docs/docs/debugging-profiling.md b/website/docs/docs/debugging-profiling.md index e6eeee62fd..7dcf8071db 100644 --- a/website/docs/docs/debugging-profiling.md +++ b/website/docs/docs/debugging-profiling.md @@ -247,7 +247,7 @@ agent-device audio probe start 10 1000 --platform android - `audio probe start [durationSeconds] [bucketMs]` samples live audio while the session keeps running and reports compact `rmsDbfs` and `peakDbfs` buckets. The first timing positional is seconds; the second is milliseconds. - On web, the probe samples HTML media elements through Web Audio. URL-backed media may be routed through the probe `AudioContext` while observed. -- On macOS hosts, the probe samples host system audio through ScreenCaptureKit for macOS sessions, iOS simulators, and Android emulators. It requires Screen Recording permission and is system-audio evidence, not app-instrumented audio. Physical iOS and Android devices are not supported. +- On macOS hosts, the probe samples host system audio through ScreenCaptureKit for macOS sessions, iOS simulators, and Android emulators. The sampler belongs to the `@agent-device/macos` plugin, so every one of those sessions needs it installed — see [Installation](/docs/installation#macos-desktop-notes). Without it, the probe answers `UNSUPPORTED_PLATFORM` with `error.details.reason: plugin-not-installed`, the package name, and the install command. It requires Screen Recording permission and is system-audio evidence, not app-instrumented audio. Physical iOS and Android devices are not supported. - Use `status` to poll partial buckets during a 10-20 second observation window, and `stop` to end the probe early. ### Performance snapshots From 6216a24dcdbf5afbbc58ea84c6a94a4648942717 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 23:06:03 +0100 Subject: [PATCH 14/15] docs(agents): keep the macOS device check line inside the guidance budget The plugin note took docs/agents past its 40 000-byte total. State the instruction once and leave the install command to the user docs that own it. --- docs/agents/device-verification.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/agents/device-verification.md b/docs/agents/device-verification.md index ac87cbe6ac..ce891f53d4 100644 --- a/docs/agents/device-verification.md +++ b/docs/agents/device-verification.md @@ -59,8 +59,7 @@ The first run needs XCUITest automation permission. When you change Apple targets, synchronize the kernel model, runtime-fact admission, dispatch, discovery, and xctestrun preparation. Simulator-set scoping must not hide the host macOS target. -macOS desktop automation is the managed `@agent-device/macos` plugin. -Before you run a macOS device check, install the packed plugin with `agent-device plugins add` into an isolated `AGENT_DEVICE_HOME`. +Before a macOS device check, install `@agent-device/macos`. HarmonyOS has no provisioned CI device or HDC. Mocked tests do not replace local hardware evidence. Before you run a live smoke harness, read its entry file under `test/integration/` for environment requirements. From a93826364895607c9cb8b15cec637acb95624538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 23:06:22 +0100 Subject: [PATCH 15/15] chore(release): publish @agent-device/macos and fit its device note in the docs budget --- packages/platform-macos/package.json | 1 - scripts/release-install-hints.ts | 11 ++++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/platform-macos/package.json b/packages/platform-macos/package.json index c0d0e42ee3..b5a5e6a64e 100644 --- a/packages/platform-macos/package.json +++ b/packages/platform-macos/package.json @@ -1,7 +1,6 @@ { "name": "@agent-device/macos", "version": "0.22.0-dev", - "private": true, "type": "module", "description": "Managed macOS desktop platform plugin for agent-device.", "exports": { diff --git a/scripts/release-install-hints.ts b/scripts/release-install-hints.ts index 4489bc0b60..424a3bc258 100644 --- a/scripts/release-install-hints.ts +++ b/scripts/release-install-hints.ts @@ -1,8 +1,9 @@ /** * Lists, one name per line, every plugin package the checked-out core tells a user to install. * - * Core names a plugin package in three catalogs: the optional platform families ADR 0034 makes - * installable, the provider plugin catalog `connect` points at, and the replay format declarations. + * Core names a plugin package in four places: the optional platform families ADR 0034 makes + * installable, the macOS leaf the Apple owner delegates to, the provider plugin catalog `connect` + * points at, and the replay format declarations. * Each row becomes an `agent-device plugins add ` line in the shipped help and errors, so * this reads the declarations those messages build from rather than a copy of them. * `scripts/release-workspace.mjs` compares the result with the packages it packs, so a hint naming a @@ -13,7 +14,10 @@ */ import { getReplayPluginInstallation, type ReplayFormat } from '@agent-device/ad-script'; import { OPTIONAL_PLATFORMS } from '@agent-device/contracts/platform-module'; -import { getOptionalPlatformPluginDeclaration } from '@agent-device/contracts/plugin-installation'; +import { + getOptionalPlatformPluginDeclaration, + MACOS_PLATFORM_PLUGIN_DECLARATION, +} from '@agent-device/contracts/plugin-installation'; import { providerPluginDeclarations } from '../src/commands/provider-plugin-catalog.ts'; // Totals `ReplayFormat`, so TypeScript refuses a new replay format without an installation row — @@ -32,6 +36,7 @@ function optionalPlatformPackages(): string[] { const hints = [ ...optionalPlatformPackages(), + MACOS_PLATFORM_PLUGIN_DECLARATION.package, ...providerPluginDeclarations().map((declaration) => declaration.package), ...(Object.keys(replayFormats) as ReplayFormat[]).map( (id) => getReplayPluginInstallation(id).package,