From a4bd04a4e10feab5b6525292a2a7b61c78db43ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:21:02 +0100 Subject: [PATCH 1/4] docs(linux): name what the Linux boundary answers for React Native helpers The Linux command boundary listed React Native helpers as unavailable. The command runs wherever tapping runs and answers `detected: false` on a surface with no overlay, which the React Native overlays section and the capability matrix already state. The section now says that instead, and drops the `host-launch-unavailable` refusal its host no longer makes. The package homepage anchored a heading the page no longer has. --- packages/platform-linux/package.json | 2 +- website/docs/docs/commands.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/platform-linux/package.json b/packages/platform-linux/package.json index 513a970d31..6745523aa8 100644 --- a/packages/platform-linux/package.json +++ b/packages/platform-linux/package.json @@ -49,5 +49,5 @@ "url": "git+https://github.com/callstack/agent-device.git", "directory": "packages/platform-linux" }, - "homepage": "https://agent-device.dev/docs/commands#linux-desktop-targets" + "homepage": "https://agent-device.dev/docs/commands#linux-command-boundary" } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 773746d225..24f802546f 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -626,9 +626,10 @@ HarmonyOS runs through the optional `@agent-device/harmonyos` plugin (`agent-dev Linux desktops run through the optional `@agent-device/linux` plugin (`agent-device plugins add @agent-device/linux`; see [Installation](/docs/installation#linux-prerequisites)). The Linux device is the machine the daemon runs on, so discovery answers one desktop on a Linux host. Input goes through `xdotool` on X11 and `ydotool` on Wayland; snapshots read the AT-SPI2 tree through a Python helper the plugin ships. Run `agent-device capabilities --platform linux` for the command list of a selected device. - Without the plugin, a command such as `devices` or `open` that names `--platform linux` answers `UNSUPPORTED_PLATFORM` with `error.details.reason: plugin-not-installed`, the package name, and the install command. Commands that name no platform, such as `devices` and a `doctor` call with no `--platform` and no session, skip Linux. A `doctor` call bound to a session takes the toolchain platform from that session's device. `doctor` does not fail: when its toolchain platform is Linux, it reports a failing toolchain row with `evidence.reason: plugin-not-installed`, the plugin name, and its install command. -- `open ` starts an executable from the daemon host's `PATH` detached, so the app outlives the command that opened it, and a host that cannot start a detached process refuses with `UNSUPPORTED_OPERATION` and `error.details.reason: host-launch-unavailable`. A name that is a path or URL, or one that is not an executable, goes to `xdg-open`. `close` closes the app's window through `wmctrl` when the session has it, and otherwise ends the process by name. +- `open ` starts an executable from the daemon host's `PATH` detached, so the app outlives the command that opened it. A name that is a path or URL, or one that is not an executable, goes to `xdg-open`. `close` closes the app's window through `wmctrl` when the session has it, and otherwise ends the process by name. - A missing desktop tool answers `TOOL_MISSING` and names the tool its display server needs: X11 uses `xdotool`, `xclip` or `xsel`, and `scrot`, `import`, or `gnome-screenshot`; Wayland uses `ydotool`, `wl-paste`, `wl-copy`, and `grim` or `gnome-screenshot`. -- Not available: screen recording, alerts, orientation, hover, multi-touch gestures, target-authored `gesture drag`, app logs, performance sampling, network and audio capture, trace capture, and React Native helpers. +- `react-native dismiss-overlay` runs, because it runs wherever tapping runs, and answers `detected: false`: a Linux desktop hosts no React Native development overlay. See [React Native overlays](#react-native-overlays). +- Not available: screen recording, alerts, orientation, hover, multi-touch gestures, target-authored `gesture drag`, app logs, performance sampling, network and audio capture, and trace capture. ## Diagnostics From 084a4c4543d2234fd9431d83fd7589a4c3c70a92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:21:12 +0100 Subject: [PATCH 2/4] refactor(plugins)!: give every plugin host its process facets and declare their exit once The plugin host the composition builds always provides the managed process service and the detached launcher, so `PlatformHost` makes both required and the families stop carrying refusal branches for a host facet they can never meet: Linux refused `open` with `host-launch-unavailable` and HarmonyOS refused to stream `hilog`. A host that cannot start a process is a composition bug, not an answer a plugin serves. How a detached process ended was declared three times: by the plugin contract, by the Linux provider contract, and by the host's own exec module, the last two drifting on `signal`. It is declared once in `@agent-device/contracts/platform-runtime-host`, which all three read. The published plugin declarations still inline it, so writing a plugin needs no Node type packages. A plugin that ships a helper beside its own code had no host probe for it: the executable probe is the wrong question for a non-executable resource, so `isFilePresent` is the right one, and the Linux family reads its AT-SPI helper through it rather than through its bundle's copy of the host kit. `which` now answers through the host's own PATH probe instead of walking `PATH` over the executable probe, so a probe and the spawn it authorizes read one host primitive. --- .../contracts/src/platform-runtime-host.ts | 20 ++++ packages/host-kit/src/host-file.ts | 1 + packages/host-kit/src/internal/exec.ts | 21 ++-- packages/host-kit/src/internal/host-file.ts | 10 ++ .../src/__tests__/hdc.test.ts | 12 -- .../platform-harmonyos/src/command-host.ts | 17 +-- packages/platform-harmonyos/src/index.test.ts | 10 ++ .../src/__tests__/command-runner.test.ts | 14 +-- packages/platform-linux/src/command-runner.ts | 103 ++++++------------ packages/platform-linux/src/index.test.ts | 46 ++++++-- .../platform-linux/src/toolbox.fixtures.ts | 27 +++-- packages/platform-vega/src/index.test.ts | 9 ++ .../src/index-startup-cleanup.test.ts | 9 ++ packages/plugins/src/platform.test.ts | 9 ++ packages/plugins/src/platform.ts | 40 +++---- src/platform-runtime/plugin-host.ts | 4 + 16 files changed, 201 insertions(+), 151 deletions(-) diff --git a/packages/contracts/src/platform-runtime-host.ts b/packages/contracts/src/platform-runtime-host.ts index 9ff69073a6..bec261e09f 100644 --- a/packages/contracts/src/platform-runtime-host.ts +++ b/packages/contracts/src/platform-runtime-host.ts @@ -65,6 +65,26 @@ export type HostCommandRunner = Readonly<{ run(request: HostCommandRequest, signal?: AbortSignal): Promise; }>; +/** + * How a process the host started detached ended: a start failure, a non-zero exit, or a signal. + * Declared once here rather than by its shape in each contract that reports one, because a host that + * starts a detached process, a family that launches through that host, and the host's own exec module + * all answer the same question. It names `signal` as a `string` rather than as Node's `Signals`, so a + * consumer that writes a plugin reads this declaration without Node's own type packages. + */ +export type DetachedCommandExit = Readonly<{ + pid: number; + exitCode?: number; + signal?: string; + error?: string; +}>; + +/** What the host answered a detached launch: the process it started and how that process ended. */ +export type DetachedCommandLaunch = Readonly<{ + pid: number; + exited: Promise; +}>; + export type AppleXcrunTool = 'simctl' | 'devicectl' | 'xctrace'; declare const scopedSimctlArgs: unique symbol; diff --git a/packages/host-kit/src/host-file.ts b/packages/host-kit/src/host-file.ts index b62bd3859f..ae38ce2096 100644 --- a/packages/host-kit/src/host-file.ts +++ b/packages/host-kit/src/host-file.ts @@ -6,6 +6,7 @@ export { copyHostPath, ensureHostDirectory, ensureHostDirectorySync, + hostFileExists, hostFileExistsSync, hostFileLstatSync, hostFileStat, diff --git a/packages/host-kit/src/internal/exec.ts b/packages/host-kit/src/internal/exec.ts index 9ae7ef941c..6cd3247ca9 100644 --- a/packages/host-kit/src/internal/exec.ts +++ b/packages/host-kit/src/internal/exec.ts @@ -18,6 +18,10 @@ import { } from './exec-trace.ts'; export { signalProcessGroupBestEffort } from './exec-trace.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; +import type { + DetachedCommandExit, + DetachedCommandLaunch, +} from '@agent-device/contracts/platform-runtime-host'; /** The `error.details.reason` values a failed command publishes beside its settlement. */ const EXEC_FAILURE_REASONS = { @@ -77,12 +81,12 @@ type ExecDetachedOptions = ExecOptions & { stdio?: StdioOptions; }; -export type ExecDetachedExit = { - pid: number; - exitCode?: number; - signal?: NodeJS.Signals; - error?: string; -}; +/** + * How a detached process ended. The shape is owned by `@agent-device/contracts/platform-runtime-host` + * so the host's exec module, the host a plugin is set up with, and the families that launch through + * it answer the same question; this is the host kit's own name for it. + */ +export type ExecDetachedExit = DetachedCommandExit; /** * The child's side of the Node IPC channel, present only when `stdio` includes `'ipc'`. It is @@ -93,9 +97,8 @@ export type ExecDetachedChannel = Readonly<{ onMessage(listener: (message: unknown) => void): void; }>; -export type ExecDetachedProcess = { - pid: number; - exited: Promise; +export type ExecDetachedProcess = DetachedCommandLaunch & { + /** Present only when `stdio` includes `'ipc'`: the child's own progress channel. */ channel?: ExecDetachedChannel; }; diff --git a/packages/host-kit/src/internal/host-file.ts b/packages/host-kit/src/internal/host-file.ts index a0e580d531..829049aaf0 100644 --- a/packages/host-kit/src/internal/host-file.ts +++ b/packages/host-kit/src/internal/host-file.ts @@ -123,6 +123,16 @@ export function hostFileExistsSync(filePath: string): boolean { return fs.existsSync(filePath); } +/** Whether the host has a file at `path`, whatever its permissions, without reading it. */ +export async function hostFileExists(filePath: string): Promise { + try { + await fsPromises.access(filePath, fs.constants.F_OK); + return true; + } catch { + return false; + } +} + export function hostFileStatSync(filePath: string): fs.Stats { return fs.statSync(filePath); } diff --git a/packages/platform-harmonyos/src/__tests__/hdc.test.ts b/packages/platform-harmonyos/src/__tests__/hdc.test.ts index a8e211b384..d387f74984 100644 --- a/packages/platform-harmonyos/src/__tests__/hdc.test.ts +++ b/packages/platform-harmonyos/src/__tests__/hdc.test.ts @@ -225,15 +225,3 @@ test('the command runner streams with the same toolchain environment it runs wit await stream.terminate(); assert.equal((await stream.wait).exitCode, 0); }); - -test('the command runner refuses to stream on a host with no managed process service', async () => { - const host = { ...createHarmonyHostStub().host, startBackgroundCommand: undefined }; - const commands = createHarmonyCommandRunner(host); - - await assert.rejects( - commands.start('hdc', ['shell', 'hilog'], { - output: { write: async () => {}, [Symbol.asyncDispose]: async () => {} }, - }), - (error: unknown) => asAppError(error).code === 'UNSUPPORTED_OPERATION', - ); -}); diff --git a/packages/platform-harmonyos/src/command-host.ts b/packages/platform-harmonyos/src/command-host.ts index 53a8650061..d252dd9a89 100644 --- a/packages/platform-harmonyos/src/command-host.ts +++ b/packages/platform-harmonyos/src/command-host.ts @@ -1,5 +1,4 @@ import path from 'node:path'; -import { AppError } from '@agent-device/kernel/errors'; import type { PlatformBackgroundProcess, PlatformHost, @@ -81,14 +80,8 @@ export function createHarmonyCommandRunner(host: PlatformHost): HarmonyCommandRu ...options, env: await spawnEnvironment(), }), - start: async (executable, args, options) => { - const startManaged = host.startBackgroundCommand; - if (!startManaged) { - throw new AppError('UNSUPPORTED_OPERATION', NO_MANAGED_PROCESS_MESSAGE, { - hint: 'Run logs start against a daemon, which owns the managed app-log process service.', - }); - } - return await startManaged( + start: async (executable, args, options) => + await host.startBackgroundCommand( { command: { executable, @@ -100,16 +93,12 @@ export function createHarmonyCommandRunner(host: PlatformHost): HarmonyCommandRu ...(options.markerPath === undefined ? {} : { markerPath: options.markerPath }), }, options.signal, - ); - }, + ), resolveHdc: async () => (await harmonyToolchainHdc(env, isExecutable)) ?? 'hdc', toolchainHdc: async () => await harmonyToolchainHdc(env, isExecutable), }); } -const NO_MANAGED_PROCESS_MESSAGE = - 'The selected host cannot keep a HarmonyOS command running, so it cannot stream hilog.'; - /** * DevEco's command-line tools do not amend `PATH` for non-interactive processes. Honoring the * documented roots here means the daemon spawns the HDC an interactive shell resolves, without the diff --git a/packages/platform-harmonyos/src/index.test.ts b/packages/platform-harmonyos/src/index.test.ts index 081658b8dc..907084dd06 100644 --- a/packages/platform-harmonyos/src/index.test.ts +++ b/packages/platform-harmonyos/src/index.test.ts @@ -5,6 +5,7 @@ import type { HarmonyPlatformRegistration } from '@agent-device/contracts/platfo import type { PlatformHost } from 'agent-device/plugins'; import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; import { isExecutablePath, whichCmd } from '@agent-device/host-kit/command'; +import { hostFileExists } from '@agent-device/host-kit/host-file'; import path from 'node:path'; import harmonyPlatformPlugin from './index.ts'; import { createHarmonyToolchainRoot } from './toolbox.fixtures.ts'; @@ -48,6 +49,7 @@ function createPluginHost( // The host probe the real one is: a test that names a toolchain root proves the plugin resolves // HDC from a file on disk, not from a verdict this fixture hands it. isFileExecutable: isExecutablePath, + isFilePresent: hostFileExists, isExecutableOnPath: async (executable) => await whichCmd(executable, env), // Neither this family nor its devices are host processes: everything goes through HDC. processes: { @@ -64,6 +66,14 @@ function createPluginHost( throw new Error('the HarmonyOS family takes no host lock'); }, } satisfies PlatformHost['processes'], + // This host is asked for neither: the tests that stream `hilog` use the toolbox stub, which + // records the managed process the family starts, and nothing starts a detached process. + startBackgroundCommand: async () => { + throw new Error('this host is not asked to keep a command running'); + }, + launchDetached: async () => { + throw new Error('the HarmonyOS family starts no detached process'); + }, emitDiagnostic, withDiagnosticTimer, }; diff --git a/packages/platform-linux/src/__tests__/command-runner.test.ts b/packages/platform-linux/src/__tests__/command-runner.test.ts index 58382a3277..ea2a46b70e 100644 --- a/packages/platform-linux/src/__tests__/command-runner.test.ts +++ b/packages/platform-linux/src/__tests__/command-runner.test.ts @@ -2,15 +2,15 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import { createLinuxHostStub } from '../toolbox.fixtures.ts'; -test('which looks up only bare names in the host PATH', async () => { - const stub = createLinuxHostStub({ env: { PATH: '/usr/bin' }, tools: ['xdotool', 'evil'] }); +test('which asks the host and passes its answer through', async () => { + // The lookup rules belong to the host: it searches its own `PATH` for a bare name and asks an + // absolute name of the filesystem (host-kit's `whichCmd` covers those branches). What this family + // owns is asking the host rather than searching `PATH` itself, so a probe and the spawn it + // authorizes read one environment. + const stub = createLinuxHostStub({ env: { PATH: '/usr/bin' }, tools: ['xdotool'] }); const { which } = stub.toolbox.commands; assert.equal(await which('xdotool'), true); assert.equal(await which('/usr/bin/xdotool'), true); - // A relative path would be joined onto each PATH entry and resolve outside it. - assert.equal(await which('../../tmp/evil'), false); - assert.equal(await which('tmp/evil'), false); - assert.equal(await which('evil\0'), false); - assert.equal(await which(' '), false); + assert.equal(await which('wmctrl'), false); }); diff --git a/packages/platform-linux/src/command-runner.ts b/packages/platform-linux/src/command-runner.ts index b87246a3df..0670c47d52 100644 --- a/packages/platform-linux/src/command-runner.ts +++ b/packages/platform-linux/src/command-runner.ts @@ -1,24 +1,25 @@ -import path from 'node:path'; import type { PlatformHost } from 'agent-device/plugins'; -import { AppError, normalizeError } from '@agent-device/kernel/errors'; +import { normalizeError } from '@agent-device/kernel/errors'; import { setTimeout as sleep } from 'node:timers/promises'; -import type { HostOperatingSystem } from '@agent-device/contracts/platform-runtime-host'; +import type { + DetachedCommandExit, + HostOperatingSystem, +} from '@agent-device/contracts/platform-runtime-host'; import type { LinuxCommandOptions, LinuxCommandResult, - LinuxDetachedExit, } from '@agent-device/contracts/linux-tool-provider'; /** * The plugin's route to host commands, bound to the `PlatformHost` the core handed `setup()`. The - * core owns the spawn environment, the exec trace and the filesystem probe, so a `--debug` log shows - * what this family ran under its request id, and a tool the host cannot execute answers the same way - * for an availability probe as for the spawn that probe authorized. + * core owns the spawn environment, the exec trace and every host probe, so a `--debug` log shows what + * this family ran under its request id, and a tool the host cannot execute answers the same way for + * the availability probe as for the spawn that probe authorized. * - * Every spawn and every availability check goes through that host rather than this bundle's own copy - * of the host kit: the daemon's command scope never enters the bundled copy, so a spawn made from it - * would run with the daemon process environment instead of the host environment captured for the - * request, and would drop the family's traces. + * Every spawn, availability check and file probe goes through that host rather than this bundle's own + * copy of the host kit: the daemon's command scope never enters the bundled copy, so a spawn made + * from it would run with the daemon process environment instead of the host environment captured for + * the request, and would drop the family's traces. */ export type LinuxCommandRunner = Readonly<{ run( @@ -28,8 +29,16 @@ export type LinuxCommandRunner = Readonly<{ ): Promise; /** The operating system of the host the family was set up with. */ hostOs: HostOperatingSystem; - /** True when the host resolves `cmd` on its `PATH`, or when `cmd` names an executable path. */ + /** + * True when the host can execute `cmd`: it looks a bare name up in the host `PATH` and asks an + * absolute path of the host filesystem. One host primitive answers both shapes. + */ which(cmd: string): Promise; + /** + * True when the host has `path` at all, executable or not. The family asks this of the helper it + * ships beside its own code: the file is not a host tool, so its absence names a broken install. + */ + isFilePresent(path: string): Promise; /** * Starts `cmd` detached with its output discarded and answers how it ended. A desktop app outlives * the command that opened it, so nothing awaits this beyond its exit report. @@ -37,7 +46,7 @@ export type LinuxCommandRunner = Readonly<{ launchDetached( cmd: string, args: readonly string[], - ): Readonly<{ exited: Promise }>; + ): Readonly<{ exited: Promise }>; /** Records one family diagnostic in the request's diagnostic store. */ diagnose( event: Readonly<{ @@ -50,67 +59,25 @@ export type LinuxCommandRunner = Readonly<{ sleep(milliseconds: number): Promise; }>; -/** Why the family refuses instead of opening an app: the host it was set up with cannot start a - * process that outlives the request. Published on the wire, so it is named here, not at the call. */ -const LINUX_LAUNCH_REFUSAL_REASONS = { - hostLaunchUnavailable: 'host-launch-unavailable', -} as const satisfies Record; - -const BARE_COMMAND_NAME = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/; - export function createLinuxCommandRunner(host: PlatformHost): LinuxCommandRunner { const env = host.env; return Object.freeze({ run: async (cmd, args, options) => await host.runCommand(cmd, [...args], { ...options, env }), hostOs: host.hostOs, - which: async (cmd) => await hostResolvesExecutable(host, env, cmd), - launchDetached: (cmd, args) => { - // A host that cannot start a process outliving the request cannot open a desktop app: waiting - // on a spawned binary would hold the request open for the app's whole life, so the family - // refuses on the spot rather than approximating it with a blocking spawn. - if (!host.launchDetached) { - throw new AppError('UNSUPPORTED_OPERATION', `Cannot start ${cmd} on this host.`, { - reason: LINUX_LAUNCH_REFUSAL_REASONS.hostLaunchUnavailable, - command: cmd, - }); - } - return { - exited: host - .launchDetached(cmd, [...args], { env }) - .then((launched) => launched.exited) - .catch((error: unknown) => ({ pid: 0, error: normalizeError(error).message })), - }; - }, + // One host primitive answers both shapes: `whichCmd` behind it asks an absolute path of the + // filesystem and looks a bare name up in the host `PATH`, so a probe and the spawn it authorizes + // read one environment and one authority (ADR 0019). + which: async (cmd) => await host.isExecutableOnPath(cmd), + isFilePresent: async (path) => await host.isFilePresent(path), + launchDetached: (cmd, args) => ({ + // The host owns the detached spawn, so the exit it reports arrives through the request's own + // exec trace. A spawn that could not start rejects; that is an exit with `error`. + exited: host + .launchDetached(cmd, [...args], { env }) + .then((launched) => launched.exited) + .catch((error: unknown) => ({ pid: 0, error: normalizeError(error).message })), + }), diagnose: (event) => host.emitDiagnostic(event), sleep: async (milliseconds) => await sleep(milliseconds), }); } - -/** - * Whether the host can execute `cmd`. An absolute name is asked of the host directly; a bare name is - * looked up in the host `PATH` entries through the same host authority, so a probe and a spawn cannot - * disagree about a tool, and neither reads the filesystem on its own (ADR 0019). - */ -async function hostResolvesExecutable( - host: PlatformHost, - env: Readonly>, - cmd: string, -): Promise { - const candidate = cmd.trim(); - if (!candidate || candidate.includes('\0')) return false; - if (candidate.startsWith('/')) return await host.isFileExecutable(candidate); - // A bare name only: a relative path such as `../../tmp/tool` would resolve outside every PATH entry. - if (!BARE_COMMAND_NAME.test(candidate)) return false; - const directories = (env.PATH ?? '') - .split(path.delimiter) - .map((entry) => entry.trim()) - .filter(Boolean); - for (const directory of directories) { - if (await host.isFileExecutable(joinHostPath(directory, candidate))) return true; - } - return false; -} - -function joinHostPath(directory: string, file: string): string { - return path.join(directory, file); -} diff --git a/packages/platform-linux/src/index.test.ts b/packages/platform-linux/src/index.test.ts index f3ef830749..ac073960de 100644 --- a/packages/platform-linux/src/index.test.ts +++ b/packages/platform-linux/src/index.test.ts @@ -36,7 +36,13 @@ function createPluginHost( nodeVersion: 'v24.0.0', temporaryDirectory: '/tmp', processId: 4242, - isExecutableOnPath: async (executable) => (tools === undefined ? false : tools.has(executable)), + // The host's PATH probe: the tool list stands in for what the host resolves, so a test names the + // desktop tools rather than writing executables. + isExecutableOnPath: async (executable) => + tools === undefined ? false : tools.has(executable.split('/').pop() ?? executable), + // Only the AT-SPI helper this package ships is asked of this probe; the install carries it unless + // a test names a broken one. + isFilePresent: async () => true, // The family tracks no host process records: `close` ends an app through the desktop tools. processes: { list: async () => [], @@ -62,6 +68,10 @@ function createPluginHost( input.launches?.push({ executable, args }); return { pid: 4242, exited: Promise.resolve({ pid: 4242, exitCode: 0 }) }; }, + // This family streams no command: `close` ends an app through the desktop tools. + startBackgroundCommand: async () => { + throw new Error('the Linux family streams no host process'); + }, emitDiagnostic: () => {}, withDiagnosticTimer: async (_phase, operation) => await operation(), }; @@ -158,9 +168,9 @@ test('the toolchain check probes the host the plugin was set up with', async () const probed: string[] = []; const registration = setupLinuxPlatform({ ...host, - isFileExecutable: async (candidate) => { - probed.push(candidate); - return await host.isFileExecutable(candidate); + isExecutableOnPath: async (executable) => { + probed.push(executable); + return await host.isExecutableOnPath(executable); }, }); @@ -168,11 +178,9 @@ test('the toolchain check probes the host the plugin was set up with', async () assert.equal(check.id, 'toolchain'); assert.equal(check.status, 'pass'); - // The probe is the host's, over the host PATH, for the tools the X11 session needs. - assert.deepEqual( - probed, - tools.map((tool) => `/opt/tools/${tool}`), - ); + // The probe is the host's PATH probe, asked for the tools the X11 session needs. The host searches + // its own `PATH` for each name, so the family names a tool and never assembles a path of its own. + assert.deepEqual(probed, tools); }); test('the toolchain check reports the tools the host is missing', async () => { @@ -286,6 +294,26 @@ test('a request-scoped provider answers the interactor instead of the setup host openTarget: async () => {}, closeApp: async () => {}, }, + // The parts this request never reaches: reading one would mean the tap went somewhere the test + // did not script, so the assertion is the throw. + clipboard: { + readText: async () => { + throw new Error('this request reads no clipboard'); + }, + writeText: async () => { + throw new Error('this request writes no clipboard'); + }, + }, + screenshot: { + capture: async () => { + throw new Error('this request captures no screenshot'); + }, + }, + accessibility: { + captureTree: async () => { + throw new Error('this request captures no tree'); + }, + }, }; const interactor = await registration.createInteractor( { diff --git a/packages/platform-linux/src/toolbox.fixtures.ts b/packages/platform-linux/src/toolbox.fixtures.ts index 24c0dfe532..7f26d51b39 100644 --- a/packages/platform-linux/src/toolbox.fixtures.ts +++ b/packages/platform-linux/src/toolbox.fixtures.ts @@ -3,10 +3,8 @@ import path from 'node:path'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { PlatformHost } from 'agent-device/plugins'; -import type { - LinuxCommandResult, - LinuxDetachedExit, -} from '@agent-device/contracts/linux-tool-provider'; +import type { DetachedCommandExit } from '@agent-device/contracts/platform-runtime-host'; +import type { LinuxCommandResult } from '@agent-device/contracts/linux-tool-provider'; import { createLinuxToolbox, type LinuxToolbox } from './toolbox.ts'; /** One command this stubbed host was asked to run, plus the environment it was handed. */ @@ -39,7 +37,7 @@ export type LinuxHostStub = Readonly<{ /** Queues one answer for the next command; exit code 0 is the common case. */ answer(answer?: Partial & Readonly<{ stdout?: string }>): void; /** Queues one exit for the next detached launch. */ - answerLaunch(exit: LinuxDetachedExit): void; + answerLaunch(exit: DetachedCommandExit): void; }>; /** One family diagnostic the plugin recorded through the host. */ @@ -68,6 +66,8 @@ export function createLinuxHostStub( hostOs?: 'darwin' | 'linux' | 'win32' | 'other'; /** Tools the host can execute. When set, `isFileExecutable` answers from it alone. */ tools?: Iterable; + /** Whether the host sees the helper this package ships. True unless a test names a broken install. */ + shippedHelperPresent?: boolean; /** Answers one command. Takes precedence over the queued answers. */ respond?: ( executable: string, @@ -76,7 +76,7 @@ export function createLinuxHostStub( /** Rejected one command, the way the host rejects a spawn it cannot start. */ reject?: (executable: string, args: readonly string[]) => Error; /** Answers a detached launch. Takes precedence over the queued exits. */ - launchExit?: (executable: string, args: readonly string[]) => LinuxDetachedExit; + launchExit?: (executable: string, args: readonly string[]) => DetachedCommandExit; }> = {}, ): LinuxHostStub { const env = input.env ?? { PATH: '/usr/bin' }; @@ -84,7 +84,7 @@ export function createLinuxHostStub( const commands: LinuxHostStubCommand[] = []; const launches: LinuxHostStubLaunch[] = []; const answers: LinuxCommandResult[] = []; - const launchExits: LinuxDetachedExit[] = []; + const launchExits: DetachedCommandExit[] = []; const diagnostics: LinuxHostDiagnostic[] = []; function recordCommand( executable: string, @@ -122,10 +122,19 @@ export function createLinuxHostStub( }, withDiagnosticTimer: async (_phase: string, operation: () => Promise) => await operation(), - // The availability probe the plugin is allowed to make: the tool list stands in for the host's - // `PATH`, so a test states which desktop tools exist rather than writing executables. + // The availability probes the plugin is allowed to make: the tool list stands in for the host's + // `PATH`, so a test states which desktop tools exist rather than writing executables. The plain-file + // probe answers separately: the helper the family ships beside its own code is there unless a test + // names a broken install. isFileExecutable: async (candidate: string) => tools === undefined ? false : tools.has(path.basename(candidate)), + isFilePresent: async () => input.shippedHelperPresent ?? true, + // The availability probe the real host answers: an absolute name is asked of the filesystem, a + // bare name is looked up in the tool list that stands in for the host `PATH`. + isExecutableOnPath: async (executable: string) => + executable.startsWith('/') + ? tools !== undefined && tools.has(path.basename(executable)) + : tools !== undefined && tools.has(executable), runCommand: async ( executable: string, args: string[], diff --git a/packages/platform-vega/src/index.test.ts b/packages/platform-vega/src/index.test.ts index 83d77c6d23..47f9ebf9ac 100644 --- a/packages/platform-vega/src/index.test.ts +++ b/packages/platform-vega/src/index.test.ts @@ -5,6 +5,7 @@ import type { VegaPlatformRegistration } from '@agent-device/contracts/platform- import type { PlatformHost } from 'agent-device/plugins'; import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; import { isExecutablePath } from '@agent-device/host-kit/command'; +import { hostFileExists } from '@agent-device/host-kit/host-file'; import vegaPlatformPlugin from './index.ts'; import { createVegaDefaultInstall, createVegaHostHome } from './command-host.fixtures.ts'; @@ -54,6 +55,7 @@ function createPluginHost( // The real host probe: a test that names a home proves the plugin resolves the CLI from a file // on disk, not from a verdict this fixture hands it. isFileExecutable: isExecutablePath, + isFilePresent: hostFileExists, isExecutableOnPath: async (executable) => onPath.has(executable), // Neither this family nor its devices are host processes: everything goes through the Vega CLI. processes: { @@ -70,6 +72,13 @@ function createPluginHost( throw new Error('the Vega family takes no host lock'); }, } satisfies PlatformHost['processes'], + // This family is asked for neither: the Vega CLI owns its devices, and nothing streams. + startBackgroundCommand: async () => { + throw new Error('the Vega family streams no host process'); + }, + launchDetached: async () => { + throw new Error('the Vega family starts no detached process'); + }, emitDiagnostic, withDiagnosticTimer, }; diff --git a/packages/platform-web/src/index-startup-cleanup.test.ts b/packages/platform-web/src/index-startup-cleanup.test.ts index 19bbf12849..42fc1e2bf1 100644 --- a/packages/platform-web/src/index-startup-cleanup.test.ts +++ b/packages/platform-web/src/index-startup-cleanup.test.ts @@ -21,6 +21,7 @@ import webPlatformPlugin from './index.ts'; import type { PlatformHost } from 'agent-device/plugins'; import { emitDiagnostic, withDiagnosticTimer } from '@agent-device/host-kit/diagnostics'; import { runCmd, isExecutablePath, whichCmd } from '@agent-device/host-kit/command'; +import { hostFileExists } from '@agent-device/host-kit/host-file'; function cleanupWebBrowserOrphansForDaemonStartup(stateDir: string) { const host = { @@ -29,6 +30,7 @@ function cleanupWebBrowserOrphansForDaemonStartup(stateDir: string) { stateDir, runCommand: runCmd, isFileExecutable: isExecutablePath, + isFilePresent: hostFileExists, isExecutableOnPath: async (executable: string) => await whichCmd(executable, process.env), // The reaper and the record probe are the only host process reads this family makes, and both are // stood in for below, so the port itself has nothing to answer. @@ -46,6 +48,13 @@ function cleanupWebBrowserOrphansForDaemonStartup(stateDir: string) { throw new Error('this suite stands the install lock in for'); }, } satisfies PlatformHost['processes'], + // This suite runs the startup cleanup only: it neither streams a command nor starts a detached one. + startBackgroundCommand: async () => { + throw new Error('startup cleanup starts no host process'); + }, + launchDetached: async () => { + throw new Error('startup cleanup starts no detached process'); + }, emitDiagnostic, withDiagnosticTimer, }; diff --git a/packages/plugins/src/platform.test.ts b/packages/plugins/src/platform.test.ts index 9473c7f671..bf129abea1 100644 --- a/packages/plugins/src/platform.test.ts +++ b/packages/plugins/src/platform.test.ts @@ -64,6 +64,7 @@ async function startStore(env: HostEnvironment['env'], builtins: readonly Plugin throw new Error('setup must not start a process'); }, isFileExecutable: async () => false, + isFilePresent: async () => false, isExecutableOnPath: async () => false, processes: { list: async () => [], @@ -78,6 +79,14 @@ async function startStore(env: HostEnvironment['env'], builtins: readonly Plugin }, emitDiagnostic: () => {}, withDiagnosticTimer: async (_phase, run) => await run(), + // The managed process service and the detached launcher are part of every plugin host. No + // family this test serves uses either: the web plugin under test only names its state dir. + startBackgroundCommand: async () => { + throw new Error('setup must not keep a command running'); + }, + launchDetached: async () => { + throw new Error('setup must not launch a detached process'); + }, }, adaptWebDriver: async () => { throw new Error('unexpected WebDriver'); diff --git a/packages/plugins/src/platform.ts b/packages/plugins/src/platform.ts index f34a3c14a4..3f51507e61 100644 --- a/packages/plugins/src/platform.ts +++ b/packages/plugins/src/platform.ts @@ -15,6 +15,7 @@ import type { PlatformRuntimeModule } from '@agent-device/contracts/platform-run import type { LinuxToolProvider } from '@agent-device/contracts/linux-tool-provider'; import type { MacOsPlatformLeafRegistration } from '@agent-device/contracts/macos-platform-leaf'; import type { + DetachedCommandLaunch, HostOperatingSystem, OwnedProcessRecord, RecordedProcessLiveness, @@ -61,23 +62,11 @@ export type PlatformBackgroundProcess = AsyncDisposable & }>; /** - * How a process the host started detached ended: a start failure, a non-zero exit, or a signal. - * Declared by its shape rather than taken from the host's exec module, because this contract ships in - * the published bundle's declarations and a consumer that writes a plugin must not need Node's own - * type packages to read it. + * How a detached process ended, and what that launch answered: both are declared once in + * `@agent-device/contracts/platform-runtime-host`, which the host's own exec module and the Linux + * family read from too, so the surfaces that answer that one question cannot drift. The published + * plugin declarations inline them, so a plugin author reads the shape without Node's type packages. */ -export type DetachedCommandExit = Readonly<{ - pid: number; - exitCode?: number; - signal?: string; - error?: string; -}>; - -/** What the host answered a detached launch: the process it started and how that process ended. */ -export type DetachedCommandLaunch = Readonly<{ - pid: number; - exited: Promise; -}>; /** Authority shared by web setup and daemon-owned web sessions. */ export type PlatformHost = HostEnvironment & @@ -102,6 +91,14 @@ export type PlatformHost = HostEnvironment & * the probe uses the same host authority as the spawn it authorizes. */ isFileExecutable(path: string): Promise; + /** + * True when the host has a file at `path`, whatever its permissions. A plugin that ships a + * resource beside its own code asks the host whether the installed package carries it rather than + * reading the filesystem itself, so the probe is answered by the same authority as the spawn that + * resource is about to feed. A shipped helper is not executable: its absence names a broken + * install, not a missing tool, so this is the probe for it and {@link isFileExecutable} is not. + */ + isFilePresent(path: string): Promise; /** * Whether the host resolves `executable` on its `PATH`, answered against the host environment * the plugin was set up with. A plugin that prefers a tool from `PATH` asks this rather than @@ -139,10 +136,9 @@ export type PlatformHost = HostEnvironment & * Starts one streamed command as a managed process: the host publishes an ownership marker at * `markerPath` while the process lives, clears it when the process ends, and stops the process on * `terminate()`. A plugin streams through this rather than spawning a process of its own, so a - * streamed log is the same kind of durable resource the core recovers and cleans up. Absent when - * the process composing this host owns no session artifacts to confine a marker to. + * streamed log is the same kind of durable resource the core recovers and cleans up. */ - startBackgroundCommand?( + startBackgroundCommand( request: Readonly<{ command: PlatformBackgroundCommand; output: PlatformOutputSink; @@ -154,11 +150,9 @@ export type PlatformHost = HostEnvironment & * Starts `executable` detached, with its output discarded, and answers how it ended. A target * that outlives the call that started it — a desktop app, a display-server helper — must not * hold the request open for its whole life, so the host starts it, unrefs it, and reports its - * exit through `exited` instead of awaiting it. Absent where the host cannot start a process - * that outlives the request; a family that needs it says so rather than waiting on a spawn it - * never got. + * exit through `exited` instead of awaiting it. */ - launchDetached?( + launchDetached( executable: string, args: string[], options: { env?: HostEnvironment['env'] }, diff --git a/src/platform-runtime/plugin-host.ts b/src/platform-runtime/plugin-host.ts index 355cc501ce..79ba36997e 100644 --- a/src/platform-runtime/plugin-host.ts +++ b/src/platform-runtime/plugin-host.ts @@ -59,6 +59,10 @@ export function createPlatformPluginHost( const { isExecutablePath } = await import('@agent-device/host-kit/command'); return await isExecutablePath(path); }, + isFilePresent: async (path) => { + const { hostFileExists } = await import('@agent-device/host-kit/host-file'); + return await hostFileExists(path); + }, isExecutableOnPath: async (executable) => { const { whichCmd } = await import('@agent-device/host-kit/command'); return await whichCmd(executable, host.env); From e8a0af42721785a133d9f280f6156d474dd1cac4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:21:12 +0100 Subject: [PATCH 3/4] refactor(linux): make the provider parts a request reads mandatory The Linux interactor reads the capture, clipboard and screenshot parts on a plain request, so optional ones only moved the failure from a caller's type error to a `TypeError` at the family's `!` dereference. Each part the interactor reads is now required, and `input` stays optional because the family's own synthesis answers for it. The runtime resolved the request's provider and passed it to the surface capture, which resolved the same question again. The binding resolves it once and the capture takes the answer. --- packages/contracts/src/linux-tool-provider.ts | 21 ++++------ .../src/__tests__/atspi-bridge.test.ts | 28 +++++++++++--- .../src/__tests__/tool-provider.test.ts | 2 +- packages/platform-linux/src/atspi-bridge.ts | 17 ++++++++- packages/platform-linux/src/atspi-script.ts | 38 ++++++++----------- packages/platform-linux/src/clipboard.ts | 4 +- packages/platform-linux/src/runtime.ts | 10 +++-- packages/platform-linux/src/screenshot.ts | 2 +- packages/platform-linux/src/snapshot.ts | 2 +- .../platform-linux/src/surface-snapshot.ts | 8 ++-- packages/platform-linux/src/tool-provider.ts | 1 + 11 files changed, 79 insertions(+), 54 deletions(-) diff --git a/packages/contracts/src/linux-tool-provider.ts b/packages/contracts/src/linux-tool-provider.ts index fb5615fdf5..e39cdbec80 100644 --- a/packages/contracts/src/linux-tool-provider.ts +++ b/packages/contracts/src/linux-tool-provider.ts @@ -9,6 +9,7 @@ */ import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; +import type { DetachedCommandExit } from './platform-runtime-host.ts'; import type { ClickButton } from './click-button.ts'; import type { ScrollDirection } from './scroll-gesture.ts'; import type { SessionSurface } from './session-surface.ts'; @@ -39,19 +40,13 @@ export type LinuxCommandOptions = Readonly<{ stdin?: string; }>; -/** Why a process that outlived its launch ended: a start failure, a non-zero exit, or a signal. */ -export type LinuxDetachedExit = Readonly<{ - pid: number; - exitCode?: number; - signal?: string; - error?: string; -}>; - /** * The desktop-provider parts one request may supply. Each part answers one semantic intent of the * Linux interactor, so a caller that owns a surface — a scripted desktop, a display server it * drives directly — substitutes it for the family's own tool route without reimplementing the - * interactor. The command primitives stay mandatory: every Linux tool call goes through them. + * interactor. Only `input` is optional, and only because the family's own synthesis is a fallback for + * it. Every other part is mandatory: the interactor reads each one on a plain Linux request, so a + * caller that omits one is a type error rather than a `TypeError` at the first dereference. */ export type LinuxToolProvider = Readonly<{ /** The display decision every local tool selection in this provider shares (#3794). */ @@ -69,13 +64,13 @@ export type LinuxToolProvider = Readonly<{ launchDetached( cmd: string, args: readonly string[], - ): Readonly<{ exited: Promise }>; + ): Readonly<{ exited: Promise }>; /** Waits for interaction pacing between synthesized input steps. */ sleep(milliseconds: number): Promise; desktop: LinuxDesktopProvider; - clipboard?: LinuxClipboardProvider; - screenshot?: LinuxScreenshotProvider; - accessibility?: LinuxAccessibilityProvider; + clipboard: LinuxClipboardProvider; + screenshot: LinuxScreenshotProvider; + accessibility: LinuxAccessibilityProvider; input?: LinuxInputProvider; }>; diff --git a/packages/platform-linux/src/__tests__/atspi-bridge.test.ts b/packages/platform-linux/src/__tests__/atspi-bridge.test.ts index f347cb28b7..5e8349a8df 100644 --- a/packages/platform-linux/src/__tests__/atspi-bridge.test.ts +++ b/packages/platform-linux/src/__tests__/atspi-bridge.test.ts @@ -3,7 +3,6 @@ import assert from 'node:assert/strict'; import path from 'node:path'; import { createLinuxHostStub, type LinuxHostStub } from '../toolbox.fixtures.ts'; import { createLinuxToolProvider } from '../tool-provider.ts'; -import { resolveLinuxAtspiScriptPath } from '../atspi-script.ts'; import { AppError } from '@agent-device/kernel/errors'; /** The AT-SPI2 capture route, answering through the host the plugin was set up with. */ @@ -13,7 +12,7 @@ function captureAtspi( options: { maxNodes?: number; maxDepth?: number; maxApps?: number; signal?: AbortSignal } = {}, ) { const provider = createLinuxToolProvider(stub.toolbox); - return provider.accessibility!.captureTree(surface, options); + return provider.accessibility.captureTree(surface, options); } function stubPython( @@ -55,10 +54,27 @@ test('the AT-SPI capture runs the helper shipped with the plugin', async () => { const command = stub.commands[0]!; assert.equal(command.executable, 'python3'); - assert.equal(command.args[0], resolveLinuxAtspiScriptPath()); - // The helper has to ship inside the installed package, not resolve against a repository layout. - assert.equal(path.basename(command.args[0]!), 'atspi-dump.py'); - assert.equal(path.dirname(command.args[0]!).endsWith('linux'), true); + // The helper is resolved beside the code that runs it, not against a repository layout: the + // installed package carries it under `linux`. + assert.equal( + command.args[0], + path.resolve(import.meta.dirname, '../..', 'linux', 'atspi-dump.py'), + ); +}); + +test('the AT-SPI capture names a broken install when the host cannot see the shipped helper', async () => { + const stub = createLinuxHostStub({ + env: { PATH: '/usr/bin', XDG_SESSION_TYPE: 'x11' }, + tools: ['python3'], + shippedHelperPresent: false, + respond: () => ({ stdout: TREE }), + }); + + await assert.rejects(captureAtspi(stub), (error: unknown) => { + const failure = error as AppError; + return failure.code === 'TOOL_MISSING' && failure.message.includes('atspi-dump.py'); + }); + assert.equal(stub.commands.length, 0); }); test('the AT-SPI capture passes the surface and traversal limits', async () => { diff --git a/packages/platform-linux/src/__tests__/tool-provider.test.ts b/packages/platform-linux/src/__tests__/tool-provider.test.ts index 7b10e43c65..cc2e0ed8c0 100644 --- a/packages/platform-linux/src/__tests__/tool-provider.test.ts +++ b/packages/platform-linux/src/__tests__/tool-provider.test.ts @@ -231,7 +231,7 @@ test('the desktop provider falls back to pkill when the host has no wmctrl', asy test('the screenshot provider translates capture to the tool the host reports', async () => { const stub = x11Stub(['scrot']); - await providerFor(stub).screenshot!.capture('/tmp/screen.png'); + await providerFor(stub).screenshot.capture('/tmp/screen.png'); assert.deepEqual(tuples(stub.commands), [['scrot', ['/tmp/screen.png']]]); }); diff --git a/packages/platform-linux/src/atspi-bridge.ts b/packages/platform-linux/src/atspi-bridge.ts index 09c7bda3d4..82f942bc00 100644 --- a/packages/platform-linux/src/atspi-bridge.ts +++ b/packages/platform-linux/src/atspi-bridge.ts @@ -13,7 +13,7 @@ import type { RawSnapshotNode, Rect } from '@agent-device/kernel/snapshot'; import type { LinuxAccessibilityProvider } from '@agent-device/contracts/linux-tool-provider'; import { normalizeAtspiRole } from './role-map.ts'; import type { LinuxCommandRunner } from './command-runner.ts'; -import { resolveLinuxAtspiScriptPath } from './atspi-script.ts'; +import { createLinuxAtspiScriptResolver, LINUX_ATSPI_SCRIPT_NAME } from './atspi-script.ts'; /** Limits matching the macOS helper's SnapshotTraversalLimits. */ const MAX_DESKTOP_APPS = 24; @@ -47,6 +47,11 @@ type PythonResult = { export function createLinuxAccessibilityProvider( commands: LinuxCommandRunner, ): LinuxAccessibilityProvider { + // Probed once per setup: the helper's location never changes while the process lives, and a repair + // of a broken install needs a restarted process anyway. + const resolveScriptPath = createLinuxAtspiScriptResolver((candidate) => + commands.isFilePresent(candidate), + ); return { async captureTree(surface, options = {}) { if (commands.hostOs !== 'linux') { @@ -60,8 +65,16 @@ export function createLinuxAccessibilityProvider( ); } + const scriptPath = await resolveScriptPath(); + if (scriptPath === undefined) { + throw new AppError( + 'TOOL_MISSING', + `Cannot find ${LINUX_ATSPI_SCRIPT_NAME}. Ensure the @agent-device/linux plugin package is installed correctly.`, + ); + } + const args = [ - resolveLinuxAtspiScriptPath(), + scriptPath, '--surface', surface, '--max-nodes', diff --git a/packages/platform-linux/src/atspi-script.ts b/packages/platform-linux/src/atspi-script.ts index 9b2f1bb077..d94e79f0be 100644 --- a/packages/platform-linux/src/atspi-script.ts +++ b/packages/platform-linux/src/atspi-script.ts @@ -1,29 +1,23 @@ import path from 'node:path'; -import { hostFileExistsSync } from '@agent-device/host-kit/host-file'; -import { AppError } from '@agent-device/kernel/errors'; -const SCRIPT_NAME = 'atspi-dump.py'; +/** The shipped AT-SPI2 helper's file name, which the manifest packages under `linux/`. */ +export const LINUX_ATSPI_SCRIPT_NAME = 'atspi-dump.py'; /** - * The AT-SPI2 helper, shipped with this package under `linux/`. + * Resolves the AT-SPI2 helper shipped with this package: answers its path, or `undefined` when the + * install does not carry it. * - * It is resolved next to the code that runs it rather than against the process working directory or - * a repository layout: from the source tree that is `/linux`, and from an installed package - * it is `/linux` beside `dist`, because the manifest ships that directory with the bundle. - * The name is resolved once per process; the first capture of a process pays the probe. + * The location is derived next to the code that runs it rather than against the process working + * directory or a repository layout: from the source tree that is `/linux`, and from an + * installed package it is `/linux` beside `dist`, because the manifest ships that directory + * with the bundle. Whether that file is really there is asked through `probe`, so the read belongs to + * the host that runs the helper rather than to this bundle (ADR 0019). The probe runs once: the first + * capture of one `setup` pays it. */ -let cachedScriptPath: string | undefined; - -export function resolveLinuxAtspiScriptPath(): string { - if (cachedScriptPath) return cachedScriptPath; - const candidate = path.join(path.dirname(import.meta.dirname), 'linux', SCRIPT_NAME); - if (!hostFileExistsSync(candidate)) { - throw new AppError( - 'TOOL_MISSING', - `Cannot find ${SCRIPT_NAME}. Ensure the @agent-device/linux plugin package is installed correctly.`, - { path: candidate }, - ); - } - cachedScriptPath = candidate; - return candidate; +export function createLinuxAtspiScriptResolver( + probe: (candidate: string) => Promise, +): () => Promise { + const candidate = path.join(path.dirname(import.meta.dirname), 'linux', LINUX_ATSPI_SCRIPT_NAME); + let resolved: Promise | undefined; + return () => (resolved ??= probe(candidate).then((present) => (present ? candidate : undefined))); } diff --git a/packages/platform-linux/src/clipboard.ts b/packages/platform-linux/src/clipboard.ts index f759e7f8ba..60106cd12b 100644 --- a/packages/platform-linux/src/clipboard.ts +++ b/packages/platform-linux/src/clipboard.ts @@ -1,12 +1,12 @@ import type { LinuxToolProvider } from '@agent-device/contracts/linux-tool-provider'; export async function readLinuxClipboard(provider: LinuxToolProvider): Promise { - return await provider.clipboard!.readText(); + return await provider.clipboard.readText(); } export async function writeLinuxClipboard( provider: LinuxToolProvider, text: string, ): Promise { - await provider.clipboard!.writeText(text); + await provider.clipboard.writeText(text); } diff --git a/packages/platform-linux/src/runtime.ts b/packages/platform-linux/src/runtime.ts index b21ef9ef37..8e25019dc3 100644 --- a/packages/platform-linux/src/runtime.ts +++ b/packages/platform-linux/src/runtime.ts @@ -156,6 +156,11 @@ export function createLinuxPlatformRuntime( throw new AppError('UNSUPPORTED_PLATFORM', 'Linux runtime cannot bind this device'); } const facts = linuxFacts(request.device); + // The provider this binding answers with, resolved once: the request scope is already entered + // when the runtime gateway binds, so a request that scoped its own provider is the one that + // answers for every operation of this binding. Resolving here rather than per call is what keeps + // one binding from asking the same question twice. + const running = resolveLinuxToolProvider(provider); const lifecycle = bindLocalDirectApplicationLifecycle({ owner: 'Linux', openTargetIdentity: 'app-name', @@ -170,7 +175,7 @@ export function createLinuxPlatformRuntime( operations: Object.freeze({ ...availableApplicationLifecycleOperations(lifecycle, facts.operations), ...(facts.operations.captureSnapshot.available - ? linuxSnapshotOperations(toolbox, provider, request) + ? linuxSnapshotOperations(toolbox, running, request) : {}), ...linuxInteractionOperations(host, request, facts), }), @@ -332,8 +337,7 @@ function linuxSnapshotOperations( async () => await captureLinuxSurfaceSnapshot( toolbox, - // The provider the request scoped, when it scoped one; otherwise this runtime's own. - resolveLinuxToolProvider(provider), + provider, input.options, captureSnapshotSignal(request.scope.signal, input), ), diff --git a/packages/platform-linux/src/screenshot.ts b/packages/platform-linux/src/screenshot.ts index 7c5e399f0b..5b1a3b77fa 100644 --- a/packages/platform-linux/src/screenshot.ts +++ b/packages/platform-linux/src/screenshot.ts @@ -6,5 +6,5 @@ export async function screenshotLinux( outPath: string, options?: ScreenshotOptions, ): Promise { - await provider.screenshot!.capture(outPath, options); + await provider.screenshot.capture(outPath, options); } diff --git a/packages/platform-linux/src/snapshot.ts b/packages/platform-linux/src/snapshot.ts index 3440731ef7..0712b3fa0a 100644 --- a/packages/platform-linux/src/snapshot.ts +++ b/packages/platform-linux/src/snapshot.ts @@ -35,7 +35,7 @@ export async function snapshotLinux( truncated?: boolean; }> { const linuxSurface = resolveLinuxSurface(toolbox, surface); - const result = await provider.accessibility!.captureTree(linuxSurface, { signal }); + const result = await provider.accessibility.captureTree(linuxSurface, { signal }); return { nodes: [...result.nodes], diff --git a/packages/platform-linux/src/surface-snapshot.ts b/packages/platform-linux/src/surface-snapshot.ts index 261cbdeb5f..7c73794642 100644 --- a/packages/platform-linux/src/surface-snapshot.ts +++ b/packages/platform-linux/src/surface-snapshot.ts @@ -2,7 +2,6 @@ import { stampSnapshotIdentity } from '@agent-device/contracts/snapshot-producer import type { CaptureSnapshotInput } from '@agent-device/contracts/snapshot-runtime'; import { shapeDesktopSurfaceSnapshot } from '@agent-device/capture-kit/snapshot-desktop-projection'; import { snapshotLinux } from './snapshot.ts'; -import { resolveLinuxToolProvider } from './tool-provider.ts'; import type { LinuxToolProvider } from '@agent-device/contracts/linux-tool-provider'; import type { LinuxToolbox } from './toolbox.ts'; @@ -10,14 +9,17 @@ import type { LinuxToolbox } from './toolbox.ts'; * One Linux surface capture, shaped like every other desktop surface capture. The core no longer * routes this: the family's runtime owns it, so a `snapshot` of a Linux device runs here and lands in * the request's exec trace through the host the plugin was set up with. + * + * The caller passes the provider it resolved for its own request, because that is the question each + * caller answers differently: the runtime and the interactor prefer a provider a request scoped over + * the one built from their host, and resolve it once per operation rather than per leg of one. */ export async function captureLinuxSurfaceSnapshot( toolbox: LinuxToolbox, - own: LinuxToolProvider, + provider: LinuxToolProvider, options: CaptureSnapshotInput['options'], signal?: AbortSignal, ) { - const provider = resolveLinuxToolProvider(own); const result = await snapshotLinux(toolbox, provider, options?.surface, signal); return shapeDesktopSurfaceSnapshot( stampSnapshotIdentity( diff --git a/packages/platform-linux/src/tool-provider.ts b/packages/platform-linux/src/tool-provider.ts index 0f76c4b799..a032c547a2 100644 --- a/packages/platform-linux/src/tool-provider.ts +++ b/packages/platform-linux/src/tool-provider.ts @@ -53,6 +53,7 @@ function withCommandOverrides( hostOs: commands.hostOs, run: overrides.runCommand ?? commands.run, which: overrides.whichCommand ?? commands.which, + isFilePresent: commands.isFilePresent, launchDetached: overrides.launchDetached ?? commands.launchDetached, sleep: overrides.sleep ?? commands.sleep, diagnose: commands.diagnose, From 099d4186401f8b6109ffe8519710b37d4b838c78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:41:56 +0100 Subject: [PATCH 4/4] fix(linux): name the probed AT-SPI helper path and retry a rejected probe --- .../src/__tests__/atspi-bridge.test.ts | 21 ++++++++++++++++- packages/platform-linux/src/atspi-bridge.ts | 8 ++++--- packages/platform-linux/src/atspi-script.ts | 23 +++++++++++++------ 3 files changed, 41 insertions(+), 11 deletions(-) diff --git a/packages/platform-linux/src/__tests__/atspi-bridge.test.ts b/packages/platform-linux/src/__tests__/atspi-bridge.test.ts index 5e8349a8df..e71ad041af 100644 --- a/packages/platform-linux/src/__tests__/atspi-bridge.test.ts +++ b/packages/platform-linux/src/__tests__/atspi-bridge.test.ts @@ -2,6 +2,7 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import path from 'node:path'; import { createLinuxHostStub, type LinuxHostStub } from '../toolbox.fixtures.ts'; +import { createLinuxAtspiScriptResolver } from '../atspi-script.ts'; import { createLinuxToolProvider } from '../tool-provider.ts'; import { AppError } from '@agent-device/kernel/errors'; @@ -72,11 +73,29 @@ test('the AT-SPI capture names a broken install when the host cannot see the shi await assert.rejects(captureAtspi(stub), (error: unknown) => { const failure = error as AppError; - return failure.code === 'TOOL_MISSING' && failure.message.includes('atspi-dump.py'); + return ( + failure.code === 'TOOL_MISSING' && + failure.message.includes('atspi-dump.py') && + failure.details?.path === path.resolve(import.meta.dirname, '../..', 'linux', 'atspi-dump.py') + ); }); assert.equal(stub.commands.length, 0); }); +test('the AT-SPI helper probe asks again after a rejected probe and keeps an answered one', async () => { + let calls = 0; + const resolve = createLinuxAtspiScriptResolver(async () => { + calls += 1; + if (calls === 1) throw new Error('EMFILE'); + return true; + }); + + await assert.rejects(resolve(), /EMFILE/); + assert.equal((await resolve()).present, true); + await resolve(); + assert.equal(calls, 2); +}); + test('the AT-SPI capture passes the surface and traversal limits', async () => { const stub = stubPython(TREE); diff --git a/packages/platform-linux/src/atspi-bridge.ts b/packages/platform-linux/src/atspi-bridge.ts index 82f942bc00..8d2d07c885 100644 --- a/packages/platform-linux/src/atspi-bridge.ts +++ b/packages/platform-linux/src/atspi-bridge.ts @@ -49,7 +49,7 @@ export function createLinuxAccessibilityProvider( ): LinuxAccessibilityProvider { // Probed once per setup: the helper's location never changes while the process lives, and a repair // of a broken install needs a restarted process anyway. - const resolveScriptPath = createLinuxAtspiScriptResolver((candidate) => + const resolveScript = createLinuxAtspiScriptResolver((candidate) => commands.isFilePresent(candidate), ); return { @@ -65,13 +65,15 @@ export function createLinuxAccessibilityProvider( ); } - const scriptPath = await resolveScriptPath(); - if (scriptPath === undefined) { + const script = await resolveScript(); + if (!script.present) { throw new AppError( 'TOOL_MISSING', `Cannot find ${LINUX_ATSPI_SCRIPT_NAME}. Ensure the @agent-device/linux plugin package is installed correctly.`, + { path: script.path }, ); } + const scriptPath = script.path; const args = [ scriptPath, diff --git a/packages/platform-linux/src/atspi-script.ts b/packages/platform-linux/src/atspi-script.ts index d94e79f0be..a12b933f77 100644 --- a/packages/platform-linux/src/atspi-script.ts +++ b/packages/platform-linux/src/atspi-script.ts @@ -4,20 +4,29 @@ import path from 'node:path'; export const LINUX_ATSPI_SCRIPT_NAME = 'atspi-dump.py'; /** - * Resolves the AT-SPI2 helper shipped with this package: answers its path, or `undefined` when the - * install does not carry it. + * Resolves the AT-SPI2 helper shipped with this package: answers the probed path and whether the + * install carries it. * * The location is derived next to the code that runs it rather than against the process working * directory or a repository layout: from the source tree that is `/linux`, and from an * installed package it is `/linux` beside `dist`, because the manifest ships that directory * with the bundle. Whether that file is really there is asked through `probe`, so the read belongs to - * the host that runs the helper rather than to this bundle (ADR 0019). The probe runs once: the first - * capture of one `setup` pays it. + * the host that runs the helper rather than to this bundle (ADR 0019). An answered probe is kept for + * the `setup`; a rejected probe is not, so the next capture asks again. */ export function createLinuxAtspiScriptResolver( probe: (candidate: string) => Promise, -): () => Promise { +): () => Promise<{ path: string; present: boolean }> { const candidate = path.join(path.dirname(import.meta.dirname), 'linux', LINUX_ATSPI_SCRIPT_NAME); - let resolved: Promise | undefined; - return () => (resolved ??= probe(candidate).then((present) => (present ? candidate : undefined))); + let resolved: Promise<{ path: string; present: boolean }> | undefined; + return () => { + resolved ??= probe(candidate).then( + (present) => ({ path: candidate, present }), + (error: unknown) => { + resolved = undefined; + throw error; + }, + ); + return resolved; + }; }