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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions packages/contracts/src/linux-tool-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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). */
Expand All @@ -69,13 +64,13 @@ export type LinuxToolProvider = Readonly<{
launchDetached(
cmd: string,
args: readonly string[],
): Readonly<{ exited: Promise<LinuxDetachedExit> }>;
): Readonly<{ exited: Promise<DetachedCommandExit> }>;
/** Waits for interaction pacing between synthesized input steps. */
sleep(milliseconds: number): Promise<void>;
desktop: LinuxDesktopProvider;
clipboard?: LinuxClipboardProvider;
screenshot?: LinuxScreenshotProvider;
accessibility?: LinuxAccessibilityProvider;
clipboard: LinuxClipboardProvider;
screenshot: LinuxScreenshotProvider;
accessibility: LinuxAccessibilityProvider;
input?: LinuxInputProvider;
}>;

Expand Down
20 changes: 20 additions & 0 deletions packages/contracts/src/platform-runtime-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,26 @@ export type HostCommandRunner = Readonly<{
run(request: HostCommandRequest, signal?: AbortSignal): Promise<HostCommandResult>;
}>;

/**
* 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<DetachedCommandExit>;
}>;

export type AppleXcrunTool = 'simctl' | 'devicectl' | 'xctrace';

declare const scopedSimctlArgs: unique symbol;
Expand Down
1 change: 1 addition & 0 deletions packages/host-kit/src/host-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export {
copyHostPath,
ensureHostDirectory,
ensureHostDirectorySync,
hostFileExists,
hostFileExistsSync,
hostFileLstatSync,
hostFileStat,
Expand Down
21 changes: 12 additions & 9 deletions packages/host-kit/src/internal/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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
Expand All @@ -93,9 +97,8 @@ export type ExecDetachedChannel = Readonly<{
onMessage(listener: (message: unknown) => void): void;
}>;

export type ExecDetachedProcess = {
pid: number;
exited: Promise<ExecDetachedExit>;
export type ExecDetachedProcess = DetachedCommandLaunch & {
/** Present only when `stdio` includes `'ipc'`: the child's own progress channel. */
channel?: ExecDetachedChannel;
};

Expand Down
10 changes: 10 additions & 0 deletions packages/host-kit/src/internal/host-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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);
}
Expand Down
12 changes: 0 additions & 12 deletions packages/platform-harmonyos/src/__tests__/hdc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);
});
17 changes: 3 additions & 14 deletions packages/platform-harmonyos/src/command-host.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import path from 'node:path';
import { AppError } from '@agent-device/kernel/errors';
import type {
PlatformBackgroundProcess,
PlatformHost,
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions packages/platform-harmonyos/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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: {
Expand All @@ -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,
};
Expand Down
2 changes: 1 addition & 1 deletion packages/platform-linux/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
47 changes: 41 additions & 6 deletions packages/platform-linux/src/__tests__/atspi-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ 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 { 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. */
Expand All @@ -13,7 +13,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(
Expand Down Expand Up @@ -55,10 +55,45 @@ 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') &&
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 () => {
Expand Down
14 changes: 7 additions & 7 deletions packages/platform-linux/src/__tests__/command-runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Original file line number Diff line number Diff line change
Expand Up @@ -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']]]);
});
Expand Down
19 changes: 17 additions & 2 deletions packages/platform-linux/src/atspi-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 resolveScript = createLinuxAtspiScriptResolver((candidate) =>
commands.isFilePresent(candidate),
);
return {
async captureTree(surface, options = {}) {
if (commands.hostOs !== 'linux') {
Expand All @@ -60,8 +65,18 @@ export function createLinuxAccessibilityProvider(
);
}

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 = [
resolveLinuxAtspiScriptPath(),
scriptPath,
'--surface',
surface,
'--max-nodes',
Expand Down
Loading
Loading